@payez/next-mvp 4.1.9 → 4.1.11

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 (164) hide show
  1. package/README.md +792 -792
  2. package/dist/api-handlers/auth/refresh.js +38 -15
  3. package/dist/auth/better-auth.js +4 -3
  4. package/dist/components/account/MobileNavDrawer.js +18 -18
  5. package/dist/components/account/UserAvatarMenu.js +1 -1
  6. package/dist/components/admin/AlertSettingsTab.js +40 -40
  7. package/dist/components/admin/LoggingSettingsTab.js +28 -28
  8. package/dist/lib/ensure-fresh-access-token.js +42 -8
  9. package/dist/lib/idp-fetch.js +25 -9
  10. package/dist/lib/session-store.d.ts +1 -0
  11. package/dist/lib/session-store.js +12 -8
  12. package/dist/lib/token-lifecycle.d.ts +2 -0
  13. package/dist/lib/token-lifecycle.js +21 -3
  14. package/dist/pages/login/page.js +28 -28
  15. package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
  16. package/package.json +893 -893
  17. package/scripts/dev-broker.ps1 +35 -35
  18. package/scripts/dev-local.ps1 +45 -45
  19. package/src/api/auth-handler.ts +548 -548
  20. package/src/api-handlers/account/change-password.ts +142 -142
  21. package/src/api-handlers/account/update-phone.ts +79 -79
  22. package/src/api-handlers/account/verify-email.ts +125 -125
  23. package/src/api-handlers/account/verify-sms.ts +125 -125
  24. package/src/api-handlers/admin/analytics.ts +443 -443
  25. package/src/api-handlers/admin/audit.ts +223 -223
  26. package/src/api-handlers/admin/index.ts +63 -63
  27. package/src/api-handlers/admin/redis-sessions.ts +251 -251
  28. package/src/api-handlers/admin/sessions.ts +318 -318
  29. package/src/api-handlers/admin/site-logs.ts +365 -365
  30. package/src/api-handlers/admin/users.ts +242 -242
  31. package/src/api-handlers/admin/vibe-data.ts +324 -324
  32. package/src/api-handlers/auth/refresh.ts +705 -682
  33. package/src/api-handlers/auth/signout.ts +199 -199
  34. package/src/api-handlers/auth/status.ts +20 -20
  35. package/src/api-handlers/auth/update-session.ts +110 -110
  36. package/src/api-handlers/auth/verify-code.ts +112 -112
  37. package/src/api-handlers/session/refresh-viability.ts +36 -36
  38. package/src/api-handlers/test/force-expire.ts +60 -60
  39. package/src/auth/auth-decision.ts +229 -229
  40. package/src/auth/better-auth.ts +467 -466
  41. package/src/auth/route-config.ts +219 -219
  42. package/src/auth/types/auth-types.ts +555 -555
  43. package/src/auth/types/index.ts +7 -7
  44. package/src/auth/utils/idp-client.ts +445 -445
  45. package/src/auth/utils/index.ts +6 -6
  46. package/src/auth/utils/token-utils.ts +243 -243
  47. package/src/client/AuthContext.tsx +143 -143
  48. package/src/client/fetch-with-auth.ts +47 -47
  49. package/src/components/SessionSync.tsx +138 -138
  50. package/src/components/SignalRHealthCheck.tsx +131 -131
  51. package/src/components/account/MobileNavDrawer.tsx +305 -305
  52. package/src/components/account/UserAvatarMenu.tsx +266 -266
  53. package/src/components/account/index.ts +13 -13
  54. package/src/components/admin/AlertSettingsTab.tsx +728 -728
  55. package/src/components/admin/AnalyticsTab.tsx +703 -703
  56. package/src/components/admin/DataBrowserTab.tsx +505 -505
  57. package/src/components/admin/LoggingSettingsTab.tsx +665 -665
  58. package/src/components/admin/SessionsTab.tsx +414 -414
  59. package/src/components/admin/StatsTab.tsx +379 -379
  60. package/src/components/admin/VibeAdminLayout.tsx +187 -187
  61. package/src/components/admin/index.ts +59 -59
  62. package/src/components/auth/FederatedAuthSection.tsx +95 -95
  63. package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
  64. package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
  65. package/src/components/auth/TraditionalAuthSection.tsx +99 -99
  66. package/src/components/recovery/CompleteStep.tsx +36 -36
  67. package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
  68. package/src/components/recovery/SelectMethodStep.tsx +73 -73
  69. package/src/components/recovery/SetPasswordStep.tsx +97 -97
  70. package/src/components/recovery/VerifyCodeStep.tsx +90 -90
  71. package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
  72. package/src/components/reserved/ReservedStatusBox.tsx +118 -118
  73. package/src/components/ui/BetaBadge.tsx +58 -58
  74. package/src/components/ui/Footer.tsx +93 -93
  75. package/src/config/env.ts +57 -57
  76. package/src/config/logger.ts +62 -62
  77. package/src/config/vibe-log-transport.ts +264 -264
  78. package/src/hooks/useAuth.ts +117 -117
  79. package/src/hooks/useAuthSettings.ts +97 -97
  80. package/src/hooks/useAvailableProviders.ts +120 -120
  81. package/src/hooks/usePasswordValidation.ts +127 -127
  82. package/src/hooks/usePublicAuthSettings.ts +149 -149
  83. package/src/hooks/useSessionExpiration.ts +101 -101
  84. package/src/hooks/useViabilitySession.ts +336 -336
  85. package/src/index.ts +60 -60
  86. package/src/lib/api-handler.ts +643 -643
  87. package/src/lib/app-slug.ts +178 -178
  88. package/src/lib/ensure-fresh-access-token.ts +369 -335
  89. package/src/lib/geolocation.ts +265 -265
  90. package/src/lib/idp-fetch.ts +26 -10
  91. package/src/lib/jwt-decode.ts +82 -82
  92. package/src/lib/roles.ts +177 -177
  93. package/src/lib/session-store.ts +4 -1
  94. package/src/lib/site-logger.ts +245 -245
  95. package/src/lib/standardized-client-api.ts +901 -901
  96. package/src/lib/test-aware-get-token.ts +41 -41
  97. package/src/lib/token-lifecycle.ts +30 -3
  98. package/src/lib/user-agent-parser.ts +252 -252
  99. package/src/logging/api/admin-analytics.ts +51 -51
  100. package/src/logging/api/audit-log.ts +53 -53
  101. package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
  102. package/src/logging/components/AuditLogViewer.tsx +125 -125
  103. package/src/logging/components/ErrorMetricsCard.tsx +98 -98
  104. package/src/logging/components/HealthMetricsCard.tsx +70 -70
  105. package/src/logging/hooks/useAdminAnalytics.ts +22 -22
  106. package/src/logging/hooks/useAuditLog.ts +24 -24
  107. package/src/logging/hooks/useErrorMetrics.ts +40 -40
  108. package/src/logging/hooks/useHealthMetrics.ts +44 -44
  109. package/src/logging/index.ts +18 -18
  110. package/src/logging/types/analytics.ts +81 -81
  111. package/src/logging/types/audit.ts +31 -31
  112. package/src/logging/types/index.ts +3 -3
  113. package/src/middleware/create-middleware.ts +663 -663
  114. package/src/middleware/rbac-check.ts +279 -279
  115. package/src/middleware/twofa-presets.ts +224 -224
  116. package/src/pages/admin-login/page.tsx +221 -221
  117. package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
  118. package/src/pages/admin-page-permissions/index.ts +7 -7
  119. package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
  120. package/src/pages/admin-roles/modals.tsx +469 -469
  121. package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
  122. package/src/pages/client-admin/index.ts +33 -33
  123. package/src/pages/coming-soon/page.tsx +83 -83
  124. package/src/pages/login/page.tsx +456 -456
  125. package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
  126. package/src/pages/profile/index.ts +9 -9
  127. package/src/pages/profile/page.tsx +166 -166
  128. package/src/pages/recovery/page.tsx +234 -234
  129. package/src/pages/roles/MyRolesPage.tsx +211 -211
  130. package/src/pages/roles/components.tsx +294 -294
  131. package/src/pages/roles/index.ts +17 -17
  132. package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
  133. package/src/pages/security/index.ts +9 -9
  134. package/src/pages/security/page.tsx +507 -507
  135. package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
  136. package/src/pages/settings/index.ts +9 -9
  137. package/src/pages/settings/page.tsx +47 -47
  138. package/src/pages/showcase/ShowcasePage.tsx +532 -532
  139. package/src/pages/showcase/index.ts +13 -13
  140. package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
  141. package/src/pages/test-env/JwtInspectPage.tsx +456 -456
  142. package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
  143. package/src/pages/test-env/TestEnvPage.tsx +118 -118
  144. package/src/pages/test-env/index.ts +25 -25
  145. package/src/pages/verify-code/page.tsx +652 -652
  146. package/src/routes/account/update-phone.ts +13 -13
  147. package/src/routes/auth/logout.ts +108 -108
  148. package/src/routes/auth/nextauth.ts +45 -45
  149. package/src/routes/auth/settings.ts +75 -75
  150. package/src/routes/auth/viability.ts +224 -224
  151. package/src/server/auth-guard.ts +170 -170
  152. package/src/server/slim-middleware.ts +117 -117
  153. package/src/server/with-auth.ts +93 -93
  154. package/src/stores/authStore.ts +1899 -1899
  155. package/src/templates/instrumentation.ts +41 -41
  156. package/src/utils/logout.ts +30 -30
  157. package/src/vibe/client.ts +590 -590
  158. package/src/vibe/enterprise-auth.ts +208 -208
  159. package/src/vibe/errors.ts +185 -185
  160. package/src/vibe/generic.ts +431 -431
  161. package/src/vibe/hooks/index.ts +367 -367
  162. package/src/vibe/index.ts +132 -132
  163. package/src/vibe/sessions.ts +551 -551
  164. package/src/vibe/types.ts +577 -577
@@ -1,335 +1,369 @@
1
- /**
2
- * ensureFreshAccessToken — server-side preflight refresh.
3
- *
4
- * Returns a non-expired IDP access token for a given session. Refreshes
5
- * proactively when the stored token is within the safety window of expiry,
6
- * using the same Redis lock and IDP wire shape as `createRefreshHandler`.
7
- *
8
- * Designed for proxy-route auth helpers that today read the stored token
9
- * blindly and let the backend reject it with a 401. Calling this instead of
10
- * `getSession(...).idpAccessToken` means a good token client never sends
11
- * credentials it already knows are invalid.
12
- *
13
- * Single-use refresh-token semantics are preserved via Redis-backed
14
- * single-flight locking (see `acquireRefreshLock`).
15
- */
16
- import {
17
- getSession,
18
- getBetterAuthSession,
19
- updateSession,
20
- acquireRefreshLock,
21
- releaseRefreshLock,
22
- checkRefreshLock,
23
- } from './session-store';
24
- import { computeTokenExpiries } from './token-expiry';
25
- import { extractKidFromToken } from '../auth/utils/token-utils';
26
-
27
- export interface EnsureFreshConfig {
28
- idpBaseUrl: string;
29
- clientId: string;
30
- refreshEndpoint?: string;
31
- }
32
-
33
- export interface EnsureFreshOptions {
34
- /** Refresh if the access token is within this many ms of expiry. Default 60_000. */
35
- safetyWindowMs?: number;
36
- /** Max wait while another caller holds the refresh lock. Default 5000. */
37
- lockWaitMs?: number;
38
- /** Optional caller request id for lock attribution. */
39
- requestId?: string;
40
- }
41
-
42
- export type EnsureFreshResult =
43
- | {
44
- ok: true;
45
- accessToken: string;
46
- accessTokenExpires: number;
47
- /** True if we refreshed (or a concurrent refresh completed); false if the stored token was already fresh. */
48
- refreshed: boolean;
49
- }
50
- | {
51
- ok: false;
52
- code: string;
53
- message: string;
54
- status: number;
55
- terminal?: boolean;
56
- discardToken?: boolean;
57
- retryable?: boolean;
58
- resolution?: string;
59
- };
60
-
61
- const DEFAULT_SAFETY_WINDOW_MS = 60_000;
62
- const DEFAULT_LOCK_WAIT_MS = 5000;
63
-
64
- function decodeJwtExp(token: string): number {
65
- const parts = token.split('.');
66
- if (parts.length !== 3) return -1;
67
- try {
68
- const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
69
- return (payload.exp || 0) * 1000;
70
- } catch {
71
- return -1;
72
- }
73
- }
74
-
75
- export async function ensureFreshAccessToken(
76
- sessionToken: string,
77
- config: EnsureFreshConfig,
78
- options: EnsureFreshOptions = {}
79
- ): Promise<EnsureFreshResult> {
80
- const { idpBaseUrl, clientId, refreshEndpoint = '/api/ExternalAuth/refresh' } = config;
81
- const safetyWindowMs = options.safetyWindowMs ?? DEFAULT_SAFETY_WINDOW_MS;
82
- const lockWaitMs = options.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS;
83
- const requestId = options.requestId ?? `ensure_fresh_${Date.now()}`;
84
-
85
- let session = await getSession(sessionToken);
86
- if (!session || !session.idpRefreshToken) {
87
- const baSession = await getBetterAuthSession(sessionToken);
88
- if (baSession?.idpRefreshToken) {
89
- session = baSession;
90
- }
91
- }
92
- if (!session) {
93
- return { ok: false, code: 'NO_SESSION', message: 'No session for token', status: 401, terminal: true };
94
- }
95
-
96
- const storedToken = session.idpAccessToken;
97
- if (!storedToken) {
98
- return { ok: false, code: 'NO_TOKEN', message: 'No IDP access token in session', status: 401, terminal: true };
99
- }
100
-
101
- const now = Date.now();
102
- const redisExpires = session.idpAccessTokenExpires ?? 0;
103
- const jwtExpires = decodeJwtExp(storedToken);
104
- // Use the smaller of the two to be conservative — Redis can be stale, JWT exp is authoritative.
105
- const effectiveExpires = jwtExpires > 0 ? Math.min(redisExpires || jwtExpires, jwtExpires) : redisExpires;
106
- const msUntilExpiry = effectiveExpires - now;
107
-
108
- if (msUntilExpiry > safetyWindowMs) {
109
- return { ok: true, accessToken: storedToken, accessTokenExpires: effectiveExpires, refreshed: false };
110
- }
111
-
112
- if (!session.idpRefreshToken) {
113
- return {
114
- ok: false,
115
- code: 'NO_REFRESH_TOKEN',
116
- message: 'Access token expired and no refresh token available',
117
- status: 401,
118
- terminal: true,
119
- resolution: 'User must re-authenticate',
120
- };
121
- }
122
-
123
- const lock = await acquireRefreshLock(sessionToken, requestId, lockWaitMs);
124
- let weHoldLock = false;
125
- let releaseVersion: number | undefined;
126
-
127
- if (!lock.acquired) {
128
- const existing = await checkRefreshLock(sessionToken);
129
- if (!existing || existing.acquiredBy !== requestId) {
130
- const startWait = Date.now();
131
- while (Date.now() - startWait < lockWaitMs) {
132
- await new Promise(r => setTimeout(r, 200));
133
- const stillLocked = await checkRefreshLock(sessionToken);
134
- if (!stillLocked) {
135
- let after = await getSession(sessionToken);
136
- if (!after || !after.idpRefreshToken) {
137
- const baAfter = await getBetterAuthSession(sessionToken);
138
- if (baAfter?.idpRefreshToken) after = baAfter;
139
- }
140
- if (after?.idpAccessToken && after.idpAccessTokenExpires) {
141
- const remaining = after.idpAccessTokenExpires - Date.now();
142
- if (remaining > safetyWindowMs) {
143
- return {
144
- ok: true,
145
- accessToken: after.idpAccessToken,
146
- accessTokenExpires: after.idpAccessTokenExpires,
147
- refreshed: true,
148
- };
149
- }
150
- }
151
- break;
152
- }
153
- }
154
- return {
155
- ok: false,
156
- code: 'CONFLICT',
157
- message: 'Refresh already in progress',
158
- status: 409,
159
- retryable: true,
160
- };
161
- }
162
- } else {
163
- weHoldLock = true;
164
- releaseVersion = lock.lockInfo?.lockVersion;
165
- }
166
-
167
- try {
168
- // Re-check after lock — another caller may have already refreshed.
169
- let latest = await getSession(sessionToken);
170
- if (!latest || !latest.idpRefreshToken) {
171
- const baLatest = await getBetterAuthSession(sessionToken);
172
- if (baLatest?.idpRefreshToken) latest = baLatest;
173
- }
174
- if (latest?.idpAccessToken && latest.idpAccessTokenExpires) {
175
- const latestRemaining = latest.idpAccessTokenExpires - Date.now();
176
- const latestJwtExp = decodeJwtExp(latest.idpAccessToken);
177
- const stillStale = latestRemaining <= safetyWindowMs || (latestJwtExp > 0 && latestJwtExp <= Date.now());
178
- if (!stillStale) {
179
- return {
180
- ok: true,
181
- accessToken: latest.idpAccessToken,
182
- accessTokenExpires: latest.idpAccessTokenExpires,
183
- refreshed: true,
184
- };
185
- }
186
- }
187
-
188
- // Build refresh request body — wire shape must match what the IDP expects.
189
- let authMethods: string[] = [];
190
- if (Array.isArray(session.authenticationMethods)) {
191
- authMethods = session.authenticationMethods;
192
- } else if (typeof session.authenticationMethods === 'string') {
193
- try { authMethods = JSON.parse(session.authenticationMethods); } catch { /* fall through */ }
194
- }
195
- const isOAuthSession = !!session.oauthProvider;
196
- if (authMethods.length === 0 && isOAuthSession) {
197
- authMethods = ['pwd', 'mfa'];
198
- }
199
- const twoFactorMethod =
200
- authMethods.find(m => ['sms', 'totp', 'email'].includes(m)) ||
201
- session.mfaMethod ||
202
- (isOAuthSession ? 'oauth' : null);
203
-
204
- let acrValue = String(session.authenticationLevel ?? '1');
205
- if (isOAuthSession && session.mfaVerified && acrValue === '1') {
206
- acrValue = '2';
207
- }
208
-
209
- const body: Record<string, unknown> = {
210
- refresh_token: session.idpRefreshToken,
211
- amr: authMethods,
212
- acr: acrValue,
213
- };
214
- if (session.mfaVerified) body.two_factor_verified = true;
215
- if (twoFactorMethod) body.two_factor_method = twoFactorMethod;
216
- if (session.mfaCompletedAt) body.two_factor_completed_at = new Date(session.mfaCompletedAt).toISOString();
217
-
218
- let idpResponse: Response;
219
- try {
220
- idpResponse = await fetch(`${idpBaseUrl}${refreshEndpoint}`, {
221
- method: 'POST',
222
- headers: { 'Content-Type': 'application/json', 'X-Client-Id': clientId },
223
- body: JSON.stringify(body),
224
- });
225
- } catch (err) {
226
- return {
227
- ok: false,
228
- code: 'UPSTREAM_SERVICE_UNAVAILABLE',
229
- message: err instanceof Error ? err.message : 'IDP unreachable',
230
- status: 503,
231
- retryable: true,
232
- };
233
- }
234
-
235
- let responseData: any;
236
- try {
237
- const text = await idpResponse.text();
238
- if (!text.trim()) {
239
- return { ok: false, code: 'UPSTREAM_SERVICE_ERROR', message: 'Empty response from IDP', status: 502, retryable: true };
240
- }
241
- responseData = JSON.parse(text);
242
- } catch (err) {
243
- return { ok: false, code: 'UPSTREAM_SERVICE_ERROR', message: 'Invalid JSON from IDP', status: 502, retryable: true };
244
- }
245
-
246
- if (!idpResponse.ok) {
247
- const idpError = responseData?.error || {};
248
- const code = idpError.code || 'UNKNOWN_ERROR';
249
- const discardToken = idpResponse.status === 401 || idpError.discard_token === true;
250
- const retryable = idpResponse.status !== 401 && idpError.retryable === true;
251
- if (discardToken) {
252
- await updateSession(sessionToken, {
253
- idpRefreshToken: '',
254
- idpRefreshTokenExpires: undefined,
255
- refreshTokenClearedAt: Date.now(),
256
- refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${code}`,
257
- });
258
- }
259
- return {
260
- ok: false,
261
- code,
262
- message: idpError.message || 'Token refresh failed',
263
- status: idpResponse.status,
264
- discardToken,
265
- retryable,
266
- resolution: idpError.resolution,
267
- terminal: discardToken,
268
- };
269
- }
270
-
271
- // Validate canonical envelope.
272
- if (
273
- !responseData ||
274
- typeof responseData !== 'object' ||
275
- responseData.success !== true ||
276
- !responseData.data
277
- ) {
278
- return { ok: false, code: 'UPSTREAM_SERVICE_ERROR', message: 'Non-compliant IDP envelope', status: 502, retryable: true };
279
- }
280
-
281
- const newAccess = responseData.data.access_token;
282
- const newRefresh = responseData.data.refresh_token;
283
- if (!newAccess) {
284
- return { ok: false, code: 'INTERNAL_SERVER_ERROR', message: 'Missing access token in IDP response', status: 500 };
285
- }
286
-
287
- let accessTokenExpires: number;
288
- let refreshTokenExpires: number | undefined;
289
- let decoded: any;
290
- try {
291
- const r = computeTokenExpiries({ accessToken: newAccess, refreshToken: newRefresh, preferJwt: true });
292
- decoded = r.decodedAccessToken;
293
- accessTokenExpires = r.accessTokenExpires;
294
- refreshTokenExpires = r.refreshTokenExpires;
295
- } catch {
296
- return { ok: false, code: 'INTERNAL_SERVER_ERROR', message: 'Failed to decode new tokens', status: 500 };
297
- }
298
-
299
- let amrClaims: string[] = [];
300
- if (decoded?.amr) {
301
- try {
302
- amrClaims = typeof decoded.amr === 'string' ? JSON.parse(decoded.amr) : decoded.amr;
303
- } catch {
304
- amrClaims = session.authenticationMethods || [];
305
- }
306
- } else {
307
- amrClaims = session.authenticationMethods || [];
308
- }
309
- const acrLevel = String(decoded?.acr || session.authenticationLevel || '1');
310
- const hasNewRefresh = typeof newRefresh === 'string' && newRefresh.length > 0;
311
- const newKid = extractKidFromToken(newAccess);
312
-
313
- await updateSession(sessionToken, {
314
- ...session,
315
- idpAccessToken: newAccess,
316
- idpAccessTokenExpires: accessTokenExpires,
317
- idpRefreshToken: hasNewRefresh ? newRefresh : session.idpRefreshToken,
318
- idpRefreshTokenExpires: hasNewRefresh ? refreshTokenExpires : session.idpRefreshTokenExpires,
319
- decodedAccessToken: decoded,
320
- bearerKeyId: newKid || session.bearerKeyId,
321
- authenticationMethods: amrClaims,
322
- authenticationLevel: acrLevel,
323
- mfaVerified: amrClaims.includes('mfa') || session.mfaVerified,
324
- mfaCompletedAt: decoded?.mfa_time ? parseInt(decoded.mfa_time) * 1000 : session.mfaCompletedAt,
325
- mfaExpiresAt: decoded?.mfa_expires ? parseInt(decoded.mfa_expires) * 1000 : session.mfaExpiresAt,
326
- mfaValidityHours: decoded?.mfa_validity_hours ? parseInt(decoded.mfa_validity_hours) : session.mfaValidityHours,
327
- });
328
-
329
- return { ok: true, accessToken: newAccess, accessTokenExpires, refreshed: true };
330
- } finally {
331
- if (weHoldLock) {
332
- await releaseRefreshLock(sessionToken, requestId, releaseVersion);
333
- }
334
- }
335
- }
1
+ /**
2
+ * ensureFreshAccessToken — server-side preflight refresh.
3
+ *
4
+ * Returns a non-expired IDP access token for a given session. Refreshes
5
+ * proactively when the stored token is within the safety window of expiry,
6
+ * using the same Redis lock and IDP wire shape as `createRefreshHandler`.
7
+ *
8
+ * Designed for proxy-route auth helpers that today read the stored token
9
+ * blindly and let the backend reject it with a 401. Calling this instead of
10
+ * `getSession(...).idpAccessToken` means a good token client never sends
11
+ * credentials it already knows are invalid.
12
+ *
13
+ * Single-use refresh-token semantics are preserved via Redis-backed
14
+ * single-flight locking (see `acquireRefreshLock`).
15
+ */
16
+ import {
17
+ getSession,
18
+ getBetterAuthSession,
19
+ updateSession,
20
+ acquireRefreshLock,
21
+ releaseRefreshLock,
22
+ checkRefreshLock,
23
+ } from './session-store';
24
+ import { computeTokenExpiries } from './token-expiry';
25
+ import { extractKidFromToken } from '../auth/utils/token-utils';
26
+
27
+ export interface EnsureFreshConfig {
28
+ idpBaseUrl: string;
29
+ clientId: string;
30
+ refreshEndpoint?: string;
31
+ }
32
+
33
+ export interface EnsureFreshOptions {
34
+ /** Refresh if the access token is within this many ms of expiry. Default 60_000. */
35
+ safetyWindowMs?: number;
36
+ /** Max wait while another caller holds the refresh lock. Default 5000. */
37
+ lockWaitMs?: number;
38
+ /** Optional caller request id for lock attribution. */
39
+ requestId?: string;
40
+ }
41
+
42
+ export type EnsureFreshResult =
43
+ | {
44
+ ok: true;
45
+ accessToken: string;
46
+ accessTokenExpires: number;
47
+ /** True if we refreshed (or a concurrent refresh completed); false if the stored token was already fresh. */
48
+ refreshed: boolean;
49
+ }
50
+ | {
51
+ ok: false;
52
+ code: string;
53
+ message: string;
54
+ status: number;
55
+ terminal?: boolean;
56
+ discardToken?: boolean;
57
+ retryable?: boolean;
58
+ resolution?: string;
59
+ };
60
+
61
+ const DEFAULT_SAFETY_WINDOW_MS = 60_000;
62
+ const DEFAULT_LOCK_WAIT_MS = 5000;
63
+
64
+ function decodeJwtExp(token: string): number {
65
+ const parts = token.split('.');
66
+ if (parts.length !== 3) return -1;
67
+ try {
68
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
69
+ return (payload.exp || 0) * 1000;
70
+ } catch {
71
+ return -1;
72
+ }
73
+ }
74
+
75
+ export async function ensureFreshAccessToken(
76
+ sessionToken: string,
77
+ config: EnsureFreshConfig,
78
+ options: EnsureFreshOptions = {}
79
+ ): Promise<EnsureFreshResult> {
80
+ const { idpBaseUrl, clientId, refreshEndpoint = '/api/ExternalAuth/refresh' } = config;
81
+ const safetyWindowMs = options.safetyWindowMs ?? DEFAULT_SAFETY_WINDOW_MS;
82
+ const lockWaitMs = options.lockWaitMs ?? DEFAULT_LOCK_WAIT_MS;
83
+ const requestId = options.requestId ?? `ensure_fresh_${Date.now()}`;
84
+
85
+ let session = await getSession(sessionToken);
86
+ if (!session || !session.idpRefreshToken) {
87
+ const baSession = await getBetterAuthSession(sessionToken);
88
+ if (baSession?.idpRefreshToken) {
89
+ session = baSession;
90
+ }
91
+ }
92
+ if (!session) {
93
+ return { ok: false, code: 'NO_SESSION', message: 'No session for token', status: 401, terminal: true };
94
+ }
95
+
96
+ const storedToken = session.idpAccessToken;
97
+ if (!storedToken) {
98
+ return { ok: false, code: 'NO_TOKEN', message: 'No IDP access token in session', status: 401, terminal: true };
99
+ }
100
+
101
+ const now = Date.now();
102
+ const redisExpires = session.idpAccessTokenExpires ?? 0;
103
+ const jwtExpires = decodeJwtExp(storedToken);
104
+ // Use the smaller of the two to be conservative — Redis can be stale, JWT exp is authoritative.
105
+ const effectiveExpires = jwtExpires > 0 ? Math.min(redisExpires || jwtExpires, jwtExpires) : redisExpires;
106
+ const msUntilExpiry = effectiveExpires - now;
107
+
108
+ if (msUntilExpiry > safetyWindowMs) {
109
+ return { ok: true, accessToken: storedToken, accessTokenExpires: effectiveExpires, refreshed: false };
110
+ }
111
+
112
+ if (!session.idpRefreshToken) {
113
+ return {
114
+ ok: false,
115
+ code: 'NO_REFRESH_TOKEN',
116
+ message: 'Access token expired and no refresh token available',
117
+ status: 401,
118
+ terminal: true,
119
+ resolution: 'User must re-authenticate',
120
+ };
121
+ }
122
+
123
+ const lock = await acquireRefreshLock(sessionToken, requestId, lockWaitMs);
124
+ let weHoldLock = false;
125
+ let releaseVersion: number | undefined;
126
+
127
+ if (!lock.acquired) {
128
+ const existing = await checkRefreshLock(sessionToken);
129
+ if (!existing || existing.acquiredBy !== requestId) {
130
+ const startWait = Date.now();
131
+ while (Date.now() - startWait < lockWaitMs) {
132
+ await new Promise(r => setTimeout(r, 200));
133
+ const stillLocked = await checkRefreshLock(sessionToken);
134
+ if (!stillLocked) {
135
+ let after = await getSession(sessionToken);
136
+ if (!after || !after.idpRefreshToken) {
137
+ const baAfter = await getBetterAuthSession(sessionToken);
138
+ if (baAfter?.idpRefreshToken) after = baAfter;
139
+ }
140
+ if (after?.idpAccessToken && after.idpAccessTokenExpires) {
141
+ const remaining = after.idpAccessTokenExpires - Date.now();
142
+ if (remaining > safetyWindowMs) {
143
+ return {
144
+ ok: true,
145
+ accessToken: after.idpAccessToken,
146
+ accessTokenExpires: after.idpAccessTokenExpires,
147
+ refreshed: true,
148
+ };
149
+ }
150
+ }
151
+ break;
152
+ }
153
+ }
154
+ return {
155
+ ok: false,
156
+ code: 'CONFLICT',
157
+ message: 'Refresh already in progress',
158
+ status: 409,
159
+ retryable: true,
160
+ };
161
+ }
162
+ } else {
163
+ weHoldLock = true;
164
+ releaseVersion = lock.lockInfo?.lockVersion;
165
+ }
166
+
167
+ try {
168
+ // Re-check after lock — another caller may have already refreshed.
169
+ let latest = await getSession(sessionToken);
170
+ if (!latest || !latest.idpRefreshToken) {
171
+ const baLatest = await getBetterAuthSession(sessionToken);
172
+ if (baLatest?.idpRefreshToken) latest = baLatest;
173
+ }
174
+ if (latest?.idpAccessToken && latest.idpAccessTokenExpires) {
175
+ const latestRemaining = latest.idpAccessTokenExpires - Date.now();
176
+ const latestJwtExp = decodeJwtExp(latest.idpAccessToken);
177
+ const stillStale = latestRemaining <= safetyWindowMs || (latestJwtExp > 0 && latestJwtExp <= Date.now());
178
+ if (!stillStale) {
179
+ return {
180
+ ok: true,
181
+ accessToken: latest.idpAccessToken,
182
+ accessTokenExpires: latest.idpAccessTokenExpires,
183
+ refreshed: true,
184
+ };
185
+ }
186
+ }
187
+
188
+ // Build refresh request body — wire shape must match what the IDP expects.
189
+ let authMethods: string[] = [];
190
+ if (Array.isArray(session.authenticationMethods)) {
191
+ authMethods = session.authenticationMethods;
192
+ } else if (typeof session.authenticationMethods === 'string') {
193
+ try { authMethods = JSON.parse(session.authenticationMethods); } catch { /* fall through */ }
194
+ }
195
+ const isOAuthSession = !!session.oauthProvider;
196
+ if (authMethods.length === 0 && isOAuthSession) {
197
+ authMethods = ['pwd', 'mfa'];
198
+ }
199
+ const twoFactorMethod =
200
+ authMethods.find(m => ['sms', 'totp', 'email'].includes(m)) ||
201
+ session.mfaMethod ||
202
+ (isOAuthSession ? 'oauth' : null);
203
+
204
+ let acrValue = String(session.authenticationLevel ?? '1');
205
+ if (isOAuthSession && session.mfaVerified && acrValue === '1') {
206
+ acrValue = '2';
207
+ }
208
+
209
+ // WO-2: send the POST-lock current refresh token, not the pre-lock snapshot.
210
+ // `session` was read before we acquired the lock; a concurrent refresh that
211
+ // completed while we waited rotates the token, so the pre-lock value is stale
212
+ // and would draw an avoidable 401 (the CAS now catches the resulting wipe, but
213
+ // the round-trip is wasted). `latest` is the authoritative post-lock session.
214
+ // Auth-context (amr/acr/2FA) intentionally still derives from `session` — it is
215
+ // the identity context of THIS request, unchanged by a token rotation.
216
+ const sentRefreshToken = latest?.idpRefreshToken ?? session.idpRefreshToken;
217
+ const body: Record<string, unknown> = {
218
+ refresh_token: sentRefreshToken,
219
+ amr: authMethods,
220
+ acr: acrValue,
221
+ };
222
+ if (session.mfaVerified) body.two_factor_verified = true;
223
+ if (twoFactorMethod) body.two_factor_method = twoFactorMethod;
224
+ if (session.mfaCompletedAt) body.two_factor_completed_at = new Date(session.mfaCompletedAt).toISOString();
225
+
226
+ let idpResponse: Response;
227
+ try {
228
+ idpResponse = await fetch(`${idpBaseUrl}${refreshEndpoint}`, {
229
+ method: 'POST',
230
+ headers: { 'Content-Type': 'application/json', 'X-Client-Id': clientId },
231
+ body: JSON.stringify(body),
232
+ });
233
+ } catch (err) {
234
+ return {
235
+ ok: false,
236
+ code: 'UPSTREAM_SERVICE_UNAVAILABLE',
237
+ message: err instanceof Error ? err.message : 'IDP unreachable',
238
+ status: 503,
239
+ retryable: true,
240
+ };
241
+ }
242
+
243
+ let responseData: any;
244
+ try {
245
+ const text = await idpResponse.text();
246
+ if (!text.trim()) {
247
+ return { ok: false, code: 'UPSTREAM_SERVICE_ERROR', message: 'Empty response from IDP', status: 502, retryable: true };
248
+ }
249
+ responseData = JSON.parse(text);
250
+ } catch (err) {
251
+ return { ok: false, code: 'UPSTREAM_SERVICE_ERROR', message: 'Invalid JSON from IDP', status: 502, retryable: true };
252
+ }
253
+
254
+ if (!idpResponse.ok) {
255
+ const idpError = responseData?.error || {};
256
+ const code = idpError.code || 'UNKNOWN_ERROR';
257
+ let discardToken = idpResponse.status === 401 || idpError.discard_token === true;
258
+ const retryable = idpResponse.status !== 401 && idpError.retryable === true;
259
+ if (discardToken) {
260
+ // Race-safe discard (CAS): only clear if the refresh token we used is STILL
261
+ // current. A concurrent refresh may have already rotated it — our 401 is then
262
+ // stale/expected, and wiping here would silently log out a healthy session
263
+ // (the rotation-race wipe, QA 6873 site 1/2). Compare-and-skip if it changed;
264
+ // a concurrent rotation is NOT a terminal condition.
265
+ const postRefresh = await getSession(sessionToken);
266
+ // CAS compares against the token we ACTUALLY SENT (WO-2: sentRefreshToken,
267
+ // the post-lock value), not the pre-lock snapshot — otherwise a token rotated
268
+ // between pre-lock read and our send would be misjudged.
269
+ const tokenUnchanged =
270
+ !!sentRefreshToken && postRefresh?.idpRefreshToken === sentRefreshToken;
271
+ if (tokenUnchanged) {
272
+ await updateSession(sessionToken, {
273
+ idpRefreshToken: '',
274
+ idpRefreshTokenExpires: undefined,
275
+ refreshTokenClearedAt: Date.now(),
276
+ refreshTokenClearedReason: `IDP_DISCARD_TOKEN:${code}`,
277
+ });
278
+ } else {
279
+ // Concurrent refresh already rotated the token — our 401 is stale. Return the
280
+ // freshly-rotated token directly so the loser succeeds without a retry round-trip
281
+ // (race-fix follow-up #1).
282
+ discardToken = false;
283
+ if (postRefresh?.idpAccessToken && postRefresh.idpAccessTokenExpires) {
284
+ return {
285
+ ok: true,
286
+ accessToken: postRefresh.idpAccessToken,
287
+ accessTokenExpires: postRefresh.idpAccessTokenExpires,
288
+ refreshed: true,
289
+ };
290
+ }
291
+ }
292
+ }
293
+ return {
294
+ ok: false,
295
+ code,
296
+ message: idpError.message || 'Token refresh failed',
297
+ status: idpResponse.status,
298
+ discardToken,
299
+ retryable,
300
+ resolution: idpError.resolution,
301
+ terminal: discardToken,
302
+ };
303
+ }
304
+
305
+ // Validate canonical envelope.
306
+ if (
307
+ !responseData ||
308
+ typeof responseData !== 'object' ||
309
+ responseData.success !== true ||
310
+ !responseData.data
311
+ ) {
312
+ return { ok: false, code: 'UPSTREAM_SERVICE_ERROR', message: 'Non-compliant IDP envelope', status: 502, retryable: true };
313
+ }
314
+
315
+ const newAccess = responseData.data.access_token;
316
+ const newRefresh = responseData.data.refresh_token;
317
+ if (!newAccess) {
318
+ return { ok: false, code: 'INTERNAL_SERVER_ERROR', message: 'Missing access token in IDP response', status: 500 };
319
+ }
320
+
321
+ let accessTokenExpires: number;
322
+ let refreshTokenExpires: number | undefined;
323
+ let decoded: any;
324
+ try {
325
+ const r = computeTokenExpiries({ accessToken: newAccess, refreshToken: newRefresh, preferJwt: true });
326
+ decoded = r.decodedAccessToken;
327
+ accessTokenExpires = r.accessTokenExpires;
328
+ refreshTokenExpires = r.refreshTokenExpires;
329
+ } catch {
330
+ return { ok: false, code: 'INTERNAL_SERVER_ERROR', message: 'Failed to decode new tokens', status: 500 };
331
+ }
332
+
333
+ let amrClaims: string[] = [];
334
+ if (decoded?.amr) {
335
+ try {
336
+ amrClaims = typeof decoded.amr === 'string' ? JSON.parse(decoded.amr) : decoded.amr;
337
+ } catch {
338
+ amrClaims = session.authenticationMethods || [];
339
+ }
340
+ } else {
341
+ amrClaims = session.authenticationMethods || [];
342
+ }
343
+ const acrLevel = String(decoded?.acr || session.authenticationLevel || '1');
344
+ const hasNewRefresh = typeof newRefresh === 'string' && newRefresh.length > 0;
345
+ const newKid = extractKidFromToken(newAccess);
346
+
347
+ await updateSession(sessionToken, {
348
+ ...session,
349
+ idpAccessToken: newAccess,
350
+ idpAccessTokenExpires: accessTokenExpires,
351
+ idpRefreshToken: hasNewRefresh ? newRefresh : session.idpRefreshToken,
352
+ idpRefreshTokenExpires: hasNewRefresh ? refreshTokenExpires : session.idpRefreshTokenExpires,
353
+ decodedAccessToken: decoded,
354
+ bearerKeyId: newKid || session.bearerKeyId,
355
+ authenticationMethods: amrClaims,
356
+ authenticationLevel: acrLevel,
357
+ mfaVerified: amrClaims.includes('mfa') || session.mfaVerified,
358
+ mfaCompletedAt: decoded?.mfa_time ? parseInt(decoded.mfa_time) * 1000 : session.mfaCompletedAt,
359
+ mfaExpiresAt: decoded?.mfa_expires ? parseInt(decoded.mfa_expires) * 1000 : session.mfaExpiresAt,
360
+ mfaValidityHours: decoded?.mfa_validity_hours ? parseInt(decoded.mfa_validity_hours) : session.mfaValidityHours,
361
+ });
362
+
363
+ return { ok: true, accessToken: newAccess, accessTokenExpires, refreshed: true };
364
+ } finally {
365
+ if (weHoldLock) {
366
+ await releaseRefreshLock(sessionToken, requestId, releaseVersion);
367
+ }
368
+ }
369
+ }