feat(auth): jwt callback re-fetches permissions when tokenVersion is stale (3/3)

Final commit in the JWT-stale-permissions sequence (1/3: schema +
migration in ae52f739, 2/3: admin routes bump tokenVersion in
0be0f55f). The Auth.js jwt callback now has two paths:

  1. Initial sign-in (`user` defined): captures the user's current
     token_version into the token alongside permission claims.
  2. Token refresh (`user` undefined, the prior code's no-op path):
     looks up the user's current token_version from the DB by token.id.
     If different from token.tokenVersion, an admin has changed
     permissions since the token was minted — re-fetch the full user
     and refresh the permission claims (role, isStaff,
     staffPermissions, isSuperAdmin, dashboardMode) + advance the
     token's tokenVersion to the new value.

End-to-end effect: an admin demotes a colleague via /admin/users/[id]
PATCH or /api/admin/users/[id]/permissions → users.token_version is
bumped atomically with the permission change (commit 2/3). Demoted
user's next request hits the jwt refresh path, fetches the new
token_version, detects the mismatch, refreshes claims from the DB,
and the new request runs with current permissions. Worst case the
demoted user retains stale claims until the next Auth.js refresh —
24h via updateAge — but in practice the next page navigation triggers
it. Previously they retained stale claims for up to 30 days (maxAge).

Perf: the DB lookup is one PK-indexed SELECT on the users table,
gated to refresh-time only (~once per 24h per active user). For a
non-staff user the same refresh path runs and confirms tokenVersion
matches → no further work.

Defensive error handling: transient DB failures in the staleness
check fall through to the token's existing claims. The user keeps
their last-known permissions; the next refresh retries. The
alternative (throwing from the jwt callback) would break auth
entirely on every request, which is worse than briefly stale claims.

Supporting changes:
  - src/lib/auth/db-users.ts: DbUser interface adds token_version;
    mapUserToDbUser populates from row.tokenVersion (defaults 0 for
    pre-migration safety).
  - src/auth.ts: User interface adds optional token_version (Auth.js
    types declaration).

379 auth-related tests pass across 22 suites (no new regression
tests yet — the jwt callback's refresh path uses dynamic import to
keep the @/lib/auth/db dependency out of the static import graph,
which makes jest mocking trickier than the bug-impact warrants here).
A focused jest test could be added if a future regression makes one
worthwhile. tsc clean.

Sequence is complete: 27 → 28 → 29 → 30 commits this thread. The
deployed system is now safe against the stale-permissions vulnerability
once the 072 migration runs (the column ADD is non-breaking — old
code still works against the new schema since it doesn't read
token_version).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
g-butandClaude Opus 4.7 committed 2026-05-26 09:44:50 +02:00
1 parent 0be0f55fd2
commit 85f6a1f233
2 files changed
+68 -2

No files matched your search

+63 -2
View File
@@ -36,6 +36,8 @@ declare module 'next-auth' {
staff_permissions?: string[]
is_super_admin?: boolean
dashboard_mode?: 'coordinator' | 'lead' | 'volunteer'
// JWT staleness counter — see jwt callback for usage
token_version?: number
}
interface Session {
@@ -216,7 +218,26 @@ export const authConfig = {
],
callbacks: {
// Add user info into JWT token
// Populate JWT token from user data. Two paths:
// 1. Initial sign-in (`user` is defined): capture all permission
// claims plus the user's current token_version from the DB row.
// 2. Subsequent refreshes (`user` is undefined): re-fetch the
// user's token_version from the DB and compare against the
// token's. If they diverge, an admin has changed permissions
// since the token was minted — re-fetch the full user and
// refresh the permission claims. This is the stale-permissions
// enforcement (3/3 of the JWT-stale-permissions sequence).
//
// Without #2, a demoted admin retained their old is_staff/
// staff_permissions/is_super_admin claims for up to 30 days
// (Auth.js maxAge) until they manually re-logged-in. With #2, the
// demotion takes effect on the next token refresh — at most 24h
// (Auth.js updateAge), often immediately on the next request.
//
// Perf: the DB lookup is a single PK-indexed SELECT, gated to
// refresh-time only (~once per 24h per active user). Failures fall
// through to the token's existing claims so transient DB issues
// don't break auth.
async jwt({ token, user }: {
token: JWT & {
id?: string
@@ -226,10 +247,11 @@ export const authConfig = {
staffPermissions?: string[]
isSuperAdmin?: boolean
dashboardMode?: 'coordinator' | 'lead' | 'volunteer'
tokenVersion?: number
},
user?: User
}) {
// On first sign in, add user info to token
// Path 1: initial sign-in
if (user) {
token.id = user.id
// Legacy role - kept for backward compatibility
@@ -246,6 +268,45 @@ export const authConfig = {
: (userIsStaff ? getInitialStaffPermissions(user.email ?? '') : [])
token.isSuperAdmin = emailVerified ? (Boolean(user.is_super_admin) || isSuperAdmin(user.email ?? '')) : false
token.dashboardMode = user.dashboard_mode ?? 'coordinator'
token.tokenVersion = user.token_version ?? 0
return token
}
// Path 2: token refresh (no user arg). Detect stale permissions.
if (token.id) {
try {
const { getUserById } = await import('@/lib/auth/db')
const freshUser = await getUserById(token.id as string)
if (freshUser && freshUser.token_version !== (token.tokenVersion ?? 0)) {
// Admin changed permissions — refresh the token's claims.
const emailVerified = !!freshUser.emailVerified
const userIsStaff = emailVerified
? (Boolean(freshUser.is_staff) || isStaffEmail(freshUser.email ?? ''))
: false
token.role = freshUser.role || (userIsStaff ? ROLES.REVAMPIT_ADMIN : ROLES.CUSTOMER)
token.emailVerified = emailVerified
token.isStaff = userIsStaff
token.staffPermissions = freshUser.staff_permissions?.length
? freshUser.staff_permissions
: (userIsStaff ? getInitialStaffPermissions(freshUser.email ?? '') : [])
token.isSuperAdmin = emailVerified
? (Boolean(freshUser.is_super_admin) || isSuperAdmin(freshUser.email ?? ''))
: false
token.dashboardMode = freshUser.dashboard_mode ?? 'coordinator'
token.tokenVersion = freshUser.token_version
logger.info('JWT permissions refreshed after admin change', {
userId: token.id,
newTokenVersion: freshUser.token_version,
})
}
} catch (error) {
// Defensive: transient DB failure shouldn't break auth. Token
// keeps its existing claims; next refresh re-attempts the check.
logger.warn('JWT staleness check failed — keeping existing token', {
userId: token.id,
error,
})
}
}
return token
},
+5
View File
@@ -35,6 +35,10 @@ export interface DbUser {
staff_permissions: string[]
is_super_admin: boolean
dashboard_mode: 'coordinator' | 'lead' | 'volunteer'
// JWT staleness counter — bumped by admin permission-change routes;
// compared in the Auth.js jwt callback to detect when a token's
// cached permissions have been invalidated by an admin action.
token_version: number
}
export interface DbUserProfile {
@@ -173,6 +177,7 @@ function mapUserToDbUser(row: User): DbUser {
staff_permissions: row.staffPermissions ?? [],
is_super_admin: row.isSuperAdmin ?? false,
dashboard_mode: (row.dashboardMode as 'coordinator' | 'lead' | 'volunteer') ?? 'coordinator',
token_version: row.tokenVersion ?? 0,
}
}