Skip to content

armgit / fx0

Public Imported from GitHub
0

A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.

TypeScript

Refuse a signed-out login's grant on pages and API routes

Pranit4c391d1d8968
diff --git a/app/login/page.tsx b/app/login/page.tsx
index 6d9450e..590c22f 100644
--- a/app/login/page.tsx
+++ b/app/login/page.tsx
@@ -1,7 +1,7 @@
import { Suspense } from 'react'
import { redirect } from 'next/navigation'
import { connection } from 'next/server.js'
-import { getSession, isAuthenticatedSession } from '@/lib/secure-session'
+import { requireUserSession } from '@/lib/auth'
export const metadata = { title: 'Sign in · fx0' }
@@ -25,9 +25,10 @@ function SignInLink({ href }: { href: string }) {
async function SignIn({ searchParams }: { searchParams: SearchParams }) {
// Unsealing the session reads the clock, which must happen at request time.
await connection()
- const [session, params] = await Promise.all([getSession(), searchParams])
+ // A signed-out login's grant, or any failure to check it, shows sign-in.
+ const [session, params] = await Promise.all([requireUserSession().catch(() => null), searchParams])
// An expired grant is not a usable session: sending it to / would loop back here.
- if (isAuthenticatedSession(session) && session.expiresAt > Date.now() && !params.error) redirect('/')
+ if (session && session.expiresAt > Date.now() && !params.error) redirect('/')
const message = typeof params.error === 'string'
? ERRORS[params.error] ?? 'Sign in could not be completed. Please try again.'
: params.error ? 'Sign in could not be completed. Please try again.' : null
diff --git a/lib/auth.ts b/lib/auth.ts
index 563af1d..e4555e1 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -8,10 +8,14 @@ import { hashHandle, randomHandle } from './auth-crypto.ts'
import { getSession, getSessionOptions, isAuthenticatedSession, type SessionData } from './secure-session.ts'
// @ts-expect-error Node strip-types tests require the source extension.
import { MIN_GATEWAY_VALIDITY_MS, TOKEN_ENDPOINT, validOAuthTokens, type OAuthTokens } from './auth-protocol.ts'
+// @ts-expect-error Node strip-types tests require the source extension.
+import { loginRevoked } from './turn-credential.ts'
+// Pages read identity here. A signed-out login's grant is no session, even
+// replayed from a copy: sign-out records the revocation before it answers.
export async function requireUserSession(): Promise<SessionData> {
const session = await getSession()
- if (!isAuthenticatedSession(session)) throw new AuthError()
+ if (!isAuthenticatedSession(session) || await loginRevoked(session.loginId)) throw new AuthError()
return session
}
diff --git a/lib/request-session.ts b/lib/request-session.ts
index 5809788..d8c1685 100644
--- a/lib/request-session.ts
+++ b/lib/request-session.ts
@@ -5,6 +5,8 @@ import { needsTokenRefresh, refreshAccessToken, sessionWithRefresh } from './aut
import { forwardSessionCookie, grantCookieName, GRANT_COOKIE_PREFIX, isLoginId, SESSION_COOKIE_NAME } from './auth-protocol.ts'
// @ts-expect-error Node strip-types tests require the source extension.
import { getGrantFromRequest, getSessionFromRequest, isAuthenticatedSession, sealSessionCookie, type SessionCookie, type SessionData } from './secure-session.ts'
+// @ts-expect-error Node strip-types tests require the source extension.
+import { loginRevoked } from './turn-credential.ts'
type SessionHandler = (request: Request, session: Partial<SessionData>) => Response | Promise<Response>
@@ -25,9 +27,13 @@ export function withRequestSession(body: SessionHandler) {
cookies.push(...await Promise.all(obsolete.map(({ name }) => sealSessionCookie(null, name.slice(GRANT_COOKIE_PREFIX.length)))))
const grant = await getGrantFromRequest(incoming)
+ // A signed-out login's grant is no session, even replayed from a copy: the
+ // request runs signed out, its grant cookie is cleared, and it never refreshes.
+ const revoked = isAuthenticatedSession(grant) && await loginRevoked(grant.loginId)
+ if (revoked) cookies.push(await sealSessionCookie(null, grant.loginId))
let sealed: SessionCookie | undefined
let expiresAt = grant.expiresAt ?? 0
- if (isAuthenticatedSession(grant) && needsTokenRefresh(grant)) {
+ if (!revoked && isAuthenticatedSession(grant) && needsTokenRefresh(grant)) {
const result = await refreshAccessToken(grant.refreshToken!)
if (result.status === 'terminal') {
sealed = await sealSessionCookie(null, grant.loginId)
@@ -39,7 +45,7 @@ export function withRequestSession(body: SessionHandler) {
if (sealed) cookies.push(sealed)
}
- if (isAuthenticatedSession(grant) && expiresAt <= Date.now() && sealed?.value !== '') {
+ if (!revoked && isAuthenticatedSession(grant) && expiresAt <= Date.now() && sealed?.value !== '') {
response = Response.json({ error: 'Authentication temporarily unavailable. Retry shortly.' }, {
status: 503, headers: { 'Cache-Control': 'no-store', 'Retry-After': '5' },
})
diff --git a/lib/turn-credential.ts b/lib/turn-credential.ts
index 4ec8b88..1abb3e0 100644
--- a/lib/turn-credential.ts
+++ b/lib/turn-credential.ts
@@ -33,7 +33,9 @@ const turnCredentialKey = (chatId: string, turnId: number) => `${credentialKey(c
const loginKey = (loginId: string) => prefixed(`login-chats:${loginId}`)
const revokedLoginKey = (loginId: string) => prefixed(`revoked-login:${loginId}`)
-async function loginRevoked(loginId: string): Promise<boolean> {
+// Whether sign-out has revoked this login. Session readers check it as well as
+// credential reads and writes, so a copied grant is no session either.
+export async function loginRevoked(loginId: string): Promise<boolean> {
return await redis().get(revokedLoginKey(loginId)) !== null
}
diff --git a/tests/auth-callback.test.mjs b/tests/auth-callback.test.mjs
index 9d7f00f..6e596a7 100644
--- a/tests/auth-callback.test.mjs
+++ b/tests/auth-callback.test.mjs
@@ -12,6 +12,10 @@ globalThis.__authCallbackAccountWrites = writes
registerHooks({
resolve(specifier, context, next) {
if (specifier === '@/lib/turn-credential' && context.parentURL?.endsWith('/api/auth/signout/route.ts')) return { url: 'data:text/javascript,export async function revokeLoginCredentials() {}', shortCircuit: true }
+ // No login is signed out here; tests/auth.test.mjs covers revoked grants.
+ if (specifier === './turn-credential.ts' && /\/lib\/(auth|request-session)\.ts$/.test(context.parentURL ?? '')) {
+ return { url: 'data:text/javascript,export async function loginRevoked() { return false }', shortCircuit: true }
+ }
if (specifier === '@/lib/accounts' && context.parentURL.endsWith('/api/auth/callback/route.ts')) {
return { url: 'auth-test:account-boundary', shortCircuit: true }
}
diff --git a/tests/auth.test.mjs b/tests/auth.test.mjs
index b4eba5f..c462a10 100644
--- a/tests/auth.test.mjs
+++ b/tests/auth.test.mjs
@@ -10,6 +10,15 @@ import { NextRequest } from 'next/server.js'
// bundler. This only resolves paths, not replacement implementations.
registerHooks({ resolve(specifier, context, next) {
if (specifier === '@/lib/turn-credential' && context.parentURL?.endsWith('/api/auth/signout/route.ts')) return { url: 'data:text/javascript,export async function revokeLoginCredentials() {}', shortCircuit: true }
+ // Session readers check sign-out revocation in the credential store's Redis;
+ // these tests hold it in memory (globalThis.__revokedLogins).
+ if (specifier === './turn-credential.ts' && /\/lib\/(auth|request-session)\.ts$/.test(context.parentURL ?? '')) {
+ return { url: `data:text/javascript,${encodeURIComponent('export async function loginRevoked(id) { const r = globalThis.__revokedLogins; r.checks.push(id); if (r.fail) throw new Error("synthetic revocation read failure"); return r.ids.has(id) }')}`, shortCircuit: true }
+ }
+ // Pages read cookies from next/headers; a test hands them a request's jar.
+ if (specifier === 'next/headers.js' && context.parentURL?.endsWith('/lib/secure-session.ts')) {
+ return { url: `data:text/javascript,${encodeURIComponent('export async function cookies() { return globalThis.__pageCookies ?? new Map() }')}`, shortCircuit: true }
+ }
if (specifier === '@/lib/agent') return { url: 'data:text/javascript,export async function cancelUserRuntime(id) { globalThis.__signedOutUser = id }', shortCircuit: true }
if (specifier.startsWith('@/lib/')) return next(new URL(`../${specifier.slice(2)}.ts`, import.meta.url).href, context)
// after() needs a Next request scope; the sign-out's follow-up runs at once and tests await it.
@@ -37,6 +46,15 @@ const secure = await import('../lib/secure-session.ts')
const auth = await import('../lib/auth.ts')
const { withRequestSession } = await import('../lib/request-session.ts')
const { withChatRoute, withUserRoute } = await import('../lib/route-auth.ts')
+const noRevocations = () => ({ ids: new Set(), checks: [], fail: false })
+globalThis.__revokedLogins = noRevocations()
+// Logins sign-out has revoked, for one test.
+function revocations(t) {
+ const revoked = noRevocations()
+ globalThis.__revokedLogins = revoked
+ t.after(() => { globalThis.__revokedLogins = noRevocations() })
+ return revoked
+}
const handledRequests = new WeakMap()
async function requestSession(request) {
let handled
@@ -355,23 +373,64 @@ test('request cleanup bounds obsolete grant deletions and never touches selector
assert.deepEqual(await secure.getSessionFromRequest(forwardedRequest(cleanup)), {})
})
-test('refresh floor covers 800s routes; ordinary requests perform no network or cookie writes', async (t) => {
+test('refresh floor covers 800s routes; ordinary requests refresh nothing and write no cookies', async (t) => {
assert.equal(protocol.MIN_GATEWAY_VALIDITY_MS, 15 * 60_000)
assert.ok(protocol.MIN_GATEWAY_VALIDITY_MS > 800 * 1000)
const now = Date.now()
assert.equal(auth.needsTokenRefresh(session({ expiresAt: now + protocol.MIN_GATEWAY_VALIDITY_MS + 1 }), now), false)
assert.equal(auth.needsTokenRefresh(session({ expiresAt: now + protocol.MIN_GATEWAY_VALIDITY_MS }), now), true)
- t.mock.method(globalThis, 'fetch', async () => assert.fail('ordinary auth must remain cookie-only'))
+ const revoked = revocations(t)
+ t.mock.method(globalThis, 'fetch', async () => assert.fail('ordinary auth makes no refresh request'))
const request = await requestWithSession('/api/prompt', session({ expiresAt: now + 3600_000 }))
const response = await requestSession(request)
assert.ok(handledRequests.has(response))
assert.equal(response.headers.get('set-cookie'), null)
+ assert.deepEqual(revoked.checks, [session().loginId], 'its one store read is the sign-out check')
assert.deepEqual(await auth.resolveGrantedTeam(session()), { teamId: 'team_granted', teamSlug: 'granted' })
assert.deepEqual((await (await me(request)).json()).user, auth.publicUser(session()))
assert.deepEqual(Object.keys(auth.publicUser(session())), ['id', 'name', 'email', 'picture'])
await assert.rejects(auth.resolveGrantedTeam(session({ teamId: undefined })), (error) => error instanceof AuthError && error.status === 403)
})
+test('a signed-out login\'s grant replayed from a copy is no session for API routes: no refresh, and its cookie is cleared', async (t) => {
+ const revoked = revocations(t)
+ // Within the refresh floor: a live grant would refresh here.
+ const grant = session({ expiresAt: Date.now() + 60_000 })
+ revoked.ids.add(grant.loginId)
+ // Refresh contains its own errors, so count requests rather than fail in one.
+ const network = t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 500 }))
+ const response = await requestSession(await requestWithSession('/api/prompt', grant))
+ assert.equal(network.mock.callCount(), 0, 'a revoked grant never refreshes')
+ assert.equal(response.status, 200)
+ assert.deepEqual(handledRequests.get(response).session, {})
+ const grantCookie = secure.grantCookieName(grant.loginId)
+ assert.ok(response.headers.getSetCookie().some((value) => value.startsWith(`${grantCookie}=`) && value.includes('Max-Age=0')))
+ assert.equal(forwardedRequest(response).cookies.has(grantCookie), false)
+ assert.equal((await (await me(await requestWithSession('/api/auth/me', grant))).json()).user, null)
+})
+
+test('API routes fail closed when the sign-out check is unavailable', async (t) => {
+ const revoked = revocations(t)
+ revoked.fail = true
+ const network = t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 500 }))
+ const response = await requestSession(await requestWithSession('/api/prompt', session()))
+ assert.equal(response.status, 503)
+ assert.equal(handledRequests.has(response), false)
+ assert.equal(network.mock.callCount(), 0, 'no refresh without the sign-out check')
+})
+
+test('pages read no session from a signed-out login\'s grant', async (t) => {
+ const revoked = revocations(t)
+ const grant = session({ expiresAt: Date.now() + 3600_000 })
+ globalThis.__pageCookies = (await requestWithSession('/', grant)).cookies
+ t.after(() => { delete globalThis.__pageCookies })
+ assert.equal((await auth.requireUserSession()).loginId, grant.loginId)
+ revoked.ids.add(grant.loginId)
+ await assert.rejects(auth.requireUserSession(), (error) => error instanceof AuthError && error.status === 401)
+ revoked.fail = true
+ await assert.rejects(auth.requireUserSession(), /synthetic revocation read failure/, 'an unavailable check is no session either')
+})
+
// In-memory REST endpoint exercises the REAL installed Redis adapter and request wrapper,
// not a replacement request wrapper. The separate coordinator tests inject only its cache
// and fetch boundary. No service credentials or remote requests are used.
diff --git a/tests/route-security.test.mjs b/tests/route-security.test.mjs
index ed3df66..8c0c252 100644
--- a/tests/route-security.test.mjs
+++ b/tests/route-security.test.mjs
@@ -76,6 +76,9 @@ const mocks = {
export async function recordTurn() { return true; }
export async function recordGeneration() { return true; }
`,
+ // The session mock ignores cookies, so revoked grants are covered with the real
+ // readers in tests/auth.test.mjs.
+ 'lib/turn-credential.ts': 'export async function loginRevoked() { return false }',
'lib/journal.ts': `
function record(name, id) { const s = globalThis.securityTest; s.trace.push(name); s.redisReads.push(id); return s; }
export async function sessionExists(id) { return record('exists', id).existing.has(id); }