SPB Git

Repository Public

signature.test.ts 8.0 KB 155 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Identity8 * File             : sdk/typescript/tests/unit/signature.test.ts9 * Module           : sdk10 * Repository       : https://git.spboucher.ai/maclustr-identity11 * Project Website  : https://identity.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { createHmac } from "node:crypto";43import { afterEach, describe, expect, it, vi } from "vitest";44import { SignatureVerificationError, constructEvent, isDecisionEvent, isSessionEvent, sessionEndedWithoutDecision, parseSignatureHeader, signPayload, timingSafeEqual, verifySignature } from "../../src/index";4546const secret = "whsec_test_secret";47const body = JSON.stringify({ id: "evt_1", object: "event", type: "verification.verified", api_version: "2026-12-01", created: 1, livemode: false, data: { object: { object: "verification", verification_id: "ver_1" } } });48const now = () => Math.floor(Date.now() / 1000);49const ref = (s: string, t: number, b: string) => createHmac("sha256", s).update(`${t}.${b}`).digest("hex");5051afterEach(() => vi.unstubAllGlobals());5253describe("webhook signature", () => {54  it("accepts a valid signature and returns the parsed event", async () => {55    const t = now();56    const event = await constructEvent(body, `t=${t},v1=${ref(secret, t, body)}`, secret);57    expect(event.id).toBe("evt_1");58    expect(event.type).toBe("verification.verified");59  });6061  it("matches the reference HMAC-SHA256(secret, '<t>.' + body)", async () => {62    expect(await signPayload(body, secret, 1700000000)).toBe(`t=1700000000,v1=${ref(secret, 1700000000, body)}`);63  });6465  it("accepts Buffer, Uint8Array and ArrayBuffer raw bodies", async () => {66    const t = now();67    const header = `t=${t},v1=${ref(secret, t, body)}`;68    const buf = Buffer.from(body);69    await expect(constructEvent(buf, header, secret)).resolves.toMatchObject({ id: "evt_1" });70    await expect(constructEvent(new Uint8Array(buf), header, secret)).resolves.toMatchObject({ id: "evt_1" });71    await expect(constructEvent(new Uint8Array(buf).buffer.slice(0) as ArrayBuffer, header, secret)).resolves.toMatchObject({ id: "evt_1" });72  });7374  it("rejects a tampered body", async () => {75    const t = now();76    await expect(constructEvent(body + " ", `t=${t},v1=${ref(secret, t, body)}`, secret)).rejects.toMatchObject({ name: "SignatureVerificationError", code: "signature_mismatch" });77  });7879  it("rejects another secret", async () => {80    const t = now();81    await expect(constructEvent(body, `t=${t},v1=${ref("whsec_other", t, body)}`, secret)).rejects.toBeInstanceOf(SignatureVerificationError);82  });8384  it("rejects a signature older than the tolerance", async () => {85    const t = now() - 301;86    await expect(constructEvent(body, `t=${t},v1=${ref(secret, t, body)}`, secret)).rejects.toMatchObject({ code: "signature_expired" });87    await expect(constructEvent(body, `t=${t},v1=${ref(secret, t, body)}`, secret, 600)).resolves.toBeTruthy();88  });8990  it("rejects a timestamp too far in the future", async () => {91    const t = now() + 1000;92    await expect(verifySignature(body, `t=${t},v1=${ref(secret, t, body)}`, secret)).rejects.toMatchObject({ code: "signature_expired" });93  });9495  it("accepts either secret during a rotation (several v1)", async () => {96    const t = now();97    const header = `t=${t},v1=${ref("whsec_new", t, body)},v1=${ref("whsec_old", t, body)}`;98    await expect(constructEvent(body, header, "whsec_new")).resolves.toBeTruthy();99    await expect(constructEvent(body, header, "whsec_old")).resolves.toBeTruthy();100    await expect(constructEvent(body, header, "whsec_unrelated")).rejects.toMatchObject({ code: "signature_mismatch" });101  });102103  it("rejects missing or malformed headers", async () => {104    for (const h of [undefined, null, "", "garbage", "t=abc,v1=00", `t=${now()}`, `v1=${"0".repeat(64)}`]) {105      await expect(constructEvent(body, h as string, secret)).rejects.toMatchObject({ code: "signature_header_invalid" });106    }107    expect(parseSignatureHeader("t=12,v1=aa,v1=bb,v0=cc")).toEqual({ timestamp: 12, signatures: ["aa", "bb"] });108  });109110  it("refuses an already parsed object instead of the raw body", async () => {111    const t = now();112    await expect(constructEvent(JSON.parse(body) as never, `t=${t},v1=${ref(secret, t, body)}`, secret)).rejects.toMatchObject({ code: "payload_not_raw" });113  });114115  it("rejects a correctly signed payload that is not an event", async () => {116    const t = now();117    await expect(constructEvent("[]", `t=${t},v1=${ref(secret, t, "[]")}`, secret)).rejects.toMatchObject({ code: "payload_invalid" });118  });119120  it("types verification.cancelled as a session event and tolerates an event type added later", async () => {121    const t = now();122    const cancelled = JSON.stringify({ id: "evt_c", object: "event", type: "verification.cancelled", api_version: "2026-12-01", created: t, livemode: false, data: { object: { id: "vs_1", object: "verification_session", status: "cancelled" } } });123    const e = await constructEvent(cancelled, `t=${t},v1=${ref(secret, t, cancelled)}`, secret);124    expect(e.type).toBe("verification.cancelled");125    expect(isSessionEvent(e)).toBe(true);126    expect(isDecisionEvent(e)).toBe(false);127    expect(sessionEndedWithoutDecision(e)).toBe(true);128    if (e.type === "verification.cancelled") expect(e.data.object.status).toBe("cancelled");129    const future = JSON.stringify({ id: "evt_f", object: "event", type: "verification.something_new", created: t, livemode: false, data: { object: { object: "something_else" } }, extra: 1 });130    const f = await constructEvent(future, `t=${t},v1=${ref(secret, t, future)}`, secret);131    expect(f.id).toBe("evt_f");132    expect(isDecisionEvent(f)).toBe(false);133    expect(isSessionEvent(f)).toBe(false);134    expect(sessionEndedWithoutDecision(f)).toBe(false);135    const bare = JSON.stringify({ id: "evt_b", object: "event", type: "x" });136    const b = await constructEvent(bare, `t=${t},v1=${ref(secret, t, bare)}`, secret);137    expect(isDecisionEvent(b)).toBe(false);138  });139140  it("falls back to node:crypto when WebCrypto is absent", async () => {141    vi.stubGlobal("crypto", undefined);142    const t = now();143    await expect(constructEvent(body, `t=${t},v1=${ref(secret, t, body)}`, secret)).resolves.toMatchObject({ id: "evt_1" });144    await expect(constructEvent(body, `t=${t},v1=${ref("x", t, body)}`, secret)).rejects.toBeInstanceOf(SignatureVerificationError);145  });146147  it("compares in constant time semantics (equal / different / different length)", () => {148    expect(timingSafeEqual("abcd", "abcd")).toBe(true);149    expect(timingSafeEqual("abcd", "abce")).toBe(false);150    expect(timingSafeEqual("abcd", "abc")).toBe(false);151    expect(timingSafeEqual("abcd", "")).toBe(false);152    expect(timingSafeEqual("", "")).toBe(true);153  });154});155
Files main
Menu

Theme