Documentation menuMenu da documentação

$ cat docs/middleware/webhook-signature.md

Webhook signaturesAssinatura de webhooks

Accept a webhook only when it really comes from the provider, only once, and keep the raw body for the handler.Aceite um webhook só quando vem mesmo do provedor, uma vez só, e mantenha o corpo cru para o handler.

What it doesO que faz

webhookSignature(options: WebhookSignatureOptions): MiddlewareHandler. HMAC-SHA256 signatures (hex or base64, optional sha256= prefix, Stripe's t=…,v1=…) are checked with crypto.subtle.verify, in constant time, against any secret of a rotation list. A timestamp outside toleranceSec (default 5 min) is refused. mode: 'token' compares a static token in constant time. With a store, a delivery id seen before answers 200 { duplicate: true } without calling the handler. Presets: github, stripe, asaas.

webhookSignature(options: WebhookSignatureOptions): MiddlewareHandler. Assinaturas HMAC-SHA256 (hex ou base64, prefixo sha256= opcional, o t=…,v1=… da Stripe) são conferidas com crypto.subtle.verify, em tempo constante, contra qualquer segredo de uma lista de rotação. Um timestamp fora de toleranceSec (padrão 5 min) é recusado. mode: 'token' compara um token fixo em tempo constante. Com um store, um id de entrega já visto responde 200 { duplicate: true } sem chamar o handler. Presets: github, stripe, asaas.

Install and orderInstalar e ordenar

terminal
pnpm add @tupik/middleware

Put it on the webhook module only, before the handler. The body is read from a clone: ctx.req.text() and getRawBody(ctx) still work. A failed or 5xx delivery releases its id, so the provider retry goes through.

Coloque só no módulo do webhook, antes do handler. O corpo é lido de um clone: ctx.req.text() e getRawBody(ctx) continuam funcionando. Uma entrega que falha ou dá 5xx libera o id, então a nova tentativa do provedor passa.

ExampleExemplo

webhook-signature.ts
import { createModule } from '@tupik/core';
import { D1TtlStore, webhookSignature } from '@tupik/middleware';

const deliveries = new D1TtlStore({ database: (env) => (env as Env).DB });

const hooks = createModule('/webhooks')
  .use(webhookSignature({ preset: 'asaas', secret: env.ASAAS_WEBHOOK_TOKEN, store: deliveries }))
  // the signature is the check; there is no user
  .post('/asaas', { access: 'public', handler: async (ctx) => handlePayment(await ctx.req.json()) });

const github = createModule('/webhooks/github')
  .use(webhookSignature({ preset: 'github', secret: [env.GH_SECRET_NEW, env.GH_SECRET_OLD], store: deliveries }))
  .post('/', { access: 'public', handler: () => ({ ok: true }) });
import { createModule } from '@tupik/core';
import { D1TtlStore, webhookSignature } from '@tupik/middleware';

const deliveries = new D1TtlStore({ database: (env) => (env as Env).DB });

const hooks = createModule('/webhooks')
  .use(webhookSignature({ preset: 'asaas', secret: env.ASAAS_WEBHOOK_TOKEN, store: deliveries }))
  // a assinatura é a checagem; não há usuário
  .post('/asaas', { access: 'public', handler: async (ctx) => handlePayment(await ctx.req.json()) });

const github = createModule('/webhooks/github')
  .use(webhookSignature({ preset: 'github', secret: [env.GH_SECRET_NEW, env.GH_SECRET_OLD], store: deliveries }))
  .post('/', { access: 'public', handler: () => ({ ok: true }) });

APIAPI

OptionOpçãoTypeTipoDefault / behaviorPadrão / comportamento
preset 'github' | 'stripe' | 'asaas' Provider defaults (header, format, delivery id); other options override them.Padrões do provedor (header, formato, id de entrega); as outras opções os sobrescrevem.
secret / token string | readonly string[] Required. Several values during a rotation.Obrigatório. Vários valores durante uma rotação.
header, prefix, encoding, format string Custom HMAC: signature header, 'sha256=', 'hex' | 'base64', 'plain' | 'stripe'.HMAC próprio: header da assinatura, 'sha256=', 'hex' | 'base64', 'plain' | 'stripe'.
timestampHeader, toleranceSec string, number Signs "<timestamp>.<body>"; 300 s window.Assina "<timestamp>.<body>"; janela de 300 s.
store, deliveryId, dedupeTtlMs TtlStore, string | fn, number Dedup by header or body id; 24 h.Dedup por header ou id do corpo; 24 h.
maxBytes number 1 MiB. Larger bodies answer 413.1 MiB. Corpos maiores respondem 413.

type WebhookSignatureOptions = HmacWebhookOptions | TokenWebhookOptions | PresetWebhookOptions

type WebhookSignatureOptions = HmacWebhookOptions | TokenWebhookOptions | PresetWebhookOptions

Errors and limitsErros e limites

  • Bad or missing signature, token or timestamp: 401 WEBHOOK_SIGNATURE_INVALID (one code for all, no oracle).
  • An empty secret list, an unknown preset or a missing header throws at creation.
  • Dedup runs only after the signature passes, so forged ids cannot poison the store. KVTtlStore is not atomic: two racing deliveries may both pass.
  • Assinatura, token ou timestamp inválido ou ausente: 401 WEBHOOK_SIGNATURE_INVALID (um código só, sem oráculo).
  • Lista de segredos vazia, preset desconhecido ou header ausente lança na criação.
  • A dedup só roda depois da assinatura passar, então ids forjados não envenenam o store. O KVTtlStore não é atômico: duas entregas simultâneas podem passar.

When not to use itQuando não usar

Token mode (Asaas) has no signature over the body: anyone with the token can send events, so keep it secret and check the event against the provider API for money moves.

O modo token (Asaas) não assina o corpo: quem tem o token envia eventos, então guarde-o em segredo e confira o evento na API do provedor para movimentos de dinheiro.