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
8 changes: 7 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions src/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -152,6 +167,8 @@ export function handleConnectRequest(
authenticate: Authenticate,
): (request: Request) => Promise<Response> {
return async (request: Request): Promise<Response> => {
if (!isJson(request)) return json(NOT_JSON, 415);

const customerId = await authenticate(request);
if (!customerId) return json({ error: "Unauthorized" }, 401);

Expand Down Expand Up @@ -181,6 +198,7 @@ export function handlePreviewRequest(
authenticate: Authenticate,
): (request: Request) => Promise<Response> {
return async (request: Request): Promise<Response> => {
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 };
Expand Down
50 changes: 47 additions & 3 deletions tests/connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Loading