Constant-Time HMAC-SHA256 Webhook Verification in TypeScript (And Why === Leaks Secrets)
When your backend receives a webhook from Stripe, GitHub, or an inbound email gateway, you verify its X-Signature header by computing an HMAC-SHA256 (or HMAC-SHA384) digest over the raw request body and comparing it to the header value. The most common bug in webhook handlers is comparing those two hex strings with ===.
Why === Is a Timing Side Channel
Standard string equality (expected === actual) short-circuits on the first mismatched byte. If byte 0 mismatches, the comparison returns in nanoseconds. If the first 12 bytes match and byte 13 mismatches, it takes slightly longer.
Over enough automated requests, an attacker can measure those sub-microsecond timing differences and guess a valid HMAC byte by byte without knowing your signing secret.
The Fix: Constant-Time Byte Comparison
Never compare cryptographic digests with ===. Always decode both values into equal-length Uint8Array buffers and compare every byte in constant time.
In Node or Bun, node:crypto provides timingSafeEqual. If you want zero-dependency Web Crypto code that also runs on Cloudflare Workers and Deno, you can write the XOR accumulator in five lines:
function timingSafeEqualHex(aHex: string, bHex: string): boolean {
if (aHex.length !== bHex.length) {
return false;
}
let diff = 0;
for (let i = 0; i < aHex.length; i++) {
diff |= aHex.charCodeAt(i) ^ bHex.charCodeAt(i);
}
return diff === 0;
}
Here is the complete Web Crypto HMAC-SHA256 verifier:
export async function verifyWebhookSignature(
secret: string,
rawBody: string,
signatureHeader: string,
): Promise<boolean> {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
encoder.encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const macBuffer = await crypto.subtle.sign("HMAC", key, encoder.encode(rawBody));
const expectedHex = Array.from(new Uint8Array(macBuffer))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
const cleanHeader = signatureHeader.replace(/^sha256=/, "").toLowerCase();
return timingSafeEqualHex(expectedHex, cleanHeader);
}
Two Operational Rules Worth Remembering
- Hash the raw bytes, not
JSON.stringify(req.body): Re-serializing parsed JSON changes whitespace and key ordering, which breaks valid signatures. - Enforce a timestamp window: Pair HMAC verification with a signed timestamp header (rejecting payloads older than 5 minutes) so captured requests cannot be replayed later.
💡 Developer Infrastructure Note: If your AI agent processes inbound email webhooks, verifying HMAC signatures and stripping untrusted HTML before prompting is essential. SadaSend delivers signed, markdown-normalized inbound webhooks alongside outbound spend guards and active Port 25 bounce checks.
Comments
No comments yet. Start the discussion.