Something went wrong. Try again.
🌿 Collaborative wiki on ATProto forked from juprodh.me/lichen.wiki
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";import { ForbiddenError } from "./errors.ts";
// Stateless CSRF: token = HMAC(secret, did). Bound to the session DID so a// cross-origin attacker without read access to the session cookie can't forge// a valid token. SameSite=Lax on the session cookie already blocks the basic// CSRF case — this is the defense-in-depth layer the project's known-improvements// list called out.//// The secret is read from CSRF_SECRET if provided, otherwise generated per// process. A per-process secret means tokens invalidate across restarts, which// is fine: the cost is a single resubmit on the rare destructive form open// across a deploy. Set CSRF_SECRET to share state across processes.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");}
/** * Verify a CSRF token. Throws ForbiddenError on mismatch. * Call from destructive POST handlers after the session has been resolved. */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"); }}
/** * Read form data and verify CSRF. Accepts the token from either the hidden * _csrf form field (standard forms) or the X-CSRF-Token header (HTMX requests * and bodyless POSTs). Throws ForbiddenError if `did` is null so route * handlers don't need to non-null-assert their session. */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;}
// Return an empty FormData rather than throwing when the request has no body// — that path is for routes whose form has only the auto-injected _csrf field// and falls back to header-only verification.async function readFormData(request: Request) { try { return await request.formData(); } catch { return new FormData(); }}