// oauth-state.ts: the `state` and the PKCE verifier of an OAuth sign-in. Server only. // Three checks, so a forged callback fails whichever way it is made: // 1. the state is signed (HMAC-SHA256 with SESSION_SECRET) and expires after 10 minutes; // 2. its random nonce must equal the nonce in a short-lived HttpOnly cookie set when the sign-in started, // which ties the callback to the browser that began it (login CSRF); // 3. PKCE (S256): the provider gets a hash of a random secret (the challenge) at the start, and the secret itself (the // verifier, kept in a cookie like the nonce) when the code is traded, so a stolen code is useless without it. // RFC 9700 section 2.1.1: clients must prevent authorization code injection, and PKCE is recommended for // confidential clients too (https://www.rfc-editor.org/rfc/rfc9700.html, read 2026-11-22). // The HMAC input starts with a fixed label, so a state can never pass as a session cookie, nor the other way round. import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; export const STATE_TTL_MS = 10 * 60 * 1000; export const STATE_COOKIE = 'oauth_state'; export const VERIFIER_COOKIE = 'oauth_verifier'; const LABEL = 'oauth-state-v1\n'; const secretOf = (secret?: string): string => { const s = secret ?? process.env.SESSION_SECRET; if (!s) throw new Error('SESSION_SECRET is not set'); if (Buffer.byteLength(s) < 32) throw new Error('SESSION_SECRET must be at least 32 bytes'); return s; }; const mac = (part: string, secret: string): Buffer => createHmac('sha256', secret).update(LABEL + part).digest(); export const newNonce = (): string => randomBytes(18).toString('base64url'); /** The PKCE verifier: 32 random bytes, 43 characters (RFC 7636 asks for 43 to 128). */ export const newVerifier = (): string => randomBytes(32).toString('base64url'); /** The PKCE challenge sent to the provider: the S256 hash of the verifier (RFC 7636 section 4.2). */ export const challengeOf = (verifier: string): string => createHash('sha256').update(verifier).digest('base64url'); export function signState(nonce: string, expiresAt: number, secret?: string): string { const part = Buffer.from(JSON.stringify({ n: nonce, e: expiresAt })).toString('base64url'); return `${part}.${mac(part, secretOf(secret)).toString('base64url')}`; } /** The state's nonce, or null for a bad format, a bad signature or an expired state. Never throws. */ export function verifyState(value: unknown, nowMs: number, secret?: string): string | null { if (typeof value !== 'string') return null; const dot = value.indexOf('.'); if (dot <= 0 || dot !== value.lastIndexOf('.')) return null; const part = value.slice(0, dot); const sig = value.slice(dot + 1); if (!/^[A-Za-z0-9_-]+$/.test(part) || !/^[A-Za-z0-9_-]+$/.test(sig)) return null; const given = Buffer.from(sig, 'base64url'); const expected = mac(part, secretOf(secret)); if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null; let parsed: unknown; try { parsed = JSON.parse(Buffer.from(part, 'base64url').toString('utf8')); } catch { return null; } if (typeof parsed !== 'object' || parsed === null) return null; const { n, e } = parsed as Record; if (typeof n !== 'string' || n === '') return null; if (typeof e !== 'number' || !Number.isFinite(e) || e <= nowMs) return null; return n; } // These cookies are only sent to the sign-in routes: nothing else needs them. export const stateCookie = (nonce: string): string => `${STATE_COOKIE}=${nonce}; HttpOnly; Secure; SameSite=Lax; Path=/api/auth; Max-Age=${STATE_TTL_MS / 1000}`; export const clearStateCookie = (): string => `${STATE_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/api/auth; Max-Age=0`; export const verifierCookie = (verifier: string): string => `${VERIFIER_COOKIE}=${verifier}; HttpOnly; Secure; SameSite=Lax; Path=/api/auth; Max-Age=${STATE_TTL_MS / 1000}`; export const clearVerifierCookie = (): string => `${VERIFIER_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/api/auth; Max-Age=0`;