@usehercules/auth 1.1.0 → 1.2.0

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,5 +1,4 @@
1
1
  import { ReactNode } from "react";
2
- import * as react_jsx_runtime0 from "react/jsx-runtime";
3
2
  import { ConvexReactClient } from "convex/react";
4
3
 
5
4
  //#region src/convex-react/ConvexProviderWithHercules.d.ts
@@ -9,7 +8,7 @@ declare function ConvexProviderWithHerculesAuth({
9
8
  }: {
10
9
  children: ReactNode;
11
10
  client: ConvexReactClient;
12
- }): react_jsx_runtime0.JSX.Element;
11
+ }): import("react").JSX.Element;
13
12
  //#endregion
14
13
  export { ConvexProviderWithHerculesAuth };
15
14
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":[],"mappings":";;;;;iBA2FgB,8BAAA;;;AAAhB;YAIY;UACF;AALV,CAAA,CAAA,EAMC,kBAAA,CAAA,GAAA,CAAA,OAN6C"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"mappings":";;;;iBAqFgB,8BAAA;EACd,QAAA;EACA;AAAA;EAEA,QAAA,EAAU,SAAA;EACV,MAAA,EAAQ,iBAAA;AAAA,oBACT,GAAA,CAAA,OAAA"}
@@ -1,10 +1,9 @@
1
- import { t as withRefreshLock } from "../refresh-lock-DYW9ITwj.mjs";
1
+ import { t as withRefreshLock } from "../refresh-lock-Cv63qcNd.mjs";
2
2
  import { useCallback, useMemo, useRef } from "react";
3
3
  import { useAuth } from "react-oidc-context";
4
4
  import { jsx } from "react/jsx-runtime";
5
5
  import { ConvexProviderWithAuth } from "convex/react";
6
6
  import { jwtDecode } from "jwt-decode";
7
-
8
7
  //#region src/convex-react/ConvexProviderWithHercules.tsx
9
8
  const REFRESH_THRESHOLD_MS = 3600 * 1e3;
10
9
  function tokenExpiresWithin(token, ms) {
@@ -68,7 +67,7 @@ function ConvexProviderWithHerculesAuth({ children, client }) {
68
67
  children
69
68
  });
70
69
  }
71
-
72
70
  //#endregion
73
71
  export { ConvexProviderWithHerculesAuth };
72
+
74
73
  //# 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 (\n currentToken != null &&\n !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)\n ) {\n return currentToken;\n }\n if (inFlightRefresh.current) {\n return inFlightRefresh.current;\n }\n const refresh = withRefreshLock(async () => {\n const tokenAfterLock = idTokenRef.current;\n if (\n tokenAfterLock != null &&\n !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)\n ) {\n return tokenAfterLock;\n }\n try {\n const refreshed = await signinSilentRef.current();\n return refreshed?.id_token ?? null;\n } catch {\n return null;\n }\n }).finally(() => {\n inFlightRefresh.current = null;\n });\n inFlightRefresh.current = refresh;\n return refresh;\n },\n [issuer, subject],\n );\n\n return useMemo(\n () => ({\n isLoading: isAuthenticated ? false : isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n\n/**\n * A wrapper React component which provides a {@link ConvexReactClient}\n * authenticated with Hercules Auth.\n *\n * It must be wrapped by a configured `{@link HerculesAuthProvider}`.\n *\n * @public\n */\nexport function ConvexProviderWithHerculesAuth({\n children,\n client,\n}: {\n children: ReactNode;\n client: ConvexReactClient;\n}) {\n return (\n <ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>\n {children}\n </ConvexProviderWithAuth>\n );\n}\n"],"mappings":";;;;;;;;AAUA,MAAM,uBAAuB,OAAU;AAEvC,SAAS,mBAAmB,OAAe,IAAqB;AAC9D,KAAI;AAEF,SADgB,UAAU,MAAM,CACjB,MAAO,MAAO,KAAK,KAAK,GAAG;SACpC;AACN,SAAO;;;AAIX,SAAS,yBAAyB;CAChC,MAAM,EAAE,iBAAiB,MAAM,WAAW,iBAAiB,SAAS;CACpE,MAAM,UAAU,MAAM;CACtB,MAAM,SAAS,MAAM,SAAS;CAC9B,MAAM,UAAU,MAAM,SAAS;CAE/B,MAAM,aAAa,OAAO,QAAQ;AAClC,YAAW,UAAU;CAErB,MAAM,kBAAkB,OAAO,aAAa;AAC5C,iBAAgB,UAAU;CAE1B,MAAM,kBAAkB,OAAsC,KAAK;CAEnE,MAAM,mBAAmB,YACvB,OAAO,EAAE,wBAAwD;EAC/D,MAAM,eAAe,WAAW;AAChC,MAAI,CAAC,kBACH,QAAO,gBAAgB;AAEzB,MACE,gBAAgB,QAChB,CAAC,mBAAmB,cAAc,qBAAqB,CAEvD,QAAO;AAET,MAAI,gBAAgB,QAClB,QAAO,gBAAgB;EAEzB,MAAM,UAAU,gBAAgB,YAAY;GAC1C,MAAM,iBAAiB,WAAW;AAClC,OACE,kBAAkB,QAClB,CAAC,mBAAmB,gBAAgB,qBAAqB,CAEzD,QAAO;AAET,OAAI;AAEF,YADkB,MAAM,gBAAgB,SAAS,GAC/B,YAAY;WACxB;AACN,WAAO;;IAET,CAAC,cAAc;AACf,mBAAgB,UAAU;IAC1B;AACF,kBAAgB,UAAU;AAC1B,SAAO;IAET,CAAC,QAAQ,QAAQ,CAClB;AAED,QAAO,eACE;EACL,WAAW,kBAAkB,QAAQ;EACrC;EACA;EACD,GACD;EAAC;EAAW;EAAiB;EAAiB,CAC/C;;;;;;;;;;AAWH,SAAgB,+BAA+B,EAC7C,UACA,UAIC;AACD,QACE,oBAAC;EAA+B;EAAQ,SAAS;EAC9C;GACsB"}
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,10 +1,6 @@
1
- import * as react0 from "react";
2
1
  import { ReactNode } from "react";
3
- import * as react_oidc_context0 from "react-oidc-context";
4
2
  import { AuthContextProps as AuthContextProps$1, AuthProviderUserManagerProps, hasAuthParams } from "react-oidc-context";
5
- import * as oidc_client_ts0 from "oidc-client-ts";
6
3
  import { UserManager, UserManagerSettings } from "oidc-client-ts";
7
- import * as react_jsx_runtime0 from "react/jsx-runtime";
8
4
 
9
5
  //#region src/react/auth-callback-hook.d.ts
10
6
  type AuthCallbackStatus = "processing-oauth" | "waiting-backend" | "syncing" | "success" | "error";
@@ -36,7 +32,7 @@ interface HerculesAuthProviderContext {
36
32
  userManager: UserManager;
37
33
  impersonationStorageKey: string;
38
34
  }
39
- declare const HerculesAuthProviderContext: react0.Context<HerculesAuthProviderContext | null>;
35
+ declare const HerculesAuthProviderContext: import("react").Context<HerculesAuthProviderContext | null>;
40
36
  declare function useHerculesAuthProvider(): HerculesAuthProviderContext;
41
37
  declare function HerculesAuthProvider({
42
38
  children,
@@ -45,7 +41,7 @@ declare function HerculesAuthProvider({
45
41
  client_id,
46
42
  loadingFallback,
47
43
  ...props
48
- }: HerculesAuthProviderProps): react_jsx_runtime0.JSX.Element;
44
+ }: HerculesAuthProviderProps): import("react").JSX.Element;
49
45
  //#endregion
50
46
  //#region src/react/impersonation-core.d.ts
51
47
  declare const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
@@ -70,25 +66,28 @@ declare function useUser(): {
70
66
  avatar: string | undefined;
71
67
  isAuthenticated: boolean;
72
68
  isLoading: boolean;
73
- error: react_oidc_context0.ErrorContext | undefined;
69
+ error: import("react-oidc-context").ErrorContext | undefined;
74
70
  id_token?: string;
75
71
  session_state?: string | null | undefined;
76
72
  access_token?: string | undefined;
77
73
  refresh_token?: string;
78
74
  token_type?: string | undefined;
79
75
  scope?: string;
80
- profile?: oidc_client_ts0.IdTokenClaims | undefined;
76
+ profile?: import("oidc-client-ts").IdTokenClaims | undefined;
81
77
  expires_at?: number;
82
78
  state?: unknown;
83
79
  url_state?: string;
84
80
  };
85
81
  //#endregion
86
82
  //#region src/react/use-auth.d.ts
83
+ interface SigninOptions {
84
+ returnTo?: string;
85
+ }
87
86
  interface AuthContextProps extends AuthContextProps$1 {
88
87
  signout: () => Promise<void>;
89
- signin: () => Promise<void>;
88
+ signin: (options?: SigninOptions) => Promise<void>;
90
89
  }
91
90
  declare function useAuth(): AuthContextProps;
92
91
  //#endregion
93
- export { AuthCallbackStatus, AuthContextProps, HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, HerculesAuthProviderProps, HerculesImpersonationState, UseAuthCallbackOptions, UseAuthCallbackResult, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
92
+ 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 };
94
93
  //# 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"],"sourcesContent":[],"mappings":";;;;;;;;;KAiBY,kBAAA;UAWK,sBAAA;;;iBAkBA;;;;UAoBA,qBAAA;EAjDL,MAAA,EAmDF,kBAnDoB;EAWb,KAAA,EAAA,MAAA,GAAA,IAAA;EAsCA,SAAA,EAAA,OAAA;EAqDD,SAAA,EAAA,OAAe;;eApChB;;ACnDH,iBDuFI,eAAA,CCvFqB,OAAA,CAAA,EDwF1B,sBCxF0B,CAAA,EDyFlC,qBCzFkC;;;KAAzB,yBAAA,GAA4B,KACtC;wBAGsB,QAAQ;;;oBAGZ;;ADtBpB,UCsCU,2BAAA,CDtCoB;EAWb,WAAA,EC4BF,WD5BE;EAsCA,uBAAA,EAAqB,MAAA;AAqDtC;cC3DM,6BAA2B,MAAA,CAAA,QAAA;iBAGjB,uBAAA,CAAA,GAAuB;iBA0EvB,oBAAA;;;;;;;GAOb,4BAAyB,kBAAA,CAAA,GAAA,CAAA;;;cC9If,uCAAA;cAEA,kCAAA;iBAQG,kCAAA;iBAOA,oCAAA;;;KCHJ,0BAAA;;;;2BAIe;;iBAGX,wBAAA,CAAA,GAA4B;;;iBCb5B,OAAA,CAAA;;;;;;;SAAO,mBAAA,CAAA,YAAA;;EJOX,aAAA,CAAA,EAAA,MAAkB,GAAA,IAAA,GAAA,SAAA;EAWb,YAAA,CAAA,EAAA,MAAA,GAAA,SAAsB;EAsCtB,aAAA,CAAA,EAAA,MAAA;EAqDD,UAAA,CAAA,EAAA,MAAe,GAAA,SACpB;;YI9GY,eAAA,CAAA,aAAA;;EHsBX,KAAA,CAAA,EAAA,OAAA;EACV,SAAA,CAAA,EAAA,MAAA;CADsC;;;UIzBvB,gBAAA,SAAyB;iBACzB;gBACD;;iBAGA,OAAA,CAAA,GAAW"}
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":";;;;;KAiBY,kBAAA;AAAA,UAWK,sBAAA;EAKf,SAAA;EAMA,sBAAA;EAOA,MAAA,SAAe,OAAO;EAMtB,SAAA;EAOA,cAAA;AAAA;AAAA,UAOe,qBAAA;EAEf,MAAA,EAAQ,kBAAA;EAGR,KAAA;EAGA,SAAA;EAGA,SAAA;EAGA,OAAA;EAGA,KAAA,QAAa,OAAO;AAAA;AAAA,iBAoCN,eAAA,CAAgB,OAAA,GAAS,sBAAA,GAA8B,qBAAqB;;;KClGhF,yBAAA,GAA4B,IAAA,CAAK,4BAAA;EAC3C,mBAAA,GAAsB,OAAA,CAAQ,mBAAA;EAC9B,SAAA;EACA,SAAA;EACA,eAAA,GAAkB,SAAA;AAAA;AAAA,UAgBV,2BAAA;EACR,WAAA,EAAa,WAAW;EACxB,uBAAA;AAAA;AAAA,cAGI,2BAAA,kBAA2B,OAAA,CAAA,2BAAA;AAAA,iBAEjB,uBAAA,IAAuB,2BAAA;AAAA,iBAsEvB,oBAAA;EACd,QAAA;EACA,mBAAA;EACA,SAAA;EACA,SAAA;EACA,eAAA;EAAA,GACG;AAAA,GACF,yBAAA,mBAAyB,GAAA,CAAA,OAAA;;;cC3Hf,uCAAA;AAAA,cACA,kCAAA;AAAA,iBAOG,kCAAA,CAAmC,SAAA,UAAmB,QAAgB;AAAA,iBAItE,oCAAA,CAAqC,UAAA,UAAoB,SAAiB;;;KCE9E,0BAAA;EACV,eAAA;EACA,SAAA;EACA,QAAA;EACA,iBAAA,QAAyB,OAAO;AAAA;AAAA,iBAGlB,wBAAA,IAA4B,0BAA0B;;;iBCbtD,OAAA;;;;;;;;;;;;;;;;;;;;;UCHC,aAAA;EAOf,QAAQ;AAAA;AAAA,UAGO,gBAAA,SAAyB,kBAAA;EACxC,OAAA,QAAe,OAAA;EACf,MAAA,GAAS,OAAA,GAAU,aAAA,KAAkB,OAAA;AAAA;AAAA,iBAGvB,OAAA,IAAW,gBAAgB"}
@@ -1,11 +1,10 @@
1
- import { t as withRefreshLock } from "../refresh-lock-DYW9ITwj.mjs";
1
+ import { t as withRefreshLock } from "../refresh-lock-Cv63qcNd.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";
5
5
  import * as z from "zod";
6
6
  import { UserManager, WebStorageStateStore } from "oidc-client-ts";
7
7
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
-
9
8
  //#region src/react/auth-callback-hook.tsx
10
9
  const DEFAULT_TIMEOUT_MS = 2e4;
11
10
  const convexErrorSchema = z.object({ message: z.string() });
@@ -149,7 +148,6 @@ function useAuthCallback(options = {}) {
149
148
  retry
150
149
  };
151
150
  }
152
-
153
151
  //#endregion
154
152
  //#region src/react/impersonation-core.ts
155
153
  const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
@@ -169,11 +167,9 @@ function clearHerculesImpersonationParamsFromUrl(url) {
169
167
  url.searchParams.delete(HERCULES_IMPERSONATION_TOKEN_PARAM);
170
168
  return url;
171
169
  }
172
-
173
170
  //#endregion
174
171
  //#region src/react/HerculesAuthProvider.tsx
175
172
  const RECOVERY_TIMEOUT_MS = 1e4;
176
- const LOCK_GRACE_MS = 5e3;
177
173
  function onSigninCallback() {
178
174
  window.history.replaceState({}, document.title, window.location.pathname);
179
175
  }
@@ -218,7 +214,7 @@ function AuthRecoveryGate({ children, loadingFallback, skipRecovery }) {
218
214
  };
219
215
  setTimeout(finish, RECOVERY_TIMEOUT_MS);
220
216
  withRefreshLock(async () => {
221
- await Promise.race([signinSilentRef.current().catch(() => void 0), new Promise((resolve) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS))]);
217
+ await Promise.race([signinSilentRef.current().catch(() => void 0), new Promise((resolve) => setTimeout(resolve, 15e3))]);
222
218
  }).finally(finish);
223
219
  }, [
224
220
  isLoading,
@@ -345,9 +341,8 @@ function HerculesImpersonationHandoff({ storageKey }) {
345
341
  function hasCompleteImpersonationHandoff() {
346
342
  if (typeof window === "undefined") return false;
347
343
  const params = new URL(window.location.href).searchParams;
348
- return params.has(HERCULES_IMPERSONATION_SESSION_ID_PARAM) && params.has(HERCULES_IMPERSONATION_TOKEN_PARAM);
344
+ return params.has("hercules_impersonation_session_id") && params.has("hercules_impersonation_token");
349
345
  }
350
-
351
346
  //#endregion
352
347
  //#region src/react/impersonation.ts
353
348
  function useHerculesImpersonation() {
@@ -405,7 +400,6 @@ function readStoredImpersonationSessionId(storageKey) {
405
400
  return null;
406
401
  }
407
402
  }
408
-
409
403
  //#endregion
410
404
  //#region src/react/use-user.ts
411
405
  /**
@@ -437,7 +431,6 @@ function useUser() {
437
431
  error
438
432
  ]);
439
433
  }
440
-
441
434
  //#endregion
442
435
  //#region src/react/use-auth.ts
443
436
  function useAuth() {
@@ -452,8 +445,9 @@ function useAuth() {
452
445
  signoutRedirect,
453
446
  removeUser
454
447
  ]);
455
- const signin = useCallback(async () => {
456
- await signinRedirect();
448
+ const signin = useCallback(async (options) => {
449
+ const returnTo = options?.returnTo ?? window.location.pathname + window.location.search + window.location.hash;
450
+ await signinRedirect({ state: { returnTo } });
457
451
  }, [signinRedirect]);
458
452
  return useMemo(() => {
459
453
  return {
@@ -467,7 +461,7 @@ function useAuth() {
467
461
  signin
468
462
  ]);
469
463
  }
470
-
471
464
  //#endregion
472
465
  export { HERCULES_IMPERSONATION_SESSION_ID_PARAM, HERCULES_IMPERSONATION_TOKEN_PARAM, HerculesAuthProvider, getHerculesImpersonationStorageKey, hasAuthParams, rememberHerculesImpersonationSession, useAuth, useAuthCallback, useHerculesAuthProvider, useHerculesImpersonation, useUser };
466
+
473
467
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps>","useAuth","retryTimerId: ReturnType<typeof setTimeout> | null","ReactAuthProvider","useOidcAuth","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../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 } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(\n options: UseAuthCallbackOptions = {},\n): UseAuthCallbackResult {\n const {\n timeoutMs = DEFAULT_TIMEOUT_MS,\n isBackendAuthenticated = true,\n onSync,\n onSuccess,\n onNoAuthParams,\n } = options;\n\n const {\n isLoading: isAuthLoading,\n isAuthenticated: isOidcAuthenticated,\n error: oidcError,\n signinRedirect,\n } = useAuth();\n\n const [status, setStatus] = useState<AuthCallbackStatus>(\"processing-oauth\");\n const [error, setError] = useState<string | null>(null);\n\n // Track mount state to prevent state updates after unmount\n const mountedRef = useRef(true);\n // Track if we had auth params on mount (won't change during lifecycle)\n const hadAuthParams = useRef(hasAuthParams());\n // Track if we've already started sync to prevent double execution\n const syncStarted = useRef(false);\n\n // Reset on mount, cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n syncStarted.current = false;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (\n !isAuthLoading &&\n isOidcAuthenticated &&\n status === \"processing-oauth\"\n ) {\n setStatus(\"waiting-backend\");\n return;\n }\n\n // OIDC finished but not authenticated (and we had auth params)\n // Wait a bit before declaring failure to avoid race conditions\n if (\n hadAuthParams.current &&\n !isAuthLoading &&\n !isOidcAuthenticated &&\n !oidcError &&\n status === \"processing-oauth\"\n ) {\n // Use a small delay to avoid race condition during OIDC state transitions\n const failureTimeout = setTimeout(() => {\n if (mountedRef.current && !isOidcAuthenticated) {\n setStatus(\"error\");\n setError(\"Authentication was cancelled or failed. Please try again.\");\n }\n }, 500);\n\n return () => clearTimeout(failureTimeout);\n }\n\n return;\n }, [isAuthLoading, isOidcAuthenticated, oidcError, status, onNoAuthParams]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n if (err instanceof ConvexError) {\n // try to extract the error message from the convex error\n const parseResult = convexErrorSchema.safeParse(err.data);\n if (parseResult.success) {\n setStatus(\"error\");\n setError(parseResult.data.message);\n return;\n }\n }\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error\n ? err.message\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\nexport const HERCULES_IMPERSONATION_SESSION_ID_PARAM =\n \"hercules_impersonation_session_id\";\nexport const HERCULES_IMPERSONATION_TOKEN_PARAM =\n \"hercules_impersonation_token\";\n\nexport type StoredHerculesImpersonation = {\n sessionId: string;\n startedAt: string;\n};\n\nexport function getHerculesImpersonationStorageKey(\n authority: string,\n clientId: string,\n) {\n return `hercules.impersonation.${authority}.${clientId}`;\n}\n\nexport function rememberHerculesImpersonationSession(\n storageKey: string,\n sessionId: string,\n) {\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 {\n createContext,\n useContext,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport {\n AuthProvider as ReactAuthProvider,\n type AuthProviderUserManagerProps,\n useAuth,\n} from \"react-oidc-context\";\nimport {\n UserManager,\n WebStorageStateStore,\n type UserManagerSettings,\n} from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\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<\n AuthProviderUserManagerProps,\n \"userManager\"\n> & {\n userManagerSettings?: Partial<UserManagerSettings>;\n authority: string;\n client_id: string;\n loadingFallback?: ReactNode;\n};\n\nfunction onSigninCallback() {\n window.history.replaceState({}, document.title, window.location.pathname);\n}\n\nfunction onSignoutCallback() {\n window.location.pathname = \"\";\n}\n\nconst DEFAULT_AUTH_CONFIG: Partial<HerculesAuthProviderProps> = {\n onSignoutCallback,\n onSigninCallback,\n};\n\ninterface HerculesAuthProviderContext {\n userManager: UserManager;\n impersonationStorageKey: string;\n}\n\nconst HerculesAuthProviderContext =\n createContext<HerculesAuthProviderContext | null>(null);\n\nexport function useHerculesAuthProvider() {\n const context = useContext(HerculesAuthProviderContext);\n if (!context) {\n throw new Error(\"HerculesAuthProviderContext not found\");\n }\n return context;\n}\n\nfunction AuthRecoveryGate({\n children,\n loadingFallback,\n 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) =>\n setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),\n ),\n ]);\n }).finally(finish);\n }, [isLoading, skipRecovery, userExpired]);\n\n const shouldBlock =\n !skipRecovery &&\n (recovering || (!recoveryDone && !isLoading && userExpired));\n\n if (shouldBlock) {\n return <>{loadingFallback}</>;\n }\n\n return <>{children}</>;\n}\n\n/**\n * A wrapper React component which provides a {@link ReactAuthProvider}\n * configured with Hercules Auth.\n *\n * @public\n */\nexport function HerculesAuthProvider({\n children,\n userManagerSettings,\n authority,\n client_id,\n loadingFallback = null,\n ...props\n}: HerculesAuthProviderProps) {\n const automaticSilentRenewExplicit =\n userManagerSettings?.automaticSilentRenew === true;\n const [{ userManager, impersonationStorageKey }] = useState(() => {\n const effectiveAuthority = userManagerSettings?.authority ?? authority;\n const effectiveClientId = userManagerSettings?.client_id ?? client_id;\n\n return {\n userManager: new UserManager({\n ...userManagerSettings,\n authority: effectiveAuthority,\n client_id: effectiveClientId,\n prompt: userManagerSettings?.prompt ?? \"select_account\",\n response_type: userManagerSettings?.response_type ?? \"code\",\n scope:\n userManagerSettings?.scope ?? \"openid profile email offline_access\",\n redirect_uri:\n userManagerSettings?.redirect_uri ??\n `${window.location.origin}/auth/callback`,\n post_logout_redirect_uri:\n userManagerSettings?.post_logout_redirect_uri ??\n window.location.origin,\n userStore:\n userManagerSettings?.userStore ??\n new WebStorageStateStore({ store: window.localStorage }),\n automaticSilentRenew:\n userManagerSettings?.automaticSilentRenew ?? false,\n silentRequestTimeoutInSeconds:\n userManagerSettings?.silentRequestTimeoutInSeconds ??\n RECOVERY_TIMEOUT_MS / 1000,\n }),\n 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\n value={{ userManager, impersonationStorageKey }}\n >\n <ReactAuthProvider\n userManager={userManager}\n {...DEFAULT_AUTH_CONFIG}\n {...props}\n >\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(\n HERCULES_IMPERSONATION_SESSION_ID_PARAM,\n );\n const impersonationToken = url.searchParams.get(\n HERCULES_IMPERSONATION_TOKEN_PARAM,\n );\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\"\n ? profile.hercules_actor_sub\n : null;\n const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;\n\n useEffect(() => {\n if (!auth.isAuthenticated) return;\n\n if (profileSessionId) {\n rememberHerculesImpersonationSession(\n impersonationStorageKey,\n profileSessionId,\n );\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 AuthContextProps extends OidcAuthContextProps {\n signout: () => Promise<void>;\n signin: () => Promise<void>;\n}\n\nexport function useAuth(): AuthContextProps {\n const { userManager } = useHerculesAuthProvider();\n const auth = useOidcAuth();\n\n const { signoutRedirect, removeUser, signinRedirect } = auth;\n const signout = useCallback(async () => {\n const endpoint = await userManager.metadataService.getEndSessionEndpoint();\n if (endpoint != null) {\n await signoutRedirect();\n } else {\n await removeUser();\n }\n }, [userManager, signoutRedirect, removeUser]);\n\n const signin = useCallback(async () => {\n await signinRedirect();\n }, [signinRedirect]);\n\n return useMemo(() => {\n return {\n ...auth,\n signout,\n signin,\n } satisfies AuthContextProps;\n }, [auth, signout, signin]);\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,EAAE,OAAO,EACjC,SAAS,EAAE,QAAQ,EACpB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GF,SAAgB,gBACd,UAAkC,EAAE,EACb;CACvB,MAAM,EACJ,YAAY,oBACZ,yBAAyB,MACzB,QACA,WACA,mBACE;CAEJ,MAAM,EACJ,WAAW,eACX,iBAAiB,qBACjB,OAAO,WACP,mBACEA,WAAS;CAEb,MAAM,CAAC,QAAQ,aAAa,SAA6B,mBAAmB;CAC5E,MAAM,CAAC,OAAO,YAAY,SAAwB,KAAK;CAGvD,MAAM,aAAa,OAAO,KAAK;CAE/B,MAAM,gBAAgB,OAAOC,iBAAe,CAAC;CAE7C,MAAM,cAAc,OAAO,MAAM;AAGjC,iBAAgB;AACd,aAAW,UAAU;AACrB,cAAY,UAAU;AACtB,eAAa;AACX,cAAW,UAAU;;IAEtB,EAAE,CAAC;AAGN,iBAAgB;AACd,MAAI,WAAW,aAAa,WAAW,QAAS;EAEhD,MAAM,UAAU,iBAAiB;AAC/B,OAAI,WAAW,SAAS;AACtB,cAAU,QAAQ;AAClB,aAAS,8CAA8C;;KAExD,UAAU;AAEb,eAAa,aAAa,QAAQ;IACjC,CAAC,QAAQ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E,gBAAgB,yBAAyB;CACjD,MAAM,OAAOC,WAAa;CAE1B,MAAM,EAAE,iBAAiB,YAAY,mBAAmB;CACxD,MAAM,UAAU,YAAY,YAAY;AAEtC,MADiB,MAAM,YAAY,gBAAgB,uBAAuB,IAC1D,KACd,OAAM,iBAAiB;MAEvB,OAAM,YAAY;IAEnB;EAAC;EAAa;EAAiB;EAAW,CAAC;CAE9C,MAAM,SAAS,YAAY,YAAY;AACrC,QAAM,gBAAgB;IACrB,CAAC,eAAe,CAAC;AAEpB,QAAO,cAAc;AACnB,SAAO;GACL,GAAG;GACH;GACA;GACD;IACA;EAAC;EAAM;EAAS;EAAO,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["useAuth","hasAuthParams","useAuth","ReactAuthProvider","useOidcAuth","useAuth","useOidcAuth"],"sources":["../../src/react/auth-callback-hook.tsx","../../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 } from \"react-oidc-context\";\nimport { ConvexError } from \"convex/values\";\nimport * as z from \"zod\";\n\nconst DEFAULT_TIMEOUT_MS = 20000; // 20 second timeout\n\nconst convexErrorSchema = z.object({\n message: z.string(),\n});\n\n/**\n * Authentication callback status states\n * @public\n */\nexport type AuthCallbackStatus =\n | \"processing-oauth\" // OIDC is processing the callback\n | \"waiting-backend\" // OIDC authenticated, waiting for backend\n | \"syncing\" // Syncing user with backend (e.g., creating user record)\n | \"success\" // All done\n | \"error\"; // Something went wrong\n\n/**\n * Options for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackOptions {\n /**\n * Timeout in milliseconds before the callback is considered failed.\n * @default 20000\n */\n timeoutMs?: number;\n\n /**\n * Whether the backend (e.g., Convex) is authenticated.\n * The hook will wait for this to be true before calling onSync.\n */\n isBackendAuthenticated?: boolean;\n\n /**\n * Called when the backend is authenticated and ready to sync.\n * Use this to create/update the user in your backend.\n * Return a promise that resolves when sync is complete.\n */\n onSync?: () => Promise<void>;\n\n /**\n * Called when authentication is successful and sync is complete.\n * Use this to redirect the user.\n */\n onSuccess?: () => void;\n\n /**\n * Called when OIDC is not authenticated and there are no auth params.\n * This typically means the user navigated directly to the callback page.\n * Use this to redirect them away.\n */\n onNoAuthParams?: () => void;\n}\n\n/**\n * Return type for the useAuthCallback hook\n * @public\n */\nexport interface UseAuthCallbackResult {\n /** Current status of the auth callback flow */\n status: AuthCallbackStatus;\n\n /** Error message if status is \"error\" */\n error: string | null;\n\n /** Whether the auth callback is still in progress */\n isLoading: boolean;\n\n /** Whether the auth callback completed successfully */\n isSuccess: boolean;\n\n /** Whether there was an error */\n isError: boolean;\n\n /** Retry the authentication flow by redirecting to the auth provider */\n retry: () => Promise<void>;\n}\n\n/**\n * A hook for handling OAuth/OIDC callback flows.\n *\n * This hook manages the complete authentication callback lifecycle:\n * 1. Processing the OAuth callback from the identity provider\n * 2. Waiting for backend authentication (e.g., Convex)\n * 3. Syncing user data with your backend\n * 4. Handling success and error states\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const navigate = useNavigate();\n * const { isAuthenticated } = useConvexAuth();\n * const updateUser = useMutation(api.users.updateCurrentUser);\n *\n * const { status, error, retry } = useAuthCallback({\n * isBackendAuthenticated: isAuthenticated,\n * onSync: () => updateUser(),\n * onSuccess: () => navigate(\"/\", { replace: true }),\n * onNoAuthParams: () => navigate(\"/\", { replace: true }),\n * });\n *\n * if (status === \"error\") {\n * return <ErrorState message={error} onRetry={retry} />;\n * }\n *\n * return <LoadingSpinner />;\n * }\n * ```\n *\n * @public\n */\nexport function useAuthCallback(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\n // Reset on mount, cleanup on unmount\n useEffect(() => {\n mountedRef.current = true;\n syncStarted.current = false;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Timeout protection with state awareness\n useEffect(() => {\n if (status === \"success\" || status === \"error\") return;\n\n const timeout = setTimeout(() => {\n if (mountedRef.current) {\n setStatus(\"error\");\n setError(\"Authentication timed out. Please try again.\");\n }\n }, timeoutMs);\n\n return () => clearTimeout(timeout);\n }, [status, timeoutMs]);\n\n // Track OIDC authentication progression\n useEffect(() => {\n // Don't update if we're already past processing or in an error state\n if (status !== \"processing-oauth\" && status !== \"waiting-backend\") return;\n\n // Handle OIDC errors\n if (oidcError) {\n setStatus(\"error\");\n setError(oidcError.message || \"Authentication failed\");\n return;\n }\n\n // No auth params and not authenticated - navigated here directly\n if (!hadAuthParams.current && !isAuthLoading && !isOidcAuthenticated) {\n onNoAuthParams?.();\n return;\n }\n\n // OIDC is done loading and authenticated - move to waiting for backend\n if (!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]);\n\n // Sync with backend once backend is authenticated\n useEffect(() => {\n if (status !== \"waiting-backend\" || !isBackendAuthenticated) return;\n if (syncStarted.current) return;\n\n syncStarted.current = true;\n\n async function performSync() {\n if (!mountedRef.current) return;\n\n setStatus(\"syncing\");\n\n try {\n if (onSync) {\n await onSync();\n }\n\n if (mountedRef.current) {\n setStatus(\"success\");\n }\n } catch (err) {\n console.error(\"Auth callback sync failed:\", err);\n\n if (!mountedRef.current) return;\n\n if (err instanceof ConvexError) {\n // try to extract the error message from the convex error\n const parseResult = convexErrorSchema.safeParse(err.data);\n if (parseResult.success) {\n setStatus(\"error\");\n setError(parseResult.data.message);\n return;\n }\n }\n\n // Check if it's an authentication error\n const errorMessage =\n err instanceof Error\n ? err.message\n : \"Failed to complete authentication. Please try again.\";\n\n setStatus(\"error\");\n setError(errorMessage);\n }\n }\n\n performSync();\n }, [status, isBackendAuthenticated, onSync]);\n\n // Handle successful completion\n useEffect(() => {\n if (status === \"success\") {\n onSuccess?.();\n }\n }, [status, onSuccess]);\n\n // Retry handler\n const retry = useCallback(async () => {\n try {\n await signinRedirect();\n } catch (err) {\n console.error(\"Failed to restart auth:\", err);\n }\n }, [signinRedirect]);\n\n return {\n status,\n error,\n isLoading: status !== \"success\" && status !== \"error\",\n isSuccess: status === \"success\",\n isError: status === \"error\",\n retry,\n };\n}\n","\"use client\";\n\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 { UserManager, WebStorageStateStore, type UserManagerSettings } from \"oidc-client-ts\";\nimport { withRefreshLock } from \"../internal/refresh-lock\";\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\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 = null,\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 UserManager({\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 ??\n new WebStorageStateStore({ store: window.localStorage }),\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 {\n ...auth,\n signout,\n signin,\n } satisfies AuthContextProps;\n }, [auth, signout, signin]);\n}\n"],"mappings":";;;;;;;;AAOA,MAAM,qBAAqB;AAE3B,MAAM,oBAAoB,EAAE,OAAO,EACjC,SAAS,EAAE,OAAO,EACpB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GD,SAAgB,gBAAgB,UAAkC,CAAC,GAA0B;CAC3F,MAAM,EACJ,YAAY,oBACZ,yBAAyB,MACzB,QACA,WACA,mBACE;CAEJ,MAAM,EACJ,WAAW,eACX,iBAAiB,qBACjB,OAAO,WACP,mBACEA,UAAQ;CAEZ,MAAM,CAAC,QAAQ,aAAa,SAA6B,kBAAkB;CAC3E,MAAM,CAAC,OAAO,YAAY,SAAwB,IAAI;CAGtD,MAAM,aAAa,OAAO,IAAI;CAE9B,MAAM,gBAAgB,OAAOC,gBAAc,CAAC;CAE5C,MAAM,cAAc,OAAO,KAAK;CAGhC,gBAAgB;EACd,WAAW,UAAU;EACrB,YAAY,UAAU;EACtB,aAAa;GACX,WAAW,UAAU;EACvB;CACF,GAAG,CAAC,CAAC;CAGL,gBAAgB;EACd,IAAI,WAAW,aAAa,WAAW,SAAS;EAEhD,MAAM,UAAU,iBAAiB;GAC/B,IAAI,WAAW,SAAS;IACtB,UAAU,OAAO;IACjB,SAAS,6CAA6C;GACxD;EACF,GAAG,SAAS;EAEZ,aAAa,aAAa,OAAO;CACnC,GAAG,CAAC,QAAQ,SAAS,CAAC;CAGtB,gBAAgB;EAEd,IAAI,WAAW,sBAAsB,WAAW,mBAAmB;EAGnE,IAAI,WAAW;GACb,UAAU,OAAO;GACjB,SAAS,UAAU,WAAW,uBAAuB;GACrD;EACF;EAGA,IAAI,CAAC,cAAc,WAAW,CAAC,iBAAiB,CAAC,qBAAqB;GACpE,iB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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"}
@@ -4,10 +4,10 @@ const mutexes = /* @__PURE__ */ new Map();
4
4
  async function manualMutex(key, callback) {
5
5
  return new Promise((resolve, reject) => {
6
6
  const wrapped = () => callback().then(resolve).catch(reject).finally(() => {
7
- const mutex$1 = mutexes.get(key);
8
- const next = mutex$1.waiting.shift();
9
- if (next) mutex$1.running = next();
10
- else mutex$1.running = null;
7
+ const mutex = mutexes.get(key);
8
+ const next = mutex.waiting.shift();
9
+ if (next) mutex.running = next();
10
+ else mutex.running = null;
11
11
  });
12
12
  let mutex = mutexes.get(key);
13
13
  if (!mutex) {
@@ -25,7 +25,7 @@ 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
-
29
28
  //#endregion
30
29
  export { withRefreshLock as t };
31
- //# sourceMappingURL=refresh-lock-DYW9ITwj.mjs.map
30
+
31
+ //# sourceMappingURL=refresh-lock-Cv63qcNd.mjs.map
@@ -0,0 +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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usehercules/auth",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Authentication utilities for Hercules applications using OIDC",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -27,9 +27,9 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "jwt-decode": "^4.0.0",
30
- "oidc-client-ts": "^3.4.1",
30
+ "oidc-client-ts": "^3.5.0",
31
31
  "react-oidc-context": "^3.3.1",
32
- "zod": "^4.3.6"
32
+ "zod": "^4.4.3"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "convex": "^1.29.0",
@@ -38,15 +38,15 @@
38
38
  "devDependencies": {
39
39
  "@testing-library/jest-dom": "^6.9.1",
40
40
  "@testing-library/react": "^16.3.2",
41
- "@types/react": "^19.2.14",
41
+ "@types/react": "^19.2.17",
42
42
  "@types/react-dom": "^19.2.3",
43
- "convex": "^1.38.0",
44
- "jsdom": "^28.1.0",
45
- "react": "^19.2.4",
46
- "react-dom": "^19.2.4",
47
- "tsdown": "^0.18.4",
48
- "typescript": "^5.9.3",
49
- "vitest": "^4.1.0"
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.3",
48
+ "typescript": "^6.0.3",
49
+ "vitest": "^4.1.10"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsdown",
@@ -23,9 +23,7 @@ vi.mock("react-oidc-context", () => ({
23
23
  type CapturedUseAuth = () => {
24
24
  isLoading: boolean;
25
25
  isAuthenticated: boolean;
26
- fetchAccessToken: (args: {
27
- forceRefreshToken: boolean;
28
- }) => Promise<string | null>;
26
+ fetchAccessToken: (args: { forceRefreshToken: boolean }) => Promise<string | null>;
29
27
  };
30
28
 
31
29
  let capturedUseAuth: CapturedUseAuth | null = null;
@@ -200,11 +198,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
200
198
 
201
199
  resolveSilent?.({ id_token: "fresh-token" });
202
200
 
203
- [firstToken, secondToken, thirdToken] = await Promise.all([
204
- first,
205
- second,
206
- third,
207
- ]);
201
+ [firstToken, secondToken, thirdToken] = await Promise.all([first, second, third]);
208
202
  });
209
203
 
210
204
  expect(firstToken).toBe("fresh-token");
@@ -252,9 +246,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
252
246
  const { result, rerender } = renderUseAuth();
253
247
  const firstFetch = result.current.fetchAccessToken;
254
248
 
255
- expect(
256
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
257
- ).toBe(FIRST_TOKEN);
249
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(FIRST_TOKEN);
258
250
 
259
251
  setAuthState({
260
252
  user: {
@@ -265,9 +257,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
265
257
  rerender();
266
258
 
267
259
  expect(result.current.fetchAccessToken).toBe(firstFetch);
268
- expect(
269
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
270
- ).toBe(SECOND_TOKEN);
260
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(SECOND_TOKEN);
271
261
  });
272
262
 
273
263
  it("re-identifies fetchAccessToken when the subject changes", async () => {
@@ -285,9 +275,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
285
275
  });
286
276
  rerender();
287
277
 
288
- expect(
289
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
290
- ).toBe(BOB_TOKEN);
278
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(BOB_TOKEN);
291
279
  expect(result.current.fetchAccessToken).not.toBe(aliceFetch);
292
280
  });
293
281
 
@@ -313,8 +301,6 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
313
301
  rerender();
314
302
 
315
303
  expect(result.current.fetchAccessToken).not.toBe(firstFetch);
316
- expect(
317
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
318
- ).toBe(SECOND_TOKEN);
304
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(SECOND_TOKEN);
319
305
  });
320
306
  });
@@ -39,10 +39,7 @@ function useUseAuthFromHercules() {
39
39
  if (!forceRefreshToken) {
40
40
  return currentToken ?? null;
41
41
  }
42
- if (
43
- currentToken != null &&
44
- !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
45
- ) {
42
+ if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) {
46
43
  return currentToken;
47
44
  }
48
45
  if (inFlightRefresh.current) {
@@ -50,10 +47,7 @@ function useUseAuthFromHercules() {
50
47
  }
51
48
  const refresh = withRefreshLock(async () => {
52
49
  const tokenAfterLock = idTokenRef.current;
53
- if (
54
- tokenAfterLock != null &&
55
- !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)
56
- ) {
50
+ if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) {
57
51
  return tokenAfterLock;
58
52
  }
59
53
  try {
@@ -7,10 +7,7 @@ type Queue = {
7
7
 
8
8
  const mutexes = new Map<string, Queue>();
9
9
 
10
- async function manualMutex<T>(
11
- key: string,
12
- callback: () => Promise<T>,
13
- ): Promise<T> {
10
+ async function manualMutex<T>(key: string, callback: () => Promise<T>): Promise<T> {
14
11
  return new Promise<T>((resolve, reject) => {
15
12
  const wrapped = () =>
16
13
  callback()
@@ -40,9 +37,7 @@ async function manualMutex<T>(
40
37
  });
41
38
  }
42
39
 
43
- export async function withRefreshLock<T>(
44
- callback: () => Promise<T>,
45
- ): Promise<T> {
40
+ export async function withRefreshLock<T>(callback: () => Promise<T>): Promise<T> {
46
41
  if (typeof navigator !== "undefined" && navigator.locks) {
47
42
  return navigator.locks.request(REFRESH_LOCK_KEY, callback);
48
43
  }
@@ -1,11 +1,5 @@
1
1
  import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import {
3
- act,
4
- render,
5
- screen,
6
- waitFor,
7
- configure,
8
- } from "@testing-library/react";
2
+ import { act, render, screen, waitFor, configure } from "@testing-library/react";
9
3
  import { HerculesAuthProvider } from "./HerculesAuthProvider.js";
10
4
 
11
5
  configure({ reactStrictMode: false });
@@ -22,9 +16,7 @@ Object.defineProperty(window, "localStorage", {
22
16
  });
23
17
 
24
18
  vi.mock("react-oidc-context", () => ({
25
- AuthProvider: ({ children }: { children: React.ReactNode }) => (
26
- <>{children}</>
27
- ),
19
+ AuthProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
28
20
  useAuth: () => mockAuthState,
29
21
  }));
30
22
 
@@ -83,10 +75,7 @@ function renderProvider(
83
75
  describe("HerculesAuthProvider accessTokenExpiring renewal listener", () => {
84
76
  it("registers the lock-wrapped renewal listener by default", () => {
85
77
  render(
86
- <HerculesAuthProvider
87
- authority="https://auth.example.com"
88
- client_id="test-client"
89
- >
78
+ <HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
90
79
  <div data-testid="app">app</div>
91
80
  </HerculesAuthProvider>,
92
81
  );
@@ -188,9 +177,7 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
188
177
  isLoading: false,
189
178
  user: { expired: true, id_token: "stale" },
190
179
  });
191
- const { rerender } = renderProvider(
192
- <div data-testid="loading">loading</div>,
193
- );
180
+ const { rerender } = renderProvider(<div data-testid="loading">loading</div>);
194
181
  expect(screen.getByTestId("loading")).toBeDefined();
195
182
  await waitFor(() => {
196
183
  expect(mockSigninSilent).toHaveBeenCalledTimes(1);
@@ -357,10 +344,7 @@ describe("HerculesAuthProvider AuthRecoveryGate", () => {
357
344
  });
358
345
  setAuthState({ user: { expired: true, id_token: "stale-2" } });
359
346
  rerender(
360
- <HerculesAuthProvider
361
- authority="https://auth.example.com"
362
- client_id="test-client"
363
- >
347
+ <HerculesAuthProvider authority="https://auth.example.com" client_id="test-client">
364
348
  <div data-testid="app">app content</div>
365
349
  </HerculesAuthProvider>,
366
350
  );
@@ -1,23 +1,12 @@
1
1
  "use client";
2
2
 
3
- import {
4
- createContext,
5
- useContext,
6
- useEffect,
7
- useRef,
8
- useState,
9
- type ReactNode,
10
- } from "react";
3
+ import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from "react";
11
4
  import {
12
5
  AuthProvider as ReactAuthProvider,
13
6
  type AuthProviderUserManagerProps,
14
7
  useAuth,
15
8
  } from "react-oidc-context";
16
- import {
17
- UserManager,
18
- WebStorageStateStore,
19
- type UserManagerSettings,
20
- } from "oidc-client-ts";
9
+ import { UserManager, WebStorageStateStore, type UserManagerSettings } from "oidc-client-ts";
21
10
  import { withRefreshLock } from "../internal/refresh-lock";
22
11
  import {
23
12
  clearHerculesImpersonationParamsFromUrl,
@@ -30,10 +19,7 @@ import {
30
19
  const RECOVERY_TIMEOUT_MS = 10_000;
31
20
  const LOCK_GRACE_MS = 5_000;
32
21
 
33
- export type HerculesAuthProviderProps = Omit<
34
- AuthProviderUserManagerProps,
35
- "userManager"
36
- > & {
22
+ export type HerculesAuthProviderProps = Omit<AuthProviderUserManagerProps, "userManager"> & {
37
23
  userManagerSettings?: Partial<UserManagerSettings>;
38
24
  authority: string;
39
25
  client_id: string;
@@ -58,8 +44,7 @@ interface HerculesAuthProviderContext {
58
44
  impersonationStorageKey: string;
59
45
  }
60
46
 
61
- const HerculesAuthProviderContext =
62
- createContext<HerculesAuthProviderContext | null>(null);
47
+ const HerculesAuthProviderContext = createContext<HerculesAuthProviderContext | null>(null);
63
48
 
64
49
  export function useHerculesAuthProvider() {
65
50
  const context = useContext(HerculesAuthProviderContext);
@@ -111,16 +96,12 @@ function AuthRecoveryGate({
111
96
  void withRefreshLock(async () => {
112
97
  await Promise.race([
113
98
  signinSilentRef.current().catch(() => undefined),
114
- new Promise<void>((resolve) =>
115
- setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS),
116
- ),
99
+ new Promise<void>((resolve) => setTimeout(resolve, RECOVERY_TIMEOUT_MS + LOCK_GRACE_MS)),
117
100
  ]);
118
101
  }).finally(finish);
119
102
  }, [isLoading, skipRecovery, userExpired]);
120
103
 
121
- const shouldBlock =
122
- !skipRecovery &&
123
- (recovering || (!recoveryDone && !isLoading && userExpired));
104
+ const shouldBlock = !skipRecovery && (recovering || (!recoveryDone && !isLoading && userExpired));
124
105
 
125
106
  if (shouldBlock) {
126
107
  return <>{loadingFallback}</>;
@@ -143,8 +124,7 @@ export function HerculesAuthProvider({
143
124
  loadingFallback = null,
144
125
  ...props
145
126
  }: HerculesAuthProviderProps) {
146
- const automaticSilentRenewExplicit =
147
- userManagerSettings?.automaticSilentRenew === true;
127
+ const automaticSilentRenewExplicit = userManagerSettings?.automaticSilentRenew === true;
148
128
  const [{ userManager, impersonationStorageKey }] = useState(() => {
149
129
  const effectiveAuthority = userManagerSettings?.authority ?? authority;
150
130
  const effectiveClientId = userManagerSettings?.client_id ?? client_id;
@@ -156,22 +136,17 @@ export function HerculesAuthProvider({
156
136
  client_id: effectiveClientId,
157
137
  prompt: userManagerSettings?.prompt ?? "select_account",
158
138
  response_type: userManagerSettings?.response_type ?? "code",
159
- scope:
160
- userManagerSettings?.scope ?? "openid profile email offline_access",
139
+ scope: userManagerSettings?.scope ?? "openid profile email offline_access",
161
140
  redirect_uri:
162
- userManagerSettings?.redirect_uri ??
163
- `${window.location.origin}/auth/callback`,
141
+ userManagerSettings?.redirect_uri ?? `${window.location.origin}/auth/callback`,
164
142
  post_logout_redirect_uri:
165
- userManagerSettings?.post_logout_redirect_uri ??
166
- window.location.origin,
143
+ userManagerSettings?.post_logout_redirect_uri ?? window.location.origin,
167
144
  userStore:
168
145
  userManagerSettings?.userStore ??
169
146
  new WebStorageStateStore({ store: window.localStorage }),
170
- automaticSilentRenew:
171
- userManagerSettings?.automaticSilentRenew ?? false,
147
+ automaticSilentRenew: userManagerSettings?.automaticSilentRenew ?? false,
172
148
  silentRequestTimeoutInSeconds:
173
- userManagerSettings?.silentRequestTimeoutInSeconds ??
174
- RECOVERY_TIMEOUT_MS / 1000,
149
+ userManagerSettings?.silentRequestTimeoutInSeconds ?? RECOVERY_TIMEOUT_MS / 1000,
175
150
  }),
176
151
  impersonationStorageKey: getHerculesImpersonationStorageKey(
177
152
  effectiveAuthority,
@@ -231,14 +206,8 @@ export function HerculesAuthProvider({
231
206
  }, [userManager, automaticSilentRenewExplicit]);
232
207
 
233
208
  return (
234
- <HerculesAuthProviderContext.Provider
235
- value={{ userManager, impersonationStorageKey }}
236
- >
237
- <ReactAuthProvider
238
- userManager={userManager}
239
- {...DEFAULT_AUTH_CONFIG}
240
- {...props}
241
- >
209
+ <HerculesAuthProviderContext.Provider value={{ userManager, impersonationStorageKey }}>
210
+ <ReactAuthProvider userManager={userManager} {...DEFAULT_AUTH_CONFIG} {...props}>
242
211
  <HerculesImpersonationHandoff storageKey={impersonationStorageKey} />
243
212
  <AuthRecoveryGate
244
213
  loadingFallback={loadingFallback}
@@ -259,12 +228,8 @@ function HerculesImpersonationHandoff({ storageKey }: { storageKey: string }) {
259
228
  if (hasStartedRef.current || typeof window === "undefined") return;
260
229
 
261
230
  const url = new URL(window.location.href);
262
- const impersonationSessionId = url.searchParams.get(
263
- HERCULES_IMPERSONATION_SESSION_ID_PARAM,
264
- );
265
- const impersonationToken = url.searchParams.get(
266
- HERCULES_IMPERSONATION_TOKEN_PARAM,
267
- );
231
+ const impersonationSessionId = url.searchParams.get(HERCULES_IMPERSONATION_SESSION_ID_PARAM);
232
+ const impersonationToken = url.searchParams.get(HERCULES_IMPERSONATION_TOKEN_PARAM);
268
233
  if (!impersonationSessionId && !impersonationToken) return;
269
234
  if (!impersonationSessionId || !impersonationToken) {
270
235
  window.history.replaceState(
@@ -120,9 +120,7 @@ describe("useAuthCallback", () => {
120
120
  vi.useFakeTimers();
121
121
 
122
122
  try {
123
- const { result } = renderHook(() =>
124
- useAuthCallback({ timeoutMs: 5000 }),
125
- );
123
+ const { result } = renderHook(() => useAuthCallback({ timeoutMs: 5000 }));
126
124
 
127
125
  expect(result.current.status).toBe("processing-oauth");
128
126
 
@@ -131,9 +129,7 @@ describe("useAuthCallback", () => {
131
129
  });
132
130
 
133
131
  expect(result.current.status).toBe("error");
134
- expect(result.current.error).toBe(
135
- "Authentication timed out. Please try again.",
136
- );
132
+ expect(result.current.error).toBe("Authentication timed out. Please try again.");
137
133
  expect(result.current.isError).toBe(true);
138
134
  expect(result.current.isLoading).toBe(false);
139
135
  } finally {
@@ -269,9 +265,7 @@ describe("useAuthCallback", () => {
269
265
  it("goes straight to success when onSync is omitted", async () => {
270
266
  setAuthState({ isLoading: false, isAuthenticated: true });
271
267
 
272
- const { result } = renderHook(() =>
273
- useAuthCallback({ isBackendAuthenticated: true }),
274
- );
268
+ const { result } = renderHook(() => useAuthCallback({ isBackendAuthenticated: true }));
275
269
 
276
270
  await waitFor(() => {
277
271
  expect(result.current.status).toBe("success");
@@ -117,9 +117,7 @@ export interface UseAuthCallbackResult {
117
117
  *
118
118
  * @public
119
119
  */
120
- export function useAuthCallback(
121
- options: UseAuthCallbackOptions = {},
122
- ): UseAuthCallbackResult {
120
+ export function useAuthCallback(options: UseAuthCallbackOptions = {}): UseAuthCallbackResult {
123
121
  const {
124
122
  timeoutMs = DEFAULT_TIMEOUT_MS,
125
123
  isBackendAuthenticated = true,
@@ -187,11 +185,7 @@ export function useAuthCallback(
187
185
  }
188
186
 
189
187
  // OIDC is done loading and authenticated - move to waiting for backend
190
- if (
191
- !isAuthLoading &&
192
- isOidcAuthenticated &&
193
- status === "processing-oauth"
194
- ) {
188
+ if (!isAuthLoading && isOidcAuthenticated && status === "processing-oauth") {
195
189
  setStatus("waiting-backend");
196
190
  return;
197
191
  }
@@ -1,26 +1,18 @@
1
1
  "use client";
2
2
 
3
- export const HERCULES_IMPERSONATION_SESSION_ID_PARAM =
4
- "hercules_impersonation_session_id";
5
- export const HERCULES_IMPERSONATION_TOKEN_PARAM =
6
- "hercules_impersonation_token";
3
+ export const HERCULES_IMPERSONATION_SESSION_ID_PARAM = "hercules_impersonation_session_id";
4
+ export const HERCULES_IMPERSONATION_TOKEN_PARAM = "hercules_impersonation_token";
7
5
 
8
6
  export type StoredHerculesImpersonation = {
9
7
  sessionId: string;
10
8
  startedAt: string;
11
9
  };
12
10
 
13
- export function getHerculesImpersonationStorageKey(
14
- authority: string,
15
- clientId: string,
16
- ) {
11
+ export function getHerculesImpersonationStorageKey(authority: string, clientId: string) {
17
12
  return `hercules.impersonation.${authority}.${clientId}`;
18
13
  }
19
14
 
20
- export function rememberHerculesImpersonationSession(
21
- storageKey: string,
22
- sessionId: string,
23
- ) {
15
+ export function rememberHerculesImpersonationSession(storageKey: string, sessionId: string) {
24
16
  if (typeof window === "undefined") return;
25
17
  window.localStorage.setItem(
26
18
  storageKey,
@@ -8,10 +8,7 @@ import {
8
8
 
9
9
  configure({ reactStrictMode: true });
10
10
 
11
- const storageKey = getHerculesImpersonationStorageKey(
12
- "https://auth.example.com",
13
- "client_1",
14
- );
11
+ const storageKey = getHerculesImpersonationStorageKey("https://auth.example.com", "client_1");
15
12
  const mockSignoutRedirect = vi.fn();
16
13
  const mockRemoveUser = vi.fn();
17
14
  const mockGetEndSessionEndpoint = vi.fn();
@@ -34,19 +34,14 @@ export function useHerculesImpersonation(): HerculesImpersonationState {
34
34
  ? profile.hercules_impersonation_session_id
35
35
  : null;
36
36
  const actorSub =
37
- typeof profile.hercules_actor_sub === "string"
38
- ? profile.hercules_actor_sub
39
- : null;
37
+ typeof profile.hercules_actor_sub === "string" ? profile.hercules_actor_sub : null;
40
38
  const sessionId = auth.isAuthenticated ? profileSessionId : storedSessionId;
41
39
 
42
40
  useEffect(() => {
43
41
  if (!auth.isAuthenticated) return;
44
42
 
45
43
  if (profileSessionId) {
46
- rememberHerculesImpersonationSession(
47
- impersonationStorageKey,
48
- profileSessionId,
49
- );
44
+ rememberHerculesImpersonationSession(impersonationStorageKey, profileSessionId);
50
45
  setStoredSessionId(profileSessionId);
51
46
  return;
52
47
  }
@@ -71,9 +71,7 @@ describe("useAuth", () => {
71
71
 
72
72
  describe("signout", () => {
73
73
  it("calls signoutRedirect when end session endpoint exists", async () => {
74
- mockGetEndSessionEndpoint.mockResolvedValue(
75
- "https://auth.example.com/logout",
76
- );
74
+ mockGetEndSessionEndpoint.mockResolvedValue("https://auth.example.com/logout");
77
75
  mockSignoutRedirect.mockResolvedValue(undefined);
78
76
 
79
77
  const { result } = renderHook(() => useAuth());
@@ -116,7 +114,7 @@ describe("useAuth", () => {
116
114
  });
117
115
 
118
116
  describe("signin", () => {
119
- it("calls signinRedirect", async () => {
117
+ it("passes the current URL as returnTo state by default", async () => {
120
118
  mockSigninRedirect.mockResolvedValue(undefined);
121
119
 
122
120
  const { result } = renderHook(() => useAuth());
@@ -126,6 +124,26 @@ describe("useAuth", () => {
126
124
  });
127
125
 
128
126
  expect(mockSigninRedirect).toHaveBeenCalledOnce();
127
+ expect(mockSigninRedirect).toHaveBeenCalledWith({
128
+ state: {
129
+ returnTo: window.location.pathname + window.location.search + window.location.hash,
130
+ },
131
+ });
132
+ });
133
+
134
+ it("passes an explicit returnTo as state", async () => {
135
+ mockSigninRedirect.mockResolvedValue(undefined);
136
+
137
+ const { result } = renderHook(() => useAuth());
138
+
139
+ await act(async () => {
140
+ await result.current.signin({ returnTo: "/projects/42?tab=members" });
141
+ });
142
+
143
+ expect(mockSigninRedirect).toHaveBeenCalledOnce();
144
+ expect(mockSigninRedirect).toHaveBeenCalledWith({
145
+ state: { returnTo: "/projects/42?tab=members" },
146
+ });
129
147
  });
130
148
  });
131
149
 
@@ -5,9 +5,19 @@ import {
5
5
  import { useHerculesAuthProvider } from "./HerculesAuthProvider";
6
6
  import { useCallback, useMemo } from "react";
7
7
 
8
+ export interface SigninOptions {
9
+ /**
10
+ * In-app path to land on after sign-in (e.g. "/projects/42"). Round-tripped
11
+ * through the OIDC `state` value and surfaced on `auth.user.state` as
12
+ * `{ returnTo }` for the callback page to honor. Defaults to the current
13
+ * URL (path + query + hash) so sign-in returns users to where they were.
14
+ */
15
+ returnTo?: string;
16
+ }
17
+
8
18
  export interface AuthContextProps extends OidcAuthContextProps {
9
19
  signout: () => Promise<void>;
10
- signin: () => Promise<void>;
20
+ signin: (options?: SigninOptions) => Promise<void>;
11
21
  }
12
22
 
13
23
  export function useAuth(): AuthContextProps {
@@ -24,9 +34,15 @@ export function useAuth(): AuthContextProps {
24
34
  }
25
35
  }, [userManager, signoutRedirect, removeUser]);
26
36
 
27
- const signin = useCallback(async () => {
28
- await signinRedirect();
29
- }, [signinRedirect]);
37
+ const signin = useCallback(
38
+ async (options?: SigninOptions) => {
39
+ const returnTo =
40
+ options?.returnTo ??
41
+ window.location.pathname + window.location.search + window.location.hash;
42
+ await signinRedirect({ state: { returnTo } });
43
+ },
44
+ [signinRedirect],
45
+ );
30
46
 
31
47
  return useMemo(() => {
32
48
  return {
@@ -1 +0,0 @@
1
- {"version":3,"file":"refresh-lock-DYW9ITwj.mjs","names":["mutex"],"sources":["../src/internal/refresh-lock.ts"],"sourcesContent":["export const REFRESH_LOCK_KEY = \"__herculesAuthRefresh\";\n\ntype Queue = {\n running: Promise<void> | null;\n waiting: Array<() => Promise<void>>;\n};\n\nconst mutexes = new Map<string, Queue>();\n\nasync function manualMutex<T>(\n key: string,\n callback: () => Promise<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const wrapped = () =>\n callback()\n .then(resolve)\n .catch(reject)\n .finally(() => {\n const mutex = mutexes.get(key)!;\n const next = mutex.waiting.shift();\n if (next) {\n mutex.running = next();\n } else {\n mutex.running = null;\n }\n });\n\n let mutex = mutexes.get(key);\n if (!mutex) {\n mutex = { running: null, waiting: [] };\n mutexes.set(key, mutex);\n }\n\n if (mutex.running === null) {\n mutex.running = wrapped();\n } else {\n mutex.waiting.push(wrapped);\n }\n });\n}\n\nexport async function withRefreshLock<T>(\n callback: () => Promise<T>,\n): Promise<T> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(REFRESH_LOCK_KEY, callback);\n }\n return manualMutex(REFRESH_LOCK_KEY, callback);\n}\n"],"mappings":";AAAA,MAAa,mBAAmB;AAOhC,MAAM,0BAAU,IAAI,KAAoB;AAExC,eAAe,YACb,KACA,UACY;AACZ,QAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,gBACJ,UAAU,CACP,KAAK,QAAQ,CACb,MAAM,OAAO,CACb,cAAc;GACb,MAAMA,UAAQ,QAAQ,IAAI,IAAI;GAC9B,MAAM,OAAOA,QAAM,QAAQ,OAAO;AAClC,OAAI,KACF,SAAM,UAAU,MAAM;OAEtB,SAAM,UAAU;IAElB;EAEN,IAAI,QAAQ,QAAQ,IAAI,IAAI;AAC5B,MAAI,CAAC,OAAO;AACV,WAAQ;IAAE,SAAS;IAAM,SAAS,EAAE;IAAE;AACtC,WAAQ,IAAI,KAAK,MAAM;;AAGzB,MAAI,MAAM,YAAY,KACpB,OAAM,UAAU,SAAS;MAEzB,OAAM,QAAQ,KAAK,QAAQ;GAE7B;;AAGJ,eAAsB,gBACpB,UACY;AACZ,KAAI,OAAO,cAAc,eAAe,UAAU,MAChD,QAAO,UAAU,MAAM,QAAQ,kBAAkB,SAAS;AAE5D,QAAO,YAAY,kBAAkB,SAAS"}