diff --git a/AGENTS.md b/AGENTS.md index 62a471d..d2c7637 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,11 +18,17 @@ Koa), drop `handleConnectRequest` and call `redeemLinkToken(token, customerId)` from a handler written in that framework's own style. `redeemLinkToken` is the part that matters; the wrapper is convenience. -Two things this endpoint must not do, because they are the whole security model: +Three things this endpoint must not do, because they are the whole security model: - Do not accept a `customerId` from the request body. The server decides who the caller is; a body-supplied id lets anyone link a chat account to anyone - Do not expose the endpoint unauthenticated +- Do not accept a body that is not `Content-Type: application/json`. Refuse it + with 415 before reading the session. Parsing whatever arrives is not enough: + a `text/plain` form on another site can send a body that parses as JSON, and + would redeem its own token as whoever is signed in here. The handlers do this; + a handler you write in your framework's own style has to as well, and so does + your preview route Mount `handlePreviewRequest` at `POST /connect/preview`. The page calls it first so it can name the chat account before anyone clicks Connect. diff --git a/README.md b/README.md index a6cfdfb..7233a7d 100644 --- a/README.md +++ b/README.md @@ -73,10 +73,13 @@ That is what `preview` is for. **Take a JSON body, not a form post.** An HTML form can only send urlencoded, multipart, or plain text bodies, so a server that requires `application/json` -cannot be driven by a form on someone else's site. Combined with a `SameSite=Lax` -session cookie, that is what stops another origin redeeming a link as whoever is -signed in — no CSRF token needed. If you change `/connect` to accept a form -post, add one. +cannot be driven by a form on someone else's site. *Requires* means checking +the `Content-Type` header, not just parsing the body: a `text/plain` form can +send `{"token":"…","x":"="}`, which parses as JSON fine. Both handlers refuse +anything else with 415 before they read the session. Combined with a +`SameSite=Lax` session cookie, that is what stops another origin redeeming a +link as whoever is signed in — no CSRF token needed. If you change `/connect` to +accept a form post, add one. ## Running the checks diff --git a/src/connect.ts b/src/connect.ts index 35d3697..dfb0faf 100644 --- a/src/connect.ts +++ b/src/connect.ts @@ -143,6 +143,21 @@ const json = (body: unknown, status: number): Response => headers: { "Content-Type": "application/json" }, }); +/** + * Whether a request says its body is JSON. + * + * Checked before anything else, and the reason is CSRF. An HTML form can only + * send urlencoded, multipart, or plain text, but a `text/plain` form can carry + * a body that parses as JSON perfectly well — `{"token":"…","x":"="}` — so + * parsing whatever arrives would let a page on another site redeem *its own* + * token as whoever is signed in here, with their cookies, and never show them + * the preview. Requiring the header is what a form cannot do. + */ +const isJson = (request: Request): boolean => + request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() === "application/json"; + +const NOT_JSON = { error: "Send the token as JSON, with Content-Type: application/json" }; + /** * Builds the route handler. * @param authenticate Your own session check, returning the customer id. @@ -152,6 +167,8 @@ export function handleConnectRequest( authenticate: Authenticate, ): (request: Request) => Promise { return async (request: Request): Promise => { + if (!isJson(request)) return json(NOT_JSON, 415); + const customerId = await authenticate(request); if (!customerId) return json({ error: "Unauthorized" }, 401); @@ -181,6 +198,7 @@ export function handlePreviewRequest( authenticate: Authenticate, ): (request: Request) => Promise { return async (request: Request): Promise => { + if (!isJson(request)) return json(NOT_JSON, 415); if (!(await authenticate(request))) return json({ error: "Unauthorized" }, 401); const body = (await request.json().catch(() => ({}))) as { token?: string }; diff --git a/tests/connect.test.ts b/tests/connect.test.ts index 896aaa5..9191511 100644 --- a/tests/connect.test.ts +++ b/tests/connect.test.ts @@ -29,13 +29,17 @@ const DESCRIPTION = { expiresAt: "2026-01-01T00:10:00.000Z", }; -const post = (body: unknown): Request => +const post = (body: unknown, contentType = "application/json"): Request => new Request("https://example.com/connect", { method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(body), + headers: { "Content-Type": contentType }, + body: typeof body === "string" ? body : JSON.stringify(body), }); +// All a cross-site form can send. `text/plain` carries JSON as well as any, +// which is how a form on another site would redeem its own token here. +const FORM_TYPES = ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data"]; + beforeEach(() => { process.env.AGENTA_API_URL = "https://app.buildagenta.com/api/v1"; process.env.AGENTA_API_KEY = "agenta_test"; @@ -109,6 +113,32 @@ describe("handleConnectRequest", () => { expect((await handler(post({}))).status).toBe(400); }); + test.each(FORM_TYPES)("refuses a %s post before asking who is signed in", async (type) => { + let reached = false; + globalThis.fetch = (async () => { + reached = true; + return new Response(null, { status: 200 }); + }) as unknown as typeof fetch; + let authenticated = false; + const handler = handleConnectRequest(async () => { + authenticated = true; + return "customer-1"; + }); + + const response = await handler(post(JSON.stringify({ token: "attacker-token" }), type)); + + expect(response.status).toBe(415); + expect(authenticated).toBe(false); + expect(reached).toBe(false); + }); + + test("accepts JSON with a charset", async () => { + respondWith(200); + const handler = handleConnectRequest(authenticated); + const response = await handler(post({ token: "token" }, "application/json; charset=utf-8")); + expect(response.status).toBe(200); + }); + test("answers 200 once the link is made", async () => { respondWith(200); const handler = handleConnectRequest(authenticated); @@ -173,6 +203,20 @@ describe("handlePreviewRequest", () => { expect((await handler(post({}))).status).toBe(400); }); + test.each(FORM_TYPES)("refuses a %s post", async (type) => { + let reached = false; + globalThis.fetch = (async () => { + reached = true; + return new Response(null, { status: 200 }); + }) as unknown as typeof fetch; + const handler = handlePreviewRequest(authenticated); + + const response = await handler(post(JSON.stringify({ token: "token" }), type)); + + expect(response.status).toBe(415); + expect(reached).toBe(false); + }); + test("answers the description, and never the API key that fetched it", async () => { respondWith(200, DESCRIPTION); const handler = handlePreviewRequest(authenticated);