@usehercules/auth 1.0.44 → 1.0.45
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":";;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/convex-react/ConvexProviderWithHercules.tsx"],"sourcesContent":[],"mappings":";;;;;iBA6IgB,8BAAA;;;AAAhB;YAIY;UACF;AALV,CAAA,CAAA,EAMC,kBAAA,CAAA,GAAA,CAAA,OAN6C"}
|
|
@@ -42,18 +42,23 @@ async function manualMutex(key, callback) {
|
|
|
42
42
|
function useUseAuthFromHercules() {
|
|
43
43
|
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
44
44
|
const idToken = user?.id_token;
|
|
45
|
+
const issuer = user?.profile?.iss;
|
|
46
|
+
const subject = user?.profile?.sub;
|
|
45
47
|
const idTokenRef = useRef(idToken);
|
|
46
48
|
idTokenRef.current = idToken;
|
|
49
|
+
const signinSilentRef = useRef(signinSilent);
|
|
50
|
+
signinSilentRef.current = signinSilent;
|
|
47
51
|
const inFlightRefresh = useRef(null);
|
|
48
52
|
const fetchAccessToken = useCallback(async ({ forceRefreshToken }) => {
|
|
49
|
-
|
|
50
|
-
if (
|
|
53
|
+
const currentToken = idTokenRef.current;
|
|
54
|
+
if (!forceRefreshToken) return currentToken ?? null;
|
|
55
|
+
if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) return currentToken;
|
|
51
56
|
if (inFlightRefresh.current) return inFlightRefresh.current;
|
|
52
57
|
const refresh = withLock(LOCK_KEY, async () => {
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
58
|
+
const tokenAfterLock = idTokenRef.current;
|
|
59
|
+
if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) return tokenAfterLock;
|
|
55
60
|
try {
|
|
56
|
-
return (await
|
|
61
|
+
return (await signinSilentRef.current())?.id_token ?? null;
|
|
57
62
|
} catch {
|
|
58
63
|
return null;
|
|
59
64
|
}
|
|
@@ -62,7 +67,7 @@ function useUseAuthFromHercules() {
|
|
|
62
67
|
});
|
|
63
68
|
inFlightRefresh.current = refresh;
|
|
64
69
|
return refresh;
|
|
65
|
-
}, [
|
|
70
|
+
}, [issuer, subject]);
|
|
66
71
|
return useMemo(() => ({
|
|
67
72
|
isLoading: isAuthenticated ? false : isLoading,
|
|
68
73
|
isAuthenticated,
|
|
@@ -1 +1 @@
|
|
|
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
|
|
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>(\n key: string,\n callback: () => Promise<T>,\n): 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 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 = withLock(LOCK_KEY, 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":";;;;;;;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,SACb,KACA,UACY;AACZ,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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AAC,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@usehercules/auth",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.45",
|
|
4
4
|
"description": "Authentication utilities for Hercules applications using OIDC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"jwt-decode": "^4.0.0",
|
|
30
30
|
"oidc-client-ts": "^3.4.1",
|
|
31
|
-
"react-oidc-context": "^3.3.
|
|
31
|
+
"react-oidc-context": "^3.3.1",
|
|
32
32
|
"zod": "^4.3.6"
|
|
33
33
|
},
|
|
34
34
|
"peerDependencies": {
|
|
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
2
2
|
import type { ReactNode } from "react";
|
|
3
3
|
import { renderHook, act, configure } from "@testing-library/react";
|
|
4
4
|
import { ConvexProviderWithHerculesAuth } from "./ConvexProviderWithHercules.js";
|
|
5
|
+
import React from "react";
|
|
5
6
|
|
|
6
7
|
configure({ reactStrictMode: true });
|
|
7
8
|
|
|
@@ -237,4 +238,83 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
|
|
|
237
238
|
expect(secondToken).toBe("second-fresh");
|
|
238
239
|
expect(mockSigninSilent).toHaveBeenCalledTimes(2);
|
|
239
240
|
});
|
|
241
|
+
|
|
242
|
+
it("keeps fetchAccessToken stable across silent renewal of the same subject", async () => {
|
|
243
|
+
const FIRST_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
244
|
+
const SECOND_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 60 * 60);
|
|
245
|
+
setAuthState({
|
|
246
|
+
user: {
|
|
247
|
+
id_token: FIRST_TOKEN,
|
|
248
|
+
profile: { iss: "https://issuer.example", sub: "alice" },
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
const { result, rerender } = renderUseAuth();
|
|
253
|
+
const firstFetch = result.current.fetchAccessToken;
|
|
254
|
+
|
|
255
|
+
expect(
|
|
256
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
257
|
+
).toBe(FIRST_TOKEN);
|
|
258
|
+
|
|
259
|
+
setAuthState({
|
|
260
|
+
user: {
|
|
261
|
+
id_token: SECOND_TOKEN,
|
|
262
|
+
profile: { iss: "https://issuer.example", sub: "alice" },
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
rerender();
|
|
266
|
+
|
|
267
|
+
expect(result.current.fetchAccessToken).toBe(firstFetch);
|
|
268
|
+
expect(
|
|
269
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
270
|
+
).toBe(SECOND_TOKEN);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
it("re-identifies fetchAccessToken when the subject changes", async () => {
|
|
274
|
+
const ALICE_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
275
|
+
const BOB_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
276
|
+
setAuthState({
|
|
277
|
+
user: { id_token: ALICE_TOKEN, profile: { sub: "alice" } },
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
const { result, rerender } = renderUseAuth();
|
|
281
|
+
const aliceFetch = result.current.fetchAccessToken;
|
|
282
|
+
|
|
283
|
+
setAuthState({
|
|
284
|
+
user: { id_token: BOB_TOKEN, profile: { sub: "bob" } },
|
|
285
|
+
});
|
|
286
|
+
rerender();
|
|
287
|
+
|
|
288
|
+
expect(
|
|
289
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
290
|
+
).toBe(BOB_TOKEN);
|
|
291
|
+
expect(result.current.fetchAccessToken).not.toBe(aliceFetch);
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("re-identifies fetchAccessToken when the issuer changes", async () => {
|
|
295
|
+
const FIRST_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
296
|
+
const SECOND_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
297
|
+
setAuthState({
|
|
298
|
+
user: {
|
|
299
|
+
id_token: FIRST_TOKEN,
|
|
300
|
+
profile: { iss: "https://issuer-a.example", sub: "shared-sub" },
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
const { result, rerender } = renderUseAuth();
|
|
305
|
+
const firstFetch = result.current.fetchAccessToken;
|
|
306
|
+
|
|
307
|
+
setAuthState({
|
|
308
|
+
user: {
|
|
309
|
+
id_token: SECOND_TOKEN,
|
|
310
|
+
profile: { iss: "https://issuer-b.example", sub: "shared-sub" },
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
rerender();
|
|
314
|
+
|
|
315
|
+
expect(result.current.fetchAccessToken).not.toBe(firstFetch);
|
|
316
|
+
expect(
|
|
317
|
+
await result.current.fetchAccessToken({ forceRefreshToken: false }),
|
|
318
|
+
).toBe(SECOND_TOKEN);
|
|
319
|
+
});
|
|
240
320
|
});
|
|
@@ -21,7 +21,10 @@ function tokenExpiresWithin(token: string, ms: number): boolean {
|
|
|
21
21
|
|
|
22
22
|
// Cross-tab mutex: uses Web Locks API when available, falls back to a
|
|
23
23
|
// simple in-memory queue for environments that don't support it.
|
|
24
|
-
async function withLock<T>(
|
|
24
|
+
async function withLock<T>(
|
|
25
|
+
key: string,
|
|
26
|
+
callback: () => Promise<T>,
|
|
27
|
+
): Promise<T> {
|
|
25
28
|
if (typeof navigator !== "undefined" && navigator.locks) {
|
|
26
29
|
return navigator.locks.request(key, callback);
|
|
27
30
|
}
|
|
@@ -69,39 +72,42 @@ async function manualMutex<T>(
|
|
|
69
72
|
function useUseAuthFromHercules() {
|
|
70
73
|
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
71
74
|
const idToken = user?.id_token;
|
|
75
|
+
const issuer = user?.profile?.iss;
|
|
76
|
+
const subject = user?.profile?.sub;
|
|
72
77
|
|
|
73
|
-
// Ref so the re-check inside the lock sees updates from other tabs
|
|
74
78
|
const idTokenRef = useRef(idToken);
|
|
75
79
|
idTokenRef.current = idToken;
|
|
76
80
|
|
|
81
|
+
const signinSilentRef = useRef(signinSilent);
|
|
82
|
+
signinSilentRef.current = signinSilent;
|
|
83
|
+
|
|
77
84
|
const inFlightRefresh = useRef<Promise<string | null> | null>(null);
|
|
78
85
|
|
|
79
86
|
const fetchAccessToken = useCallback(
|
|
80
87
|
async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
|
|
88
|
+
const currentToken = idTokenRef.current;
|
|
81
89
|
if (!forceRefreshToken) {
|
|
82
|
-
return
|
|
90
|
+
return currentToken ?? null;
|
|
83
91
|
}
|
|
84
92
|
if (
|
|
85
|
-
|
|
86
|
-
!tokenExpiresWithin(
|
|
93
|
+
currentToken != null &&
|
|
94
|
+
!tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
|
|
87
95
|
) {
|
|
88
|
-
return
|
|
96
|
+
return currentToken;
|
|
89
97
|
}
|
|
90
|
-
// Same-tab dedup: concurrent callers share one promise
|
|
91
98
|
if (inFlightRefresh.current) {
|
|
92
99
|
return inFlightRefresh.current;
|
|
93
100
|
}
|
|
94
101
|
const refresh = withLock(LOCK_KEY, async () => {
|
|
95
|
-
|
|
96
|
-
const currentToken = idTokenRef.current;
|
|
102
|
+
const tokenAfterLock = idTokenRef.current;
|
|
97
103
|
if (
|
|
98
|
-
|
|
99
|
-
!tokenExpiresWithin(
|
|
104
|
+
tokenAfterLock != null &&
|
|
105
|
+
!tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)
|
|
100
106
|
) {
|
|
101
|
-
return
|
|
107
|
+
return tokenAfterLock;
|
|
102
108
|
}
|
|
103
109
|
try {
|
|
104
|
-
const refreshed = await
|
|
110
|
+
const refreshed = await signinSilentRef.current();
|
|
105
111
|
return refreshed?.id_token ?? null;
|
|
106
112
|
} catch {
|
|
107
113
|
return null;
|
|
@@ -112,7 +118,7 @@ function useUseAuthFromHercules() {
|
|
|
112
118
|
inFlightRefresh.current = refresh;
|
|
113
119
|
return refresh;
|
|
114
120
|
},
|
|
115
|
-
[
|
|
121
|
+
[issuer, subject],
|
|
116
122
|
);
|
|
117
123
|
|
|
118
124
|
return useMemo(
|