From 3b6d43623bb8f4e26df5f6fb170bcf7ddb660d19 Mon Sep 17 00:00:00 2001 From: Nic Benders Date: Thu, 12 Nov 2026 18:04:59 -0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(auth):=20session=20hardening=20?= =?UTF-8?q?=E2=80=94=20token=20types,=20revocation,=20cookie=20flags,=20CO?= =?UTF-8?q?RS,=20auth=20throttle=20(#315)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - JWTs carry a type; verifyToken accepts access tokens only, so a refresh token is good only at /admin/refresh. HS256 pinned on verify. - users.token_version, embedded as the tv claim; bumped on password change, admin-status change and logout. requireAuth and requireOwner share one verification path (authenticateSession). - No JWT from the query string. - Session cookies set through one helper; Secure when the request arrived over HTTPS. - CORS: no cross-origin access to the cookie-authenticated API unless listed in CORS_ALLOWED_ORIGINS; /rest/* answers any origin, never credentialed. - Failed-password throttle shared by /admin/login and Subsonic auth, keyed on request.ip; TRUST_PROXY sets Fastify trustProxy. Invite limiter moved onto the same primitives. - Login decrypts a decoy for unknown usernames. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01M98ML9i5X7crjKVomscTNt --- hub/src/auth/jwt.ts | 114 +++--- hub/src/auth/middleware.ts | 104 +++--- hub/src/auth/rate-limit.ts | 136 +++++++ hub/src/auth/session.ts | 73 ++++ hub/src/auth/subsonic-auth.ts | 51 ++- hub/src/config.ts | 44 +++ hub/src/db/client.ts | 12 + hub/src/db/schema.sql | 1 + hub/src/routes/admin.ts | 174 +++++---- hub/src/routes/invites.ts | 56 +-- hub/src/server.ts | 27 +- hub/test/session-hardening.test.ts | 575 +++++++++++++++++++++++++++++ 12 files changed, 1150 insertions(+), 217 deletions(-) create mode 100644 hub/src/auth/rate-limit.ts create mode 100644 hub/src/auth/session.ts create mode 100644 hub/test/session-hardening.test.ts 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