CI / test (pull_request) Successful in 4m13s
Production now runs from ygg/deployments, so a deploy from here would write over it. Renovate opens a PR there for the new version, and merging it deploys. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
153 lines
18 KiB
Markdown
153 lines
18 KiB
Markdown
# tern-server
|
||
|
||
The sync server for [Tern](../) — the only component that ever speaks IMAP/SMTP. See [`docs/server-architecture-spec.md`](docs/server-architecture-spec.md) for the full design.
|
||
|
||
## What's built (build-order phases 1–8)
|
||
|
||
- **DB schema** (`migrations/`): users/sessions, accounts + per-account sync state, messages/bodies/attachments, folders, tags, rules, devices — the full data model from the spec, even though rules/tags/threading execution isn't implemented yet.
|
||
- **IMAP sync engine** (`src/imap_sync/`): one task per account — connects over TLS, selects INBOX, tracks `UIDVALIDITY` (re-syncing the account from scratch if it changes), fetches new mail headers-first (`ENVELOPE`/`FLAGS`) then lazily fills in bodies/attachments in a trailing pass, and IDLEs for pushed changes with a periodic renewal and jittered-backoff reconnect on any failure.
|
||
- **Minimal REST API** (`src/api/`): local username/password auth (Argon2 + bearer session tokens), account management (IMAP credentials encrypted at rest with ChaCha20-Poly1305), folder listing, cursor-paginated message listing, single-message + thread-by-id fetch.
|
||
- **Thread-grouped listing** (`GET /api/threads`): one row per conversation, which is how both clients render the inbox. Grouped server-side because a thread's messages are spread through the flat list by date, so a client grouping page-by-page would split threads across page boundaries and miscount unread.
|
||
- **Sending** (`src/smtp/`, `/api/outbox`): drafts and a send queue, drained by a background worker — never in the request path (§3.3). Retries with backoff (1, 2, 4, 8, 16 min), fails fast on 5xx replies and auth or TLS errors, and reclaims messages a crashed worker left mid-send. Replies get In-Reply-To/References derived server-side from the parent message. Sent mail is filed into its thread alongside received mail.
|
||
- **Mark read** (`POST /api/threads/:id/read`) — local state only; see below.
|
||
- **Threading** (`src/threading.rs`, §3.6) — an incremental, database-backed JWZ. Each message links to its ancestors, to replies that arrived before it, and to siblings sharing a *missing* ancestor (what JWZ's placeholder containers do), merging every thread it touches into the one holding the oldest message. Subject-only grouping applies only to `Re:`/`Fwd:` messages with no reference headers — lists that strip References still thread, while unrelated mail sharing a generic subject never merges. Existing mail is re-threaded once per account via a versioned backfill (`THREADING_VERSION`).
|
||
- **Spam filtering** (`src/spam.rs`, §3.5) — every message's spam score is extracted at ingest from whichever filter header it carries, and a *spam score* rule condition compares it numerically. The webapp's **Add spam filter** creates the spec's threshold rule — score over 5 → Junk, placed first, stopping later rules — as an ordinary rule you can edit. Junk is a system folder like Archive.
|
||
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|junk|trash|folder|tag`, paged by an opaque keyset cursor. A thread appears in a view if any of its messages does, but the row summarises the whole conversation, so a reply to an archived thread brings it back to the inbox. Archive is a system folder found by role, so it can be renamed.
|
||
- **Rules** (`src/rules.rs`, `/api/rules`, §3.5) — structured JSON: one level of all/any tests (from, to, cc, recipients, subject, body, any header; contains, is, regex, exists, greater/less than) and an action list (tag, move, archive, mark read, delete). Run on new mail after its body is fetched; every matching rule applies in priority order, until one marked *stop after match*. Any rule can also be **run now** against existing mail (`POST /api/rules/:id/run`) — disabled ones too, so a rule can be tried before it's switched on. Manual thread actions (`POST /api/threads/:id/actions`) use the same action format and code.
|
||
- **UnifiedPush** (`src/push/`, `/api/devices`, §3.8) — the server is the UnifiedPush application server for Android: phones register their distributor's endpoint and Web Push keys, and new mail that should notify triggers a content-free, encrypted "sync now" push. See [Push notifications](#push-notifications-android).
|
||
- **Change notifications** (`src/events.rs`, `/api/ws`, `/api/events`, §3.8) — every change is appended to an event log and pushed to open WebSockets; the same log serves the polling fallback, so a client switches between the two without losing its place. See [Notifications](#notifications).
|
||
|
||
## How rules behave
|
||
|
||
- **Delete moves to Trash.** A rule runs on every incoming message, so one with an over-broad pattern must not be able to destroy mail. Trashed mail can be restored until it's purged — see below.
|
||
- **Patterns can't hang ingest.** The `regex` crate matches in linear time (no catastrophic backtracking), and patterns are size-capped and validated when the rule is saved.
|
||
- **Numeric comparisons read the first number in a value**, so both `X-Spam-Score: 5.3` and `X-Spam-Status: Yes, score=5.3` work — ready for phase 6's PMG headers.
|
||
- **Run now** covers everything outside Trash, including mail already filed away, and skips sent mail (rules are for incoming mail). Stored raw messages are only re-read when the rule tests a header, so body/subject/sender rules stay a fast database scan.
|
||
- **Rules see a message a moment after it appears.** Headers sync first so new mail shows quickly; rules need the full headers and body, so they run once the body arrives, seconds later.
|
||
- **Notify / don't notify.** New mail notifies if it's unread and still in the inbox after rules run. A *don't notify* action silences a message that would; *notify* alerts for one a rule filed away. If several matching rules say different things, the last one applied wins. Both are rule-only, and do nothing when a rule is run on existing mail.
|
||
|
||
## Spam scores
|
||
|
||
Proxmox Mail Gateway runs SpamAssassin, and header names are configurable, so the extractor recognises each format seen in practice rather than one fixed header — in order of precision:
|
||
|
||
| Header | Example | Read as |
|
||
|---|---|---|
|
||
| `X-SPAM-LEVEL` (PMG) | `Spam detection results: 8` followed by per-rule scores, folded over several lines | the total, 8 |
|
||
| `X-Spam-Score` | `5.3` | 5.3 |
|
||
| `X-Spam-Status` | `Yes, score=7.2 required=5.0 …` | 7.2 |
|
||
| `X-Spam-Level` (SpamAssassin) | `*******` | 7 (one per star) |
|
||
|
||
The first and last rows are the same header name — PMG and SpamAssassin use it for completely different formats — which is why each format is matched explicitly rather than taking "the first number in the header".
|
||
|
||
**PMG only adds its header from spam level 3 by default**, so mail below that has no score at all. That's stored as "unknown", not 0, and a rule treats it as neither over nor under any threshold. Thresholds of 3 and above work as expected; to act on lower scores, change PMG's rule that adds the header.
|
||
|
||
Scores are extracted for mail ingested from this version on. Older mail has none stored, but *run now* still finds it: when a stored score is missing it re-reads the raw message.
|
||
|
||
## Trash retention
|
||
|
||
Mail in Trash is permanently deleted after `TRASH_RETENTION_DAYS` (default 30; `0` disables purging), checked hourly. Stored files are content-addressed and shared between identical messages or attachments, so a file is only removed once nothing references it — and not if it was written or reused in the last hour, which covers the gap between ingest writing a file and inserting the row that points at it.
|
||
|
||
Purged mail doesn't come back: the sync engine only fetches UIDs above the last one it has seen. The exception is a UIDVALIDITY reset, which re-syncs the whole INBOX.
|
||
|
||
## How sending behaves
|
||
|
||
A few consequences worth knowing, because they aren't visible from the UI:
|
||
|
||
- **Sent mail exists only in Tern.** Nothing is appended to the IMAP server's Sent folder — sync is one-way (§2.1) and never writes back. If you ever use another client against the same account, it won't see mail sent from Tern. The same goes for mark-read: it's Tern-local. Bringing either to the source server is the two-way-sync item in §11, not a small add-on.
|
||
- **TLS always, enforced by type.** `mail-send`'s `connect()` returns a TLS-typed client and fails with `MissingStartTls` rather than downgrading; plaintext would need a separate `connect_plain()` which isn't used. Verified live: pointing an account at a server that doesn't offer STARTTLS fails permanently and delivers nothing.
|
||
- **SMTP trusts the OS certificate store**, same as IMAP. `mail-send` on its own trusts only compiled-in public CAs, so a mail server with an internal-CA certificate would sync fine and then fail every send. If your mail server uses an internal CA, add it to the container's trust store (`/usr/local/share/ca-certificates` + `update-ca-certificates`) and both protocols will trust it.
|
||
- **Bcc goes in the envelope only.** `mail-builder`'s `.bcc()` writes an ordinary `Bcc:` header that every recipient would see, so it's deliberately not used; a test checks that blind-copied addresses never reach the rendered message. The Bcc list is kept on the outbox row, not on the sent message.
|
||
- **Delivery is at-least-once.** If the server accepts a message but the process dies before recording it, it's re-sent. Every attempt reuses the same Message-ID, so a duplicate is at least recognisable as the same message. Exactly-once isn't achievable over SMTP.
|
||
- **SMTP port conventions:** STARTTLS by default, implicit TLS when the port is 465 — overridable per account with `smtp_use_starttls`. IMAP is implicit TLS only (993); STARTTLS on 143 isn't supported.
|
||
|
||
## Notifications
|
||
|
||
Clients learn about changes from one event log, over either transport:
|
||
|
||
- **`GET /api/ws`** — a WebSocket. Browsers can't set headers on one, and a token in the URL would land in proxy logs, so the client authenticates in-band: its first message is `{"type":"auth","token":"<session>","since":<cursor or null>}`. The server replies `{"type":"ready","cursor":N,"reset":false}`, replays anything after `since`, then streams `{"type":"event","id":…,"kind":…,"data":…}` as changes happen. It pings every 25 s (inside nginx's default 60 s read timeout) and closes with code 4401 when the session ends.
|
||
- **`GET /api/events?since=<cursor>`** — the polling fallback and delta endpoint: `{events, cursor, reset, more}`. Without `since` it just returns the current cursor.
|
||
|
||
Event kinds are `message_new` (with the final `notify` decision, sender and subject), `mailbox_changed` (thread ids, or `null` for "reload everything"), `outbox_changed` and `config_changed` (tags, folders, rules or accounts). They say *what* changed, not the new state; clients re-fetch through the normal API.
|
||
|
||
Worth knowing:
|
||
|
||
- **Only mail that arrives live notifies.** An account's first sync, and a UIDVALIDITY re-sync, are backlog: they're announced once per batch as `mailbox_changed` and never alert, however recent the mail.
|
||
- **Cursors survive seven days.** Events are purged after that; a client presenting an older (or unknown) cursor gets `reset: true` and should reload everything. Replays longer than 1,000 events also reset — reloading is quicker.
|
||
- **Ids are ordered by commit, not by start.** Events are inserted under a lock, one at a time, so a client that has seen id N has seen everything before it. Without that, two concurrent inserts could commit out of order and a resuming client would skip one forever.
|
||
- **One server process.** Live delivery is an in-process broadcast. Several instances behind a load balancer would each only push their own changes (polling would still be complete) — Postgres `LISTEN/NOTIFY` is the fix if that's ever needed.
|
||
|
||
## Push notifications (Android)
|
||
|
||
The phone's UnifiedPush distributor (e.g. the ntfy app) hands it an endpoint on a push server; the app registers that endpoint here with `POST /api/devices`. When new mail arrives whose `notify` decision is true, the server POSTs to each of the user's endpoints; the app then syncs over the API.
|
||
|
||
- **Content-free and encrypted.** The payload is just `{"kind":"sync"}`, encrypted to the phone's key per RFC 8291, so the push server learns nothing but timing. Requests are VAPID-signed (RFC 8292) for push services that require it; the app fetches the public key from `GET /api/push`. The key is generated on first start and stored encrypted with `CREDENTIAL_KEY`.
|
||
- **Only notifying mail pushes.** Don't-notify rules, mail filed away by rules, and backlog from an account's first sync send nothing — the app catches up next time it syncs.
|
||
- **Bursts coalesce.** Pushes are sent two seconds after the first notifying message, and one push covers everything that arrived meanwhile.
|
||
- **Dead endpoints clean themselves up.** A 404 or 410 from the push server removes the device; other failures are recorded on it (`GET /api/devices` shows `last_error`), and `POST /api/devices/:id/test` pushes once and reports what the push server said.
|
||
- **Reaching a self-hosted push server:**
|
||
- `PUSH_URL_REWRITE=https://ntfy.example.org/=>http://ntfy:80/` — endpoints carry the push server's *public* URL; rewrite the prefix when this server should reach it another way (container network, internal address). Comma-separate several. The VAPID audience stays the public origin.
|
||
- `PUSH_CA_CERT=/path/ca.pem` — trust an extra CA for push requests (the OS store is trusted too).
|
||
- `PUSH_TLS_INSECURE=true` — skip certificate verification for push requests. Logged as a warning at startup.
|
||
- `PUSH_VAPID_SUBJECT=mailto:you@example.org` — a contact address for push-service operators.
|
||
- **Any signed-in user can make the server POST to a URL of their choosing** (their push endpoint). Fine for a personal server; on a shared one, restrict outbound traffic at the network level.
|
||
|
||
## Registration
|
||
|
||
Only the first user can sign up, which is how a new server gets its owner. After that, `POST /api/auth/register` answers 403 unless `OPEN_REGISTRATION=true`. An open sign-up would let anyone on the internet use the server to make outbound IMAP, SMTP and push connections.
|
||
|
||
## Deployment
|
||
|
||
A `v*` tag builds the image and pushes it to the registry. Production, tern-api.mtps.pl, is defined in [`ygg/deployments`](https://git.app.ygg/ygg/deployments/src/branch/main/deployments/tern-server.yml), secrets included: Renovate opens a PR there for the new version, and merging it deploys. The webapp is released separately, from tern-web. Back up `CREDENTIAL_KEY` outside the deployments repository: without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted. The image's `HEALTHCHECK` runs `tern-server healthcheck`, so `docker compose up --wait` only succeeds once the server answers `/healthz`.
|
||
|
||
## Sessions
|
||
|
||
Sessions expire `SESSION_TTL_HOURS` (default 30 days) after they were last *used*, not after sign-in: each request pushes expiry back out, at most once an hour. A phone that syncs on push, or an open tab, stays signed in; a device left unused for the full period has to sign in again.
|
||
|
||
## What's explicitly deferred
|
||
|
||
Everything in the spec's build order (§9) is built. Deferred beyond it:
|
||
|
||
- **App lock** on Android (android-client-spec.md §7) — agreed to come after phase 8.
|
||
|
||
Also deferred, and worth knowing because they aren't obvious from the code:
|
||
|
||
- **Permissive CORS.** `CorsLayer::permissive()` lets the webapp, deployed on its own origin, call the API. Clients authenticate with a bearer token, never a cookie, so a foreign page can't borrow a signed-in browser's session. Restricting it to the webapp's origin would still be tidier.
|
||
- **API-level rate limiting.** The nginx layer covers most of this — see [`nginx-rate-limiting.md`](nginx-rate-limiting.md). A per-username limiter in the API is the remaining gap.
|
||
|
||
### Fixed: mail announced mid-fetch could wait for the next renewal
|
||
|
||
A server announces new mail once per session, as an untagged `EXISTS` attached to whatever response is in flight. Mail landing while Tern was fetching — or while IDLE was starting — was announced that way; async-imap files such announcements in a side channel instead of waking IDLE, and the server doesn't repeat them. The message then sat unfetched until the next IDLE renewal or the next new mail.
|
||
|
||
Measured before the fix: in bursts of 4 messages separated by quiet gaps, 4 of 12 bursts had a message stuck for the whole gap; one message sat 358 s in an earlier run. After: 0 of 12, worst case 0.2 s. The sync loop now drains that channel after IDLE starts and fetches again if it announced mail. Draining also matters on its own — the channel holds 100 entries and silently drops announcements once full.
|
||
|
||
IDLE is also renewed every 10 minutes rather than 25; each renewal re-runs the fetch pass, so it doubles as the 5–15 minute safety-net poll the spec asks for (§3.1).
|
||
|
||
### Decided: the sync engine only moves forward
|
||
|
||
`fetch_new_headers` only looks at UIDs above `last_synced_uid`, so **flag changes and deletions made on the source IMAP server are never noticed.** A message read or deleted in another client stays unread and present in Tern forever.
|
||
|
||
This is a deliberate call, not an oversight — it keeps the sync loop trivial, and §2.1's one-way model means the source server isn't treated as authoritative for state anyway. Revisit if either of these becomes true:
|
||
|
||
- You start using another mail client against the same mailbox, so divergence becomes visible day to day.
|
||
- The mailbox is large enough that never noticing server-side expunges bloats local storage.
|
||
|
||
The fix when it comes is a periodic reconciliation pass — `UID SEARCH ALL` to diff against stored UIDs for deletions, plus a `UID FETCH <range> FLAGS` sweep for flag drift. That's cheap to bolt on precisely because UIDs and `UIDVALIDITY` are already tracked per account.
|
||
|
||
## Running locally
|
||
|
||
```bash
|
||
cp .env.example .env
|
||
openssl rand -hex 32 # paste into .env as CREDENTIAL_KEY (base64 works too)
|
||
docker compose up -d db
|
||
cargo run
|
||
```
|
||
|
||
Or the whole stack (server + Postgres + nginx) via `docker compose up -d` once `CREDENTIAL_KEY` is exported in your shell or a `.env` file docker compose picks up.
|
||
|
||
Migrations run automatically on startup (`sqlx::migrate!`).
|
||
|
||
## Notes on deviations from the spec
|
||
|
||
- **Encryption**: §7 suggests libsodium secretbox; this uses ChaCha20-Poly1305 (RustCrypto) instead — same AEAD construction family, but pure Rust with no libsodium system dependency. See `src/crypto.rs`.
|
||
- **Web framework**: axum, per your choice between the spec's axum/actix-web options.
|