Mateusz PstruchaandClaude Opus 5.5 90fc65dbf5 Add live change notifications and notify/don't-notify rules
Every change is appended to an events table and broadcast to open
WebSockets (GET /api/ws); GET /api/events?since= reads the same log as
the polling fallback and delta endpoint, so clients can switch
transports without losing their place. Inserts are serialised so ids
are ordered by commit, cursors older than the 7-day retention reset,
and the socket authenticates in-band since browsers can't set headers.

New mail notifies when it's unread and still in the inbox after rules;
rule actions notify / dont_notify override that, last one applied
wins. An account's first sync and UIDVALIDITY re-syncs are backlog and
never notify. Thread actions, outbox status, and tag/folder/rule/
account edits emit events too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 18:55:34 +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–7)

  • 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.
  • 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.

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.

What's explicitly deferred

Per the spec's suggested build order (§9), not yet built: the Android client and UnifiedPush (phase 8), which will push content-free wake-ups for message_new events whose notify is true.

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.

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

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%