import { createHmac } from "node:crypto"; import { describe, expect, test } from "vitest"; import { buildPublicWebhookIdempotencyKey, createPublicWebhookDeliveryHeaders, derivePublicApiSecretMetadata, derivePublicWebhookSigningSecret, hashJsonValue, planPublicWebhookRetry, verifyPublicApiSecret, verifyPublicWebhookHmacWithPresentedSecret, } from "./public-api.server.js"; describe("public-api.server", () => { test("stores only secret metadata and verifies presented webhook secrets", () => { const metadata = derivePublicApiSecretMetadata("hgwh_plain_secret", "test-hash-secret"); expect(metadata.hash).not.toContain("hgwh_plain_secret"); expect(metadata.prefix).toBe("hgwh_plain"); expect(metadata.lastFour).toBe("cret"); expect(verifyPublicApiSecret("hgwh_plain_secret", metadata.hash, "test-hash-secret")).toBe(true); expect(verifyPublicApiSecret("wrong", metadata.hash, "test-hash-secret")).toBe(false); }); test("verifies incoming HMAC signatures from the once-visible webhook secret", () => { const secret = "hgwh_incoming_secret"; const body = JSON.stringify({ email: "lead@example.test" }); const timestamp = "1783055796"; const signature = `sha256=${createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex")}`; const metadata = derivePublicApiSecretMetadata(secret, "test-hash-secret"); expect( verifyPublicWebhookHmacWithPresentedSecret({ body, timestamp, signature, presentedSecret: secret, secretHash: metadata.hash, hashSecret: "test-hash-secret", }), ).toBe(true); expect( verifyPublicWebhookHmacWithPresentedSecret({ body, timestamp, signature: "sha256=bad", presentedSecret: secret, secretHash: metadata.hash, hashSecret: "test-hash-secret", }), ).toBe(false); }); test("creates deterministic outgoing HMAC headers and idempotency keys", () => { const payload = { b: 2, a: 1 }; const signingSecret = derivePublicWebhookSigningSecret({ tenantId: "tenant_1", subscriptionId: "subscription_1" }, "test-hash-secret"); const headers = createPublicWebhookDeliveryHeaders({ eventType: "contact.created", deliveryId: "delivery_1", idempotencyKey: buildPublicWebhookIdempotencyKey({ subscriptionId: "subscription_1", eventType: "contact.created", sourceEventId: "event_1", payloadHash: hashJsonValue(payload), }), payload, signingSecret, timestamp: new Date("2026-07-03T00:00:00.000Z"), }); expect(headers["X-HiveGrid-Event"]).toBe("contact.created"); expect(headers["X-HiveGrid-Delivery"]).toBe("delivery_1"); expect(headers["X-HiveGrid-Idempotency-Key"]).toBe("subscription_1:contact.created:event_1"); expect(headers["X-HiveGrid-Signature"]).toMatch(/^sha256=[a-f0-9]{64}$/); }); test("plans exponential retry delays from the current attempt", () => { const now = new Date("2026-07-03T00:00:00.000Z"); expect(planPublicWebhookRetry({ attempt: 1, now, baseDelayMs: 1_000 }).toISOString()).toBe("2026-07-03T00:00:01.000Z"); expect(planPublicWebhookRetry({ attempt: 4, now, baseDelayMs: 1_000 }).toISOString()).toBe("2026-07-03T00:00:08.000Z"); }); });