diff --git a/SECURITY.md b/SECURITY.md index 4bce693..fa5078d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -66,6 +66,10 @@ assumption should stay documented. ### H1 — No TLS, no `Secure` cookies, no HSTS +> **Status: partly fixed (#315).** Session cookies are `Secure` when the +> request arrived over HTTPS (`X-Forwarded-Proto` from the proxy). Still open: +> no HSTS, no boot warning when TLS is absent. + `server.ts` serves plain HTTP on `0.0.0.0:PORT`. TLS is documented as the operator's responsibility (`example.env`: "Cloudflare Tunnel, Caddy, Traefic, nginx, Tailscale Funnel"), but nothing enforces or detects it: @@ -86,6 +90,10 @@ indicating TLS termination. ### H2 — CORS reflects any origin with credentials +> **Status: fixed (#315).** The cookie-authenticated API is same-origin unless +> an origin is listed in `CORS_ALLOWED_ORIGINS`; `/rest/*` answers `*`, never +> credentialed. See `docs/authentication.md` ("CORS"). + ```ts app.register(cors, { origin: true, credentials: true }); ``` @@ -155,6 +163,11 @@ actually needs); reject everything else with 404. Add a regression test assertin ### H5 — No rate limiting or lockout +> **Status: fixed (#315).** Failed-password throttle shared by `/admin/login` +> and Subsonic auth, per (client address, username) and per address; see +> `docs/authentication.md` ("Failed-password throttle"). Operators behind a +> reverse proxy must set `TRUST_PROXY`. + No 429, no throttle, no lockout exists anywhere in the codebase (verified by grep). On a public endpoint: @@ -210,6 +223,11 @@ they share the same heuristic. ### M3 — JWT weaknesses +> **Status: items 1, 2 and 4 fixed (#315).** Tokens are typed; a per-user +> `token_version` revokes sessions on password change, admin-status change and +> logout; `?token=` is gone. Still open: item 3 (secret in SQLite), and +> revocation is per user, not per session. + `auth/jwt.ts` signs `{ sub, username, role }` with HS256. Verified gaps: 1. **No token type.** `verifyToken` checks signature/expiry only. A refresh diff --git a/docker-compose.yml b/docker-compose.yml index 5368a05..aaa9f50 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -41,6 +41,11 @@ services: # nothing is caught. Set to "false" to reduce it to ping + DB only. - NAVIDROME_STREAM_PROBE=${NAVIDROME_STREAM_PROBE:-} - NAVIDROME_HEALTH_INTERVAL_MS=${NAVIDROME_HEALTH_INTERVAL_MS:-} + # Reverse proxy trust (#315). Set TRUST_PROXY when the hub sits behind a + # proxy or tunnel, or every client shares one auth rate-limit bucket. + # CORS_ALLOWED_ORIGINS is only for an SPA served from another origin. + - TRUST_PROXY=${TRUST_PROXY:-} + - CORS_ALLOWED_ORIGINS=${CORS_ALLOWED_ORIGINS:-} # Library-shrink guard (#297): a sync that drops more than this % of an # instance's tracks (or to 0) is held, not applied. 0 disables; default 20. - POUTINE_SHRINK_GUARD_PERCENT=${POUTINE_SHRINK_GUARD_PERCENT:-} diff --git a/docs/authentication.md b/docs/authentication.md index 8ca6567..2a61048 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -6,7 +6,7 @@ Poutine has three authentication mechanisms, each scoped to a different API surf | Surface | Prefix | Mechanism | |-------------------|-----------------|---------------------------------------------------------------------------------------| -| Admin | `/admin/*` | JWT (cookie + `Authorization: Bearer` header) | +| Admin | `/admin/*`, `/api/admin/*` | Access JWT (`Authorization: Bearer` header or `access_token` cookie) | | Subsonic (JSON) | `/rest/*` | Subsonic `u+p` (plaintext / `enc:`) **or** `u+t+s` (MD5 token+salt) | | Subsonic (binary) | `/rest/stream`, `/rest/getCoverArt` | Same as Subsonic JSON, but errors use HTTP status codes, not Subsonic envelopes. `/rest/stream(.view)` also accepts a `castToken=` query param (#218) as an alternate auth for non-Subsonic clients (Sonos devices, DLNA renderers) — see "Cast tokens" below | | Proxy | `/proxy/*` | Ed25519-signed peers **only** — no JWT, no Subsonic. `GET` on a read-only allowlist | @@ -22,22 +22,27 @@ The encryption key is generated on first boot, persisted at `$POUTINE_PASSWORD_K ## JWT tokens -Used for `/admin/*` only. Signed with HS256. Secret: auto-generated on first boot (32 random bytes, hex-encoded) and persisted in the `settings` table under key `jwt_secret`. Resetting the DB regenerates the secret and invalidates all existing tokens. Two token types: +Used for the admin API only. Signed with HS256 (pinned on verify). Secret: auto-generated on first boot (32 random bytes, hex-encoded) and persisted in the `settings` table under key `jwt_secret`. Resetting the DB regenerates the secret and invalidates all existing tokens. Two token types, never interchangeable (#315): -| Token | Lifetime | Cookie | Cookie path | Claims | -|---------------|----------|---------------------|--------------------|---------------------------| -| Access token | 15 min | `access_token` | `/` | `{ userId, sub: userId }` | -| Refresh token | 7 days | `refresh_token` | `/admin/refresh` | `{ userId, sub: userId, type: "refresh" }` | +| Token | Lifetime | Cookie | Cookie path | Claims | +|---------------|----------|---------------------|--------------------|------------------------------------------------------| +| Access token | 15 min | `access_token` | `/` | `{ userId, sub: userId, type: "access", tv }` | +| Refresh token | 7 days | `refresh_token` | `/admin/refresh` | `{ userId, sub: userId, type: "refresh", tv }` | -Lifetimes configurable via `JWT_ACCESS_EXPIRES_IN` / `JWT_REFRESH_EXPIRES_IN` env vars. Both cookies are `httpOnly`, `sameSite: lax`. +Lifetimes configurable via `JWT_ACCESS_EXPIRES_IN` / `JWT_REFRESH_EXPIRES_IN` env vars. + +**Type check.** `verifyToken` accepts `type: "access"` only; `verifyRefreshToken` accepts `type: "refresh"` only (`hub/src/auth/jwt.ts`). A refresh token is good at `POST /admin/refresh` and nowhere else. A token with no `type` (minted before #315) is rejected — the SPA recovers through one silent refresh. + +**Token version.** `tv` is the user's `users.token_version` at mint time. `authenticateSession` (`hub/src/auth/middleware.ts`) and the refresh handler compare it to the current row and reject a mismatch, so bumping the column revokes every outstanding access *and* refresh token for that user. Bumped on: password change, admin-status change, logout. A token with no `tv` reads as `0`, the column default. + +**Cookies.** Set only by `issueSession` (`hub/src/auth/session.ts`) — login, refresh, invite redemption and the self-password-change reissue all go through it. `httpOnly`, `sameSite: lax`, and `secure` when the request arrived over HTTPS (`request.protocol`, or `X-Forwarded-Proto: https` from the TLS-terminating proxy). ### Token extraction order (admin) 1. `Authorization: Bearer ` header 2. `access_token` cookie -3. `token` query parameter -`verifyToken` accepts any valid JWT. `verifyRefreshToken` additionally requires the `type: "refresh"` claim — separate functions in `hub/src/auth/jwt.ts`. +No query-string source: a JWT in a URL lands in access logs, history and Referer headers. `requireAuth` and `requireOwner` both resolve the user through `authenticateSession`; keep it the single verification path. ## Admin auth flow @@ -45,9 +50,10 @@ Lifetimes configurable via `JWT_ACCESS_EXPIRES_IN` / `JWT_REFRESH_EXPIRES_IN` en `POST /admin/login` with `{ username, password }`. -1. Looks up user, verifies password by AES-decrypting `password_enc` and constant-time comparing. -2. Creates access + refresh JWTs, sets both httpOnly cookies. -3. Returns `{ user, accessToken, subsonicCredentials: { username, password } | null }`. +1. Refuses with `429` + `Retry-After` if this (client address, username) is locked out — see "Failed-password throttle". +2. Looks up user, verifies password by AES-decrypting `password_enc` and constant-time comparing. An unknown username decrypts a decoy, so it costs the same as a wrong password. +3. Creates access + refresh JWTs, sets both httpOnly cookies. +4. Returns `{ user, accessToken, subsonicCredentials: { username, password } | null }`. Both admin and non-admin users can log in (#232). The returned `user.isAdmin` lets the SPA hide admin-only nav; admin-only routes (`requireOwner` preHandler) still 403 non-admin sessions. `GET /admin/me` and `POST /admin/refresh` accept any logged-in user. @@ -55,15 +61,17 @@ The body's `accessToken` goes into `localStorage` for `Authorization` header use ### Token refresh -`POST /admin/refresh` — no preHandler. Reads only the `refresh_token` cookie. Verifies → rotates both tokens → sets new cookies. On failure: clears the refresh cookie, returns 401. +`POST /admin/refresh` — no preHandler. Reads only the `refresh_token` cookie. Verifies type + token version → mints both tokens under the same version → sets new cookies. On failure: clears the refresh cookie, returns 401. + +Rotation does not invalidate the *previous* refresh token on its own — there is no per-session state. It dies at expiry or at the next version bump. ### Logout -`POST /admin/logout` — clears both cookies, returns 204. The SPA also clears `accessToken`, `subsonicUser`, and `subsonicPass` from `localStorage`. +`POST /admin/logout` — bumps the caller's `token_version`, clears both cookies, returns 204. Revocation is per user, not per session: logging out on one device signs the user out everywhere. Without a valid access token there is nobody to revoke for; the cookies are still cleared. The SPA also clears `accessToken`, `subsonicUser`, and `subsonicPass` from `localStorage`. ### Password update -`PUT /api/admin/hub/users/:id/password` (admin-only) with `{ password }`. Re-encrypts via `setPassword` and updates `users.password_enc`. Returns 204. Validates `password.length >= 8`. An admin can target their own id; when they do, the `subsonicCredentials` cached in `localStorage` are now stale — the admin must log out and back in to refresh them. JWTs remain valid until expiry (no forced revocation). +`PUT /api/admin/hub/users/:id/password` (admin-only) with `{ password }`. Re-encrypts via `setPassword` and updates `users.password_enc`. Returns 204. Validates `password.length >= 8`. The write bumps the target's `token_version`, revoking all their sessions (#315). An admin can target their own id; the response then re-issues session cookies under the new version, so that browser stays signed in (its stale bearer token recovers through `/admin/refresh`) while the admin's other sessions end. The `subsonicCredentials` cached in `localStorage` are still stale — the admin must log out and back in to refresh them. ### Admin status and user deletion (#274) @@ -80,7 +88,7 @@ Both run their target through `loadTargetUser()` (`routes/admin.ts`), which hold The self-check alone does **not** keep an admin alive. `requireOwner` reads `is_admin` in the preHandler, so two admins can both be authorized before either write lands and then demote or delete each other, leaving none — after which no `requireOwner` route is reachable and recovery is manual SQL. `otherAdminCount()` runs in the handler body, synchronously with the write, so the second request observes the first. -Neither operation revokes outstanding tokens. A demoted or deleted user's access JWT stays syntactically valid until it expires (≤15 min), but `requireOwner` and `requireAuth` both re-read the `users` row per request, so a demotion 403s on the next call and a deletion 401s ("User not found"). Refresh fails the same way. +An admin-status change bumps the target's `token_version`, so their access and refresh tokens are rejected at once and they must sign in again. Deletion needs no bump: `authenticateSession` re-reads the `users` row per request, so a deleted user's tokens 401 ("User not found") on the next call, refresh included. Deletion relies on `ON DELETE CASCADE` to drop `playlists`, `user_stars`, `play_events`, and the `user_invitations` the user issued (so their pending invites stop redeeming); `user_invitations.consumed_by_id` is `SET NULL`. `instances.owner_id` has **no** cascade, so owned instance rows are reassigned to the acting admin first — see [pitfalls.md](pitfalls.md#auth). That column is vestigial and read by nothing; #275 removes it. @@ -129,7 +137,7 @@ Redeem creates the account and signs the invitee straight in, so the SPA reuses - Both public routes are POST, so the token never appears in a URL, an access log, or a Referer header. The SPA carries it in the URL **fragment** (`/invite#`) and clears the hash after reading it. - One uniform `400 {error:"Invitation is not valid"}` for forged, expired, consumed, revoked, and unknown tokens alike — no enumeration, same posture as Subsonic error 40. Username-taken (`409`) is the one distinguishable case, and has to be. -- Per-IP fixed-window rate limit (20 / 10 min) in the plugin closure. This is the only unauthenticated write surface on the hub. +- Per-address fixed-window rate limit (20 requests / 10 min, successes included) in the plugin closure. This is the only unauthenticated write surface on the hub. The address is `request.ip` — see `TRUST_PROXY` in [hub-internals.md](hub-internals.md#auth). - `/invite` fires no authenticated fetch on mount — see the `/login` self-redirect trap in [pitfalls.md](pitfalls.md#auth). ## Subsonic auth flow @@ -141,6 +149,34 @@ Redeem creates the account and signs the invitee straight in, so the SPA reuses Either form authenticates a user identically. Unknown user and bad credentials both surface as Subsonic error 40 (no enumeration hint). +## Failed-password throttle (#315) + +`AuthThrottle` (`hub/src/auth/rate-limit.ts`, `app.authThrottle`) — one in-process budget shared by `POST /admin/login` and Subsonic `u+p` / `u+t+s`, since both guess the same password. Fixed 10-minute windows, **failures only**: + +| Limit | Threshold | Purpose | +|--------------------------------|-----------|------------------------------------------------------------| +| per (client address, username) | 10 | Guessing one account from one address | +| per client address | 100 | Spraying across usernames; bounds per-username key growth | + +- A locked-out caller is refused **before** the password is checked, right password or not. Blocked attempts are not counted, so a client retrying a stale password neither extends its lockout nor spends the per-address budget. +- A success clears the (address, username) count. +- Refusal: `/admin/login` → `429`; Subsonic JSON → HTTP 200 envelope with **error 0** (not 40 — clients treat 40 as "re-prompt for the password"); Subsonic binary → `429`. All carry `Retry-After`. +- Not counted: cast tokens, the trusted in-process path, requests with no credentials at all. +- **No per-username limit across addresses, by design.** It would let anyone who knows a username lock that user out of their own music from anywhere; a variant that exempts correct passwords stops no guessing. +- The address is `request.ip`. Behind a reverse proxy set `TRUST_PROXY`, or all clients share one bucket — [hub-internals.md](hub-internals.md#auth). +- State is per process and resets on restart. + +## CORS (#315) + +Decided per request in `server.ts`: + +| Path | Policy | +|------------------|-----------------------------------------------------------------------------------------------------| +| `/rest/*` | `Access-Control-Allow-Origin: *`, never credentialed. Browser Subsonic clients are cross-origin; auth is in the query, no cookie is read | +| everything else | Same-origin only. `CORS_ALLOWED_ORIGINS` (exact origins) opts specific origins in, with credentials | + +Never reflect an arbitrary `Origin` next to `Access-Control-Allow-Credentials`. The SPA is same-origin in production and behind the Vite proxy in dev; it needs no CORS. + ### Binary vs JSON error handling - **`requireSubsonicAuth`** — returns errors as Subsonic XML/JSON envelopes with HTTP 200 (Subsonic protocol convention). @@ -200,7 +236,7 @@ Setting a different `POUTINE_OWNER_PASSWORD` in env never overwrites a non-empty **Who** — `hub/src/proxy/auth.ts`, peers only: - All four `x-poutine-*` signing headers required; missing any → `401`. Validated against the in-memory peer registry (DB-backed, sourced from the `instances` table since federation v5; see [federation-api.md](federation-api.md)). Sets `request.proxyAuth = { kind: "peer", peerId }`. -- **No local-user path.** A JWT (header, cookie, or `token=` query) or Subsonic `u+p` / `u+t+s` is not a credential here → `401`. Local users reach the library through `/rest/*`; nothing in the SPA calls `/proxy/*`. +- **No local-user path.** A JWT (header or cookie) or Subsonic `u+p` / `u+t+s` is not a credential here → `401`. Local users reach the library through `/rest/*`; nothing in the SPA calls `/proxy/*`. - Then, in order: version floor (`Poutine-Api-Version` ≥ `MIN_FEDERATION_API_VERSION`, else `403`) and lifecycle gate (non-`active` peer → uniform `403 {"error":"forbidden"}`), both after signature verification. Same policy as `/federation/*` (`federation/peer-auth.ts`) — keep the two in step. - Signed body hash is always `-`: the tier takes no bodies. diff --git a/docs/hub-internals.md b/docs/hub-internals.md index 029ca3a..a49af0e 100644 --- a/docs/hub-internals.md +++ b/docs/hub-internals.md @@ -42,6 +42,8 @@ Root `package.json` scripts fan out to both: `dev`, `build`, `test`, `lint`, `ty | `NAVIDROME_STREAM_PROBE` | no | `true` | Set to `false` to drop the byte-range stream leg from `/api/health/ready` (#277) — readiness then covers hub DB + Navidrome ping only | | `NAVIDROME_HEALTH_INTERVAL_MS`| no | `60000` | Cadence of the background health watchdog (#277). Started only from the real entrypoint, never in tests | | `POUTINE_SHRINK_GUARD_PERCENT`| no | `20` | Library-shrink guard (#297): hold a sync that drops more than this % of an instance's tracks. `0` disables. See "Library-shrink guard" | +| `TRUST_PROXY` | no | — (trust nothing) | Fastify `trustProxy` (#315): which peers may set `X-Forwarded-*`, so what `request.ip` is. `true`, or a comma-separated list of proxy addresses / CIDRs / `loopback` / `linklocal` / `uniquelocal`. A hop count is refused at boot. See "Auth" | +| `CORS_ALLOWED_ORIGINS` | no | — | Exact origins allowed credentialed cross-origin access to the cookie-authenticated API (#315). Unset = same-origin only. `/rest/*` is unaffected (always `*`, never credentialed) | | `NAVIDROME_SCAN_SCHEDULE` | no | `@every 1h` | Compose only — becomes Navidrome's `ND_SCANNER_SCHEDULE` (#296). Robfig cron (`@every 6h`, `0 3 * * *`); `0` disables. Lengthen for a large library on a slow NAS | | `NEW_RELIC_LICENSE_KEY` | no | — | Enables the New Relic APM agent (#3) **and** the app-level telemetry bridge (#277). Secret — `.env` only, never committed. Consumed by the agent, `hub/docker-entrypoint.sh` and `services/telemetry.ts` | | `NEW_RELIC_APP_NAME` | no | `poutine-hub-` | APM entity name; default set in `hub/docker-entrypoint.sh` | @@ -97,6 +99,14 @@ See [authentication.md](authentication.md) for the full auth reference: JWT flow JWT signing secret auto-generates on first boot and lives in the `settings` table (key `jwt_secret`). No env override. DB reset regenerates it and invalidates every existing token. +**Client address and `TRUST_PROXY` (#315).** The failed-password throttle and the invite limiter key on `request.ip` — never on a forwarding header read directly, which a direct caller could vary per request. Unset, `request.ip` is the socket peer: correct for a directly exposed hub, but behind a reverse proxy it is the proxy, so every client shares one bucket (logged once: "Request carries a forwarding header but TRUST_PROXY is unset"). Set it to the proxy's address or CIDR; `proxy-addr` then walks `X-Forwarded-For` from the right and takes the first untrusted hop, which a client cannot forge. + +- Proxy on the same host or Docker network: `TRUST_PROXY=loopback,uniquelocal`. +- `true` trusts the leftmost `X-Forwarded-For` entry from anyone — only when the hub port is reachable solely through a proxy that overwrites the header. +- No hop counts: Fastify fails closed on a number (it cannot validate the immediate peer), so `parseTrustProxy` throws at boot rather than silently trust nothing. +- Docker Desktop NATs every inbound connection to one gateway address. Direct LAN clients there share a bucket whatever this is set to. +- The cookie `Secure` flag needs `X-Forwarded-Proto: https` from the proxy; that header is read regardless of `TRUST_PROXY`. + ## /proxy/* Peer-only, read-only proxy to the local Navidrome. Introduced in Phase 1 (issue #50); narrowed to peers + an endpoint allowlist in #308. diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 6741160..67c6714 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -95,6 +95,13 @@ Full protocol: [federation-api.md](federation-api.md). | Demoting or deleting the `POUTINE_OWNER_USERNAME` account | #274 | Refused by `loadTargetUser({ protectOwner })`. There is no way back: `seedOwner` re-seeds only when the `users` table holds no real accounts, and `reset-password.sh` errors on a missing user. Worse, the DLNA browse path authenticates as that account's u+p (`HubSubsonicCaller` with no `asUser`), so deleting it makes every Browse fail Subsonic auth → `routes/dlna.ts` catches and serves an empty container: the whole library silently disappears behind one `warn` line. Promoting it back to admin is still allowed — that is the recovery path | | Letting anything create a user named `__system__` | #274 | The placeholder name is load-bearing: `GET /users` hides it and every user mutation refuses it. A real account with that name would be invisible in the admin UI, undeletable through the API, and uncounted by `seedOwner`'s "no real users" check. `POST /users` reserves it | | Relying on the self-target check alone to keep one admin alive | #274 | `requireOwner` reads `is_admin` in the **preHandler**, so two admins can both be authorized before either write lands and then demote or delete each other — leaving zero admins and no reachable `requireOwner` route. Both handlers call `otherAdminCount()` in the handler body, synchronously with the write, so the second request observes the first | +| Verifying a session JWT anywhere but `authenticateSession` | #315 | It is the one path that checks token type **and** `token_version`. A second `verifyToken` call site that skips the version compare silently un-revokes sessions | +| Changing a user's password or admin flag without bumping `token_version` | #315 | The bump is the revocation. Put it in the same `UPDATE` as the change (`routes/admin.ts`); `reset-password.sh` does the same in its direct SQL | +| Setting a session cookie by hand | #315 | Use `issueSession` (`auth/session.ts`) — it owns `httpOnly` / `sameSite` / `secure` and the refresh path. Three hand-rolled copies all lacked `secure` | +| Keying a rate limit on `X-Forwarded-For` read directly | #315 | A direct caller rotates the header and gets a fresh bucket per request. Key on `request.ip` only and let `TRUST_PROXY` decide what it is | +| A per-username auth lockout across addresses | #315 | Anyone who knows a username could lock its owner out of streaming. Lockouts are per (address, username) plus a per-address cap | +| `TRUST_PROXY=` | #315 | Fastify 5.12 fails closed on a numeric `trustProxy` (trusts nothing). `parseTrustProxy` throws at boot; use addresses / CIDRs | +| `origin: true` with `credentials: true` in the CORS config | #315 | Reflects any origin onto the cookie-authenticated API. Admin API is same-origin unless listed in `CORS_ALLOWED_ORIGINS`; only `/rest/*` gets `*`, uncredentialed | Full flow: [authentication.md](authentication.md). diff --git a/example.env b/example.env index c1f7945..a860622 100644 --- a/example.env +++ b/example.env @@ -6,6 +6,23 @@ # Caddy, Traefik, nginx, Tailscale Funnel, etc.). Poutine itself serves plain # HTTP inside its container. +# --- Reverse proxy ----------------------------------------------------------- + +# Behind a reverse proxy or tunnel, tell the hub which peers are proxies so it +# sees the real client address. Failed-login throttling keys on that address; +# unset, every visitor shares one bucket and one person's typos lock everyone +# out. Value: a comma-separated list of proxy addresses / CIDRs, or the names +# loopback, linklocal, uniquelocal (all RFC 1918 + ULA). `true` trusts any +# peer — only safe if the hub port is unreachable except through the proxy. +# The proxy must also send X-Forwarded-Proto so session cookies get `Secure`. +# +# TRUST_PROXY=loopback,uniquelocal + +# Only if the web UI is served from a different origin than the hub. Exact +# origins, comma-separated. Leave unset otherwise. +# +# CORS_ALLOWED_ORIGINS=https://music.example.com + # --- Bundled Navidrome ------------------------------------------------------- # Credentials for the hub's service account on the bundled Navidrome. diff --git a/hub/src/auth/jwt.ts b/hub/src/auth/jwt.ts index 94bfaf5..b93bfe2 100644 --- a/hub/src/auth/jwt.ts +++ b/hub/src/auth/jwt.ts @@ -1,66 +1,92 @@ import { SignJWT, jwtVerify } from "jose"; import type { Config } from "../config.js"; -function getSecretKey(config: Config): Uint8Array { - return new TextEncoder().encode(config.jwtSecret); -} +/** + * Session JWTs (#315). Two types, never interchangeable: + * + * - `access` — bearer credential for `requireAuth` / `requireOwner` routes. + * - `refresh` — good only at `POST /admin/refresh`. + * + * Both carry `tv`, the user's `users.token_version` at mint time. Callers + * compare it against the current row; bumping the column revokes every + * outstanding token for that user (see `auth/session.ts`). + */ +export type TokenType = "access" | "refresh"; -function parseDuration(duration: string): string { - // jose accepts durations like "15m", "7d" directly - return duration; +export interface VerifiedToken { + userId: string; + tokenVersion: number; } -export async function createAccessToken( - userId: string, - config: Config -): Promise { - const secret = getSecretKey(config); - return new SignJWT({ userId }) - .setProtectedHeader({ alg: "HS256" }) - .setIssuedAt() - .setExpirationTime(parseDuration(config.jwtAccessExpiresIn)) - .setSubject(userId) - .sign(secret); +const ALGORITHM = "HS256"; + +function getSecretKey(config: Config): Uint8Array { + return new TextEncoder().encode(config.jwtSecret); } -export async function createRefreshToken( +async function signToken( + type: TokenType, userId: string, - config: Config + tokenVersion: number, + expiresIn: string, + config: Config, ): Promise { - const secret = getSecretKey(config); - return new SignJWT({ userId, type: "refresh" }) - .setProtectedHeader({ alg: "HS256" }) + return new SignJWT({ userId, type, tv: tokenVersion }) + .setProtectedHeader({ alg: ALGORITHM }) .setIssuedAt() - .setExpirationTime(parseDuration(config.jwtRefreshExpiresIn)) + .setExpirationTime(expiresIn) // jose accepts "15m", "7d" directly .setSubject(userId) - .sign(secret); + .sign(getSecretKey(config)); } -export async function verifyToken( +async function verifyTyped( + type: TokenType, token: string, - config: Config -): Promise<{ userId: string }> { - const secret = getSecretKey(config); - const { payload } = await jwtVerify(token, secret); - const userId = payload.sub || (payload as Record).userId; + config: Config, +): Promise { + const { payload } = await jwtVerify(token, getSecretKey(config), { + algorithms: [ALGORITHM], + }); + if (payload.type !== type) { + throw new Error(`Not an ${type} token`); + } + const userId = payload.sub || payload.userId; if (typeof userId !== "string") { throw new Error("Invalid token: missing userId"); } - return { userId: userId as string }; + // Tokens minted before #315 carry no `tv`; they match the column default. + const tv = payload.tv ?? 0; + if (typeof tv !== "number" || !Number.isInteger(tv)) { + throw new Error("Invalid token: bad token version"); + } + return { userId, tokenVersion: tv }; +} + +export function createAccessToken( + userId: string, + config: Config, + tokenVersion = 0, +): Promise { + return signToken("access", userId, tokenVersion, config.jwtAccessExpiresIn, config); +} + +export function createRefreshToken( + userId: string, + config: Config, + tokenVersion = 0, +): Promise { + return signToken("refresh", userId, tokenVersion, config.jwtRefreshExpiresIn, config); } -export async function verifyRefreshToken( +/** Verify an **access** token. A refresh token is rejected. */ +export function verifyToken(token: string, config: Config): Promise { + return verifyTyped("access", token, config); +} + +/** Verify a **refresh** token. An access token is rejected. */ +export function verifyRefreshToken( token: string, - config: Config -): Promise<{ userId: string }> { - const secret = getSecretKey(config); - const { payload } = await jwtVerify(token, secret); - if ((payload as Record).type !== "refresh") { - throw new Error("Not a refresh token"); - } - const userId = payload.sub || (payload as Record).userId; - if (typeof userId !== "string") { - throw new Error("Invalid token: missing userId"); - } - return { userId }; + config: Config, +): Promise { + return verifyTyped("refresh", token, config); } diff --git a/hub/src/auth/middleware.ts b/hub/src/auth/middleware.ts index 8c9c9aa..15e81dd 100644 --- a/hub/src/auth/middleware.ts +++ b/hub/src/auth/middleware.ts @@ -14,60 +14,76 @@ declare module "fastify" { } } -export async function requireAuth( +export interface SessionUser { + id: string; + username: string; + isAdmin: boolean; + tokenVersion: number; +} + +export type SessionLookup = { user: SessionUser } | { code: 401; error: string }; + +/** + * Resolve the session user from the request's **access** token — the single + * verification path behind `requireAuth` and `requireOwner` (#315). + * + * Token sources, in order: `Authorization: Bearer`, then the `access_token` + * cookie. There is deliberately no query-string source: a JWT in a URL ends up + * in access logs, browser history and Referer headers. + * + * The `users` row is re-read on every request, so a deletion, a demotion, or a + * `token_version` bump (password change, logout) takes effect immediately. + */ +export async function authenticateSession( request: FastifyRequest, - reply: FastifyReply -): Promise { - const app = request.server; - const config = app.config; - const db = app.db; +): Promise { + const { config, db } = request.server; let token: string | undefined; - - // Try Authorization header first const authHeader = request.headers.authorization; - if (authHeader?.startsWith("Bearer ")) { - token = authHeader.slice(7); - } - - // Fall back to cookie - if (!token && request.cookies?.access_token) { - token = request.cookies.access_token; - } + if (authHeader?.startsWith("Bearer ")) token = authHeader.slice(7); + if (!token && request.cookies?.access_token) token = request.cookies.access_token; - // Fall back to query param (for