Skip to content

Commit 01900a2

Browse files
TheAlexLichterBrooooooklynclaude
authored
fix(auth): keep private route cache policies on authenticated responses (#408)
## Problem Void's auth middleware copies the session lookup's `cache-control: no-store` and `pragma: no-cache` onto every signed-in response. This overwrites the route's own policy. So signed-in data can never be revalidated: `private, no-cache` plus an `ETag` never gives a `304`. ``` signed-in GET /report (route sends private, no-cache + ETag) route ──► auth middleware ──► Cache-Control: no-store ✗ never a 304 ``` ## What this PR changes ``` route Cache-Control (signed-in) before after ──────────────────────────────────── ───────── ────────────────────────── no-store no-store kept (no pragma) private, no-cache (+ any max-age) no-store kept → etag() answers 304 private / private, max-age=60 no-store no-store private="set-cookie" / no-cache="…" no-store no-store no-cache / public / none no-store no-store anonymous request unchanged unchanged ``` - A kept policy also skips the cookie-rotation fallback (`private, no-store`). The rotated `Set-Cookie` is still sent. - Directive parsing keeps quoted values intact. A comma inside `no-cache="a,private"` does not make a bare `private`. ## Decisions | Question | Choice | Why | | --- | --- | --- | | Keep bare `private`? | No | The browser can reuse it without asking the Worker. After sign-out, the next account on the same browser can see it. | | Keep `private, no-cache`? | Yes | Shared caches can't store it, and the browser must ask before each reuse. This is the `304` case. | | Send `Clear-Site-Data` on sign-out? | Not here | Separate product decision. | ## Known limits - The app sends the `304`, not Void. Use Hono's `etag()` middleware. - A hand-written `ETag` must differ per user. Otherwise user B can get a `304` for user A's cached page. - The browser Back button can show a kept `private, no-cache` page after sign-out. Pages that must not stay in the browser cache should keep the default `no-store`. Shared caches stay safe: ISR and dispatch skip requests with credentials, and they never store `private`, `no-cache` or `no-store`. ## Testing | Test | Covers | | --- | --- | | `auth-isr-cache-policy.test.ts` (real Better Auth) | kept and `no-store` tables, quoted values, case and tab variants, `etag()` `304` end to end | | `auth-middleware.test.ts` | cookie rotation with kept and not-kept policies | | `vp run test`, `vp run check`, lint, fmt | pass | 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: LongYinan <lynweklm@gmail.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 38d8b23 commit 01900a2

4 files changed

Lines changed: 163 additions & 6 deletions

File tree

‎docs/guide/auth.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@ Auth sessions use the same database as your app. Void creates `BETTER_AUTH_SECRE
127127

128128
Local development needs no secret setup. To preview a production build locally, provide `BETTER_AUTH_SECRET`.
129129

130+
Responses to signed-in requests get `Cache-Control: no-store`, so neither the browser cache nor a shared cache keeps a user's data. A route keeps its own policy when it sets `no-store`, or `private` together with `no-cache`. To answer repeat requests with `304`, use `private, no-cache` with Hono's [`etag()`](https://hono.dev/docs/middleware/builtin/etag) middleware. If you set the `ETag` yourself, make it differ per user, so the `304` doesn't reuse another account's page. The browser cache keeps a copy of a `private, no-cache` page, so the Back button can show it again after the user signs out. Keep the default `no-store` for pages that must not stay in the browser cache.
131+
130132
`POST`, `PUT`, `PATCH` and `DELETE` requests and WebSocket connections from another origin don't use the signed-in session unless that origin is in `trustedOrigins`. If a separate frontend calls your app, add its origin there (see [Customization](#customization)). If your routes use their own cookies, check the request `Origin` yourself, for example with Hono's [`csrf()`](https://hono.dev/docs/middleware/builtin/csrf) middleware.
131133

132134
Deployed apps on Cloudflare limit auth requests per client IP with Better Auth's defaults, for example 3 sign-in attempts per 10 seconds. Each Worker instance keeps its own count. Change or turn off the limits with `rateLimit` in `auth.ts`. To share one count across instances, set `rateLimit: { storage: 'database' }`, then run `void db generate` for a direct Cloudflare deploy.

‎packages/void/src/runtime/better-auth-shared.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -215,28 +215,48 @@ function appendAuthHeaders(
215215
return;
216216
}
217217

218+
// `no-store`, or `private` with `no-cache`, keeps the response out of shared
219+
// caches and makes the browser ask before reusing it, which allows ETag + 304
220+
// (the ETag must differ per user). `private` alone lets the browser show the
221+
// response to the next account that signs in.
222+
const routeDirectives = bareCacheDirectives(c.res.headers.get('cache-control'));
223+
const keepRoutePolicy =
224+
routeDirectives.has('no-store') ||
225+
(routeDirectives.has('private') && routeDirectives.has('no-cache'));
218226
source.forEach((value, key) => {
219227
// getSession's response policy belongs to the session endpoint. An anonymous
220228
// lookup must not make the application's public page or asset uncacheable.
221-
if (!includeCachePolicy && ['cache-control', 'pragma'].includes(key.toLowerCase())) {
229+
if (
230+
(!includeCachePolicy || keepRoutePolicy) &&
231+
['cache-control', 'pragma'].includes(key.toLowerCase())
232+
) {
222233
return;
223234
}
224235
c.header(key, value, {
225236
append: key.toLowerCase() === 'set-cookie',
226237
});
227238
});
239+
const sessionDirectives = bareCacheDirectives(source.get('cache-control'));
228240
if (
229241
source.has('set-cookie') &&
230-
!(source.get('cache-control') ?? '')
231-
.split(',')
232-
.some((directive) =>
233-
['private', 'no-store', 'no-cache'].includes(directive.trim().toLowerCase()),
234-
)
242+
!keepRoutePolicy &&
243+
!['private', 'no-store', 'no-cache'].some((directive) => sessionDirectives.has(directive))
235244
) {
236245
c.header('Cache-Control', 'private, no-store');
237246
}
238247
}
239248

249+
// Lowercased Cache-Control directive names that carry no value. Commas inside a
250+
// quoted value do not split directives, so `no-cache="a,private"` has no `private`.
251+
function bareCacheDirectives(policy: string | null): Set<string> {
252+
const directives = (policy ?? '').match(/(?:[^",]|"(?:[^"\\]|\\.)*"?)+/g) ?? [];
253+
return new Set(
254+
directives
255+
.map((directive) => directive.trim().toLowerCase())
256+
.filter((directive) => !directive.includes('=')),
257+
);
258+
}
259+
240260
function resolveUserConfig(
241261
userConfig: VoidAuthConfig | undefined,
242262
defaults: BetterAuthOptions,

‎packages/void/test/integration/auth-isr-cache-policy.test.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { handleIsr, type IsrCacheEnv } from '@void/isr/runtime';
22
import { memoryAdapter } from 'better-auth/adapters/memory';
33
import { Hono } from 'hono';
4+
import { etag } from 'hono/etag';
45
import { describe, expect, it } from 'vite-plus/test';
56
import { createVoidAuthRuntime } from '../../src/runtime/better-auth-shared.ts';
67

@@ -91,3 +92,100 @@ describe('real anonymous Better Auth lookup cache policy', () => {
9192
await expect(response.json()).resolves.toBeNull();
9293
});
9394
});
95+
96+
describe('real authenticated Better Auth session cache policy', () => {
97+
async function signedInApp(routeHeaders: Record<string, string>, { withEtag = false } = {}) {
98+
const database = memoryAdapter({ user: [], session: [], account: [], verification: [] });
99+
const runtime = createVoidAuthRuntime('sqlite', async () => {});
100+
const app = new Hono();
101+
app.use(async (c, next) => runtime.runVoidAuthMiddleware(c, next, options, database));
102+
app.on(['GET', 'POST'], '/api/auth/*', (c) =>
103+
runtime.handleVoidAuthRequest(c, options, database),
104+
);
105+
if (withEtag) {
106+
app.use('/api/report', etag());
107+
}
108+
app.get('/api/report', (c) => c.text('report', 200, routeHeaders));
109+
const signUp = await app.request(
110+
'https://app.test/api/auth/sign-up/email',
111+
{
112+
method: 'POST',
113+
headers: { 'content-type': 'application/json' },
114+
body: JSON.stringify({
115+
name: 'Cache user',
116+
email: 'cache-user@example.test',
117+
password: 'correct-horse-battery-staple',
118+
}),
119+
},
120+
env,
121+
);
122+
expect(signUp.status).toBe(200);
123+
const cookie = signUp.headers
124+
.getSetCookie()
125+
.map((value) => value.split(';')[0])
126+
.join('; ');
127+
const session = await app.request(
128+
'https://app.test/api/auth/get-session',
129+
{ headers: { cookie } },
130+
env,
131+
);
132+
await expect(session.json()).resolves.toMatchObject({
133+
user: { email: 'cache-user@example.test' },
134+
});
135+
return { app, cookie };
136+
}
137+
138+
it.each(['private, no-cache', 'no-store', 'Private, No-Cache, max-age=60', 'private,\tno-cache'])(
139+
'keeps a no-store or private, no-cache route policy: %s',
140+
async (policy) => {
141+
const { app, cookie } = await signedInApp({ 'cache-control': policy, etag: 'W/"report-1"' });
142+
const response = await app.request(
143+
'https://app.test/api/report',
144+
{ headers: { cookie } },
145+
env,
146+
);
147+
expect(response.status).toBe(200);
148+
expect(response.headers.get('cache-control')).toBe(policy);
149+
expect(response.headers.has('pragma')).toBe(false);
150+
expect(response.headers.get('etag')).toBe('W/"report-1"');
151+
},
152+
);
153+
154+
it.each([
155+
null,
156+
'public, max-age=60',
157+
'no-cache',
158+
'private="set-cookie", max-age=60',
159+
'private',
160+
'private, max-age=60',
161+
'private, no-cache="set-cookie"',
162+
'no-cache="x,private,y", public, max-age=600',
163+
'no-cache="x,no-store,y", public, max-age=600',
164+
'no-cache="a\\",no-store,b", public, max-age=600',
165+
])('applies the session lookup no-store to a route policy of %s', async (policy) => {
166+
const { app, cookie } = await signedInApp(policy ? { 'cache-control': policy } : {});
167+
const response = await app.request('https://app.test/api/report', { headers: { cookie } }, env);
168+
expect(response.headers.get('cache-control')).toBe('no-store');
169+
expect(response.headers.get('pragma')).toBe('no-cache');
170+
});
171+
172+
it('answers a signed-in repeat request with 304 through etag()', async () => {
173+
const { app, cookie } = await signedInApp(
174+
{ 'cache-control': 'private, no-cache' },
175+
{ withEtag: true },
176+
);
177+
const first = await app.request('https://app.test/api/report', { headers: { cookie } }, env);
178+
expect(first.status).toBe(200);
179+
const tag = first.headers.get('etag');
180+
expect(tag).toBeTruthy();
181+
const repeat = await app.request(
182+
'https://app.test/api/report',
183+
{ headers: { cookie, 'if-none-match': tag! } },
184+
env,
185+
);
186+
expect(repeat.status).toBe(304);
187+
expect(repeat.headers.get('cache-control')).toBe('private, no-cache');
188+
expect(repeat.headers.has('pragma')).toBe(false);
189+
expect(repeat.headers.get('etag')).toBe(tag);
190+
});
191+
});

‎packages/void/test/unit/auth-middleware.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,43 @@ describe('runVoidAuthMiddleware response headers', () => {
173173
expect(response.headers.get('cache-control')).toBe('private, no-store');
174174
expect(response.headers.getSetCookie()).toEqual(['session=rotated; Path=/; HttpOnly']);
175175
});
176+
177+
it.each([
178+
['without its own cache policy', new Headers()],
179+
['with a no-store policy', new Headers({ 'cache-control': 'no-store', pragma: 'no-cache' })],
180+
])(
181+
'keeps a private, no-cache route policy through a cookie rotation %s',
182+
async (_label, authHeaders) => {
183+
authHeaders.append('set-cookie', 'session=rotated; Path=/; HttpOnly');
184+
const app = createApp({ response: null, headers: authHeaders });
185+
app.get('/refresh', (c) =>
186+
c.text('content', 200, { 'cache-control': 'private, no-cache', etag: 'W/"v1"' }),
187+
);
188+
const response = await app.request(
189+
'http://localhost/refresh',
190+
{ headers: { cookie: 'session=current' } },
191+
{ BETTER_AUTH_SECRET: 'test-secret' },
192+
);
193+
expect(response.headers.get('cache-control')).toBe('private, no-cache');
194+
expect(response.headers.has('pragma')).toBe(false);
195+
expect(response.headers.getSetCookie()).toEqual(['session=rotated; Path=/; HttpOnly']);
196+
},
197+
);
198+
199+
it('does not let a cookie rotation keep a private route policy the browser may reuse', async () => {
200+
const app = createApp({
201+
response: null,
202+
headers: new Headers({ 'set-cookie': 'session=rotated; Path=/; HttpOnly' }),
203+
});
204+
app.get('/refresh', (c) => c.text('content', 200, { 'cache-control': 'private, max-age=60' }));
205+
const response = await app.request(
206+
'http://localhost/refresh',
207+
{ headers: { cookie: 'session=current' } },
208+
{ BETTER_AUTH_SECRET: 'test-secret' },
209+
);
210+
expect(response.headers.get('cache-control')).toBe('private, no-store');
211+
expect(response.headers.getSetCookie()).toEqual(['session=rotated; Path=/; HttpOnly']);
212+
});
176213
});
177214

178215
describe('cross-origin cookie sessions', () => {

0 commit comments

Comments
 (0)