Mateusz PstruchaandClaude Opus 5.5 807775726c
CI / test (push) Successful in 3m3s
Add threading, tags, rules and thread actions
Threading (§3.6) is 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, so 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.

Rules (§3.5) are structured JSON — one level of all/any tests, exactly
what the editor can show — run after the body is fetched since they need
headers. Every matching rule applies in priority order until a `stop`.
Patterns use the regex crate: linear-time, so a user-written pattern run
against every incoming message can't hang ingest. Numeric comparison
reads the first number in a value, so both "5.3" and "Yes, score=5.3"
spam headers work for phase 6.

Rule "delete" is a soft delete to Trash: a rule with an over-broad
pattern must not be able to destroy mail. Archive moves to a system
folder found by role, so renaming it doesn't break archiving. Manual
thread actions use the same action type and applier as rules, so the two
can't drift.

Thread listing now takes a view (inbox/all/sent/trash/folder/tag). A
thread appears in a view if any message matches, but the row summarises
the whole conversation — so a reply to an archived thread brings it back
to the inbox. Row subjects come from the root when present, not merely
the earliest Date (replies can be dated earlier, and Date ties are
common at one-second resolution).

Verified against a live TLS mail server: out-of-order parent/reply,
replies to a missing root, a list that strips References, and two
unrelated "Invoice" mails kept apart; rules tagging, archiving, trashing
on spam score, and `stop` blocking a lower rule; the backfill rebuilding
the same 9 threads from 13 split messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:19:35 +02:00

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