@payez/next-mvp 3.9.0 → 4.0.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 (149) hide show
  1. package/dist/api/auth-handler.d.ts +1 -2
  2. package/dist/api/auth-handler.js +9 -9
  3. package/dist/api-handlers/account/change-password.js +110 -112
  4. package/dist/api-handlers/admin/analytics.d.ts +19 -20
  5. package/dist/api-handlers/admin/analytics.js +378 -379
  6. package/dist/api-handlers/admin/audit.d.ts +19 -20
  7. package/dist/api-handlers/admin/audit.js +213 -214
  8. package/dist/api-handlers/admin/index.d.ts +21 -22
  9. package/dist/api-handlers/admin/index.js +42 -43
  10. package/dist/api-handlers/admin/redis-sessions.d.ts +35 -36
  11. package/dist/api-handlers/admin/redis-sessions.js +203 -204
  12. package/dist/api-handlers/admin/sessions.d.ts +20 -21
  13. package/dist/api-handlers/admin/sessions.js +283 -284
  14. package/dist/api-handlers/admin/site-logs.d.ts +45 -46
  15. package/dist/api-handlers/admin/site-logs.js +317 -318
  16. package/dist/api-handlers/admin/stats.d.ts +20 -21
  17. package/dist/api-handlers/admin/stats.js +239 -240
  18. package/dist/api-handlers/admin/users.d.ts +19 -20
  19. package/dist/api-handlers/admin/users.js +221 -222
  20. package/dist/api-handlers/admin/vibe-data.d.ts +79 -80
  21. package/dist/api-handlers/admin/vibe-data.js +267 -268
  22. package/dist/api-handlers/auth/refresh.js +633 -635
  23. package/dist/api-handlers/auth/signout.js +186 -187
  24. package/dist/api-handlers/auth/status.js +4 -7
  25. package/dist/api-handlers/auth/update-session.d.ts +1 -1
  26. package/dist/api-handlers/auth/update-session.js +12 -14
  27. package/dist/api-handlers/auth/verify-code.d.ts +43 -43
  28. package/dist/api-handlers/auth/verify-code.js +90 -94
  29. package/dist/api-handlers/session/viability.js +114 -146
  30. package/dist/api-handlers/test/force-expire.js +59 -65
  31. package/dist/auth/auth-decision.js +182 -182
  32. package/dist/auth/better-auth.d.ts +3 -6
  33. package/dist/auth/better-auth.js +3 -6
  34. package/dist/auth/route-config.js +2 -2
  35. package/dist/auth/utils/token-utils.d.ts +83 -84
  36. package/dist/auth/utils/token-utils.js +218 -219
  37. package/dist/client/AuthContext.js +115 -112
  38. package/dist/client/better-auth-client.d.ts +1020 -961
  39. package/dist/client/better-auth-client.js +54 -7
  40. package/dist/client/fetch-with-auth.js +2 -2
  41. package/dist/components/SessionSync.js +121 -119
  42. package/dist/components/account/MobileNavDrawer.js +64 -64
  43. package/dist/components/account/UserAvatarMenu.js +91 -88
  44. package/dist/components/admin/VibeAdminLayout.js +71 -69
  45. package/dist/hooks/useAuth.js +9 -7
  46. package/dist/hooks/useAuthSettings.js +93 -93
  47. package/dist/hooks/useAvailableProviders.d.ts +43 -45
  48. package/dist/hooks/useAvailableProviders.js +112 -108
  49. package/dist/hooks/useSessionExpiration.d.ts +2 -3
  50. package/dist/hooks/useSessionExpiration.js +2 -2
  51. package/dist/hooks/useViabilitySession.js +3 -2
  52. package/dist/index.js +4 -6
  53. package/dist/lib/app-slug.d.ts +95 -95
  54. package/dist/lib/app-slug.js +172 -172
  55. package/dist/lib/standardized-client-api.js +10 -5
  56. package/dist/lib/startup-init.js +21 -25
  57. package/dist/lib/test-aware-get-token.js +86 -81
  58. package/dist/lib/token-lifecycle.d.ts +78 -52
  59. package/dist/lib/token-lifecycle.js +360 -398
  60. package/dist/pages/admin-login/page.js +73 -83
  61. package/dist/pages/client-admin/ClientSiteAdminPage.js +179 -177
  62. package/dist/pages/login/page.js +202 -211
  63. package/dist/pages/showcase/ShowcasePage.js +142 -140
  64. package/dist/pages/test-env/EmergencyLogoutPage.js +99 -98
  65. package/dist/pages/test-env/JwtInspectPage.js +116 -114
  66. package/dist/pages/test-env/RefreshTokenPage.js +4 -2
  67. package/dist/pages/test-env/TestEnvPage.js +51 -49
  68. package/dist/pages/verify-code/page.js +412 -408
  69. package/dist/routes/auth/logout.d.ts +31 -31
  70. package/dist/routes/auth/logout.js +98 -113
  71. package/dist/routes/auth/nextauth.d.ts +14 -11
  72. package/dist/routes/auth/nextauth.js +25 -57
  73. package/dist/routes/auth/session.js +157 -179
  74. package/dist/routes/auth/viability.js +190 -201
  75. package/dist/server/auth.d.ts +50 -0
  76. package/dist/server/auth.js +62 -0
  77. package/dist/stores/authStore.js +19 -23
  78. package/dist/utils/logout.js +5 -5
  79. package/package.json +1 -3
  80. package/src/api/auth-handler.ts +550 -549
  81. package/src/api-handlers/account/change-password.ts +5 -8
  82. package/src/api-handlers/admin/analytics.ts +4 -6
  83. package/src/api-handlers/admin/audit.ts +5 -7
  84. package/src/api-handlers/admin/index.ts +1 -2
  85. package/src/api-handlers/admin/redis-sessions.ts +6 -8
  86. package/src/api-handlers/admin/sessions.ts +5 -7
  87. package/src/api-handlers/admin/site-logs.ts +8 -10
  88. package/src/api-handlers/admin/stats.ts +4 -6
  89. package/src/api-handlers/admin/users.ts +5 -7
  90. package/src/api-handlers/admin/vibe-data.ts +10 -12
  91. package/src/api-handlers/auth/refresh.ts +5 -7
  92. package/src/api-handlers/auth/signout.ts +5 -6
  93. package/src/api-handlers/auth/status.ts +4 -7
  94. package/src/api-handlers/auth/update-session.ts +123 -125
  95. package/src/api-handlers/auth/verify-code.ts +9 -13
  96. package/src/api-handlers/session/viability.ts +10 -47
  97. package/src/api-handlers/test/force-expire.ts +4 -11
  98. package/src/auth/auth-decision.ts +1 -1
  99. package/src/auth/better-auth.ts +138 -141
  100. package/src/auth/route-config.ts +219 -219
  101. package/src/auth/utils/token-utils.ts +0 -1
  102. package/src/client/AuthContext.tsx +6 -2
  103. package/src/client/better-auth-client.ts +54 -7
  104. package/src/client/fetch-with-auth.ts +47 -47
  105. package/src/components/SessionSync.tsx +6 -5
  106. package/src/components/account/MobileNavDrawer.tsx +3 -3
  107. package/src/components/account/UserAvatarMenu.tsx +6 -3
  108. package/src/components/admin/VibeAdminLayout.tsx +4 -2
  109. package/src/config/logger.ts +1 -1
  110. package/src/hooks/useAuth.ts +117 -115
  111. package/src/hooks/useAuthSettings.ts +2 -2
  112. package/src/hooks/useAvailableProviders.ts +9 -5
  113. package/src/hooks/useSessionExpiration.ts +101 -102
  114. package/src/hooks/useViabilitySession.ts +336 -335
  115. package/src/index.ts +60 -63
  116. package/src/lib/api-handler.ts +0 -1
  117. package/src/lib/app-slug.ts +6 -6
  118. package/src/lib/standardized-client-api.ts +901 -895
  119. package/src/lib/startup-init.ts +243 -247
  120. package/src/lib/test-aware-get-token.ts +22 -12
  121. package/src/lib/token-lifecycle.ts +12 -53
  122. package/src/pages/admin-login/page.tsx +9 -17
  123. package/src/pages/client-admin/ClientSiteAdminPage.tsx +4 -2
  124. package/src/pages/login/page.tsx +21 -28
  125. package/src/pages/showcase/ShowcasePage.tsx +4 -2
  126. package/src/pages/test-env/EmergencyLogoutPage.tsx +7 -6
  127. package/src/pages/test-env/JwtInspectPage.tsx +5 -3
  128. package/src/pages/test-env/RefreshTokenPage.tsx +157 -155
  129. package/src/pages/test-env/TestEnvPage.tsx +4 -2
  130. package/src/pages/verify-code/page.tsx +10 -6
  131. package/src/routes/auth/logout.ts +7 -25
  132. package/src/routes/auth/nextauth.ts +45 -71
  133. package/src/routes/auth/session.ts +25 -50
  134. package/src/routes/auth/viability.ts +7 -19
  135. package/src/server/auth.ts +60 -0
  136. package/src/stores/authStore.ts +1899 -1904
  137. package/src/utils/logout.ts +30 -30
  138. package/src/auth/auth-options.ts +0 -237
  139. package/src/auth/callbacks/index.ts +0 -7
  140. package/src/auth/callbacks/jwt.ts +0 -382
  141. package/src/auth/callbacks/session.ts +0 -243
  142. package/src/auth/callbacks/signin.ts +0 -56
  143. package/src/auth/events/index.ts +0 -5
  144. package/src/auth/events/signout.ts +0 -33
  145. package/src/auth/providers/credentials.ts +0 -256
  146. package/src/auth/providers/index.ts +0 -6
  147. package/src/auth/providers/oauth.ts +0 -114
  148. package/src/lib/nextauth-secret.ts +0 -121
  149. package/src/types/next-auth.d.ts +0 -15
@@ -1,635 +1,633 @@
1
- "use strict";
2
- /**
3
- * CRITICAL REFRESH TOKEN API HANDLER
4
- *
5
- * ASK BEFORE EDITING - TESTED AND WORKING SYSTEM
6
- *
7
- * This handler manages the server-side refresh token cycle with:
8
- * - NextAuth JWT token extraction
9
- * - Session token fallback for internal calls
10
- * - PayEz IDP refresh token exchange
11
- * - Session state updates with new tokens
12
- * - Proper error handling and logging
13
- * - Single-use semantics enforcement
14
- *
15
- * @version 2.0
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.POST = void 0;
19
- exports.createRefreshHandler = createRefreshHandler;
20
- const server_1 = require("next/server");
21
- const jwt_1 = require("next-auth/jwt");
22
- const session_store_1 = require("../../lib/session-store");
23
- const token_expiry_1 = require("../../lib/token-expiry");
24
- const app_slug_1 = require("../../lib/app-slug");
25
- const token_utils_1 = require("../../auth/utils/token-utils");
26
- /**
27
- * Creates a refresh token handler for Next.js API routes
28
- *
29
- * @param config Configuration for IDP connection and NextAuth
30
- * @returns Next.js POST handler function
31
- *
32
- * @example
33
- * ```typescript
34
- * // In your app's /app/api/auth/refresh/route.ts
35
- * import { createRefreshHandler } from '@payez/next-mvp/api-handlers/auth/refresh';
36
- *
37
- * export const POST = createRefreshHandler({
38
- * idpBaseUrl: process.env.IDP_URL!,
39
- * clientId: process.env.CLIENT_ID!,
40
- * nextAuthSecret: process.env.NEXTAUTH_SECRET!,
41
- * refreshEndpoint: '/api/ExternalAuth/refresh'
42
- * });
43
- * ```
44
- */
45
- function createRefreshHandler(config) {
46
- const { idpBaseUrl, clientId, nextAuthSecret, refreshEndpoint = '/api/ExternalAuth/refresh' } = config;
47
- return async function POST(req) {
48
- try {
49
- // Extract session token from NextAuth JWT
50
- const token = await (0, jwt_1.getToken)({ req, secret: nextAuthSecret, cookieName: (0, app_slug_1.getJwtCookieName)() });
51
- // Support both field names: sessionToken (auth.ts JWT) and redisSessionId (legacy)
52
- let sessionToken = (token?.sessionToken || token?.redisSessionId);
53
- let userId = token?.sub;
54
- if (!sessionToken) {
55
- // Fallback: check for session token in header (for internal server-to-server calls)
56
- const headerSessionToken = req.headers.get('x-session-token');
57
- if (headerSessionToken) {
58
- sessionToken = headerSessionToken;
59
- const currentSession = await (0, session_store_1.getSession)(sessionToken);
60
- userId = currentSession?.userId || currentSession?.email;
61
- }
62
- }
63
- if (!sessionToken || !userId) {
64
- console.warn('[AUTH_REFRESH] Missing sessionToken or user id on token');
65
- return server_1.NextResponse.json({
66
- error: 'No session available for refresh',
67
- code: 'UNAUTHORIZED'
68
- }, { status: 401 });
69
- }
70
- // Get current session
71
- const currentSession = await (0, session_store_1.getSession)(sessionToken);
72
- // NOTE: Field is idpRefreshToken (not refreshToken) per normalized naming convention
73
- if (!currentSession?.idpRefreshToken) {
74
- console.warn('[AUTH_REFRESH] No refresh token available', { userId });
75
- return server_1.NextResponse.json({
76
- error: 'No refresh token available',
77
- code: 'NO_REFRESH_TOKEN', // Terminal state - session cannot be refreshed
78
- terminal: true, // Signal to frontend: don't retry, redirect to login
79
- resolution: 'User must re-authenticate'
80
- }, { status: 401 });
81
- }
82
- // ============================================================================
83
- // HIGH VISIBILITY: PRE-FLIGHT REFRESH DIAGNOSTICS
84
- // ============================================================================
85
- const now = Date.now();
86
- const refreshTokenAge = currentSession.idpRefreshTokenIssuedAt
87
- ? Math.round((now - currentSession.idpRefreshTokenIssuedAt) / 1000)
88
- : 'unknown';
89
- const refreshTokenExpiresIn = currentSession.idpRefreshTokenExpires
90
- ? Math.round((currentSession.idpRefreshTokenExpires - now) / 1000)
91
- : 'unknown';
92
- const accessTokenExpiresIn = currentSession.idpAccessTokenExpires
93
- ? Math.round((currentSession.idpAccessTokenExpires - now) / 1000)
94
- : 'unknown';
95
- console.log('╔══════════════════════════════════════════════════════════════════════════════╗');
96
- console.log('║ REFRESH TOKEN ATTEMPT - PRE-FLIGHT ║');
97
- console.log('╠══════════════════════════════════════════════════════════════════════════════╣');
98
- console.log(`║ User: ${(userId || 'unknown').substring(0, 50).padEnd(50)} ║`);
99
- console.log(`║ Session: ${sessionToken.substring(0, 8)}... ║`);
100
- console.log('╠──────────────────────────────────────────────────────────────────────────────╣');
101
- console.log(`║ Access Token Expires In: ${String(accessTokenExpiresIn).padEnd(10)} seconds ║`);
102
- console.log(`║ Refresh Token Age: ${String(refreshTokenAge).padEnd(10)} seconds ║`);
103
- console.log(`║ Refresh Token Expires In: ${String(refreshTokenExpiresIn).padEnd(10)} seconds ║`);
104
- console.log(`║ Refresh Token Length: ${String(currentSession.idpRefreshToken?.length || 0).padEnd(10)} chars ║`);
105
- console.log(`║ 2FA Complete: ${String(!!currentSession.mfaVerified).padEnd(10)} ║`);
106
- console.log(`║ Auth Level (ACR): ${String(currentSession.authenticationLevel || '1').padEnd(10)} ║`);
107
- console.log('╚══════════════════════════════════════════════════════════════════════════════╝');
108
- // Try to acquire refresh lock to prevent concurrent refresh attempts
109
- const requestId = req.headers.get('x-request-id') ?? `refresh_${Date.now()}`;
110
- const lockAcquired = await (0, session_store_1.acquireRefreshLock)(sessionToken, requestId, 5000);
111
- let weAcquiredLock = false;
112
- let releaseLockVersion;
113
- if (!lockAcquired.acquired) {
114
- const existingLock = await (0, session_store_1.checkRefreshLock)(sessionToken);
115
- if (existingLock && existingLock.acquiredBy === requestId) {
116
- console.info('[AUTH_REFRESH] Proceeding under existing caller-held lock', { requestId });
117
- }
118
- else {
119
- // Wait for the lock to release, then check if token is now fresh
120
- console.info('[AUTH_REFRESH] Refresh in progress by another request, waiting for completion...', { requestId });
121
- const maxWaitMs = 5000;
122
- const checkIntervalMs = 200;
123
- const startWait = Date.now();
124
- while (Date.now() - startWait < maxWaitMs) {
125
- await new Promise(resolve => setTimeout(resolve, checkIntervalMs));
126
- // Check if lock was released
127
- const lockCheck = await (0, session_store_1.checkRefreshLock)(sessionToken);
128
- if (!lockCheck) {
129
- // Lock released - check if token is now fresh
130
- const refreshedSession = await (0, session_store_1.getSession)(sessionToken);
131
- if (refreshedSession?.idpAccessToken && refreshedSession?.idpAccessTokenExpires) {
132
- const timeUntilExpiry = refreshedSession.idpAccessTokenExpires - Date.now();
133
- const fiveMinutes = 5 * 60 * 1000;
134
- if (timeUntilExpiry > fiveMinutes) {
135
- console.info('[AUTH_REFRESH] Lock released, token is fresh - returning success', {
136
- requestId,
137
- accessTokenExpires: new Date(refreshedSession.idpAccessTokenExpires).toISOString(),
138
- waitedMs: Date.now() - startWait,
139
- });
140
- return server_1.NextResponse.json({
141
- refreshed: true,
142
- reason: 'completed_by_concurrent_request',
143
- accessTokenExpires: refreshedSession.idpAccessTokenExpires,
144
- hasRefreshToken: !!refreshedSession.idpRefreshToken,
145
- });
146
- }
147
- }
148
- // Lock released but token not fresh - try to acquire lock ourselves
149
- break;
150
- }
151
- }
152
- // Still locked after waiting - return 409
153
- console.warn('[AUTH_REFRESH] Refresh still in progress after waiting', { requestId, waitedMs: Date.now() - startWait });
154
- return server_1.NextResponse.json({
155
- error: 'Refresh already in progress',
156
- code: 'CONFLICT'
157
- }, { status: 409 });
158
- }
159
- }
160
- else {
161
- weAcquiredLock = true;
162
- releaseLockVersion = lockAcquired.lockInfo?.lockVersion;
163
- }
164
- // Before performing network refresh, re-check if tokens are already fresh
165
- const latestAfterLock = await (0, session_store_1.getSession)(sessionToken);
166
- const fiveMinutes = 5 * 60 * 1000;
167
- const timeUntilExpiry = latestAfterLock?.idpAccessTokenExpires
168
- ? latestAfterLock.idpAccessTokenExpires - Date.now()
169
- : -1;
170
- // CRITICAL: Also check the actual JWT's exp claim - Redis might have stale data
171
- let actualJwtExpMs = -1;
172
- let tokenMismatch = false;
173
- if (latestAfterLock?.idpAccessToken) {
174
- try {
175
- const tokenParts = latestAfterLock.idpAccessToken.split('.');
176
- if (tokenParts.length === 3) {
177
- const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString());
178
- actualJwtExpMs = (payload.exp || 0) * 1000;
179
- const now = Date.now();
180
- // If the actual JWT is expired, we MUST refresh regardless of what Redis says
181
- if (actualJwtExpMs < now) {
182
- tokenMismatch = true;
183
- }
184
- }
185
- }
186
- catch (e) {
187
- // If we can't decode, proceed with normal logic
188
- }
189
- }
190
- console.log('[AUTH_REFRESH] Pre-refresh check:', {
191
- userId,
192
- hasAccessToken: !!latestAfterLock?.idpAccessToken,
193
- accessTokenExpires: latestAfterLock?.idpAccessTokenExpires
194
- ? new Date(latestAfterLock.idpAccessTokenExpires).toISOString()
195
- : 'undefined',
196
- actualJwtExp: actualJwtExpMs > 0 ? new Date(actualJwtExpMs).toISOString() : 'unknown',
197
- now: new Date().toISOString(),
198
- timeUntilExpiryMs: timeUntilExpiry,
199
- tokenMismatch,
200
- willRefresh: timeUntilExpiry <= fiveMinutes || tokenMismatch
201
- });
202
- // Only skip refresh if BOTH Redis says fresh AND the actual JWT is not expired
203
- if (latestAfterLock?.idpAccessToken && latestAfterLock?.idpAccessTokenExpires &&
204
- timeUntilExpiry > fiveMinutes && !tokenMismatch) {
205
- console.info('[AUTH_REFRESH] Skipping refresh: tokens already fresh', { userId, timeUntilExpiryMs: timeUntilExpiry });
206
- if (weAcquiredLock) {
207
- await (0, session_store_1.releaseRefreshLock)(sessionToken, requestId, releaseLockVersion);
208
- weAcquiredLock = false;
209
- }
210
- return server_1.NextResponse.json({
211
- refreshed: false,
212
- reason: 'already_fresh',
213
- accessTokenExpires: latestAfterLock.idpAccessTokenExpires,
214
- hasRefreshToken: !!latestAfterLock.idpRefreshToken,
215
- });
216
- }
217
- // If we detected a token mismatch, log it prominently
218
- if (tokenMismatch) {
219
- console.warn('[AUTH_REFRESH] Token mismatch detected - forcing refresh despite Redis claiming fresh', {
220
- userId,
221
- redisExpires: latestAfterLock?.idpAccessTokenExpires ? new Date(latestAfterLock.idpAccessTokenExpires).toISOString() : 'N/A',
222
- actualJwtExp: new Date(actualJwtExpMs).toISOString()
223
- });
224
- }
225
- // Copy refresh token for use in IDP call
226
- // Note: Token is NOT cleared preemptively - it will be replaced on success.
227
- // The lock mechanism prevents concurrent refresh attempts within the same session.
228
- // If IDP call fails, user can retry with the same token.
229
- const originalRefreshToken = currentSession.idpRefreshToken;
230
- try {
231
- // Extract 2FA claims from current session
232
- let authMethods = [];
233
- if (currentSession.authenticationMethods) {
234
- if (typeof currentSession.authenticationMethods === 'string') {
235
- try {
236
- authMethods = JSON.parse(currentSession.authenticationMethods);
237
- }
238
- catch (e) {
239
- console.warn('[AUTH_REFRESH] Failed to parse authenticationMethods', { authenticationMethods: currentSession.authenticationMethods });
240
- }
241
- }
242
- else if (Array.isArray(currentSession.authenticationMethods)) {
243
- authMethods = currentSession.authenticationMethods;
244
- }
245
- }
246
- // For OAuth sessions with empty AMR claims, provide defaults
247
- // OAuth IS a form of multi-factor auth (you authenticated with another provider)
248
- let isOAuthSession = !!currentSession.oauthProvider;
249
- if (authMethods.length === 0 && isOAuthSession) {
250
- // OAuth sessions get default AMR claims
251
- authMethods = ['pwd', 'mfa'];
252
- console.log('[AUTH_REFRESH] OAuth session with empty AMR - using defaults:', {
253
- oauthProvider: currentSession.oauthProvider,
254
- defaultAmr: authMethods
255
- });
256
- }
257
- // Check authMethods first, then fallback to twoFactorMethod field (set by transitionTo2FASession)
258
- // For OAuth sessions, use 'oauth' as the 2FA method since OAuth itself is the authentication
259
- const twoFactorMethod = authMethods.find(m => ['sms', 'totp', 'email'].includes(m))
260
- || currentSession.mfaMethod
261
- || (isOAuthSession ? 'oauth' : null);
262
- // DEBUG: Log what we have for 2FA
263
- console.log('[AUTH_REFRESH] 2FA Debug:', {
264
- authMethods,
265
- authMethodsRaw: currentSession.authenticationMethods,
266
- twoFactorMethodFromSession: currentSession.mfaMethod,
267
- twoFactorMethodResolved: twoFactorMethod,
268
- twoFactorComplete: currentSession.mfaVerified,
269
- sessionKeys: Object.keys(currentSession)
270
- });
271
- // Build refresh request body per PayEz wire standard (snake_case)
272
- // See: 2FA-TOKEN-REFRESH-CONTEXT.md - "The Ninja Shit"
273
- // For OAuth sessions with 2FA complete, use ACR level 2
274
- let acrValue = String(currentSession.authenticationLevel ?? '1');
275
- if (currentSession.oauthProvider && currentSession.mfaVerified && acrValue === '1') {
276
- acrValue = '2'; // OAuth with 2FA complete = full authentication
277
- }
278
- const refreshRequestBody = {
279
- refresh_token: originalRefreshToken,
280
- amr: authMethods,
281
- acr: acrValue
282
- };
283
- // DEBUG: Log exact request body
284
- console.log('[AUTH_REFRESH] Request body:', JSON.stringify({
285
- refresh_token: '***REDACTED***',
286
- amr: authMethods,
287
- acr: acrValue,
288
- acrType: typeof acrValue
289
- }));
290
- const twoFactorVerified = !!currentSession.mfaVerified;
291
- if (twoFactorVerified) {
292
- refreshRequestBody.two_factor_verified = true;
293
- }
294
- if (twoFactorMethod) {
295
- refreshRequestBody.two_factor_method = twoFactorMethod;
296
- }
297
- if (currentSession.mfaCompletedAt) {
298
- refreshRequestBody.two_factor_completed_at = new Date(currentSession.mfaCompletedAt).toISOString();
299
- }
300
- // Log the full request details for debugging
301
- console.log('[AUTH_REFRESH] Sending refresh request:', {
302
- url: `${idpBaseUrl}${refreshEndpoint}`,
303
- clientId,
304
- hasRefreshToken: !!refreshRequestBody.refresh_token,
305
- refreshTokenLength: refreshRequestBody.refresh_token?.length,
306
- amr: refreshRequestBody.amr,
307
- acr: refreshRequestBody.acr
308
- });
309
- let refreshResponse;
310
- try {
311
- refreshResponse = await fetch(`${idpBaseUrl}${refreshEndpoint}`, {
312
- method: 'POST',
313
- headers: {
314
- 'Content-Type': 'application/json',
315
- 'X-Client-Id': clientId,
316
- },
317
- body: JSON.stringify(refreshRequestBody),
318
- });
319
- }
320
- catch (fetchError) {
321
- // Network error - IDP unreachable
322
- // Note: Lock will be released by finally block
323
- console.error('[AUTH_REFRESH] IDP unreachable:', {
324
- error: fetchError instanceof Error ? fetchError.message : String(fetchError),
325
- idpUrl: idpBaseUrl,
326
- userId
327
- });
328
- return server_1.NextResponse.json({
329
- error: 'IDP service unavailable',
330
- code: 'UPSTREAM_SERVICE_UNAVAILABLE',
331
- retryable: true,
332
- discardToken: false
333
- }, { status: 503 });
334
- }
335
- // Parse response body - handle empty or invalid JSON
336
- let responseData;
337
- try {
338
- const responseText = await refreshResponse.text();
339
- if (!responseText || responseText.trim() === '') {
340
- // Note: Lock will be released by finally block
341
- console.error('[AUTH_REFRESH] Empty response from IDP:', {
342
- status: refreshResponse.status,
343
- statusText: refreshResponse.statusText,
344
- userId
345
- });
346
- return server_1.NextResponse.json({
347
- error: 'Empty response from IDP',
348
- code: 'UPSTREAM_SERVICE_ERROR',
349
- retryable: true,
350
- discardToken: false
351
- }, { status: 502 });
352
- }
353
- responseData = JSON.parse(responseText);
354
- }
355
- catch (parseError) {
356
- // Note: Lock will be released by finally block
357
- console.error('[AUTH_REFRESH] Failed to parse IDP response:', {
358
- error: parseError instanceof Error ? parseError.message : String(parseError),
359
- status: refreshResponse.status,
360
- userId
361
- });
362
- return server_1.NextResponse.json({
363
- error: 'Invalid response from IDP',
364
- code: 'UPSTREAM_SERVICE_ERROR',
365
- retryable: true,
366
- discardToken: false
367
- }, { status: 502 });
368
- }
369
- // Handle non-OK responses with structured error format
370
- if (!refreshResponse.ok) {
371
- // Parse structured error from IDP
372
- const idpError = responseData?.error || {};
373
- const errorCode = idpError.code || 'UNKNOWN_ERROR';
374
- const errorMessage = idpError.message || 'Token refresh failed';
375
- // CRITICAL: 401 means token is definitively invalid - always discard
376
- // This prevents redirect loops where viability check keeps returning canRefresh:true
377
- const discardToken = refreshResponse.status === 401 || idpError.discard_token === true;
378
- const retryable = refreshResponse.status !== 401 && idpError.retryable === true;
379
- const resolution = idpError.resolution || null;
380
- // ============================================================================
381
- // HIGH VISIBILITY: REFRESH TOKEN FAILURE DIAGNOSTICS
382
- // ============================================================================
383
- // Translate error codes to human-readable explanations
384
- const failureReasons = {
385
- 'UNAUTHORIZED': 'Token was already used (rotation) OR token is expired OR token was revoked',
386
- 'INVALID_REFRESH_TOKEN': 'Token format invalid OR token not found in IDP database',
387
- 'TOKEN_EXPIRED': 'Refresh token exceeded its max lifetime',
388
- 'TOKEN_REVOKED': 'Token was explicitly revoked (logout, password change, admin action)',
389
- 'TOKEN_REUSE_DETECTED': 'Same refresh token used twice - possible token theft, all tokens revoked',
390
- 'UPSTREAM_SERVICE_ERROR': 'IDP internal error - token may have been rotated before failure',
391
- 'INTERNAL_ERROR': 'IDP internal error - check IDP logs for details',
392
- 'RATE_LIMITED': 'Too many refresh attempts - try again later',
393
- };
394
- const whyItFailed = failureReasons[errorCode] || 'Unknown error - check IDP logs';
395
- console.error('╔══════════════════════════════════════════════════════════════════════════════╗');
396
- console.error('║ ❌ REFRESH TOKEN FAILURE - DIAGNOSTIC REPORT ║');
397
- console.error('╠══════════════════════════════════════════════════════════════════════════════╣');
398
- console.error(`║ HTTP Status: ${String(refreshResponse.status).padEnd(60)}║`);
399
- console.error(`║ Error Code: ${errorCode.padEnd(60)}║`);
400
- console.error(`║ Discard Token: ${String(discardToken).padEnd(60)}║`);
401
- console.error(`║ Retryable: ${String(retryable).padEnd(60)}║`);
402
- console.error('╠──────────────────────────────────────────────────────────────────────────────╣');
403
- console.error(`║ WHY IT FAILED: ║`);
404
- console.error(`║ ${whyItFailed.substring(0, 76).padEnd(76)} ║`);
405
- console.error('╠──────────────────────────────────────────────────────────────────────────────╣');
406
- console.error(`║ User: ${(userId || 'unknown').substring(0, 60).padEnd(60)}║`);
407
- console.error(`║ Session: ${sessionToken.substring(0, 8)}... ║`);
408
- console.error(`║ Resolution: ${(resolution || 'Check IDP logs').substring(0, 60).padEnd(60)}║`);
409
- console.error('╚══════════════════════════════════════════════════════════════════════════════╝');
410
- // Also log the full response for detailed debugging
411
- console.error('[AUTH_REFRESH] Full IDP error response:', JSON.stringify(responseData, null, 2).substring(0, 1000));
412
- // If IDP signals to discard token, clear it from Redis
413
- if (discardToken) {
414
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP signaled discard_token', {
415
- reason: 'IDP_DISCARD_TOKEN',
416
- errorCode,
417
- userId,
418
- sessionToken: sessionToken.substring(0, 8) + '...',
419
- hadRefreshToken: !!currentSession.idpRefreshToken,
420
- stack: new Error().stack
421
- });
422
- await (0, session_store_1.updateSession)(sessionToken, {
423
- idpRefreshToken: '',
424
- idpRefreshTokenExpires: undefined,
425
- refreshTokenClearedAt: Date.now(),
426
- refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${errorCode}`
427
- });
428
- }
429
- return server_1.NextResponse.json({
430
- error: errorMessage,
431
- code: errorCode,
432
- discardToken,
433
- retryable,
434
- resolution,
435
- status: refreshResponse.status
436
- }, { status: refreshResponse.status });
437
- }
438
- // Validate PayEz canonical envelope for success responses
439
- const isCompliant = responseData && typeof responseData === 'object' &&
440
- Object.prototype.hasOwnProperty.call(responseData, 'success') &&
441
- (responseData.success === true ? Object.prototype.hasOwnProperty.call(responseData, 'data') : Object.prototype.hasOwnProperty.call(responseData, 'error')) &&
442
- Object.prototype.hasOwnProperty.call(responseData, 'meta');
443
- if (!isCompliant) {
444
- console.error('[AUTH_REFRESH] Upstream non-compliant IDP response', { bodySample: responseData });
445
- return server_1.NextResponse.json({
446
- error: 'Upstream non-compliance',
447
- code: 'UPSTREAM_SERVICE_ERROR',
448
- retryable: true,
449
- discardToken: false
450
- }, { status: 502 });
451
- }
452
- if (responseData.success !== true || !responseData.data) {
453
- // Handle success:false with structured error
454
- const idpError = responseData?.error || {};
455
- const errorCode = idpError.code || 'UPSTREAM_VALIDATION_ERROR';
456
- const discardToken = idpError.discard_token === true;
457
- const retryable = idpError.retryable === true;
458
- console.warn('[AUTH_REFRESH] IDP refresh unsuccessful', {
459
- code: errorCode,
460
- discardToken,
461
- body: responseData
462
- });
463
- if (discardToken) {
464
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP success:false with discard_token', {
465
- reason: 'IDP_SUCCESS_FALSE_DISCARD',
466
- errorCode,
467
- userId,
468
- sessionToken: sessionToken.substring(0, 8) + '...',
469
- hadRefreshToken: !!currentSession.idpRefreshToken,
470
- stack: new Error().stack
471
- });
472
- await (0, session_store_1.updateSession)(sessionToken, {
473
- idpRefreshToken: '',
474
- idpRefreshTokenExpires: undefined,
475
- refreshTokenClearedAt: Date.now(),
476
- refreshTokenClearedReason: `IDP_SUCCESS_FALSE_DISCARD:${errorCode}`
477
- });
478
- }
479
- return server_1.NextResponse.json({
480
- error: idpError.message || 'Token refresh failed',
481
- code: errorCode,
482
- discardToken,
483
- retryable,
484
- resolution: idpError.resolution || null
485
- }, { status: refreshResponse.status || 400 });
486
- }
487
- // Extract tokens from response
488
- const payload = responseData.data;
489
- const accessToken = payload?.access_token;
490
- const refreshToken = payload?.refresh_token;
491
- if (!accessToken) {
492
- console.error('[AUTH_REFRESH] Missing access token in IDP response');
493
- return server_1.NextResponse.json({
494
- error: 'Invalid token response from IDP',
495
- code: 'INTERNAL_SERVER_ERROR'
496
- }, { status: 500 });
497
- }
498
- // Decode and compute token expiries
499
- let decodedAccessToken;
500
- let accessTokenExpires;
501
- let computedRefreshTokenExpires;
502
- try {
503
- const result = (0, token_expiry_1.computeTokenExpiries)({ accessToken, refreshToken, preferJwt: true });
504
- decodedAccessToken = result.decodedAccessToken;
505
- accessTokenExpires = result.accessTokenExpires;
506
- computedRefreshTokenExpires = result.refreshTokenExpires;
507
- console.info('[AUTH_REFRESH] Successfully decoded new token pair', {
508
- accessTokenExpires: new Date(accessTokenExpires).toISOString(),
509
- refreshTokenExpires: computedRefreshTokenExpires ? new Date(computedRefreshTokenExpires).toISOString() : null
510
- });
511
- }
512
- catch (decodeError) {
513
- console.error('[AUTH_REFRESH] Failed to compute token expiries', { error: decodeError });
514
- return server_1.NextResponse.json({
515
- error: 'Failed to decode JWT tokens',
516
- code: 'INTERNAL_SERVER_ERROR'
517
- }, { status: 500 });
518
- }
519
- // Extract 2FA claims from the new access token
520
- let amrClaims = [];
521
- if (decodedAccessToken.amr) {
522
- try {
523
- amrClaims = typeof decodedAccessToken.amr === 'string'
524
- ? JSON.parse(decodedAccessToken.amr)
525
- : decodedAccessToken.amr;
526
- }
527
- catch (e) {
528
- console.warn('[AUTH_REFRESH] Failed to parse AMR claims', { amr: decodedAccessToken.amr });
529
- amrClaims = currentSession.authenticationMethods || [];
530
- }
531
- }
532
- else {
533
- amrClaims = currentSession.authenticationMethods || [];
534
- }
535
- const acrLevel = String(decodedAccessToken.acr || currentSession.authenticationLevel || '1');
536
- // Extract MFA timing claims
537
- const mfaTime = decodedAccessToken.mfa_time ? parseInt(decodedAccessToken.mfa_time) * 1000 : currentSession.mfaCompletedAt;
538
- const mfaExpires = decodedAccessToken.mfa_expires ? parseInt(decodedAccessToken.mfa_expires) * 1000 : currentSession.mfaExpiresAt;
539
- const mfaValidityHours = decodedAccessToken.mfa_validity_hours ? parseInt(decodedAccessToken.mfa_validity_hours) : currentSession.mfaValidityHours;
540
- // Update session with new tokens
541
- const hasNewRefresh = typeof refreshToken === 'string' && refreshToken.length > 0;
542
- const newRefreshTokenExpires = hasNewRefresh ? computedRefreshTokenExpires : undefined;
543
- // CRITICAL: Log if we're about to clear the refresh token due to missing new token
544
- if (!hasNewRefresh && currentSession.idpRefreshToken) {
545
- console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: No new refresh token in IDP response', {
546
- reason: 'NO_NEW_REFRESH_TOKEN_IN_RESPONSE',
547
- userId,
548
- sessionToken: sessionToken.substring(0, 8) + '...',
549
- hadRefreshToken: true,
550
- refreshTokenFromResponse: refreshToken,
551
- refreshTokenType: typeof refreshToken,
552
- payloadKeys: Object.keys(payload || {}),
553
- stack: new Error().stack
554
- });
555
- }
556
- // Keep existing refresh token if IDP doesn't provide a new one
557
- // Only clear if IDP explicitly signals discard_token=true (handled in error paths)
558
- // NOTE: Use normalized field names (idp* prefix) per SessionData interface
559
- // CRITICAL: Extract kid from JWT header - IDP may rotate keys during refresh
560
- const newBearerKeyId = (0, token_utils_1.extractKidFromToken)(accessToken);
561
- if (newBearerKeyId) {
562
- console.log('[AUTH_REFRESH] Extracted bearerKeyId (kid) from new JWT header:', newBearerKeyId);
563
- }
564
- else {
565
- console.warn('[AUTH_REFRESH] No kid found in new JWT header');
566
- }
567
- const sessionUpdate = {
568
- ...currentSession,
569
- idpAccessToken: accessToken,
570
- idpAccessTokenExpires: accessTokenExpires,
571
- idpRefreshToken: hasNewRefresh ? refreshToken : currentSession.idpRefreshToken,
572
- idpRefreshTokenExpires: hasNewRefresh ? newRefreshTokenExpires : currentSession.idpRefreshTokenExpires,
573
- decodedAccessToken: decodedAccessToken,
574
- // Bearer key ID from JWT header (may change on key rotation)
575
- bearerKeyId: newBearerKeyId || currentSession.bearerKeyId,
576
- authenticationMethods: amrClaims,
577
- authenticationLevel: acrLevel,
578
- mfaVerified: amrClaims.includes('mfa') || currentSession.mfaVerified,
579
- mfaCompletedAt: mfaTime,
580
- mfaExpiresAt: mfaExpires,
581
- mfaValidityHours: mfaValidityHours
582
- };
583
- await (0, session_store_1.updateSession)(sessionToken, sessionUpdate);
584
- console.info('[AUTH_REFRESH] Token refreshed successfully', {
585
- expiresAt: new Date(accessTokenExpires).toISOString(),
586
- userId,
587
- hasNewRefreshToken: hasNewRefresh,
588
- tokenPreview: accessToken ? accessToken.substring(0, 20) + '...' : 'none'
589
- });
590
- }
591
- catch (error) {
592
- console.error('[AUTH_REFRESH] Error during token refresh', { error });
593
- return server_1.NextResponse.json({
594
- error: 'Token refresh error',
595
- code: 'INTERNAL_SERVER_ERROR'
596
- }, { status: 500 });
597
- }
598
- finally {
599
- if (weAcquiredLock) {
600
- await (0, session_store_1.releaseRefreshLock)(sessionToken, requestId, releaseLockVersion);
601
- }
602
- }
603
- // Load the latest session to return basic status
604
- const latest = await (0, session_store_1.getSession)(sessionToken);
605
- if (!latest?.idpAccessToken) {
606
- return server_1.NextResponse.json({
607
- error: 'No access token after refresh',
608
- code: 'INTERNAL_SERVER_ERROR'
609
- }, { status: 500 });
610
- }
611
- return server_1.NextResponse.json({
612
- refreshed: true,
613
- accessTokenExpires: latest.idpAccessTokenExpires,
614
- hasRefreshToken: !!latest.idpRefreshToken,
615
- });
616
- }
617
- catch (err) {
618
- console.error('[AUTH_REFRESH] Unexpected error', { error: err?.message || String(err) });
619
- return server_1.NextResponse.json({
620
- error: 'Unexpected error during refresh',
621
- code: 'INTERNAL_SERVER_ERROR'
622
- }, { status: 500 });
623
- }
624
- };
625
- }
626
- /**
627
- * Default export for backward compatibility
628
- * Requires environment variables: IDP_URL, CLIENT_ID, NEXTAUTH_SECRET
629
- */
630
- exports.POST = createRefreshHandler({
631
- idpBaseUrl: process.env.IDP_URL,
632
- clientId: process.env.CLIENT_ID || 'payez_default_client',
633
- nextAuthSecret: process.env.NEXTAUTH_SECRET || '',
634
- refreshEndpoint: '/api/ExternalAuth/refresh'
635
- });
1
+ "use strict";
2
+ /**
3
+ * CRITICAL REFRESH TOKEN API HANDLER
4
+ *
5
+ * ASK BEFORE EDITING - TESTED AND WORKING SYSTEM
6
+ *
7
+ * This handler manages the server-side refresh token cycle with:
8
+ * - NextAuth JWT token extraction
9
+ * - Session token fallback for internal calls
10
+ * - PayEz IDP refresh token exchange
11
+ * - Session state updates with new tokens
12
+ * - Proper error handling and logging
13
+ * - Single-use semantics enforcement
14
+ *
15
+ * @version 2.0
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.POST = void 0;
19
+ exports.createRefreshHandler = createRefreshHandler;
20
+ const server_1 = require("next/server");
21
+ const auth_1 = require("../../server/auth");
22
+ const session_store_1 = require("../../lib/session-store");
23
+ const token_expiry_1 = require("../../lib/token-expiry");
24
+ const token_utils_1 = require("../../auth/utils/token-utils");
25
+ /**
26
+ * Creates a refresh token handler for Next.js API routes
27
+ *
28
+ * @param config Configuration for IDP connection and NextAuth
29
+ * @returns Next.js POST handler function
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * // In your app's /app/api/auth/refresh/route.ts
34
+ * import { createRefreshHandler } from '@payez/next-mvp/api-handlers/auth/refresh';
35
+ *
36
+ * export const POST = createRefreshHandler({
37
+ * idpBaseUrl: process.env.IDP_URL!,
38
+ * clientId: process.env.CLIENT_ID!,
39
+ * nextAuthSecret: process.env.NEXTAUTH_SECRET!,
40
+ * refreshEndpoint: '/api/ExternalAuth/refresh'
41
+ * });
42
+ * ```
43
+ */
44
+ function createRefreshHandler(config) {
45
+ const { idpBaseUrl, clientId, nextAuthSecret, refreshEndpoint = '/api/ExternalAuth/refresh' } = config;
46
+ return async function POST(req) {
47
+ try {
48
+ // Extract session from Better Auth
49
+ const betterAuthSession = await (0, auth_1.getSession)(req);
50
+ let sessionToken = (betterAuthSession?.session?.token);
51
+ let userId = betterAuthSession?.user?.id;
52
+ if (!sessionToken) {
53
+ // Fallback: check for session token in header (for internal server-to-server calls)
54
+ const headerSessionToken = req.headers.get('x-session-token');
55
+ if (headerSessionToken) {
56
+ sessionToken = headerSessionToken;
57
+ const currentSession = await (0, session_store_1.getSession)(sessionToken);
58
+ userId = currentSession?.userId || currentSession?.email;
59
+ }
60
+ }
61
+ if (!sessionToken || !userId) {
62
+ console.warn('[AUTH_REFRESH] Missing sessionToken or user id on token');
63
+ return server_1.NextResponse.json({
64
+ error: 'No session available for refresh',
65
+ code: 'UNAUTHORIZED'
66
+ }, { status: 401 });
67
+ }
68
+ // Get current session
69
+ const currentSession = await (0, session_store_1.getSession)(sessionToken);
70
+ // NOTE: Field is idpRefreshToken (not refreshToken) per normalized naming convention
71
+ if (!currentSession?.idpRefreshToken) {
72
+ console.warn('[AUTH_REFRESH] No refresh token available', { userId });
73
+ return server_1.NextResponse.json({
74
+ error: 'No refresh token available',
75
+ code: 'NO_REFRESH_TOKEN', // Terminal state - session cannot be refreshed
76
+ terminal: true, // Signal to frontend: don't retry, redirect to login
77
+ resolution: 'User must re-authenticate'
78
+ }, { status: 401 });
79
+ }
80
+ // ============================================================================
81
+ // HIGH VISIBILITY: PRE-FLIGHT REFRESH DIAGNOSTICS
82
+ // ============================================================================
83
+ const now = Date.now();
84
+ const refreshTokenAge = currentSession.idpRefreshTokenIssuedAt
85
+ ? Math.round((now - currentSession.idpRefreshTokenIssuedAt) / 1000)
86
+ : 'unknown';
87
+ const refreshTokenExpiresIn = currentSession.idpRefreshTokenExpires
88
+ ? Math.round((currentSession.idpRefreshTokenExpires - now) / 1000)
89
+ : 'unknown';
90
+ const accessTokenExpiresIn = currentSession.idpAccessTokenExpires
91
+ ? Math.round((currentSession.idpAccessTokenExpires - now) / 1000)
92
+ : 'unknown';
93
+ console.log('╔══════════════════════════════════════════════════════════════════════════════╗');
94
+ console.log('║ REFRESH TOKEN ATTEMPT - PRE-FLIGHT ║');
95
+ console.log('╠══════════════════════════════════════════════════════════════════════════════╣');
96
+ console.log(`║ User: ${(userId || 'unknown').substring(0, 50).padEnd(50)} ║`);
97
+ console.log(`║ Session: ${sessionToken.substring(0, 8)}... ║`);
98
+ console.log('╠──────────────────────────────────────────────────────────────────────────────╣');
99
+ console.log(`║ Access Token Expires In: ${String(accessTokenExpiresIn).padEnd(10)} seconds ║`);
100
+ console.log(`║ Refresh Token Age: ${String(refreshTokenAge).padEnd(10)} seconds ║`);
101
+ console.log(`║ Refresh Token Expires In: ${String(refreshTokenExpiresIn).padEnd(10)} seconds ║`);
102
+ console.log(`║ Refresh Token Length: ${String(currentSession.idpRefreshToken?.length || 0).padEnd(10)} chars ║`);
103
+ console.log(`║ 2FA Complete: ${String(!!currentSession.mfaVerified).padEnd(10)} ║`);
104
+ console.log(`║ Auth Level (ACR): ${String(currentSession.authenticationLevel || '1').padEnd(10)} ║`);
105
+ console.log('╚══════════════════════════════════════════════════════════════════════════════╝');
106
+ // Try to acquire refresh lock to prevent concurrent refresh attempts
107
+ const requestId = req.headers.get('x-request-id') ?? `refresh_${Date.now()}`;
108
+ const lockAcquired = await (0, session_store_1.acquireRefreshLock)(sessionToken, requestId, 5000);
109
+ let weAcquiredLock = false;
110
+ let releaseLockVersion;
111
+ if (!lockAcquired.acquired) {
112
+ const existingLock = await (0, session_store_1.checkRefreshLock)(sessionToken);
113
+ if (existingLock && existingLock.acquiredBy === requestId) {
114
+ console.info('[AUTH_REFRESH] Proceeding under existing caller-held lock', { requestId });
115
+ }
116
+ else {
117
+ // Wait for the lock to release, then check if token is now fresh
118
+ console.info('[AUTH_REFRESH] Refresh in progress by another request, waiting for completion...', { requestId });
119
+ const maxWaitMs = 5000;
120
+ const checkIntervalMs = 200;
121
+ const startWait = Date.now();
122
+ while (Date.now() - startWait < maxWaitMs) {
123
+ await new Promise(resolve => setTimeout(resolve, checkIntervalMs));
124
+ // Check if lock was released
125
+ const lockCheck = await (0, session_store_1.checkRefreshLock)(sessionToken);
126
+ if (!lockCheck) {
127
+ // Lock released - check if token is now fresh
128
+ const refreshedSession = await (0, session_store_1.getSession)(sessionToken);
129
+ if (refreshedSession?.idpAccessToken && refreshedSession?.idpAccessTokenExpires) {
130
+ const timeUntilExpiry = refreshedSession.idpAccessTokenExpires - Date.now();
131
+ const fiveMinutes = 5 * 60 * 1000;
132
+ if (timeUntilExpiry > fiveMinutes) {
133
+ console.info('[AUTH_REFRESH] Lock released, token is fresh - returning success', {
134
+ requestId,
135
+ accessTokenExpires: new Date(refreshedSession.idpAccessTokenExpires).toISOString(),
136
+ waitedMs: Date.now() - startWait,
137
+ });
138
+ return server_1.NextResponse.json({
139
+ refreshed: true,
140
+ reason: 'completed_by_concurrent_request',
141
+ accessTokenExpires: refreshedSession.idpAccessTokenExpires,
142
+ hasRefreshToken: !!refreshedSession.idpRefreshToken,
143
+ });
144
+ }
145
+ }
146
+ // Lock released but token not fresh - try to acquire lock ourselves
147
+ break;
148
+ }
149
+ }
150
+ // Still locked after waiting - return 409
151
+ console.warn('[AUTH_REFRESH] Refresh still in progress after waiting', { requestId, waitedMs: Date.now() - startWait });
152
+ return server_1.NextResponse.json({
153
+ error: 'Refresh already in progress',
154
+ code: 'CONFLICT'
155
+ }, { status: 409 });
156
+ }
157
+ }
158
+ else {
159
+ weAcquiredLock = true;
160
+ releaseLockVersion = lockAcquired.lockInfo?.lockVersion;
161
+ }
162
+ // Before performing network refresh, re-check if tokens are already fresh
163
+ const latestAfterLock = await (0, session_store_1.getSession)(sessionToken);
164
+ const fiveMinutes = 5 * 60 * 1000;
165
+ const timeUntilExpiry = latestAfterLock?.idpAccessTokenExpires
166
+ ? latestAfterLock.idpAccessTokenExpires - Date.now()
167
+ : -1;
168
+ // CRITICAL: Also check the actual JWT's exp claim - Redis might have stale data
169
+ let actualJwtExpMs = -1;
170
+ let tokenMismatch = false;
171
+ if (latestAfterLock?.idpAccessToken) {
172
+ try {
173
+ const tokenParts = latestAfterLock.idpAccessToken.split('.');
174
+ if (tokenParts.length === 3) {
175
+ const payload = JSON.parse(Buffer.from(tokenParts[1], 'base64url').toString());
176
+ actualJwtExpMs = (payload.exp || 0) * 1000;
177
+ const now = Date.now();
178
+ // If the actual JWT is expired, we MUST refresh regardless of what Redis says
179
+ if (actualJwtExpMs < now) {
180
+ tokenMismatch = true;
181
+ }
182
+ }
183
+ }
184
+ catch (e) {
185
+ // If we can't decode, proceed with normal logic
186
+ }
187
+ }
188
+ console.log('[AUTH_REFRESH] Pre-refresh check:', {
189
+ userId,
190
+ hasAccessToken: !!latestAfterLock?.idpAccessToken,
191
+ accessTokenExpires: latestAfterLock?.idpAccessTokenExpires
192
+ ? new Date(latestAfterLock.idpAccessTokenExpires).toISOString()
193
+ : 'undefined',
194
+ actualJwtExp: actualJwtExpMs > 0 ? new Date(actualJwtExpMs).toISOString() : 'unknown',
195
+ now: new Date().toISOString(),
196
+ timeUntilExpiryMs: timeUntilExpiry,
197
+ tokenMismatch,
198
+ willRefresh: timeUntilExpiry <= fiveMinutes || tokenMismatch
199
+ });
200
+ // Only skip refresh if BOTH Redis says fresh AND the actual JWT is not expired
201
+ if (latestAfterLock?.idpAccessToken && latestAfterLock?.idpAccessTokenExpires &&
202
+ timeUntilExpiry > fiveMinutes && !tokenMismatch) {
203
+ console.info('[AUTH_REFRESH] Skipping refresh: tokens already fresh', { userId, timeUntilExpiryMs: timeUntilExpiry });
204
+ if (weAcquiredLock) {
205
+ await (0, session_store_1.releaseRefreshLock)(sessionToken, requestId, releaseLockVersion);
206
+ weAcquiredLock = false;
207
+ }
208
+ return server_1.NextResponse.json({
209
+ refreshed: false,
210
+ reason: 'already_fresh',
211
+ accessTokenExpires: latestAfterLock.idpAccessTokenExpires,
212
+ hasRefreshToken: !!latestAfterLock.idpRefreshToken,
213
+ });
214
+ }
215
+ // If we detected a token mismatch, log it prominently
216
+ if (tokenMismatch) {
217
+ console.warn('[AUTH_REFRESH] Token mismatch detected - forcing refresh despite Redis claiming fresh', {
218
+ userId,
219
+ redisExpires: latestAfterLock?.idpAccessTokenExpires ? new Date(latestAfterLock.idpAccessTokenExpires).toISOString() : 'N/A',
220
+ actualJwtExp: new Date(actualJwtExpMs).toISOString()
221
+ });
222
+ }
223
+ // Copy refresh token for use in IDP call
224
+ // Note: Token is NOT cleared preemptively - it will be replaced on success.
225
+ // The lock mechanism prevents concurrent refresh attempts within the same session.
226
+ // If IDP call fails, user can retry with the same token.
227
+ const originalRefreshToken = currentSession.idpRefreshToken;
228
+ try {
229
+ // Extract 2FA claims from current session
230
+ let authMethods = [];
231
+ if (currentSession.authenticationMethods) {
232
+ if (typeof currentSession.authenticationMethods === 'string') {
233
+ try {
234
+ authMethods = JSON.parse(currentSession.authenticationMethods);
235
+ }
236
+ catch (e) {
237
+ console.warn('[AUTH_REFRESH] Failed to parse authenticationMethods', { authenticationMethods: currentSession.authenticationMethods });
238
+ }
239
+ }
240
+ else if (Array.isArray(currentSession.authenticationMethods)) {
241
+ authMethods = currentSession.authenticationMethods;
242
+ }
243
+ }
244
+ // For OAuth sessions with empty AMR claims, provide defaults
245
+ // OAuth IS a form of multi-factor auth (you authenticated with another provider)
246
+ let isOAuthSession = !!currentSession.oauthProvider;
247
+ if (authMethods.length === 0 && isOAuthSession) {
248
+ // OAuth sessions get default AMR claims
249
+ authMethods = ['pwd', 'mfa'];
250
+ console.log('[AUTH_REFRESH] OAuth session with empty AMR - using defaults:', {
251
+ oauthProvider: currentSession.oauthProvider,
252
+ defaultAmr: authMethods
253
+ });
254
+ }
255
+ // Check authMethods first, then fallback to twoFactorMethod field (set by transitionTo2FASession)
256
+ // For OAuth sessions, use 'oauth' as the 2FA method since OAuth itself is the authentication
257
+ const twoFactorMethod = authMethods.find(m => ['sms', 'totp', 'email'].includes(m))
258
+ || currentSession.mfaMethod
259
+ || (isOAuthSession ? 'oauth' : null);
260
+ // DEBUG: Log what we have for 2FA
261
+ console.log('[AUTH_REFRESH] 2FA Debug:', {
262
+ authMethods,
263
+ authMethodsRaw: currentSession.authenticationMethods,
264
+ twoFactorMethodFromSession: currentSession.mfaMethod,
265
+ twoFactorMethodResolved: twoFactorMethod,
266
+ twoFactorComplete: currentSession.mfaVerified,
267
+ sessionKeys: Object.keys(currentSession)
268
+ });
269
+ // Build refresh request body per PayEz wire standard (snake_case)
270
+ // See: 2FA-TOKEN-REFRESH-CONTEXT.md - "The Ninja Shit"
271
+ // For OAuth sessions with 2FA complete, use ACR level 2
272
+ let acrValue = String(currentSession.authenticationLevel ?? '1');
273
+ if (currentSession.oauthProvider && currentSession.mfaVerified && acrValue === '1') {
274
+ acrValue = '2'; // OAuth with 2FA complete = full authentication
275
+ }
276
+ const refreshRequestBody = {
277
+ refresh_token: originalRefreshToken,
278
+ amr: authMethods,
279
+ acr: acrValue
280
+ };
281
+ // DEBUG: Log exact request body
282
+ console.log('[AUTH_REFRESH] Request body:', JSON.stringify({
283
+ refresh_token: '***REDACTED***',
284
+ amr: authMethods,
285
+ acr: acrValue,
286
+ acrType: typeof acrValue
287
+ }));
288
+ const twoFactorVerified = !!currentSession.mfaVerified;
289
+ if (twoFactorVerified) {
290
+ refreshRequestBody.two_factor_verified = true;
291
+ }
292
+ if (twoFactorMethod) {
293
+ refreshRequestBody.two_factor_method = twoFactorMethod;
294
+ }
295
+ if (currentSession.mfaCompletedAt) {
296
+ refreshRequestBody.two_factor_completed_at = new Date(currentSession.mfaCompletedAt).toISOString();
297
+ }
298
+ // Log the full request details for debugging
299
+ console.log('[AUTH_REFRESH] Sending refresh request:', {
300
+ url: `${idpBaseUrl}${refreshEndpoint}`,
301
+ clientId,
302
+ hasRefreshToken: !!refreshRequestBody.refresh_token,
303
+ refreshTokenLength: refreshRequestBody.refresh_token?.length,
304
+ amr: refreshRequestBody.amr,
305
+ acr: refreshRequestBody.acr
306
+ });
307
+ let refreshResponse;
308
+ try {
309
+ refreshResponse = await fetch(`${idpBaseUrl}${refreshEndpoint}`, {
310
+ method: 'POST',
311
+ headers: {
312
+ 'Content-Type': 'application/json',
313
+ 'X-Client-Id': clientId,
314
+ },
315
+ body: JSON.stringify(refreshRequestBody),
316
+ });
317
+ }
318
+ catch (fetchError) {
319
+ // Network error - IDP unreachable
320
+ // Note: Lock will be released by finally block
321
+ console.error('[AUTH_REFRESH] IDP unreachable:', {
322
+ error: fetchError instanceof Error ? fetchError.message : String(fetchError),
323
+ idpUrl: idpBaseUrl,
324
+ userId
325
+ });
326
+ return server_1.NextResponse.json({
327
+ error: 'IDP service unavailable',
328
+ code: 'UPSTREAM_SERVICE_UNAVAILABLE',
329
+ retryable: true,
330
+ discardToken: false
331
+ }, { status: 503 });
332
+ }
333
+ // Parse response body - handle empty or invalid JSON
334
+ let responseData;
335
+ try {
336
+ const responseText = await refreshResponse.text();
337
+ if (!responseText || responseText.trim() === '') {
338
+ // Note: Lock will be released by finally block
339
+ console.error('[AUTH_REFRESH] Empty response from IDP:', {
340
+ status: refreshResponse.status,
341
+ statusText: refreshResponse.statusText,
342
+ userId
343
+ });
344
+ return server_1.NextResponse.json({
345
+ error: 'Empty response from IDP',
346
+ code: 'UPSTREAM_SERVICE_ERROR',
347
+ retryable: true,
348
+ discardToken: false
349
+ }, { status: 502 });
350
+ }
351
+ responseData = JSON.parse(responseText);
352
+ }
353
+ catch (parseError) {
354
+ // Note: Lock will be released by finally block
355
+ console.error('[AUTH_REFRESH] Failed to parse IDP response:', {
356
+ error: parseError instanceof Error ? parseError.message : String(parseError),
357
+ status: refreshResponse.status,
358
+ userId
359
+ });
360
+ return server_1.NextResponse.json({
361
+ error: 'Invalid response from IDP',
362
+ code: 'UPSTREAM_SERVICE_ERROR',
363
+ retryable: true,
364
+ discardToken: false
365
+ }, { status: 502 });
366
+ }
367
+ // Handle non-OK responses with structured error format
368
+ if (!refreshResponse.ok) {
369
+ // Parse structured error from IDP
370
+ const idpError = responseData?.error || {};
371
+ const errorCode = idpError.code || 'UNKNOWN_ERROR';
372
+ const errorMessage = idpError.message || 'Token refresh failed';
373
+ // CRITICAL: 401 means token is definitively invalid - always discard
374
+ // This prevents redirect loops where viability check keeps returning canRefresh:true
375
+ const discardToken = refreshResponse.status === 401 || idpError.discard_token === true;
376
+ const retryable = refreshResponse.status !== 401 && idpError.retryable === true;
377
+ const resolution = idpError.resolution || null;
378
+ // ============================================================================
379
+ // HIGH VISIBILITY: REFRESH TOKEN FAILURE DIAGNOSTICS
380
+ // ============================================================================
381
+ // Translate error codes to human-readable explanations
382
+ const failureReasons = {
383
+ 'UNAUTHORIZED': 'Token was already used (rotation) OR token is expired OR token was revoked',
384
+ 'INVALID_REFRESH_TOKEN': 'Token format invalid OR token not found in IDP database',
385
+ 'TOKEN_EXPIRED': 'Refresh token exceeded its max lifetime',
386
+ 'TOKEN_REVOKED': 'Token was explicitly revoked (logout, password change, admin action)',
387
+ 'TOKEN_REUSE_DETECTED': 'Same refresh token used twice - possible token theft, all tokens revoked',
388
+ 'UPSTREAM_SERVICE_ERROR': 'IDP internal error - token may have been rotated before failure',
389
+ 'INTERNAL_ERROR': 'IDP internal error - check IDP logs for details',
390
+ 'RATE_LIMITED': 'Too many refresh attempts - try again later',
391
+ };
392
+ const whyItFailed = failureReasons[errorCode] || 'Unknown error - check IDP logs';
393
+ console.error('╔══════════════════════════════════════════════════════════════════════════════╗');
394
+ console.error('║ ❌ REFRESH TOKEN FAILURE - DIAGNOSTIC REPORT ║');
395
+ console.error('╠══════════════════════════════════════════════════════════════════════════════╣');
396
+ console.error(`║ HTTP Status: ${String(refreshResponse.status).padEnd(60)}║`);
397
+ console.error(`║ Error Code: ${errorCode.padEnd(60)}║`);
398
+ console.error(`║ Discard Token: ${String(discardToken).padEnd(60)}║`);
399
+ console.error(`║ Retryable: ${String(retryable).padEnd(60)}║`);
400
+ console.error('╠──────────────────────────────────────────────────────────────────────────────╣');
401
+ console.error(`║ WHY IT FAILED: ║`);
402
+ console.error(`║ ${whyItFailed.substring(0, 76).padEnd(76)} ║`);
403
+ console.error('╠──────────────────────────────────────────────────────────────────────────────╣');
404
+ console.error(`║ User: ${(userId || 'unknown').substring(0, 60).padEnd(60)}║`);
405
+ console.error(`║ Session: ${sessionToken.substring(0, 8)}... ║`);
406
+ console.error(`║ Resolution: ${(resolution || 'Check IDP logs').substring(0, 60).padEnd(60)}║`);
407
+ console.error('╚══════════════════════════════════════════════════════════════════════════════╝');
408
+ // Also log the full response for detailed debugging
409
+ console.error('[AUTH_REFRESH] Full IDP error response:', JSON.stringify(responseData, null, 2).substring(0, 1000));
410
+ // If IDP signals to discard token, clear it from Redis
411
+ if (discardToken) {
412
+ console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP signaled discard_token', {
413
+ reason: 'IDP_DISCARD_TOKEN',
414
+ errorCode,
415
+ userId,
416
+ sessionToken: sessionToken.substring(0, 8) + '...',
417
+ hadRefreshToken: !!currentSession.idpRefreshToken,
418
+ stack: new Error().stack
419
+ });
420
+ await (0, session_store_1.updateSession)(sessionToken, {
421
+ idpRefreshToken: '',
422
+ idpRefreshTokenExpires: undefined,
423
+ refreshTokenClearedAt: Date.now(),
424
+ refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${errorCode}`
425
+ });
426
+ }
427
+ return server_1.NextResponse.json({
428
+ error: errorMessage,
429
+ code: errorCode,
430
+ discardToken,
431
+ retryable,
432
+ resolution,
433
+ status: refreshResponse.status
434
+ }, { status: refreshResponse.status });
435
+ }
436
+ // Validate PayEz canonical envelope for success responses
437
+ const isCompliant = responseData && typeof responseData === 'object' &&
438
+ Object.prototype.hasOwnProperty.call(responseData, 'success') &&
439
+ (responseData.success === true ? Object.prototype.hasOwnProperty.call(responseData, 'data') : Object.prototype.hasOwnProperty.call(responseData, 'error')) &&
440
+ Object.prototype.hasOwnProperty.call(responseData, 'meta');
441
+ if (!isCompliant) {
442
+ console.error('[AUTH_REFRESH] Upstream non-compliant IDP response', { bodySample: responseData });
443
+ return server_1.NextResponse.json({
444
+ error: 'Upstream non-compliance',
445
+ code: 'UPSTREAM_SERVICE_ERROR',
446
+ retryable: true,
447
+ discardToken: false
448
+ }, { status: 502 });
449
+ }
450
+ if (responseData.success !== true || !responseData.data) {
451
+ // Handle success:false with structured error
452
+ const idpError = responseData?.error || {};
453
+ const errorCode = idpError.code || 'UPSTREAM_VALIDATION_ERROR';
454
+ const discardToken = idpError.discard_token === true;
455
+ const retryable = idpError.retryable === true;
456
+ console.warn('[AUTH_REFRESH] IDP refresh unsuccessful', {
457
+ code: errorCode,
458
+ discardToken,
459
+ body: responseData
460
+ });
461
+ if (discardToken) {
462
+ console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: IDP success:false with discard_token', {
463
+ reason: 'IDP_SUCCESS_FALSE_DISCARD',
464
+ errorCode,
465
+ userId,
466
+ sessionToken: sessionToken.substring(0, 8) + '...',
467
+ hadRefreshToken: !!currentSession.idpRefreshToken,
468
+ stack: new Error().stack
469
+ });
470
+ await (0, session_store_1.updateSession)(sessionToken, {
471
+ idpRefreshToken: '',
472
+ idpRefreshTokenExpires: undefined,
473
+ refreshTokenClearedAt: Date.now(),
474
+ refreshTokenClearedReason: `IDP_SUCCESS_FALSE_DISCARD:${errorCode}`
475
+ });
476
+ }
477
+ return server_1.NextResponse.json({
478
+ error: idpError.message || 'Token refresh failed',
479
+ code: errorCode,
480
+ discardToken,
481
+ retryable,
482
+ resolution: idpError.resolution || null
483
+ }, { status: refreshResponse.status || 400 });
484
+ }
485
+ // Extract tokens from response
486
+ const payload = responseData.data;
487
+ const accessToken = payload?.access_token;
488
+ const refreshToken = payload?.refresh_token;
489
+ if (!accessToken) {
490
+ console.error('[AUTH_REFRESH] Missing access token in IDP response');
491
+ return server_1.NextResponse.json({
492
+ error: 'Invalid token response from IDP',
493
+ code: 'INTERNAL_SERVER_ERROR'
494
+ }, { status: 500 });
495
+ }
496
+ // Decode and compute token expiries
497
+ let decodedAccessToken;
498
+ let accessTokenExpires;
499
+ let computedRefreshTokenExpires;
500
+ try {
501
+ const result = (0, token_expiry_1.computeTokenExpiries)({ accessToken, refreshToken, preferJwt: true });
502
+ decodedAccessToken = result.decodedAccessToken;
503
+ accessTokenExpires = result.accessTokenExpires;
504
+ computedRefreshTokenExpires = result.refreshTokenExpires;
505
+ console.info('[AUTH_REFRESH] Successfully decoded new token pair', {
506
+ accessTokenExpires: new Date(accessTokenExpires).toISOString(),
507
+ refreshTokenExpires: computedRefreshTokenExpires ? new Date(computedRefreshTokenExpires).toISOString() : null
508
+ });
509
+ }
510
+ catch (decodeError) {
511
+ console.error('[AUTH_REFRESH] Failed to compute token expiries', { error: decodeError });
512
+ return server_1.NextResponse.json({
513
+ error: 'Failed to decode JWT tokens',
514
+ code: 'INTERNAL_SERVER_ERROR'
515
+ }, { status: 500 });
516
+ }
517
+ // Extract 2FA claims from the new access token
518
+ let amrClaims = [];
519
+ if (decodedAccessToken.amr) {
520
+ try {
521
+ amrClaims = typeof decodedAccessToken.amr === 'string'
522
+ ? JSON.parse(decodedAccessToken.amr)
523
+ : decodedAccessToken.amr;
524
+ }
525
+ catch (e) {
526
+ console.warn('[AUTH_REFRESH] Failed to parse AMR claims', { amr: decodedAccessToken.amr });
527
+ amrClaims = currentSession.authenticationMethods || [];
528
+ }
529
+ }
530
+ else {
531
+ amrClaims = currentSession.authenticationMethods || [];
532
+ }
533
+ const acrLevel = String(decodedAccessToken.acr || currentSession.authenticationLevel || '1');
534
+ // Extract MFA timing claims
535
+ const mfaTime = decodedAccessToken.mfa_time ? parseInt(decodedAccessToken.mfa_time) * 1000 : currentSession.mfaCompletedAt;
536
+ const mfaExpires = decodedAccessToken.mfa_expires ? parseInt(decodedAccessToken.mfa_expires) * 1000 : currentSession.mfaExpiresAt;
537
+ const mfaValidityHours = decodedAccessToken.mfa_validity_hours ? parseInt(decodedAccessToken.mfa_validity_hours) : currentSession.mfaValidityHours;
538
+ // Update session with new tokens
539
+ const hasNewRefresh = typeof refreshToken === 'string' && refreshToken.length > 0;
540
+ const newRefreshTokenExpires = hasNewRefresh ? computedRefreshTokenExpires : undefined;
541
+ // CRITICAL: Log if we're about to clear the refresh token due to missing new token
542
+ if (!hasNewRefresh && currentSession.idpRefreshToken) {
543
+ console.error('[AUTH_REFRESH] ⚠️ REFRESH_TOKEN_REMOVAL: No new refresh token in IDP response', {
544
+ reason: 'NO_NEW_REFRESH_TOKEN_IN_RESPONSE',
545
+ userId,
546
+ sessionToken: sessionToken.substring(0, 8) + '...',
547
+ hadRefreshToken: true,
548
+ refreshTokenFromResponse: refreshToken,
549
+ refreshTokenType: typeof refreshToken,
550
+ payloadKeys: Object.keys(payload || {}),
551
+ stack: new Error().stack
552
+ });
553
+ }
554
+ // Keep existing refresh token if IDP doesn't provide a new one
555
+ // Only clear if IDP explicitly signals discard_token=true (handled in error paths)
556
+ // NOTE: Use normalized field names (idp* prefix) per SessionData interface
557
+ // CRITICAL: Extract kid from JWT header - IDP may rotate keys during refresh
558
+ const newBearerKeyId = (0, token_utils_1.extractKidFromToken)(accessToken);
559
+ if (newBearerKeyId) {
560
+ console.log('[AUTH_REFRESH] Extracted bearerKeyId (kid) from new JWT header:', newBearerKeyId);
561
+ }
562
+ else {
563
+ console.warn('[AUTH_REFRESH] No kid found in new JWT header');
564
+ }
565
+ const sessionUpdate = {
566
+ ...currentSession,
567
+ idpAccessToken: accessToken,
568
+ idpAccessTokenExpires: accessTokenExpires,
569
+ idpRefreshToken: hasNewRefresh ? refreshToken : currentSession.idpRefreshToken,
570
+ idpRefreshTokenExpires: hasNewRefresh ? newRefreshTokenExpires : currentSession.idpRefreshTokenExpires,
571
+ decodedAccessToken: decodedAccessToken,
572
+ // Bearer key ID from JWT header (may change on key rotation)
573
+ bearerKeyId: newBearerKeyId || currentSession.bearerKeyId,
574
+ authenticationMethods: amrClaims,
575
+ authenticationLevel: acrLevel,
576
+ mfaVerified: amrClaims.includes('mfa') || currentSession.mfaVerified,
577
+ mfaCompletedAt: mfaTime,
578
+ mfaExpiresAt: mfaExpires,
579
+ mfaValidityHours: mfaValidityHours
580
+ };
581
+ await (0, session_store_1.updateSession)(sessionToken, sessionUpdate);
582
+ console.info('[AUTH_REFRESH] Token refreshed successfully', {
583
+ expiresAt: new Date(accessTokenExpires).toISOString(),
584
+ userId,
585
+ hasNewRefreshToken: hasNewRefresh,
586
+ tokenPreview: accessToken ? accessToken.substring(0, 20) + '...' : 'none'
587
+ });
588
+ }
589
+ catch (error) {
590
+ console.error('[AUTH_REFRESH] Error during token refresh', { error });
591
+ return server_1.NextResponse.json({
592
+ error: 'Token refresh error',
593
+ code: 'INTERNAL_SERVER_ERROR'
594
+ }, { status: 500 });
595
+ }
596
+ finally {
597
+ if (weAcquiredLock) {
598
+ await (0, session_store_1.releaseRefreshLock)(sessionToken, requestId, releaseLockVersion);
599
+ }
600
+ }
601
+ // Load the latest session to return basic status
602
+ const latest = await (0, session_store_1.getSession)(sessionToken);
603
+ if (!latest?.idpAccessToken) {
604
+ return server_1.NextResponse.json({
605
+ error: 'No access token after refresh',
606
+ code: 'INTERNAL_SERVER_ERROR'
607
+ }, { status: 500 });
608
+ }
609
+ return server_1.NextResponse.json({
610
+ refreshed: true,
611
+ accessTokenExpires: latest.idpAccessTokenExpires,
612
+ hasRefreshToken: !!latest.idpRefreshToken,
613
+ });
614
+ }
615
+ catch (err) {
616
+ console.error('[AUTH_REFRESH] Unexpected error', { error: err?.message || String(err) });
617
+ return server_1.NextResponse.json({
618
+ error: 'Unexpected error during refresh',
619
+ code: 'INTERNAL_SERVER_ERROR'
620
+ }, { status: 500 });
621
+ }
622
+ };
623
+ }
624
+ /**
625
+ * Default export for backward compatibility
626
+ * Requires environment variables: IDP_URL, CLIENT_ID, NEXTAUTH_SECRET
627
+ */
628
+ exports.POST = createRefreshHandler({
629
+ idpBaseUrl: process.env.IDP_URL,
630
+ clientId: process.env.CLIENT_ID || 'payez_default_client',
631
+ nextAuthSecret: process.env.NEXTAUTH_SECRET || '',
632
+ refreshEndpoint: '/api/ExternalAuth/refresh'
633
+ });