9 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 56e2c89999 Allow editing an account
CI / test (push) Failing after 3m23s
PUT /api/accounts/:id replaces an account's settings; the password is
kept unless a new one is given. Accounts now have an updated_at, and
the sync manager restarts a task whose account changed since it
started — the task holds its own copy of the settings. Its status is
reset to pending so the old error doesn't linger.

Mail already synced stays when it's still the same mailbox (new
password, renamed host); a genuinely different mailbox shows up as a
UIDVALIDITY change on connect and re-syncs, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 14:11:10 +02:00
Mateusz PstruchaandClaude Opus 5.5 e5cba55989 Store HTML bodies only for real text/html parts
CI / test (push) Successful in 6m22s
mail-parser's body_html() synthesises HTML from a plain-text body when a
message has no HTML part, so every plain-text mail was stored — and shown
by both clients — as HTML. Only a genuine text/html part is kept now.
Bodies stored before this that may be affected are flagged by migration
0011 and re-parsed from their raw message once at startup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:03:00 +02:00
Mateusz PstruchaandClaude Opus 5.5 b718bc4c3a Add UnifiedPush delivery, device API and sliding sessions
CI / test (push) Successful in 6m31s
New mail whose notify decision is true now wakes the user's registered
phones: a content-free {"kind":"sync"} payload, encrypted per RFC 8291
and VAPID-signed per RFC 8292 (key generated on first start, stored
encrypted with CREDENTIAL_KEY). Bursts coalesce into one push, and a
404/410 from the push server removes the device.

/api/devices registers, updates, lists and removes endpoints, and can
send a test push; GET /api/push returns the VAPID public key. For
self-hosted push servers, PUSH_URL_REWRITE maps the public endpoint
prefix to an internal one, and PUSH_CA_CERT / PUSH_TLS_INSECURE handle
private certificates.

Sessions now slide: each use extends expiry to the full TTL (at most
one write an hour), so a phone in regular use is never signed out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 19:46:33 +02:00
Mateusz PstruchaandClaude Opus 5.5 90fc65dbf5 Add live change notifications and notify/don't-notify rules
Every change is appended to an events table and broadcast to open
WebSockets (GET /api/ws); GET /api/events?since= reads the same log as
the polling fallback and delta endpoint, so clients can switch
transports without losing their place. Inserts are serialised so ids
are ordered by commit, cursors older than the 7-day retention reset,
and the socket authenticates in-band since browsers can't set headers.

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 18:55:34 +02:00
Mateusz PstruchaandClaude Opus 5.5 e2bee05b30 Add spam scoring and Junk; fix IDLE race and thread paging
CI / test (push) Successful in 4m8s
Spam (§3.5, phase 6): each message's score is extracted at ingest from
whichever filter header it carries — PMG's folded X-SPAM-LEVEL
"Spam detection results: N", X-Spam-Score, X-Spam-Status score=N, or
SpamAssassin's X-Spam-Level star bar. PMG and SpamAssassin use that same
header name for different formats, so each format is matched explicitly
rather than taking the first number. No spam header means "unknown", not
0; a spam-score rule condition treats it as neither over nor under a
threshold. A Junk system folder and `junk` action join Archive; run-now
re-parses stored mail that predates score extraction.

Fix: mail announced during a fetch could wait for the next IDLE renewal.
A server announces new mail once, as an untagged EXISTS on whatever
response is in flight; async-imap files those in a side channel rather
than waking IDLE, and the server never repeats them. Measured with
bursts separated by quiet gaps: 4 of 12 bursts left a message stuck for
the whole gap before, 0 of 12 (worst 0.2s) after. The loop now drains
that channel once IDLE has started. IDLE renewal drops from 25 to 10
minutes, doubling as the spec's safety-net poll (§3.1).

Fix: thread paging and sorting could hide mail.
- The cursor was a bare timestamp compared with `<`; Date headers have
  one-second resolution, so threads tied with a page's last row were
  skipped. It's now a keyset of (sort time, thread id).
- With no cursor the query defaulted to before=now(), so future-dated
  mail never appeared; undated mail had a NULL sort key and never
  appeared either. The sort key is now LEAST(COALESCE(sent_at,
  created_at), created_at): the Date header, clamped to arrival time.
- next_cursor is null on the last page.
Verified: 121 inbox threads walked in pages of 17 with no gaps or
duplicates; future-dated and undated mail visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 15:32:35 +02:00
Mateusz PstruchaandClaude Opus 5.5 3f1d9227c6 Add trash retention, stop-after-match and run-now
CI / test (push) Successful in 46s
Mail in Trash is purged after TRASH_RETENTION_DAYS (default 30, 0
disables), hourly. Stored files are content-addressed and shared, so a
file is only removed once nothing references it — and not if written or
reused in the last hour, since ingest writes a file before inserting the
row that points at it. Reusing an existing blob now refreshes its mtime
so that grace period protects it too. Trash rows report when they purge.

"Stop processing further rules" moves from an action to a per-rule
option (stop_after_match): it's a property of the rule, not something
done to a message. Migration 0007 converts existing stop actions, and a
stop submitted as an action is now rejected.

Rules can be run now against existing mail outside Trash, disabled ones
included so a rule can be tried before it's switched on. It pages by
key, one transaction per page, and only re-reads stored raw messages
when the rule tests a header.

All JSON bodies now go through an AppJson extractor so malformed or
mistyped bodies return the API's {"error": …} shape. Axum's default was
a plain-text 422 the webapp could only show as "request failed: 422" —
losing the useful part, e.g. "unknown variant `stop`".

Verified live: the stop flag blocks a lower rule on arriving mail; run
now on a disabled header rule archived 2 of 4 messages; a purge removed
an expired message and its unique raw file while keeping an attachment
file still shared with a live copy, with no orphaned rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:00:04 +02:00
Mateusz PstruchaandClaude Opus 5.5 807775726c Add threading, tags, rules and thread actions
CI / test (push) Successful in 3m3s
Threading (§3.6) is an incremental, database-backed JWZ: each message
links to its ancestors, to replies that arrived before it, and to
siblings sharing a missing ancestor (what JWZ's placeholder containers
do), merging every thread it touches into the one holding the oldest
message. Subject-only grouping applies only to Re:/Fwd: messages with no
reference headers, so lists that strip References still thread while
unrelated mail sharing a generic subject never merges. Existing mail is
re-threaded once per account via a versioned backfill.

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:19:35 +02:00
Mateusz PstruchaandClaude Opus 5.5 fd8ee8311c Add sending: outbox queue, SMTP worker, drafts
CI / test (push) Successful in 2m28s
Drafts and queued sends are one outbox row in different states, drained
by a background worker so SMTP never runs in the request path (§3.3).
Retries back off 1-16 min; 5xx, auth and TLS failures fail fast; items
a crashed worker left mid-send are reclaimed. Each message keeps its
Message-ID across retries, so an at-least-once duplicate is recognisable.
Reply headers are derived server-side from the parent, and sent mail is
filed into its thread alongside received mail.

Three things the libraries would have got wrong:
- mail-builder's .bcc() writes an ordinary Bcc header every recipient
  sees. Bcc goes in the envelope only; a test checks it never reaches the
  rendered bytes, and was confirmed to fail if .bcc() is reintroduced.
- mail-send trusts only compiled-in public CAs, while IMAP (native-tls)
  uses the OS store — a server with an internal-CA cert would sync but
  never send. SMTP now uses the OS store too.
- rustls is added with default-features off: its defaults pull in
  aws-lc-rs, which needs cmake/clang and would break the runner build.

Also fixes: UIDVALIDITY resets now only delete IMAP-sourced rows (sent
mail shares the table and exists nowhere else); first sync no longer
logs a false "UIDVALIDITY changed" warning; Message-IDs are stored bare
whichever path writes them (ENVELOPE brackets them, mail-parser doesn't);
accounts can choose STARTTLS vs implicit TLS for SMTP, defaulting by port.

Verified end to end against a TLS mail server with a private-CA cert,
with no plaintext patching: IMAPS sync, SMTPS send, delivery and headers
checked from the recipients' mailboxes, Bcc absent from other copies,
plaintext refused when STARTTLS is unavailable, retry scheduling on
connection failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 10:59:28 +02:00
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