@usehercules/auth 1.0.43 → 1.0.44

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 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":[],"mappings":";;;;;iBAgBgB,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"],"sourcesContent":[],"mappings":";;;;;iBAuIgB,8BAAA;;;AAAhB;YAIY;UACF;AALV,CAAA,CAAA,EAMC,kBAAA,CAAA,GAAA,CAAA,OAN6C"}
@@ -2,44 +2,69 @@ import { useCallback, useMemo, useRef } from "react";
2
2
  import { useAuth } from "react-oidc-context";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  import { ConvexProviderWithAuth } from "convex/react";
5
+ import { jwtDecode } from "jwt-decode";
5
6
 
6
7
  //#region src/convex-react/ConvexProviderWithHercules.tsx
7
- /**
8
- * A wrapper React component which provides a {@link ConvexReactClient}
9
- * authenticated with Hercules Auth.
10
- *
11
- * It must be wrapped by a configured `{@link HerculesAuthProvider}`.
12
- *
13
- * @public
14
- */
15
- function ConvexProviderWithHerculesAuth({ children, client }) {
16
- return /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
17
- client,
18
- useAuth: useUseAuthFromHercules,
19
- children
8
+ const REFRESH_THRESHOLD_MS = 3600 * 1e3;
9
+ const LOCK_KEY = "__herculesAuthRefresh";
10
+ function tokenExpiresWithin(token, ms) {
11
+ try {
12
+ return jwtDecode(token).exp * 1e3 - Date.now() < ms;
13
+ } catch {
14
+ return true;
15
+ }
16
+ }
17
+ async function withLock(key, callback) {
18
+ if (typeof navigator !== "undefined" && navigator.locks) return navigator.locks.request(key, callback);
19
+ return manualMutex(key, callback);
20
+ }
21
+ const mutexes = /* @__PURE__ */ new Map();
22
+ async function manualMutex(key, callback) {
23
+ return new Promise((resolve, reject) => {
24
+ const wrapped = () => callback().then(resolve).catch(reject).finally(() => {
25
+ const mutex$1 = mutexes.get(key);
26
+ const next = mutex$1.waiting.shift();
27
+ if (next) mutex$1.running = next();
28
+ else mutex$1.running = null;
29
+ });
30
+ let mutex = mutexes.get(key);
31
+ if (!mutex) {
32
+ mutex = {
33
+ running: null,
34
+ waiting: []
35
+ };
36
+ mutexes.set(key, mutex);
37
+ }
38
+ if (mutex.running === null) mutex.running = wrapped();
39
+ else mutex.waiting.push(wrapped);
20
40
  });
21
41
  }
22
42
  function useUseAuthFromHercules() {
23
43
  const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
24
44
  const idToken = user?.id_token;
45
+ const idTokenRef = useRef(idToken);
46
+ idTokenRef.current = idToken;
25
47
  const inFlightRefresh = useRef(null);
26
48
  const fetchAccessToken = useCallback(async ({ forceRefreshToken }) => {
27
49
  if (!forceRefreshToken) return idToken ?? null;
50
+ if (idToken != null && !tokenExpiresWithin(idToken, REFRESH_THRESHOLD_MS)) return idToken;
28
51
  if (inFlightRefresh.current) return inFlightRefresh.current;
29
- const refresh = (async () => {
52
+ const refresh = withLock(LOCK_KEY, async () => {
53
+ const currentToken = idTokenRef.current;
54
+ if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) return currentToken;
30
55
  try {
31
56
  return (await signinSilent())?.id_token ?? null;
32
57
  } catch {
33
58
  return null;
34
- } finally {
35
- inFlightRefresh.current = null;
36
59
  }
37
- })();
60
+ }).finally(() => {
61
+ inFlightRefresh.current = null;
62
+ });
38
63
  inFlightRefresh.current = refresh;
39
64
  return refresh;
40
65
  }, [idToken, signinSilent]);
41
66
  return useMemo(() => ({
42
- isLoading,
67
+ isLoading: isAuthenticated ? false : isLoading,
43
68
  isAuthenticated,
44
69
  fetchAccessToken
45
70
  }), [
@@ -48,6 +73,21 @@ function useUseAuthFromHercules() {
48
73
  fetchAccessToken
49
74
  ]);
50
75
  }
76
+ /**
77
+ * A wrapper React component which provides a {@link ConvexReactClient}
78
+ * authenticated with Hercules Auth.
79
+ *
80
+ * It must be wrapped by a configured `{@link HerculesAuthProvider}`.
81
+ *
82
+ * @public
83
+ */
84
+ function ConvexProviderWithHerculesAuth({ children, client }) {
85
+ return /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
86
+ client,
87
+ useAuth: useUseAuthFromHercules,
88
+ children
89
+ });
90
+ }
51
91
 
52
92
  //#endregion
53
93
  export { ConvexProviderWithHerculesAuth };
@@ -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 { useCallback, useMemo, useRef } from \"react\";\nimport { useAuth } from \"react-oidc-context\";\nimport type { HerculesAuthProvider } from \"../react/HerculesAuthProvider\";\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\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n\n const inFlightRefresh = useRef<Promise<string | null> | null>(null);\n\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {\n if (!forceRefreshToken) {\n return idToken ?? null;\n }\n if (inFlightRefresh.current) {\n return inFlightRefresh.current;\n }\n const refresh = (async () => {\n try {\n const refreshed = await signinSilent();\n return refreshed?.id_token ?? null;\n } catch {\n return null;\n } finally {\n inFlightRefresh.current = null;\n }\n })();\n inFlightRefresh.current = refresh;\n return refresh;\n },\n [idToken, signinSilent],\n );\n return useMemo(\n () => ({\n isLoading,\n isAuthenticated,\n fetchAccessToken,\n }),\n [isLoading, isAuthenticated, fetchAccessToken],\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,SAAgB,+BAA+B,EAC7C,UACA,UAIC;AACD,QACE,oBAAC;EAA+B;EAAQ,SAAS;EAC9C;GACsB;;AAI7B,SAAS,yBAAyB;CAChC,MAAM,EAAE,iBAAiB,MAAM,WAAW,iBAAiB,SAAS;CACpE,MAAM,UAAU,MAAM;CAEtB,MAAM,kBAAkB,OAAsC,KAAK;CAEnE,MAAM,mBAAmB,YACvB,OAAO,EAAE,wBAAwD;AAC/D,MAAI,CAAC,kBACH,QAAO,WAAW;AAEpB,MAAI,gBAAgB,QAClB,QAAO,gBAAgB;EAEzB,MAAM,WAAW,YAAY;AAC3B,OAAI;AAEF,YADkB,MAAM,cAAc,GACpB,YAAY;WACxB;AACN,WAAO;aACC;AACR,oBAAgB,UAAU;;MAE1B;AACJ,kBAAgB,UAAU;AAC1B,SAAO;IAET,CAAC,SAAS,aAAa,CACxB;AACD,QAAO,eACE;EACL;EACA;EACA;EACD,GACD;EAAC;EAAW;EAAiB;EAAiB,CAC/C"}
1
+ {"version":3,"file":"index.mjs","names":["mutex"],"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 type { HerculesAuthProvider } from \"../react/HerculesAuthProvider\";\n\nconst REFRESH_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour\nconst LOCK_KEY = \"__herculesAuthRefresh\";\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\n// Cross-tab mutex: uses Web Locks API when available, falls back to a\n// simple in-memory queue for environments that don't support it.\nasync function withLock<T>(key: string, callback: () => Promise<T>): Promise<T> {\n if (typeof navigator !== \"undefined\" && navigator.locks) {\n return navigator.locks.request(key, callback);\n }\n return manualMutex(key, callback);\n}\n\nconst mutexes = new Map<\n string,\n { running: Promise<void> | null; waiting: Array<() => Promise<void>> }\n>();\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\nfunction useUseAuthFromHercules() {\n const { isAuthenticated, user, isLoading, signinSilent } = useAuth();\n const idToken = user?.id_token;\n\n // Ref so the re-check inside the lock sees updates from other tabs\n const idTokenRef = useRef(idToken);\n idTokenRef.current = idToken;\n\n const inFlightRefresh = useRef<Promise<string | null> | null>(null);\n\n const fetchAccessToken = useCallback(\n async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {\n if (!forceRefreshToken) {\n return idToken ?? null;\n }\n if (\n idToken != null &&\n !tokenExpiresWithin(idToken, REFRESH_THRESHOLD_MS)\n ) {\n return idToken;\n }\n // Same-tab dedup: concurrent callers share one promise\n if (inFlightRefresh.current) {\n return inFlightRefresh.current;\n }\n const refresh = withLock(LOCK_KEY, async () => {\n // Re-check after acquiring lock — another tab may have refreshed\n const currentToken = idTokenRef.current;\n if (\n currentToken != null &&\n !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)\n ) {\n return currentToken;\n }\n try {\n const refreshed = await signinSilent();\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 [idToken, signinSilent],\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":";;;;;;;AASA,MAAM,uBAAuB,OAAU;AACvC,MAAM,WAAW;AAEjB,SAAS,mBAAmB,OAAe,IAAqB;AAC9D,KAAI;AAEF,SADgB,UAAU,MAAM,CACjB,MAAO,MAAO,KAAK,KAAK,GAAG;SACpC;AACN,SAAO;;;AAMX,eAAe,SAAY,KAAa,UAAwC;AAC9E,KAAI,OAAO,cAAc,eAAe,UAAU,MAChD,QAAO,UAAU,MAAM,QAAQ,KAAK,SAAS;AAE/C,QAAO,YAAY,KAAK,SAAS;;AAGnC,MAAM,0BAAU,IAAI,KAGjB;AAEH,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,SAAS,yBAAyB;CAChC,MAAM,EAAE,iBAAiB,MAAM,WAAW,iBAAiB,SAAS;CACpE,MAAM,UAAU,MAAM;CAGtB,MAAM,aAAa,OAAO,QAAQ;AAClC,YAAW,UAAU;CAErB,MAAM,kBAAkB,OAAsC,KAAK;CAEnE,MAAM,mBAAmB,YACvB,OAAO,EAAE,wBAAwD;AAC/D,MAAI,CAAC,kBACH,QAAO,WAAW;AAEpB,MACE,WAAW,QACX,CAAC,mBAAmB,SAAS,qBAAqB,CAElD,QAAO;AAGT,MAAI,gBAAgB,QAClB,QAAO,gBAAgB;EAEzB,MAAM,UAAU,SAAS,UAAU,YAAY;GAE7C,MAAM,eAAe,WAAW;AAChC,OACE,gBAAgB,QAChB,CAAC,mBAAmB,cAAc,qBAAqB,CAEvD,QAAO;AAET,OAAI;AAEF,YADkB,MAAM,cAAc,GACpB,YAAY;WACxB;AACN,WAAO;;IAET,CAAC,cAAc;AACf,mBAAgB,UAAU;IAC1B;AACF,kBAAgB,UAAU;AAC1B,SAAO;IAET,CAAC,SAAS,aAAa,CACxB;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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usehercules/auth",
3
- "version": "1.0.43",
3
+ "version": "1.0.44",
4
4
  "description": "Authentication utilities for Hercules applications using OIDC",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -26,6 +26,7 @@
26
26
  "access": "public"
27
27
  },
28
28
  "dependencies": {
29
+ "jwt-decode": "^4.0.0",
29
30
  "oidc-client-ts": "^3.4.1",
30
31
  "react-oidc-context": "^3.3.0",
31
32
  "zod": "^4.3.6"
@@ -5,6 +5,12 @@ import { ConvexProviderWithHerculesAuth } from "./ConvexProviderWithHercules.js"
5
5
 
6
6
  configure({ reactStrictMode: true });
7
7
 
8
+ function makeJwt(exp: number): string {
9
+ const header = btoa(JSON.stringify({ alg: "none" }));
10
+ const payload = btoa(JSON.stringify({ exp }));
11
+ return `${header}.${payload}.sig`;
12
+ }
13
+
8
14
  const mockSigninSilent = vi.fn();
9
15
 
10
16
  let mockAuthState: Record<string, unknown> = {};
@@ -36,11 +42,16 @@ vi.mock("convex/react", () => ({
36
42
  },
37
43
  }));
38
44
 
45
+ // Token expiring in 30 minutes (within the 1hr refresh threshold)
46
+ const EXPIRING_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
47
+ // Token expiring in 2 hours (outside the 1hr refresh threshold)
48
+ const LONG_LIVED_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 2 * 60 * 60);
49
+
39
50
  function setAuthState(overrides: Record<string, unknown>) {
40
51
  mockAuthState = {
41
52
  isLoading: false,
42
53
  isAuthenticated: true,
43
- user: { id_token: "cached-token" },
54
+ user: { id_token: EXPIRING_TOKEN },
44
55
  signinSilent: mockSigninSilent,
45
56
  ...overrides,
46
57
  };
@@ -67,6 +78,26 @@ function renderUseAuth() {
67
78
  return renderHook(() => captured());
68
79
  }
69
80
 
81
+ describe("ConvexProviderWithHerculesAuth isLoading", () => {
82
+ it("reports isLoading false when isAuthenticated is true even if underlying isLoading is true", () => {
83
+ setAuthState({ isLoading: true, isAuthenticated: true });
84
+
85
+ const { result } = renderUseAuth();
86
+
87
+ expect(result.current.isLoading).toBe(false);
88
+ expect(result.current.isAuthenticated).toBe(true);
89
+ });
90
+
91
+ it("reports isLoading true when not authenticated and still loading", () => {
92
+ setAuthState({ isLoading: true, isAuthenticated: false, user: null });
93
+
94
+ const { result } = renderUseAuth();
95
+
96
+ expect(result.current.isLoading).toBe(true);
97
+ expect(result.current.isAuthenticated).toBe(false);
98
+ });
99
+ });
100
+
70
101
  describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
71
102
  it("returns the cached id token when forceRefreshToken is false", async () => {
72
103
  const { result } = renderUseAuth();
@@ -75,7 +106,20 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
75
106
  forceRefreshToken: false,
76
107
  });
77
108
 
78
- expect(token).toBe("cached-token");
109
+ expect(token).toBe(EXPIRING_TOKEN);
110
+ expect(mockSigninSilent).not.toHaveBeenCalled();
111
+ });
112
+
113
+ it("skips refresh when token expires more than 1 hour from now", async () => {
114
+ setAuthState({ user: { id_token: LONG_LIVED_TOKEN } });
115
+
116
+ const { result } = renderUseAuth();
117
+
118
+ const token = await result.current.fetchAccessToken({
119
+ forceRefreshToken: true,
120
+ });
121
+
122
+ expect(token).toBe(LONG_LIVED_TOKEN);
79
123
  expect(mockSigninSilent).not.toHaveBeenCalled();
80
124
  });
81
125
 
@@ -2,36 +2,78 @@
2
2
 
3
3
  import type { ReactNode } from "react";
4
4
  import { ConvexProviderWithAuth, type ConvexReactClient } from "convex/react";
5
+ import { jwtDecode } from "jwt-decode";
5
6
  import { useCallback, useMemo, useRef } from "react";
6
7
  import { useAuth } from "react-oidc-context";
7
8
  import type { HerculesAuthProvider } from "../react/HerculesAuthProvider";
8
9
 
9
- /**
10
- * A wrapper React component which provides a {@link ConvexReactClient}
11
- * authenticated with Hercules Auth.
12
- *
13
- * It must be wrapped by a configured `{@link HerculesAuthProvider}`.
14
- *
15
- * @public
16
- */
17
- export function ConvexProviderWithHerculesAuth({
18
- children,
19
- client,
20
- }: {
21
- children: ReactNode;
22
- client: ConvexReactClient;
23
- }) {
24
- return (
25
- <ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>
26
- {children}
27
- </ConvexProviderWithAuth>
28
- );
10
+ const REFRESH_THRESHOLD_MS = 60 * 60 * 1000; // 1 hour
11
+ const LOCK_KEY = "__herculesAuthRefresh";
12
+
13
+ function tokenExpiresWithin(token: string, ms: number): boolean {
14
+ try {
15
+ const payload = jwtDecode(token);
16
+ return payload.exp! * 1000 - Date.now() < ms;
17
+ } catch {
18
+ return true;
19
+ }
20
+ }
21
+
22
+ // Cross-tab mutex: uses Web Locks API when available, falls back to a
23
+ // simple in-memory queue for environments that don't support it.
24
+ async function withLock<T>(key: string, callback: () => Promise<T>): Promise<T> {
25
+ if (typeof navigator !== "undefined" && navigator.locks) {
26
+ return navigator.locks.request(key, callback);
27
+ }
28
+ return manualMutex(key, callback);
29
+ }
30
+
31
+ const mutexes = new Map<
32
+ string,
33
+ { running: Promise<void> | null; waiting: Array<() => Promise<void>> }
34
+ >();
35
+
36
+ async function manualMutex<T>(
37
+ key: string,
38
+ callback: () => Promise<T>,
39
+ ): Promise<T> {
40
+ return new Promise<T>((resolve, reject) => {
41
+ const wrapped = () =>
42
+ callback()
43
+ .then(resolve)
44
+ .catch(reject)
45
+ .finally(() => {
46
+ const mutex = mutexes.get(key)!;
47
+ const next = mutex.waiting.shift();
48
+ if (next) {
49
+ mutex.running = next();
50
+ } else {
51
+ mutex.running = null;
52
+ }
53
+ });
54
+
55
+ let mutex = mutexes.get(key);
56
+ if (!mutex) {
57
+ mutex = { running: null, waiting: [] };
58
+ mutexes.set(key, mutex);
59
+ }
60
+
61
+ if (mutex.running === null) {
62
+ mutex.running = wrapped();
63
+ } else {
64
+ mutex.waiting.push(wrapped);
65
+ }
66
+ });
29
67
  }
30
68
 
31
69
  function useUseAuthFromHercules() {
32
70
  const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
33
71
  const idToken = user?.id_token;
34
72
 
73
+ // Ref so the re-check inside the lock sees updates from other tabs
74
+ const idTokenRef = useRef(idToken);
75
+ idTokenRef.current = idToken;
76
+
35
77
  const inFlightRefresh = useRef<Promise<string | null> | null>(null);
36
78
 
37
79
  const fetchAccessToken = useCallback(
@@ -39,30 +81,68 @@ function useUseAuthFromHercules() {
39
81
  if (!forceRefreshToken) {
40
82
  return idToken ?? null;
41
83
  }
84
+ if (
85
+ idToken != null &&
86
+ !tokenExpiresWithin(idToken, REFRESH_THRESHOLD_MS)
87
+ ) {
88
+ return idToken;
89
+ }
90
+ // Same-tab dedup: concurrent callers share one promise
42
91
  if (inFlightRefresh.current) {
43
92
  return inFlightRefresh.current;
44
93
  }
45
- const refresh = (async () => {
94
+ const refresh = withLock(LOCK_KEY, async () => {
95
+ // Re-check after acquiring lock — another tab may have refreshed
96
+ const currentToken = idTokenRef.current;
97
+ if (
98
+ currentToken != null &&
99
+ !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
100
+ ) {
101
+ return currentToken;
102
+ }
46
103
  try {
47
104
  const refreshed = await signinSilent();
48
105
  return refreshed?.id_token ?? null;
49
106
  } catch {
50
107
  return null;
51
- } finally {
52
- inFlightRefresh.current = null;
53
108
  }
54
- })();
109
+ }).finally(() => {
110
+ inFlightRefresh.current = null;
111
+ });
55
112
  inFlightRefresh.current = refresh;
56
113
  return refresh;
57
114
  },
58
115
  [idToken, signinSilent],
59
116
  );
117
+
60
118
  return useMemo(
61
119
  () => ({
62
- isLoading,
120
+ isLoading: isAuthenticated ? false : isLoading,
63
121
  isAuthenticated,
64
122
  fetchAccessToken,
65
123
  }),
66
124
  [isLoading, isAuthenticated, fetchAccessToken],
67
125
  );
68
126
  }
127
+
128
+ /**
129
+ * A wrapper React component which provides a {@link ConvexReactClient}
130
+ * authenticated with Hercules Auth.
131
+ *
132
+ * It must be wrapped by a configured `{@link HerculesAuthProvider}`.
133
+ *
134
+ * @public
135
+ */
136
+ export function ConvexProviderWithHerculesAuth({
137
+ children,
138
+ client,
139
+ }: {
140
+ children: ReactNode;
141
+ client: ConvexReactClient;
142
+ }) {
143
+ return (
144
+ <ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>
145
+ {children}
146
+ </ConvexProviderWithAuth>
147
+ );
148
+ }