Compare commits

..
19 changed files with 1125 additions and 79 deletions

No files matched your search

+2
View File
@@ -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=
+2
View File
@@ -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
+5 -1
View File
@@ -18,7 +18,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v7
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
@@ -44,6 +44,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Validate installer syntax
run: |
bash -n scripts/install-server.sh
sh -n deploy/certbot/deploy-hook.sh
- name: Validate Compose configuration
env:
MAIL_HOSTNAME: mail.example.com
+2 -1
View File
@@ -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
View File
@@ -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
+56 -9
View File
@@ -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,20 +46,62 @@ 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
```
The hostname's A/AAAA record must already point to the server and inbound port
80 must be reachable so Let's Encrypt can issue the certificate. The installer
does not change DNS, PTR, provider firewall rules, SSH, or UFW. It detects
unmanaged Nginx hostname conflicts and conflicting Docker packages instead of
overwriting or removing them. If Docker is already installed without Compose
v2, it adds the matching Compose package from the configured APT repositories.
Use `--yes` only for a reviewed, non-interactive installation.
Visit the printed HTTPS URL and complete the browser wizard. After creating and
testing a permanent administrator, finish the security setup:
```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.
### 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
./mailctl configure-tls
./mailctl doctor --hostname mail.example.com
```
@@ -109,7 +156,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
+197 -7
View File
@@ -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/api", "loopback Stalwart management 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 != "/api" || managementURL.User != nil || managementURL.RawQuery != "" || managementURL.Fragment != "" {
return errors.New("--url must be a loopback HTTP URL ending in /api")
}
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)
+44 -1
View File
@@ -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/api"})
if err == nil || !strings.Contains(err.Error(), "loopback") {
t.Fatalf("expected loopback URL rejection, got %v", err)
}
}
func TestConfigureTLSRejectsHTTPSManagementURL(t *testing.T) {
err := configureTLS([]string{"--directory", t.TempDir(), "--url", "https://127.0.0.1:8081/api"})
if err == nil || !strings.Contains(err.Error(), "loopback HTTP URL") {
t.Fatalf("expected plain loopback HTTP requirement, got %v", err)
}
}
+6 -25
View File
@@ -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:
-26
View File
@@ -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
}
}
+23
View File
@@ -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
+71
View File
@@ -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
View File
@@ -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.
+129
View File
@@ -0,0 +1,129 @@
# 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. It also stops when it finds a conflicting unmanaged Nginx site
or container package rather than replacing an existing setup. After the browser
wizard and permanent administrator verification, run:
```bash
sudo ./scripts/install-server.sh finalize
```
The rest of this document describes the same integration for manual installs
and explains the files managed by the installer.
## 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
./mailctl configure-tls
./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/api
```
## 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
View File
@@ -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
View File
@@ -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
+2 -2
View File
@@ -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,7 +32,7 @@ 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"},
+549
View File
@@ -0,0 +1,549 @@
#!/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 NGINX_AVAILABLE="/etc/nginx/sites-available/meovv-mail"
readonly NGINX_ENABLED="/etc/nginx/sites-enabled/meovv-mail"
readonly CERTBOT_WEBROOT="/var/www/certbot"
readonly CERTBOT_HOOK="/etc/letsencrypt/renewal-hooks/deploy/meovv-mail"
readonly MAILCTL_BIN="/usr/local/bin/mailctl"
readonly MANAGED_MARKER="Managed by MEOVV Mail installer"
readonly MEOVV_RELEASE="0.1.0"
COMMAND=""
MAIL_HOSTNAME=""
ADMIN_EMAIL=""
BUNDLE_DIR="$REPOSITORY_DIR"
ASSUME_YES=false
TEMP_CONTAINER=""
TEMP_FILES=()
log() {
printf '\n\033[1;35m==>\033[0m %s\n' "$*"
}
warn() {
printf '\033[1;33mWARNING:\033[0m %s\n' "$*" >&2
}
die() {
printf '\033[1;31mERROR:\033[0m %s\n' "$*" >&2
exit 1
}
cleanup() {
if [[ -n "$TEMP_CONTAINER" ]]; then
docker rm -f "$TEMP_CONTAINER" >/dev/null 2>&1 || true
fi
local temporary_file
for temporary_file in "${TEMP_FILES[@]}"; do
rm -f -- "$temporary_file"
done
}
trap cleanup EXIT
usage() {
cat <<'EOF'
Install and operate MEOVV Mail prerequisites on Ubuntu 24.04/26.04 or Debian 13.
Usage:
sudo ./scripts/install-server.sh install \
--hostname mail.example.com \
--email admin@example.com \
[--bundle-dir /opt/meovv-mail] [--yes]
sudo ./scripts/install-server.sh finalize \
[--bundle-dir /opt/meovv-mail] [--yes]
sudo ./scripts/install-server.sh status \
[--bundle-dir /opt/meovv-mail]
Commands:
install Install Docker, Nginx, and Certbot; initialize the bundle; obtain
TLS; install proxy/renewal configuration; and start the appliance.
finalize After completing the browser wizard and creating a permanent
administrator, register TLS with Stalwart and remove recovery access.
status Show service, certificate, and local endpoint status without changes.
This script does not modify DNS, PTR records, provider firewalls, SSH, or UFW.
EOF
}
parse_arguments() {
[[ $# -gt 0 ]] || { usage; exit 2; }
COMMAND="$1"
shift
while [[ $# -gt 0 ]]; do
case "$1" in
--hostname)
[[ $# -ge 2 ]] || die "--hostname requires a value"
MAIL_HOSTNAME="$2"
shift 2
;;
--email)
[[ $# -ge 2 ]] || die "--email requires a value"
ADMIN_EMAIL="$2"
shift 2
;;
--bundle-dir)
[[ $# -ge 2 ]] || die "--bundle-dir requires a value"
BUNDLE_DIR="$2"
shift 2
;;
--yes|-y)
ASSUME_YES=true
shift
;;
--help|-h)
usage
exit 0
;;
*)
die "unknown argument: $1"
;;
esac
done
case "$COMMAND" in
install|finalize|status) ;;
*) die "unknown command: $COMMAND" ;;
esac
[[ "$BUNDLE_DIR" = /* ]] || die "--bundle-dir must be an absolute path"
[[ "$BUNDLE_DIR" != *$'\n'* ]] || die "--bundle-dir contains a newline"
}
require_root() {
[[ ${EUID:-$(id -u)} -eq 0 ]] || die "run this command with sudo or as root"
}
validate_hostname() {
[[ "$MAIL_HOSTNAME" =~ ^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$ ]] || \
die "invalid fully-qualified hostname: $MAIL_HOSTNAME"
[[ ${#MAIL_HOSTNAME} -le 253 ]] || die "hostname is too long"
MAIL_HOSTNAME="${MAIL_HOSTNAME,,}"
}
validate_email() {
[[ "$ADMIN_EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]] || \
die "invalid email address: $ADMIN_EMAIL"
}
require_bundle() {
[[ -f "$BUNDLE_DIR/compose.yaml" ]] || die "compose.yaml not found in $BUNDLE_DIR"
[[ -f "$BUNDLE_DIR/Dockerfile" ]] || die "Dockerfile not found in $BUNDLE_DIR"
[[ -f "$BUNDLE_DIR/deploy/nginx/meovv-mail.conf.example" ]] || die "Nginx template is missing"
[[ -x "$BUNDLE_DIR/deploy/certbot/deploy-hook.sh" ]] || die "Certbot hook is missing or not executable"
}
confirm_install() {
$ASSUME_YES && return
[[ -t 0 ]] || die "non-interactive use requires --yes"
cat <<EOF
This will install or update Docker Engine, Nginx, and Certbot, write:
$NGINX_AVAILABLE
$CERTBOT_HOOK
and start MEOVV Mail from:
$BUNDLE_DIR
It will not alter unrelated Nginx files, DNS, PTR, or firewall rules.
EOF
read -r -p "Continue? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || die "installation cancelled"
}
detect_platform() {
[[ -r /etc/os-release ]] || die "/etc/os-release is unavailable"
# This is a trusted operating-system file.
# shellcheck disable=SC1091
source /etc/os-release
case "${ID:-}" in
ubuntu)
case "${VERSION_ID:-}" in
24.04|26.04) ;;
*) die "supported Ubuntu releases are 24.04 and 26.04; found ${VERSION_ID:-unknown}" ;;
esac
;;
debian)
[[ "${VERSION_ID:-}" == "13" ]] || die "Debian 13 is required; found ${VERSION_ID:-unknown}"
;;
*)
die "supported systems are Ubuntu 24.04/26.04 and Debian 13; found ${ID:-unknown}"
;;
esac
OS_ID="$ID"
OS_CODENAME="${VERSION_CODENAME:-}"
[[ -n "$OS_CODENAME" ]] || die "the operating-system codename is unavailable"
readonly OS_ID OS_CODENAME
}
install_base_packages() {
log "Installing host packages"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends \
ca-certificates \
certbot \
curl \
dnsutils \
gnupg \
iproute2 \
nginx \
openssl \
python3-certbot-nginx
}
package_is_installed() {
dpkg-query -W -f='${Status}' "$1" 2>/dev/null | grep -Fq 'install ok installed'
}
install_compose_for_existing_docker() {
local candidates=()
if package_is_installed docker-ce || package_is_installed docker-ce-cli; then
candidates=(docker-compose-plugin docker-compose-v2)
else
candidates=(docker-compose-v2 docker-compose-plugin)
fi
local package
for package in "${candidates[@]}"; do
if apt-cache show "$package" >/dev/null 2>&1; then
log "Installing $package for the existing Docker Engine"
if apt-get install -y --no-install-recommends "$package" && \
docker compose version >/dev/null 2>&1; then
systemctl enable --now docker
docker compose version
return
fi
fi
done
die "Docker is installed, but no compatible Compose v2 package is available from the configured APT repositories"
}
install_docker() {
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
log "Docker Engine and Compose are already installed"
systemctl enable --now docker
return
fi
if command -v docker >/dev/null 2>&1; then
install_compose_for_existing_docker
return
fi
local conflicting_packages=() package
for package in docker.io docker-compose docker-compose-v2 podman-docker containerd runc; do
if package_is_installed "$package"; then
conflicting_packages+=("$package")
fi
done
if (( ${#conflicting_packages[@]} > 0 )); then
die "conflicting container packages are installed (${conflicting_packages[*]}); review them manually before installing Docker CE"
fi
log "Installing Docker Engine from Docker's official repository"
install -m 0755 -d /etc/apt/keyrings
local docker_key
docker_key="$(mktemp /tmp/meovv-docker.XXXXXX.asc)"
TEMP_FILES+=("$docker_key")
curl -fsSL "https://download.docker.com/linux/$OS_ID/gpg" -o "$docker_key"
gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg "$docker_key"
chmod a+r /etc/apt/keyrings/docker.gpg
local architecture
architecture="$(dpkg --print-architecture)"
printf 'deb [arch=%s signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/%s %s stable\n' \
"$architecture" "$OS_ID" "$OS_CODENAME" \
> /etc/apt/sources.list.d/docker.list
apt-get update
apt-get install -y --no-install-recommends \
containerd.io \
docker-buildx-plugin \
docker-ce \
docker-ce-cli \
docker-compose-plugin
systemctl enable --now docker
docker compose version >/dev/null
}
assert_hostname_is_available() {
local conflict=""
if [[ -d /etc/nginx/sites-enabled ]]; then
while IFS= read -r candidate; do
[[ -e "$candidate" ]] || continue
[[ "$(readlink -f "$candidate")" == "$(readlink -f "$NGINX_AVAILABLE" 2>/dev/null || printf '%s' "$NGINX_AVAILABLE")" ]] && continue
if grep -Eq "^[[:space:]]*server_name[[:space:]][^;]*\b${MAIL_HOSTNAME//./\.}\b" "$candidate"; then
conflict="$candidate"
break
fi
done < <(find /etc/nginx/sites-enabled -maxdepth 1 \( -type f -o -type l \) 2>/dev/null)
fi
[[ -z "$conflict" ]] || die "$MAIL_HOSTNAME is already configured by $conflict; merge or disable that site manually"
if [[ -e "$NGINX_AVAILABLE" ]] && ! grep -Fq "$MANAGED_MARKER" "$NGINX_AVAILABLE"; then
die "$NGINX_AVAILABLE exists but is not managed by this installer"
fi
}
install_challenge_site() {
install -d -m 0755 "$CERTBOT_WEBROOT"
install -d -m 0755 /etc/nginx/sites-available /etc/nginx/sites-enabled
if [[ -r "/etc/letsencrypt/live/$MAIL_HOSTNAME/fullchain.pem" ]] && \
[[ -r "/etc/letsencrypt/live/$MAIL_HOSTNAME/privkey.pem" ]] && \
[[ -f "$NGINX_AVAILABLE" ]] && grep -Fq "listen 443 ssl" "$NGINX_AVAILABLE"; then
log "Keeping the existing managed HTTPS site during certificate renewal"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
nginx -t
systemctl enable --now nginx
systemctl reload nginx
return
fi
log "Preparing the initial ACME challenge site"
cat > "$NGINX_AVAILABLE" <<EOF
# $MANAGED_MARKER
server {
listen 80;
listen [::]:80;
server_name $MAIL_HOSTNAME;
location ^~ /.well-known/acme-challenge/ {
root $CERTBOT_WEBROOT;
default_type text/plain;
}
location / {
return 404;
}
}
EOF
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
nginx -t
systemctl enable --now nginx
systemctl reload nginx
}
obtain_certificate() {
log "Obtaining or reusing the Let's Encrypt certificate"
certbot certonly \
--webroot \
--webroot-path "$CERTBOT_WEBROOT" \
--cert-name "$MAIL_HOSTNAME" \
--domain "$MAIL_HOSTNAME" \
--email "$ADMIN_EMAIL" \
--agree-tos \
--no-eff-email \
--non-interactive \
--keep-until-expiring
[[ -r "/etc/letsencrypt/live/$MAIL_HOSTNAME/fullchain.pem" ]] || die "Certbot did not create the expected certificate lineage"
[[ -r "/etc/letsencrypt/live/$MAIL_HOSTNAME/privkey.pem" ]] || die "Certbot did not create the expected private key"
}
install_final_nginx_site() {
log "Installing the HTTPS Nginx route split"
sed "s/__MAIL_HOSTNAME__/$MAIL_HOSTNAME/g" \
"$BUNDLE_DIR/deploy/nginx/meovv-mail.conf.example" \
> "$NGINX_AVAILABLE"
ln -sfn "$NGINX_AVAILABLE" "$NGINX_ENABLED"
nginx -t
systemctl reload nginx
}
compose() {
docker compose --project-directory "$BUNDLE_DIR" -f "$BUNDLE_DIR/compose.yaml" "$@"
}
build_and_install_mailctl() {
log "Building the pinned MEOVV application image"
MAIL_HOSTNAME="$MAIL_HOSTNAME" MEOVV_VERSION="$MEOVV_RELEASE" compose build meovv
local image_ref temporary_binary
image_ref="meovv-mail:$MEOVV_RELEASE"
docker image inspect "$image_ref" >/dev/null 2>&1 || \
die "the expected MEOVV image $image_ref was not created"
TEMP_CONTAINER="$(docker create "$image_ref")"
temporary_binary="$(mktemp /tmp/meovv-mailctl.XXXXXX)"
TEMP_FILES+=("$temporary_binary")
docker cp "$TEMP_CONTAINER:/usr/local/bin/mailctl" "$temporary_binary"
install -m 0755 "$temporary_binary" "$MAILCTL_BIN"
rm -f "$temporary_binary"
docker rm "$TEMP_CONTAINER" >/dev/null
TEMP_CONTAINER=""
}
initialize_bundle() {
if [[ -f "$BUNDLE_DIR/.env" ]]; then
local configured_hostname
configured_hostname="$(sed -n 's/^MAIL_HOSTNAME=//p' "$BUNDLE_DIR/.env" | tail -n 1)"
[[ "$configured_hostname" == "$MAIL_HOSTNAME" ]] || \
die "$BUNDLE_DIR/.env belongs to $configured_hostname, not $MAIL_HOSTNAME"
log "The appliance is already initialized"
else
log "Initializing appliance secrets"
"$MAILCTL_BIN" init --directory "$BUNDLE_DIR" --hostname "$MAIL_HOSTNAME"
fi
# The MEOVV image runs with group 2001. Keep secrets unreadable to other
# host users while allowing the application process to read its inputs.
chown -R root:2001 "$BUNDLE_DIR/secrets"
find "$BUNDLE_DIR/secrets" -type d -exec chmod 0750 {} +
find "$BUNDLE_DIR/secrets" -type f -exec chmod 0640 {} +
chmod 0600 "$BUNDLE_DIR/.env"
}
copy_certificate_to_stalwart() {
log "Copying the Certbot certificate into the protected appliance directory"
MEOVV_BUNDLE_DIR="$BUNDLE_DIR" \
RENEWED_LINEAGE="/etc/letsencrypt/live/$MAIL_HOSTNAME" \
"$BUNDLE_DIR/deploy/certbot/deploy-hook.sh"
chown root:2001 "$BUNDLE_DIR/secrets/tls/fullchain.pem" "$BUNDLE_DIR/secrets/tls/privkey.pem"
chmod 0644 "$BUNDLE_DIR/secrets/tls/fullchain.pem"
chmod 0640 "$BUNDLE_DIR/secrets/tls/privkey.pem"
}
install_certbot_hook() {
log "Installing the Certbot deploy hook"
install -d -m 0755 "$(dirname "$CERTBOT_HOOK")"
local escaped_bundle escaped_hook
printf -v escaped_bundle '%q' "$BUNDLE_DIR"
printf -v escaped_hook '%q' "$BUNDLE_DIR/deploy/certbot/deploy-hook.sh"
cat > "$CERTBOT_HOOK" <<EOF
#!/usr/bin/env bash
set -Eeuo pipefail
export MEOVV_BUNDLE_DIR=$escaped_bundle
$escaped_hook
nginx -t
systemctl reload nginx
EOF
chmod 0755 "$CERTBOT_HOOK"
systemctl enable --now certbot.timer
}
start_appliance() {
log "Starting MEOVV Mail"
compose up -d --build --remove-orphans
local attempt
for attempt in {1..30}; do
if curl --fail --silent --show-error --max-time 3 http://127.0.0.1:8080/health/live >/dev/null; then
return
fi
sleep 2
done
compose ps
die "MEOVV did not become live within 60 seconds; inspect 'docker compose logs'"
}
install_command() {
require_root
[[ -n "$MAIL_HOSTNAME" ]] || die "install requires --hostname"
[[ -n "$ADMIN_EMAIL" ]] || die "install requires --email"
validate_hostname
validate_email
require_bundle
confirm_install
detect_platform
install_base_packages
assert_hostname_is_available
install_docker
build_and_install_mailctl
initialize_bundle
install_challenge_site
obtain_certificate
copy_certificate_to_stalwart
install_certbot_hook
install_final_nginx_site
start_appliance
cat <<EOF
MEOVV Mail prerequisites and services are installed.
Next:
1. Open https://$MAIL_HOSTNAME and complete the setup wizard.
2. Create and verify a permanent Stalwart administrator.
3. Run:
sudo $BUNDLE_DIR/scripts/install-server.sh finalize --bundle-dir $BUNDLE_DIR
Required provider-side work that this script cannot perform:
- Permit inbound TCP 25, 80, 443, 465, 587, and 993.
- Permit outbound TCP 25 or configure a smart host.
- Configure A/AAAA, MX, PTR, SPF, DKIM, and DMARC.
The one-time setup token is stored at:
$BUNDLE_DIR/secrets/bootstrap_token
EOF
}
finalize_command() {
require_root
require_bundle
[[ -x "$MAILCTL_BIN" ]] || die "$MAILCTL_BIN is missing; run install first"
[[ -f "$BUNDLE_DIR/.env" ]] || die "$BUNDLE_DIR is not initialized"
if ! $ASSUME_YES; then
[[ -t 0 ]] || die "non-interactive use requires --yes"
warn "Finalize removes the temporary Stalwart recovery administrator."
read -r -p "Have you completed the wizard and verified a permanent administrator? [y/N] " answer
[[ "$answer" =~ ^[Yy]$ ]] || die "finalization cancelled"
fi
log "Registering Certbot TLS with Stalwart"
"$MAILCTL_BIN" configure-tls --directory "$BUNDLE_DIR"
log "Removing temporary recovery access"
"$MAILCTL_BIN" harden --directory "$BUNDLE_DIR"
nginx -t
systemctl reload nginx
log "Final appliance status"
compose ps
cat <<EOF
Finalization complete. Recovery access is disabled.
Run the following after DNS and firewall configuration is complete:
sudo $MAILCTL_BIN doctor --directory $BUNDLE_DIR
sudo certbot renew --dry-run
EOF
}
status_command() {
require_root
require_bundle
log "Docker services"
compose ps || true
log "Nginx"
systemctl --no-pager --full status nginx || true
log "Certbot lineages"
certbot certificates || true
log "Loopback endpoints"
curl --silent --show-error --max-time 3 http://127.0.0.1:8080/health/live || true
printf '\n'
curl --silent --show-error --max-time 3 http://127.0.0.1:8081/.well-known/jmap || true
printf '\n'
}
main() {
parse_arguments "$@"
case "$COMMAND" in
install) install_command ;;
finalize) finalize_command ;;
status) status_command ;;
esac
}
main "$@"
+7 -1
View File
@@ -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/);
});