Documentation menuMenu da documentação

$ cat docs/middleware/csrf.md

CSRFCSRF

Protect state-changing routes with a signed double-submit token: the cookie proves the client can read it, and the signature proves the value was issued by this app.Proteja rotas que mudam estado com um token double-submit assinado: o cookie prova que o cliente consegue lê-lo, e a assinatura prova que o valor foi emitido por este app.

What it doesO que faz

csrf(options: CsrfOptions): MiddlewareHandler. Safe methods (GET, HEAD, OPTIONS, TRACE) ensure a valid signed cookie exists; a missing or invalid cookie gets a new token, while a valid one is never rotated. Unsafe methods require the configured header to equal the cookie and the token signature to verify. The token is a base64url 32-byte nonce plus a dot plus a base64url HMAC-SHA-256 signature over that nonce (and the session id, when given), produced with crypto.subtle and the configured secret. The cookie defaults to __Host-tupik_csrf with Path=/, Secure, SameSite=Lax and no Domain; the header defaults to x-csrf-token. On failure the middleware answers 403 { code: 'CSRF_INVALID', message: 'Invalid CSRF token' } without calling the handler.

csrf(options: CsrfOptions): MiddlewareHandler. Métodos seguros (GET, HEAD, OPTIONS, TRACE) garantem que existe um cookie assinado válido; um cookie ausente ou inválido recebe um token novo, enquanto um válido nunca é rotacionado. Métodos inseguros exigem que o header configurado seja igual ao cookie e que a assinatura do token confira. O token é um nonce de 32 bytes em base64url, um ponto e uma assinatura HMAC-SHA-256 em base64url sobre esse nonce (e o id da session, quando informado), produzida com crypto.subtle e o secret configurado. O cookie padrão é __Host-tupik_csrf com Path=/, Secure, SameSite=Lax e sem Domain; o header padrão é x-csrf-token. Em falha o middleware responde 403 { code: 'CSRF_INVALID', message: 'Invalid CSRF token' } sem chamar o handler.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Register it with app.use(csrf(...)) so every state-changing route is covered, or with createModule().use(csrf(...)) to protect one module. Put it before the routes it protects. Read secret from your environment; rotating the secret invalidates every token already issued. Pass origins when browsers call the API cross-origin: an unsafe request whose Origin is not listed gets 403. Without Origin (or without origins), Sec-Fetch-Site must be same-origin, same-site, none or absent (older browsers and non-browser clients); same-site admits sibling subdomains.

Registre com app.use(csrf(...)) para cobrir todas as rotas que mudam estado, ou com createModule().use(csrf(...)) para proteger um módulo. Coloque-o antes das rotas que ele protege. Leia secret do ambiente; rotacionar o segredo invalida todos os tokens já emitidos. Passe origins quando navegadores chamam a API de outra origem: requisição insegura com Origin fora da lista recebe 403. Sem Origin (ou sem origins), o Sec-Fetch-Site precisa ser same-origin, same-site, none ou ausente (navegadores antigos e clientes fora do navegador); same-site admite subdomínios irmãos.

ExampleExemplo

csrf.ts
import { createApp, createModule } from '@tupik/core';
import { csrf } from '@tupik/middleware';

// Secrets come from the runtime environment, never from source control.
const CSRF_SECRET = 'replace-with-a-long-random-secret';

// currentUser reads your session; csrf is not authentication
const app = createApp({ authenticate: (ctx) => currentUser(ctx) }).use(
  csrf({
    secret: CSRF_SECRET,
    origins: ['https://app.example.com'],
    // binds the token to the session (from your session middleware)
    session: (ctx) => ctx.rawStore.get('sessionId') as string | undefined,
  }),
);

app.register(
  createModule('/api')
    // safe route: sets __Host-tupik_csrf when the cookie is missing or invalid
    .get('/session', { access: 'public', handler: () => ({ ok: true }) })
    // unsafe route: needs cookie === x-csrf-token
    .post('/orders', { access: 'authenticated', handler: () => ({ created: true }) }),
);

// Client: read the non-HttpOnly cookie and echo it in the header.
const token = document.cookie
  .split('; ')
  .find((part) => part.startsWith('__Host-tupik_csrf='))
  ?.slice('__Host-tupik_csrf='.length);

await fetch('/api/orders', {
  method: 'POST',
  headers: token === undefined ? {} : { 'x-csrf-token': token },
});
import { createApp, createModule } from '@tupik/core';
import { csrf } from '@tupik/middleware';

// Secrets come from the runtime environment, never from source control.
const CSRF_SECRET = 'replace-with-a-long-random-secret';

// currentUser lê a sua sessão; csrf não é autenticação
const app = createApp({ authenticate: (ctx) => currentUser(ctx) }).use(
  csrf({
    secret: CSRF_SECRET,
    origins: ['https://app.example.com'],
    // liga o token à sessão (do seu middleware de sessão)
    session: (ctx) => ctx.rawStore.get('sessionId') as string | undefined,
  }),
);

app.register(
  createModule('/api')
    // rota segura: define __Host-tupik_csrf quando o cookie falta ou é inválido
    .get('/session', { access: 'public', handler: () => ({ ok: true }) })
    // rota insegura: exige cookie === x-csrf-token
    .post('/orders', { access: 'authenticated', handler: () => ({ created: true }) }),
);

// Client: read the non-HttpOnly cookie and echo it in the header.
const token = document.cookie
  .split('; ')
  .find((part) => part.startsWith('__Host-tupik_csrf='))
  ?.slice('__Host-tupik_csrf='.length);

await fetch('/api/orders', {
  method: 'POST',
  headers: token === undefined ? {} : { 'x-csrf-token': token },
});

A first GET to /api/session receives the token cookie. JavaScript can read it because the cookie is intentionally not HttpOnly; the client then echoes the same value in x-csrf-token on POST. A cross-site form cannot read the cookie, so it cannot fill the header.

Um primeiro GET em /api/session recebe o cookie com o token. O JavaScript consegue lê-lo porque o cookie de propósito não é HttpOnly; o cliente então ecoa o mesmo valor em x-csrf-token no POST. Um formulário de outro site não consegue ler o cookie, então não consegue preencher o header.

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
secretstringRequired. HMAC key used to sign and verify; an empty value throws TypeError.Obrigatório. Chave HMAC usada para assinar e verificar; um valor vazio lança TypeError.
cookieNamestring__Host-tupik_csrf. Must be a valid HTTP token; the cookie is always emitted on Path=/ without Domain.__Host-tupik_csrf. Precisa ser um token HTTP válido; o cookie é sempre emitido em Path=/ sem Domain.
headerNamestringx-csrf-token. Must be a valid HTTP token; compared case-insensitively as a header name.x-csrf-token. Precisa ser um token HTTP válido; comparado sem diferenciar maiúsculas como nome de header.
originsreadonly string[]Absent. When set, an unlisted Origin gets 403; without Origin, Sec-Fetch-Site decides.Ausente. Quando definido, Origin fora da lista recebe 403; sem Origin, o Sec-Fetch-Site decide.
session(ctx) => string | undefined | Promise<…>Absent. Session id mixed into the HMAC: a token from another session is rejected.Ausente. Id da sessão incluído no HMAC: token de outra sessão é rejeitado.
securebooleantrue. Emits Secure on the cookie; false is only for local HTTP development and needs a cookieName without __Host-.true. Emite Secure no cookie; false serve só para desenvolvimento HTTP local e exige cookieName sem __Host-.
sameSite'Strict' | 'Lax' | 'None'Lax. None requires secure: true, otherwise the factory throws TypeError.Lax. None exige secure: true, senão a factory lança TypeError.

interface CsrfOptions { secret: string; session?: (ctx) => string | undefined | Promise<string | undefined>; cookieName?: string; headerName?: string; origins?: readonly string[]; secure?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' }

interface CsrfOptions { secret: string; session?: (ctx) => string | undefined | Promise<string | undefined>; cookieName?: string; headerName?: string; origins?: readonly string[]; secure?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' }

Errors and limitsErros e limites

  • This is not authentication, session storage or a replacement for HTTPS. It proves only that the caller could read the token cookie; pair it with an authenticated session when you need identity.
  • The signed token has no expiry. Without session it is not bound to a user: a valid cookie/header pair can be replayed until the cookie is replaced, cleared or the secret changes. Pass session to bind it.
  • The cookie is intentionally not HttpOnly, so any script running on the page, including injected XSS, can read it. Keep output escaping and a Content Security Policy.
  • Origin is supplied by the client; non-browser clients can forge it. The exact-match check is a defense in depth, not proof of origin.
  • Safe methods are not protected. A state-changing GET is outside this middleware's guarantees.
  • An empty secret or sameSite: 'None' with secure: false throws TypeError when the factory is called. Existing set-cookie values from the handler are preserved.
  • Isto não é autenticação, armazenamento de sessão nem substituto para HTTPS. Ele prova apenas que o chamador conseguia ler o cookie do token; combine com uma sessão autenticada quando precisar de identidade.
  • O token assinado não expira. Sem session ele não é ligado a um usuário: um par cookie/header válido pode ser reenviado até o cookie ser substituído, apagado ou o segredo mudar. Passe session para ligá-lo.
  • O cookie de propósito não é HttpOnly, então qualquer script na página, inclusive XSS injetado, consegue lê-lo. Mantenha escape de saída e uma Content Security Policy.
  • Origin é fornecido pelo cliente; clientes que não são navegadores podem forjá-lo. A checagem exata é defesa em profundidade, não prova de origem.
  • Métodos seguros não são protegidos. Um GET que muda estado está fora das garantias deste middleware.
  • Um secret vazio ou sameSite: 'None' com secure: false lança TypeError quando a factory é chamada. Valores set-cookie já definidos pelo handler são preservados.

When not to use itQuando não usar

Do not use csrf as your authentication layer, as server-side session storage or as a substitute for HTTPS. If the API is called only by trusted server-to-server clients, a bearer token or mutual TLS is the right control. If you need revocation or per-user tokens, keep the session server-side and validate it; this middleware deliberately keeps no state. Do not rely on it alone for same-site policy: set SameSite and a correct Origin allow-list as well.

Não use csrf como camada de autenticação, como armazenamento de sessão no servidor nem como substituto de HTTPS. Se a API é chamada só por clientes confiáveis servidor a servidor, um token bearer ou mTLS é o controle certo. Se precisar de revogação ou tokens por usuário, mantenha a sessão no servidor e valide-a; este middleware de propósito não guarda estado. Não confie só nele para política same-site: defina SameSite e uma allow-list correta de Origin também.