@payez/next-mvp 4.10.0 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/api-handlers/auth/refresh.d.ts +17 -58
  3. package/dist/api-handlers/auth/refresh.js +71 -772
  4. package/dist/auth/utils/token-utils.d.ts +1 -1
  5. package/dist/auth/utils/token-utils.js +3 -2
  6. package/dist/lib/api-handler.js +4 -3
  7. package/dist/lib/ensure-fresh-access-token.d.ts +24 -1
  8. package/dist/lib/ensure-fresh-access-token.js +194 -28
  9. package/dist/lib/idp-fetch.js +3 -2
  10. package/dist/lib/refresh-in-doubt.d.ts +31 -0
  11. package/dist/lib/refresh-in-doubt.js +81 -0
  12. package/dist/lib/refresh-token-validator.js +2 -1
  13. package/dist/lib/refresh-window.d.ts +16 -0
  14. package/dist/lib/refresh-window.js +19 -0
  15. package/dist/lib/safe-trace-id.d.ts +11 -0
  16. package/dist/lib/safe-trace-id.js +23 -0
  17. package/dist/lib/session-store.js +14 -4
  18. package/dist/lib/token-lifecycle.js +3 -2
  19. package/dist/models/SessionModel.d.ts +7 -0
  20. package/dist/routes/auth/refresh.d.ts +1 -15
  21. package/dist/server/auth.d.ts +1 -1
  22. package/dist/stores/authStore.js +3 -2
  23. package/package.json +1 -1
  24. package/scripts/verify-release-provenance.mjs +1 -0
  25. package/src/api-handlers/auth/refresh.ts +72 -812
  26. package/src/auth/utils/token-utils.ts +3 -2
  27. package/src/lib/api-handler.ts +4 -3
  28. package/src/lib/ensure-fresh-access-token.ts +213 -29
  29. package/src/lib/idp-fetch.ts +3 -2
  30. package/src/lib/refresh-in-doubt.ts +79 -0
  31. package/src/lib/refresh-token-validator.ts +2 -1
  32. package/src/lib/refresh-window.ts +16 -0
  33. package/src/lib/safe-trace-id.ts +21 -0
  34. package/src/lib/session-store.ts +15 -3
  35. package/src/lib/token-lifecycle.ts +3 -2
  36. package/src/models/SessionModel.ts +7 -0
  37. package/src/server/auth.ts +1 -1
  38. package/src/stores/authStore.ts +3 -2
@@ -1,47 +1,31 @@
1
1
  /**
2
- * CRITICAL REFRESH TOKEN API HANDLER
2
+ * REFRESH TOKEN API HANDLER - a thin HTTP wrapper over `ensureFreshAccessToken` (R-over-E, BAPert 76449; design: docs/refresh-r-over-e-delta.md)
3
3
  *
4
- * ASK BEFORE EDITING - TESTED AND WORKING SYSTEM
4
+ * ASK BEFORE EDITING - this is the route every browser, middleware and `internalRefresh` caller reaches.
5
5
  *
6
- * This handler manages the server-side refresh token cycle with:
7
- * - Better Auth session extraction (the ONLY way a session is established here)
8
- * - PayEz IDP refresh token exchange
9
- * - Session state updates with new tokens
10
- * - Proper error handling and logging
11
- * - Single-use semantics enforcement
6
+ * `lib/ensure-fresh-access-token` is the ONE implementation that talks to the IdP, holds the refresh lock and writes the tokens (post-lock
7
+ * token, in-doubt marker, fetch timeout, envelope rule, dropped-persist and canonical-row handling all live there). This file keeps what only
8
+ * an HTTP request has:
9
+ * - resolving the session from the request's own Better Auth cookie,
10
+ * - the `x-session-token` ownership rejection (below),
11
+ * - the `x-request-id` trace id (log correlation only; it is never the lock identity),
12
+ * - mapping E's typed result onto this route's existing JSON bodies and status codes.
13
+ * The bodies did not change except where E's rules did (see CHANGELOG): the browser, `middleware/create-middleware`, `lib/token-lifecycle`
14
+ * (which reads `reason === 'already_fresh'`) and `lib/idp-fetch` / `lib/api-handler` (via `internalRefresh`) depend on them.
12
15
  *
13
16
  * ── 246007: THE `x-session-token` FALLBACK IS GONE. IT NOW HARD-DENIES. ────
14
- * This list previously advertised an x-session-token fallback for internal
15
- * callers as a current capability. That behaviour has been REMOVED: a request presenting `x-session-token` with
16
- * no cookie-resolved session of its own is rejected 401 UNAUTHORIZED, because
17
- * there is no session to establish ownership of the token it names. Accepting
18
- * it let a caller refresh a session they did not own.
17
+ * A request presenting `x-session-token` with no cookie-resolved session of its own is rejected 401 UNAUTHORIZED, because there is no
18
+ * session to establish ownership of the token it names. Accepting it let a caller refresh a session they did not own. This docstring
19
+ * ships (it is compiled into dist and the .d.ts), so it describes what the code does.
19
20
  *
20
- * The line is corrected here rather than merely deleted, and it is called out
21
- * rather than quietly dropped, because THIS DOCSTRING SHIPS. It is compiled
22
- * into dist and into the .d.ts, so it reaches every consumer's editor as hover
23
- * text. QAPert-NightHawk caught that the fixed build was still describing the
24
- * removed capability as a current feature (34973) — her verifier tests code
25
- * properties and reads no comments, so a correct build could have published
26
- * documentation asserting the opposite of what the code does.
27
- *
28
- * That matters twice over: an internal caller relying on the fallback gets a
29
- * silent behavioural break while the docs promise it still works, and a
30
- * published package that misdescribes its own auth behaviour is the same
31
- * amplifier that put other defects onto three surfaces — shipped code carrying
32
- * instructions for using it wrongly.
33
- *
34
- * @version 2.1
21
+ * @version 3.0
35
22
  */
36
23
 
37
24
  import { NextRequest, NextResponse } from 'next/server';
38
- import { randomUUID } from 'crypto';
39
25
  import { getSession as getBetterAuthSession } from '../../server/auth';
40
- import { getSession, updateSession, acquireRefreshLock, releaseRefreshLock, checkRefreshLock } from '../../lib/session-store';
41
- import { computeTokenExpiries } from '../../lib/token-expiry';
42
- import { extractKidFromToken } from '../../auth/utils/token-utils';
43
- import { tokenLogId } from '../../lib/token-log-id';
44
- import { rotatedRowIsUsable } from '../../lib/refresh-rotation';
26
+ import { ensureFreshAccessToken, type EnsureFreshResult } from '../../lib/ensure-fresh-access-token';
27
+ import { UPSTREAM_TIMEOUT_CODE } from '../../lib/refresh-in-doubt';
28
+ import { sanitizeTraceId } from '../../lib/safe-trace-id';
45
29
 
46
30
  interface RefreshConfig {
47
31
  idpBaseUrl: string;
@@ -49,6 +33,36 @@ interface RefreshConfig {
49
33
  refreshEndpoint?: string;
50
34
  }
51
35
 
36
+ /** E's failure -> this route's body and status. Bodies for the cases the route always had are exactly as they were. */
37
+ function failureResponse(r: Extract<EnsureFreshResult, { ok: false }>): NextResponse {
38
+ switch (r.code) {
39
+ case 'NO_SESSION':
40
+ return NextResponse.json({ error: 'No session available for refresh', code: 'UNAUTHORIZED' }, { status: 401 });
41
+ case 'NO_REFRESH_TOKEN':
42
+ return NextResponse.json({
43
+ error: 'No refresh token available',
44
+ code: 'NO_REFRESH_TOKEN', // Terminal state - session cannot be refreshed
45
+ terminal: true, // Signal to frontend: don't retry, redirect to login
46
+ resolution: r.resolution ?? 'User must re-authenticate',
47
+ }, { status: 401 });
48
+ case 'CONFLICT':
49
+ return NextResponse.json({ error: 'Refresh already in progress', code: 'CONFLICT', retryable: true }, { status: 409 });
50
+ default: {
51
+ const body: Record<string, unknown> = {
52
+ error: r.message,
53
+ code: r.code,
54
+ retryable: r.retryable ?? false,
55
+ discardToken: r.discardToken ?? false,
56
+ };
57
+ if (r.terminal !== undefined) body.terminal = r.terminal;
58
+ if (r.resolution !== undefined) body.resolution = r.resolution;
59
+ // A timed-out refresh is outcome-UNKNOWN (BAPert 76403): say so, so a client does not treat it as a plain upstream failure.
60
+ if (r.code === UPSTREAM_TIMEOUT_CODE) body.outcomeUnknown = true;
61
+ return NextResponse.json(body, { status: r.status });
62
+ }
63
+ }
64
+ }
65
+
52
66
  /**
53
67
  * Creates a refresh token handler for Next.js API routes
54
68
  *
@@ -72,48 +86,20 @@ export function createRefreshHandler(config: RefreshConfig) {
72
86
 
73
87
  return async function POST(req: NextRequest) {
74
88
  try {
75
- // Extract session from Better Auth
89
+ // Extract session from Better Auth (the ONLY way a session is established here)
76
90
  const betterAuthSession = await getBetterAuthSession(req);
77
91
 
78
- let sessionToken = (betterAuthSession?.session?.token) as string | undefined;
79
- let userId = betterAuthSession?.user?.id;
92
+ const sessionToken = (betterAuthSession?.session?.token) as string | undefined;
93
+ const userId = betterAuthSession?.user?.id;
80
94
 
81
95
  if (!sessionToken) {
82
- // OWNERSHIP CHECK on the x-session-token fallback (246007). BAPert ruled
83
- // 34708: ship it, accept the one-time re-login cost, do not gate on 240654.
84
- //
85
- // WHAT THIS CLOSED: the fallback took a session token from a CALLER-SUPPLIED
86
- // header and acted on that session with no check that it belonged to the
87
- // caller. /api/auth/* is in publicRoutes on the consuming surfaces, so an
88
- // UNAUTHENTICATED caller who knew any session token could cause that session
89
- // to be refreshed -- an identity assumption, and the precondition for the
90
- // forced-logout chain via IDP reuse detection.
91
- //
92
- // WHY THE CHECK IS A HARD DENY RATHER THAN A COMPARISON, which is the part
93
- // worth understanding before anyone "improves" it: this branch is reached
94
- // ONLY when getBetterAuthSession() failed to resolve a session from the
95
- // request's own cookie. The natural ownership check -- "the header may only
96
- // name the session the caller's cookie already resolves to" -- therefore has
97
- // nothing to compare against by construction. Any correct ownership test at
98
- // this point evaluates to reject. So the check and outright removal coincide
99
- // here; a more permissive version is not possible without moving the check
100
- // somewhere it can actually see an authenticated identity.
101
- //
102
- // WHO THIS AFFECTS, and it is a deliberate accepted cost, not an oversight:
103
- // internal callers (lib/internal-api internalRefresh, from api-handler and
104
- // idp-fetch) forward the end user's cookie. Where that cookie resolves they
105
- // never enter this branch and are unaffected. Where it does not -- sessions
106
- // minted before the graft dual-write (8a5ac21) whose cookie carries only the
107
- // __Secure- name, which the pre-240654 resolver could not read -- the refresh
108
- // now fails and the user re-authenticates ONCE. Their next login writes both
109
- // cookie names and they are permanently fine. That population cannot grow, does
110
- // not age out (session TTL slides on every write), and does not self-heal on
111
- // use (this handler sets no cookie) -- so the only ways out were to accept the
112
- // re-login or leave the defect live. BAPert chose to accept it.
113
- //
114
- // If server-to-server refresh must work WITHOUT an end-user cookie, that needs
115
- // real service authentication -- a shared secret, mTLS, or a network policy --
116
- // never a header any client can set.
96
+ // OWNERSHIP CHECK on the x-session-token fallback (246007; BAPert ruled 34708: ship it, accept the one-time re-login cost).
97
+ // This branch is reached ONLY when getBetterAuthSession() failed to resolve a session from the request's own cookie, so the natural
98
+ // check ("the header may only name the session the caller's cookie already resolves to") has nothing to compare against by
99
+ // construction: any correct ownership test here evaluates to reject. So the check and outright removal coincide. Internal callers
100
+ // (lib/internal-api internalRefresh) forward the end user's cookie and never enter this branch where that cookie resolves. If
101
+ // server-to-server refresh must work WITHOUT an end-user cookie it needs real service authentication (a shared secret, mTLS, a network
102
+ // policy), never a header any client can set.
117
103
  const headerSessionToken = req.headers.get('x-session-token');
118
104
  if (headerSessionToken) {
119
105
  console.warn(
@@ -139,750 +125,24 @@ export function createRefreshHandler(config: RefreshConfig) {
139
125
  }, { status: 401 });
140
126
  }
141
127
 
142
- // Get current session
143
- const currentSession = await getSession(sessionToken);
144
- // NOTE: Field is idpRefreshToken (not refreshToken) per normalized naming convention
145
- if (!currentSession?.idpRefreshToken) {
146
- console.warn('[AUTH_REFRESH] No refresh token available', { userId });
147
- return NextResponse.json({
148
- error: 'No refresh token available',
149
- code: 'NO_REFRESH_TOKEN', // Terminal state - session cannot be refreshed
150
- terminal: true, // Signal to frontend: don't retry, redirect to login
151
- resolution: 'User must re-authenticate'
152
- }, { status: 401 });
153
- }
154
-
155
- // ============================================================================
156
- // HIGH VISIBILITY: PRE-FLIGHT REFRESH DIAGNOSTICS
157
- // ============================================================================
158
- const now = Date.now();
159
- const refreshTokenAge = currentSession.idpRefreshTokenIssuedAt
160
- ? Math.round((now - currentSession.idpRefreshTokenIssuedAt) / 1000)
161
- : 'unknown';
162
- const refreshTokenExpiresIn = currentSession.idpRefreshTokenExpires
163
- ? Math.round((currentSession.idpRefreshTokenExpires - now) / 1000)
164
- : 'unknown';
165
- const accessTokenExpiresIn = currentSession.idpAccessTokenExpires
166
- ? Math.round((currentSession.idpAccessTokenExpires - now) / 1000)
167
- : 'unknown';
168
-
169
- console.log('╔══════════════════════════════════════════════════════════════════════════════╗');
170
- console.log('║ REFRESH TOKEN ATTEMPT - PRE-FLIGHT ║');
171
- console.log('╠══════════════════════════════════════════════════════════════════════════════╣');
172
- console.log(`║ User: ${(userId || 'unknown').substring(0, 50).padEnd(50)} ║`);
173
- console.log(`║ Session: ${tokenLogId(sessionToken)} ║`);
174
- console.log('╠──────────────────────────────────────────────────────────────────────────────╣');
175
- console.log(`║ Access Token Expires In: ${String(accessTokenExpiresIn).padEnd(10)} seconds ║`);
176
- console.log(`║ Refresh Token Age: ${String(refreshTokenAge).padEnd(10)} seconds ║`);
177
- console.log(`║ Refresh Token Expires In: ${String(refreshTokenExpiresIn).padEnd(10)} seconds ║`);
178
- console.log(`║ Refresh Token Length: ${String(currentSession.idpRefreshToken?.length || 0).padEnd(10)} chars ║`);
179
- console.log(`║ 2FA Complete: ${String(!!currentSession.mfaVerified).padEnd(10)} ║`);
180
- console.log(`║ Auth Level (ACR): ${String(currentSession.authenticationLevel || '1').padEnd(10)} ║`);
181
- console.log('╚══════════════════════════════════════════════════════════════════════════════╝');
182
-
183
- // LOCK IDENTITY IS MINTED SERVER-SIDE. It must never come from a header.
184
- //
185
- // This was `req.headers.get('x-request-id') ?? \`refresh_${Date.now()}\``, and the
186
- // value was used as the lock's `acquiredBy`. Below it, a branch let a caller
187
- // PROCEED WITHOUT THE LOCK when the existing lock's acquiredBy equalled the id
188
- // they had supplied. Since the caller chose that id, the branch was a lock
189
- // bypass requiring no guesswork: send N concurrent requests all carrying the
190
- // same x-request-id, and every one after the first skips the wait.
191
- //
192
- // That completed an attacker-controlled forced logout, because the serialisation
193
- // is what prevents refresh-token REUSE, and the IDP treats reuse as compromise:
194
- // IdentityRefreshTokenService:166 -> RevokeDescendantTokens ->
195
- // IdentityRefreshTokenRepository:142 revokes every ACTIVE token for that USER
196
- // issued after the reused one -- across all devices and all client apps. So a
197
- // caller who knew one session token could log a user out everywhere by sending
198
- // a few requests with a header value of their own choosing.
199
- //
200
- // Minting server-side removes the bypass by construction: no caller can produce
201
- // a value that matches an in-flight lock, so the equality branch can never be
202
- // true and is deleted rather than left inert -- an unreachable branch that
203
- // trusts a header is a trap for whoever edits this next.
204
- //
205
- // The anti-deadlock intent that branch served is preserved by the wait path
206
- // below, which is the correct handling anyway: a genuine duplicate waits for the
207
- // in-flight refresh and returns its result instead of starting a second one.
208
- // The header is still read, for TRACING ONLY, and never influences control flow.
209
- const traceId = req.headers.get('x-request-id') ?? undefined;
210
- const requestId = `refresh_${randomUUID()}`;
211
- const lockAcquired = await acquireRefreshLock(sessionToken, requestId, 5000);
212
-
213
- let weAcquiredLock = false;
214
- let releaseLockVersion: number | undefined;
215
-
216
- if (!lockAcquired.acquired) {
217
- {
218
- // Wait for the lock to release, then check if token is now fresh
219
- console.info('[AUTH_REFRESH] Refresh in progress by another request, waiting for completion...', { requestId, traceId });
220
-
221
- const maxWaitMs = 5000;
222
- const checkIntervalMs = 200;
223
- const startWait = Date.now();
224
-
225
- while (Date.now() - startWait < maxWaitMs) {
226
- await new Promise(resolve => setTimeout(resolve, checkIntervalMs));
227
-
228
- // Check if lock was released
229
- const lockCheck = await checkRefreshLock(sessionToken);
230
- if (!lockCheck) {
231
- // Lock released - check if token is now fresh
232
- const refreshedSession = await getSession(sessionToken);
233
- if (refreshedSession?.idpAccessToken && refreshedSession?.idpAccessTokenExpires) {
234
- const timeUntilExpiry = refreshedSession.idpAccessTokenExpires - Date.now();
235
- const fiveMinutes = 5 * 60 * 1000;
236
-
237
- if (timeUntilExpiry > fiveMinutes) {
238
- console.info('[AUTH_REFRESH] Lock released, token is fresh - returning success', {
239
- requestId,
240
- accessTokenExpires: new Date(refreshedSession.idpAccessTokenExpires).toISOString(),
241
- waitedMs: Date.now() - startWait,
242
- });
243
- return NextResponse.json({
244
- refreshed: true,
245
- reason: 'completed_by_concurrent_request',
246
- accessTokenExpires: refreshedSession.idpAccessTokenExpires,
247
- hasRefreshToken: !!refreshedSession.idpRefreshToken,
248
- });
249
- }
250
- }
251
- // Lock released but token not fresh - try to acquire lock ourselves
252
- break;
253
- }
254
- }
255
-
256
- // Still locked after waiting - return 409
257
- console.warn('[AUTH_REFRESH] Refresh still in progress after waiting', { requestId, waitedMs: Date.now() - startWait });
258
- return NextResponse.json({
259
- error: 'Refresh already in progress',
260
- code: 'CONFLICT'
261
- }, { status: 409 });
262
- }
263
- } else {
264
- weAcquiredLock = true;
265
- releaseLockVersion = lockAcquired.lockInfo?.lockVersion;
266
- }
267
-
268
- // Before performing network refresh, re-check if tokens are already fresh
269
- const latestAfterLock = await getSession(sessionToken);
270
- const fiveMinutes = 5 * 60 * 1000;
271
- const timeUntilExpiry = latestAfterLock?.idpAccessTokenExpires
272
- ? latestAfterLock.idpAccessTokenExpires - Date.now()
273
- : -1;
274
-
275
- // CRITICAL: Also check the actual JWT's exp claim - Redis might have stale data
276
- let actualJwtExpMs = -1;
277
- let tokenMismatch = false;
278
- if (latestAfterLock?.idpAccessToken) {
279
- try {
280
- const tokenParts = latestAfterLock.idpAccessToken.split('.');
281
- if (tokenParts.length === 3) {
282
- const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString());
283
- actualJwtExpMs = (payload.exp || 0) * 1000;
284
- const now = Date.now();
285
- // If the actual JWT is expired, we MUST refresh regardless of what Redis says
286
- if (actualJwtExpMs < now) {
287
- tokenMismatch = true;
288
- }
289
- }
290
- } catch (e) {
291
- // If we can't decode, proceed with normal logic
292
- }
293
- }
294
-
295
- console.log('[AUTH_REFRESH] Pre-refresh check:', {
296
- userId,
297
- hasAccessToken: !!latestAfterLock?.idpAccessToken,
298
- accessTokenExpires: latestAfterLock?.idpAccessTokenExpires
299
- ? new Date(latestAfterLock.idpAccessTokenExpires).toISOString()
300
- : 'undefined',
301
- actualJwtExp: actualJwtExpMs > 0 ? new Date(actualJwtExpMs).toISOString() : 'unknown',
302
- now: new Date().toISOString(),
303
- timeUntilExpiryMs: timeUntilExpiry,
304
- tokenMismatch,
305
- willRefresh: timeUntilExpiry <= fiveMinutes || tokenMismatch
306
- });
307
-
308
- // Only skip refresh if BOTH Redis says fresh AND the actual JWT is not expired
309
- if (latestAfterLock?.idpAccessToken && latestAfterLock?.idpAccessTokenExpires &&
310
- timeUntilExpiry > fiveMinutes && !tokenMismatch) {
311
- console.info('[AUTH_REFRESH] Skipping refresh: tokens already fresh', { userId, timeUntilExpiryMs: timeUntilExpiry });
312
- if (weAcquiredLock) {
313
- await releaseRefreshLock(sessionToken, requestId, releaseLockVersion);
314
- weAcquiredLock = false;
315
- }
316
- return NextResponse.json({
317
- refreshed: false,
318
- reason: 'already_fresh',
319
- accessTokenExpires: latestAfterLock.idpAccessTokenExpires,
320
- hasRefreshToken: !!latestAfterLock.idpRefreshToken,
321
- });
322
- }
323
-
324
- // If we detected a token mismatch, log it prominently
325
- if (tokenMismatch) {
326
- console.warn('[AUTH_REFRESH] Token mismatch detected - forcing refresh despite Redis claiming fresh', {
327
- userId,
328
- redisExpires: latestAfterLock?.idpAccessTokenExpires ? new Date(latestAfterLock.idpAccessTokenExpires).toISOString() : 'N/A',
329
- actualJwtExp: new Date(actualJwtExpMs).toISOString()
330
- });
331
- }
332
-
333
- // Copy refresh token for use in IDP call
334
- // Note: Token is NOT cleared preemptively - it will be replaced on success.
335
- // The lock mechanism prevents concurrent refresh attempts within the same session.
336
- // If IDP call fails, user can retry with the same token.
337
- // 4.9.0 (BAPert 76298 (b2), 76330): the token we SEND is the one read AFTER the lock was taken (`latestAfterLock`), and it is the ONLY
338
- // source: there is NO fallback to `currentSession`, which was read BEFORE the lock. Between those reads another request can rotate the
339
- // refresh token (sending the pre-lock value would send a SPENT token) or DISCARD it (the IdP answered 401 for it; re-sending it is a
340
- // reuse). The IdP treats reuse as compromise and revokes descendants across devices. So:
341
- // - the post-lock read has NO ROW: the session vanished while we waited; it is not ours to refresh -> the 'No session' 401, no IdP call
342
- // - the row has NO refresh token: -> the same terminal NO_REFRESH_TOKEN as the pre-lock guard, no IdP call; the row is left exactly as
343
- // it is (a discard marker stays on it)
344
- // (A row whose access token is still fresh was answered `already_fresh` above and never reaches here.)
345
- if (!latestAfterLock) {
346
- console.warn('[AUTH_REFRESH] Session vanished while waiting for the refresh lock; not refreshing', { userId });
347
- if (weAcquiredLock) {
348
- await releaseRefreshLock(sessionToken, requestId, releaseLockVersion);
349
- weAcquiredLock = false;
350
- }
351
- return NextResponse.json({
352
- error: 'No session available for refresh',
353
- code: 'UNAUTHORIZED'
354
- }, { status: 401 });
355
- }
356
- if (!latestAfterLock.idpRefreshToken) {
357
- console.warn('[AUTH_REFRESH] No refresh token after the lock was taken; not calling the IdP', { userId });
358
- if (weAcquiredLock) {
359
- await releaseRefreshLock(sessionToken, requestId, releaseLockVersion);
360
- weAcquiredLock = false;
361
- }
362
- return NextResponse.json({
363
- error: 'No refresh token available',
364
- code: 'NO_REFRESH_TOKEN',
365
- terminal: true,
366
- resolution: 'User must re-authenticate'
367
- }, { status: 401 });
368
- }
369
- const originalRefreshToken = latestAfterLock.idpRefreshToken as string;
370
- // The base of everything WRITTEN BACK after a successful exchange is the same post-lock read (BAPert 76318 item 4): writing
371
- // `...currentSession` over a rotated row would put a SPENT token back. With no new refresh token from the IdP the stored token is the
372
- // one that was SENT (`originalRefreshToken`).
373
- const baseSession = latestAfterLock;
374
-
375
- try {
376
- // Extract 2FA claims from current session
377
- let authMethods: string[] = [];
378
- if (currentSession.authenticationMethods) {
379
- if (typeof currentSession.authenticationMethods === 'string') {
380
- try {
381
- authMethods = JSON.parse(currentSession.authenticationMethods);
382
- } catch (e) {
383
- console.warn('[AUTH_REFRESH] Failed to parse authenticationMethods', { authenticationMethods: currentSession.authenticationMethods });
384
- }
385
- } else if (Array.isArray(currentSession.authenticationMethods)) {
386
- authMethods = currentSession.authenticationMethods;
387
- }
388
- }
389
-
390
- // For OAuth sessions with empty AMR claims, provide defaults
391
- // OAuth IS a form of multi-factor auth (you authenticated with another provider)
392
- let isOAuthSession = !!currentSession.oauthProvider;
393
- if (authMethods.length === 0 && isOAuthSession) {
394
- // OAuth sessions get default AMR claims
395
- authMethods = ['pwd', 'mfa'];
396
- console.log('[AUTH_REFRESH] OAuth session with empty AMR - using defaults:', {
397
- oauthProvider: currentSession.oauthProvider,
398
- defaultAmr: authMethods
399
- });
400
- }
401
-
402
- // Check authMethods first, then fallback to twoFactorMethod field (set by transitionTo2FASession)
403
- // For OAuth sessions, use 'oauth' as the 2FA method since OAuth itself is the authentication
404
- const twoFactorMethod = authMethods.find(m => ['sms', 'totp', 'email'].includes(m))
405
- || currentSession.mfaMethod
406
- || (isOAuthSession ? 'oauth' : null);
407
-
408
- // DEBUG: Log what we have for 2FA
409
- console.log('[AUTH_REFRESH] 2FA Debug:', {
410
- authMethods,
411
- authMethodsRaw: currentSession.authenticationMethods,
412
- twoFactorMethodFromSession: currentSession.mfaMethod,
413
- twoFactorMethodResolved: twoFactorMethod,
414
- twoFactorComplete: currentSession.mfaVerified,
415
- sessionKeys: Object.keys(currentSession)
416
- });
417
-
418
- // Build refresh request body per PayEz wire standard (snake_case)
419
- // See: 2FA-TOKEN-REFRESH-CONTEXT.md - "The Ninja Shit"
420
- // For OAuth sessions with 2FA complete, use ACR level 2
421
- let acrValue = String(currentSession.authenticationLevel ?? '1');
422
- if (currentSession.oauthProvider && currentSession.mfaVerified && acrValue === '1') {
423
- acrValue = '2'; // OAuth with 2FA complete = full authentication
424
- }
425
- const refreshRequestBody: any = {
426
- refresh_token: originalRefreshToken,
427
- amr: authMethods,
428
- acr: acrValue
429
- };
430
-
431
- // DEBUG: Log exact request body
432
- console.log('[AUTH_REFRESH] Request body:', JSON.stringify({
433
- refresh_token: '***REDACTED***',
434
- amr: authMethods,
435
- acr: acrValue,
436
- acrType: typeof acrValue
437
- }));
438
-
439
- const twoFactorVerified = !!currentSession.mfaVerified;
440
- if (twoFactorVerified) {
441
- refreshRequestBody.two_factor_verified = true;
442
- }
443
- if (twoFactorMethod) {
444
- refreshRequestBody.two_factor_method = twoFactorMethod;
445
- }
446
- if (currentSession.mfaCompletedAt) {
447
- refreshRequestBody.two_factor_completed_at = new Date(currentSession.mfaCompletedAt).toISOString();
448
- }
449
-
450
- // Log the full request details for debugging
451
- console.log('[AUTH_REFRESH] Sending refresh request:', {
452
- url: `${idpBaseUrl}${refreshEndpoint}`,
453
- clientId,
454
- hasRefreshToken: !!refreshRequestBody.refresh_token,
455
- refreshTokenLength: refreshRequestBody.refresh_token?.length,
456
- amr: refreshRequestBody.amr,
457
- acr: refreshRequestBody.acr
458
- });
459
-
460
- let refreshResponse: Response;
461
- try {
462
- refreshResponse = await fetch(`${idpBaseUrl}${refreshEndpoint}`, {
463
- method: 'POST',
464
- headers: {
465
- 'Content-Type': 'application/json',
466
- 'X-Client-Id': clientId,
467
- },
468
- body: JSON.stringify(refreshRequestBody),
469
- });
470
- } catch (fetchError) {
471
- // Network error - IDP unreachable
472
- // Note: Lock will be released by finally block
473
- console.error('[AUTH_REFRESH] IDP unreachable:', {
474
- error: fetchError instanceof Error ? fetchError.message : String(fetchError),
475
- idpUrl: idpBaseUrl,
476
- userId
477
- });
478
- return NextResponse.json({
479
- error: 'IDP service unavailable',
480
- code: 'UPSTREAM_SERVICE_UNAVAILABLE',
481
- retryable: true,
482
- discardToken: false
483
- }, { status: 503 });
484
- }
485
-
486
- // Parse response body - handle empty or invalid JSON
487
- let responseData: any;
488
- try {
489
- const responseText = await refreshResponse.text();
490
- if (!responseText || responseText.trim() === '') {
491
- // Note: Lock will be released by finally block
492
- console.error('[AUTH_REFRESH] Empty response from IDP:', {
493
- status: refreshResponse.status,
494
- statusText: refreshResponse.statusText,
495
- userId
496
- });
497
- return NextResponse.json({
498
- error: 'Empty response from IDP',
499
- code: 'UPSTREAM_SERVICE_ERROR',
500
- retryable: true,
501
- discardToken: false
502
- }, { status: 502 });
503
- }
504
- responseData = JSON.parse(responseText);
505
- } catch (parseError) {
506
- // Note: Lock will be released by finally block
507
- console.error('[AUTH_REFRESH] Failed to parse IDP response:', {
508
- error: parseError instanceof Error ? parseError.message : String(parseError),
509
- status: refreshResponse.status,
510
- userId
511
- });
512
- return NextResponse.json({
513
- error: 'Invalid response from IDP',
514
- code: 'UPSTREAM_SERVICE_ERROR',
515
- retryable: true,
516
- discardToken: false
517
- }, { status: 502 });
518
- }
519
-
520
- // Handle non-OK responses with structured error format
521
- if (!refreshResponse.ok) {
522
- // Parse structured error from IDP
523
- const idpError = responseData?.error || {};
524
- const errorCode = idpError.code || 'UNKNOWN_ERROR';
525
- const errorMessage = idpError.message || 'Token refresh failed';
526
- // CRITICAL: 401 means token is definitively invalid - always discard
527
- // This prevents redirect loops where viability check keeps returning canRefresh:true
528
- let discardToken = refreshResponse.status === 401 || idpError.discard_token === true;
529
- const retryable = refreshResponse.status !== 401 && idpError.retryable === true;
530
- const resolution = idpError.resolution || null;
128
+ // The caller's x-request-id is TRACE ONLY (E keeps it as `traceId` for logs); the lock identity is minted inside E.
129
+ const traceId = sanitizeTraceId(req.headers.get('x-request-id'));
531
130
 
532
- // ============================================================================
533
- // HIGH VISIBILITY: REFRESH TOKEN FAILURE DIAGNOSTICS
534
- // ============================================================================
535
- // Translate error codes to human-readable explanations
536
- const failureReasons: Record<string, string> = {
537
- 'UNAUTHORIZED': 'Token was already used (rotation) OR token is expired OR token was revoked',
538
- 'INVALID_REFRESH_TOKEN': 'Token format invalid OR token not found in IDP database',
539
- 'TOKEN_EXPIRED': 'Refresh token exceeded its max lifetime',
540
- 'TOKEN_REVOKED': 'Token was explicitly revoked (logout, password change, admin action)',
541
- 'TOKEN_REUSE_DETECTED': 'Same refresh token used twice - possible token theft, all tokens revoked',
542
- 'UPSTREAM_SERVICE_ERROR': 'IDP internal error - token may have been rotated before failure',
543
- 'INTERNAL_ERROR': 'IDP internal error - check IDP logs for details',
544
- 'RATE_LIMITED': 'Too many refresh attempts - try again later',
545
- };
131
+ const result = await ensureFreshAccessToken(
132
+ sessionToken,
133
+ { idpBaseUrl, clientId, refreshEndpoint },
134
+ { requestId: traceId, requireRefreshToken: true },
135
+ );
546
136
 
547
- const whyItFailed = failureReasons[errorCode] || 'Unknown error - check IDP logs';
548
-
549
- console.error('╔══════════════════════════════════════════════════════════════════════════════╗');
550
- console.error('║ ❌ REFRESH TOKEN FAILURE - DIAGNOSTIC REPORT ║');
551
- console.error('╠══════════════════════════════════════════════════════════════════════════════╣');
552
- console.error(`║ HTTP Status: ${String(refreshResponse.status).padEnd(60)}║`);
553
- console.error(`║ Error Code: ${errorCode.padEnd(60)}║`);
554
- console.error(`║ Discard Token: ${String(discardToken).padEnd(60)}║`);
555
- console.error(`║ Retryable: ${String(retryable).padEnd(60)}║`);
556
- console.error('╠──────────────────────────────────────────────────────────────────────────────╣');
557
- console.error(`║ WHY IT FAILED: ║`);
558
- console.error(`║ ${whyItFailed.substring(0, 76).padEnd(76)} ║`);
559
- console.error('╠──────────────────────────────────────────────────────────────────────────────╣');
560
- console.error(`║ User: ${(userId || 'unknown').substring(0, 60).padEnd(60)}║`);
561
- console.error(`║ Session: ${tokenLogId(sessionToken)} ║`);
562
- console.error(`║ Resolution: ${(resolution || 'Check IDP logs').substring(0, 60).padEnd(60)}║`);
563
- console.error('╚══════════════════════════════════════════════════════════════════════════════╝');
564
-
565
- // NEVER the raw envelope (DotNetPert-Scout, PR 139 review / mail 58691): this used to print
566
- // a stringified dump of responseData (first 1000 chars) - the same whole IDP body the :618
567
- // "unsuccessful" branch stopped logging. The box above already carries status, code and
568
- // flags; add envelope SHAPE only (key names), never values.
569
- console.error('[AUTH_REFRESH] IDP error response shape', {
570
- bodyKeys: responseData && typeof responseData === 'object' ? Object.keys(responseData) : undefined,
571
- errorKeys: idpError && typeof idpError === 'object' ? Object.keys(idpError) : undefined,
572
- errorHasMessage: !!idpError.message,
573
- });
574
-
575
- // If IDP signals to discard token, clear it from Redis
576
- if (discardToken) {
577
- // Race-safe discard (CAS): only clear if the refresh token we sent is STILL
578
- // the current one. A concurrent refresh may have already rotated it — our 401
579
- // is then stale, and wiping here would silently log out a healthy session
580
- // (the rotation-race wipe, QA 6873 site 2). Skip the wipe + drop terminal if changed.
581
- const postRefresh = await getSession(sessionToken);
582
- const tokenUnchanged =
583
- !!originalRefreshToken && postRefresh?.idpRefreshToken === originalRefreshToken;
584
- if (tokenUnchanged) {
585
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP signaled discard_token', {
586
- reason: 'IDP_DISCARD_TOKEN',
587
- errorCode,
588
- userId,
589
- sessionToken: tokenLogId(sessionToken),
590
- hadRefreshToken: !!currentSession.idpRefreshToken,
591
- stack: new Error().stack
592
- });
593
- await updateSession(sessionToken, {
594
- idpRefreshToken: '',
595
- idpRefreshTokenExpires: undefined,
596
- refreshTokenClearedAt: Date.now(),
597
- refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${errorCode}`
598
- });
599
- } else {
600
- // Concurrent refresh already rotated the token — our 401 is stale. Return the
601
- // freshly-rotated token directly so the loser succeeds without a retry
602
- // (race-fix follow-up #1).
603
- discardToken = false;
604
- console.warn('[AUTH_REFRESH] Discard suppressed: refresh token already rotated by a concurrent refresh — returning the fresh token (race-safe).');
605
- if (rotatedRowIsUsable(postRefresh)) {
606
- return NextResponse.json({
607
- refreshed: true,
608
- reason: 'completed_by_concurrent_request',
609
- accessTokenExpires: postRefresh.idpAccessTokenExpires,
610
- hasRefreshToken: !!postRefresh.idpRefreshToken,
611
- });
612
- }
613
- // Rotated by a concurrent refresh but the row it left is NOT usable (BAPert 76359): the retryable 502, the rotated token kept,
614
- // no marker. Same meaning in every branch (lib/refresh-rotation).
615
- return NextResponse.json({
616
- error: errorMessage,
617
- code: errorCode,
618
- discardToken: false,
619
- retryable: true,
620
- resolution,
621
- status: 502
622
- }, { status: 502 });
623
- }
624
- }
625
-
626
- return NextResponse.json({
627
- error: errorMessage,
628
- code: errorCode,
629
- discardToken,
630
- retryable,
631
- resolution,
632
- status: refreshResponse.status
633
- }, { status: refreshResponse.status });
634
- }
635
-
636
- // Validate PayEz canonical envelope for success responses
637
- const isCompliant = responseData && typeof responseData === 'object' &&
638
- Object.prototype.hasOwnProperty.call(responseData, 'success') &&
639
- (responseData.success === true ? Object.prototype.hasOwnProperty.call(responseData, 'data') : Object.prototype.hasOwnProperty.call(responseData, 'error')) &&
640
- Object.prototype.hasOwnProperty.call(responseData, 'meta');
641
-
642
- if (!isCompliant) {
643
- // NEVER the raw body (DotNetPert-Scout, mail 58678): a non-compliant response has an
644
- // UNKNOWN shape by definition, so there is no basis to assume it is free of tokens or
645
- // other IDP-side secrets. Log shape metadata only - same "kind, never value" reasoning
646
- // as the session-store.ts / refresh.ts REFRESH_TOKEN_REMOVAL fixes in PR 138.
647
- console.error('[AUTH_REFRESH] Upstream non-compliant IDP response', {
648
- bodyType: typeof responseData,
649
- bodyKeys: responseData && typeof responseData === 'object' ? Object.keys(responseData) : undefined,
650
- hasSuccessKey: !!(responseData && typeof responseData === 'object' && Object.prototype.hasOwnProperty.call(responseData, 'success')),
651
- hasMetaKey: !!(responseData && typeof responseData === 'object' && Object.prototype.hasOwnProperty.call(responseData, 'meta')),
652
- });
653
- return NextResponse.json({
654
- error: 'Upstream non-compliance',
655
- code: 'UPSTREAM_SERVICE_ERROR',
656
- retryable: true,
657
- discardToken: false
658
- }, { status: 502 });
659
- }
660
-
661
- if (responseData.success !== true || !responseData.data) {
662
- // Handle success:false with structured error
663
- const idpError = responseData?.error || {};
664
- const errorCode = idpError.code || 'UPSTREAM_VALIDATION_ERROR';
665
- const discardToken = idpError.discard_token === true;
666
- const retryable = idpError.retryable === true;
667
-
668
- // NEVER the raw envelope (DotNetPert-Scout, mail 58678): `responseData` here is the
669
- // WHOLE IDP response body, and its `error` sub-object's contents are not something this
670
- // handler controls or has audited - printing it wholesale would ship whatever the IDP
671
- // decided to put there straight to the log sink. Log the fields THIS handler already
672
- // extracts and acts on (retryable, plus envelope-shape flags for diagnosis) instead.
673
- console.warn('[AUTH_REFRESH] IDP refresh unsuccessful', {
674
- code: errorCode,
675
- discardToken,
676
- retryable,
677
- errorHasMessage: !!idpError.message,
678
- errorKeys: Object.keys(idpError),
679
- });
680
-
681
- // 4.9.0 (BAPert 76298 (c)): ONE IdP answer, ONE meaning, in both refresh implementations. This branch used to answer the upstream
682
- // status, i.e. HTTP 200, with an error body, so `internalRefresh` reported `ok` and idpFetchJSON's 401-retry trusted a refresh that
683
- // had failed; and it wrote a DIFFERENT marker (IDP_SUCCESS_FALSE_DISCARD) than the IdP-401 branch, which the logout dead-grant check
684
- // does not recognise. Now:
685
- // success:false + discard_token -> the stored token is discarded (same CAS as the 401 branch) with the IDP_DISCARD_TOKEN marker, and the
686
- // answer is 401 (never 200 with an error body)
687
- // success:false, no discard_token -> 502 retryable, the token is KEPT
688
- if (discardToken) {
689
- const postRefresh = await getSession(sessionToken);
690
- const tokenUnchanged = !!originalRefreshToken && postRefresh?.idpRefreshToken === originalRefreshToken;
691
- if (tokenUnchanged) {
692
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP success:false with discard_token', {
693
- reason: 'IDP_DISCARD_TOKEN',
694
- errorCode,
695
- userId,
696
- sessionToken: tokenLogId(sessionToken),
697
- hadRefreshToken: !!currentSession.idpRefreshToken,
698
- stack: new Error().stack
699
- });
700
- await updateSession(sessionToken, {
701
- idpRefreshToken: '',
702
- idpRefreshTokenExpires: undefined,
703
- refreshTokenClearedAt: Date.now(),
704
- refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${errorCode}`
705
- });
706
- return NextResponse.json({
707
- error: idpError.message || 'Token refresh failed',
708
- code: errorCode,
709
- discardToken: true,
710
- retryable: false,
711
- resolution: idpError.resolution || null,
712
- status: 401
713
- }, { status: 401 });
714
- }
715
- // A concurrent refresh already rotated the token: ours is stale. Return the fresh tokens if there are any (as the 401 branch does).
716
- if (rotatedRowIsUsable(postRefresh)) {
717
- return NextResponse.json({
718
- refreshed: true,
719
- reason: 'completed_by_concurrent_request',
720
- accessTokenExpires: postRefresh.idpAccessTokenExpires,
721
- hasRefreshToken: !!postRefresh.idpRefreshToken,
722
- });
723
- }
724
- }
725
-
726
- return NextResponse.json({
727
- error: idpError.message || 'Token refresh failed',
728
- code: errorCode,
729
- discardToken: false,
730
- retryable: true,
731
- resolution: idpError.resolution || null,
732
- status: 502
733
- }, { status: 502 });
734
- }
735
-
736
- // Extract tokens from response
737
- const payload = responseData.data as any;
738
- const accessToken = payload?.access_token;
739
- const refreshToken = payload?.refresh_token;
740
-
741
- if (!accessToken) {
742
- console.error('[AUTH_REFRESH] Missing access token in IDP response');
743
- return NextResponse.json({
744
- error: 'Invalid token response from IDP',
745
- code: 'INTERNAL_SERVER_ERROR'
746
- }, { status: 500 });
747
- }
748
-
749
- // Decode and compute token expiries
750
- let decodedAccessToken: any;
751
- let accessTokenExpires: number;
752
- let computedRefreshTokenExpires: number | undefined;
753
- try {
754
- const result = computeTokenExpiries({ accessToken, refreshToken, preferJwt: true });
755
- decodedAccessToken = result.decodedAccessToken;
756
- accessTokenExpires = result.accessTokenExpires;
757
- computedRefreshTokenExpires = result.refreshTokenExpires;
758
-
759
- console.info('[AUTH_REFRESH] Successfully decoded new token pair', {
760
- accessTokenExpires: new Date(accessTokenExpires).toISOString(),
761
- refreshTokenExpires: computedRefreshTokenExpires ? new Date(computedRefreshTokenExpires).toISOString() : null
762
- });
763
- } catch (decodeError) {
764
- console.error('[AUTH_REFRESH] Failed to compute token expiries', { error: decodeError });
765
- return NextResponse.json({
766
- error: 'Failed to decode JWT tokens',
767
- code: 'INTERNAL_SERVER_ERROR'
768
- }, { status: 500 });
769
- }
770
-
771
- // Extract 2FA claims from the new access token
772
- let amrClaims: string[] = [];
773
- if (decodedAccessToken.amr) {
774
- try {
775
- amrClaims = typeof decodedAccessToken.amr === 'string'
776
- ? JSON.parse(decodedAccessToken.amr)
777
- : decodedAccessToken.amr;
778
- } catch (e) {
779
- console.warn('[AUTH_REFRESH] Failed to parse AMR claims', { amr: decodedAccessToken.amr });
780
- amrClaims = baseSession.authenticationMethods || [];
781
- }
782
- } else {
783
- amrClaims = baseSession.authenticationMethods || [];
784
- }
785
- const acrLevel = String(decodedAccessToken.acr || baseSession.authenticationLevel || '1');
786
-
787
- // Extract MFA timing claims
788
- const mfaTime = decodedAccessToken.mfa_time ? parseInt(decodedAccessToken.mfa_time) * 1000 : baseSession.mfaCompletedAt;
789
- const mfaExpires = decodedAccessToken.mfa_expires ? parseInt(decodedAccessToken.mfa_expires) * 1000 : baseSession.mfaExpiresAt;
790
- const mfaValidityHours = decodedAccessToken.mfa_validity_hours ? parseInt(decodedAccessToken.mfa_validity_hours) : baseSession.mfaValidityHours;
791
-
792
- // Update session with new tokens
793
- const hasNewRefresh = typeof refreshToken === 'string' && refreshToken.length > 0;
794
- const newRefreshTokenExpires = hasNewRefresh ? computedRefreshTokenExpires : undefined;
795
-
796
- // CRITICAL: Log if we're about to clear the refresh token due to missing new token
797
- if (!hasNewRefresh && baseSession.idpRefreshToken) {
798
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: No new refresh token in IDP response', {
799
- reason: 'NO_NEW_REFRESH_TOKEN_IN_RESPONSE',
800
- userId,
801
- sessionToken: tokenLogId(sessionToken),
802
- hadRefreshToken: true,
803
- // Kind only, never the value (credential). This branch runs when refreshToken is not a
804
- // non-empty string, so the old raw value was almost always empty - but a token-shaped
805
- // non-string would have been printed. refreshTokenType below already carries the kind.
806
- refreshTokenFromResponsePresent: refreshToken !== undefined && refreshToken !== null && refreshToken !== '',
807
- refreshTokenType: typeof refreshToken,
808
- payloadKeys: Object.keys(payload || {}),
809
- stack: new Error().stack
810
- });
811
- }
812
-
813
- // Keep existing refresh token if IDP doesn't provide a new one
814
- // Only clear if IDP explicitly signals discard_token=true (handled in error paths)
815
- // NOTE: Use normalized field names (idp* prefix) per SessionData interface
816
-
817
- // CRITICAL: Extract kid from JWT header - IDP may rotate keys during refresh
818
- const newBearerKeyId = extractKidFromToken(accessToken);
819
- if (newBearerKeyId) {
820
- console.log('[AUTH_REFRESH] Extracted bearerKeyId (kid) from new JWT header:', newBearerKeyId);
821
- } else {
822
- console.warn('[AUTH_REFRESH] No kid found in new JWT header');
823
- }
824
-
825
- const sessionUpdate: any = {
826
- ...baseSession,
827
- idpAccessToken: accessToken,
828
- idpAccessTokenExpires: accessTokenExpires,
829
- idpRefreshToken: hasNewRefresh ? (refreshToken as string) : originalRefreshToken,
830
- idpRefreshTokenExpires: hasNewRefresh ? newRefreshTokenExpires : baseSession.idpRefreshTokenExpires,
831
- decodedAccessToken: decodedAccessToken,
832
- // Bearer key ID from JWT header (may change on key rotation)
833
- bearerKeyId: newBearerKeyId || baseSession.bearerKeyId,
834
- authenticationMethods: amrClaims,
835
- authenticationLevel: acrLevel,
836
- // 170007 rule 2 (BAPert ruling on 121350): '||' is the wrong operator
837
- // for a fact with an expiry. mfaVerified is derived from amrClaims,
838
- // which is FRESH every exchange (decoded from the token just
839
- // returned, falling back to the prior session's amr only on a
840
- // genuine decode failure a few lines up — not on "this token
841
- // doesn't currently carry mfa"). ORing in currentSession.mfaVerified
842
- // made the flag MONOTONIC against a claim that DECAYS (mfa_time,
843
- // 10 minutes): once true, it stayed true forever regardless of
844
- // what the current token actually says, silently re-opening the
845
- // 2FA bypass with no bug in the bridge. Re-derive only.
846
- mfaVerified: amrClaims.includes('mfa'),
847
- mfaCompletedAt: mfaTime,
848
- mfaExpiresAt: mfaExpires,
849
- mfaValidityHours: mfaValidityHours
850
- };
851
-
852
- await updateSession(sessionToken, sessionUpdate);
853
-
854
- console.info('[AUTH_REFRESH] Token refreshed successfully', {
855
- expiresAt: new Date(accessTokenExpires).toISOString(),
856
- userId,
857
- hasNewRefreshToken: hasNewRefresh,
858
- hasAccessToken: !!accessToken // PAY-1427: was tokenPreview (first 20 chars of the new access token)
859
- });
860
-
861
- } catch (error) {
862
- console.error('[AUTH_REFRESH] Error during token refresh', { error });
863
- return NextResponse.json({
864
- error: 'Token refresh error',
865
- code: 'INTERNAL_SERVER_ERROR'
866
- }, { status: 500 });
867
- } finally {
868
- if (weAcquiredLock) {
869
- await releaseRefreshLock(sessionToken, requestId, releaseLockVersion);
870
- }
871
- }
872
-
873
- // Load the latest session to return basic status
874
- const latest = await getSession(sessionToken);
875
- if (!latest?.idpAccessToken) {
876
- return NextResponse.json({
877
- error: 'No access token after refresh',
878
- code: 'INTERNAL_SERVER_ERROR'
879
- }, { status: 500 });
880
- }
137
+ if (!result.ok) return failureResponse(result);
881
138
 
139
+ // The access token is deliberately NOT in this body (E's result carries it; this route never returns it).
882
140
  return NextResponse.json({
883
- refreshed: true,
884
- accessTokenExpires: latest.idpAccessTokenExpires,
885
- hasRefreshToken: !!latest.idpRefreshToken,
141
+ refreshed: result.refreshed,
142
+ // The route's bodies carried a `reason` for two cases only; a plain refresh had none.
143
+ ...(result.reason === 'refreshed' ? {} : { reason: result.reason }),
144
+ accessTokenExpires: result.accessTokenExpires,
145
+ hasRefreshToken: result.hasRefreshToken,
886
146
  });
887
147
  } catch (err: any) {
888
148
  console.error('[AUTH_REFRESH] Unexpected error', { error: err?.message || String(err) });