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>
This commit is contained in:
commit
4c1a6457c5
41 files changed
+5538
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# Copy to .env for local development (docker-compose reads this automatically
|
||||
# for the `db` service password; the app reads it via dotenvy at startup).
|
||||
|
||||
DATABASE_URL=postgres://tern:tern@localhost:5432/tern
|
||||
BIND_ADDR=127.0.0.1:8080
|
||||
|
||||
# 32 random bytes, base64-encoded. Generate with: openssl rand -base64 32
|
||||
# Encrypts stored IMAP/SMTP credentials at rest (see src/crypto.rs). Losing
|
||||
# this key makes every stored account credential unrecoverable — back it up
|
||||
# outside the database.
|
||||
CREDENTIAL_KEY=
|
||||
|
||||
BLOB_STORAGE_DIR=./data/blobs
|
||||
SESSION_TTL_HOURS=720
|
||||
|
||||
RUST_LOG=tern_server=debug,tower_http=debug
|
||||
@@ -0,0 +1,5 @@
|
||||
/target
|
||||
.env
|
||||
/data
|
||||
*.log
|
||||
.DS_Store
|
||||
Generated
+3589
File diff suppressed because it is too large.
Load diff
+41
@@ -0,0 +1,41 @@
|
||||
[package]
|
||||
name = "tern-server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Tern sync server — the only component that speaks IMAP/SMTP"
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
axum = { version = "0.7", features = ["macros"] }
|
||||
tower = "0.5"
|
||||
tower-http = { version = "0.6", features = ["trace", "cors"] }
|
||||
|
||||
sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "uuid", "migrate"] }
|
||||
|
||||
async-imap = { version = "0.11", default-features = false, features = ["runtime-tokio"] }
|
||||
async-native-tls = { version = "0.6", default-features = false, features = ["runtime-tokio"] }
|
||||
mail-parser = "0.11"
|
||||
mail-send = "0.4"
|
||||
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
|
||||
argon2 = "0.5"
|
||||
rand = "0.8"
|
||||
chacha20poly1305 = "0.10"
|
||||
base64 = "0.22"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
|
||||
thiserror = "2"
|
||||
anyhow = "1"
|
||||
dotenvy = "0.15"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
futures = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4"
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
FROM rust:1-bookworm AS builder
|
||||
WORKDIR /build
|
||||
COPY Cargo.toml Cargo.lock* ./
|
||||
COPY src ./src
|
||||
COPY migrations ./migrations
|
||||
RUN cargo build --release
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
COPY --from=builder /build/target/release/tern-server ./tern-server
|
||||
COPY migrations ./migrations
|
||||
EXPOSE 8080
|
||||
CMD ["./tern-server"]
|
||||
@@ -0,0 +1,31 @@
|
||||
# tern-server
|
||||
|
||||
The sync server for [Tern](../) — the only component that ever speaks IMAP/SMTP. See [`docs/server-architecture-spec.md`](docs/server-architecture-spec.md) for the full design.
|
||||
|
||||
## What's built (build-order phases 1–2)
|
||||
|
||||
- **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.
|
||||
|
||||
## What's explicitly deferred
|
||||
|
||||
Per the spec's suggested build order (§9), not yet built: SMTP sending/outbox, 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.
|
||||
|
||||
## Running locally
|
||||
|
||||
```bash
|
||||
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.
|
||||
@@ -0,0 +1,50 @@
|
||||
services:
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: tern
|
||||
POSTGRES_PASSWORD: tern
|
||||
POSTGRES_DB: tern
|
||||
volumes:
|
||||
- db-data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U tern"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
server:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
DATABASE_URL: postgres://tern:tern@db:5432/tern
|
||||
BIND_ADDR: 0.0.0.0:8080
|
||||
CREDENTIAL_KEY: ${CREDENTIAL_KEY}
|
||||
BLOB_STORAGE_DIR: /data/blobs
|
||||
RUST_LOG: tern_server=info
|
||||
volumes:
|
||||
- blob-data:/data/blobs
|
||||
# Not published directly — nginx is the only thing that should be
|
||||
# reachable from outside (server-architecture-spec.md §7).
|
||||
expose:
|
||||
- "8080"
|
||||
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- server
|
||||
ports:
|
||||
- "80:80"
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
|
||||
volumes:
|
||||
db-data:
|
||||
blob-data:
|
||||
@@ -0,0 +1,160 @@
|
||||
# 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.
|
||||
@@ -0,0 +1 @@
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto; -- gen_random_uuid()
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Local API auth, independent of IMAP credentials (server-architecture-spec.md §2.4)
|
||||
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_id_idx ON sessions(user_id);
|
||||
@@ -0,0 +1,32 @@
|
||||
-- IMAP/SMTP accounts a user has added, plus per-account sync bookkeeping.
|
||||
-- One-way sync: server only ever fetches from IMAP INBOX (§2.1), so
|
||||
-- sync_state has exactly one row per account, not per-folder.
|
||||
|
||||
CREATE TABLE accounts (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
provider_type TEXT NOT NULL DEFAULT 'generic_imap', -- reserved for future oauth providers (gmail, apple)
|
||||
imap_host TEXT NOT NULL,
|
||||
imap_port INTEGER NOT NULL DEFAULT 993,
|
||||
imap_use_tls BOOLEAN NOT NULL DEFAULT true,
|
||||
smtp_host TEXT NOT NULL,
|
||||
smtp_port INTEGER NOT NULL DEFAULT 587,
|
||||
smtp_use_starttls BOOLEAN NOT NULL DEFAULT true,
|
||||
username TEXT NOT NULL,
|
||||
-- credentials encrypted at rest (ChaCha20-Poly1305, server-held key) — never stored plaintext
|
||||
encrypted_password BYTEA NOT NULL,
|
||||
password_nonce BYTEA NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX accounts_user_id_idx ON accounts(user_id);
|
||||
|
||||
CREATE TABLE sync_state (
|
||||
account_id UUID PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
uidvalidity BIGINT,
|
||||
last_synced_uid BIGINT NOT NULL DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT 'pending', -- pending | syncing | idle | error
|
||||
last_error TEXT,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,60 @@
|
||||
-- Core message store (server-architecture-spec.md §3.4, §3.6).
|
||||
-- thread_id is its own generated id (not the root Message-ID) because threads
|
||||
-- can merge later once a missing ancestor arrives — see §3.6.
|
||||
|
||||
CREATE TABLE folders (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (user_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
folder_id UUID REFERENCES folders(id) ON DELETE SET NULL,
|
||||
uid BIGINT NOT NULL,
|
||||
message_id TEXT, -- Message-ID header (not guaranteed unique across servers)
|
||||
in_reply_to TEXT,
|
||||
references_ TEXT[] NOT NULL DEFAULT '{}',
|
||||
thread_id UUID NOT NULL DEFAULT gen_random_uuid(),
|
||||
from_addr TEXT,
|
||||
from_name TEXT,
|
||||
to_addrs TEXT[] NOT NULL DEFAULT '{}',
|
||||
cc_addrs TEXT[] NOT NULL DEFAULT '{}',
|
||||
subject TEXT,
|
||||
sent_at TIMESTAMPTZ,
|
||||
flags TEXT[] NOT NULL DEFAULT '{}', -- \Seen, \Flagged, etc, plus app flags
|
||||
spam_score REAL,
|
||||
body_fetched BOOLEAN NOT NULL DEFAULT false, -- headers-first sync: body may be lazy
|
||||
raw_blob_ref TEXT, -- filesystem path to the raw MIME blob
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (account_id, uid)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_account_id_idx ON messages(account_id);
|
||||
CREATE INDEX messages_thread_id_idx ON messages(thread_id);
|
||||
CREATE INDEX messages_message_id_idx ON messages(message_id);
|
||||
CREATE INDEX messages_in_reply_to_idx ON messages(in_reply_to);
|
||||
CREATE INDEX messages_sent_at_idx ON messages(sent_at DESC);
|
||||
CREATE INDEX messages_folder_id_idx ON messages(folder_id);
|
||||
|
||||
CREATE TABLE bodies (
|
||||
message_id UUID PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
|
||||
text_body TEXT,
|
||||
html_body TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
filename TEXT,
|
||||
content_type TEXT,
|
||||
size BIGINT NOT NULL,
|
||||
content_hash TEXT NOT NULL, -- dedupe identical attachments across messages
|
||||
blob_ref TEXT NOT NULL -- filesystem path derived from content_hash
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_message_id_idx ON attachments(message_id);
|
||||
CREATE INDEX attachments_content_hash_idx ON attachments(content_hash);
|
||||
@@ -0,0 +1,43 @@
|
||||
-- Tags, rule engine, and push-notification device registrations.
|
||||
-- Schema only in this phase — the rule engine execution itself is a later
|
||||
-- build-order phase (server-architecture-spec.md §9, item 5).
|
||||
|
||||
CREATE TABLE tags (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT,
|
||||
UNIQUE (user_id, name)
|
||||
);
|
||||
|
||||
CREATE TABLE message_tags (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
tag_id UUID NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (message_id, tag_id)
|
||||
);
|
||||
|
||||
-- Structured JSON (condition tree + action list) rather than a free-text DSL,
|
||||
-- so both webapp and rule-engine can render/edit rules without a parser (§3.5).
|
||||
CREATE TABLE rules (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
conditions JSONB NOT NULL,
|
||||
actions JSONB NOT NULL,
|
||||
enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
priority INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX rules_user_id_priority_idx ON rules(user_id, priority);
|
||||
|
||||
CREATE TABLE devices (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, -- 'unifiedpush' | 'websocket'
|
||||
endpoint TEXT, -- unifiedpush distributor endpoint URL
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_seen_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX devices_user_id_idx ON devices(user_id);
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
# Minimal reverse proxy per server-architecture-spec.md §7: nginx terminates
|
||||
# TLS (add a cert + `listen 443 ssl;` for real deployment — this is the
|
||||
# plain-HTTP local-dev shape) and forwards to the API, which never needs to
|
||||
# be reachable directly.
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
|
||||
location / {
|
||||
proxy_pass http://server:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# WebSocket upgrade support, once the WS notification endpoint lands.
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use crate::api::middleware::CurrentUser;
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::ApiResult;
|
||||
use crate::models::account::{Account, AccountPublic};
|
||||
use axum::{extract::State, Json};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateAccountRequest {
|
||||
pub name: String,
|
||||
pub imap_host: String,
|
||||
pub imap_port: i32,
|
||||
pub smtp_host: String,
|
||||
pub smtp_port: i32,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
pub async fn list(State(state): State<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<AccountPublic>>> {
|
||||
let accounts: Vec<Account> = sqlx::query_as("SELECT * FROM accounts WHERE user_id = $1 ORDER BY created_at")
|
||||
.bind(user.user_id)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(accounts.into_iter().map(AccountPublic::from).collect()))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Json(req): Json<CreateAccountRequest>,
|
||||
) -> ApiResult<Json<AccountPublic>> {
|
||||
let encrypted = state.cipher.encrypt(&req.password)?;
|
||||
|
||||
let account: Account = sqlx::query_as(
|
||||
"INSERT INTO accounts \
|
||||
(user_id, name, imap_host, imap_port, smtp_host, smtp_port, username, encrypted_password, password_nonce) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *",
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.bind(&req.name)
|
||||
.bind(&req.imap_host)
|
||||
.bind(req.imap_port)
|
||||
.bind(&req.smtp_host)
|
||||
.bind(req.smtp_port)
|
||||
.bind(&req.username)
|
||||
.bind(&encrypted.ciphertext)
|
||||
.bind(&encrypted.nonce)
|
||||
.fetch_one(&state.pool)
|
||||
.await?;
|
||||
|
||||
sqlx::query("INSERT INTO sync_state (account_id) VALUES ($1)")
|
||||
.bind(account.id)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(account.into()))
|
||||
}
|
||||
|
||||
pub async fn delete(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
|
||||
) -> ApiResult<Json<serde_json::Value>> {
|
||||
sqlx::query("DELETE FROM accounts WHERE id = $1 AND user_id = $2")
|
||||
.bind(account_id)
|
||||
.bind(user.user_id)
|
||||
.execute(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(serde_json::json!({ "ok": true })))
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use crate::api::state::AppState;
|
||||
use crate::auth::{hash_password, verify_password};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::models::User;
|
||||
use axum::{extract::State, Json};
|
||||
use chrono::{Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RegisterRequest {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct LoginRequest {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct SessionResponse {
|
||||
pub token: Uuid,
|
||||
pub user_id: Uuid,
|
||||
}
|
||||
|
||||
pub async fn register(State(state): State<AppState>, Json(req): Json<RegisterRequest>) -> ApiResult<Json<SessionResponse>> {
|
||||
if req.username.trim().is_empty() || req.password.len() < 8 {
|
||||
return Err(ApiError::BadRequest(
|
||||
"username must be non-empty and password must be at least 8 characters".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let password_hash = hash_password(&req.password)?;
|
||||
|
||||
let user: User = sqlx::query_as(
|
||||
"INSERT INTO users (username, password_hash) VALUES ($1, $2) RETURNING *",
|
||||
)
|
||||
.bind(&req.username)
|
||||
.bind(&password_hash)
|
||||
.fetch_one(&state.pool)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
sqlx::Error::Database(db_err) if db_err.is_unique_violation() => {
|
||||
ApiError::BadRequest("username already taken".into())
|
||||
}
|
||||
other => ApiError::Sqlx(other),
|
||||
})?;
|
||||
|
||||
create_session(&state, user.id).await.map(Json)
|
||||
}
|
||||
|
||||
pub async fn login(State(state): State<AppState>, Json(req): Json<LoginRequest>) -> ApiResult<Json<SessionResponse>> {
|
||||
let user: Option<User> = sqlx::query_as("SELECT * FROM users WHERE username = $1")
|
||||
.bind(&req.username)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?;
|
||||
|
||||
let user = user.ok_or(ApiError::Unauthorized)?;
|
||||
if !verify_password(&req.password, &user.password_hash)? {
|
||||
return Err(ApiError::Unauthorized);
|
||||
}
|
||||
|
||||
create_session(&state, user.id).await.map(Json)
|
||||
}
|
||||
|
||||
async fn create_session(state: &AppState, user_id: Uuid) -> ApiResult<SessionResponse> {
|
||||
let expires_at = Utc::now() + Duration::hours(state.session_ttl_hours);
|
||||
let row: (Uuid,) = sqlx::query_as(
|
||||
"INSERT INTO sessions (user_id, expires_at) VALUES ($1, $2) RETURNING token",
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(expires_at)
|
||||
.fetch_one(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(SessionResponse { token: row.0, user_id })
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//! `GET /events?since=<cursor>` — the delta/sync endpoint from
|
||||
//! server-architecture-spec.md §4 and the polling-fallback path from §3.8.
|
||||
//! WebSocket push is a later build-order phase (§9 item 7); this polling
|
||||
//! endpoint is what mobile/degraded clients use meanwhile, and stays the
|
||||
//! fallback afterwards.
|
||||
|
||||
use crate::api::middleware::CurrentUser;
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::ApiResult;
|
||||
use crate::models::Message;
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
Json,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct EventsQuery {
|
||||
pub since: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct EventsResponse {
|
||||
pub changed_messages: Vec<Message>,
|
||||
pub cursor: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub async fn poll(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Query(q): Query<EventsQuery>,
|
||||
) -> ApiResult<Json<EventsResponse>> {
|
||||
let since = q.since.unwrap_or_else(|| Utc::now() - chrono::Duration::days(1));
|
||||
let cursor = Utc::now();
|
||||
|
||||
let changed_messages: Vec<Message> = sqlx::query_as(
|
||||
"SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \
|
||||
WHERE a.user_id = $1 AND m.created_at > $2 \
|
||||
ORDER BY m.created_at ASC \
|
||||
LIMIT 500",
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.bind(since)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(EventsResponse { changed_messages, cursor }))
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use crate::api::middleware::CurrentUser;
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::ApiResult;
|
||||
use crate::models::Folder;
|
||||
use axum::{extract::State, Json};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateFolderRequest {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub async fn list(State(state): State<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<Folder>>> {
|
||||
let folders: Vec<Folder> = sqlx::query_as("SELECT * FROM folders WHERE user_id = $1 ORDER BY name")
|
||||
.bind(user.user_id)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
Ok(Json(folders))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Json(req): Json<CreateFolderRequest>,
|
||||
) -> ApiResult<Json<Folder>> {
|
||||
let folder: Folder = sqlx::query_as("INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *")
|
||||
.bind(user.user_id)
|
||||
.bind(&req.name)
|
||||
.fetch_one(&state.pool)
|
||||
.await?;
|
||||
Ok(Json(folder))
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Cursor-based message listing (server-architecture-spec.md §4 — cursor,
|
||||
//! not offset, since new mail arrives continuously and would shift an
|
||||
//! offset-based page). The cursor is just the `sent_at` of the last item
|
||||
//! returned; callers pass it back as `before` to get the next page.
|
||||
|
||||
use crate::api::middleware::CurrentUser;
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::models::message::Body;
|
||||
use crate::models::Message;
|
||||
use axum::{
|
||||
extract::{Path, Query, State},
|
||||
Json,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ListMessagesQuery {
|
||||
pub folder_id: Option<Uuid>,
|
||||
pub thread_id: Option<Uuid>,
|
||||
pub before: Option<DateTime<Utc>>,
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ListMessagesResponse {
|
||||
pub messages: Vec<Message>,
|
||||
pub next_cursor: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Query(q): Query<ListMessagesQuery>,
|
||||
) -> ApiResult<Json<ListMessagesResponse>> {
|
||||
let limit = q.limit.unwrap_or(50).clamp(1, 200);
|
||||
let before = q.before.unwrap_or_else(Utc::now);
|
||||
|
||||
let messages: Vec<Message> = sqlx::query_as(
|
||||
"SELECT m.* FROM messages m \
|
||||
JOIN accounts a ON a.id = m.account_id \
|
||||
WHERE a.user_id = $1 \
|
||||
AND m.sent_at < $2 \
|
||||
AND ($3::uuid IS NULL OR m.folder_id = $3) \
|
||||
AND ($4::uuid IS NULL OR m.thread_id = $4) \
|
||||
ORDER BY m.sent_at DESC \
|
||||
LIMIT $5",
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.bind(before)
|
||||
.bind(q.folder_id)
|
||||
.bind(q.thread_id)
|
||||
.bind(limit)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
let next_cursor = messages.last().and_then(|m| m.sent_at);
|
||||
|
||||
Ok(Json(ListMessagesResponse { messages, next_cursor }))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct MessageDetail {
|
||||
#[serde(flatten)]
|
||||
pub message: Message,
|
||||
pub body: Option<Body>,
|
||||
}
|
||||
|
||||
pub async fn get(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(message_id): Path<Uuid>,
|
||||
) -> ApiResult<Json<MessageDetail>> {
|
||||
let message: Message = sqlx::query_as(
|
||||
"SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \
|
||||
WHERE m.id = $1 AND a.user_id = $2",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(user.user_id)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound)?;
|
||||
|
||||
let body: Option<Body> = sqlx::query_as("SELECT * FROM bodies WHERE message_id = $1")
|
||||
.bind(message_id)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(MessageDetail { message, body }))
|
||||
}
|
||||
|
||||
/// "Fetch thread" endpoint (§3.6) — the client just needs thread_id exposed
|
||||
/// plus a way to pull every message in it; how to render it (collapsed vs
|
||||
/// flat) is left entirely to the client.
|
||||
pub async fn get_thread(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(thread_id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Vec<Message>>> {
|
||||
let messages: Vec<Message> = sqlx::query_as(
|
||||
"SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \
|
||||
WHERE m.thread_id = $1 AND a.user_id = $2 \
|
||||
ORDER BY m.sent_at ASC",
|
||||
)
|
||||
.bind(thread_id)
|
||||
.bind(user.user_id)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(messages))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::ApiError;
|
||||
use axum::{
|
||||
extract::FromRequestParts,
|
||||
http::request::Parts,
|
||||
};
|
||||
use chrono::Utc;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// The authenticated user for a request, resolved from a bearer session
|
||||
/// token (`Authorization: Bearer <session-token>`). API auth is independent
|
||||
/// of IMAP credentials (server-architecture-spec.md §2.4) — this is purely
|
||||
/// local session state.
|
||||
pub struct CurrentUser {
|
||||
pub user_id: Uuid,
|
||||
}
|
||||
|
||||
#[axum::async_trait]
|
||||
impl FromRequestParts<AppState> for CurrentUser {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(parts: &mut Parts, state: &AppState) -> Result<Self, Self::Rejection> {
|
||||
let header = parts
|
||||
.headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or(ApiError::Unauthorized)?;
|
||||
|
||||
let token_str = header.strip_prefix("Bearer ").ok_or(ApiError::Unauthorized)?;
|
||||
let token = Uuid::parse_str(token_str).map_err(|_| ApiError::Unauthorized)?;
|
||||
|
||||
let row: Option<(Uuid, chrono::DateTime<Utc>)> =
|
||||
sqlx::query_as("SELECT user_id, expires_at FROM sessions WHERE token = $1")
|
||||
.bind(token)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?;
|
||||
|
||||
match row {
|
||||
Some((user_id, expires_at)) if expires_at > Utc::now() => Ok(CurrentUser { user_id }),
|
||||
_ => Err(ApiError::Unauthorized),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pub mod accounts;
|
||||
pub mod auth;
|
||||
pub mod events;
|
||||
pub mod folders;
|
||||
pub mod messages;
|
||||
pub mod middleware;
|
||||
pub mod router;
|
||||
pub mod state;
|
||||
|
||||
pub use router::build;
|
||||
pub use state::AppState;
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::api::state::AppState;
|
||||
use crate::api::{accounts, auth, events, folders, messages};
|
||||
use axum::routing::{delete, get, post};
|
||||
use axum::Router;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
pub fn build(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/api/auth/register", post(auth::register))
|
||||
.route("/api/auth/login", post(auth::login))
|
||||
.route("/api/accounts", get(accounts::list).post(accounts::create))
|
||||
.route("/api/accounts/{id}", delete(accounts::delete))
|
||||
.route("/api/folders", get(folders::list).post(folders::create))
|
||||
.route("/api/messages", get(messages::list))
|
||||
.route("/api/messages/{id}", get(messages::get))
|
||||
.route("/api/threads/{id}", get(messages::get_thread))
|
||||
.route("/api/events", get(events::poll))
|
||||
.route("/healthz", get(|| async { "ok" }))
|
||||
.layer(TraceLayer::new_for_http())
|
||||
.layer(CorsLayer::permissive())
|
||||
.with_state(state)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::config::Config;
|
||||
use crate::crypto::CredentialCipher;
|
||||
use crate::storage::BlobStore;
|
||||
use sqlx::PgPool;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub pool: PgPool,
|
||||
pub cipher: CredentialCipher,
|
||||
pub blobs: BlobStore,
|
||||
pub session_ttl_hours: i64,
|
||||
pub config: Config,
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
use anyhow::Result;
|
||||
use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||
Argon2,
|
||||
};
|
||||
|
||||
pub fn hash_password(password: &str) -> Result<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default()
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|h| h.to_string())
|
||||
.map_err(|e| anyhow::anyhow!("password hashing failed: {e}"))
|
||||
}
|
||||
|
||||
pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
|
||||
let parsed = PasswordHash::new(hash).map_err(|e| anyhow::anyhow!("stored password hash is malformed: {e}"))?;
|
||||
Ok(Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok())
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
pub database_url: String,
|
||||
pub bind_addr: String,
|
||||
/// 32-byte key, base64-encoded, used for ChaCha20-Poly1305 encryption of
|
||||
/// stored IMAP/SMTP credentials (server-architecture-spec.md §7).
|
||||
pub credential_key: [u8; 32],
|
||||
/// Directory raw MIME blobs and attachments are stored under (§3.2).
|
||||
pub blob_storage_dir: std::path::PathBuf,
|
||||
pub session_ttl_hours: i64,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Result<Self> {
|
||||
let database_url = std::env::var("DATABASE_URL")
|
||||
.context("DATABASE_URL must be set (e.g. postgres://tern:tern@localhost/tern)")?;
|
||||
|
||||
let bind_addr = std::env::var("BIND_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".to_string());
|
||||
|
||||
let key_b64 = std::env::var("CREDENTIAL_KEY").context(
|
||||
"CREDENTIAL_KEY must be set: a base64-encoded 32-byte key used to encrypt stored \
|
||||
IMAP/SMTP credentials at rest. Generate one with: openssl rand -base64 32",
|
||||
)?;
|
||||
let key_bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, key_b64.trim())
|
||||
.context("CREDENTIAL_KEY is not valid base64")?;
|
||||
let credential_key: [u8; 32] = key_bytes
|
||||
.try_into()
|
||||
.map_err(|v: Vec<u8>| anyhow::anyhow!("CREDENTIAL_KEY must decode to exactly 32 bytes, got {}", v.len()))?;
|
||||
|
||||
let blob_storage_dir = std::env::var("BLOB_STORAGE_DIR")
|
||||
.unwrap_or_else(|_| "./data/blobs".to_string())
|
||||
.into();
|
||||
|
||||
let session_ttl_hours = std::env::var("SESSION_TTL_HOURS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(24 * 30);
|
||||
|
||||
Ok(Self {
|
||||
database_url,
|
||||
bind_addr,
|
||||
credential_key,
|
||||
blob_storage_dir,
|
||||
session_ttl_hours,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
//! Encryption at rest for stored IMAP/SMTP credentials.
|
||||
//!
|
||||
//! server-architecture-spec.md §7 asks for "libsodium secretbox... or better, a
|
||||
//! key derived from something you don't also store in the same DB". We use
|
||||
//! ChaCha20-Poly1305 (RustCrypto, pure Rust, no libsodium system dependency)
|
||||
//! which is the same construction family as secretbox (XSalsa20-Poly1305) —
|
||||
//! an AEAD cipher with a random nonce per message. The key itself comes from
|
||||
//! the `CREDENTIAL_KEY` env var (see config.rs), not from the database.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use chacha20poly1305::{
|
||||
aead::{Aead, KeyInit},
|
||||
ChaCha20Poly1305, Key, Nonce,
|
||||
};
|
||||
use rand::RngCore;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CredentialCipher {
|
||||
cipher: ChaCha20Poly1305,
|
||||
}
|
||||
|
||||
pub struct Encrypted {
|
||||
pub ciphertext: Vec<u8>,
|
||||
pub nonce: Vec<u8>,
|
||||
}
|
||||
|
||||
impl CredentialCipher {
|
||||
pub fn new(key: &[u8; 32]) -> Self {
|
||||
Self {
|
||||
cipher: ChaCha20Poly1305::new(Key::from_slice(key)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encrypt(&self, plaintext: &str) -> Result<Encrypted> {
|
||||
let mut nonce_bytes = [0u8; 12];
|
||||
rand::thread_rng().fill_bytes(&mut nonce_bytes);
|
||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||
|
||||
let ciphertext = self
|
||||
.cipher
|
||||
.encrypt(nonce, plaintext.as_bytes())
|
||||
.map_err(|e| anyhow::anyhow!("credential encryption failed: {e}"))?;
|
||||
|
||||
Ok(Encrypted {
|
||||
ciphertext,
|
||||
nonce: nonce_bytes.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn decrypt(&self, ciphertext: &[u8], nonce: &[u8]) -> Result<String> {
|
||||
let nonce = Nonce::from_slice(nonce);
|
||||
let plaintext = self
|
||||
.cipher
|
||||
.decrypt(nonce, ciphertext)
|
||||
.map_err(|e| anyhow::anyhow!("credential decryption failed: {e}"))?;
|
||||
String::from_utf8(plaintext).context("decrypted credential was not valid utf-8")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips() {
|
||||
let key = [7u8; 32];
|
||||
let c = CredentialCipher::new(&key);
|
||||
let enc = c.encrypt("hunter2").unwrap();
|
||||
assert_eq!(c.decrypt(&enc.ciphertext, &enc.nonce).unwrap(), "hunter2");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use anyhow::{Context, Result};
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
|
||||
pub async fn connect(database_url: &str) -> Result<PgPool> {
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(10)
|
||||
.connect(database_url)
|
||||
.await
|
||||
.context("failed to connect to Postgres")?;
|
||||
|
||||
sqlx::migrate!("./migrations")
|
||||
.run(&pool)
|
||||
.await
|
||||
.context("failed to run database migrations")?;
|
||||
|
||||
Ok(pool)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum ApiError {
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
#[error("unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
#[error(transparent)]
|
||||
Internal(#[from] anyhow::Error),
|
||||
#[error(transparent)]
|
||||
Sqlx(#[from] sqlx::Error),
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, message) = match &self {
|
||||
ApiError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
|
||||
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
|
||||
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
|
||||
ApiError::Sqlx(e) => {
|
||||
tracing::error!("db error: {e:#}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_string())
|
||||
}
|
||||
ApiError::Internal(e) => {
|
||||
tracing::error!("internal error: {e:#}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_string())
|
||||
}
|
||||
};
|
||||
(status, Json(json!({ "error": message }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
pub type ApiResult<T> = Result<T, ApiError>;
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Jittered exponential backoff for reconnecting to flaky IMAP servers
|
||||
//! (server-architecture-spec.md §3.1).
|
||||
|
||||
use rand::Rng;
|
||||
use std::time::Duration;
|
||||
|
||||
pub struct Backoff {
|
||||
attempt: u32,
|
||||
base: Duration,
|
||||
max: Duration,
|
||||
}
|
||||
|
||||
impl Backoff {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
attempt: 0,
|
||||
base: Duration::from_secs(1),
|
||||
max: Duration::from_secs(300),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.attempt = 0;
|
||||
}
|
||||
|
||||
/// Next delay, doubling each call up to `max`, plus up to 30% jitter so
|
||||
/// many accounts reconnecting at once don't hammer the server in lockstep.
|
||||
pub fn next_delay(&mut self) -> Duration {
|
||||
let exp = self.base.as_secs_f64() * 2f64.powi(self.attempt as i32);
|
||||
let capped = exp.min(self.max.as_secs_f64());
|
||||
self.attempt = self.attempt.saturating_add(1);
|
||||
|
||||
let jitter_factor = rand::thread_rng().gen_range(1.0..1.3);
|
||||
Duration::from_secs_f64(capped * jitter_factor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
//! Per-account IMAP sync: connect, catch up on new mail, then IDLE and react
|
||||
//! to server pushes. One task per account (spawned by `manager.rs`).
|
||||
//!
|
||||
//! Design per server-architecture-spec.md §3.1:
|
||||
//! - One IDLE connection per account, watching INBOX only (§2.5 — folders
|
||||
//! are virtual/app-level, the sync engine only ever watches INBOX).
|
||||
//! - A NOOP-based watchdog: IDLE is re-issued periodically (servers commonly
|
||||
//! time out an IDLE session around 30 min) and a stalled connection (no
|
||||
//! response within the watchdog window) forces a reconnect.
|
||||
//! - Jittered exponential backoff on any connection failure.
|
||||
//! - Headers first: the initial/catch-up pass stores ENVELOPE + flags
|
||||
//! immediately; bodies are fetched lazily in a trailing pass so a large
|
||||
//! backlog doesn't block new-mail visibility.
|
||||
|
||||
use crate::crypto::CredentialCipher;
|
||||
use crate::imap_sync::backoff::Backoff;
|
||||
use crate::imap_sync::parse::parse_raw_message;
|
||||
use crate::models::account::Account;
|
||||
use crate::storage::BlobStore;
|
||||
use anyhow::{Context, Result};
|
||||
use async_imap::extensions::idle::IdleResponse;
|
||||
use futures::TryStreamExt;
|
||||
use sqlx::PgPool;
|
||||
use std::time::Duration;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Re-issue IDLE this often even if the server hasn't timed out, and treat a
|
||||
/// connection as stalled if nothing happens for this long.
|
||||
const IDLE_RENEW: Duration = Duration::from_secs(25 * 60);
|
||||
const BODY_FETCH_BATCH: i64 = 25;
|
||||
|
||||
type ImapSession = async_imap::Session<async_native_tls::TlsStream<tokio::net::TcpStream>>;
|
||||
|
||||
pub struct AccountSyncer {
|
||||
pub account: Account,
|
||||
pub pool: PgPool,
|
||||
pub cipher: CredentialCipher,
|
||||
pub blobs: BlobStore,
|
||||
}
|
||||
|
||||
impl AccountSyncer {
|
||||
/// Runs forever: connect, sync, idle, reconnect with backoff on failure.
|
||||
pub async fn run(self) {
|
||||
let mut backoff = Backoff::new();
|
||||
loop {
|
||||
match self.sync_once().await {
|
||||
Ok(()) => {
|
||||
// sync_once only returns Ok on a clean shutdown request.
|
||||
tracing::info!(account_id = %self.account.id, "sync loop stopped cleanly");
|
||||
return;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(account_id = %self.account.id, error = %e, "sync connection dropped, reconnecting");
|
||||
let _ = self.mark_status("error", Some(&e.to_string())).await;
|
||||
tokio::time::sleep(backoff.next_delay()).await;
|
||||
}
|
||||
}
|
||||
backoff.reset();
|
||||
}
|
||||
}
|
||||
|
||||
async fn mark_status(&self, status: &str, last_error: Option<&str>) -> Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE sync_state SET status = $2, last_error = $3, updated_at = now() WHERE account_id = $1",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
.bind(status)
|
||||
.bind(last_error)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn sync_once(&self) -> Result<()> {
|
||||
let password = self
|
||||
.cipher
|
||||
.decrypt(&self.account.encrypted_password, &self.account.password_nonce)
|
||||
.context("decrypting stored IMAP password")?;
|
||||
|
||||
self.mark_status("syncing", None).await?;
|
||||
|
||||
let tcp = tokio::net::TcpStream::connect((self.account.imap_host.as_str(), self.account.imap_port as u16))
|
||||
.await
|
||||
.context("TCP connect to IMAP host failed")?;
|
||||
|
||||
let tls = async_native_tls::TlsConnector::new();
|
||||
let tls_stream = tls
|
||||
.connect(self.account.imap_host.as_str(), tcp)
|
||||
.await
|
||||
.context("IMAP TLS handshake failed")?;
|
||||
|
||||
let client = async_imap::Client::new(tls_stream);
|
||||
let mut session = client
|
||||
.login(&self.account.username, &password)
|
||||
.await
|
||||
.map_err(|(e, _client)| anyhow::anyhow!("IMAP login failed: {e}"))?;
|
||||
|
||||
let mailbox = session.select("INBOX").await.context("SELECT INBOX failed")?;
|
||||
let server_uidvalidity = mailbox.uid_validity.map(|v| v as i64);
|
||||
|
||||
self.reconcile_uidvalidity(server_uidvalidity).await?;
|
||||
|
||||
// Catch up on anything new, then keep going until told to stop.
|
||||
// `Session::idle()` consumes the session and hands back a `Handle`;
|
||||
// `Handle::done()` hands the session back once IDLE ends, so it gets
|
||||
// threaded through the loop by value rather than by `&mut`.
|
||||
loop {
|
||||
self.fetch_new_headers(&mut session).await?;
|
||||
self.fetch_pending_bodies(&mut session).await?;
|
||||
self.mark_status("idle", None).await?;
|
||||
|
||||
let (went_idle, returned_session) = self.idle_until_change(session).await?;
|
||||
session = returned_session;
|
||||
if !went_idle {
|
||||
// Server doesn't support IDLE (or it isn't available) — fall
|
||||
// back to a plain poll interval instead of a tight loop.
|
||||
tokio::time::sleep(Duration::from_secs(5 * 60)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn reconcile_uidvalidity(&self, server_uidvalidity: Option<i64>) -> Result<()> {
|
||||
let existing: Option<(Option<i64>,)> =
|
||||
sqlx::query_as("SELECT uidvalidity FROM sync_state WHERE account_id = $1")
|
||||
.bind(self.account.id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
match existing {
|
||||
None => {
|
||||
sqlx::query(
|
||||
"INSERT INTO sync_state (account_id, uidvalidity, last_synced_uid, status) \
|
||||
VALUES ($1, $2, 0, 'syncing')",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
.bind(server_uidvalidity)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
Some((stored,)) if stored != server_uidvalidity => {
|
||||
// UIDVALIDITY changed: every previously cached UID is now
|
||||
// meaningless. Drop this account's messages and start over.
|
||||
tracing::warn!(account_id = %self.account.id, "UIDVALIDITY changed, re-syncing folder from scratch");
|
||||
let mut tx = self.pool.begin().await?;
|
||||
sqlx::query("DELETE FROM messages WHERE account_id = $1")
|
||||
.bind(self.account.id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE sync_state SET uidvalidity = $2, last_synced_uid = 0, updated_at = now() \
|
||||
WHERE account_id = $1",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
.bind(server_uidvalidity)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn last_synced_uid(&self) -> Result<i64> {
|
||||
let row: (i64,) = sqlx::query_as("SELECT last_synced_uid FROM sync_state WHERE account_id = $1")
|
||||
.bind(self.account.id)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
Ok(row.0)
|
||||
}
|
||||
|
||||
/// Headers-first catch-up pass: fetch ENVELOPE + FLAGS for any UID beyond
|
||||
/// the last one we've stored, insert stub message rows (body_fetched =
|
||||
/// false). Bodies are filled in by `fetch_pending_bodies`.
|
||||
async fn fetch_new_headers(
|
||||
&self,
|
||||
session: &mut ImapSession,
|
||||
) -> Result<()> {
|
||||
let last_uid = self.last_synced_uid().await?;
|
||||
let range = format!("{}:*", last_uid + 1);
|
||||
|
||||
let fetches: Vec<_> = session
|
||||
.uid_fetch(&range, "(UID FLAGS ENVELOPE)")
|
||||
.await
|
||||
.context("UID FETCH (headers) failed")?
|
||||
.try_collect()
|
||||
.await
|
||||
.context("reading UID FETCH response")?;
|
||||
|
||||
let mut max_uid = last_uid;
|
||||
for f in &fetches {
|
||||
let Some(uid) = f.uid else { continue };
|
||||
if uid as i64 <= last_uid {
|
||||
// The "N:*" range syntax always includes the highest UID in
|
||||
// the mailbox even when N is past it; skip anything we
|
||||
// already have.
|
||||
continue;
|
||||
}
|
||||
max_uid = max_uid.max(uid as i64);
|
||||
|
||||
let envelope = f.envelope();
|
||||
let subject = envelope
|
||||
.and_then(|e| e.subject.as_ref())
|
||||
.map(|s| String::from_utf8_lossy(s).to_string());
|
||||
let message_id = envelope
|
||||
.and_then(|e| e.message_id.as_ref())
|
||||
.map(|s| String::from_utf8_lossy(s).to_string());
|
||||
let in_reply_to = envelope
|
||||
.and_then(|e| e.in_reply_to.as_ref())
|
||||
.map(|s| String::from_utf8_lossy(s).to_string());
|
||||
|
||||
let flags: Vec<String> = f.flags().map(|flag| format!("{flag:?}")).collect();
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO messages \
|
||||
(account_id, uid, message_id, in_reply_to, subject, flags, body_fetched) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, false) \
|
||||
ON CONFLICT (account_id, uid) DO UPDATE SET flags = EXCLUDED.flags",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
.bind(uid as i64)
|
||||
.bind(&message_id)
|
||||
.bind(&in_reply_to)
|
||||
.bind(&subject)
|
||||
.bind(&flags)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
if max_uid > last_uid {
|
||||
sqlx::query("UPDATE sync_state SET last_synced_uid = $2, updated_at = now() WHERE account_id = $1")
|
||||
.bind(self.account.id)
|
||||
.bind(max_uid)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Trailing pass: pull full bodies for a batch of messages that only
|
||||
/// have headers so far, parse and store them, then mark body_fetched.
|
||||
async fn fetch_pending_bodies(
|
||||
&self,
|
||||
session: &mut ImapSession,
|
||||
) -> Result<()> {
|
||||
loop {
|
||||
let pending: Vec<(Uuid, i64)> = sqlx::query_as(
|
||||
"SELECT id, uid FROM messages WHERE account_id = $1 AND body_fetched = false \
|
||||
ORDER BY uid ASC LIMIT $2",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
.bind(BODY_FETCH_BATCH)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
|
||||
if pending.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let uid_set = pending
|
||||
.iter()
|
||||
.map(|(_, uid)| uid.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
|
||||
let fetches: Vec<_> = session
|
||||
.uid_fetch(&uid_set, "(UID RFC822)")
|
||||
.await
|
||||
.context("UID FETCH (body) failed")?
|
||||
.try_collect()
|
||||
.await
|
||||
.context("reading UID FETCH body response")?;
|
||||
|
||||
for f in &fetches {
|
||||
let (Some(uid), Some(raw)) = (f.uid, f.body()) else { continue };
|
||||
let Some((row_id, _)) = pending.iter().find(|(_, u)| *u == uid as i64) else { continue };
|
||||
|
||||
if let Err(e) = self.store_body(*row_id, raw).await {
|
||||
tracing::error!(account_id = %self.account.id, uid, error = %e, "failed to store message body");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn store_body(&self, message_row_id: Uuid, raw: &[u8]) -> Result<()> {
|
||||
let parsed = parse_raw_message(raw)?;
|
||||
let (_, raw_blob_ref) = self.blobs.put(&parsed.raw).await?;
|
||||
|
||||
let mut tx = self.pool.begin().await?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE messages SET \
|
||||
message_id = COALESCE($2, message_id), \
|
||||
in_reply_to = COALESCE($3, in_reply_to), \
|
||||
references_ = $4, \
|
||||
from_addr = $5, from_name = $6, \
|
||||
to_addrs = $7, cc_addrs = $8, \
|
||||
subject = COALESCE($9, subject), \
|
||||
sent_at = $10, \
|
||||
raw_blob_ref = $11, \
|
||||
body_fetched = true \
|
||||
WHERE id = $1",
|
||||
)
|
||||
.bind(message_row_id)
|
||||
.bind(&parsed.message_id)
|
||||
.bind(&parsed.in_reply_to)
|
||||
.bind(&parsed.references)
|
||||
.bind(&parsed.from_addr)
|
||||
.bind(&parsed.from_name)
|
||||
.bind(&parsed.to_addrs)
|
||||
.bind(&parsed.cc_addrs)
|
||||
.bind(&parsed.subject)
|
||||
.bind(parsed.sent_at)
|
||||
.bind(&raw_blob_ref)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO bodies (message_id, text_body, html_body) VALUES ($1, $2, $3) \
|
||||
ON CONFLICT (message_id) DO UPDATE SET text_body = EXCLUDED.text_body, html_body = EXCLUDED.html_body",
|
||||
)
|
||||
.bind(message_row_id)
|
||||
.bind(&parsed.text_body)
|
||||
.bind(&parsed.html_body)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
for att in &parsed.attachments {
|
||||
let (content_hash, blob_ref) = self.blobs.put(&att.data).await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO attachments (message_id, filename, content_type, size, content_hash, blob_ref) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6)",
|
||||
)
|
||||
.bind(message_row_id)
|
||||
.bind(&att.filename)
|
||||
.bind(&att.content_type)
|
||||
.bind(att.data.len() as i64)
|
||||
.bind(&content_hash)
|
||||
.bind(&blob_ref)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Issues IDLE and waits for either a mailbox change or the renewal
|
||||
/// timeout. Returns `Ok((true, session))` if IDLE was used, or
|
||||
/// `Ok((false, session))` if the server rejected it (caller should fall
|
||||
/// back to polling) — either way the session is handed back so the
|
||||
/// caller can keep using it. `Session::idle()` takes the session by
|
||||
/// value; `Handle::done()` gives it back once IDLE ends.
|
||||
async fn idle_until_change(&self, session: ImapSession) -> Result<(bool, ImapSession)> {
|
||||
let mut handle = session.idle();
|
||||
if let Err(e) = handle.init().await {
|
||||
tracing::warn!(account_id = %self.account.id, error = %e, "server rejected IDLE, falling back to polling");
|
||||
let session = handle.done().await.context("recovering session after failed IDLE init")?;
|
||||
return Ok((false, session));
|
||||
}
|
||||
|
||||
let (idle_wait, _stop_source) = handle.wait_with_timeout(IDLE_RENEW);
|
||||
let wait_result = idle_wait.await;
|
||||
|
||||
let session = handle.done().await.context("DONE after IDLE failed")?;
|
||||
|
||||
match wait_result {
|
||||
Ok(IdleResponse::NewData(_)) => {
|
||||
tracing::debug!(account_id = %self.account.id, "IDLE reported new data");
|
||||
}
|
||||
Ok(IdleResponse::Timeout) => {
|
||||
// Just a renewal tick — nothing necessarily changed.
|
||||
}
|
||||
Ok(IdleResponse::ManualInterrupt) => {}
|
||||
Err(e) => {
|
||||
return Err(anyhow::anyhow!("IDLE wait failed: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok((true, session))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Spawns and tracks one sync task per account. Polls for newly-added
|
||||
//! accounts periodically rather than requiring a restart to pick them up.
|
||||
|
||||
use crate::crypto::CredentialCipher;
|
||||
use crate::imap_sync::connection::AccountSyncer;
|
||||
use crate::models::account::Account;
|
||||
use crate::storage::BlobStore;
|
||||
use sqlx::PgPool;
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
use uuid::Uuid;
|
||||
|
||||
const ACCOUNT_POLL_INTERVAL: Duration = Duration::from_secs(30);
|
||||
|
||||
pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore) {
|
||||
let mut running: HashMap<Uuid, tokio::task::JoinHandle<()>> = HashMap::new();
|
||||
|
||||
loop {
|
||||
running.retain(|_, handle| !handle.is_finished());
|
||||
|
||||
match sqlx::query_as::<_, Account>("SELECT * FROM accounts")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
{
|
||||
Ok(accounts) => {
|
||||
for account in accounts {
|
||||
if running.contains_key(&account.id) {
|
||||
continue;
|
||||
}
|
||||
tracing::info!(account_id = %account.id, name = %account.name, "starting sync task");
|
||||
let syncer = AccountSyncer {
|
||||
account,
|
||||
pool: pool.clone(),
|
||||
cipher: cipher.clone(),
|
||||
blobs: blobs.clone(),
|
||||
};
|
||||
let id = syncer.account.id;
|
||||
let handle = tokio::spawn(syncer.run());
|
||||
running.insert(id, handle);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
|
||||
}
|
||||
|
||||
tokio::time::sleep(ACCOUNT_POLL_INTERVAL).await;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
pub mod backoff;
|
||||
pub mod connection;
|
||||
pub mod manager;
|
||||
pub mod parse;
|
||||
|
||||
pub use manager::run;
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Turn a raw MIME blob into a `ParsedMessage` ready for insertion.
|
||||
//! Threading headers (Message-ID / In-Reply-To / References) are parsed here
|
||||
//! per server-architecture-spec.md §3.6, though the JWZ linking/merging pass
|
||||
//! itself is a later build-order phase — for now each message just carries
|
||||
//! its own generated `thread_id` and these headers for future re-threading.
|
||||
|
||||
use crate::models::message::{ParsedAttachment, ParsedMessage};
|
||||
use chrono::{DateTime, Utc};
|
||||
use mail_parser::{Address, MessageParser, MimeHeaders};
|
||||
|
||||
pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
|
||||
let message = MessageParser::default()
|
||||
.parse(raw)
|
||||
.ok_or_else(|| anyhow::anyhow!("mail-parser failed to parse message"))?;
|
||||
|
||||
let message_id = message.message_id().map(String::from);
|
||||
let in_reply_to = message.in_reply_to().as_text().map(|s| s.to_string());
|
||||
let references: Vec<String> = message
|
||||
.references()
|
||||
.as_text_list()
|
||||
.map(|list| list.into_iter().map(|s| s.to_string()).collect())
|
||||
.unwrap_or_default();
|
||||
|
||||
let (from_addr, from_name) = message
|
||||
.from()
|
||||
.and_then(first_address)
|
||||
.unwrap_or((None, None));
|
||||
|
||||
let to_addrs = message
|
||||
.to()
|
||||
.map(all_addresses)
|
||||
.unwrap_or_default();
|
||||
let cc_addrs = message
|
||||
.cc()
|
||||
.map(all_addresses)
|
||||
.unwrap_or_default();
|
||||
|
||||
let subject = message.subject().map(|s| s.to_string());
|
||||
let sent_at: Option<DateTime<Utc>> = message
|
||||
.date()
|
||||
.and_then(|d| DateTime::parse_from_rfc3339(&d.to_rfc3339()).ok())
|
||||
.map(|d| d.with_timezone(&Utc));
|
||||
|
||||
let text_body = message.body_text(0).map(|s| s.to_string());
|
||||
let html_body = message.body_html(0).map(|s| s.to_string());
|
||||
|
||||
let attachments = message
|
||||
.attachments()
|
||||
.map(|a| ParsedAttachment {
|
||||
filename: a.attachment_name().map(|s| s.to_string()),
|
||||
content_type: a.content_type().map(|ct| ct.ctype().to_string()),
|
||||
data: a.contents().to_vec(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ParsedMessage {
|
||||
message_id,
|
||||
in_reply_to,
|
||||
references,
|
||||
from_addr,
|
||||
from_name,
|
||||
to_addrs,
|
||||
cc_addrs,
|
||||
subject,
|
||||
sent_at,
|
||||
text_body,
|
||||
html_body,
|
||||
attachments,
|
||||
raw: raw.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn first_address(addr: &Address) -> Option<(Option<String>, Option<String>)> {
|
||||
addr.first().map(|a| {
|
||||
(
|
||||
a.address().map(|s| s.to_string()),
|
||||
a.name().map(|s| s.to_string()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn all_addresses(addr: &Address) -> Vec<String> {
|
||||
addr.iter()
|
||||
.filter_map(|a| a.address().map(|s| s.to_string()))
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod api;
|
||||
pub mod auth;
|
||||
pub mod config;
|
||||
pub mod crypto;
|
||||
pub mod db;
|
||||
pub mod error;
|
||||
pub mod imap_sync;
|
||||
pub mod models;
|
||||
pub mod storage;
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
use tern_server::api::{self, AppState};
|
||||
use tern_server::config::Config;
|
||||
use tern_server::crypto::CredentialCipher;
|
||||
use tern_server::storage::BlobStore;
|
||||
use tern_server::{db, imap_sync};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let _ = dotenvy::dotenv();
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env().add_directive("tern_server=info".parse()?))
|
||||
.init();
|
||||
|
||||
let config = Config::from_env()?;
|
||||
tern_server::storage::ensure_dir(&config.blob_storage_dir)?;
|
||||
|
||||
let pool = db::connect(&config.database_url).await?;
|
||||
let cipher = CredentialCipher::new(&config.credential_key);
|
||||
let blobs = BlobStore::new(config.blob_storage_dir.clone());
|
||||
|
||||
// The sync manager owns one long-running task per IMAP account
|
||||
// (server-architecture-spec.md §3.1) — it runs alongside the API server.
|
||||
tokio::spawn(imap_sync::run(pool.clone(), cipher.clone(), blobs.clone()));
|
||||
|
||||
let state = AppState {
|
||||
pool,
|
||||
cipher,
|
||||
blobs,
|
||||
session_ttl_hours: config.session_ttl_hours,
|
||||
config: config.clone(),
|
||||
};
|
||||
|
||||
let app = api::build(state);
|
||||
|
||||
tracing::info!("listening on {}", config.bind_addr);
|
||||
let listener = tokio::net::TcpListener::bind(&config.bind_addr).await?;
|
||||
axum::serve(listener, app).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct Account {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub name: String,
|
||||
pub provider_type: String,
|
||||
pub imap_host: String,
|
||||
pub imap_port: i32,
|
||||
pub imap_use_tls: bool,
|
||||
pub smtp_host: String,
|
||||
pub smtp_port: i32,
|
||||
pub smtp_use_starttls: bool,
|
||||
pub username: String,
|
||||
pub encrypted_password: Vec<u8>,
|
||||
pub password_nonce: Vec<u8>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// What the API actually returns — never the encrypted credential blob.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct AccountPublic {
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub provider_type: String,
|
||||
pub imap_host: String,
|
||||
pub imap_port: i32,
|
||||
pub smtp_host: String,
|
||||
pub smtp_port: i32,
|
||||
pub username: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl From<Account> for AccountPublic {
|
||||
fn from(a: Account) -> Self {
|
||||
Self {
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
provider_type: a.provider_type,
|
||||
imap_host: a.imap_host,
|
||||
imap_port: a.imap_port,
|
||||
smtp_host: a.smtp_host,
|
||||
smtp_port: a.smtp_port,
|
||||
username: a.username,
|
||||
created_at: a.created_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||
pub struct SyncState {
|
||||
pub account_id: Uuid,
|
||||
pub uidvalidity: Option<i64>,
|
||||
pub last_synced_uid: i64,
|
||||
pub status: String,
|
||||
pub last_error: Option<String>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
|
||||
pub struct Folder {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub name: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
|
||||
pub struct Message {
|
||||
pub id: Uuid,
|
||||
pub account_id: Uuid,
|
||||
pub folder_id: Option<Uuid>,
|
||||
pub uid: i64,
|
||||
pub message_id: Option<String>,
|
||||
pub in_reply_to: Option<String>,
|
||||
pub references_: Vec<String>,
|
||||
pub thread_id: Uuid,
|
||||
pub from_addr: Option<String>,
|
||||
pub from_name: Option<String>,
|
||||
pub to_addrs: Vec<String>,
|
||||
pub cc_addrs: Vec<String>,
|
||||
pub subject: Option<String>,
|
||||
pub sent_at: Option<DateTime<Utc>>,
|
||||
pub flags: Vec<String>,
|
||||
pub spam_score: Option<f32>,
|
||||
pub body_fetched: bool,
|
||||
pub raw_blob_ref: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
|
||||
pub struct Body {
|
||||
pub message_id: Uuid,
|
||||
pub text_body: Option<String>,
|
||||
pub html_body: Option<String>,
|
||||
}
|
||||
|
||||
/// Fields extracted from a raw MIME message, ready to insert (imap_sync::parse).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParsedMessage {
|
||||
pub message_id: Option<String>,
|
||||
pub in_reply_to: Option<String>,
|
||||
pub references: Vec<String>,
|
||||
pub from_addr: Option<String>,
|
||||
pub from_name: Option<String>,
|
||||
pub to_addrs: Vec<String>,
|
||||
pub cc_addrs: Vec<String>,
|
||||
pub subject: Option<String>,
|
||||
pub sent_at: Option<DateTime<Utc>>,
|
||||
pub text_body: Option<String>,
|
||||
pub html_body: Option<String>,
|
||||
pub attachments: Vec<ParsedAttachment>,
|
||||
pub raw: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParsedAttachment {
|
||||
pub filename: Option<String>,
|
||||
pub content_type: Option<String>,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod account;
|
||||
pub mod folder;
|
||||
pub mod message;
|
||||
pub mod user;
|
||||
|
||||
pub use account::Account;
|
||||
pub use folder::Folder;
|
||||
pub use message::{Body, Message};
|
||||
pub use user::User;
|
||||
@@ -0,0 +1,12 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
#[serde(skip_serializing)]
|
||||
pub password_hash: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Filesystem, content-hash-addressed blob storage for raw MIME messages and
|
||||
//! attachments (server-architecture-spec.md §3.2). Kept content-hash-addressed
|
||||
//! from day one so a future swap to S3-compatible storage (§11) is a
|
||||
//! backend change, not a data-model change.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BlobStore {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
impl BlobStore {
|
||||
pub fn new(root: PathBuf) -> Self {
|
||||
Self { root }
|
||||
}
|
||||
|
||||
pub fn hash(data: &[u8]) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(data);
|
||||
hex::encode(hasher.finalize())
|
||||
}
|
||||
|
||||
fn path_for_hash(&self, hash: &str) -> PathBuf {
|
||||
// shard by the first 2 hex chars to avoid one giant flat directory
|
||||
self.root.join(&hash[0..2]).join(hash)
|
||||
}
|
||||
|
||||
/// Writes `data` under its content hash if not already present. Returns
|
||||
/// the hash and the path it was stored at (relative to `root`, so the
|
||||
/// stored `blob_ref` doesn't embed an absolute deployment path).
|
||||
pub async fn put(&self, data: &[u8]) -> Result<(String, String)> {
|
||||
let hash = Self::hash(data);
|
||||
let full_path = self.path_for_hash(&hash);
|
||||
|
||||
if !tokio::fs::try_exists(&full_path).await.unwrap_or(false) {
|
||||
if let Some(parent) = full_path.parent() {
|
||||
tokio::fs::create_dir_all(parent)
|
||||
.await
|
||||
.with_context(|| format!("creating blob directory {}", parent.display()))?;
|
||||
}
|
||||
tokio::fs::write(&full_path, data)
|
||||
.await
|
||||
.with_context(|| format!("writing blob {}", full_path.display()))?;
|
||||
}
|
||||
|
||||
let rel_ref = format!("{}/{}", &hash[0..2], hash);
|
||||
Ok((hash, rel_ref))
|
||||
}
|
||||
|
||||
pub async fn read(&self, blob_ref: &str) -> Result<Vec<u8>> {
|
||||
let path = self.resolve(blob_ref);
|
||||
tokio::fs::read(&path)
|
||||
.await
|
||||
.with_context(|| format!("reading blob {}", path.display()))
|
||||
}
|
||||
|
||||
pub fn resolve(&self, blob_ref: &str) -> PathBuf {
|
||||
self.root.join(blob_ref)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure_dir(path: &Path) -> Result<()> {
|
||||
std::fs::create_dir_all(path).with_context(|| format!("creating directory {}", path.display()))
|
||||
}
|
||||
Reference in new issue
Block a user