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–5)

  • 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.
  • 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).
  • Tags, folders and views — thread listing takes view=inbox|all|sent|trash|folder|tag. 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.

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.
  • No notify/don't-notify action yet — it arrives with the notification work in phases 7–8.

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.

What's explicitly deferred

Per the spec's suggested build order (§9), not yet built: spam header rules (the rule engine already supports them — phase 6 is about defaults and a UI for the threshold), 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:

  • 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.
S
Description
No description provided
Readme
943 KiB
0 Stars 1 Watchers 0 Forks
Languages
Rust 99.8%
Dockerfile 0.2%