@usehercules/auth 1.2.1 → 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.
@@ -1,10 +1,7 @@
1
1
  import { ReactNode } from "react";
2
2
  import { ConvexReactClient } from "convex/react";
3
- //#region src/convex-react/ConvexProviderWithHercules.d.ts
4
- declare function ConvexProviderWithHerculesAuth({ children, client }: {
3
+ export declare function ConvexProviderWithHerculesAuth({ children, client }: {
5
4
  children: ReactNode;
6
5
  client: ConvexReactClient;
7
6
  }): import("react").JSX.Element;
8
- //#endregion
9
- export { ConvexProviderWithHerculesAuth };
10
7
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"mappings":";;;iBAqFgB,iCACd,UACA;EAEA,UAAU;EACV,QAAQ;oBACT,IAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"mappings":";;wBAoFgB,iCACd,UACA;EAEA,UAAU;EACV,QAAQ;oBACT,IAAA"}
@@ -1,11 +1,11 @@
1
- import { t as withRefreshLock } from "../refresh-lock-Cv63qcNd.mjs";
1
+ import { t as withRefreshLock } from "../refresh-lock-RJUGj8im.mjs";
2
2
  import { useCallback, useMemo, useRef } from "react";
3
3
  import { useAuth } from "react-oidc-context";
4
4
  import { jwtDecode } from "jwt-decode";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  import { ConvexProviderWithAuth } from "convex/react";
7
- //#region src/convex-react/ConvexProviderWithHercules.tsx
8
- const REFRESH_THRESHOLD_MS = 3600 * 1e3;
7
+ // src/convex-react/ConvexProviderWithHercules.tsx
8
+ const REFRESH_THRESHOLD_MS = 36e5;
9
9
  function tokenExpiresWithin(token, ms) {
10
10
  try {
11
11
  return jwtDecode(token).exp * 1e3 - Date.now() < ms;
@@ -56,7 +56,7 @@ function useUseAuthFromHercules() {
56
56
  * A wrapper React component which provides a {@link ConvexReactClient}
57
57
  * authenticated with Hercules Auth.
58
58
  *
59
- * It must be wrapped by a configured `{@link HerculesAuthProvider}`.
59
+ * It must be wrapped by a configured `HerculesAuthProvider`.
60
60
  *
61
61
  * @public
62
62
  */
@@ -67,7 +67,6 @@ function ConvexProviderWithHerculesAuth({ children, client }) {
67
67
  children
68
68
  });
69
69
  }
70
- //#endregion
71
70
  export { ConvexProviderWithHerculesAuth };
72
71
 
73
72
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
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 (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) {\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 (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) {\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 <ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>\n {children}\n </ConvexProviderWithAuth>\n );\n}\n"],"mappings":";;;;;;;AAUA,MAAM,uBAAuB,OAAU;AAEvC,SAAS,mBAAmB,OAAe,IAAqB;CAC9D,IAAI;EAEF,OADgB,UAAU,KACb,CAAC,CAAC,MAAO,MAAO,KAAK,IAAI,IAAI;CAC5C,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,yBAAyB;CAChC,MAAM,EAAE,iBAAiB,MAAM,WAAW,iBAAiB,QAAQ;CACnE,MAAM,UAAU,MAAM;CACtB,MAAM,SAAS,MAAM,SAAS;CAC9B,MAAM,UAAU,MAAM,SAAS;CAE/B,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CAErB,MAAM,kBAAkB,OAAO,YAAY;CAC3C,gBAAgB,UAAU;CAE1B,MAAM,kBAAkB,OAAsC,IAAI;CAElE,MAAM,mBAAmB,YACvB,OAAO,EAAE,wBAAwD;EAC/D,MAAM,eAAe,WAAW;EAChC,IAAI,CAAC,mBACH,OAAO,gBAAgB;EAEzB,IAAI,gBAAgB,QAAQ,CAAC,mBAAmB,cAAc,oBAAoB,GAChF,OAAO;EAET,IAAI,gBAAgB,SAClB,OAAO,gBAAgB;EAEzB,MAAM,UAAU,gBAAgB,YAAY;GAC1C,MAAM,iBAAiB,WAAW;GAClC,IAAI,kBAAkB,QAAQ,CAAC,mBAAmB,gBAAgB,oBAAoB,GACpF,OAAO;GAET,IAAI;IAEF,QAAO,MADiB,gBAAgB,QAAQ,EAAA,EAC9B,YAAY;GAChC,QAAQ;IACN,OAAO;GACT;EACF,CAAC,CAAC,CAAC,cAAc;GACf,gBAAgB,UAAU;EAC5B,CAAC;EACD,gBAAgB,UAAU;EAC1B,OAAO;CACT,GACA,CAAC,QAAQ,OAAO,CAClB;CAEA,OAAO,eACE;EACL,WAAW,kBAAkB,QAAQ;EACrC;EACA;CACF,IACA;EAAC;EAAW;EAAiB;CAAgB,CAC/C;AACF;;;;;;;;;AAUA,SAAgB,+BAA+B,EAC7C,UACA,UAIC;CACD,OACE,oBAAC,wBAAD;EAAgC;EAAQ,SAAS;EAC9C;CACqB,CAAA;AAE5B"}
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\";\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 (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) {\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 (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) {\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 `HerculesAuthProvider`.\n *\n * @public\n */\nexport function ConvexProviderWithHerculesAuth({\n children,\n client,\n}: {\n children: ReactNode;\n client: ConvexReactClient;\n}) {\n return (\n <ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>\n {children}\n </ConvexProviderWithAuth>\n );\n}\n"],"mappings":";;;;;;;AASA,MAAM,uBAAuB;AAE7B,SAAS,mBAAmB,OAAe,IAAqB;CAC9D,IAAI;EAEF,OADgB,UAAU,KACb,CAAC,CAAC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1, AuthProviderUserManagerProps, hasAuthParams } from "react-oidc-context";
3
3
  import { UserManager, UserManagerSettings } from "oidc-client-ts";
4
- //#region src/react/auth-callback-hook.d.ts
5
- type AuthCallbackStatus = "processing-oauth" | "waiting-backend" | "syncing" | "success" | "error";
6
- interface UseAuthCallbackOptions {
4
+ export type AuthCallbackStatus = "processing-oauth" | "waiting-backend" | "syncing" | "success" | "error";
5
+ export interface UseAuthCallbackOptions {
7
6
  timeoutMs?: number;
8
7
  isBackendAuthenticated?: boolean;
9
8
  onSync?: () => Promise<void>;
10
9
  onSuccess?: () => void;
11
10
  onNoAuthParams?: () => void;
12
11
  }
13
- interface UseAuthCallbackResult {
12
+ export interface UseAuthCallbackResult {
14
13
  status: AuthCallbackStatus;
15
14
  error: string | null;
16
15
  isLoading: boolean;
@@ -18,10 +17,8 @@ interface UseAuthCallbackResult {
18
17
  isError: boolean;
19
18
  retry: () => Promise<void>;
20
19
  }
21
- declare function useAuthCallback(options?: UseAuthCallbackOptions): UseAuthCallbackResult;
22
- //#endregion
23
- //#region src/react/HerculesAuthProvider.d.ts
24
- type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
20
+ export declare function useAuthCallback(options?: UseAuthCallbackOptions): UseAuthCallbackResult;
21
+ export type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
25
22
  userManagerSettings?: Partial<UserManagerSettings>;
26
23
  authority: string;
27
24
  client_id: string;
@@ -32,33 +29,20 @@ interface HerculesAuthProviderContext {
32
29
  impersonationStorageKey: string;
33
30
  }
34
31
  declare const HerculesAuthProviderContext: import("react").Context<HerculesAuthProviderContext | null>;
35
- declare function useHerculesAuthProvider(): HerculesAuthProviderContext;
36
- declare function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback, ...props }: HerculesAuthProviderProps): import("react").JSX.Element;
37
- //#endregion
38
- //#region src/react/impersonation-core.d.ts
39
- declare const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
40
- declare const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
41
- declare function getHerculesImpersonationStorageKey(authority: string, clientId: string): string;
42
- declare function rememberHerculesImpersonationSession(storageKey: string, sessionId: string): void;
43
- //#endregion
44
- //#region src/react/impersonation.d.ts
45
- type HerculesImpersonationState = {
32
+ export declare function useHerculesAuthProvider(): HerculesAuthProviderContext;
33
+ export declare function HerculesAuthProvider({ children, userManagerSettings, authority, client_id, loadingFallback, ...props }: HerculesAuthProviderProps): import("react").JSX.Element;
34
+ export declare const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
35
+ export declare const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
36
+ export declare function getHerculesImpersonationStorageKey(authority: string, clientId: string): string;
37
+ export declare function rememberHerculesImpersonationSession(storageKey: string, sessionId: string): void;
38
+ export type HerculesImpersonationState = {
46
39
  isImpersonating: boolean;
47
40
  sessionId: string | null;
48
41
  actorSub: string | null;
49
42
  stopImpersonating: () => Promise<void>;
50
43
  };
51
- declare function useHerculesImpersonation(): HerculesImpersonationState;
52
- //#endregion
53
- //#region src/react/use-user.d.ts
54
- declare function useUser(): {
55
- id: string | undefined;
56
- name: string | undefined;
57
- email: string | undefined;
58
- avatar: string | undefined;
59
- isAuthenticated: boolean;
60
- isLoading: boolean;
61
- error: import("react-oidc-context").ErrorContext | undefined;
44
+ export declare function useHerculesImpersonation(): HerculesImpersonationState;
45
+ export declare function useUser(): {
62
46
  id_token?: string;
63
47
  session_state?: string | null | undefined;
64
48
  access_token?: string | undefined;
@@ -69,17 +53,21 @@ declare function useUser(): {
69
53
  expires_at?: number;
70
54
  state?: unknown;
71
55
  url_state?: string;
56
+ id: string | undefined;
57
+ name: string | undefined;
58
+ email: string | undefined;
59
+ avatar: string | undefined;
60
+ isAuthenticated: boolean;
61
+ isLoading: boolean;
62
+ error: import("react-oidc-context").ErrorContext | undefined;
72
63
  };
73
- //#endregion
74
- //#region src/react/use-auth.d.ts
75
- interface SigninOptions {
64
+ export interface SigninOptions {
76
65
  returnTo?: string;
77
66
  }
78
- interface AuthContextProps extends AuthContextProps$1 {
67
+ export interface AuthContextProps extends AuthContextProps$1 {
79
68
  signout: () => Promise<void>;
80
69
  signin: (options?: SigninOptions) => Promise<void>;
81
70
  }
82
- declare function useAuth(): AuthContextProps;
83
- //#endregion
84
- export { AuthCallbackStatus, AuthContextProps, HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, HerculesAuthProviderProps, HerculesImpersonationState, SigninOptions, UseAuthCallbackOptions, UseAuthCallbackResult, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
71
+ export declare function useAuth(): AuthContextProps;
72
+ export { hasAuthParams };
85
73
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation-core.ts","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"mappings":";;;;KAsCY;UAWK;EAKf;EAMA;EAOA,eAAe;EAMf;EAOA;;UAOe;EAEf,QAAQ;EAGR;EAGA;EAGA;EAGA;EAGA,aAAa;;iBAoCC,gBAAgB,UAAS,yBAA8B;;;KCjH3D,4BAA4B,KAAK;EAC3C,sBAAsB,QAAQ;EAC9B;EACA;EACA,kBAAkB;;UAgBV;EACR,aAAa;EACb;;cAGI,6CAA2B,QAAA;iBAEjB,2BAAuB;iBAgIvB,uBACd,UACA,qBACA,WACA,WACA,oBACG,SACF,4CAAyB,IAAA;;;cC3Lf;cACA;iBAOG,mCAAmC,mBAAmB;iBAItD,qCAAqC,oBAAoB;;;KCE7D;EACV;EACA;EACA;EACA,yBAAyB;;iBAGX,4BAA4B;;;iBCb5B;;;;;;;;;;;;;;;;;;;;;UCHC;EAOf;;UAGe,yBAAyB;EACxC,eAAe;EACf,SAAS,UAAU,kBAAkB;;iBAGvB,WAAW"}
1
+ {"version":3,"file":"index.d.mts","names":["OidcAuthContextProps"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation-core.ts","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"mappings":";;;YAyCY;iBAWK;EAMf;EAMA;EAOA,eAAe;EAMf;EAOA;;iBAOe;EAEf,QAAQ;EAGR;EAGA;EAGA;EAGA;EAGA,aAAa;;wBAoCC,gBAAgB,UAAS,yBAA8B;YCrH3D,4BAA4B,KAAK;EAC3C,sBAAsB,QAAQ;EAC9B;EACA;EACA,kBAAkB;;UAgBV;EACR,aAAa;EACb;;cAGI,6CAA2B,QAAA;wBAEjB,2BAAuB;wBAgIvB,uBACd,UACA,qBACA,WACA,WACA,oBACG,SACF,4CAAyB,IAAA;qBC3Lf;qBACA;wBAOG,mCAAmC,mBAAmB;wBAItD,qCAAqC,oBAAoB;YCE7D;EACV;EACA;EACA;EACA,yBAAyB;;wBAGX,4BAA4B;wBCb5B;;;;;;;;;;;;;;;;;;;iBCHC;EAOf;;iBAGe,yBAAyBA;EACxC,eAAe;EACf,SAAS,UAAU,kBAAkB;;wBAGvB,WAAW"}
@@ -1,4 +1,4 @@
1
- import { t as withRefreshLock } from "../refresh-lock-Cv63qcNd.mjs";
1
+ import { t as withRefreshLock } from "../refresh-lock-RJUGj8im.mjs";
2
2
  import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
3
3
  import { AuthProvider, hasAuthParams, hasAuthParams as hasAuthParams$1, useAuth as useAuth$1 } from "react-oidc-context";
4
4
  import { ConvexError } from "convex/values";
@@ -6,8 +6,9 @@ import * as z from "zod";
6
6
  import { InMemoryWebStorage, UserManager, WebStorageStateStore } from "oidc-client-ts";
7
7
  import { jwtDecode } from "jwt-decode";
8
8
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
- //#region src/react/auth-callback-hook.tsx
9
+ // src/react/auth-callback-hook.tsx
10
10
  const DEFAULT_TIMEOUT_MS = 2e4;
11
+ const MIN_TIMEOUT_AFTER_TOKENS_MS = 6e4;
11
12
  const MISSING_STATE_MESSAGE = "No matching state found in storage";
12
13
  const MISSING_STATE_RETRY_KEY = "hercules-auth:missing-state-retry";
13
14
  const convexErrorSchema = z.object({ message: z.string() });
@@ -82,7 +83,7 @@ function useAuthCallback(options = {}) {
82
83
  setStatus("error");
83
84
  setError("Authentication timed out. Please try again.");
84
85
  }
85
- }, timeoutMs);
86
+ }, status === "processing-oauth" ? timeoutMs : Math.max(timeoutMs, MIN_TIMEOUT_AFTER_TOKENS_MS));
86
87
  return () => clearTimeout(timeout);
87
88
  }, [status, timeoutMs]);
88
89
  useEffect(() => {
@@ -174,8 +175,7 @@ function useAuthCallback(options = {}) {
174
175
  retry
175
176
  };
176
177
  }
177
- //#endregion
178
- //#region src/internal/user-manager.ts
178
+ // src/internal/user-manager.ts
179
179
  function logoutRedirectUrl(requestUrl, clientId) {
180
180
  const url = new URL(requestUrl);
181
181
  const hints = url.searchParams.getAll("id_token_hint");
@@ -227,8 +227,7 @@ var HerculesUserManager = class extends UserManager {
227
227
  });
228
228
  }
229
229
  };
230
- //#endregion
231
- //#region src/react/impersonation-core.ts
230
+ // src/react/impersonation-core.ts
232
231
  const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
233
232
  const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
234
233
  function getHerculesImpersonationStorageKey(authority, clientId) {
@@ -246,8 +245,7 @@ function clearHerculesImpersonationParamsFromUrl(url) {
246
245
  url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);
247
246
  return url;
248
247
  }
249
- //#endregion
250
- //#region src/react/HerculesAuthProvider.tsx
248
+ // src/react/HerculesAuthProvider.tsx
251
249
  const RECOVERY_TIMEOUT_MS = 1e4;
252
250
  function onSigninCallback() {
253
251
  window.history.replaceState({}, document.title, window.location.pathname);
@@ -372,26 +370,31 @@ function HerculesAuthProvider({ children, userManagerSettings, authority, client
372
370
  const [{ userManager, impersonationStorageKey }] = useState(() => {
373
371
  const effectiveAuthority = userManagerSettings?.authority ?? authority;
374
372
  const effectiveClientId = userManagerSettings?.client_id ?? client_id;
373
+ const userManager = new HerculesUserManager({
374
+ ...userManagerSettings,
375
+ authority: effectiveAuthority,
376
+ client_id: effectiveClientId,
377
+ prompt: userManagerSettings?.prompt ?? "select_account",
378
+ response_type: userManagerSettings?.response_type ?? "code",
379
+ scope: userManagerSettings?.scope ?? "openid profile email offline_access",
380
+ redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
381
+ post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
382
+ userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
383
+ stateStore: userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
384
+ automaticSilentRenew: false,
385
+ silentRequestTimeoutInSeconds: userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1e3
386
+ });
387
+ Object.assign(userManager.settings, { automaticSilentRenew: automaticSilentRenewExplicit });
375
388
  return {
376
- userManager: new HerculesUserManager({
377
- ...userManagerSettings,
378
- authority: effectiveAuthority,
379
- client_id: effectiveClientId,
380
- prompt: userManagerSettings?.prompt ?? "select_account",
381
- response_type: userManagerSettings?.response_type ?? "code",
382
- scope: userManagerSettings?.scope ?? "openid profile email offline_access",
383
- redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
384
- post_logout_redirect_uri: userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
385
- userStore: userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
386
- stateStore: userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
387
- automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
388
- silentRequestTimeoutInSeconds: userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1e3
389
- }),
389
+ userManager,
390
390
  impersonationStorageKey: getHerculesImpersonationStorageKey(effectiveAuthority, effectiveClientId)
391
391
  };
392
392
  });
393
393
  useEffect(() => {
394
- if (automaticSilentRenewExplicit) return;
394
+ if (automaticSilentRenewExplicit) {
395
+ userManager.startSilentRenew();
396
+ return () => userManager.stopSilentRenew();
397
+ }
395
398
  let retryTimerId = null;
396
399
  let timeoutRetryCount = 0;
397
400
  let stopped = false;
@@ -481,8 +484,7 @@ function hasCompleteImpersonationHandoff() {
481
484
  const params = new URL(window.location.href).searchParams;
482
485
  return params.has("hercules_impersonation_session_id") && params.has("hercules_impersonation_token");
483
486
  }
484
- //#endregion
485
- //#region src/react/impersonation.ts
487
+ // src/react/impersonation.ts
486
488
  function useHerculesImpersonation() {
487
489
  const { userManager, impersonationStorageKey } = useHerculesAuthProvider();
488
490
  const auth = useAuth$1();
@@ -538,8 +540,7 @@ function readStoredImpersonationSessionId(storageKey) {
538
540
  return null;
539
541
  }
540
542
  }
541
- //#endregion
542
- //#region src/react/use-user.ts
543
+ // src/react/use-user.ts
543
544
  /**
544
545
  * A hook that returns the current user if authenticated
545
546
  *
@@ -569,8 +570,7 @@ function useUser() {
569
570
  error
570
571
  ]);
571
572
  }
572
- //#endregion
573
- //#region src/react/use-auth.ts
573
+ // src/react/use-auth.ts
574
574
  function useAuth() {
575
575
  const { userManager } = useHerculesAuthProvider();
576
576
  const auth = useAuth$1();
@@ -599,7 +599,6 @@ function useAuth() {
599
599
  signin
600
600
  ]);
601
601
  }
602
- //#endregion
603
602
  export { HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
604
603
 
605
604
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","useAuth","ReactAuthProvider","useOidcAuth","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/internal/user-manager.ts","../../src/react/impersonation-core.ts","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams, type ErrorContext } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\nconst MISSING_STATE_MESSAGE = \"No matching state found in storage\";\nconst MISSING_STATE_RETRY_KEY = \"hercules-auth:missing-state-retry\";\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\nfunction claimMissingStateRetry(error: ErrorContext): boolean {\n if (error.source !== \"signinCallback\" || error.message !== MISSING_STATE_MESSAGE) return false;\n\n const url = new URL(window.location.href);\n if (!url.searchParams.has(\"code\")) return false;\n\n try {\n if (window.sessionStorage.getItem(MISSING_STATE_RETRY_KEY) !== null) return false;\n window.sessionStorage.setItem(MISSING_STATE_RETRY_KEY, \"1\");\n } catch {\n return false;\n }\n\n url.searchParams.delete(\"code\");\n url.searchParams.delete(\"state\");\n window.history.replaceState({}, document.title, url.toString());\n return true;\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(options: UseAuthCallbackOptions = {}): 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 const missingStateRetryError = useRef<ErrorContext | null>(null);\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 if (oidcError === missingStateRetryError.current) return;\n if (claimMissingStateRetry(oidcError)) {\n missingStateRetryError.current = oidcError;\n void signinRedirect();\n return;\n }\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 (!isAuthLoading && isOidcAuthenticated && status === \"processing-oauth\") {\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, signinRedirect]);\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","import { jwtDecode } from \"jwt-decode\";\nimport {\n UserManager,\n type CreateSignoutRequestArgs,\n type IWindow,\n type NavigateResponse,\n} from \"oidc-client-ts\";\n\nfunction logoutRedirectUrl(requestUrl: string, clientId: string): string {\n const url = new URL(requestUrl);\n const hints = url.searchParams.getAll(\"id_token_hint\");\n const idToken = hints[0];\n if (!idToken || hints.length !== 1) return requestUrl;\n\n let sessionId: unknown;\n try {\n sessionId = jwtDecode<{ sid?: unknown }>(idToken).sid;\n } catch {\n return requestUrl;\n }\n if (typeof sessionId === \"string\" && sessionId.length > 0) return requestUrl;\n\n const clients = url.searchParams.getAll(\"client_id\");\n if (clients.length > 1 || (clients.length === 1 && clients[0] !== clientId)) return requestUrl;\n\n url.searchParams.delete(\"id_token_hint\");\n url.searchParams.set(\"client_id\", clientId);\n return url.toString();\n}\n\nconst END_SESSION_TIMEOUT_MS = 5000;\n\nfunction isFramed(): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n\nasync function endSessionInBackground(url: string): Promise<NavigateResponse> {\n await fetch(url, {\n mode: \"no-cors\",\n credentials: \"omit\",\n signal: AbortSignal.timeout(END_SESSION_TIMEOUT_MS),\n }).catch(() => undefined);\n return { url };\n}\n\nexport class HerculesUserManager extends UserManager {\n // Transform after UserManager's revocation and single storage removal, inside its navigator action.\n protected override _signoutStart(\n args: CreateSignoutRequestArgs = {},\n handle: IWindow,\n ): Promise<NavigateResponse> {\n if (args.request_type !== \"so:r\") return super._signoutStart(args, handle);\n\n return super._signoutStart(args, {\n close: () => handle.close(),\n navigate: (params) => {\n const url = logoutRedirectUrl(params.url, this.settings.client_id);\n if (this.settings.redirectTarget !== \"top\" && isFramed()) {\n return endSessionInBackground(url);\n }\n return handle.navigate({ ...params, url });\n },\n });\n }\n}\n","\"use client\";\n\nexport const HERCULES_IMPERSONATION_SESSION_ID_PARAM = \"hercules_impersonation_session_id\";\nexport const HERCULES_IMPERSONATION_TOKEN_PARAM = \"hercules_impersonation_token\";\n\nexport type StoredHerculesImpersonation = {\n sessionId: string;\n startedAt: string;\n};\n\nexport function getHerculesImpersonationStorageKey(authority: string, clientId: string) {\n return `hercules.impersonation.${authority}.${clientId}`;\n}\n\nexport function rememberHerculesImpersonationSession(storageKey: string, sessionId: string) {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(\n storageKey,\n JSON.stringify({ sessionId, startedAt: new Date().toISOString() }),\n );\n}\n\nexport function clearHerculesImpersonationParamsFromUrl(url: URL) {\n url.searchParams.delete(HERCULES_IMPERSONATION_SESSION_ID_PARAM);\n url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);\n return url;\n}\n","\"use client\";\n\nimport { createContext, useContext, useEffect, useRef, useState, type ReactNode } from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n useAuth,\n} from \"react-oidc-context\";\nimport {\n InMemoryWebStorage,\n WebStorageStateStore,\n type UserManager,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\nimport { HerculesUserManager } from \"../internal/user-manager\";\nimport {\n clearHerculesImpersonationParamsFromUrl,\n getHerculesImpersonationStorageKey,\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n rememberHerculesImpersonationSession,\n} from \"./impersonation-core\";\n\nconst RECOVERY_TIMEOUT_MS = 10_000;\nconst LOCK_GRACE_MS = 5_000;\n\nexport type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, \"userManager\"> & {\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 impersonationStorageKey: string;\n}\n\nconst HerculesAuthProviderContext = 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 * Browsers that deny storage to a frame, such as a third-party iframe with\n * third-party cookies blocked, throw `SecurityError` from the `localStorage`\n * getter. Firefox still allows `sessionStorage` there, which keeps the OIDC\n * state across the sign-in redirect. Memory is the last resort: the app\n * renders, but a redirect sign-in cannot complete in that frame. The state\n * store needs this too: the oidc-client-ts default reads `localStorage`.\n */\nfunction getAuthStorage(): Storage {\n try {\n return window.localStorage;\n } catch {\n try {\n return window.sessionStorage;\n } catch {\n return new InMemoryWebStorage();\n }\n }\n}\n\nfunction DefaultLoadingFallback() {\n return (\n <div\n role=\"status\"\n aria-label=\"Loading\"\n style={{\n position: \"fixed\",\n inset: 0,\n display: \"grid\",\n placeItems: \"center\",\n pointerEvents: \"none\",\n }}\n >\n <svg\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n aria-hidden=\"true\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" opacity=\"0.25\" />\n <path d=\"M22 12a10 10 0 0 0-10-10\" strokeLinecap=\"round\">\n <animateTransform\n attributeName=\"transform\"\n type=\"rotate\"\n from=\"0 12 12\"\n to=\"360 12 12\"\n dur=\"0.8s\"\n repeatCount=\"indefinite\"\n />\n </path>\n </svg>\n </div>\n );\n}\n\nfunction AuthRecoveryGate({\n children,\n loadingFallback,\n skipRecovery,\n}: {\n children: ReactNode;\n loadingFallback: ReactNode;\n skipRecovery: boolean;\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 (skipRecovery) {\n hasAttempted.current = true;\n setRecoveryDone(true);\n return;\n }\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) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS)),\n ]);\n }).finally(finish);\n }, [isLoading, skipRecovery, userExpired]);\n\n const shouldBlock = !skipRecovery && (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 = <DefaultLoadingFallback />,\n ...props\n}: HerculesAuthProviderProps) {\n const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;\n const [{ userManager, impersonationStorageKey }] = useState(() => {\n const effectiveAuthority = userManagerSettings?.authority ?? authority;\n const effectiveClientId = userManagerSettings?.client_id ?? client_id;\n\n return {\n userManager: new HerculesUserManager({\n ...userManagerSettings,\n authority: effectiveAuthority,\n client_id: effectiveClientId,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope: userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,\n userStore:\n userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),\n stateStore:\n userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),\n automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,\n silentRequestTimeoutInSeconds:\n userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,\n }),\n impersonationStorageKey: getHerculesImpersonationStorageKey(\n effectiveAuthority,\n effectiveClientId,\n ),\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 = 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, impersonationStorageKey }}>\n <ReactAuthProvider userManager={userManager} {...DEFAULT_AUTH_CONFIG} {...props}>\n <HerculesImpersonationHandoff storageKey={impersonationStorageKey} />\n <AuthRecoveryGate\n loadingFallback={loadingFallback}\n skipRecovery={hasCompleteImpersonationHandoff()}\n >\n {children}\n </AuthRecoveryGate>\n </ReactAuthProvider>\n </HerculesAuthProviderContext.Provider>\n );\n}\n\nfunction HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {\n const auth = useAuth();\n const hasStartedRef = useRef(false);\n\n useEffect(() => {\n if (hasStartedRef.current || typeof window === \"undefined\") return;\n\n const url = new URL(window.location.href);\n const impersonationSessionId = url.searchParams.get(HERCULES_IMPERSONATION_SESSION_ID_PARAM);\n const impersonationToken = url.searchParams.get(HERCULES_IMPERSONATION_TOKEN_PARAM);\n if (!impersonationSessionId && !impersonationToken) return;\n if (!impersonationSessionId || !impersonationToken) {\n window.history.replaceState(\n {},\n document.title,\n clearHerculesImpersonationParamsFromUrl(url).toString(),\n );\n return;\n }\n if (auth.isLoading) return;\n\n hasStartedRef.current = true;\n rememberHerculesImpersonationSession(storageKey, impersonationSessionId);\n window.history.replaceState(\n {},\n document.title,\n clearHerculesImpersonationParamsFromUrl(url).toString(),\n );\n\n void (async () => {\n if (auth.isAuthenticated) {\n await auth.removeUser();\n }\n\n await auth.signinRedirect({\n extraQueryParams: {\n [HERCULES_IMPERSONATION_SESSION_ID_PARAM]: impersonationSessionId,\n [HERCULES_IMPERSONATION_TOKEN_PARAM]: impersonationToken,\n },\n });\n })();\n }, [auth, storageKey]);\n\n return null;\n}\n\nfunction hasCompleteImpersonationHandoff(): boolean {\n if (typeof window === \"undefined\") return false;\n\n const params = new URL(window.location.href).searchParams;\n return (\n params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) &&\n params.has(HERCULES_IMPERSONATION_TOKEN_PARAM)\n );\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useAuth as useOidcAuth } from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport {\n rememberHerculesImpersonationSession,\n type StoredHerculesImpersonation,\n} from \"./impersonation-core\";\nexport {\n getHerculesImpersonationStorageKey,\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n rememberHerculesImpersonationSession,\n} from \"./impersonation-core\";\n\nexport type HerculesImpersonationState = {\n isImpersonating: boolean;\n sessionId: string | null;\n actorSub: string | null;\n stopImpersonating: () => Promise<void>;\n};\n\nexport function useHerculesImpersonation(): HerculesImpersonationState {\n const { userManager, impersonationStorageKey } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n const [storedSessionId, setStoredSessionId] = useState<string | null>(() =>\n readStoredImpersonationSessionId(impersonationStorageKey),\n );\n\n const profile = (auth.user?.profile ?? {}) as Record<string, unknown>;\n const profileSessionId =\n typeof profile.hercules_impersonation_session_id === \"string\"\n ? profile.hercules_impersonation_session_id\n : null;\n const actorSub =\n typeof profile.hercules_actor_sub === \"string\" ? profile.hercules_actor_sub : null;\n const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;\n\n useEffect(() => {\n if (!auth.isAuthenticated) return;\n\n if (profileSessionId) {\n rememberHerculesImpersonationSession(impersonationStorageKey, profileSessionId);\n setStoredSessionId(profileSessionId);\n return;\n }\n\n if (typeof window !== \"undefined\") {\n window.localStorage.removeItem(impersonationStorageKey);\n }\n setStoredSessionId(null);\n }, [auth.isAuthenticated, impersonationStorageKey, profileSessionId]);\n\n const stopImpersonating = useCallback(async () => {\n if (typeof window !== \"undefined\") {\n window.localStorage.removeItem(impersonationStorageKey);\n }\n setStoredSessionId(null);\n\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await auth.signoutRedirect();\n } else {\n await auth.removeUser();\n }\n }, [auth, impersonationStorageKey, userManager]);\n\n return useMemo(\n () => ({\n isImpersonating: auth.isAuthenticated && sessionId != null,\n sessionId,\n actorSub,\n stopImpersonating,\n }),\n [actorSub, auth.isAuthenticated, sessionId, stopImpersonating],\n );\n}\n\nfunction readStoredImpersonationSessionId(storageKey: string) {\n if (typeof window === \"undefined\") return null;\n\n try {\n const stored = window.localStorage.getItem(storageKey);\n if (!stored) return null;\n const parsed = JSON.parse(stored) as Partial<StoredHerculesImpersonation>;\n return typeof parsed.sessionId === \"string\" ? parsed.sessionId : null;\n } catch {\n return null;\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 SigninOptions {\n /**\n * In-app path to land on after sign-in (e.g. \"/projects/42\"). Round-tripped\n * through the OIDC `state` value and surfaced on `auth.user.state` as\n * `{ returnTo }` for the callback page to honor. Defaults to the current\n * URL (path + query + hash) so sign-in returns users to where they were.\n */\n returnTo?: string;\n}\n\nexport interface AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: (options?: SigninOptions) => 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(\n async (options?: SigninOptions) => {\n const returnTo =\n options?.returnTo ??\n window.location.pathname + window.location.search + window.location.hash;\n await signinRedirect({ state: { returnTo } });\n },\n [signinRedirect],\n );\n\n return useMemo(() => {\n return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WAAW,OAAO,oBAAoBC,UAAQ;CAE5D,OAAO,cAAc;EACnB,MAAM,KAAK,MAAM,QAAQ;EACzB,MAAM,OAAO,MAAM,QAAQ;EAC3B,MAAM,QAAQ,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,QAAQ;EAC7B,OAAO;GACL,GAAI,QAAQ,CAAC;GACb;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF,GAAG;EAAC;EAAM;EAAiB;EAAW;CAAK,CAAC;AAC9C;;;ACPA,SAAgB,UAA4B;CAC1C,MAAM,EAAE,gBAAgB,wBAAwB;CAChD,MAAM,OAAOC,UAAY;CAEzB,MAAM,EAAE,iBAAiB,YAAY,mBAAmB;CACxD,MAAM,UAAU,YAAY,YAAY;EAEtC,IAAI,MADmB,YAAY,gBAAgB,sBAAsB,KACzD,MACd,MAAM,gBAAgB;OAEtB,MAAM,WAAW;CAErB,GAAG;EAAC;EAAa;EAAiB;CAAU,CAAC;CAE7C,MAAM,SAAS,YACb,OAAO,YAA4B;EACjC,MAAM,WACJ,SAAS,YACT,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;EACtE,MAAM,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC9C,GACA,CAAC,cAAc,CACjB;CAEA,OAAO,cAAc;EACnB,OAAO;GACL,GAAG;GACH;GACA;EACF;CACF,GAAG;EAAC;EAAM;EAAS;CAAM,CAAC;AAC5B"}
1
+ {"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","useAuth","ReactAuthProvider","useOidcAuth","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../src/internal/user-manager.ts","../../src/react/impersonation-core.ts","../../src/react/HerculesAuthProvider.tsx","../../src/react/impersonation.ts","../../src/react/use-user.ts","../../src/react/use-auth.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState, useRef, useCallback } from \"react\";\nimport { useAuth, hasAuthParams, type ErrorContext } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n// Once the tokens are saved, the backend confirming them (such as a Convex\n// WebSocket on Safari) can take longer than the token exchange.\nconst MIN_TIMEOUT_AFTER_TOKENS_MS = 60_000;\nconst MISSING_STATE_MESSAGE = \"No matching state found in storage\";\nconst MISSING_STATE_RETRY_KEY = \"hercules-auth:missing-state-retry\";\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\nfunction claimMissingStateRetry(error: ErrorContext): boolean {\n if (error.source !== \"signinCallback\" || error.message !== MISSING_STATE_MESSAGE) return false;\n\n const url = new URL(window.location.href);\n if (!url.searchParams.has(\"code\")) return false;\n\n try {\n if (window.sessionStorage.getItem(MISSING_STATE_RETRY_KEY) !== null) return false;\n window.sessionStorage.setItem(MISSING_STATE_RETRY_KEY, \"1\");\n } catch {\n return false;\n }\n\n url.searchParams.delete(\"code\");\n url.searchParams.delete(\"state\");\n window.history.replaceState({}, document.title, url.toString());\n return true;\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 for each step of the callback. Once the tokens are\n * saved, the backend and sync steps each get at least 60 seconds.\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(options: UseAuthCallbackOptions = {}): 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 const missingStateRetryError = useRef<ErrorContext | null>(null);\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 stepTimeoutMs =\n status === \"processing-oauth\" ? timeoutMs : Math.max(timeoutMs, MIN_TIMEOUT_AFTER_TOKENS_MS);\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, stepTimeoutMs);\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 if (oidcError === missingStateRetryError.current) return;\n if (claimMissingStateRetry(oidcError)) {\n missingStateRetryError.current = oidcError;\n void signinRedirect();\n return;\n }\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 (!isAuthLoading && isOidcAuthenticated && status === \"processing-oauth\") {\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, signinRedirect]);\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","import { jwtDecode } from \"jwt-decode\";\nimport {\n UserManager,\n type CreateSignoutRequestArgs,\n type IWindow,\n type NavigateResponse,\n} from \"oidc-client-ts\";\n\nfunction logoutRedirectUrl(requestUrl: string, clientId: string): string {\n const url = new URL(requestUrl);\n const hints = url.searchParams.getAll(\"id_token_hint\");\n const idToken = hints[0];\n if (!idToken || hints.length !== 1) return requestUrl;\n\n let sessionId: unknown;\n try {\n sessionId = jwtDecode<{ sid?: unknown }>(idToken).sid;\n } catch {\n return requestUrl;\n }\n if (typeof sessionId === \"string\" && sessionId.length > 0) return requestUrl;\n\n const clients = url.searchParams.getAll(\"client_id\");\n if (clients.length > 1 || (clients.length === 1 && clients[0] !== clientId)) return requestUrl;\n\n url.searchParams.delete(\"id_token_hint\");\n url.searchParams.set(\"client_id\", clientId);\n return url.toString();\n}\n\nconst END_SESSION_TIMEOUT_MS = 5000;\n\nfunction isFramed(): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n\nasync function endSessionInBackground(url: string): Promise<NavigateResponse> {\n await fetch(url, {\n mode: \"no-cors\",\n credentials: \"omit\",\n signal: AbortSignal.timeout(END_SESSION_TIMEOUT_MS),\n }).catch(() => undefined);\n return { url };\n}\n\nexport class HerculesUserManager extends UserManager {\n // Transform after UserManager's revocation and single storage removal, inside its navigator action.\n protected override _signoutStart(\n args: CreateSignoutRequestArgs = {},\n handle: IWindow,\n ): Promise<NavigateResponse> {\n if (args.request_type !== \"so:r\") return super._signoutStart(args, handle);\n\n return super._signoutStart(args, {\n close: () => handle.close(),\n navigate: (params) => {\n const url = logoutRedirectUrl(params.url, this.settings.client_id);\n if (this.settings.redirectTarget !== \"top\" && isFramed()) {\n return endSessionInBackground(url);\n }\n return handle.navigate({ ...params, url });\n },\n });\n }\n}\n","\"use client\";\n\nexport const HERCULES_IMPERSONATION_SESSION_ID_PARAM = \"hercules_impersonation_session_id\";\nexport const HERCULES_IMPERSONATION_TOKEN_PARAM = \"hercules_impersonation_token\";\n\nexport type StoredHerculesImpersonation = {\n sessionId: string;\n startedAt: string;\n};\n\nexport function getHerculesImpersonationStorageKey(authority: string, clientId: string) {\n return `hercules.impersonation.${authority}.${clientId}`;\n}\n\nexport function rememberHerculesImpersonationSession(storageKey: string, sessionId: string) {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(\n storageKey,\n JSON.stringify({ sessionId, startedAt: new Date().toISOString() }),\n );\n}\n\nexport function clearHerculesImpersonationParamsFromUrl(url: URL) {\n url.searchParams.delete(HERCULES_IMPERSONATION_SESSION_ID_PARAM);\n url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);\n return url;\n}\n","\"use client\";\n\nimport { createContext, useContext, useEffect, useRef, useState, type ReactNode } from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n useAuth,\n} from \"react-oidc-context\";\nimport {\n InMemoryWebStorage,\n WebStorageStateStore,\n type UserManager,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\nimport { HerculesUserManager } from \"../internal/user-manager\";\nimport {\n clearHerculesImpersonationParamsFromUrl,\n getHerculesImpersonationStorageKey,\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n rememberHerculesImpersonationSession,\n} from \"./impersonation-core\";\n\nconst RECOVERY_TIMEOUT_MS = 10_000;\nconst LOCK_GRACE_MS = 5_000;\n\nexport type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, \"userManager\"> & {\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 impersonationStorageKey: string;\n}\n\nconst HerculesAuthProviderContext = 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 * Browsers that deny storage to a frame, such as a third-party iframe with\n * third-party cookies blocked, throw `SecurityError` from the `localStorage`\n * getter. Firefox still allows `sessionStorage` there, which keeps the OIDC\n * state across the sign-in redirect. Memory is the last resort: the app\n * renders, but a redirect sign-in cannot complete in that frame. The state\n * store needs this too: the oidc-client-ts default reads `localStorage`.\n */\nfunction getAuthStorage(): Storage {\n try {\n return window.localStorage;\n } catch {\n try {\n return window.sessionStorage;\n } catch {\n return new InMemoryWebStorage();\n }\n }\n}\n\nfunction DefaultLoadingFallback() {\n return (\n <div\n role=\"status\"\n aria-label=\"Loading\"\n style={{\n position: \"fixed\",\n inset: 0,\n display: \"grid\",\n placeItems: \"center\",\n pointerEvents: \"none\",\n }}\n >\n <svg\n width=\"32\"\n height=\"32\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2.5\"\n aria-hidden=\"true\"\n >\n <circle cx=\"12\" cy=\"12\" r=\"10\" opacity=\"0.25\" />\n <path d=\"M22 12a10 10 0 0 0-10-10\" strokeLinecap=\"round\">\n <animateTransform\n attributeName=\"transform\"\n type=\"rotate\"\n from=\"0 12 12\"\n to=\"360 12 12\"\n dur=\"0.8s\"\n repeatCount=\"indefinite\"\n />\n </path>\n </svg>\n </div>\n );\n}\n\nfunction AuthRecoveryGate({\n children,\n loadingFallback,\n skipRecovery,\n}: {\n children: ReactNode;\n loadingFallback: ReactNode;\n skipRecovery: boolean;\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 (skipRecovery) {\n hasAttempted.current = true;\n setRecoveryDone(true);\n return;\n }\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) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS)),\n ]);\n }).finally(finish);\n }, [isLoading, skipRecovery, userExpired]);\n\n const shouldBlock = !skipRecovery && (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 = <DefaultLoadingFallback />,\n ...props\n}: HerculesAuthProviderProps) {\n const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;\n const [{ userManager, impersonationStorageKey }] = useState(() => {\n const effectiveAuthority = userManagerSettings?.authority ?? authority;\n const effectiveClientId = userManagerSettings?.client_id ?? client_id;\n\n const userManager = new HerculesUserManager({\n ...userManagerSettings,\n authority: effectiveAuthority,\n client_id: effectiveClientId,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope: userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri: userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,\n userStore:\n userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),\n stateStore:\n userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),\n // Started in the effect below, so a manager that React creates and\n // discards (Strict Mode runs this initializer twice) never renews.\n automaticSilentRenew: false,\n silentRequestTimeoutInSeconds:\n userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,\n });\n // Only the constructor reads this, so report the caller's value afterward.\n Object.assign(userManager.settings, { automaticSilentRenew: automaticSilentRenewExplicit });\n\n return {\n userManager,\n impersonationStorageKey: getHerculesImpersonationStorageKey(\n effectiveAuthority,\n effectiveClientId,\n ),\n };\n });\n\n useEffect(() => {\n if (automaticSilentRenewExplicit) {\n userManager.startSilentRenew();\n return () => userManager.stopSilentRenew();\n }\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 = 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, impersonationStorageKey }}>\n <ReactAuthProvider userManager={userManager} {...DEFAULT_AUTH_CONFIG} {...props}>\n <HerculesImpersonationHandoff storageKey={impersonationStorageKey} />\n <AuthRecoveryGate\n loadingFallback={loadingFallback}\n skipRecovery={hasCompleteImpersonationHandoff()}\n >\n {children}\n </AuthRecoveryGate>\n </ReactAuthProvider>\n </HerculesAuthProviderContext.Provider>\n );\n}\n\nfunction HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {\n const auth = useAuth();\n const hasStartedRef = useRef(false);\n\n useEffect(() => {\n if (hasStartedRef.current || typeof window === \"undefined\") return;\n\n const url = new URL(window.location.href);\n const impersonationSessionId = url.searchParams.get(HERCULES_IMPERSONATION_SESSION_ID_PARAM);\n const impersonationToken = url.searchParams.get(HERCULES_IMPERSONATION_TOKEN_PARAM);\n if (!impersonationSessionId && !impersonationToken) return;\n if (!impersonationSessionId || !impersonationToken) {\n window.history.replaceState(\n {},\n document.title,\n clearHerculesImpersonationParamsFromUrl(url).toString(),\n );\n return;\n }\n if (auth.isLoading) return;\n\n hasStartedRef.current = true;\n rememberHerculesImpersonationSession(storageKey, impersonationSessionId);\n window.history.replaceState(\n {},\n document.title,\n clearHerculesImpersonationParamsFromUrl(url).toString(),\n );\n\n void (async () => {\n if (auth.isAuthenticated) {\n await auth.removeUser();\n }\n\n await auth.signinRedirect({\n extraQueryParams: {\n [HERCULES_IMPERSONATION_SESSION_ID_PARAM]: impersonationSessionId,\n [HERCULES_IMPERSONATION_TOKEN_PARAM]: impersonationToken,\n },\n });\n })();\n }, [auth, storageKey]);\n\n return null;\n}\n\nfunction hasCompleteImpersonationHandoff(): boolean {\n if (typeof window === \"undefined\") return false;\n\n const params = new URL(window.location.href).searchParams;\n return (\n params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) &&\n params.has(HERCULES_IMPERSONATION_TOKEN_PARAM)\n );\n}\n","\"use client\";\n\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useAuth as useOidcAuth } from \"react-oidc-context\";\nimport { useHerculesAuthProvider } from \"./HerculesAuthProvider\";\nimport {\n rememberHerculesImpersonationSession,\n type StoredHerculesImpersonation,\n} from \"./impersonation-core\";\nexport {\n getHerculesImpersonationStorageKey,\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n rememberHerculesImpersonationSession,\n} from \"./impersonation-core\";\n\nexport type HerculesImpersonationState = {\n isImpersonating: boolean;\n sessionId: string | null;\n actorSub: string | null;\n stopImpersonating: () => Promise<void>;\n};\n\nexport function useHerculesImpersonation(): HerculesImpersonationState {\n const { userManager, impersonationStorageKey } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n const [storedSessionId, setStoredSessionId] = useState<string | null>(() =>\n readStoredImpersonationSessionId(impersonationStorageKey),\n );\n\n const profile = (auth.user?.profile ?? {}) as Record<string, unknown>;\n const profileSessionId =\n typeof profile.hercules_impersonation_session_id === \"string\"\n ? profile.hercules_impersonation_session_id\n : null;\n const actorSub =\n typeof profile.hercules_actor_sub === \"string\" ? profile.hercules_actor_sub : null;\n const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;\n\n useEffect(() => {\n if (!auth.isAuthenticated) return;\n\n if (profileSessionId) {\n rememberHerculesImpersonationSession(impersonationStorageKey, profileSessionId);\n setStoredSessionId(profileSessionId);\n return;\n }\n\n if (typeof window !== \"undefined\") {\n window.localStorage.removeItem(impersonationStorageKey);\n }\n setStoredSessionId(null);\n }, [auth.isAuthenticated, impersonationStorageKey, profileSessionId]);\n\n const stopImpersonating = useCallback(async () => {\n if (typeof window !== \"undefined\") {\n window.localStorage.removeItem(impersonationStorageKey);\n }\n setStoredSessionId(null);\n\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await auth.signoutRedirect();\n } else {\n await auth.removeUser();\n }\n }, [auth, impersonationStorageKey, userManager]);\n\n return useMemo(\n () => ({\n isImpersonating: auth.isAuthenticated && sessionId != null,\n sessionId,\n actorSub,\n stopImpersonating,\n }),\n [actorSub, auth.isAuthenticated, sessionId, stopImpersonating],\n );\n}\n\nfunction readStoredImpersonationSessionId(storageKey: string) {\n if (typeof window === \"undefined\") return null;\n\n try {\n const stored = window.localStorage.getItem(storageKey);\n if (!stored) return null;\n const parsed = JSON.parse(stored) as Partial<StoredHerculesImpersonation>;\n return typeof parsed.sessionId === \"string\" ? parsed.sessionId : null;\n } catch {\n return null;\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 SigninOptions {\n /**\n * In-app path to land on after sign-in (e.g. \"/projects/42\"). Round-tripped\n * through the OIDC `state` value and surfaced on `auth.user.state` as\n * `{ returnTo }` for the callback page to honor. Defaults to the current\n * URL (path + query + hash) so sign-in returns users to where they were.\n */\n returnTo?: string;\n}\n\nexport interface AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: (options?: SigninOptions) => 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(\n async (options?: SigninOptions) => {\n const returnTo =\n options?.returnTo ??\n window.location.pathname + window.location.search + window.location.hash;\n await signinRedirect({ state: { returnTo } });\n },\n [signinRedirect],\n );\n\n return useMemo(() => {\n return {\n ...auth,\n signout,\n signin,\n } satisfies AuthContextProps;\n }, [auth, signout,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,KAAK,MAAM,MAAM;EAChC,OAAO,OAAO,OAAO,cAAc,WAAW,OAAO,YAAY;CACnE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;AChFA,SAAgB,UAAU;CACxB,MAAM,EAAE,MAAM,WAAW,OAAO,oBAAoBC,UAAQ;CAE5D,OAAO,cAAc;EACnB,MAAM,KAAK,MAAM,QAAQ;EACzB,MAAM,OAAO,MAAM,QAAQ;EAC3B,MAAM,QAAQ,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,QAAQ;EAC7B,OAAO;GACL,GAAI,QAAQ,CAAC;GACb;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF,GAAG;EAAC;EAAM;EAAiB;EAAW;CAAK,CAAC;AAC9C;;ACPA,SAAgB,UAA4B;CAC1C,MAAM,EAAE,gBAAgB,wBAAwB;CAChD,MAAM,OAAOC,UAAY;CAEzB,MAAM,EAAE,iBAAiB,YAAY,mBAAmB;CACxD,MAAM,UAAU,YAAY,YAAY;EAEtC,IAAI,MADmB,YAAY,gBAAgB,sBAAsB,KACzD,MACd,MAAM,gBAAgB;OAEtB,MAAM,WAAW;CAErB,GAAG;EAAC;EAAa;EAAiB;CAAU,CAAC;CAE7C,MAAM,SAAS,YACb,OAAO,YAA4B;EACjC,MAAM,WACJ,SAAS,YACT,OAAO,SAAS,WAAW,OAAO,SAAS,SAAS,OAAO,SAAS;EACtE,MAAM,eAAe,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC9C,GACA,CAAC,cAAc,CACjB;CAEA,OAAO,cAAc;EACnB,OAAO;GACL,GAAG;GACH;GACA;EACF;CACF,GAAG;EAAC;EAAM;EAAS;CAAM,CAAC;AAC5B"}
@@ -1,4 +1,4 @@
1
- //#region src/internal/refresh-lock.ts
1
+ // src/internal/refresh-lock.ts
2
2
  const REFRESH_LOCK_KEY = "__herculesAuthRefresh";
3
3
  const mutexes = /* @__PURE__ */ new Map();
4
4
  async function manualMutex(key, callback) {
@@ -25,7 +25,6 @@ async function withRefreshLock(callback) {
25
25
  if (typeof navigator !== "undefined" && navigator.locks) return navigator.locks.request(REFRESH_LOCK_KEY, callback);
26
26
  return manualMutex(REFRESH_LOCK_KEY, callback);
27
27
  }
28
- //#endregion
29
28
  export { withRefreshLock as t };
30
29
 
31
- //# sourceMappingURL=refresh-lock-Cv63qcNd.mjs.map
30
+ //# sourceMappingURL=refresh-lock-RJUGj8im.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-lock-Cv63qcNd.mjs","names":[],"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>(key: string, callback: () => Promise<T>): 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>(callback: () => Promise<T>): 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,IAAmB;AAEvC,eAAe,YAAe,KAAa,UAAwC;CACjF,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,gBACJ,SAAS,CAAC,CACP,KAAK,OAAO,CAAC,CACb,MAAM,MAAM,CAAC,CACb,cAAc;GACb,MAAM,QAAQ,QAAQ,IAAI,GAAG;GAC7B,MAAM,OAAO,MAAM,QAAQ,MAAM;GACjC,IAAI,MACF,MAAM,UAAU,KAAK;QAErB,MAAM,UAAU;EAEpB,CAAC;EAEL,IAAI,QAAQ,QAAQ,IAAI,GAAG;EAC3B,IAAI,CAAC,OAAO;GACV,QAAQ;IAAE,SAAS;IAAM,SAAS,CAAC;GAAE;GACrC,QAAQ,IAAI,KAAK,KAAK;EACxB;EAEA,IAAI,MAAM,YAAY,MACpB,MAAM,UAAU,QAAQ;OAExB,MAAM,QAAQ,KAAK,OAAO;CAE9B,CAAC;AACH;AAEA,eAAsB,gBAAmB,UAAwC;CAC/E,IAAI,OAAO,cAAc,eAAe,UAAU,OAChD,OAAO,UAAU,MAAM,QAAQ,kBAAkB,QAAQ;CAE3D,OAAO,YAAY,kBAAkB,QAAQ;AAC/C"}
1
+ {"version":3,"file":"refresh-lock-RJUGj8im.mjs","names":[],"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>(key: string, callback: () => Promise<T>): 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>(callback: () => Promise<T>): 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,IAAmB;AAEvC,eAAe,YAAe,KAAa,UAAwC;CACjF,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,gBACJ,SAAS,CAAC,CACP,KAAK,OAAO,CAAC,CACb,MAAM,MAAM,CAAC,CACb,cAAc;GACb,MAAM,QAAQ,QAAQ,IAAI,GAAG;GAC7B,MAAM,OAAO,MAAM,QAAQ,MAAM;GACjC,IAAI,MACF,MAAM,UAAU,KAAK;QAErB,MAAM,UAAU;EAEpB,CAAC;EAEL,IAAI,QAAQ,QAAQ,IAAI,GAAG;EAC3B,IAAI,CAAC,OAAO;GACV,QAAQ;IAAE,SAAS;IAAM,SAAS,CAAC;GAAE;GACrC,QAAQ,IAAI,KAAK,KAAK;EACxB;EAEA,IAAI,MAAM,YAAY,MACpB,MAAM,UAAU,QAAQ;OAExB,MAAM,QAAQ,KAAK,OAAO;CAE9B,CAAC;AACH;AAEA,eAAsB,gBAAmB,UAAwC;CAC/E,IAAI,OAAO,cAAc,eAAe,UAAU,OAChD,OAAO,UAAU,MAAM,QAAQ,kBAAkB,QAAQ;CAE3D,OAAO,YAAY,kBAAkB,QAAQ;AAC/C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usehercules/auth",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "Authentication utilities for Hercules applications using OIDC",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -29,24 +29,24 @@
29
29
  "jwt-decode": "^4.0.0",
30
30
  "oidc-client-ts": "^3.5.0",
31
31
  "react-oidc-context": "^3.3.1",
32
- "zod": "^4.4.3"
32
+ "zod": "^4.6.7"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "convex": "^1.29.0",
36
36
  "react": "^18.0.0 || ^19.0.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@testing-library/jest-dom": "^6.9.1",
40
- "@testing-library/react": "^16.3.2",
41
- "@types/react": "^19.2.17",
42
- "@types/react-dom": "^19.2.3",
43
- "convex": "^1.42.1",
44
- "jsdom": "^29.1.1",
45
- "react": "^19.2.7",
46
- "react-dom": "^19.2.7",
47
- "tsdown": "^0.22.8",
48
- "typescript": "^6.0.3",
49
- "vitest": "^4.1.11"
39
+ "@testing-library/jest-dom": "^7.0.1",
40
+ "@testing-library/react": "^16.3.3",
41
+ "@types/react": "^19.3.0",
42
+ "@types/react-dom": "^19.3.0",
43
+ "convex": "^1.47.0",
44
+ "jsdom": "^30.1.3",
45
+ "react": "^19.3.1",
46
+ "react-dom": "^19.3.1",
47
+ "tsdown": "^0.23.1",
48
+ "typescript": "^7.0.2",
49
+ "vitest": "^5.0.5"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsdown",
@@ -6,7 +6,6 @@ import { jwtDecode } from "jwt-decode";
6
6
  import { useCallback, useMemo, useRef } from "react";
7
7
  import { useAuth } from "react-oidc-context";
8
8
  import { withRefreshLock } from "../internal/refresh-lock";
9
- import type { HerculesAuthProvider } from "../react/HerculesAuthProvider";
10
9
 
11
10
  const REFRESH_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour
12
11
 
@@ -79,7 +78,7 @@ function useUseAuthFromHercules() {
79
78
  * A wrapper React component which provides a {@link ConvexReactClient}
80
79
  * authenticated with Hercules Auth.
81
80
  *
82
- * It must be wrapped by a configured `{@link HerculesAuthProvider}`.
81
+ * It must be wrapped by a configured `HerculesAuthProvider`.
83
82
  *
84
83
  * @public
85
84
  */
@@ -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
- constructor() {}
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 {
@@ -193,26 +193,31 @@ export function HerculesAuthProvider({
193
193
  const effectiveAuthority = userManagerSettings?.authority ?? authority;
194
194
  const effectiveClientId = userManagerSettings?.client_id ?? client_id;
195
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
+
196
219
  return {
197
- userManager: new HerculesUserManager({
198
- ...userManagerSettings,
199
- authority: effectiveAuthority,
200
- client_id: effectiveClientId,
201
- prompt: userManagerSettings?.prompt ?? "select_account",
202
- response_type: userManagerSettings?.response_type ?? "code",
203
- scope: userManagerSettings?.scope ?? "openid profile email offline_access",
204
- redirect_uri:
205
- userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
206
- post_logout_redirect_uri:
207
- userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
208
- userStore:
209
- userManagerSettings?.userStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
210
- stateStore:
211
- userManagerSettings?.stateStore ?? new WebStorageStateStore({ store: getAuthStorage() }),
212
- automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
213
- silentRequestTimeoutInSeconds:
214
- userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
215
- }),
220
+ userManager,
216
221
  impersonationStorageKey: getHerculesImpersonationStorageKey(
217
222
  effectiveAuthority,
218
223
  effectiveClientId,
@@ -221,7 +226,10 @@ export function HerculesAuthProvider({
221
226
  });
222
227
 
223
228
  useEffect(() => {
224
- if (automaticSilentRenewExplicit) return;
229
+ if (automaticSilentRenewExplicit) {
230
+ userManager.startSilentRenew();
231
+ return () => userManager.stopSilentRenew();
232
+ }
225
233
  let retryTimerId: ReturnType<typeof setTimeout> | null = null;
226
234
  let timeoutRetryCount = 0;
227
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
 
@@ -6,6 +6,9 @@ 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;
9
12
  const MISSING_STATE_MESSAGE = "No matching state found in storage";
10
13
  const MISSING_STATE_RETRY_KEY = "hercules-auth:missing-state-retry";
11
14
 
@@ -49,7 +52,8 @@ export type AuthCallbackStatus =
49
52
  */
50
53
  export interface UseAuthCallbackOptions {
51
54
  /**
52
- * Timeout in milliseconds before the callback is considered failed.
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.
53
57
  * @default 20000
54
58
  */
55
59
  timeoutMs?: number;
@@ -178,12 +182,14 @@ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCa
178
182
  useEffect(() => {
179
183
  if (status === "success" || status === "error") return;
180
184
 
185
+ const stepTimeoutMs =
186
+ status === "processing-oauth" ? timeoutMs : Math.max(timeoutMs, MIN_TIMEOUT_AFTER_TOKENS_MS);
181
187
  const timeout = setTimeout(() => {
182
188
  if (mountedRef.current) {
183
189
  setStatus("error");
184
190
  setError("Authentication timed out. Please try again.");
185
191
  }
186
- }, timeoutMs);
192
+ }, stepTimeoutMs);
187
193
 
188
194
  return () => clearTimeout(timeout);
189
195
  }, [status, timeoutMs]);