Skip to content

CSRF

In short

The threat

Another site makes your user’s browser send a request to your app, cookie attached. The harm is in the request, not the response.

The rule

Never change state on GET, and refuse a cross-site request at three layers: the cookie, where the request came from, and a signed token.

In the package

SameSite=Lax on the session cookie by default; the origin check and the signed token in http/csrf.ts.

Browsers attach cookies to every request for a site, including requests another site triggers: a hidden form that posts to your /logout or /change-email, or a link to a URL that changes state. The browser’s same-origin policy stops the other site from reading the response, but some requests (a GET, a form POST) are sent anyway.

The browser strips the forged request of its cookie, and two server checks refuse it, each covering the case the layer before can miss. Your own page passes all three.

Two requests reach the same POST route. A request from your own page carries the session cookie, says Sec-Fetch-Site same-origin and echoes a valid signed token, so it passes all three layers and is handled. A hidden form on another site posts to /change-email. The first layer, SameSite=Lax on the session cookie, is in the browser: the request still goes, but without the cookie, so it carries no session. If the cookie goes anyway, from a sibling subdomain or an old browser, the second layer on the server, verifyFetchSite or verifyRequestOrigin, refuses it because it is not same-origin. If it is let through because it comes from a listed cross-site origin that runs script, the third layer, verifyCsrfToken, refuses it because it holds no valid signed token.

Text version

Never change state on GET. A redirect or an image tag can trigger a GET from anywhere. Every flow that changes something is meant for POST or another unsafe method. Then three layers, each stopping what the one before can miss.

The browser leaves the session cookie off cross-site subrequests and cross-site form posts, while still sending it when a user follows a link to your site. This is the default and stops most attacks on its own, but not all:

  • sibling subdomains count as the same site;
  • very old browsers ignore the attribute.
  • One origin. verifyFetchSite refuses any unsafe request whose Sec-Fetch-Site header is missing or not same-origin. Browsers set that header themselves and page scripts cannot change it.
  • A desktop shell or trusted sibling subdomains. Apps that also serve a desktop shell (an app:// origin) or trusted sibling subdomains use verifyRequestOrigin with an explicit allowlist instead, refusing requests without an Origin.

A shell’s requests say Sec-Fetch-Site: cross-site, like an attack’s. The NestJS and tRPC adapters accept them only from origins listed in csrf.crossSiteOrigins (empty by default), matched exactly with no wildcards; the core’s verifyFetchSite takes the same list with the request’s origin.

createCsrfToken mints a random nonce with an HMAC over it and a binding, which the page reads from a cookie and echoes in a header. verifyCsrfToken checks that:

  • the cookie and the header match;
  • the nonce is 32 hex characters;
  • the HMAC is valid for the current binding.

The MAC input is length-prefixed (csrf:<binding length>:<binding>:<nonce>), so no binding and nonce pair can be read as another. The HMAC stops a sibling origin that can write cookies from planting a pair of its own; the binding stops a token minted for one session from working in another.

The secret must be at least 32 bytes, should be used for CSRF only (not the auth secret), and can be rotated with a list of accepted previous secrets. During a rotation, hand out a token under the current secret whenever a safe request arrives with one signed by a previous secret, or no client ever moves and the previous secret can never be removed without refusing each of them once. Keep the strict compare of header and cookie while doing it: a page that kept the old token in memory is refused once after another request replaced the cookie, and must read the token again (or retry once after a safe request). Accepting an old-secret header over the new cookie would let anyone holding the previous secret, and the binding, mint a header.

Signed in, bind to the session. Signed out, do not bind every visitor to one shared value, or a token pair minted in the attacker’s browser works in the victim’s. Give each logged-out browser its own random pre-session id in an HttpOnly cookie and bind to that; the example app issues it with the first token and renews it on logout.

The example app combines all three; see examples/basic in the repository.

Layers two and three for a signed-in request. The Node server guide has the full module, with the Origin allowlist and the pre-session binding.

csrf.ts
import { createCsrfToken, verifyCsrfToken, verifyFetchSite } from '@noctcore/auth';
// A secret for CSRF only, never the auth secret.
// createCsrfToken refuses one that is too short.
const value = process.env.CSRF_SECRET;
if (!value) throw new Error('Set CSRF_SECRET');
const secret = new TextEncoder().encode(value);
/** Signed in: a token bound to this session, read by the page from a cookie. */
export function csrfToken(sessionId: string): string {
return createCsrfToken(secret, `session:${sessionId}`);
}
/**
* Layers two and three, for a POST, PUT, PATCH or DELETE.
* Layer one is the session cookie's SameSite.
*/
export function csrfAllowed(request: {
method: string;
secFetchSite: string | undefined;
cookieToken: string | undefined;
headerToken: string | undefined;
sessionId: string;
}): boolean {
const sameOrigin = verifyFetchSite({
method: request.method,
secFetchSite: request.secFetchSite,
});
return (
sameOrigin &&
verifyCsrfToken({
cookieToken: request.cookieToken,
headerToken: request.headerToken,
binding: `session:${request.sessionId}`,
secrets: [secret],
})
);
}

The guide’s first recommendation is the Sec-Fetch-Site check, then Origin, then tokens for legacy browsers. The package offers all three, and its example app applies the stricter combination, because apps that serve a desktop shell send requests that are cross-site by definition and need the allowlist anyway:

  • the Origin allowlist always;
  • Sec-Fetch-Site whenever the browser sends it;
  • the token on top.
Test Attack Stopped by
A008 Cross-site request forgery http/csrf.ts, http/cookie.ts
A021 Passing an unsafe request as a safe method through Unicode case folding http/csrf.ts
A026 Cross-site request forgery against a Nest app auth-nestjs/csrf.middleware.ts
A033 Cross-site request forgery against a tRPC mutation auth-trpc/middlewares.ts
A079 Riding the cross-site origin allowlist, through the Nest adapter auth-nestjs/csrf.middleware.ts
A080 Riding the cross-site origin allowlist, through the tRPC adapter auth-trpc/context.ts
A100 Using a token read from the Nest token route for another session or pre-session auth-nestjs/session-cookies.ts
A101 Using a token read from ctx.auth.csrfToken() for another session or pre-session auth-trpc/context.ts
A104 Writing the session from a tRPC query that a link on another site can run auth-trpc/middlewares.ts
A106 Keeping a previous secret in use, so a leaked one cannot be retired without breaking every client http/csrf-adapter.ts