Documentation menuMenu da documentação

$ cat docs/recipes/webhooks.md

Recipe: webhooksReceita: webhooks

Accept webhooks only with a valid signature, drop repeated deliveries and make your own write endpoints safe to retry.Aceite webhooks só com assinatura válida, descarte entregas repetidas e deixe os seus endpoints de escrita seguros para nova tentativa.

Verify the signatureConferir a assinatura

webhookSignature has presets: github (x-hub-signature-256, sha256= hex), stripe (stripe-signature with t= and v1=) and asaas (static token in asaas-access-token). The HMAC is compared in constant time. With a timestamp, a delivery older than toleranceSec (300 s by default) fails. A failure answers 401 WEBHOOK_SIGNATURE_INVALID; a body over maxBytes (1 MiB) answers 413.

webhookSignature tem presets: github (x-hub-signature-256, hex com sha256=), stripe (stripe-signature com t= e v1=) e asaas (token fixo em asaas-access-token). O HMAC é comparado em tempo constante. Com carimbo de tempo, entrega mais velha que toleranceSec (300 s por padrão) falha. A falha responde 401 WEBHOOK_SIGNATURE_INVALID; corpo acima de maxBytes (1 MiB) responde 413.

The route is access: 'public' because there is no user: the signature is what authenticates the caller. secret also takes a list, for rotation.

A rota é access: 'public' porque não há usuário: a assinatura é o que autentica quem chama. O secret também aceita uma lista, para rotação.

Drop repeated deliveriesDescartar entregas repetidas

Providers retry. With a store, the delivery id (x-github-delivery, or the event id for Stripe and Asaas) is remembered for dedupeTtlMs (24 h). A repeat answers 200 { duplicate: true } without running the handler. If the handler throws or answers 5xx, the id is forgotten so the next retry runs.

Os provedores tentam de novo. Com um store, o id da entrega (x-github-delivery, ou o id do evento no Stripe e no Asaas) fica guardado por dedupeTtlMs (24 h). A repetição responde 200 { duplicate: true } sem rodar o handler. Se o handler lançar ou responder 5xx, o id é esquecido e a próxima tentativa roda.

Idempotent writes for your clientsEscritas idempotentes para os seus clientes

idempotency covers your own POST and PATCH routes. The first response per Idempotency-Key, principal and route is stored and replayed with idempotent-replayed: true. The same key with another body answers 422 IDEMPOTENCY_KEY_REUSED; a retry while the first is running answers 409 IDEMPOTENCY_IN_PROGRESS. Errors are not stored.

idempotency cobre as suas rotas POST e PATCH. A primeira resposta por Idempotency-Key, principal e rota fica guardada e é repetida com idempotent-replayed: true. A mesma chave com outro corpo responde 422 IDEMPOTENCY_KEY_REUSED; nova tentativa enquanto a primeira roda responde 409 IDEMPOTENCY_IN_PROGRESS. Erros não são guardados.

app.ts
import { createApp, createModule } from '@tupik/core';
import { D1TtlStore, idempotency, rateLimit, webhookSignature } from '@tupik/middleware';
import { z } from 'zod';
import { auth, payments } from './services';

// run D1TtlStore.schema() once as a migration
const seen = new D1TtlStore({ database: (env) => (env as Env).DB });

const Event = z.object({ id: z.string(), type: z.string(), data: z.unknown() });

const webhooks = createModule('/webhooks')
  .use(
    webhookSignature({
      preset: 'stripe', // stripe-signature: t=...,v1=..., 300 s window
      secret: STRIPE_WEBHOOK_SECRET,
      store: seen, // a repeated event id answers 200 { duplicate: true }
    }),
  )
  .post('/stripe', {
    // no user here: the signature is the authentication
    access: 'public',
    schema: { body: Event },
    handler: async (ctx) => {
      if (ctx.body.type === 'checkout.session.completed') await payments.markPaid(ctx.body.id, ctx.body.data);
      return { received: true };
    },
  });

const api = createModule('/payments')
  .use(rateLimit({ windowMs: 60_000, limit: 30, trust: 'cloudflare' }))
  .use(
    idempotency({
      store: seen,
      required: true, // no Idempotency-Key: 400
      principal: async (ctx) => (await ctx.getPrincipal())?.id, // the user, not a header
    }),
  )
  .post('/', {
    access: 'authenticated',
    schema: { body: z.object({ amount: z.number().int().positive() }) },
    handler: async (ctx) => ctx.status(201).json(await payments.create(ctx.principal.id, ctx.body.amount)),
  });

export default createApp({ authenticate: (ctx) => auth.userFromRequest(ctx.req) }).register(webhooks).register(api);
import { createApp, createModule } from '@tupik/core';
import { D1TtlStore, idempotency, rateLimit, webhookSignature } from '@tupik/middleware';
import { z } from 'zod';
import { auth, payments } from './services';

// rode D1TtlStore.schema() uma vez como migration
const seen = new D1TtlStore({ database: (env) => (env as Env).DB });

const Event = z.object({ id: z.string(), type: z.string(), data: z.unknown() });

const webhooks = createModule('/webhooks')
  .use(
    webhookSignature({
      preset: 'stripe', // stripe-signature: t=...,v1=..., janela de 300 s
      secret: STRIPE_WEBHOOK_SECRET,
      store: seen, // um id de evento repetido responde 200 { duplicate: true }
    }),
  )
  .post('/stripe', {
    // não há usuário aqui: a assinatura é a autenticação
    access: 'public',
    schema: { body: Event },
    handler: async (ctx) => {
      if (ctx.body.type === 'checkout.session.completed') await payments.markPaid(ctx.body.id, ctx.body.data);
      return { received: true };
    },
  });

const api = createModule('/payments')
  .use(rateLimit({ windowMs: 60_000, limit: 30, trust: 'cloudflare' }))
  .use(
    idempotency({
      store: seen,
      required: true, // sem Idempotency-Key: 400
      principal: async (ctx) => (await ctx.getPrincipal())?.id, // o usuário, não um header
    }),
  )
  .post('/', {
    access: 'authenticated',
    schema: { body: z.object({ amount: z.number().int().positive() }) },
    handler: async (ctx) => ctx.status(201).json(await payments.create(ctx.principal.id, ctx.body.amount)),
  });

export default createApp({ authenticate: (ctx) => auth.userFromRequest(ctx.req) }).register(webhooks).register(api);

What can go wrongO que pode dar errado

  • KVTtlStore can race: two copies of the same delivery may both run. Use D1TtlStore or MemoryTtlStore, where add is atomic.
  • A Hono or proxy layer that reads the body first breaks the signature. The bytes must reach the middleware untouched.
  • idempotency runs before access, so principal reads the caller with await ctx.getPrincipal(). The id is hashed into the key and never stored; access reuses the same principal.
  • O KVTtlStore pode correr em paralelo: duas cópias da mesma entrega podem rodar. Use D1TtlStore ou MemoryTtlStore, onde o add é atômico.
  • Uma camada Hono ou proxy que lê o corpo antes quebra a assinatura. Os bytes precisam chegar intactos ao middleware.
  • O idempotency roda antes do access, então o principal lê quem chama com await ctx.getPrincipal(). O id entra no hash da chave e nunca é guardado; o access reaproveita o mesmo principal.