diff --git a/README.md b/README.md index 1680e0636..e2e78a65d 100644 --- a/README.md +++ b/README.md @@ -1206,6 +1206,28 @@ Validated sends append one record per email to the `resend.send_attempts` store Read attempts with `getResendStore(store).sendAttempts.all()` from `@emulators/resend`, or inspect the persisted state. Shared adapter snapshots use the key `resend:resend.send_attempts`. Attempts and recipient restrictions survive saved-state restoration, including rejected sends. There is no additional Resend API endpoint for attempts. A rejected send has an attempt without an email; a send that never happened has neither. +### Webhooks + +Register endpoints with `POST /webhooks` (`endpoint` and `events`) on hosts listed in `resend.webhook_hosts`, or seed them with `resend.webhooks`. Deliveries carry Svix `svix-id`, `svix-timestamp`, and `svix-signature` headers, signed with the webhook's `whsec_` signing secret as Resend signs them, so `resend.webhooks.verify()` and the `svix` library accept them. `GET /webhooks/:id` returns the secret. A `3xx` response counts as a failed attempt and is not followed, as Svix treats redirects. + +```yaml +resend: + webhooks: + - endpoint: http://localhost:3000/api/webhooks/resend + events: [email.sent, email.delivered] +``` + +Without `events`, a seeded webhook subscribes to every event the emulator sends. Without `signing_secret`, it gets a secret derived from the endpoint URL that stays the same across resets and restarts. + +Webhooks created or updated through the API must use an `http` or `https` endpoint on a host listed in `resend.webhook_hosts`. Without that setting, the API registers no webhooks: `POST /webhooks` and an endpoint change through `PATCH /webhooks/:id` return `403 validation_error`. A host missing from the list also returns `403 validation_error`, and an endpoint that isn't an HTTP URL returns `422 validation_error`. Seeded webhooks come from your own config and are not checked. Hosts match by exact name, without ports or wildcards. To register a local receiver or a Docker Compose service through the API, list its host: + +```yaml +resend: + webhook_hosts: [localhost, app] +``` + +The emulator sends deliveries from its own host and accepts any API key, so this list decides which hosts its clients can make it contact. Keep it to the receivers you expect, especially when the emulator listens on a network address. This is a local control, not part of Resend's API. + ## Linear API Stateful Linear GraphQL API emulation with seeded organizations, users, teams, workflow states, issues, comments, labels, projects, cycles, OAuth apps, tokens, webhooks, and basic agent sessions. GraphQL reads and writes mutate in-memory state and use Relay-style connections with opaque cursors. OAuth supports authorization code, PKCE, refresh token, revoke, client credentials, and `actor=app` tokens for local app-actor tests. Supported writes dispatch Linear-shaped webhook payloads with `Linear-Delivery`, `Linear-Event`, and `Linear-Signature` headers when webhooks are configured. diff --git a/apps/web/content/docs/resend.mdx b/apps/web/content/docs/resend.mdx index 443bbb23a..964587da8 100644 --- a/apps/web/content/docs/resend.mdx +++ b/apps/web/content/docs/resend.mdx @@ -58,6 +58,37 @@ Read attempts with `getResendStore(store).sendAttempts.all()` from `@emulators/r - `GET /audiences/:audience_id/contacts` — list contacts - `DELETE /audiences/:audience_id/contacts/:id` — delete contact +## Webhooks + +- `POST /webhooks` — create webhook and return its `signing_secret` +- `GET /webhooks` — list webhooks +- `GET /webhooks/:id` — get webhook, including its `signing_secret` +- `PATCH /webhooks/:id` — update `endpoint`, `events`, or `status` +- `DELETE /webhooks/:id` — delete webhook + +Deliveries are signed with Svix, as Resend signs them. Each request carries `svix-id`, `svix-timestamp`, and `svix-signature` headers, so `resend.webhooks.verify()` and the `svix` library accept them when given the webhook's signing secret. The emulator sends `email.sent` and `email.delivered` for each email that isn't scheduled, `domain.created` and `domain.deleted`, and `contact.created` and `contact.deleted`. A webhook receives only the events in its `events` list, and a `disabled` webhook receives none. Each event is attempted once, with a 10-second timeout and no retries. A `3xx` response counts as a failed attempt and is not followed, as Svix treats redirects. + +Webhooks can also be seeded: + +```yaml +resend: + webhooks: + - endpoint: http://localhost:3000/api/webhooks/resend + events: [email.sent, email.delivered] + signing_secret: whsec_emulateTestSecretDoNotUseInProd0 +``` + +Without `events`, a seeded webhook subscribes to every event the emulator sends. Without `signing_secret`, it gets a secret derived from the endpoint URL that stays the same across resets and restarts; read it with `GET /webhooks/:id`. + +Webhooks created or updated through the API must use an `http` or `https` endpoint on a host listed in `resend.webhook_hosts`. Without that setting, the API registers no webhooks: `POST /webhooks` and an endpoint change through `PATCH /webhooks/:id` return `403 validation_error`. A host missing from the list also returns `403 validation_error`, and an endpoint that isn't an HTTP URL returns `422 validation_error`. Seeded webhooks come from your own config and are not checked. Hosts match by exact name, without ports or wildcards. To register a local receiver or a Docker Compose service through the API, list its host: + +```yaml +resend: + webhook_hosts: [localhost, app] +``` + +The emulator sends deliveries from its own host and accepts any API key, so this list decides which hosts its clients can make it contact. Keep it to the receivers you expect, especially when the emulator listens on a network address. This is a local control, not part of Resend's API. + ## Inbox - `GET /inbox` — list captured emails diff --git a/apps/web/tests/fixtures/docs-baseline.json b/apps/web/tests/fixtures/docs-baseline.json index 77a42333c..7acea37e2 100644 --- a/apps/web/tests/fixtures/docs-baseline.json +++ b/apps/web/tests/fixtures/docs-baseline.json @@ -282,7 +282,7 @@ "description": "Local drop-in replacement services for CI and no-network sandboxes. Fully stateful, production-fidelity API emulation.", "ogImage": "/og/resend", "ogTitle": "Resend | emulate", - "headings": ["Emails", "Idempotency", "Domains", "API Keys", "Audiences & Contacts", "Inbox"] + "headings": ["Emails", "Idempotency", "Domains", "API Keys", "Audiences & Contacts", "Webhooks", "Inbox"] }, "/docs/stripe": { "title": "Stripe | emulate", diff --git a/packages/@emulators/core/src/__tests__/webhooks.test.ts b/packages/@emulators/core/src/__tests__/webhooks.test.ts index 79e9f4436..9de541018 100644 --- a/packages/@emulators/core/src/__tests__/webhooks.test.ts +++ b/packages/@emulators/core/src/__tests__/webhooks.test.ts @@ -224,6 +224,22 @@ describe("WebhookDispatcher", () => { expect(mockFetch).not.toHaveBeenCalled(); }); + it("follows redirects unless the subscription opts out", async () => { + const d = new WebhookDispatcher(); + d.register({ url: "https://hooks.example/default", events: ["push"], active: true, owner: "o" }); + d.register({ + url: "https://hooks.example/strict", + events: ["push"], + active: true, + owner: "o", + followRedirects: false, + }); + + await d.dispatch("push", undefined, {}, "o"); + + expect(mockFetch.mock.calls.map((c) => (c[1] as RequestInit).redirect)).toEqual(["follow", "manual"]); + }); + it("records deliveries with status and success from the response", async () => { const d = new WebhookDispatcher(); const sub = d.register({ diff --git a/packages/@emulators/core/src/webhooks.ts b/packages/@emulators/core/src/webhooks.ts index 35742b0ed..42dabdaca 100644 --- a/packages/@emulators/core/src/webhooks.ts +++ b/packages/@emulators/core/src/webhooks.ts @@ -8,6 +8,8 @@ export interface WebhookSubscription { secret?: string; owner: string; repo?: string; + /** When false, a 3xx response is recorded as a failed delivery instead of being followed. Defaults to true. */ + followRedirects?: boolean; } export interface WebhookDelivery { @@ -182,6 +184,7 @@ export class WebhookDispatcher { method: "POST", headers, body, + redirect: sub.followRedirects === false ? "manual" : "follow", signal: this.options.signal ? AbortSignal.any([this.options.signal, AbortSignal.timeout(10000)]) : AbortSignal.timeout(10000), diff --git a/packages/@emulators/resend/README.md b/packages/@emulators/resend/README.md index fbb1dcfe0..5f8196dfd 100644 --- a/packages/@emulators/resend/README.md +++ b/packages/@emulators/resend/README.md @@ -62,6 +62,15 @@ Read attempts with `getResendStore(store).sendAttempts.all()` from `@emulators/r - `GET /audiences/:audience_id/contacts` — list contacts - `DELETE /audiences/:audience_id/contacts/:id` — delete contact +### Webhooks +- `POST /webhooks` — create webhook and return its `signing_secret` +- `GET /webhooks` — list webhooks +- `GET /webhooks/:id` — get webhook, including its `signing_secret` +- `PATCH /webhooks/:id` — update `endpoint`, `events`, or `status` +- `DELETE /webhooks/:id` — delete webhook + +Deliveries are signed with Svix, as Resend signs them. Each request carries `svix-id`, `svix-timestamp`, and `svix-signature` headers, so `resend.webhooks.verify()` and the `svix` library accept them when given the webhook's signing secret. The emulator sends `email.sent` and `email.delivered` for each email that isn't scheduled, `domain.created` and `domain.deleted`, and `contact.created` and `contact.deleted`. A webhook receives only the events in its `events` list, and a `disabled` webhook receives none. Each event is attempted once, with a 10-second timeout and no retries. A `3xx` response counts as a failed attempt and is not followed, as Svix treats redirects. + ### Inbox - `GET /inbox` — list captured emails - `GET /inbox/:id` — view captured email @@ -74,8 +83,22 @@ resend: - name: example.com api_keys: - name: default + webhooks: + - endpoint: http://localhost:3000/api/webhooks/resend + events: [email.sent, email.delivered] ``` +Without `events`, a seeded webhook subscribes to every event the emulator sends. Without `signing_secret`, it gets a secret derived from the endpoint URL that stays the same across resets and restarts; read it with `GET /webhooks/:id`. + +Webhooks created or updated through the API must use an `http` or `https` endpoint on a host listed in `resend.webhook_hosts`. Without that setting, the API registers no webhooks: `POST /webhooks` and an endpoint change through `PATCH /webhooks/:id` return `403 validation_error`. A host missing from the list also returns `403 validation_error`, and an endpoint that isn't an HTTP URL returns `422 validation_error`. Seeded webhooks come from your own config and are not checked. Hosts match by exact name, without ports or wildcards. To register a local receiver or a Docker Compose service through the API, list its host: + +```yaml +resend: + webhook_hosts: [localhost, app] +``` + +The emulator sends deliveries from its own host and accepts any API key, so this list decides which hosts its clients can make it contact. Keep it to the receivers you expect, especially when the emulator listens on a network address. This is a local control, not part of Resend's API. + ## Links - [Full documentation](https://emulate.dev) diff --git a/packages/@emulators/resend/src/__tests__/webhooks.test.ts b/packages/@emulators/resend/src/__tests__/webhooks.test.ts new file mode 100644 index 000000000..84fdb4be9 --- /dev/null +++ b/packages/@emulators/resend/src/__tests__/webhooks.test.ts @@ -0,0 +1,333 @@ +import { createHmac, timingSafeEqual } from "crypto"; +import { createServer as createHttpServer, type IncomingHttpHeaders, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { createServer, Store, WebhookDispatcher } from "@emulators/core"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { getResendStore, resendPlugin, seedFromConfig, type ResendSeedConfig } from "../index.js"; +import { svixSignature } from "../webhooks.js"; + +const base = "http://localhost:4000"; +// A made-up signing secret. The part after whsec_ is valid base64 for a 24-byte key. +const exampleSecret = "whsec_emulateTestSecretDoNotUseInProd0"; + +interface Received { + path: string; + headers: IncomingHttpHeaders; + body: string; +} + +let receiver: Server; +let receiverUrl: string; +let received: Received[]; + +beforeEach(async () => { + received = []; + receiver = createHttpServer((req, res) => { + let body = ""; + req.on("data", (chunk) => (body += chunk)); + req.on("end", () => { + received.push({ path: req.url ?? "", headers: req.headers, body }); + res.writeHead(200).end(); + }); + }); + await new Promise((resolve) => receiver.listen(0, "127.0.0.1", resolve)); + receiverUrl = `http://127.0.0.1:${(receiver.address() as AddressInfo).port}`; +}); + +afterEach(async () => { + await new Promise((resolve) => receiver.close(() => resolve())); +}); + +// The local receivers listen on 127.0.0.1, so tests allow that host unless they pass their own config. +function setup(config: ResendSeedConfig = { webhook_hosts: ["127.0.0.1"] }) { + const server = createServer(resendPlugin, { tokens: { re_test: { login: "test", id: 1 } } }); + seedFromConfig(server.store, base, config, server.webhooks); + return server; +} + +function request(server: ReturnType, method: string, path: string, body?: unknown) { + return server.app.request(`${base}${path}`, { + method, + headers: { "Content-Type": "application/json", Authorization: "Bearer re_test" }, + body: body === undefined ? undefined : JSON.stringify(body), + }); +} + +function sendEmail(server: ReturnType) { + return request(server, "POST", "/emails", { + from: "sender@example.com", + to: "user@example.com", + subject: "Hooked", + }); +} + +// Independent of the emulator's signer, following https://docs.svix.com/receiving/verifying-payloads/how-manual. +function verifySvix(secret: string, delivery: Received): boolean { + const id = String(delivery.headers["svix-id"]); + const timestamp = String(delivery.headers["svix-timestamp"]); + if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; + const key = Buffer.from(secret.split("_")[1], "base64"); + const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${delivery.body}`).digest(); + return String(delivery.headers["svix-signature"]) + .split(" ") + .some((entry) => { + const [version, signature] = entry.split(","); + const actual = Buffer.from(signature ?? "", "base64"); + return version === "v1" && actual.length === expected.length && timingSafeEqual(actual, expected); + }); +} + +describe("Resend webhook signatures", () => { + it("signs with the Svix scheme", () => { + // Expected value computed with the svix library's Webhook.sign for the same inputs. + const signature = svixSignature( + exampleSecret, + "msg_emulateExampleDelivery", + "1767225600", + '{"event_type":"ping","data":{"success":true}}', + ); + expect(signature).toBe("v1,eojTRJNaE5ax1s5imPnr3B/GTzgMVqPlB67pBOo03kA="); + }); +}); + +describe("Resend Webhooks API", () => { + it("creates, retrieves, lists, updates, and deletes a webhook", async () => { + const server = setup(); + const createRes = await request(server, "POST", "/webhooks", { + endpoint: `${receiverUrl}/hook`, + events: ["email.sent"], + }); + expect(createRes.status).toBe(200); + const created = (await createRes.json()) as { object: string; id: string; signing_secret: string }; + expect(created.object).toBe("webhook"); + expect(created.signing_secret).toMatch(/^whsec_[A-Za-z0-9+/]{32}$/); + + const getRes = await request(server, "GET", `/webhooks/${created.id}`); + expect(await getRes.json()).toEqual({ + object: "webhook", + id: created.id, + created_at: expect.any(String), + status: "enabled", + endpoint: `${receiverUrl}/hook`, + events: ["email.sent"], + signing_secret: created.signing_secret, + }); + + const listed = (await (await request(server, "GET", "/webhooks")).json()) as { + object: string; + has_more: boolean; + data: Array>; + }; + expect(listed.object).toBe("list"); + expect(listed.has_more).toBe(false); + expect(listed.data).toHaveLength(1); + expect(listed.data[0].id).toBe(created.id); + expect(listed.data[0]).not.toHaveProperty("signing_secret"); + + const updateRes = await request(server, "PATCH", `/webhooks/${created.id}`, { + events: ["email.sent", "email.delivered"], + status: "disabled", + }); + expect(await updateRes.json()).toEqual({ object: "webhook", id: created.id }); + const updated = (await (await request(server, "GET", `/webhooks/${created.id}`)).json()) as Record; + expect(updated.status).toBe("disabled"); + expect(updated.events).toEqual(["email.sent", "email.delivered"]); + + const deleteRes = await request(server, "DELETE", `/webhooks/${created.id}`); + expect(await deleteRes.json()).toEqual({ object: "webhook", id: created.id, deleted: true }); + expect((await request(server, "GET", `/webhooks/${created.id}`)).status).toBe(404); + }); + + it("validates the endpoint, events, and status", async () => { + const server = setup(); + expect((await request(server, "POST", "/webhooks", { events: ["email.sent"] })).status).toBe(422); + expect((await request(server, "POST", "/webhooks", { endpoint: receiverUrl, events: [] })).status).toBe(422); + const created = (await ( + await request(server, "POST", "/webhooks", { endpoint: receiverUrl, events: ["email.sent"] }) + ).json()) as { id: string }; + const res = await request(server, "PATCH", `/webhooks/${created.id}`, { status: "paused" }); + expect(res.status).toBe(422); + expect(((await res.json()) as { name: string }).name).toBe("validation_error"); + expect((await request(server, "PATCH", "/webhooks/missing", { status: "enabled" })).status).toBe(404); + }); +}); + +describe("Resend webhook delivery", () => { + it("delivers subscribed events with Svix headers that verify against the signing secret", async () => { + const server = setup(); + const created = (await ( + await request(server, "POST", "/webhooks", { endpoint: `${receiverUrl}/hook`, events: ["email.delivered"] }) + ).json()) as { signing_secret: string }; + + expect((await sendEmail(server)).status).toBe(200); + + expect(received).toHaveLength(1); + const [delivery] = received; + expect(delivery.path).toBe("/hook"); + expect(JSON.parse(delivery.body).type).toBe("email.delivered"); + expect(delivery.headers["content-type"]).toBe("application/json"); + expect(delivery.headers["svix-id"]).toMatch(/^msg_[0-9A-Za-z]+$/); + expect(delivery.headers["svix-timestamp"]).toMatch(/^\d{10}$/); + expect(delivery.headers["svix-signature"]).toMatch(/^v1,[A-Za-z0-9+/]+=*$/); + expect(delivery.headers).not.toHaveProperty("x-hub-signature-256"); + expect(verifySvix(created.signing_secret, delivery)).toBe(true); + expect(verifySvix("whsec_" + Buffer.alloc(24).toString("base64"), delivery)).toBe(false); + }); + + it("gives each delivery its own svix-id", async () => { + const server = setup(); + await request(server, "POST", "/webhooks", { endpoint: receiverUrl, events: ["email.sent", "email.delivered"] }); + await sendEmail(server); + expect(received.map((delivery) => JSON.parse(delivery.body).type)).toEqual(["email.sent", "email.delivered"]); + expect(new Set(received.map((delivery) => delivery.headers["svix-id"])).size).toBe(2); + }); + + it("stops delivering to disabled and deleted webhooks", async () => { + const server = setup(); + const { id } = (await ( + await request(server, "POST", "/webhooks", { endpoint: receiverUrl, events: ["email.sent"] }) + ).json()) as { id: string }; + + await request(server, "PATCH", `/webhooks/${id}`, { status: "disabled" }); + await sendEmail(server); + expect(received).toHaveLength(0); + + await request(server, "PATCH", `/webhooks/${id}`, { status: "enabled" }); + await sendEmail(server); + expect(received).toHaveLength(1); + + await request(server, "DELETE", `/webhooks/${id}`); + await sendEmail(server); + expect(received).toHaveLength(1); + }); +}); + +describe("Resend seeded webhooks", () => { + it("registers seeded webhooks with an explicit signing secret", async () => { + const server = setup({ + webhooks: [{ endpoint: receiverUrl, events: ["email.sent"], signing_secret: exampleSecret }], + }); + await sendEmail(server); + expect(received).toHaveLength(1); + expect(verifySvix(exampleSecret, received[0])).toBe(true); + }); + + it("subscribes to every emitted event and derives a stable secret when the seed leaves them out", async () => { + const config: ResendSeedConfig = { webhooks: [{ endpoint: receiverUrl }] }; + const server = setup(config); + const [webhook] = getResendStore(server.store).webhooks.all(); + expect(webhook.events).toContain("email.delivered"); + expect(webhook.events).toContain("domain.created"); + expect(webhook.signing_secret).toMatch(/^whsec_/); + + const other = new Store(); + seedFromConfig(other, base, config, new WebhookDispatcher()); + expect(getResendStore(other).webhooks.all()[0].signing_secret).toBe(webhook.signing_secret); + + await request(server, "POST", "/domains", { name: "example.com" }); + expect(received).toHaveLength(1); + expect(JSON.parse(received[0].body).type).toBe("domain.created"); + expect(verifySvix(webhook.signing_secret, received[0])).toBe(true); + }); + + it("does not duplicate a seeded webhook when the seed runs again", () => { + const store = new Store(); + const webhooks = new WebhookDispatcher(); + const config: ResendSeedConfig = { webhooks: [{ endpoint: receiverUrl }] }; + seedFromConfig(store, base, config, webhooks); + seedFromConfig(store, base, config, webhooks); + expect(getResendStore(store).webhooks.all()).toHaveLength(1); + expect(webhooks.getSubscriptions("resend")).toHaveLength(1); + }); +}); + +describe("Resend webhook destinations", () => { + async function create(server: ReturnType, endpoint: string) { + return request(server, "POST", "/webhooks", { endpoint, events: ["domain.created"] }); + } + + it("registers no endpoint through the API unless resend.webhook_hosts lists its host", async () => { + const server = setup({}); + for (const endpoint of ["http://localhost:3000/hook", `${receiverUrl}/hook`, "http://169.254.169.254/latest/"]) { + const res = await create(server, endpoint); + expect(res.status).toBe(403); + expect(((await res.json()) as { name: string }).name).toBe("validation_error"); + } + expect(await (await create(server, "http://localhost:3000/hook")).json()).toEqual({ + statusCode: 403, + name: "validation_error", + message: "Webhook registration through the API is off. List localhost in resend.webhook_hosts to allow it.", + }); + expect(getResendStore(server.store).webhooks.all()).toHaveLength(0); + + await request(server, "POST", "/domains", { name: "example.com" }); + expect(received).toEqual([]); + }); + + it("checks API endpoints against resend.webhook_hosts", async () => { + const server = setup({ webhook_hosts: ["localhost", "::1"] }); + for (const endpoint of ["http://localhost:3000/hook", "http://LOCALHOST:3000/hook", "http://[::1]:3000/hook"]) { + expect((await create(server, endpoint)).status).toBe(200); + } + + const internal = await create(server, "http://169.254.169.254/latest/meta-data/"); + expect(internal.status).toBe(403); + expect(await internal.json()).toEqual({ + statusCode: 403, + name: "validation_error", + message: "169.254.169.254 is not in resend.webhook_hosts: localhost, ::1.", + }); + expect((await create(server, "http://0.0.0.0:3000/hook")).status).toBe(403); + expect((await create(server, "file:///etc/passwd")).status).toBe(422); + expect((await create(server, "not a url")).status).toBe(422); + expect(getResendStore(server.store).webhooks.all()).toHaveLength(3); + }); + + it("refuses to move a webhook to a host that is not allowed", async () => { + const server = setup(); + const created = (await (await create(server, `${receiverUrl}/hook`)).json()) as { id: string }; + const res = await request(server, "PATCH", `/webhooks/${created.id}`, { endpoint: "http://10.0.0.5/hook" }); + expect(res.status).toBe(403); + + await request(server, "POST", "/domains", { name: "example.com" }); + expect(received.map((delivery) => delivery.path)).toEqual(["/hook"]); + }); + + it("matches resend.webhook_hosts entries by exact name", async () => { + const server = setup({ webhook_hosts: ["app", " Hooks.Example.Test "] }); + expect((await create(server, "http://app:3000/hook")).status).toBe(200); + expect((await create(server, "https://hooks.example.test/hook")).status).toBe(200); + expect((await create(server, "http://localhost:3000/hook")).status).toBe(403); + + const closed = setup({ webhook_hosts: [] }); + expect((await create(closed, "http://localhost:3000/hook")).status).toBe(403); + expect(() => setup({ webhook_hosts: [""] })).toThrow("Resend webhook_hosts"); + }); + + it("records a redirect as a failed delivery without following it", async () => { + const server = setup(); + const created = (await (await create(server, `${receiverUrl}/moved`)).json()) as { id: string }; + const redirector = createHttpServer((_req, res) => { + res.writeHead(307, { Location: `${receiverUrl}/elsewhere` }).end(); + }); + await new Promise((resolve) => redirector.listen(0, "127.0.0.1", resolve)); + try { + const port = (redirector.address() as AddressInfo).port; + await request(server, "PATCH", `/webhooks/${created.id}`, { endpoint: `http://127.0.0.1:${port}/hook` }); + await request(server, "POST", "/domains", { name: "example.com" }); + } finally { + await new Promise((resolve) => redirector.close(() => resolve())); + } + + expect(received).toEqual([]); + const [delivery] = server.webhooks.getDeliveries(); + expect(delivery.status_code).toBe(307); + expect(delivery.success).toBe(false); + }); + + it("delivers to seeded endpoints without checking them", async () => { + const server = setup({ webhook_hosts: [], webhooks: [{ endpoint: `${receiverUrl}/seeded` }] }); + await request(server, "POST", "/domains", { name: "example.com" }); + expect(received.map((delivery) => delivery.path)).toEqual(["/seeded"]); + }); +}); diff --git a/packages/@emulators/resend/src/entities.ts b/packages/@emulators/resend/src/entities.ts index c9009b953..0f7c9cbfa 100644 --- a/packages/@emulators/resend/src/entities.ts +++ b/packages/@emulators/resend/src/entities.ts @@ -68,3 +68,11 @@ export interface ResendContact extends Entity { last_name: string | null; unsubscribed: boolean; } + +export interface ResendWebhook extends Entity { + uuid: string; + endpoint: string; + events: string[]; + status: "enabled" | "disabled"; + signing_secret: string; +} diff --git a/packages/@emulators/resend/src/index.ts b/packages/@emulators/resend/src/index.ts index 3d40df89b..c363e53eb 100644 --- a/packages/@emulators/resend/src/index.ts +++ b/packages/@emulators/resend/src/index.ts @@ -7,6 +7,14 @@ import { domainRoutes } from "./routes/domains.js"; import { apiKeyRoutes } from "./routes/api-keys.js"; import { contactRoutes } from "./routes/contacts.js"; import { inboxRoutes } from "./routes/inbox.js"; +import { webhookRoutes } from "./routes/webhooks.js"; +import { + RESEND_WEBHOOK_EVENTS, + normalizeWebhookHost, + seededSigningSecret, + subscribeWebhook, + svixWebhookHeaders, +} from "./webhooks.js"; export { getResendStore, type ResendStore } from "./store.js"; export * from "./entities.js"; @@ -14,6 +22,7 @@ export * from "./entities.js"; export interface ResendSeedConfig { port?: number; allowlist?: string[]; + webhook_hosts?: string[]; domains?: Array<{ name: string; region?: string; @@ -24,9 +33,20 @@ export interface ResendSeedConfig { last_name?: string; audience?: string; }>; + webhooks?: Array<{ + endpoint: string; + events?: string[]; + status?: "enabled" | "disabled"; + signing_secret?: string; + }>; } -export function seedFromConfig(store: Store, _baseUrl: string, config: ResendSeedConfig): void { +export function seedFromConfig( + store: Store, + _baseUrl: string, + config: ResendSeedConfig, + webhooks?: WebhookDispatcher, +): void { if (config.allowlist !== undefined) { if ( !Array.isArray(config.allowlist) || @@ -39,6 +59,15 @@ export function seedFromConfig(store: Store, _baseUrl: string, config: ResendSee config.allowlist.map((address) => address.trim()), ); } + if (config.webhook_hosts !== undefined) { + if ( + !Array.isArray(config.webhook_hosts) || + config.webhook_hosts.some((host) => typeof host !== "string" || !host.trim()) + ) { + throw new Error("Resend webhook_hosts must be an array of non-empty host names"); + } + store.setData("resend.webhook_hosts", config.webhook_hosts.map(normalizeWebhookHost)); + } const rs = getResendStore(store); if (config.domains) { @@ -111,17 +140,35 @@ export function seedFromConfig(store: Store, _baseUrl: string, config: ResendSee }); } } + + if (config.webhooks && webhooks) { + webhooks.setHeaderFactory(svixWebhookHeaders); + for (const wh of config.webhooks) { + if (rs.webhooks.all().some((existing) => existing.endpoint === wh.endpoint)) continue; + const webhook = rs.webhooks.insert({ + uuid: generateUuid(), + endpoint: wh.endpoint, + events: wh.events ?? [...RESEND_WEBHOOK_EVENTS], + status: wh.status ?? "enabled", + signing_secret: wh.signing_secret ?? seededSigningSecret(wh.endpoint), + }); + subscribeWebhook(webhooks, webhook); + } + } } export const resendPlugin: ServicePlugin = { name: "resend", register(app: Hono, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void { + webhooks.setHeaderFactory(svixWebhookHeaders); + const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap }; emailRoutes(ctx); domainRoutes(ctx); apiKeyRoutes(ctx); contactRoutes(ctx); inboxRoutes(ctx); + webhookRoutes(ctx); }, seed(_store: Store, _baseUrl: string): void { // No default seed data - inbox starts empty diff --git a/packages/@emulators/resend/src/routes/webhooks.ts b/packages/@emulators/resend/src/routes/webhooks.ts new file mode 100644 index 000000000..18260b303 --- /dev/null +++ b/packages/@emulators/resend/src/routes/webhooks.ts @@ -0,0 +1,104 @@ +import type { RouteContext } from "@emulators/core"; +import { getResendStore } from "../store.js"; +import { generateUuid, resendError, parseResendBody } from "../helpers.js"; +import type { ResendWebhook } from "../entities.js"; +import { generateSigningSecret, subscribeWebhook, webhookEndpointRejection } from "../webhooks.js"; + +const STATUSES = ["enabled", "disabled"] as const; + +function isEventList(value: unknown): value is string[] { + return Array.isArray(value) && value.length > 0 && value.every((event) => typeof event === "string" && event); +} + +function formatWebhook(webhook: ResendWebhook) { + return { + id: webhook.uuid, + created_at: webhook.created_at, + status: webhook.status, + endpoint: webhook.endpoint, + events: webhook.events, + }; +} + +export function webhookRoutes(ctx: RouteContext): void { + const { app, store, webhooks } = ctx; + const rs = () => getResendStore(store); + const endpointRejection = (endpoint: string) => + webhookEndpointRejection(endpoint, store.getData("resend.webhook_hosts")); + + app.post("/webhooks", async (c) => { + const body = await parseResendBody(c); + if (typeof body.endpoint !== "string" || !body.endpoint) { + return resendError(c, 422, "validation_error", "Missing required field: endpoint"); + } + if (!isEventList(body.events)) { + return resendError(c, 422, "validation_error", "Missing required field: events"); + } + const rejection = endpointRejection(body.endpoint); + if (rejection) return resendError(c, rejection.status, "validation_error", rejection.message); + + const webhook = rs().webhooks.insert({ + uuid: generateUuid(), + endpoint: body.endpoint, + events: body.events, + status: "enabled", + signing_secret: generateSigningSecret(), + }); + subscribeWebhook(webhooks, webhook); + + return c.json({ object: "webhook", id: webhook.uuid, signing_secret: webhook.signing_secret }, 200); + }); + + app.get("/webhooks", (c) => { + return c.json({ object: "list", has_more: false, data: rs().webhooks.all().map(formatWebhook) }); + }); + + app.get("/webhooks/:id", (c) => { + const webhook = rs().webhooks.findOneBy("uuid", c.req.param("id")); + if (!webhook) return resendError(c, 404, "not_found", "Webhook not found"); + return c.json({ object: "webhook", ...formatWebhook(webhook), signing_secret: webhook.signing_secret }); + }); + + app.patch("/webhooks/:id", async (c) => { + const webhook = rs().webhooks.findOneBy("uuid", c.req.param("id")); + if (!webhook) return resendError(c, 404, "not_found", "Webhook not found"); + + const body = await parseResendBody(c); + const changes: Partial> = {}; + if (body.endpoint !== undefined) { + if (typeof body.endpoint !== "string" || !body.endpoint) { + return resendError(c, 422, "validation_error", "endpoint must be a non-empty string"); + } + const rejection = endpointRejection(body.endpoint); + if (rejection) return resendError(c, rejection.status, "validation_error", rejection.message); + changes.endpoint = body.endpoint; + } + if (body.events !== undefined) { + if (!isEventList(body.events)) { + return resendError(c, 422, "validation_error", "events must be a non-empty array of event types"); + } + changes.events = body.events; + } + if (body.status !== undefined) { + if (!STATUSES.includes(body.status as ResendWebhook["status"])) { + return resendError(c, 422, "validation_error", "status must be one of: enabled, disabled"); + } + changes.status = body.status as ResendWebhook["status"]; + } + + const updated = rs().webhooks.update(webhook.id, changes)!; + subscribeWebhook(webhooks, updated); + + return c.json({ object: "webhook", id: updated.uuid }); + }); + + app.delete("/webhooks/:id", (c) => { + const webhook = rs().webhooks.findOneBy("uuid", c.req.param("id")); + if (!webhook) return resendError(c, 404, "not_found", "Webhook not found"); + + rs().webhooks.delete(webhook.id); + webhooks.unregister(webhook.id); + + return c.json({ object: "webhook", id: webhook.uuid, deleted: true }); + }); +} diff --git a/packages/@emulators/resend/src/store.ts b/packages/@emulators/resend/src/store.ts index c280e2fa4..976b5a14f 100644 --- a/packages/@emulators/resend/src/store.ts +++ b/packages/@emulators/resend/src/store.ts @@ -7,6 +7,7 @@ import type { ResendContact, ResendIdempotencyRecord, ResendSendAttempt, + ResendWebhook, } from "./entities.js"; export interface ResendStore { @@ -17,6 +18,7 @@ export interface ResendStore { apiKeys: Collection; audiences: Collection; contacts: Collection; + webhooks: Collection; } export function getResendStore(store: Store): ResendStore { @@ -28,5 +30,6 @@ export function getResendStore(store: Store): ResendStore { apiKeys: store.collection("resend.api_keys", ["uuid"]), audiences: store.collection("resend.audiences", ["uuid"]), contacts: store.collection("resend.contacts", ["uuid", "audience_id"]), + webhooks: store.collection("resend.webhooks", ["uuid"]), }; } diff --git a/packages/@emulators/resend/src/webhooks.ts b/packages/@emulators/resend/src/webhooks.ts new file mode 100644 index 000000000..360084cb7 --- /dev/null +++ b/packages/@emulators/resend/src/webhooks.ts @@ -0,0 +1,107 @@ +import { createHash, createHmac, randomBytes } from "crypto"; +import type { WebhookDispatcher, WebhookHeaderContext } from "@emulators/core"; +import type { ResendWebhook } from "./entities.js"; + +const SECRET_PREFIX = "whsec_"; +const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +// Event types the emulator emits. Seeded webhooks that list no events subscribe to all of them. +export const RESEND_WEBHOOK_EVENTS = [ + "email.sent", + "email.delivered", + "domain.created", + "domain.deleted", + "contact.created", + "contact.deleted", +]; + +export function normalizeWebhookHost(host: string): string { + return host + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1"); +} + +export type WebhookEndpointRejection = { status: 403 | 422; message: string }; + +// The emulator sends deliveries from its own host and its routes take any API key, so an API client may only point a +// webhook at a host the operator listed in resend.webhook_hosts. With no list, the API registers nothing, so anyone who +// can reach the emulator can't make it post to services only its host can reach. Seeded webhooks come from the +// operator's own config and are not checked. +export function webhookEndpointRejection( + endpoint: string, + allowedHosts: string[] = [], +): WebhookEndpointRejection | undefined { + let url: URL; + try { + url = new URL(endpoint); + } catch { + return { status: 422, message: "endpoint must be an http or https URL" }; + } + if (url.protocol !== "http:" && url.protocol !== "https:") { + return { status: 422, message: "endpoint must be an http or https URL" }; + } + const host = normalizeWebhookHost(url.hostname); + if (allowedHosts.some((allowed) => normalizeWebhookHost(allowed) === host)) return undefined; + if (allowedHosts.length === 0) { + return { + status: 403, + message: `Webhook registration through the API is off. List ${host} in resend.webhook_hosts to allow it.`, + }; + } + return { + status: 403, + message: `${host} is not in resend.webhook_hosts: ${allowedHosts.join(", ") || "(empty)"}.`, + }; +} + +export function generateSigningSecret(): string { + return SECRET_PREFIX + randomBytes(24).toString("base64"); +} + +// Seeded webhooks without a signing_secret get one derived from the endpoint, so it survives resets and restarts. +export function seededSigningSecret(endpoint: string): string { + const digest = createHash("sha256").update(`emulate resend webhook ${endpoint}`).digest(); + return SECRET_PREFIX + digest.subarray(0, 24).toString("base64"); +} + +function svixMessageId(): string { + const bytes = randomBytes(27); + let id = "msg_"; + for (const byte of bytes) id += BASE62[byte % BASE62.length]; + return id; +} + +// Svix signs `${svix-id}.${svix-timestamp}.${body}` with HMAC-SHA256, keyed with the base64-decoded secret after the whsec_ prefix. +export function svixSignature(secret: string, id: string, timestamp: string, body: string): string { + const key = Buffer.from(secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : secret, "base64"); + return "v1," + createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest("base64"); +} + +export function svixWebhookHeaders({ body, subscription }: WebhookHeaderContext): Record { + const headers: Record = { "Content-Type": "application/json" }; + if (!subscription.secret) return headers; + + const id = svixMessageId(); + const timestamp = String(Math.floor(Date.now() / 1000)); + headers["svix-id"] = id; + headers["svix-timestamp"] = timestamp; + headers["svix-signature"] = svixSignature(subscription.secret, id, timestamp, body); + return headers; +} + +export function subscribeWebhook(webhooks: WebhookDispatcher, webhook: ResendWebhook): void { + const subscription = { + url: webhook.endpoint, + events: webhook.events, + active: webhook.status === "enabled", + secret: webhook.signing_secret, + }; + if (webhooks.getSubscription(webhook.id)) { + webhooks.updateSubscription(webhook.id, subscription); + } else { + // Svix treats a 3xx response as a failed attempt and does not follow it. Following one would also let an + // allowed endpoint send the delivery on to a host outside resend.webhook_hosts. + webhooks.register({ id: webhook.id, owner: "resend", followRedirects: false, ...subscription }); + } +} diff --git a/packages/emulate/src/program.ts b/packages/emulate/src/program.ts index abd1323f1..ab1800677 100644 --- a/packages/emulate/src/program.ts +++ b/packages/emulate/src/program.ts @@ -102,6 +102,7 @@ Google OIDC: Resend API coverage: POST /emails and POST /emails/batch support 24-hour Idempotency-Key replay without duplicate emails or webhooks. Optional resend.allowlist restricts to/cc/bcc recipients; [] rejects all, and omission accepts all. + POST and PATCH /webhooks accept only hosts in resend.webhook_hosts; without it, API registration is off. Rejected batches create no emails or webhooks. Validated sends record resend.send_attempts in saved state. Idempotency replays and malformed requests do not add attempts; rejected sends can be retried with the same key. diff --git a/packages/emulate/src/registry.ts b/packages/emulate/src/registry.ts index 4891200ca..f470c6049 100644 --- a/packages/emulate/src/registry.ts +++ b/packages/emulate/src/registry.ts @@ -416,7 +416,8 @@ export const SERVICE_REGISTRY: Record = { }, resend: { label: "Resend email API emulator", - endpoints: "emails with idempotency, recipient restrictions, send attempts, domains, contacts, API keys, inbox UI", + endpoints: + "emails with idempotency, recipient restrictions, send attempts, domains, contacts, API keys, Svix-signed webhooks, inbox UI", async load() { const mod = await import("@emulators/resend"); return { plugin: mod.resendPlugin, seedFromConfig: mod.seedFromConfig }; diff --git a/skills/resend/SKILL.md b/skills/resend/SKILL.md index 09aa29473..ae181b4cb 100644 --- a/skills/resend/SKILL.md +++ b/skills/resend/SKILL.md @@ -317,12 +317,43 @@ curl -X DELETE http://localhost:4000/audiences//contacts/ \ ## Webhooks +Register an endpoint with the Webhooks API once its host is listed in `resend.webhook_hosts` (see below). The response includes the webhook's `signing_secret`: + +```bash +curl -X POST http://localhost:4000/webhooks \ + -H "Authorization: Bearer $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"endpoint": "http://localhost:3000/api/webhooks/resend", "events": ["email.sent", "email.delivered"]}' +``` + +`GET /webhooks`, `GET /webhooks/:id` (which also returns `signing_secret`), `PATCH /webhooks/:id` (`endpoint`, `events`, or `status` of `enabled` or `disabled`), and `DELETE /webhooks/:id` manage registered webhooks. + The emulator dispatches webhook events when state changes: -- `email.sent` and `email.delivered` on `POST /emails` +- `email.sent` and `email.delivered` on `POST /emails` and `POST /emails/batch`, except for scheduled emails - `domain.created` and `domain.deleted` on domain operations - `contact.created` and `contact.deleted` on contact operations +Each delivery is signed with Svix, as Resend signs them, through the `svix-id`, `svix-timestamp`, and `svix-signature` headers. Verify it in your handler with `resend.webhooks.verify({ payload, headers: { id, timestamp, signature }, webhookSecret })` or the `svix` library, using the raw request body. A webhook receives only the events in its `events` list, a `disabled` webhook receives none, and each event is attempted once without retries. A `3xx` response counts as a failed attempt and is not followed, as Svix treats redirects. + +Webhooks can also be seeded. Without `events`, a seeded webhook subscribes to every event above. Without `signing_secret`, it gets a secret derived from the endpoint URL that stays the same across resets and restarts: + +```yaml +resend: + webhooks: + - endpoint: http://localhost:3000/api/webhooks/resend + signing_secret: whsec_emulateTestSecretDoNotUseInProd0 +``` + +Webhooks created or updated through the API must use an `http` or `https` endpoint on a host listed in `resend.webhook_hosts`. Without that setting, the API registers no webhooks: `POST /webhooks` and an endpoint change through `PATCH /webhooks/:id` return `403 validation_error`. A host missing from the list also returns `403 validation_error`, and an endpoint that isn't an HTTP URL returns `422 validation_error`. Seeded webhooks come from your own config and are not checked. Hosts match by exact name, without ports or wildcards. To register a local receiver or a Docker Compose service through the API, list its host: + +```yaml +resend: + webhook_hosts: [localhost, app] +``` + +The emulator sends deliveries from its own host and accepts any API key, so this list decides which hosts its clients can make it contact. Keep it to the receivers you expect, especially when the emulator listens on a network address. This is a local control, not part of Resend's API. + ## Common Patterns ### Magic Link / Verification Code Flow