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

webhookVerification.ts

32 lines1.4 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto has no createHmac or timingSafeEqual.
2import * as NodeCrypto from "node:crypto";
3​
4import type { ScheduledTaskWebhookSignature } from "@t3tools/contracts";
5​
6/** Constant-time string comparison that does not leak length through timing. */
7export function constantTimeEquals(a: string, b: string): boolean {
8 const digestA = NodeCrypto.createHash("sha256").update(a).digest();
9 const digestB = NodeCrypto.createHash("sha256").update(b).digest();
10 return NodeCrypto.timingSafeEqual(digestA, digestB);
12​
13export function verifyWebhookSignature(input: {
14 readonly signature: ScheduledTaskWebhookSignature;
15 readonly secret: string;
16 readonly headers: Readonly<Record<string, string>>;
17 readonly body: Uint8Array;
18}): boolean {
19 const received = input.headers[input.signature.header.toLowerCase()];
20 if (received === undefined) return false;
21 const value = received.trim();
22 const prefix = input.signature.prefix;
23 if (prefix !== "" && !value.toLowerCase().startsWith(prefix.toLowerCase())) return false;
24 const digest = NodeCrypto.createHmac("sha256", input.secret).update(input.body).digest();
25 const expected =
26 input.signature.encoding === "hex" ? digest.toString("hex") : digest.toString("base64");
27 const candidate = value.slice(prefix.length);
28 return constantTimeEquals(
29 input.signature.encoding === "hex" ? candidate.toLowerCase() : candidate,
30 expected,
31 );