feat(auth): enforce session idle and absolute timeouts (#1387)

* feat(auth): enforce session idle and absolute timeouts

Hosted browser sessions now carry an HMAC-signed, HttpOnly cookie holding
session start, last activity and sign-in method, bound to the Supabase
session. Middleware enforces a 30 min idle and 12 h absolute limit
(reason-coded redirects to /login), a heartbeat route advances idle
activity from real user input, and a client controller warns 2 minutes
before expiry. BankID users are routed back to BankID on re-auth via a
short-lived method hint. API-key and MCP bearer surfaces are exempt;
self-hosted installs default off and can opt in via env vars.

Fixes #362

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(auth): derive session-timeout signing key via HKDF

The HMAC key is now HKDF-derived with a purpose-bound info string, so
the SUPABASE_SERVICE_ROLE_KEY fallback never uses the privileged
credential directly as a signing key. Addresses the security review
finding on PR #1387.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(auth): back signature bytes with a plain ArrayBuffer

crypto.subtle.verify requires a BufferSource; Uint8Array.from is typed
over ArrayBufferLike, which the Vercel TypeScript build rejects. Decode
base64url into a Uint8Array constructed over a fresh ArrayBuffer.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(auth): address session-timeout review findings

- signSessionTimeoutState returns null on signing failure instead of
  throwing, so a missing secret degrades the timeout feature in line
  with verifySessionTimeoutState rather than crashing authenticated
  requests; middleware and heartbeat skip the cookie write when null
- heartbeat initializes a fresh signed state for a missing or
  session-mismatched cookie, mirroring middleware, instead of
  returning SESSION_EXPIRED during normal initialization
- sessionStateMatchesUser treats an unresolved current session id as
  a mismatch for session-bound state so another session's cookie is
  never accepted on the userId fallback alone
- drop aria-live from the countdown DialogDescription so screen
  readers are not interrupted every second

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-04 09:59:42 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent f55bfc478b
commit 1c9d378df8
21 changed files with 1610 additions and 13 deletions
+191 -1
View File
@@ -5,6 +5,24 @@ import { apiPathSkipsMfaGate } from '@/lib/auth/api-mfa-gate'
import { DEFAULT_LOCALE, LOCALE_COOKIE, isLocale } from '@/i18n/config'
import { userHasPassword } from '@/lib/auth/has-password'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import {
apiRequestSkipsSessionTimeout,
createSessionTimeoutState,
evaluateSessionTimeout,
getSessionTimeoutConfig,
sessionStateMatchesUser,
sessionTimeoutClearCookieOptions,
sessionTimeoutCookieOptions,
signSessionTimeoutState,
verifySessionTimeoutState,
} from '@/lib/auth/session-timeout'
import {
isSessionAuthMethod,
SESSION_AUTH_METHOD_HINT_COOKIE,
SESSION_TIMEOUT_COOKIE,
type SessionAuthMethod,
type SessionTimeoutReason,
} from '@/lib/auth/session-timeout-shared'
export async function updateSession(request: NextRequest) {
let supabaseResponse = NextResponse.next({
@@ -62,6 +80,72 @@ export async function updateSession(request: NextRequest) {
}
}
const timeoutConfig = getSessionTimeoutConfig()
const hasAuthorizationHeader = request.headers.get('authorization') !== null
if (!user) {
clearSessionTimeoutCookies(request, supabaseResponse)
} else if (
timeoutConfig.enabled &&
!apiRequestSkipsSessionTimeout(pathname, hasAuthorizationHeader)
) {
const encodedState = request.cookies.get(SESSION_TIMEOUT_COOKIE)?.value
const sessionId = await getSupabaseSessionId(supabase)
const verifiedState = await verifySessionTimeoutState(encodedState)
if (encodedState && !verifiedState) {
await signOutTimedOutSession(supabase)
return sessionTimeoutResponse(
request,
supabaseResponse,
'absolute',
'password',
)
}
if (
!verifiedState ||
!sessionStateMatchesUser(verifiedState, user.id, sessionId)
) {
const hintedMethod = request.cookies.get(
SESSION_AUTH_METHOD_HINT_COOKIE,
)?.value
const method = isSessionAuthMethod(hintedMethod)
? hintedMethod
: 'password'
const state = createSessionTimeoutState({
userId: user.id,
sessionId,
method,
})
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(
verifiedState,
timeoutConfig,
)
if (timeoutReason) {
await signOutTimedOutSession(supabase)
return sessionTimeoutResponse(
request,
supabaseResponse,
timeoutReason,
verifiedState.method,
)
}
}
}
// ── API routes ──────────────────────────────────────────────────────────
// API routes authenticate themselves (requireAuth, API-key Bearer, cron
// secret, webhook signatures). Middleware runs on them for ONE reason: to
@@ -78,7 +162,7 @@ export async function updateSession(request: NextRequest) {
if (pathname.startsWith('/api')) {
const skipMfaGate = apiPathSkipsMfaGate(
pathname,
request.headers.get('authorization') !== null,
hasAuthorizationHeader,
)
if (!skipMfaGate && user && shouldEnforceMfa(user)) {
const { data: aal } =
@@ -300,6 +384,112 @@ export async function updateSession(request: NextRequest) {
return supabaseResponse
}
async function getSupabaseSessionId(
supabase: ReturnType<typeof createServerClient>,
): Promise<string | null> {
if (typeof supabase.auth.getClaims !== 'function') return null
try {
const { data } = await supabase.auth.getClaims()
return typeof data?.claims?.session_id === 'string'
? data.claims.session_id
: null
} catch (error) {
console.warn('[middleware] could not resolve Supabase session id', error)
return null
}
}
async function signOutTimedOutSession(
supabase: ReturnType<typeof createServerClient>,
): Promise<void> {
try {
await supabase.auth.signOut({ scope: 'local' })
} catch (error) {
console.warn('[middleware] timed-out session revocation failed', error)
}
}
function clearAuthMethodHint(
request: NextRequest,
response: NextResponse,
): void {
if (!request.cookies.has(SESSION_AUTH_METHOD_HINT_COOKIE)) return
request.cookies.delete(SESSION_AUTH_METHOD_HINT_COOKIE)
response.cookies.set(SESSION_AUTH_METHOD_HINT_COOKIE, '', {
path: '/',
maxAge: 0,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
})
}
function clearSessionTimeoutCookies(
request: NextRequest,
response: NextResponse,
): void {
if (request.cookies.has(SESSION_TIMEOUT_COOKIE)) {
request.cookies.delete(SESSION_TIMEOUT_COOKIE)
response.cookies.set(
SESSION_TIMEOUT_COOKIE,
'',
sessionTimeoutClearCookieOptions(),
)
}
clearAuthMethodHint(request, response)
}
function copyResponseCookies(from: NextResponse, to: NextResponse): void {
for (const cookie of from.cookies.getAll()) {
to.cookies.set(cookie)
}
}
function sessionTimeoutResponse(
request: NextRequest,
authResponse: NextResponse,
reason: SessionTimeoutReason,
method: SessionAuthMethod,
): NextResponse {
clearSessionTimeoutCookies(request, authResponse)
if (request.nextUrl.pathname.startsWith('/api')) {
const response = NextResponse.json(
{
error: {
code: 'SESSION_EXPIRED',
message: reason === 'idle'
? 'Sessionen har upphört på grund av inaktivitet.'
: 'Sessionen har upphört av säkerhetsskäl.',
message_en: reason === 'idle'
? 'The session expired due to inactivity.'
: 'The session expired for security reasons.',
reason,
},
},
{ status: 401 },
)
response.headers.set('X-Session-Timeout-Reason', reason)
response.headers.set('Cache-Control', 'no-store')
copyResponseCookies(authResponse, response)
return response
}
const url = new URL('/login', request.url)
url.searchParams.set('reason', reason)
url.searchParams.set('method', method)
const destination = safeReturnTo(
request.nextUrl.pathname + request.nextUrl.search,
'/',
)
if (destination !== '/') url.searchParams.set('next', destination)
const response = NextResponse.redirect(url)
response.headers.set('Cache-Control', 'no-store')
copyResponseCookies(authResponse, response)
return response
}
/**
* Which query parameter each auth page reads its post-auth destination from.
* /login reads `next` (app/(auth)/login/page.tsx), the MFA pages read