@usehercules/auth 1.0.46 → 1.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usehercules/auth",
3
- "version": "1.0.46",
3
+ "version": "1.2.0",
4
4
  "description": "Authentication utilities for Hercules applications using OIDC",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -27,9 +27,9 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "jwt-decode": "^4.0.0",
30
- "oidc-client-ts": "^3.4.1",
30
+ "oidc-client-ts": "^3.5.0",
31
31
  "react-oidc-context": "^3.3.1",
32
- "zod": "^4.3.6"
32
+ "zod": "^4.4.3"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "convex": "^1.29.0",
@@ -38,15 +38,15 @@
38
38
  "devDependencies": {
39
39
  "@testing-library/jest-dom": "^6.9.1",
40
40
  "@testing-library/react": "^16.3.2",
41
- "@types/react": "^19.2.14",
41
+ "@types/react": "^19.2.17",
42
42
  "@types/react-dom": "^19.2.3",
43
- "convex": "^1.38.0",
44
- "jsdom": "^28.1.0",
45
- "react": "^19.2.4",
46
- "react-dom": "^19.2.4",
47
- "tsdown": "^0.18.4",
48
- "typescript": "^5.9.3",
49
- "vitest": "^4.1.0"
43
+ "convex": "^1.42.1",
44
+ "jsdom": "^29.1.1",
45
+ "react": "^19.2.7",
46
+ "react-dom": "^19.2.7",
47
+ "tsdown": "^0.22.3",
48
+ "typescript": "^6.0.3",
49
+ "vitest": "^4.1.10"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsdown",
@@ -23,9 +23,7 @@ vi.mock("react-oidc-context", () => ({
23
23
  type CapturedUseAuth = () => {
24
24
  isLoading: boolean;
25
25
  isAuthenticated: boolean;
26
- fetchAccessToken: (args: {
27
- forceRefreshToken: boolean;
28
- }) => Promise<string | null>;
26
+ fetchAccessToken: (args: { forceRefreshToken: boolean }) => Promise<string | null>;
29
27
  };
30
28
 
31
29
  let capturedUseAuth: CapturedUseAuth | null = null;
@@ -43,9 +41,9 @@ vi.mock("convex/react", () => ({
43
41
  },
44
42
  }));
45
43
 
46
- // Token expiring in 30 minutes (within the 1hr refresh threshold)
44
+ // Token expiring in 30 minutes (within the one-hour refresh threshold).
47
45
  const EXPIRING_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
48
- // Token expiring in 2 hours (outside the 1hr refresh threshold)
46
+ // Token expiring in two hours (outside the one-hour refresh threshold).
49
47
  const LONG_LIVED_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 2 * 60 * 60);
50
48
 
51
49
  function setAuthState(overrides: Record<string, unknown>) {
@@ -111,7 +109,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
111
109
  expect(mockSigninSilent).not.toHaveBeenCalled();
112
110
  });
113
111
 
114
- it("skips refresh when token expires more than 1 hour from now", async () => {
112
+ it("skips refresh when token expires more than one hour from now", async () => {
115
113
  setAuthState({ user: { id_token: LONG_LIVED_TOKEN } });
116
114
 
117
115
  const { result } = renderUseAuth();
@@ -200,11 +198,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
200
198
 
201
199
  resolveSilent?.({ id_token: "fresh-token" });
202
200
 
203
- [firstToken, secondToken, thirdToken] = await Promise.all([
204
- first,
205
- second,
206
- third,
207
- ]);
201
+ [firstToken, secondToken, thirdToken] = await Promise.all([first, second, third]);
208
202
  });
209
203
 
210
204
  expect(firstToken).toBe("fresh-token");
@@ -252,9 +246,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
252
246
  const { result, rerender } = renderUseAuth();
253
247
  const firstFetch = result.current.fetchAccessToken;
254
248
 
255
- expect(
256
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
257
- ).toBe(FIRST_TOKEN);
249
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(FIRST_TOKEN);
258
250
 
259
251
  setAuthState({
260
252
  user: {
@@ -265,9 +257,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
265
257
  rerender();
266
258
 
267
259
  expect(result.current.fetchAccessToken).toBe(firstFetch);
268
- expect(
269
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
270
- ).toBe(SECOND_TOKEN);
260
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(SECOND_TOKEN);
271
261
  });
272
262
 
273
263
  it("re-identifies fetchAccessToken when the subject changes", async () => {
@@ -285,9 +275,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
285
275
  });
286
276
  rerender();
287
277
 
288
- expect(
289
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
290
- ).toBe(BOB_TOKEN);
278
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(BOB_TOKEN);
291
279
  expect(result.current.fetchAccessToken).not.toBe(aliceFetch);
292
280
  });
293
281
 
@@ -313,8 +301,6 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
313
301
  rerender();
314
302
 
315
303
  expect(result.current.fetchAccessToken).not.toBe(firstFetch);
316
- expect(
317
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
318
- ).toBe(SECOND_TOKEN);
304
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(SECOND_TOKEN);
319
305
  });
320
306
  });
@@ -39,10 +39,7 @@ function useUseAuthFromHercules() {
39
39
  if (!forceRefreshToken) {
40
40
  return currentToken ?? null;
41
41
  }
42
- if (
43
- currentToken != null &&
44
- !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
45
- ) {
42
+ if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) {
46
43
  return currentToken;
47
44
  }
48
45
  if (inFlightRefresh.current) {
@@ -50,10 +47,7 @@ function useUseAuthFromHercules() {
50
47
  }
51
48
  const refresh = withRefreshLock(async () => {
52
49
  const tokenAfterLock = idTokenRef.current;
53
- if (
54
- tokenAfterLock != null &&
55
- !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)
56
- ) {
50
+ if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) {
57
51
  return tokenAfterLock;
58
52
  }
59
53
  try {
@@ -7,10 +7,7 @@ type Queue = {
7
7
 
8
8
  const mutexes = new Map<string, Queue>();
9
9
 
10
- async function manualMutex<T>(
11
- key: string,
12
- callback: () => Promise<T>,
13
- ): Promise<T> {
10
+ async function manualMutex<T>(key: string, callback: () => Promise<T>): Promise<T> {
14
11
  return new Promise<T>((resolve, reject) => {
15
12
  const wrapped = () =>
16
13
  callback()
@@ -40,9 +37,7 @@ async function manualMutex<T>(
40
37
  });
41
38
  }
42
39
 
43
- export async function withRefreshLock<T>(
44
- callback: () => Promise<T>,
45
- ): Promise<T> {
40
+ export async function withRefreshLock<T>(callback: () => Promise<T>): Promise<T> {
46
41
  if (typeof navigator !== "undefined" && navigator.locks) {
47
42
  return navigator.locks.request(REFRESH_LOCK_KEY, callback);
48
43
  }
@@ -5,7 +5,15 @@ import { HerculesAuthProvider } from "./HerculesAuthProvider.js";
5
5
  configure({ reactStrictMode: false });
6
6
 
7
7
  const mockSigninSilent = vi.fn();
8
+ const mockSigninRedirect = vi.fn();
9
+ const mockRemoveUser = vi.fn();
8
10
  let mockAuthState: Record<string, unknown> = {};
11
+ const localStorageMock = createMemoryStorage();
12
+
13
+ Object.defineProperty(window, "localStorage", {
14
+ value: localStorageMock,
15
+ configurable: true,
16
+ });
9
17
 
10
18
  vi.mock("react-oidc-context", () => ({
11
19
  AuthProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
@@ -41,8 +49,12 @@ function setAuthState(overrides: Record<string, unknown>) {
41
49
  }
42
50
 
43
51
  beforeEach(() => {
52
+ window.history.replaceState({}, "", "/");
53
+ window.localStorage.clear();
44
54
  setAuthState({});
45
55
  mockSigninSilent.mockReset();
56
+ mockSigninRedirect.mockReset();
57
+ mockRemoveUser.mockReset();
46
58
  });
47
59
 
48
60
  function renderProvider(
@@ -84,7 +96,56 @@ describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
84
96
  });
85
97
  });
86
98
 
99
+ function createMemoryStorage(): Storage {
100
+ const store = new Map<string, string>();
101
+
102
+ return {
103
+ get length() {
104
+ return store.size;
105
+ },
106
+ clear() {
107
+ store.clear();
108
+ },
109
+ getItem(key: string) {
110
+ return store.get(key) ?? null;
111
+ },
112
+ key(index: number) {
113
+ return Array.from(store.keys())[index] ?? null;
114
+ },
115
+ removeItem(key: string) {
116
+ store.delete(key);
117
+ },
118
+ setItem(key: string, value: string) {
119
+ store.set(key, value);
120
+ },
121
+ };
122
+ }
123
+
87
124
  describe("HerculesAuthProvider AuthRecoveryGate", () => {
125
+ it("prioritizes an impersonation handoff over expired-session recovery", async () => {
126
+ window.history.replaceState(
127
+ {},
128
+ "",
129
+ "/?hercules_impersonation_session_id=session_1&hercules_impersonation_token=token_1",
130
+ );
131
+ setAuthState({
132
+ isAuthenticated: true,
133
+ removeUser: mockRemoveUser.mockResolvedValue(undefined),
134
+ signinRedirect: mockSigninRedirect.mockResolvedValue(undefined),
135
+ user: { expired: true, id_token: "stale" },
136
+ });
137
+
138
+ renderProvider(<div data-testid="loading">loading</div>);
139
+
140
+ expect(screen.getByTestId("app")).toBeDefined();
141
+ expect(screen.queryByTestId("loading")).toBeNull();
142
+ await waitFor(() => {
143
+ expect(mockSigninRedirect).toHaveBeenCalledTimes(1);
144
+ });
145
+ expect(mockRemoveUser).toHaveBeenCalledTimes(1);
146
+ expect(mockSigninSilent).not.toHaveBeenCalled();
147
+ });
148
+
88
149
  it("renders children (not loadingFallback) while isLoading is true", async () => {
89
150
  setAuthState({ isLoading: true, user: null });
90
151
  renderProvider(<div data-testid="loading">loading</div>);
@@ -95,7 +156,10 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
95
156
 
96
157
  it("blocks children on the very first commit when user is already expired", () => {
97
158
  mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
98
- setAuthState({ isLoading: false, user: { expired: true, id_token: "stale" } });
159
+ setAuthState({
160
+ isLoading: false,
161
+ user: { expired: true, id_token: "stale" },
162
+ });
99
163
  renderProvider(<div data-testid="loading">loading</div>);
100
164
  expect(screen.getByTestId("loading")).toBeDefined();
101
165
  expect(screen.queryByTestId("app")).toBeNull();
@@ -109,14 +173,20 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
109
173
  resolveSilent = resolve;
110
174
  }),
111
175
  );
112
- setAuthState({ isLoading: false, user: { expired: true, id_token: "stale" } });
176
+ setAuthState({
177
+ isLoading: false,
178
+ user: { expired: true, id_token: "stale" },
179
+ });
113
180
  const { rerender } = renderProvider(<div data-testid="loading">loading</div>);
114
181
  expect(screen.getByTestId("loading")).toBeDefined();
115
182
  await waitFor(() => {
116
183
  expect(mockSigninSilent).toHaveBeenCalledTimes(1);
117
184
  });
118
185
 
119
- setAuthState({ isLoading: true, user: { expired: true, id_token: "stale" } });
186
+ setAuthState({
187
+ isLoading: true,
188
+ user: { expired: true, id_token: "stale" },
189
+ });
120
190
  rerender(
121
191
  <HerculesAuthProvider
122
192
  authority="https://auth.example.com"
@@ -274,10 +344,7 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
274
344
  });
275
345
  setAuthState({ user: { expired: true, id_token: "stale-2" } });
276
346
  rerender(
277
- <HerculesAuthProvider
278
- authority="https://auth.example.com"
279
- client_id="test-client"
280
- >
347
+ <HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
281
348
  <div data-testid="app">app content</div>
282
349
  </HerculesAuthProvider>,
283
350
  );
@@ -1,32 +1,25 @@
1
1
  "use client";
2
2
 
3
- import {
4
- createContext,
5
- useContext,
6
- useEffect,
7
- useRef,
8
- useState,
9
- type ReactNode,
10
- } from "react";
3
+ import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react";
11
4
  import {
12
5
  AuthProvider as ReactAuthProvider,
13
6
  type AuthProviderUserManagerProps,
14
7
  useAuth,
15
8
  } from "react-oidc-context";
16
- import {
17
- UserManager,
18
- WebStorageStateStore,
19
- type UserManagerSettings,
20
- } from "oidc-client-ts";
9
+ import { UserManager, WebStorageStateStore, type UserManagerSettings } from "oidc-client-ts";
21
10
  import { withRefreshLock } from "../internal/refresh-lock";
11
+ import {
12
+ clearHerculesImpersonationParamsFromUrl,
13
+ getHerculesImpersonationStorageKey,
14
+ HERCULES_IMPERSONATION_SESSION_ID_PARAM,
15
+ HERCULES_IMPERSONATION_TOKEN_PARAM,
16
+ rememberHerculesImpersonationSession,
17
+ } from "./impersonation-core";
22
18
 
23
19
  const RECOVERY_TIMEOUT_MS = 10_000;
24
20
  const LOCK_GRACE_MS = 5_000;
25
21
 
26
- export type HerculesAuthProviderProps = Omit<
27
- AuthProviderUserManagerProps,
28
- "userManager"
29
- > & {
22
+ export type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
30
23
  userManagerSettings?: Partial<UserManagerSettings>;
31
24
  authority: string;
32
25
  client_id: string;
@@ -48,10 +41,10 @@ const DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {
48
41
 
49
42
  interface HerculesAuthProviderContext {
50
43
  userManager: UserManager;
44
+ impersonationStorageKey: string;
51
45
  }
52
46
 
53
- const HerculesAuthProviderContext =
54
- createContext<HerculesAuthProviderContext | null>(null);
47
+ const HerculesAuthProviderContext = createContext<HerculesAuthProviderContext | null>(null);
55
48
 
56
49
  export function useHerculesAuthProvider() {
57
50
  const context = useContext(HerculesAuthProviderContext);
@@ -64,9 +57,11 @@ export function useHerculesAuthProvider() {
64
57
  function AuthRecoveryGate({
65
58
  children,
66
59
  loadingFallback,
60
+ skipRecovery,
67
61
  }: {
68
62
  children: ReactNode;
69
63
  loadingFallback: ReactNode;
64
+ skipRecovery: boolean;
70
65
  }) {
71
66
  const { user, isLoading, signinSilent } = useAuth();
72
67
  const userExpired = user?.expired === true;
@@ -77,6 +72,11 @@ function AuthRecoveryGate({
77
72
  const [recovering, setRecovering] = useState(false);
78
73
 
79
74
  useEffect(() => {
75
+ if (skipRecovery) {
76
+ hasAttempted.current = true;
77
+ setRecoveryDone(true);
78
+ return;
79
+ }
80
80
  if (isLoading) return;
81
81
  if (hasAttempted.current) return;
82
82
  hasAttempted.current = true;
@@ -96,15 +96,12 @@ function AuthRecoveryGate({
96
96
  void withRefreshLock(async () => {
97
97
  await Promise.race([
98
98
  signinSilentRef.current().catch(() => undefined),
99
- new Promise<void>((resolve) =>
100
- setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),
101
- ),
99
+ new Promise<void>((resolve) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS)),
102
100
  ]);
103
101
  }).finally(finish);
104
- }, [isLoading, userExpired]);
102
+ }, [isLoading, skipRecovery, userExpired]);
105
103
 
106
- const shouldBlock =
107
- recovering || (!recoveryDone && !isLoading && userExpired);
104
+ const shouldBlock = !skipRecovery && (recovering || (!recoveryDone && !isLoading && userExpired));
108
105
 
109
106
  if (shouldBlock) {
110
107
  return <>{loadingFallback}</>;
@@ -127,34 +124,36 @@ export function HerculesAuthProvider({
127
124
  loadingFallback = null,
128
125
  ...props
129
126
  }: HerculesAuthProviderProps) {
130
- const automaticSilentRenewExplicit =
131
- userManagerSettings?.automaticSilentRenew === true;
132
- const [userManager] = useState(
133
- () =>
134
- new UserManager({
127
+ const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
128
+ const [{ userManager, impersonationStorageKey }] = useState(() => {
129
+ const effectiveAuthority = userManagerSettings?.authority ?? authority;
130
+ const effectiveClientId = userManagerSettings?.client_id ?? client_id;
131
+
132
+ return {
133
+ userManager: new UserManager({
135
134
  ...userManagerSettings,
136
- authority: userManagerSettings?.authority ?? authority,
137
- client_id: userManagerSettings?.client_id ?? client_id,
135
+ authority: effectiveAuthority,
136
+ client_id: effectiveClientId,
138
137
  prompt: userManagerSettings?.prompt ?? "select_account",
139
138
  response_type: userManagerSettings?.response_type ?? "code",
140
- scope:
141
- userManagerSettings?.scope ?? "openid profile email offline_access",
139
+ scope: userManagerSettings?.scope ?? "openid profile email offline_access",
142
140
  redirect_uri:
143
- userManagerSettings?.redirect_uri ??
144
- `${window.location.origin}/auth/callback`,
141
+ userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
145
142
  post_logout_redirect_uri:
146
- userManagerSettings?.post_logout_redirect_uri ??
147
- window.location.origin,
143
+ userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
148
144
  userStore:
149
145
  userManagerSettings?.userStore ??
150
146
  new WebStorageStateStore({ store: window.localStorage }),
151
- automaticSilentRenew:
152
- userManagerSettings?.automaticSilentRenew ?? false,
147
+ automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
153
148
  silentRequestTimeoutInSeconds:
154
- userManagerSettings?.silentRequestTimeoutInSeconds ??
155
- RECOVERY_TIMEOUT_MS / 1000,
149
+ userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
156
150
  }),
157
- );
151
+ impersonationStorageKey: getHerculesImpersonationStorageKey(
152
+ effectiveAuthority,
153
+ effectiveClientId,
154
+ ),
155
+ };
156
+ });
158
157
 
159
158
  useEffect(() => {
160
159
  if (automaticSilentRenewExplicit) return;
@@ -173,8 +172,7 @@ export function HerculesAuthProvider({
173
172
  timeoutRetryCount = 0;
174
173
  } catch (err) {
175
174
  if (stopped) return;
176
- const isTimeout =
177
- err instanceof Error && err.name === "ErrorTimeout";
175
+ const isTimeout = err instanceof Error && err.name === "ErrorTimeout";
178
176
  if (isTimeout) {
179
177
  timeoutRetryCount++;
180
178
  const maxRetries = (
@@ -208,16 +206,72 @@ export function HerculesAuthProvider({
208
206
  }, [userManager, automaticSilentRenewExplicit]);
209
207
 
210
208
  return (
211
- <HerculesAuthProviderContext.Provider value={{ userManager }}>
212
- <ReactAuthProvider
213
- userManager={userManager}
214
- {...DEFAULT_AUTH_CONFIG}
215
- {...props}
216
- >
217
- <AuthRecoveryGate loadingFallback={loadingFallback}>
209
+ <HerculesAuthProviderContext.Provider value={{ userManager, impersonationStorageKey }}>
210
+ <ReactAuthProvider userManager={userManager} {...DEFAULT_AUTH_CONFIG} {...props}>
211
+ <HerculesImpersonationHandoff storageKey={impersonationStorageKey} />
212
+ <AuthRecoveryGate
213
+ loadingFallback={loadingFallback}
214
+ skipRecovery={hasCompleteImpersonationHandoff()}
215
+ >
218
216
  {children}
219
217
  </AuthRecoveryGate>
220
218
  </ReactAuthProvider>
221
219
  </HerculesAuthProviderContext.Provider>
222
220
  );
223
221
  }
222
+
223
+ function HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {
224
+ const auth = useAuth();
225
+ const hasStartedRef = useRef(false);
226
+
227
+ useEffect(() => {
228
+ if (hasStartedRef.current || typeof window === "undefined") return;
229
+
230
+ const url = new URL(window.location.href);
231
+ const impersonationSessionId = url.searchParams.get(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
232
+ const impersonationToken = url.searchParams.get(HERCULES_IMPERSONATION_TOKEN_PARAM);
233
+ if (!impersonationSessionId && !impersonationToken) return;
234
+ if (!impersonationSessionId || !impersonationToken) {
235
+ window.history.replaceState(
236
+ {},
237
+ document.title,
238
+ clearHerculesImpersonationParamsFromUrl(url).toString(),
239
+ );
240
+ return;
241
+ }
242
+ if (auth.isLoading) return;
243
+
244
+ hasStartedRef.current = true;
245
+ rememberHerculesImpersonationSession(storageKey, impersonationSessionId);
246
+ window.history.replaceState(
247
+ {},
248
+ document.title,
249
+ clearHerculesImpersonationParamsFromUrl(url).toString(),
250
+ );
251
+
252
+ void (async () => {
253
+ if (auth.isAuthenticated) {
254
+ await auth.removeUser();
255
+ }
256
+
257
+ await auth.signinRedirect({
258
+ extraQueryParams: {
259
+ [HERCULES_IMPERSONATION_SESSION_ID_PARAM]: impersonationSessionId,
260
+ [HERCULES_IMPERSONATION_TOKEN_PARAM]: impersonationToken,
261
+ },
262
+ });
263
+ })();
264
+ }, [auth, storageKey]);
265
+
266
+ return null;
267
+ }
268
+
269
+ function hasCompleteImpersonationHandoff(): boolean {
270
+ if (typeof window === "undefined") return false;
271
+
272
+ const params = new URL(window.location.href).searchParams;
273
+ return (
274
+ params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) &&
275
+ params.has(HERCULES_IMPERSONATION_TOKEN_PARAM)
276
+ );
277
+ }
@@ -120,9 +120,7 @@ describe("useAuthCallback", () => {
120
120
  vi.useFakeTimers();
121
121
 
122
122
  try {
123
- const { result } = renderHook(() =>
124
- useAuthCallback({ timeoutMs: 5000 }),
125
- );
123
+ const { result } = renderHook(() => useAuthCallback({ timeoutMs: 5000 }));
126
124
 
127
125
  expect(result.current.status).toBe("processing-oauth");
128
126
 
@@ -131,9 +129,7 @@ describe("useAuthCallback", () => {
131
129
  });
132
130
 
133
131
  expect(result.current.status).toBe("error");
134
- expect(result.current.error).toBe(
135
- "Authentication timed out. Please try again.",
136
- );
132
+ expect(result.current.error).toBe("Authentication timed out. Please try again.");
137
133
  expect(result.current.isError).toBe(true);
138
134
  expect(result.current.isLoading).toBe(false);
139
135
  } finally {
@@ -269,9 +265,7 @@ describe("useAuthCallback", () => {
269
265
  it("goes straight to success when onSync is omitted", async () => {
270
266
  setAuthState({ isLoading: false, isAuthenticated: true });
271
267
 
272
- const { result } = renderHook(() =>
273
- useAuthCallback({ isBackendAuthenticated: true }),
274
- );
268
+ const { result } = renderHook(() => useAuthCallback({ isBackendAuthenticated: true }));
275
269
 
276
270
  await waitFor(() => {
277
271
  expect(result.current.status).toBe("success");
@@ -117,9 +117,7 @@ export interface UseAuthCallbackResult {
117
117
  *
118
118
  * @public
119
119
  */
120
- export function useAuthCallback(
121
- options: UseAuthCallbackOptions = {},
122
- ): UseAuthCallbackResult {
120
+ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCallbackResult {
123
121
  const {
124
122
  timeoutMs = DEFAULT_TIMEOUT_MS,
125
123
  isBackendAuthenticated = true,
@@ -187,11 +185,7 @@ export function useAuthCallback(
187
185
  }
188
186
 
189
187
  // OIDC is done loading and authenticated - move to waiting for backend
190
- if (
191
- !isAuthLoading &&
192
- isOidcAuthenticated &&
193
- status === "processing-oauth"
194
- ) {
188
+ if (!isAuthLoading && isOidcAuthenticated && status === "processing-oauth") {
195
189
  setStatus("waiting-backend");
196
190
  return;
197
191
  }
@@ -0,0 +1,27 @@
1
+ "use client";
2
+
3
+ export const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
4
+ export const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
5
+
6
+ export type StoredHerculesImpersonation = {
7
+ sessionId: string;
8
+ startedAt: string;
9
+ };
10
+
11
+ export function getHerculesImpersonationStorageKey(authority: string, clientId: string) {
12
+ return `hercules.impersonation.${authority}.${clientId}`;
13
+ }
14
+
15
+ export function rememberHerculesImpersonationSession(storageKey: string, sessionId: string) {
16
+ if (typeof window === "undefined") return;
17
+ window.localStorage.setItem(
18
+ storageKey,
19
+ JSON.stringify({ sessionId, startedAt: new Date().toISOString() }),
20
+ );
21
+ }
22
+
23
+ export function clearHerculesImpersonationParamsFromUrl(url: URL) {
24
+ url.searchParams.delete(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
25
+ url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);
26
+ return url;
27
+ }