Skip to main content
The backend half of the kit — Fastify + Drizzle + PostgreSQL + Redis. Single-app: one deployment serves one product. Every route follows the shared wire contract — versioning, field format, errors and token auth (Bearer, or DPoP-bound).

Module architecture

Each feature is organized into three layers:
Supporting 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 Redis INCR, 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_pending as a code. Apple on the web and desktop (/apple/web → Apple → /apple/web/callback → /apple/web/exchange) issues a single-use OAuth state (10 minutes, kept in Redis); a callback with a missing, unknown or reused one is refused with 400 invalid_oauth_state, which closes login CSRF.
  • Access 15 min, refresh 30 days, HS256, rotation on every refresh; each pair bound to a sessions row; live-session check cached in Redis with a DB fallback. An expired access token answers 401 token_expired, any other bad one 401 invalid_token.
  • Signing-key rotation without a mass sign-out: every token carries a kid. To rotate JWT_SECRET, move the old value into JWT_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 fresh DPoP proof, so a token copied off the device is useless. A bad proof on a sign-in or refresh is a 422 (never a sign-out); a valid proof of another key is 401 dpop_key_mismatch and 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-separated client_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 / review accounts: 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-version on launch + hourly, and every request sends X-App-Version so the API answers 426 Upgrade Required for 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.
Leave a field empty to disable that half. Bump Latest each release; raise Min. supported only to force everyone off a broken build (e.g. a bad billing or security release). API deprecation. Separately, 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://localhost iOS, https://localhost Android, tauri://localhost macOS/Linux, http://tauri.localhost Windows) and the admin’s ADMIN_URL are always allowed.
  • Client allowlist: CLIENT_IDS = your app’s client_id(s), comma-separated; admin is always allowed. A sign-in from any other id gets 400 unknown_client before a code is emailed or an account is created.
  • Reverse proxy: TRUST_PROXY (default loopback,uniquelocal) = the proxy IPs/CIDRs whose X-Forwarded-For is trusted; never true on a publicly reachable API.