CSRF Double-Submit Token

Issue HMAC-bound CSRF tokens and verify that the header, cookie and session agree before accepting a state change.

TypescriptAuth Jwt

Code

typescriptsnippet
40 lines
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";

export interface CsrfCheckInput {
  headerToken?: string;
  cookieToken?: string;
  sessionId: string;
}

export function createCsrfToken(sessionId: string, secret: string): string {
  if (!sessionId || !secret) throw new TypeError("sessionId and secret are required");
  const nonce = randomBytes(18).toString("base64url");
  const signature = createHmac("sha256", secret)
    .update(sessionId + "." + nonce)
    .digest("base64url");
  return nonce + "." + signature;
}

export function verifyCsrfToken(input: CsrfCheckInput, secret: string): boolean {
  const { headerToken, cookieToken, sessionId } = input;
  if (!headerToken || !cookieToken || !sessionId) return false;
  const header = Buffer.from(headerToken);
  const cookie = Buffer.from(cookieToken);
  if (header.length !== cookie.length || !timingSafeEqual(header, cookie)) return false;
  const separator = headerToken.lastIndexOf(".");
  if (separator <= 0) return false;
  const nonce = headerToken.slice(0, separator);
  const signature = headerToken.slice(separator + 1);
  const expected = createHmac("sha256", secret)
    .update(sessionId + "." + nonce)
    .digest("base64url");
  const provided = Buffer.from(signature);
  const expectedBuffer = Buffer.from(expected);
  return provided.length === expectedBuffer.length
    && timingSafeEqual(provided, expectedBuffer);
}

export function csrfCookie(token: string, secure = true): string {
  const flags = ["Path=/", "SameSite=Lax", secure ? "Secure" : ""].filter(Boolean);
  return "csrf_token=" + encodeURIComponent(token) + "; " + flags.join("; ");
}

How it works

Count the functions createCsrfToken, verifyCsrfToken and csrfCookie as the entire surface area of CSRF Double-Submit Token.

The only import source is node:crypto, a Node.js built-in, exposing createHmac, randomBytes, timingSafeEqual. When the guard condition holds, TypeError is thrown rather than a bogus value returned.

Points of care

  • The only import, node:crypto, is part of the Node.js standard library.
  • crypto exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard !sessionId || !secret short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is export function createCsrfToken(sessionId: string, secret: string)

Import createCsrfToken from the file and call it — the rest of the code is implementation detail.

Key statements

if (header.length !== cookie.length || !timingSafeEqual(header, cookie)) return false;
if (!sessionId || !secret) throw new TypeError("sessionId and secret are required");
return "csrf_token=" + encodeURIComponent(token) + "; " + flags.join("; ");

Interactive Tools for This Topic

FAQ

How does the code behave when input is bad?
`TypeError` is raised at the guard (`!sessionId || !secret`), so invalid state never reaches the main logic.
Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.