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