Documentation menuMenu da documentação

$ cat docs/middleware/jwt.md

JWTJWT

Verify HMAC-signed bearer tokens with WebCrypto and expose the claims to the matched handler through ctx.rawStore.Verifique tokens Bearer assinados com HMAC usando WebCrypto e exponha as claims ao handler casado via ctx.rawStore.

What it doesO que faz

jwt(options: JwtOptions): MiddlewareHandler. Reads a Bearer token from authorization (or the raw value of a custom header), verifies HMAC HS256/HS384/HS512 with crypto.subtle and checks exp/nbf/iat with clockToleranceSec leeway. exp is required by default (requireExp: false to opt out), audience/issuer are checked when given, secrets shorter than 32 bytes throw at creation and a kid → secret map enables key rotation. On success the payload goes to ctx.rawStore under 'jwt' and 'jwt.claims'. On failure: 401 { code: 'UNAUTHORIZED' } plus www-authenticate.

jwt(options: JwtOptions): MiddlewareHandler. Lê um token Bearer de authorization (ou o valor cru de um header customizado), verifica HMAC HS256/HS384/HS512 com crypto.subtle e checa exp/nbf/iat com tolerância clockToleranceSec. exp é obrigatório por padrão (requireExp: false desliga), audience/issuer são checados quando informados, segredos com menos de 32 bytes lançam na criação e um mapa kid → segredo permite rotação de chave. Em caso de sucesso o payload vai para ctx.rawStore em 'jwt' e 'jwt.claims'. Em falha: 401 { code: 'UNAUTHORIZED' } mais www-authenticate.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Put .use(jwt(...)) before the protected routes of a module. alg: none and algorithms outside algorithms are always rejected; a secret under 32 bytes (UTF-8) throws at setup, in signJwt and in verifyJwt. With required: false, requests without a token continue without a payload (an invalid token is still 401).

Coloque .use(jwt(...)) antes das rotas protegidas do módulo. alg: none e algoritmos fora de algorithms são sempre rejeitados; secret com menos de 32 bytes (UTF-8) lança na configuração, no signJwt e no verifyJwt. Com required: false, requisições sem token seguem sem payload (um token inválido continua 401).

ExampleExemplo

auth.ts
import { createApp, createModule } from '@tupik/core';
import { jwt, signJwt, verifyJwt } from '@tupik/middleware';

const secret = env.JWT_SECRET; // at least 32 bytes
const admin = createModule('/admin')
  .use(jwt({ secret, audience: 'api', issuer: 'https://auth.example', clockToleranceSec: 5 }))
// rotation: kid → secret; a token with an unknown kid is rejected
// jwt({ secret: { '2026-12': env.JWT_SECRET, '2026-11': env.JWT_SECRET_OLD } })
  .get('/me', { access: 'authenticated', handler: (ctx) => ({ claims: ctx.rawStore.get('jwt.claims') }) });

// the verified claims become the principal that access checks
const app = createApp({ authenticate: (ctx) => ctx.rawStore.get('jwt.claims') ?? null }).register(admin);

const token = await signJwt({ sub: 'u_1', aud: 'api', iss: 'https://auth.example' }, secret, { expiresInSec: 3600 });
// GET /admin/me + authorization: Bearer <token> → 200 { claims: { sub: 'u_1', ... } }
// no token → 401 { code: 'UNAUTHORIZED', message: 'Missing bearer token' }
//            www-authenticate: Bearer realm="tupik"

const result = await verifyJwt(token, secret);
if (result.valid) console.log(result.payload.sub); // 'u_1'
else console.log(result.reason); // 'Token expired' | 'Missing exp claim' | 'Invalid audience' | 'Unknown key id' | ...
import { createApp, createModule } from '@tupik/core';
import { jwt, signJwt, verifyJwt } from '@tupik/middleware';

const secret = env.JWT_SECRET; // pelo menos 32 bytes
const admin = createModule('/admin')
  .use(jwt({ secret, audience: 'api', issuer: 'https://auth.example', clockToleranceSec: 5 }))
// rotação: kid → segredo; token com kid desconhecido é rejeitado
// jwt({ secret: { '2026-12': env.JWT_SECRET, '2026-11': env.JWT_SECRET_OLD } })
  .get('/me', { access: 'authenticated', handler: (ctx) => ({ claims: ctx.rawStore.get('jwt.claims') }) });

// as claims verificadas viram o principal que o access confere
const app = createApp({ authenticate: (ctx) => ctx.rawStore.get('jwt.claims') ?? null }).register(admin);

const token = await signJwt({ sub: 'u_1', aud: 'api', iss: 'https://auth.example' }, secret, { expiresInSec: 3600 });
// GET /admin/me + authorization: Bearer <token> → 200 { claims: { sub: 'u_1', ... } }
// sem token → 401 { code: 'UNAUTHORIZED', message: 'Missing bearer token' }
//            www-authenticate: Bearer realm="tupik"

const result = await verifyJwt(token, secret);
if (result.valid) console.log(result.payload.sub); // 'u_1'
else console.log(result.reason); // 'Token expired' | 'Missing exp claim' | 'Invalid audience' | 'Unknown key id' | ...

APIAPI

ExportExportSignatureAssinatura
JwtOptions{ secret: JwtSecret; algorithms?: JwtAlgorithm[]; header?: string; required?: boolean; requireExp?: boolean; audience?: string | string[]; issuer?: string | string[]; clockToleranceSec?: number }
signJwt(payload: JwtPayload, secret: string, options?: SignJwtOptions) => Promise<string>
verifyJwt(token: string, secret: JwtSecret, options?: VerifyJwtOptions) => Promise<JwtVerifyResult>
JwtSecretstring | Readonly<Record<string, string>> (kid → secret map for rotation)(mapa kid → segredo para rotação)
base64UrlEncode(bytes: Uint8Array) => string
base64UrlDecode(input: string) => Uint8Array (strict; throws TypeError on invalid input)(estrito; lança TypeError em entrada inválida)
JwtAlgorithm'HS256' | 'HS384' | 'HS512'
JwtPayloadRecord<string, unknown>
JwtHeader{ alg: string; typ?: string; [key: string]: unknown }
SignJwtOptions{ algorithm?: JwtAlgorithm; expiresInSec?: number; header?: Record<string, unknown> }
VerifyJwtOptions{ algorithms?: readonly JwtAlgorithm[]; requireExp?: boolean; audience?: string | string[]; issuer?: string | string[]; clockToleranceSec?: number; now?: number }
JwtVerifyResult{ valid: true; header: JwtHeader; payload: JwtPayload } | { valid: false; reason: string }

Errors and limitsErros e limites

  • jwt is not a session store: there is no revocation, refresh, logout or central user record. A stolen token is valid until it expires.
  • Only HMAC HS256/HS384/HS512 are supported; asymmetric keys are not. Pass audience and issuer so a token minted for another service is rejected.
  • An invalid token is always 401, even with required: false; only a missing token may pass through.
  • jwt não é um session store: não há revogação, refresh, logout ou registro central de usuários. Um token roubado vale até expirar.
  • Só HMAC HS256/HS384/HS512 são suportados; chaves assimétricas não. Passe audience e issuer para rejeitar token emitido para outro serviço.
  • Um token inválido é sempre 401, mesmo com required: false; só a ausência de token pode passar.

When not to use itQuando não usar

Use a full identity provider or a session layer when you need revocation, roles stored server-side or asymmetric signing. Leave public routes outside the module that carries the jwt middleware.

Use um provedor de identidade completo ou uma camada de sessão quando precisar de revogação, papéis guardados no servidor ou assinatura assimétrica. Deixe rotas públicas fora do módulo que carrega o middleware jwt.