feat(auth): make automatic logout an opt-in per-user setting (#1536)
* feat(auth): make automatic logout an opt-in per-user setting Session timeouts (30 min idle / 12 h absolute on hosted) now apply only to users who enable "Automatic logout" in Settings > Security. Default is off: sessions live for the full Supabase refresh-token lifetime, the behavior from before the 2026-07 session hardening. - user_preferences.auto_logout (migration, default false), toggled via the extended /api/user/preferences route - The opt-in is snapshotted into the signed timeout cookie at mint, so enforcement stays DB-read-free per request; the preferences route clears the cookie on change so a toggle takes effect immediately - Pre-toggle cookies are authentic-but-stale: re-minted preserving their timers, never routed down the tamper path, so the rollout does not log anyone out - NEXT_PUBLIC_SESSION_TIMEOUT_FORCE_ALL=true enforces timeouts for every user regardless of preference (emergency lever, also plumbed through the Docker image); self-hosted stays disabled by default Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(auth): resolve PR #1536 review findings - Replace the spread upsert in /api/user/preferences with one literal payload per field: the phantom-column schema guard cannot resolve spread payloads (Unit tests 3/4 ceiling failure) - Map the preferences 500 through getErrorMessage so the user-facing text is Swedish (CodeRabbit) - fetchAutoLogoutPreference now returns null on a FAILED read instead of a fail-open false: callers skip minting so an unknown preference is never persisted into the year-long signed cookie, and the next request retries; failures log at error level, distinct from the normal opt-out path (compliance swarm GDPR Art.32(1)(b) / ISO A.8.5) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(auth): write multi-field preference updates as one atomic upsert A request carrying both hide_assistant_fab and auto_logout previously issued two sequential writes, so a failure of the second returned 500 after half the request had persisted (CodeRabbit, PR #1536). One literal upsert per accepted field combination keeps the write atomic and stays resolvable for the phantom-column schema guard. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
2e2a64dd0a
commit
11995b1b0c
@@ -3,9 +3,12 @@ import {
|
||||
apiRequestSkipsSessionTimeout,
|
||||
createSessionTimeoutState,
|
||||
evaluateSessionTimeout,
|
||||
fetchAutoLogoutPreference,
|
||||
getSessionTimeoutConfig,
|
||||
sessionStateMatchesUser,
|
||||
sessionStateNeedsRemint,
|
||||
signSessionTimeoutState,
|
||||
toSessionTimeoutClientState,
|
||||
verifySessionTimeoutState,
|
||||
} from '../session-timeout'
|
||||
|
||||
@@ -20,6 +23,7 @@ describe('session timeout configuration', () => {
|
||||
idleTimeoutMs: 30 * 60 * 1000,
|
||||
absoluteTimeoutMs: 12 * 60 * 60 * 1000,
|
||||
warningMs: 2 * 60 * 1000,
|
||||
enforceForAll: false,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -29,6 +33,7 @@ describe('session timeout configuration', () => {
|
||||
idleTimeoutMs: 0,
|
||||
absoluteTimeoutMs: 0,
|
||||
warningMs: 0,
|
||||
enforceForAll: false,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -42,6 +47,7 @@ describe('session timeout configuration', () => {
|
||||
idleTimeoutMs: 60000,
|
||||
absoluteTimeoutMs: 0,
|
||||
warningMs: 60000,
|
||||
enforceForAll: false,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -55,9 +61,16 @@ describe('session timeout configuration', () => {
|
||||
idleTimeoutMs: 0,
|
||||
absoluteTimeoutMs: 60000,
|
||||
warningMs: 10000,
|
||||
enforceForAll: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('reads the force-all override', () => {
|
||||
expect(getSessionTimeoutConfig({
|
||||
NEXT_PUBLIC_SESSION_TIMEOUT_FORCE_ALL: 'true',
|
||||
})).toMatchObject({ enforceForAll: true })
|
||||
})
|
||||
|
||||
it('ignores negative and non-integer overrides', () => {
|
||||
expect(getSessionTimeoutConfig({
|
||||
NEXT_PUBLIC_SESSION_IDLE_TIMEOUT_MS: '-1',
|
||||
@@ -75,6 +88,7 @@ describe('signed session timeout state', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'bankid',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
|
||||
@@ -89,6 +103,7 @@ describe('signed session timeout state', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
|
||||
@@ -100,6 +115,7 @@ describe('signed session timeout state', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
const signed = await signSessionTimeoutState(state, SIGNING_ENV)
|
||||
@@ -118,6 +134,7 @@ describe('signed session timeout state', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
|
||||
@@ -131,12 +148,14 @@ describe('signed session timeout state', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
const unbound = createSessionTimeoutState({
|
||||
userId: 'user-1',
|
||||
sessionId: null,
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
|
||||
@@ -152,6 +171,7 @@ describe('session expiry', () => {
|
||||
idleTimeoutMs: 30_000,
|
||||
absoluteTimeoutMs: 60_000,
|
||||
warningMs: 10_000,
|
||||
enforceForAll: false,
|
||||
}
|
||||
|
||||
it('uses inclusive boundaries and gives absolute expiry precedence', () => {
|
||||
@@ -160,6 +180,7 @@ describe('session expiry', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: 'session-1',
|
||||
method: 'password' as const,
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
}),
|
||||
lastActivityAt: 31_000,
|
||||
@@ -174,6 +195,7 @@ describe('session expiry', () => {
|
||||
userId: 'user-1',
|
||||
sessionId: null,
|
||||
method: 'password',
|
||||
autoLogout: true,
|
||||
now: 1000,
|
||||
})
|
||||
|
||||
@@ -182,6 +204,121 @@ describe('session expiry', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('per-user opt-in gating', () => {
|
||||
const config = {
|
||||
enabled: true,
|
||||
idleTimeoutMs: 30_000,
|
||||
absoluteTimeoutMs: 60_000,
|
||||
warningMs: 10_000,
|
||||
enforceForAll: false,
|
||||
}
|
||||
|
||||
function makeState(autoLogout: boolean) {
|
||||
return createSessionTimeoutState({
|
||||
userId: 'user-1',
|
||||
sessionId: null,
|
||||
method: 'password' as const,
|
||||
autoLogout,
|
||||
now: 1000,
|
||||
})
|
||||
}
|
||||
|
||||
it('never expires a session that has not opted in', () => {
|
||||
const state = makeState(false)
|
||||
|
||||
// Far past both limits: still no timeout without the opt-in.
|
||||
expect(evaluateSessionTimeout(state, config, 10_000_000)).toBeNull()
|
||||
})
|
||||
|
||||
it('expires an opted-in session normally', () => {
|
||||
const state = makeState(true)
|
||||
|
||||
expect(evaluateSessionTimeout(state, config, 61_000)).toBe('absolute')
|
||||
})
|
||||
|
||||
it('lets enforceForAll override the opt-out', () => {
|
||||
const state = makeState(false)
|
||||
|
||||
expect(
|
||||
evaluateSessionTimeout(state, { ...config, enforceForAll: true }, 61_000),
|
||||
).toBe('absolute')
|
||||
})
|
||||
|
||||
it('treats a pre-toggle state as authentic but needing a re-mint', async () => {
|
||||
const legacy = makeState(true) as { autoLogout?: boolean }
|
||||
delete legacy.autoLogout
|
||||
const state = legacy as ReturnType<typeof makeState>
|
||||
|
||||
const signed = await signSessionTimeoutState(state, SIGNING_ENV)
|
||||
await expect(verifySessionTimeoutState(signed!, SIGNING_ENV)).resolves.toEqual(state)
|
||||
expect(sessionStateNeedsRemint(state)).toBe(true)
|
||||
expect(sessionStateNeedsRemint(makeState(false))).toBe(false)
|
||||
// A legacy state is never enforced against until it has been re-minted.
|
||||
expect(evaluateSessionTimeout(state, config, 10_000_000)).toBeNull()
|
||||
})
|
||||
|
||||
it('reports the client state as enabled only when enforced', () => {
|
||||
expect(toSessionTimeoutClientState(makeState(true), config, 2000).enabled).toBe(true)
|
||||
expect(toSessionTimeoutClientState(makeState(false), config, 2000).enabled).toBe(false)
|
||||
expect(
|
||||
toSessionTimeoutClientState(
|
||||
makeState(false),
|
||||
{ ...config, enforceForAll: true },
|
||||
2000,
|
||||
).enabled,
|
||||
).toBe(true)
|
||||
expect(
|
||||
toSessionTimeoutClientState(
|
||||
makeState(true),
|
||||
{ ...config, enabled: false },
|
||||
2000,
|
||||
).enabled,
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchAutoLogoutPreference', () => {
|
||||
function client(result: { data: unknown; error: unknown } | 'throw') {
|
||||
return {
|
||||
from: () => ({
|
||||
select: () => ({
|
||||
eq: () => ({
|
||||
maybeSingle: async () => {
|
||||
if (result === 'throw') throw new Error('network down')
|
||||
return result
|
||||
},
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
} as unknown as Parameters<typeof fetchAutoLogoutPreference>[0]
|
||||
}
|
||||
|
||||
it('returns the stored opt-in', async () => {
|
||||
await expect(
|
||||
fetchAutoLogoutPreference(client({ data: { auto_logout: true }, error: null }), 'u1'),
|
||||
).resolves.toBe(true)
|
||||
await expect(
|
||||
fetchAutoLogoutPreference(client({ data: { auto_logout: false }, error: null }), 'u1'),
|
||||
).resolves.toBe(false)
|
||||
})
|
||||
|
||||
it('treats a missing row as a definitive opt-out', async () => {
|
||||
await expect(
|
||||
fetchAutoLogoutPreference(client({ data: null, error: null }), 'u1'),
|
||||
).resolves.toBe(false)
|
||||
})
|
||||
|
||||
it('returns null (unknown) on a failed read, never a fail-open false', async () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
await expect(
|
||||
fetchAutoLogoutPreference(client({ data: null, error: { message: 'boom' } }), 'u1'),
|
||||
).resolves.toBeNull()
|
||||
await expect(fetchAutoLogoutPreference(client('throw'), 'u1')).resolves.toBeNull()
|
||||
expect(errorSpy).toHaveBeenCalled()
|
||||
errorSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('API exclusions', () => {
|
||||
it('only lets bearer-authenticated machine surfaces bypass timeouts', () => {
|
||||
expect(apiRequestSkipsSessionTimeout('/api/v1/companies/c1/invoices', true)).toBe(true)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
type SessionAuthMethod,
|
||||
@@ -16,6 +17,9 @@ export interface SessionTimeoutConfig {
|
||||
idleTimeoutMs: number
|
||||
absoluteTimeoutMs: number
|
||||
warningMs: number
|
||||
// Ignore the per-user auto_logout opt-in and enforce timeouts for every
|
||||
// cookie session (emergency lever / strict self-hosted deployments).
|
||||
enforceForAll: boolean
|
||||
}
|
||||
|
||||
export interface SessionTimeoutState {
|
||||
@@ -25,6 +29,10 @@ export interface SessionTimeoutState {
|
||||
startedAt: number
|
||||
lastActivityAt: number
|
||||
method: SessionAuthMethod
|
||||
// Snapshot of user_preferences.auto_logout taken when the state was minted.
|
||||
// Absent on cookies minted before the opt-in toggle existed: those must be
|
||||
// re-minted (reading the preference), never treated as tampered.
|
||||
autoLogout?: boolean
|
||||
}
|
||||
|
||||
type Environment = Record<string, string | undefined>
|
||||
@@ -64,6 +72,7 @@ export function getSessionTimeoutConfig(
|
||||
idleTimeoutMs,
|
||||
absoluteTimeoutMs,
|
||||
warningMs,
|
||||
enforceForAll: env.NEXT_PUBLIC_SESSION_TIMEOUT_FORCE_ALL === 'true',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +80,7 @@ export function createSessionTimeoutState(args: {
|
||||
userId: string
|
||||
sessionId: string | null
|
||||
method: SessionAuthMethod
|
||||
autoLogout: boolean
|
||||
now?: number
|
||||
}): SessionTimeoutState {
|
||||
const now = args.now ?? Date.now()
|
||||
@@ -81,6 +91,56 @@ export function createSessionTimeoutState(args: {
|
||||
startedAt: now,
|
||||
lastActivityAt: now,
|
||||
method: args.method,
|
||||
autoLogout: args.autoLogout,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether timeouts actually apply to this session. Auto logout is opt-in
|
||||
* per user (founder decision 2026-08-12): without the opt-in snapshot, or
|
||||
* the global force-all override, a session lives as long as the Supabase
|
||||
* refresh token.
|
||||
*/
|
||||
export function sessionTimeoutEnforced(
|
||||
state: SessionTimeoutState,
|
||||
config: SessionTimeoutConfig,
|
||||
): boolean {
|
||||
return config.enabled && (state.autoLogout === true || config.enforceForAll)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the user's auto_logout opt-in. A missing row is a definitive false
|
||||
* (never opted in); a FAILED read returns null, deliberately distinct from
|
||||
* the opt-out path: callers must not persist a snapshot for an unknown
|
||||
* preference (which would silently disable the control for an opted-in
|
||||
* user for the cookie's lifetime) and instead skip minting so the next
|
||||
* request retries the read. Sessions that already carry a snapshot are
|
||||
* unaffected: enforcement keeps running off the signed cookie.
|
||||
*/
|
||||
export async function fetchAutoLogoutPreference(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
): Promise<boolean | null> {
|
||||
try {
|
||||
const { data, error } = await supabase
|
||||
.from('user_preferences')
|
||||
.select('auto_logout')
|
||||
.eq('user_id', userId)
|
||||
.maybeSingle()
|
||||
if (error) {
|
||||
console.error(
|
||||
'[session-timeout] auto_logout preference read FAILED; enforcement undetermined for this request',
|
||||
error,
|
||||
)
|
||||
return null
|
||||
}
|
||||
return data?.auto_logout === true
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'[session-timeout] auto_logout preference read FAILED; enforcement undetermined for this request',
|
||||
error,
|
||||
)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +149,8 @@ export function evaluateSessionTimeout(
|
||||
config: SessionTimeoutConfig,
|
||||
now = Date.now(),
|
||||
): SessionTimeoutReason | null {
|
||||
if (!sessionTimeoutEnforced(state, config)) return null
|
||||
|
||||
if (
|
||||
config.absoluteTimeoutMs > 0 &&
|
||||
now - state.startedAt >= config.absoluteTimeoutMs
|
||||
@@ -169,6 +231,9 @@ function isValidState(value: unknown): value is SessionTimeoutState {
|
||||
Number.isSafeInteger(state.startedAt) &&
|
||||
Number.isSafeInteger(state.lastActivityAt) &&
|
||||
(state.method === 'password' || state.method === 'bankid') &&
|
||||
// Absent on pre-toggle cookies: valid, but callers re-mint (see
|
||||
// sessionStateNeedsRemint) instead of treating the cookie as forged.
|
||||
(state.autoLogout === undefined || typeof state.autoLogout === 'boolean') &&
|
||||
(state.startedAt as number) > 0 &&
|
||||
(state.lastActivityAt as number) >= (state.startedAt as number)
|
||||
)
|
||||
@@ -284,7 +349,7 @@ export function toSessionTimeoutClientState(
|
||||
serverNow = Date.now(),
|
||||
): SessionTimeoutClientState {
|
||||
return {
|
||||
enabled: config.enabled,
|
||||
enabled: sessionTimeoutEnforced(state, config),
|
||||
idleTimeoutMs: config.idleTimeoutMs,
|
||||
absoluteTimeoutMs: config.absoluteTimeoutMs,
|
||||
warningMs: config.warningMs,
|
||||
@@ -309,6 +374,15 @@ export function sessionStateMatchesUser(
|
||||
return state.sessionId === sessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-toggle cookies carry no auto_logout snapshot. They are authentic, so
|
||||
* they must not hit the tampering path; callers re-mint them, reading the
|
||||
* preference, so every live cookie converges on the v-with-snapshot shape.
|
||||
*/
|
||||
export function sessionStateNeedsRemint(state: SessionTimeoutState): boolean {
|
||||
return state.autoLogout === undefined
|
||||
}
|
||||
|
||||
export function apiRequestSkipsSessionTimeout(
|
||||
pathname: string,
|
||||
hasAuthorizationHeader: boolean,
|
||||
|
||||
@@ -27,6 +27,9 @@ const state = vi.hoisted(() => ({
|
||||
error: unknown
|
||||
},
|
||||
signOut: vi.fn(async () => ({ error: null })),
|
||||
// Row returned for user_preferences reads (the auto_logout mint lookup).
|
||||
userPreferences: null as null | { auto_logout: boolean },
|
||||
userPreferencesError: null as unknown,
|
||||
}))
|
||||
|
||||
vi.mock('@supabase/ssr', () => ({
|
||||
@@ -46,13 +49,20 @@ vi.mock('@supabase/ssr', () => ({
|
||||
},
|
||||
},
|
||||
rpc: vi.fn(async () => state.company),
|
||||
from: vi.fn(() => {
|
||||
from: vi.fn((table: string) => {
|
||||
const chain: Record<string, unknown> = {}
|
||||
const self = new Proxy(chain, {
|
||||
get: (_t, prop) => {
|
||||
if (prop === 'then') return undefined
|
||||
if (prop === 'maybeSingle' || prop === 'single') {
|
||||
return async () => ({ data: null, error: null })
|
||||
return async () => ({
|
||||
data:
|
||||
table === 'user_preferences' && !state.userPreferencesError
|
||||
? state.userPreferences
|
||||
: null,
|
||||
error:
|
||||
table === 'user_preferences' ? state.userPreferencesError : null,
|
||||
})
|
||||
}
|
||||
return () => self
|
||||
},
|
||||
@@ -102,6 +112,8 @@ describe('updateSession redirect destinations', () => {
|
||||
data: [{ company_id: 'company-1', locale: 'sv', used_fallback: false }],
|
||||
error: null,
|
||||
}
|
||||
state.userPreferences = null
|
||||
state.userPreferencesError = null
|
||||
delete process.env.NEXT_PUBLIC_REQUIRE_MFA
|
||||
delete process.env.NEXT_PUBLIC_SELF_HOSTED
|
||||
process.env.SESSION_TIMEOUT_SECRET = 'middleware-test-secret'
|
||||
@@ -139,18 +151,26 @@ describe('updateSession redirect destinations', () => {
|
||||
method?: 'password' | 'bankid'
|
||||
userId?: string
|
||||
sessionId?: string | null
|
||||
autoLogout?: boolean
|
||||
legacy?: boolean
|
||||
}) {
|
||||
const stateValue = {
|
||||
...createSessionTimeoutState({
|
||||
userId: args?.userId ?? 'user-1',
|
||||
sessionId: args?.sessionId === undefined ? 'session-1' : args.sessionId,
|
||||
method: args?.method ?? 'password',
|
||||
// Default the opt-in to true: these tests exercise enforcement.
|
||||
autoLogout: args?.autoLogout ?? true,
|
||||
now: args?.startedAt ?? Date.now(),
|
||||
}),
|
||||
...(args?.lastActivityAt === undefined
|
||||
? {}
|
||||
: { lastActivityAt: args.lastActivityAt }),
|
||||
}
|
||||
if (args?.legacy) {
|
||||
// Pre-toggle cookies carry no auto_logout snapshot.
|
||||
delete (stateValue as { autoLogout?: boolean }).autoLogout
|
||||
}
|
||||
const signed = await signSessionTimeoutState(stateValue)
|
||||
if (!signed) throw new Error('test signing secret missing')
|
||||
return signed
|
||||
@@ -233,6 +253,77 @@ describe('updateSession redirect destinations', () => {
|
||||
expect((await run('/api/v1/companies/c1/invoices', { headers })).status).toBe(200)
|
||||
})
|
||||
|
||||
it('mints the cookie with the auto_logout opt-out default for new sessions', async () => {
|
||||
const response = await run('/settings/tax')
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const encoded = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
await expect(verifySessionTimeoutState(encoded)).resolves.toMatchObject({
|
||||
autoLogout: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('snapshots an opted-in preference at mint time', async () => {
|
||||
state.userPreferences = { auto_logout: true }
|
||||
|
||||
const response = await run('/settings/tax')
|
||||
|
||||
const encoded = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
await expect(verifySessionTimeoutState(encoded)).resolves.toMatchObject({
|
||||
autoLogout: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('persists no snapshot when the preference read fails', async () => {
|
||||
state.userPreferencesError = { message: 'connection reset' }
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
const response = await run('/settings/tax')
|
||||
|
||||
// Unknown preference: nothing minted, nobody logged out; the next
|
||||
// request retries the read.
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.cookies.get(SESSION_TIMEOUT_COOKIE)).toBeUndefined()
|
||||
expect(state.signOut).not.toHaveBeenCalled()
|
||||
errorSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('never logs out a session that has not opted in', async () => {
|
||||
const now = Date.now()
|
||||
// Far past both limits: without the opt-in the session must survive.
|
||||
const encoded = await signedCookie({
|
||||
startedAt: now - 600_000,
|
||||
lastActivityAt: now - 600_000,
|
||||
autoLogout: false,
|
||||
})
|
||||
|
||||
const response = await run('/reports/vat', {
|
||||
headers: { cookie: `${SESSION_TIMEOUT_COOKIE}=${encoded}` },
|
||||
})
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(state.signOut).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('upgrades a pre-toggle cookie in place instead of treating it as forged', async () => {
|
||||
state.userPreferences = { auto_logout: true }
|
||||
const startedAt = Date.now() - 5_000
|
||||
const encoded = await signedCookie({ startedAt, legacy: true })
|
||||
|
||||
const response = await run('/settings/tax', {
|
||||
headers: { cookie: `${SESSION_TIMEOUT_COOKIE}=${encoded}` },
|
||||
})
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(state.signOut).not.toHaveBeenCalled()
|
||||
const upgraded = response.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
|
||||
// Timers survive the upgrade: only the opt-in snapshot is added.
|
||||
await expect(verifySessionTimeoutState(upgraded)).resolves.toMatchObject({
|
||||
startedAt,
|
||||
autoLogout: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('starts a new timeout window when the Supabase session changes', async () => {
|
||||
const encoded = await signedCookie({ sessionId: 'old-session' })
|
||||
|
||||
|
||||
+33
-15
@@ -9,8 +9,10 @@ import {
|
||||
apiRequestSkipsSessionTimeout,
|
||||
createSessionTimeoutState,
|
||||
evaluateSessionTimeout,
|
||||
fetchAutoLogoutPreference,
|
||||
getSessionTimeoutConfig,
|
||||
sessionStateMatchesUser,
|
||||
sessionStateNeedsRemint,
|
||||
sessionTimeoutClearCookieOptions,
|
||||
sessionTimeoutCookieOptions,
|
||||
signSessionTimeoutState,
|
||||
@@ -103,9 +105,14 @@ export async function updateSession(request: NextRequest) {
|
||||
)
|
||||
}
|
||||
|
||||
const stateMatches =
|
||||
verifiedState !== null &&
|
||||
sessionStateMatchesUser(verifiedState, user.id, sessionId)
|
||||
|
||||
if (
|
||||
!verifiedState ||
|
||||
!sessionStateMatchesUser(verifiedState, user.id, sessionId)
|
||||
!stateMatches ||
|
||||
sessionStateNeedsRemint(verifiedState)
|
||||
) {
|
||||
const hintedMethod = request.cookies.get(
|
||||
SESSION_AUTH_METHOD_HINT_COOKIE,
|
||||
@@ -113,21 +120,32 @@ export async function updateSession(request: NextRequest) {
|
||||
const method = isSessionAuthMethod(hintedMethod)
|
||||
? hintedMethod
|
||||
: 'password'
|
||||
const state = createSessionTimeoutState({
|
||||
userId: user.id,
|
||||
sessionId,
|
||||
method,
|
||||
})
|
||||
const signedState = await signSessionTimeoutState(state)
|
||||
const autoLogout = await fetchAutoLogoutPreference(supabase, user.id)
|
||||
|
||||
if (signedState) {
|
||||
request.cookies.set(SESSION_TIMEOUT_COOKIE, signedState)
|
||||
supabaseResponse.cookies.set(
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
signedState,
|
||||
sessionTimeoutCookieOptions(),
|
||||
)
|
||||
clearAuthMethodHint(request, supabaseResponse)
|
||||
// Unknown preference (failed read): mint nothing, so no fail-open
|
||||
// snapshot gets persisted; the next request retries the read.
|
||||
if (autoLogout !== null) {
|
||||
// A matching pre-toggle cookie keeps its timers: upgrading the shape
|
||||
// must not restart the absolute window.
|
||||
const state = verifiedState && stateMatches
|
||||
? { ...verifiedState, autoLogout }
|
||||
: createSessionTimeoutState({
|
||||
userId: user.id,
|
||||
sessionId,
|
||||
method,
|
||||
autoLogout,
|
||||
})
|
||||
const signedState = await signSessionTimeoutState(state)
|
||||
|
||||
if (signedState) {
|
||||
request.cookies.set(SESSION_TIMEOUT_COOKIE, signedState)
|
||||
supabaseResponse.cookies.set(
|
||||
SESSION_TIMEOUT_COOKIE,
|
||||
signedState,
|
||||
sessionTimeoutCookieOptions(),
|
||||
)
|
||||
clearAuthMethodHint(request, supabaseResponse)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const timeoutReason = evaluateSessionTimeout(
|
||||
|
||||
Reference in New Issue
Block a user