Archived
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65f81ff7cd | ||
|
|
b582f8b6f8 | ||
|
|
482e9bcb47 | ||
|
|
7159f122ce | ||
|
|
9272a10f72 | ||
|
|
2d84a780d4 | ||
|
|
493cc66bed | ||
|
|
ac34455f13 | ||
|
|
e0a3fd49da | ||
|
|
66f9811f48 | ||
|
|
fc2041a50c | ||
|
|
3f10533dbd | ||
|
|
4ac4a6d636 | ||
|
|
c5b2c2a1ec | ||
|
|
6aca6d5a80 | ||
|
|
6e97feb9a2 |
No files matched your search
@@ -1,5 +1,7 @@
|
||||
# Documentation only. Run `mailctl init`; do not deploy this file as `.env`.
|
||||
MEOVV_VERSION=0.1.0
|
||||
MAIL_HOSTNAME=mail.example.com
|
||||
MEOVV_HTTP_BIND=127.0.0.1:8080
|
||||
STALWART_HTTP_BIND=127.0.0.1:8081
|
||||
STALWART_RECOVERY_ADMIN=
|
||||
API_SUBMISSION_USER=
|
||||
@@ -20,6 +20,8 @@ body:
|
||||
options:
|
||||
- Ubuntu 24.04 amd64
|
||||
- Ubuntu 24.04 arm64
|
||||
- Ubuntu 26.04 amd64
|
||||
- Ubuntu 26.04 arm64
|
||||
- Debian 13 amd64
|
||||
- Debian 13 arm64
|
||||
- Development workstation
|
||||
|
||||
@@ -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,7 +43,12 @@ jobs:
|
||||
name: Appliance bundle
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- 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:
|
||||
MAIL_HOSTNAME: mail.example.com
|
||||
|
||||
@@ -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
|
||||
+2
-1
@@ -7,7 +7,8 @@ All notable project changes will be recorded here. This project follows
|
||||
|
||||
### Added
|
||||
|
||||
- Initial three-container self-hosted appliance architecture.
|
||||
- Initial two-container self-hosted appliance architecture with external Nginx
|
||||
and Certbot integration.
|
||||
- React/Vite mailbox, setup, authentication, and administration interfaces.
|
||||
- Go control plane, REST send API, JMAP session proxy, delivery events, and
|
||||
signed webhook delivery.
|
||||
|
||||
+2
-1
@@ -19,7 +19,8 @@ corrections are welcome while that policy is finalized.
|
||||
|
||||
## Development checks
|
||||
|
||||
Install Node.js 22+, Go 1.24+, and Docker with Compose. Then run:
|
||||
Install Node.js 22+, Go 1.24+, and Docker with Compose. Production deployments
|
||||
also require host-managed Nginx and Certbot. Then run:
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
MEOVV Mail is a single-tenant, self-hosted email appliance for one organization.
|
||||
It combines a polished web inbox and administration experience with a pinned Stalwart mail core,
|
||||
a Go control plane, and automatic HTTPS through Caddy.
|
||||
a Go control plane, and your host-managed Nginx and Certbot edge.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> MEOVV Mail is pre-1.0 software under active development. The architecture,
|
||||
@@ -19,19 +19,24 @@ and a scoped REST send API. POP3 and plaintext IMAP are not published.
|
||||
|
||||
## Architecture
|
||||
|
||||
The production bundle runs exactly three containers:
|
||||
The production bundle runs exactly two containers:
|
||||
|
||||
- `caddy` terminates public TLS, publishes discovery routes, and sends product traffic to MEOVV.
|
||||
- `meovv` serves the web application, encrypted OAuth sessions, REST API, setup, delivery metadata, webhook jobs, audit events, and operational endpoints.
|
||||
- `stalwart` stores accounts and all mailbox data and provides SMTP, IMAP, JMAP, filtering, queues, and delivery telemetry.
|
||||
|
||||
Nginx and Certbot remain host infrastructure outside Compose. Nginx terminates
|
||||
HTTPS and routes loopback-only upstreams to the two services. Stalwart receives
|
||||
a controlled copy of the Certbot certificate for SMTP and IMAP TLS. See
|
||||
[`docs/nginx-certbot.md`](docs/nginx-certbot.md).
|
||||
|
||||
Stalwart is pinned to `v0.16.17` and multi-architecture digest `sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa`.
|
||||
Mail bodies and attachments never enter the MEOVV SQLite database.
|
||||
|
||||
## Host requirements
|
||||
|
||||
- Ubuntu 24.04 or Debian 13 on amd64 or arm64
|
||||
- Ubuntu 24.04, Ubuntu 26.04, or Debian 13 on amd64 or arm64
|
||||
- Docker Engine with the Compose plugin
|
||||
- Host-managed Nginx and Certbot
|
||||
- 4 vCPU, 8 GB RAM, and SSD storage for the reference 500-account deployment
|
||||
- A public static IP and control of DNS for direct delivery
|
||||
- Inbound TCP 25, 80, 443, 465, 587, and 993
|
||||
@@ -41,24 +46,145 @@ Direct delivery also needs working reverse DNS and acceptable IP reputation. If
|
||||
|
||||
## Install
|
||||
|
||||
Build the local operator utility, initialize the bundle, and start it:
|
||||
For a fresh Ubuntu 24.04, Ubuntu 26.04, or Debian 13 server, clone this
|
||||
repository and run the host installer from the repository root. It installs
|
||||
Docker Engine with the Compose plugin, Nginx, Certbot, and required host
|
||||
utilities; initializes MEOVV; obtains the first Let's Encrypt certificate;
|
||||
installs renewal and proxy configuration; and starts the appliance:
|
||||
|
||||
```bash
|
||||
sudo ./scripts/install-server.sh install \
|
||||
--hostname mail.example.com \
|
||||
--email admin@example.com
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
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:
|
||||
|
||||
```bash
|
||||
go build -o mailctl ./cmd/mailctl
|
||||
./mailctl init --hostname mail.example.com
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
`mailctl init` prints a one-time browser bootstrap token and temporary Stalwart recovery credential. Store both securely. Visit `https://mail.example.com`, complete the three-step wizard, and save the one-time result shown on the final screen.
|
||||
`mailctl init` prints a one-time browser bootstrap token and temporary Stalwart
|
||||
recovery credential. Store both securely. Next, issue the hostname certificate,
|
||||
install the provided Nginx route split, and copy the Certbot lineage by following
|
||||
[`docs/nginx-certbot.md`](docs/nginx-certbot.md). Then start the appliance:
|
||||
|
||||
```bash
|
||||
docker compose up -d --build --remove-orphans
|
||||
```
|
||||
|
||||
Visit `https://mail.example.com`, complete the three-step wizard, and save the
|
||||
one-time result shown on the final screen.
|
||||
|
||||
After setup:
|
||||
|
||||
```bash
|
||||
docker compose restart stalwart meovv
|
||||
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
|
||||
@@ -109,7 +235,7 @@ Create a consistency-safe backup:
|
||||
./mailctl backup
|
||||
```
|
||||
|
||||
The command stops Stalwart and MEOVV writers, archives all five named volumes plus Compose configuration and secrets, writes SHA-256 checksums, and restarts the services. Restore is intentionally destructive and only accepts a backup from the same MEOVV and Stalwart release:
|
||||
The command stops Stalwart and MEOVV writers, archives all three named volumes plus Compose configuration and secrets, writes SHA-256 checksums, and restarts the services. Host-managed Nginx and Certbot configuration remains part of the host backup policy. Restore is intentionally destructive and only accepts a backup from the same MEOVV and Stalwart release:
|
||||
|
||||
```bash
|
||||
./mailctl restore --from backups/20260812T103000Z --yes
|
||||
|
||||
+1
-1
@@ -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">
|
||||
|
||||
+197
-7
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
@@ -15,6 +16,8 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -35,8 +38,6 @@ const (
|
||||
)
|
||||
|
||||
var volumeArchives = map[string]string{
|
||||
"meovv-mail-caddy-data": "caddy-data.tgz",
|
||||
"meovv-mail-caddy-config": "caddy-config.tgz",
|
||||
"meovv-mail-app-data": "meovv-data.tgz",
|
||||
"meovv-mail-stalwart-config": "stalwart-config.tgz",
|
||||
"meovv-mail-stalwart-data": "stalwart-data.tgz",
|
||||
@@ -63,6 +64,8 @@ func main() {
|
||||
err = doctor(os.Args[2:])
|
||||
case "create-api-key":
|
||||
err = createAPIKey(os.Args[2:])
|
||||
case "configure-tls":
|
||||
err = configureTLS(os.Args[2:])
|
||||
case "backup":
|
||||
err = backup(os.Args[2:])
|
||||
case "restore":
|
||||
@@ -94,6 +97,7 @@ Usage: mailctl <command> [options]
|
||||
init Create .env and one-time installation secrets
|
||||
doctor Check DNS, ports, files, and the running appliance
|
||||
create-api-key Create a hashed REST API key (run inside app container)
|
||||
configure-tls Register the Certbot certificate with Stalwart
|
||||
backup Stop mail writers and create a checksummed backup
|
||||
restore Verify and restore a same-release backup
|
||||
upgrade Verify compatibility, back up, and apply an approved release
|
||||
@@ -126,6 +130,9 @@ func initialize(args []string) error {
|
||||
if err = os.MkdirAll(secretDir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Join(secretDir, "tls"), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
values := map[string]string{
|
||||
"bootstrap_token": randomSecret(32),
|
||||
"session_key": randomSecret(32),
|
||||
@@ -138,11 +145,11 @@ func initialize(args []string) error {
|
||||
}
|
||||
}
|
||||
recovery := "admin:" + randomSecret(24)
|
||||
env := fmt.Sprintf("MEOVV_VERSION=%s\nMAIL_HOSTNAME=%s\nSTALWART_RECOVERY_ADMIN=%s\nAPI_SUBMISSION_USER=api-sender@%s\n", version, *hostname, recovery, strings.TrimPrefix(*hostname, "mail."))
|
||||
env := fmt.Sprintf("MEOVV_VERSION=%s\nMAIL_HOSTNAME=%s\nMEOVV_HTTP_BIND=127.0.0.1:8080\nSTALWART_HTTP_BIND=127.0.0.1:8081\nSTALWART_RECOVERY_ADMIN=%s\nAPI_SUBMISSION_USER=api-sender@%s\n", version, *hostname, recovery, strings.TrimPrefix(*hostname, "mail."))
|
||||
if err = writeExclusive(filepath.Join(root, ".env"), []byte(env), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Initialized %s\nBootstrap token: %s\nTemporary Stalwart recovery user: admin\nTemporary Stalwart recovery password: %s\n\nStore these values securely. Run 'docker compose up -d --build', complete setup, create a permanent administrator, then run 'mailctl harden'.\n", root, values["bootstrap_token"], strings.TrimPrefix(recovery, "admin:"))
|
||||
fmt.Printf("Initialized %s\nBootstrap token: %s\nTemporary Stalwart recovery user: admin\nTemporary Stalwart recovery password: %s\n\nStore these values securely. Configure host Nginx/Certbot, run 'docker compose up -d --build --remove-orphans', complete setup, then run 'mailctl configure-tls' before 'mailctl harden'.\n", root, values["bootstrap_token"], strings.TrimPrefix(recovery, "admin:"))
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -171,6 +178,12 @@ func doctor(args []string) error {
|
||||
check("Compose bundle", err)
|
||||
_, err = os.Stat(filepath.Join(root, "secrets", "session_key"))
|
||||
check("Secrets", err)
|
||||
_, err = os.Stat(filepath.Join(root, "secrets", "tls", "fullchain.pem"))
|
||||
check("TLS certificate", err)
|
||||
_, err = os.Stat(filepath.Join(root, "secrets", "tls", "privkey.pem"))
|
||||
check("TLS private key", err)
|
||||
_, err = os.Stat(filepath.Join(root, "secrets", "tls", "certificate_id"))
|
||||
check("Stalwart TLS link", err)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
addresses, err := net.DefaultResolver.LookupHost(ctx, *hostname)
|
||||
@@ -236,6 +249,183 @@ func createAPIKey(args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
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/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 {
|
||||
return err
|
||||
}
|
||||
root, _ := filepath.Abs(*dir)
|
||||
managementURL, err := url.Parse(*endpoint)
|
||||
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)
|
||||
if managementHost != "localhost" && (managementIP == nil || !managementIP.IsLoopback()) {
|
||||
return errors.New("--url must use localhost or a loopback IP so the recovery credential is never sent over a network")
|
||||
}
|
||||
for _, name := range []string{"fullchain.pem", "privkey.pem"} {
|
||||
if _, err := os.Stat(filepath.Join(root, "secrets", "tls", name)); err != nil {
|
||||
return fmt.Errorf("secrets/tls/%s is unavailable; copy the Certbot lineage first: %w", name, err)
|
||||
}
|
||||
}
|
||||
env, err := readEnv(filepath.Join(root, ".env"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
recovery := env["STALWART_RECOVERY_ADMIN"]
|
||||
if parts := strings.SplitN(recovery, ":", 2); len(parts) != 2 || parts[0] == "" || parts[1] == "" {
|
||||
return errors.New("STALWART_RECOVERY_ADMIN is required; run configure-tls before mailctl harden")
|
||||
}
|
||||
idPath := filepath.Join(root, "secrets", "tls", "certificate_id")
|
||||
idBytes, readErr := os.ReadFile(idPath)
|
||||
certificateID := strings.TrimSpace(string(idBytes))
|
||||
certificate := map[string]any{"@type": "File", "filePath": *certificatePath}
|
||||
privateKey := map[string]any{"@type": "File", "filePath": *privateKeyPath}
|
||||
var payload map[string]any
|
||||
creating := errors.Is(readErr, os.ErrNotExist) || certificateID == ""
|
||||
if readErr != nil && !errors.Is(readErr, os.ErrNotExist) {
|
||||
return readErr
|
||||
}
|
||||
if creating {
|
||||
payload = jmapPayload("x:Certificate/set", map[string]any{"create": map[string]any{"certbot": map[string]any{"certificate": certificate, "privateKey": privateKey}}}, "certificate")
|
||||
} else {
|
||||
payload = jmapPayload("x:Certificate/set", map[string]any{"update": map[string]any{certificateID: map[string]any{"certificate": certificate, "privateKey": privateKey}}}, "certificate")
|
||||
}
|
||||
raw, err := callStalwart(*endpoint, recovery, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if creating {
|
||||
certificateID, err = createdObjectID(raw, "certbot")
|
||||
} else {
|
||||
err = jmapSucceeded(raw)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("register Certbot certificate: %w", err)
|
||||
}
|
||||
if creating {
|
||||
if err = writeExclusive(idPath, []byte(certificateID+"\n"), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payload = jmapPayload("x:SystemSettings/set", map[string]any{"update": map[string]any{"singleton": map[string]any{"defaultCertificateId": certificateID}}}, "settings")
|
||||
raw, err = callStalwart(*endpoint, recovery, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = jmapSucceeded(raw); err != nil {
|
||||
return fmt.Errorf("select default certificate: %w", err)
|
||||
}
|
||||
if err = run(root, "docker", "compose", "restart", "stalwart"); err != nil {
|
||||
return fmt.Errorf("certificate registered, but Stalwart could not be restarted: %w", err)
|
||||
}
|
||||
fmt.Println("Certbot certificate registered as Stalwart's default TLS certificate.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func jmapPayload(method string, arguments map[string]any, callID string) map[string]any {
|
||||
return map[string]any{
|
||||
"using": []string{"urn:ietf:params:jmap:core", "urn:stalwart:jmap"},
|
||||
"methodCalls": []any{[]any{method, arguments, callID}},
|
||||
}
|
||||
}
|
||||
|
||||
func callStalwart(endpoint, recovery string, payload any) ([]byte, error) {
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.SplitN(recovery, ":", 2)
|
||||
req.SetBasicAuth(parts[0], parts[1])
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.Proxy = nil
|
||||
client := &http.Client{
|
||||
Timeout: 20 * time.Second,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("contact Stalwart management endpoint: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.StatusCode/100 != 2 {
|
||||
return nil, fmt.Errorf("Stalwart returned %s: %s", response.Status, strings.TrimSpace(string(body)))
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func jmapMethodBody(raw []byte) (string, json.RawMessage, error) {
|
||||
var response struct {
|
||||
MethodResponses [][]json.RawMessage `json:"methodResponses"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &response); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
if len(response.MethodResponses) != 1 || len(response.MethodResponses[0]) < 2 {
|
||||
return "", nil, fmt.Errorf("unexpected JMAP response: %s", strings.TrimSpace(string(raw)))
|
||||
}
|
||||
var method string
|
||||
if err := json.Unmarshal(response.MethodResponses[0][0], &method); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return method, response.MethodResponses[0][1], nil
|
||||
}
|
||||
|
||||
func jmapSucceeded(raw []byte) error {
|
||||
method, body, err := jmapMethodBody(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if method == "error" || bytes.Contains(body, []byte(`"notUpdated"`)) || bytes.Contains(body, []byte(`"notCreated"`)) {
|
||||
return fmt.Errorf("Stalwart rejected the change: %s", strings.TrimSpace(string(body)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createdObjectID(raw []byte, clientID string) (string, error) {
|
||||
method, body, err := jmapMethodBody(raw)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if method == "error" {
|
||||
return "", fmt.Errorf("Stalwart rejected the change: %s", strings.TrimSpace(string(body)))
|
||||
}
|
||||
var result struct {
|
||||
Created map[string]struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"created"`
|
||||
NotCreated map[string]json.RawMessage `json:"notCreated"`
|
||||
}
|
||||
if err = json.Unmarshal(body, &result); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if failure := result.NotCreated[clientID]; len(failure) > 0 {
|
||||
return "", fmt.Errorf("Stalwart rejected the certificate: %s", strings.TrimSpace(string(failure)))
|
||||
}
|
||||
id := result.Created[clientID].ID
|
||||
if id == "" {
|
||||
return "", fmt.Errorf("certificate id missing from response: %s", strings.TrimSpace(string(body)))
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func backup(args []string) error {
|
||||
fs := flag.NewFlagSet("backup", flag.ContinueOnError)
|
||||
dir := fs.String("directory", ".", "Compose bundle directory")
|
||||
@@ -306,7 +496,7 @@ func restore(args []string) error {
|
||||
if manifest.MEOVVVersion != version || manifest.StalwartVersion != stalwartVersion {
|
||||
return fmt.Errorf("backup release is MEOVV %s / Stalwart %s; this binary is %s / %s", manifest.MEOVVVersion, manifest.StalwartVersion, version, stalwartVersion)
|
||||
}
|
||||
if err = run(root, "docker", "compose", "stop", "meovv", "stalwart", "caddy"); err != nil {
|
||||
if err = run(root, "docker", "compose", "stop", "meovv", "stalwart"); err != nil {
|
||||
return err
|
||||
}
|
||||
for volume, archive := range volumeArchives {
|
||||
@@ -469,7 +659,7 @@ func archiveConfiguration(root, destination string) error {
|
||||
defer gz.Close()
|
||||
tw := tar.NewWriter(gz)
|
||||
defer tw.Close()
|
||||
paths := []string{".env", "compose.yaml", "deploy/caddy/Caddyfile"}
|
||||
paths := []string{".env", "compose.yaml"}
|
||||
_ = filepath.WalkDir(filepath.Join(root, "secrets"), func(path string, entry os.DirEntry, walkErr error) error {
|
||||
if walkErr == nil && !entry.IsDir() {
|
||||
rel, _ := filepath.Rel(root, path)
|
||||
@@ -522,7 +712,7 @@ func restoreConfiguration(root, archive string) error {
|
||||
return err
|
||||
}
|
||||
clean := filepath.Clean(header.Name)
|
||||
if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") || (clean != ".env" && clean != "compose.yaml" && clean != "deploy/caddy/Caddyfile" && !strings.HasPrefix(clean, "secrets/")) {
|
||||
if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") || (clean != ".env" && clean != "compose.yaml" && !strings.HasPrefix(clean, "secrets/")) {
|
||||
return fmt.Errorf("unsafe configuration archive entry %q", header.Name)
|
||||
}
|
||||
target := filepath.Join(root, clean)
|
||||
|
||||
@@ -1,9 +1,52 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSignedCompatibilityManifest(t *testing.T) {
|
||||
if err := verifyCompatibility("../../release/compatibility.json", "../../release/compatibility.sig"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatedObjectID(t *testing.T) {
|
||||
raw := []byte(`{"methodResponses":[["x:Certificate/set",{"created":{"certbot":{"id":"cert_123"}}},"certificate"]]}`)
|
||||
id, err := createdObjectID(raw, "certbot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id != "cert_123" {
|
||||
t.Fatalf("got %q", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatedObjectIDRejectsNotCreated(t *testing.T) {
|
||||
raw := []byte(`{"methodResponses":[["x:Certificate/set",{"notCreated":{"certbot":{"type":"invalidProperties"}}},"certificate"]]}`)
|
||||
_, err := createdObjectID(raw, "certbot")
|
||||
if err == nil || !strings.Contains(err.Error(), "invalidProperties") {
|
||||
t.Fatalf("expected Stalwart error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJMAPSucceededRejectsFailedUpdate(t *testing.T) {
|
||||
raw := []byte(`{"methodResponses":[["x:SystemSettings/set",{"notUpdated":{"singleton":{"type":"forbidden"}}},"settings"]]}`)
|
||||
if err := jmapSucceeded(raw); err == nil || !strings.Contains(err.Error(), "forbidden") {
|
||||
t.Fatalf("expected forbidden update, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigureTLSRejectsRemoteManagementURL(t *testing.T) {
|
||||
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/jmap"})
|
||||
if err == nil || !strings.Contains(err.Error(), "loopback HTTP URL") {
|
||||
t.Fatalf("expected plain loopback HTTP requirement, got %v", err)
|
||||
}
|
||||
}
|
||||
+6
-25
@@ -1,25 +1,6 @@
|
||||
name: meovv-mail
|
||||
|
||||
services:
|
||||
caddy:
|
||||
image: caddy:2.10.2-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MAIL_HOSTNAME: ${MAIL_HOSTNAME:?Set MAIL_HOSTNAME in .env}
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./deploy/caddy/Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- caddy_data:/data
|
||||
- caddy_config:/config
|
||||
networks: [mail]
|
||||
depends_on:
|
||||
meovv:
|
||||
condition: service_healthy
|
||||
stalwart:
|
||||
condition: service_started
|
||||
|
||||
meovv:
|
||||
build:
|
||||
context: .
|
||||
@@ -32,9 +13,9 @@ services:
|
||||
MEOVV_BOOTSTRAP_TOKEN_FILE: /run/secrets/bootstrap_token
|
||||
MEOVV_INTERNAL_WEBHOOK_SECRET_FILE: /run/secrets/internal_webhook_secret
|
||||
MEOVV_SESSION_KEY_FILE: /run/secrets/session_key
|
||||
STALWART_URL: https://stalwart:443
|
||||
STALWART_URL: http://stalwart:8080
|
||||
STALWART_BOOTSTRAP_URL: http://stalwart:8080
|
||||
STALWART_TLS_INSECURE: "true"
|
||||
STALWART_TLS_INSECURE: "false"
|
||||
STALWART_RECOVERY_ADMIN: ${STALWART_RECOVERY_ADMIN:-}
|
||||
STALWART_SMTP_ADDRESS: stalwart:587
|
||||
STALWART_TLS_SERVER_NAME: ${MAIL_HOSTNAME}
|
||||
@@ -43,6 +24,8 @@ services:
|
||||
volumes:
|
||||
- meovv_data:/var/lib/meovv-mail
|
||||
- ./secrets:/run/secrets:ro
|
||||
ports:
|
||||
- "${MEOVV_HTTP_BIND:-127.0.0.1:8080}:8080"
|
||||
networks: [mail]
|
||||
depends_on:
|
||||
stalwart:
|
||||
@@ -60,6 +43,7 @@ services:
|
||||
STALWART_PUBLIC_URL: https://${MAIL_HOSTNAME}
|
||||
STALWART_RECOVERY_ADMIN: ${STALWART_RECOVERY_ADMIN:-}
|
||||
ports:
|
||||
- "${STALWART_HTTP_BIND:-127.0.0.1:8081}:8080"
|
||||
- "25:25"
|
||||
- "465:465"
|
||||
- "587:587"
|
||||
@@ -67,6 +51,7 @@ services:
|
||||
volumes:
|
||||
- stalwart_config:/etc/stalwart
|
||||
- stalwart_data:/var/lib/stalwart
|
||||
- ./secrets/tls:/etc/stalwart/tls:ro
|
||||
networks: [mail]
|
||||
|
||||
networks:
|
||||
@@ -74,10 +59,6 @@ networks:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
caddy_data:
|
||||
name: meovv-mail-caddy-data
|
||||
caddy_config:
|
||||
name: meovv-mail-caddy-config
|
||||
meovv_data:
|
||||
name: meovv-mail-app-data
|
||||
stalwart_config:
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
{$MAIL_HOSTNAME} {
|
||||
encode zstd gzip
|
||||
|
||||
@meovv path / /assets/* /favicon.svg /health/* /metrics /api/setup/* /api/session/* /api/mail/* /api/admin/* /api/internal/* /api/v1/*
|
||||
handle @meovv {
|
||||
reverse_proxy meovv:8080
|
||||
}
|
||||
|
||||
@stalwart path /.well-known/* /jmap /jmap/* /auth/* /api/auth /api/discover/* /api/account /api/token/* /mail/config-v1.1.xml /autodiscover/*
|
||||
handle @stalwart {
|
||||
reverse_proxy https://stalwart:443 {
|
||||
transport http {
|
||||
tls_insecure_skip_verify
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handle {
|
||||
reverse_proxy meovv:8080
|
||||
}
|
||||
|
||||
header {
|
||||
Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||
-Server
|
||||
}
|
||||
}
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${RENEWED_LINEAGE:?Certbot must provide RENEWED_LINEAGE}"
|
||||
|
||||
bundle_dir="${MEOVV_BUNDLE_DIR:-/opt/meovv-mail}"
|
||||
tls_dir="$bundle_dir/secrets/tls"
|
||||
|
||||
if [ ! -f "$bundle_dir/compose.yaml" ]; then
|
||||
echo "MEOVV bundle not found at $bundle_dir" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
install -d -m 700 "$tls_dir"
|
||||
install -m 644 "$RENEWED_LINEAGE/fullchain.pem" "$tls_dir/fullchain.pem"
|
||||
install -m 600 "$RENEWED_LINEAGE/privkey.pem" "$tls_dir/privkey.pem"
|
||||
|
||||
# Once the Certificate object points at /etc/stalwart/tls, restarting Stalwart
|
||||
# makes renewed files active for SMTP submission and IMAP TLS as well as HTTPS.
|
||||
if [ -n "$(cd "$bundle_dir" && docker compose ps -q stalwart 2>/dev/null || true)" ]; then
|
||||
cd "$bundle_dir"
|
||||
docker compose restart stalwart
|
||||
fi
|
||||
@@ -0,0 +1,71 @@
|
||||
# Managed by MEOVV Mail installer. Replace every __MAIL_HOSTNAME__ token before enabling this file.
|
||||
# The upstream ports are loopback-only bindings from compose.yaml.
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name __MAIL_HOSTNAME__;
|
||||
|
||||
# Keep this location if Certbot uses the webroot authenticator.
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
default_type text/plain;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name __MAIL_HOSTNAME__;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/__MAIL_HOSTNAME__/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/__MAIL_HOSTNAME__/privkey.pem;
|
||||
|
||||
client_max_body_size 35m;
|
||||
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
# Stalwart owns public discovery, OAuth, JMAP, and client-autoconfiguration
|
||||
# routes. The HTTP upstream is safe because it is bound to loopback only.
|
||||
location ~* ^/(?:\.well-known(?:/|$)|jmap(?:/|$)|auth(?:/|$)|api/(?:auth(?:/|$)|discover(?:/|$)|account(?:/|$)|token(?:/|$))|mail/config-v1\.1\.xml$|autodiscover(?:/|$)) {
|
||||
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_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 75s;
|
||||
}
|
||||
|
||||
# JMAP push is proxied by MEOVV as a server-sent event stream.
|
||||
location = /api/mail/events {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
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_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 75s;
|
||||
}
|
||||
|
||||
# The product UI, sessions, REST API, administration, health, and metrics.
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
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_read_timeout 75s;
|
||||
}
|
||||
}
|
||||
+12
-2
@@ -2,9 +2,19 @@
|
||||
|
||||
## Trust and data boundaries
|
||||
|
||||
Public HTTPS reaches Caddy first. Caddy sends product UI, session, administration, health, and REST API routes to the Go service. Standards discovery, OAuth authorization, public JMAP, mail-client configuration, and ACME challenge routes go to Stalwart. Mail protocols reach Stalwart directly on their dedicated TLS-capable ports, so Stalwart obtains its own certificate for SMTP and IMAP while Caddy independently manages the public web certificate.
|
||||
Public HTTPS reaches host-managed Nginx first. Nginx sends product UI, session,
|
||||
administration, health, and REST API routes to the loopback MEOVV upstream.
|
||||
Standards discovery, OAuth authorization, public JMAP, and mail-client
|
||||
configuration routes go to the loopback Stalwart HTTP upstream. Neither upstream
|
||||
port is publicly bound.
|
||||
|
||||
The branded sign-in form posts the password directly to same-origin `/api/auth`, which Caddy routes to Stalwart. The browser creates a PKCE verifier and sends only the one-time authorization code and verifier to MEOVV. The Go service exchanges that code, encrypts access and refresh tokens with AES-GCM, and returns an opaque Secure, HttpOnly, SameSite cookie. User passwords are never sent to or persisted by MEOVV.
|
||||
Mail protocols reach Stalwart directly on their dedicated TLS-capable ports.
|
||||
Certbot remains the single certificate authority client: its deploy hook copies
|
||||
the hostname certificate into the appliance's protected `secrets/tls` directory.
|
||||
Stalwart loads that certificate through file-backed `Certificate` fields for
|
||||
SMTP and IMAP, while Nginx reads the original Certbot lineage for HTTPS.
|
||||
|
||||
The branded sign-in form posts the password directly to same-origin `/api/auth`, which Nginx routes to Stalwart. The browser creates a PKCE verifier and sends only the one-time authorization code and verifier to MEOVV. The Go service exchanges that code, encrypts access and refresh tokens with AES-GCM, and returns an opaque Secure, HttpOnly, SameSite cookie. User passwords are never sent to or persisted by MEOVV.
|
||||
|
||||
Authenticated browser JMAP calls go through `/api/mail/jmap`; discovery goes through `/api/mail/session`; the event stream uses `/api/mail/events`. The Stalwart adapter is the only Go package that knows these upstream routes, which contains pre-1.0 compatibility changes.
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Nginx and Certbot integration
|
||||
|
||||
Nginx and Certbot are host infrastructure. They are intentionally not part of
|
||||
the MEOVV Compose project. Compose publishes two HTTP upstreams on loopback:
|
||||
|
||||
- `127.0.0.1:8080` — MEOVV web application and product API
|
||||
- `127.0.0.1:8081` — Stalwart discovery, OAuth, JMAP, and autoconfiguration
|
||||
|
||||
Mail protocols remain directly exposed by Stalwart on 25, 465, 587, and 993.
|
||||
|
||||
## Automated host setup
|
||||
|
||||
On a fresh supported server, the repository installer performs the host steps
|
||||
documented below without putting Nginx or Certbot inside Compose:
|
||||
|
||||
```bash
|
||||
sudo ./scripts/install-server.sh install \
|
||||
--hostname mail.example.com \
|
||||
--email admin@example.com
|
||||
```
|
||||
|
||||
Run it from the cloned repository root, or pass the repository's absolute path
|
||||
with `--bundle-dir`. It supports Ubuntu 24.04, Ubuntu 26.04, and Debian 13.
|
||||
Before running it, point the hostname's A/AAAA record at the server and allow
|
||||
inbound port 80. The script obtains a certificate using Certbot's webroot flow,
|
||||
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 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,
|
||||
replace `__MAIL_HOSTNAME__`, and change the two upstream ports if the bind values
|
||||
in `.env` were customized. The routing split is required: sending every path to
|
||||
MEOVV breaks OAuth/JMAP discovery, while sending every path to Stalwart hides the
|
||||
MEOVV interface and REST API.
|
||||
|
||||
Validate and reload using the host's normal Nginx process. The example keeps
|
||||
ACME HTTP-01 challenges under `/var/www/certbot`; it is compatible with Certbot's
|
||||
webroot authenticator. If your existing Certbot integration uses the Nginx
|
||||
authenticator, retain its generated challenge configuration instead.
|
||||
|
||||
The complete example references the final Certbot lineage and therefore should
|
||||
be enabled only after that lineage exists. For a new hostname, obtain the first
|
||||
certificate through your existing Nginx integration or a temporary port-80-only
|
||||
challenge server, then enable the HTTPS server block.
|
||||
|
||||
Both Compose HTTP bindings default to `127.0.0.1`. Do not change them to a public
|
||||
address. The Stalwart management/recovery endpoint must never be internet-facing.
|
||||
|
||||
## One certificate, two termination points
|
||||
|
||||
Nginx uses the Certbot certificate for HTTPS. Stalwart must use the same
|
||||
certificate independently for SMTP submission and IMAP TLS. MEOVV mounts:
|
||||
|
||||
```text
|
||||
secrets/tls/fullchain.pem -> /etc/stalwart/tls/fullchain.pem
|
||||
secrets/tls/privkey.pem -> /etc/stalwart/tls/privkey.pem
|
||||
```
|
||||
|
||||
After Certbot has issued the hostname certificate, make the initial controlled
|
||||
copy (replace the two paths as needed):
|
||||
|
||||
```bash
|
||||
sudo env \
|
||||
MEOVV_BUNDLE_DIR=/opt/meovv-mail \
|
||||
RENEWED_LINEAGE=/etc/letsencrypt/live/mail.example.com \
|
||||
/opt/meovv-mail/deploy/certbot/deploy-hook.sh
|
||||
```
|
||||
|
||||
Start the two containers and complete the MEOVV browser setup. Before removing
|
||||
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
|
||||
```
|
||||
|
||||
`configure-tls` sends the recovery credential only to the loopback Stalwart
|
||||
endpoint. It creates or updates a Stalwart `Certificate` object using file
|
||||
references, selects it as `defaultCertificateId`, records the object id in
|
||||
`secrets/tls/certificate_id`, and restarts Stalwart. If the Stalwart loopback
|
||||
port was changed, pass a loopback URL explicitly:
|
||||
|
||||
```bash
|
||||
./mailctl configure-tls --url http://127.0.0.1:9081/jmap
|
||||
```
|
||||
|
||||
## Renewal hook
|
||||
|
||||
Install the hook in Certbot's renewal deploy-hook directory and set the bundle
|
||||
location inside a small wrapper or Certbot service environment. For example:
|
||||
|
||||
```bash
|
||||
sudo install -m 0755 \
|
||||
/opt/meovv-mail/deploy/certbot/deploy-hook.sh \
|
||||
/etc/letsencrypt/renewal-hooks/deploy/meovv-mail
|
||||
```
|
||||
|
||||
The default hook expects the bundle at `/opt/meovv-mail`; set
|
||||
`MEOVV_BUNDLE_DIR` if it lives elsewhere. Certbot supplies `RENEWED_LINEAGE`.
|
||||
The hook copies only the certificate chain and private key, applies restrictive
|
||||
permissions, and restarts Stalwart if it is running. When installed by
|
||||
`install-server.sh`, a managed wrapper also validates and reloads Nginx after a
|
||||
successful copy. Manual installations should retain their existing Nginx reload
|
||||
hook or add an equivalent one.
|
||||
|
||||
Test the entire renewal path before production:
|
||||
|
||||
```bash
|
||||
sudo certbot renew --dry-run
|
||||
openssl s_client -connect mail.example.com:465 -servername mail.example.com </dev/null
|
||||
openssl s_client -connect mail.example.com:993 -servername mail.example.com </dev/null
|
||||
```
|
||||
|
||||
Confirm that HTTPS, SMTP submission, and IMAP present the same current hostname
|
||||
certificate after the dry run.
|
||||
+9
-1
@@ -4,9 +4,17 @@
|
||||
|
||||
Direct delivery is the default. Use it only when the host has a stable public IP, outbound TCP 25, correct PTR, and an IP range suitable for email. Relay mode sends through an authenticated TLS smart host and is the supported fallback. Changing mode does not require reinstalling; update the delivery configuration and run diagnostics before switching traffic.
|
||||
|
||||
## Edge proxy and certificates
|
||||
|
||||
Nginx and Certbot are operated outside Compose. The required path split,
|
||||
loopback bindings, initial certificate registration, and renewal hook are in
|
||||
[`nginx-certbot.md`](nginx-certbot.md). After every Nginx or certificate-policy
|
||||
change, verify HTTPS plus TLS on ports 465 and 993; success on HTTPS alone does
|
||||
not prove mail clients receive the renewed certificate.
|
||||
|
||||
## Backups and restore drills
|
||||
|
||||
`mailctl backup` stops the two data writers, archives every named volume and the host configuration/secrets, computes checksums, and starts the services again. Copy the resulting directory to storage that is encrypted, access-controlled, and separate from the mail host.
|
||||
`mailctl backup` stops the two data writers, archives the three appliance volumes and appliance configuration/secrets, computes checksums, and starts the services again. Nginx configuration and the canonical Certbot lineage are external host state and must be covered by the host's backup policy. Copy the resulting directory to storage that is encrypted, access-controlled, and separate from the mail host.
|
||||
|
||||
Run a restore drill for every release:
|
||||
|
||||
|
||||
+7
-2
@@ -11,14 +11,19 @@
|
||||
- Email HTML is sanitized, remote content is blocked by default, and attachment filenames are reduced to safe basenames.
|
||||
- Webhooks require public HTTPS and reject loopback, private, link-local, unspecified, and multicast resolutions.
|
||||
- External webhooks sign `{timestamp}.{raw_body}` with HMAC-SHA256 and retain event IDs across retries.
|
||||
- Caddy adds HSTS; the application adds CSP, anti-framing, MIME-sniffing, referrer, and permissions policies.
|
||||
- The provided Nginx template adds HSTS and response hardening; the application adds CSP, anti-framing, MIME-sniffing, referrer, and permissions policies.
|
||||
- Only 25, 465, 587, and 993 are published for mail. POP3 and plaintext IMAP are absent.
|
||||
|
||||
## Deployment invariants
|
||||
|
||||
Before exposure, confirm that unauthenticated SMTP cannot relay to a third-party domain, sender authorization is enforced on submission, recovery administrator access is removed, and Stalwart's spam/phishing, SPF, DKIM, DMARC, TLS, abuse-ban, and rate-limit defaults remain enabled.
|
||||
|
||||
The internal Docker network is not a trust substitute. Stalwart delivery events use a separate shared HMAC secret. The Stalwart management API is not routed publicly by Caddy; administrators use the authenticated Go adapter.
|
||||
The internal Docker network is not a trust substitute. Stalwart delivery events use a separate shared HMAC secret. The Stalwart management API is not routed publicly by Nginx; administrators use the authenticated Go adapter. Compose binds recovery HTTP to loopback only, and `mailctl configure-tls` rejects non-loopback management URLs before sending the temporary recovery credential.
|
||||
|
||||
The operator must configure Stalwart to trust forwarded HTTP headers only from
|
||||
the exact Docker bridge used by the host Nginx connection. Never trust arbitrary
|
||||
public networks, and never publish the Stalwart HTTP binding on a non-loopback
|
||||
host address.
|
||||
|
||||
## Audit and response
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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) {
|
||||
|
||||
@@ -20,7 +20,7 @@ type Client struct {
|
||||
|
||||
func New(base string, insecure bool) *Client {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} // Internal Docker TLS; public TLS terminates at Caddy.
|
||||
transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} // #nosec G402 -- explicitly controlled for deployments that re-encrypt to a private Stalwart endpoint.
|
||||
return &Client{BaseURL: strings.TrimRight(base, "/"), HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport}}
|
||||
}
|
||||
|
||||
@@ -32,14 +32,14 @@ func (c *Client) Bootstrap(ctx context.Context, bootstrapURL, recoveryAdmin, hos
|
||||
payload := map[string]any{
|
||||
"using": []string{"urn:ietf:params:jmap:core", "urn:stalwart:jmap"},
|
||||
"methodCalls": []any{[]any{"x:Bootstrap/set", map[string]any{"update": map[string]any{"singleton": map[string]any{
|
||||
"serverHostname": hostname, "defaultDomain": domain, "requestTlsCertificate": true, "generateDkimKeys": true,
|
||||
"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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Executable
+1001
File diff suppressed because it is too large.
Load diff
Executable
+384
@@ -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 "$@"
|
||||
@@ -14,11 +14,13 @@ test("builds the standalone MEOVV application shell", async () => {
|
||||
});
|
||||
|
||||
test("includes production auth, JMAP, sanitization, and responsive UI paths", async () => {
|
||||
const [page, css, openapi, standalone] = await Promise.all([
|
||||
const [page, css, openapi, standalone, compose, nginx] = await Promise.all([
|
||||
readFile(new URL("../app/page.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../app/globals.css", import.meta.url), "utf8"),
|
||||
readFile(new URL("../api/openapi.yaml", import.meta.url), "utf8"),
|
||||
readFile(new URL("../web-dist/index.html", import.meta.url), "utf8"),
|
||||
readFile(new URL("../compose.yaml", import.meta.url), "utf8"),
|
||||
readFile(new URL("../deploy/nginx/meovv-mail.conf.example", import.meta.url), "utf8"),
|
||||
]);
|
||||
assert.match(page, /crypto\.subtle\.digest\("SHA-256"/);
|
||||
assert.match(page, /fetch\("\/api\/auth"/);
|
||||
@@ -33,4 +35,8 @@ test("includes production auth, JMAP, sanitization, and responsive UI paths", as
|
||||
assert.match(openapi, /Idempotency-Key/);
|
||||
assert.match(standalone, /<div id="root"><\/div>/);
|
||||
await access(new URL("../web-dist/assets", import.meta.url));
|
||||
assert.match(compose, /127\.0\.0\.1:8080/);
|
||||
assert.match(compose, /127\.0\.0\.1:8081/);
|
||||
assert.match(nginx, /proxy_pass http:\/\/127\.0\.0\.1:8080/);
|
||||
assert.match(nginx, /proxy_pass http:\/\/127\.0\.0\.1:8081/);
|
||||
});
|
||||
Reference in new issue
Block a user