21 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 08c2b1b286 Bump to 0.8.5
CI / test (push) Successful in 4m20s
Release / image (push) Successful in 3m26s
Release account editing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:55:22 +01:00
Mateusz PstruchaandClaude Opus 5.5 53d7e2a612 Ignore local Claude and tooling files
CI / test (push) Successful in 4m28s
CLAUDE.md, scripts/ and .claude/ are per-machine coordination and
tooling files; they stay untracked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:50:09 +01:00
mtps b93c50b8ac Merge pull request 'Release builds the image only, ygg/deployments deploys it' (#1) from claude/release-image-only into master
CI / test (push) Successful in 50s
2026-11-09 18:58:59 +01:00
Mateusz PstruchaandClaude Opus 5.5 30a8d52500 Release builds the image only, ygg/deployments deploys it
CI / test (pull_request) Successful in 4m13s
Production now runs from ygg/deployments, so a deploy from here would write
over it. Renovate opens a PR there for the new version, and merging it deploys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:37:24 +01:00
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 3614dffa1a Bump to 0.8.4
Release / image (push) Successful in 2m49s
CI / test (push) Successful in 4m48s
Release / deploy (push) Successful in 36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:53:50 +02:00
Mateusz PstruchaandClaude Opus 5.5 dfd446617b Report account sync status; stop syncing removed accounts
CI / test (push) Successful in 4m22s
GET /api/accounts now includes each account's sync status, last error,
when it last changed, whether the first pass finished and how many
messages it has — what an accounts screen needs to show whether a
mailbox is working. The stored error now carries its cause chain
("…failed to lookup address information…", not just "TCP connect to
IMAP host failed").

Removing an account used to leave its sync task retrying forever
against rows that no longer exist; the manager now aborts tasks for
accounts that are gone. It's also woken when accounts are added or
removed, so a new mailbox starts syncing immediately instead of at the
next 30-second poll.

Creating an account now rejects blank hosts/login/password and
out-of-range ports up front, and removing a nonexistent one is a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:48:57 +02:00
Mateusz PstruchaandClaude Opus 5.5 740b43c74b Bump to 0.8.3
Release / image (push) Successful in 2m38s
CI / test (push) Successful in 4m24s
Release / deploy (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:12:30 +02:00
Mateusz PstruchaandClaude Opus 5.5 0f497d88de Deploy tern-server on its own; accept hex keys; fix cross-origin auth
CI / test (push) Successful in 3m56s
The integrated stack is gone: deploy/compose.yml is just the server and
its Postgres, published on 11901 behind the existing nginx as
tern-api.mtps.pl, and this repo's release deploys it after pushing the
image. The webapp deploys separately from tern-web.

CREDENTIAL_KEY may now be 64 hex digits as well as base64, and a wrong
length says how to generate a right one. The database password reaches
the server as PGPASSWORD rather than inside DATABASE_URL, so it needs
no URL-escaping.

CORS now names Authorization and Content-Type instead of `*`: browsers
don't let the wildcard cover Authorization, so every signed-in request
from the webapp's own origin would have been refused. A route test
checks the preflight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 12:44:22 +02:00
Mateusz PstruchaandClaude Opus 5.5 84ee932c27 Bump to 0.8.2
Release / image (push) Successful in 3m0s
CI / test (push) Successful in 3m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:24:02 +02:00
Mateusz PstruchaandClaude Opus 5.5 77f21a4734 Fix the release workflow failing to parse; check workflows in CI
CI / test (push) Successful in 3m26s
The "Show image" step's run line was a plain YAML scalar containing
": ", which Gitea's parser rejects, so v0.8.1's release never ran. It's
a block scalar now, and CI parses every workflow file so a broken
release.yml fails on master before anything is tagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 21:08:35 +02:00
Mateusz PstruchaandClaude Opus 5.5 a24cf5ac3c Bump to 0.8.1
release.yml (push) Invalid workflow file
CI / test (push) Successful in 3m35s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 20:58:25 +02:00
Mateusz PstruchaandClaude Opus 5.5 22c55854f3 Add the tern.mtps.pl deployment, a registration gate and a healthcheck
CI / test (push) Successful in 4m39s
deploy/tern.yml is the whole stack as one compose project for
ygg/actions/deploy (deploy/compose on kara): Postgres, the server at the
released version, ygg/static-server serving the matching tern-web
release, and an nginx proxy putting webapp and API (incl. /api/ws) on
one origin on port 11901, with sign-in rate-limited. Kara's nginx
fronts it as tern.mtps.pl. tern-web's release triggers the deploy.

Only the first user may now register unless OPEN_REGISTRATION=true,
so a public deployment isn't open sign-up; an advisory lock keeps two
racing first registrations from both succeeding.

`tern-server healthcheck` backs a Dockerfile HEALTHCHECK, so
`docker compose up --wait` waits for the server to serve — and fails a
deploy whose server can't start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:47:32 +02:00
Mateusz PstruchaandClaude Opus 5.5 b59388065f Push the release image with the shared ygg push-image action
CI / test (push) Successful in 4m25s
Replaces the hand-written login/build/push/logout steps with
ygg/actions/push-image@v2. Tags stay the same (X.Y.Z and latest, same
image name); it adds OCI source/revision/created/version labels and
logs in through a temporary DOCKER_CONFIG, so the registry token never
touches the shared runner's ~/.docker. The job now exposes the version
and digest as outputs, ready for a deploy job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 20:10:09 +02:00
Mateusz PstruchaandClaude Opus 5.5 830bc3ab73 Bump to 0.8.0
CI / test (push) Successful in 4m36s
Release / image (push) Successful in 2m45s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 21:20:12 +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 4a2e32cc6f Bump to 0.7.0
CI / test (push) Successful in 5m13s
Release / image (push) Successful in 2m47s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 18:55:34 +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 77c1813539 Bump to 0.6.0
CI / test (push) Successful in 4m30s
Release / image (push) Successful in 3m4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 15:37:28 +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
46 changed files with 3374 additions and 224 deletions

No files matched your search

+22 -4
View File
@@ -4,16 +4,34 @@
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.
# 32 random bytes, as 64 hex digits (openssl rand -hex 32) or base64
# (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
# Sessions last this long since they were last *used* — a client in regular
# use stays signed in; one left alone for this long has to sign in again.
SESSION_TTL_HOURS=720
# Anyone may create a user. Off by default: then only the first user can
# register, which is how a new server gets its owner.
#OPEN_REGISTRATION=true
# Days mail stays in Trash before it's permanently deleted. 0 disables purging.
TRASH_RETENTION_DAYS=30
# --- UnifiedPush (Android notifications) ---
# Endpoints come from the phone's distributor (e.g. the ntfy app), so they
# carry the push server's *public* URL. If this server should reach it some
# other way, rewrite the prefix: comma-separated from=>to pairs.
#PUSH_URL_REWRITE=https://ntfy.example.org/=>http://ntfy:80/
# Trust an extra CA (PEM) for the push server, e.g. an internal CA...
#PUSH_CA_CERT=/etc/tern/push-ca.pem
# ...or, last resort, skip certificate checks for push requests entirely.
#PUSH_TLS_INSECURE=true
# Contact for push-service operators, sent in VAPID-signed requests.
#PUSH_VAPID_SUBJECT=mailto:you@example.org
RUST_LOG=tern_server=debug,tower_http=debug
+12
View File
@@ -19,6 +19,18 @@ jobs:
- name: Check out source
uses: actions/checkout@v4
# Gitea rejects a workflow file it can't parse without running
# anything, which for release.yml only shows up when a tag is pushed.
# Parsing them all here catches that on master, before tagging.
- name: Check workflow files parse
run: |
python3 - <<'PY'
import glob, yaml
for f in sorted(glob.glob(".gitea/workflows/*.yml")):
yaml.safe_load(open(f))
print("ok", f)
PY
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
with:
+17 -33
View File
@@ -1,5 +1,7 @@
name: Release
# Builds and pushes the image. Production runs from ygg/deployments: Renovate
# opens a PR there for the new version, and merging it deploys.
on:
push:
tags: ['v*']
@@ -11,38 +13,20 @@ jobs:
- name: Check out source
uses: actions/checkout@v4
- name: Derive registry and version
id: meta
run: |
# gitea.server_url is the web root, e.g. https://git.app.ygg — the
# container registry lives on that same host, so there's no
# hostname to hardcode or keep in sync.
REGISTRY="$(echo '${{ gitea.server_url }}' | sed -E 's#^https?://##')"
VERSION="${GITHUB_REF_NAME#v}"
echo "registry=$REGISTRY" >> "$GITHUB_OUTPUT"
echo "image=$REGISTRY/${{ gitea.repository }}" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Log in to container registry
run: |
echo '${{ secrets.REGISTRY_TOKEN }}' \
| docker login '${{ steps.meta.outputs.registry }}' \
-u '${{ gitea.actor }}' --password-stdin
# The shared ygg action builds ./Dockerfile as
# git.app.ygg/mtps/tern-server, tagged with the version (v stripped)
# and latest, with OCI source/revision/created/version labels. It logs
# in through a temporary DOCKER_CONFIG, so the token never lands in the
# runner's ~/.docker, and builds with --progress=plain.
- name: Build and push image
env:
DOCKER_BUILDKIT: '1'
run: |
IMAGE='${{ steps.meta.outputs.image }}'
VERSION='${{ steps.meta.outputs.version }}'
# --progress=plain: without it BuildKit renders an animated TTY
# progress display, repainting every step on each frame. In a log
# file that became ~15k lines of cursor-movement escapes for a
# build that only has a few hundred lines of real output.
docker build --progress=plain -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
docker push "$IMAGE:$VERSION"
docker push "$IMAGE:latest"
id: image
uses: https://git.app.ygg/ygg/actions/push-image@v2
with:
registry-token: ${{ secrets.REGISTRY_TOKEN }}
- name: Log out
if: always()
run: docker logout '${{ steps.meta.outputs.registry }}' || true
- name: Show image
env:
TAGS: ${{ steps.image.outputs.tags }}
DIGEST: ${{ steps.image.outputs.digest }}
run: |
printf 'tags: %s\ndigest: %s\n' "$TAGS" "$DIGEST"
+5
View File
@@ -3,3 +3,8 @@
/data
*.log
.DS_Store
# Local coordination and tooling files, kept out of the repo
/CLAUDE.md
/scripts/
/.claude/
Generated
+470 -21
View File
@@ -26,7 +26,21 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"cpufeatures 0.2.17",
]
[[package]]
name = "aes-gcm"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1"
dependencies = [
"aead",
"aes",
"cipher",
"ctr",
"ghash",
"subtle",
]
[[package]]
@@ -89,7 +103,7 @@ checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
dependencies = [
"base64ct",
"blake2",
"cpufeatures",
"cpufeatures 0.2.17",
"password-hash",
]
@@ -204,6 +218,7 @@ dependencies = [
"async-trait",
"axum-core",
"axum-macros",
"base64 0.22.1",
"bytes",
"futures-util",
"http",
@@ -222,8 +237,10 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sha1",
"sync_wrapper",
"tokio",
"tokio-tungstenite",
"tower",
"tower-layer",
"tower-service",
@@ -262,6 +279,12 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "base16ct"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
[[package]]
name = "base64"
version = "0.21.7"
@@ -362,6 +385,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "chacha20"
version = "0.9.1"
@@ -370,7 +399,18 @@ checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"cpufeatures 0.2.17",
]
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures 0.3.1",
"rand_core 0.10.1",
]
[[package]]
@@ -380,7 +420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
dependencies = [
"aead",
"chacha20",
"chacha20 0.9.1",
"cipher",
"poly1305",
"zeroize",
@@ -479,6 +519,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "3.4.0"
@@ -518,6 +567,18 @@ version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "crypto-bigint"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
dependencies = [
"generic-array",
"rand_core 0.6.4",
"subtle",
"zeroize",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -525,10 +586,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"rand_core",
"rand_core 0.6.4",
"typenum",
]
[[package]]
name = "ctr"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
dependencies = [
"cipher",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
@@ -598,6 +668,20 @@ version = "0.15.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
[[package]]
name = "ecdsa"
version = "0.16.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [
"der",
"digest",
"elliptic-curve",
"rfc6979",
"signature",
"spki",
]
[[package]]
name = "either"
version = "1.18.0"
@@ -607,6 +691,27 @@ dependencies = [
"serde",
]
[[package]]
name = "elliptic-curve"
version = "0.13.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
dependencies = [
"base16ct",
"crypto-bigint",
"digest",
"ff",
"generic-array",
"group",
"hkdf",
"pem-rfc7468",
"pkcs8",
"rand_core 0.6.4",
"sec1",
"subtle",
"zeroize",
]
[[package]]
name = "encoding_rs"
version = "0.8.41"
@@ -693,6 +798,16 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "ff"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
dependencies = [
"rand_core 0.6.4",
"subtle",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.13"
@@ -858,6 +973,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
"zeroize",
]
[[package]]
@@ -877,8 +993,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
@@ -902,8 +1020,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi 6.0.0",
"rand_core 0.10.1",
"wasm-bindgen",
]
[[package]]
name = "ghash"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1"
dependencies = [
"opaque-debug",
"polyval",
]
[[package]]
name = "group"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
dependencies = [
"ff",
"rand_core 0.6.4",
"subtle",
]
[[package]]
@@ -972,7 +1114,7 @@ dependencies = [
"idna",
"ipnet",
"once_cell",
"rand",
"rand 0.8.8",
"ring",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
@@ -997,7 +1139,7 @@ dependencies = [
"lru-cache",
"once_cell",
"parking_lot",
"rand",
"rand 0.8.8",
"resolv-conf",
"rustls 0.21.12",
"smallvec",
@@ -1097,6 +1239,23 @@ dependencies = [
"pin-project-lite",
"smallvec",
"tokio",
"want",
]
[[package]]
name = "hyper-rustls"
version = "0.27.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
dependencies = [
"http",
"hyper",
"hyper-util",
"rustls 0.23.45",
"rustls-native-certs",
"tokio",
"tokio-rustls 0.26.5",
"tower-service",
]
[[package]]
@@ -1105,13 +1264,21 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64 0.22.1",
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"hyper",
"ipnet",
"libc",
"percent-encoding",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
]
[[package]]
@@ -1401,6 +1568,12 @@ dependencies = [
"linked-hash-map",
]
[[package]]
name = "lru-slab"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "lzma-rs"
version = "0.3.0"
@@ -1481,7 +1654,7 @@ dependencies = [
"mail-auth",
"mail-builder",
"md5",
"rand",
"rand 0.8.8",
"rustls 0.23.45",
"rustls-pki-types",
"smtp-proto",
@@ -1634,7 +1807,7 @@ dependencies = [
"num-integer",
"num-iter",
"num-traits",
"rand",
"rand 0.8.8",
"smallvec",
"zeroize",
]
@@ -1729,6 +1902,18 @@ dependencies = [
"vcpkg",
]
[[package]]
name = "p256"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
dependencies = [
"ecdsa",
"elliptic-curve",
"primeorder",
"sha2",
]
[[package]]
name = "parking"
version = "2.2.1"
@@ -1765,7 +1950,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core",
"rand_core 0.6.4",
"subtle",
]
@@ -1865,7 +2050,19 @@ version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
dependencies = [
"cpufeatures",
"cpufeatures 0.2.17",
"opaque-debug",
"universal-hash",
]
[[package]]
name = "polyval"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"opaque-debug",
"universal-hash",
]
@@ -1894,6 +2091,15 @@ dependencies = [
"zerocopy",
]
[[package]]
name = "primeorder"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
dependencies = [
"elliptic-curve",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -1912,6 +2118,62 @@ dependencies = [
"memchr",
]
[[package]]
name = "quinn"
version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
"bytes",
"cfg_aliases",
"pin-project-lite",
"quinn-proto",
"quinn-udp",
"rustc-hash",
"rustls 0.23.45",
"socket2",
"thiserror 2.0.20",
"tokio",
"tracing",
"web-time",
]
[[package]]
name = "quinn-proto"
version = "0.11.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"
dependencies = [
"bytes",
"getrandom 0.4.3",
"lru-slab",
"rand 0.10.3",
"rand_pcg",
"ring",
"rustc-hash",
"rustls 0.23.45",
"rustls-pki-types",
"slab",
"thiserror 2.0.20",
"tinyvec",
"tracing",
"web-time",
]
[[package]]
name = "quinn-udp"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
]
[[package]]
name = "quote"
version = "1.0.47"
@@ -1941,7 +2203,18 @@ checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20 0.10.2",
"getrandom 0.4.3",
"rand_core 0.10.1",
]
[[package]]
@@ -1951,7 +2224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -1963,6 +2236,21 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_pcg"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -2010,12 +2298,60 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "reqwest"
version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"js-sys",
"log",
"percent-encoding",
"pin-project-lite",
"quinn",
"rustls 0.23.45",
"rustls-native-certs",
"rustls-pki-types",
"serde",
"serde_json",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tokio-rustls 0.26.5",
"tower",
"tower-http",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
name = "resolv-conf"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
[[package]]
name = "rfc6979"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
dependencies = [
"hmac",
"subtle",
]
[[package]]
name = "ring"
version = "0.17.14"
@@ -2043,13 +2379,19 @@ dependencies = [
"num-traits",
"pkcs1",
"pkcs8",
"rand_core",
"rand_core 0.6.4",
"signature",
"spki",
"subtle",
"zeroize",
]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustix"
version = "1.1.5"
@@ -2125,6 +2467,7 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"web-time",
"zeroize",
]
@@ -2186,6 +2529,20 @@ dependencies = [
"untrusted",
]
[[package]]
name = "sec1"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
dependencies = [
"base16ct",
"der",
"generic-array",
"pkcs8",
"subtle",
"zeroize",
]
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -2288,7 +2645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -2299,7 +2656,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -2335,7 +2692,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -2519,7 +2876,7 @@ dependencies = [
"memchr",
"once_cell",
"percent-encoding",
"rand",
"rand 0.8.8",
"rsa",
"serde",
"sha1",
@@ -2559,7 +2916,7 @@ dependencies = [
"md-5",
"memchr",
"once_cell",
"rand",
"rand 0.8.8",
"serde",
"serde_json",
"sha2",
@@ -2660,6 +3017,9 @@ name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
dependencies = [
"futures-core",
]
[[package]]
name = "synstructure"
@@ -2687,10 +3047,12 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.5.0"
version = "0.8.5"
dependencies = [
"aes-gcm",
"anyhow",
"argon2",
"async-channel 2.5.0",
"async-imap",
"async-native-tls",
"axum",
@@ -2700,10 +3062,13 @@ dependencies = [
"dotenvy",
"futures",
"hex",
"hkdf",
"mail-parser 0.11.9",
"mail-send",
"rand",
"p256",
"rand 0.8.8",
"regex",
"reqwest",
"rustls 0.23.45",
"rustls-native-certs",
"serde",
@@ -2876,6 +3241,18 @@ dependencies = [
"tokio-stream",
]
[[package]]
name = "tokio-tungstenite"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
]
[[package]]
name = "tower"
version = "0.5.3"
@@ -2900,12 +3277,15 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags",
"bytes",
"futures-util",
"http",
"http-body",
"pin-project-lite",
"tower",
"tower-layer",
"tower-service",
"tracing",
"url",
]
[[package]]
@@ -2982,6 +3362,30 @@ dependencies = [
"tracing-log",
]
[[package]]
name = "try-lock"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a"
dependencies = [
"byteorder",
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand 0.8.8",
"sha1",
"thiserror 1.0.69",
"utf-8",
]
[[package]]
name = "typenum"
version = "1.20.1"
@@ -3043,6 +3447,12 @@ dependencies = [
"serde",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -3079,6 +3489,15 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "want"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
dependencies = [
"try-lock",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -3113,6 +3532,16 @@ dependencies = [
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.128"
@@ -3145,6 +3574,26 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
+11 -2
View File
@@ -1,18 +1,19 @@
[package]
name = "tern-server"
version = "0.5.0"
version = "0.8.5"
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"] }
axum = { version = "0.7", features = ["macros", "ws"] }
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-channel = "2" # same major as async-imap uses, for its unsolicited-response channel
async-native-tls = { version = "0.6", default-features = false, features = ["runtime-tokio"] }
mail-parser = "0.11"
mail-send = "0.4"
@@ -24,6 +25,14 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std"
tokio-rustls = { version = "0.26", default-features = false }
rustls-native-certs = "0.8"
regex = "1"
# Web Push (RFC 8291 encryption, RFC 8292 VAPID) for UnifiedPush — pure
# RustCrypto, no OpenSSL.
p256 = { version = "0.13", features = ["ecdh", "ecdsa"] }
hkdf = "0.12"
aes-gcm = "0.10"
# Push delivery. rustls-tls-native-roots selects ring (like rustls above),
# not aws-lc, and trusts the OS store.
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+3
View File
@@ -11,4 +11,7 @@ WORKDIR /app
COPY --from=builder /build/target/release/tern-server ./tern-server
COPY migrations ./migrations
EXPOSE 8080
# Healthy once the server answers /healthz (after migrations, on its port).
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=5 \
CMD ["./tern-server", "healthcheck"]
CMD ["./tern-server"]
+80 -7
View File
@@ -2,17 +2,20 @@
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–5)
## What's built (build-order phases 1–8)
- **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.
- **Minimal REST API** (`src/api/`): local username/password auth (Argon2 + bearer session tokens), account management (IMAP credentials encrypted at rest with ChaCha20-Poly1305), folder listing, cursor-paginated message listing, single-message + thread-by-id fetch.
- **Thread-grouped listing** (`GET /api/threads`): one row per conversation, which is how both clients render the inbox. Grouped server-side because a thread's messages are spread through the flat list by date, so a client grouping page-by-page would split threads across page boundaries and miscount unread.
- **Sending** (`src/smtp/`, `/api/outbox`): drafts and a send queue, drained by a background worker — never in the request path (§3.3). Retries with backoff (1, 2, 4, 8, 16 min), fails fast on 5xx replies and auth or TLS errors, and reclaims messages a crashed worker left mid-send. Replies get In-Reply-To/References derived server-side from the parent message. Sent mail is filed into its thread alongside received mail.
- **Mark read** (`POST /api/threads/:id/read`) — local state only; see below.
- **Threading** (`src/threading.rs`, §3.6) — an incremental, database-backed JWZ. Each message links to its ancestors, to replies that arrived before it, and to siblings sharing a *missing* ancestor (what JWZ's placeholder containers do), merging every thread it touches into the one holding the oldest message. Subject-only grouping applies only to `Re:`/`Fwd:` messages with no reference headers — lists that strip References still thread, while unrelated mail sharing a generic subject never merges. Existing mail is re-threaded once per account via a versioned backfill (`THREADING_VERSION`).
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|trash|folder|tag`. A thread appears in a view if any of its messages does, but the row summarises the whole conversation, so a reply to an archived thread brings it back to the inbox. Archive is a system folder found by role, so it can be renamed.
- **Spam filtering** (`src/spam.rs`, §3.5) — every message's spam score is extracted at ingest from whichever filter header it carries, and a *spam score* rule condition compares it numerically. The webapp's **Add spam filter** creates the spec's threshold rule — score over 5 → Junk, placed first, stopping later rules — as an ordinary rule you can edit. Junk is a system folder like Archive.
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|junk|trash|folder|tag`, paged by an opaque keyset cursor. A thread appears in a view if any of its messages does, but the row summarises the whole conversation, so a reply to an archived thread brings it back to the inbox. Archive is a system folder found by role, so it can be renamed.
- **Rules** (`src/rules.rs`, `/api/rules`, §3.5) — structured JSON: one level of all/any tests (from, to, cc, recipients, subject, body, any header; contains, is, regex, exists, greater/less than) and an action list (tag, move, archive, mark read, delete). Run on new mail after its body is fetched; every matching rule applies in priority order, until one marked *stop after match*. Any rule can also be **run now** against existing mail (`POST /api/rules/:id/run`) — disabled ones too, so a rule can be tried before it's switched on. Manual thread actions (`POST /api/threads/:id/actions`) use the same action format and code.
- **UnifiedPush** (`src/push/`, `/api/devices`, §3.8) — the server is the UnifiedPush application server for Android: phones register their distributor's endpoint and Web Push keys, and new mail that should notify triggers a content-free, encrypted "sync now" push. See [Push notifications](#push-notifications-android).
- **Change notifications** (`src/events.rs`, `/api/ws`, `/api/events`, §3.8) — every change is appended to an event log and pushed to open WebSockets; the same log serves the polling fallback, so a client switches between the two without losing its place. See [Notifications](#notifications).
## How rules behave
@@ -21,7 +24,24 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **Numeric comparisons read the first number in a value**, so both `X-Spam-Score: 5.3` and `X-Spam-Status: Yes, score=5.3` work — ready for phase 6's PMG headers.
- **Run now** covers everything outside Trash, including mail already filed away, and skips sent mail (rules are for incoming mail). Stored raw messages are only re-read when the rule tests a header, so body/subject/sender rules stay a fast database scan.
- **Rules see a message a moment after it appears.** Headers sync first so new mail shows quickly; rules need the full headers and body, so they run once the body arrives, seconds later.
- **No notify/don't-notify action yet** — it arrives with the notification work in phases 7–8.
- **Notify / don't notify.** New mail notifies if it's unread and still in the inbox after rules run. A *don't notify* action silences a message that would; *notify* alerts for one a rule filed away. If several matching rules say different things, the last one applied wins. Both are rule-only, and do nothing when a rule is run on existing mail.
## Spam scores
Proxmox Mail Gateway runs SpamAssassin, and header names are configurable, so the extractor recognises each format seen in practice rather than one fixed header — in order of precision:
| Header | Example | Read as |
|---|---|---|
| `X-SPAM-LEVEL` (PMG) | `Spam detection results: 8` followed by per-rule scores, folded over several lines | the total, 8 |
| `X-Spam-Score` | `5.3` | 5.3 |
| `X-Spam-Status` | `Yes, score=7.2 required=5.0 …` | 7.2 |
| `X-Spam-Level` (SpamAssassin) | `*******` | 7 (one per star) |
The first and last rows are the same header name — PMG and SpamAssassin use it for completely different formats — which is why each format is matched explicitly rather than taking "the first number in the header".
**PMG only adds its header from spam level 3 by default**, so mail below that has no score at all. That's stored as "unknown", not 0, and a rule treats it as neither over nor under any threshold. Thresholds of 3 and above work as expected; to act on lower scores, change PMG's rule that adds the header.
Scores are extracted for mail ingested from this version on. Older mail has none stored, but *run now* still finds it: when a stored score is missing it re-reads the raw message.
## Trash retention
@@ -40,15 +60,68 @@ A few consequences worth knowing, because they aren't visible from the UI:
- **Delivery is at-least-once.** If the server accepts a message but the process dies before recording it, it's re-sent. Every attempt reuses the same Message-ID, so a duplicate is at least recognisable as the same message. Exactly-once isn't achievable over SMTP.
- **SMTP port conventions:** STARTTLS by default, implicit TLS when the port is 465 — overridable per account with `smtp_use_starttls`. IMAP is implicit TLS only (993); STARTTLS on 143 isn't supported.
## Notifications
Clients learn about changes from one event log, over either transport:
- **`GET /api/ws`** — a WebSocket. Browsers can't set headers on one, and a token in the URL would land in proxy logs, so the client authenticates in-band: its first message is `{"type":"auth","token":"<session>","since":<cursor or null>}`. The server replies `{"type":"ready","cursor":N,"reset":false}`, replays anything after `since`, then streams `{"type":"event","id":…,"kind":…,"data":…}` as changes happen. It pings every 25 s (inside nginx's default 60 s read timeout) and closes with code 4401 when the session ends.
- **`GET /api/events?since=<cursor>`** — the polling fallback and delta endpoint: `{events, cursor, reset, more}`. Without `since` it just returns the current cursor.
Event kinds are `message_new` (with the final `notify` decision, sender and subject), `mailbox_changed` (thread ids, or `null` for "reload everything"), `outbox_changed` and `config_changed` (tags, folders, rules or accounts). They say *what* changed, not the new state; clients re-fetch through the normal API.
Worth knowing:
- **Only mail that arrives live notifies.** An account's first sync, and a UIDVALIDITY re-sync, are backlog: they're announced once per batch as `mailbox_changed` and never alert, however recent the mail.
- **Cursors survive seven days.** Events are purged after that; a client presenting an older (or unknown) cursor gets `reset: true` and should reload everything. Replays longer than 1,000 events also reset — reloading is quicker.
- **Ids are ordered by commit, not by start.** Events are inserted under a lock, one at a time, so a client that has seen id N has seen everything before it. Without that, two concurrent inserts could commit out of order and a resuming client would skip one forever.
- **One server process.** Live delivery is an in-process broadcast. Several instances behind a load balancer would each only push their own changes (polling would still be complete) — Postgres `LISTEN/NOTIFY` is the fix if that's ever needed.
## Push notifications (Android)
The phone's UnifiedPush distributor (e.g. the ntfy app) hands it an endpoint on a push server; the app registers that endpoint here with `POST /api/devices`. When new mail arrives whose `notify` decision is true, the server POSTs to each of the user's endpoints; the app then syncs over the API.
- **Content-free and encrypted.** The payload is just `{"kind":"sync"}`, encrypted to the phone's key per RFC 8291, so the push server learns nothing but timing. Requests are VAPID-signed (RFC 8292) for push services that require it; the app fetches the public key from `GET /api/push`. The key is generated on first start and stored encrypted with `CREDENTIAL_KEY`.
- **Only notifying mail pushes.** Don't-notify rules, mail filed away by rules, and backlog from an account's first sync send nothing — the app catches up next time it syncs.
- **Bursts coalesce.** Pushes are sent two seconds after the first notifying message, and one push covers everything that arrived meanwhile.
- **Dead endpoints clean themselves up.** A 404 or 410 from the push server removes the device; other failures are recorded on it (`GET /api/devices` shows `last_error`), and `POST /api/devices/:id/test` pushes once and reports what the push server said.
- **Reaching a self-hosted push server:**
- `PUSH_URL_REWRITE=https://ntfy.example.org/=>http://ntfy:80/` — endpoints carry the push server's *public* URL; rewrite the prefix when this server should reach it another way (container network, internal address). Comma-separate several. The VAPID audience stays the public origin.
- `PUSH_CA_CERT=/path/ca.pem` — trust an extra CA for push requests (the OS store is trusted too).
- `PUSH_TLS_INSECURE=true` — skip certificate verification for push requests. Logged as a warning at startup.
- `PUSH_VAPID_SUBJECT=mailto:you@example.org` — a contact address for push-service operators.
- **Any signed-in user can make the server POST to a URL of their choosing** (their push endpoint). Fine for a personal server; on a shared one, restrict outbound traffic at the network level.
## Registration
Only the first user can sign up, which is how a new server gets its owner. After that, `POST /api/auth/register` answers 403 unless `OPEN_REGISTRATION=true`. An open sign-up would let anyone on the internet use the server to make outbound IMAP, SMTP and push connections.
## Deployment
A `v*` tag builds the image and pushes it to the registry. Production, tern-api.mtps.pl, is defined in [`ygg/deployments`](https://git.app.ygg/ygg/deployments/src/branch/main/deployments/tern-server.yml), secrets included: Renovate opens a PR there for the new version, and merging it deploys. The webapp is released separately, from tern-web. Back up `CREDENTIAL_KEY` outside the deployments repository: without it, the stored IMAP/SMTP passwords and the VAPID key can't be decrypted. The image's `HEALTHCHECK` runs `tern-server healthcheck`, so `docker compose up --wait` only succeeds once the server answers `/healthz`.
## Sessions
Sessions expire `SESSION_TTL_HOURS` (default 30 days) after they were last *used*, not after sign-in: each request pushes expiry back out, at most once an hour. A phone that syncs on push, or an open tab, stays signed in; a device left unused for the full period has to sign in again.
## What's explicitly deferred
Per the spec's suggested build order (§9), not yet built: spam header rules (the rule engine already supports them — phase 6 is about defaults and a UI for the threshold), WebSocket push (the `/events` poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration.
Everything in the spec's build order (§9) is built. Deferred beyond it:
- **App lock** on Android (android-client-spec.md §7) — agreed to come after phase 8.
Also deferred, and worth knowing because they aren't obvious from the code:
- **Permissive CORS.** `CorsLayer::permissive()` is a dev convenience so the Vite dev server on another port can talk to the API. Tighten it when the webapp is served from the same origin behind nginx.
- **Permissive CORS.** `CorsLayer::permissive()` lets the webapp, deployed on its own origin, call the API. Clients authenticate with a bearer token, never a cookie, so a foreign page can't borrow a signed-in browser's session. Restricting it to the webapp's origin would still be tidier.
- **API-level rate limiting.** The nginx layer covers most of this — see [`nginx-rate-limiting.md`](nginx-rate-limiting.md). A per-username limiter in the API is the remaining gap.
### Fixed: mail announced mid-fetch could wait for the next renewal
A server announces new mail once per session, as an untagged `EXISTS` attached to whatever response is in flight. Mail landing while Tern was fetching — or while IDLE was starting — was announced that way; async-imap files such announcements in a side channel instead of waking IDLE, and the server doesn't repeat them. The message then sat unfetched until the next IDLE renewal or the next new mail.
Measured before the fix: in bursts of 4 messages separated by quiet gaps, 4 of 12 bursts had a message stuck for the whole gap; one message sat 358 s in an earlier run. After: 0 of 12, worst case 0.2 s. The sync loop now drains that channel after IDLE starts and fetches again if it announced mail. Draining also matters on its own — the channel holds 100 entries and silently drops announcements once full.
IDLE is also renewed every 10 minutes rather than 25; each renewal re-runs the fetch pass, so it doubles as the 5–15 minute safety-net poll the spec asks for (§3.1).
### Decided: the sync engine only moves forward
`fetch_new_headers` only looks at UIDs above `last_synced_uid`, so **flag changes and deletions made on the source IMAP server are never noticed.** A message read or deleted in another client stays unread and present in Tern forever.
@@ -64,7 +137,7 @@ The fix when it comes is a periodic reconciliation pass — `UID SEARCH ALL` to
```bash
cp .env.example .env
openssl rand -base64 32 # paste into .env as CREDENTIAL_KEY
openssl rand -hex 32 # paste into .env as CREDENTIAL_KEY (base64 works too)
docker compose up -d db
cargo run
```
+2 -2
View File
@@ -114,8 +114,8 @@ All three workflows target `runs-on: rocky-10` and follow the conventions alread
What still needs doing, in order of how likely it is to bite:
1. **`REGISTRY_TOKEN` secret on `tern-server`** — a token with `write:package` scope, for pushing the image. Unlike the release jobs, this one can't use the automatic `GITHUB_TOKEN`, whose scope doesn't reliably cover the package registry. (Worth trying `GITHUB_TOKEN` first on your instance; if it works, drop the extra secret.)
2. **The container registry is enabled**, and `gitea.server_url` matches the registry host. The workflow derives the registry from that rather than hardcoding — verify on the first run that the pushed image lands where you expect.
1. **`REGISTRY_TOKEN` secret on `tern-server`** — a token with `write:package` scope, for pushing the image. The automatic `GITHUB_TOKEN` can't push packages on this instance. The secret is passed to the shared [`ygg/actions/push-image`](https://git.app.ygg/ygg/actions/src/branch/main/push-image) action as an input, because actions can't read secrets themselves.
2. **The container registry is enabled**, and `gitea.server_url` matches the registry host. `push-image` derives the registry from it rather than hardcoding one, and pushes `git.app.ygg/mtps/tern-server`.
3. **Android signing secrets** — see §3 above: `ANDROID_KEYSTORE_B64`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD`.
4. **`docker build` available to the job** — already proven on this runner.
+4
View File
@@ -0,0 +1,4 @@
-- Phase 6: a system Junk folder alongside Archive (server-architecture-spec.md
-- §3.5 — "score > N → tag as spam / move to Junk").
ALTER TABLE folders DROP CONSTRAINT folders_role_check;
ALTER TABLE folders ADD CONSTRAINT folders_role_check CHECK (role IN ('archive', 'junk'));
+28
View File
@@ -0,0 +1,28 @@
-- Change events for WebSocket push and the polling fallback
-- (server-architecture-spec.md §3.8, webapp-client-spec.md §3).
--
-- One append-only log per server, read per user. The id is the cursor
-- clients resume from, so it has to be monotonic in commit order — the
-- server serialises inserts (see src/events.rs) rather than relying on the
-- sequence alone, which hands out ids in *start* order across concurrent
-- transactions.
CREATE TABLE events (
id BIGSERIAL PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
payload JSONB NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX events_user_id_id_idx ON events(user_id, id);
CREATE INDEX events_created_at_idx ON events(created_at);
-- Set when a message is discovered by an incremental sync pass, as opposed
-- to the first sync of an account or a UIDVALIDITY re-sync — only mail that
-- genuinely just arrived is a candidate for a "new mail" notification.
ALTER TABLE messages ADD COLUMN arrived_live BOOLEAN NOT NULL DEFAULT false;
-- Whether the account has finished its first full pass. Until then every
-- message found is backlog, however recent, and shouldn't notify.
ALTER TABLE sync_state ADD COLUMN caught_up BOOLEAN NOT NULL DEFAULT false;
UPDATE sync_state SET caught_up = last_synced_uid > 0;
+23
View File
@@ -0,0 +1,23 @@
-- UnifiedPush device registrations (server-architecture-spec.md §3.8) and
-- server-held keys.
--
-- A device row is one phone's push subscription: the distributor-issued
-- endpoint plus the Web Push keys its messages are encrypted for (RFC 8291).
-- Keys are nullable for distributors that don't do Web Push encryption.
ALTER TABLE devices
ADD COLUMN name TEXT,
ADD COLUMN p256dh TEXT,
ADD COLUMN auth TEXT,
ADD COLUMN last_push_at TIMESTAMPTZ,
ADD COLUMN last_error TEXT;
CREATE UNIQUE INDEX devices_user_id_endpoint_idx ON devices(user_id, endpoint);
-- Keys the server generates for itself (currently the VAPID signing key),
-- encrypted with CREDENTIAL_KEY like account passwords.
CREATE TABLE server_keys (
name TEXT PRIMARY KEY,
ciphertext BYTEA NOT NULL,
nonce BYTEA NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+6
View File
@@ -0,0 +1,6 @@
-- Plain-text mail used to be stored with an HTML body the parser had
-- synthesised from the text (see src/imap_sync/parse.rs), so clients showed
-- it as HTML. Rows that may be affected are flagged here and re-parsed from
-- their stored raw message once, at startup (src/imap_sync/body_backfill.rs).
ALTER TABLE bodies ADD COLUMN html_checked BOOLEAN NOT NULL DEFAULT true;
UPDATE bodies SET html_checked = false WHERE html_body LIKE '<html><body>%';
+4
View File
@@ -0,0 +1,4 @@
-- When an account's settings last changed. The sync manager compares it
-- with the version its running task started from, and restarts the task
-- after an edit (new password, host, …) — the task holds its own copy.
ALTER TABLE accounts ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
+11 -2
View File
@@ -3,6 +3,13 @@
# plain-HTTP local-dev shape) and forwards to the API, which never needs to
# be reachable directly.
# Only ask for an upgrade when the client did; plain requests keep
# ordinary keep-alive semantics.
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name _;
@@ -15,8 +22,10 @@ server {
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.
# WebSocket upgrade for /api/ws (live notifications). The server
# pings every 25 s, so the default 60 s proxy_read_timeout never
# cuts an idle socket.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Connection $connection_upgrade;
}
}
+187 -9
View File
@@ -1,7 +1,8 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiResult, AppJson};
use crate::models::account::{Account, AccountPublic};
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::{Change, ConfigKind};
use crate::models::account::{Account, AccountPublic, AccountSync};
use axum::{extract::State, Json};
use serde::Deserialize;
use uuid::Uuid;
@@ -34,17 +35,79 @@ pub async fn list(
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
let mut sync: std::collections::HashMap<Uuid, AccountSync> = sqlx::query_as::<_, AccountSync>(
"SELECT s.account_id, s.status, s.last_error, s.updated_at, s.caught_up, \
(SELECT count(*) FROM messages m \
WHERE m.account_id = s.account_id AND m.source = 'imap') AS messages \
FROM sync_state s JOIN accounts a ON a.id = s.account_id WHERE a.user_id = $1",
)
.bind(user.user_id)
.fetch_all(&state.pool)
.await?
.into_iter()
.map(|s| (s.account_id, s))
.collect();
Ok(Json(
accounts.into_iter().map(AccountPublic::from).collect(),
accounts
.into_iter()
.map(|a| {
let id = a.id;
AccountPublic {
sync: sync.remove(&id),
..AccountPublic::from(a)
}
})
.collect(),
))
}
/// Catches what would otherwise only fail later, in the sync task's log.
fn validate_settings(
name: &str,
imap_host: &str,
imap_port: i32,
smtp_host: &str,
smtp_port: i32,
username: &str,
) -> ApiResult<()> {
let blank = |s: &str| s.trim().is_empty();
if blank(name) || blank(imap_host) || blank(smtp_host) || blank(username) {
return Err(ApiError::BadRequest(
"name, IMAP server, SMTP server and login are all required".into(),
));
}
for (what, port) in [("IMAP", imap_port), ("SMTP", smtp_port)] {
if !(1..=65535).contains(&port) {
return Err(ApiError::BadRequest(format!("{what} port must be 1–65535")));
}
}
Ok(())
}
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
validate_settings(
&req.name,
&req.imap_host,
req.imap_port,
&req.smtp_host,
req.smtp_port,
&req.username,
)?;
if req.password.is_empty() {
return Err(ApiError::BadRequest(
"the mailbox password is required".into(),
));
}
Ok(())
}
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<CreateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
validate(&req)?;
let encrypted = state.cipher.encrypt(&req.password)?;
let account: Account = sqlx::query_as(
@@ -55,12 +118,12 @@ pub async fn create(
COALESCE($10, CASE WHEN $7 LIKE '%@%' THEN $7 END), $11, $12) RETURNING *",
)
.bind(user.user_id)
.bind(&req.name)
.bind(&req.imap_host)
.bind(req.name.trim())
.bind(req.imap_host.trim())
.bind(req.imap_port)
.bind(&req.smtp_host)
.bind(req.smtp_host.trim())
.bind(req.smtp_port)
.bind(&req.username)
.bind(req.username.trim())
.bind(&encrypted.ciphertext)
.bind(&encrypted.nonce)
.bind(req.email_address.as_deref().map(str::trim).filter(|e| !e.is_empty()))
@@ -74,6 +137,109 @@ pub async fn create(
.execute(&state.pool)
.await?;
// Start syncing now rather than at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
.await;
Ok(Json(account.into()))
}
/// The account's settings, replaced as a whole — except the password,
/// which stays as it is unless a new one is given.
#[derive(Deserialize)]
pub struct UpdateAccountRequest {
pub name: String,
pub imap_host: String,
pub imap_port: i32,
pub smtp_host: String,
pub smtp_port: i32,
pub username: String,
/// Omitted or empty: keep the stored password.
pub password: Option<String>,
pub email_address: Option<String>,
pub display_name: Option<String>,
/// Defaults by port, as when creating.
pub smtp_use_starttls: Option<bool>,
}
/// Edits an account. Its sync task is restarted with the new settings.
/// Mail already synced stays when it's still the same mailbox (say, a new
/// password or a renamed host); pointing it at a different mailbox shows up
/// as a UIDVALIDITY change on the next connect, and that re-syncs it.
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
AppJson(req): AppJson<UpdateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
validate_settings(
&req.name,
&req.imap_host,
req.imap_port,
&req.smtp_host,
req.smtp_port,
&req.username,
)?;
let sealed = match req.password.as_deref().filter(|p| !p.is_empty()) {
Some(p) => Some(state.cipher.encrypt(p)?),
None => None,
};
let account: Option<Account> = sqlx::query_as(
"UPDATE accounts SET \
name = $3, imap_host = $4, imap_port = $5, smtp_host = $6, smtp_port = $7, \
username = $8, \
email_address = COALESCE($9, CASE WHEN $8 LIKE '%@%' THEN $8 END), \
display_name = $10, smtp_use_starttls = $11, \
encrypted_password = COALESCE($12, encrypted_password), \
password_nonce = COALESCE($13, password_nonce), \
updated_at = now() \
WHERE id = $1 AND user_id = $2 RETURNING *",
)
.bind(account_id)
.bind(user.user_id)
.bind(req.name.trim())
.bind(req.imap_host.trim())
.bind(req.imap_port)
.bind(req.smtp_host.trim())
.bind(req.smtp_port)
.bind(req.username.trim())
.bind(
req.email_address
.as_deref()
.map(str::trim)
.filter(|e| !e.is_empty()),
)
.bind(
req.display_name
.as_deref()
.map(str::trim)
.filter(|n| !n.is_empty()),
)
.bind(req.smtp_use_starttls.unwrap_or(req.smtp_port != 465))
.bind(sealed.as_ref().map(|s| &s.ciphertext))
.bind(sealed.as_ref().map(|s| &s.nonce))
.fetch_optional(&state.pool)
.await?;
let account = account.ok_or(ApiError::NotFound)?;
// The old status described the old settings.
sqlx::query(
"UPDATE sync_state SET status = 'pending', last_error = NULL, updated_at = now() \
WHERE account_id = $1",
)
.bind(account_id)
.execute(&state.pool)
.await?;
// Restart its sync task now rather than at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
.await;
Ok(Json(account.into()))
}
@@ -82,11 +248,23 @@ pub async fn delete(
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")
// Its mail goes with it (ON DELETE CASCADE); the clients say so before
// asking. Stored files are cleaned up by the retention task's orphan GC.
let deleted = sqlx::query("DELETE FROM accounts WHERE id = $1 AND user_id = $2")
.bind(account_id)
.bind(user.user_id)
.execute(&state.pool)
.await?;
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
// Stop its sync task now, not at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
.await;
Ok(Json(serde_json::json!({ "ok": true })))
}
+19 -1
View File
@@ -37,11 +37,28 @@ pub async fn register(
let password_hash = hash_password(&req.password)?;
// Unless sign-up is open, only the first user may register. The lock
// makes "is this the first user?" and the insert one step, so two
// registrations racing on a fresh server can't both be first.
let mut tx = state.pool.begin().await?;
sqlx::query("SELECT pg_advisory_xact_lock(hashtext('tern-register'))")
.execute(&mut *tx)
.await?;
if !state.config.open_registration {
let has_users: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM users)")
.fetch_one(&mut *tx)
.await?;
if has_users {
return Err(ApiError::Forbidden(
"registration is closed on this server — ask its owner for an account".into(),
));
}
}
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)
.fetch_one(&mut *tx)
.await
.map_err(|e| match e {
sqlx::Error::Database(db_err) if db_err.is_unique_violation() => {
@@ -49,6 +66,7 @@ pub async fn register(
}
other => ApiError::Sqlx(other),
})?;
tx.commit().await?;
create_session(&state, user.id).await.map(Json)
}
+178
View File
@@ -0,0 +1,178 @@
//! Push device registrations (server-architecture-spec.md §3.8). The phone
//! registers the endpoint its UnifiedPush distributor handed it, plus the
//! Web Push keys to encrypt for, and removes it when it signs out or the
//! distributor unregisters it.
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::push::webpush::Subscription;
use axum::{
extract::{Path, State},
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Serialize, sqlx::FromRow)]
pub struct Device {
pub id: Uuid,
pub name: Option<String>,
pub endpoint: Option<String>,
pub created_at: DateTime<Utc>,
pub last_push_at: Option<DateTime<Utc>>,
/// Why the last push didn't go through, if it didn't.
pub last_error: Option<String>,
}
const COLUMNS: &str = "id, name, endpoint, created_at, last_push_at, last_error";
#[derive(Deserialize)]
pub struct DeviceRequest {
pub endpoint: String,
/// Web Push keys (base64url), from the UnifiedPush connector. Omit both
/// for a distributor that doesn't encrypt.
pub p256dh: Option<String>,
pub auth: Option<String>,
/// Shown in the device list, e.g. the phone model.
pub name: Option<String>,
}
fn validate(req: &DeviceRequest) -> ApiResult<()> {
let url = reqwest::Url::parse(&req.endpoint)
.map_err(|_| ApiError::BadRequest("endpoint must be a URL".into()))?;
if !matches!(url.scheme(), "https" | "http") {
return Err(ApiError::BadRequest(
"endpoint must be an http(s) URL".into(),
));
}
match (&req.p256dh, &req.auth) {
(Some(p), Some(a)) => {
Subscription::from_base64(p, a).map_err(ApiError::BadRequest)?;
}
(None, None) => {}
_ => {
return Err(ApiError::BadRequest(
"p256dh and auth go together — send both or neither".into(),
))
}
}
Ok(())
}
#[derive(Serialize)]
pub struct PushInfo {
/// Pass to `UnifiedPush.register(vapid = …)`.
pub vapid_public_key: String,
}
pub async fn push_info(State(state): State<AppState>, _user: CurrentUser) -> Json<PushInfo> {
Json(PushInfo {
vapid_public_key: state.pusher.vapid_public_key(),
})
}
pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<Device>>> {
Ok(Json(
sqlx::query_as(&format!(
"SELECT {COLUMNS} FROM devices WHERE user_id = $1 AND kind = 'unifiedpush' \
ORDER BY created_at"
))
.bind(user.user_id)
.fetch_all(&state.pool)
.await?,
))
}
/// Registers an endpoint, or refreshes the keys and name of one already
/// registered — a reinstall or re-registration hands back the same endpoint.
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<DeviceRequest>,
) -> ApiResult<Json<Device>> {
validate(&req)?;
let device = sqlx::query_as(&format!(
"INSERT INTO devices (user_id, kind, endpoint, p256dh, auth, name, last_seen_at) \
VALUES ($1, 'unifiedpush', $2, $3, $4, $5, now()) \
ON CONFLICT (user_id, endpoint) DO UPDATE SET \
p256dh = EXCLUDED.p256dh, auth = EXCLUDED.auth, \
name = COALESCE(EXCLUDED.name, devices.name), \
last_seen_at = now(), last_error = NULL \
RETURNING {COLUMNS}"
))
.bind(user.user_id)
.bind(&req.endpoint)
.bind(&req.p256dh)
.bind(&req.auth)
.bind(req.name.as_deref().map(str::trim).filter(|n| !n.is_empty()))
.fetch_one(&state.pool)
.await?;
Ok(Json(device))
}
/// Replaces a device's endpoint — distributors rotate them.
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
AppJson(req): AppJson<DeviceRequest>,
) -> ApiResult<Json<Device>> {
validate(&req)?;
let device: Option<Device> = sqlx::query_as(&format!(
"UPDATE devices SET endpoint = $3, p256dh = $4, auth = $5, \
name = COALESCE($6, name), last_seen_at = now(), last_error = NULL \
WHERE id = $1 AND user_id = $2 RETURNING {COLUMNS}"
))
.bind(id)
.bind(user.user_id)
.bind(&req.endpoint)
.bind(&req.p256dh)
.bind(&req.auth)
.bind(req.name.as_deref().map(str::trim).filter(|n| !n.is_empty()))
.fetch_optional(&state.pool)
.await
.map_err(|e| match e {
sqlx::Error::Database(db) if db.is_unique_violation() => {
ApiError::BadRequest("that endpoint is already registered as another device".into())
}
other => ApiError::Sqlx(other),
})?;
device.map(Json).ok_or(ApiError::NotFound)
}
pub async fn delete(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
let deleted = sqlx::query("DELETE FROM devices WHERE id = $1 AND user_id = $2")
.bind(id)
.bind(user.user_id)
.execute(&state.pool)
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
Ok(Json(serde_json::json!({ "ok": true })))
}
/// Pushes to one device right away and reports what the push server said —
/// for checking the whole path from the app's settings.
pub async fn test(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<crate::push::Outcome>> {
state
.pusher
.test(user.user_id, id)
.await?
.map(Json)
.ok_or(ApiError::NotFound)
}
+263 -34
View File
@@ -1,54 +1,283 @@
//! `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.
//! Change notifications (server-architecture-spec.md §3.8,
//! webapp-client-spec.md §3): `GET /api/ws` pushes events as they happen,
//! `GET /api/events?since=<cursor>` is the polling fallback and the delta
//! endpoint for clients that were away (§4). Both read the same log, so a
//! client can switch between them mid-stream without losing its place.
//!
//! Cursors are event ids. A client with no cursor asks without `since` and
//! gets the current head; a client whose cursor is too old (events purged)
//! or otherwise unusable gets `reset: true` and should reload everything.
use crate::api::middleware::CurrentUser;
use crate::api::middleware::{session_user, CurrentUser};
use crate::api::state::AppState;
use crate::error::ApiResult;
use crate::models::Message;
use crate::events::{self, Event};
use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade};
use axum::{
extract::{Query, State},
response::Response,
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tokio::sync::broadcast::error::RecvError;
use uuid::Uuid;
/// Replaying more than this is slower than a client reloading its view.
const MAX_REPLAY: i64 = 1000;
const DEFAULT_POLL_LIMIT: i64 = 500;
/// Where a client should resume from, given the cursor it presented.
async fn resume_point(state: &AppState, since: Option<i64>) -> sqlx::Result<(i64, bool)> {
let head = state.events.head().await?;
Ok(match since {
None => (head, false),
// A cursor from the future means another database (restored backup,
// reinstall) — nothing it says about "what I've seen" holds here.
Some(s) if s > head || events::is_stale(&state.pool, s).await? => (head, true),
Some(s) => (s, false),
})
}
#[derive(Deserialize)]
pub struct EventsQuery {
pub since: Option<DateTime<Utc>>,
pub struct PollQuery {
pub since: Option<i64>,
pub limit: Option<i64>,
}
#[derive(Serialize)]
pub struct EventsResponse {
pub changed_messages: Vec<Message>,
pub cursor: DateTime<Utc>,
pub struct PollResponse {
pub events: Vec<Event>,
/// Pass back as `since` next time.
pub cursor: i64,
/// The cursor couldn't be honoured; reload everything, then carry on
/// from `cursor`.
pub reset: bool,
/// More events are waiting — poll again straight away.
pub more: bool,
}
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,
Query(q): Query<PollQuery>,
) -> ApiResult<Json<PollResponse>> {
let limit = q.limit.unwrap_or(DEFAULT_POLL_LIMIT).clamp(1, MAX_REPLAY);
let (from, reset) = resume_point(&state, q.since).await?;
if reset || q.since.is_none() {
return Ok(Json(PollResponse {
events: vec![],
cursor: from,
reset,
more: false,
}));
}
let events = events::after(&state.pool, user.user_id, from, limit).await?;
Ok(Json(PollResponse {
cursor: events.last().map_or(from, |e| e.id),
more: events.len() as i64 == limit,
events,
reset: false,
}))
}
// --- WebSocket -------------------------------------------------------------
/// A client has this long after connecting to authenticate.
const AUTH_TIMEOUT: Duration = Duration::from_secs(10);
/// Server pings this often — comfortably inside nginx's default 60 s
/// proxy_read_timeout, so an idle socket isn't cut by the proxy. Each tick
/// also re-checks the session, so logging out or expiry ends the stream.
const HEARTBEAT: Duration = Duration::from_secs(25);
/// Application close codes (4000–4999 are free for applications).
const CLOSE_UNAUTHORIZED: u16 = 4401;
const CLOSE_BAD_HELLO: u16 = 4400;
/// First (and only) message a client sends. Browsers can't put an
/// Authorization header on a WebSocket, and a token in the URL would end up
/// in proxy access logs, so the session token travels in-band.
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ClientMsg {
Auth { token: Uuid, since: Option<i64> },
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ServerMsg<'a> {
/// Authenticated. Same meaning as the poll response's fields; replayed
/// events (if any) follow immediately.
Ready {
cursor: i64,
reset: bool,
},
Event(&'a Event),
}
pub async fn socket(State(state): State<AppState>, ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(move |socket| async move {
if let Err(e) = serve(state, socket).await {
tracing::debug!(error = %e, "websocket ended with error");
}
})
}
async fn send(socket: &mut WebSocket, msg: &ServerMsg<'_>) -> anyhow::Result<()> {
let text = serde_json::to_string(msg)?;
socket.send(Message::Text(text)).await?;
Ok(())
}
async fn close(socket: &mut WebSocket, code: u16, reason: &'static str) {
let _ = socket
.send(Message::Close(Some(CloseFrame {
code,
reason: reason.into(),
})))
.await;
}
async fn serve(state: AppState, mut socket: WebSocket) -> anyhow::Result<()> {
let hello = match tokio::time::timeout(AUTH_TIMEOUT, socket.recv()).await {
Ok(Some(Ok(Message::Text(t)))) => serde_json::from_str::<ClientMsg>(&t).ok(),
Ok(_) => None,
Err(_) => {
close(&mut socket, CLOSE_BAD_HELLO, "authenticate first").await;
return Ok(());
}
};
let Some(ClientMsg::Auth { token, since }) = hello else {
close(&mut socket, CLOSE_BAD_HELLO, "expected auth message").await;
return Ok(());
};
let Some(user_id) = session_user(&state, token).await? else {
close(&mut socket, CLOSE_UNAUTHORIZED, "unauthorized").await;
return Ok(());
};
// Subscribe before reading the backlog: anything emitted in between is
// then seen twice (once from each) rather than not at all, and the id
// check below drops the duplicate.
let mut live = state.events.subscribe();
let (mut cursor, reset) = resume_point(&state, since).await?;
send(&mut socket, &ServerMsg::Ready { cursor, reset }).await?;
if !reset && since.is_some() {
cursor = catch_up(&state, &mut socket, user_id, cursor).await?;
}
let mut heartbeat = tokio::time::interval(HEARTBEAT);
heartbeat.tick().await; // the first tick is immediate
loop {
tokio::select! {
received = live.recv() => match received {
Ok(event) => {
if event.user_id == user_id && event.id > cursor {
send(&mut socket, &ServerMsg::Event(&event)).await?;
cursor = event.id;
}
}
// Fell behind the broadcast buffer: the log has everything.
Err(RecvError::Lagged(_)) => {
cursor = catch_up(&state, &mut socket, user_id, cursor).await?;
}
Err(RecvError::Closed) => return Ok(()),
},
incoming = socket.recv() => match incoming {
// Completes the closing handshake: tungstenite queues its
// reply on reading the client's Close frame but only sends it
// while the stream keeps being polled, so read to the end
// rather than dropping — otherwise the client sees 1006.
Some(Ok(Message::Close(_))) => {
while let Some(Ok(_)) = socket.recv().await {}
return Ok(());
}
None | Some(Err(_)) => return Ok(()),
// Pongs and anything else a client sends are ignored; axum
// answers pings itself.
Some(Ok(_)) => {}
},
_ = heartbeat.tick() => {
if session_user(&state, token).await? != Some(user_id) {
close(&mut socket, CLOSE_UNAUTHORIZED, "session ended").await;
return Ok(());
}
socket.send(Message::Ping(Vec::new())).await?;
}
}
}
}
/// Sends everything after `cursor` from the log, or a reset if that's more
/// than is worth replaying. Returns the new cursor.
async fn catch_up(
state: &AppState,
socket: &mut WebSocket,
user_id: Uuid,
mut cursor: i64,
) -> anyhow::Result<i64> {
let backlog = events::after(&state.pool, user_id, cursor, MAX_REPLAY + 1).await?;
if backlog.len() as i64 > MAX_REPLAY {
let head = state.events.head().await?;
send(
socket,
&ServerMsg::Ready {
cursor: head,
reset: true,
},
)
.await?;
return Ok(head);
}
for event in &backlog {
send(socket, &ServerMsg::Event(event)).await?;
cursor = event.id;
}
Ok(cursor)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_messages_are_flat_and_tagged() {
let event = Event {
id: 7,
user_id: Uuid::nil(),
kind: "outbox_changed".into(),
payload: serde_json::json!({ "status": "sent" }),
created_at: chrono::DateTime::UNIX_EPOCH,
};
let v = serde_json::to_value(ServerMsg::Event(&event)).unwrap();
assert_eq!(v["type"], "event");
assert_eq!(v["id"], 7);
assert_eq!(v["kind"], "outbox_changed");
assert_eq!(v["data"]["status"], "sent");
assert!(v.get("user_id").is_none(), "user id isn't sent to clients");
let v = serde_json::to_value(ServerMsg::Ready {
cursor: 3,
reset: true,
})
.unwrap();
assert_eq!(
v,
serde_json::json!({ "type": "ready", "cursor": 3, "reset": true })
);
}
#[test]
fn client_hello_parses_with_and_without_cursor() {
let t = Uuid::new_v4();
let m: ClientMsg =
serde_json::from_str(&format!(r#"{{"type":"auth","token":"{t}","since":12}}"#))
.unwrap();
let ClientMsg::Auth { token, since } = m;
assert_eq!((token, since), (t, Some(12)));
let m: ClientMsg =
serde_json::from_str(&format!(r#"{{"type":"auth","token":"{t}"}}"#)).unwrap();
let ClientMsg::Auth { since, .. } = m;
assert_eq!(since, None);
}
}
+15 -1
View File
@@ -1,6 +1,7 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiResult, AppJson};
use crate::events::{Change, ConfigKind};
use crate::models::Folder;
use axum::{extract::State, Json};
use serde::Deserialize;
@@ -34,6 +35,10 @@ pub async fn create(
.bind(&req.name)
.fetch_one(&state.pool)
.await?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Folders))
.await;
Ok(Json(folder))
}
@@ -61,7 +66,12 @@ pub async fn rename(
.bind(name)
.fetch_optional(&state.pool)
.await?;
folder.map(Json).ok_or(crate::error::ApiError::NotFound)
let folder = folder.ok_or(crate::error::ApiError::NotFound)?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Folders))
.await;
Ok(Json(folder))
}
/// Messages in a deleted folder go back to the inbox (FK ON DELETE SET
@@ -84,5 +94,9 @@ pub async fn delete(
"folder not found, or it's the Archive folder, which can't be deleted".into(),
));
}
state
.events
.emit(user.user_id, Change::config(ConfigKind::Folders))
.await;
Ok(Json(serde_json::json!({ "ok": true })))
}
+29 -11
View File
@@ -1,7 +1,6 @@
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
@@ -31,15 +30,34 @@ impl FromRequestParts<AppState> for CurrentUser {
.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),
}
session_user(state, token)
.await?
.map(|user_id| CurrentUser { user_id })
.ok_or(ApiError::Unauthorized)
}
}
/// The user a session token belongs to, if the session exists and hasn't
/// expired. Shared with the WebSocket, which authenticates in-band because
/// browsers can't set headers on a socket.
///
/// Expiry slides: using a session pushes its expiry back out to the full
/// TTL, so a client in regular use — a phone syncing on push, an open tab —
/// is never signed out, while an abandoned one still lapses. The write is
/// skipped unless the session is at least an hour into its current window,
/// so a busy client doesn't turn every request into an UPDATE.
pub async fn session_user(state: &AppState, token: Uuid) -> sqlx::Result<Option<Uuid>> {
sqlx::query_scalar(
"WITH s AS ( \
SELECT token, user_id FROM sessions WHERE token = $1 AND expires_at > now()), \
bump AS ( \
UPDATE sessions SET expires_at = now() + make_interval(hours => $2) \
WHERE token IN (SELECT token FROM s) \
AND expires_at < now() + make_interval(hours => $2) - interval '1 hour') \
SELECT user_id FROM s",
)
.bind(token)
.bind(state.session_ttl_hours as i32)
.fetch_optional(&state.pool)
.await
}
+1
View File
@@ -1,5 +1,6 @@
pub mod accounts;
pub mod auth;
pub mod devices;
pub mod events;
pub mod folders;
pub mod messages;
+31 -1
View File
@@ -10,6 +10,7 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::Change;
use crate::models::account::Account;
use crate::models::outbox::OutboxItem;
use crate::models::Message;
@@ -121,6 +122,7 @@ pub async fn create(
if req.send {
return queue(&state, &account, item).await.map(Json);
}
changed(&state, &item).await;
Ok(Json(item))
}
@@ -152,7 +154,9 @@ pub async fn update(
.fetch_optional(&state.pool)
.await?;
item.map(Json).ok_or_else(|| editable_or_not_found(id))
let item = item.ok_or_else(|| editable_or_not_found(id))?;
changed(&state, &item).await;
Ok(Json(item))
}
pub async fn send(
@@ -190,9 +194,32 @@ pub async fn delete(
if deleted == 0 {
return Err(editable_or_not_found(id));
}
state
.events
.emit(
user.user_id,
Change::OutboxChanged {
id,
status: "deleted".into(),
},
)
.await;
Ok(Json(serde_json::json!({ "ok": true })))
}
async fn changed(state: &AppState, item: &OutboxItem) {
state
.events
.emit(
item.user_id,
Change::OutboxChanged {
id: item.id,
status: item.status.clone(),
},
)
.await;
}
/// Validates that the message is actually sendable, assigns its Message-ID
/// (once — retries reuse it), marks it pending and wakes the worker so it
/// goes out now rather than at the next poll.
@@ -209,6 +236,9 @@ async fn queue(state: &AppState, account: &Account, item: OutboxItem) -> ApiResu
.fetch_one(&state.pool)
.await?;
// Announced before the worker is woken, so "pending" can't land in the
// event log after the worker's own "sent".
changed(state, &item).await;
state.outbox_wake.notify_one();
Ok(item)
}
+31 -5
View File
@@ -1,8 +1,11 @@
use crate::api::state::AppState;
use crate::api::{accounts, auth, events, folders, messages, outbox, rules, tags, threads};
use axum::routing::{delete, get, post, put};
use crate::api::{
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
};
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
use axum::routing::{get, post, put};
use axum::Router;
use tower_http::cors::CorsLayer;
use tower_http::cors::{Any, CorsLayer};
use tower_http::trace::TraceLayer;
pub fn build(state: AppState) -> Router {
@@ -10,7 +13,10 @@ pub fn build(state: AppState) -> Router {
.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/accounts/:id",
put(accounts::update).delete(accounts::delete),
)
.route("/api/folders", get(folders::list).post(folders::create))
.route(
"/api/folders/:id",
@@ -35,8 +41,28 @@ pub fn build(state: AppState) -> Router {
)
.route("/api/outbox/:id/send", post(outbox::send))
.route("/api/events", get(events::poll))
.route("/api/ws", get(events::socket))
.route("/api/push", get(devices::push_info))
.route("/api/devices", get(devices::list).post(devices::create))
.route(
"/api/devices/:id",
put(devices::update).delete(devices::delete),
)
.route("/api/devices/:id/test", post(devices::test))
.route("/healthz", get(|| async { "ok" }))
.layer(TraceLayer::new_for_http())
.layer(CorsLayer::permissive())
.layer(cors())
.with_state(state)
}
/// The webapp is deployed on its own origin, so the API answers
/// cross-origin requests from anywhere. That's safe because auth is a
/// bearer token the page must hold, never a cookie the browser would attach
/// on its own. Headers are listed rather than `*`: a wildcard doesn't cover
/// `Authorization`, so browsers would refuse every signed-in request.
fn cors() -> CorsLayer {
CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers([AUTHORIZATION, CONTENT_TYPE])
}
+25 -1
View File
@@ -5,6 +5,7 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::{Change, ConfigKind};
use crate::rules::{self, Action, Conditions};
use axum::{
extract::{Path, State},
@@ -97,6 +98,10 @@ pub async fn create(
.bind(req.stop_after_match)
.fetch_one(&state.pool)
.await?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Rules))
.await;
Ok(Json(rule))
}
@@ -121,7 +126,12 @@ pub async fn update(
.bind(req.stop_after_match)
.fetch_optional(&state.pool)
.await?;
rule.map(Json).ok_or(ApiError::NotFound)
let rule = rule.ok_or(ApiError::NotFound)?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Rules))
.await;
Ok(Json(rule))
}
pub async fn delete(
@@ -138,6 +148,10 @@ pub async fn delete(
if deleted == 0 {
return Err(ApiError::NotFound);
}
state
.events
.emit(user.user_id, Change::config(ConfigKind::Rules))
.await;
Ok(Json(serde_json::json!({ "ok": true })))
}
@@ -175,6 +189,10 @@ pub async fn reorder(
.execute(&mut *tx)
.await?;
tx.commit().await?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Rules))
.await;
list(State(state), user).await
}
@@ -206,6 +224,12 @@ pub async fn run(
.map_err(ApiError::BadRequest)?;
let summary = rules::run_on_existing(&state.pool, &state.blobs, user.user_id, &rule).await?;
tracing::info!(rule_id = %id, scanned = summary.scanned, matched = summary.matched, "ran rule on existing mail");
if summary.matched > 0 {
state
.events
.emit(user.user_id, Change::MailboxChanged { thread_ids: None })
.await;
}
Ok(Json(RunResponse {
scanned: summary.scanned,
+6
View File
@@ -1,5 +1,7 @@
use crate::config::Config;
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use crate::push::Pusher;
use crate::storage::BlobStore;
use sqlx::PgPool;
use std::sync::Arc;
@@ -15,4 +17,8 @@ pub struct AppState {
/// Wakes the outbox worker as soon as something is queued, so a send
/// goes out immediately rather than at the next idle poll.
pub outbox_wake: Arc<Notify>,
/// Wakes the sync manager when accounts are added or removed.
pub sync_wake: Arc<Notify>,
pub events: EventHub,
pub pusher: Pusher,
}
+15 -1
View File
@@ -1,6 +1,7 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::{Change, ConfigKind};
use crate::models::tag::Tag;
use axum::{
extract::{Path, State},
@@ -74,6 +75,10 @@ pub async fn create(
.fetch_one(&state.pool)
.await
.map_err(conflict)?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Tags))
.await;
Ok(Json(tag))
}
@@ -94,7 +99,12 @@ pub async fn update(
.fetch_optional(&state.pool)
.await
.map_err(conflict)?;
tag.map(Json).ok_or(ApiError::NotFound)
let tag = tag.ok_or(ApiError::NotFound)?;
state
.events
.emit(user.user_id, Change::config(ConfigKind::Tags))
.await;
Ok(Json(tag))
}
/// Removes the tag from every message (cascade). Rules still naming it
@@ -113,5 +123,9 @@ pub async fn delete(
if deleted == 0 {
return Err(ApiError::NotFound);
}
state
.events
.emit(user.user_id, Change::config(ConfigKind::Tags))
.await;
Ok(Json(serde_json::json!({ "ok": true })))
}
+96 -12
View File
@@ -16,6 +16,7 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::Change;
use crate::rules::{self, Action};
use axum::{
extract::{Path, Query, State},
@@ -34,6 +35,8 @@ pub enum View {
All,
Sent,
Trash,
/// The system Junk folder, which may not exist yet.
Junk,
Folder,
Tag,
}
@@ -45,6 +48,7 @@ impl View {
View::All => "all",
View::Sent => "sent",
View::Trash => "trash",
View::Junk => "junk",
View::Folder => "folder",
View::Tag => "tag",
}
@@ -57,17 +61,45 @@ pub struct ListThreadsQuery {
pub view: View,
pub folder_id: Option<Uuid>,
pub tag_id: Option<Uuid>,
pub before: Option<DateTime<Utc>>,
/// Opaque cursor from a previous page's `next_cursor`.
pub before: Option<String>,
pub limit: Option<i64>,
}
/// Keyset position: the last row's sort time plus its thread id. The id
/// breaks ties — sort times come from Date headers with one-second
/// resolution, so a burst of mail shares them, and a timestamp-only cursor
/// with `<` would skip every thread tied with the last row of a page.
struct Cursor {
at: DateTime<Utc>,
thread_id: Uuid,
}
impl Cursor {
fn encode(at: DateTime<Utc>, thread_id: Uuid) -> String {
format!(
"{}|{thread_id}",
at.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
)
}
fn decode(s: &str) -> Option<Self> {
let (at, id) = s.split_once('|')?;
Some(Cursor {
at: DateTime::parse_from_rfc3339(at).ok()?.with_timezone(&Utc),
thread_id: id.parse().ok()?,
})
}
}
#[derive(Debug, Serialize, sqlx::FromRow)]
pub struct ThreadSummary {
pub thread_id: Uuid,
pub subject: Option<String>,
/// Display name (falling back to address) of the most recent sender.
pub last_from: Option<String>,
pub last_message_at: Option<DateTime<Utc>>,
/// When the newest message arrived, by the sort key described in `list`.
pub last_message_at: DateTime<Utc>,
pub message_count: i64,
pub unread_count: i64,
pub has_attachments: bool,
@@ -80,7 +112,8 @@ pub struct ThreadSummary {
#[derive(Serialize)]
pub struct ListThreadsResponse {
pub threads: Vec<ThreadSummary>,
pub next_cursor: Option<DateTime<Utc>>,
/// None when this was the last page.
pub next_cursor: Option<String>,
}
pub async fn list(
@@ -89,7 +122,12 @@ pub async fn list(
Query(q): Query<ListThreadsQuery>,
) -> ApiResult<Json<ListThreadsResponse>> {
let limit = q.limit.unwrap_or(50).clamp(1, 200);
let before = q.before.unwrap_or_else(Utc::now);
let cursor = match q.before.as_deref() {
Some(raw) => {
Some(Cursor::decode(raw).ok_or_else(|| ApiError::BadRequest("invalid cursor".into()))?)
}
None => None,
};
match q.view {
View::Folder if q.folder_id.is_none() => {
return Err(ApiError::BadRequest("view=folder needs folder_id".into()))
@@ -102,10 +140,19 @@ pub async fn list(
// Deleted messages are left out of every summary except Trash's, so a
// thread with one message deleted by a rule doesn't count it.
//
// Threads sort by `sort_at` = LEAST(COALESCE(sent_at, created_at),
// created_at): the Date header, but never later than when we received
// the message. A mail with no Date header still sorts (by arrival), and
// one dated in the future — clock skew, or spam trying to pin itself to
// the top — is clamped to its arrival time. An older mailbox synced
// for the first time keeps its real chronology, since its Date headers
// all precede the sync.
let threads: Vec<ThreadSummary> = sqlx::query_as(
r#"
WITH mine AS (
SELECT m.* FROM messages m
SELECT m.*, LEAST(COALESCE(m.sent_at, m.created_at), m.created_at) AS sort_at
FROM messages m
JOIN accounts a ON a.id = m.account_id
WHERE a.user_id = $1
),
@@ -116,6 +163,8 @@ pub async fn list(
WHEN 'all' THEN v.deleted_at IS NULL
WHEN 'sent' THEN v.deleted_at IS NULL AND v.source = 'sent'
WHEN 'trash' THEN v.deleted_at IS NOT NULL
WHEN 'junk' THEN v.deleted_at IS NULL AND v.folder_id =
(SELECT id FROM folders WHERE user_id = $1 AND role = 'junk')
WHEN 'folder' THEN v.deleted_at IS NULL AND v.folder_id = $3
WHEN 'tag' THEN v.deleted_at IS NULL AND EXISTS (
SELECT 1 FROM message_tags mt WHERE mt.message_id = v.id AND mt.tag_id = $4)
@@ -130,11 +179,11 @@ pub async fn list(
-- order breaks the remaining ties deterministically.
(ARRAY_AGG(m.subject ORDER BY
(m.in_reply_to IS NOT NULL OR cardinality(m.references_) > 0),
m.sent_at ASC NULLS LAST,
m.sort_at ASC,
m.created_at ASC))[1] AS subject,
(ARRAY_AGG(COALESCE(NULLIF(m.from_name, ''), m.from_addr)
ORDER BY m.sent_at DESC NULLS LAST))[1] AS last_from,
MAX(m.sent_at) AS last_message_at,
ORDER BY m.sort_at DESC))[1] AS last_from,
MAX(m.sort_at) AS last_message_at,
COUNT(*) AS message_count,
COUNT(*) FILTER (WHERE NOT ('\Seen' = ANY(m.flags))) AS unread_count,
BOOL_OR(EXISTS (SELECT 1 FROM attachments att WHERE att.message_id = m.id)) AS has_attachments,
@@ -149,8 +198,8 @@ pub async fn list(
JOIN selected USING (thread_id)
WHERE ($2 = 'trash') = (m.deleted_at IS NOT NULL)
GROUP BY m.thread_id
HAVING MAX(m.sent_at) < $5
ORDER BY last_message_at DESC
HAVING $5::timestamptz IS NULL OR (MAX(m.sort_at), m.thread_id) < ($5, $8)
ORDER BY last_message_at DESC, m.thread_id DESC
LIMIT $6
"#,
)
@@ -158,13 +207,17 @@ pub async fn list(
.bind(q.view.as_str())
.bind(q.folder_id)
.bind(q.tag_id)
.bind(before)
.bind(cursor.as_ref().map(|c| c.at))
.bind(limit)
.bind(state.config.trash_retention_days as i32)
.bind(cursor.as_ref().map(|c| c.thread_id))
.fetch_all(&state.pool)
.await?;
let next_cursor = threads.last().and_then(|t| t.last_message_at);
let next_cursor = (threads.len() as i64 == limit)
.then(|| threads.last())
.flatten()
.map(|t| Cursor::encode(t.last_message_at, t.thread_id));
Ok(Json(ListThreadsResponse {
threads,
@@ -210,6 +263,10 @@ pub async fn act(
let mut tx = state.pool.begin().await?;
rules::apply_actions(&mut tx, user.user_id, &ids, &req.actions).await?;
tx.commit().await?;
state
.events
.emit(user.user_id, Change::threads([thread_id]))
.await;
Ok(Json(serde_json::json!({ "messages": ids.len() })))
}
@@ -232,3 +289,30 @@ pub async fn mark_read(
)
.await
}
#[cfg(test)]
mod tests {
use super::Cursor;
#[test]
fn cursor_round_trips_with_microseconds_and_id() {
let at = chrono::DateTime::parse_from_rfc3339("2026-09-23T10:08:20.123456Z")
.unwrap()
.with_timezone(&chrono::Utc);
let id = uuid::Uuid::new_v4();
let c = Cursor::decode(&Cursor::encode(at, id)).unwrap();
assert_eq!((c.at, c.thread_id), (at, id));
}
#[test]
fn malformed_cursors_are_rejected() {
for bad in [
"",
"2026-09-23T10:08:20Z",
"nonsense|also-nonsense",
"2026-09-23T10:08:20Z|not-a-uuid",
] {
assert!(Cursor::decode(bad).is_none(), "{bad:?}");
}
}
}
+141 -12
View File
@@ -12,6 +12,92 @@ pub struct Config {
pub session_ttl_hours: i64,
/// Days mail stays in Trash before it's purged for good. 0 disables.
pub trash_retention_days: u32,
/// Whether anyone may create a user. When off, only the very first
/// user can register — enough to set a server up, without leaving
/// sign-up open on a public address.
pub open_registration: bool,
pub push: PushConfig,
}
/// How the server reaches UnifiedPush endpoints (see `src/push/`).
#[derive(Clone, Debug, Default)]
pub struct PushConfig {
/// URL prefix rewrites, applied to an endpoint before sending — for when
/// the push server's public URL (what the phone registered) isn't how
/// this server should reach it, e.g. a container-network address.
pub rewrites: Vec<(String, String)>,
/// Skip TLS certificate verification for push requests.
pub tls_insecure: bool,
/// Extra CA certificate (PEM) to trust for push requests, on top of the
/// OS store — for a push server behind an internal CA.
pub ca_cert: Option<std::path::PathBuf>,
/// VAPID `sub` claim: a contact for push-service operators.
pub vapid_subject: String,
}
impl PushConfig {
/// `PUSH_URL_REWRITE`: comma-separated `from=>to` prefix pairs.
fn parse_rewrites(raw: &str) -> Result<Vec<(String, String)>> {
raw.split(',')
.map(str::trim)
.filter(|r| !r.is_empty())
.map(|r| {
let (from, to) = r.split_once("=>").with_context(|| {
format!("PUSH_URL_REWRITE entry {r:?} must look like https://public/=>http://internal/")
})?;
Ok((from.trim().to_string(), to.trim().to_string()))
})
.collect()
}
fn from_env() -> Result<Self> {
Ok(Self {
rewrites: Self::parse_rewrites(&std::env::var("PUSH_URL_REWRITE").unwrap_or_default())?,
tls_insecure: matches!(
std::env::var("PUSH_TLS_INSECURE").as_deref(),
Ok("1" | "true" | "yes")
),
ca_cert: std::env::var("PUSH_CA_CERT")
.ok()
.filter(|p| !p.trim().is_empty())
.map(Into::into),
vapid_subject: std::env::var("PUSH_VAPID_SUBJECT")
.unwrap_or_else(|_| "mailto:postmaster@localhost".to_string()),
})
}
/// The URL to actually send to, after rewrites (first match wins).
pub fn rewrite(&self, endpoint: &str) -> String {
for (from, to) in &self.rewrites {
if let Some(rest) = endpoint.strip_prefix(from.as_str()) {
return format!("{to}{rest}");
}
}
endpoint.to_string()
}
}
/// The credential key, as 64 hex digits (`openssl rand -hex 32`) or base64
/// (`openssl rand -base64 32`). Hex is tried first: a 64-digit hex string
/// is never a valid base64 encoding of 32 bytes, so the two can't be
/// confused.
fn parse_key(raw: &str) -> Result<[u8; 32]> {
let raw = raw.trim();
let bytes = if raw.len() == 64 && raw.bytes().all(|b| b.is_ascii_hexdigit()) {
hex::decode(raw).context("CREDENTIAL_KEY is not valid hex")?
} else {
base64::Engine::decode(&base64::engine::general_purpose::STANDARD, raw).context(
"CREDENTIAL_KEY must be 64 hex digits (openssl rand -hex 32) or base64 \
(openssl rand -base64 32)",
)?
};
bytes.try_into().map_err(|v: Vec<u8>| {
anyhow::anyhow!(
"CREDENTIAL_KEY must be 32 bytes — 64 hex digits (openssl rand -hex 32) or base64 \
(openssl rand -base64 32) — but it decodes to {} bytes",
v.len()
)
})
}
impl Config {
@@ -21,19 +107,12 @@ impl Config {
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 raw_key = std::env::var("CREDENTIAL_KEY").context(
"CREDENTIAL_KEY must be set: a 32-byte key used to encrypt stored IMAP/SMTP \
credentials at rest, as 64 hex digits or base64. Generate one with: \
openssl rand -hex 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 credential_key = parse_key(&raw_key)?;
let blob_storage_dir = std::env::var("BLOB_STORAGE_DIR")
.unwrap_or_else(|_| "./data/blobs".to_string())
@@ -60,6 +139,56 @@ impl Config {
blob_storage_dir,
session_ttl_hours,
trash_retention_days,
open_registration: matches!(
std::env::var("OPEN_REGISTRATION").as_deref(),
Ok("1" | "true" | "yes")
),
push: PushConfig::from_env()?,
})
}
}
#[cfg(test)]
mod tests {
use super::{parse_key, PushConfig};
#[test]
fn credential_keys_parse_as_hex_or_base64() {
let hex_key = "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF";
assert_eq!(parse_key(hex_key).unwrap()[..2], [0x00, 0x11]);
let b64 = "ABEiM0RVZneImaq7zN3u/wARIjNEVWZ3iJmqu8zd7v8=";
assert_eq!(parse_key(b64).unwrap(), parse_key(hex_key).unwrap());
assert_eq!(
parse_key(&format!(" {hex_key}\n")).unwrap()[0],
0x00,
"trimmed"
);
// openssl rand -hex 48: hex, but too long — must say so, not
// "not valid base64".
let err = parse_key(&"ab".repeat(48)).unwrap_err().to_string();
assert!(err.contains("32 bytes") && err.contains("72"), "{err}");
assert!(parse_key("not a key!").is_err());
}
#[test]
fn push_rewrites_replace_the_first_matching_prefix() {
let cfg = PushConfig {
rewrites: PushConfig::parse_rewrites(
" https://ntfy.example.org/=>http://ntfy:80/ , https://ntfy.example.org/up=>http://never/",
)
.unwrap(),
..Default::default()
};
assert_eq!(
cfg.rewrite("https://ntfy.example.org/upABC?up=1"),
"http://ntfy:80/upABC?up=1"
);
assert_eq!(
cfg.rewrite("https://other.example/x"),
"https://other.example/x"
);
assert!(PushConfig::parse_rewrites("no-arrow-here").is_err());
assert!(PushConfig::parse_rewrites("").unwrap().is_empty());
}
}
+3
View File
@@ -13,6 +13,8 @@ pub enum ApiError {
Unauthorized,
#[error("bad request: {0}")]
BadRequest(String),
#[error("{0}")]
Forbidden(String),
#[error(transparent)]
Internal(#[from] anyhow::Error),
#[error(transparent)]
@@ -25,6 +27,7 @@ impl IntoResponse for ApiError {
ApiError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
ApiError::Unauthorized => (StatusCode::UNAUTHORIZED, self.to_string()),
ApiError::BadRequest(_) => (StatusCode::BAD_REQUEST, self.to_string()),
ApiError::Forbidden(_) => (StatusCode::FORBIDDEN, self.to_string()),
ApiError::Sqlx(e) => {
tracing::error!("db error: {e:#}");
(
+254
View File
@@ -0,0 +1,254 @@
//! Change events: what the WebSocket pushes and `GET /api/events` returns
//! (server-architecture-spec.md §3.8, webapp-client-spec.md §3).
//!
//! Every event is written to the `events` table first and then broadcast
//! in-process to connected sockets. The table is what makes the cursor
//! meaningful: a client that drops off resumes from the last id it saw,
//! over either transport, and gets exactly what it missed.
//!
//! Events say *that* something changed and where, not the new state —
//! clients re-fetch through the normal API. The exception is `message_new`,
//! which carries sender and subject so an open tab can show a notification
//! without a round trip. Nothing here goes to a third party; content-free
//! UnifiedPush pushes are built from these separately.
use serde::Serialize;
use sqlx::PgPool;
use std::sync::Arc;
use tokio::sync::{broadcast, Mutex};
use uuid::Uuid;
/// How long events are kept. A client whose cursor is older than this is
/// told to reset (reload everything) instead of replaying.
pub const RETENTION_DAYS: i32 = 7;
/// Live-broadcast buffer. A socket that falls further behind than this
/// catches up from the table instead, so it's a throughput knob, not a
/// correctness one.
const BROADCAST_CAPACITY: usize = 1024;
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
pub enum Change {
/// A message finished ingesting (body fetched, threaded, rules run).
/// `notify` is the final decision after rules — clients alert on it and
/// only on it.
MessageNew {
message_id: Uuid,
thread_id: Option<Uuid>,
account_id: Uuid,
notify: bool,
from: Option<String>,
subject: Option<String>,
},
/// Thread contents or state changed — flags, tags, folder, trash, new
/// messages that aren't notification-worthy. `None` means "could be
/// anything; reload".
MailboxChanged {
thread_ids: Option<Vec<Uuid>>,
},
OutboxChanged {
id: Uuid,
status: String,
},
/// Tags, folders, rules or accounts were edited.
ConfigChanged {
what: ConfigKind,
},
}
#[derive(Debug, Clone, Copy, Serialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ConfigKind {
Tags,
Folders,
Rules,
Accounts,
}
/// Thread-id lists longer than this are sent as "reload everything" — a
/// bulk rule run shouldn't produce a megabyte event.
const MAX_THREAD_IDS: usize = 200;
impl Change {
pub fn config(what: ConfigKind) -> Self {
Change::ConfigChanged { what }
}
pub fn threads(ids: impl IntoIterator<Item = Uuid>) -> Self {
let mut ids: Vec<Uuid> = ids.into_iter().collect();
ids.sort();
ids.dedup();
Change::MailboxChanged {
thread_ids: (ids.len() <= MAX_THREAD_IDS).then_some(ids),
}
}
fn split(&self) -> (String, serde_json::Value) {
let mut v = serde_json::to_value(self).expect("Change always serialises");
let kind = v["kind"].as_str().unwrap_or_default().to_string();
let data = v
.get_mut("data")
.map(serde_json::Value::take)
.unwrap_or_else(|| serde_json::json!({}));
(kind, data)
}
}
/// An event as stored and as sent to clients.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct Event {
pub id: i64,
#[serde(skip)]
pub user_id: Uuid,
pub kind: String,
#[serde(rename = "data")]
pub payload: serde_json::Value,
pub created_at: chrono::DateTime<chrono::Utc>,
}
#[derive(Clone)]
pub struct EventHub {
pool: PgPool,
tx: broadcast::Sender<Arc<Event>>,
/// Held across insert + broadcast so ids become visible, and are
/// broadcast, in increasing order. Without it two concurrent emits
/// could commit 8 before 7, and a client that read 8 would resume
/// past 7 forever. Emits are one short insert, so contention is cheap.
order: Arc<Mutex<()>>,
}
impl EventHub {
pub fn new(pool: PgPool) -> Self {
let (tx, _) = broadcast::channel(BROADCAST_CAPACITY);
Self {
pool,
tx,
order: Arc::new(Mutex::new(())),
}
}
pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
self.tx.subscribe()
}
/// The cursor a client with no history should start from: the last id
/// handed out. Read from the sequence rather than the table so it
/// stays correct once old events are purged, and under the ordering
/// lock so it can't name an insert that hasn't committed yet.
pub async fn head(&self) -> sqlx::Result<i64> {
let _guard = self.order.lock().await;
sqlx::query_scalar(
"SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM events_id_seq",
)
.fetch_one(&self.pool)
.await
}
/// Records and broadcasts a change. Call only after the transaction that
/// made the change has committed — otherwise a client can fetch before
/// the change is visible. Failures are logged, not returned: the change
/// itself already happened, and clients recover on their next reload.
pub async fn emit(&self, user_id: Uuid, change: Change) {
let (kind, payload) = change.split();
let _guard = self.order.lock().await;
let row: Result<Event, _> = sqlx::query_as(
"INSERT INTO events (user_id, kind, payload) VALUES ($1, $2, $3) \
RETURNING id, user_id, kind, payload, created_at",
)
.bind(user_id)
.bind(&kind)
.bind(&payload)
.fetch_one(&self.pool)
.await;
match row {
// No receivers is fine — nobody has a socket open.
Ok(event) => {
let _ = self.tx.send(Arc::new(event));
}
Err(e) => tracing::error!(error = %e, %kind, "failed to record event"),
}
}
}
/// The user's events after `since`, oldest first, capped at `limit`.
pub async fn after(
pool: &PgPool,
user_id: Uuid,
since: i64,
limit: i64,
) -> sqlx::Result<Vec<Event>> {
sqlx::query_as(
"SELECT id, user_id, kind, payload, created_at FROM events \
WHERE user_id = $1 AND id > $2 ORDER BY id LIMIT $3",
)
.bind(user_id)
.bind(since)
.bind(limit)
.fetch_all(pool)
.await
}
/// Whether events after `since` may already have been purged, so replaying
/// from it would silently miss changes. Conservative: it can say yes when
/// nothing was actually lost (e.g. ids skipped by a failed insert), which
/// only costs the client a reload.
pub async fn is_stale(pool: &PgPool, since: i64) -> sqlx::Result<bool> {
// Oldest id still kept; if the table is empty, everything up to the
// sequence's current value is gone (or never existed).
let floor: i64 = sqlx::query_scalar(
"SELECT COALESCE((SELECT MIN(id) FROM events), \
(SELECT CASE WHEN is_called THEN last_value + 1 ELSE last_value END \
FROM events_id_seq))",
)
.fetch_one(pool)
.await?;
Ok(since < floor - 1)
}
pub async fn purge_expired(pool: &PgPool) -> sqlx::Result<u64> {
Ok(
sqlx::query("DELETE FROM events WHERE created_at < now() - make_interval(days => $1)")
.bind(RETENTION_DAYS)
.execute(pool)
.await?
.rows_affected(),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn changes_split_into_kind_and_data() {
let id = Uuid::nil();
let (kind, data) = Change::OutboxChanged {
id,
status: "sent".into(),
}
.split();
assert_eq!(kind, "outbox_changed");
assert_eq!(data, serde_json::json!({ "id": id, "status": "sent" }));
let (kind, data) = Change::ConfigChanged {
what: ConfigKind::Tags,
}
.split();
assert_eq!(kind, "config_changed");
assert_eq!(data, serde_json::json!({ "what": "tags" }));
}
#[test]
fn long_thread_lists_become_reload_everything() {
let few = Change::threads([Uuid::nil(), Uuid::nil()]);
assert_eq!(
few,
Change::MailboxChanged {
thread_ids: Some(vec![Uuid::nil()])
}
);
let many = Change::threads((0..=MAX_THREAD_IDS).map(|_| Uuid::new_v4()));
assert_eq!(many, Change::MailboxChanged { thread_ids: None });
}
}
+63
View File
@@ -0,0 +1,63 @@
//! One-time repair for bodies stored before plain-text mail stopped getting
//! a synthesised HTML body (migration 0011): re-parses each flagged message
//! from its stored raw copy and keeps HTML only if it really had some.
use crate::imap_sync::parse::parse_raw_message;
use crate::storage::BlobStore;
use sqlx::PgPool;
use uuid::Uuid;
const BATCH: i64 = 200;
pub async fn run(pool: PgPool, blobs: BlobStore) {
match repair(&pool, &blobs).await {
Ok(0) => {}
Ok(n) => tracing::info!(repaired = n, "re-checked stored HTML bodies"),
Err(e) => tracing::error!(error = %e, "HTML body backfill failed"),
}
}
async fn repair(pool: &PgPool, blobs: &BlobStore) -> anyhow::Result<usize> {
let mut total = 0;
loop {
let batch: Vec<(Uuid, Option<String>)> = sqlx::query_as(
"SELECT b.message_id, m.raw_blob_ref FROM bodies b JOIN messages m ON m.id = b.message_id \
WHERE NOT b.html_checked LIMIT $1",
)
.bind(BATCH)
.fetch_all(pool)
.await?;
if batch.is_empty() {
return Ok(total);
}
for (id, raw_ref) in batch {
// Without the raw message the stored body is the best there is.
let html = match raw_ref {
Some(r) => match blobs.read(&r).await.and_then(|raw| parse_raw_message(&raw)) {
Ok(parsed) => Some(parsed.html_body),
Err(e) => {
tracing::warn!(message = %id, error = %e, "couldn't re-parse; leaving body as is");
None
}
},
None => None,
};
match html {
Some(html) => sqlx::query(
"UPDATE bodies SET html_body = $2, html_checked = true WHERE message_id = $1",
)
.bind(id)
.bind(html)
.execute(pool)
.await?,
None => {
sqlx::query("UPDATE bodies SET html_checked = true WHERE message_id = $1")
.bind(id)
.execute(pool)
.await?
}
};
total += 1;
}
}
}
+137 -22
View File
@@ -13,6 +13,7 @@
//! backlog doesn't block new-mail visibility.
use crate::crypto::CredentialCipher;
use crate::events::{Change, EventHub};
use crate::imap_sync::backoff::Backoff;
use crate::imap_sync::parse::parse_raw_message;
use crate::models::account::Account;
@@ -25,9 +26,26 @@ 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);
/// Re-issue IDLE this often even if nothing happened. Each renewal re-runs
/// the fetch pass, so it doubles as the safety-net poll the spec asks for
/// (§3.1, 5–15 min) in case a notification is ever lost — and keeps well
/// inside the ~30 min after which servers drop an IDLE session.
const IDLE_RENEW: Duration = Duration::from_secs(10 * 60);
/// Empties async-imap's side channel of unsolicited responses, reporting
/// whether any of them announced new mail. Draining also matters on its
/// own: the channel holds 100 entries and silently drops announcements once
/// full, which an undrained long-lived session eventually reaches.
fn announced_new_mail(
notices: &async_channel::Receiver<async_imap::types::UnsolicitedResponse>,
) -> bool {
use async_imap::types::UnsolicitedResponse as U;
let mut new_mail = false;
while let Ok(notice) = notices.try_recv() {
new_mail |= matches!(notice, U::Exists(_) | U::Recent(_));
}
new_mail
}
const BODY_FETCH_BATCH: i64 = 25;
type ImapSession = async_imap::Session<async_native_tls::TlsStream<tokio::net::TcpStream>>;
@@ -54,6 +72,18 @@ pub struct AccountSyncer {
pub pool: PgPool,
pub cipher: CredentialCipher,
pub blobs: BlobStore,
pub events: EventHub,
}
/// What ingesting a body produced, for the change event that follows once
/// its transaction has committed.
struct Ingested {
message_id: Uuid,
thread_id: Option<Uuid>,
arrived_live: bool,
notify: bool,
from: Option<String>,
subject: Option<String>,
}
impl AccountSyncer {
@@ -68,8 +98,11 @@ impl AccountSyncer {
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;
// {:#} includes the cause chain — "TCP connect failed"
// alone doesn't say it was DNS, a refused port or TLS.
let detail = format!("{e:#}");
tracing::warn!(account_id = %self.account.id, error = %detail, "sync connection dropped, reconnecting");
let _ = self.mark_status("error", Some(&detail)).await;
tokio::time::sleep(backoff.next_delay()).await;
}
}
@@ -191,8 +224,8 @@ impl AccountSyncer {
.execute(&mut *tx)
.await?;
sqlx::query(
"UPDATE sync_state SET uidvalidity = $2, last_synced_uid = 0, updated_at = now() \
WHERE account_id = $1",
"UPDATE sync_state SET uidvalidity = $2, last_synced_uid = 0, caught_up = false, \
updated_at = now() WHERE account_id = $1",
)
.bind(self.account.id)
.bind(server_uidvalidity)
@@ -205,20 +238,21 @@ impl AccountSyncer {
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)
/// The last UID stored, and whether the first full pass has finished.
async fn sync_position(&self) -> Result<(i64, bool)> {
Ok(sqlx::query_as(
"SELECT last_synced_uid, caught_up FROM sync_state WHERE account_id = $1",
)
.bind(self.account.id)
.fetch_one(&self.pool)
.await?)
}
/// 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 (last_uid, caught_up) = self.sync_position().await?;
let range = format!("{}:*", last_uid + 1);
let fetches: Vec<_> = session
@@ -257,8 +291,9 @@ impl AccountSyncer {
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) \
(account_id, uid, message_id, in_reply_to, subject, flags, body_fetched, \
arrived_live) \
VALUES ($1, $2, $3, $4, $5, $6, false, $7) \
ON CONFLICT (account_id, uid) DO UPDATE SET flags = EXCLUDED.flags",
)
.bind(self.account.id)
@@ -267,6 +302,7 @@ impl AccountSyncer {
.bind(&in_reply_to)
.bind(&subject)
.bind(&flags)
.bind(caught_up)
.execute(&self.pool)
.await?;
}
@@ -278,6 +314,12 @@ impl AccountSyncer {
.execute(&self.pool)
.await?;
}
if !caught_up {
sqlx::query("UPDATE sync_state SET caught_up = true WHERE account_id = $1")
.bind(self.account.id)
.execute(&self.pool)
.await?;
}
Ok(())
}
@@ -314,6 +356,9 @@ impl AccountSyncer {
.await
.context("reading UID FETCH body response")?;
// Backlog is announced once per batch rather than per message,
// so an initial sync of thousands doesn't send thousands of events.
let mut backlog_threads = Vec::new();
for f in &fetches {
let (Some(uid), Some(raw)) = (f.uid, f.body()) else {
continue;
@@ -322,14 +367,37 @@ impl AccountSyncer {
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");
match self.store_body(*row_id, raw).await {
Ok(m) if m.arrived_live => {
self.events
.emit(
self.account.user_id,
Change::MessageNew {
message_id: m.message_id,
thread_id: m.thread_id,
account_id: self.account.id,
notify: m.notify,
from: m.from,
subject: m.subject,
},
)
.await;
}
Ok(m) => backlog_threads.extend(m.thread_id),
Err(e) => {
tracing::error!(account_id = %self.account.id, uid, error = %e, "failed to store message body")
}
}
}
if !backlog_threads.is_empty() {
self.events
.emit(self.account.user_id, Change::threads(backlog_threads))
.await;
}
}
}
async fn store_body(&self, message_row_id: Uuid, raw: &[u8]) -> Result<()> {
async fn store_body(&self, message_row_id: Uuid, raw: &[u8]) -> Result<Ingested> {
let parsed = parse_raw_message(raw)?;
let (_, raw_blob_ref) = self.blobs.put(&parsed.raw).await?;
@@ -388,6 +456,12 @@ impl AccountSyncer {
.await?;
}
sqlx::query("UPDATE messages SET spam_score = $2 WHERE id = $1")
.bind(message_row_id)
.bind(crate::spam::extract_score(&parsed.headers).map(|s| s as f32))
.execute(&mut *tx)
.await?;
// Threading and rules need the full headers (References isn't in
// ENVELOPE), so they run here rather than at header ingest — the
// message may be visible for the moment between the two.
@@ -404,7 +478,7 @@ impl AccountSyncer {
)
.await?;
crate::rules::apply_rules(
let rules_say = crate::rules::apply_rules(
&mut tx,
self.account.user_id,
message_row_id,
@@ -412,8 +486,34 @@ impl AccountSyncer {
)
.await?;
// Where the message ended up after rules decides the default: new,
// unread mail that stayed in the inbox notifies; anything a rule
// filed away, junked, deleted or marked read doesn't. A notify /
// don't-notify action overrides that either way — but backlog
// never notifies, whatever the rules say.
let (thread_id, arrived_live, in_inbox_unread): (Option<Uuid>, bool, bool) =
sqlx::query_as(
r#"SELECT thread_id, arrived_live,
folder_id IS NULL AND deleted_at IS NULL AND NOT ('\Seen' = ANY(flags))
FROM messages WHERE id = $1"#,
)
.bind(message_row_id)
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
Ok(Ingested {
message_id: message_row_id,
thread_id,
arrived_live,
notify: arrived_live && rules_say.unwrap_or(in_inbox_unread),
from: parsed
.from_name
.clone()
.filter(|n| !n.trim().is_empty())
.or_else(|| parsed.from_addr.clone()),
subject: parsed.subject.clone(),
})
}
/// Issues IDLE and waits for either a mailbox change or the renewal
@@ -423,6 +523,8 @@ impl AccountSyncer {
/// 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)> {
// Cloned before idle() takes the session, so it can be read mid-IDLE.
let notices = session.unsolicited_responses.clone();
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");
@@ -433,6 +535,19 @@ impl AccountSyncer {
return Ok((false, session));
}
// A server announces new mail once per session, as an untagged
// EXISTS attached to whatever response is in flight. Mail landing
// during our own fetches, or while IDLE was starting up, was
// announced that way — async-imap files those in a side channel
// rather than waking IDLE, and the server won't repeat them. The
// wait below only sees responses from here on, so without this the
// message would sit unfetched until the next renewal.
if announced_new_mail(&notices) {
tracing::debug!(account_id = %self.account.id, "new mail announced before IDLE began");
let session = handle.done().await.context("DONE after IDLE failed")?;
return Ok((true, session));
}
let (idle_wait, _stop_source) = handle.wait_with_timeout(IDLE_RENEW);
let wait_result = idle_wait.await;
+42 -8
View File
@@ -1,28 +1,58 @@
//! Spawns and tracks one sync task per account. Polls for newly-added
//! accounts periodically rather than requiring a restart to pick them up.
//! Spawns and tracks one sync task per account; stops the task of an
//! account that was removed, and restarts the task of one that was edited
//! (it holds its own copy of the settings). Woken by the API when accounts
//! change, and polls as a fallback.
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use crate::imap_sync::connection::AccountSyncer;
use crate::models::account::Account;
use crate::storage::BlobStore;
use chrono::{DateTime, Utc};
use sqlx::PgPool;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
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();
pub async fn run(
pool: PgPool,
cipher: CredentialCipher,
blobs: BlobStore,
events: EventHub,
wake: Arc<Notify>,
) {
// Each task, with the account version (updated_at) it was started from.
let mut running: HashMap<Uuid, (tokio::task::JoinHandle<()>, DateTime<Utc>)> = HashMap::new();
loop {
running.retain(|_, handle| !handle.is_finished());
running.retain(|_, (handle, _)| !handle.is_finished());
match sqlx::query_as::<_, Account>("SELECT * FROM accounts")
.fetch_all(&pool)
.await
{
Ok(accounts) => {
// A removed account's task would otherwise retry forever
// against rows that no longer exist.
let present: HashMap<Uuid, DateTime<Utc>> =
accounts.iter().map(|a| (a.id, a.updated_at)).collect();
running.retain(|id, (handle, version)| match present.get(id) {
None => {
tracing::info!(account_id = %id, "account removed; stopping sync task");
handle.abort();
false
}
Some(current) if current != version => {
tracing::info!(account_id = %id, "account edited; restarting sync task");
handle.abort();
false
}
Some(_) => true,
});
for account in accounts {
if running.contains_key(&account.id) {
continue;
@@ -33,15 +63,19 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore) {
pool: pool.clone(),
cipher: cipher.clone(),
blobs: blobs.clone(),
events: events.clone(),
};
let id = syncer.account.id;
let (id, version) = (syncer.account.id, syncer.account.updated_at);
let handle = tokio::spawn(syncer.run());
running.insert(id, handle);
running.insert(id, (handle, version));
}
}
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
}
tokio::time::sleep(ACCOUNT_POLL_INTERVAL).await;
tokio::select! {
_ = wake.notified() => {}
_ = tokio::time::sleep(ACCOUNT_POLL_INTERVAL) => {}
}
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod backoff;
pub mod body_backfill;
pub mod connection;
pub mod manager;
pub mod parse;
+38 -1
View File
@@ -36,7 +36,14 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
.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());
// Only a real text/html part: mail-parser's body_html() otherwise
// synthesises HTML from a plain-text body, which made every plain
// message look like HTML mail to the clients.
let html_body = message
.html_part(0)
.filter(|p| p.is_text_html())
.and_then(|_| message.body_html(0))
.map(|s| s.to_string());
let attachments = message
.attachments()
@@ -131,4 +138,34 @@ body\r\n";
assert_eq!(get("x-spam-score"), vec!["5.3"]);
assert_eq!(get("from"), vec!["Bob <bob@example.com>"]);
}
#[test]
fn plain_text_mail_has_no_html_body() {
let plain = parse_raw_message(
b"From: a@example.com\r\nSubject: hi\r\nContent-Type: text/plain\r\n\r\nJust text.\r\n",
)
.unwrap();
assert_eq!(
plain.text_body.as_deref().map(str::trim),
Some("Just text.")
);
assert_eq!(plain.html_body, None, "no HTML synthesised from text");
let both = parse_raw_message(
b"From: a@example.com\r\nSubject: hi\r\nMIME-Version: 1.0\r\n\
Content-Type: multipart/alternative; boundary=b\r\n\r\n\
--b\r\nContent-Type: text/plain\r\n\r\nPlain\r\n\
--b\r\nContent-Type: text/html\r\n\r\n<p>Rich</p>\r\n--b--\r\n",
)
.unwrap();
assert!(both.html_body.unwrap().contains("<p>Rich</p>"));
// HTML-only mail still gets a text version (notifications, rules).
let html_only = parse_raw_message(
b"From: a@example.com\r\nSubject: hi\r\nContent-Type: text/html\r\n\r\n<p>Only <b>rich</b></p>\r\n",
)
.unwrap();
assert!(html_only.html_body.is_some());
assert!(html_only.text_body.unwrap().contains("rich"));
}
}
+3
View File
@@ -4,10 +4,13 @@ pub mod config;
pub mod crypto;
pub mod db;
pub mod error;
pub mod events;
pub mod imap_sync;
pub mod models;
pub mod push;
pub mod retention;
pub mod rules;
pub mod smtp;
pub mod spam;
pub mod storage;
pub mod threading;
+42 -1
View File
@@ -7,6 +7,9 @@ use tern_server::{db, imap_sync};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let _ = dotenvy::dotenv();
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
return healthcheck();
}
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
@@ -20,10 +23,20 @@ async fn main() -> anyhow::Result<()> {
let pool = db::connect(&config.database_url).await?;
let cipher = CredentialCipher::new(&config.credential_key);
let blobs = BlobStore::new(config.blob_storage_dir.clone());
let events = tern_server::events::EventHub::new(pool.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 sync_wake = std::sync::Arc::new(tokio::sync::Notify::new());
tokio::spawn(imap_sync::run(
pool.clone(),
cipher.clone(),
blobs.clone(),
events.clone(),
sync_wake.clone(),
));
tokio::spawn(imap_sync::body_backfill::run(pool.clone(), blobs.clone()));
tokio::spawn(tern_server::retention::run(
pool.clone(),
@@ -37,8 +50,12 @@ async fn main() -> anyhow::Result<()> {
cipher.clone(),
blobs.clone(),
outbox_wake.clone(),
events.clone(),
));
let pusher = tern_server::push::Pusher::new(pool.clone(), &cipher, config.push.clone()).await?;
tokio::spawn(pusher.clone().run(events.clone()));
let state = AppState {
pool,
cipher,
@@ -46,6 +63,9 @@ async fn main() -> anyhow::Result<()> {
session_ttl_hours: config.session_ttl_hours,
config: config.clone(),
outbox_wake,
sync_wake,
events,
pusher,
};
let app = api::build(state);
@@ -56,3 +76,24 @@ async fn main() -> anyhow::Result<()> {
Ok(())
}
/// `tern-server healthcheck`: exits 0 if the server on this host answers
/// `/healthz`. For the image's HEALTHCHECK, which has no curl, so that
/// `docker compose up --wait` waits until the server is really serving —
/// and fails a deploy whose server can't start.
fn healthcheck() -> anyhow::Result<()> {
use std::io::{Read, Write};
let bind = std::env::var("BIND_ADDR").unwrap_or_else(|_| "127.0.0.1:8080".to_string());
let port = bind.rsplit(':').next().unwrap_or("8080");
let mut stream = std::net::TcpStream::connect(format!("127.0.0.1:{port}"))?;
stream.set_read_timeout(Some(std::time::Duration::from_secs(3)))?;
stream.write_all(b"GET /healthz HTTP/1.0\r\nHost: localhost\r\n\r\n")?;
let mut response = String::new();
stream.read_to_string(&mut response)?;
anyhow::ensure!(
response.starts_with("HTTP/1.1 200") || response.starts_with("HTTP/1.0 200"),
"unhealthy: {}",
response.lines().next().unwrap_or("no response")
);
Ok(())
}
+18
View File
@@ -20,6 +20,7 @@ pub struct Account {
pub created_at: DateTime<Utc>,
pub email_address: Option<String>,
pub display_name: Option<String>,
pub updated_at: DateTime<Utc>,
}
impl Account {
@@ -48,6 +49,22 @@ pub struct AccountPublic {
pub email_address: Option<String>,
pub display_name: Option<String>,
pub created_at: DateTime<Utc>,
/// How syncing is going; filled in by the account list.
pub sync: Option<AccountSync>,
}
/// An account's sync health, for showing whether it's working.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct AccountSync {
#[serde(skip)]
pub account_id: Uuid,
/// pending | syncing | idle | error
pub status: String,
pub last_error: Option<String>,
pub updated_at: DateTime<Utc>,
/// The first full pass over the mailbox has finished.
pub caught_up: bool,
pub messages: i64,
}
impl From<Account> for AccountPublic {
@@ -64,6 +81,7 @@ impl From<Account> for AccountPublic {
email_address: a.email_address,
display_name: a.display_name,
created_at: a.created_at,
sync: None,
}
}
}
+307
View File
@@ -0,0 +1,307 @@
//! UnifiedPush delivery (server-architecture-spec.md §3.8): Tern acts as the
//! application server, POSTing a content-free "sync now" message to each of
//! a user's registered push endpoints when new mail should notify. The phone
//! then pulls the actual changes over the authenticated API, so no mail
//! content ever passes through the push server.
//!
//! Only `message_new` events whose `notify` is true trigger a push — that is
//! where rules' notify / don't-notify decisions take effect for Android.
pub mod webpush;
use crate::config::PushConfig;
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
use anyhow::Context;
use sqlx::PgPool;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::broadcast::error::RecvError;
use uuid::Uuid;
use webpush::{Subscription, Vapid};
/// Mail tends to arrive in bursts (a thread catching up, a list digest);
/// one wake-up covers all of it, since the phone syncs everything anyway.
const COALESCE: Duration = Duration::from_secs(2);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
/// How long a push service should hold the message for an offline phone.
const TTL_SECONDS: &str = "86400";
/// Lets a push service replace an undelivered wake-up with a newer one
/// rather than queueing both (RFC 8030 §5.4).
const TOPIC: &str = "tern-sync";
/// The payload. Deliberately says nothing about the mail itself.
const PAYLOAD: &[u8] = br#"{"kind":"sync"}"#;
#[derive(Clone)]
pub struct Pusher {
pool: PgPool,
client: reqwest::Client,
vapid: Vapid,
config: Arc<PushConfig>,
pending: Arc<Mutex<HashSet<Uuid>>>,
}
#[derive(sqlx::FromRow)]
struct Device {
id: Uuid,
endpoint: Option<String>,
p256dh: Option<String>,
auth: Option<String>,
}
/// What happened to one push attempt.
#[derive(Debug, serde::Serialize)]
pub struct Outcome {
pub delivered: bool,
/// HTTP status from the push server, if it answered.
pub status: Option<u16>,
pub error: Option<String>,
/// The push server said this endpoint no longer exists; the device
/// registration was removed.
pub removed: bool,
}
impl Pusher {
/// Loads (or creates) the server's VAPID key and builds the HTTP client.
pub async fn new(
pool: PgPool,
cipher: &CredentialCipher,
config: PushConfig,
) -> anyhow::Result<Self> {
let vapid = load_or_create_vapid(&pool, cipher, &config.vapid_subject).await?;
Self::with_key(pool, vapid, config)
}
pub fn with_key(pool: PgPool, vapid: Vapid, config: PushConfig) -> anyhow::Result<Self> {
let mut client = reqwest::Client::builder()
.timeout(REQUEST_TIMEOUT)
.user_agent(concat!("tern-server/", env!("CARGO_PKG_VERSION")));
if let Some(path) = &config.ca_cert {
let pem = std::fs::read(path)
.with_context(|| format!("reading PUSH_CA_CERT {}", path.display()))?;
for cert in reqwest::Certificate::from_pem_bundle(&pem)
.with_context(|| format!("PUSH_CA_CERT {} isn't PEM", path.display()))?
{
client = client.add_root_certificate(cert);
}
}
if config.tls_insecure {
tracing::warn!("PUSH_TLS_INSECURE is set: push server certificates are not verified");
client = client.danger_accept_invalid_certs(true);
}
Ok(Self {
pool,
client: client.build()?,
vapid,
config: Arc::new(config),
pending: Arc::default(),
})
}
/// The public key clients hand their distributor when registering.
pub fn vapid_public_key(&self) -> String {
self.vapid.public_base64()
}
/// Follows the event stream and pushes for notifying new mail. Runs for
/// the life of the server.
pub async fn run(self, events: EventHub) {
let mut rx = events.subscribe();
loop {
match rx.recv().await {
Ok(event) => {
if event.kind == "message_new" && event.payload["notify"] == true {
self.schedule(event.user_id);
}
}
// Missed events can't be told apart, so wake everyone who
// has a device rather than risk a silent phone.
Err(RecvError::Lagged(n)) => {
tracing::warn!(
missed = n,
"push dispatcher fell behind; waking all devices"
);
match sqlx::query_scalar::<_, Uuid>("SELECT DISTINCT user_id FROM devices")
.fetch_all(&self.pool)
.await
{
Ok(users) => users.into_iter().for_each(|u| self.schedule(u)),
Err(e) => tracing::error!(error = %e, "couldn't list devices"),
}
}
Err(RecvError::Closed) => return,
}
}
}
/// Pushes to the user's devices shortly, unless a push is already
/// scheduled — that one will cover this mail too.
fn schedule(&self, user_id: Uuid) {
if !self.pending.lock().expect("pending lock").insert(user_id) {
return;
}
let this = self.clone();
tokio::spawn(async move {
tokio::time::sleep(COALESCE).await;
this.pending.lock().expect("pending lock").remove(&user_id);
if let Err(e) = this.push_user(user_id).await {
tracing::error!(%user_id, error = %e, "push failed");
}
});
}
async fn push_user(&self, user_id: Uuid) -> sqlx::Result<()> {
let devices: Vec<Device> = sqlx::query_as(
"SELECT id, endpoint, p256dh, auth FROM devices \
WHERE user_id = $1 AND kind = 'unifiedpush' AND endpoint IS NOT NULL",
)
.bind(user_id)
.fetch_all(&self.pool)
.await?;
for device in devices {
self.push_device(&device).await?;
}
Ok(())
}
/// Pushes once to one of the user's devices — the settings screen's
/// "send a test notification". `None` if there's no such device.
pub async fn test(&self, user_id: Uuid, device_id: Uuid) -> sqlx::Result<Option<Outcome>> {
let device: Option<Device> = sqlx::query_as(
"SELECT id, endpoint, p256dh, auth FROM devices WHERE id = $1 AND user_id = $2",
)
.bind(device_id)
.bind(user_id)
.fetch_optional(&self.pool)
.await?;
match device {
Some(d) => self.push_device(&d).await.map(Some),
None => Ok(None),
}
}
/// Sends and records the result on the device row.
async fn push_device(&self, device: &Device) -> sqlx::Result<Outcome> {
let outcome = self.send(device).await;
if outcome.removed {
tracing::info!(device = %device.id, "push endpoint gone; removing device");
sqlx::query("DELETE FROM devices WHERE id = $1")
.bind(device.id)
.execute(&self.pool)
.await?;
} else if outcome.delivered {
sqlx::query("UPDATE devices SET last_push_at = now(), last_error = NULL WHERE id = $1")
.bind(device.id)
.execute(&self.pool)
.await?;
} else {
tracing::warn!(device = %device.id, error = ?outcome.error, "push not delivered");
sqlx::query("UPDATE devices SET last_error = $2 WHERE id = $1")
.bind(device.id)
.bind(&outcome.error)
.execute(&self.pool)
.await?;
}
Ok(outcome)
}
async fn send(&self, device: &Device) -> Outcome {
let failed = |error: String| Outcome {
delivered: false,
status: None,
error: Some(error),
removed: false,
};
let Some(endpoint) = device.endpoint.as_deref() else {
return failed("device has no endpoint".into());
};
let Ok(public_url) = reqwest::Url::parse(endpoint) else {
return failed(format!("endpoint isn't a URL: {endpoint}"));
};
let target = self.config.rewrite(endpoint);
let mut request = self
.client
.post(&target)
.header("TTL", TTL_SECONDS)
.header("Urgency", "high")
.header("Topic", TOPIC)
.header(
"Authorization",
self.vapid
.authorization(&public_url, chrono::Utc::now().timestamp()),
);
request = match (&device.p256dh, &device.auth) {
(Some(p256dh), Some(auth)) => {
let body = Subscription::from_base64(p256dh, auth)
.and_then(|sub| webpush::encrypt(&sub, PAYLOAD));
match body {
Ok(body) => request
.header("Content-Encoding", "aes128gcm")
.header("Content-Type", "application/octet-stream")
.body(body),
Err(e) => return failed(format!("couldn't encrypt: {e}")),
}
}
// A distributor without Web Push keys gets the payload as is.
_ => request
.header("Content-Type", "application/json")
.body(PAYLOAD),
};
match request.send().await {
Ok(res) if res.status().is_success() => Outcome {
delivered: true,
status: Some(res.status().as_u16()),
error: None,
removed: false,
},
Ok(res) => {
let status = res.status();
let text = res.text().await.unwrap_or_default();
Outcome {
delivered: false,
status: Some(status.as_u16()),
error: Some(format!(
"push server answered {status}: {}",
text.chars().take(200).collect::<String>()
)),
// RFC 8030 §6.4 / UnifiedPush: the subscription is gone.
removed: status == reqwest::StatusCode::NOT_FOUND
|| status == reqwest::StatusCode::GONE,
}
}
// {:#} walks the source chain, where TLS failures explain themselves.
Err(e) => failed(format!("{:#}", anyhow::Error::from(e))),
}
}
}
/// The server's VAPID key, created on first start. Concurrent first starts
/// agree on one key: the insert is a no-op if another got there first, and
/// whatever is stored is what's used.
async fn load_or_create_vapid(
pool: &PgPool,
cipher: &CredentialCipher,
subject: &str,
) -> anyhow::Result<Vapid> {
let fresh = Vapid::generate(subject.to_string());
let sealed = cipher.encrypt(&fresh.private_base64())?;
sqlx::query(
"INSERT INTO server_keys (name, ciphertext, nonce) VALUES ('vapid', $1, $2) \
ON CONFLICT (name) DO NOTHING",
)
.bind(&sealed.ciphertext)
.bind(&sealed.nonce)
.execute(pool)
.await?;
let (ciphertext, nonce): (Vec<u8>, Vec<u8>) =
sqlx::query_as("SELECT ciphertext, nonce FROM server_keys WHERE name = 'vapid'")
.fetch_one(pool)
.await?;
let private = cipher
.decrypt(&ciphertext, &nonce)
.context("decrypting the stored VAPID key — was CREDENTIAL_KEY changed?")?;
Vapid::from_private(&private, subject.to_string()).map_err(|e| anyhow::anyhow!(e))
}
+288
View File
@@ -0,0 +1,288 @@
//! Web Push message encryption (RFC 8291, `aes128gcm` from RFC 8188) and
//! VAPID signing (RFC 8292).
//!
//! UnifiedPush distributors deliver Web Push messages, and the Android
//! connector decrypts them with the key pair it registered. Tern's payload
//! is content-free anyway, but encrypting keeps it indistinguishable from
//! any other push, and some push services refuse unencrypted bodies.
use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes128Gcm, Nonce};
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use base64::Engine;
use hkdf::Hkdf;
use p256::ecdsa::signature::Signer;
use p256::ecdsa::{Signature, SigningKey};
use p256::elliptic_curve::sec1::ToEncodedPoint;
use p256::{PublicKey, SecretKey};
use rand::rngs::OsRng;
use rand::RngCore;
use sha2::Sha256;
/// One record is plenty for a content-free payload; this is the record size
/// advertised in the header, per RFC 8188 (the receiver's buffer size).
const RECORD_SIZE: u32 = 4096;
/// The subscription keys a client registered: its P-256 public key
/// (uncompressed point) and 16-byte auth secret.
pub struct Subscription {
pub p256dh: Vec<u8>,
pub auth: Vec<u8>,
}
impl Subscription {
/// From the base64url strings clients send (padding tolerated).
pub fn from_base64(p256dh: &str, auth: &str) -> Result<Self, String> {
let decode = |s: &str| {
B64.decode(s.trim_end_matches('='))
.map_err(|e| format!("not base64url: {e}"))
};
let sub = Subscription {
p256dh: decode(p256dh)?,
auth: decode(auth)?,
};
PublicKey::from_sec1_bytes(&sub.p256dh).map_err(|_| "p256dh isn't a P-256 public key")?;
if sub.auth.len() != 16 {
return Err(format!(
"auth secret must be 16 bytes, got {}",
sub.auth.len()
));
}
Ok(sub)
}
}
/// Encrypts `plaintext` for a subscription. Returns the request body; send
/// it with `Content-Encoding: aes128gcm`.
pub fn encrypt(sub: &Subscription, plaintext: &[u8]) -> Result<Vec<u8>, String> {
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
encrypt_with(sub, plaintext, &SecretKey::random(&mut OsRng), &salt)
}
fn encrypt_with(
sub: &Subscription,
plaintext: &[u8],
as_secret: &SecretKey,
salt: &[u8; 16],
) -> Result<Vec<u8>, String> {
let ua_public =
PublicKey::from_sec1_bytes(&sub.p256dh).map_err(|_| "invalid subscription public key")?;
let as_public = as_secret.public_key().to_encoded_point(false);
let as_public = as_public.as_bytes();
// RFC 8291 §3.3–3.4: combine the ECDH secret with the auth secret...
let ecdh = p256::ecdh::diffie_hellman(as_secret.to_nonzero_scalar(), ua_public.as_affine());
let mut key_info = b"WebPush: info\0".to_vec();
key_info.extend_from_slice(&sub.p256dh);
key_info.extend_from_slice(as_public);
let mut ikm = [0u8; 32];
Hkdf::<Sha256>::new(Some(&sub.auth), ecdh.raw_secret_bytes())
.expand(&key_info, &mut ikm)
.map_err(|e| e.to_string())?;
// ...then derive the content key and nonce as RFC 8188 does.
let hk = Hkdf::<Sha256>::new(Some(salt), &ikm);
let mut cek = [0u8; 16];
let mut nonce = [0u8; 12];
hk.expand(b"Content-Encoding: aes128gcm\0", &mut cek)
.map_err(|e| e.to_string())?;
hk.expand(b"Content-Encoding: nonce\0", &mut nonce)
.map_err(|e| e.to_string())?;
// A single, final record: the content followed by the 0x02 delimiter.
let mut record = plaintext.to_vec();
record.push(2);
let ciphertext = Aes128Gcm::new_from_slice(&cek)
.map_err(|e| e.to_string())?
.encrypt(Nonce::from_slice(&nonce), record.as_slice())
.map_err(|e| e.to_string())?;
// Header: salt, record size, key id (the sender's public key).
let mut body = Vec::with_capacity(16 + 4 + 1 + as_public.len() + ciphertext.len());
body.extend_from_slice(salt);
body.extend_from_slice(&RECORD_SIZE.to_be_bytes());
body.push(as_public.len() as u8);
body.extend_from_slice(as_public);
body.extend_from_slice(&ciphertext);
Ok(body)
}
/// The server's VAPID key (RFC 8292), which identifies Tern to push
/// services that require it. One key for the whole server, generated on
/// first start and kept in the database.
#[derive(Clone)]
pub struct Vapid {
key: SigningKey,
subject: String,
}
impl Vapid {
pub fn generate(subject: String) -> Self {
Self {
key: SigningKey::random(&mut OsRng),
subject,
}
}
pub fn from_private(private_b64: &str, subject: String) -> Result<Self, String> {
let bytes = B64.decode(private_b64).map_err(|e| e.to_string())?;
let key = SigningKey::from_slice(&bytes).map_err(|e| e.to_string())?;
Ok(Self { key, subject })
}
pub fn private_base64(&self) -> String {
B64.encode(self.key.to_bytes())
}
/// The public key clients pass to their distributor when registering:
/// an uncompressed P-256 point, base64url without padding.
pub fn public_base64(&self) -> String {
B64.encode(self.key.verifying_key().to_encoded_point(false).as_bytes())
}
/// The `Authorization` header value for a push to `endpoint`. The
/// audience is the endpoint's origin — as the push service knows
/// itself, so it must be the URL the client registered, not a
/// rewritten internal one.
pub fn authorization(&self, endpoint: &reqwest::Url, now: i64) -> String {
let aud = endpoint.origin().ascii_serialization();
let header = B64.encode(br#"{"typ":"JWT","alg":"ES256"}"#);
let claims = B64.encode(
serde_json::json!({ "aud": aud, "exp": now + 12 * 3600, "sub": self.subject })
.to_string(),
);
let signing_input = format!("{header}.{claims}");
let signature: Signature = self.key.sign(signing_input.as_bytes());
format!(
"vapid t={signing_input}.{}, k={}",
B64.encode(signature.to_bytes()),
self.public_base64()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use aes_gcm::aead::Aead;
use p256::ecdsa::signature::Verifier;
use p256::ecdsa::VerifyingKey;
fn b64(s: &str) -> Vec<u8> {
B64.decode(s.replace(' ', "")).unwrap()
}
/// RFC 8291 Appendix A, end to end: fixed sender key and salt must
/// reproduce the RFC's exact message.
#[test]
fn matches_rfc8291_example() {
let sub = Subscription {
p256dh: b64("BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"),
auth: b64("BTBZMqHH6r4Tts7J_aSIgg"),
};
let as_secret =
SecretKey::from_slice(&b64("yfWPiYE-n46HLnH0KqZOF1fJJU3MYrct3AELtAQ-oRw")).unwrap();
let salt: [u8; 16] = b64("DGv6ra1nlYgDCS1FRnbzlw").try_into().unwrap();
let body = encrypt_with(
&sub,
b"When I grow up, I want to be a watermelon",
&as_secret,
&salt,
)
.unwrap();
let expected = [
"DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27ml",
"mlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8",
]
.concat();
let ciphertext =
"8pfeW0KbunFT06SuDKoJH9Ql87S1QUrdirN6GcG7sFz1y1sqLgVi1VhjVkHsUoEsbI_0LpXMuGvnzQ";
assert_eq!(B64.encode(&body[..86]), expected, "header");
assert_eq!(B64.encode(&body[86..]), ciphertext, "ciphertext");
}
/// The other direction, as the phone does it: a random key and salt
/// still decrypt with the subscriber's private key.
#[test]
fn subscriber_can_decrypt_a_random_message() {
let ua_secret = SecretKey::random(&mut OsRng);
let sub = Subscription {
p256dh: ua_secret
.public_key()
.to_encoded_point(false)
.as_bytes()
.to_vec(),
auth: vec![7; 16],
};
let body = encrypt(&sub, b"{\"kind\":\"sync\"}").unwrap();
let salt = &body[..16];
let as_public = PublicKey::from_sec1_bytes(&body[21..86]).unwrap();
let ecdh = p256::ecdh::diffie_hellman(ua_secret.to_nonzero_scalar(), as_public.as_affine());
let mut info = b"WebPush: info\0".to_vec();
info.extend_from_slice(&sub.p256dh);
info.extend_from_slice(&body[21..86]);
let mut ikm = [0u8; 32];
Hkdf::<Sha256>::new(Some(&sub.auth), ecdh.raw_secret_bytes())
.expand(&info, &mut ikm)
.unwrap();
let hk = Hkdf::<Sha256>::new(Some(salt), &ikm);
let (mut cek, mut nonce) = ([0u8; 16], [0u8; 12]);
hk.expand(b"Content-Encoding: aes128gcm\0", &mut cek)
.unwrap();
hk.expand(b"Content-Encoding: nonce\0", &mut nonce).unwrap();
let plain = Aes128Gcm::new_from_slice(&cek)
.unwrap()
.decrypt(Nonce::from_slice(&nonce), &body[86..])
.unwrap();
assert_eq!(plain, b"{\"kind\":\"sync\"}\x02");
}
#[test]
fn subscriptions_are_validated() {
let good_key = B64.encode(
SecretKey::random(&mut OsRng)
.public_key()
.to_encoded_point(false)
.as_bytes(),
);
assert!(Subscription::from_base64(&good_key, "BTBZMqHH6r4Tts7J_aSIgg").is_ok());
assert!(Subscription::from_base64(&good_key, "BTBZMqHH6r4Tts7J_aSIgg==").is_ok());
assert!(Subscription::from_base64("AAAA", "BTBZMqHH6r4Tts7J_aSIgg").is_err());
assert!(Subscription::from_base64(&good_key, "c2hvcnQ").is_err());
}
#[test]
fn vapid_header_is_a_verifiable_es256_jwt() {
let vapid = Vapid::generate("mailto:admin@example.org".into());
let restored =
Vapid::from_private(&vapid.private_base64(), "mailto:admin@example.org".into())
.unwrap();
assert_eq!(restored.public_base64(), vapid.public_base64());
let url = reqwest::Url::parse("https://push.example.net:8443/up/abc?up=1").unwrap();
let header = vapid.authorization(&url, 1_000_000);
let (t, k) = header
.strip_prefix("vapid t=")
.and_then(|r| r.split_once(", k="))
.unwrap();
assert_eq!(k, vapid.public_base64());
let (signing_input, sig) = t.rsplit_once('.').unwrap();
let claims: serde_json::Value = serde_json::from_slice(
&B64.decode(signing_input.split('.').nth(1).unwrap())
.unwrap(),
)
.unwrap();
assert_eq!(claims["aud"], "https://push.example.net:8443");
assert_eq!(claims["exp"], 1_000_000 + 12 * 3600);
assert_eq!(claims["sub"], "mailto:admin@example.org");
let key = VerifyingKey::from_sec1_bytes(&B64.decode(k).unwrap()).unwrap();
let sig = Signature::from_slice(&B64.decode(sig).unwrap()).unwrap();
assert!(key.verify(signing_input.as_bytes(), &sig).is_ok());
}
}
+15 -9
View File
@@ -21,20 +21,26 @@ const INTERVAL: Duration = Duration::from_secs(60 * 60);
const BATCH: i64 = 500;
const BLOB_GRACE: Duration = Duration::from_secs(60 * 60);
/// Hourly housekeeping: expired Trash, and change events older than
/// clients are expected to resume from (`events::RETENTION_DAYS`).
pub async fn run(pool: PgPool, blobs: BlobStore, retention_days: u32) {
if retention_days == 0 {
tracing::info!("trash retention disabled (TRASH_RETENTION_DAYS=0)");
return;
}
loop {
match purge(&pool, &blobs, retention_days).await {
Ok(0) => {}
Ok(n) => tracing::info!(
purged = n,
retention_days,
"purged expired messages from trash"
),
Err(e) => tracing::error!(error = %e, "trash purge failed"),
if retention_days > 0 {
match purge(&pool, &blobs, retention_days).await {
Ok(0) => {}
Ok(n) => tracing::info!(
purged = n,
retention_days,
"purged expired messages from trash"
),
Err(e) => tracing::error!(error = %e, "trash purge failed"),
}
}
if let Err(e) = crate::events::purge_expired(&pool).await {
tracing::error!(error = %e, "event purge failed");
}
tokio::time::sleep(INTERVAL).await;
}
+215 -23
View File
@@ -45,9 +45,11 @@ pub enum Field {
Recipients,
Subject,
Body,
/// Any header by name, e.g. List-Id, or the PMG spam headers phase 6
/// will use.
/// Any header by name, e.g. List-Id.
Header,
/// The spam filter's score, read from whichever spam header the
/// message carries (see `crate::spam`). Numeric comparisons only.
SpamScore,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -97,11 +99,20 @@ pub enum Action {
folder_id: Option<Uuid>,
},
Archive,
/// Move to the system Junk folder — "report spam". Not-spam is a
/// `move` back to the inbox.
Junk,
MarkRead,
MarkUnread,
/// Soft delete — to Trash, restorable.
Delete,
Restore,
/// Alert about this message even though it didn't stay in the inbox
/// (e.g. filed straight into a folder by an earlier action).
Notify,
/// Don't alert about this message — it still arrives and shows as
/// unread, it just doesn't ping anyone.
DontNotify,
}
impl Action {
@@ -111,10 +122,19 @@ impl Action {
Action::Tag { .. }
| Action::Move { .. }
| Action::Archive
| Action::Junk
| Action::MarkRead
| Action::Delete
| Action::Notify
| Action::DontNotify
)
}
/// Actions that only mean something while a message is being ingested.
/// They're rule-only, and a no-op when a rule is run on existing mail.
fn is_notification(&self) -> bool {
matches!(self, Action::Notify | Action::DontNotify)
}
}
/// What a rule can see about a message.
@@ -126,6 +146,9 @@ pub struct Facts {
pub body: String,
/// Lowercased names; a header can repeat (Received, …).
pub headers: Vec<(String, String)>,
/// None when the message carries no spam header at all — PMG only adds
/// one from spam level 3 by default — which is "not flagged", not 0.
pub spam_score: Option<f64>,
}
impl Facts {
@@ -142,6 +165,7 @@ impl Facts {
.or_else(|| p.html_body.clone())
.unwrap_or_default(),
headers: p.headers.clone(),
spam_score: crate::spam::extract_score(&p.headers),
}
}
}
@@ -183,6 +207,13 @@ pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) ->
if t.field == Field::Header && t.header.as_deref().map(str::trim).unwrap_or("").is_empty() {
return Err("a header condition needs a header name".into());
}
if t.field == Field::SpamScore
&& !matches!(t.op, Op::GreaterThan | Op::LessThan | Op::Exists)
{
return Err(
"spam score can only be compared as a number (greater than, less than) or tested for presence".into(),
);
}
match t.op {
Op::Matches => {
compile_pattern(&t.value)?;
@@ -210,6 +241,8 @@ pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) ->
if let Some(a) = actions.iter().find(|a| !a.allowed_in_rules()) {
return Err(format!("{a:?} isn't available as a rule action"));
}
} else if let Some(a) = actions.iter().find(|a| a.is_notification()) {
return Err(format!("{a:?} only applies to incoming mail, in a rule"));
}
Ok(())
}
@@ -241,7 +274,7 @@ impl CompiledRule {
self.conditions
.tests
.iter()
.any(|t| t.field == Field::Header)
.any(|t| matches!(t.field, Field::Header | Field::SpamScore))
}
pub fn matches(&self, facts: &Facts) -> bool {
@@ -259,6 +292,17 @@ impl CompiledRule {
}
fn eval_test(t: &Test, re: Option<&Regex>, facts: &Facts) -> bool {
if t.field == Field::SpamScore {
let threshold = t.value.trim().parse::<f64>().ok();
return match (&t.op, facts.spam_score, threshold) {
(Op::Exists, score, _) => score.is_some(),
(Op::GreaterThan, Some(score), Some(n)) => score > n,
(Op::LessThan, Some(score), Some(n)) => score < n,
// No score means the filter didn't flag it: not over any
// threshold, and — deliberately — not "under" one either.
_ => false,
};
}
let recipients;
let values: Vec<&str> = match t.field {
Field::From => vec![&facts.from],
@@ -270,6 +314,7 @@ fn eval_test(t: &Test, re: Option<&Regex>, facts: &Facts) -> bool {
}
Field::Subject => vec![&facts.subject],
Field::Body => vec![&facts.body],
Field::SpamScore => unreachable!("spam score is compared numerically above"),
Field::Header => {
let name = t.header.as_deref().unwrap_or("").trim().to_lowercase();
facts
@@ -301,12 +346,18 @@ fn cmp_number(value: &str, threshold: &str) -> Option<(f64, f64)> {
/// the ingest transaction. A rule that no longer compiles (e.g. written
/// before a validation change) is skipped and logged rather than blocking
/// mail.
///
/// Returns the rules' say on notifying: `Some(true)` for notify,
/// `Some(false)` for don't-notify, `None` if no matching rule expressed
/// one. When several do, the last one applied wins — the same way a later
/// `move` overrides an earlier one.
pub async fn apply_rules(
tx: &mut Transaction<'_, Postgres>,
user_id: Uuid,
message_row_id: Uuid,
facts: &Facts,
) -> sqlx::Result<()> {
) -> sqlx::Result<Option<bool>> {
let mut notify = None;
let rows: Vec<StoredRule> = sqlx::query_as(
"SELECT id, conditions, actions, stop_after_match FROM rules \
WHERE user_id = $1 AND enabled ORDER BY priority, created_at",
@@ -334,11 +385,20 @@ pub async fn apply_rules(
}
tracing::debug!(rule_id = %id, message = %message_row_id, "rule matched");
apply_actions(tx, user_id, &[message_row_id], &rule.actions).await?;
notify = notification_choice(&rule.actions).or(notify);
if stop_after_match {
break;
}
}
Ok(())
Ok(notify)
}
fn notification_choice(actions: &[Action]) -> Option<bool> {
actions.iter().rev().find_map(|a| match a {
Action::Notify => Some(true),
Action::DontNotify => Some(false),
_ => None,
})
}
#[derive(sqlx::FromRow)]
@@ -350,6 +410,7 @@ struct ExistingMessage {
cc_addrs: Vec<String>,
subject: Option<String>,
raw_blob_ref: Option<String>,
spam_score: Option<f32>,
text_body: Option<String>,
html_body: Option<String>,
}
@@ -387,7 +448,7 @@ pub async fn run_on_existing(
loop {
let page: Vec<ExistingMessage> = sqlx::query_as(
"SELECT m.id, m.from_addr, m.from_name, m.to_addrs, m.cc_addrs, m.subject, \
m.raw_blob_ref, b.text_body, b.html_body \
m.raw_blob_ref, m.spam_score, b.text_body, b.html_body \
FROM messages m \
JOIN accounts a ON a.id = m.account_id \
LEFT JOIN bodies b ON b.message_id = m.id \
@@ -428,6 +489,12 @@ pub async fn run_on_existing(
.clone()
.or_else(|| m.html_body.clone())
.unwrap_or_default(),
// Stored at ingest; mail from before spam scores were
// extracted has none, so fall back to its re-parsed headers.
spam_score: m
.spam_score
.map(f64::from)
.or_else(|| crate::spam::extract_score(&headers)),
headers,
};
if rule.matches(&facts) {
@@ -504,11 +571,16 @@ pub async fn apply_actions(
.execute(&mut **tx)
.await?;
}
Action::Archive => {
let archive = archive_folder(tx, user_id).await?;
Action::Archive | Action::Junk => {
let which = if *action == Action::Junk {
SystemFolder::Junk
} else {
SystemFolder::Archive
};
let folder = system_folder(tx, user_id, which).await?;
sqlx::query("UPDATE messages SET folder_id = $2 WHERE id = ANY($1)")
.bind(message_ids)
.bind(archive)
.bind(folder)
.execute(&mut **tx)
.await?;
}
@@ -539,35 +611,75 @@ pub async fn apply_actions(
.execute(&mut **tx)
.await?;
}
// Decided by the caller from `apply_rules`' return value.
Action::Notify | Action::DontNotify => {}
}
}
Ok(())
}
/// The user's Archive folder, created on first use. An existing folder the
/// user happened to name "Archive" is adopted rather than colliding with it.
pub async fn archive_folder(
#[derive(Clone, Copy)]
pub enum SystemFolder {
Archive,
Junk,
}
impl SystemFolder {
fn role(self) -> &'static str {
match self {
SystemFolder::Archive => "archive",
SystemFolder::Junk => "junk",
}
}
fn default_name(self) -> &'static str {
match self {
SystemFolder::Archive => "Archive",
SystemFolder::Junk => "Junk",
}
}
}
/// A system folder (Archive, Junk), created on first use. A plain folder
/// the user happened to give the same name is adopted rather than colliding
/// with it — but never one that's already a *different* system folder,
/// which would otherwise let "Junk" steal the role of an Archive folder the
/// user had renamed to "Junk".
pub async fn system_folder(
tx: &mut Transaction<'_, Postgres>,
user_id: Uuid,
which: SystemFolder,
) -> sqlx::Result<Uuid> {
if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>(
"SELECT id FROM folders WHERE user_id = $1 AND role = 'archive'",
)
.bind(user_id)
.fetch_optional(&mut **tx)
.await?
if let Some(id) =
sqlx::query_scalar::<_, Uuid>("SELECT id FROM folders WHERE user_id = $1 AND role = $2")
.bind(user_id)
.bind(which.role())
.fetch_optional(&mut **tx)
.await?
{
return Ok(id);
}
let (id,): (Uuid,) = sqlx::query_as(
"INSERT INTO folders (user_id, name, role) VALUES ($1, 'Archive', 'archive') \
ON CONFLICT (user_id, name) DO UPDATE SET role = 'archive' \
let adopted: Option<Uuid> = sqlx::query_scalar(
"INSERT INTO folders (user_id, name, role) VALUES ($1, $2, $3) \
ON CONFLICT (user_id, name) DO UPDATE SET role = EXCLUDED.role WHERE folders.role IS NULL \
RETURNING id",
)
.bind(user_id)
.fetch_one(&mut **tx)
.bind(which.default_name())
.bind(which.role())
.fetch_optional(&mut **tx)
.await?;
Ok(id)
if let Some(id) = adopted {
return Ok(id);
}
// The name belongs to another system folder: take a distinct one.
sqlx::query_scalar(
"INSERT INTO folders (user_id, name, role) VALUES ($1, $2 || ' (' || $3 || ')', $3) RETURNING id",
)
.bind(user_id)
.bind(which.default_name())
.bind(which.role())
.fetch_one(&mut **tx)
.await
}
/// Whether every tag and folder an action list references belongs to the
@@ -612,6 +724,7 @@ mod tests {
("received".into(), "from a".into()),
("received".into(), "from relay.example.net".into()),
],
spam_score: None,
}
}
@@ -800,6 +913,50 @@ mod tests {
assert_eq!(serde_json::from_str::<Vec<Action>>(&json).unwrap(), a);
}
fn spam(op: Op, value: &str) -> Test {
Test {
field: Field::SpamScore,
header: None,
op,
value: value.into(),
negate: false,
}
}
#[test]
fn spam_score_compares_numerically() {
// facts() carries PMG-less headers: X-Spam-Score 5.3 and a
// SpamAssassin status of 7.25; extract_score prefers the bare score.
let mut f = facts();
f.spam_score = crate::spam::extract_score(&f.headers);
assert_eq!(f.spam_score, Some(5.3));
assert!(rule(Match::All, vec![spam(Op::GreaterThan, "5")]).matches(&f));
assert!(!rule(Match::All, vec![spam(Op::GreaterThan, "6")]).matches(&f));
assert!(rule(Match::All, vec![spam(Op::Exists, "")]).matches(&f));
}
#[test]
fn unscored_mail_is_neither_over_nor_under_a_threshold() {
let mut f = facts();
f.spam_score = None;
assert!(!rule(Match::All, vec![spam(Op::GreaterThan, "0")]).matches(&f));
assert!(!rule(Match::All, vec![spam(Op::LessThan, "100")]).matches(&f));
assert!(!rule(Match::All, vec![spam(Op::Exists, "")]).matches(&f));
}
#[test]
fn spam_score_rejects_text_comparisons() {
let bad = validate(
&Conditions {
match_: Match::All,
tests: vec![spam(Op::Contains, "5")],
},
&[Action::Junk],
true,
);
assert!(bad.is_err());
}
#[test]
fn stop_is_no_longer_an_action() {
// It's a rule option now (stop_after_match). A submitted
@@ -819,4 +976,39 @@ mod tests {
)
.needs_headers());
}
#[test]
fn notification_actions_are_rule_only_and_last_one_wins() {
let only = |actions: Vec<Action>, for_rule: bool| {
let tests = if for_rule {
vec![test(Field::Subject, Op::Contains, "x")]
} else {
vec![]
};
validate(
&Conditions {
match_: Match::All,
tests,
},
&actions,
for_rule,
)
};
assert!(only(vec![Action::DontNotify], true).is_ok());
assert!(only(vec![Action::Archive, Action::Notify], true).is_ok());
assert!(
only(vec![Action::DontNotify], false).is_err(),
"a thread action can't suppress a notification that already happened"
);
assert_eq!(notification_choice(&[Action::Archive]), None);
assert_eq!(
notification_choice(&[Action::Notify, Action::MarkRead, Action::DontNotify]),
Some(false)
);
assert_eq!(
serde_json::to_string(&Action::DontNotify).unwrap(),
r#"{"type":"dont_notify"}"#
);
}
}
+35 -1
View File
@@ -9,6 +9,7 @@
//! clients. True exactly-once isn't achievable over SMTP.
use crate::crypto::CredentialCipher;
use crate::events::{Change, EventHub};
use crate::models::account::Account;
use crate::models::outbox::OutboxItem;
use crate::smtp::compose::{self, Draft, Sender};
@@ -65,7 +66,13 @@ pub fn classify(err: &mail_send::Error) -> Failure {
}
}
pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake: Arc<Notify>) {
pub async fn run(
pool: PgPool,
cipher: CredentialCipher,
blobs: BlobStore,
wake: Arc<Notify>,
events: EventHub,
) {
if let Err(e) = recover_stale(&pool).await {
tracing::error!(error = %e, "failed to recover stale outbox items");
}
@@ -79,6 +86,7 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake:
// the row stays 'sending' and recover_stale picks it up.
tracing::error!(outbox_id = %id, error = %e, "failed to record send outcome");
}
announce(&pool, &events, id).await;
continue;
}
Ok(None) => {}
@@ -92,6 +100,32 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake:
}
}
/// Tells the sender's clients how the attempt went — and, once sent, that
/// the conversation it belongs to has a new message.
async fn announce(pool: &PgPool, events: &EventHub, id: uuid::Uuid) {
let row: Result<Option<(uuid::Uuid, String, Option<uuid::Uuid>)>, _> = sqlx::query_as(
"SELECT o.user_id, o.status, m.thread_id FROM outbox o \
LEFT JOIN messages m ON m.id = o.sent_message_id WHERE o.id = $1",
)
.bind(id)
.fetch_optional(pool)
.await;
match row {
Ok(Some((user_id, status, thread_id))) => {
events
.emit(user_id, Change::OutboxChanged { id, status })
.await;
if let Some(thread_id) = thread_id {
events.emit(user_id, Change::threads([thread_id])).await;
}
}
Ok(None) => {}
Err(e) => {
tracing::error!(outbox_id = %id, error = %e, "failed to read outbox item for event")
}
}
}
async fn recover_stale(pool: &PgPool) -> anyhow::Result<()> {
let recovered = sqlx::query(
"UPDATE outbox SET status = 'pending', next_attempt_at = now(), updated_at = now() \
+134
View File
@@ -0,0 +1,134 @@
//! Spam score extraction from filter headers (server-architecture-spec.md
//! §3.5, build-order phase 6).
//!
//! Proxmox Mail Gateway runs SpamAssassin and reports through headers whose
//! names are configurable, so this recognises the formats actually seen in
//! the wild rather than one fixed header:
//!
//! - PMG's `X-SPAM-LEVEL: Spam detection results: 8` — folded across lines,
//! with each matching rule and its score listed after the total.
//! - `X-Spam-Score: 5.3` — a bare number.
//! - `X-Spam-Status: Yes, score=7.2 required=5.0 …` — SpamAssassin's status.
//! - `X-Spam-Level: *******` — SpamAssassin's star bar, one per point.
//!
//! Note the name collision: PMG and SpamAssassin both use X-Spam-Level (header
//! names are case-insensitive), for completely different formats. Taking
//! "the first number in the header" would work for PMG and read nothing
//! from the star bar, so each format is matched explicitly.
//!
//! PMG only adds its header from spam level 3 upwards by default, so mail
//! below that has no score — `None`, meaning "not flagged", not "zero".
use regex::Regex;
use std::sync::LazyLock;
static PMG_RESULTS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)spam detection results:\s*(-?\d+(?:\.\d+)?)").unwrap());
static STATUS_SCORE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)\bscore=(-?\d+(?:\.\d+)?)").unwrap());
static BARE_NUMBER: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(-?\d+(?:\.\d+)?)\s*$").unwrap());
fn values_of<'a>(headers: &'a [(String, String)], name: &'a str) -> impl Iterator<Item = &'a str> {
headers
.iter()
.filter(move |(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
/// The message's spam score, from the most specific header present.
/// `headers` are (lowercased name, unfolded value) pairs.
pub fn extract_score(headers: &[(String, String)]) -> Option<f64> {
let values = |name: &'static str| values_of(headers, name);
// PMG's detailed result, the one this deployment is built around.
for v in values("x-spam-level") {
if let Some(c) = PMG_RESULTS.captures(v) {
return c[1].parse().ok();
}
}
for v in values("x-spam-score") {
if let Some(c) = BARE_NUMBER.captures(v) {
return c[1].parse().ok();
}
}
for v in values("x-spam-status") {
if let Some(c) = STATUS_SCORE.captures(v) {
return c[1].parse().ok();
}
}
// SpamAssassin's star bar is the least precise (whole points, floored),
// so it's the last resort.
for v in values("x-spam-level") {
let v = v.trim();
if !v.is_empty() && v.chars().all(|c| c == '*') {
return Some(v.len() as f64);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn h(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
pairs
.iter()
.map(|(n, v)| (n.to_string(), v.to_string()))
.collect()
}
#[test]
fn pmg_detection_results_take_the_total_not_a_rule_score() {
// As unfolded by the parser: total first, then per-rule scores —
// including negative ones that must not be mistaken for the total.
let pmg = "Spam detection results: 8 DKIM_SIGNED 0.1 Message has a DKIM or DK signature, not necessarily valid DKIM_VALID -0.1 Message has at least one valid DKIM or DK signature";
assert_eq!(extract_score(&h(&[("x-spam-level", pmg)])), Some(8.0));
assert_eq!(
extract_score(&h(&[("x-spam-level", "Spam detection results: -1.5")])),
Some(-1.5)
);
}
#[test]
fn spamassassin_star_bar_counts_stars() {
assert_eq!(extract_score(&h(&[("x-spam-level", "*******")])), Some(7.0));
}
#[test]
fn bare_score_and_status_formats() {
assert_eq!(extract_score(&h(&[("x-spam-score", "5.3")])), Some(5.3));
assert_eq!(
extract_score(&h(&[(
"x-spam-status",
"Yes, score=7.25 required=5.0 tests=BAYES_99"
)])),
Some(7.25)
);
assert_eq!(
extract_score(&h(&[("x-spam-status", "No, score=1.41")])),
Some(1.41)
);
}
#[test]
fn pmg_wins_over_less_precise_headers() {
let both = h(&[
("x-spam-level", "****"),
("x-spam-status", "Yes, score=4.9"),
("x-spam-level", "Spam detection results: 6"),
]);
assert_eq!(extract_score(&both), Some(6.0));
}
#[test]
fn unflagged_mail_has_no_score_rather_than_zero() {
assert_eq!(
extract_score(&h(&[("subject", "hi"), ("x-spam-flag", "NO")])),
None
);
// Not a star bar, not a number: ignored rather than guessed at.
assert_eq!(extract_score(&h(&[("x-spam-score", "high")])), None);
}
}
+44
View File
@@ -24,6 +24,13 @@ fn test_router() -> axum::Router {
.expect("lazy pool");
let state = tern_server::api::AppState {
events: tern_server::events::EventHub::new(pool.clone()),
pusher: tern_server::push::Pusher::with_key(
pool.clone(),
tern_server::push::webpush::Vapid::generate("mailto:test@example.org".into()),
Default::default(),
)
.expect("pusher"),
pool,
cipher: tern_server::crypto::CredentialCipher::new(&[0u8; 32]),
blobs: tern_server::storage::BlobStore::new(std::path::PathBuf::from("/tmp/tern-test")),
@@ -35,8 +42,11 @@ fn test_router() -> axum::Router {
blob_storage_dir: std::path::PathBuf::from("/tmp/tern-test"),
session_ttl_hours: 1,
trash_retention_days: 30,
open_registration: false,
push: Default::default(),
},
outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
sync_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
};
tern_server::api::build(state)
@@ -60,6 +70,7 @@ async fn parameterised_routes_match() {
("GET", format!("/api/messages/{id}")),
("GET", format!("/api/threads/{id}")),
("DELETE", format!("/api/accounts/{id}")),
("PUT", format!("/api/accounts/{id}")),
("POST", format!("/api/threads/{id}/read")),
("PUT", format!("/api/outbox/{id}")),
("DELETE", format!("/api/outbox/{id}")),
@@ -72,6 +83,9 @@ async fn parameterised_routes_match() {
("PUT", format!("/api/rules/{id}")),
("DELETE", format!("/api/rules/{id}")),
("POST", format!("/api/rules/{id}/run")),
("PUT", format!("/api/devices/{id}")),
("DELETE", format!("/api/devices/{id}")),
("POST", format!("/api/devices/{id}/test")),
] {
let status = status_for(method, &uri).await;
assert_ne!(
@@ -91,6 +105,9 @@ async fn collection_routes_match() {
"/api/messages",
"/api/threads",
"/api/events",
"/api/ws",
"/api/push",
"/api/devices",
"/api/outbox",
"/api/tags",
"/api/rules",
@@ -117,3 +134,30 @@ async fn unknown_route_still_404s() {
"sanity check: a genuinely missing route should 404"
);
}
/// The deployed webapp lives on another origin and sends `Authorization`.
/// Browsers don't let `Access-Control-Allow-Headers: *` cover that header,
/// so it has to be named in the preflight answer.
#[tokio::test]
async fn cors_preflight_allows_the_authorization_header() {
let request = Request::builder()
.method("OPTIONS")
.uri("/api/threads")
.header("Origin", "https://tern.mtps.pl")
.header("Access-Control-Request-Method", "GET")
.header("Access-Control-Request-Headers", "authorization")
.body(Body::empty())
.unwrap();
let response = test_router().oneshot(request).await.unwrap();
assert!(response.status().is_success());
let allowed = response
.headers()
.get("access-control-allow-headers")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_lowercase();
assert!(
allowed.contains("authorization"),
"allowed headers: {allowed:?}"
);
}