/** * The browser-bound value of a social-login round trip (CF-070 / S6b-02). * * The OAuth callback route (`app/api/auth/oauth-callback/route.ts`) turns a one-time `auth_code` into a * customer session cookie. The code is a bearer value that travels in a URL, so without more, anyone * can start a login with THEIR OWN provider account and hand the finished callback link to a victim * ("login CSRF"): the victim's browser would sign in as the attacker, and whatever the victim then * saves (an address, a card, an order) lands in the attacker's account. * * The fix binds the round trip to the browser that started it, with no backend change: * * 1. before sending the shopper to the provider, `POST /api/auth/oauth-state` makes a random nonce, * keeps it in an httpOnly cookie and returns it to the page; * 2. the page puts it on the `redirectUrl` it gives the backend (`.../oauth-callback?n=`), which * the backend stores and appends its own params to; * 3. the callback exchanges the code ONLY when the `n` on the URL equals the cookie, and always * clears the cookie. A link built in someone else's browser has no matching cookie here. * * ⛔ Imports nothing, on purpose: `scripts/check-oauth-state.mjs` runs this file as plain TypeScript. */ /** The query parameter that carries the nonce on the redirect URL. */ export const OAUTH_NONCE_PARAM = 'n'; /** How long a login round trip may take before its nonce stops being accepted (seconds). */ export const OAUTH_NONCE_MAX_AGE = 10 * 60; const NONCE_SHAPE = /^[A-Za-z0-9_-]{32,64}$/; /** 32 random bytes as base64url (43 characters). Works in Node route handlers and on the edge. */ export function createOAuthNonce(): string { const bytes = new Uint8Array(32); crypto.getRandomValues(bytes); let binary = ''; for (const b of bytes) binary += String.fromCharCode(b); return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export function isOAuthNonce(value: unknown): value is string { return typeof value === 'string' && NONCE_SHAPE.test(value); } /** True only when both are well-formed nonces and equal. Compares every character, whatever the input. */ export function oauthNonceMatches(cookieValue: unknown, urlValue: unknown): boolean { if (!isOAuthNonce(cookieValue) || !isOAuthNonce(urlValue)) return false; if (cookieValue.length !== urlValue.length) return false; let diff = 0; for (let i = 0; i < cookieValue.length; i++) { diff |= cookieValue.charCodeAt(i) ^ urlValue.charCodeAt(i); } return diff === 0; } const ERROR_CODE = /^[a-z][a-z0-9_]{0,63}$/; /** * `?oauth_error=` is copied onto the redirect to the callback page, which picks a message by code. * A code that is not a plain snake_case identifier (markup, a URL, a long string) becomes * `server_error` instead of being forwarded. */ export function safeOAuthErrorCode(code: string | null | undefined): string { return code && ERROR_CODE.test(code) ? code : 'server_error'; }