Skip to content

Commit 4b3e1fd

Browse files
committed
feat(plugin-auth): the hand-off carries only a session signed in within five minutes, and refuses a cross-site navigation
Claude-Session: https://claude.ai/code/session_01JQwxbZkE4E6sE72j23Afwx Co-authored-by: Claude <noreply@anthropic.com>
1 parent 34edeb9 commit 4b3e1fd

3 files changed

Lines changed: 116 additions & 10 deletions

File tree

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4020,18 +4020,21 @@ export class AuthPlugin implements Plugin {
40204020
// the app redeems at better-auth's own `/one-time-token/verify`, bound to
40214021
// the shell's PKCE challenge so an intercepted callback cannot be
40224022
// redeemed. Mounted unconditionally: with no registered scheme every
4023-
// target is refused with a 400 that says how to register one. Session
4024-
// required; the reasons for every refusal live in
4023+
// target is refused with a 400 that says how to register one. A session
4024+
// signed in within the last five minutes is required, and a cross-site
4025+
// navigation is refused (ruling A); the reasons for every refusal live in
40254026
// `one-time-token-handoff.ts`. Ledgered in auth-route-ledger.ts.
40264027
rawApp.get(`${basePath}/one-time-token/handoff`, async (c: any) => {
40274028
try {
40284029
const manager = this.authManager!;
40294030
const answer = await runOneTimeTokenHandoff(
40304031
{
40314032
registeredSchemes: manager.getRegisteredAppSchemes(),
4032-
hasSession: async (headers) => {
4033+
sessionCreatedAt: async (headers) => {
40334034
const api: any = await manager.getApi();
4034-
return Boolean(await api.getSession({ headers }));
4035+
const live = await api.getSession({ headers });
4036+
const createdAt = live?.session?.createdAt;
4037+
return createdAt ? new Date(createdAt) : null;
40354038
},
40364039
generate: async (headers) => {
40374040
const api: any = await manager.getApi();

‎packages/plugins/plugin-auth/src/one-time-token-handoff.test.ts‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { memoizeScrypt } from './__tests__/scrypt-memo.testkit';
2727
import {
2828
NEVER_APP_SCHEMES,
2929
ONE_TIME_TOKEN_EXPIRES_IN_MINUTES,
30+
ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS,
3031
ONE_TIME_TOKEN_GENERATE_PATH,
3132
ONE_TIME_TOKEN_HANDOFF_PATH,
3233
ONE_TIME_TOKEN_VERIFY_PATH,
@@ -108,9 +109,9 @@ const arrange = async (trustedAppSchemes?: string[]) => {
108109
};
109110

110111
/** GET the hand-off through the Hono app, as the system browser does. */
111-
const handoff = (cookie: string | undefined, query: Record<string, string>) =>
112+
const handoff = (cookie: string | undefined, query: Record<string, string>, extra: Record<string, string> = {}) =>
112113
app.request(`${ORIGIN}${BASE}${ONE_TIME_TOKEN_HANDOFF_PATH}?${new URLSearchParams(query)}`, {
113-
headers: cookie ? { cookie } : {},
114+
headers: { ...(cookie ? { cookie } : {}), ...extra },
114115
});
115116

116117
/** Hand off and return the token the app callback received. */
@@ -259,9 +260,53 @@ describe('one-time-token hand-off — the redirect goes to a registered app sche
259260
});
260261
});
261262

263+
describe('one-time-token hand-off — only a fresh sign-in, opened by the app itself (ruling A)', () => {
264+
const query = { redirect_uri: CALLBACK, code_challenge: s256Challenge(VERIFIER) };
265+
266+
it(`refuses a session older than ${ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS} seconds with 401 and mints nothing`, async () => {
267+
const { engine, signIn, handoff } = await arrange();
268+
const cookie = await signIn();
269+
const before = verificationRows(engine).length;
270+
vi.useFakeTimers({ toFake: ['Date'], now: Date.now() + ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS * 1000 + 1_000 });
271+
const res = await handoff(cookie, query);
272+
expect(res.status).toBe(401);
273+
expect(((await res.json()) as any).error.code).toBe('UNAUTHENTICATED');
274+
expect(res.headers.get('location')).toBeNull();
275+
expect(verificationRows(engine).length).toBe(before);
276+
});
277+
278+
it('still hands off a session inside the window', async () => {
279+
const { signIn, handoff } = await arrange();
280+
const cookie = await signIn();
281+
vi.useFakeTimers({ toFake: ['Date'], now: Date.now() + ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS * 1000 - 5_000 });
282+
expect((await handoff(cookie, query)).status).toBe(302);
283+
});
284+
285+
it('refuses a cross-site navigation with 400 and mints nothing', async () => {
286+
const { engine, signIn, handoff } = await arrange();
287+
const cookie = await signIn();
288+
const before = verificationRows(engine).length;
289+
const res = await handoff(cookie, query, { 'sec-fetch-site': 'cross-site' });
290+
expect(res.status).toBe(400);
291+
expect(((await res.json()) as any).error.code).toBe('VALIDATION_ERROR');
292+
expect(res.headers.get('location')).toBeNull();
293+
expect(verificationRows(engine).length).toBe(before);
294+
});
295+
296+
it.each([['none'], ['same-origin'], ['same-site']])('hands off when Sec-Fetch-Site is %s', async (site) => {
297+
const { signIn, handoff } = await arrange();
298+
expect((await handoff(await signIn(), query, { 'sec-fetch-site': site })).status).toBe(302);
299+
});
300+
301+
it('does not refuse a request that carries no Sec-Fetch-Site at all', async () => {
302+
const { signIn, handoff } = await arrange();
303+
expect((await handoff(await signIn(), query)).status).toBe(302);
304+
});
305+
});
306+
262307
describe('one-time-token hand-off — the request is validated before anything is minted', () => {
263308
const generate = vi.fn(async () => ({ token: 'never' }));
264-
const deps = { registeredSchemes: [APP_SCHEME], hasSession: async () => true, generate };
309+
const deps = { registeredSchemes: [APP_SCHEME], sessionCreatedAt: async () => new Date(), generate };
265310
const ask = (queries: Record<string, string[]>) => runOneTimeTokenHandoff(deps, { queries, headers: new Headers() });
266311
const challenge = s256Challenge(VERIFIER);
267312

‎packages/plugins/plugin-auth/src/one-time-token-handoff.ts‎

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,24 @@
5151
* consumes nothing: the real holder still redeems afterwards. The verifier
5252
* never leaves the device (only its hash travels, in step 2).
5353
*
54+
* ## Who can open it (maintainer ruling A, card comment 6597001931)
55+
*
56+
* The binding stops a callback being redeemed by an app that intercepts it.
57+
* It does not stop an app or a web page from OPENING the hand-off itself,
58+
* with its own challenge, in a browser that already holds the user's session.
59+
* Two refusals close that:
60+
*
61+
* - **Freshness.** The session must have been created within
62+
* {@link ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS}; an older one
63+
* answers `401 UNAUTHENTICATED` (the remedy is a sign-in, the same remedy
64+
* as no session). So the shell completes a full sign-in in the system auth
65+
* session before every hand-off (an ephemeral session is fine); an existing
66+
* Safari or Custom Tabs session is not enough.
67+
* - **Cross-site navigation.** A request carrying `Sec-Fetch-Site:
68+
* cross-site` answers `400 VALIDATION_ERROR` before anything else is read:
69+
* a malformed request context, not a missing sign-in. The header is judged
70+
* only when present.
71+
*
5472
* Generation happens only inside this route ({@link withHandoffChallenge}):
5573
* the plugin's generate endpoint refuses every HTTP request
5674
* (`disableClientRequest`), and a server-side call made outside this route's
@@ -94,6 +112,17 @@ export const ONE_TIME_TOKEN_GENERATE_PATH = '/one-time-token/generate';
94112
*/
95113
export const ONE_TIME_TOKEN_EXPIRES_IN_MINUTES = 1;
96114

115+
/**
116+
* How old the caller's session may be, in SECONDS, for the hand-off to carry
117+
* it (maintainer ruling A on the residual risk this PR raised, card comment
118+
* 6597001931). The hand-off hands over a session the shell has just watched
119+
* the user create in the system auth session; a session older than this was
120+
* made for something else, and a page or app that opens the hand-off against
121+
* it would carry it off silently. Five minutes covers a sign-in with a slow
122+
* second factor.
123+
*/
124+
export const ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS = 5 * 60;
125+
97126
/** The route's CLOSED query-parameter set. */
98127
export const ONE_TIME_TOKEN_HANDOFF_QUERY_PARAMS: readonly string[] = [
99128
'redirect_uri',
@@ -228,8 +257,14 @@ export interface HandoffAnswer {
228257
export interface HandoffDeps {
229258
/** The registered app schemes ({@link registeredAppSchemesOf}). */
230259
registeredSchemes: readonly string[];
231-
/** Whether `headers` carry a live session. */
232-
hasSession(headers: Headers): Promise<boolean>;
260+
/**
261+
* When the live session `headers` carry was created, or `null` when they
262+
* carry none: the vendor session's `session.createdAt` (`sys_session.created_at`),
263+
* which a refresh or a bearer replay never moves (those move `updatedAt`).
264+
*/
265+
sessionCreatedAt(headers: Headers): Promise<Date | null>;
266+
/** The clock, for the freshness window; `Date.now` by default. */
267+
now?: () => number;
233268
/** The vendor plugin's generate endpoint, called server-side with the caller's headers. */
234269
generate(headers: Headers): Promise<{ token: string }>;
235270
}
@@ -256,6 +291,19 @@ function single(queries: Record<string, readonly string[]>, name: string): { val
256291

257292
/** `GET /api/v1/auth/one-time-token/handoff` — see the module docblock. */
258293
export async function runOneTimeTokenHandoff(deps: HandoffDeps, request: HandoffRequest): Promise<HandoffAnswer> {
294+
// A navigation another site started (a link, a form, a script) arrives with
295+
// `Sec-Fetch-Site: cross-site` and the session cookie, since `SameSite=Lax`
296+
// sends it on a top-level GET. The shell opens the hand-off itself, which a
297+
// browser reports as `none`. Judged only when the header is present: a
298+
// browser that sends none is not refused for its absence (ruling A).
299+
if (request.headers.get('sec-fetch-site')?.trim().toLowerCase() === 'cross-site') {
300+
return refusal(
301+
400,
302+
'VALIDATION_ERROR',
303+
'The sign-in hand-off cannot be opened from another site: the app opens it in its own system auth session.',
304+
);
305+
}
306+
259307
const unknown = unknownQueryParamRefusalMessage(request.queries, ONE_TIME_TOKEN_HANDOFF_QUERY_PARAMS);
260308
if (unknown !== undefined) return refusal(400, 'VALIDATION_ERROR', unknown);
261309

@@ -296,9 +344,19 @@ export async function runOneTimeTokenHandoff(deps: HandoffDeps, request: Handoff
296344
return refusal(400, 'VALIDATION_ERROR', 'The "code_challenge_method" query parameter accepts only "S256".');
297345
}
298346

299-
if (!(await deps.hasSession(request.headers))) {
347+
const createdAt = await deps.sessionCreatedAt(request.headers);
348+
if (!createdAt) {
300349
return refusal(401, 'UNAUTHENTICATED', 'Sign in first: the hand-off carries the signed-in session of this browser to the app.');
301350
}
351+
const ageMs = (deps.now ?? Date.now)() - createdAt.getTime();
352+
if (!(ageMs <= ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS * 1000)) {
353+
return refusal(
354+
401,
355+
'UNAUTHENTICATED',
356+
`Sign in again: the hand-off carries only a session signed in within the last ${ONE_TIME_TOKEN_HANDOFF_SESSION_MAX_AGE_SECONDS / 60} minutes, ` +
357+
'so the app completes a sign-in in its system auth session before every hand-off.',
358+
);
359+
}
302360

303361
const { token } = await withHandoffChallenge(challenge.value, () => deps.generate(request.headers));
304362
target.searchParams.set('token', token);

0 commit comments

Comments
 (0)