Module architecture
Each feature is organized into three layers:src/config (zod env + constants), src/db (Drizzle client, schema,
migrate, seed), src/plugins (cors, rate-limit, auth, swagger, error handler), src/shared
(errors, crypto, uuidv7, username rules, email, serializers), src/jobs.
Every service function, handler, schema and type is exported and ready to use — including
handlers that no default route mounts yet, so you can wire them into your own routes as you
build.
Auth model — passwordless only
One model: a six-digit email code. Sign-in and sign-up are the same act — the first valid code for an unknown address creates the account. No password, no register/login split, no reset, no separate email verification.POST /v1/auth/code— emails a code. 204 for any address (not an enumeration oracle). 10-min life, 5 attempts, single use, hashed at rest, constant-time compare. Wrong guesses are counted with an atomic RedisINCR, so guesses sent in parallel can’t stretch the limit — the fifth wrong one burns the code.POST /v1/auth/code/verify— sign in · create-and-sign-in (username auto-generated from the email) ·deletion_pending(soft-deleted →restoreToken).- Google / Apple sign-in available alongside: the account is found by the provider id, else linked by
an address the provider verified (an unverified one never adopts an existing account), else
created. A match that is pending deletion answers the same
deletion_pendingas a code. Apple on the web and desktop (/apple/web→ Apple →/apple/web/callback→/apple/web/exchange) issues a single-use OAuthstate(10 minutes, kept in Redis); a callback with a missing, unknown or reused one is refused with400 invalid_oauth_state, which closes login CSRF. - Access 15 min, refresh 30 days, HS256, rotation on every refresh; each pair bound to a
sessionsrow; live-session check cached in Redis with a DB fallback. An expired access token answers401 token_expired, any other bad one401 invalid_token. - Signing-key rotation without a mass sign-out: every token carries a
kid. To rotateJWT_SECRET, move the old value intoJWT_PREVIOUS_SECRETS(comma-separated) — tokens it signed keep verifying until they expire; remove it after the refresh lifetime. - Refresh-token reuse detection: a refresh token is single-use. Rotation locks the session
row, so presenting a token that was already rotated — a replay — revokes the whole session
(
401 refresh_token_reused). One exception, a 2-minute grace window: the token the last rotation spent may be presented again for a replacement pair, so a rotation whose response was lost (dropped connection, killed app) never signs the user out. Two concurrent refreshes both get an answer, but only the later pair stays valid: the re-issue retires the first one. The window is pinned to that rotation; a re-issue never extends it. The app and the admin panel queue their refreshes across tabs, so a legitimate client never relies on it in normal use. - DPoP — sessions bound to the device (RFC 9449):
the app and the admin panel hold a non-exportable P-256 key and sign a short proof for every
request. A sign-in or refresh with a proof binds the session to that key; from then on its tokens
work only as
Authorization: DPoP <access>plus a freshDPoPproof, so a token copied off the device is useless. A bad proof on a sign-in or refresh is a422(never a sign-out); a valid proof of another key is401 dpop_key_mismatchand revokes nothing — except for the token in the grace window: grace is for the holder whose answer got lost, so another key there means a second holder, and the session is revoked as reuse. Clients without a key stay on Bearer;DPOP_REQUIRED(comma-separatedclient_ids, empty by default) makes binding mandatory once every live build of an app sends proofs. - Revocation is immediate and complete: sign-out, device revoke and “sign out everywhere” delete
the session rows and evict exactly the access tokens they held — including one a concurrent
refresh just issued. A session past its refresh lifetime is no longer listed and is removed by
purge.
Authentication is passwordless by design — there is intentionally no password, no reset,
and no separate email-verification step.
TEST_ACCOUNTS=email:6digits,… — a fixed code for App Store /
Google Play review and CI. Verifies only against a pre-seeded is_test account, so a fixed
code never creates one. Every fixed-code sign-in is logged at warn.
What’s in the box
Interactive reference at
/docs (Swagger UI). Other mechanics: username (auto from email,
live availability, 30-day change cooldown; old names stay reserved in username_history),
email change by code, avatar upload (POST /v1/account/avatar, multipart file: JPEG, PNG
or WebP up to 2 MB, 30 per hour; the previous picture is deleted, and PATCH /me accepts only the
account’s own upload or null as avatar), data export (GET /v1/account/export — the whole
account as one JSON document for GDPR access / portability: profile, sign-in methods, username
history, sessions, subscriptions, support tickets, uploads and the Notes example’s data; 10 per
hour per account), account deletion that feels instant (sessions killed now) with
physical purge after PURGE_AFTER_DAYS — and a way back: signing in during that window returns
deletion_pending with a restoreToken, which POST /v1/auth/restore exchanges to restore the
account and sign in.
Uploads. A single-shot upload streams to disk, never into memory. A chunked upload is resumable:
GET /chunk/:uploadId/status lists the chunks the server holds, and useFileUpload resumes a
paused or failed upload into the same uploadId, sending only what is missing. The server checks
every step against the declaration: the chunk count must fit the size (invalid_chunk_count), a
chunk index must be one of the declared ones (invalid_chunk_index), a chunk may not be larger than
the declaration allows (invalid_chunk_size), and on completion the bytes must add up to the
declared size (size_mismatch). The declared type is read canonically before the allowlist check
and stored that way: lower-cased, without parameters, and with other names for the same type
resolved — Chrome and Edge on Windows send a .zip as application/x-zip-compressed, which is
stored as application/zip. A file claiming an image or PDF type — by its declared type or its
extension — must start with that format’s signature (file_type_mismatch). One account holds at
most 20 unfinished uploads (409 too_many_uploads); one with no new chunk for a day is abandoned
and swept by purge. GET /files/:filename streams the file with byte ranges (206 / 416) and
validators (ETag, Last-Modified): an interrupted download resumes with If-Range — from the
same copy only — and a cached copy is confirmed with 304. Every response carries nosniff and a
CSP with sandbox (PDFs: without sandbox); types a browser could run as active content (SVG
above all) download as attachments.
App version policy & upgrade gate
The app publishes a version policy the client honours — set it in Admin → Settings, no deploy:- Latest version → a soft “update available” dot (bottom bar, side menu and About) and an Update store-link button on About when the installed build is older. A nudge.
- Min. supported version → a hard gate: a build below it is blocked with a
non-dismissable “Update required” screen. Enforced two ways — the app checks
/v1/app-versionon launch + hourly, and every request sendsX-App-Versionso the API answers426 Upgrade Requiredfor a stale build (the app’s interceptor then shows the block). Recovery endpoints (/health,/version,/app-version) are never gated, and a request without the header isn’t either — so tooling and monitors keep working.
API_DEPRECATION / API_SUNSET, when set, add the RFC 8594
Deprecation / Sunset headers to every response — a standards-compliant way to signal that the
API version is winding down. Unset by default.
Scripts
Operational notes
- The container boots
migrate → seed → serve. - Run purge daily on cron; in the prod image use the compiled path:
node dist/jobs/purge.js. - Email: point
SMTP_*at a transactional provider (Postmark works). Set SPF, DKIM, DMARC — with passwordless auth, a code in spam means nobody can sign in. - CORS:
CORS_ORIGINS= exact web origin(s); the native app origins (capacitor://localhostiOS,https://localhostAndroid,tauri://localhostmacOS/Linux,http://tauri.localhostWindows) and the admin’sADMIN_URLare always allowed. - Client allowlist:
CLIENT_IDS= your app’sclient_id(s), comma-separated;adminis always allowed. A sign-in from any other id gets400 unknown_clientbefore a code is emailed or an account is created. - Reverse proxy:
TRUST_PROXY(defaultloopback,uniquelocal) = the proxy IPs/CIDRs whoseX-Forwarded-Foris trusted; nevertrueon a publicly reachable API.