@usehercules/auth 1.2.0 → 1.2.2
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 +1 -8
- package/dist/convex-react/index.d.mts.map +1 -1
- package/dist/convex-react/index.mjs +5 -6
- package/dist/convex-react/index.mjs.map +1 -1
- package/dist/react/index.d.mts +25 -45
- package/dist/react/index.d.mts.map +1 -1
- package/dist/react/index.mjs +168 -31
- package/dist/react/index.mjs.map +1 -1
- package/dist/{refresh-lock-Cv63qcNd.mjs → refresh-lock-RJUGj8im.mjs} +2 -3
- package/dist/{refresh-lock-Cv63qcNd.mjs.map → refresh-lock-RJUGj8im.mjs.map} +1 -1
- package/package.json +13 -13
- package/src/convex-react/ConvexProviderWithHercules.tsx +1 -2
- package/src/internal/user-manager.test.tsx +487 -0
- package/src/internal/user-manager.ts +70 -0
- package/src/react/HerculesAuthProvider.storage.test.tsx +66 -0
- package/src/react/HerculesAuthProvider.test.tsx +50 -1
- package/src/react/HerculesAuthProvider.tsx +94 -21
- package/src/react/auth-callback-hook.test.tsx +156 -0
- package/src/react/auth-callback-hook.tsx +38 -4
|
@@ -8,6 +8,8 @@ const mockSigninSilent = vi.fn();
|
|
|
8
8
|
const mockSigninRedirect = vi.fn();
|
|
9
9
|
const mockRemoveUser = vi.fn();
|
|
10
10
|
let mockAuthState: Record<string, unknown> = {};
|
|
11
|
+
// Managers whose silent renewal is running, as oidc-client-ts tracks it.
|
|
12
|
+
const renewingManagers = new Set<{ settings: { automaticSilentRenew?: boolean } }>();
|
|
11
13
|
const localStorageMock = createMemoryStorage();
|
|
12
14
|
|
|
13
15
|
Object.defineProperty(window, "localStorage", {
|
|
@@ -22,7 +24,17 @@ vi.mock("react-oidc-context", () => ({
|
|
|
22
24
|
|
|
23
25
|
vi.mock("oidc-client-ts", () => ({
|
|
24
26
|
UserManager: class {
|
|
25
|
-
|
|
27
|
+
settings: { automaticSilentRenew?: boolean };
|
|
28
|
+
constructor(settings: { automaticSilentRenew?: boolean }) {
|
|
29
|
+
this.settings = { ...settings };
|
|
30
|
+
if (settings.automaticSilentRenew) renewingManagers.add(this);
|
|
31
|
+
}
|
|
32
|
+
startSilentRenew() {
|
|
33
|
+
renewingManagers.add(this);
|
|
34
|
+
}
|
|
35
|
+
stopSilentRenew() {
|
|
36
|
+
renewingManagers.delete(this);
|
|
37
|
+
}
|
|
26
38
|
events = {
|
|
27
39
|
addAccessTokenExpiring: vi.fn(),
|
|
28
40
|
removeAccessTokenExpiring: vi.fn(),
|
|
@@ -55,6 +67,7 @@ beforeEach(() => {
|
|
|
55
67
|
mockSigninSilent.mockReset();
|
|
56
68
|
mockSigninRedirect.mockReset();
|
|
57
69
|
mockRemoveUser.mockReset();
|
|
70
|
+
renewingManagers.clear();
|
|
58
71
|
});
|
|
59
72
|
|
|
60
73
|
function renderProvider(
|
|
@@ -94,6 +107,27 @@ describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
|
|
|
94
107
|
);
|
|
95
108
|
expect(screen.getByTestId("app")).toBeDefined();
|
|
96
109
|
});
|
|
110
|
+
|
|
111
|
+
it("runs one silent renewal under Strict Mode and stops it on unmount", () => {
|
|
112
|
+
configure({ reactStrictMode: true });
|
|
113
|
+
try {
|
|
114
|
+
const { unmount } = render(
|
|
115
|
+
<HerculesAuthProvider
|
|
116
|
+
authority="https://auth.example.com"
|
|
117
|
+
client_id="test-client"
|
|
118
|
+
userManagerSettings={{ automaticSilentRenew: true }}
|
|
119
|
+
>
|
|
120
|
+
<div data-testid="app">app</div>
|
|
121
|
+
</HerculesAuthProvider>,
|
|
122
|
+
);
|
|
123
|
+
expect(renewingManagers.size).toBe(1);
|
|
124
|
+
expect([...renewingManagers][0]?.settings.automaticSilentRenew).toBe(true);
|
|
125
|
+
unmount();
|
|
126
|
+
expect(renewingManagers.size).toBe(0);
|
|
127
|
+
} finally {
|
|
128
|
+
configure({ reactStrictMode: false });
|
|
129
|
+
}
|
|
130
|
+
});
|
|
97
131
|
});
|
|
98
132
|
|
|
99
133
|
function createMemoryStorage(): Storage {
|
|
@@ -291,6 +325,21 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
|
|
|
291
325
|
});
|
|
292
326
|
});
|
|
293
327
|
|
|
328
|
+
it("renders an accessible default loading status when no loadingFallback is passed", () => {
|
|
329
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
330
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
331
|
+
renderProvider();
|
|
332
|
+
expect(screen.getByRole("status", { name: "Loading" })).toBeDefined();
|
|
333
|
+
expect(screen.queryByTestId("app")).toBeNull();
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
it("renders nothing during recovery when loadingFallback is null", () => {
|
|
337
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
338
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
339
|
+
const { container } = renderProvider(null);
|
|
340
|
+
expect(container.innerHTML).toBe("");
|
|
341
|
+
});
|
|
342
|
+
|
|
294
343
|
it("renders children after the recovery times out", async () => {
|
|
295
344
|
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
296
345
|
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
@@ -6,8 +6,14 @@ import {
|
|
|
6
6
|
type AuthProviderUserManagerProps,
|
|
7
7
|
useAuth,
|
|
8
8
|
} from "react-oidc-context";
|
|
9
|
-
import {
|
|
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 =
|
|
188
|
+
loadingFallback = <DefaultLoadingFallback />,
|
|
125
189
|
...props
|
|
126
190
|
}: HerculesAuthProviderProps) {
|
|
127
191
|
const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
|
|
@@ -129,25 +193,31 @@ export function HerculesAuthProvider({
|
|
|
129
193
|
const effectiveAuthority = userManagerSettings?.authority ?? authority;
|
|
130
194
|
const effectiveClientId = userManagerSettings?.client_id ?? client_id;
|
|
131
195
|
|
|
196
|
+
const userManager = new HerculesUserManager({
|
|
197
|
+
...userManagerSettings,
|
|
198
|
+
authority: effectiveAuthority,
|
|
199
|
+
client_id: effectiveClientId,
|
|
200
|
+
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
201
|
+
response_type: userManagerSettings?.response_type ?? "code",
|
|
202
|
+
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
203
|
+
redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
204
|
+
post_logout_redirect_uri:
|
|
205
|
+
userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
206
|
+
userStore:
|
|
207
|
+
userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
|
|
208
|
+
stateStore:
|
|
209
|
+
userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
|
|
210
|
+
// Started in the effect below, so a manager that React creates and
|
|
211
|
+
// discards (Strict Mode runs this initializer twice) never renews.
|
|
212
|
+
automaticSilentRenew: false,
|
|
213
|
+
silentRequestTimeoutInSeconds:
|
|
214
|
+
userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
|
|
215
|
+
});
|
|
216
|
+
// Only the constructor reads this, so report the caller's value afterward.
|
|
217
|
+
Object.assign(userManager.settings, { automaticSilentRenew: automaticSilentRenewExplicit });
|
|
218
|
+
|
|
132
219
|
return {
|
|
133
|
-
userManager
|
|
134
|
-
...userManagerSettings,
|
|
135
|
-
authority: effectiveAuthority,
|
|
136
|
-
client_id: effectiveClientId,
|
|
137
|
-
prompt: userManagerSettings?.prompt ?? "select_account",
|
|
138
|
-
response_type: userManagerSettings?.response_type ?? "code",
|
|
139
|
-
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
140
|
-
redirect_uri:
|
|
141
|
-
userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
142
|
-
post_logout_redirect_uri:
|
|
143
|
-
userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
144
|
-
userStore:
|
|
145
|
-
userManagerSettings?.userStore ??
|
|
146
|
-
new WebStorageStateStore({ store: window.localStorage }),
|
|
147
|
-
automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
|
|
148
|
-
silentRequestTimeoutInSeconds:
|
|
149
|
-
userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
|
|
150
|
-
}),
|
|
220
|
+
userManager,
|
|
151
221
|
impersonationStorageKey: getHerculesImpersonationStorageKey(
|
|
152
222
|
effectiveAuthority,
|
|
153
223
|
effectiveClientId,
|
|
@@ -156,7 +226,10 @@ export function HerculesAuthProvider({
|
|
|
156
226
|
});
|
|
157
227
|
|
|
158
228
|
useEffect(() => {
|
|
159
|
-
if (automaticSilentRenewExplicit)
|
|
229
|
+
if (automaticSilentRenewExplicit) {
|
|
230
|
+
userManager.startSilentRenew();
|
|
231
|
+
return () => userManager.stopSilentRenew();
|
|
232
|
+
}
|
|
160
233
|
let retryTimerId: ReturnType<typeof setTimeout> | null = null;
|
|
161
234
|
let timeoutRetryCount = 0;
|
|
162
235
|
let stopped = false;
|
|
@@ -137,6 +137,90 @@ describe("useAuthCallback", () => {
|
|
|
137
137
|
}
|
|
138
138
|
});
|
|
139
139
|
|
|
140
|
+
it("keeps waiting when the backend confirms the saved tokens after 30 seconds", async () => {
|
|
141
|
+
vi.useFakeTimers();
|
|
142
|
+
|
|
143
|
+
try {
|
|
144
|
+
const onSync = vi.fn().mockResolvedValue(undefined);
|
|
145
|
+
setAuthState({ isLoading: false, isAuthenticated: true });
|
|
146
|
+
|
|
147
|
+
const { result, rerender } = renderHook(
|
|
148
|
+
({ backendAuth }: { backendAuth: boolean }) =>
|
|
149
|
+
useAuthCallback({ isBackendAuthenticated: backendAuth, onSync, timeoutMs: 5000 }),
|
|
150
|
+
{ initialProps: { backendAuth: false } },
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
act(() => {
|
|
154
|
+
vi.advanceTimersByTime(30_000);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
expect(result.current.status).toBe("waiting-backend");
|
|
158
|
+
|
|
159
|
+
rerender({ backendAuth: true });
|
|
160
|
+
await act(async () => {
|
|
161
|
+
await vi.advanceTimersByTimeAsync(0);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
expect(result.current.status).toBe("success");
|
|
165
|
+
} finally {
|
|
166
|
+
vi.useRealTimers();
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("still times out when the backend never confirms the saved tokens", () => {
|
|
171
|
+
vi.useFakeTimers();
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
setAuthState({ isLoading: false, isAuthenticated: true });
|
|
175
|
+
|
|
176
|
+
const { result } = renderHook(() =>
|
|
177
|
+
useAuthCallback({ isBackendAuthenticated: false, timeoutMs: 5000 }),
|
|
178
|
+
);
|
|
179
|
+
|
|
180
|
+
act(() => {
|
|
181
|
+
vi.advanceTimersByTime(59_999);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
expect(result.current.status).toBe("waiting-backend");
|
|
185
|
+
|
|
186
|
+
act(() => {
|
|
187
|
+
vi.advanceTimersByTime(1);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
expect(result.current.status).toBe("error");
|
|
191
|
+
expect(result.current.error).toBe("Authentication timed out. Please try again.");
|
|
192
|
+
} finally {
|
|
193
|
+
vi.useRealTimers();
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("does not show a timeout while a sync takes 30 seconds", async () => {
|
|
198
|
+
vi.useFakeTimers();
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const onSync = vi.fn(() => new Promise<void>((resolve) => setTimeout(resolve, 30_000)));
|
|
202
|
+
setAuthState({ isLoading: false, isAuthenticated: true });
|
|
203
|
+
|
|
204
|
+
const { result } = renderHook(() =>
|
|
205
|
+
useAuthCallback({ isBackendAuthenticated: true, onSync, timeoutMs: 5000 }),
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
await act(async () => {
|
|
209
|
+
await vi.advanceTimersByTimeAsync(29_999);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
expect(result.current.status).toBe("syncing");
|
|
213
|
+
|
|
214
|
+
await act(async () => {
|
|
215
|
+
await vi.advanceTimersByTimeAsync(1);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
expect(result.current.status).toBe("success");
|
|
219
|
+
} finally {
|
|
220
|
+
vi.useRealTimers();
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
|
|
140
224
|
it("does not timeout after reaching success", async () => {
|
|
141
225
|
vi.useFakeTimers();
|
|
142
226
|
|
|
@@ -183,6 +267,78 @@ describe("useAuthCallback", () => {
|
|
|
183
267
|
});
|
|
184
268
|
});
|
|
185
269
|
|
|
270
|
+
describe("missing OIDC state", () => {
|
|
271
|
+
const missingStateError = () =>
|
|
272
|
+
Object.assign(new Error("No matching state found in storage"), {
|
|
273
|
+
source: "signinCallback",
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
beforeEach(() => {
|
|
277
|
+
window.sessionStorage.clear();
|
|
278
|
+
window.history.replaceState({}, "", "/auth/callback?code=orphan&state=dead");
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
it("strips the orphaned code and restarts sign-in once", () => {
|
|
282
|
+
setAuthState({ isLoading: false, error: missingStateError() });
|
|
283
|
+
|
|
284
|
+
const { result } = renderHook(() => useAuthCallback());
|
|
285
|
+
|
|
286
|
+
expect(mockSigninRedirect).toHaveBeenCalledOnce();
|
|
287
|
+
expect(window.location.search).toBe("");
|
|
288
|
+
expect(window.sessionStorage.getItem("hercules-auth:missing-state-retry")).toBe("1");
|
|
289
|
+
expect(result.current.status).toBe("processing-oauth");
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it("shows the error when the restarted sign-in also misses state", () => {
|
|
293
|
+
window.sessionStorage.setItem("hercules-auth:missing-state-retry", "1");
|
|
294
|
+
setAuthState({ isLoading: false, error: missingStateError() });
|
|
295
|
+
|
|
296
|
+
const { result } = renderHook(() => useAuthCallback());
|
|
297
|
+
|
|
298
|
+
expect(mockSigninRedirect).not.toHaveBeenCalled();
|
|
299
|
+
expect(result.current.status).toBe("error");
|
|
300
|
+
expect(result.current.error).toBe("No matching state found in storage");
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
it("shows the error when the restarted sign-in fails to start", () => {
|
|
304
|
+
setAuthState({ isLoading: false, error: missingStateError() });
|
|
305
|
+
|
|
306
|
+
const { result, rerender } = renderHook(() => useAuthCallback());
|
|
307
|
+
|
|
308
|
+
setAuthState({
|
|
309
|
+
error: Object.assign(new Error("Network down"), { source: "signinRedirect" }),
|
|
310
|
+
});
|
|
311
|
+
rerender();
|
|
312
|
+
|
|
313
|
+
expect(mockSigninRedirect).toHaveBeenCalledOnce();
|
|
314
|
+
expect(result.current.status).toBe("error");
|
|
315
|
+
expect(result.current.error).toBe("Network down");
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it("does not restart sign-in without an authorization code", () => {
|
|
319
|
+
window.history.replaceState({}, "", "/auth/callback?error=access_denied&state=dead");
|
|
320
|
+
setAuthState({ isLoading: false, error: missingStateError() });
|
|
321
|
+
|
|
322
|
+
const { result } = renderHook(() => useAuthCallback());
|
|
323
|
+
|
|
324
|
+
expect(mockSigninRedirect).not.toHaveBeenCalled();
|
|
325
|
+
expect(result.current.status).toBe("error");
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
it("does not restart sign-in for other callback errors", () => {
|
|
329
|
+
setAuthState({
|
|
330
|
+
isLoading: false,
|
|
331
|
+
error: Object.assign(new Error("invalid_grant"), { source: "signinCallback" }),
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
const { result } = renderHook(() => useAuthCallback());
|
|
335
|
+
|
|
336
|
+
expect(mockSigninRedirect).not.toHaveBeenCalled();
|
|
337
|
+
expect(result.current.status).toBe("error");
|
|
338
|
+
expect(window.location.search).toBe("?code=orphan&state=dead");
|
|
339
|
+
});
|
|
340
|
+
});
|
|
341
|
+
|
|
186
342
|
describe("no auth params", () => {
|
|
187
343
|
it("calls onNoAuthParams when no auth params and not authenticated", () => {
|
|
188
344
|
mockHasAuthParams = false;
|
|
@@ -1,16 +1,40 @@
|
|
|
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
|
+
// Once the tokens are saved, the backend confirming them (such as a Convex
|
|
10
|
+
// WebSocket on Safari) can take longer than the token exchange.
|
|
11
|
+
const MIN_TIMEOUT_AFTER_TOKENS_MS = 60_000;
|
|
12
|
+
const MISSING_STATE_MESSAGE = "No matching state found in storage";
|
|
13
|
+
const MISSING_STATE_RETRY_KEY = "hercules-auth:missing-state-retry";
|
|
9
14
|
|
|
10
15
|
const convexErrorSchema = z.object({
|
|
11
16
|
message: z.string(),
|
|
12
17
|
});
|
|
13
18
|
|
|
19
|
+
function claimMissingStateRetry(error: ErrorContext): boolean {
|
|
20
|
+
if (error.source !== "signinCallback" || error.message !== MISSING_STATE_MESSAGE) return false;
|
|
21
|
+
|
|
22
|
+
const url = new URL(window.location.href);
|
|
23
|
+
if (!url.searchParams.has("code")) return false;
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
if (window.sessionStorage.getItem(MISSING_STATE_RETRY_KEY) !== null) return false;
|
|
27
|
+
window.sessionStorage.setItem(MISSING_STATE_RETRY_KEY, "1");
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
url.searchParams.delete("code");
|
|
33
|
+
url.searchParams.delete("state");
|
|
34
|
+
window.history.replaceState({}, document.title, url.toString());
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
|
|
14
38
|
/**
|
|
15
39
|
* Authentication callback status states
|
|
16
40
|
* @public
|
|
@@ -28,7 +52,8 @@ export type AuthCallbackStatus =
|
|
|
28
52
|
*/
|
|
29
53
|
export interface UseAuthCallbackOptions {
|
|
30
54
|
/**
|
|
31
|
-
* Timeout in milliseconds
|
|
55
|
+
* Timeout in milliseconds for each step of the callback. Once the tokens are
|
|
56
|
+
* saved, the backend and sync steps each get at least 60 seconds.
|
|
32
57
|
* @default 20000
|
|
33
58
|
*/
|
|
34
59
|
timeoutMs?: number;
|
|
@@ -142,6 +167,7 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
|
|
|
142
167
|
const hadAuthParams = useRef(hasAuthParams());
|
|
143
168
|
// Track if we've already started sync to prevent double execution
|
|
144
169
|
const syncStarted = useRef(false);
|
|
170
|
+
const missingStateRetryError = useRef<ErrorContext | null>(null);
|
|
145
171
|
|
|
146
172
|
// Reset on mount, cleanup on unmount
|
|
147
173
|
useEffect(() => {
|
|
@@ -156,12 +182,14 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
|
|
|
156
182
|
useEffect(() => {
|
|
157
183
|
if (status === "success" || status === "error") return;
|
|
158
184
|
|
|
185
|
+
const stepTimeoutMs =
|
|
186
|
+
status === "processing-oauth" ? timeoutMs : Math.max(timeoutMs, MIN_TIMEOUT_AFTER_TOKENS_MS);
|
|
159
187
|
const timeout = setTimeout(() => {
|
|
160
188
|
if (mountedRef.current) {
|
|
161
189
|
setStatus("error");
|
|
162
190
|
setError("Authentication timed out. Please try again.");
|
|
163
191
|
}
|
|
164
|
-
},
|
|
192
|
+
}, stepTimeoutMs);
|
|
165
193
|
|
|
166
194
|
return () => clearTimeout(timeout);
|
|
167
195
|
}, [status, timeoutMs]);
|
|
@@ -173,6 +201,12 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
|
|
|
173
201
|
|
|
174
202
|
// Handle OIDC errors
|
|
175
203
|
if (oidcError) {
|
|
204
|
+
if (oidcError === missingStateRetryError.current) return;
|
|
205
|
+
if (claimMissingStateRetry(oidcError)) {
|
|
206
|
+
missingStateRetryError.current = oidcError;
|
|
207
|
+
void signinRedirect();
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
176
210
|
setStatus("error");
|
|
177
211
|
setError(oidcError.message || "Authentication failed");
|
|
178
212
|
return;
|
|
@@ -211,7 +245,7 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
|
|
|
211
245
|
}
|
|
212
246
|
|
|
213
247
|
return;
|
|
214
|
-
}, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);
|
|
248
|
+
}, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams, signinRedirect]);
|
|
215
249
|
|
|
216
250
|
// Sync with backend once backend is authenticated
|
|
217
251
|
useEffect(() => {
|