Pular para o conteúdo

Webhook

O gateway notifica o lojista por HTTP POST; o receptor valida a assinatura HMAC antes de aceitar (padrão Stripe, PagSeguro, Pagar.me).

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

Aprovação do PAY-001 chega ao lojista; uma notificação forjada com valor maior é recusada.

Planta

Sequência
5/5
POST webhook-id, webhook-timestamp, webhook-signature v11HMAC em tempo constante e janela de 5 min22003POST assinado com segredo errado44005Gateway de pagamentosReceptor do lojistaAtacante
5

5 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.

  1. 1

    HMAC-SHA256 de id.timestamp.corpo com segredo compartilhado (Standard Webhooks)

  2. 2

    O receptor recalcula sobre o corpo cru

  3. 3

    Comparação em tempo constante; timestamp fora de 5 min recusado

  4. 4

    Assinatura inválida400, nunca 5xx, para não haver retry

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: assinatura com o segredo compartilhado: 200 e evento payment.approved aceito; assinatura com segredo chutado: 400.

Requisitos
Bun

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

Linhas de TypeScript
36
Tipo
A — código puro

Padrões do catálogo que implementa

Variáveis de ambiente

WEBHOOK_SECRET
local-demo-secret-with-at-least-32-chars
Secret shared between the payment gateway and the merchant, at least 32 characters. Secret: never commit the real one.
WEBHOOK_RECEIVER_PORT
3099
Port of the merchant's webhook receiver (POST /webhooks/payments).

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Webhook?

Próximo projeto, Mensageria & EventosWire Tap
Esc

↑ ↓ navegarEnter abrir239 resultados