import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { ForbiddenError } from "./errors.ts"; // Stateless CSRF: token = HMAC(secret, did), bound to the session DID (defense-in-depth over SameSite=Lax). // Per-process secret unless CSRF_SECRET is set, so tokens reset on restart — costs only a rare form resubmit. const CSRF_SECRET = process.env["CSRF_SECRET"] ?? randomBytes(32).toString("hex"); const CSRF_FIELD = "_csrf"; export function csrfTokenFor(did: string): string { return createHmac("sha256", CSRF_SECRET).update(did).digest("base64url"); } export function verifyCsrfToken(submitted: string | null, did: string): void { if (!submitted) throw new ForbiddenError("Missing CSRF token"); const expected = csrfTokenFor(did); const a = Buffer.from(submitted, "base64url"); const b = Buffer.from(expected, "base64url"); if (a.length !== b.length || !timingSafeEqual(a, b)) { throw new ForbiddenError("Invalid CSRF token"); } } // Token comes from the _csrf field or the X-CSRF-Token header (HTMX/bodyless POSTs). export async function verifyCsrfForm(request: Request, did: string | null) { if (!did) throw new ForbiddenError(); const form = await readFormData(request); const submitted = (form.get(CSRF_FIELD) as string | null) ?? request.headers.get("X-CSRF-Token"); verifyCsrfToken(submitted, did); return form; } // Empty FormData (not a throw) for bodyless POSTs that verify via header only. async function readFormData(request: Request) { try { return await request.formData(); } catch { return new FormData(); } }