Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

webhookVerification.ts

36 lines1.5 KB

1import * as NodeCrypto from "node:crypto";
2​
3import type { ScheduledTaskWebhookSignature } from "@t3tools/contracts";
4​
5/** Constant-time string comparison that does not leak length through timing. */
6export function constantTimeEquals(a: string, b: string): boolean {
7 const digestA = NodeCrypto.createHash("sha256").update(a).digest();
8 const digestB = NodeCrypto.createHash("sha256").update(b).digest();
9 return NodeCrypto.timingSafeEqual(digestA, digestB);
11​
12/**
13 * Checks an HMAC-SHA256 signature over the raw body bytes, as GitHub, Linear,
14 * Shopify and most other signing senders do. The header value is
15 * `<prefix><digest>`, with the digest hex- or base64-encoded.
16 */
17export function verifyWebhookSignature(input: {
18 readonly signature: ScheduledTaskWebhookSignature;
19 readonly secret: string;
20 readonly headers: Readonly<Record<string, string>>;
21 readonly body: Uint8Array;
22}): boolean {
23 const received = input.headers[input.signature.header.toLowerCase()];
24 if (received === undefined) return false;
25 const value = received.trim();
26 const prefix = input.signature.prefix;
27 if (prefix !== "" && !value.toLowerCase().startsWith(prefix.toLowerCase())) return false;
28 const digest = NodeCrypto.createHmac("sha256", input.secret).update(input.body).digest();
29 const expected =
30 input.signature.encoding === "hex" ? digest.toString("hex") : digest.toString("base64");
31 const candidate = value.slice(prefix.length);
32 return constantTimeEquals(
33 input.signature.encoding === "hex" ? candidate.toLowerCase() : candidate,
34 expected,
35 );