@usehercules/auth 1.1.0 → 1.2.1

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.
@@ -0,0 +1,70 @@
1
+ import { jwtDecode } from "jwt-decode";
2
+ import {
3
+ UserManager,
4
+ type CreateSignoutRequestArgs,
5
+ type IWindow,
6
+ type NavigateResponse,
7
+ } from "oidc-client-ts";
8
+
9
+ function logoutRedirectUrl(requestUrl: string, clientId: string): string {
10
+ const url = new URL(requestUrl);
11
+ const hints = url.searchParams.getAll("id_token_hint");
12
+ const idToken = hints[0];
13
+ if (!idToken || hints.length !== 1) return requestUrl;
14
+
15
+ let sessionId: unknown;
16
+ try {
17
+ sessionId = jwtDecode<{ sid?: unknown }>(idToken).sid;
18
+ } catch {
19
+ return requestUrl;
20
+ }
21
+ if (typeof sessionId === "string" && sessionId.length > 0) return requestUrl;
22
+
23
+ const clients = url.searchParams.getAll("client_id");
24
+ if (clients.length > 1 || (clients.length === 1 && clients[0] !== clientId)) return requestUrl;
25
+
26
+ url.searchParams.delete("id_token_hint");
27
+ url.searchParams.set("client_id", clientId);
28
+ return url.toString();
29
+ }
30
+
31
+ const END_SESSION_TIMEOUT_MS = 5000;
32
+
33
+ function isFramed(): boolean {
34
+ if (typeof window === "undefined") return false;
35
+ try {
36
+ return window.self !== window.top;
37
+ } catch {
38
+ return true;
39
+ }
40
+ }
41
+
42
+ async function endSessionInBackground(url: string): Promise<NavigateResponse> {
43
+ await fetch(url, {
44
+ mode: "no-cors",
45
+ credentials: "omit",
46
+ signal: AbortSignal.timeout(END_SESSION_TIMEOUT_MS),
47
+ }).catch(() => undefined);
48
+ return { url };
49
+ }
50
+
51
+ export class HerculesUserManager extends UserManager {
52
+ // Transform after UserManager's revocation and single storage removal, inside its navigator action.
53
+ protected override _signoutStart(
54
+ args: CreateSignoutRequestArgs = {},
55
+ handle: IWindow,
56
+ ): Promise<NavigateResponse> {
57
+ if (args.request_type !== "so:r") return super._signoutStart(args, handle);
58
+
59
+ return super._signoutStart(args, {
60
+ close: () => handle.close(),
61
+ navigate: (params) => {
62
+ const url = logoutRedirectUrl(params.url, this.settings.client_id);
63
+ if (this.settings.redirectTarget !== "top" && isFramed()) {
64
+ return endSessionInBackground(url);
65
+ }
66
+ return handle.navigate({ ...params, url });
67
+ },
68
+ });
69
+ }
70
+ }
@@ -0,0 +1,66 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import type { UserManager } from "oidc-client-ts";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { HerculesAuthProvider, useHerculesAuthProvider } from "./HerculesAuthProvider";
5
+
6
+ function blockStorage(name: "localStorage" | "sessionStorage") {
7
+ vi.spyOn(window, name, "get").mockImplementation(() => {
8
+ throw new DOMException("The operation is insecure.", "SecurityError");
9
+ });
10
+ }
11
+
12
+ function mountProvider(): UserManager {
13
+ let manager: UserManager | undefined;
14
+ function Capture() {
15
+ manager = useHerculesAuthProvider().userManager;
16
+ return <div data-testid="app">app</div>;
17
+ }
18
+ const { unmount } = render(
19
+ <HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
20
+ <Capture />
21
+ </HerculesAuthProvider>,
22
+ );
23
+ expect(screen.getByTestId("app")).toBeTruthy();
24
+ unmount();
25
+ return manager!;
26
+ }
27
+
28
+ beforeEach(() => {
29
+ window.localStorage.clear();
30
+ window.sessionStorage.clear();
31
+ });
32
+
33
+ afterEach(() => {
34
+ vi.restoreAllMocks();
35
+ });
36
+
37
+ describe("HerculesAuthProvider storage", () => {
38
+ it("keeps OIDC state in localStorage when it is available", async () => {
39
+ const { stateStore, userStore } = mountProvider().settings;
40
+
41
+ await stateStore.set("request", "state");
42
+ await userStore.set("user", "session");
43
+
44
+ expect(window.localStorage.getItem("oidc.request")).toBe("state");
45
+ expect(window.localStorage.getItem("oidc.user")).toBe("session");
46
+ });
47
+
48
+ it("falls back to sessionStorage, which survives the sign-in redirect", async () => {
49
+ blockStorage("localStorage");
50
+
51
+ await mountProvider().settings.stateStore.set("request", "state");
52
+
53
+ expect(window.sessionStorage.getItem("oidc.request")).toBe("state");
54
+ await expect(mountProvider().settings.stateStore.get("request")).resolves.toBe("state");
55
+ });
56
+
57
+ it("mounts with in-memory storage when the browser blocks all Web Storage", async () => {
58
+ blockStorage("localStorage");
59
+ blockStorage("sessionStorage");
60
+
61
+ const { stateStore } = mountProvider().settings;
62
+ await stateStore.set("request", "state");
63
+
64
+ await expect(stateStore.get("request")).resolves.toBe("state");
65
+ });
66
+ });
@@ -1,11 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import {
3
- act,
4
- render,
5
- screen,
6
- waitFor,
7
- configure,
8
- } from "@testing-library/react";
2
+ import { act, render, screen, waitFor, configure } from "@testing-library/react";
9
3
  import { HerculesAuthProvider } from "./HerculesAuthProvider.js";
10
4
 
11
5
  configure({ reactStrictMode: false });
@@ -22,9 +16,7 @@ Object.defineProperty(window, "localStorage", {
22
16
  });
23
17
 
24
18
  vi.mock("react-oidc-context", () => ({
25
- AuthProvider: ({ children }: { children: React.ReactNode }) => (
26
- <>{children}</>
27
- ),
19
+ AuthProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
28
20
  useAuth: () => mockAuthState,
29
21
  }));
30
22
 
@@ -83,10 +75,7 @@ function renderProvider(
83
75
  describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
84
76
  it("registers the lock-wrapped renewal listener by default", () => {
85
77
  render(
86
- <HerculesAuthProvider
87
- authority="https://auth.example.com"
88
- client_id="test-client"
89
- >
78
+ <HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
90
79
  <div data-testid="app">app</div>
91
80
  </HerculesAuthProvider>,
92
81
  );
@@ -188,9 +177,7 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
188
177
  isLoading: false,
189
178
  user: { expired: true, id_token: "stale" },
190
179
  });
191
- const { rerender } = renderProvider(
192
- <div data-testid="loading">loading</div>,
193
- );
180
+ const { rerender } = renderProvider(<div data-testid="loading">loading</div>);
194
181
  expect(screen.getByTestId("loading")).toBeDefined();
195
182
  await waitFor(() => {
196
183
  expect(mockSigninSilent).toHaveBeenCalledTimes(1);
@@ -304,6 +291,21 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
304
291
  });
305
292
  });
306
293
 
294
+ it("renders an accessible default loading status when no loadingFallback is passed", () => {
295
+ mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
296
+ setAuthState({ user: { expired: true, id_token: "stale" } });
297
+ renderProvider();
298
+ expect(screen.getByRole("status", { name: "Loading" })).toBeDefined();
299
+ expect(screen.queryByTestId("app")).toBeNull();
300
+ });
301
+
302
+ it("renders nothing during recovery when loadingFallback is null", () => {
303
+ mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
304
+ setAuthState({ user: { expired: true, id_token: "stale" } });
305
+ const { container } = renderProvider(null);
306
+ expect(container.innerHTML).toBe("");
307
+ });
308
+
307
309
  it("renders children after the recovery times out", async () => {
308
310
  vi.useFakeTimers({ shouldAdvanceTime: true });
309
311
  mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
@@ -357,10 +359,7 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
357
359
  });
358
360
  setAuthState({ user: { expired: true, id_token: "stale-2" } });
359
361
  rerender(
360
- <HerculesAuthProvider
361
- authority="https://auth.example.com"
362
- client_id="test-client"
363
- >
362
+ <HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
364
363
  <div data-testid="app">app content</div>
365
364
  </HerculesAuthProvider>,
366
365
  );
@@ -1,24 +1,19 @@
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
9
  import {
17
- UserManager,
10
+ InMemoryWebStorage,
18
11
  WebStorageStateStore,
12
+ type UserManager,
19
13
  type UserManagerSettings,
20
14
  } from "oidc-client-ts";
21
15
  import { withRefreshLock } from "../internal/refresh-lock";
16
+ import { HerculesUserManager } from "../internal/user-manager";
22
17
  import {
23
18
  clearHerculesImpersonationParamsFromUrl,
24
19
  getHerculesImpersonationStorageKey,
@@ -30,10 +25,7 @@ import {
30
25
  const RECOVERY_TIMEOUT_MS = 10_000;
31
26
  const LOCK_GRACE_MS = 5_000;
32
27
 
33
- export type HerculesAuthProviderProps = Omit<
34
- AuthProviderUserManagerProps,
35
- "userManager"
36
- > & {
28
+ export type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
37
29
  userManagerSettings?: Partial<UserManagerSettings>;
38
30
  authority: string;
39
31
  client_id: string;
@@ -58,8 +50,7 @@ interface HerculesAuthProviderContext {
58
50
  impersonationStorageKey: string;
59
51
  }
60
52
 
61
- const HerculesAuthProviderContext =
62
- createContext<HerculesAuthProviderContext | null>(null);
53
+ const HerculesAuthProviderContext = createContext<HerculesAuthProviderContext | null>(null);
63
54
 
64
55
  export function useHerculesAuthProvider() {
65
56
  const context = useContext(HerculesAuthProviderContext);
@@ -69,6 +60,64 @@ export function useHerculesAuthProvider() {
69
60
  return context;
70
61
  }
71
62
 
63
+ /**
64
+ * Browsers that deny storage to a frame, such as a third-party iframe with
65
+ * third-party cookies blocked, throw `SecurityError` from the `localStorage`
66
+ * getter. Firefox still allows `sessionStorage` there, which keeps the OIDC
67
+ * state across the sign-in redirect. Memory is the last resort: the app
68
+ * renders, but a redirect sign-in cannot complete in that frame. The state
69
+ * store needs this too: the oidc-client-ts default reads `localStorage`.
70
+ */
71
+ function getAuthStorage(): Storage {
72
+ try {
73
+ return window.localStorage;
74
+ } catch {
75
+ try {
76
+ return window.sessionStorage;
77
+ } catch {
78
+ return new InMemoryWebStorage();
79
+ }
80
+ }
81
+ }
82
+
83
+ function DefaultLoadingFallback() {
84
+ return (
85
+ <div
86
+ role="status"
87
+ aria-label="Loading"
88
+ style={{
89
+ position: "fixed",
90
+ inset: 0,
91
+ display: "grid",
92
+ placeItems: "center",
93
+ pointerEvents: "none",
94
+ }}
95
+ >
96
+ <svg
97
+ width="32"
98
+ height="32"
99
+ viewBox="0 0 24 24"
100
+ fill="none"
101
+ stroke="currentColor"
102
+ strokeWidth="2.5"
103
+ aria-hidden="true"
104
+ >
105
+ <circle cx="12" cy="12" r="10" opacity="0.25" />
106
+ <path d="M22 12a10 10 0 0 0-10-10" strokeLinecap="round">
107
+ <animateTransform
108
+ attributeName="transform"
109
+ type="rotate"
110
+ from="0 12 12"
111
+ to="360 12 12"
112
+ dur="0.8s"
113
+ repeatCount="indefinite"
114
+ />
115
+ </path>
116
+ </svg>
117
+ </div>
118
+ );
119
+ }
120
+
72
121
  function AuthRecoveryGate({
73
122
  children,
74
123
  loadingFallback,
@@ -111,16 +160,12 @@ function AuthRecoveryGate({
111
160
  void withRefreshLock(async () => {
112
161
  await Promise.race([
113
162
  signinSilentRef.current().catch(() => undefined),
114
- new Promise<void>((resolve) =>
115
- setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),
116
- ),
163
+ new Promise<void>((resolve) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS)),
117
164
  ]);
118
165
  }).finally(finish);
119
166
  }, [isLoading, skipRecovery, userExpired]);
120
167
 
121
- const shouldBlock =
122
- !skipRecovery &&
123
- (recovering || (!recoveryDone && !isLoading && userExpired));
168
+ const shouldBlock = !skipRecovery && (recovering || (!recoveryDone && !isLoading && userExpired));
124
169
 
125
170
  if (shouldBlock) {
126
171
  return <>{loadingFallback}</>;
@@ -140,38 +185,33 @@ export function HerculesAuthProvider({
140
185
  userManagerSettings,
141
186
  authority,
142
187
  client_id,
143
- loadingFallback = null,
188
+ loadingFallback = <DefaultLoadingFallback />,
144
189
  ...props
145
190
  }: HerculesAuthProviderProps) {
146
- const automaticSilentRenewExplicit =
147
- userManagerSettings?.automaticSilentRenew === true;
191
+ const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
148
192
  const [{ userManager, impersonationStorageKey }] = useState(() => {
149
193
  const effectiveAuthority = userManagerSettings?.authority ?? authority;
150
194
  const effectiveClientId = userManagerSettings?.client_id ?? client_id;
151
195
 
152
196
  return {
153
- userManager: new UserManager({
197
+ userManager: new HerculesUserManager({
154
198
  ...userManagerSettings,
155
199
  authority: effectiveAuthority,
156
200
  client_id: effectiveClientId,
157
201
  prompt: userManagerSettings?.prompt ?? "select_account",
158
202
  response_type: userManagerSettings?.response_type ?? "code",
159
- scope:
160
- userManagerSettings?.scope ?? "openid profile email offline_access",
203
+ scope: userManagerSettings?.scope ?? "openid profile email offline_access",
161
204
  redirect_uri:
162
- userManagerSettings?.redirect_uri ??
163
- `${window.location.origin}/auth/callback`,
205
+ userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
164
206
  post_logout_redirect_uri:
165
- userManagerSettings?.post_logout_redirect_uri ??
166
- window.location.origin,
207
+ userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
167
208
  userStore:
168
- userManagerSettings?.userStore ??
169
- new WebStorageStateStore({ store: window.localStorage }),
170
- automaticSilentRenew:
171
- userManagerSettings?.automaticSilentRenew ?? false,
209
+ userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
210
+ stateStore:
211
+ userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
212
+ automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
172
213
  silentRequestTimeoutInSeconds:
173
- userManagerSettings?.silentRequestTimeoutInSeconds ??
174
- RECOVERY_TIMEOUT_MS / 1000,
214
+ userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
175
215
  }),
176
216
  impersonationStorageKey: getHerculesImpersonationStorageKey(
177
217
  effectiveAuthority,
@@ -231,14 +271,8 @@ export function HerculesAuthProvider({
231
271
  }, [userManager, automaticSilentRenewExplicit]);
232
272
 
233
273
  return (
234
- <HerculesAuthProviderContext.Provider
235
- value={{ userManager, impersonationStorageKey }}
236
- >
237
- <ReactAuthProvider
238
- userManager={userManager}
239
- {...DEFAULT_AUTH_CONFIG}
240
- {...props}
241
- >
274
+ <HerculesAuthProviderContext.Provider value={{ userManager, impersonationStorageKey }}>
275
+ <ReactAuthProvider userManager={userManager} {...DEFAULT_AUTH_CONFIG} {...props}>
242
276
  <HerculesImpersonationHandoff storageKey={impersonationStorageKey} />
243
277
  <AuthRecoveryGate
244
278
  loadingFallback={loadingFallback}
@@ -259,12 +293,8 @@ function HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {
259
293
  if (hasStartedRef.current || typeof window === "undefined") return;
260
294
 
261
295
  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
- );
296
+ const impersonationSessionId = url.searchParams.get(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
297
+ const impersonationToken = url.searchParams.get(HERCULES_IMPERSONATION_TOKEN_PARAM);
268
298
  if (!impersonationSessionId && !impersonationToken) return;
269
299
  if (!impersonationSessionId || !impersonationToken) {
270
300
  window.history.replaceState(
@@ -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 {
@@ -187,6 +183,78 @@ describe("useAuthCallback", () => {
187
183
  });
188
184
  });
189
185
 
186
+ describe("missing OIDC state", () => {
187
+ const missingStateError = () =>
188
+ Object.assign(new Error("No matching state found in storage"), {
189
+ source: "signinCallback",
190
+ });
191
+
192
+ beforeEach(() => {
193
+ window.sessionStorage.clear();
194
+ window.history.replaceState({}, "", "/auth/callback?code=orphan&state=dead");
195
+ });
196
+
197
+ it("strips the orphaned code and restarts sign-in once", () => {
198
+ setAuthState({ isLoading: false, error: missingStateError() });
199
+
200
+ const { result } = renderHook(() => useAuthCallback());
201
+
202
+ expect(mockSigninRedirect).toHaveBeenCalledOnce();
203
+ expect(window.location.search).toBe("");
204
+ expect(window.sessionStorage.getItem("hercules-auth:missing-state-retry")).toBe("1");
205
+ expect(result.current.status).toBe("processing-oauth");
206
+ });
207
+
208
+ it("shows the error when the restarted sign-in also misses state", () => {
209
+ window.sessionStorage.setItem("hercules-auth:missing-state-retry", "1");
210
+ setAuthState({ isLoading: false, error: missingStateError() });
211
+
212
+ const { result } = renderHook(() => useAuthCallback());
213
+
214
+ expect(mockSigninRedirect).not.toHaveBeenCalled();
215
+ expect(result.current.status).toBe("error");
216
+ expect(result.current.error).toBe("No matching state found in storage");
217
+ });
218
+
219
+ it("shows the error when the restarted sign-in fails to start", () => {
220
+ setAuthState({ isLoading: false, error: missingStateError() });
221
+
222
+ const { result, rerender } = renderHook(() => useAuthCallback());
223
+
224
+ setAuthState({
225
+ error: Object.assign(new Error("Network down"), { source: "signinRedirect" }),
226
+ });
227
+ rerender();
228
+
229
+ expect(mockSigninRedirect).toHaveBeenCalledOnce();
230
+ expect(result.current.status).toBe("error");
231
+ expect(result.current.error).toBe("Network down");
232
+ });
233
+
234
+ it("does not restart sign-in without an authorization code", () => {
235
+ window.history.replaceState({}, "", "/auth/callback?error=access_denied&state=dead");
236
+ setAuthState({ isLoading: false, error: missingStateError() });
237
+
238
+ const { result } = renderHook(() => useAuthCallback());
239
+
240
+ expect(mockSigninRedirect).not.toHaveBeenCalled();
241
+ expect(result.current.status).toBe("error");
242
+ });
243
+
244
+ it("does not restart sign-in for other callback errors", () => {
245
+ setAuthState({
246
+ isLoading: false,
247
+ error: Object.assign(new Error("invalid_grant"), { source: "signinCallback" }),
248
+ });
249
+
250
+ const { result } = renderHook(() => useAuthCallback());
251
+
252
+ expect(mockSigninRedirect).not.toHaveBeenCalled();
253
+ expect(result.current.status).toBe("error");
254
+ expect(window.location.search).toBe("?code=orphan&state=dead");
255
+ });
256
+ });
257
+
190
258
  describe("no auth params", () => {
191
259
  it("calls onNoAuthParams when no auth params and not authenticated", () => {
192
260
  mockHasAuthParams = false;
@@ -269,9 +337,7 @@ describe("useAuthCallback", () => {
269
337
  it("goes straight to success when onSync is omitted", async () => {
270
338
  setAuthState({ isLoading: false, isAuthenticated: true });
271
339
 
272
- const { result } = renderHook(() =>
273
- useAuthCallback({ isBackendAuthenticated: true }),
274
- );
340
+ const { result } = renderHook(() => useAuthCallback({ isBackendAuthenticated: true }));
275
341
 
276
342
  await waitFor(() => {
277
343
  expect(result.current.status).toBe("success");
@@ -1,16 +1,37 @@
1
1
  "use client";
2
2
 
3
3
  import { useEffect, useState, useRef, useCallback } from "react";
4
- import { useAuth, hasAuthParams } from "react-oidc-context";
4
+ import { useAuth, hasAuthParams, type ErrorContext } from "react-oidc-context";
5
5
  import { ConvexError } from "convex/values";
6
6
  import * as z from "zod";
7
7
 
8
8
  const DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout
9
+ const MISSING_STATE_MESSAGE = "No matching state found in storage";
10
+ const MISSING_STATE_RETRY_KEY = "hercules-auth:missing-state-retry";
9
11
 
10
12
  const convexErrorSchema = z.object({
11
13
  message: z.string(),
12
14
  });
13
15
 
16
+ function claimMissingStateRetry(error: ErrorContext): boolean {
17
+ if (error.source !== "signinCallback" || error.message !== MISSING_STATE_MESSAGE) return false;
18
+
19
+ const url = new URL(window.location.href);
20
+ if (!url.searchParams.has("code")) return false;
21
+
22
+ try {
23
+ if (window.sessionStorage.getItem(MISSING_STATE_RETRY_KEY) !== null) return false;
24
+ window.sessionStorage.setItem(MISSING_STATE_RETRY_KEY, "1");
25
+ } catch {
26
+ return false;
27
+ }
28
+
29
+ url.searchParams.delete("code");
30
+ url.searchParams.delete("state");
31
+ window.history.replaceState({}, document.title, url.toString());
32
+ return true;
33
+ }
34
+
14
35
  /**
15
36
  * Authentication callback status states
16
37
  * @public
@@ -117,9 +138,7 @@ export interface UseAuthCallbackResult {
117
138
  *
118
139
  * @public
119
140
  */
120
- export function useAuthCallback(
121
- options: UseAuthCallbackOptions = {},
122
- ): UseAuthCallbackResult {
141
+ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCallbackResult {
123
142
  const {
124
143
  timeoutMs = DEFAULT_TIMEOUT_MS,
125
144
  isBackendAuthenticated = true,
@@ -144,6 +163,7 @@ export function useAuthCallback(
144
163
  const hadAuthParams = useRef(hasAuthParams());
145
164
  // Track if we've already started sync to prevent double execution
146
165
  const syncStarted = useRef(false);
166
+ const missingStateRetryError = useRef<ErrorContext | null>(null);
147
167
 
148
168
  // Reset on mount, cleanup on unmount
149
169
  useEffect(() => {
@@ -175,6 +195,12 @@ export function useAuthCallback(
175
195
 
176
196
  // Handle OIDC errors
177
197
  if (oidcError) {
198
+ if (oidcError === missingStateRetryError.current) return;
199
+ if (claimMissingStateRetry(oidcError)) {
200
+ missingStateRetryError.current = oidcError;
201
+ void signinRedirect();
202
+ return;
203
+ }
178
204
  setStatus("error");
179
205
  setError(oidcError.message || "Authentication failed");
180
206
  return;
@@ -187,11 +213,7 @@ export function useAuthCallback(
187
213
  }
188
214
 
189
215
  // OIDC is done loading and authenticated - move to waiting for backend
190
- if (
191
- !isAuthLoading &&
192
- isOidcAuthenticated &&
193
- status === "processing-oauth"
194
- ) {
216
+ if (!isAuthLoading && isOidcAuthenticated && status === "processing-oauth") {
195
217
  setStatus("waiting-backend");
196
218
  return;
197
219
  }
@@ -217,7 +239,7 @@ export function useAuthCallback(
217
239
  }
218
240
 
219
241
  return;
220
- }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);
242
+ }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams, signinRedirect]);
221
243
 
222
244
  // Sync with backend once backend is authenticated
223
245
  useEffect(() => {
@@ -1,26 +1,18 @@
1
1
  "use client";
2
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";
3
+ export const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
4
+ export const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
7
5
 
8
6
  export type StoredHerculesImpersonation = {
9
7
  sessionId: string;
10
8
  startedAt: string;
11
9
  };
12
10
 
13
- export function getHerculesImpersonationStorageKey(
14
- authority: string,
15
- clientId: string,
16
- ) {
11
+ export function getHerculesImpersonationStorageKey(authority: string, clientId: string) {
17
12
  return `hercules.impersonation.${authority}.${clientId}`;
18
13
  }
19
14
 
20
- export function rememberHerculesImpersonationSession(
21
- storageKey: string,
22
- sessionId: string,
23
- ) {
15
+ export function rememberHerculesImpersonationSession(storageKey: string, sessionId: string) {
24
16
  if (typeof window === "undefined") return;
25
17
  window.localStorage.setItem(
26
18
  storageKey,
@@ -8,10 +8,7 @@ import {
8
8
 
9
9
  configure({ reactStrictMode: true });
10
10
 
11
- const storageKey = getHerculesImpersonationStorageKey(
12
- "https://auth.example.com",
13
- "client_1",
14
- );
11
+ const storageKey = getHerculesImpersonationStorageKey("https://auth.example.com", "client_1");
15
12
  const mockSignoutRedirect = vi.fn();
16
13
  const mockRemoveUser = vi.fn();
17
14
  const mockGetEndSessionEndpoint = vi.fn();