PerfectParser Docs

Verify Webhooks

Timing-safe HMAC-SHA256 signature verification code recipes.

To ensure incoming webhook requests originate from PerfectParser and have not been altered, you must verify the signature sent in the X-PerfectParser-Signature header.

The signature is a HMAC-SHA256 hash of the raw HTTP request body, signed using your Webhook Secret. Always perform a timing-safe string comparison to prevent timing attacks.

import crypto from "crypto";
 
function verifyWebhookSignature(
  rawBody: string,
  signature: string,
  secret: string
): boolean {
  const expectedSig = crypto
    .createHmac("sha256", secret)
    .update(rawBody)
    .digest("hex");
    
  return crypto.timingSafeEqual(
    Buffer.from(signature, "utf-8"),
    Buffer.from(expectedSig, "utf-8")
  );
}

Verify the signature on the raw request body string/bytes prior to parsing it into a JSON object. Minor formatting differences in JSON stringification will cause validation to fail.