@usehercules/auth 1.0.46 → 1.1.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.
- package/dist/react/index.d.mts +17 -1
- package/dist/react/index.d.mts.map +1 -1
- package/dist/react/index.mjs +152 -22
- package/dist/react/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/convex-react/ConvexProviderWithHercules.test.tsx +3 -3
- package/src/react/HerculesAuthProvider.test.tsx +90 -7
- package/src/react/HerculesAuthProvider.tsx +101 -12
- package/src/react/impersonation-core.ts +35 -0
- package/src/react/impersonation.test.tsx +121 -0
- package/src/react/impersonation.ts +96 -0
- package/src/react/index.ts +1 -0
package/dist/react/index.d.mts
CHANGED
|
@@ -34,6 +34,7 @@ type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager
|
|
|
34
34
|
};
|
|
35
35
|
interface HerculesAuthProviderContext {
|
|
36
36
|
userManager: UserManager;
|
|
37
|
+
impersonationStorageKey: string;
|
|
37
38
|
}
|
|
38
39
|
declare const HerculesAuthProviderContext: react0.Context<HerculesAuthProviderContext | null>;
|
|
39
40
|
declare function useHerculesAuthProvider(): HerculesAuthProviderContext;
|
|
@@ -46,6 +47,21 @@ declare function HerculesAuthProvider({
|
|
|
46
47
|
...props
|
|
47
48
|
}: HerculesAuthProviderProps): react_jsx_runtime0.JSX.Element;
|
|
48
49
|
//#endregion
|
|
50
|
+
//#region src/react/impersonation-core.d.ts
|
|
51
|
+
declare const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
|
|
52
|
+
declare const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
|
|
53
|
+
declare function getHerculesImpersonationStorageKey(authority: string, clientId: string): string;
|
|
54
|
+
declare function rememberHerculesImpersonationSession(storageKey: string, sessionId: string): void;
|
|
55
|
+
//#endregion
|
|
56
|
+
//#region src/react/impersonation.d.ts
|
|
57
|
+
type HerculesImpersonationState = {
|
|
58
|
+
isImpersonating: boolean;
|
|
59
|
+
sessionId: string | null;
|
|
60
|
+
actorSub: string | null;
|
|
61
|
+
stopImpersonating: () => Promise<void>;
|
|
62
|
+
};
|
|
63
|
+
declare function useHerculesImpersonation(): HerculesImpersonationState;
|
|
64
|
+
//#endregion
|
|
49
65
|
//#region src/react/use-user.d.ts
|
|
50
66
|
declare function useUser(): {
|
|
51
67
|
id: string | undefined;
|
|
@@ -74,5 +90,5 @@ interface AuthContextProps extends AuthContextProps$1 {
|
|
|
74
90
|
}
|
|
75
91
|
declare function useAuth(): AuthContextProps;
|
|
76
92
|
//#endregion
|
|
77
|
-
export { AuthCallbackStatus, AuthContextProps, HerculesAuthProvider, HerculesAuthProviderProps, UseAuthCallbackOptions, UseAuthCallbackResult, hasAuthParams, useAuth, useAuthCallback, useHerculesAuthProvider, useUser };
|
|
93
|
+
export { AuthCallbackStatus, AuthContextProps, HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, HerculesAuthProviderProps, HerculesImpersonationState, UseAuthCallbackOptions, UseAuthCallbackResult, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
|
|
78
94
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":[],"mappings":";;;;;;;;;KAiBY,kBAAA;UAWK,sBAAA;;;iBAkBA;;;;UAoBA,qBAAA;EAjDL,MAAA,EAmDF,kBAnDoB;EAWb,KAAA,EAAA,MAAA,GAAA,IAAA;EAsCA,SAAA,EAAA,OAAA;EAqDD,SAAA,EAAA,OAAe;;eApChB;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation-core.ts","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":[],"mappings":";;;;;;;;;KAiBY,kBAAA;UAWK,sBAAA;;;iBAkBA;;;;UAoBA,qBAAA;EAjDL,MAAA,EAmDF,kBAnDoB;EAWb,KAAA,EAAA,MAAA,GAAA,IAAA;EAsCA,SAAA,EAAA,OAAA;EAqDD,SAAA,EAAA,OAAe;;eApChB;;ACnDH,iBDuFI,eAAA,CCvFqB,OAAA,CAAA,EDwF1B,sBCxF0B,CAAA,EDyFlC,qBCzFkC;;;KAAzB,yBAAA,GAA4B,KACtC;wBAGsB,QAAQ;;;oBAGZ;;ADtBpB,UCsCU,2BAAA,CDtCoB;EAWb,WAAA,EC4BF,WD5BE;EAsCA,uBAAA,EAAqB,MAAA;AAqDtC;cC3DM,6BAA2B,MAAA,CAAA,QAAA;iBAGjB,uBAAA,CAAA,GAAuB;iBA0EvB,oBAAA;;;;;;;GAOb,4BAAyB,kBAAA,CAAA,GAAA,CAAA;;;cC9If,uCAAA;cAEA,kCAAA;iBAQG,kCAAA;iBAOA,oCAAA;;;KCHJ,0BAAA;;;;2BAIe;;iBAGX,wBAAA,CAAA,GAA4B;;;iBCb5B,OAAA,CAAA;;;;;;;SAAO,mBAAA,CAAA,YAAA;;EJOX,aAAA,CAAA,EAAA,MAAkB,GAAA,IAAA,GAAA,SAAA;EAWb,YAAA,CAAA,EAAA,MAAA,GAAA,SAAsB;EAsCtB,aAAA,CAAA,EAAA,MAAA;EAqDD,UAAA,CAAA,EAAA,MAAe,GAAA,SACpB;;YI9GY,eAAA,CAAA,aAAA;;EHsBX,KAAA,CAAA,EAAA,OAAA;EACV,SAAA,CAAA,EAAA,MAAA;CADsC;;;UIzBvB,gBAAA,SAAyB;iBACzB;gBACD;;iBAGA,OAAA,CAAA,GAAW"}
|
package/dist/react/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { AuthProvider, hasAuthParams, hasAuthParams as hasAuthParams$1, useAuth
|
|
|
4
4
|
import { ConvexError } from "convex/values";
|
|
5
5
|
import * as z from "zod";
|
|
6
6
|
import { UserManager, WebStorageStateStore } from "oidc-client-ts";
|
|
7
|
-
import { Fragment, jsx } from "react/jsx-runtime";
|
|
7
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
8
8
|
|
|
9
9
|
//#region src/react/auth-callback-hook.tsx
|
|
10
10
|
const DEFAULT_TIMEOUT_MS = 2e4;
|
|
@@ -150,6 +150,26 @@ function useAuthCallback(options = {}) {
|
|
|
150
150
|
};
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region src/react/impersonation-core.ts
|
|
155
|
+
const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
|
|
156
|
+
const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
|
|
157
|
+
function getHerculesImpersonationStorageKey(authority, clientId) {
|
|
158
|
+
return `hercules.impersonation.${authority}.${clientId}`;
|
|
159
|
+
}
|
|
160
|
+
function rememberHerculesImpersonationSession(storageKey, sessionId) {
|
|
161
|
+
if (typeof window === "undefined") return;
|
|
162
|
+
window.localStorage.setItem(storageKey, JSON.stringify({
|
|
163
|
+
sessionId,
|
|
164
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
165
|
+
}));
|
|
166
|
+
}
|
|
167
|
+
function clearHerculesImpersonationParamsFromUrl(url) {
|
|
168
|
+
url.searchParams.delete(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
|
|
169
|
+
url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);
|
|
170
|
+
return url;
|
|
171
|
+
}
|
|
172
|
+
|
|
153
173
|
//#endregion
|
|
154
174
|
//#region src/react/HerculesAuthProvider.tsx
|
|
155
175
|
const RECOVERY_TIMEOUT_MS = 1e4;
|
|
@@ -170,7 +190,7 @@ function useHerculesAuthProvider() {
|
|
|
170
190
|
if (!context) throw new Error("HerculesAuthProviderContext not found");
|
|
171
191
|
return context;
|
|
172
192
|
}
|
|
173
|
-
function AuthRecoveryGate({ children, loadingFallback }) {
|
|
193
|
+
function AuthRecoveryGate({ children, loadingFallback, skipRecovery }) {
|
|
174
194
|
const { user, isLoading, signinSilent } = useAuth$1();
|
|
175
195
|
const userExpired = user?.expired === true;
|
|
176
196
|
const hasAttempted = useRef(false);
|
|
@@ -179,6 +199,11 @@ function AuthRecoveryGate({ children, loadingFallback }) {
|
|
|
179
199
|
const [recoveryDone, setRecoveryDone] = useState(false);
|
|
180
200
|
const [recovering, setRecovering] = useState(false);
|
|
181
201
|
useEffect(() => {
|
|
202
|
+
if (skipRecovery) {
|
|
203
|
+
hasAttempted.current = true;
|
|
204
|
+
setRecoveryDone(true);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
182
207
|
if (isLoading) return;
|
|
183
208
|
if (hasAttempted.current) return;
|
|
184
209
|
hasAttempted.current = true;
|
|
@@ -195,8 +220,12 @@ function AuthRecoveryGate({ children, loadingFallback }) {
|
|
|
195
220
|
withRefreshLock(async () => {
|
|
196
221
|
await Promise.race([signinSilentRef.current().catch(() => void 0), new Promise((resolve) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS))]);
|
|
197
222
|
}).finally(finish);
|
|
198
|
-
}, [
|
|
199
|
-
|
|
223
|
+
}, [
|
|
224
|
+
isLoading,
|
|
225
|
+
skipRecovery,
|
|
226
|
+
userExpired
|
|
227
|
+
]);
|
|
228
|
+
if (!skipRecovery && (recovering || !recoveryDone && !isLoading && userExpired)) return /* @__PURE__ */ jsx(Fragment, { children: loadingFallback });
|
|
200
229
|
return /* @__PURE__ */ jsx(Fragment, { children });
|
|
201
230
|
}
|
|
202
231
|
/**
|
|
@@ -207,19 +236,26 @@ function AuthRecoveryGate({ children, loadingFallback }) {
|
|
|
207
236
|
*/
|
|
208
237
|
function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback = null, ...props }) {
|
|
209
238
|
const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
|
|
210
|
-
const [userManager] = useState(() =>
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
239
|
+
const [{ userManager, impersonationStorageKey }] = useState(() => {
|
|
240
|
+
const effectiveAuthority = userManagerSettings?.authority ?? authority;
|
|
241
|
+
const effectiveClientId = userManagerSettings?.client_id ?? client_id;
|
|
242
|
+
return {
|
|
243
|
+
userManager: new UserManager({
|
|
244
|
+
...userManagerSettings,
|
|
245
|
+
authority: effectiveAuthority,
|
|
246
|
+
client_id: effectiveClientId,
|
|
247
|
+
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
248
|
+
response_type: userManagerSettings?.response_type ?? "code",
|
|
249
|
+
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
250
|
+
redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
251
|
+
post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
252
|
+
userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: window.localStorage }),
|
|
253
|
+
automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
|
|
254
|
+
silentRequestTimeoutInSeconds: userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1e3
|
|
255
|
+
}),
|
|
256
|
+
impersonationStorageKey: getHerculesImpersonationStorageKey(effectiveAuthority, effectiveClientId)
|
|
257
|
+
};
|
|
258
|
+
});
|
|
223
259
|
useEffect(() => {
|
|
224
260
|
if (automaticSilentRenewExplicit) return;
|
|
225
261
|
let retryTimerId = null;
|
|
@@ -263,18 +299,112 @@ function HerculesAuthProvider({ children, userManagerSettings, authority, client
|
|
|
263
299
|
};
|
|
264
300
|
}, [userManager, automaticSilentRenewExplicit]);
|
|
265
301
|
return /* @__PURE__ */ jsx(HerculesAuthProviderContext.Provider, {
|
|
266
|
-
value: {
|
|
267
|
-
|
|
302
|
+
value: {
|
|
303
|
+
userManager,
|
|
304
|
+
impersonationStorageKey
|
|
305
|
+
},
|
|
306
|
+
children: /* @__PURE__ */ jsxs(AuthProvider, {
|
|
268
307
|
userManager,
|
|
269
308
|
...DEFAULT_AUTH_CONFIG,
|
|
270
309
|
...props,
|
|
271
|
-
children: /* @__PURE__ */ jsx(AuthRecoveryGate, {
|
|
310
|
+
children: [/* @__PURE__ */ jsx(HerculesImpersonationHandoff, { storageKey: impersonationStorageKey }), /* @__PURE__ */ jsx(AuthRecoveryGate, {
|
|
272
311
|
loadingFallback,
|
|
312
|
+
skipRecovery: hasCompleteImpersonationHandoff(),
|
|
273
313
|
children
|
|
274
|
-
})
|
|
314
|
+
})]
|
|
275
315
|
})
|
|
276
316
|
});
|
|
277
317
|
}
|
|
318
|
+
function HerculesImpersonationHandoff({ storageKey }) {
|
|
319
|
+
const auth = useAuth$1();
|
|
320
|
+
const hasStartedRef = useRef(false);
|
|
321
|
+
useEffect(() => {
|
|
322
|
+
if (hasStartedRef.current || typeof window === "undefined") return;
|
|
323
|
+
const url = new URL(window.location.href);
|
|
324
|
+
const impersonationSessionId = url.searchParams.get(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
|
|
325
|
+
const impersonationToken = url.searchParams.get(HERCULES_IMPERSONATION_TOKEN_PARAM);
|
|
326
|
+
if (!impersonationSessionId && !impersonationToken) return;
|
|
327
|
+
if (!impersonationSessionId || !impersonationToken) {
|
|
328
|
+
window.history.replaceState({}, document.title, clearHerculesImpersonationParamsFromUrl(url).toString());
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (auth.isLoading) return;
|
|
332
|
+
hasStartedRef.current = true;
|
|
333
|
+
rememberHerculesImpersonationSession(storageKey, impersonationSessionId);
|
|
334
|
+
window.history.replaceState({}, document.title, clearHerculesImpersonationParamsFromUrl(url).toString());
|
|
335
|
+
(async () => {
|
|
336
|
+
if (auth.isAuthenticated) await auth.removeUser();
|
|
337
|
+
await auth.signinRedirect({ extraQueryParams: {
|
|
338
|
+
[HERCULES_IMPERSONATION_SESSION_ID_PARAM]: impersonationSessionId,
|
|
339
|
+
[HERCULES_IMPERSONATION_TOKEN_PARAM]: impersonationToken
|
|
340
|
+
} });
|
|
341
|
+
})();
|
|
342
|
+
}, [auth, storageKey]);
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
function hasCompleteImpersonationHandoff() {
|
|
346
|
+
if (typeof window === "undefined") return false;
|
|
347
|
+
const params = new URL(window.location.href).searchParams;
|
|
348
|
+
return params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) && params.has(HERCULES_IMPERSONATION_TOKEN_PARAM);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
//#endregion
|
|
352
|
+
//#region src/react/impersonation.ts
|
|
353
|
+
function useHerculesImpersonation() {
|
|
354
|
+
const { userManager, impersonationStorageKey } = useHerculesAuthProvider();
|
|
355
|
+
const auth = useAuth$1();
|
|
356
|
+
const [storedSessionId, setStoredSessionId] = useState(() => readStoredImpersonationSessionId(impersonationStorageKey));
|
|
357
|
+
const profile = auth.user?.profile ?? {};
|
|
358
|
+
const profileSessionId = typeof profile.hercules_impersonation_session_id === "string" ? profile.hercules_impersonation_session_id : null;
|
|
359
|
+
const actorSub = typeof profile.hercules_actor_sub === "string" ? profile.hercules_actor_sub : null;
|
|
360
|
+
const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;
|
|
361
|
+
useEffect(() => {
|
|
362
|
+
if (!auth.isAuthenticated) return;
|
|
363
|
+
if (profileSessionId) {
|
|
364
|
+
rememberHerculesImpersonationSession(impersonationStorageKey, profileSessionId);
|
|
365
|
+
setStoredSessionId(profileSessionId);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (typeof window !== "undefined") window.localStorage.removeItem(impersonationStorageKey);
|
|
369
|
+
setStoredSessionId(null);
|
|
370
|
+
}, [
|
|
371
|
+
auth.isAuthenticated,
|
|
372
|
+
impersonationStorageKey,
|
|
373
|
+
profileSessionId
|
|
374
|
+
]);
|
|
375
|
+
const stopImpersonating = useCallback(async () => {
|
|
376
|
+
if (typeof window !== "undefined") window.localStorage.removeItem(impersonationStorageKey);
|
|
377
|
+
setStoredSessionId(null);
|
|
378
|
+
if (await userManager.metadataService.getEndSessionEndpoint() != null) await auth.signoutRedirect();
|
|
379
|
+
else await auth.removeUser();
|
|
380
|
+
}, [
|
|
381
|
+
auth,
|
|
382
|
+
impersonationStorageKey,
|
|
383
|
+
userManager
|
|
384
|
+
]);
|
|
385
|
+
return useMemo(() => ({
|
|
386
|
+
isImpersonating: auth.isAuthenticated && sessionId != null,
|
|
387
|
+
sessionId,
|
|
388
|
+
actorSub,
|
|
389
|
+
stopImpersonating
|
|
390
|
+
}), [
|
|
391
|
+
actorSub,
|
|
392
|
+
auth.isAuthenticated,
|
|
393
|
+
sessionId,
|
|
394
|
+
stopImpersonating
|
|
395
|
+
]);
|
|
396
|
+
}
|
|
397
|
+
function readStoredImpersonationSessionId(storageKey) {
|
|
398
|
+
if (typeof window === "undefined") return null;
|
|
399
|
+
try {
|
|
400
|
+
const stored = window.localStorage.getItem(storageKey);
|
|
401
|
+
if (!stored) return null;
|
|
402
|
+
const parsed = JSON.parse(stored);
|
|
403
|
+
return typeof parsed.sessionId === "string" ? parsed.sessionId : null;
|
|
404
|
+
} catch {
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
278
408
|
|
|
279
409
|
//#endregion
|
|
280
410
|
//#region src/react/use-user.ts
|
|
@@ -339,5 +469,5 @@ function useAuth() {
|
|
|
339
469
|
}
|
|
340
470
|
|
|
341
471
|
//#endregion
|
|
342
|
-
export { HerculesAuthProvider, hasAuthParams, useAuth, useAuthCallback, useHerculesAuthProvider, useUser };
|
|
472
|
+
export { HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
|
|
343
473
|
//# sourceMappingURL=index.mjs.map
|
package/dist/react/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps>","useAuth","retryTimerId: ReturnType<typeof setTimeout> | null","ReactAuthProvider","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(\n options: UseAuthCallbackOptions = {},\n): UseAuthCallbackResult {\n const {\n timeoutMs = DEFAULT_TIMEOUT_MS,\n isBackendAuthenticated = true,\n onSync,\n onSuccess,\n onNoAuthParams,\n } = options;\n\n const {\n isLoading: isAuthLoading,\n isAuthenticated: isOidcAuthenticated,\n error: oidcError,\n signinRedirect,\n } = useAuth();\n\n const [status, setStatus] = useState<AuthCallbackStatus>(\"processing-oauth\");\n const [error, setError] = useState<string | null>(null);\n\n // Track mount state to prevent state updates after unmount\n const mountedRef = useRef(true);\n // Track if we had auth params on mount (won't change during lifecycle)\n const hadAuthParams = useRef(hasAuthParams());\n // Track if we've already started sync to prevent double execution\n const syncStarted = useRef(false);\n\n // Reset on mount, cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n syncStarted.current = false;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (\n !isAuthLoading &&\n isOidcAuthenticated &&\n status === \"processing-oauth\"\n ) {\n setStatus(\"waiting-backend\");\n return;\n }\n\n // OIDC finished but not authenticated (and we had auth params)\n // Wait a bit before declaring failure to avoid race conditions\n if (\n hadAuthParams.current &&\n !isAuthLoading &&\n !isOidcAuthenticated &&\n !oidcError &&\n status === \"processing-oauth\"\n ) {\n // Use a small delay to avoid race condition during OIDC state transitions\n const failureTimeout = setTimeout(() => {\n if (mountedRef.current && !isOidcAuthenticated) {\n setStatus(\"error\");\n setError(\"Authentication was cancelled or failed. Please try again.\");\n }\n }, 500);\n\n return () => clearTimeout(failureTimeout);\n }\n\n return;\n }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n if (err instanceof ConvexError) {\n // try to extract the error message from the convex error\n const parseResult = convexErrorSchema.safeParse(err.data);\n if (parseResult.success) {\n setStatus(\"error\");\n setError(parseResult.data.message);\n return;\n }\n }\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error\n ? err.message\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n useAuth,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\n\nconst RECOVERY_TIMEOUT_MS = 10_000;\nconst LOCK_GRACE_MS = 5_000;\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n loadingFallback?: ReactNode;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\ninterface HerculesAuthProviderContext {\n userManager: UserManager;\n}\n\nconst HerculesAuthProviderContext =\n createContext<HerculesAuthProviderContext | null>(null);\n\nexport function useHerculesAuthProvider() {\n const context = useContext(HerculesAuthProviderContext);\n if (!context) {\n throw new Error(\"HerculesAuthProviderContext not found\");\n }\n return context;\n}\n\nfunction AuthRecoveryGate({\n children,\n loadingFallback,\n}: {\n children: ReactNode;\n loadingFallback: ReactNode;\n}) {\n const { user, isLoading, signinSilent } = useAuth();\n const userExpired = user?.expired === true;\n const hasAttempted = useRef(false);\n const signinSilentRef = useRef(signinSilent);\n signinSilentRef.current = signinSilent;\n const [recoveryDone, setRecoveryDone] = useState(false);\n const [recovering, setRecovering] = useState(false);\n\n useEffect(() => {\n if (isLoading) return;\n if (hasAttempted.current) return;\n hasAttempted.current = true;\n\n if (!user || !userExpired) {\n setRecoveryDone(true);\n return;\n }\n\n setRecovering(true);\n const finish = () => {\n setRecovering(false);\n setRecoveryDone(true);\n };\n setTimeout(finish, RECOVERY_TIMEOUT_MS);\n\n void withRefreshLock(async () => {\n await Promise.race([\n signinSilentRef.current().catch(() => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),\n ),\n ]);\n }).finally(finish);\n }, [isLoading, userExpired]);\n\n const shouldBlock =\n recovering || (!recoveryDone && !isLoading && userExpired);\n\n if (shouldBlock) {\n return <>{loadingFallback}</>;\n }\n\n return <>{children}</>;\n}\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n loadingFallback = null,\n ...props\n}: HerculesAuthProviderProps) {\n const automaticSilentRenewExplicit =\n userManagerSettings?.automaticSilentRenew === true;\n const [userManager] = useState(\n () =>\n new UserManager({\n ...userManagerSettings,\n authority: userManagerSettings?.authority ?? authority,\n client_id: userManagerSettings?.client_id ?? client_id,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n automaticSilentRenew:\n userManagerSettings?.automaticSilentRenew ?? false,\n silentRequestTimeoutInSeconds:\n userManagerSettings?.silentRequestTimeoutInSeconds ??\n RECOVERY_TIMEOUT_MS / 1000,\n }),\n );\n\n useEffect(() => {\n if (automaticSilentRenewExplicit) return;\n let retryTimerId: ReturnType<typeof setTimeout> | null = null;\n let timeoutRetryCount = 0;\n let stopped = false;\n const events = userManager.events as unknown as {\n _raiseSilentRenewError?: (e: Error) => void;\n };\n const tryRenew = () => {\n if (stopped) return;\n void withRefreshLock(async () => {\n if (stopped) return;\n try {\n await userManager.signinSilent();\n timeoutRetryCount = 0;\n } catch (err) {\n if (stopped) return;\n const isTimeout =\n err instanceof Error && err.name === \"ErrorTimeout\";\n if (isTimeout) {\n timeoutRetryCount++;\n const maxRetries = (\n userManager.settings as {\n maxSilentRenewTimeoutRetries?: number;\n }\n ).maxSilentRenewTimeoutRetries;\n if (maxRetries !== undefined && timeoutRetryCount > maxRetries) {\n timeoutRetryCount = 0;\n events._raiseSilentRenewError?.(err as Error);\n return;\n }\n retryTimerId = setTimeout(() => {\n retryTimerId = null;\n tryRenew();\n }, 5000);\n } else {\n timeoutRetryCount = 0;\n events._raiseSilentRenewError?.(err as Error);\n }\n }\n });\n };\n const onExpiring = () => tryRenew();\n userManager.events.addAccessTokenExpiring(onExpiring);\n return () => {\n stopped = true;\n userManager.events.removeAccessTokenExpiring(onExpiring);\n if (retryTimerId !== null) clearTimeout(retryTimerId);\n };\n }, [userManager, automaticSilentRenewExplicit]);\n\n return (\n <HerculesAuthProviderContext.Provider value={{ userManager }}>\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n <AuthRecoveryGate loadingFallback={loadingFallback}>\n {children}\n </AuthRecoveryGate>\n </ReactAuthProvider>\n </HerculesAuthProviderContext.Provider>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n","import {\n useAuth as useOidcAuth,\n type AuthContextProps as OidcAuthContextProps,\n} from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport { useCallback, useMemo } from \"react\";\n\nexport interface AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: () => Promise<void>;\n}\n\nexport function useAuth(): AuthContextProps {\n const { userManager } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n\n const { signoutRedirect, removeUser, signinRedirect } = auth;\n const signout = useCallback(async () => {\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await signoutRedirect();\n } else {\n await removeUser();\n }\n }, [userManager, signoutRedirect, removeUser]);\n\n const signin = useCallback(async () => {\n await signinRedirect();\n }, [signinRedirect]);\n\n return useMemo(() => {\n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OAAO,EAAE,aAAa;YAC1D,oBAACC;GACc;GACb,GAAI;GACJ,GAAI;aAEJ,oBAAC;IAAkC;IAChC;KACgB;IACD;GACiB;;;;;;;;;;AClN3C,SAAgB,UAAU;CACxB,MAAM,EAAE,MAAM,WAAW,OAAO,oBAAoBC,WAAS;AAE7D,QAAO,cAAc;EACnB,MAAM,KAAK,MAAM,QAAQ;EACzB,MAAM,OAAO,MAAM,QAAQ;EAC3B,MAAM,QAAQ,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,QAAQ;AAC7B,SAAO;GACL,GAAI,QAAQ,EAAE;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACD;IACA;EAAC;EAAM;EAAiB;EAAW;EAAM,CAAC;;;;;AChB/C,SAAgB,UAA4B;CAC1C,MAAM,EAAE,gBAAgB,yBAAyB;CACjD,MAAM,OAAOC,WAAa;CAE1B,MAAM,EAAE,iBAAiB,YAAY,mBAAmB;CACxD,MAAM,UAAU,YAAY,YAAY;AAEtC,MADiB,MAAM,YAAY,gBAAgB,uBAAuB,IAC1D,KACd,OAAM,iBAAiB;MAEvB,OAAM,YAAY;IAEnB;EAAC;EAAa;EAAiB;EAAW,CAAC;CAE9C,MAAM,SAAS,YAAY,YAAY;AACrC,QAAM,gBAAgB;IACrB,CAAC,eAAe,CAAC;AAEpB,QAAO,cAAc;AACnB,SAAO;GACL,GAAG;GACH;GACA;GACD;IACA;EAAC;EAAM;EAAS;EAAO,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps>","useAuth","retryTimerId: ReturnType<typeof setTimeout> | null","ReactAuthProvider","useOidcAuth","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/impersonation-core.ts","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(\n options: UseAuthCallbackOptions = {},\n): UseAuthCallbackResult {\n const {\n timeoutMs = DEFAULT_TIMEOUT_MS,\n isBackendAuthenticated = true,\n onSync,\n onSuccess,\n onNoAuthParams,\n } = options;\n\n const {\n isLoading: isAuthLoading,\n isAuthenticated: isOidcAuthenticated,\n error: oidcError,\n signinRedirect,\n } = useAuth();\n\n const [status, setStatus] = useState<AuthCallbackStatus>(\"processing-oauth\");\n const [error, setError] = useState<string | null>(null);\n\n // Track mount state to prevent state updates after unmount\n const mountedRef = useRef(true);\n // Track if we had auth params on mount (won't change during lifecycle)\n const hadAuthParams = useRef(hasAuthParams());\n // Track if we've already started sync to prevent double execution\n const syncStarted = useRef(false);\n\n // Reset on mount, cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n syncStarted.current = false;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (\n !isAuthLoading &&\n isOidcAuthenticated &&\n status === \"processing-oauth\"\n ) {\n setStatus(\"waiting-backend\");\n return;\n }\n\n // OIDC finished but not authenticated (and we had auth params)\n // Wait a bit before declaring failure to avoid race conditions\n if (\n hadAuthParams.current &&\n !isAuthLoading &&\n !isOidcAuthenticated &&\n !oidcError &&\n status === \"processing-oauth\"\n ) {\n // Use a small delay to avoid race condition during OIDC state transitions\n const failureTimeout = setTimeout(() => {\n if (mountedRef.current && !isOidcAuthenticated) {\n setStatus(\"error\");\n setError(\"Authentication was cancelled or failed. Please try again.\");\n }\n }, 500);\n\n return () => clearTimeout(failureTimeout);\n }\n\n return;\n }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n if (err instanceof ConvexError) {\n // try to extract the error message from the convex error\n const parseResult = convexErrorSchema.safeParse(err.data);\n if (parseResult.success) {\n setStatus(\"error\");\n setError(parseResult.data.message);\n return;\n }\n }\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error\n ? err.message\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\nexport const HERCULES_IMPERSONATION_SESSION_ID_PARAM =\n \"hercules_impersonation_session_id\";\nexport const HERCULES_IMPERSONATION_TOKEN_PARAM =\n \"hercules_impersonation_token\";\n\nexport type StoredHerculesImpersonation = {\n sessionId: string;\n startedAt: string;\n};\n\nexport function getHerculesImpersonationStorageKey(\n authority: string,\n clientId: string,\n) {\n return `hercules.impersonation.${authority}.${clientId}`;\n}\n\nexport function rememberHerculesImpersonationSession(\n storageKey: string,\n sessionId: string,\n) {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(\n storageKey,\n JSON.stringify({ sessionId, startedAt: new Date().toISOString() }),\n );\n}\n\nexport function clearHerculesImpersonationParamsFromUrl(url: URL) {\n url.searchParams.delete(HERCULES_IMPERSONATION_SESSION_ID_PARAM);\n url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);\n return url;\n}\n","\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n useAuth,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\nimport {\n clearHerculesImpersonationParamsFromUrl,\n getHerculesImpersonationStorageKey,\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n rememberHerculesImpersonationSession,\n} from \"./impersonation-core\";\n\nconst RECOVERY_TIMEOUT_MS = 10_000;\nconst LOCK_GRACE_MS = 5_000;\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n loadingFallback?: ReactNode;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\ninterface HerculesAuthProviderContext {\n userManager: UserManager;\n impersonationStorageKey: string;\n}\n\nconst HerculesAuthProviderContext =\n createContext<HerculesAuthProviderContext | null>(null);\n\nexport function useHerculesAuthProvider() {\n const context = useContext(HerculesAuthProviderContext);\n if (!context) {\n throw new Error(\"HerculesAuthProviderContext not found\");\n }\n return context;\n}\n\nfunction AuthRecoveryGate({\n children,\n loadingFallback,\n skipRecovery,\n}: {\n children: ReactNode;\n loadingFallback: ReactNode;\n skipRecovery: boolean;\n}) {\n const { user, isLoading, signinSilent } = useAuth();\n const userExpired = user?.expired === true;\n const hasAttempted = useRef(false);\n const signinSilentRef = useRef(signinSilent);\n signinSilentRef.current = signinSilent;\n const [recoveryDone, setRecoveryDone] = useState(false);\n const [recovering, setRecovering] = useState(false);\n\n useEffect(() => {\n if (skipRecovery) {\n hasAttempted.current = true;\n setRecoveryDone(true);\n return;\n }\n if (isLoading) return;\n if (hasAttempted.current) return;\n hasAttempted.current = true;\n\n if (!user || !userExpired) {\n setRecoveryDone(true);\n return;\n }\n\n setRecovering(true);\n const finish = () => {\n setRecovering(false);\n setRecoveryDone(true);\n };\n setTimeout(finish, RECOVERY_TIMEOUT_MS);\n\n void withRefreshLock(async () => {\n await Promise.race([\n signinSilentRef.current().catch(() => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),\n ),\n ]);\n }).finally(finish);\n }, [isLoading, skipRecovery, userExpired]);\n\n const shouldBlock =\n !skipRecovery &&\n (recovering || (!recoveryDone && !isLoading && userExpired));\n\n if (shouldBlock) {\n return <>{loadingFallback}</>;\n }\n\n return <>{children}</>;\n}\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n loadingFallback = null,\n ...props\n}: HerculesAuthProviderProps) {\n const automaticSilentRenewExplicit =\n userManagerSettings?.automaticSilentRenew === true;\n const [{ userManager, impersonationStorageKey }] = useState(() => {\n const effectiveAuthority = userManagerSettings?.authority ?? authority;\n const effectiveClientId = userManagerSettings?.client_id ?? client_id;\n\n return {\n userManager: new UserManager({\n ...userManagerSettings,\n authority: effectiveAuthority,\n client_id: effectiveClientId,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n automaticSilentRenew:\n userManagerSettings?.automaticSilentRenew ?? false,\n silentRequestTimeoutInSeconds:\n userManagerSettings?.silentRequestTimeoutInSeconds ??\n RECOVERY_TIMEOUT_MS / 1000,\n }),\n impersonationStorageKey: getHerculesImpersonationStorageKey(\n effectiveAuthority,\n effectiveClientId,\n ),\n };\n });\n\n useEffect(() => {\n if (automaticSilentRenewExplicit) return;\n let retryTimerId: ReturnType<typeof setTimeout> | null = null;\n let timeoutRetryCount = 0;\n let stopped = false;\n const events = userManager.events as unknown as {\n _raiseSilentRenewError?: (e: Error) => void;\n };\n const tryRenew = () => {\n if (stopped) return;\n void withRefreshLock(async () => {\n if (stopped) return;\n try {\n await userManager.signinSilent();\n timeoutRetryCount = 0;\n } catch (err) {\n if (stopped) return;\n const isTimeout = err instanceof Error && err.name === \"ErrorTimeout\";\n if (isTimeout) {\n timeoutRetryCount++;\n const maxRetries = (\n userManager.settings as {\n maxSilentRenewTimeoutRetries?: number;\n }\n ).maxSilentRenewTimeoutRetries;\n if (maxRetries !== undefined && timeoutRetryCount > maxRetries) {\n timeoutRetryCount = 0;\n events._raiseSilentRenewError?.(err as Error);\n return;\n }\n retryTimerId = setTimeout(() => {\n retryTimerId = null;\n tryRenew();\n }, 5000);\n } else {\n timeoutRetryCount = 0;\n events._raiseSilentRenewError?.(err as Error);\n }\n }\n });\n };\n const onExpiring = () => tryRenew();\n userManager.events.addAccessTokenExpiring(onExpiring);\n return () => {\n stopped = true;\n userManager.events.removeAccessTokenExpiring(onExpiring);\n if (retryTimerId !== null) clearTimeout(retryTimerId);\n };\n }, [userManager, automaticSilentRenewExplicit]);\n\n return (\n <HerculesAuthProviderContext.Provider\n value={{ userManager, impersonationStorageKey }}\n >\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n <HerculesImpersonationHandoff storageKey={impersonationStorageKey} />\n <AuthRecoveryGate\n loadingFallback={loadingFallback}\n skipRecovery={hasCompleteImpersonationHandoff()}\n >\n {children}\n </AuthRecoveryGate>\n </ReactAuthProvider>\n </HerculesAuthProviderContext.Provider>\n );\n}\n\nfunction HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {\n const auth = useAuth();\n const hasStartedRef = useRef(false);\n\n useEffect(() => {\n if (hasStartedRef.current || typeof window === \"undefined\") return;\n\n const url = new URL(window.location.href);\n const impersonationSessionId = url.searchParams.get(\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n );\n const impersonationToken = url.searchParams.get(\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n );\n if (!impersonationSessionId && !impersonationToken) return;\n if (!impersonationSessionId || !impersonationToken) {\n window.history.replaceState(\n {},\n document.title,\n clearHerculesImpersonationParamsFromUrl(url).toString(),\n );\n return;\n }\n if (auth.isLoading) return;\n\n hasStartedRef.current = true;\n rememberHerculesImpersonationSession(storageKey, impersonationSessionId);\n window.history.replaceState(\n {},\n document.title,\n clearHerculesImpersonationParamsFromUrl(url).toString(),\n );\n\n void (async () => {\n if (auth.isAuthenticated) {\n await auth.removeUser();\n }\n\n await auth.signinRedirect({\n extraQueryParams: {\n [HERCULES_IMPERSONATION_SESSION_ID_PARAM]: impersonationSessionId,\n [HERCULES_IMPERSONATION_TOKEN_PARAM]: impersonationToken,\n },\n });\n })();\n }, [auth, storageKey]);\n\n return null;\n}\n\nfunction hasCompleteImpersonationHandoff(): boolean {\n if (typeof window === \"undefined\") return false;\n\n const params = new URL(window.location.href).searchParams;\n return (\n params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) &&\n params.has(HERCULES_IMPERSONATION_TOKEN_PARAM)\n );\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useAuth as useOidcAuth } from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport {\n rememberHerculesImpersonationSession,\n type StoredHerculesImpersonation,\n} from \"./impersonation-core\";\nexport {\n getHerculesImpersonationStorageKey,\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n rememberHerculesImpersonationSession,\n} from \"./impersonation-core\";\n\nexport type HerculesImpersonationState = {\n isImpersonating: boolean;\n sessionId: string | null;\n actorSub: string | null;\n stopImpersonating: () => Promise<void>;\n};\n\nexport function useHerculesImpersonation(): HerculesImpersonationState {\n const { userManager, impersonationStorageKey } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n const [storedSessionId, setStoredSessionId] = useState<string | null>(() =>\n readStoredImpersonationSessionId(impersonationStorageKey),\n );\n\n const profile = (auth.user?.profile ?? {}) as Record<string, unknown>;\n const profileSessionId =\n typeof profile.hercules_impersonation_session_id === \"string\"\n ? profile.hercules_impersonation_session_id\n : null;\n const actorSub =\n typeof profile.hercules_actor_sub === \"string\"\n ? profile.hercules_actor_sub\n : null;\n const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;\n\n useEffect(() => {\n if (!auth.isAuthenticated) return;\n\n if (profileSessionId) {\n rememberHerculesImpersonationSession(\n impersonationStorageKey,\n profileSessionId,\n );\n setStoredSessionId(profileSessionId);\n return;\n }\n\n if (typeof window !== \"undefined\") {\n window.localStorage.removeItem(impersonationStorageKey);\n }\n setStoredSessionId(null);\n }, [auth.isAuthenticated, impersonationStorageKey, profileSessionId]);\n\n const stopImpersonating = useCallback(async () => {\n if (typeof window !== \"undefined\") {\n window.localStorage.removeItem(impersonationStorageKey);\n }\n setStoredSessionId(null);\n\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await auth.signoutRedirect();\n } else {\n await auth.removeUser();\n }\n }, [auth, impersonationStorageKey, userManager]);\n\n return useMemo(\n () => ({\n isImpersonating: auth.isAuthenticated && sessionId != null,\n sessionId,\n actorSub,\n stopImpersonating,\n }),\n [actorSub, auth.isAuthenticated, sessionId, stopImpersonating],\n );\n}\n\nfunction readStoredImpersonationSessionId(storageKey: string) {\n if (typeof window === \"undefined\") return null;\n\n try {\n const stored = window.localStorage.getItem(storageKey);\n if (!stored) return null;\n const parsed = JSON.parse(stored) as Partial<StoredHerculesImpersonation>;\n return typeof parsed.sessionId === \"string\" ? parsed.sessionId : null;\n } catch {\n return null;\n }\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n","import {\n useAuth as useOidcAuth,\n type AuthContextProps as OidcAuthContextProps,\n} from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport { useCallback, useMemo } from \"react\";\n\nexport interface AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: () => Promise<void>;\n}\n\nexport function useAuth(): AuthContextProps {\n const { userManager } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n\n const { signoutRedirect, removeUser, signinRedirect } = auth;\n const signout = useCallback(async () => {\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await signoutRedirect();\n } else {\n await removeUser();\n }\n }, [userManager, signoutRedirect, removeUser]);\n\n const signin = useCallback(async () => {\n await signinRedirect();\n }, [signinRedirect]);\n\n return useMemo(() => {\n return {\n ...auth,\n signout,\n signin,\n } satisfies AuthContextProps;\n }, [auth, signout, signin]);\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,EAAE,OAAO,EACjC,SAAS,EAAE,QAAQ,EACpB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GF,SAAgB,gBACd,UAAkC,EAAE,EACb;CACvB,MAAM,EACJ,YAAY,oBACZ,yBAAyB,MACzB,QACA,WACA,mBACE;CAEJ,MAAM,EACJ,WAAW,eACX,iBAAiB,qBACjB,OAAO,WACP,mBACEA,WAAS;CAEb,MAAM,CAAC,QAAQ,aAAa,SAA6B,mBAAmB;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAwB,KAAK;CAGvD,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,gBAAgB,OAAOC,iBAAe,CAAC;CAE7C,MAAM,cAAc,OAAO,MAAM;AAGjC,iBAAgB;AACd,aAAW,UAAU;AACrB,cAAY,UAAU;AACtB,eAAa;AACX,cAAW,UAAU;;IAEtB,EAAE,CAAC;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AQ;EAC5B,MAAM,SAAS,MAAM,QAAQ;AAC7B,SAAO;GACL,GAAI,QAAQ,EAAE;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACD;IACA;EAAC;EAAM;EAAiB;EAAW;EAAM,CAAC;;;;;AChB/C,SAAgB,UAA4B;CAC1C,MAAM,EAAE,gBAAgB,yBAAyB;CACjD,MAAM,OAAOC,WAAa;CAE1B,MAAM,EAAE,iBAAiB,YAAY,mBAAmB;CACxD,MAAM,UAAU,YAAY,YAAY;AAEtC,MADiB,MAAM,YAAY,gBAAgB,uBAAuB,IAC1D,KACd,OAAM,iBAAiB;MAEvB,OAAM,YAAY;IAEnB;EAAC;EAAa;EAAiB;EAAW,CAAC;CAE9C,MAAM,SAAS,YAAY,YAAY;AACrC,QAAM,gBAAgB;IACrB,CAAC,eAAe,CAAC;AAEpB,QAAO,cAAc;AACnB,SAAO;GACL,GAAG;GACH;GACA;GACD;IACA;EAAC;EAAM;EAAS;EAAO,CAAC"}
|
package/package.json
CHANGED
|
@@ -43,9 +43,9 @@ vi.mock("convex/react", () => ({
|
|
|
43
43
|
},
|
|
44
44
|
}));
|
|
45
45
|
|
|
46
|
-
// Token expiring in 30 minutes (within the
|
|
46
|
+
// Token expiring in 30 minutes (within the one-hour refresh threshold).
|
|
47
47
|
const EXPIRING_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
48
|
-
// Token expiring in
|
|
48
|
+
// Token expiring in two hours (outside the one-hour refresh threshold).
|
|
49
49
|
const LONG_LIVED_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 2 * 60 * 60);
|
|
50
50
|
|
|
51
51
|
function setAuthState(overrides: Record<string, unknown>) {
|
|
@@ -111,7 +111,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
|
|
|
111
111
|
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
112
112
|
});
|
|
113
113
|
|
|
114
|
-
it("skips refresh when token expires more than
|
|
114
|
+
it("skips refresh when token expires more than one hour from now", async () => {
|
|
115
115
|
setAuthState({ user: { id_token: LONG_LIVED_TOKEN } });
|
|
116
116
|
|
|
117
117
|
const { result } = renderUseAuth();
|
|
@@ -1,14 +1,30 @@
|
|
|
1
1
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
act,
|
|
4
|
+
render,
|
|
5
|
+
screen,
|
|
6
|
+
waitFor,
|
|
7
|
+
configure,
|
|
8
|
+
} from "@testing-library/react";
|
|
3
9
|
import { HerculesAuthProvider } from "./HerculesAuthProvider.js";
|
|
4
10
|
|
|
5
11
|
configure({ reactStrictMode: false });
|
|
6
12
|
|
|
7
13
|
const mockSigninSilent = vi.fn();
|
|
14
|
+
const mockSigninRedirect = vi.fn();
|
|
15
|
+
const mockRemoveUser = vi.fn();
|
|
8
16
|
let mockAuthState: Record<string, unknown> = {};
|
|
17
|
+
const localStorageMock = createMemoryStorage();
|
|
18
|
+
|
|
19
|
+
Object.defineProperty(window, "localStorage", {
|
|
20
|
+
value: localStorageMock,
|
|
21
|
+
configurable: true,
|
|
22
|
+
});
|
|
9
23
|
|
|
10
24
|
vi.mock("react-oidc-context", () => ({
|
|
11
|
-
AuthProvider: ({ children }: { children: React.ReactNode }) =>
|
|
25
|
+
AuthProvider: ({ children }: { children: React.ReactNode }) => (
|
|
26
|
+
<>{children}</>
|
|
27
|
+
),
|
|
12
28
|
useAuth: () => mockAuthState,
|
|
13
29
|
}));
|
|
14
30
|
|
|
@@ -41,8 +57,12 @@ function setAuthState(overrides: Record<string, unknown>) {
|
|
|
41
57
|
}
|
|
42
58
|
|
|
43
59
|
beforeEach(() => {
|
|
60
|
+
window.history.replaceState({}, "", "/");
|
|
61
|
+
window.localStorage.clear();
|
|
44
62
|
setAuthState({});
|
|
45
63
|
mockSigninSilent.mockReset();
|
|
64
|
+
mockSigninRedirect.mockReset();
|
|
65
|
+
mockRemoveUser.mockReset();
|
|
46
66
|
});
|
|
47
67
|
|
|
48
68
|
function renderProvider(
|
|
@@ -63,7 +83,10 @@ function renderProvider(
|
|
|
63
83
|
describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
|
|
64
84
|
it("registers the lock-wrapped renewal listener by default", () => {
|
|
65
85
|
render(
|
|
66
|
-
<HerculesAuthProvider
|
|
86
|
+
<HerculesAuthProvider
|
|
87
|
+
authority="https://auth.example.com"
|
|
88
|
+
client_id="test-client"
|
|
89
|
+
>
|
|
67
90
|
<div data-testid="app">app</div>
|
|
68
91
|
</HerculesAuthProvider>,
|
|
69
92
|
);
|
|
@@ -84,7 +107,56 @@ describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
|
|
|
84
107
|
});
|
|
85
108
|
});
|
|
86
109
|
|
|
110
|
+
function createMemoryStorage(): Storage {
|
|
111
|
+
const store = new Map<string, string>();
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
get length() {
|
|
115
|
+
return store.size;
|
|
116
|
+
},
|
|
117
|
+
clear() {
|
|
118
|
+
store.clear();
|
|
119
|
+
},
|
|
120
|
+
getItem(key: string) {
|
|
121
|
+
return store.get(key) ?? null;
|
|
122
|
+
},
|
|
123
|
+
key(index: number) {
|
|
124
|
+
return Array.from(store.keys())[index] ?? null;
|
|
125
|
+
},
|
|
126
|
+
removeItem(key: string) {
|
|
127
|
+
store.delete(key);
|
|
128
|
+
},
|
|
129
|
+
setItem(key: string, value: string) {
|
|
130
|
+
store.set(key, value);
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
87
135
|
describe("HerculesAuthProvider AuthRecoveryGate", () => {
|
|
136
|
+
it("prioritizes an impersonation handoff over expired-session recovery", async () => {
|
|
137
|
+
window.history.replaceState(
|
|
138
|
+
{},
|
|
139
|
+
"",
|
|
140
|
+
"/?hercules_impersonation_session_id=session_1&hercules_impersonation_token=token_1",
|
|
141
|
+
);
|
|
142
|
+
setAuthState({
|
|
143
|
+
isAuthenticated: true,
|
|
144
|
+
removeUser: mockRemoveUser.mockResolvedValue(undefined),
|
|
145
|
+
signinRedirect: mockSigninRedirect.mockResolvedValue(undefined),
|
|
146
|
+
user: { expired: true, id_token: "stale" },
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
150
|
+
|
|
151
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
152
|
+
expect(screen.queryByTestId("loading")).toBeNull();
|
|
153
|
+
await waitFor(() => {
|
|
154
|
+
expect(mockSigninRedirect).toHaveBeenCalledTimes(1);
|
|
155
|
+
});
|
|
156
|
+
expect(mockRemoveUser).toHaveBeenCalledTimes(1);
|
|
157
|
+
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
158
|
+
});
|
|
159
|
+
|
|
88
160
|
it("renders children (not loadingFallback) while isLoading is true", async () => {
|
|
89
161
|
setAuthState({ isLoading: true, user: null });
|
|
90
162
|
renderProvider(<div data-testid="loading">loading</div>);
|
|
@@ -95,7 +167,10 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
|
|
|
95
167
|
|
|
96
168
|
it("blocks children on the very first commit when user is already expired", () => {
|
|
97
169
|
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
98
|
-
setAuthState({
|
|
170
|
+
setAuthState({
|
|
171
|
+
isLoading: false,
|
|
172
|
+
user: { expired: true, id_token: "stale" },
|
|
173
|
+
});
|
|
99
174
|
renderProvider(<div data-testid="loading">loading</div>);
|
|
100
175
|
expect(screen.getByTestId("loading")).toBeDefined();
|
|
101
176
|
expect(screen.queryByTestId("app")).toBeNull();
|
|
@@ -109,14 +184,22 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
|
|
|
109
184
|
resolveSilent = resolve;
|
|
110
185
|
}),
|
|
111
186
|
);
|
|
112
|
-
setAuthState({
|
|
113
|
-
|
|
187
|
+
setAuthState({
|
|
188
|
+
isLoading: false,
|
|
189
|
+
user: { expired: true, id_token: "stale" },
|
|
190
|
+
});
|
|
191
|
+
const { rerender } = renderProvider(
|
|
192
|
+
<div data-testid="loading">loading</div>,
|
|
193
|
+
);
|
|
114
194
|
expect(screen.getByTestId("loading")).toBeDefined();
|
|
115
195
|
await waitFor(() => {
|
|
116
196
|
expect(mockSigninSilent).toHaveBeenCalledTimes(1);
|
|
117
197
|
});
|
|
118
198
|
|
|
119
|
-
setAuthState({
|
|
199
|
+
setAuthState({
|
|
200
|
+
isLoading: true,
|
|
201
|
+
user: { expired: true, id_token: "stale" },
|
|
202
|
+
});
|
|
120
203
|
rerender(
|
|
121
204
|
<HerculesAuthProvider
|
|
122
205
|
authority="https://auth.example.com"
|
|
@@ -19,6 +19,13 @@ import {
|
|
|
19
19
|
type UserManagerSettings,
|
|
20
20
|
} from "oidc-client-ts";
|
|
21
21
|
import { withRefreshLock } from "../internal/refresh-lock";
|
|
22
|
+
import {
|
|
23
|
+
clearHerculesImpersonationParamsFromUrl,
|
|
24
|
+
getHerculesImpersonationStorageKey,
|
|
25
|
+
HERCULES_IMPERSONATION_SESSION_ID_PARAM,
|
|
26
|
+
HERCULES_IMPERSONATION_TOKEN_PARAM,
|
|
27
|
+
rememberHerculesImpersonationSession,
|
|
28
|
+
} from "./impersonation-core";
|
|
22
29
|
|
|
23
30
|
const RECOVERY_TIMEOUT_MS = 10_000;
|
|
24
31
|
const LOCK_GRACE_MS = 5_000;
|
|
@@ -48,6 +55,7 @@ const DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {
|
|
|
48
55
|
|
|
49
56
|
interface HerculesAuthProviderContext {
|
|
50
57
|
userManager: UserManager;
|
|
58
|
+
impersonationStorageKey: string;
|
|
51
59
|
}
|
|
52
60
|
|
|
53
61
|
const HerculesAuthProviderContext =
|
|
@@ -64,9 +72,11 @@ export function useHerculesAuthProvider() {
|
|
|
64
72
|
function AuthRecoveryGate({
|
|
65
73
|
children,
|
|
66
74
|
loadingFallback,
|
|
75
|
+
skipRecovery,
|
|
67
76
|
}: {
|
|
68
77
|
children: ReactNode;
|
|
69
78
|
loadingFallback: ReactNode;
|
|
79
|
+
skipRecovery: boolean;
|
|
70
80
|
}) {
|
|
71
81
|
const { user, isLoading, signinSilent } = useAuth();
|
|
72
82
|
const userExpired = user?.expired === true;
|
|
@@ -77,6 +87,11 @@ function AuthRecoveryGate({
|
|
|
77
87
|
const [recovering, setRecovering] = useState(false);
|
|
78
88
|
|
|
79
89
|
useEffect(() => {
|
|
90
|
+
if (skipRecovery) {
|
|
91
|
+
hasAttempted.current = true;
|
|
92
|
+
setRecoveryDone(true);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
80
95
|
if (isLoading) return;
|
|
81
96
|
if (hasAttempted.current) return;
|
|
82
97
|
hasAttempted.current = true;
|
|
@@ -101,10 +116,11 @@ function AuthRecoveryGate({
|
|
|
101
116
|
),
|
|
102
117
|
]);
|
|
103
118
|
}).finally(finish);
|
|
104
|
-
}, [isLoading, userExpired]);
|
|
119
|
+
}, [isLoading, skipRecovery, userExpired]);
|
|
105
120
|
|
|
106
121
|
const shouldBlock =
|
|
107
|
-
|
|
122
|
+
!skipRecovery &&
|
|
123
|
+
(recovering || (!recoveryDone && !isLoading && userExpired));
|
|
108
124
|
|
|
109
125
|
if (shouldBlock) {
|
|
110
126
|
return <>{loadingFallback}</>;
|
|
@@ -129,12 +145,15 @@ export function HerculesAuthProvider({
|
|
|
129
145
|
}: HerculesAuthProviderProps) {
|
|
130
146
|
const automaticSilentRenewExplicit =
|
|
131
147
|
userManagerSettings?.automaticSilentRenew === true;
|
|
132
|
-
const [userManager] = useState(
|
|
133
|
-
|
|
134
|
-
|
|
148
|
+
const [{ userManager, impersonationStorageKey }] = useState(() => {
|
|
149
|
+
const effectiveAuthority = userManagerSettings?.authority ?? authority;
|
|
150
|
+
const effectiveClientId = userManagerSettings?.client_id ?? client_id;
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
userManager: new UserManager({
|
|
135
154
|
...userManagerSettings,
|
|
136
|
-
authority:
|
|
137
|
-
client_id:
|
|
155
|
+
authority: effectiveAuthority,
|
|
156
|
+
client_id: effectiveClientId,
|
|
138
157
|
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
139
158
|
response_type: userManagerSettings?.response_type ?? "code",
|
|
140
159
|
scope:
|
|
@@ -154,7 +173,12 @@ export function HerculesAuthProvider({
|
|
|
154
173
|
userManagerSettings?.silentRequestTimeoutInSeconds ??
|
|
155
174
|
RECOVERY_TIMEOUT_MS / 1000,
|
|
156
175
|
}),
|
|
157
|
-
|
|
176
|
+
impersonationStorageKey: getHerculesImpersonationStorageKey(
|
|
177
|
+
effectiveAuthority,
|
|
178
|
+
effectiveClientId,
|
|
179
|
+
),
|
|
180
|
+
};
|
|
181
|
+
});
|
|
158
182
|
|
|
159
183
|
useEffect(() => {
|
|
160
184
|
if (automaticSilentRenewExplicit) return;
|
|
@@ -173,8 +197,7 @@ export function HerculesAuthProvider({
|
|
|
173
197
|
timeoutRetryCount = 0;
|
|
174
198
|
} catch (err) {
|
|
175
199
|
if (stopped) return;
|
|
176
|
-
const isTimeout =
|
|
177
|
-
err instanceof Error && err.name === "ErrorTimeout";
|
|
200
|
+
const isTimeout = err instanceof Error && err.name === "ErrorTimeout";
|
|
178
201
|
if (isTimeout) {
|
|
179
202
|
timeoutRetryCount++;
|
|
180
203
|
const maxRetries = (
|
|
@@ -208,16 +231,82 @@ export function HerculesAuthProvider({
|
|
|
208
231
|
}, [userManager, automaticSilentRenewExplicit]);
|
|
209
232
|
|
|
210
233
|
return (
|
|
211
|
-
<HerculesAuthProviderContext.Provider
|
|
234
|
+
<HerculesAuthProviderContext.Provider
|
|
235
|
+
value={{ userManager, impersonationStorageKey }}
|
|
236
|
+
>
|
|
212
237
|
<ReactAuthProvider
|
|
213
238
|
userManager={userManager}
|
|
214
239
|
{...DEFAULT_AUTH_CONFIG}
|
|
215
240
|
{...props}
|
|
216
241
|
>
|
|
217
|
-
<
|
|
242
|
+
<HerculesImpersonationHandoff storageKey={impersonationStorageKey} />
|
|
243
|
+
<AuthRecoveryGate
|
|
244
|
+
loadingFallback={loadingFallback}
|
|
245
|
+
skipRecovery={hasCompleteImpersonationHandoff()}
|
|
246
|
+
>
|
|
218
247
|
{children}
|
|
219
248
|
</AuthRecoveryGate>
|
|
220
249
|
</ReactAuthProvider>
|
|
221
250
|
</HerculesAuthProviderContext.Provider>
|
|
222
251
|
);
|
|
223
252
|
}
|
|
253
|
+
|
|
254
|
+
function HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {
|
|
255
|
+
const auth = useAuth();
|
|
256
|
+
const hasStartedRef = useRef(false);
|
|
257
|
+
|
|
258
|
+
useEffect(() => {
|
|
259
|
+
if (hasStartedRef.current || typeof window === "undefined") return;
|
|
260
|
+
|
|
261
|
+
const url = new URL(window.location.href);
|
|
262
|
+
const impersonationSessionId = url.searchParams.get(
|
|
263
|
+
HERCULES_IMPERSONATION_SESSION_ID_PARAM,
|
|
264
|
+
);
|
|
265
|
+
const impersonationToken = url.searchParams.get(
|
|
266
|
+
HERCULES_IMPERSONATION_TOKEN_PARAM,
|
|
267
|
+
);
|
|
268
|
+
if (!impersonationSessionId && !impersonationToken) return;
|
|
269
|
+
if (!impersonationSessionId || !impersonationToken) {
|
|
270
|
+
window.history.replaceState(
|
|
271
|
+
{},
|
|
272
|
+
document.title,
|
|
273
|
+
clearHerculesImpersonationParamsFromUrl(url).toString(),
|
|
274
|
+
);
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (auth.isLoading) return;
|
|
278
|
+
|
|
279
|
+
hasStartedRef.current = true;
|
|
280
|
+
rememberHerculesImpersonationSession(storageKey, impersonationSessionId);
|
|
281
|
+
window.history.replaceState(
|
|
282
|
+
{},
|
|
283
|
+
document.title,
|
|
284
|
+
clearHerculesImpersonationParamsFromUrl(url).toString(),
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
void (async () => {
|
|
288
|
+
if (auth.isAuthenticated) {
|
|
289
|
+
await auth.removeUser();
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
await auth.signinRedirect({
|
|
293
|
+
extraQueryParams: {
|
|
294
|
+
[HERCULES_IMPERSONATION_SESSION_ID_PARAM]: impersonationSessionId,
|
|
295
|
+
[HERCULES_IMPERSONATION_TOKEN_PARAM]: impersonationToken,
|
|
296
|
+
},
|
|
297
|
+
});
|
|
298
|
+
})();
|
|
299
|
+
}, [auth, storageKey]);
|
|
300
|
+
|
|
301
|
+
return null;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function hasCompleteImpersonationHandoff(): boolean {
|
|
305
|
+
if (typeof window === "undefined") return false;
|
|
306
|
+
|
|
307
|
+
const params = new URL(window.location.href).searchParams;
|
|
308
|
+
return (
|
|
309
|
+
params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) &&
|
|
310
|
+
params.has(HERCULES_IMPERSONATION_TOKEN_PARAM)
|
|
311
|
+
);
|
|
312
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
export const HERCULES_IMPERSONATION_SESSION_ID_PARAM =
|
|
4
|
+
"hercules_impersonation_session_id";
|
|
5
|
+
export const HERCULES_IMPERSONATION_TOKEN_PARAM =
|
|
6
|
+
"hercules_impersonation_token";
|
|
7
|
+
|
|
8
|
+
export type StoredHerculesImpersonation = {
|
|
9
|
+
sessionId: string;
|
|
10
|
+
startedAt: string;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function getHerculesImpersonationStorageKey(
|
|
14
|
+
authority: string,
|
|
15
|
+
clientId: string,
|
|
16
|
+
) {
|
|
17
|
+
return `hercules.impersonation.${authority}.${clientId}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function rememberHerculesImpersonationSession(
|
|
21
|
+
storageKey: string,
|
|
22
|
+
sessionId: string,
|
|
23
|
+
) {
|
|
24
|
+
if (typeof window === "undefined") return;
|
|
25
|
+
window.localStorage.setItem(
|
|
26
|
+
storageKey,
|
|
27
|
+
JSON.stringify({ sessionId, startedAt: new Date().toISOString() }),
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function clearHerculesImpersonationParamsFromUrl(url: URL) {
|
|
32
|
+
url.searchParams.delete(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
|
|
33
|
+
url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);
|
|
34
|
+
return url;
|
|
35
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { renderHook, waitFor, configure } from "@testing-library/react";
|
|
2
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
3
|
+
import { useHerculesImpersonation } from "./impersonation";
|
|
4
|
+
import {
|
|
5
|
+
getHerculesImpersonationStorageKey,
|
|
6
|
+
rememberHerculesImpersonationSession,
|
|
7
|
+
} from "./impersonation-core";
|
|
8
|
+
|
|
9
|
+
configure({ reactStrictMode: true });
|
|
10
|
+
|
|
11
|
+
const storageKey = getHerculesImpersonationStorageKey(
|
|
12
|
+
"https://auth.example.com",
|
|
13
|
+
"client_1",
|
|
14
|
+
);
|
|
15
|
+
const mockSignoutRedirect = vi.fn();
|
|
16
|
+
const mockRemoveUser = vi.fn();
|
|
17
|
+
const mockGetEndSessionEndpoint = vi.fn();
|
|
18
|
+
const mockUserManager = {
|
|
19
|
+
metadataService: {
|
|
20
|
+
getEndSessionEndpoint: mockGetEndSessionEndpoint,
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
let mockAuthState: Record<string, unknown> = {};
|
|
25
|
+
const localStorageMock = createMemoryStorage();
|
|
26
|
+
|
|
27
|
+
Object.defineProperty(window, "localStorage", {
|
|
28
|
+
value: localStorageMock,
|
|
29
|
+
configurable: true,
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
vi.mock("react-oidc-context", () => ({
|
|
33
|
+
useAuth: () => mockAuthState,
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
vi.mock("./HerculesAuthProvider", () => ({
|
|
37
|
+
useHerculesAuthProvider: () => ({
|
|
38
|
+
userManager: mockUserManager,
|
|
39
|
+
impersonationStorageKey: storageKey,
|
|
40
|
+
}),
|
|
41
|
+
}));
|
|
42
|
+
|
|
43
|
+
beforeEach(() => {
|
|
44
|
+
window.localStorage.removeItem(storageKey);
|
|
45
|
+
mockSignoutRedirect.mockReset();
|
|
46
|
+
mockRemoveUser.mockReset();
|
|
47
|
+
mockGetEndSessionEndpoint.mockReset();
|
|
48
|
+
mockAuthState = {
|
|
49
|
+
isAuthenticated: true,
|
|
50
|
+
signoutRedirect: mockSignoutRedirect,
|
|
51
|
+
removeUser: mockRemoveUser,
|
|
52
|
+
user: {
|
|
53
|
+
profile: {},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe("useHerculesImpersonation", () => {
|
|
59
|
+
it("uses impersonation claims from the authenticated profile", async () => {
|
|
60
|
+
mockAuthState = {
|
|
61
|
+
...mockAuthState,
|
|
62
|
+
user: {
|
|
63
|
+
profile: {
|
|
64
|
+
hercules_impersonation_session_id: "session_1",
|
|
65
|
+
hercules_actor_sub: "actor_1",
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const { result } = renderHook(() => useHerculesImpersonation());
|
|
71
|
+
|
|
72
|
+
expect(result.current).toMatchObject({
|
|
73
|
+
isImpersonating: true,
|
|
74
|
+
sessionId: "session_1",
|
|
75
|
+
actorSub: "actor_1",
|
|
76
|
+
});
|
|
77
|
+
await waitFor(() => {
|
|
78
|
+
expect(window.localStorage.getItem(storageKey)).toContain("session_1");
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("ignores stale stored impersonation after normal login", async () => {
|
|
83
|
+
rememberHerculesImpersonationSession(storageKey, "old_session");
|
|
84
|
+
|
|
85
|
+
const { result } = renderHook(() => useHerculesImpersonation());
|
|
86
|
+
|
|
87
|
+
expect(result.current).toMatchObject({
|
|
88
|
+
isImpersonating: false,
|
|
89
|
+
sessionId: null,
|
|
90
|
+
actorSub: null,
|
|
91
|
+
});
|
|
92
|
+
await waitFor(() => {
|
|
93
|
+
expect(window.localStorage.getItem(storageKey)).toBeNull();
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
function createMemoryStorage(): Storage {
|
|
99
|
+
const store = new Map<string, string>();
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
get length() {
|
|
103
|
+
return store.size;
|
|
104
|
+
},
|
|
105
|
+
clear() {
|
|
106
|
+
store.clear();
|
|
107
|
+
},
|
|
108
|
+
getItem(key: string) {
|
|
109
|
+
return store.get(key) ?? null;
|
|
110
|
+
},
|
|
111
|
+
key(index: number) {
|
|
112
|
+
return Array.from(store.keys())[index] ?? null;
|
|
113
|
+
},
|
|
114
|
+
removeItem(key: string) {
|
|
115
|
+
store.delete(key);
|
|
116
|
+
},
|
|
117
|
+
setItem(key: string, value: string) {
|
|
118
|
+
store.set(key, value);
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
4
|
+
import { useAuth as useOidcAuth } from "react-oidc-context";
|
|
5
|
+
import { useHerculesAuthProvider } from "./HerculesAuthProvider";
|
|
6
|
+
import {
|
|
7
|
+
rememberHerculesImpersonationSession,
|
|
8
|
+
type StoredHerculesImpersonation,
|
|
9
|
+
} from "./impersonation-core";
|
|
10
|
+
export {
|
|
11
|
+
getHerculesImpersonationStorageKey,
|
|
12
|
+
HERCULES_IMPERSONATION_SESSION_ID_PARAM,
|
|
13
|
+
HERCULES_IMPERSONATION_TOKEN_PARAM,
|
|
14
|
+
rememberHerculesImpersonationSession,
|
|
15
|
+
} from "./impersonation-core";
|
|
16
|
+
|
|
17
|
+
export type HerculesImpersonationState = {
|
|
18
|
+
isImpersonating: boolean;
|
|
19
|
+
sessionId: string | null;
|
|
20
|
+
actorSub: string | null;
|
|
21
|
+
stopImpersonating: () => Promise<void>;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export function useHerculesImpersonation(): HerculesImpersonationState {
|
|
25
|
+
const { userManager, impersonationStorageKey } = useHerculesAuthProvider();
|
|
26
|
+
const auth = useOidcAuth();
|
|
27
|
+
const [storedSessionId, setStoredSessionId] = useState<string | null>(() =>
|
|
28
|
+
readStoredImpersonationSessionId(impersonationStorageKey),
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
const profile = (auth.user?.profile ?? {}) as Record<string, unknown>;
|
|
32
|
+
const profileSessionId =
|
|
33
|
+
typeof profile.hercules_impersonation_session_id === "string"
|
|
34
|
+
? profile.hercules_impersonation_session_id
|
|
35
|
+
: null;
|
|
36
|
+
const actorSub =
|
|
37
|
+
typeof profile.hercules_actor_sub === "string"
|
|
38
|
+
? profile.hercules_actor_sub
|
|
39
|
+
: null;
|
|
40
|
+
const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;
|
|
41
|
+
|
|
42
|
+
useEffect(() => {
|
|
43
|
+
if (!auth.isAuthenticated) return;
|
|
44
|
+
|
|
45
|
+
if (profileSessionId) {
|
|
46
|
+
rememberHerculesImpersonationSession(
|
|
47
|
+
impersonationStorageKey,
|
|
48
|
+
profileSessionId,
|
|
49
|
+
);
|
|
50
|
+
setStoredSessionId(profileSessionId);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (typeof window !== "undefined") {
|
|
55
|
+
window.localStorage.removeItem(impersonationStorageKey);
|
|
56
|
+
}
|
|
57
|
+
setStoredSessionId(null);
|
|
58
|
+
}, [auth.isAuthenticated, impersonationStorageKey, profileSessionId]);
|
|
59
|
+
|
|
60
|
+
const stopImpersonating = useCallback(async () => {
|
|
61
|
+
if (typeof window !== "undefined") {
|
|
62
|
+
window.localStorage.removeItem(impersonationStorageKey);
|
|
63
|
+
}
|
|
64
|
+
setStoredSessionId(null);
|
|
65
|
+
|
|
66
|
+
const endpoint = await userManager.metadataService.getEndSessionEndpoint();
|
|
67
|
+
if (endpoint != null) {
|
|
68
|
+
await auth.signoutRedirect();
|
|
69
|
+
} else {
|
|
70
|
+
await auth.removeUser();
|
|
71
|
+
}
|
|
72
|
+
}, [auth, impersonationStorageKey, userManager]);
|
|
73
|
+
|
|
74
|
+
return useMemo(
|
|
75
|
+
() => ({
|
|
76
|
+
isImpersonating: auth.isAuthenticated && sessionId != null,
|
|
77
|
+
sessionId,
|
|
78
|
+
actorSub,
|
|
79
|
+
stopImpersonating,
|
|
80
|
+
}),
|
|
81
|
+
[actorSub, auth.isAuthenticated, sessionId, stopImpersonating],
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function readStoredImpersonationSessionId(storageKey: string) {
|
|
86
|
+
if (typeof window === "undefined") return null;
|
|
87
|
+
|
|
88
|
+
try {
|
|
89
|
+
const stored = window.localStorage.getItem(storageKey);
|
|
90
|
+
if (!stored) return null;
|
|
91
|
+
const parsed = JSON.parse(stored) as Partial<StoredHerculesImpersonation>;
|
|
92
|
+
return typeof parsed.sessionId === "string" ? parsed.sessionId : null;
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|