pattern/messaging/webhook
- Bun
- ElysiaJS
- TypeScript
- node:crypto
O gateway notifica o lojista por HTTP POST; o receptor valida a assinatura HMAC antes de aceitar (padrão Stripe, PagSeguro, Pagar.me).
pattern/messaging/webhook
Cenário
Aprovação do PAY-001 chega ao lojista; uma notificação forjada com valor maior é recusada.
Planta
Sequência5 passos — reproduza para seguir o fluxo
Como funciona
4passos
O gateway notifica o lojista por HTTP POST e o receptor valida a assinatura HMAC antes de aceitar
Esconde cada passo: lembre antes de tocar para revelar.
HMAC-SHA256 de id.timestamp.corpo com segredo compartilhado (Standard Webhooks)
O receptor recalcula sobre o corpo cru
Comparação em tempo constante; timestamp fora de 5 min recusado
Assinatura inválida400, nunca 5xx, para não haver retry
Trade-offs
O que se ganha, o que se paga
Vantagens
Notificação imediata, sem polling
Origem comprovada
Custos
Receptor precisa ser público
Segredo exige rotação e guarda
Código
pattern/messaging/webhook
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: assinatura com o segredo compartilhado: 200 e evento payment.approved aceito; assinatura com segredo chutado: 400.
Código
src/demo.ts// Demo: the payment gateway posts a signed event to the merchant's Elysia receiver, which accepts it only if the HMAC matches.
import { createHmac, timingSafeEqual } from "node:crypto";
import { Elysia } from "elysia";
const WEBHOOK_SECRET = Bun.env.WEBHOOK_SECRET ?? "local-demo-secret-with-at-least-32-chars";
// A captured request stops being replayable after five minutes.
const WEBHOOK_TOLERANCE_S = 300;
const WEBHOOK_RECEIVER_PORT = Number(Bun.env.WEBHOOK_RECEIVER_PORT ?? 3099);
// Standard Webhooks: HMAC-SHA256 over "id.timestamp.body", so neither the id nor the timestamp can be swapped.
const webhookSign = (secret: string, id: string, timestamp: string, body: string) => `v1,${createHmac("sha256", secret).update(`${id}.${timestamp}.${body}`).digest("base64")}`;
const receiver = new Elysia()
.post(
"/webhooks/payments",
async ({ request, headers, status }) => {
const body = await request.text(); // raw: the signature covers these exact bytes
const [id, timestamp] = [headers["webhook-id"] ?? "", headers["webhook-timestamp"] ?? ""];
const expected = Buffer.from(webhookSign(WEBHOOK_SECRET, id, timestamp, body));
const received = Buffer.from(headers["webhook-signature"] ?? "");
// Constant-time compare, length first: timingSafeEqual throws on different lengths.
const signed = received.length === expected.length && timingSafeEqual(received, expected);
// 400, never 5xx: a 5xx would make the gateway retry a request that can never pass.
if (!signed || Math.abs(Date.now() / 1_000 - Number(timestamp)) > WEBHOOK_TOLERANCE_S) return status(400, { error: "webhook.signature.invalid" });
console.log(` [MERCHANT] ${id} accepted: ${body}`);
return { received: true };
},
{ parse: "none" }, // no parser: the body reaches the handler untouched
)
.listen(WEBHOOK_RECEIVER_PORT);
async function webhookPost(secret: string, event: object): Promise<number> {
const [id, timestamp, body] = [`evt_${crypto.randomUUID().slice(0, 8)}`, String(Math.floor(Date.now() / 1_000)), JSON.stringify(event)];
const headers = { "content-type": "application/json", "webhook-id": id, "webhook-timestamp": timestamp, "webhook-signature": webhookSign(secret, id, timestamp, body) };
return (await fetch(`http://localhost:${WEBHOOK_RECEIVER_PORT}/webhooks/payments`, { method: "POST", headers, body })).status;
}
const event = { type: "payment.approved", paymentId: "PAY-001", amountCents: 29_990 };
console.log(` [GATEWAY] signed with the shared secret → ${await webhookPost(WEBHOOK_SECRET, event)}`);
console.log(` [ATTACKER] signed with a guessed secret → ${await webhookPost("not-the-secret-not-the-secret-000", { ...event, amountCents: 2_999_000 })}`);
await receiver.stop();
Nível
introdutório
1/13
Padrões do catálogo que implementa
Variáveis de ambiente
Parecidos
Por que se relacionam
Combina com
Alternativa a
Teste rápido
Qual destes combina com Webhook?
Entrega o evento por push HTTP. Abrir Azure Event Grid
Seu progresso
0/157 estudados
Fica salvo só neste navegador.