// auth-routes.ts: sign in with an OAuth provider, keep the person in a signed cookie, sign out. Server only. // Web-standard Request/Response handlers: they run on any Node.js 22.18+ server or serverless platform. // The provider is any OAuth 2.0 service your users already have (Google, GitHub, Microsoft and others work the same way). import type { Db } from './db.ts'; import { newNonce, newVerifier, challengeOf, signState, verifyState, stateCookie, clearStateCookie, verifierCookie, clearVerifierCookie, STATE_COOKIE, VERIFIER_COOKIE, STATE_TTL_MS, } from './oauth-state.ts'; import { signSession, sessionCookie, clearSessionCookie, readCookie, SESSION_TTL_MS } from './session.ts'; /** What the routes need from the provider: its consent page, and the person behind a code. */ export interface OAuthProvider { name: string; /** * The provider's consent page URL, with your client id, redirect URI, scopes and this state. * Add code_challenge= and code_challenge_method=S256 (PKCE). */ authorizeUrl(state: string, codeChallenge: string): string; /** Exchanges the code for a token, then reads who signed in. Send code_verifier= in the token request. */ identify(code: string, codeVerifier: string): Promise<{ providerUserId: string; email: string | null }>; } export interface AuthDeps { db: Pick; provider: OAuthProvider; /** Your site's origin, e.g. https://app.example.com: POSTs must come from it. */ appOrigin: string; now?: () => number; } function redirect(location: string, cookies: string[]): Response { const headers = new Headers({ location, 'cache-control': 'no-store' }); for (const c of cookies) headers.append('set-cookie', c); return new Response(null, { status: 302, headers }); } /** GET /api/auth/start: to the provider's consent page, with a signed state and PKCE challenge; their secrets go in cookies. */ export function handleStart(deps: AuthDeps): Response { const now = (deps.now ?? Date.now)(); const nonce = newNonce(); const verifier = newVerifier(); const url = deps.provider.authorizeUrl(signState(nonce, now + STATE_TTL_MS), challengeOf(verifier)); return redirect(url, [stateCookie(nonce), verifierCookie(verifier)]); } /** GET /api/auth/callback?code&state: check the state and the PKCE verifier, find or create the user, set the session cookie. */ export async function handleCallback(request: Request, deps: AuthDeps): Promise { const now = (deps.now ?? Date.now)(); const q = new URL(request.url).searchParams; // Every way out of the callback clears both cookies: each sign-in attempt gets one try. const back = (code: string): Response => redirect(`/?error=${code}`, [clearStateCookie(), clearVerifierCookie()]); if (q.get('error')) return back('denied'); // the person said no on the provider's page const nonce = verifyState(q.get('state'), now); const code = q.get('code'); const verifier = readCookie(request, VERIFIER_COOKIE); if (!nonce || nonce !== readCookie(request, STATE_COOKIE) || !code || !verifier) return back('bad_state'); try { const who = await deps.provider.identify(code, verifier); const userId = await deps.db.upsertUser({ provider: deps.provider.name, providerUserId: who.providerUserId, email: who.email }); const session = { userId, expiresAt: now + SESSION_TTL_MS }; return redirect('/app', [sessionCookie(signSession(session), session, now), clearStateCookie(), clearVerifierCookie()]); } catch { return back('signin_failed'); // log the error on your side; never show its text to the visitor } } /** POST /api/auth/logout: clears the cookie. There is nothing to revoke on the server: the cookie was the session. */ export function handleLogout(request: Request, deps: AuthDeps): Response { if (request.method !== 'POST') return new Response(null, { status: 405, headers: { allow: 'POST' } }); if (request.headers.get('origin') !== deps.appOrigin) return new Response(null, { status: 403 }); return new Response(null, { status: 204, headers: { 'set-cookie': clearSessionCookie() } }); }