48 lines
2.0 KiB
TypeScript
48 lines
2.0 KiB
TypeScript
import { describe, it, expect } from "vitest";
|
|
import { verifyWebhookSignature, signWebhookPayload } from "./webhooks.js";
|
|
|
|
const SECRET = "whsec_test_super_secret";
|
|
const PAYLOAD = `{"event":"contact.created","data":{"id":"c_42"}}`;
|
|
const TIMESTAMP = 1_700_000_000;
|
|
|
|
describe("verifyWebhookSignature — defensive paths", () => {
|
|
it("returns false when the provided signature is same-length but not valid hex", () => {
|
|
// expectedHex is 64 hex chars; a 64-char all-`g` string passes the length
|
|
// gate but decodes to an empty buffer, so timingSafeEqual throws and is caught.
|
|
const provided = "g".repeat(64);
|
|
expect(
|
|
verifyWebhookSignature({
|
|
secret: SECRET,
|
|
payload: PAYLOAD,
|
|
signature: provided,
|
|
timestamp: TIMESTAMP,
|
|
now: () => TIMESTAMP * 1000,
|
|
})
|
|
).toBe(false);
|
|
});
|
|
|
|
it("defaults to Date.now() for the replay window when no clock override is given", () => {
|
|
const fresh = Math.floor(Date.now() / 1000);
|
|
const signature = signWebhookPayload({ secret: SECRET, payload: PAYLOAD, timestamp: fresh });
|
|
// No `now` passed → exercises the Date.now() default branch; a just-issued
|
|
// signature is inside the 5-minute window.
|
|
expect(verifyWebhookSignature({ secret: SECRET, payload: PAYLOAD, signature, timestamp: fresh })).toBe(true);
|
|
});
|
|
|
|
it("does not strip a late `=` (index >= 16) as an algorithm prefix", () => {
|
|
const signature = signWebhookPayload({ secret: SECRET, payload: PAYLOAD, timestamp: TIMESTAMP });
|
|
// Insert an `=` past position 16 — normalizeSignature must keep the value as-is,
|
|
// so the now-malformed/longer string fails verification rather than being trimmed.
|
|
const withLateEquals = `${signature.slice(0, 20)}=${signature.slice(20)}`;
|
|
expect(
|
|
verifyWebhookSignature({
|
|
secret: SECRET,
|
|
payload: PAYLOAD,
|
|
signature: withLateEquals,
|
|
timestamp: TIMESTAMP,
|
|
now: () => TIMESTAMP * 1000,
|
|
})
|
|
).toBe(false);
|
|
});
|
|
});
|