Verifying HMAC-SHA256 webhooks from social publishing workflows

5 min readReliability engineeringView as Markdown

Always verify PubNio webhook signatures using HMAC-SHA256 over the raw unparsed request body bytes with a constant-time comparison, deduplicate deliveries by event ID, and guard database state transitions so late out-of-order webhooks never overwrite a terminal published outcome.

1. Hash raw bytes, never re-serialized JSON

Middleware that parses req.body into an object and runs JSON.stringify() again breaks signature verification whenever whitespace or key ordering differs. Read the raw request text or ArrayBuffer first, verify the digest with timingSafeEqual, and only then parse the JSON payload.

verify-webhook.ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyPubNioWebhook(
  rawBody: string,
  signatureHeader: string,
  secret: string,
): boolean {
  const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
  const actual = signatureHeader.replace(/^sha256=/, "");
  if (expected.length !== actual.length) return false;
  return timingSafeEqual(Buffer.from(expected), Buffer.from(actual));
}

2. Deduplicate events and protect terminal states

HTTP webhooks are at-least-once. Store each processed event ID in a unique-indexed table and ignore duplicates with HTTP 200. Treat published, provider_draft, and cancelled as terminal so a delayed retry never regresses a confirmed live post.