Skip to content

Commit b1bc0be

Browse files
committed
Let native OAuth clients post to the token and revocation endpoints
SvelteKit's cross-site form check refused every form POST whose Origin isn't this site's, including requests with no Origin. Native OAuth clients (Claude Code and pi signing in to Syntax Lab's MCP endpoint, https://lab.syntax.fm/mcp) post forms to /api/auth/oauth2/token with no Origin, so the code exchange got 403 "Cross-site POST form submissions are forbidden" and agents couldn't sign in. Seen live on 2026-10-05 (Lab task k86p8oe0). SvelteKit's config can't exempt a path, so svelte.config.js turns its copy off (trustedOrigins ['*']) and hooks.server.ts runs the same check first, in built servers as SvelteKit did, on every path except /api/auth/oauth2/token and /api/auth/oauth2/revoke (src/lib/server/cross_site_forms.ts). Those read no cookie and only act on what the caller already holds (a code with its PKCE verifier, a refresh token, the token to revoke), so CSRF doesn't apply. Remote functions keep SvelteKit's separate cross-site check. Scott approved this change and the deploy on 2026-10-05. Tests: cross_site_forms.test.ts (exempt paths, refusals with and without Origin, every form content type, the JSON refusal, same-site posts); hooks.server.test.ts's new case against a built server: a no-Origin token or revoke form post reaches Better Auth, a no-Origin or cross-site consent form post still gets SvelteKit's 403. That case fails without this change. pnpm check, pnpm lint, and pnpm test (99 pass) pass.
1 parent ac07dd1 commit b1bc0be

5 files changed

Lines changed: 154 additions & 1 deletion

File tree

‎src/hooks.server.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,3 +523,37 @@ test('a session made on localhost still validates and signs out', async () => {
523523
assert.equal(get_cookie(reply, LOOPBACK_SESSION_COOKIE).attributes.get('max-age'), '0');
524524
assert.equal((await get_session_user_id(loopback_host, loopback_cookie)).user_id, null);
525525
});
526+
527+
test("native OAuth clients' token requests reach Better Auth, while other cross-site form posts are still refused", async () => {
528+
const form_headers = { 'content-type': 'application/x-www-form-urlencoded' };
529+
530+
// No Origin, as Claude Code and pi send it. Better Auth answers (an unknown client here),
531+
// not SvelteKit's cross-site refusal.
532+
const token = await send('/api/auth/oauth2/token', {
533+
host: loopback_host,
534+
method: 'POST',
535+
headers: form_headers,
536+
body: 'grant_type=authorization_code&code=made-up&client_id=made-up&code_verifier=made-up'
537+
});
538+
assert.notEqual(token.status, 403, token.body);
539+
assert.doesNotMatch(token.body, /Cross-site/);
540+
541+
const revoke = await send('/api/auth/oauth2/revoke', {
542+
host: loopback_host,
543+
method: 'POST',
544+
headers: form_headers,
545+
body: 'token=made-up&client_id=made-up'
546+
});
547+
assert.doesNotMatch(revoke.body, /Cross-site/);
548+
549+
for (const headers of [form_headers, { ...form_headers, origin: 'https://evil.example' }]) {
550+
const consent = await send('/api/auth/oauth2/consent', {
551+
host: loopback_host,
552+
method: 'POST',
553+
headers,
554+
body: 'accept=true'
555+
});
556+
assert.equal(consent.status, 403);
557+
assert.equal(consent.body, 'Cross-site POST form submissions are forbidden');
558+
}
559+
});

‎src/hooks.server.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { building } from '$app/environment';
1+
import { building, dev } from '$app/environment';
22
import { create_auth } from '$lib/server/auth';
3+
import { refuse_cross_site_form } from '$lib/server/cross_site_forms';
34
import { for_local_site, get_auth_environment } from '$lib/server/env';
45
import { get_local_site, local_host_refusal, name_refused_origin } from '$lib/utils/local_hosts';
56
import { svelteKitHandler } from 'better-auth/svelte-kit';
@@ -11,6 +12,13 @@ export const handle: Handle = async ({ event, resolve }) => {
1112
event.locals.user = null;
1213
event.locals.is_local_development = false;
1314

15+
// SvelteKit's own cross-site form check, run first as SvelteKit ran it (and, like it, only in
16+
// built servers), except on the endpoints native OAuth clients post to.
17+
if (!dev && !building) {
18+
const refusal = refuse_cross_site_form(event.request, event.url);
19+
if (refusal) return refusal;
20+
}
21+
1422
if (building || event.url.pathname === '/api/health') {
1523
return resolve(event);
1624
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'node:test';
3+
4+
import { refuse_cross_site_form } from './cross_site_forms';
5+
6+
const ORIGIN = 'https://auth.syntax.fm';
7+
8+
function form_post(path: string, headers: Record<string, string> = {}, method = 'POST') {
9+
const url = new URL(path, ORIGIN);
10+
const request = new Request(url, {
11+
method,
12+
headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers },
13+
body: 'grant_type=authorization_code'
14+
});
15+
return refuse_cross_site_form(request, url);
16+
}
17+
18+
test('a native client may post forms to the token and revocation endpoints with no Origin', () => {
19+
assert.equal(form_post('/api/auth/oauth2/token'), null);
20+
assert.equal(form_post('/api/auth/oauth2/revoke'), null);
21+
assert.equal(form_post('/api/auth/oauth2/token', { origin: 'https://evil.example' }), null);
22+
});
23+
24+
test('every other path still refuses a form post from another site or with no Origin, as SvelteKit did', async () => {
25+
for (const [path, headers] of [
26+
['/api/auth/oauth2/token/', {}],
27+
['/api/auth/oauth2/consent', {}],
28+
['/api/auth/sign-out', { origin: 'https://evil.example' }],
29+
['/consent', { origin: 'null' }]
30+
] as const) {
31+
const refusal = form_post(path, headers);
32+
assert.equal(refusal?.status, 403, path);
33+
assert.equal(await refusal?.text(), 'Cross-site POST form submissions are forbidden');
34+
}
35+
36+
for (const content_type of [
37+
'multipart/form-data; boundary=x',
38+
'TEXT/PLAIN',
39+
'application/x-sveltekit-formdata'
40+
]) {
41+
assert.equal(
42+
form_post('/consent', { 'content-type': content_type })?.status,
43+
403,
44+
content_type
45+
);
46+
}
47+
48+
const json_refusal = form_post('/consent', { accept: 'application/json' }, 'DELETE');
49+
assert.equal(json_refusal?.status, 403);
50+
assert.deepEqual(await json_refusal?.json(), {
51+
message: 'Cross-site DELETE form submissions are forbidden'
52+
});
53+
});
54+
55+
test('same-site form posts, other content types, and GETs go on', () => {
56+
assert.equal(form_post('/api/auth/sign-out', { origin: ORIGIN }), null);
57+
assert.equal(form_post('/consent', { 'content-type': 'application/json' }), null);
58+
59+
const url = new URL('/consent', ORIGIN);
60+
assert.equal(refuse_cross_site_form(new Request(url), url), null);
61+
});

‎src/lib/server/cross_site_forms.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// SvelteKit refuses a cross-site form post (a POST, PUT, PATCH, or DELETE with a form content
2+
// type whose Origin isn't this site's), to stop CSRF. Native OAuth clients, such as Claude Code
3+
// and pi signing in to Syntax Lab's MCP endpoint, post forms to the token and revocation endpoints
4+
// from no website, so they send no Origin and SvelteKit's check refused them with 403. Its config
5+
// can't exempt a path, so svelte.config.js turns it off and hooks.server.ts runs this same check
6+
// instead, on every path but those two. They need no CSRF protection: they read no cookie, and a
7+
// request only works with what the caller already holds (an authorization code with its PKCE
8+
// verifier, a refresh token, or the token to revoke), never with a signed-in browser's session.
9+
10+
// RFC 6749's token endpoint and RFC 7009's revocation endpoint, as Better Auth's OAuth provider
11+
// serves them (see /.well-known/oauth-authorization-server).
12+
const NATIVE_CLIENT_FORM_PATHS = new Set(['/api/auth/oauth2/token', '/api/auth/oauth2/revoke']);
13+
14+
// The content types SvelteKit treats as form submissions (@sveltejs/kit src/utils/http.js).
15+
const FORM_CONTENT_TYPES = new Set([
16+
'application/x-www-form-urlencoded',
17+
'multipart/form-data',
18+
'text/plain',
19+
'application/x-sveltekit-formdata'
20+
]);
21+
22+
const CHECKED_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
23+
24+
function is_form_content_type(request: Request): boolean {
25+
const content_type = request.headers.get('content-type')?.split(';', 1)[0].trim() ?? '';
26+
return FORM_CONTENT_TYPES.has(content_type.toLowerCase());
27+
}
28+
29+
/**
30+
* SvelteKit's refusal of a cross-site form submission, with its status and message, or null when
31+
* the request may go on. A form post to the token or revocation endpoint always goes on.
32+
*/
33+
export function refuse_cross_site_form(request: Request, url: URL): Response | null {
34+
if (NATIVE_CLIENT_FORM_PATHS.has(url.pathname)) return null;
35+
if (!CHECKED_METHODS.has(request.method) || !is_form_content_type(request)) return null;
36+
if (request.headers.get('origin') === url.origin) return null;
37+
38+
const message = `Cross-site ${request.method} form submissions are forbidden`;
39+
40+
return request.headers.get('accept') === 'application/json'
41+
? Response.json({ message }, { status: 403 })
42+
: new Response(message, {
43+
status: 403,
44+
headers: { 'content-type': 'text/plain;charset=UTF-8' }
45+
});
46+
}

‎svelte.config.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
55
const config = {
66
preprocess: vitePreprocess(),
77
kit: {
8+
// SvelteKit's cross-site form check can't exempt a path, and it refused native OAuth
9+
// clients' token requests. hooks.server.ts runs the same check on every other path
10+
// (src/lib/server/cross_site_forms.ts), so this turns off only SvelteKit's copy.
11+
csrf: { trustedOrigins: ['*'] },
812
adapter: adapter({
913
// `vite dev` reads the committed `local` Wrangler env; deploys use the top-level config.
1014
platformProxy: { environment: 'local' }

0 commit comments

Comments
 (0)