@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.
- package/README.md +792 -792
- package/dist/api-handlers/auth/refresh.js +38 -15
- package/dist/auth/better-auth.js +4 -3
- package/dist/components/account/MobileNavDrawer.js +18 -18
- package/dist/components/account/UserAvatarMenu.js +1 -1
- package/dist/components/admin/AlertSettingsTab.js +40 -40
- package/dist/components/admin/LoggingSettingsTab.js +28 -28
- package/dist/lib/ensure-fresh-access-token.js +42 -8
- package/dist/lib/idp-fetch.js +25 -9
- package/dist/lib/session-store.d.ts +1 -0
- package/dist/lib/session-store.js +12 -8
- package/dist/lib/token-lifecycle.d.ts +2 -0
- package/dist/lib/token-lifecycle.js +21 -3
- package/dist/pages/login/page.js +28 -28
- package/dist/pages/settings/EnhancedSettingsPage.js +17 -17
- package/package.json +893 -893
- package/scripts/dev-broker.ps1 +35 -35
- package/scripts/dev-local.ps1 +45 -45
- package/src/api/auth-handler.ts +548 -548
- package/src/api-handlers/account/change-password.ts +142 -142
- package/src/api-handlers/account/update-phone.ts +79 -79
- package/src/api-handlers/account/verify-email.ts +125 -125
- package/src/api-handlers/account/verify-sms.ts +125 -125
- package/src/api-handlers/admin/analytics.ts +443 -443
- package/src/api-handlers/admin/audit.ts +223 -223
- package/src/api-handlers/admin/index.ts +63 -63
- package/src/api-handlers/admin/redis-sessions.ts +251 -251
- package/src/api-handlers/admin/sessions.ts +318 -318
- package/src/api-handlers/admin/site-logs.ts +365 -365
- package/src/api-handlers/admin/users.ts +242 -242
- package/src/api-handlers/admin/vibe-data.ts +324 -324
- package/src/api-handlers/auth/refresh.ts +705 -682
- package/src/api-handlers/auth/signout.ts +199 -199
- package/src/api-handlers/auth/status.ts +20 -20
- package/src/api-handlers/auth/update-session.ts +110 -110
- package/src/api-handlers/auth/verify-code.ts +112 -112
- package/src/api-handlers/session/refresh-viability.ts +36 -36
- package/src/api-handlers/test/force-expire.ts +60 -60
- package/src/auth/auth-decision.ts +229 -229
- package/src/auth/better-auth.ts +467 -466
- package/src/auth/route-config.ts +219 -219
- package/src/auth/types/auth-types.ts +555 -555
- package/src/auth/types/index.ts +7 -7
- package/src/auth/utils/idp-client.ts +445 -445
- package/src/auth/utils/index.ts +6 -6
- package/src/auth/utils/token-utils.ts +243 -243
- package/src/client/AuthContext.tsx +143 -143
- package/src/client/fetch-with-auth.ts +47 -47
- package/src/components/SessionSync.tsx +138 -138
- package/src/components/SignalRHealthCheck.tsx +131 -131
- package/src/components/account/MobileNavDrawer.tsx +305 -305
- package/src/components/account/UserAvatarMenu.tsx +266 -266
- package/src/components/account/index.ts +13 -13
- package/src/components/admin/AlertSettingsTab.tsx +728 -728
- package/src/components/admin/AnalyticsTab.tsx +703 -703
- package/src/components/admin/DataBrowserTab.tsx +505 -505
- package/src/components/admin/LoggingSettingsTab.tsx +665 -665
- package/src/components/admin/SessionsTab.tsx +414 -414
- package/src/components/admin/StatsTab.tsx +379 -379
- package/src/components/admin/VibeAdminLayout.tsx +187 -187
- package/src/components/admin/index.ts +59 -59
- package/src/components/auth/FederatedAuthSection.tsx +95 -95
- package/src/components/auth/ModeAwareLoginPage.tsx +135 -135
- package/src/components/auth/ModeAwareSignupPage.tsx +267 -267
- package/src/components/auth/TraditionalAuthSection.tsx +99 -99
- package/src/components/recovery/CompleteStep.tsx +36 -36
- package/src/components/recovery/InitiateRecoveryStep.tsx +68 -68
- package/src/components/recovery/SelectMethodStep.tsx +73 -73
- package/src/components/recovery/SetPasswordStep.tsx +97 -97
- package/src/components/recovery/VerifyCodeStep.tsx +90 -90
- package/src/components/reserved/ReservedRecoveryWarning.tsx +160 -160
- package/src/components/reserved/ReservedStatusBox.tsx +118 -118
- package/src/components/ui/BetaBadge.tsx +58 -58
- package/src/components/ui/Footer.tsx +93 -93
- package/src/config/env.ts +57 -57
- package/src/config/logger.ts +62 -62
- package/src/config/vibe-log-transport.ts +264 -264
- package/src/hooks/useAuth.ts +117 -117
- package/src/hooks/useAuthSettings.ts +97 -97
- package/src/hooks/useAvailableProviders.ts +120 -120
- package/src/hooks/usePasswordValidation.ts +127 -127
- package/src/hooks/usePublicAuthSettings.ts +149 -149
- package/src/hooks/useSessionExpiration.ts +101 -101
- package/src/hooks/useViabilitySession.ts +336 -336
- package/src/index.ts +60 -60
- package/src/lib/api-handler.ts +643 -643
- package/src/lib/app-slug.ts +178 -178
- package/src/lib/ensure-fresh-access-token.ts +369 -335
- package/src/lib/geolocation.ts +265 -265
- package/src/lib/idp-fetch.ts +26 -10
- package/src/lib/jwt-decode.ts +82 -82
- package/src/lib/roles.ts +177 -177
- package/src/lib/session-store.ts +4 -1
- package/src/lib/site-logger.ts +245 -245
- package/src/lib/standardized-client-api.ts +901 -901
- package/src/lib/test-aware-get-token.ts +41 -41
- package/src/lib/token-lifecycle.ts +30 -3
- package/src/lib/user-agent-parser.ts +252 -252
- package/src/logging/api/admin-analytics.ts +51 -51
- package/src/logging/api/audit-log.ts +53 -53
- package/src/logging/components/AdminAnalyticsLayout.tsx +49 -49
- package/src/logging/components/AuditLogViewer.tsx +125 -125
- package/src/logging/components/ErrorMetricsCard.tsx +98 -98
- package/src/logging/components/HealthMetricsCard.tsx +70 -70
- package/src/logging/hooks/useAdminAnalytics.ts +22 -22
- package/src/logging/hooks/useAuditLog.ts +24 -24
- package/src/logging/hooks/useErrorMetrics.ts +40 -40
- package/src/logging/hooks/useHealthMetrics.ts +44 -44
- package/src/logging/index.ts +18 -18
- package/src/logging/types/analytics.ts +81 -81
- package/src/logging/types/audit.ts +31 -31
- package/src/logging/types/index.ts +3 -3
- package/src/middleware/create-middleware.ts +663 -663
- package/src/middleware/rbac-check.ts +279 -279
- package/src/middleware/twofa-presets.ts +224 -224
- package/src/pages/admin-login/page.tsx +221 -221
- package/src/pages/admin-page-permissions/PagePermissionsAdminPage.tsx +527 -527
- package/src/pages/admin-page-permissions/index.ts +7 -7
- package/src/pages/admin-roles/RolesAdminPage.tsx +533 -533
- package/src/pages/admin-roles/modals.tsx +469 -469
- package/src/pages/client-admin/ClientSiteAdminPage.tsx +382 -382
- package/src/pages/client-admin/index.ts +33 -33
- package/src/pages/coming-soon/page.tsx +83 -83
- package/src/pages/login/page.tsx +456 -456
- package/src/pages/profile/EnhancedProfilePage.tsx +485 -485
- package/src/pages/profile/index.ts +9 -9
- package/src/pages/profile/page.tsx +166 -166
- package/src/pages/recovery/page.tsx +234 -234
- package/src/pages/roles/MyRolesPage.tsx +211 -211
- package/src/pages/roles/components.tsx +294 -294
- package/src/pages/roles/index.ts +17 -17
- package/src/pages/security/EnhancedSecurityPage.tsx +565 -565
- package/src/pages/security/index.ts +9 -9
- package/src/pages/security/page.tsx +507 -507
- package/src/pages/settings/EnhancedSettingsPage.tsx +642 -642
- package/src/pages/settings/index.ts +9 -9
- package/src/pages/settings/page.tsx +47 -47
- package/src/pages/showcase/ShowcasePage.tsx +532 -532
- package/src/pages/showcase/index.ts +13 -13
- package/src/pages/test-env/EmergencyLogoutPage.tsx +180 -180
- package/src/pages/test-env/JwtInspectPage.tsx +456 -456
- package/src/pages/test-env/RefreshTokenPage.tsx +157 -157
- package/src/pages/test-env/TestEnvPage.tsx +118 -118
- package/src/pages/test-env/index.ts +25 -25
- package/src/pages/verify-code/page.tsx +652 -652
- package/src/routes/account/update-phone.ts +13 -13
- package/src/routes/auth/logout.ts +108 -108
- package/src/routes/auth/nextauth.ts +45 -45
- package/src/routes/auth/settings.ts +75 -75
- package/src/routes/auth/viability.ts +224 -224
- package/src/server/auth-guard.ts +170 -170
- package/src/server/slim-middleware.ts +117 -117
- package/src/server/with-auth.ts +93 -93
- package/src/stores/authStore.ts +1899 -1899
- package/src/templates/instrumentation.ts +41 -41
- package/src/utils/logout.ts +30 -30
- package/src/vibe/client.ts +590 -590
- package/src/vibe/enterprise-auth.ts +208 -208
- package/src/vibe/errors.ts +185 -185
- package/src/vibe/generic.ts +431 -431
- package/src/vibe/hooks/index.ts +367 -367
- package/src/vibe/index.ts +132 -132
- package/src/vibe/sessions.ts +551 -551
- 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
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
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
|
+
}
|