Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
- `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/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.

Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/docs/x/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ Creating a webhook sends `GET <url>?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.
- `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/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.

Expand Down
73 changes: 73 additions & 0 deletions packages/@emulators/x/src/__tests__/webhooks-media.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,79 @@ describe("X webhooks and the CRC", () => {
});
});

describe("webhook addresses in each CRC mode on an https instance", () => {
function httpsInstance(mode: "outbound" | "control") {
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: mode,
});
const xs = getXStore(server.store);
const token = (user: string | null) => {
const t = `tok_${randomBytes(8).toString("hex")}`;
xs.accessTokens.insert({
token: t,
client_id: "dm-app",
user_id: user,
scopes: user ? ["dm.read", "dm.write", "tweet.read", "users.read"] : [],
app_only: user === null,
expires: 0,
});
return t;
};
const post = (path: string, t: string, body: unknown) =>
server.app.request(`${host}${path}`, {
method: "POST",
headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
return { token, post };
}
const local = ["http://localhost:3000/webhooks/x", "https://app.example.test:8443/webhooks/x"];

it("keeps X's rule in outbound mode: no http address, no port", async () => {
const { token, post } = httpsInstance("outbound");
const app = token(null);
for (const url of local) {
const res = await post("/2/webhooks", app, { url });
expect(((await res.json()) as Json).errors[0].message, url).toBe("UrlValidationFailed");
}
});

it("accepts a local http address with a port in control mode, with subscriptions and previews", async () => {
const { token, post } = httpsInstance("control");
const app = token(null);
const dev = token(DEV);
const ids: string[] = [];
for (const url of local) {
const res = await post("/2/webhooks", app, { url });
expect(res.status, url).toBe(200);
ids.push(((await res.json()) as Json).data.id);
}
const sub = await post("/2/activity/subscriptions", dev, {
event_type: "dm.received",
filter: { user_id: DEV },
webhook_id: ids[0],
});
expect(sub.status).toBe(200);
const arrived = (await (
await post("/_emulate/x/dm/arrive", app, { to: "developer", from: "alice", text: "hi" })
).json()) as Json;
const preview = (await (
await post("/_emulate/x/dm/preview-delivery", app, { dm_event_id: arrived.dm_event_id, include_invalid: true })
).json()) as Json;
expect(preview.deliveries.map((d: Json) => d.url)).toEqual([local[0]]);
expect(preview.deliveries[0].headers["x-twitter-webhooks-signature-oauth2"]).toBe(
sign(SECRET, preview.deliveries[0].body),
);
});
});

describe("X Activity API DM deliveries", () => {
async function subscribed(extra: Partial<XSeedConfig> = {}) {
const r = await receiver(SECRET);
Expand Down
6 changes: 3 additions & 3 deletions packages/@emulators/x/src/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,9 @@ export async function sendDeliveries(

/**
* X's URL rules for webhooks: HTTPS, at most 200 characters, no explicit port.
* Enforced when the emulator itself is served over HTTPS (a hosted instance); a
* local instance also accepts `http://` and ports so a test can register a local
* receiver.
* Enforced when the emulator itself is served over HTTPS (a hosted instance) in
* outbound CRC mode; a local instance, or any instance in control mode, also
* accepts `http://` and ports so a test can register a local receiver.
*/
export function webhookUrlProblem(url: string, strict: boolean): string | null {
let parsed: URL;
Expand Down
4 changes: 2 additions & 2 deletions packages/@emulators/x/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
"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.",
},
{
id: "account-activity",
Expand Down Expand Up @@ -382,7 +382,7 @@ export const manifest: ServiceManifest = {
key: "webhook_crc_delivery",
title: "CRC delivery mode",
description:
"outbound (default, X's behaviour) or control: an emulator mode in which webhook creation sends no challenge and each challenge is held at GET /_emulate/x/webhooks/:id/challenge for the test to deliver.",
"outbound (default, X's behaviour) or control: an emulator mode in which webhook creation sends no challenge, each challenge is held at GET /_emulate/x/webhooks/:id/challenge for the test to deliver, and webhook addresses may be http or carry a port (an emulator-only relaxation of X's rule).",
example: "control",
},
],
Expand Down
8 changes: 6 additions & 2 deletions packages/@emulators/x/src/routes/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ const XAA_EVENT_TYPES = new Set<string>(DM_ACTIVITY_EVENT_TYPES);

export function webhookRoutes({ app, store, baseUrl }: RouteContext): void {
const xs = getXStore(store);
const strictUrls = baseUrl.startsWith("https://");
// X's https and no-port rules apply on an https instance (a hosted one), except in the
// emulator's control mode: there the challenge is held for the test rather than sent to
// the address, so a local http address with a port can be registered and subscribed to.
// An emulator-only relaxation, listed as such in the manifest.
const strictUrls = () => baseUrl.startsWith("https://") && getCrcDeliveryMode(store) === "outbound";

// POST /2/webhooks: register a webhook; X sends a CRC to it first.
app.post("/2/webhooks", async (c) => {
Expand All @@ -80,7 +84,7 @@ export function webhookRoutes({ app, store, baseUrl }: RouteContext): void {
const body = (await c.req.json().catch(() => undefined)) as Record<string, unknown> | undefined;
const url = typeof body?.url === "string" ? body.url : "";
if (!url) return invalidRequest(c, "url", "", "`url` is required.");
const urlProblem = webhookUrlProblem(url, strictUrls);
const urlProblem = webhookUrlProblem(url, strictUrls());
if (urlProblem) return webhookFailure(c, "UrlValidationFailed", urlProblem);
if (xs.webhooks.findBy("client_id", auth.token.client_id).some((w) => w.url === url)) {
return webhookFailure(
Expand Down
3 changes: 2 additions & 1 deletion skills/x/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ Register with `POST /2/webhooks` (X sends a CRC first), subscribe with `POST /2/
When the emulator cannot reach the app under test:

```bash
# Emulator mode: hold CRC challenges for the test to deliver itself.
# 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).
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"

Expand Down
Loading