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