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

webhookVerification.test.ts

59 lines1.9 KB

1import * as NodeCrypto from "node:crypto";
2​
3import { assert, describe, it } from "@effect/vitest";
4​
5import { verifyWebhookSignature } from "./webhookVerification.ts";
6​
7const body = new TextEncoder().encode('{"action":"opened"}');
8const secret = "shared-secret";
9const hmac = () => NodeCrypto.createHmac("sha256", secret).update(body);
10​
11describe("verifyWebhookSignature", () => {
12 const github = { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=" } as const;
13​
14 it("accepts a GitHub-style hex signature with prefix", () => {
15 const headers = { "x-hub-signature-256": `sha256=${hmac().digest("hex")}` };
16 assert.isTrue(verifyWebhookSignature({ signature: github, secret, headers, body }));
17 });
18​
19 it("rejects a tampered body, a wrong secret, a missing header and a missing prefix", () => {
20 const valid = `sha256=${hmac().digest("hex")}`;
21 const tampered = new TextEncoder().encode('{"action":"closed"}');
22 assert.isFalse(
23 verifyWebhookSignature({
24 signature: github,
25 secret,
26 headers: { "x-hub-signature-256": valid },
27 body: tampered,
28 }),
29 );
30 assert.isFalse(
31 verifyWebhookSignature({
32 signature: github,
33 secret: "other",
34 headers: { "x-hub-signature-256": valid },
35 body,
36 }),
37 );
38 assert.isFalse(verifyWebhookSignature({ signature: github, secret, headers: {}, body }));
39 assert.isFalse(
40 verifyWebhookSignature({
41 signature: github,
42 secret,
43 headers: { "x-hub-signature-256": hmac().digest("hex") },
44 body,
45 }),
46 );
47 });
48​
49 it("accepts a base64 signature without prefix", () => {
50 assert.isTrue(
51 verifyWebhookSignature({
52 signature: { header: "X-Signature", encoding: "base64", prefix: "" },
53 secret,
54 headers: { "x-signature": hmac().digest("base64") },
55 body,
56 }),
57 );
58 });
59});