From 68636aaaf75cd9fb9311aebf1525f7a6d37e36b7 Mon Sep 17 00:00:00 2001 From: Rhys Sullivan <39114868+RhysSullivan@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:58:18 -0800 Subject: [PATCH] X: deliver only to webhooks whose challenge was answered A webhook address accepted only through control mode's relaxation (http, or a port, on an https instance) is never called: its deliveries are held, listed as held in the arrival's response and on the ledger entry of a DM sent through X's route, and previewable with preview-delivery. Any webhook now gets deliveries only once a challenge has been answered for it, as on X: the CRC at creation or on PUT in outbound mode, or a correct answer at POST /_emulate/x/webhooks/:id/challenge in control mode. Until then, and for a seeded webhook until PUT, deliveries are held. Control mode used to deliver to an https address nobody had answered a challenge from. --- README.md | 2 +- apps/web/app/docs/x/page.mdx | 2 +- .../x/src/__tests__/webhooks-media.test.ts | 121 ++++++++++++++++++ packages/@emulators/x/src/activity.ts | 35 +++++ packages/@emulators/x/src/entities.ts | 6 + packages/@emulators/x/src/index.ts | 2 + packages/@emulators/x/src/manifest.ts | 2 +- packages/@emulators/x/src/routes/control.ts | 5 +- packages/@emulators/x/src/routes/dm.ts | 17 ++- packages/@emulators/x/src/routes/webhooks.ts | 3 +- skills/x/SKILL.md | 4 +- 11 files changed, 191 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 939790ebc..a72806915 100644 --- a/README.md +++ b/README.md @@ -1086,7 +1086,7 @@ x: For a test the emulator cannot reach: -- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` (or seed `webhook_crc_delivery: control`) is an emulator mode: creation sends no challenge, and `GET /_emulate/x/webhooks/:id/challenge` returns the GET X would send for the test to deliver; report the answer with `POST /_emulate/x/webhooks/:id/challenge`. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port). +- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` (or seed `webhook_crc_delivery: control`) is an emulator mode: creation sends no challenge, and `GET /_emulate/x/webhooks/:id/challenge` returns the GET X would send for the test to deliver; report the answer with `POST /_emulate/x/webhooks/:id/challenge`. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port). The emulator never calls such an address: its deliveries are held and listed as held, and `POST /_emulate/x/dm/preview-delivery` gives the exact signed request. Deliveries go only to a webhook whose challenge was answered (X's CRC at creation or on `PUT /2/webhooks/:id`, or, in control mode, a correct answer at `POST /_emulate/x/webhooks/:id/challenge`); until then they are held, as are a seeded webhook's until `PUT`. - `POST /_emulate/x/dm/arrive` with `{"to":"developer","from":"alice","text":"hi"}` makes a message arrive (stored, then delivered). - `POST /_emulate/x/dm/preview-delivery` with `{"dm_event_id":"..."}` returns the exact URL, headers and body of each delivery without sending it. diff --git a/apps/web/app/docs/x/page.mdx b/apps/web/app/docs/x/page.mdx index f8ca7d550..fdd276b28 100644 --- a/apps/web/app/docs/x/page.mdx +++ b/apps/web/app/docs/x/page.mdx @@ -62,7 +62,7 @@ Creating a webhook sends `GET ?crc_token=...`; the answer must be `sha256=` ### Tests the emulator cannot reach -- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` switches the instance to an emulator mode: webhook creation sends no challenge, `GET /_emulate/x/webhooks/:id/challenge` returns the request X would make, and `POST /_emulate/x/webhooks/:id/challenge` with the app's `response_token` checks it as X would. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port). +- `POST /_emulate/x/webhooks/crc-delivery` with `{"mode":"control"}` switches the instance to an emulator mode: webhook creation sends no challenge, `GET /_emulate/x/webhooks/:id/challenge` returns the request X would make, and `POST /_emulate/x/webhooks/:id/challenge` with the app's `response_token` checks it as X would. In control mode `POST /2/webhooks` also accepts an `http` address or one with a port, which X refuses (an emulator-only relaxation), so a local receiver can be registered, subscribed to and its deliveries previewed; outbound mode keeps X's rule (https, no port). The emulator never calls such an address: its deliveries are held and listed as held, and `POST /_emulate/x/dm/preview-delivery` gives the exact signed request. Deliveries go only to a webhook whose challenge was answered (X's CRC at creation or on `PUT /2/webhooks/:id`, or, in control mode, a correct answer at `POST /_emulate/x/webhooks/:id/challenge`); until then they are held, as are a seeded webhook's until `PUT`. - `POST /_emulate/x/dm/arrive` with `{"to":"developer","from":"alice","text":"hi"}` makes a message arrive: stored, readable, and delivered to subscribers. - `POST /_emulate/x/dm/preview-delivery` with `{"dm_event_id":"..."}` returns each delivery's URL, headers and body without sending it; the bytes match a real delivery. diff --git a/packages/@emulators/x/src/__tests__/webhooks-media.test.ts b/packages/@emulators/x/src/__tests__/webhooks-media.test.ts index daa6379d0..5aedd011c 100644 --- a/packages/@emulators/x/src/__tests__/webhooks-media.test.ts +++ b/packages/@emulators/x/src/__tests__/webhooks-media.test.ts @@ -257,6 +257,127 @@ describe("webhook addresses in each CRC mode on an https instance", () => { }); }); +describe("deliveries go only to an address whose owner answered the challenge", () => { + const answer = async (control: (path: string, body?: unknown) => Promise, id: string) => { + const challenge = (await (await control(`/webhooks/${id}/challenge`)).json()) as Json; + return (await ( + await control(`/webhooks/${id}/challenge`, { response_token: sign(SECRET, challenge.crc_token) }) + ).json()) as Json; + }; + + it("never calls an address accepted only through control mode's relaxation, even once answered", async () => { + const r = await receiver(SECRET); // http://127.0.0.1:: http and a port + const host = "https://x.example.test"; + const server = createServer(xPlugin, { baseUrl: host }); + seedFromConfig(server.store, host, { + users: [ + { username: "developer", user_id: DEV }, + { username: "alice", user_id: ALICE }, + ], + oauth_clients: [{ client_id: "dm-app", client_secret: SECRET, client_type: "confidential" }], + webhook_crc_delivery: "control", + }); + const xs = getXStore(server.store); + for (const [t, user] of [ + ["app", null], + ["dev", DEV], + ["alice", ALICE], + ] as const) { + xs.accessTokens.insert({ + token: t, + client_id: "dm-app", + user_id: user, + scopes: ["dm.read", "dm.write", "tweet.read", "users.read"], + app_only: !user, + expires: 0, + }); + } + const req = (path: string, token: string | null, body?: unknown) => + server.app.request(`${host}${path}`, { + method: body === undefined ? "GET" : "POST", + headers: { ...(token ? { Authorization: `Bearer ${token}` } : {}), "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const control = (path: string, body?: unknown) => req(`/_emulate/x${path}`, null, body); + const hook = ((await (await req("/2/webhooks", "app", { url: r.url })).json()) as Json).data; + await req("/2/activity/subscriptions", "dev", { + event_type: "dm.received", + filter: { user_id: DEV }, + webhook_id: hook.id, + }); + expect((await answer(control, hook.id)).valid).toBe(true); + + const arrived = (await ( + await control("/dm/arrive", { to: "developer", from: "alice", text: "hi" }) + ).json()) as Json; + expect(arrived.deliveries).toHaveLength(1); + expect(arrived.deliveries[0].held).toMatch(/never calls such an address/); + expect(arrived.deliveries[0].success).toBe(false); + expect(r.received).toHaveLength(0); + const preview = (await ( + await control("/dm/preview-delivery", { dm_event_id: arrived.dm_event_id }) + ).json()) as Json; + expect(preview.deliveries[0].url).toBe(r.url); + expect(preview.deliveries[0].headers["x-twitter-webhooks-signature-oauth2"]).toBe( + sign(SECRET, preview.deliveries[0].body), + ); + // A DM sent through X's own route is on the ledger, with the held delivery. + const sent = await req(`/2/dm_conversations/with/${DEV}/messages`, "alice", { text: "via the API" }); + expect(sent.status).toBe(201); + expect(r.received).toHaveLength(0); + const entry = server.ledger.list().find((e) => e.method === "POST" && e.path.endsWith("/messages"))!; + expect(entry.summary).toBeDefined(); + expect(entry.sideEffects.find((e) => e.collection === "x.dm_events")!.summary).toMatch( + /0 webhook deliveries sent, 1 held/, + ); + expect( + entry.sideEffects.some((e) => e.collection === "x.webhook_deliveries" && /never calls/.test(e.summary ?? "")), + ).toBe(true); + }); + + it("holds deliveries in control mode until the test answers the challenge, then sends them", async () => { + const r = await receiver(SECRET); + const { call, mint, control } = setup({ webhook_crc_delivery: "control" }); + const hook = ( + (await ( + await call("/2/webhooks", mint(null), { method: "POST", body: JSON.stringify({ url: r.url }) }) + ).json()) as Json + ).data; + await call("/2/activity/subscriptions", mint(DEV), { + method: "POST", + body: JSON.stringify({ event_type: "dm.received", filter: { user_id: DEV }, webhook_id: hook.id }), + }); + const before = (await ( + await control("/dm/arrive", { to: "developer", from: "alice", text: "one" }) + ).json()) as Json; + expect(before.deliveries[0].held).toMatch(/no challenge has been answered/); + expect(r.received).toHaveLength(0); + + expect((await answer(control, hook.id)).valid).toBe(true); + const after = (await (await control("/dm/arrive", { to: "developer", from: "alice", text: "two" })).json()) as Json; + expect(after.deliveries[0]).toMatchObject({ success: true }); + expect(after.deliveries[0].held).toBeUndefined(); + expect(r.received.filter((x) => x.method === "POST")).toHaveLength(1); + }); + + it("holds deliveries to a seeded webhook until PUT passes X's CRC", async () => { + const r = await receiver(SECRET); + const { call, mint, control } = setup({ + webhooks: [{ client_id: "dm-app", url: r.url }], + activity_subscriptions: [{ event_type: "dm.received", user: "developer", webhook: r.url }], + }); + const before = (await ( + await control("/dm/arrive", { to: "developer", from: "alice", text: "one" }) + ).json()) as Json; + expect(before.deliveries[0].held).toMatch(/no challenge has been answered/); + const hooks = (await (await call("/2/webhooks", mint(null))).json()) as Json; + expect((await call(`/2/webhooks/${hooks.data[0].id}`, mint(null), { method: "PUT" })).status).toBe(200); + const after = (await (await control("/dm/arrive", { to: "developer", from: "alice", text: "two" })).json()) as Json; + expect(after.deliveries[0].success).toBe(true); + expect(r.received.filter((x) => x.method === "POST")).toHaveLength(1); + }); +}); + describe("X Activity API DM deliveries", () => { async function subscribed(extra: Partial = {}) { const r = await receiver(SECRET); diff --git a/packages/@emulators/x/src/activity.ts b/packages/@emulators/x/src/activity.ts index 36c1937c1..2a18ac2ca 100644 --- a/packages/@emulators/x/src/activity.ts +++ b/packages/@emulators/x/src/activity.ts @@ -197,6 +197,24 @@ export interface PreparedDelivery { method: "POST"; headers: Record; body: string; + /** Why the emulator holds this delivery instead of sending it (it is still previewable). */ + held?: string; +} + +/** + * Why a delivery to this webhook is held, or null when it may be sent. X delivers only + * to an address whose owner answered the challenge; and an address accepted only through + * control mode's relaxation (http, or a port, on an https instance) is never called at all, + * so a public instance cannot be pointed at an arbitrary host and port. + */ +export function deliveryHold(baseUrl: string, webhook: XWebhook): string | null { + if (baseUrl.startsWith("https://") && webhookUrlProblem(webhook.url, true)) { + return "held: the address was accepted only through control mode's relaxation (http or a port), and the emulator never calls such an address"; + } + if (!webhook.crc_proven) { + return "held: no challenge has been answered for this webhook; answer it (the CRC on PUT /2/webhooks/:id, or POST /_emulate/x/webhooks/:id/challenge in control mode) before deliveries are sent"; + } + return null; } function activeSubscription(sub: XActivitySubscription, now: number): boolean { @@ -237,6 +255,7 @@ export function prepareDmDeliveries( method: "POST", headers: { "content-type": "application/json", ...signatureHeaders(client, body) }, body, + ...(deliveryHold(baseUrl, webhook) ? { held: deliveryHold(baseUrl, webhook)! } : {}), }); } } @@ -252,6 +271,8 @@ export interface DeliveryResult { status_code: number | null; success: boolean; delivery_id: number; + /** Set when the delivery was held, not sent: the reason. */ + held?: string; } export async function sendDeliveries( @@ -260,6 +281,20 @@ export async function sendDeliveries( ): Promise { const results: DeliveryResult[] = []; for (const d of deliveries) { + if (d.held) { + results.push({ + subscription_id: d.subscription_id, + webhook_id: d.webhook_id, + event_type: d.event_type, + for_user_id: d.for_user_id, + url: d.url, + status_code: null, + success: false, + delivery_id: 0, + held: d.held, + }); + continue; + } const rec: WebhookDelivery = await dispatcher.deliver({ hookRef: d.webhook_id, event: d.event_type, diff --git a/packages/@emulators/x/src/entities.ts b/packages/@emulators/x/src/entities.ts index 29e5a3346..9258b5c19 100644 --- a/packages/@emulators/x/src/entities.ts +++ b/packages/@emulators/x/src/entities.ts @@ -178,6 +178,12 @@ export interface XWebhook extends Entity { client_id: string; url: string; valid: boolean; + /** + * True once an answered challenge has proved the owner controls the address: X's + * CRC at creation or on PUT, or, in control mode, a correct answer reported at + * POST /_emulate/x/webhooks/:id/challenge. Deliveries go only to proven webhooks. + */ + crc_proven?: boolean; created_at_x: string; } diff --git a/packages/@emulators/x/src/index.ts b/packages/@emulators/x/src/index.ts index 31feacc73..6069f8cdb 100644 --- a/packages/@emulators/x/src/index.ts +++ b/packages/@emulators/x/src/index.ts @@ -156,6 +156,8 @@ export function seedFromConfig(store: Store, baseUrl: string, config: XSeedConfi client_id: w.client_id, url: w.url, valid: w.valid ?? true, + // No challenge has been answered for a seeded webhook: PUT /2/webhooks/:id proves it. + crc_proven: false, created_at_x: new Date().toISOString(), }); } diff --git a/packages/@emulators/x/src/manifest.ts b/packages/@emulators/x/src/manifest.ts index 795f62a56..bdbcaed27 100644 --- a/packages/@emulators/x/src/manifest.ts +++ b/packages/@emulators/x/src/manifest.ts @@ -40,7 +40,7 @@ export const manifest: ServiceManifest = { status: "partial", basePath: "/2/webhooks", notes: - "Webhook configs with the CRC at creation and on PUT; X Activity API subscriptions for dm.sent and dm.received, delivered as the documented envelope and signed with X-Twitter-Webhooks-Signature-OAuth2 (client secret) plus X-Twitter-Webhooks-Signature when a consumer_secret is seeded. Other XAA event types, the persistent stream, replay, filter qualifiers and the hourly CRC are not emulated. CRC delivery mode `control` (POST /_emulate/x/webhooks/crc-delivery) is an emulator mode, not X behaviour. Emulator-only relaxation: in control mode POST /2/webhooks also accepts an http address and one with a port, which X refuses, so a test can register a local receiver and preview its deliveries; DM deliveries to that address are still attempted and recorded (from a hosted instance a local address is unreachable). Outbound mode keeps X's rule: https, no port, at most 200 characters.", + "Webhook configs with the CRC at creation and on PUT; X Activity API subscriptions for dm.sent and dm.received, delivered as the documented envelope and signed with X-Twitter-Webhooks-Signature-OAuth2 (client secret) plus X-Twitter-Webhooks-Signature when a consumer_secret is seeded. Other XAA event types, the persistent stream, replay, filter qualifiers and the hourly CRC are not emulated. CRC delivery mode `control` (POST /_emulate/x/webhooks/crc-delivery) is an emulator mode, not X behaviour. Emulator-only relaxation: in control mode POST /2/webhooks also accepts an http address and one with a port, which X refuses, so a test can register a local receiver and preview its deliveries; the emulator never calls such an address, and its deliveries are held (listed as held, previewable with POST /_emulate/x/dm/preview-delivery). Outbound mode keeps X's rule: https, no port, at most 200 characters. As on X, deliveries go only to a webhook whose challenge was answered: X's CRC at creation or on PUT in outbound mode, or a correct answer at POST /_emulate/x/webhooks/:id/challenge in control mode; until then, and for a seeded webhook until PUT, they are held.", }, { id: "account-activity", diff --git a/packages/@emulators/x/src/routes/control.ts b/packages/@emulators/x/src/routes/control.ts index 10783041d..b1941e801 100644 --- a/packages/@emulators/x/src/routes/control.ts +++ b/packages/@emulators/x/src/routes/control.ts @@ -11,7 +11,7 @@ import { setCrcDeliveryMode, } from "../activity.js"; import { clearRateWindows, getRateLimitConfig, rateLimitState, setRateLimitConfig } from "../rate-limits.js"; -import { ensureOneToOne, storeAndDeliverMessage } from "./dm.js"; +import { ensureOneToOne, recordHeldDeliveries, storeAndDeliverMessage } from "./dm.js"; import type { XSeedAttachment } from "../dm-seed.js"; /** @@ -87,6 +87,7 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext): text, mediaKeys, }); + recordHeldDeliveries(c, deliveries); return c.json({ dm_event_id: view.id, dm_conversation_id: conv.conversation_id, @@ -174,7 +175,7 @@ export function controlRoutes({ app, store, baseUrl, webhooks }: RouteContext): body.response_token ?? (body.response as Record | undefined)?.response_token ?? undefined; const valid = !!client && crcAnswerValid(client, pending.crc_token, answer); xs.pendingChallenges.update(pending.id, { answered: true, valid }); - xs.webhooks.update(webhook.id, { valid }); + xs.webhooks.update(webhook.id, { valid, crc_proven: valid }); return c.json({ webhook_id: webhook.webhook_id, valid }); }); diff --git a/packages/@emulators/x/src/routes/dm.ts b/packages/@emulators/x/src/routes/dm.ts index 6633c6c5a..6ca794831 100644 --- a/packages/@emulators/x/src/routes/dm.ts +++ b/packages/@emulators/x/src/routes/dm.ts @@ -212,6 +212,19 @@ export async function storeAndDeliverMessage( return { view, deliveries }; } +/** Put each held delivery on the request's ledger entry, with the reason it was held. */ +export function recordHeldDeliveries(c: Context, deliveries: DeliveryResult[]): void { + for (const d of deliveries) { + if (!d.held) continue; + recordSideEffect(c, { + type: "custom", + collection: "x.webhook_deliveries", + id: d.webhook_id, + summary: `${d.event_type} for ${d.for_user_id} to ${d.url} ${d.held}`, + }); + } +} + /** Find or create the one-to-one conversation between two users. */ export function ensureOneToOne(store: Store, a: string, b: string): XDmConversation { const xs = getXStore(store); @@ -409,12 +422,14 @@ export function dmRoutes({ app, store, baseUrl, webhooks }: RouteContext): void text: parsed.text, mediaKeys: parsed.mediaKeys, }); + const held = deliveries.filter((d) => d.held).length; recordSideEffect(c, { type: "create", collection: "x.dm_events", id: view.id, - summary: `DM sent in ${conv.conversation_id}; ${deliveries.length} webhook deliveries`, + summary: `DM sent in ${conv.conversation_id}; ${deliveries.length - held} webhook deliveries sent, ${held} held`, }); + recordHeldDeliveries(c, deliveries); return c.json({ data: { dm_conversation_id: conv.conversation_id, dm_event_id: view.id } }, 201); } diff --git a/packages/@emulators/x/src/routes/webhooks.ts b/packages/@emulators/x/src/routes/webhooks.ts index 9232544b9..17720eb1b 100644 --- a/packages/@emulators/x/src/routes/webhooks.ts +++ b/packages/@emulators/x/src/routes/webhooks.ts @@ -104,6 +104,7 @@ export function webhookRoutes({ app, store, baseUrl }: RouteContext): void { client_id: client.client_id, url, valid: true, + crc_proven: mode === "outbound", created_at_x: new Date().toISOString(), }); if (mode === "control") holdChallenge(store, webhook); @@ -142,7 +143,7 @@ export function webhookRoutes({ app, store, baseUrl }: RouteContext): void { } const client = xs.oauthClients.findOneBy("client_id", webhook.client_id)!; const crc = await runCrc(client, webhook.url); - xs.webhooks.update(webhook.id, { valid: crc.valid }); + xs.webhooks.update(webhook.id, { valid: crc.valid, crc_proven: crc.valid }); if (!crc.valid) return webhookFailure(c, "CrcValidationFailed", crc.reason ?? "The CRC check failed."); return c.json({ data: { valid: true } }); }); diff --git a/skills/x/SKILL.md b/skills/x/SKILL.md index c18cfe0cc..123dbab11 100644 --- a/skills/x/SKILL.md +++ b/skills/x/SKILL.md @@ -48,7 +48,9 @@ When the emulator cannot reach the app under test: ```bash # Emulator mode: hold CRC challenges for the test to deliver itself. In this mode a webhook -# address may also be http or carry a port (an emulator-only relaxation of X's rule). +# address may also be http or carry a port (an emulator-only relaxation of X's rule); the emulator +# never calls such an address and holds its deliveries (preview them instead). Any webhook gets +# deliveries only after its challenge is answered. curl -X POST "$X_EMULATOR_URL/_emulate/x/webhooks/crc-delivery" -H "Content-Type: application/json" -d '{"mode":"control"}' curl "$X_EMULATOR_URL/_emulate/x/webhooks/$WEBHOOK_ID/challenge"