Files
tern-server/README.md
T
Mateusz PstruchaandClaude Opus 5.5 fd8ee8311c
CI / test (push) Successful in 2m28s
Add sending: outbox queue, SMTP worker, drafts
Drafts and queued sends are one outbox row in different states, drained
by a background worker so SMTP never runs in the request path (§3.3).
Retries back off 1-16 min; 5xx, auth and TLS failures fail fast; items
a crashed worker left mid-send are reclaimed. Each message keeps its
Message-ID across retries, so an at-least-once duplicate is recognisable.
Reply headers are derived server-side from the parent, and sent mail is
filed into its thread alongside received mail.

Three things the libraries would have got wrong:
- mail-builder's .bcc() writes an ordinary Bcc header every recipient
  sees. Bcc goes in the envelope only; a test checks it never reaches the
  rendered bytes, and was confirmed to fail if .bcc() is reintroduced.
- mail-send trusts only compiled-in public CAs, while IMAP (native-tls)
  uses the OS store — a server with an internal-CA cert would sync but
  never send. SMTP now uses the OS store too.
- rustls is added with default-features off: its defaults pull in
  aws-lc-rs, which needs cmake/clang and would break the runner build.

Also fixes: UIDVALIDITY resets now only delete IMAP-sourced rows (sent
mail shares the table and exists nowhere else); first sync no longer
logs a false "UIDVALIDITY changed" warning; Message-IDs are stored bare
whichever path writes them (ENVELOPE brackets them, mail-parser doesn't);
accounts can choose STARTTLS vs implicit TLS for SMTP, defaulting by port.

Verified end to end against a TLS mail server with a private-CA cert,
with no plaintext patching: IMAPS sync, SMTPS send, delivery and headers
checked from the recipients' mailboxes, Bcc absent from other copies,
plaintext refused when STARTTLS is unavailable, retry scheduling on
connection failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 10:59:28 +02:00

6.4 KiB
Raw Permalink Blame History

tern-server

The sync server for Tern — the only component that ever speaks IMAP/SMTP. See docs/server-architecture-spec.md for the full design.

What's built (build-order phases 1–4)

  • 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, and a polling /events delta endpoint.
  • 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.

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.

What's explicitly deferred

Per the spec's suggested build order (§9), not yet built: tag & rule execution (schema exists, engine doesn't), the JWZ threading algorithm (each message currently gets its own thread_id — no linking/merging pass yet), spam header rules, WebSocket push (the /events poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration.

Also deferred, and worth knowing because they aren't obvious from the code:

  • Most mutations. Mark-read exists; tagging and moving to folders arrive with phase 5.
  • Permissive CORS. CorsLayer::permissive() is a dev convenience so the Vite dev server on another port can talk to the API. Tighten it when the webapp is served from the same origin behind nginx.
  • API-level rate limiting. The nginx layer covers most of this — see nginx-rate-limiting.md. A per-username limiter in the API is the remaining gap.

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

cp .env.example .env
openssl rand -base64 32   # paste into .env as CREDENTIAL_KEY
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.