cloud / internal-packages / dummy-petshop / src / webhook-inbox.test.tsmain at aacbc74
/**
* The webhook inbox (webhook-inbox.ts): it keeps what it gets, answers the MCP Events challenge,
* and says whether a delivery verifies under a secret.
*/
import { Webhook } from "standardwebhooks";
import { expect, test } from "vitest";
import { memoryPetshop } from "./memory-state.ts";
import { handleWebhookInbox } from "./webhook-inbox.ts";
const INBOX = "https://petshop.example/webhook-inbox/an-inbox-of-a-test";
const SECRET = `whsec_${btoa("0123456789abcdef0123456789abcdef")}`;
test("an inbox answers a challenge, keeps a signed delivery and checks it under its secret", async () => {
const deps = memoryPetshop();
const challenged = await handleWebhookInbox(
new Request(INBOX, {
method: "POST",
body: JSON.stringify({ type: "verification", challenge: "n-1" }),
}),
deps,
);
expect(await challenged!.json()).toEqual({ challenge: "n-1" });
const body = JSON.stringify({ eventId: "evt_1", name: "note", data: { text: "hello" } });
const now = new Date();
const delivered = await handleWebhookInbox(
new Request(INBOX, {
method: "POST",
headers: {
"webhook-id": "evt_1",
"webhook-timestamp": String(Math.floor(now.getTime() / 1000)),
"webhook-signature": new Webhook(SECRET).sign("evt_1", now, body),
"x-mcp-subscription-id": "sub_1",
cookie: "not-kept=1",
},
body,
}),
deps,
);
expect(await delivered!.json()).toEqual({});
const read = async (query: string) =>
(await (await handleWebhookInbox(new Request(`${INBOX}${query}`), deps))!.json()) as {
deliveries: { headers: Record<string, string>; signatureAndTimestampVerifyNow?: boolean }[];
};
const withSecret = await read(`?secret=${encodeURIComponent(SECRET)}`);
expect(withSecret.deliveries).toMatchObject([
{ signatureAndTimestampVerifyNow: false },
{ headers: { "x-mcp-subscription-id": "sub_1" }, signatureAndTimestampVerifyNow: true },
]);
expect(withSecret.deliveries[1]!.headers).not.toHaveProperty("cookie");
const other = await read(
`?secret=${encodeURIComponent(`whsec_${btoa("another-secret-of-32-bytes-long!")}`)}`,
);
expect(other.deliveries).toMatchObject([{}, { signatureAndTimestampVerifyNow: false }]);
});
test("a path that names no inbox is left to the other routes", async () => {
const deps = memoryPetshop();
expect(
await handleWebhookInbox(new Request("https://petshop.example/webhook-inbox/short"), deps),
).toBeNull();
expect(
await handleWebhookInbox(new Request("https://petshop.example/api/pets"), deps),
).toBeNull();
});