تخطَّ إلى المحتوى
توثيق المطورين

استقبال الويب هوك بأمان

A complete handler: verify the signature, deduplicate, acknowledge fast, and survive retries.

استقبال الويب هوك بأمان

A complete handler: verify the signature, deduplicate, acknowledge fast, and survive retries.

The mechanics of the signature are in the Webhooks reference. This guide is the handler you actually deploy: one route, one ordering, and the four failure modes that bite in production.

ts
// app/api/bardiya/webhook/route.ts  (Next.js route handler)
import { createHmac, timingSafeEqual } from "node:crypto";

export async function POST(request: Request) {
  // 1. Raw bytes, before any JSON parsing.
  const raw = await request.text();
  const timestamp = request.headers.get("x-bardiya-timestamp");
  const signature = request.headers.get("x-bardiya-signature");
  const deliveryId = request.headers.get("x-bardiya-webhook-id");
  if (!timestamp || !signature || !deliveryId) {
    return new Response("missing headers", { status: 400 });
  }

  // 2. Freshness window.
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {
    return new Response("stale", { status: 400 });
  }

  // 3. Constant-time comparison.
  const expected = createHmac("sha256", process.env.BARDIYA_WEBHOOK_SECRET!)
    .update(`${timestamp}.${raw}`)
    .digest();
  const received = Buffer.from(signature.replace(/^v1=/, ""), "hex");
  if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
    return new Response("bad signature", { status: 400 });
  }

  // 4. Deduplicate on the delivery id, durably, before side effects.
  if (await store.hasProcessed(deliveryId)) {
    return new Response(null, { status: 200 });
  }
  await store.markProcessed(deliveryId);

  // 5. Acknowledge, then work.
  await queue.enqueue(raw);
  return new Response(null, { status: 200 });
}

The four failure modes

  1. The framework parsed the body first

    Re-serialising JSON changes whitespace and key order, so the signature never matches. Read the raw body for this route only.

  2. The handler did the work before acknowledging

    A slow handler looks like a failure and gets retried, so the work happens twice. Enqueue and return.

  3. No deduplication

    Retries reuse the delivery id. Upsert on it, or your ledger gains a duplicate row for a real event.

  4. Hard-coded event list

    Subscribing to fewer events than you handle is harmless; assuming you receive an event you never subscribed to is not. Treat unknown event types as no-ops and log them.