From 4c7eda76f0da613e2c1e3389204b8a145e01983f Mon Sep 17 00:00:00 2001 From: karthic Date: Sat, 14 Nov 2026 11:12:12 +0530 Subject: [PATCH 1/2] Send cookies set by getAuth(c).api calls with the response. Cookies that Better Auth endpoints set when called through getAuth(c).api in route handlers, loaders and actions were dropped; only the session lookup's cookies reached the browser. With the cookie cache on, a renamed user kept the old name and a signed-out user stayed signed in until the cache expired. The middleware's Better Auth instance now gets an internal plugin that collects those cookies. They are merged with the session lookup's cookies so the browser receives the latest cookie for each name, domain and path. A cookie the route sent itself keeps its place, and an /api/auth response is no longer overridden by the lookup's refresh. Cookies are not sent on an unsafe request from an origin Better Auth does not trust. Closes #829. Co-Authored-By: Claude Opus 5.5 --- docs/guide/auth.md | 2 + docs/reference/api/auth.md | 2 + .../void/src/runtime/better-auth-shared.ts | 173 ++- .../auth-forwarded-cookies.test.ts | 1045 +++++++++++++++++ .../void/test/unit/auth-middleware.test.ts | 65 + 5 files changed, 1267 insertions(+), 20 deletions(-) create mode 100644 packages/void/test/integration/auth-forwarded-cookies.test.ts diff --git a/docs/guide/auth.md b/docs/guide/auth.md index 090042ea2..ef08f1fd2 100644 --- a/docs/guide/auth.md +++ b/docs/guide/auth.md @@ -130,6 +130,8 @@ import { getSession, getUser, requireAuth } from 'void/auth'; - `requireAuth(c, { throwRedirect: '/login' })` returns the user or throws a login redirect - [`getAuth(c)`](../reference/api/auth.md#getauth-c) returns the request's Better Auth instance, with plugin APIs inferred from `auth.ts`, for use with Better Auth helpers. +Cookies set by `getAuth(c).api` calls are sent with the response, so the browser picks up changes such as a renamed user or a sign-out on its next request. An endpoint that signs someone in, like `signUpEmail`, signs the current browser in as that user; to create accounts for other people, use the admin plugin's `createUser`. `getUser()` and `getSession()` still return the user from the start of the request, so redirect after an action that changes the signed-in user to render the new data. + Import `AuthUser` and `AuthSession` from `void/auth` for type annotations. They include the fields your Better Auth plugins and `user.additionalFields` add, such as `role` from `admin()`. See their fields in the [API reference](../reference/api/auth.md#authuser). ## Querying Authentication Tables diff --git a/docs/reference/api/auth.md b/docs/reference/api/auth.md index ac1471324..991ed9f26 100644 --- a/docs/reference/api/auth.md +++ b/docs/reference/api/auth.md @@ -71,6 +71,8 @@ export const GET = defineHandler((c) => getAuth(c).handler(c.req.raw)); Enable [authentication](../../guide/auth.md) before calling this helper; it throws if no instance is available. Anonymous requests can use it too. Call `requireAuth(c)` separately to require a signed-in user. +Cookies set by `getAuth(c).api` calls are sent with the response, so endpoints such as `signInEmail` and `signUpEmail` sign in the current browser. They are not sent on a `POST` from another origin unless it is in `trustedOrigins`. See [server usage](../../guide/auth.md#server-usage). + **Signature:** ```ts diff --git a/packages/void/src/runtime/better-auth-shared.ts b/packages/void/src/runtime/better-auth-shared.ts index ae9e034dd..35161ac0d 100644 --- a/packages/void/src/runtime/better-auth-shared.ts +++ b/packages/void/src/runtime/better-auth-shared.ts @@ -1,5 +1,6 @@ import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto'; -import { betterAuth, type BetterAuthOptions } from 'better-auth'; +import { betterAuth, type BetterAuthOptions, type BetterAuthPlugin } from 'better-auth'; +import { createAuthMiddleware } from 'better-auth/api'; import type { Context } from 'hono'; import type { VoidAuthMigrationSchema } from '../auth/drizzle.ts'; import { @@ -367,8 +368,7 @@ function setsAuthCookie( } } return headers.getSetCookie().some((value) => { - const equals = value.indexOf('='); - let name = (equals === -1 ? value : value.slice(0, equals)).trim(); + let name = cookieName(value); for (const secure of ['__Secure-', '__Host-']) { if (name.startsWith(secure)) { name = name.slice(secure.length); @@ -448,6 +448,102 @@ function resolveUserConfig( return mergeEmailAndPasswordDefaults({ ...defaults, ...userConfig }); } +/** + * Collects cookies that `auth.api.*` calls set while a request runs. Router + * calls (`auth.handler`) return their cookies on their own response. Better + * Auth runs plugin `after` hooks in array order, so the plugin goes last to + * see cookies set by earlier hooks. + */ +function createCookieForwarder(): { + plugin: BetterAuthPlugin; + start(): void; + cookies(): Array; +} { + let collecting = false; + const cookies: Array = []; + const plugin: BetterAuthPlugin = { + id: 'void-cookies', + hooks: { + after: [ + { + matcher: (ctx) => collecting && !('_flag' in ctx && ctx._flag === 'router'), + handler: createAuthMiddleware(async (ctx) => { + const headers = ctx.context.responseHeaders; + if (headers instanceof Headers) { + cookies.push(...headers.getSetCookie()); + } + }), + }, + ], + }, + }; + return { + plugin, + start() { + collecting = true; + }, + cookies: () => cookies, + }; +} + +function cookieName(cookie: string): string { + const pair = cookie.split(';', 1)[0] ?? ''; + const equals = pair.indexOf('='); + return (equals === -1 ? pair : pair.slice(0, equals)).trim(); +} + +// A browser stores one cookie per name, domain and path. Domains ignore case +// and a leading dot; paths are case-sensitive. +function cookieKey(cookie: string): string { + let domain = ''; + let path = ''; + for (const attribute of cookie.split(';').slice(1)) { + const equals = attribute.indexOf('='); + const name = (equals === -1 ? attribute : attribute.slice(0, equals)).trim().toLowerCase(); + const value = equals === -1 ? '' : attribute.slice(equals + 1).trim(); + if (name === 'domain') { + domain = value.replace(/^\./, '').toLowerCase(); + } else if (name === 'path') { + path = value; + } + } + return `${cookieName(cookie)};${domain};${path}`; +} + +/** + * The session lookup's headers with only the cookies the browser should still + * receive: the last one for each key. The lookup runs first, then the + * `auth.api.*` calls in order. A cookie the route sent itself, such as an + * `asResponse` result, keeps its place among those calls when it came from + * one; otherwise, as with an `/api/auth` response, it is the latest. + */ +function mergeAuthCookies( + lookup: Headers | undefined, + forwarded: Array, + sent: Array, +): Headers | undefined { + if (forwarded.length === 0 && !lookup?.has('set-cookie')) { + return lookup; + } + // `at` is the position among the `auth.api.*` calls, and -1 for the lookup. + const latest = new Map(); + for (const cookie of lookup?.getSetCookie() ?? []) { + latest.set(cookieKey(cookie), { cookie, at: -1 }); + } + forwarded.forEach((cookie, at) => latest.set(cookieKey(cookie), { cookie, at })); + const sentByKey = new Map(sent.map((cookie) => [cookieKey(cookie), cookie])); + const headers = new Headers(lookup); + headers.delete('set-cookie'); + for (const [key, { cookie, at }] of latest) { + const routeCookie = sentByKey.get(key); + const sentAt = routeCookie === undefined ? -1 : forwarded.lastIndexOf(routeCookie); + if (routeCookie === undefined || (sentAt !== -1 && at > sentAt)) { + headers.append('set-cookie', cookie); + } + } + return headers; +} + const SESSION_SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']); // An http page never counts for an https request. An https page counts for an @@ -478,21 +574,39 @@ async function sessionHeaders( auth: ReturnType, ): Promise { const headers = request.headers; - if (!headers.has('cookie')) { + if (!headers.has('cookie') || (await isTrustedRequestOrigin(request, auth))) { return headers; } + + const withoutCookie = new Headers(headers); + withoutCookie.delete('cookie'); + console.warn( + `auth: Ignored the session cookie on a ${request.method} request from ${headers.get('origin')}. Add this origin to auth trustedOrigins if it should use the signed-in session.`, + ); + return withoutCookie; +} + +/** + * True when the request may use and change the signed-in session: a safe + * method, or a request from its own origin or one Better Auth trusts. + */ +async function isTrustedRequestOrigin( + request: Request, + auth: ReturnType, +): Promise { + const headers = request.headers; if ( SESSION_SAFE_METHODS.has(request.method) && headers.get('upgrade')?.toLowerCase() !== 'websocket' ) { - return headers; + return true; } const origin = headers.get('origin'); if (!origin || isRequestOrigin(origin, request.url)) { - return headers; + return true; } if (origin === 'null' && headers.get('sec-fetch-site') === 'same-origin') { - return headers; + return true; } // Better Auth skips its origin check when CSRF checks are off, and treats @@ -502,12 +616,12 @@ async function sessionHeaders( advanced?.disableCSRFCheck === true || (advanced?.disableOriginCheck === true && advanced.disableCSRFCheck === undefined) ) { - return headers; + return true; } const context = await auth.$context; if (context.isTrustedOrigin(origin, { allowRelativePaths: false })) { - return headers; + return true; } // The function form is evaluated per request by Better Auth, while the // context list was built once without a request. `isTrustedOrigin` matches @@ -522,16 +636,11 @@ async function sessionHeaders( allowRelativePaths: false, }) ) { - return headers; + return true; } } - const withoutCookie = new Headers(headers); - withoutCookie.delete('cookie'); - console.warn( - `auth: Ignored the session cookie on a ${request.method} request from ${origin}. Add this origin to auth trustedOrigins if it should use the signed-in session.`, - ); - return withoutCookie; + return false; } const LOOPBACK_IP = /^(127\.|::1$|::ffff:127\.)/; @@ -616,8 +725,16 @@ export function createVoidAuthRuntime( env: VoidAuthEnv, runtime: VoidAuthRuntimeOptions, database: AuthDatabase, + plugins: Array = [], ): Promise> { - return betterAuth(await resolveVoidAuthOptions(request, env, runtime, database)); + const options = await resolveVoidAuthOptions(request, env, runtime, database); + if (plugins.length === 0) { + return betterAuth(options); + } + return betterAuth({ + ...options, + plugins: [...(options.plugins ?? []), ...plugins], + }); } async function resolveVoidAuthState( @@ -651,7 +768,10 @@ export function createVoidAuthRuntime( return next(); } - const auth = await createVoidAuth(c.req.raw, c.env as VoidAuthEnv, runtime, database); + const forwarder = createCookieForwarder(); + const auth = await createVoidAuth(c.req.raw, c.env as VoidAuthEnv, runtime, database, [ + forwarder.plugin, + ]); c.set('__voidAuth', auth); const result = await auth.api.getSession({ @@ -669,19 +789,32 @@ export function createVoidAuthRuntime( authDependentRequests.add(c.req.raw); } + // The session lookup's own cookies are already in `result.headers`. + forwarder.start(); await authContext.run({ user: state?.user ?? null, state }, async () => { await next(); }); + // `auth.api.*` calls skip Better Auth's origin check, so a cross-site form + // post must not sign the browser in or out through an app route. + let forwarded = forwarder.cookies(); + if (forwarded.length > 0 && !(await isTrustedRequestOrigin(c.req.raw, auth))) { + console.warn( + `auth: Did not send cookies set by auth.api calls on a ${c.req.method} request from ${c.req.header('origin')}. Add this origin to auth trustedOrigins if it should change the session.`, + ); + forwarded = []; + } + const headers = mergeAuthCookies(result.headers, forwarded, c.res.headers.getSetCookie()); + const credentialed = ['cookie', 'authorization', 'cf-access-jwt-assertion'].some((header) => c.req.raw.headers.has(header), ); appendAuthHeaders( c, - result.headers, + headers, state !== null || credentialed || - result.headers?.has('set-cookie') === true || + headers?.has('set-cookie') === true || setsAuthCookie(c.res.headers, auth.options.advanced) || authEndpoint, isUnchangedStaticAsset(c), diff --git a/packages/void/test/integration/auth-forwarded-cookies.test.ts b/packages/void/test/integration/auth-forwarded-cookies.test.ts new file mode 100644 index 000000000..154a41056 --- /dev/null +++ b/packages/void/test/integration/auth-forwarded-cookies.test.ts @@ -0,0 +1,1045 @@ +import type { BetterAuthOptions, BetterAuthPlugin } from 'better-auth'; +import { memoryAdapter } from 'better-auth/adapters/memory'; +import { APIError, createAuthMiddleware } from 'better-auth/api'; +import { getCookieCache } from 'better-auth/cookies'; +import { Hono } from 'hono'; +import { describe, expect, it, vi } from 'vite-plus/test'; +import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; +import { getAuth, getSession, getUser, type VoidAuthConfig } from '../../src/runtime/auth.ts'; +import { + createVoidAuthRuntime, + type VoidAuthRuntimeOptions, +} from '../../src/runtime/better-auth-shared.ts'; +import { createPageMutationHandler } from '../../src/runtime/routing-pages.ts'; +import { createRoutingRuntime, type RoutingContext } from '../../src/runtime/routing.ts'; + +const env = { BETTER_AUTH_SECRET: 'local-test-secret-with-at-least-32-characters' }; +const origin = 'https://app.test'; +const email = 'cookies@example.test'; +const password = 'correct-horse-battery-staple'; +const cdnHeaders = ['cdn-cache-control', 'cloudflare-cdn-cache-control', 'surrogate-control']; +const cookieCache = { session: { cookieCache: { enabled: true, maxAge: 60 } } }; + +/** A browser cookie store: later cookies replace earlier ones, Max-Age=0 removes one. */ +class CookieJar { + readonly cookies = new Map(); + + apply(response: Response): this { + for (const cookie of response.headers.getSetCookie()) { + const [pair = '', ...attributes] = cookie.split(';'); + const name = cookieName(cookie); + const value = pair.slice(pair.indexOf('=') + 1).trim(); + if ( + value === '' || + attributes.some((attribute) => /^\s*max-age\s*=\s*0\s*$/i.test(attribute)) + ) { + this.cookies.delete(name); + } else { + this.cookies.set(name, value); + } + } + return this; + } + + clone(): CookieJar { + const jar = new CookieJar(); + for (const [name, value] of this.cookies) { + jar.cookies.set(name, value); + } + return jar; + } + + without(suffix: string): CookieJar { + const jar = this.clone(); + for (const name of jar.cookies.keys()) { + if (name.endsWith(`better-auth.${suffix}`)) { + jar.cookies.delete(name); + } + } + return jar; + } + + header(): string { + return Array.from(this.cookies, ([name, value]) => `${name}=${value}`).join('; '); + } +} + +function cookieName(cookie: string): string { + return cookie.slice(0, cookie.indexOf('=')).trim(); +} + +/** Better Auth cookies with this name suffix (it adds `__Secure-` on https). */ +function authCookies(response: Response, suffix: string): Array { + return response.headers + .getSetCookie() + .filter((cookie) => cookieName(cookie).endsWith(`better-auth.${suffix}`)); +} + +/** The user inside a session cache cookie. */ +function cachedUser(cookie: string): { name: string; image?: string | null } { + const value = decodeURIComponent(cookie.slice(cookie.indexOf('=') + 1).split(';')[0]!); + const cache = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as { + session: { user: { name: string; image?: string | null } }; + }; + return cache.session.user; +} + +function cachedName(cookie: string): string { + return cachedUser(cookie).name; +} + +function isCleared(cookie: string): boolean { + return /;\s*max-age=0(?:;|$)/i.test(cookie); +} + +function expectNoDuplicateCookies(response: Response): void { + const names = response.headers.getSetCookie().map(cookieName); + expect(names).toEqual([...new Set(names)]); +} + +/** `beforeRoutes` registers user middleware after auth and before every route. */ +function fixture(userConfig: VoidAuthConfig = cookieCache, beforeRoutes?: (app: Hono) => void) { + const database = memoryAdapter({ user: [], session: [], account: [], verification: [] }); + const runtime = createVoidAuthRuntime('sqlite', async () => {}); + const options: VoidAuthRuntimeOptions = { dialect: 'sqlite', providers: null, userConfig }; + const app = new Hono(); + const routing = createRoutingRuntime(app, { nodeTarget: true }); + app.use(routing.contextMiddleware); + app.use(async (c, next) => runtime.runVoidAuthMiddleware(c, next, options, database)); + beforeRoutes?.(app); + app.on(['GET', 'POST'], '/api/auth/*', (c) => + runtime.handleVoidAuthRequest(c, options, database), + ); + app.get('/me', (c) => + c.json({ user: getUser()?.name ?? null, session: getSession()?.user.name ?? null }), + ); + return { app, runtime, options, database }; +} + +/** A GET, or a same-origin JSON POST when there is a body. */ +async function send( + app: Hono, + path: string, + { jar, body }: { jar?: CookieJar; body?: unknown } = {}, +): Promise { + const cookie = jar?.header(); + return app.request( + origin + path, + { + method: body === undefined ? 'GET' : 'POST', + headers: { + ...(body === undefined ? {} : { 'content-type': 'application/json', origin }), + ...(cookie ? { cookie } : {}), + }, + ...(body === undefined ? {} : { body: JSON.stringify(body) }), + }, + env, + ); +} + +async function me( + app: Hono, + jar: CookieJar, +): Promise<{ user: string | null; session: string | null }> { + const response = await send(app, '/me', { jar }); + expect(response.status).toBe(200); + return response.json(); +} + +/** Signs up, then signs in through the auth router and returns the browser's cookies. */ +async function signIn(app: Hono, name = 'Old name', address = email): Promise { + const signUp = await send(app, '/api/auth/sign-up/email', { + body: { name, email: address, password }, + }); + expect(signUp.status).toBe(200); + await signUp.arrayBuffer(); + const response = await send(app, '/api/auth/sign-in/email', { + body: { email: address, password }, + }); + expect(response.status).toBe(200); + await response.arrayBuffer(); + const jar = new CookieJar().apply(response); + expect([...jar.cookies.keys()].some((key) => key.endsWith('better-auth.session_token'))).toBe( + true, + ); + return jar; +} + +describe('cookies set by auth.api calls during a request', () => { + it('refreshes the session cache cookie after updateUser in a route', async () => { + const { app } = fixture(); + app.post('/profile', async (c) => { + const { name } = await c.req.json<{ name: string }>(); + await getAuth(c).api.updateUser({ body: { name }, headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + const jar = await signIn(app); + const stale = jar.clone(); + + const response = await send(app, '/profile', { jar, body: { name: 'New name' } }); + + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ ok: true }); + expect(authCookies(response, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(response); + expect(response.headers.get('cache-control')).toBe('no-store'); + + await expect(me(app, jar.apply(response))).resolves.toEqual({ + user: 'New name', + session: 'New name', + }); + // Without the forwarded cookie the browser keeps the cached old name, + // although the stored user has changed. + await expect(me(app, stale)).resolves.toEqual({ user: 'Old name', session: 'Old name' }); + const uncached = await send(app, '/api/auth/get-session?disableCookieCache=true', { + jar: stale, + }); + await expect(uncached.json()).resolves.toMatchObject({ user: { name: 'New name' } }); + }); + + it('clears the session cookies after signOut in a route', async () => { + const { app } = fixture(); + app.post('/logout', async (c) => { + await getAuth(c).api.signOut({ headers: c.req.raw.headers }); + return c.redirect('/', 303); + }); + const jar = await signIn(app); + const stale = jar.clone(); + + const response = await send(app, '/logout', { jar, body: {} }); + + expect(response.status).toBe(303); + expect(response.headers.get('location')).toBe('/'); + const token = authCookies(response, 'session_token'); + const data = authCookies(response, 'session_data'); + expect(token).toHaveLength(1); + expect(data).toHaveLength(1); + expect(isCleared(token[0]!)).toBe(true); + expect(isCleared(data[0]!)).toBe(true); + expectNoDuplicateCookies(response); + + jar.apply(response); + expect([...jar.cookies.keys()].filter((name) => name.includes('better-auth.'))).toEqual([]); + await expect(me(app, jar)).resolves.toEqual({ user: null, session: null }); + // The old cache cookie would still look signed in until it expires. + await expect(me(app, stale)).resolves.toEqual({ user: 'Old name', session: 'Old name' }); + }); + + it('keeps a single copy of each cookie from the auth router', async () => { + const { app, runtime, options, database } = fixture(); + const signUp = await send(app, '/api/auth/sign-up/email', { + body: { name: 'Router', email, password }, + }); + expect(signUp.status).toBe(200); + expect(authCookies(signUp, 'session_token')).toHaveLength(1); + expectNoDuplicateCookies(signUp); + + const signIn = await send(app, '/api/auth/sign-in/email', { body: { email, password } }); + expect(signIn.status).toBe(200); + expect(authCookies(signIn, 'session_token')).toHaveLength(1); + expect(authCookies(signIn, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(signIn); + expect(signIn.headers.get('cache-control')).toBe('no-store'); + + // Sign-out sends the same cookies as Better Auth's own handler. + const jar = new CookieJar().apply(signIn); + const signOut = await send(app, '/api/auth/sign-out', { jar, body: {} }); + expect(signOut.status).toBe(200); + expect(authCookies(signOut, 'session_token')).toHaveLength(1); + const other = new CookieJar().apply( + await send(app, '/api/auth/sign-in/email', { body: { email, password } }), + ); + const request = new Request(origin + '/api/auth/sign-out', { + method: 'POST', + headers: { 'content-type': 'application/json', origin, cookie: other.header() }, + body: '{}', + }); + const auth = await runtime.createVoidAuth(request, env, options, database); + const direct = await auth.handler(request); + expect(direct.status).toBe(200); + expect(signOut.headers.getSetCookie()).toEqual(direct.headers.getSetCookie()); + }); + + it('keeps a single copy when the route returns an asResponse result', async () => { + const { app } = fixture(); + app.post('/profile', async (c) => + getAuth(c).api.updateUser({ + body: { name: 'As response' }, + headers: c.req.raw.headers, + asResponse: true, + }), + ); + const jar = await signIn(app); + + const response = await send(app, '/profile', { jar, body: {} }); + + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ status: true }); + expect(authCookies(response, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(response); + await expect(me(app, jar.apply(response))).resolves.toEqual({ + user: 'As response', + session: 'As response', + }); + }); + + it('keeps a single copy when the route appends returned headers itself', async () => { + const { app } = fixture(); + app.post('/profile', async (c) => { + const { headers } = await getAuth(c).api.updateUser({ + body: { name: 'Returned headers' }, + headers: c.req.raw.headers, + returnHeaders: true, + }); + for (const cookie of headers.getSetCookie()) { + c.header('set-cookie', cookie, { append: true }); + } + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, '/profile', { jar, body: {} }); + + expect(response.status).toBe(200); + expect(authCookies(response, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(response); + await expect(me(app, jar.apply(response))).resolves.toMatchObject({ + user: 'Returned headers', + }); + }); + + it('leaves requests without an auth.api cookie unchanged', async () => { + const { app } = fixture(); + const routeHeaders = { + 'cache-control': 'public, max-age=60', + ...Object.fromEntries(cdnHeaders.map((name) => [name, 'max-age=600'])), + }; + app.get('/public', (c) => c.text('public', 200, routeHeaders)); + app.get('/sessions', async (c) => { + const sessions = await getAuth(c).api.listSessions({ headers: c.req.raw.headers }); + return c.json({ count: sessions.length }); + }); + + const anonymous = await send(app, '/public'); + expect(anonymous.status).toBe(200); + expect(anonymous.headers.has('set-cookie')).toBe(false); + expect(anonymous.headers.get('cache-control')).toBe('public, max-age=60'); + expect(anonymous.headers.has('pragma')).toBe(false); + for (const name of cdnHeaders) { + expect(anonymous.headers.get(name)).toBe('max-age=600'); + } + + const jar = await signIn(app); + const signedIn = await send(app, '/me', { jar }); + expect(signedIn.headers.has('set-cookie')).toBe(false); + const sessions = await send(app, '/sessions', { jar }); + await expect(sessions.json()).resolves.toEqual({ count: 2 }); + expect(sessions.headers.has('set-cookie')).toBe(false); + }); + + it('makes an anonymous response private when an auth.api call sets a cookie', async () => { + const { app } = fixture(); + app.post('/login', async (c) => { + const credentials = await c.req.json<{ email: string; password: string }>(); + await getAuth(c).api.signInEmail({ body: credentials, headers: c.req.raw.headers }); + return c.text('signed in', 200, { + 'cache-control': 'public, max-age=60', + ...Object.fromEntries(cdnHeaders.map((name) => [name, 'max-age=600'])), + }); + }); + await signIn(app, 'Custom login'); + + const response = await send(app, '/login', { body: { email, password } }); + + expect(response.status).toBe(200); + await expect(response.text()).resolves.toBe('signed in'); + expect(authCookies(response, 'session_token')).toHaveLength(1); + expectNoDuplicateCookies(response); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(response.headers.get('pragma')).toBe('no-cache'); + for (const name of cdnHeaders) { + expect(response.headers.has(name)).toBe(false); + } + await expect(me(app, new CookieJar().apply(response))).resolves.toEqual({ + user: 'Custom login', + session: 'Custom login', + }); + }); + + it('sends only the latest cookie per key after a session lookup refresh', async () => { + const { app } = fixture(); + app.post('/logout', async (c) => { + await getAuth(c).api.signOut({ headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + app.post('/profile', async (c) => { + await getAuth(c).api.updateUser({ body: { name: 'Latest' }, headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + // Without the cache cookie, the session lookup sets a new one. + const jar = (await signIn(app)).without('session_data'); + const lookup = await send(app, '/me', { jar }); + expect(authCookies(lookup, 'session_data')).toHaveLength(1); + + // The lookup, updateUser's own session check and its result each set the + // cache cookie. The browser only needs the last one. + const profile = await send(app, '/profile', { jar, body: {} }); + expect(authCookies(profile, 'session_data').map(cachedName)).toEqual(['Latest']); + expectNoDuplicateCookies(profile); + await expect(me(app, jar.clone().apply(profile))).resolves.toEqual({ + user: 'Latest', + session: 'Latest', + }); + + // The lookup refreshes the cache cookie and signOut then clears it. + const logout = await send(app, '/logout', { jar, body: {} }); + const data = authCookies(logout, 'session_data'); + const token = authCookies(logout, 'session_token'); + expect(data).toHaveLength(1); + expect(token).toHaveLength(1); + expect(isCleared(data[0]!)).toBe(true); + expect(isCleared(token[0]!)).toBe(true); + expectNoDuplicateCookies(logout); + jar.apply(logout); + expect([...jar.cookies.keys()].filter((name) => name.includes('better-auth.'))).toEqual([]); + await expect(me(app, jar)).resolves.toEqual({ user: null, session: null }); + }); + + it.each(['asResponse', 'returnHeaders'] as const)( + 'lets cookies returned through %s win over the session lookup refresh', + async (mode) => { + const { app } = fixture(); + app.post('/profile', async (c) => { + const input = { body: { name: 'Returned' }, headers: c.req.raw.headers }; + if (mode === 'asResponse') { + return getAuth(c).api.updateUser({ ...input, asResponse: true }); + } + const { headers } = await getAuth(c).api.updateUser({ ...input, returnHeaders: true }); + for (const cookie of headers.getSetCookie()) { + c.header('set-cookie', cookie, { append: true }); + } + return c.json({ ok: true }); + }); + // An expired cache cookie makes the session lookup set a new one first. + const jar = (await signIn(app)).without('session_data'); + + const response = await send(app, '/profile', { jar, body: {} }); + + expect(response.status).toBe(200); + expect(authCookies(response, 'session_data').map(cachedName).at(-1)).toBe('Returned'); + await expect(me(app, jar.apply(response))).resolves.toEqual({ + user: 'Returned', + session: 'Returned', + }); + }, + ); + + it('keeps a single copy of cookies from a rewritten route', async () => { + const { app } = fixture(); + app.post('/profile', (c) => (c as RoutingContext).rewrite('/profile/save')); + app.post('/profile/save', async (c) => { + await getAuth(c).api.updateUser({ body: { name: 'Rewritten' }, headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, '/profile', { jar, body: {} }); + + expect(response.status).toBe(200); + expect(authCookies(response, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(response); + await expect(me(app, jar.apply(response))).resolves.toMatchObject({ user: 'Rewritten' }); + }); + + it.each([ + ['object', (config: BetterAuthOptions) => config], + [ + 'function', + (config: BetterAuthOptions) => + ({ defaults }: { defaults: BetterAuthOptions }) => ({ ...defaults, ...config }), + ], + ] as const)('forwards cookies set by user hooks and plugins (%s config)', async (_form, wrap) => { + const plugin = { + id: 'app-plugin', + hooks: { + after: [ + { + matcher: (ctx) => ctx.path === '/update-user', + handler: createAuthMiddleware(async (ctx) => { + ctx.setCookie('app_plugin', 'updated', { path: '/' }); + }), + }, + ], + }, + } satisfies BetterAuthPlugin; + const plugins = [plugin]; + const { app } = fixture( + wrap({ + ...cookieCache, + plugins, + hooks: { + after: createAuthMiddleware(async (ctx) => { + if (ctx.path === '/update-user') { + ctx.setCookie('app_hook', 'updated', { path: '/' }); + } + }), + }, + }), + ); + app.post('/profile', async (c) => { + const auth = getAuth(c); + await auth.api.updateUser({ body: { name: 'Hooked' }, headers: c.req.raw.headers }); + return c.json({ plugins: auth.options.plugins?.map((entry) => entry.id) }); + }); + const jar = await signIn(app); + + const response = await send(app, '/profile', { jar, body: {} }); + + await expect(response.json()).resolves.toEqual({ plugins: ['app-plugin', 'void-cookies'] }); + expect(plugins).toEqual([plugin]); + const cookies = response.headers.getSetCookie(); + expect(cookies.some((cookie) => cookie.startsWith('app_hook=updated'))).toBe(true); + expect(cookies.some((cookie) => cookie.startsWith('app_plugin=updated'))).toBe(true); + expect(authCookies(response, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(response); + jar.apply(response); + expect(jar.cookies.get('app_hook')).toBe('updated'); + await expect(me(app, jar)).resolves.toMatchObject({ user: 'Hooked' }); + }); + + it('lets a route answer an APIError from an auth.api call', async () => { + const { app } = fixture(); + app.post('/password', async (c) => { + try { + await getAuth(c).api.changePassword({ + body: { currentPassword: 'wrong-password-value', newPassword: 'another-long-password' }, + headers: c.req.raw.headers, + }); + } catch (error) { + if (error instanceof APIError) { + return c.json({ error: error.body?.code ?? error.message }, 400); + } + throw error; + } + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, '/password', { jar, body: {} }); + + expect(response.status).toBe(400); + await expect(response.json()).resolves.toEqual({ error: 'INVALID_PASSWORD' }); + // changePassword reads the session without its cache, so Better Auth + // refreshes the cache cookie before the password check fails. + expect(authCookies(response, 'session_token')).toEqual([]); + expect(authCookies(response, 'session_data').map(cachedName)).toEqual(['Old name']); + expectNoDuplicateCookies(response); + await expect(me(app, jar.apply(response))).resolves.toEqual({ + user: 'Old name', + session: 'Old name', + }); + }); + + it('forwards cookies from a successful call when the route then fails', async () => { + const { app } = fixture(); + app.onError((_error, c) => c.text('failed', 500)); + app.post('/profile', async (c) => { + await getAuth(c).api.updateUser({ body: { name: 'Saved' }, headers: c.req.raw.headers }); + throw new Error('after save'); + }); + const jar = await signIn(app); + + const response = await send(app, '/profile', { jar, body: {} }); + + expect(response.status).toBe(500); + await expect(response.text()).resolves.toBe('failed'); + expect(authCookies(response, 'session_data')).toHaveLength(1); + await expect(me(app, jar.apply(response))).resolves.toMatchObject({ user: 'Saved' }); + }); + + it('forwards calls from middleware after auth and from the route', async () => { + const { app } = fixture(); + app.use('/settings/*', async (c, next) => { + await getAuth(c).api.updateUser({ + body: { name: 'From middleware' }, + headers: c.req.raw.headers, + }); + await next(); + }); + app.post('/settings/avatar', async (c) => { + await getAuth(c).api.updateUser({ + body: { image: 'https://app.test/avatar.png' }, + headers: c.req.raw.headers, + }); + return c.json({ ok: true }); + }); + app.get('/settings/view', (c) => c.json({ ok: true })); + const jar = await signIn(app); + + const view = await send(app, '/settings/view', { jar }); + expect(authCookies(view, 'session_data')).toHaveLength(1); + await expect(me(app, jar.clone().apply(view))).resolves.toMatchObject({ + user: 'From middleware', + }); + + // Both calls set the cache cookie. The route's later one has both changes. + const response = await send(app, '/settings/avatar', { jar, body: {} }); + const data = authCookies(response, 'session_data'); + expect(data.map(cachedUser)).toMatchObject([ + { name: 'From middleware', image: 'https://app.test/avatar.png' }, + ]); + expectNoDuplicateCookies(response); + jar.apply(response); + const session = await send(app, '/api/auth/get-session', { jar }); + await expect(session.json()).resolves.toMatchObject({ + user: { name: 'From middleware', image: 'https://app.test/avatar.png' }, + }); + }); + + it('does not share cookies between concurrent requests', async () => { + const { app } = fixture(); + let release!: () => void; + const held = new Promise((resolve) => (release = resolve)); + app.post('/profile', async (c) => { + await getAuth(c).api.updateUser({ body: { name: 'Concurrent' }, headers: c.req.raw.headers }); + await held; + return c.json({ ok: true }); + }); + app.get('/plain', async (c) => { + await held; + return c.text('plain'); + }); + const jar = await signIn(app); + + const pending = Promise.all([ + send(app, '/profile', { jar, body: {} }), + send(app, '/plain', { jar }), + send(app, '/plain'), + ]); + setTimeout(release, 10); + const [profile, signedIn, anonymous] = await pending; + + expect(authCookies(profile, 'session_data')).toHaveLength(1); + expect(signedIn.headers.has('set-cookie')).toBe(false); + expect(anonymous.headers.has('set-cookie')).toBe(false); + }); +}); + +describe('merging session lookup cookies with auth.api cookies', () => { + function authCookieName(jar: CookieJar, suffix: string): string { + const name = [...jar.cookies.keys()].find((key) => key.endsWith(`better-auth.${suffix}`)); + expect(name).toBeDefined(); + return name!; + } + + it('signs out after a route reads a session whose cache cookie is unreadable', async () => { + const { app } = fixture(); + app.post('/switch', async (c) => { + const headers = c.req.raw.headers; + await getAuth(c).api.getSession({ headers }); + await getAuth(c).api.signOut({ headers }); + return c.json({ ok: true }); + }); + const jar = await signIn(app); + jar.cookies.set(authCookieName(jar, 'session_data'), 'not-a-cache-cookie'); + const logged = vi.spyOn(console, 'error').mockImplementation(() => {}); + + const response = await send(app, '/switch', { jar, body: {} }); + + logged.mockRestore(); + expect(response.status).toBe(200); + const data = authCookies(response, 'session_data'); + const token = authCookies(response, 'session_token'); + expect(data).toHaveLength(1); + expect(token).toHaveLength(1); + expect(isCleared(data[0]!)).toBe(true); + expect(isCleared(token[0]!)).toBe(true); + expectNoDuplicateCookies(response); + jar.apply(response); + expect([...jar.cookies.keys()].filter((name) => name.includes('better-auth.'))).toEqual([]); + await expect(me(app, jar)).resolves.toEqual({ user: null, session: null }); + const cache = await getCookieCache(new Request(origin, { headers: { cookie: jar.header() } }), { + secret: env.BETTER_AUTH_SECRET, + isSecure: true, + }); + expect(cache).toBeNull(); + }); + + it('clears the token from a signOut asResponse after the lookup refreshed it', async () => { + const { app } = fixture({ session: { updateAge: 0 } }); + app.post('/logout', (c) => + getAuth(c).api.signOut({ headers: c.req.raw.headers, asResponse: true }), + ); + const jar = await signIn(app); + // With updateAge 0 the session lookup sends a refreshed token every time. + const refresh = await send(app, '/me', { jar }); + expect(authCookies(refresh, 'session_token')).toHaveLength(1); + expect(isCleared(authCookies(refresh, 'session_token')[0]!)).toBe(false); + + const response = await send(app, '/logout', { jar, body: {} }); + + expect(response.status).toBe(200); + const token = authCookies(response, 'session_token'); + expect(token).toHaveLength(1); + expect(isCleared(token[0]!)).toBe(true); + jar.apply(response); + expect([...jar.cookies.keys()].filter((name) => name.includes('better-auth.'))).toEqual([]); + await expect(me(app, jar)).resolves.toEqual({ user: null, session: null }); + }); + + it('keeps a cookie the route set under an auth cookie key', async () => { + const { app } = fixture(); + let cleared = ''; + app.post('/forget-cache', (c) => { + c.header('set-cookie', cleared, { append: true }); + return c.json({ ok: true }); + }); + const signedIn = await signIn(app); + const dataName = authCookieName(signedIn, 'session_data'); + cleared = `${dataName}=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=Lax`; + // Without the cache cookie, the session lookup sets a new one. + const jar = signedIn.without('session_data'); + + const response = await send(app, '/forget-cache', { jar, body: {} }); + + expect(authCookies(response, 'session_data')).toEqual([cleared]); + expectNoDuplicateCookies(response); + jar.apply(response); + expect(jar.cookies.has(dataName)).toBe(false); + await expect(me(app, jar)).resolves.toEqual({ user: 'Old name', session: 'Old name' }); + }); + + it('leaves app cookies and their cache policy to the route', async () => { + const { app } = fixture(); + app.get('/theme', (c) => { + c.header('set-cookie', 'theme=dark; Path=/; Max-Age=600', { append: true }); + return c.text('theme', 200, { 'cache-control': 'public, max-age=60' }); + }); + app.post('/profile', async (c) => { + c.header('set-cookie', 'theme=light; Path=/', { append: true }); + await getAuth(c).api.updateUser({ body: { name: 'Themed' }, headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + + const anonymous = await send(app, '/theme'); + expect(anonymous.headers.getSetCookie()).toEqual(['theme=dark; Path=/; Max-Age=600']); + expect(anonymous.headers.get('cache-control')).toBe('public, max-age=60'); + expect(anonymous.headers.has('pragma')).toBe(false); + + const jar = await signIn(app); + const response = await send(app, '/profile', { jar, body: {} }); + const cookies = response.headers.getSetCookie(); + expect(cookies.filter((cookie) => cookie.startsWith('theme='))).toEqual([ + 'theme=light; Path=/', + ]); + expect(authCookies(response, 'session_data').map(cachedName)).toEqual(['Themed']); + expectNoDuplicateCookies(response); + }); + + it('sends only the last cookie for a key the session lookup set twice', async () => { + const visit = (value: string) => + createAuthMiddleware(async (ctx) => { + if (ctx.path === '/get-session') { + ctx.setCookie('app_visit', value, { path: '/' }); + } + }); + const { app } = fixture({ + ...cookieCache, + hooks: { after: visit('first') }, + plugins: [ + { + id: 'app-visit', + hooks: { after: [{ matcher: () => true, handler: visit('second') }] }, + }, + ], + }); + app.get('/page', (c) => c.text('page')); + + const response = await send(app, '/page'); + + expect(response.status).toBe(200); + expect(response.headers.getSetCookie()).toEqual(['app_visit=second; Path=/']); + expect(response.headers.get('cache-control')).toBe('no-store'); + }); +}); + +describe('auth router responses after auth.api calls in middleware', () => { + // A user middleware reads the session again. Without the cache cookie, that + // call sets a new one for the signed-in user. + const readSession = (app: Hono) => + app.use(async (c, next) => { + await getAuth(c).api.getSession({ headers: c.req.raw.headers }); + await next(); + }); + + it('keeps the router sign-out over a cache cookie from middleware', async () => { + const { app } = fixture(cookieCache, readSession); + const jar = (await signIn(app)).without('session_data'); + + const response = await send(app, '/api/auth/sign-out', { jar, body: {} }); + + expect(response.status).toBe(200); + expect(authCookies(response, 'session_data').every(isCleared)).toBe(true); + expect(authCookies(response, 'session_token').every(isCleared)).toBe(true); + jar.apply(response); + expect([...jar.cookies.keys()].filter((name) => name.includes('better-auth.'))).toEqual([]); + await expect(me(app, jar)).resolves.toEqual({ user: null, session: null }); + }); + + it('keeps the router sign-in of another user over a cache cookie from middleware', async () => { + const { app } = fixture(cookieCache, readSession); + await signIn(app, 'Second user', 'second@example.test'); + const jar = (await signIn(app, 'First user')).without('session_data'); + + const response = await send(app, '/api/auth/sign-in/email', { + jar, + body: { email: 'second@example.test', password }, + }); + + expect(response.status).toBe(200); + expect(authCookies(response, 'session_data').map(cachedName)).toEqual(['Second user']); + expectNoDuplicateCookies(response); + await expect(me(app, jar.apply(response))).resolves.toEqual({ + user: 'Second user', + session: 'Second user', + }); + }); +}); + +describe('auth.api cookies on requests from another origin', () => { + const evil = 'https://evil.test'; + const partner = 'https://partner.test'; + + function loginFixture(config: BetterAuthOptions = cookieCache) { + const { app } = fixture(config); + app.post('/login', async (c) => { + const credentials = await c.req.json<{ email: string; password: string }>(); + await getAuth(c).api.signInEmail({ body: credentials, headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + app.get('/login', async (c) => { + const { email, password } = c.req.query(); + await getAuth(c).api.signInEmail({ body: { email: email!, password: password! } }); + return c.json({ ok: true }); + }); + return app; + } + + async function postLogin(app: Hono, origin?: string): Promise { + return app.request( + 'https://app.test/login', + { + method: 'POST', + headers: { 'content-type': 'application/json', ...(origin ? { origin } : {}) }, + body: JSON.stringify({ email, password }), + }, + env, + ); + } + + async function expectSignedIn(app: Hono, response: Response): Promise { + expect(response.status).toBe(200); + expect(authCookies(response, 'session_token')).toHaveLength(1); + await expect(me(app, new CookieJar().apply(response))).resolves.toEqual({ + user: 'Old name', + session: 'Old name', + }); + } + + it('does not send session cookies from a cross-origin POST', async () => { + const app = loginFixture(); + await signIn(app); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + const response = await postLogin(app, evil); + + expect(warn).toHaveBeenCalledOnce(); + expect(warn.mock.calls[0]![0]).toMatch(/^auth: Did not send cookies set by auth\.api calls/); + warn.mockRestore(); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ ok: true }); + expect(response.headers.getSetCookie()).toEqual([]); + await expect(me(app, new CookieJar().apply(response))).resolves.toEqual({ + user: null, + session: null, + }); + }); + + it.each([ + ['the request origin', 'https://app.test'], + ['no Origin header', undefined], + ])('sends session cookies for %s', async (_label, origin) => { + const app = loginFixture(); + await signIn(app); + const warn = vi.spyOn(console, 'warn'); + + await expectSignedIn(app, await postLogin(app, origin)); + + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); + + it.each<[string, BetterAuthOptions, string]>([ + [ + 'a trustedOrigins list', + { ...cookieCache, trustedOrigins: ['https://app.test', partner] }, + partner, + ], + ['trustedOrigins function', { ...cookieCache, trustedOrigins: async () => [partner] }, partner], + ['disableCSRFCheck', { ...cookieCache, advanced: { disableCSRFCheck: true } }, evil], + ])('sends session cookies for a foreign origin allowed by %s', async (_label, config, origin) => { + const app = loginFixture(config); + await signIn(app); + + await expectSignedIn(app, await postLogin(app, origin)); + }); + + it('sends session cookies for a GET from another origin', async () => { + const app = loginFixture(); + await signIn(app); + const query = new URLSearchParams({ email, password }); + + const response = await app.request( + `https://app.test/login?${query}`, + { headers: { origin: evil } }, + env, + ); + + await expectSignedIn(app, response); + }); +}); + +describe('cookie keys and positions', () => { + it('treats cookie domains without case or a leading dot, and paths with case', async () => { + const plugin = { + id: 'app-cookies', + hooks: { + after: [ + { + matcher: (ctx) => ctx.path === '/update-user', + handler: createAuthMiddleware(async (ctx) => { + ctx.setCookie('x', 'forwarded', { domain: '.example.com', path: '/' }); + ctx.setCookie('y', 'forwarded', { path: '/a' }); + }), + }, + ], + }, + } satisfies BetterAuthPlugin; + const { app } = fixture({ ...cookieCache, plugins: [plugin] }); + app.post('/profile', async (c) => { + c.header('set-cookie', 'x=route; Domain=Example.com; Path=/', { append: true }); + c.header('set-cookie', 'y=route; Path=/A', { append: true }); + await getAuth(c).api.updateUser({ body: { name: 'Keys' }, headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, '/profile', { jar, body: {} }); + + const cookies = response.headers.getSetCookie(); + expect(cookies.filter((cookie) => cookie.startsWith('x='))).toEqual([ + 'x=route; Domain=Example.com; Path=/', + ]); + const y = cookies.filter((cookie) => cookie.startsWith('y=')); + expect(y).toHaveLength(2); + expect(y[0]).toBe('y=route; Path=/A'); + expect(y[1]).toMatch(/^y=forwarded;.*Path=\/a(?:;|$)/); + }); + + it('sends a later signOut after the route copied returned headers', async () => { + const { app } = fixture(); + app.post('/rename-and-leave', async (c) => { + const { headers } = await getAuth(c).api.updateUser({ + body: { name: 'Leaving' }, + headers: c.req.raw.headers, + returnHeaders: true, + }); + for (const cookie of headers.getSetCookie()) { + c.header('set-cookie', cookie, { append: true }); + } + await getAuth(c).api.signOut({ headers: c.req.raw.headers }); + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, '/rename-and-leave', { jar, body: {} }); + + expect(response.status).toBe(200); + expect(isCleared(authCookies(response, 'session_data').at(-1)!)).toBe(true); + expect(isCleared(authCookies(response, 'session_token').at(-1)!)).toBe(true); + jar.apply(response); + expect([...jar.cookies.keys()].filter((name) => name.includes('better-auth.'))).toEqual([]); + await expect(me(app, jar)).resolves.toEqual({ user: null, session: null }); + }); +}); + +describe('cookies from auth.api calls in Pages actions', () => { + function pagesFixture() { + const { app } = fixture(); + app.post( + '/settings', + createPageMutationHandler({ + componentId: 'settings', + render: async () => '', + assets: async () => ({ css: '', body: '', preloads: '' }), + headConfig: null, + renderOptions: { renderMode: 'server' }, + load: async () => ({ + action: async (c) => { + const form = await c.req.formData(); + await getAuth(c).api.updateUser({ + body: { name: String(form.get('name')) }, + headers: c.req.raw.headers, + }); + return c.redirect('/settings', 303); + }, + }), + }), + ); + return app; + } + + function submit(app: Hono, jar: CookieJar, name: string, headers: Record) { + const body = new FormData(); + body.set('name', name); + return app.request( + origin + '/settings', + { method: 'POST', body, headers: { cookie: jar.header(), origin, ...headers } }, + env, + ); + } + + it('keeps the refreshed cookie on a manual Pages redirect', async () => { + const app = pagesFixture(); + const jar = await signIn(app); + + const response = await submit(app, jar, 'Pages action', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Redirect': 'manual', + }); + + expect(response.status).toBe(200); + expect(response.headers.get('X-VoidPages-Redirect')).toBe('303'); + expect(response.headers.get('location')).toBe('/settings'); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(authCookies(response, 'session_data')).toHaveLength(1); + expectNoDuplicateCookies(response); + await expect(me(app, jar.apply(response))).resolves.toEqual({ + user: 'Pages action', + session: 'Pages action', + }); + }); + + it('keeps the refreshed cookie on a document form redirect', async () => { + const app = pagesFixture(); + const jar = await signIn(app); + + const response = await submit(app, jar, 'Form action', {}); + + expect(response.status).toBe(303); + expect(response.headers.get('location')).toBe('/settings'); + expect(authCookies(response, 'session_data')).toHaveLength(1); + await expect(me(app, jar.apply(response))).resolves.toMatchObject({ user: 'Form action' }); + }); +}); diff --git a/packages/void/test/unit/auth-middleware.test.ts b/packages/void/test/unit/auth-middleware.test.ts index ec92789a4..6ac4d41e3 100644 --- a/packages/void/test/unit/auth-middleware.test.ts +++ b/packages/void/test/unit/auth-middleware.test.ts @@ -278,6 +278,71 @@ describe('runVoidAuthMiddleware response headers', () => { }); }); +describe('runVoidAuthMiddleware Better Auth plugins', () => { + const env = { BETTER_AUTH_SECRET: 'test-secret' }; + type PluginList = Array<{ id: string }>; + const pluginsOf = (call: number): PluginList => + (mocks.betterAuth.mock.calls[call]![0] as { plugins?: PluginList }).plugins ?? []; + + function pluginApp(userConfig?: VoidAuthRuntimeOptions['userConfig']): Hono { + mocks.getSession.mockResolvedValue({ response: null, headers: new Headers() }); + mocks.betterAuth.mockReturnValue({ api: { getSession: mocks.getSession }, options: {} }); + const app = new Hono(); + app.use((c, next) => + runtime.runVoidAuthMiddleware(c, next, { ...authRuntimeOptions, userConfig }, {} as never), + ); + app.get('/', (c) => c.text('ok')); + return app; + } + + it.each([ + ['object', (plugins: PluginList) => ({ plugins })], + [ + 'function', + (plugins: PluginList) => + ({ defaults }: { defaults: object }) => ({ ...defaults, plugins }), + ], + ] as const)('keeps user plugins first with a %s config', async (_form, config) => { + const plugins = [{ id: 'first' }, { id: 'second' }]; + const app = pluginApp(config(plugins) as VoidAuthRuntimeOptions['userConfig']); + + expect((await app.request('/', undefined, env)).status).toBe(200); + + expect(pluginsOf(0).map((plugin) => plugin.id)).toEqual(['first', 'second', 'void-cookies']); + expect(pluginsOf(0)[0]).toBe(plugins[0]); + expect(plugins.map((plugin) => plugin.id)).toEqual(['first', 'second']); + }); + + it('creates a separate cookie plugin for each request', async () => { + const app = pluginApp(); + + await app.request('/', undefined, env); + await app.request('/', undefined, env); + + expect(pluginsOf(0).map((plugin) => plugin.id)).toEqual(['void-cookies']); + expect(pluginsOf(1).map((plugin) => plugin.id)).toEqual(['void-cookies']); + expect(pluginsOf(0)[0]).not.toBe(pluginsOf(1)[0]); + }); + + it('leaves the cookie plugin out of instances created outside the middleware', async () => { + mocks.betterAuth.mockReturnValue({ api: {}, options: {} }); + await runtime.createVoidAuth( + new Request('http://localhost/'), + env, + { ...authRuntimeOptions, userConfig: { plugins: [{ id: 'only' }] } }, + {} as never, + ); + expect(pluginsOf(0).map((plugin) => plugin.id)).toEqual(['only']); + }); + + it('skips Better Auth for internal routes', async () => { + const app = pluginApp(); + app.get('/__void/cron', (c) => c.text('internal')); + expect((await app.request('/__void/cron', undefined, env)).status).toBe(200); + expect(mocks.betterAuth).not.toHaveBeenCalled(); + }); +}); + describe('cross-origin cookie sessions', () => { const env = { BETTER_AUTH_SECRET: 'test-secret' }; const now = new Date(); From 4e1ea48fd584fd1c524121095a5ce89bae21aa49 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Sun, 15 Nov 2026 14:20:27 +0900 Subject: [PATCH 2/2] Fix default paths when merging auth cookies. --- .../void/src/runtime/better-auth-shared.ts | 27 ++++-- .../auth-forwarded-cookies.test.ts | 92 +++++++++++++++++++ 2 files changed, 111 insertions(+), 8 deletions(-) diff --git a/packages/void/src/runtime/better-auth-shared.ts b/packages/void/src/runtime/better-auth-shared.ts index 35161ac0d..49f86b129 100644 --- a/packages/void/src/runtime/better-auth-shared.ts +++ b/packages/void/src/runtime/better-auth-shared.ts @@ -493,10 +493,11 @@ function cookieName(cookie: string): string { } // A browser stores one cookie per name, domain and path. Domains ignore case -// and a leading dot; paths are case-sensitive. -function cookieKey(cookie: string): string { +// and a leading dot; paths are case-sensitive. Missing or invalid paths default +// to the request directory. +function cookieKey(cookie: string, defaultPath: string): string { let domain = ''; - let path = ''; + let path = defaultPath; for (const attribute of cookie.split(';').slice(1)) { const equals = attribute.indexOf('='); const name = (equals === -1 ? attribute : attribute.slice(0, equals)).trim().toLowerCase(); @@ -504,7 +505,7 @@ function cookieKey(cookie: string): string { if (name === 'domain') { domain = value.replace(/^\./, '').toLowerCase(); } else if (name === 'path') { - path = value; + path = value.startsWith('/') ? value : defaultPath; } } return `${cookieName(cookie)};${domain};${path}`; @@ -521,17 +522,21 @@ function mergeAuthCookies( lookup: Headers | undefined, forwarded: Array, sent: Array, + requestUrl: string, ): Headers | undefined { if (forwarded.length === 0 && !lookup?.has('set-cookie')) { return lookup; } + const requestPath = new URL(requestUrl).pathname; + const lastSlash = requestPath.lastIndexOf('/'); + const defaultPath = lastSlash <= 0 ? '/' : requestPath.slice(0, lastSlash); // `at` is the position among the `auth.api.*` calls, and -1 for the lookup. const latest = new Map(); for (const cookie of lookup?.getSetCookie() ?? []) { - latest.set(cookieKey(cookie), { cookie, at: -1 }); + latest.set(cookieKey(cookie, defaultPath), { cookie, at: -1 }); } - forwarded.forEach((cookie, at) => latest.set(cookieKey(cookie), { cookie, at })); - const sentByKey = new Map(sent.map((cookie) => [cookieKey(cookie), cookie])); + forwarded.forEach((cookie, at) => latest.set(cookieKey(cookie, defaultPath), { cookie, at })); + const sentByKey = new Map(sent.map((cookie) => [cookieKey(cookie, defaultPath), cookie])); const headers = new Headers(lookup); headers.delete('set-cookie'); for (const [key, { cookie, at }] of latest) { @@ -768,6 +773,7 @@ export function createVoidAuthRuntime( return next(); } + const requestUrl = c.originalUrl?.()?.href ?? c.req.raw.url; const forwarder = createCookieForwarder(); const auth = await createVoidAuth(c.req.raw, c.env as VoidAuthEnv, runtime, database, [ forwarder.plugin, @@ -804,7 +810,12 @@ export function createVoidAuthRuntime( ); forwarded = []; } - const headers = mergeAuthCookies(result.headers, forwarded, c.res.headers.getSetCookie()); + const headers = mergeAuthCookies( + result.headers, + forwarded, + c.res.headers.getSetCookie(), + requestUrl, + ); const credentialed = ['cookie', 'authorization', 'cf-access-jwt-assertion'].some((header) => c.req.raw.headers.has(header), diff --git a/packages/void/test/integration/auth-forwarded-cookies.test.ts b/packages/void/test/integration/auth-forwarded-cookies.test.ts index 154a41056..4f61a57ce 100644 --- a/packages/void/test/integration/auth-forwarded-cookies.test.ts +++ b/packages/void/test/integration/auth-forwarded-cookies.test.ts @@ -910,6 +910,98 @@ describe('auth.api cookies on requests from another origin', () => { }); describe('cookie keys and positions', () => { + it.each<[string, string, boolean, string?]>([ + ['/profile', '/', true], + ['/account/profile', '/account', true], + ['/account/profile/', '/account/profile', true], + ['/account/profile?next=/elsewhere', '/account', true], + ['/account/profile', '', true], + ['/account/profile', 'relative', true], + ['/account/profile', '/', false], + ['/account/profile', '/other', false], + ['/account/profile', '/account', true, '/internal/save'], + ['/account/profile', '/internal', false, '/internal/save'], + ])( + 'preserves route cookie overrides using the browser default path (%s, Path=%s) [%#]', + async (requestPath, routePath, samePath, rewritePath) => { + const plugin = { + id: 'default-path-cookie', + hooks: { + after: [ + { + matcher: (ctx) => ctx.path === '/update-user', + handler: createAuthMiddleware(async (ctx) => { + ctx.setCookie('theme', 'auth'); + }), + }, + ], + }, + } satisfies BetterAuthPlugin; + const { app } = fixture({ ...cookieCache, plugins: [plugin] }); + const routeCookie = `theme=route; Path=${routePath}`; + const pathname = new URL(origin + requestPath).pathname; + if (rewritePath) { + app.post(pathname, (c) => c.rewrite(rewritePath)); + } + app.post(rewritePath ?? pathname, async (c) => { + await getAuth(c).api.updateUser({ + body: { name: 'Default path' }, + headers: c.req.raw.headers, + }); + c.header('set-cookie', routeCookie, { append: true }); + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, requestPath, { jar, body: {} }); + + expect(response.status).toBe(200); + const cookies = response.headers + .getSetCookie() + .filter((cookie) => cookie.startsWith('theme=')); + if (samePath) { + expect(cookies).toEqual([routeCookie]); + } else { + expect(cookies).toHaveLength(2); + expect(cookies[0]).toBe(routeCookie); + expect(cookies[1]).toMatch(/^theme=auth(?:;|$)/); + } + }, + ); + + it('keeps the latest forwarded cookie when omitted and explicit paths match', async () => { + let updates = 0; + const plugin = { + id: 'default-path-cookie', + hooks: { + after: [ + { + matcher: (ctx) => ctx.path === '/update-user', + handler: createAuthMiddleware(async (ctx) => { + updates++; + ctx.setCookie('theme', String(updates), updates === 1 ? {} : { path: '/account' }); + }), + }, + ], + }, + } satisfies BetterAuthPlugin; + const { app } = fixture({ ...cookieCache, plugins: [plugin] }); + app.post('/account/profile', async (c) => { + for (const name of ['First', 'Second']) { + await getAuth(c).api.updateUser({ body: { name }, headers: c.req.raw.headers }); + } + return c.json({ ok: true }); + }); + const jar = await signIn(app); + + const response = await send(app, '/account/profile', { jar, body: {} }); + + expect(response.status).toBe(200); + const cookies = response.headers.getSetCookie().filter((cookie) => cookie.startsWith('theme=')); + expect(cookies).toHaveLength(1); + expect(cookies[0]).toMatch(/^theme=2;.*Path=\/account(?:;|$)/); + }); + it('treats cookie domains without case or a leading dot, and paths with case', async () => { const plugin = { id: 'app-cookies',