Files
tern-server/docs/server-architecture-spec.md
Mateusz PstruchaandClaude Opus 5 4c1a6457c5 Initial sync server: IMAP engine, schema, and read API
Covers phases 1-2 of the build order in the architecture spec: the IMAP
sync engine (IDLE + UIDVALIDITY tracking + jittered reconnect, headers
first with lazy body fetch), the full data model, and a minimal REST API
for auth, accounts, folders, messages and delta polling.

Credentials are encrypted at rest with ChaCha20-Poly1305 rather than
libsodium secretbox, to avoid a system dependency for the same
construction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 19:00:59 +02:00

161 lines
14 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Modern Email App — Architecture & Planning Doc
## 1. High-Level Shape
```
[IMAP/SMTP server] <--IMAP IDLE + SMTP submission--> [Sync Server / API] <--REST/WS--> [Webapp]
|
|--DB (Postgres/SQLite)
|--Rule Engine
|--Push (UnifiedPush/WS)
|
[Android Client]
```
Your server is the **only** thing that ever speaks IMAP/SMTP. Clients only ever talk to your API. This is the right call — it means clients stay dumb, and you can swap the mail-protocol layer later (e.g. add JMAP) without touching clients.
---
## 2. Core Decisions
1. **Sync direction: one-way.** Server only fetches from IMAP INBOX; it never writes state back to the source server. Sending is the one outbound path, via SMTP submission. This simplifies the whole system considerably — no UID conflict handling, no reconciling flag changes made by another client.
2. **Multi-user, multi-account server.** This is a shared/universal server: multiple people use one deployment. Each user has one local (internal) account plus any number of external IMAP accounts they add. Data model needs a `users` table, with `accounts` belonging to a `user_id`.
3. **Provider support: self-hosted only, for now.** Target is a Docker-based mail server (plain IMAP/SMTP auth). Gmail/Apple (OAuth2/XOAUTH2) is future work — see §11.
4. **Auth: independent, local.** Your own user accounts/sessions, decoupled from IMAP credentials (which are stored server-side, encrypted, per added account). SSO via Authentik is future work — see §11.
5. **Folders: virtual.** The sync engine only ever fetches from IMAP INBOX. All organization (folders, tags, rules) happens inside the app on top of that flat incoming stream — there's no concept of mirroring the source server's folder tree.
6. **Threading: use the standard algorithm.** See §3.6 below.
---
## 3. Server
### 3.1 IMAP Sync Engine
- One persistent IDLE connection per account per folder (or per account, cycling folders — IDLE only watches one folder at a time per connection, so watching multiple folders means multiple connections or periodic re-select).
- Fallback poll interval (e.g. every 5–15 min) for servers that don't support IDLE, and as a safety net if IDLE silently dies (it does, in practice — TCP connections die without FIN, so you need a NOOP/keepalive heartbeat and a watchdog to detect a stalled IDLE session and reconnect).
- Backoff/reconnect logic with jitter for flaky servers.
- Initial sync: full folder fetch with UID ranges, paged, don't pull full bodies for old mail unless requested (fetch headers/flags first, bodies lazily or in a background pass).
- Track `UIDVALIDITY` per folder — if it changes, your cached UIDs are invalid and you need to re-sync that folder.
- MIME parsing library (don't hand-roll this — e.g. Rust: `mail-parser`; Python: `email` stdlib or `flanker`; Go: `emersion/go-message`; Node: `mailparser`).
### 3.2 Storage
- Store parsed structure (headers, text/html body, attachment metadata) in DB.
- Store raw MIME blob too (for re-parsing if your parser improves, and for "view source"). **Filesystem** for now (keep large binary out of Postgres) — S3-compatible object storage is future work, see §11.
- Attachments: store by content-hash, dedupe identical attachments across messages; filesystem path derived from the hash.
### 3.3 Sending
- SMTP submission (port 587, STARTTLS) using stored credentials.
- Outbox/queue table with status (pending/sent/failed) and retry with backoff — don't send synchronously in the request path.
- Draft storage.
### 3.4 Data Model (sketch)
- `users` (local API auth: username, password hash, etc.)
- `accounts` (user_id, IMAP/SMTP creds encrypted, server host/port, provider type — for future OAuth support)
- `sync_state` (account_id, uidvalidity, last_synced_uid — one row per account, since we only ever watch INBOX)
- `messages` (account_id, uid, message_id header, in_reply_to, references[], from/to/subject, date, flags, thread_id, spam_score, raw_blob_ref)
- `bodies` (message_id, text, html — or separate table if you lazy-load)
- `attachments` (message_id, filename, content_type, size, blob_ref, content_hash)
- `folders` (user_id, name — app-level/virtual, not tied to IMAP) + `message_folders` (message_id, folder_id) if a message can live in more than one virtual folder, otherwise just a `folder_id` column on `messages`
- `tags` (user_id, name, color) + `message_tags` (many-to-many)
- `rules` (user_id, name, conditions JSON, actions JSON, enabled, priority/order)
- `devices` (user_id, for push: unifiedpush endpoint / websocket session)
### 3.5 Rule Engine
- **Manual rules**: user-defined, run on new-mail arrival (and optionally re-runnable on demand against existing mail). Conditions: header match (from/to/subject/list-id), body contains, regex; Actions: tag, move folder, mark read, delete, notify/don't-notify.
- **Spam rules**: same engine, but with header-parsing conditions specifically for Proxmox Mail Gateway's added headers — it runs SpamAssassin under the hood, so look for:
- `X-SPAM-LEVEL`, `X-SPAM-STATUS`, `X-SPAM-SCORE` (or similarly named, check your PMG config — these are configurable)
- Threshold-based rule: score > N → tag as spam / move to Junk.
- Keep rules as structured JSON (condition tree + action list) rather than free-text DSL, so both webapp and rule-engine can render/edit them without a parser.
- Order/priority matters if multiple rules can match — decide first-match-wins vs all-matches-apply.
### 3.6 Threading
Use the **JWZ algorithm** (Jamie Zawinski's threading algorithm) rather than building your own — it's the de facto standard (Gmail, Thunderbird, and most mail clients implement a variant of it) and it already handles the annoying edge cases: missing parent messages, out-of-order arrival, duplicate Message-IDs, and messages with no reference headers at all.
**Headers to parse and store per message:**
- `Message-ID` — unique ID of this message
- `In-Reply-To` — direct parent's Message-ID
- `References` — full ancestor chain (more reliable than In-Reply-To alone; some clients/lists only set one or the other)
- `Subject` — fallback only, used for subject-based grouping when a message has no reference headers (common with some mailing lists that strip them)
**How it works, roughly:**
1. Build a lookup table of all messages by Message-ID.
2. For each message, walk its `References` (falling back to `In-Reply-To`) to find its parent; link them into a tree. Create placeholder "container" nodes for referenced-but-not-yet-fetched parents (they may arrive later, out of order — since IDLE delivers mail as it arrives, not in thread order).
3. Group root-level containers that share a normalized subject (strip `Re:`/`Fwd:`/`[list-name]` prefixes) when they have no reference-based link, as a fallback.
**Data model:**
- Store `in_reply_to` and `references` on each message (already added to §3.4).
- Compute a `thread_id` at ingest time — make it its own generated ID (not just "use the root Message-ID"), because threads sometimes need to **merge** later: a message you thought was a new thread turns out to be a reply once a missing ancestor message arrives. A separate `thread_id` with a re-parent/merge step handles this cleanly; reusing the root Message-ID as the thread key doesn't.
- Threading is scoped **per account** (a thread never spans two different IMAP accounts, even for the same user) — keeps this simple and matches how threads actually form.
**Left to the client/UI layer, not the backend:** whether to display as a collapsed conversation view (one row per thread) or a flat list with grouping. The API just needs to expose `thread_id` on each message and, ideally, a "fetch thread" endpoint — the rendering choice doesn't change the backend work.
### 3.7 Future: AI tagging/summarization hook
- Don't build this now, but design the rule engine's action list to be extensible — an action type like `run_pipeline: summarize` that enqueues a background job is enough of a hook. Keep it async (job queue), not inline in the sync path, so a slow/down AI backend never blocks mail ingestion.
### 3.8 Notifications
- **WebSocket**: for webapp, push events as they happen (new mail, flag change, rule action).
- **Polling fallback**: simple `GET /events?since=<cursor>` for legacy/degraded clients.
- **UnifiedPush**: primary for Android — makes sense given GrapheneOS has no Google Play Services/FCM. Your server acts as the UnifiedPush application server; register the distributor endpoint per device, POST a (minimal, content-free — just "you have new mail, sync now") message on new mail. Keep push payloads content-free and have the client pull the actual message over the authenticated API, so you're not putting email content through a third-party push relay.
---
## 4. API Layer — REST
- Decided: REST, not GraphQL.
- Needs a **delta/sync endpoint** per client (mobile especially): "give me everything changed since cursor X" rather than clients re-fetching full folder listings.
- Pagination on message lists (cursor-based, not offset, since new mail arrives continuously).
## 5. Webapp
UI/UX is being scoped in a separate doc. Backend-relevant constraints only:
- HTML email rendering: sandbox it (iframe with strict CSP, or sanitize to a safe subset) — untrusted HTML email is a real XSS vector. Block remote image loading by default (common privacy leak vector — read receipts via tracking pixels).
## 6. Android Client
UI/UX is being scoped in a separate doc. Backend-relevant constraints only:
- UnifiedPush receiver + local notification.
- Local cache (Room/SQLite) synced via the delta endpoint.
- Runs fine as a standard GrapheneOS-compatible app as long as you don't depend on Play Services for anything (auth, push, maps, etc.) — UnifiedPush avoids that for notifications specifically.
## 7. Security Notes
- Encrypt stored IMAP/SMTP credentials at rest (not just DB access control — actual encryption, e.g. libsodium secretbox with a server-held key, or better, a key derived from something you don't also store in the same DB).
- Server↔IMAP/SMTP: TLS always (implicit TLS or STARTTLS, never plaintext).
- Client↔API: assumed to always sit behind **nginx** as reverse proxy — nginx terminates TLS and forwards plain HTTP internally; the API itself doesn't need to handle certs. Bind the API to localhost/internal network only, never expose it directly.
- Rate-limit login/API auth endpoints (can partly live at the nginx layer too).
- Sanitize all rendered HTML server-side or client-side before display — don't trust the sanitizer step to be "someone else's problem."
## 8. Explicitly Out of Scope (not planned at all — flag if this changes)
- Calendar/contacts (CalDAV/CardDAV)
- PGP/S-MIME encryption
- POP3 support
- Server-side Sieve filters (your rule engine replaces this)
- Vacation/auto-responder
- Multi-protocol beyond IMAP/SMTP (no JMAP, no Exchange/EWS)
- Two-way IMAP sync (see §2.1 — deliberately one-way)
## 9. Suggested Build Order
1. IMAP sync engine + DB schema (no clients yet) — prove IDLE + reconnect logic works reliably first, it's the riskiest part.
2. Minimal REST API + folder/message read endpoints.
3. Webapp: read-only mail view.
4. Sending (SMTP submission + outbox).
5. Tags + manual rules + threading.
6. Spam header rules (Proxmox-specific).
7. WebSocket + polling notifications.
8. Android client + UnifiedPush.
9. Future items from §11, as needed.
---
## 10. Stack — Decided
- **Server**: Rust. Suggested crates: `async-imap` (IMAP + IDLE), `lettre` or `mail-send` (SMTP submission), `mail-parser` (MIME parsing), `tokio` (async runtime), `axum` or `actix-web` (REST API), `sqlx` (Postgres access, compile-time checked queries).
- **DB**: Postgres — gives full-text search (`tsvector`) and scales cleanly across multiple users/accounts.
- **Deployment**: Docker Compose (server + Postgres, nginx as reverse proxy in front — see §7).
---
## 11. Future Plans (explicitly deferred, not designed yet)
These are noted so the current design doesn't accidentally box them out, but none of this is being built now:
- **Gmail / Apple Mail support** — requires OAuth2/XOAUTH2 for IMAP auth instead of plain password. The `accounts` table already has a `provider type` field for this reason; when this lands, the sync engine needs a token-refresh flow alongside the current password-based auth, and Gmail's IMAP quirks (e.g. `X-GM-THRID`, label-as-folder model) may end up feeding directly into the threading model rather than relying purely on JWZ for that provider.
- **SSO via Authentik** — replace/augment local username+password API auth with OIDC against Authentik. Since API auth is already independent of IMAP credentials (§2.4), this should slot in without touching the mail-sync side at all.
- **AI tagging/sorting/summarization** — hook point already reserved in the rule engine (§3.7): an async, queued pipeline action type, kept off the ingest hot path.
- **Two-way sync** — if a future need arises to reflect read/flag/delete state back to the source IMAP server (e.g. also using a native client on the same mailbox), this would need UID conflict handling and is a substantial change to §2.1's current one-way model — not a small add-on.
- **S3-compatible object storage for attachments/raw blobs** — swap in for the filesystem store from §3.2 once storage needs outgrow a single disk (or you want multi-node deployment). Keep the content-hash-addressed storage scheme from day one so this swap is a storage-backend change, not a data-model change.