iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / dummy-petshop / src / webhook-inbox.tsmain at aacbc74

/**
 * A webhook inbox: the pet shop as the RECEIVER of another server's webhooks, so that a test can
 * see what a server sent and whether it was signed. It stands in for an MCP client that takes MCP
 * Events by webhook delivery.
 *
 *   POST /webhook-inbox/<name>                  keeps the delivery. A body `{type: "verification",
 *                                               challenge}` (the MCP Events extension's handshake
 *                                               before a first delivery) is answered `{challenge}`.
 *   GET  /webhook-inbox/<name>[?secret=whsec_…] what it got, newest last. With a secret, each
 *                                               delivery says whether its Standard Webhooks
 *                                               signature verifies under it.
 *
 * No sign-in: the name is the inbox's key, 16 to 64 characters that its user makes up at random.
 */
import { Webhook } from "standardwebhooks";
import { z } from "zod";
import type { ShopDeps } from "./state.ts";

const INBOX_PATH = /^\/webhook-inbox\/([a-z0-9-]{16,64})$/;
const BODY_MAX_CHARS = 64 * 1024;
/** The headers a Standard Webhooks delivery signs with, and the MCP Events subscription's id. */
const KEPT_HEADERS = [
  "webhook-id",
  "webhook-timestamp",
  "webhook-signature",
  "x-mcp-subscription-id",
];

const Verification = z.object({ type: z.literal("verification"), challenge: z.string() });

/** Whether `delivery` verifies under `secret`: the library checks the signature and that the
 *  timestamp is within five minutes of now. */
function verifies(secret: string, delivery: { headers: Record<string, string>; body: string }) {
  try {
    new Webhook(secret).verify(delivery.body, delivery.headers);
    return true;
  } catch {
    return false;
  }
}

export async function handleWebhookInbox(
  request: Request,
  deps: Pick<ShopDeps, "state">,
): Promise<Response | null> {
  const url = new URL(request.url);
  const [, name] = INBOX_PATH.exec(url.pathname) || [];
  if (!name) return null;
  if (request.method === "GET") {
    const held = (await deps.state.getState()).webhookInboxes?.[name] || [];
    const secret = url.searchParams.get("secret");
    return Response.json(
      {
        // checked when it was kept, so that a read long after still says what was true then
        deliveries: held.map((delivery) => ({
          ...delivery,
          ...(secret && { signatureAndTimestampVerifyNow: verifies(secret, delivery) }),
        })),
      },
      { headers: { "cache-control": "no-store" } },
    );
  }
  if (request.method !== "POST")
    return new Response("Method not allowed\n", { status: 405, headers: { allow: "GET, POST" } });
  const body = await request.text();
  if (body.length > BODY_MAX_CHARS) return new Response("Too large\n", { status: 413 });
  await deps.state.recordInboxDelivery(name, {
    at: new Date().toISOString(),
    headers: Object.fromEntries(
      KEPT_HEADERS.flatMap((header) => {
        const value = request.headers.get(header);
        return value ? [[header, value]] : [];
      }),
    ),
    body,
  });
  let json: unknown = null;
  try {
    json = JSON.parse(body);
  } catch {
    // not JSON: kept as it came
  }
  const verification = Verification.safeParse(json);
  return Response.json(verification.success ? { challenge: verification.data.challenge } : {});
}