diff --git a/CHANGELOG.md b/CHANGELOG.md index 0256f83..1dfa05e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - **Arguments that don't match an event's inputSchema say what's wrong:** `poll_events` and `wait_for_event` returned only "arguments do not match the inputSchema", dropping the protocol error's `data.detail`, so an agent couldn't tell which argument was wrong (seen on 5 Nov: Claude Code passed `action` for `github.issues`, whose filter is `actions`, a list, then dropped the filter). The tool error now includes the detail, which names the unknown or wrong argument and lists the event's arguments: `arguments do not match the inputSchema: unknown argument "action". github.issues takes repository (string), actions (string[]), sender (string)`. `events/poll` and `events/subscribe` return the same `data.detail`, which was the validator's raw JSON, and `watch` and `watches add` print it. Unknown arguments were already refused, not ignored. - **Poll tools on a bridge with no subscriptions:** `wait_for_event`, `poll_events`, `events/poll`, `watch`, `get_event` and `list_events` returned no events until something subscribed. A source has a connection only per subscription, and Event Gateway rejects requests to a source with no connection as `NO_CONNECTION` (the sender still gets `200`, and the request is kept); the bridge listed only accepted requests. It now also reads verified requests rejected as `NO_CONNECTION`. Broken since 0.8.0. +- **`setup` registers again a webhook deleted at the service:** on a re-run with nothing changed, it reported `webhook existing` for a Resend or GitHub source whose webhook had been deleted at the service, so no events arrived. It now checks the saved webhook (Resend's webhook by its id; GitHub's in each repository, or the organization, by the source URL) and, if it's missing, logs `the webhook saved on bridge- is missing at ; registering it again` and reports `registered`. If it can't check (a key or token that can't read webhooks, or the service didn't answer), it keeps the saved webhook, reports `existing`, and logs a warning. Sources defined with `defineSource` can opt in with an optional `webhookExists`. ## 0.9.0 (2026-11-05) diff --git a/README.md b/README.md index 70fc10b..d07a119 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ You need: npx mcp-events-bridge setup ``` - The first run generates an MCP secret: add it to `.env` as `BRIDGE_MCP_SECRET`. Setup is safe to re-run, and updates the webhooks when you add sources or change events or repositories. Removing a source or a repository deletes nothing: delete its webhook (and its Event Gateway source) yourself. Upgrading from 0.7, setup offers to migrate your subscriptions: see [`docs/UPGRADING.md`](docs/UPGRADING.md). + The first run generates an MCP secret: add it to `.env` as `BRIDGE_MCP_SECRET`. Setup is safe to re-run, and updates the webhooks when you add sources or change events or repositories. A Resend or GitHub webhook deleted at the service is registered again. Removing a source or a repository deletes nothing: delete its webhook (and its Event Gateway source) yourself. Upgrading from 0.7, setup offers to migrate your subscriptions: see [`docs/UPGRADING.md`](docs/UPGRADING.md). 5. **Run the bridge:** @@ -488,6 +488,8 @@ Three TypeScript MCP client libraries have experimental MCP Events support, and | ``Config: `providers` in the config is now `sources` ...`` (or another name "removed in 0.8.0") | A name deprecated in 0.6.0 | Rename it as the message says | | `serve` logs `subscription ... is for "...", which this bridge doesn't offer` | The source was removed, its `id` renamed, or the subscription is from 0.1.0 (before `{id}.{event}` names); or it belongs to another bridge in the same Hookdeck project | The agent subscribes again, to a name from `events/list`; ignore another bridge's | | `events/subscribe` fails with "Unknown event" | An old or wrong name | Use a name from `events/list` | +| No events from Resend or GitHub reach the source | The webhook was deleted at the service | Run `setup` again: it checks the saved webhook, and registers it again if it's missing | +| `setup` logs `warning: could not confirm the webhook saved on bridge- still exists` | The API key or token can't read webhooks, or the service didn't answer | Setup kept the saved webhook. Fix the key or token (GitHub: Webhooks permission) and run `setup` again | | A sender gets 401 | Wrong signature, header, encoding or secret | Match the source's `verification` or secret; a new secret can take about a minute to apply | | An agent doesn't get an event | The subscription's filter didn't match, the event type isn't enabled, or the callback is failing | In the Event Gateway dashboard, the subscription's connection, `mcp-sub-`, shows each request: `FILTERED` for a filter or an event type it doesn't offer, or the failed attempts. `list_sources` shows each source's events and subscriptions | | `serve` logs `warning: is a pass-through callback URL` | A subscription uses a callback URL created without a secret | Expected for Hermes Agent and the client libraries; the receiver must verify every delivery | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ec2d213..c4cddcb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -605,6 +605,7 @@ const resend = defineSource({ runtimeConfig: undefined, // JSON, passed to the runtime register?(ctx): Promise<{ webhookId: string; signingSecret: string }>, unregister?(ctx): Promise, + webhookExists?(ctx): Promise, // on a re-run with nothing changed: false re-registers, a rejection keeps it and warns sourceConfig?(options), missingCredentials?(options), setupHint?(ctx), ... }); @@ -673,7 +674,7 @@ GitHub has about 70 webhook event types, most with several actions, and payloads - **Scope:** a list of repositories (`{ repos: ['owner/name', ...] }`) or an organization (`{ org: 'name' }`). Personal accounts have no account-wide webhooks, and organization webhooks need an org admin, so the list is the common case. Every repository's webhook points at the same `GITHUB` source with the same secret; the payload names the repository, and subscribers filter on it. - **Secret:** GitHub lets the caller choose it, so `register()` generates one and sets it on the source, which verifies `X-Hub-Signature-256`. - **Manual mode:** `github({ webhookSecret })`, with no token or scope. Setup creates the source with that secret and prints the source URL; you add webhooks to any repositories yourself. Only deliveries signed with the secret get past Event Gateway, so "any repository" means any repository you configured. A GitHub App would make this automatic across installations; that's later. -- **No ids stored:** the bridge finds its webhooks by URL (the source URL), so it doesn't keep an id per repository in the 500-character source description. Registering updates a webhook in place if one already delivers to the source, so re-running after a partial failure doesn't duplicate webhooks. +- **No ids stored:** the bridge finds its webhooks by URL (the source URL), so it doesn't keep an id per repository in the 500-character source description. Registering updates a webhook in place if one already delivers to the source, so re-running after a partial failure doesn't duplicate webhooks. On a re-run with nothing changed, setup lists each repository's (or the organization's) webhooks: if one has none delivering to the source URL (deleted on GitHub), it registers again, reusing the source's secret, so the other repositories' webhooks keep verifying. - **Changing the list:** setup keeps a fingerprint of the repositories and the enabled events in the source description. When either changes, it updates the webhooks and reuses the source's secret, so deliveries in flight still verify. Removing a repository from the list leaves its webhook in place; delete it in the repository's settings, or its events keep arriving (subscribers filtering by repository won't see them). - **Event id:** `X-GitHub-Delivery`, so also the `webhook-id` each subscription's connection dedupes on. **Occurred-at:** the main object's latest timestamp, else the push's head commit, else the time received. The `ping` sent when a webhook is created matches no event and is ignored. diff --git a/skills/mcp-events-bridge/SKILL.md b/skills/mcp-events-bridge/SKILL.md index 4e85d64..ee7a6fd 100644 --- a/skills/mcp-events-bridge/SKILL.md +++ b/skills/mcp-events-bridge/SKILL.md @@ -57,7 +57,7 @@ Write `.env` with `HOOKDECK_API_KEY`, `HOOKDECK_SIGNING_SECRET` and each source' npx mcp-events-bridge setup ``` -- **Success:** a line per source (`source resend: https://hkdk.events/..., transformation bridge-resend-envelope, webhook registered`; on a re-run, `updated` or `existing`), then the MCP endpoint. Exit code 0. With a local bridge it also logs the Hookdeck CLI in to the bridge's project in `.hookdeck/config.toml`, so `hookdeck` commands run in this directory use that project. +- **Success:** a line per source (`source resend: https://hkdk.events/..., transformation bridge-resend-envelope, webhook registered`; on a re-run, `updated` or `existing`, or `registered` again if the Resend or GitHub webhook was deleted at the service, after the log line `the webhook saved on bridge- is missing at ; registering it again`), then the MCP endpoint. Exit code 0. With a local bridge it also logs the Hookdeck CLI in to the bridge's project in `.hookdeck/config.toml`, so `hookdeck` commands run in this directory use that project. - **First run:** it generates an MCP secret and prints a `BRIDGE_MCP_SECRET=...` line. Add that line to `.env` as printed. `setup` prints the full MCP URL, secret included, on every run: don't repeat it in your replies or write it anywhere but `.env`. - **Exit code 1 with "Setup isn't complete":** a `source()`'s secret is missing (step 3). Everything else was set up. - **Data from 0.7:** setup says "The bridge's data model in Event Gateway changed in 0.8" and asks `Migrate now? [Y/n]`. Answer `y`; it ends with `migrated subscription(s) and callback URL(s)`. Declining exits 1, and `serve` won't start until it's migrated. @@ -115,6 +115,8 @@ Every event is named **`{source id}.{event}`**: the source `id` (by default its | Log: `subscription ... is for "...", which this bridge doesn't offer` | The source was removed, its `id` renamed, or the subscription is from 0.1.0; or it belongs to another bridge in the same Hookdeck project | The agent subscribes again, to a name from `events/list`; ignore another bridge's | | `events/subscribe` fails: "Unknown event" | Old or wrong name | Use a name from `events/list` | | A sender gets 401 | Wrong signature, header, encoding or secret | Match the source's `verification` or secret; a new secret can take about a minute | +| No events from Resend or GitHub reach the source | The webhook was deleted at the service | Run `setup` again: it checks the saved webhook, and registers it again if it's missing | +| `setup` logs `warning: could not confirm the webhook saved on bridge- still exists` | The API key or token can't read webhooks, or the service didn't answer | Setup kept the saved webhook. Fix the key or token (GitHub: Webhooks permission) and run `setup` again | | An agent doesn't get an event | Its filter or event type didn't match, or its callback is failing | Check the subscription's connection, `mcp-sub-`, in the Event Gateway dashboard (`FILTERED`, or failed attempts), and its name and arguments | | An event arrives after a minute or two | `hookdeck listen` occasionally takes ~30s to connect; Event Gateway occasionally queues a CLI delivery | Wait; missed deliveries are retried by the bridge | | The same event twice | A retry, or a replay | Receivers dedupe by `webhook-id` | diff --git a/src/core/setup.ts b/src/core/setup.ts index 7c6b264..ae73d07 100644 --- a/src/core/setup.ts +++ b/src/core/setup.ts @@ -9,7 +9,8 @@ import { ensureTransformations } from './transformation.js'; * `setup`: creates or updates everything the config describes in Event Gateway and at services: each source, its * webhook at the service, and the transformation its subscriptions share. Idempotent: a webhook is registered once * and its id is kept in the source description, so re-running doesn't create another. If the enabled events or the - * registration target (for example GitHub repositories) change, the webhook is updated. Subscriptions themselves are + * registration target (for example GitHub repositories) change, the webhook is updated; if it was deleted at the + * service (for sources that can check, `webhookExists`), it's registered again. Subscriptions themselves are * connections the bridge creates on each source when clients subscribe. */ @@ -129,6 +130,22 @@ export async function ensureSource(hookdeck: HookdeckClient, provider: ResolvedS return { source, existing, configured, missing }; } +/** + * Whether the webhook saved in the source description is still at the service. True when the source can't check, and + * when the check fails for another reason than the webhook being gone (a key without read access, the network): setup + * then keeps the saved webhook, as before it checked, and warns. + */ +async function savedWebhookExists(deps: SetupDeps, provider: ResolvedSource, sourceUrl: string, webhookId: string, log: (message: string) => void) { + const { definition } = provider; + if (!definition.webhookExists) return true; + try { + return await definition.webhookExists({ webhookId, sourceUrl, options: provider.options, fetch: deps.fetch }); + } catch (error) { + log(`warning: could not confirm the ${definition.displayName} webhook saved on ${providerSourceName(provider.id)} still exists, so keeping it: ${(error as Error).message}`); + return true; + } +} + async function setupProvider(deps: SetupDeps, provider: ResolvedSource) { const { config, hookdeck } = deps; const log = deps.log ?? (() => {}); @@ -164,10 +181,17 @@ async function setupProvider(deps: SetupDeps, provider: ResolvedSource) { const changed = !sameList(existing.events, provider.events) || existing.target !== target || (configured !== undefined && configured !== secret); if (typeof secret === 'string' && secret) { - if (!changed) return report('existing'); - log(`the ${definition.displayName} events, registration target or secret changed; updating the webhook`); - currentSecret = secret; - previousId = existing.webhookId; + if (!changed) { + if (await savedWebhookExists(deps, provider, source.url, existing.webhookId, log)) return report('existing'); + // Deleted at the service: register it again, as on a first run. The source's secret is offered for reuse, so + // a service that lets the caller choose it (GitHub) keeps the one its other webhooks and Event Gateway have. + log(`the ${definition.displayName} webhook saved on ${sourceName} is missing at ${definition.displayName}; registering it again`); + currentSecret = secret; + } else { + log(`the ${definition.displayName} events, registration target or secret changed; updating the webhook`); + currentSecret = secret; + previousId = existing.webhookId; + } } else { // The source lost its signing secret: replace the provider webhook, since its secret can't be read back. log(`${sourceName} has no signing secret; replacing the ${definition.displayName} webhook`); diff --git a/src/core/sources/github.ts b/src/core/sources/github.ts index eade68c..cba3a21 100644 --- a/src/core/sources/github.ts +++ b/src/core/sources/github.ts @@ -340,4 +340,18 @@ export const githubProvider: SourceDefinition = { } } }, + + /** + * True when every repository in scope (or the organization) has a webhook delivering to the source URL. Webhooks + * are matched by URL, so there's no id to look up. A failed listing (GitHub answers 404 for a repository the token + * can't see) rejects rather than resolving false. Manual-mode webhooks are added by hand, with no token to check. + */ + async webhookExists({ webhookId, sourceUrl, options, fetch: fetchFn }) { + if (webhookId === MANUAL || !options.scope) return true; + if (!options.token) throw new Error('github: a token is needed to check the webhooks (GITHUB_TOKEN)'); + for (const path of hookPaths(options.scope)) { + if (!(await hooksForUrl(fetchFn, options.token, path, sourceUrl)).length) return false; + } + return true; + }, }; diff --git a/src/core/sources/resend.ts b/src/core/sources/resend.ts index cc257bf..f633135 100644 --- a/src/core/sources/resend.ts +++ b/src/core/sources/resend.ts @@ -103,6 +103,12 @@ export const emailReceived: SourceEvent = { payloadSchema: z.toJSONSchema(emailReceivedPayload) as Record, }; +class ResendApiError extends Error { + constructor(message: string, readonly status: number) { + super(message); + } +} + async function resendApi(fetchFn: typeof fetch, apiKey: string, path: string, init: { method: string; body?: unknown }) { const res = await fetchFn(`${RESEND_API}${path}`, { method: init.method, @@ -110,7 +116,7 @@ async function resendApi(fetchFn: typeof fetch, apiKey: string, path: string, in body: init.body === undefined ? undefined : JSON.stringify(init.body), }); const text = await res.text(); - if (!res.ok) throw new Error(`Resend ${init.method} ${path} -> ${res.status} ${text.slice(0, 300)}`); + if (!res.ok) throw new ResendApiError(`Resend ${init.method} ${path} -> ${res.status} ${text.slice(0, 300)}`, res.status); return text ? (JSON.parse(text) as Record) : {}; } @@ -136,4 +142,15 @@ export const resendProvider: SourceDefinition = { async unregister({ webhookId, options, fetch: fetchFn }) { await resendApi(fetchFn, options.apiKey, `/webhooks/${encodeURIComponent(webhookId)}`, { method: 'DELETE' }); }, + + /** A 404 means the webhook was deleted at Resend; any other failure means setup can't tell. */ + async webhookExists({ webhookId, options, fetch: fetchFn }) { + try { + await resendApi(fetchFn, options.apiKey, `/webhooks/${encodeURIComponent(webhookId)}`, { method: 'GET' }); + return true; + } catch (error) { + if (error instanceof ResendApiError && error.status === 404) return false; + throw error; + } + }, }; diff --git a/src/core/sources/types.ts b/src/core/sources/types.ts index 4d9a5e4..d2c24ba 100644 --- a/src/core/sources/types.ts +++ b/src/core/sources/types.ts @@ -116,6 +116,13 @@ export interface SourceDefinition, Config = an */ register?(ctx: RegisterContext): Promise<{ webhookId: string; signingSecret: string }>; unregister?(ctx: { webhookId: string; sourceUrl: string; options: Options; fetch: typeof fetch }): Promise; + /** + * Whether the webhook `register` returned still exists at the service. On a re-run with nothing changed, setup asks + * before reporting the webhook as existing, and registers it again when this resolves false (someone deleted it at + * the service). Rejects when it can't tell (for example the key can't read webhooks, or the network fails): setup + * then keeps the saved webhook and warns. Without it, setup trusts the saved webhook id. + */ + webhookExists?(ctx: { webhookId: string; sourceUrl: string; options: Options; fetch: typeof fetch }): Promise; } /** `Name ` or `addr@example.com` to `addr@example.com`, lower-cased. For parsing arguments. */ diff --git a/test/core/setup.test.ts b/test/core/setup.test.ts index d06abea..741a2bd 100644 --- a/test/core/setup.test.ts +++ b/test/core/setup.test.ts @@ -8,13 +8,26 @@ import { FakeEventGateway } from '../support/fake-event-gateway.js'; const environment = { HOOKDECK_API_KEY: 'hk', HOOKDECK_SIGNING_SECRET: 'hs', RESEND_API_KEY: 're_1' }; +/** Resend's webhooks API: POST creates, GET reads (404 once deleted), DELETE deletes. */ function resendApi() { const calls: Array<{ url: string; body: unknown }> = []; + const webhooks = new Set(); + /** When set, GET /webhooks/{id} fails with this status (for example 401 for a key that can't read webhooks). */ + const state: { getFailsWith?: number } = {}; const fetch = (async (url: string, init: RequestInit) => { calls.push({ url, body: init.body ? JSON.parse(String(init.body)) : undefined }); - return new Response(JSON.stringify({ object: 'webhook', id: `wh_${calls.length}`, signing_secret: 'whsec_from_resend' }), { status: 201 }); + const id = /\/webhooks\/([^/]+)$/.exec(url)?.[1]; + const method = init.method ?? 'GET'; + if (method === 'POST') { + webhooks.add(`wh_${calls.length}`); + return new Response(JSON.stringify({ object: 'webhook', id: `wh_${calls.length}`, signing_secret: 'whsec_from_resend' }), { status: 201 }); + } + if (method === 'GET' && state.getFailsWith) return new Response('{"message":"API key is invalid"}', { status: state.getFailsWith }); + if (!id || !webhooks.has(id)) return new Response('{"message":"Webhook not found"}', { status: 404 }); + if (method === 'DELETE') webhooks.delete(id); + return Response.json({ object: 'webhook', id, endpoint: 'https://hkdk.events/x', events: ['email.received'] }); }) as unknown as typeof globalThis.fetch; - return { fetch, calls }; + return { fetch, calls, webhooks, state }; } function setup(over: Record = {}, env_: Record = environment) { @@ -22,7 +35,8 @@ function setup(over: Record = {}, env_: Record const hookdeck = new HookdeckClient({ apiKey: 'hk', fetch: gateway.fetch }); const config = resolveConfig(defineConfig({ deployment: 'dev', sources: [resend({ apiKey: env('RESEND_API_KEY') })], ...over }), env_); const resendFake = resendApi(); - return { gateway, run: () => runSetup({ config, hookdeck, fetch: resendFake.fetch }), resendFake }; + const logs: string[] = []; + return { gateway, run: () => runSetup({ config, hookdeck, fetch: resendFake.fetch, log: (m) => logs.push(m) }), resendFake, logs }; } describe('bridge setup', () => { @@ -40,16 +54,49 @@ describe('bridge setup', () => { expect(report.sources).toEqual([{ id: 'resend', sourceUrl: source.url, transformation: 'bridge-resend-envelope', webhook: 'registered' }]); }); - it('is idempotent: a second run reuses the registered webhook and keeps the source secret', async () => { + it('is idempotent: a second run checks the registered webhook is still at Resend, reuses it, and keeps the source secret', async () => { const { gateway, run, resendFake } = setup(); await run(); const second = await run(); - expect(resendFake.calls).toHaveLength(1); + expect(resendFake.calls.map((c) => c.url)).toEqual(['https://api.resend.com/webhooks', 'https://api.resend.com/webhooks/wh_1']); expect(second.sources[0]!.webhook).toBe('existing'); expect([...gateway.sources.values()].find((s) => s.name === 'bridge-resend')!.config).toMatchObject({ auth: { webhook_secret_key: 'whsec_from_resend' } }); expect([...gateway.transformations.values()].map((t) => t.name)).toEqual(['bridge-resend-envelope']); }); + it('registers the webhook again when it was deleted at Resend, and saves the new id and secret', async () => { + // Found live with GitHub: the webhook was deleted at the service, and re-running setup said `webhook existing`. + const { gateway, run, resendFake, logs } = setup(); + await run(); + resendFake.webhooks.clear(); + const source = [...gateway.sources.values()].find((s) => s.name === 'bridge-resend')!; + source.config = { auth: { webhook_secret_key: 'whsec_old' } }; + + logs.length = 0; + const report = await run(); + expect(report.sources[0]!.webhook).toBe('registered'); + expect(logs).toContain('the Resend webhook saved on bridge-resend is missing at Resend; registering it again'); + expect(logs).toContain('registered the Resend webhook and set its secret on bridge-resend'); + // A fresh registration: the missing webhook isn't deleted, and the new one's id and secret are saved. + expect(resendFake.calls.map((c) => c.url)).toEqual(['https://api.resend.com/webhooks', 'https://api.resend.com/webhooks/wh_1', 'https://api.resend.com/webhooks']); + expect(JSON.parse(source.description!)).toEqual({ provider: 'resend', events: ['email.received'], webhookId: 'wh_3' }); + expect(source.config).toMatchObject({ auth: { webhook_secret_key: 'whsec_from_resend' } }); + }); + + it("keeps the saved webhook and warns when it can't check it at Resend", async () => { + const { run, resendFake, logs } = setup(); + await run(); + resendFake.state.getFailsWith = 401; + + logs.length = 0; + const report = await run(); + expect(report.sources[0]!.webhook).toBe('existing'); + expect(logs).toContainEqual( + expect.stringMatching(/^warning: could not confirm the Resend webhook saved on bridge-resend still exists, so keeping it: Resend GET \/webhooks\/wh_1 -> 401/), + ); + expect(resendFake.calls.map((c) => c.url)).toEqual(['https://api.resend.com/webhooks', 'https://api.resend.com/webhooks/wh_1']); + }); + it('replaces the provider webhook if the source lost its signing secret', async () => { const { gateway, run, resendFake } = setup(); await run(); @@ -86,6 +133,61 @@ describe('bridge setup', () => { expect(gh.calls.filter((c) => c.startsWith('DELETE'))).toEqual([]); }); + it('GitHub: re-registers a webhook deleted at GitHub, keeping the secret the other repositories use', async () => { + const gateway = new FakeEventGateway(); + const hookdeck = new HookdeckClient({ apiKey: 'hk', fetch: gateway.fetch }); + const gh = new FakeGithub(); + const logs: string[] = []; + const run = () => + runSetup({ + config: resolveConfig(defineConfig({ deployment: 'dev', sources: [github({ token: 't', scope: { repos: ['o/one', 'o/two'] } })] }), environment), + hookdeck, + fetch: gh.fetch, + log: (m) => logs.push(m), + }); + + await run(); + const source = [...gateway.sources.values()].find((s) => s.name === 'bridge-github')!; + const secret = (source.config as { auth: { webhook_secret_key: string } }).auth.webhook_secret_key; + + // Present: one listing per repository, nothing written. + gh.calls.length = 0; + expect((await run()).sources[0]!.webhook).toBe('existing'); + expect(gh.calls).toEqual(['GET /repos/o/one/hooks', 'GET /repos/o/two/hooks']); + + // Deleted on one repository: registered again there; the other is updated in place with the same secret. + gh.hooks.set('/repos/o/two/hooks', []); + logs.length = 0; + expect((await run()).sources[0]!.webhook).toBe('registered'); + expect(logs).toContain('the GitHub webhook saved on bridge-github is missing at GitHub; registering it again'); + for (const path of ['/repos/o/one/hooks', '/repos/o/two/hooks']) { + expect(gh.hooks.get(path)).toEqual([expect.objectContaining({ config: expect.objectContaining({ url: source.url, secret }) })]); + } + expect(source.config).toMatchObject({ auth: { webhook_secret_key: secret } }); + expect(gh.calls.filter((c) => c.startsWith('DELETE'))).toEqual([]); + }); + + it("GitHub: keeps the saved webhook and warns when the token can't list webhooks", async () => { + const gateway = new FakeEventGateway(); + const hookdeck = new HookdeckClient({ apiKey: 'hk', fetch: gateway.fetch }); + const gh = new FakeGithub(); + const logs: string[] = []; + const run = () => + runSetup({ + config: resolveConfig(defineConfig({ deployment: 'dev', sources: [github({ token: 't', scope: { repos: ['o/one'] } })] }), environment), + hookdeck, + fetch: gh.fetch, + log: (m) => logs.push(m), + }); + + await run(); + gh.failWith = 403; + gh.calls.length = 0; + expect((await run()).sources[0]!.webhook).toBe('existing'); + expect(logs).toContainEqual(expect.stringMatching(/^warning: could not confirm the GitHub webhook saved on bridge-github still exists, so keeping it: GitHub GET .* -> 403/)); + expect(gh.calls).toEqual(['GET /repos/o/one/hooks']); + }); + it('GitHub manual mode: puts the configured secret on the source, prints a hint, and follows secret changes', async () => { const gateway = new FakeEventGateway(); const hookdeck = new HookdeckClient({ apiKey: 'hk', fetch: gateway.fetch }); diff --git a/test/core/sources/github.test.ts b/test/core/sources/github.test.ts index 7e23b73..ed0baa4 100644 --- a/test/core/sources/github.test.ts +++ b/test/core/sources/github.test.ts @@ -131,6 +131,25 @@ describe('GitHub provider', () => { expect(gh.calls.filter((c) => c.startsWith('PATCH'))).toHaveLength(1); }); + it('checks the webhooks still exist: in every repository, by source URL, and not in manual mode', async () => { + const gh = new FakeGithub(); + const sourceUrl = 'https://hkdk.events/abc'; + const options = { token: 'ghp_test', scope: { repos: ['example-org/widgets', 'example-org/gadgets'] } }; + const { webhookId } = await githubProvider.register!({ sourceUrl, providerEvents: ['issues'], options, fetch: gh.fetch }); + const exists = () => githubProvider.webhookExists!({ webhookId, sourceUrl, options, fetch: gh.fetch }); + await expect(exists()).resolves.toBe(true); + + gh.hooks.set('/repos/example-org/gadgets/hooks', [{ id: 99, events: ['push'], config: { url: 'https://other.example.com', secret: 'x' } }]); + await expect(exists()).resolves.toBe(false); + + gh.failWith = 404; + await expect(exists()).rejects.toThrow(/404/); + + const manual = new FakeGithub(); + await expect(githubProvider.webhookExists!({ webhookId: 'manual', sourceUrl, options: { webhookSecret: 'a-secret-of-16-chars-plus' }, fetch: manual.fetch })).resolves.toBe(true); + expect(manual.calls).toEqual([]); + }); + it('sends the API version and token, and rejects badly formed repositories', async () => { const seen: Array> = []; const fetchFn = (async (_url: string, init: RequestInit) => { diff --git a/test/core/sources/resend.test.ts b/test/core/sources/resend.test.ts index 3b20d2e..cd65c2b 100644 --- a/test/core/sources/resend.test.ts +++ b/test/core/sources/resend.test.ts @@ -117,6 +117,22 @@ describe('Resend register and unregister', () => { ).rejects.toThrow(/401/); }); + it('checks the webhook still exists: true when Resend has it, false on 404, and rejects on other failures', async () => { + const calls: string[] = []; + let status = 200; + const fetchFn = (async (url: string, init: RequestInit) => { + calls.push(`${init.method} ${url}`); + return new Response(status === 200 ? '{"object":"webhook","id":"wh_1"}' : '{"message":"no"}', { status }); + }) as unknown as typeof fetch; + const exists = () => resend.webhookExists!({ webhookId: 'wh_1', sourceUrl: 'https://hkdk.events/abc', options: { apiKey: 're_test' }, fetch: fetchFn }); + await expect(exists()).resolves.toBe(true); + expect(calls).toEqual(['GET https://api.resend.com/webhooks/wh_1']); + status = 404; + await expect(exists()).resolves.toBe(false); + status = 401; + await expect(exists()).rejects.toThrow(/401/); + }); + it('deletes the webhook', async () => { const calls: string[] = []; const fetchFn = (async (url: string, init: RequestInit) => { diff --git a/test/support/fake-github.ts b/test/support/fake-github.ts index 3cda971..58d4805 100644 --- a/test/support/fake-github.ts +++ b/test/support/fake-github.ts @@ -3,14 +3,18 @@ export class FakeGithub { /** Hooks by hooks path, e.g. /repos/o/r/hooks. */ readonly hooks = new Map>(); readonly calls: string[] = []; + /** When set, every request fails with this status (for example 401 for a revoked token). */ + failWith: number | undefined; private nextId = 1; readonly fetch = (async (input: string, init: RequestInit) => { const url = new URL(input); const method = init.method ?? 'GET'; this.calls.push(`${method} ${url.pathname}`); + if (this.failWith !== undefined) return new Response('{"message":"Bad credentials"}', { status: this.failWith }); const body = init.body ? JSON.parse(String(init.body)) : undefined; - const match = /^(.*\/hooks)(?:\/(\d+))?$/.exec(url.pathname); + // GitHub's owner and repository names are case-insensitive. + const match = /^(.*\/hooks)(?:\/(\d+))?$/.exec(url.pathname.toLowerCase()); if (!match) return new Response('{"message":"Not Found"}', { status: 404 }); const [, path, id] = match as unknown as [string, string, string | undefined]; const list = this.hooks.get(path) ?? [];