@usehercules/auth 1.0.44 → 1.0.46
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 +13 -33
- package/dist/convex-react/index.mjs.map +1 -1
- package/dist/react/index.d.mts +3 -0
- package/dist/react/index.d.mts.map +1 -1
- package/dist/react/index.mjs +84 -4
- 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 +4 -4
- package/src/convex-react/ConvexProviderWithHercules.test.tsx +80 -0
- package/src/convex-react/ConvexProviderWithHercules.tsx +18 -62
- package/src/internal/refresh-lock.ts +50 -0
- package/src/react/HerculesAuthProvider.test.tsx +289 -0
- package/src/react/HerculesAuthProvider.tsx +128 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":[],"mappings":";;;;;iBA2FgB,8BAAA;;;AAAhB;YAIY;UACF;AALV,CAAA,CAAA,EAMC,kBAAA,CAAA,GAAA,CAAA,OAN6C"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t as withRefreshLock } from "../refresh-lock-DYW9ITwj.mjs";
|
|
1
2
|
import { useCallback, useMemo, useRef } from "react";
|
|
2
3
|
import { useAuth } from "react-oidc-context";
|
|
3
4
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -6,7 +7,6 @@ import { jwtDecode } from "jwt-decode";
|
|
|
6
7
|
|
|
7
8
|
//#region src/convex-react/ConvexProviderWithHercules.tsx
|
|
8
9
|
const REFRESH_THRESHOLD_MS = 3600 * 1e3;
|
|
9
|
-
const LOCK_KEY = "__herculesAuthRefresh";
|
|
10
10
|
function tokenExpiresWithin(token, ms) {
|
|
11
11
|
try {
|
|
12
12
|
return jwtDecode(token).exp * 1e3 - Date.now() < ms;
|
|
@@ -14,46 +14,26 @@ function tokenExpiresWithin(token, ms) {
|
|
|
14
14
|
return true;
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
|
-
async function withLock(key, callback) {
|
|
18
|
-
if (typeof navigator !== "undefined" && navigator.locks) return navigator.locks.request(key, callback);
|
|
19
|
-
return manualMutex(key, callback);
|
|
20
|
-
}
|
|
21
|
-
const mutexes = /* @__PURE__ */ new Map();
|
|
22
|
-
async function manualMutex(key, callback) {
|
|
23
|
-
return new Promise((resolve, reject) => {
|
|
24
|
-
const wrapped = () => callback().then(resolve).catch(reject).finally(() => {
|
|
25
|
-
const mutex$1 = mutexes.get(key);
|
|
26
|
-
const next = mutex$1.waiting.shift();
|
|
27
|
-
if (next) mutex$1.running = next();
|
|
28
|
-
else mutex$1.running = null;
|
|
29
|
-
});
|
|
30
|
-
let mutex = mutexes.get(key);
|
|
31
|
-
if (!mutex) {
|
|
32
|
-
mutex = {
|
|
33
|
-
running: null,
|
|
34
|
-
waiting: []
|
|
35
|
-
};
|
|
36
|
-
mutexes.set(key, mutex);
|
|
37
|
-
}
|
|
38
|
-
if (mutex.running === null) mutex.running = wrapped();
|
|
39
|
-
else mutex.waiting.push(wrapped);
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
17
|
function useUseAuthFromHercules() {
|
|
43
18
|
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
44
19
|
const idToken = user?.id_token;
|
|
20
|
+
const issuer = user?.profile?.iss;
|
|
21
|
+
const subject = user?.profile?.sub;
|
|
45
22
|
const idTokenRef = useRef(idToken);
|
|
46
23
|
idTokenRef.current = idToken;
|
|
24
|
+
const signinSilentRef = useRef(signinSilent);
|
|
25
|
+
signinSilentRef.current = signinSilent;
|
|
47
26
|
const inFlightRefresh = useRef(null);
|
|
48
27
|
const fetchAccessToken = useCallback(async ({ forceRefreshToken }) => {
|
|
49
|
-
|
|
50
|
-
if (
|
|
28
|
+
const currentToken = idTokenRef.current;
|
|
29
|
+
if (!forceRefreshToken) return currentToken ?? null;
|
|
30
|
+
if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) return currentToken;
|
|
51
31
|
if (inFlightRefresh.current) return inFlightRefresh.current;
|
|
52
|
-
const refresh =
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
32
|
+
const refresh = withRefreshLock(async () => {
|
|
33
|
+
const tokenAfterLock = idTokenRef.current;
|
|
34
|
+
if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) return tokenAfterLock;
|
|
55
35
|
try {
|
|
56
|
-
return (await
|
|
36
|
+
return (await signinSilentRef.current())?.id_token ?? null;
|
|
57
37
|
} catch {
|
|
58
38
|
return null;
|
|
59
39
|
}
|
|
@@ -62,7 +42,7 @@ function useUseAuthFromHercules() {
|
|
|
62
42
|
});
|
|
63
43
|
inFlightRefresh.current = refresh;
|
|
64
44
|
return refresh;
|
|
65
|
-
}, [
|
|
45
|
+
}, [issuer, subject]);
|
|
66
46
|
return useMemo(() => ({
|
|
67
47
|
isLoading: isAuthenticated ? false : isLoading,
|
|
68
48
|
isAuthenticated,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport { ConvexProviderWithAuth, type ConvexReactClient } from \"convex/react\";\nimport { jwtDecode } from \"jwt-decode\";\nimport { useCallback, useMemo, useRef } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\nimport type { HerculesAuthProvider } from \"../react/HerculesAuthProvider\";\n\nconst REFRESH_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour\n\nfunction tokenExpiresWithin(token: string, ms: number): boolean {\n try {\n const payload = jwtDecode(token);\n return payload.exp! * 1000 - Date.now() < ms;\n } catch {\n return true;\n }\n}\n\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n const issuer = user?.profile?.iss;\n const subject = user?.profile?.sub;\n\n const idTokenRef = useRef(idToken);\n idTokenRef.current = idToken;\n\n const signinSilentRef = useRef(signinSilent);\n signinSilentRef.current = signinSilent;\n\n const inFlightRefresh = useRef<Promise<string | null> | null>(null);\n\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {\n const currentToken = idTokenRef.current;\n if (!forceRefreshToken) {\n return currentToken ?? null;\n }\n if (\n currentToken != null &&\n !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)\n ) {\n return currentToken;\n }\n if (inFlightRefresh.current) {\n return inFlightRefresh.current;\n }\n const refresh = withRefreshLock(async () => {\n const tokenAfterLock = idTokenRef.current;\n if (\n tokenAfterLock != null &&\n !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)\n ) {\n return tokenAfterLock;\n }\n try {\n const refreshed = await signinSilentRef.current();\n return refreshed?.id_token ?? null;\n } catch {\n return null;\n }\n }).finally(() => {\n inFlightRefresh.current = null;\n });\n inFlightRefresh.current = refresh;\n return refresh;\n },\n [issuer, subject],\n );\n\n return useMemo(\n () => ({\n isLoading: isAuthenticated ? false : isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n\n/**\n * A wrapper React component which provides a {@link ConvexReactClient}\n * authenticated with Hercules Auth.\n *\n * It must be wrapped by a configured `{@link HerculesAuthProvider}`.\n *\n * @public\n */\nexport function ConvexProviderWithHerculesAuth({\n children,\n client,\n}: {\n children: ReactNode;\n client: ConvexReactClient;\n}) {\n return (\n <ConvexProviderW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;EAA+B;EAAQ,SAAS;EAC9C;GACsB"}
|
package/dist/react/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as react0 from "react";
|
|
2
|
+
import { ReactNode } from "react";
|
|
2
3
|
import * as react_oidc_context0 from "react-oidc-context";
|
|
3
4
|
import { AuthContextProps as AuthContextProps$1, AuthProviderUserManagerProps, hasAuthParams } from "react-oidc-context";
|
|
4
5
|
import * as oidc_client_ts0 from "oidc-client-ts";
|
|
@@ -29,6 +30,7 @@ type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager
|
|
|
29
30
|
userManagerSettings?: Partial<UserManagerSettings>;
|
|
30
31
|
authority: string;
|
|
31
32
|
client_id: string;
|
|
33
|
+
loadingFallback?: ReactNode;
|
|
32
34
|
};
|
|
33
35
|
interface HerculesAuthProviderContext {
|
|
34
36
|
userManager: UserManager;
|
|
@@ -40,6 +42,7 @@ declare function HerculesAuthProvider({
|
|
|
40
42
|
userManagerSettings,
|
|
41
43
|
authority,
|
|
42
44
|
client_id,
|
|
45
|
+
loadingFallback,
|
|
43
46
|
...props
|
|
44
47
|
}: HerculesAuthProviderProps): react_jsx_runtime0.JSX.Element;
|
|
45
48
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":[],"mappings":";;;;;;;;;KAiBY,kBAAA;UAWK,sBAAA;;;iBAkBA;;;;UAoBA,qBAAA;EAjDL,MAAA,EAmDF,kBAnDoB;EAWb,KAAA,EAAA,MAAA,GAAA,IAAA;EAsCA,SAAA,EAAA,OAAA;EAqDD,SAAA,EAAA,OAAe;;eApChB;;AC1DH,iBD8FI,eAAA,CC9FqB,OAAA,CAAA,ED+F1B,sBC/F0B,CAAA,EDgGlC,qBChGkC;;;KAAzB,yBAAA,GAA4B,KACtC;wBAGsB,QAAQ;;;oBAGZ;;ADfpB,UC+BU,2BAAA,CD/BoB;EAWb,WAAA,ECqBF,WDrBE;AAsCjB;AAqDA,cCnEM,2BDoEK,ECpEsB,MAAA,CAAA,ODqE9B,CCrE8B,2BDqET,GAAA,IAAA,CAAA;iBClER,uBAAA,CAAA,GAAuB;iBAkEvB,oBAAA;;;;;;;GAOb,4BAAyB,kBAAA,CAAA,GAAA,CAAA;;;iBCtHZ,OAAA,CAAA;;;;;;;SAAO,mBAAA,CAAA,YAAA;;EFOX,aAAA,CAAA,EAAA,MAAkB,GAAA,IAAA,GAAA,SAAA;EAWb,YAAA,CAAA,EAAA,MAAA,GAAA,SAAsB;EAsCtB,aAAA,CAAA,EAAA,MAAA;EAqDD,UAAA,CAAA,EAAA,MAAe,GAAA,SACpB;;YE9GY,eAAA,CAAA,aAAA;;EDeX,KAAA,CAAA,EAAA,OAAA;EACV,SAAA,CAAA,EAAA,MAAA;CADsC;;;UElBvB,gBAAA,SAAyB;iBACzB;gBACD;;iBAGA,OAAA,CAAA,GAAW"}
|
package/dist/react/index.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { t as withRefreshLock } from "../refresh-lock-DYW9ITwj.mjs";
|
|
1
2
|
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
2
3
|
import { AuthProvider, hasAuthParams, hasAuthParams as hasAuthParams$1, useAuth as useAuth$1 } from "react-oidc-context";
|
|
3
4
|
import { ConvexError } from "convex/values";
|
|
4
5
|
import * as z from "zod";
|
|
5
6
|
import { UserManager, WebStorageStateStore } from "oidc-client-ts";
|
|
6
|
-
import { jsx } from "react/jsx-runtime";
|
|
7
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
7
8
|
|
|
8
9
|
//#region src/react/auth-callback-hook.tsx
|
|
9
10
|
const DEFAULT_TIMEOUT_MS = 2e4;
|
|
@@ -151,6 +152,8 @@ function useAuthCallback(options = {}) {
|
|
|
151
152
|
|
|
152
153
|
//#endregion
|
|
153
154
|
//#region src/react/HerculesAuthProvider.tsx
|
|
155
|
+
const RECOVERY_TIMEOUT_MS = 1e4;
|
|
156
|
+
const LOCK_GRACE_MS = 5e3;
|
|
154
157
|
function onSigninCallback() {
|
|
155
158
|
window.history.replaceState({}, document.title, window.location.pathname);
|
|
156
159
|
}
|
|
@@ -167,13 +170,43 @@ function useHerculesAuthProvider() {
|
|
|
167
170
|
if (!context) throw new Error("HerculesAuthProviderContext not found");
|
|
168
171
|
return context;
|
|
169
172
|
}
|
|
173
|
+
function AuthRecoveryGate({ children, loadingFallback }) {
|
|
174
|
+
const { user, isLoading, signinSilent } = useAuth$1();
|
|
175
|
+
const userExpired = user?.expired === true;
|
|
176
|
+
const hasAttempted = useRef(false);
|
|
177
|
+
const signinSilentRef = useRef(signinSilent);
|
|
178
|
+
signinSilentRef.current = signinSilent;
|
|
179
|
+
const [recoveryDone, setRecoveryDone] = useState(false);
|
|
180
|
+
const [recovering, setRecovering] = useState(false);
|
|
181
|
+
useEffect(() => {
|
|
182
|
+
if (isLoading) return;
|
|
183
|
+
if (hasAttempted.current) return;
|
|
184
|
+
hasAttempted.current = true;
|
|
185
|
+
if (!user || !userExpired) {
|
|
186
|
+
setRecoveryDone(true);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
setRecovering(true);
|
|
190
|
+
const finish = () => {
|
|
191
|
+
setRecovering(false);
|
|
192
|
+
setRecoveryDone(true);
|
|
193
|
+
};
|
|
194
|
+
setTimeout(finish, RECOVERY_TIMEOUT_MS);
|
|
195
|
+
withRefreshLock(async () => {
|
|
196
|
+
await Promise.race([signinSilentRef.current().catch(() => void 0), new Promise((resolve) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS))]);
|
|
197
|
+
}).finally(finish);
|
|
198
|
+
}, [isLoading, userExpired]);
|
|
199
|
+
if (recovering || !recoveryDone && !isLoading && userExpired) return /* @__PURE__ */ jsx(Fragment, { children: loadingFallback });
|
|
200
|
+
return /* @__PURE__ */ jsx(Fragment, { children });
|
|
201
|
+
}
|
|
170
202
|
/**
|
|
171
203
|
* A wrapper React component which provides a {@link ReactAuthProvider}
|
|
172
204
|
* configured with Hercules Auth.
|
|
173
205
|
*
|
|
174
206
|
* @public
|
|
175
207
|
*/
|
|
176
|
-
function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, ...props }) {
|
|
208
|
+
function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback = null, ...props }) {
|
|
209
|
+
const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
|
|
177
210
|
const [userManager] = useState(() => new UserManager({
|
|
178
211
|
...userManagerSettings,
|
|
179
212
|
authority: userManagerSettings?.authority ?? authority,
|
|
@@ -183,15 +216,62 @@ function HerculesAuthProvider({ children, userManagerSettings, authority, client
|
|
|
183
216
|
scope: userManagerSettings?.scope ?? "openid profile email offline_access",
|
|
184
217
|
redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
|
|
185
218
|
post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
|
|
186
|
-
userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: window.localStorage })
|
|
219
|
+
userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: window.localStorage }),
|
|
220
|
+
automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
|
|
221
|
+
silentRequestTimeoutInSeconds: userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1e3
|
|
187
222
|
}));
|
|
223
|
+
useEffect(() => {
|
|
224
|
+
if (automaticSilentRenewExplicit) return;
|
|
225
|
+
let retryTimerId = null;
|
|
226
|
+
let timeoutRetryCount = 0;
|
|
227
|
+
let stopped = false;
|
|
228
|
+
const events = userManager.events;
|
|
229
|
+
const tryRenew = () => {
|
|
230
|
+
if (stopped) return;
|
|
231
|
+
withRefreshLock(async () => {
|
|
232
|
+
if (stopped) return;
|
|
233
|
+
try {
|
|
234
|
+
await userManager.signinSilent();
|
|
235
|
+
timeoutRetryCount = 0;
|
|
236
|
+
} catch (err) {
|
|
237
|
+
if (stopped) return;
|
|
238
|
+
if (err instanceof Error && err.name === "ErrorTimeout") {
|
|
239
|
+
timeoutRetryCount++;
|
|
240
|
+
const maxRetries = userManager.settings.maxSilentRenewTimeoutRetries;
|
|
241
|
+
if (maxRetries !== void 0 && timeoutRetryCount > maxRetries) {
|
|
242
|
+
timeoutRetryCount = 0;
|
|
243
|
+
events._raiseSilentRenewError?.(err);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
retryTimerId = setTimeout(() => {
|
|
247
|
+
retryTimerId = null;
|
|
248
|
+
tryRenew();
|
|
249
|
+
}, 5e3);
|
|
250
|
+
} else {
|
|
251
|
+
timeoutRetryCount = 0;
|
|
252
|
+
events._raiseSilentRenewError?.(err);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
};
|
|
257
|
+
const onExpiring = () => tryRenew();
|
|
258
|
+
userManager.events.addAccessTokenExpiring(onExpiring);
|
|
259
|
+
return () => {
|
|
260
|
+
stopped = true;
|
|
261
|
+
userManager.events.removeAccessTokenExpiring(onExpiring);
|
|
262
|
+
if (retryTimerId !== null) clearTimeout(retryTimerId);
|
|
263
|
+
};
|
|
264
|
+
}, [userManager, automaticSilentRenewExplicit]);
|
|
188
265
|
return /* @__PURE__ */ jsx(HerculesAuthProviderContext.Provider, {
|
|
189
266
|
value: { userManager },
|
|
190
267
|
children: /* @__PURE__ */ jsx(AuthProvider, {
|
|
191
268
|
userManager,
|
|
192
269
|
...DEFAULT_AUTH_CONFIG,
|
|
193
270
|
...props,
|
|
194
|
-
children
|
|
271
|
+
children: /* @__PURE__ */ jsx(AuthRecoveryGate, {
|
|
272
|
+
loadingFallback,
|
|
273
|
+
children
|
|
274
|
+
})
|
|
195
275
|
})
|
|
196
276
|
});
|
|
197
277
|
}
|
package/dist/react/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps>","ReactAuthProvider","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(\n options: UseAuthCallbackOptions = {},\n): UseAuthCallbackResult {\n const {\n timeoutMs = DEFAULT_TIMEOUT_MS,\n isBackendAuthenticated = true,\n onSync,\n onSuccess,\n onNoAuthParams,\n } = options;\n\n const {\n isLoading: isAuthLoading,\n isAuthenticated: isOidcAuthenticated,\n error: oidcError,\n signinRedirect,\n } = useAuth();\n\n const [status, setStatus] = useState<AuthCallbackStatus>(\"processing-oauth\");\n const [error, setError] = useState<string | null>(null);\n\n // Track mount state to prevent state updates after unmount\n const mountedRef = useRef(true);\n // Track if we had auth params on mount (won't change during lifecycle)\n const hadAuthParams = useRef(hasAuthParams());\n // Track if we've already started sync to prevent double execution\n const syncStarted = useRef(false);\n\n // Reset on mount, cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n syncStarted.current = false;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (\n !isAuthLoading &&\n isOidcAuthenticated &&\n status === \"processing-oauth\"\n ) {\n setStatus(\"waiting-backend\");\n return;\n }\n\n // OIDC finished but not authenticated (and we had auth params)\n // Wait a bit before declaring failure to avoid race conditions\n if (\n hadAuthParams.current &&\n !isAuthLoading &&\n !isOidcAuthenticated &&\n !oidcError &&\n status === \"processing-oauth\"\n ) {\n // Use a small delay to avoid race condition during OIDC state transitions\n const failureTimeout = setTimeout(() => {\n if (mountedRef.current && !isOidcAuthenticated) {\n setStatus(\"error\");\n setError(\"Authentication was cancelled or failed. Please try again.\");\n }\n }, 500);\n\n return () => clearTimeout(failureTimeout);\n }\n\n return;\n }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n if (err instanceof ConvexError) {\n // try to extract the error message from the convex error\n const parseResult = convexErrorSchema.safeParse(err.data);\n if (parseResult.success) {\n setStatus(\"error\");\n setError(parseResult.data.message);\n return;\n }\n }\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error\n ? err.message\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\nimport { useState } from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { createContext, useContext } from \"react\";\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\ninterface HerculesAuthProviderContext {\n userManager: UserManager;\n}\n\nconst HerculesAuthProviderContext =\n createContext<HerculesAuthProviderContext | null>(null);\n\nexport function useHerculesAuthProvider() {\n const context = useContext(HerculesAuthProviderContext);\n if (!context) {\n throw new Error(\"HerculesAuthProviderContext not found\");\n }\n return context;\n}\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n ...props\n}: HerculesAuthProviderProps) {\n const [userManager] = useState(\n () =>\n new UserManager({\n ...userManagerSettings,\n authority: userManagerSettings?.authority ?? authority,\n client_id: userManagerSettings?.client_id ?? client_id,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n }),\n );\n\n return (\n <HerculesAuthProviderContext.Provider value={{ userManager }}>\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n {children}\n </ReactAuthProvider>\n </HerculesAuthProviderContext.Provider>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n","import {\n useAuth as useOidcAuth,\n type AuthContextProps as OidcAuthContextProps,\n} from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport { useCallback, useMemo } from \"react\";\n\nexport interface AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: () => Promise<void>;\n}\n\nexport function useAuth(): AuthContextProps {\n const { userManager } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n\n const { signoutRedirect, removeUser, signinRedirect } = auth;\n const signout = useCallback(async () => {\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await signoutRedirect();\n } else {\n await removeUser();\n }\n }, [userManager, signoutRedirect, removeUser]);\n\n const signin = useCallback(async () => {\n await signinRedirect();\n }, [signinRedirect]);\n\n return useMemo(() => {\n return {\n ...auth,\n signout,\n signin,\n } satisfies AuthContextProps;\n }, [auth, signout, signin]);\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,EAAE,OAAO,EACjC,SAAS,EAAE,QAAQ,EACpB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GF,SAAgB,gBACd,UAAkC,EAAE,EACb;CACvB,MAAM,EACJ,YAAY,oBACZ,yBAAyB,MACzB,QACA,WACA,mBACE;CAEJ,MAAM,EACJ,WAAW,eACX,iBAAiB,qBACjB,OAAO,WACP,mBACEA,WAAS;CAEb,MAAM,CAAC,QAAQ,aAAa,SAA6B,mBAAmB;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAwB,KAAK;CAGvD,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,gBAAgB,OAAOC,iBAAe,CAAC;CAE7C,MAAM,cAAc,OAAO,MAAM;AAGjC,iBAAgB;AACd,aAAW,UAAU;AACrB,cAAY,UAAU;AACtB,eAAa;AACX,cAAW,UAAU;;IAEtB,EAAE,CAAC;AAGN,iBAAgB;AACd,MAAI,WAAW,aAAa,WAAW,QAAS;EAEhD,MAAM,UAAU,iBAAiB;AAC/B,OAAI,WAAW,SAAS;AACtB,cAAU,QAAQ;AAClB,aAAS,8CAA8C;;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AAM,EAAE,MAAM,WAAW,OAAO,oBAAoBC,WAAS;AAE7D,QAAO,cAAc;EACnB,MAAM,KAAK,MAAM,QAAQ;EACzB,MAAM,OAAO,MAAM,QAAQ;EAC3B,MAAM,QAAQ,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,QAAQ;AAC7B,SAAO;GACL,GAAI,QAAQ,EAAE;GACd;GACA;GACA;GACA;GACA;GACA;GACA;GACD;IACA;EAAC;EAAM;EAAiB;EAAW;EAAM,CAAC;;;;;AChB/C,SAAgB,UAA4B;CAC1C,MAAM,EAAE,gBAAgB,yBAAyB;CACjD,MAAM,OAAOC,WAAa;CAE1B,MAAM,EAAE,iBAAiB,YAAY,mBAAmB;CACxD,MAAM,UAAU,YAAY,YAAY;AAEtC,MADiB,MAAM,YAAY,gBAAgB,uBAAuB,IAC1D,KACd,OAAM,iBAAiB;MAEvB,OAAM,YAAY;IAEnB;EAAC;EAAa;EAAiB;EAAW,CAAC;CAE9C,MAAM,SAAS,YAAY,YAAY;AACrC,QAAM,gBAAgB;IACrB,CAAC,eAAe,CAAC;AAEpB,QAAO,cAAc;AACnB,SAAO;GACL,GAAG;GACH;GACA;GACD;IACA;EAAC;EAAM;EAAS;EAAO,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps>","useAuth","retryTimerId: ReturnType<typeof setTimeout> | null","ReactAuthProvider","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(\n options: UseAuthCallbackOptions = {},\n): UseAuthCallbackResult {\n const {\n timeoutMs = DEFAULT_TIMEOUT_MS,\n isBackendAuthenticated = true,\n onSync,\n onSuccess,\n onNoAuthParams,\n } = options;\n\n const {\n isLoading: isAuthLoading,\n isAuthenticated: isOidcAuthenticated,\n error: oidcError,\n signinRedirect,\n } = useAuth();\n\n const [status, setStatus] = useState<AuthCallbackStatus>(\"processing-oauth\");\n const [error, setError] = useState<string | null>(null);\n\n // Track mount state to prevent state updates after unmount\n const mountedRef = useRef(true);\n // Track if we had auth params on mount (won't change during lifecycle)\n const hadAuthParams = useRef(hasAuthParams());\n // Track if we've already started sync to prevent double execution\n const syncStarted = useRef(false);\n\n // Reset on mount, cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n syncStarted.current = false;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (\n !isAuthLoading &&\n isOidcAuthenticated &&\n status === \"processing-oauth\"\n ) {\n setStatus(\"waiting-backend\");\n return;\n }\n\n // OIDC finished but not authenticated (and we had auth params)\n // Wait a bit before declaring failure to avoid race conditions\n if (\n hadAuthParams.current &&\n !isAuthLoading &&\n !isOidcAuthenticated &&\n !oidcError &&\n status === \"processing-oauth\"\n ) {\n // Use a small delay to avoid race condition during OIDC state transitions\n const failureTimeout = setTimeout(() => {\n if (mountedRef.current && !isOidcAuthenticated) {\n setStatus(\"error\");\n setError(\"Authentication was cancelled or failed. Please try again.\");\n }\n }, 500);\n\n return () => clearTimeout(failureTimeout);\n }\n\n return;\n }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n if (err instanceof ConvexError) {\n // try to extract the error message from the convex error\n const parseResult = convexErrorSchema.safeParse(err.data);\n if (parseResult.success) {\n setStatus(\"error\");\n setError(parseResult.data.message);\n return;\n }\n }\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error\n ? err.message\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\nimport {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n useAuth,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\n\nconst RECOVERY_TIMEOUT_MS = 10_000;\nconst LOCK_GRACE_MS = 5_000;\n\nexport type HerculesAuthProviderProps = Omit<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n loadingFallback?: ReactNode;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\ninterface HerculesAuthProviderContext {\n userManager: UserManager;\n}\n\nconst HerculesAuthProviderContext =\n createContext<HerculesAuthProviderContext | null>(null);\n\nexport function useHerculesAuthProvider() {\n const context = useContext(HerculesAuthProviderContext);\n if (!context) {\n throw new Error(\"HerculesAuthProviderContext not found\");\n }\n return context;\n}\n\nfunction AuthRecoveryGate({\n children,\n loadingFallback,\n}: {\n children: ReactNode;\n loadingFallback: ReactNode;\n}) {\n const { user, isLoading, signinSilent } = useAuth();\n const userExpired = user?.expired === true;\n const hasAttempted = useRef(false);\n const signinSilentRef = useRef(signinSilent);\n signinSilentRef.current = signinSilent;\n const [recoveryDone, setRecoveryDone] = useState(false);\n const [recovering, setRecovering] = useState(false);\n\n useEffect(() => {\n if (isLoading) return;\n if (hasAttempted.current) return;\n hasAttempted.current = true;\n\n if (!user || !userExpired) {\n setRecoveryDone(true);\n return;\n }\n\n setRecovering(true);\n const finish = () => {\n setRecovering(false);\n setRecoveryDone(true);\n };\n setTimeout(finish, RECOVERY_TIMEOUT_MS);\n\n void withRefreshLock(async () => {\n await Promise.race([\n signinSilentRef.current().catch(() => undefined),\n new Promise<void>((resolve) =>\n setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),\n ),\n ]);\n }).finally(finish);\n }, [isLoading, userExpired]);\n\n const shouldBlock =\n recovering || (!recoveryDone && !isLoading && userExpired);\n\n if (shouldBlock) {\n return <>{loadingFallback}</>;\n }\n\n return <>{children}</>;\n}\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n loadingFallback = null,\n ...props\n}: HerculesAuthProviderProps) {\n const automaticSilentRenewExplicit =\n userManagerSettings?.automaticSilentRenew === true;\n const [userManager] = useState(\n () =>\n new UserManager({\n ...userManagerSettings,\n authority: userManagerSettings?.authority ?? authority,\n client_id: userManagerSettings?.client_id ?? client_id,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n automaticSilentRenew:\n userManagerSettings?.automaticSilentRenew ?? false,\n silentRequestTimeoutInSeconds:\n userManagerSettings?.silentRequestTimeoutInSeconds ??\n RECOVERY_TIMEOUT_MS / 1000,\n }),\n );\n\n useEffect(() => {\n if (automaticSilentRenewExplicit) return;\n let retryTimerId: ReturnType<typeof setTimeout> | null = null;\n let timeoutRetryCount = 0;\n let stopped = false;\n const events = userManager.events as unknown as {\n _raiseSilentRenewError?: (e: Error) => void;\n };\n const tryRenew = () => {\n if (stopped) return;\n void withRefreshLock(async () => {\n if (stopped) return;\n try {\n await userManager.signinSilent();\n timeoutRetryCount = 0;\n } catch (err) {\n if (stopped) return;\n const isTimeout =\n err instanceof Error && err.name === \"ErrorTimeout\";\n if (isTimeout) {\n timeoutRetryCount++;\n const maxRetries = (\n userManager.settings as {\n maxSilentRenewTimeoutRetries?: number;\n }\n ).maxSilentRenewTimeoutRetries;\n if (maxRetries !== undefined && timeoutRetryCount > maxRetries) {\n timeoutRetryCount = 0;\n events._raiseSilentRenewError?.(err as Error);\n return;\n }\n retryTimerId = setTimeout(() => {\n retryTimerId = null;\n tryRenew();\n }, 5000);\n } else {\n timeoutRetryCount = 0;\n events._raiseSilentRenewError?.(err as Error);\n }\n }\n });\n };\n const onExpiring = () => tryRenew();\n userManager.events.addAccessTokenExpiring(onExpiring);\n return () => {\n stopped = true;\n userManager.events.removeAccessTokenExpiring(onExpiring);\n if (retryTimerId !== null) clearTimeout(retryTimerId);\n };\n }, [userManager, automaticSilentRenewExplicit]);\n\n return (\n <HerculesAuthProviderContext.Provider value={{ userManager }}>\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\n <AuthRecoveryGate loadingFallback={loadingFallback}>\n {children}\n </AuthRecoveryGate>\n </ReactAuthProvider>\n </HerculesAuthProviderContext.Provider>\n );\n}\n","\"use client\";\n\nimport { useMemo } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\n\n/**\n * A hook that returns the current user if authenticated\n *\n * @public\n */\nexport function useUser() {\n const { user, isLoading, error, isAuthenticated } = useAuth();\n\n return useMemo(() => {\n const id = user?.profile.sub;\n const name = user?.profile.name;\n const email = user?.profile.email;\n const avatar = user?.profile.picture;\n return {\n ...(user ?? {}),\n id,\n name,\n email,\n avatar,\n isAuthenticated,\n isLoading,\n error,\n };\n }, [user, isAuthenticated, isLoading, error]);\n}\n","import {\n useAuth as useOidcAuth,\n type AuthContextProps as OidcAuthContextProps,\n} from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport { useCallback, useMemo } from \"react\";\n\nexport interface AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: () => Promise<void>;\n}\n\nexport function useAuth(): AuthContextProps {\n const { userManager } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n\n const { signoutRedirect, removeUser, signinRedirect } = auth;\n const signout = useCallback(async () => {\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await signoutRedirect();\n } else {\n await removeUser();\n }\n }, [userManager, signoutRedirect, removeUser]);\n\n const signin = useCallback(async () => {\n await signinRedirect();\n }, [signinRedirect]);\n\n return useMemo(() => {\n return {\n ...auth,\n signout,\n signin,\n } satisfies AuthContextProps;\n }, [auth, signout, signin]);\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,EAAE,OAAO,EACjC,SAAS,EAAE,QAAQ,EACpB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GF,SAAgB,gBACd,UAAkC,EAAE,EACb;CACvB,MAAM,EACJ,YAAY,oBACZ,yBAAyB,MACzB,QACA,WACA,mBACE;CAEJ,MAAM,EACJ,WAAW,eACX,iBAAiB,qBACjB,OAAO,WACP,mBACEA,WAAS;CAEb,MAAM,CAAC,QAAQ,aAAa,SAA6B,mBAAmB;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAwB,KAAK;CAGvD,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,gBAAgB,OAAOC,iBAAe,CAAC;CAE7C,MAAM,cAAc,OAAO,MAAM;AAGjC,iBAAgB;AACd,aAAW,UAAU;AACrB,cAAY,UAAU;AACtB,eAAa;AACX,cAAW,UAAU;;IAEtB,EAAE,CAAC;AAGN,iBAAgB;AACd,MAAI,WAAW,aAAa,WAAW,QAAS;EAEhD,MAAM,UAAU,iBAAiB;AAC/B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,YAAY;AACrC,QAAM,gBAAgB;IACrB,CAAC,eAAe,CAAC;AAEpB,QAAO,cAAc;AACnB,SAAO;GACL,GAAG;GACH;GACA;GACD;IACA;EAAC;EAAM;EAAS;EAAO,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
//#region src/internal/refresh-lock.ts
|
|
2
|
+
const REFRESH_LOCK_KEY = "__herculesAuthRefresh";
|
|
3
|
+
const mutexes = /* @__PURE__ */ new Map();
|
|
4
|
+
async function manualMutex(key, callback) {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
const wrapped = () => callback().then(resolve).catch(reject).finally(() => {
|
|
7
|
+
const mutex$1 = mutexes.get(key);
|
|
8
|
+
const next = mutex$1.waiting.shift();
|
|
9
|
+
if (next) mutex$1.running = next();
|
|
10
|
+
else mutex$1.running = null;
|
|
11
|
+
});
|
|
12
|
+
let mutex = mutexes.get(key);
|
|
13
|
+
if (!mutex) {
|
|
14
|
+
mutex = {
|
|
15
|
+
running: null,
|
|
16
|
+
waiting: []
|
|
17
|
+
};
|
|
18
|
+
mutexes.set(key, mutex);
|
|
19
|
+
}
|
|
20
|
+
if (mutex.running === null) mutex.running = wrapped();
|
|
21
|
+
else mutex.waiting.push(wrapped);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
async function withRefreshLock(callback) {
|
|
25
|
+
if (typeof navigator !== "undefined" && navigator.locks) return navigator.locks.request(REFRESH_LOCK_KEY, callback);
|
|
26
|
+
return manualMutex(REFRESH_LOCK_KEY, callback);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
export { withRefreshLock as t };
|
|
31
|
+
//# sourceMappingURL=refresh-lock-DYW9ITwj.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refresh-lock-DYW9ITwj.mjs","names":["mutex"],"sources":["../src/internal/refresh-lock.ts"],"sourcesContent":["export const REFRESH_LOCK_KEY = \"__herculesAuthRefresh\";\n\ntype Queue = {\n running: Promise<void> | null;\n waiting: Array<() => Promise<void>>;\n};\n\nconst mutexes = new Map<string, Queue>();\n\nasync function manualMutex<T>(\n key: string,\n callback: () => Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const wrapped = () =>\n callback()\n .then(resolve)\n .catch(reject)\n .finally(() => {\n const mutex = mutexes.get(key)!;\n const next = mutex.waiting.shift();\n if (next) {\n mutex.running = next();\n } else {\n mutex.running = null;\n }\n });\n\n let mutex = mutexes.get(key);\n if (!mutex) {\n mutex = { running: null, waiting: [] };\n mutexes.set(key, mutex);\n }\n\n if (mutex.running === null) {\n mutex.running = wrapped();\n } else {\n mutex.waiting.push(wrapped);\n }\n });\n}\n\nexport async function withRefreshLock<T>(\n callback: () => Promise<T>,\n): Promise<T> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(REFRESH_LOCK_KEY, callback);\n }\n return manualMutex(REFRESH_LOCK_KEY, callback);\n}\n"],"mappings":";AAAA,MAAa,mBAAmB;AAOhC,MAAM,0BAAU,IAAI,KAAoB;AAExC,eAAe,YACb,KACA,UACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,gBACJ,UAAU,CACP,KAAK,QAAQ,CACb,MAAM,OAAO,CACb,cAAc;GACb,MAAMA,UAAQ,QAAQ,IAAI,IAAI;GAC9B,MAAM,OAAOA,QAAM,QAAQ,OAAO;AAClC,OAAI,KACF,SAAM,UAAU,MAAM;OAEtB,SAAM,UAAU;IAElB;EAEN,IAAI,QAAQ,QAAQ,IAAI,IAAI;AAC5B,MAAI,CAAC,OAAO;AACV,WAAQ;IAAE,SAAS;IAAM,SAAS,EAAE;IAAE;AACtC,WAAQ,IAAI,KAAK,MAAM;;AAGzB,MAAI,MAAM,YAAY,KACpB,OAAM,UAAU,SAAS;MAEzB,OAAM,QAAQ,KAAK,QAAQ;GAE7B;;AAGJ,eAAsB,gBACpB,UACY;AACZ,KAAI,OAAO,cAAc,eAAe,UAAU,MAChD,QAAO,UAAU,MAAM,QAAQ,kBAAkB,SAAS;AAE5D,QAAO,YAAY,kBAAkB,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usehercules/auth",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.46",
|
|
4
4
|
"description": "Authentication utilities for Hercules applications using OIDC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"jwt-decode": "^4.0.0",
|
|
30
30
|
"oidc-client-ts": "^3.4.1",
|
|
31
|
-
"react-oidc-context": "^3.3.
|
|
31
|
+
"react-oidc-context": "^3.3.1",
|
|
32
32
|
"zod": "^4.3.6"
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
@@ -40,13 +40,13 @@
|
|
|
40
40
|
"@testing-library/react": "^16.3.2",
|
|
41
41
|
"@types/react": "^19.2.14",
|
|
42
42
|
"@types/react-dom": "^19.2.3",
|
|
43
|
-
"convex": "^1.
|
|
43
|
+
"convex": "^1.38.0",
|
|
44
44
|
"jsdom": "^28.1.0",
|
|
45
45
|
"react": "^19.2.4",
|
|
46
46
|
"react-dom": "^19.2.4",
|
|
47
47
|
"tsdown": "^0.18.4",
|
|
48
48
|
"typescript": "^5.9.3",
|
|
49
|
-
"vitest": "^4.0
|
|
49
|
+
"vitest": "^4.1.0"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
52
|
"build": "tsdown",
|
|
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
2
2
|
import type { ReactNode } from "react";
|
|
3
3
|
import { renderHook, act, configure } from "@testing-library/react";
|
|
4
4
|
import { ConvexProviderWithHerculesAuth } from "./ConvexProviderWithHercules.js";
|
|
5
|
+
import React from "react";
|
|
5
6
|
|
|
6
7
|
configure({ reactStrictMode: true });
|
|
7
8
|
|
|
@@ -237,4 +238,83 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
|
|
|
237
238
|
expect(secondToken).toBe("second-fresh");
|
|
238
239
|
expect(mockSigninSilent).toHaveBeenCalledTimes(2);
|
|
239
240
|
});
|
|
241
|
+
|
|
242
|
+
it("keeps fetchAccessToken stable across silent renewal of the same subject", async () => {
|
|
243
|
+
const FIRST_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
244
|
+
const SECOND_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 60 * 60);
|
|
245
|
+
setAuthState({
|
|
246
|
+
user: {
|
|
247
|
+
id_token: FIRST_TOKEN,
|
|
248
|
+
profile: { iss: "https://issuer.example", sub: "alice" },
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
const { result, rerender } = renderUseAuth();
|
|
253
|
+
const firstFetch = result.current.fetchAccessToken;
|
|
254
|
+
|
|
255
|
+
expect(
|
|
256
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
257
|
+
).toBe(FIRST_TOKEN);
|
|
258
|
+
|
|
259
|
+
setAuthState({
|
|
260
|
+
user: {
|
|
261
|
+
id_token: SECOND_TOKEN,
|
|
262
|
+
profile: { iss: "https://issuer.example", sub: "alice" },
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
rerender();
|
|
266
|
+
|
|
267
|
+
expect(result.current.fetchAccessToken).toBe(firstFetch);
|
|
268
|
+
expect(
|
|
269
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
270
|
+
).toBe(SECOND_TOKEN);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
it("re-identifies fetchAccessToken when the subject changes", async () => {
|
|
274
|
+
const ALICE_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
275
|
+
const BOB_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
276
|
+
setAuthState({
|
|
277
|
+
user: { id_token: ALICE_TOKEN, profile: { sub: "alice" } },
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
const { result, rerender } = renderUseAuth();
|
|
281
|
+
const aliceFetch = result.current.fetchAccessToken;
|
|
282
|
+
|
|
283
|
+
setAuthState({
|
|
284
|
+
user: { id_token: BOB_TOKEN, profile: { sub: "bob" } },
|
|
285
|
+
});
|
|
286
|
+
rerender();
|
|
287
|
+
|
|
288
|
+
expect(
|
|
289
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
290
|
+
).toBe(BOB_TOKEN);
|
|
291
|
+
expect(result.current.fetchAccessToken).not.toBe(aliceFetch);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("re-identifies fetchAccessToken when the issuer changes", async () => {
|
|
295
|
+
const FIRST_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
296
|
+
const SECOND_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
297
|
+
setAuthState({
|
|
298
|
+
user: {
|
|
299
|
+
id_token: FIRST_TOKEN,
|
|
300
|
+
profile: { iss: "https://issuer-a.example", sub: "shared-sub" },
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const { result, rerender } = renderUseAuth();
|
|
305
|
+
const firstFetch = result.current.fetchAccessToken;
|
|
306
|
+
|
|
307
|
+
setAuthState({
|
|
308
|
+
user: {
|
|
309
|
+
id_token: SECOND_TOKEN,
|
|
310
|
+
profile: { iss: "https://issuer-b.example", sub: "shared-sub" },
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
rerender();
|
|
314
|
+
|
|
315
|
+
expect(result.current.fetchAccessToken).not.toBe(firstFetch);
|
|
316
|
+
expect(
|
|
317
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
318
|
+
).toBe(SECOND_TOKEN);
|
|
319
|
+
});
|
|
240
320
|
});
|
|
@@ -5,10 +5,10 @@ import { ConvexProviderWithAuth, type ConvexReactClient } from "convex/react";
|
|
|
5
5
|
import { jwtDecode } from "jwt-decode";
|
|
6
6
|
import { useCallback, useMemo, useRef } from "react";
|
|
7
7
|
import { useAuth } from "react-oidc-context";
|
|
8
|
+
import { withRefreshLock } from "../internal/refresh-lock";
|
|
8
9
|
import type { HerculesAuthProvider } from "../react/HerculesAuthProvider";
|
|
9
10
|
|
|
10
11
|
const REFRESH_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour
|
|
11
|
-
const LOCK_KEY = "__herculesAuthRefresh";
|
|
12
12
|
|
|
13
13
|
function tokenExpiresWithin(token: string, ms: number): boolean {
|
|
14
14
|
try {
|
|
@@ -19,89 +19,45 @@ function tokenExpiresWithin(token: string, ms: number): boolean {
|
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
// Cross-tab mutex: uses Web Locks API when available, falls back to a
|
|
23
|
-
// simple in-memory queue for environments that don't support it.
|
|
24
|
-
async function withLock<T>(key: string, callback: () => Promise<T>): Promise<T> {
|
|
25
|
-
if (typeof navigator !== "undefined" && navigator.locks) {
|
|
26
|
-
return navigator.locks.request(key, callback);
|
|
27
|
-
}
|
|
28
|
-
return manualMutex(key, callback);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const mutexes = new Map<
|
|
32
|
-
string,
|
|
33
|
-
{ running: Promise<void> | null; waiting: Array<() => Promise<void>> }
|
|
34
|
-
>();
|
|
35
|
-
|
|
36
|
-
async function manualMutex<T>(
|
|
37
|
-
key: string,
|
|
38
|
-
callback: () => Promise<T>,
|
|
39
|
-
): Promise<T> {
|
|
40
|
-
return new Promise<T>((resolve, reject) => {
|
|
41
|
-
const wrapped = () =>
|
|
42
|
-
callback()
|
|
43
|
-
.then(resolve)
|
|
44
|
-
.catch(reject)
|
|
45
|
-
.finally(() => {
|
|
46
|
-
const mutex = mutexes.get(key)!;
|
|
47
|
-
const next = mutex.waiting.shift();
|
|
48
|
-
if (next) {
|
|
49
|
-
mutex.running = next();
|
|
50
|
-
} else {
|
|
51
|
-
mutex.running = null;
|
|
52
|
-
}
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
let mutex = mutexes.get(key);
|
|
56
|
-
if (!mutex) {
|
|
57
|
-
mutex = { running: null, waiting: [] };
|
|
58
|
-
mutexes.set(key, mutex);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
if (mutex.running === null) {
|
|
62
|
-
mutex.running = wrapped();
|
|
63
|
-
} else {
|
|
64
|
-
mutex.waiting.push(wrapped);
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
|
|
69
22
|
function useUseAuthFromHercules() {
|
|
70
23
|
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
71
24
|
const idToken = user?.id_token;
|
|
25
|
+
const issuer = user?.profile?.iss;
|
|
26
|
+
const subject = user?.profile?.sub;
|
|
72
27
|
|
|
73
|
-
// Ref so the re-check inside the lock sees updates from other tabs
|
|
74
28
|
const idTokenRef = useRef(idToken);
|
|
75
29
|
idTokenRef.current = idToken;
|
|
76
30
|
|
|
31
|
+
const signinSilentRef = useRef(signinSilent);
|
|
32
|
+
signinSilentRef.current = signinSilent;
|
|
33
|
+
|
|
77
34
|
const inFlightRefresh = useRef<Promise<string | null> | null>(null);
|
|
78
35
|
|
|
79
36
|
const fetchAccessToken = useCallback(
|
|
80
37
|
async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
|
|
38
|
+
const currentToken = idTokenRef.current;
|
|
81
39
|
if (!forceRefreshToken) {
|
|
82
|
-
return
|
|
40
|
+
return currentToken ?? null;
|
|
83
41
|
}
|
|
84
42
|
if (
|
|
85
|
-
|
|
86
|
-
!tokenExpiresWithin(
|
|
43
|
+
currentToken != null &&
|
|
44
|
+
!tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
|
|
87
45
|
) {
|
|
88
|
-
return
|
|
46
|
+
return currentToken;
|
|
89
47
|
}
|
|
90
|
-
// Same-tab dedup: concurrent callers share one promise
|
|
91
48
|
if (inFlightRefresh.current) {
|
|
92
49
|
return inFlightRefresh.current;
|
|
93
50
|
}
|
|
94
|
-
const refresh =
|
|
95
|
-
|
|
96
|
-
const currentToken = idTokenRef.current;
|
|
51
|
+
const refresh = withRefreshLock(async () => {
|
|
52
|
+
const tokenAfterLock = idTokenRef.current;
|
|
97
53
|
if (
|
|
98
|
-
|
|
99
|
-
!tokenExpiresWithin(
|
|
54
|
+
tokenAfterLock != null &&
|
|
55
|
+
!tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)
|
|
100
56
|
) {
|
|
101
|
-
return
|
|
57
|
+
return tokenAfterLock;
|
|
102
58
|
}
|
|
103
59
|
try {
|
|
104
|
-
const refreshed = await
|
|
60
|
+
const refreshed = await signinSilentRef.current();
|
|
105
61
|
return refreshed?.id_token ?? null;
|
|
106
62
|
} catch {
|
|
107
63
|
return null;
|
|
@@ -112,7 +68,7 @@ function useUseAuthFromHercules() {
|
|
|
112
68
|
inFlightRefresh.current = refresh;
|
|
113
69
|
return refresh;
|
|
114
70
|
},
|
|
115
|
-
[
|
|
71
|
+
[issuer, subject],
|
|
116
72
|
);
|
|
117
73
|
|
|
118
74
|
return useMemo(
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export const REFRESH_LOCK_KEY = "__herculesAuthRefresh";
|
|
2
|
+
|
|
3
|
+
type Queue = {
|
|
4
|
+
running: Promise<void> | null;
|
|
5
|
+
waiting: Array<() => Promise<void>>;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
const mutexes = new Map<string, Queue>();
|
|
9
|
+
|
|
10
|
+
async function manualMutex<T>(
|
|
11
|
+
key: string,
|
|
12
|
+
callback: () => Promise<T>,
|
|
13
|
+
): Promise<T> {
|
|
14
|
+
return new Promise<T>((resolve, reject) => {
|
|
15
|
+
const wrapped = () =>
|
|
16
|
+
callback()
|
|
17
|
+
.then(resolve)
|
|
18
|
+
.catch(reject)
|
|
19
|
+
.finally(() => {
|
|
20
|
+
const mutex = mutexes.get(key)!;
|
|
21
|
+
const next = mutex.waiting.shift();
|
|
22
|
+
if (next) {
|
|
23
|
+
mutex.running = next();
|
|
24
|
+
} else {
|
|
25
|
+
mutex.running = null;
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
let mutex = mutexes.get(key);
|
|
30
|
+
if (!mutex) {
|
|
31
|
+
mutex = { running: null, waiting: [] };
|
|
32
|
+
mutexes.set(key, mutex);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (mutex.running === null) {
|
|
36
|
+
mutex.running = wrapped();
|
|
37
|
+
} else {
|
|
38
|
+
mutex.waiting.push(wrapped);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function withRefreshLock<T>(
|
|
44
|
+
callback: () => Promise<T>,
|
|
45
|
+
): Promise<T> {
|
|
46
|
+
if (typeof navigator !== "undefined" && navigator.locks) {
|
|
47
|
+
return navigator.locks.request(REFRESH_LOCK_KEY, callback);
|
|
48
|
+
}
|
|
49
|
+
return manualMutex(REFRESH_LOCK_KEY, callback);
|
|
50
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
2
|
+
import { act, render, screen, waitFor, configure } from "@testing-library/react";
|
|
3
|
+
import { HerculesAuthProvider } from "./HerculesAuthProvider.js";
|
|
4
|
+
|
|
5
|
+
configure({ reactStrictMode: false });
|
|
6
|
+
|
|
7
|
+
const mockSigninSilent = vi.fn();
|
|
8
|
+
let mockAuthState: Record<string, unknown> = {};
|
|
9
|
+
|
|
10
|
+
vi.mock("react-oidc-context", () => ({
|
|
11
|
+
AuthProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
|
12
|
+
useAuth: () => mockAuthState,
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
vi.mock("oidc-client-ts", () => ({
|
|
16
|
+
UserManager: class {
|
|
17
|
+
constructor() {}
|
|
18
|
+
events = {
|
|
19
|
+
addAccessTokenExpiring: vi.fn(),
|
|
20
|
+
removeAccessTokenExpiring: vi.fn(),
|
|
21
|
+
};
|
|
22
|
+
signinSilent = vi.fn();
|
|
23
|
+
},
|
|
24
|
+
WebStorageStateStore: class {
|
|
25
|
+
constructor() {}
|
|
26
|
+
},
|
|
27
|
+
}));
|
|
28
|
+
|
|
29
|
+
vi.mock("../internal/refresh-lock", () => ({
|
|
30
|
+
withRefreshLock: <T,>(callback: () => Promise<T>) => callback(),
|
|
31
|
+
REFRESH_LOCK_KEY: "__herculesAuthRefresh",
|
|
32
|
+
}));
|
|
33
|
+
|
|
34
|
+
function setAuthState(overrides: Record<string, unknown>) {
|
|
35
|
+
mockAuthState = {
|
|
36
|
+
isLoading: false,
|
|
37
|
+
user: null,
|
|
38
|
+
signinSilent: mockSigninSilent,
|
|
39
|
+
...overrides,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
beforeEach(() => {
|
|
44
|
+
setAuthState({});
|
|
45
|
+
mockSigninSilent.mockReset();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
function renderProvider(
|
|
49
|
+
loadingFallback?: React.ReactNode,
|
|
50
|
+
children: React.ReactNode = <div data-testid="app">app content</div>,
|
|
51
|
+
) {
|
|
52
|
+
return render(
|
|
53
|
+
<HerculesAuthProvider
|
|
54
|
+
authority="https://auth.example.com"
|
|
55
|
+
client_id="test-client"
|
|
56
|
+
loadingFallback={loadingFallback}
|
|
57
|
+
>
|
|
58
|
+
{children}
|
|
59
|
+
</HerculesAuthProvider>,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
|
|
64
|
+
it("registers the lock-wrapped renewal listener by default", () => {
|
|
65
|
+
render(
|
|
66
|
+
<HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
|
|
67
|
+
<div data-testid="app">app</div>
|
|
68
|
+
</HerculesAuthProvider>,
|
|
69
|
+
);
|
|
70
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("skips registering the listener when automaticSilentRenew is explicitly true", () => {
|
|
74
|
+
render(
|
|
75
|
+
<HerculesAuthProvider
|
|
76
|
+
authority="https://auth.example.com"
|
|
77
|
+
client_id="test-client"
|
|
78
|
+
userManagerSettings={{ automaticSilentRenew: true }}
|
|
79
|
+
>
|
|
80
|
+
<div data-testid="app">app</div>
|
|
81
|
+
</HerculesAuthProvider>,
|
|
82
|
+
);
|
|
83
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
describe("HerculesAuthProvider AuthRecoveryGate", () => {
|
|
88
|
+
it("renders children (not loadingFallback) while isLoading is true", async () => {
|
|
89
|
+
setAuthState({ isLoading: true, user: null });
|
|
90
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
91
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
92
|
+
expect(screen.queryByTestId("loading")).toBeNull();
|
|
93
|
+
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
it("blocks children on the very first commit when user is already expired", () => {
|
|
97
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
98
|
+
setAuthState({ isLoading: false, user: { expired: true, id_token: "stale" } });
|
|
99
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
100
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
101
|
+
expect(screen.queryByTestId("app")).toBeNull();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("keeps the gate closed while signinSilent is in flight even if isLoading flips true", async () => {
|
|
105
|
+
let resolveSilent!: () => void;
|
|
106
|
+
mockSigninSilent.mockImplementation(
|
|
107
|
+
() =>
|
|
108
|
+
new Promise<void>((resolve) => {
|
|
109
|
+
resolveSilent = resolve;
|
|
110
|
+
}),
|
|
111
|
+
);
|
|
112
|
+
setAuthState({ isLoading: false, user: { expired: true, id_token: "stale" } });
|
|
113
|
+
const { rerender } = renderProvider(<div data-testid="loading">loading</div>);
|
|
114
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
115
|
+
await waitFor(() => {
|
|
116
|
+
expect(mockSigninSilent).toHaveBeenCalledTimes(1);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
setAuthState({ isLoading: true, user: { expired: true, id_token: "stale" } });
|
|
120
|
+
rerender(
|
|
121
|
+
<HerculesAuthProvider
|
|
122
|
+
authority="https://auth.example.com"
|
|
123
|
+
client_id="test-client"
|
|
124
|
+
loadingFallback={<div data-testid="loading">loading</div>}
|
|
125
|
+
>
|
|
126
|
+
<div data-testid="app">app content</div>
|
|
127
|
+
</HerculesAuthProvider>,
|
|
128
|
+
);
|
|
129
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
130
|
+
expect(screen.queryByTestId("app")).toBeNull();
|
|
131
|
+
|
|
132
|
+
await act(async () => {
|
|
133
|
+
resolveSilent();
|
|
134
|
+
});
|
|
135
|
+
await waitFor(() => {
|
|
136
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it("recovers correctly under React StrictMode (double-mount)", async () => {
|
|
141
|
+
configure({ reactStrictMode: true });
|
|
142
|
+
mockSigninSilent.mockResolvedValue(undefined);
|
|
143
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
144
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
145
|
+
await waitFor(() => {
|
|
146
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
147
|
+
});
|
|
148
|
+
configure({ reactStrictMode: false });
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("falls back to the outer timeout under StrictMode when signinSilent hangs", async () => {
|
|
152
|
+
configure({ reactStrictMode: true });
|
|
153
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
154
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
155
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
156
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
157
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
158
|
+
await vi.advanceTimersByTimeAsync(10_000);
|
|
159
|
+
await waitFor(() => {
|
|
160
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
161
|
+
});
|
|
162
|
+
vi.useRealTimers();
|
|
163
|
+
configure({ reactStrictMode: false });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("releases the refresh lock at the safety deadline when signinSilent never settles", async () => {
|
|
167
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
168
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
169
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
170
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
171
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
172
|
+
await vi.advanceTimersByTimeAsync(10_000);
|
|
173
|
+
await waitFor(() => {
|
|
174
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
175
|
+
});
|
|
176
|
+
await vi.advanceTimersByTimeAsync(5_000);
|
|
177
|
+
await waitFor(() => {
|
|
178
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
179
|
+
});
|
|
180
|
+
vi.useRealTimers();
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("renders children immediately when user is null", async () => {
|
|
184
|
+
setAuthState({ user: null });
|
|
185
|
+
renderProvider();
|
|
186
|
+
await waitFor(() => {
|
|
187
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
188
|
+
});
|
|
189
|
+
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it("renders children immediately when user is fresh (not expired)", async () => {
|
|
193
|
+
setAuthState({ user: { expired: false, id_token: "token" } });
|
|
194
|
+
renderProvider();
|
|
195
|
+
await waitFor(() => {
|
|
196
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
197
|
+
});
|
|
198
|
+
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("calls signinSilent and renders loadingFallback when user is expired", async () => {
|
|
202
|
+
let resolveSilent!: () => void;
|
|
203
|
+
mockSigninSilent.mockImplementation(
|
|
204
|
+
() =>
|
|
205
|
+
new Promise<void>((resolve) => {
|
|
206
|
+
resolveSilent = resolve;
|
|
207
|
+
}),
|
|
208
|
+
);
|
|
209
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
210
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
211
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
212
|
+
expect(screen.queryByTestId("app")).toBeNull();
|
|
213
|
+
await waitFor(() => {
|
|
214
|
+
expect(mockSigninSilent).toHaveBeenCalledTimes(1);
|
|
215
|
+
});
|
|
216
|
+
await act(async () => {
|
|
217
|
+
resolveSilent();
|
|
218
|
+
});
|
|
219
|
+
await waitFor(() => {
|
|
220
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
221
|
+
});
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("renders children after the recovery times out", async () => {
|
|
225
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
226
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
227
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
228
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
229
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
230
|
+
await vi.advanceTimersByTimeAsync(10_000);
|
|
231
|
+
await waitFor(() => {
|
|
232
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
233
|
+
});
|
|
234
|
+
vi.useRealTimers();
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it("renders children after signinSilent throws", async () => {
|
|
238
|
+
mockSigninSilent.mockRejectedValueOnce(new Error("nope"));
|
|
239
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
240
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
241
|
+
await waitFor(() => {
|
|
242
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it("unblocks UI via outer timeout while keeping the lock held by in-flight signinSilent", async () => {
|
|
247
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
248
|
+
mockSigninSilent.mockImplementation(() => new Promise<void>(() => {}));
|
|
249
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
250
|
+
renderProvider(<div data-testid="loading">loading</div>);
|
|
251
|
+
expect(screen.getByTestId("loading")).toBeDefined();
|
|
252
|
+
await vi.advanceTimersByTimeAsync(10_000);
|
|
253
|
+
await waitFor(() => {
|
|
254
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
255
|
+
});
|
|
256
|
+
vi.useRealTimers();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it("does not refire signinSilent on rerenders", async () => {
|
|
260
|
+
let resolveSilent!: () => void;
|
|
261
|
+
mockSigninSilent.mockImplementation(
|
|
262
|
+
() =>
|
|
263
|
+
new Promise<void>((resolve) => {
|
|
264
|
+
resolveSilent = resolve;
|
|
265
|
+
}),
|
|
266
|
+
);
|
|
267
|
+
setAuthState({ user: { expired: true, id_token: "stale" } });
|
|
268
|
+
const { rerender } = renderProvider();
|
|
269
|
+
await waitFor(() => {
|
|
270
|
+
expect(mockSigninSilent).toHaveBeenCalledTimes(1);
|
|
271
|
+
});
|
|
272
|
+
await act(async () => {
|
|
273
|
+
resolveSilent();
|
|
274
|
+
});
|
|
275
|
+
setAuthState({ user: { expired: true, id_token: "stale-2" } });
|
|
276
|
+
rerender(
|
|
277
|
+
<HerculesAuthProvider
|
|
278
|
+
authority="https://auth.example.com"
|
|
279
|
+
client_id="test-client"
|
|
280
|
+
>
|
|
281
|
+
<div data-testid="app">app content</div>
|
|
282
|
+
</HerculesAuthProvider>,
|
|
283
|
+
);
|
|
284
|
+
await waitFor(() => {
|
|
285
|
+
expect(screen.getByTestId("app")).toBeDefined();
|
|
286
|
+
});
|
|
287
|
+
expect(mockSigninSilent).toHaveBeenCalledTimes(1);
|
|
288
|
+
});
|
|
289
|
+
});
|
|
@@ -1,16 +1,27 @@
|
|
|
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
|
+
|
|
23
|
+
const RECOVERY_TIMEOUT_MS = 10_000;
|
|
24
|
+
const LOCK_GRACE_MS = 5_000;
|
|
14
25
|
|
|
15
26
|
export type HerculesAuthProviderProps = Omit<
|
|
16
27
|
AuthProviderUserManagerProps,
|
|
@@ -19,6 +30,7 @@ export type HerculesAuthProviderProps = Omit<
|
|
|
19
30
|
userManagerSettings?: Partial<UserManagerSettings>;
|
|
20
31
|
authority: string;
|
|
21
32
|
client_id: string;
|
|
33
|
+
loadingFallback?: ReactNode;
|
|
22
34
|
};
|
|
23
35
|
|
|
24
36
|
function onSigninCallback() {
|
|
@@ -49,6 +61,58 @@ export function useHerculesAuthProvider() {
|
|
|
49
61
|
return context;
|
|
50
62
|
}
|
|
51
63
|
|
|
64
|
+
function AuthRecoveryGate({
|
|
65
|
+
children,
|
|
66
|
+
loadingFallback,
|
|
67
|
+
}: {
|
|
68
|
+
children: ReactNode;
|
|
69
|
+
loadingFallback: ReactNode;
|
|
70
|
+
}) {
|
|
71
|
+
const { user, isLoading, signinSilent } = useAuth();
|
|
72
|
+
const userExpired = user?.expired === true;
|
|
73
|
+
const hasAttempted = useRef(false);
|
|
74
|
+
const signinSilentRef = useRef(signinSilent);
|
|
75
|
+
signinSilentRef.current = signinSilent;
|
|
76
|
+
const [recoveryDone, setRecoveryDone] = useState(false);
|
|
77
|
+
const [recovering, setRecovering] = useState(false);
|
|
78
|
+
|
|
79
|
+
useEffect(() => {
|
|
80
|
+
if (isLoading) return;
|
|
81
|
+
if (hasAttempted.current) return;
|
|
82
|
+
hasAttempted.current = true;
|
|
83
|
+
|
|
84
|
+
if (!user || !userExpired) {
|
|
85
|
+
setRecoveryDone(true);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
setRecovering(true);
|
|
90
|
+
const finish = () => {
|
|
91
|
+
setRecovering(false);
|
|
92
|
+
setRecoveryDone(true);
|
|
93
|
+
};
|
|
94
|
+
setTimeout(finish, RECOVERY_TIMEOUT_MS);
|
|
95
|
+
|
|
96
|
+
void withRefreshLock(async () => {
|
|
97
|
+
await Promise.race([
|
|
98
|
+
signinSilentRef.current().catch(() => undefined),
|
|
99
|
+
new Promise<void>((resolve) =>
|
|
100
|
+
setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),
|
|
101
|
+
),
|
|
102
|
+
]);
|
|
103
|
+
}).finally(finish);
|
|
104
|
+
}, [isLoading, userExpired]);
|
|
105
|
+
|
|
106
|
+
const shouldBlock =
|
|
107
|
+
recovering || (!recoveryDone && !isLoading && userExpired);
|
|
108
|
+
|
|
109
|
+
if (shouldBlock) {
|
|
110
|
+
return <>{loadingFallback}</>;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return <>{children}</>;
|
|
114
|
+
}
|
|
115
|
+
|
|
52
116
|
/**
|
|
53
117
|
* A wrapper React component which provides a {@link ReactAuthProvider}
|
|
54
118
|
* configured with Hercules Auth.
|
|
@@ -60,8 +124,11 @@ export function HerculesAuthProvider({
|
|
|
60
124
|
userManagerSettings,
|
|
61
125
|
authority,
|
|
62
126
|
client_id,
|
|
127
|
+
loadingFallback = null,
|
|
63
128
|
...props
|
|
64
129
|
}: HerculesAuthProviderProps) {
|
|
130
|
+
const automaticSilentRenewExplicit =
|
|
131
|
+
userManagerSettings?.automaticSilentRenew === true;
|
|
65
132
|
const [userManager] = useState(
|
|
66
133
|
() =>
|
|
67
134
|
new UserManager({
|
|
@@ -81,9 +148,65 @@ export function HerculesAuthProvider({
|
|
|
81
148
|
userStore:
|
|
82
149
|
userManagerSettings?.userStore ??
|
|
83
150
|
new WebStorageStateStore({ store: window.localStorage }),
|
|
151
|
+
automaticSilentRenew:
|
|
152
|
+
userManagerSettings?.automaticSilentRenew ?? false,
|
|
153
|
+
silentRequestTimeoutInSeconds:
|
|
154
|
+
userManagerSettings?.silentRequestTimeoutInSeconds ??
|
|
155
|
+
RECOVERY_TIMEOUT_MS / 1000,
|
|
84
156
|
}),
|
|
85
157
|
);
|
|
86
158
|
|
|
159
|
+
useEffect(() => {
|
|
160
|
+
if (automaticSilentRenewExplicit) return;
|
|
161
|
+
let retryTimerId: ReturnType<typeof setTimeout> | null = null;
|
|
162
|
+
let timeoutRetryCount = 0;
|
|
163
|
+
let stopped = false;
|
|
164
|
+
const events = userManager.events as unknown as {
|
|
165
|
+
_raiseSilentRenewError?: (e: Error) => void;
|
|
166
|
+
};
|
|
167
|
+
const tryRenew = () => {
|
|
168
|
+
if (stopped) return;
|
|
169
|
+
void withRefreshLock(async () => {
|
|
170
|
+
if (stopped) return;
|
|
171
|
+
try {
|
|
172
|
+
await userManager.signinSilent();
|
|
173
|
+
timeoutRetryCount = 0;
|
|
174
|
+
} catch (err) {
|
|
175
|
+
if (stopped) return;
|
|
176
|
+
const isTimeout =
|
|
177
|
+
err instanceof Error && err.name === "ErrorTimeout";
|
|
178
|
+
if (isTimeout) {
|
|
179
|
+
timeoutRetryCount++;
|
|
180
|
+
const maxRetries = (
|
|
181
|
+
userManager.settings as {
|
|
182
|
+
maxSilentRenewTimeoutRetries?: number;
|
|
183
|
+
}
|
|
184
|
+
).maxSilentRenewTimeoutRetries;
|
|
185
|
+
if (maxRetries !== undefined && timeoutRetryCount > maxRetries) {
|
|
186
|
+
timeoutRetryCount = 0;
|
|
187
|
+
events._raiseSilentRenewError?.(err as Error);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
retryTimerId = setTimeout(() => {
|
|
191
|
+
retryTimerId = null;
|
|
192
|
+
tryRenew();
|
|
193
|
+
}, 5000);
|
|
194
|
+
} else {
|
|
195
|
+
timeoutRetryCount = 0;
|
|
196
|
+
events._raiseSilentRenewError?.(err as Error);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
};
|
|
201
|
+
const onExpiring = () => tryRenew();
|
|
202
|
+
userManager.events.addAccessTokenExpiring(onExpiring);
|
|
203
|
+
return () => {
|
|
204
|
+
stopped = true;
|
|
205
|
+
userManager.events.removeAccessTokenExpiring(onExpiring);
|
|
206
|
+
if (retryTimerId !== null) clearTimeout(retryTimerId);
|
|
207
|
+
};
|
|
208
|
+
}, [userManager, automaticSilentRenewExplicit]);
|
|
209
|
+
|
|
87
210
|
return (
|
|
88
211
|
<HerculesAuthProviderContext.Provider value={{ userManager }}>
|
|
89
212
|
<ReactAuthProvider
|
|
@@ -91,7 +214,9 @@ export function HerculesAuthProvider({
|
|
|
91
214
|
{...DEFAULT_AUTH_CONFIG}
|
|
92
215
|
{...props}
|
|
93
216
|
>
|
|
94
|
-
{
|
|
217
|
+
<AuthRecoveryGate loadingFallback={loadingFallback}>
|
|
218
|
+
{children}
|
|
219
|
+
</AuthRecoveryGate>
|
|
95
220
|
</ReactAuthProvider>
|
|
96
221
|
</HerculesAuthProviderContext.Provider>
|
|
97
222
|
);
|