Compare commits

..
Author SHA1 Message Date
dependabot[bot] 65f81ff7cd build(deps): bump actions/checkout from 4 to 7
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-13 13:45:13 +00:00
Meghdad b582f8b6f8 add stalwart-mail-setup.md 2026-08-13 17:13:48 +03:30
Meghdad 482e9bcb47 feat(installer): add guarded full-server uninstaller 2026-08-13 17:13:02 +03:30
Meghdad 7159f122ce fix(installer): restart Stalwart after bootstrap 2026-08-13 04:33:01 +03:30
Meghdad 9272a10f72 fix(installer): refresh mailctl before finalization 2026-08-13 04:28:26 +03:30
Meghdad 2d84a780d4 fix(stalwart): use v0.16 management JMAP endpoint 2026-08-13 04:20:33 +03:30
Meghdad 493cc66bed fix(installer): treat public HTTP challenge as authoritative 2026-08-13 04:10:20 +03:30
Meghdad ac34455f13 feat(installer): add complete pre-Certbot HTTP preflight 2026-08-13 04:07:56 +03:30
Meghdad e0a3fd49da docs(installer): clarify Cloudflare token creation 2026-08-13 03:50:10 +03:30
Meghdad 66f9811f48 feat(installer): add optional Cloudflare DNS configuration 2026-08-13 03:44:58 +03:30
13 changed files with 1912 additions and 40 deletions

No files matched your search

+5 -4
View File
@@ -17,7 +17,7 @@ jobs:
name: Frontend
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v4
with:
node-version: 22
@@ -30,7 +30,7 @@ jobs:
name: Go backend
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
@@ -43,10 +43,11 @@ jobs:
name: Appliance bundle
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate installer syntax
- uses: actions/checkout@v7
- name: Validate server script syntax
run: |
bash -n scripts/install-server.sh
bash -n scripts/uninstall-server.sh
sh -n deploy/certbot/deploy-hook.sh
- name: Validate Compose configuration
env:
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- uses: actions/dependency-review-action@v4
with:
fail-on-severity: high
+85 -6
View File
@@ -58,16 +58,64 @@ sudo ./scripts/install-server.sh install \
--email admin@example.com
```
The hostname's A/AAAA record must already point to the server and inbound port
80 must be reachable so Let's Encrypt can issue the certificate. The installer
does not change DNS, PTR, provider firewall rules, SSH, or UFW. It detects
Without automatic DNS setup, the hostname's A/AAAA record must already point to
the server. Inbound port 80 must always be reachable so Let's Encrypt can issue
the certificate. During an interactive installation, the script can configure
Cloudflare DNS after asking for a scoped API token through a hidden prompt. It
previews the records before making changes. The token needs `Zone:Read` and
`DNS:Edit` for the selected zone.
Create the token from the
[Cloudflare API Tokens dashboard](https://dash.cloudflare.com/profile/api-tokens),
choose **Create Custom Token**, grant `Zone → Zone → Read` and
`Zone → DNS → Edit`, and restrict its resources to the specific mail zone. Do
not use the Global API Key. The installer prints these instructions before its
hidden token prompt.
The token is used only for DNS configuration and is never stored. Certificate
issuance and renewal deliberately use HTTP-01 so installation proves the public
hostname reaches this server and renewals do not depend on Cloudflare access.
Before invoking Certbot, the installer publishes a random challenge probe and
requires the public HTTP URL to return its exact content with status `200` and
no redirect. If another proxy, NAT rule, or virtual host intercepts the request,
installation stops with a report covering the active Nginx site, public A/AAAA
answers, local-origin result, public result, and redirect target. If this host's
Nginx does not load `sites-enabled`, the installer automatically tries its
managed `conf.d` fallback before reporting a configuration problem. The public
result is authoritative: a different loopback virtual-host result is reported
as a warning but does not block Certbot when the public challenge returns exact
content.
Automatic DNS setup creates or updates the mail-host A/AAAA record, the primary
MX record, and autoconfiguration CNAMEs. It adds monitoring-mode DMARC and a
soft-fail SPF default only when those policies do not already exist. It cannot
set provider-owned PTR records, and DKIM remains a post-setup action because
Stalwart generates its value. Declining the prompt leaves DNS unchanged.
The installer does not change provider firewall rules, SSH, or UFW. It detects
unmanaged Nginx hostname conflicts and conflicting Docker packages instead of
overwriting or removing them. If Docker is already installed without Compose
v2, it adds the matching Compose package from the configured APT repositories.
Use `--yes` only for a reviewed, non-interactive installation.
Visit the printed HTTPS URL and complete the browser wizard. After creating and
testing a permanent administrator, finish the security setup:
For unattended Cloudflare setup, pass `--configure-dns` and provide the token
through the environment rather than a command-line argument:
```bash
read -r -s -p 'Cloudflare API token: ' CLOUDFLARE_API_TOKEN; export CLOUDFLARE_API_TOKEN
sudo --preserve-env=CLOUDFLARE_API_TOKEN ./scripts/install-server.sh install \
--hostname mail.example.com \
--email admin@example.com \
--configure-dns \
--dns-zone example.com \
--yes
unset CLOUDFLARE_API_TOKEN
```
Visit the printed HTTPS URL, complete the browser wizard, and save the generated
permanent-administrator credentials. Then finish the security setup. Finalize
restarts Stalwart into its persistent configuration and pauses so an interactive
operator can verify administrator sign-in before recovery access is removed:
```bash
sudo ./scripts/install-server.sh finalize
@@ -77,6 +125,33 @@ sudo ./scripts/install-server.sh status
See [`docs/nginx-certbot.md`](docs/nginx-certbot.md) for the generated routing
and certificate layout, renewal behavior, customization, and manual setup.
### Uninstall
The guarded uninstaller permanently removes the MEOVV containers, images,
volumes, mailbox/application data, local backups, secrets, Nginx site, Certbot
hook and certificate, and the host `mailctl`. It requires the mail hostname to
be typed before deletion. It separately asks whether to purge Docker, Nginx,
and Certbot APT packages and whether to delete the repository checkout:
```bash
sudo ./scripts/uninstall-server.sh
```
For reviewed non-interactive removal, choices must be explicit:
```bash
sudo ./scripts/uninstall-server.sh \
--bundle-dir /opt/meovv-mail \
--hostname mail.example.com \
--purge-packages \
--remove-bundle \
--yes
```
Package purging can affect other services using Docker, Nginx, or Certbot.
The uninstaller never changes public DNS, PTR records, firewall rules, unrelated
Nginx sites, unrelated Docker resources, or unrelated certificates.
### Manual installation
Build the local operator utility and initialize the bundle:
@@ -101,11 +176,15 @@ one-time result shown on the final screen.
After setup:
```bash
docker compose restart stalwart
./mailctl configure-tls
./mailctl doctor --hostname mail.example.com
```
Sign in with the permanent Stalwart administrator, create the dedicated `API_SUBMISSION_USER` account referenced by `.env`, put that account's application password in `secrets/api_submission_password`, verify REST submission, then remove the recovery backdoor:
Sign in with the permanent Stalwart administrator and verify it before removing
the recovery backdoor. Then create the dedicated `API_SUBMISSION_USER` account
referenced by `.env`, put that account's application password in
`secrets/api_submission_password`, and verify REST submission:
```bash
./mailctl harden
+1 -1
View File
@@ -348,7 +348,7 @@ function SetupWizard({ onComplete }: { onComplete: () => void }) {
} catch (reason) { setError(reason instanceof Error ? reason.message : "Setup failed."); }
finally { setBusy(false); }
};
if (bootstrapResult) return <div className="setup-finished"><div><span className="step-icon"><CheckCircle2 /></span><h1>Your mail appliance is configured.</h1><p>Save the one-time mail-core result below, restart the mail core, verify the permanent administrator account, and remove recovery access with <code>mailctl harden</code>.</p><pre>{JSON.stringify(bootstrapResult, null, 2)}</pre><div className="setup-warning"><ShieldCheck />This result is not stored by MEOVV Mail.</div><button className="primary" onClick={onComplete}>I saved it — continue to sign in <ArrowRight /></button></div></div>;
if (bootstrapResult) return <div className="setup-finished"><div><span className="step-icon"><CheckCircle2 /></span><h1>Your mail appliance is configured.</h1><p>Save the one-time mail-core result below, then run <code>sudo ./scripts/install-server.sh finalize</code> on the server. Finalization restarts the mail core and pauses so you can verify this administrator before recovery access is removed.</p><pre>{JSON.stringify(bootstrapResult, null, 2)}</pre><div className="setup-warning"><ShieldCheck />This result is not stored by MEOVV Mail.</div><button className="primary" onClick={onComplete}>I saved it — show sign in <ArrowRight /></button></div></div>;
return (
<div className="setup-screen">
<aside className="setup-aside">
+3 -3
View File
@@ -252,7 +252,7 @@ func createAPIKey(args []string) error {
func configureTLS(args []string) error {
fs := flag.NewFlagSet("configure-tls", flag.ContinueOnError)
dir := fs.String("directory", ".", "Compose bundle directory")
endpoint := fs.String("url", "http://127.0.0.1:8081/api", "loopback Stalwart management endpoint")
endpoint := fs.String("url", "http://127.0.0.1:8081/jmap", "loopback Stalwart management JMAP endpoint")
certificatePath := fs.String("certificate-path", "/etc/stalwart/tls/fullchain.pem", "certificate path inside the Stalwart container")
privateKeyPath := fs.String("private-key-path", "/etc/stalwart/tls/privkey.pem", "private key path inside the Stalwart container")
if err := fs.Parse(args); err != nil {
@@ -260,8 +260,8 @@ func configureTLS(args []string) error {
}
root, _ := filepath.Abs(*dir)
managementURL, err := url.Parse(*endpoint)
if err != nil || managementURL.Scheme != "http" || managementURL.Path != "/api" || managementURL.User != nil || managementURL.RawQuery != "" || managementURL.Fragment != "" {
return errors.New("--url must be a loopback HTTP URL ending in /api")
if err != nil || managementURL.Scheme != "http" || managementURL.Path != "/jmap" || managementURL.User != nil || managementURL.RawQuery != "" || managementURL.Fragment != "" {
return errors.New("--url must be a loopback HTTP URL ending in /jmap")
}
managementHost := managementURL.Hostname()
managementIP := net.ParseIP(managementHost)
+2 -2
View File
@@ -38,14 +38,14 @@ func TestJMAPSucceededRejectsFailedUpdate(t *testing.T) {
}
func TestConfigureTLSRejectsRemoteManagementURL(t *testing.T) {
err := configureTLS([]string{"--directory", t.TempDir(), "--url", "http://mail.example.com/api"})
err := configureTLS([]string{"--directory", t.TempDir(), "--url", "http://mail.example.com/jmap"})
if err == nil || !strings.Contains(err.Error(), "loopback") {
t.Fatalf("expected loopback URL rejection, got %v", err)
}
}
func TestConfigureTLSRejectsHTTPSManagementURL(t *testing.T) {
err := configureTLS([]string{"--directory", t.TempDir(), "--url", "https://127.0.0.1:8081/api"})
err := configureTLS([]string{"--directory", t.TempDir(), "--url", "https://127.0.0.1:8081/jmap"})
if err == nil || !strings.Contains(err.Error(), "loopback HTTP URL") {
t.Fatalf("expected plain loopback HTTP requirement, got %v", err)
}
+61 -4
View File
@@ -27,17 +27,67 @@ enables the final route split, copies the certificate into MEOVV's protected
secrets directory, installs the renewal hook, and starts both containers.
It deliberately leaves DNS, PTR records, provider firewall rules, SSH, and UFW
to the operator. It also stops when it finds a conflicting unmanaged Nginx site
or container package rather than replacing an existing setup. After the browser
wizard and permanent administrator verification, run:
to the operator unless the optional Cloudflare DNS prompt is accepted. It also
stops when it finds a conflicting unmanaged Nginx site or container package
rather than replacing an existing setup. After the browser wizard, save the
generated permanent-administrator credentials and run:
```bash
sudo ./scripts/install-server.sh finalize
```
Finalization restarts Stalwart so it leaves its in-memory bootstrap mode, waits
for the persistent configuration to become ready, and pauses for administrator
sign-in verification before removing recovery access.
The rest of this document describes the same integration for manual installs
and explains the files managed by the installer.
### Optional Cloudflare DNS setup
When accepted, the installer requests a Cloudflare API token with `Zone:Read`
and `DNS:Edit` through a hidden prompt. Before changing DNS, the installer shows
the selected zone, detected public addresses, and complete record plan for
confirmation.
The prompt links directly to the
[Cloudflare API Tokens dashboard](https://dash.cloudflare.com/profile/api-tokens).
Choose **Create Custom Token**, add `Zone → Zone → Read` and
`Zone → DNS → Edit`, and restrict **Zone Resources** to the selected zone. A
Global API Key is neither required nor recommended.
The token is used only for the confirmed DNS changes and is then discarded.
Certificate issuance and renewal deliberately use Certbot HTTP-01, proving that
the public hostname and port 80 reach this server without retaining Cloudflare
credentials.
Immediately before Certbot, the installer creates a random file under
`/var/www/certbot/.well-known/acme-challenge/` and requests it through the public
mail hostname without following redirects. It proceeds only when the response
is `200` with exact content. This detects unloaded Nginx site configuration,
incorrect public IP/NAT routing, canonical-host redirects, and intercepted port
80 traffic before consuming an ACME validation attempt. The report separates a
loopback request pinned to local Nginx from a normal public-hostname request and
includes public A/AAAA answers and any redirect location. If `sites-enabled` is
not loaded, the installer safely retries its managed site through
`/etc/nginx/conf.d/meovv-mail.conf`; it does not edit `nginx.conf` or unrelated
virtual hosts. The public response is the issuance gate because it matches what
the ACME server can reach. A differing loopback virtual-host response remains a
visible warning but does not block issuance when the public response is `200`
with exact challenge content.
It manages the mail hostname's unproxied A/AAAA records, the zone MX record, and
the `autoconfig` and `autodiscover` CNAMEs. Existing SPF and DMARC policies are
preserved; conservative defaults are created only when no corresponding policy
exists. Multiple existing records that would make an update ambiguous stop the
installation for manual review.
Cloudflare cannot set the server provider's PTR record. DKIM is intentionally
deferred until the domain exists in Stalwart and its generated public key can be
published. For non-interactive use, pass `--configure-dns` and provide
`CLOUDFLARE_API_TOKEN` in the environment. Optional `--dns-zone`,
`--public-ipv4`, and `--public-ipv6` flags override detected defaults.
## Nginx
Copy `deploy/nginx/meovv-mail.conf.example` into the host's Nginx configuration,
@@ -84,7 +134,14 @@ the temporary recovery account, register the mounted files with Stalwart:
```bash
docker compose up -d --build --remove-orphans
docker compose restart stalwart
./mailctl configure-tls
```
Sign in with the permanent administrator shown by the wizard. Only after that
account is verified, remove temporary recovery access:
```bash
./mailctl harden
```
@@ -95,7 +152,7 @@ references, selects it as `defaultCertificateId`, records the object id in
port was changed, pass a loopback URL explicitly:
```bash
./mailctl configure-tls --url http://127.0.0.1:9081/api
./mailctl configure-tls --url http://127.0.0.1:9081/jmap
```
## Renewal hook
+807
View File
@@ -0,0 +1,807 @@
# Stalwart Mail Server on Ubuntu with Cloudflare, Nginx, and Certbot
This guide deploys a single-node Stalwart mail server on an Ubuntu 24.04 LTS VPS.
It assumes:
- Mail server hostname: `mail.example.com`
- Email domain: `example.com`
- Example administrator/contact address: `admin@example.com`
- Nginx already owns public ports `80` and `443`
- Cloudflare is authoritative for the `example.com` DNS zone
- Stalwart runs in Docker
- Nginx terminates HTTPS for the WebUI and JMAP
- Stalwart directly handles SMTP, Submission, and IMAP
- Certbot obtains one certificate for `mail.example.com`; a renewal hook copies it to a private directory readable by Stalwart
> Replace every value written as `REPLACE_WITH_...` before running a command or importing a file.
> This guide treats `mail.example.com` as the server hostname. Mailboxes are addresses such as `alice@example.com`. If you actually want addresses such as `alice@mail.example.com`, the DNS and Stalwart domain values must be adjusted.
## 1. Architecture
```text
Internet
|
+-- TCP 80/443 --> Nginx --> 127.0.0.1:8081 --> Stalwart HTTP/JMAP
|
+-- TCP 25 -------------------------------> Stalwart SMTP
+-- TCP 465 -------------------------------> Stalwart SMTPS
+-- TCP 587 -------------------------------> Stalwart Submission + STARTTLS
+-- TCP 993 -------------------------------> Stalwart IMAPS
```
Stalwart does not bind to the host's ports `80` or `443`, so it does not conflict with the existing Nginx installation.
## 2. Preflight checklist
Before installing anything, verify that the VPS provider:
- Gives the server a static public IPv4 address.
- Does not block inbound or outbound TCP port `25`.
- Lets you set reverse DNS (PTR).
- Provides an IP address that is not on major blocklists.
- Allows at least 2 GB RAM for a comfortable small deployment.
Record these values:
```text
VPS IPv4: REPLACE_WITH_VPS_IPV4
Server hostname: mail.example.com
Email domain: example.com
ACME contact email: admin@example.com
```
Check whether port 25 is already occupied:
```bash
sudo ss -ltnp | grep -E ':(25|465|587|993|8081)\b' || true
```
If Postfix, Exim, Dovecot, or another mail stack is already listening on these ports, stop and resolve that conflict before continuing. Do not remove an existing mail service until you know it is not in use.
## 3. Configure the hostname and reverse DNS
Set the VPS hostname:
```bash
sudo hostnamectl set-hostname mail.example.com
hostnamectl
```
In the VPS provider's control panel, set the PTR/reverse-DNS record:
```text
REPLACE_WITH_VPS_IPV4 -> mail.example.com
```
Cloudflare cannot create the PTR record for a normal VPS IP. The IP owner/VPS provider must create it.
Forward and reverse DNS should eventually agree:
```text
mail.example.com -> REPLACE_WITH_VPS_IPV4
REPLACE_WITH_VPS_IPV4 -> mail.example.com
```
## 4. Import the bootstrap DNS records into Cloudflare
Create a local file named `example.com-bootstrap.zone` containing the following text. Replace `REPLACE_WITH_VPS_IPV4` first.
```dns
$ORIGIN example.com.
$TTL 300
mail.example.com. 300 IN A REPLACE_WITH_VPS_IPV4 ; cf_tags=cf-proxied:false
example.com. 300 IN MX 10 mail.example.com.
example.com. 300 IN TXT "v=spf1 mx -all"
_dmarc.example.com. 300 IN TXT "v=DMARC1; p=none; rua=mailto:dmarc@example.com; adkim=s; aspf=s"
_imaps._tcp.example.com. 300 IN SRV 0 1 993 mail.example.com.
_submissions._tcp.example.com. 300 IN SRV 0 1 465 mail.example.com.
autoconfig.example.com. 300 IN CNAME mail.example.com. ; cf_tags=cf-proxied:false
autodiscover.example.com. 300 IN CNAME mail.example.com. ; cf_tags=cf-proxied:false
```
Import it in Cloudflare:
1. Open **Cloudflare Dashboard > example.com > DNS > Records**.
2. Select **Import and Export**.
3. Import `example.com-bootstrap.zone`.
4. Review every proposed change before confirming it.
5. Ensure `mail`, `autoconfig`, and `autodiscover` are **DNS only** (grey cloud), not proxied.
Important:
- Do not delete existing website or verification records.
- If an SPF record already exists, merge its permitted senders into one SPF record. A domain must not publish multiple SPF TXT records.
- If an MX record already exists, changing it switches inbound mail delivery. Do not confirm the MX change until you intend this VPS to receive mail.
- The initial DMARC policy is deliberately `p=none` for monitoring. Tighten it only after SPF and DKIM have been verified.
- DKIM is intentionally absent at this stage because its exact public key must be generated by Stalwart.
- The `cf-proxied:false` tags force Cloudflare DNS-only mode during import.
Cloudflare's mail proxy limitation means the hostname used by MX, SMTP, and IMAP must remain DNS-only. Normal Cloudflare orange-cloud proxying does not proxy arbitrary SMTP or IMAP traffic.
## 5. Verify initial DNS propagation
Install DNS utilities:
```bash
sudo apt update
sudo apt install -y dnsutils
```
Verify the records:
```bash
dig +short A mail.example.com
dig +short MX example.com
dig +short TXT example.com
dig +short TXT _dmarc.example.com
dig +short -x REPLACE_WITH_VPS_IPV4
```
Do not continue with Certbot until `mail.example.com` resolves to the VPS and public TCP port `80` reaches this Nginx server.
## 6. Install Docker, Nginx, Certbot, and firewall tools
The following commands target Ubuntu 24.04 LTS packages:
```bash
sudo apt update
sudo apt upgrade -y
sudo apt install -y docker.io docker-compose-v2 nginx snapd ufw curl ca-certificates
sudo systemctl enable --now docker
sudo systemctl enable --now nginx
sudo systemctl enable --now snapd.socket
```
Install Certbot using the officially recommended Snap package:
```bash
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/local/bin/certbot
certbot --version
```
If `/usr/local/bin/certbot` already exists, do not recreate the link; verify that the existing `certbot` command is the intended installation.
## 7. Configure the firewall
Allow SSH before enabling UFW. Replace `OpenSSH` if SSH uses a custom port.
```bash
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 25/tcp
sudo ufw allow 465/tcp
sudo ufw allow 587/tcp
sudo ufw allow 993/tcp
sudo ufw enable
sudo ufw status verbose
```
This deployment deliberately does not expose plaintext IMAP `143`, POP3 `110/995`, ManageSieve `4190`, or Stalwart's bootstrap HTTP port.
Also open the same ports in any VPS-provider/network firewall.
## 8. Start Stalwart with Docker Compose
Create the deployment directory and the certificate-copy directory:
```bash
sudo install -d -m 0755 /opt/stalwart
sudo install -d -o 2000 -g 2000 -m 0700 /srv/stalwart/tls
cd /opt/stalwart
```
Create `/opt/stalwart/compose.yaml`:
```yaml
services:
stalwart:
image: stalwartlabs/stalwart:v0.16
container_name: stalwart
restart: unless-stopped
environment:
STALWART_PUBLIC_URL: https://mail.example.com
ports:
- "127.0.0.1:8081:8080"
- "25:25"
- "465:465"
- "587:587"
- "993:993"
volumes:
- stalwart-etc:/etc/stalwart
- stalwart-data:/var/lib/stalwart
- /srv/stalwart/tls:/run/stalwart-tls:ro
volumes:
stalwart-etc:
stalwart-data:
```
> `v0.16` is intentionally pinned because that is the stable minor-series example in the Stalwart documentation when this guide was written (2026-08-12). Before a new installation, check the official release notes and pin the exact tested release you want. Do not replace it blindly with `latest` in production.
Start the container:
```bash
cd /opt/stalwart
sudo docker compose up -d
sudo docker compose ps
sudo docker logs --tail 100 stalwart
```
Confirm that Stalwart's web listener is only exposed on loopback:
```bash
sudo ss -ltnp | grep -E ':(25|465|587|993|8081)\b'
curl -I http://127.0.0.1:8081/
```
## 9. Create a temporary HTTP-only Nginx virtual host
Create `/etc/nginx/sites-available/mail.example.com`:
```nginx
server {
listen 80;
listen [::]:80;
server_name mail.example.com;
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Enable and validate it:
```bash
sudo ln -s /etc/nginx/sites-available/mail.example.com /etc/nginx/sites-enabled/mail.example.com
sudo nginx -t
sudo systemctl reload nginx
```
If the symlink already exists, leave it in place and continue after validating its target.
Test the public HTTP route:
```bash
curl -I http://mail.example.com/
```
## 10. Obtain the public certificate with Certbot
Request a certificate without letting Certbot permanently rewrite the final Nginx configuration:
```bash
sudo certbot certonly --nginx \
-d mail.example.com \
-m admin@example.com \
--agree-tos \
--no-eff-email
```
Confirm that the files exist:
```bash
sudo ls -l /etc/letsencrypt/live/mail.example.com/
sudo certbot certificates
```
## 11. Copy the certificate securely for Stalwart
The Certbot private key is normally root-only. Do not make `/etc/letsencrypt` world-readable. Instead, create a controlled deployment script that copies only this certificate into Stalwart's private directory.
Create `/usr/local/sbin/deploy-stalwart-certificate`:
```sh
#!/bin/sh
set -eu
CERT_SOURCE=/etc/letsencrypt/live/mail.example.com
STALWART_TLS_DIR=/srv/stalwart/tls
install -d -o 2000 -g 2000 -m 0700 "$STALWART_TLS_DIR"
install -o 2000 -g 2000 -m 0644 "$CERT_SOURCE/fullchain.pem" "$STALWART_TLS_DIR/fullchain.pem"
install -o 2000 -g 2000 -m 0600 "$CERT_SOURCE/privkey.pem" "$STALWART_TLS_DIR/privkey.pem"
nginx -t
systemctl reload nginx
if docker container inspect stalwart >/dev/null 2>&1; then
docker restart stalwart >/dev/null
fi
```
Install permissions and run it once:
```bash
sudo chmod 0755 /usr/local/sbin/deploy-stalwart-certificate
sudo /usr/local/sbin/deploy-stalwart-certificate
sudo ls -l /srv/stalwart/tls
```
Register it as a Certbot deploy hook:
```bash
sudo install -d -m 0755 /etc/letsencrypt/renewal-hooks/deploy
sudo ln -s /usr/local/sbin/deploy-stalwart-certificate \
/etc/letsencrypt/renewal-hooks/deploy/stalwart-mail
```
If the hook symlink already exists, inspect it rather than overwriting it.
Test renewal and the hook:
```bash
sudo certbot renew --dry-run
```
## 12. Replace the Nginx site with the final HTTPS reverse proxy
Replace `/etc/nginx/sites-available/mail.example.com` with:
```nginx
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
listen [::]:80;
server_name mail.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name mail.example.com;
ssl_certificate /etc/letsencrypt/live/mail.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mail.example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
# Match this to Stalwart's configured maximum message/upload size.
client_max_body_size 100m;
location / {
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 300s;
proxy_send_timeout 300s;
}
}
```
Validate and reload:
```bash
sudo nginx -t
sudo systemctl reload nginx
curl -I https://mail.example.com/
```
## 13. Retrieve the temporary Stalwart administrator credentials
```bash
sudo docker logs stalwart 2>&1 | grep -A8 'bootstrap mode'
```
The log should show a temporary username and password. Store the password securely; it is only printed during bootstrap.
## 14. Complete the initial Stalwart wizard safely
The most reliable method is to use an SSH tunnel and access the bootstrap listener directly.
Run this on your local computer, not on the VPS:
```bash
ssh -L 8081:127.0.0.1:8081 REPLACE_WITH_SSH_USER@REPLACE_WITH_VPS_IPV4
```
Then open this local URL in your browser:
```text
http://127.0.0.1:8081/admin
```
Use the temporary bootstrap credentials and choose:
```text
Server hostname: mail.example.com
Default email domain: example.com
Storage: local RocksDB defaults (single-node deployment)
Directory: internal directory
Generate DKIM signing keys: enabled
Automatic DNS management: manual
Automatic TLS certificate: disabled/manual
```
Automatic Stalwart ACME is disabled in this design because Certbot owns the certificate lifecycle. Stalwart will read the Certbot certificate from the mounted private directory.
Finish the wizard, save the permanent administrator credentials, and restart:
```bash
cd /opt/stalwart
sudo docker compose restart stalwart
```
Open the normal administration URL:
```text
https://mail.example.com/admin
```
## 15. Register the Certbot certificate in Stalwart
In the Stalwart WebUI, open:
```text
Settings > TLS > Certificates
```
Create a manual certificate using file sources:
```text
Certificate chain type: File
Certificate chain path: /run/stalwart-tls/fullchain.pem
Private key type: File
Private key path: /run/stalwart-tls/privkey.pem
```
Then:
1. Save the certificate.
2. Confirm that Stalwart detects `mail.example.com` in its Subject Alternative Names.
3. Set it as the default certificate under the general TLS/system settings if it is not selected automatically.
4. Confirm that the listeners for ports `25`, `465`, `587`, and `993` have TLS enabled.
5. Port `465` and `993` should use implicit TLS.
6. Port `587` should use STARTTLS rather than implicit TLS.
7. Restart Stalwart once after saving:
```bash
sudo docker restart stalwart
```
## 16. Trust Nginx's forwarded client IP
For the HTTP listener, configure Stalwart to trust forwarded headers only from the local Nginx proxy.
In the WebUI, find the trusted proxy network setting under:
```text
Settings > Network > Services
```
Add only the loopback proxy addresses used by this deployment:
```text
127.0.0.1/32
::1/128
```
Do not trust `0.0.0.0/0` or `::/0`. Trusting the entire internet would let clients forge their source IP through forwarded headers.
## 17. Publish the real DKIM record
In Stalwart, open the `example.com` domain and view/export its generated DNS zone file. Copy the exact DKIM record generated by Stalwart. It will look similar to this, but the selector and public key will be different:
```dns
REPLACE_WITH_SELECTOR._domainkey.example.com. 300 IN TXT "v=DKIM1; k=rsa; p=REPLACE_WITH_STALWART_DKIM_PUBLIC_KEY"
```
Do not publish the example placeholder. Publish the exact selector and key shown by your server.
You can either:
- Add the DKIM TXT record manually in Cloudflare, or
- Export the complete Stalwart-generated zone file and import it through **Cloudflare > DNS > Records > Import and Export**.
When importing a complete generated zone, review the diff carefully so existing website records are not removed or incorrectly replaced. Ensure all mail hostnames remain DNS-only.
Verify DKIM after propagation:
```bash
dig +short TXT REPLACE_WITH_SELECTOR._domainkey.example.com
```
## 18. Create required accounts and aliases
Create at least:
```text
admin@example.com
postmaster@example.com
abuse@example.com
dmarc@example.com
```
They may be separate accounts or aliases routed to a monitored administrator mailbox. The DMARC record in this guide sends reports to `dmarc@example.com`, so that address must accept mail.
Create a normal test mailbox, for example:
```text
alice@example.com
```
Use a unique, strong password and enable two-factor authentication for administrator accounts.
## 19. Mail-client settings
Use these settings in Thunderbird, Apple Mail, Outlook, or another client:
```text
Username: alice@example.com
Incoming server: mail.example.com
Protocol: IMAP
Port: 993
Connection security: SSL/TLS
Authentication: Normal password or app password
Outgoing server: mail.example.com
Protocol: SMTP
Port: 465
Connection security: SSL/TLS
Authentication: Required
```
Port `587` with STARTTLS is an alternative submission configuration.
## 20. Validate the deployment
### DNS
```bash
dig +short A mail.example.com
dig +short -x REPLACE_WITH_VPS_IPV4
dig +short MX example.com
dig +short TXT example.com
dig +short TXT _dmarc.example.com
dig +short TXT REPLACE_WITH_SELECTOR._domainkey.example.com
```
Expected essentials:
```text
A: mail.example.com -> VPS IPv4
PTR: VPS IPv4 -> mail.example.com
MX: example.com -> mail.example.com
SPF: v=spf1 mx -all
DKIM: exact public key generated by Stalwart
DMARC: monitoring policy initially
```
### HTTPS and JMAP discovery
```bash
curl -fsS https://mail.example.com/.well-known/jmap
curl -fsS https://mail.example.com/.well-known/openid-configuration
```
All absolute URLs returned by Stalwart should use:
```text
https://mail.example.com
```
### TLS on mail ports
```bash
openssl s_client -connect mail.example.com:993 -servername mail.example.com </dev/null
openssl s_client -connect mail.example.com:465 -servername mail.example.com </dev/null
openssl s_client -starttls smtp -connect mail.example.com:587 -servername mail.example.com </dev/null
openssl s_client -starttls smtp -connect mail.example.com:25 -servername mail.example.com </dev/null
```
Confirm that the presented certificate is valid for `mail.example.com` and that the chain verifies successfully.
### Service and logs
```bash
sudo docker compose -f /opt/stalwart/compose.yaml ps
sudo docker logs --tail 200 stalwart
sudo journalctl -u nginx -n 100 --no-pager
sudo ss -ltnp | grep -E ':(25|80|443|465|587|993|8081)\b'
```
### Send/receive tests
1. Send from `alice@example.com` to an external Gmail or Outlook mailbox.
2. Inspect the received message headers for SPF, DKIM, and DMARC results.
3. Reply from the external mailbox to `alice@example.com`.
4. Confirm the reply reaches Stalwart.
5. Check both inbox and spam folders during early testing.
Do not tighten DMARC until legitimate messages consistently pass SPF and/or DKIM alignment.
## 21. Security hardening after verification
- Keep `127.0.0.1:8081` bound to loopback only.
- Do not expose Stalwart's bootstrap/recovery listener publicly.
- Keep Cloudflare mail records DNS-only.
- Disable unused Stalwart listeners such as POP3 and plaintext IMAP.
- Enable two-factor authentication for administrators.
- Prefer application passwords for mail clients where supported.
- Rate-limit authentication and monitor automatic bans.
- Restrict `/admin` by VPN or source IP in Nginx if operationally possible.
- Keep Ubuntu, Nginx, Docker, and Stalwart patched.
- Pin Stalwart releases and test upgrades against a backup before production rollout.
- Monitor disk space, delivery queues, TLS expiry, logs, and abuse complaints.
Example Nginx restriction if administration is only allowed from one trusted IP:
```nginx
location ^~ /admin {
allow REPLACE_WITH_TRUSTED_ADMIN_IPV4;
deny all;
proxy_pass http://127.0.0.1:8081;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
```
Only add this after confirming that the trusted address is static and that you have a recovery path.
## 22. Backups
The two Docker volumes contain configuration and local Stalwart data. Stop the service briefly for a simple consistent single-node filesystem backup:
```bash
sudo install -d -m 0700 /srv/backups/stalwart
cd /opt/stalwart
sudo docker compose stop stalwart
sudo docker run --rm \
-v stalwart-etc:/source:ro \
-v /srv/backups/stalwart:/backup \
alpine:3.22 \
tar -czf /backup/stalwart-etc.tar.gz -C /source .
sudo docker run --rm \
-v stalwart-data:/source:ro \
-v /srv/backups/stalwart:/backup \
alpine:3.22 \
tar -czf /backup/stalwart-data.tar.gz -C /source .
sudo docker compose start stalwart
sudo ls -lh /srv/backups/stalwart
```
Also back up:
```text
/opt/stalwart/compose.yaml
/etc/nginx/sites-available/mail.example.com
/usr/local/sbin/deploy-stalwart-certificate
Cloudflare DNS zone export
```
Copy backups to another machine or object-storage account. A backup stored only on the mail VPS does not protect against VPS loss. Test restoration periodically.
For larger deployments or external databases/object stores, use the backup procedure specific to that storage backend rather than copying local volumes blindly.
## 23. Upgrade procedure
Never switch a production server directly to `latest`.
1. Read the Stalwart release notes and migration guide.
2. Take and verify a backup.
3. Test the target version in a staging environment.
4. Change only the pinned image tag in `/opt/stalwart/compose.yaml`.
5. Pull and restart:
```bash
cd /opt/stalwart
sudo docker compose pull
sudo docker compose up -d
sudo docker compose ps
sudo docker logs --tail 200 stalwart
```
6. Retest SMTP, IMAP, JMAP, authentication, DKIM signing, and inbound/outbound delivery.
## 24. Common failure modes
### Cloudflare shows an orange cloud for `mail`
Set `mail.example.com` to DNS-only. SMTP and IMAP should not point at a normally proxied Cloudflare record.
### Certbot validation fails
Check:
```bash
dig +short A mail.example.com
sudo ufw status
sudo ss -ltnp | grep ':80\b'
curl -I http://mail.example.com/
sudo nginx -t
```
### Web sign-in redirects to the wrong address
Confirm the container environment contains:
```yaml
STALWART_PUBLIC_URL: https://mail.example.com
```
Then restart the container and inspect the discovery documents.
### Every web request appears to come from localhost
Verify Nginx forwards `X-Forwarded-For`, and configure Stalwart to trust forwarded headers only from `127.0.0.1/32` and `::1/128`.
### IMAP/SMTP presents a self-signed certificate
Confirm:
```bash
sudo ls -l /srv/stalwart/tls
sudo docker exec stalwart ls -l /run/stalwart-tls
```
Then verify that the manual Certificate object uses these exact container paths:
```text
/run/stalwart-tls/fullchain.pem
/run/stalwart-tls/privkey.pem
```
Restart Stalwart after correcting the certificate record.
### Outbound mail does not leave the server
Check whether the VPS provider blocks outbound TCP port `25`. If it does, request removal of the block or configure a reputable SMTP relay in Stalwart.
### Messages go to spam
Verify A/PTR agreement, SPF, DKIM, DMARC, IP reputation, message content, sending volume, and complaint/bounce handling. A technically correct server does not automatically receive good deliverability from a new or previously abused IP.
## 25. Reference documentation
- Stalwart Docker installation: <https://stalw.art/docs/install/platform/docker/>
- Stalwart Nginx reverse proxy: <https://stalw.art/docs/server/reverse-proxy/nginx/>
- Stalwart reverse-proxy concepts: <https://stalw.art/docs/server/reverse-proxy/>
- Stalwart DNS setup: <https://stalw.art/docs/install/dns/>
- Stalwart TLS certificates: <https://stalw.art/docs/domains/tls-certificates/>
- Stalwart security checklist: <https://stalw.art/docs/install/security/>
- Cloudflare DNS import/export: <https://developers.cloudflare.com/dns/manage-dns-records/how-to/import-and-export/>
- Certbot Nginx instructions: <https://certbot.eff.org/instructions?ws=nginx&os=snap>
---
Last reviewed: 2026-08-12.
This is an operational template, not a substitute for testing, monitoring, backups, abuse prevention, and a documented recovery plan.
+1 -1
View File
@@ -180,7 +180,7 @@ func (s *Server) setupComplete(w http.ResponseWriter, r *http.Request) {
return
}
_ = s.Store.Audit(r.Context(), app.RandomID("aud_"), in.AdminEmail, "installation.completed", in.Hostname, in)
writeJSON(w, 201, map[string]any{"configured": true, "next": "Save the one-time administrator result, restart Stalwart, verify permanent administrator sign-in, then run mailctl harden.", "mail_core_result": json.RawMessage(bootstrapResult), "dns_checks": []string{"A/AAAA", "MX", "PTR", "SPF", "DKIM", "DMARC", "TLS"}})
writeJSON(w, 201, map[string]any{"configured": true, "next": "Save the one-time administrator result, then run install-server.sh finalize. It restarts Stalwart and pauses for permanent administrator sign-in verification before removing recovery access.", "mail_core_result": json.RawMessage(bootstrapResult), "dns_checks": []string{"A/AAAA", "MX", "PTR", "SPF", "DKIM", "DMARC", "TLS"}})
}
func (s *Server) sessionExchange(w http.ResponseWriter, r *http.Request) {
+6 -6
View File
@@ -35,11 +35,11 @@ func (c *Client) Bootstrap(ctx context.Context, bootstrapURL, recoveryAdmin, hos
"serverHostname": hostname, "defaultDomain": domain, "requestTlsCertificate": false, "generateDkimKeys": true,
"dataStore": map[string]any{"@type": "RocksDb", "path": "/var/lib/stalwart/"},
"blobStore": map[string]any{"@type": "Default"}, "searchStore": map[string]any{"@type": "Default"}, "inMemoryStore": map[string]any{"@type": "Default"},
"directory": map[string]any{"@type": "Internal"}, "tracer": map[string]any{"@type": "Console"}, "dnsServer": map[string]any{"@type": "Manual"},
"directory": map[string]any{"@type": "Internal"}, "tracer": map[string]any{"@type": "Stdout"}, "dnsServer": map[string]any{"@type": "Manual"},
}}}, "bootstrap"}},
}
raw, _ := json.Marshal(payload)
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(bootstrapURL, "/")+"/api", bytes.NewReader(raw))
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(bootstrapURL, "/")+"/jmap", bytes.NewReader(raw))
req.SetBasicAuth(parts[0], parts[1])
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTP.Do(req)
@@ -114,11 +114,11 @@ func (c *Client) ProxyJMAP(ctx context.Context, token string, body []byte) (int,
return c.proxy(ctx, token, "/jmap", body)
}
// ProxyManagement keeps Stalwart's pre-1.0 management schema behind the MEOVV
// adapter. The browser never receives an administrator token or direct access
// to Stalwart's management endpoint.
// ProxyManagement keeps Stalwart's pre-1.0 management JMAP schema behind the
// MEOVV adapter. The browser never receives an administrator token or direct
// access to Stalwart's management endpoint.
func (c *Client) ProxyManagement(ctx context.Context, token string, body []byte) (int, http.Header, []byte, error) {
return c.proxy(ctx, token, "/api", body)
return c.proxy(ctx, token, "/jmap", body)
}
func (c *Client) JMAPSession(ctx context.Context, token string) (int, http.Header, []byte, error) {
+92
View File
@@ -0,0 +1,92 @@
package stalwart
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestBootstrapUsesPinnedManagementJMAPEndpoint(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("method = %s, want POST", r.Method)
}
if r.URL.Path != "/jmap" {
t.Errorf("path = %s, want /jmap", r.URL.Path)
}
username, password, ok := r.BasicAuth()
if !ok || username != "admin" || password != "recovery-secret" {
t.Errorf("unexpected recovery authentication: %q %q %v", username, password, ok)
}
if got := r.Header.Get("Content-Type"); got != "application/json" {
t.Errorf("Content-Type = %q", got)
}
var request struct {
Using []string `json:"using"`
MethodCalls [][]json.RawMessage `json:"methodCalls"`
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Fatal(err)
}
if len(request.MethodCalls) != 1 || len(request.MethodCalls[0]) != 3 {
t.Fatalf("unexpected method calls: %#v", request.MethodCalls)
}
var method string
if err := json.Unmarshal(request.MethodCalls[0][0], &method); err != nil {
t.Fatal(err)
}
if method != "x:Bootstrap/set" {
t.Errorf("method = %q, want x:Bootstrap/set", method)
}
var arguments struct {
Update map[string]struct {
Tracer map[string]any `json:"tracer"`
} `json:"update"`
}
if err := json.Unmarshal(request.MethodCalls[0][1], &arguments); err != nil {
t.Fatal(err)
}
if got := arguments.Update["singleton"].Tracer["@type"]; got != "Stdout" {
t.Errorf("tracer type = %v, want Stdout", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"methodResponses":[["x:Bootstrap/set",{"updated":{"singleton":{"username":"admin@example.com","secret":"generated"}}},"bootstrap"]]}`)
}))
defer server.Close()
client := New(server.URL, false)
if _, err := client.Bootstrap(context.Background(), server.URL, "admin:recovery-secret", "mail.example.com", "example.com"); err != nil {
t.Fatal(err)
}
}
func TestProxyManagementUsesJMAPEndpoint(t *testing.T) {
t.Parallel()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/jmap" {
t.Errorf("path = %s, want /jmap", r.URL.Path)
}
if got := r.Header.Get("Authorization"); got != "Bearer access-token" {
t.Errorf("Authorization = %q", got)
}
_, _ = io.WriteString(w, `{"methodResponses":[]}`)
}))
defer server.Close()
client := New(server.URL, false)
status, _, _, err := client.ProxyManagement(context.Background(), "access-token", []byte(`{"methodCalls":[]}`))
if err != nil {
t.Fatal(err)
}
if status != http.StatusOK {
t.Fatalf("status = %d, want 200", status)
}
}
+464 -12
View File
@@ -6,6 +6,7 @@ readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
readonly REPOSITORY_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd -P)"
readonly NGINX_AVAILABLE="/etc/nginx/sites-available/meovv-mail"
readonly NGINX_ENABLED="/etc/nginx/sites-enabled/meovv-mail"
readonly NGINX_CONFD="/etc/nginx/conf.d/meovv-mail.conf"
readonly CERTBOT_WEBROOT="/var/www/certbot"
readonly CERTBOT_HOOK="/etc/letsencrypt/renewal-hooks/deploy/meovv-mail"
readonly MAILCTL_BIN="/usr/local/bin/mailctl"
@@ -17,8 +18,15 @@ MAIL_HOSTNAME=""
ADMIN_EMAIL=""
BUNDLE_DIR="$REPOSITORY_DIR"
ASSUME_YES=false
CONFIGURE_DNS=false
DNS_ZONE=""
PUBLIC_IPV4=""
PUBLIC_IPV6=""
TEMP_CONTAINER=""
TEMP_FILES=()
CF_API_TOKEN=""
CF_ZONE_ID=""
NGINX_ACTIVE_LINK="$NGINX_ENABLED"
log() {
printf '\n\033[1;35m==>\033[0m %s\n' "$*"
@@ -52,6 +60,8 @@ Usage:
sudo ./scripts/install-server.sh install \
--hostname mail.example.com \
--email admin@example.com \
[--configure-dns] [--dns-zone example.com] \
[--public-ipv4 203.0.113.10] [--public-ipv6 2001:db8::10] \
[--bundle-dir /opt/meovv-mail] [--yes]
sudo ./scripts/install-server.sh finalize \
@@ -63,11 +73,16 @@ Usage:
Commands:
install Install Docker, Nginx, and Certbot; initialize the bundle; obtain
TLS; install proxy/renewal configuration; and start the appliance.
finalize After completing the browser wizard and creating a permanent
administrator, register TLS with Stalwart and remove recovery access.
finalize After completing the browser wizard, restart Stalwart into its
persistent configuration, register TLS, verify the permanent
administrator, and remove recovery access.
status Show service, certificate, and local endpoint status without changes.
This script does not modify DNS, PTR records, provider firewalls, SSH, or UFW.
This script does not modify PTR records, provider firewalls, SSH, or UFW.
Interactive installs can optionally configure supported Cloudflare DNS records;
DNS is unchanged when that option is declined.
For unattended DNS setup, use --configure-dns and provide the token through
CLOUDFLARE_API_TOKEN; the token is never written to disk.
EOF
}
@@ -93,6 +108,25 @@ parse_arguments() {
BUNDLE_DIR="$2"
shift 2
;;
--configure-dns)
CONFIGURE_DNS=true
shift
;;
--dns-zone)
[[ $# -ge 2 ]] || die "--dns-zone requires a value"
DNS_ZONE="$2"
shift 2
;;
--public-ipv4)
[[ $# -ge 2 ]] || die "--public-ipv4 requires a value"
PUBLIC_IPV4="$2"
shift 2
;;
--public-ipv6)
[[ $# -ge 2 ]] || die "--public-ipv6 requires a value"
PUBLIC_IPV6="$2"
shift 2
;;
--yes|-y)
ASSUME_YES=true
shift
@@ -114,6 +148,10 @@ parse_arguments() {
[[ "$BUNDLE_DIR" = /* ]] || die "--bundle-dir must be an absolute path"
[[ "$BUNDLE_DIR" != *$'\n'* ]] || die "--bundle-dir contains a newline"
if [[ "$COMMAND" != "install" ]] && \
{ $CONFIGURE_DNS || [[ -n "$DNS_ZONE$PUBLIC_IPV4$PUBLIC_IPV6" ]]; }; then
die "DNS options are valid only with the install command"
fi
}
require_root() {
@@ -151,7 +189,9 @@ This will install or update Docker Engine, Nginx, and Certbot, write:
and start MEOVV Mail from:
$BUNDLE_DIR
It will not alter unrelated Nginx files, DNS, PTR, or firewall rules.
It will not alter unrelated Nginx files, PTR, or firewall rules. You will be
offered optional Cloudflare DNS configuration separately; declining leaves DNS
unchanged.
EOF
read -r -p "Continue? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || die "installation cancelled"
@@ -195,11 +235,257 @@ install_base_packages() {
dnsutils \
gnupg \
iproute2 \
jq \
nginx \
openssl \
python3-certbot-nginx
}
is_ipv4() {
local address="$1" octet
local -a octets=()
[[ "$address" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1
local old_ifs="$IFS"
IFS=.
read -r -a octets <<< "$address"
IFS="$old_ifs"
for octet in "${octets[@]}"; do
(( 10#$octet <= 255 )) || return 1
done
}
is_ipv6() {
[[ "$1" == *:* && "$1" =~ ^[0-9A-Fa-f:]+$ ]]
}
validate_dns_inputs() {
[[ "$DNS_ZONE" =~ ^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$ ]] || \
die "invalid Cloudflare zone name: $DNS_ZONE"
DNS_ZONE="${DNS_ZONE,,}"
[[ "$MAIL_HOSTNAME" == "$DNS_ZONE" || "$MAIL_HOSTNAME" == *."$DNS_ZONE" ]] || \
die "$MAIL_HOSTNAME is not inside the Cloudflare zone $DNS_ZONE"
[[ -z "$PUBLIC_IPV4" ]] || is_ipv4 "$PUBLIC_IPV4" || die "invalid public IPv4 address: $PUBLIC_IPV4"
[[ -z "$PUBLIC_IPV6" ]] || is_ipv6 "$PUBLIC_IPV6" || die "invalid public IPv6 address: $PUBLIC_IPV6"
[[ -n "$PUBLIC_IPV4$PUBLIC_IPV6" ]] || die "automatic DNS setup requires a public IPv4 and/or IPv6 address"
}
discover_public_address() {
local family="$1"
curl "-$family" --fail --silent --show-error --max-time 8 \
https://1.1.1.1/cdn-cgi/trace 2>/dev/null | sed -n 's/^ip=//p' | head -n 1
}
cloudflare_api() {
local method="$1" path="$2" data="${3:-}"
local arguments=(
--fail-with-body
--silent
--show-error
--request "$method"
"https://api.cloudflare.com/client/v4$path"
)
if [[ -n "$data" ]]; then
arguments+=(--data "$data")
fi
# Read the authorization header from stdin so the token does not appear in
# the curl process arguments or get written to a temporary file.
printf 'header = "Authorization: Bearer %s"\nheader = "Content-Type: application/json"\n' \
"$CF_API_TOKEN" | curl --config - "${arguments[@]}"
}
require_cloudflare_success() {
local response="$1" action="$2"
if ! jq -e '.success == true' >/dev/null 2>&1 <<< "$response"; then
local detail
detail="$(jq -r '[.errors[]? | (.code|tostring) + ": " + .message] | join("; ")' <<< "$response" 2>/dev/null || true)"
die "Cloudflare could not $action${detail:+: $detail}"
fi
}
cloudflare_records() {
local type="$1" name="$2" response
response="$(cloudflare_api GET "/zones/$CF_ZONE_ID/dns_records?type=$type&name=$name&per_page=100")" || \
die "Cloudflare DNS lookup failed for $name"
require_cloudflare_success "$response" "read $type records for $name"
printf '%s' "$response"
}
write_cloudflare_record() {
local action="$1" record_id="$2" body="$3" response
if [[ "$action" == "create" ]]; then
response="$(cloudflare_api POST "/zones/$CF_ZONE_ID/dns_records" "$body")" || \
die "Cloudflare DNS record creation failed"
else
response="$(cloudflare_api PUT "/zones/$CF_ZONE_ID/dns_records/$record_id" "$body")" || \
die "Cloudflare DNS record update failed"
fi
require_cloudflare_success "$response" "$action a DNS record"
}
ensure_cloudflare_record() {
local type="$1" name="$2" content="$3" priority="${4:-}" response count exact_id record_id body
response="$(cloudflare_records "$type" "$name")"
count="$(jq '.result | length' <<< "$response")"
if [[ "$type" == "MX" ]]; then
exact_id="$(jq -r --arg content "$content" --argjson priority "$priority" \
'.result[] | select(.content == $content and .priority == $priority) | .id' <<< "$response" | head -n 1)"
body="$(jq -cn --arg type "$type" --arg name "$name" --arg content "$content" \
--argjson priority "$priority" '{type:$type,name:$name,content:$content,priority:$priority,ttl:1}')"
else
exact_id="$(jq -r --arg content "$content" \
'.result[] | select(.content == $content and .proxied == false) | .id' <<< "$response" | head -n 1)"
body="$(jq -cn --arg type "$type" --arg name "$name" --arg content "$content" \
'{type:$type,name:$name,content:$content,ttl:1,proxied:false}')"
fi
if (( count > 1 )); then
die "multiple Cloudflare $type records exist for $name; review them manually instead of replacing them"
fi
if [[ -n "$exact_id" ]]; then
log "Cloudflare $type record is already correct: $name"
return
fi
if (( count == 1 )); then
record_id="$(jq -r '.result[0].id' <<< "$response")"
write_cloudflare_record update "$record_id" "$body"
log "Updated Cloudflare $type record: $name"
else
write_cloudflare_record create "" "$body"
log "Created Cloudflare $type record: $name"
fi
}
ensure_cloudflare_txt_default() {
local name="$1" prefix="$2" content="$3" response exact existing body
response="$(cloudflare_records TXT "$name")"
exact="$(jq -r --arg content "$content" '.result[] | select(.content == $content) | .id' \
<<< "$response" | head -n 1)"
if [[ -n "$exact" ]]; then
log "Cloudflare TXT record is already correct: $name"
return
fi
existing="$(jq -r --arg prefix "$prefix" '.result[] | select(.content | startswith($prefix)) | .content' \
<<< "$response" | head -n 1)"
if [[ -n "$existing" ]]; then
warn "Keeping the existing TXT policy for $name: $existing"
return
fi
body="$(jq -cn --arg name "$name" --arg content "$content" \
'{type:"TXT",name:$name,content:$content,ttl:1}')"
write_cloudflare_record create "" "$body"
log "Created conservative Cloudflare TXT policy: $name"
}
wait_for_cloudflare_dns() {
log "Waiting for the mail hostname to appear in public DNS"
local attempt answer
for attempt in {1..20}; do
if [[ -n "$PUBLIC_IPV4" ]]; then
answer="$(dig +short A "$MAIL_HOSTNAME" @1.1.1.1 | grep -Fx "$PUBLIC_IPV4" || true)"
else
answer="$(dig +short AAAA "$MAIL_HOSTNAME" @1.1.1.1 | grep -Fxi "$PUBLIC_IPV6" || true)"
fi
[[ -n "$answer" ]] && return
sleep 3
done
die "Cloudflare accepted the DNS records, but $MAIL_HOSTNAME is not publicly visible yet; wait briefly and rerun the installer"
}
configure_cloudflare_dns() {
DNS_ZONE="${DNS_ZONE:-${ADMIN_EMAIL##*@}}"
local detected_ipv4 detected_ipv6 answer response zone_count
detected_ipv4="${PUBLIC_IPV4:-$(discover_public_address 4 || true)}"
detected_ipv6="$(discover_public_address 6 || true)"
if [[ -t 0 ]] && ! $ASSUME_YES; then
read -r -p "Cloudflare zone [$DNS_ZONE]: " answer
DNS_ZONE="${answer:-$DNS_ZONE}"
read -r -p "Public IPv4 [$detected_ipv4]: " answer
PUBLIC_IPV4="${answer:-$detected_ipv4}"
if [[ -z "$PUBLIC_IPV6" ]]; then
read -r -p "Public IPv6 (optional; detected $detected_ipv6, blank to skip): " PUBLIC_IPV6
fi
else
PUBLIC_IPV4="$detected_ipv4"
fi
validate_dns_inputs
CF_API_TOKEN="${CLOUDFLARE_API_TOKEN:-}"
unset CLOUDFLARE_API_TOKEN || true
if [[ -z "$CF_API_TOKEN" ]] && [[ -t 0 ]]; then
cat <<EOF
Create a scoped Cloudflare API token here:
https://dash.cloudflare.com/profile/api-tokens
Select "Create Custom Token" and configure:
Permissions:
Zone | Zone | Read
Zone | DNS | Edit
Zone Resources:
Include | Specific zone | $DNS_ZONE
Do not use the Global API Key. Paste the newly created token below; input is
hidden and the token is used only for this installation process.
EOF
read -r -s -p "Cloudflare API token (hidden): " CF_API_TOKEN
printf '\n'
fi
[[ -n "$CF_API_TOKEN" ]] || \
die "Cloudflare DNS setup requires a token through the hidden prompt or CLOUDFLARE_API_TOKEN"
[[ "$CF_API_TOKEN" != *$'\n'* && "$CF_API_TOKEN" != *'"'* && "$CF_API_TOKEN" != *'\\'* ]] || \
die "the Cloudflare API token contains unsupported characters"
response="$(cloudflare_api GET /user/tokens/verify)" || die "Cloudflare token verification request failed"
require_cloudflare_success "$response" "verify the API token"
response="$(cloudflare_api GET "/zones?name=$DNS_ZONE&status=active&per_page=2")" || \
die "Cloudflare zone lookup failed"
require_cloudflare_success "$response" "look up zone $DNS_ZONE"
zone_count="$(jq '.result | length' <<< "$response")"
[[ "$zone_count" -eq 1 ]] || die "expected one active Cloudflare zone named $DNS_ZONE; found $zone_count"
CF_ZONE_ID="$(jq -r '.result[0].id' <<< "$response")"
cat <<EOF
Cloudflare DNS changes for $DNS_ZONE:
A $MAIL_HOSTNAME -> ${PUBLIC_IPV4:-skip}
AAAA $MAIL_HOSTNAME -> ${PUBLIC_IPV6:-skip}
MX $DNS_ZONE -> $MAIL_HOSTNAME (priority 10)
CNAME autoconfig.$DNS_ZONE -> $MAIL_HOSTNAME
CNAME autodiscover.$DNS_ZONE -> $MAIL_HOSTNAME
TXT SPF and DMARC conservative defaults, only when no policy exists
DKIM is generated after domain setup. PTR must be configured at the server/IP
provider. Existing SPF or DMARC policies will never be overwritten.
EOF
if [[ -t 0 ]] && ! $ASSUME_YES; then
read -r -p "Apply these DNS changes? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || die "DNS configuration cancelled"
fi
[[ -z "$PUBLIC_IPV4" ]] || ensure_cloudflare_record A "$MAIL_HOSTNAME" "$PUBLIC_IPV4"
[[ -z "$PUBLIC_IPV6" ]] || ensure_cloudflare_record AAAA "$MAIL_HOSTNAME" "$PUBLIC_IPV6"
ensure_cloudflare_record MX "$DNS_ZONE" "$MAIL_HOSTNAME" 10
ensure_cloudflare_record CNAME "autoconfig.$DNS_ZONE" "$MAIL_HOSTNAME"
ensure_cloudflare_record CNAME "autodiscover.$DNS_ZONE" "$MAIL_HOSTNAME"
ensure_cloudflare_txt_default "$DNS_ZONE" "v=spf1 " "v=spf1 mx ~all"
ensure_cloudflare_txt_default "_dmarc.$DNS_ZONE" "v=DMARC1;" \
"v=DMARC1; p=none; rua=mailto:postmaster@$DNS_ZONE"
wait_for_cloudflare_dns
CF_API_TOKEN=""
}
configure_dns_if_requested() {
local answer
if ! $CONFIGURE_DNS && [[ -t 0 ]] && ! $ASSUME_YES; then
read -r -p "Configure the required DNS records with Cloudflare now? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] && CONFIGURE_DNS=true
fi
$CONFIGURE_DNS || return
configure_cloudflare_dns
}
package_is_installed() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -Fq 'install ok installed'
}
@@ -293,20 +579,66 @@ assert_hostname_is_available() {
if [[ -e "$NGINX_AVAILABLE" ]] && ! grep -Fq "$MANAGED_MARKER" "$NGINX_AVAILABLE"; then
die "$NGINX_AVAILABLE exists but is not managed by this installer"
fi
if [[ -e "$NGINX_CONFD" || -L "$NGINX_CONFD" ]]; then
if [[ "$(readlink -f "$NGINX_CONFD" 2>/dev/null || true)" != "$(readlink -f "$NGINX_AVAILABLE" 2>/dev/null || true)" ]] && \
! grep -Fq "$MANAGED_MARKER" "$NGINX_CONFD" 2>/dev/null; then
die "$NGINX_CONFD exists but is not managed by this installer"
fi
NGINX_ACTIVE_LINK="$NGINX_CONFD"
fi
}
ensure_managed_nginx_site_loaded() {
local nginx_configuration
nginx_configuration="$(nginx -T 2>&1)" || die "could not inspect the active Nginx configuration"
if grep -Fq "# $MANAGED_MARKER" <<< "$nginx_configuration"; then
return
fi
warn "$NGINX_ENABLED is not loaded by nginx.conf; trying the standard conf.d location"
if [[ -e "$NGINX_CONFD" || -L "$NGINX_CONFD" ]]; then
die "$NGINX_CONFD is unavailable for the managed Nginx fallback"
fi
install -d -m 0755 /etc/nginx/conf.d
ln -s "$NGINX_AVAILABLE" "$NGINX_CONFD"
if [[ -L "$NGINX_ENABLED" ]] && \
[[ "$(readlink -f "$NGINX_ENABLED")" == "$(readlink -f "$NGINX_AVAILABLE")" ]]; then
rm -f -- "$NGINX_ENABLED"
fi
NGINX_ACTIVE_LINK="$NGINX_CONFD"
if ! nginx -t || ! systemctl reload nginx; then
rm -f -- "$NGINX_CONFD"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
die "Nginx could not load the managed site from sites-enabled or conf.d"
fi
nginx_configuration="$(nginx -T 2>&1)" || die "could not re-inspect the active Nginx configuration"
if ! grep -Fq "# $MANAGED_MARKER" <<< "$nginx_configuration"; then
rm -f -- "$NGINX_CONFD"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
NGINX_ACTIVE_LINK="$NGINX_ENABLED"
die "nginx.conf loads neither /etc/nginx/sites-enabled/* nor /etc/nginx/conf.d/*.conf"
fi
log "Loaded the managed Nginx site through $NGINX_CONFD"
}
install_challenge_site() {
install -d -m 0755 "$CERTBOT_WEBROOT"
install -d -m 0755 /etc/nginx/sites-available /etc/nginx/sites-enabled
if [[ -L "$NGINX_CONFD" ]] && \
[[ "$(readlink -f "$NGINX_CONFD")" == "$(readlink -f "$NGINX_AVAILABLE" 2>/dev/null || true)" ]]; then
NGINX_ACTIVE_LINK="$NGINX_CONFD"
fi
if [[ -r "/etc/letsencrypt/live/$MAIL_HOSTNAME/fullchain.pem" ]] && \
[[ -r "/etc/letsencrypt/live/$MAIL_HOSTNAME/privkey.pem" ]] && \
[[ -f "$NGINX_AVAILABLE" ]] && grep -Fq "listen 443 ssl" "$NGINX_AVAILABLE"; then
log "Keeping the existing managed HTTPS site during certificate renewal"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ACTIVE_LINK"
nginx -t
systemctl enable --now nginx
systemctl reload nginx
ensure_managed_nginx_site_loaded
return
fi
@@ -328,10 +660,97 @@ server {
}
}
EOF
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ACTIVE_LINK"
nginx -t
systemctl enable --now nginx
systemctl reload nginx
ensure_managed_nginx_site_loaded
}
verify_http_challenge_route() {
log "Running the complete pre-Certbot HTTP-01 check"
local challenge_directory challenge_name challenge_file challenge_url
local local_body local_headers local_status="000" local_curl_ok local_content_ok
local public_body public_headers public_status="000" public_curl_ok public_content_ok
local local_redirect public_redirect public_ipv4 public_ipv6
challenge_directory="$CERTBOT_WEBROOT/.well-known/acme-challenge"
challenge_name="meovv-preflight-$(openssl rand -hex 12)"
challenge_file="$challenge_directory/$challenge_name"
local_body="$(mktemp /tmp/meovv-http-local-body.XXXXXX)"
local_headers="$(mktemp /tmp/meovv-http-local-headers.XXXXXX)"
public_body="$(mktemp /tmp/meovv-http-public-body.XXXXXX)"
public_headers="$(mktemp /tmp/meovv-http-public-headers.XXXXXX)"
TEMP_FILES+=("$challenge_file" "$local_body" "$local_headers" "$public_body" "$public_headers")
install -d -m 0755 "$challenge_directory"
printf '%s' "$challenge_name" > "$challenge_file"
chmod 0644 "$challenge_file"
challenge_url="http://$MAIL_HOSTNAME/.well-known/acme-challenge/$challenge_name"
local_curl_ok=true
if ! local_status="$(curl \
--silent \
--show-error \
--max-time 8 \
--max-redirs 0 \
--noproxy '*' \
--resolve "$MAIL_HOSTNAME:80:127.0.0.1" \
--dump-header "$local_headers" \
--output "$local_body" \
--write-out '%{http_code}' \
"$challenge_url")"; then
local_curl_ok=false
fi
local_content_ok=false
cmp -s "$challenge_file" "$local_body" && local_content_ok=true
local_redirect="$(sed -n 's/^[Ll]ocation:[[:space:]]*//p' "$local_headers" | tr -d '\r' | tail -n 1)"
public_ipv4="$(dig +short A "$MAIL_HOSTNAME" @1.1.1.1 | paste -sd ',' - || true)"
public_ipv6="$(dig +short AAAA "$MAIL_HOSTNAME" @1.1.1.1 | paste -sd ',' - || true)"
public_curl_ok=true
if ! public_status="$(curl \
--silent \
--show-error \
--max-time 15 \
--max-redirs 0 \
--noproxy '*' \
--dump-header "$public_headers" \
--output "$public_body" \
--write-out '%{http_code}' \
"$challenge_url")"; then
public_curl_ok=false
fi
public_content_ok=false
cmp -s "$challenge_file" "$public_body" && public_content_ok=true
public_redirect="$(sed -n 's/^[Ll]ocation:[[:space:]]*//p' "$public_headers" | tr -d '\r' | tail -n 1)"
cat <<EOF
HTTP-01 preflight report
Active Nginx site: $NGINX_ACTIVE_LINK
Public DNS A: ${public_ipv4:-none}
Public DNS AAAA: ${public_ipv6:-none}
Local origin: status ${local_status:-000}, exact challenge: $local_content_ok
Local redirect: ${local_redirect:-none}
Public hostname: status ${public_status:-000}, exact challenge: $public_content_ok
Public redirect: ${public_redirect:-none}
EOF
if [[ -z "$public_ipv4$public_ipv6" ]]; then
die "$MAIL_HOSTNAME has no public A or AAAA response from resolver 1.1.1.1"
fi
if ! $public_curl_ok || [[ "$public_status" != "200" ]] || ! $public_content_ok; then
if [[ -n "$public_redirect" ]]; then
die "public HTTP for $MAIL_HOSTNAME is intercepted and redirects to $public_redirect; correct the upstream proxy, NAT, or provider routing before running Certbot"
fi
die "public port 80 does not return the local MEOVV challenge; correct DNS, NAT, firewall, or upstream proxy routing before running Certbot"
fi
if ! $local_curl_ok || [[ "$local_status" != "200" ]] || ! $local_content_ok; then
warn "loopback HTTP differs from the public route${local_redirect:+ and redirects to $local_redirect}; the authoritative public challenge passed, so installation can continue"
fi
rm -f -- "$challenge_file" "$local_body" "$local_headers" "$public_body" "$public_headers"
log "All HTTP-01 checks passed; Certbot may start"
}
obtain_certificate() {
@@ -356,7 +775,7 @@ install_final_nginx_site() {
sed "s/__MAIL_HOSTNAME__/$MAIL_HOSTNAME/g" \
"$BUNDLE_DIR/deploy/nginx/meovv-mail.conf.example" \
> "$NGINX_AVAILABLE"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ACTIVE_LINK"
nginx -t
systemctl reload nginx
}
@@ -462,7 +881,9 @@ install_command() {
install_docker
build_and_install_mailctl
initialize_bundle
configure_dns_if_requested
install_challenge_site
verify_http_challenge_route
obtain_certificate
copy_certificate_to_stalwart
install_certbot_hook
@@ -475,8 +896,8 @@ MEOVV Mail prerequisites and services are installed.
Next:
1. Open https://$MAIL_HOSTNAME and complete the setup wizard.
2. Create and verify a permanent Stalwart administrator.
3. Run:
2. Save the one-time permanent administrator credentials shown by the wizard.
3. Run finalization; it restarts Stalwart and pauses for sign-in verification:
sudo $BUNDLE_DIR/scripts/install-server.sh finalize --bundle-dir $BUNDLE_DIR
Required provider-side work that this script cannot perform:
@@ -492,16 +913,47 @@ EOF
finalize_command() {
require_root
require_bundle
[[ -x "$MAILCTL_BIN" ]] || die "$MAILCTL_BIN is missing; run install first"
[[ -f "$BUNDLE_DIR/.env" ]] || die "$BUNDLE_DIR is not initialized"
# mailctl is installed on the host, outside the Compose lifecycle. Refresh
# it from this checkout before finalization so a container-only application
# update cannot leave an older management client calling stale Stalwart
# endpoints.
MAIL_HOSTNAME="$(sed -n 's/^MAIL_HOSTNAME=//p' "$BUNDLE_DIR/.env" | tail -n 1)"
[[ -n "$MAIL_HOSTNAME" ]] || die "MAIL_HOSTNAME is missing from $BUNDLE_DIR/.env"
validate_hostname
if ! $ASSUME_YES; then
[[ -t 0 ]] || die "non-interactive use requires --yes"
warn "Finalize removes the temporary Stalwart recovery administrator."
read -r -p "Have you completed the wizard and verified a permanent administrator? [y/N] " answer
warn "Finalize restarts Stalwart and then removes the temporary recovery administrator."
read -r -p "Have you completed the wizard and saved its permanent administrator credentials? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || die "finalization cancelled"
fi
build_and_install_mailctl
log "Restarting Stalwart into its persistent configuration"
compose restart stalwart
local attempt stalwart_ready=false
for attempt in {1..30}; do
if curl --fail --silent --show-error --max-time 3 \
http://127.0.0.1:8081/.well-known/jmap >/dev/null; then
stalwart_ready=true
break
fi
sleep 2
done
if [[ "$stalwart_ready" != true ]]; then
compose ps
die "Stalwart did not become ready after its post-bootstrap restart"
fi
if ! $ASSUME_YES; then
printf '\nStalwart is now running its persistent configuration.\n'
read -r -p "Can you sign in with the permanent administrator shown by the wizard? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || die "finalization stopped; recovery access remains enabled"
fi
log "Registering Certbot TLS with Stalwart"
"$MAILCTL_BIN" configure-tls --directory "$BUNDLE_DIR"
log "Removing temporary recovery access"
+384
View File
@@ -0,0 +1,384 @@
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
readonly REPOSITORY_DIR="$(cd -- "$SCRIPT_DIR/.." && pwd -P)"
readonly PROJECT_NAME="meovv-mail"
readonly NGINX_AVAILABLE="/etc/nginx/sites-available/meovv-mail"
readonly NGINX_ENABLED="/etc/nginx/sites-enabled/meovv-mail"
readonly NGINX_CONFD="/etc/nginx/conf.d/meovv-mail.conf"
readonly CERTBOT_WEBROOT="/var/www/certbot"
readonly CERTBOT_HOOK="/etc/letsencrypt/renewal-hooks/deploy/meovv-mail"
readonly MAILCTL_BIN="/usr/local/bin/mailctl"
readonly -a MEOVV_VOLUMES=(
meovv-mail-app-data
meovv-mail-stalwart-config
meovv-mail-stalwart-data
)
readonly -a OPTIONAL_APT_PACKAGES=(
certbot
containerd.io
docker-buildx-plugin
docker-ce
docker-ce-cli
docker-compose-plugin
docker-compose-v2
nginx
python3-certbot-nginx
)
BUNDLE_DIR="$REPOSITORY_DIR"
MAIL_HOSTNAME=""
ASSUME_YES=false
PURGE_PACKAGES=false
REMOVE_BUNDLE=false
KEEP_CERTIFICATE=false
FAILURES=0
log() {
printf '\n\033[1;35m==>\033[0m %s\n' "$*"
}
warn() {
printf '\033[1;33mWARNING:\033[0m %s\n' "$*" >&2
}
record_failure() {
warn "$*"
FAILURES=$((FAILURES + 1))
}
usage() {
cat <<'EOF'
Permanently uninstall MEOVV Mail from one server.
Usage:
sudo ./scripts/uninstall-server.sh \
[--bundle-dir /opt/meovv-mail] [--hostname mail.example.com] \
[--purge-packages] [--remove-bundle] [--keep-certificate] [--yes]
The uninstaller always removes:
- MEOVV and Stalwart containers, network, images, and named volumes
- all mailbox data, application data, local backups, secrets, and .env
- MEOVV Nginx sites, Certbot deploy hook, and /usr/local/bin/mailctl
- the hostname's Certbot certificate (unless --keep-certificate is used)
Options:
--purge-packages Also purge installed Docker CE/Compose, Nginx, and
Certbot packages, then remove the Docker APT source.
This can affect other services using those packages.
--remove-bundle Also delete the entire repository/bundle directory.
--keep-certificate Keep the Certbot certificate and renewal configuration.
--yes Non-interactive confirmation. Package and bundle removal
still require their explicit flags.
Cloudflare/public DNS, PTR records, firewall rules, unrelated Nginx sites,
unrelated Docker resources, and unrelated certificates are never changed.
EOF
}
parse_arguments() {
while [[ $# -gt 0 ]]; do
case "$1" in
--bundle-dir)
[[ $# -ge 2 ]] || { printf 'ERROR: --bundle-dir requires a value\n' >&2; exit 2; }
BUNDLE_DIR="$2"
shift 2
;;
--hostname)
[[ $# -ge 2 ]] || { printf 'ERROR: --hostname requires a value\n' >&2; exit 2; }
MAIL_HOSTNAME="$2"
shift 2
;;
--purge-packages)
PURGE_PACKAGES=true
shift
;;
--remove-bundle)
REMOVE_BUNDLE=true
shift
;;
--keep-certificate)
KEEP_CERTIFICATE=true
shift
;;
--yes|-y)
ASSUME_YES=true
shift
;;
--help|-h)
usage
exit 0
;;
*)
printf 'ERROR: unknown argument: %s\n' "$1" >&2
exit 2
;;
esac
done
}
require_root() {
[[ ${EUID:-$(id -u)} -eq 0 ]] || {
printf 'ERROR: run this command with sudo or as root\n' >&2
exit 1
}
}
resolve_installation() {
[[ "$BUNDLE_DIR" = /* ]] || {
printf 'ERROR: --bundle-dir must be an absolute path\n' >&2
exit 2
}
[[ "$BUNDLE_DIR" != *$'\n'* ]] || {
printf 'ERROR: --bundle-dir contains a newline\n' >&2
exit 2
}
[[ -d "$BUNDLE_DIR" ]] || {
printf 'ERROR: bundle directory does not exist: %s\n' "$BUNDLE_DIR" >&2
exit 2
}
BUNDLE_DIR="$(cd -- "$BUNDLE_DIR" && pwd -P)"
[[ -f "$BUNDLE_DIR/compose.yaml" ]] || {
printf 'ERROR: compose.yaml not found in %s\n' "$BUNDLE_DIR" >&2
exit 2
}
if [[ -z "$MAIL_HOSTNAME" && -f "$BUNDLE_DIR/.env" ]]; then
MAIL_HOSTNAME="$(sed -n 's/^MAIL_HOSTNAME=//p' "$BUNDLE_DIR/.env" | tail -n 1)"
fi
if [[ -n "$MAIL_HOSTNAME" ]]; then
MAIL_HOSTNAME="${MAIL_HOSTNAME,,}"
[[ "$MAIL_HOSTNAME" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$ ]] || {
printf 'ERROR: invalid fully-qualified hostname: %s\n' "$MAIL_HOSTNAME" >&2
exit 2
}
elif ! $KEEP_CERTIFICATE; then
printf 'ERROR: hostname is unavailable; pass --hostname or use --keep-certificate\n' >&2
exit 2
fi
}
choose_optional_cleanup() {
$ASSUME_YES && return
[[ -t 0 ]] || {
printf 'ERROR: non-interactive use requires --yes\n' >&2
exit 1
}
if ! $PURGE_PACKAGES; then
printf '\nDocker, Nginx, and Certbot may be shared with other services.\n'
read -r -p "Also purge their APT packages and Docker APT source? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] && PURGE_PACKAGES=true
fi
if ! $REMOVE_BUNDLE; then
read -r -p "Also delete the repository directory $BUNDLE_DIR? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] && REMOVE_BUNDLE=true
fi
}
confirm_uninstall() {
cat <<EOF
MEOVV Mail will be permanently removed.
Hostname: ${MAIL_HOSTNAME:-unknown}
Bundle: $BUNDLE_DIR
Mailbox/app volumes: meovv-mail-app-data, meovv-mail-stalwart-config,
meovv-mail-stalwart-data
Certbot certificate: $([[ "$KEEP_CERTIFICATE" == true ]] && printf 'keep' || printf 'delete')
Host packages: $([[ "$PURGE_PACKAGES" == true ]] && printf 'purge' || printf 'keep')
Repository checkout: $([[ "$REMOVE_BUNDLE" == true ]] && printf 'delete' || printf 'keep')
All messages, accounts, application state, secrets, and local MEOVV backups
will be irreversibly deleted. Public DNS and provider settings are unchanged.
EOF
$ASSUME_YES && return
local expected answer
expected="${MAIL_HOSTNAME:-UNINSTALL}"
read -r -p "Type '$expected' to permanently uninstall: " answer
[[ "$answer" == "$expected" ]] || {
printf 'Uninstall cancelled.\n'
exit 1
}
}
remove_docker_resources() {
command -v docker >/dev/null 2>&1 || {
warn "Docker is not installed; skipping container cleanup"
return
}
if ! docker info >/dev/null 2>&1; then
systemctl start docker >/dev/null 2>&1 || {
record_failure "Docker is installed but its daemon could not be started; MEOVV Docker data remains"
return
}
fi
log "Removing MEOVV containers, network, images, and volumes"
local -a image_ids=() container_ids=() network_ids=()
local image_ref image_id
if docker compose version >/dev/null 2>&1 && [[ -f "$BUNDLE_DIR/compose.yaml" ]]; then
while IFS= read -r image_ref; do
[[ -n "$image_ref" ]] || continue
image_id="$(docker image inspect --format '{{.Id}}' "$image_ref" 2>/dev/null || true)"
[[ -n "$image_id" ]] && image_ids+=("$image_id")
done < <(
docker compose --project-directory "$BUNDLE_DIR" \
-f "$BUNDLE_DIR/compose.yaml" config --images 2>/dev/null
)
docker compose --project-directory "$BUNDLE_DIR" \
-f "$BUNDLE_DIR/compose.yaml" down --volumes --remove-orphans --timeout 30 || \
record_failure "Docker Compose could not remove every MEOVV resource"
fi
mapfile -t container_ids < <(docker ps -aq --filter "label=com.docker.compose.project=$PROJECT_NAME")
if ((${#container_ids[@]})); then
docker rm -f "${container_ids[@]}" >/dev/null || \
record_failure "some MEOVV containers could not be removed"
fi
local volume
for volume in "${MEOVV_VOLUMES[@]}"; do
if docker volume inspect "$volume" >/dev/null 2>&1; then
docker volume rm "$volume" >/dev/null || \
record_failure "Docker volume $volume could not be removed"
fi
done
mapfile -t network_ids < <(docker network ls -q --filter "label=com.docker.compose.project=$PROJECT_NAME")
if ((${#network_ids[@]})); then
docker network rm "${network_ids[@]}" >/dev/null || \
record_failure "some MEOVV Docker networks could not be removed"
fi
while IFS= read -r image_id; do
[[ -n "$image_id" ]] && image_ids+=("$image_id")
done < <(docker image ls --format '{{.Repository}} {{.ID}}' | awk '$1 == "meovv-mail" {print $2}')
if ((${#image_ids[@]})); then
mapfile -t image_ids < <(printf '%s\n' "${image_ids[@]}" | awk 'NF && !seen[$0]++')
docker image rm "${image_ids[@]}" >/dev/null 2>&1 || \
record_failure "one or more MEOVV images are still used elsewhere and were retained"
fi
}
remove_nginx_integration() {
log "Removing MEOVV Nginx configuration"
rm -f -- "$NGINX_ENABLED" "$NGINX_CONFD" "$NGINX_AVAILABLE"
if command -v nginx >/dev/null 2>&1; then
if nginx -t; then
systemctl reload nginx || record_failure "Nginx could not be reloaded"
else
record_failure "remaining Nginx configuration is invalid; Nginx was not reloaded"
fi
fi
}
remove_certbot_integration() {
log "Removing MEOVV Certbot integration"
rm -f -- "$CERTBOT_HOOK"
if ! $KEEP_CERTIFICATE && [[ -n "$MAIL_HOSTNAME" ]]; then
if command -v certbot >/dev/null 2>&1; then
if [[ -e "/etc/letsencrypt/renewal/$MAIL_HOSTNAME.conf" || \
-e "/etc/letsencrypt/live/$MAIL_HOSTNAME" || \
-e "/etc/letsencrypt/archive/$MAIL_HOSTNAME" ]]; then
certbot delete --cert-name "$MAIL_HOSTNAME" --non-interactive || \
record_failure "Certbot certificate $MAIL_HOSTNAME could not be deleted"
fi
else
record_failure "Certbot is unavailable; certificate $MAIL_HOSTNAME was not deleted"
fi
fi
rmdir --ignore-fail-on-non-empty "$CERTBOT_WEBROOT/.well-known/acme-challenge" 2>/dev/null || true
rmdir --ignore-fail-on-non-empty "$CERTBOT_WEBROOT/.well-known" 2>/dev/null || true
rmdir --ignore-fail-on-non-empty "$CERTBOT_WEBROOT" 2>/dev/null || true
}
remove_local_state() {
log "Removing MEOVV host utility, secrets, state, and local backups"
rm -f -- "$MAILCTL_BIN"
rm -rf -- \
"$BUNDLE_DIR/.env" \
"$BUNDLE_DIR/secrets" \
"$BUNDLE_DIR/backups" \
"$BUNDLE_DIR/web-dist"
}
purge_host_packages() {
$PURGE_PACKAGES || return
command -v apt-get >/dev/null 2>&1 || {
record_failure "APT is unavailable; requested host packages were not purged"
return
}
log "Purging Docker, Nginx, and Certbot packages"
local package
local -a installed=()
for package in "${OPTIONAL_APT_PACKAGES[@]}"; do
if dpkg-query -W -f='${db:Status-Abbrev}' "$package" 2>/dev/null | grep -q '^ii'; then
installed+=("$package")
fi
done
if ((${#installed[@]})); then
DEBIAN_FRONTEND=noninteractive apt-get purge -y "${installed[@]}" || \
record_failure "some requested APT packages could not be purged"
DEBIAN_FRONTEND=noninteractive apt-get autoremove --purge -y || \
record_failure "APT automatic dependency cleanup failed"
fi
rm -f -- /etc/apt/sources.list.d/docker.list /etc/apt/keyrings/docker.gpg
apt-get update || record_failure "APT metadata could not be refreshed after Docker source removal"
}
remove_bundle_checkout() {
$REMOVE_BUNDLE || return
case "$BUNDLE_DIR" in
/|/bin|/boot|/dev|/etc|/home|/opt|/root|/srv|/tmp|/usr|/var)
record_failure "refusing to delete unsafe bundle path $BUNDLE_DIR"
return
;;
esac
if [[ ! -f "$BUNDLE_DIR/compose.yaml" ]] || \
! grep -Eq '^name:[[:space:]]+meovv-mail[[:space:]]*$' "$BUNDLE_DIR/compose.yaml"; then
record_failure "refusing to delete $BUNDLE_DIR because it is not a recognizable MEOVV bundle"
return
fi
log "Removing repository checkout"
rm -rf -- "$BUNDLE_DIR"
}
main() {
parse_arguments "$@"
require_root
resolve_installation
choose_optional_cleanup
confirm_uninstall
remove_docker_resources
remove_nginx_integration
remove_certbot_integration
remove_local_state
purge_host_packages
remove_bundle_checkout
if ((FAILURES)); then
printf '\nMEOVV uninstall completed with %d warning(s). Review the messages above.\n' "$FAILURES" >&2
exit 1
fi
cat <<EOF
MEOVV Mail has been removed from this server.
Public DNS, PTR records, and provider firewall rules were intentionally retained.
$([[ "$PURGE_PACKAGES" == false ]] && printf 'Docker, Nginx, and Certbot packages were retained.\n')$([[ "$REMOVE_BUNDLE" == false ]] && printf 'The source checkout was retained at %s.\n' "$BUNDLE_DIR")
EOF
}
main "$@"