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>
This commit is contained in:
Mateusz PstruchaandClaude Opus 5.5 committed 2026-09-23 19:46:33 +02:00
1 parent 4a2e32cc6f
commit b718bc4c3a
17 files changed
+1411 -37

No files matched your search

+14
View File
@@ -11,9 +11,23 @@ BIND_ADDR=127.0.0.1:8080
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
# 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
Generated
+430 -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",
]
@@ -265,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"
@@ -365,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"
@@ -373,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]]
@@ -383,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",
@@ -482,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"
@@ -521,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"
@@ -528,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"
@@ -601,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"
@@ -610,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"
@@ -696,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"
@@ -861,6 +973,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
"zeroize",
]
[[package]]
@@ -880,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]]
@@ -905,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]]
@@ -975,7 +1114,7 @@ dependencies = [
"idna",
"ipnet",
"once_cell",
"rand",
"rand 0.8.8",
"ring",
"rustls 0.21.12",
"rustls-pemfile 1.0.4",
@@ -1000,7 +1139,7 @@ dependencies = [
"lru-cache",
"once_cell",
"parking_lot",
"rand",
"rand 0.8.8",
"resolv-conf",
"rustls 0.21.12",
"smallvec",
@@ -1100,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]]
@@ -1108,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]]
@@ -1404,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"
@@ -1484,7 +1654,7 @@ dependencies = [
"mail-auth",
"mail-builder",
"md5",
"rand",
"rand 0.8.8",
"rustls 0.23.45",
"rustls-pki-types",
"smtp-proto",
@@ -1637,7 +1807,7 @@ dependencies = [
"num-integer",
"num-iter",
"num-traits",
"rand",
"rand 0.8.8",
"smallvec",
"zeroize",
]
@@ -1732,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"
@@ -1768,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",
]
@@ -1868,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",
]
@@ -1897,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"
@@ -1915,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"
@@ -1944,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]]
@@ -1954,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]]
@@ -1966,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"
@@ -2013,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"
@@ -2046,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"
@@ -2128,6 +2467,7 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"web-time",
"zeroize",
]
@@ -2189,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"
@@ -2291,7 +2645,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -2302,7 +2656,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -2338,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]]
@@ -2522,7 +2876,7 @@ dependencies = [
"memchr",
"once_cell",
"percent-encoding",
"rand",
"rand 0.8.8",
"rsa",
"serde",
"sha1",
@@ -2562,7 +2916,7 @@ dependencies = [
"md-5",
"memchr",
"once_cell",
"rand",
"rand 0.8.8",
"serde",
"serde_json",
"sha2",
@@ -2663,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"
@@ -2692,6 +3049,7 @@ dependencies = [
name = "tern-server"
version = "0.7.0"
dependencies = [
"aes-gcm",
"anyhow",
"argon2",
"async-channel 2.5.0",
@@ -2704,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",
@@ -2916,12 +3277,15 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"bitflags",
"bytes",
"futures-util",
"http",
"http-body",
"pin-project-lite",
"tower",
"tower-layer",
"tower-service",
"tracing",
"url",
]
[[package]]
@@ -2998,6 +3362,12 @@ 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"
@@ -3010,7 +3380,7 @@ dependencies = [
"http",
"httparse",
"log",
"rand",
"rand 0.8.8",
"sha1",
"thiserror 1.0.69",
"utf-8",
@@ -3119,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"
@@ -3153,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"
@@ -3185,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"
+8
View File
@@ -25,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"
+24 -2
View File
@@ -2,7 +2,7 @@
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–7)
## 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.
@@ -14,6 +14,7 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **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
@@ -75,9 +76,30 @@ Worth knowing:
- **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.
## 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: the Android client and UnifiedPush (phase 8), which will push content-free wake-ups for `message_new` events whose `notify` is true.
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:
+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()
);
+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)
}
+2 -2
View File
@@ -151,7 +151,7 @@ async fn serve(state: AppState, mut socket: WebSocket) -> anyhow::Result<()> {
close(&mut socket, CLOSE_BAD_HELLO, "expected auth message").await;
return Ok(());
};
let Some(user_id) = session_user(&state.pool, token).await? else {
let Some(user_id) = session_user(&state, token).await? else {
close(&mut socket, CLOSE_UNAUTHORIZED, "unauthorized").await;
return Ok(());
};
@@ -198,7 +198,7 @@ async fn serve(state: AppState, mut socket: WebSocket) -> anyhow::Result<()> {
Some(Ok(_)) => {}
},
_ = heartbeat.tick() => {
if session_user(&state.pool, token).await? != Some(user_id) {
if session_user(&state, token).await? != Some(user_id) {
close(&mut socket, CLOSE_UNAUTHORIZED, "session ended").await;
return Ok(());
}
+21 -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,7 +30,7 @@ impl FromRequestParts<AppState> for CurrentUser {
.ok_or(ApiError::Unauthorized)?;
let token = Uuid::parse_str(token_str).map_err(|_| ApiError::Unauthorized)?;
session_user(&state.pool, token)
session_user(state, token)
.await?
.map(|user_id| CurrentUser { user_id })
.ok_or(ApiError::Unauthorized)
@@ -41,13 +40,24 @@ impl FromRequestParts<AppState> for CurrentUser {
/// 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.
pub async fn session_user(pool: &sqlx::PgPool, token: Uuid) -> sqlx::Result<Option<Uuid>> {
let row: Option<(Uuid, chrono::DateTime<Utc>)> =
sqlx::query_as("SELECT user_id, expires_at FROM sessions WHERE token = $1")
.bind(token)
.fetch_optional(pool)
.await?;
Ok(row
.filter(|(_, expires_at)| *expires_at > Utc::now())
.map(|(user_id, _)| user_id))
///
/// 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;
+10 -1
View File
@@ -1,5 +1,7 @@
use crate::api::state::AppState;
use crate::api::{accounts, auth, events, folders, messages, outbox, rules, tags, threads};
use crate::api::{
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
};
use axum::routing::{delete, get, post, put};
use axum::Router;
use tower_http::cors::CorsLayer;
@@ -36,6 +38,13 @@ 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())
+2
View File
@@ -1,6 +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;
@@ -17,4 +18,5 @@ pub struct AppState {
/// goes out immediately rather than at the next idle poll.
pub outbox_wake: Arc<Notify>,
pub events: EventHub,
pub pusher: Pusher,
}
+86
View File
@@ -12,6 +12,65 @@ 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,
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()
}
}
impl Config {
@@ -60,6 +119,33 @@ impl Config {
blob_storage_dir,
session_ttl_hours,
trash_retention_days,
push: PushConfig::from_env()?,
})
}
}
#[cfg(test)]
mod tests {
use super::PushConfig;
#[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());
}
}
+1
View File
@@ -7,6 +7,7 @@ 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;
+4
View File
@@ -46,6 +46,9 @@ async fn main() -> anyhow::Result<()> {
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,
@@ -54,6 +57,7 @@ async fn main() -> anyhow::Result<()> {
config: config.clone(),
outbox_wake,
events,
pusher,
};
let app = api::build(state);
+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());
}
}
+12
View File
@@ -25,6 +25,12 @@ fn test_router() -> axum::Router {
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")),
@@ -36,6 +42,7 @@ fn test_router() -> axum::Router {
blob_storage_dir: std::path::PathBuf::from("/tmp/tern-test"),
session_ttl_hours: 1,
trash_retention_days: 30,
push: Default::default(),
},
outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
};
@@ -73,6 +80,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!(
@@ -93,6 +103,8 @@ async fn collection_routes_match() {
"/api/threads",
"/api/events",
"/api/ws",
"/api/push",
"/api/devices",
"/api/outbox",
"/api/tags",
"/api/rules",