@usehercules/auth 1.2.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.
@@ -6,8 +6,14 @@ import {
6
6
  type AuthProviderUserManagerProps,
7
7
  useAuth,
8
8
  } from "react-oidc-context";
9
- import { UserManager, WebStorageStateStore, type UserManagerSettings } from "oidc-client-ts";
9
+ import {
10
+ InMemoryWebStorage,
11
+ WebStorageStateStore,
12
+ type UserManager,
13
+ type UserManagerSettings,
14
+ } from "oidc-client-ts";
10
15
  import { withRefreshLock } from "../internal/refresh-lock";
16
+ import { HerculesUserManager } from "../internal/user-manager";
11
17
  import {
12
18
  clearHerculesImpersonationParamsFromUrl,
13
19
  getHerculesImpersonationStorageKey,
@@ -54,6 +60,64 @@ export function useHerculesAuthProvider() {
54
60
  return context;
55
61
  }
56
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
+
57
121
  function AuthRecoveryGate({
58
122
  children,
59
123
  loadingFallback,
@@ -121,7 +185,7 @@ export function HerculesAuthProvider({
121
185
  userManagerSettings,
122
186
  authority,
123
187
  client_id,
124
- loadingFallback = null,
188
+ loadingFallback = <DefaultLoadingFallback />,
125
189
  ...props
126
190
  }: HerculesAuthProviderProps) {
127
191
  const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
@@ -130,7 +194,7 @@ export function HerculesAuthProvider({
130
194
  const effectiveClientId = userManagerSettings?.client_id ?? client_id;
131
195
 
132
196
  return {
133
- userManager: new UserManager({
197
+ userManager: new HerculesUserManager({
134
198
  ...userManagerSettings,
135
199
  authority: effectiveAuthority,
136
200
  client_id: effectiveClientId,
@@ -142,8 +206,9 @@ export function HerculesAuthProvider({
142
206
  post_logout_redirect_uri:
143
207
  userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
144
208
  userStore:
145
- userManagerSettings?.userStore ??
146
- new WebStorageStateStore({ store: window.localStorage }),
209
+ userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
210
+ stateStore:
211
+ userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
147
212
  automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
148
213
  silentRequestTimeoutInSeconds:
149
214
  userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
@@ -183,6 +183,78 @@ describe("useAuthCallback", () => {
183
183
  });
184
184
  });
185
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
+
186
258
  describe("no auth params", () => {
187
259
  it("calls onNoAuthParams when no auth params and not authenticated", () => {
188
260
  mockHasAuthParams = false;
@@ -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
@@ -142,6 +163,7 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
142
163
  const hadAuthParams = useRef(hasAuthParams());
143
164
  // Track if we've already started sync to prevent double execution
144
165
  const syncStarted = useRef(false);
166
+ const missingStateRetryError = useRef<ErrorContext | null>(null);
145
167
 
146
168
  // Reset on mount, cleanup on unmount
147
169
  useEffect(() => {
@@ -173,6 +195,12 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
173
195
 
174
196
  // Handle OIDC errors
175
197
  if (oidcError) {
198
+ if (oidcError === missingStateRetryError.current) return;
199
+ if (claimMissingStateRetry(oidcError)) {
200
+ missingStateRetryError.current = oidcError;
201
+ void signinRedirect();
202
+ return;
203
+ }
176
204
  setStatus("error");
177
205
  setError(oidcError.message || "Authentication failed");
178
206
  return;
@@ -211,7 +239,7 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
211
239
  }
212
240
 
213
241
  return;
214
- }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);
242
+ }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams, signinRedirect]);
215
243
 
216
244
  // Sync with backend once backend is authenticated
217
245
  useEffect(() => {