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