@usehercules/auth 1.0.45 → 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/convex-react/index.d.mts.map +1 -1
- package/dist/convex-react/index.mjs +2 -27
- package/dist/convex-react/index.mjs.map +1 -1
- package/dist/react/index.d.mts +20 -1
- package/dist/react/index.d.mts.map +1 -1
- package/dist/react/index.mjs +227 -17
- package/dist/react/index.mjs.map +1 -1
- package/dist/refresh-lock-DYW9ITwj.mjs +31 -0
- package/dist/refresh-lock-DYW9ITwj.mjs.map +1 -0
- package/package.json +3 -3
- package/src/convex-react/ConvexProviderWithHercules.test.tsx +3 -3
- package/src/convex-react/ConvexProviderWithHercules.tsx +2 -52
- package/src/internal/refresh-lock.ts +50 -0
- package/src/react/HerculesAuthProvider.test.tsx +372 -0
- package/src/react/HerculesAuthProvider.tsx +224 -10
- 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
|
@@ -1,16 +1,34 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
createContext,
|
|
5
|
+
useContext,
|
|
6
|
+
useEffect,
|
|
7
|
+
useRef,
|
|
8
|
+
useState,
|
|
9
|
+
type ReactNode,
|
|
10
|
+
} from "react";
|
|
4
11
|
import {
|
|
5
12
|
AuthProvider as ReactAuthProvider,
|
|
6
13
|
type AuthProviderUserManagerProps,
|
|
14
|
+
useAuth,
|
|
7
15
|
} from "react-oidc-context";
|
|
8
16
|
import {
|
|
9
17
|
UserManager,
|
|
10
18
|
WebStorageStateStore,
|
|
11
19
|
type UserManagerSettings,
|
|
12
20
|
} from "oidc-client-ts";
|
|
13
|
-
import {
|
|
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";
|
|
29
|
+
|
|
30
|
+
const RECOVERY_TIMEOUT_MS = 10_000;
|
|
31
|
+
const LOCK_GRACE_MS = 5_000;
|
|
14
32
|
|
|
15
33
|
export type HerculesAuthProviderProps = Omit<
|
|
16
34
|
AuthProviderUserManagerProps,
|
|
@@ -19,6 +37,7 @@ export type HerculesAuthProviderProps = Omit<
|
|
|
19
37
|
userManagerSettings?: Partial<UserManagerSettings>;
|
|
20
38
|
authority: string;
|
|
21
39
|
client_id: string;
|
|
40
|
+
loadingFallback?: ReactNode;
|
|
22
41
|
};
|
|
23
42
|
|
|
24
43
|
function onSigninCallback() {
|
|
@@ -36,6 +55,7 @@ const DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {
|
|
|
36
55
|
|
|
37
56
|
interface HerculesAuthProviderContext {
|
|
38
57
|
userManager: UserManager;
|
|
58
|
+
impersonationStorageKey: string;
|
|
39
59
|
}
|
|
40
60
|
|
|
41
61
|
const HerculesAuthProviderContext =
|
|
@@ -49,6 +69,66 @@ export function useHerculesAuthProvider() {
|
|
|
49
69
|
return context;
|
|
50
70
|
}
|
|
51
71
|
|
|
72
|
+
function AuthRecoveryGate({
|
|
73
|
+
children,
|
|
74
|
+
loadingFallback,
|
|
75
|
+
skipRecovery,
|
|
76
|
+
}: {
|
|
77
|
+
children: ReactNode;
|
|
78
|
+
loadingFallback: ReactNode;
|
|
79
|
+
skipRecovery: boolean;
|
|
80
|
+
}) {
|
|
81
|
+
const { user, isLoading, signinSilent } = useAuth();
|
|
82
|
+
const userExpired = user?.expired === true;
|
|
83
|
+
const hasAttempted = useRef(false);
|
|
84
|
+
const signinSilentRef = useRef(signinSilent);
|
|
85
|
+
signinSilentRef.current = signinSilent;
|
|
86
|
+
const [recoveryDone, setRecoveryDone] = useState(false);
|
|
87
|
+
const [recovering, setRecovering] = useState(false);
|
|
88
|
+
|
|
89
|
+
useEffect(() => {
|
|
90
|
+
if (skipRecovery) {
|
|
91
|
+
hasAttempted.current = true;
|
|
92
|
+
setRecoveryDone(true);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (isLoading) return;
|
|
96
|
+
if (hasAttempted.current) return;
|
|
97
|
+
hasAttempted.current = true;
|
|
98
|
+
|
|
99
|
+
if (!user || !userExpired) {
|
|
100
|
+
setRecoveryDone(true);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
setRecovering(true);
|
|
105
|
+
const finish = () => {
|
|
106
|
+
setRecovering(false);
|
|
107
|
+
setRecoveryDone(true);
|
|
108
|
+
};
|
|
109
|
+
setTimeout(finish, RECOVERY_TIMEOUT_MS);
|
|
110
|
+
|
|
111
|
+
void withRefreshLock(async () => {
|
|
112
|
+
await Promise.race([
|
|
113
|
+
signinSilentRef.current().catch(() => undefined),
|
|
114
|
+
new Promise<void>((resolve) =>
|
|
115
|
+
setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),
|
|
116
|
+
),
|
|
117
|
+
]);
|
|
118
|
+
}).finally(finish);
|
|
119
|
+
}, [isLoading, skipRecovery, userExpired]);
|
|
120
|
+
|
|
121
|
+
const shouldBlock =
|
|
122
|
+
!skipRecovery &&
|
|
123
|
+
(recovering || (!recoveryDone && !isLoading && userExpired));
|
|
124
|
+
|
|
125
|
+
if (shouldBlock) {
|
|
126
|
+
return <>{loadingFallback}</>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return <>{children}</>;
|
|
130
|
+
}
|
|
131
|
+
|
|
52
132
|
/**
|
|
53
133
|
* A wrapper React component which provides a {@link ReactAuthProvider}
|
|
54
134
|
* configured with Hercules Auth.
|
|
@@ -60,14 +140,20 @@ export function HerculesAuthProvider({
|
|
|
60
140
|
userManagerSettings,
|
|
61
141
|
authority,
|
|
62
142
|
client_id,
|
|
143
|
+
loadingFallback = null,
|
|
63
144
|
...props
|
|
64
145
|
}: HerculesAuthProviderProps) {
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
146
|
+
const automaticSilentRenewExplicit =
|
|
147
|
+
userManagerSettings?.automaticSilentRenew === true;
|
|
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({
|
|
68
154
|
...userManagerSettings,
|
|
69
|
-
authority:
|
|
70
|
-
client_id:
|
|
155
|
+
authority: effectiveAuthority,
|
|
156
|
+
client_id: effectiveClientId,
|
|
71
157
|
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
72
158
|
response_type: userManagerSettings?.response_type ?? "code",
|
|
73
159
|
scope:
|
|
@@ -81,18 +167,146 @@ export function HerculesAuthProvider({
|
|
|
81
167
|
userStore:
|
|
82
168
|
userManagerSettings?.userStore ??
|
|
83
169
|
new WebStorageStateStore({ store: window.localStorage }),
|
|
170
|
+
automaticSilentRenew:
|
|
171
|
+
userManagerSettings?.automaticSilentRenew ?? false,
|
|
172
|
+
silentRequestTimeoutInSeconds:
|
|
173
|
+
userManagerSettings?.silentRequestTimeoutInSeconds ??
|
|
174
|
+
RECOVERY_TIMEOUT_MS / 1000,
|
|
84
175
|
}),
|
|
85
|
-
|
|
176
|
+
impersonationStorageKey: getHerculesImpersonationStorageKey(
|
|
177
|
+
effectiveAuthority,
|
|
178
|
+
effectiveClientId,
|
|
179
|
+
),
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
useEffect(() => {
|
|
184
|
+
if (automaticSilentRenewExplicit) return;
|
|
185
|
+
let retryTimerId: ReturnType<typeof setTimeout> | null = null;
|
|
186
|
+
let timeoutRetryCount = 0;
|
|
187
|
+
let stopped = false;
|
|
188
|
+
const events = userManager.events as unknown as {
|
|
189
|
+
_raiseSilentRenewError?: (e: Error) => void;
|
|
190
|
+
};
|
|
191
|
+
const tryRenew = () => {
|
|
192
|
+
if (stopped) return;
|
|
193
|
+
void withRefreshLock(async () => {
|
|
194
|
+
if (stopped) return;
|
|
195
|
+
try {
|
|
196
|
+
await userManager.signinSilent();
|
|
197
|
+
timeoutRetryCount = 0;
|
|
198
|
+
} catch (err) {
|
|
199
|
+
if (stopped) return;
|
|
200
|
+
const isTimeout = err instanceof Error && err.name === "ErrorTimeout";
|
|
201
|
+
if (isTimeout) {
|
|
202
|
+
timeoutRetryCount++;
|
|
203
|
+
const maxRetries = (
|
|
204
|
+
userManager.settings as {
|
|
205
|
+
maxSilentRenewTimeoutRetries?: number;
|
|
206
|
+
}
|
|
207
|
+
).maxSilentRenewTimeoutRetries;
|
|
208
|
+
if (maxRetries !== undefined && timeoutRetryCount > maxRetries) {
|
|
209
|
+
timeoutRetryCount = 0;
|
|
210
|
+
events._raiseSilentRenewError?.(err as Error);
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
retryTimerId = setTimeout(() => {
|
|
214
|
+
retryTimerId = null;
|
|
215
|
+
tryRenew();
|
|
216
|
+
}, 5000);
|
|
217
|
+
} else {
|
|
218
|
+
timeoutRetryCount = 0;
|
|
219
|
+
events._raiseSilentRenewError?.(err as Error);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
};
|
|
224
|
+
const onExpiring = () => tryRenew();
|
|
225
|
+
userManager.events.addAccessTokenExpiring(onExpiring);
|
|
226
|
+
return () => {
|
|
227
|
+
stopped = true;
|
|
228
|
+
userManager.events.removeAccessTokenExpiring(onExpiring);
|
|
229
|
+
if (retryTimerId !== null) clearTimeout(retryTimerId);
|
|
230
|
+
};
|
|
231
|
+
}, [userManager, automaticSilentRenewExplicit]);
|
|
86
232
|
|
|
87
233
|
return (
|
|
88
|
-
<HerculesAuthProviderContext.Provider
|
|
234
|
+
<HerculesAuthProviderContext.Provider
|
|
235
|
+
value={{ userManager, impersonationStorageKey }}
|
|
236
|
+
>
|
|
89
237
|
<ReactAuthProvider
|
|
90
238
|
userManager={userManager}
|
|
91
239
|
{...DEFAULT_AUTH_CONFIG}
|
|
92
240
|
{...props}
|
|
93
241
|
>
|
|
94
|
-
{
|
|
242
|
+
<HerculesImpersonationHandoff storageKey={impersonationStorageKey} />
|
|
243
|
+
<AuthRecoveryGate
|
|
244
|
+
loadingFallback={loadingFallback}
|
|
245
|
+
skipRecovery={hasCompleteImpersonationHandoff()}
|
|
246
|
+
>
|
|
247
|
+
{children}
|
|
248
|
+
</AuthRecoveryGate>
|
|
95
249
|
</ReactAuthProvider>
|
|
96
250
|
</HerculesAuthProviderContext.Provider>
|
|
97
251
|
);
|
|
98
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
|
+
}
|