Documentation menuMenu da documentação

$ cat docs/recipes/session-csrf.md

Recipe: sessions and CSRFReceita: sessão e CSRF

Log users in with a server side session, bind the CSRF token to that session and let the session feed access.Faça login com sessão no servidor, ligue o token CSRF a essa sessão e deixe a sessão alimentar o access.

The piecesAs peças

  • session keeps the login on the server. The browser holds only a random id in __Host-tupik_session (Secure, HttpOnly, SameSite=Lax); the store sees only its SHA-256.
  • csrf({ session: sessions }) signs the token with the session id, so a token from one session fails on another.
  • createApp({ authenticate }) reads the session and returns the principal. access does the rest: 401 without login, 403 for a denied policy, 404 for someone else's record.
  • session guarda o login no servidor. O navegador só tem um id aleatório em __Host-tupik_session (Secure, HttpOnly, SameSite=Lax); o store só vê o SHA-256 dele.
  • csrf({ session: sessions }) assina o token com o id da sessão, então o token de uma sessão falha em outra.
  • createApp({ authenticate }) lê a sessão e devolve o principal. O access faz o resto: 401 sem login, 403 para política negada, 404 para registro de outro.

ServerServidor

Register session before csrf. Run D1SessionStore.schema() once as a migration. authenticate runs after the middleware, so it can read sessions.get(ctx).

Registre o session antes do csrf. Rode D1SessionStore.schema() uma vez como migration. O authenticate roda depois dos middlewares, então pode ler sessions.get(ctx).

app.ts
import { createApp, createModule } from '@tupik/core';
import { csrf, D1SessionStore, rateLimit, session } from '@tupik/middleware';
import { verifyPassword } from '@tupik/password';
import { z } from 'zod';
import { users } from './users';

type User = { id: string; role: 'admin' | 'member' };

// declare the principal once for every module
declare module '@tupik/core' {
  interface TupikRegister {
    principal: User;
  }
}

const sessions = session<User>({
  store: new D1SessionStore({ database: (env) => (env as Env).DB }),
  idleTimeoutMs: 30 * 60_000,
});

const app = createApp({
  // the principal comes from the session
  authenticate: (ctx) => sessions.get(ctx).data ?? null,
})
  .use(sessions)
  .use(csrf({ secret: CSRF_SECRET, session: sessions, origins: ['https://app.example.com'] }));

const Login = z.object({ email: z.string().email(), password: z.string().min(1) });

const auth = createModule('/auth')
  .use(rateLimit({ windowMs: 60_000, limit: 10, trust: 'cloudflare' }))
  .post('/login', {
    access: 'public',
    schema: { body: Login },
    handler: async (ctx) => {
      const user = await users.byEmail(ctx.body.email);
      if (user === undefined || !(await verifyPassword(user.passwordHash, ctx.body.password))) {
        return ctx.status(401).json({ ok: false });
      }
      // always a new id: no session fixation
      await sessions.get(ctx).create({ id: user.id, role: user.role }, { userId: user.id });
      return { ok: true };
    },
  })
  .post('/logout', {
    access: 'authenticated',
    handler: async (ctx) => {
      await sessions.get(ctx).destroy();
      return { ok: true };
    },
  })
  .post('/logout-everywhere', {
    access: 'authenticated',
    handler: async (ctx) => ({ revoked: await sessions.get(ctx).revokeAll() }),
  });

const me = createModule('/me').get('/', {
  access: 'authenticated',
  handler: (ctx) => ({ id: ctx.principal.id, role: ctx.principal.role }),
});

app.register(auth).register(me);
export default app;
import { createApp, createModule } from '@tupik/core';
import { csrf, D1SessionStore, rateLimit, session } from '@tupik/middleware';
import { verifyPassword } from '@tupik/password';
import { z } from 'zod';
import { users } from './users';

type User = { id: string; role: 'admin' | 'member' };

// declare o principal uma vez para todos os módulos
declare module '@tupik/core' {
  interface TupikRegister {
    principal: User;
  }
}

const sessions = session<User>({
  store: new D1SessionStore({ database: (env) => (env as Env).DB }),
  idleTimeoutMs: 30 * 60_000,
});

const app = createApp({
  // o principal vem da sessão
  authenticate: (ctx) => sessions.get(ctx).data ?? null,
})
  .use(sessions)
  .use(csrf({ secret: CSRF_SECRET, session: sessions, origins: ['https://app.example.com'] }));

const Login = z.object({ email: z.string().email(), password: z.string().min(1) });

const auth = createModule('/auth')
  .use(rateLimit({ windowMs: 60_000, limit: 10, trust: 'cloudflare' }))
  .post('/login', {
    access: 'public',
    schema: { body: Login },
    handler: async (ctx) => {
      const user = await users.byEmail(ctx.body.email);
      if (user === undefined || !(await verifyPassword(user.passwordHash, ctx.body.password))) {
        return ctx.status(401).json({ ok: false });
      }
      // sempre um id novo: sem fixação de sessão
      await sessions.get(ctx).create({ id: user.id, role: user.role }, { userId: user.id });
      return { ok: true };
    },
  })
  .post('/logout', {
    access: 'authenticated',
    handler: async (ctx) => {
      await sessions.get(ctx).destroy();
      return { ok: true };
    },
  })
  .post('/logout-everywhere', {
    access: 'authenticated',
    handler: async (ctx) => ({ revoked: await sessions.get(ctx).revokeAll() }),
  });

const me = createModule('/me').get('/', {
  access: 'authenticated',
  handler: (ctx) => ({ id: ctx.principal.id, role: ctx.principal.role }),
});

app.register(auth).register(me);
export default app;

BrowserNavegador

The CSRF cookie is not HttpOnly on purpose: the page reads it and sends it back in x-csrf-token. Safe methods (GET, HEAD, OPTIONS) issue or refresh the cookie. Unsafe methods need the header to match the cookie and the signature to match the session.

O cookie CSRF não é HttpOnly, de propósito: a página o lê e devolve em x-csrf-token. Métodos seguros (GET, HEAD, OPTIONS) emitem ou renovam o cookie. Métodos inseguros exigem que o header bata com o cookie e que a assinatura bata com a sessão.

client.ts
// 1. any GET sets the __Host-tupik_csrf cookie (readable by the page)
await fetch('/me', { credentials: 'include' });
const token = document.cookie.match(/__Host-tupik_csrf=([^;]+)/)?.[1] ?? '';

// 2. unsafe methods echo it in x-csrf-token
await fetch('/auth/login', {
  method: 'POST',
  credentials: 'include',
  headers: { 'content-type': 'application/json', 'x-csrf-token': token },
  body: JSON.stringify({ email, password }),
});
// 1. qualquer GET grava o cookie __Host-tupik_csrf (legível pela página)
await fetch('/me', { credentials: 'include' });
const token = document.cookie.match(/__Host-tupik_csrf=([^;]+)/)?.[1] ?? '';

// 2. métodos inseguros repetem o valor em x-csrf-token
await fetch('/auth/login', {
  method: 'POST',
  credentials: 'include',
  headers: { 'content-type': 'application/json', 'x-csrf-token': token },
  body: JSON.stringify({ email, password }),
});

After login the session id changes, so the old token no longer matches. The next GET replaces it; read the cookie again before the next POST.

Depois do login o id da sessão muda, então o token antigo deixa de valer. O próximo GET troca o cookie; leia o cookie de novo antes do próximo POST.

What can go wrongO que pode dar errado

  • 403 CSRF_INVALID on login: the page sent no GET before the POST, or sent a token from before the last login.
  • A request from an Origin outside origins gets 403, even with a valid token.
  • __Host- cookies need HTTPS. On plain http://localhost use cookie: { name, secure: false } in session and cookieName plus secure: false in csrf, only in development.
  • With KVSessionStore, logout can take about a minute to reach every location. Use D1SessionStore when revocation must be immediate.
  • 403 CSRF_INVALID no login: a página não fez um GET antes do POST, ou mandou o token de antes do último login.
  • Pedido de um Origin fora de origins recebe 403, mesmo com token válido.
  • Cookies __Host- exigem HTTPS. Em http://localhost puro, use cookie: { name, secure: false } no session e cookieName com secure: false no csrf, só em desenvolvimento.
  • Com KVSessionStore, o logout pode levar cerca de um minuto para chegar a todos os locais. Use D1SessionStore quando a revogação precisa ser imediata.