@usehercules/auth 1.0.43 → 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"}
|
|
@@ -2,44 +2,74 @@ 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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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 issuer = user?.profile?.iss;
|
|
46
|
+
const subject = user?.profile?.sub;
|
|
47
|
+
const idTokenRef = useRef(idToken);
|
|
48
|
+
idTokenRef.current = idToken;
|
|
49
|
+
const signinSilentRef = useRef(signinSilent);
|
|
50
|
+
signinSilentRef.current = signinSilent;
|
|
25
51
|
const inFlightRefresh = useRef(null);
|
|
26
52
|
const fetchAccessToken = useCallback(async ({ forceRefreshToken }) => {
|
|
27
|
-
|
|
53
|
+
const currentToken = idTokenRef.current;
|
|
54
|
+
if (!forceRefreshToken) return currentToken ?? null;
|
|
55
|
+
if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) return currentToken;
|
|
28
56
|
if (inFlightRefresh.current) return inFlightRefresh.current;
|
|
29
|
-
const refresh = (async () => {
|
|
57
|
+
const refresh = withLock(LOCK_KEY, async () => {
|
|
58
|
+
const tokenAfterLock = idTokenRef.current;
|
|
59
|
+
if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) return tokenAfterLock;
|
|
30
60
|
try {
|
|
31
|
-
return (await
|
|
61
|
+
return (await signinSilentRef.current())?.id_token ?? null;
|
|
32
62
|
} catch {
|
|
33
63
|
return null;
|
|
34
|
-
} finally {
|
|
35
|
-
inFlightRefresh.current = null;
|
|
36
64
|
}
|
|
37
|
-
})()
|
|
65
|
+
}).finally(() => {
|
|
66
|
+
inFlightRefresh.current = null;
|
|
67
|
+
});
|
|
38
68
|
inFlightRefresh.current = refresh;
|
|
39
69
|
return refresh;
|
|
40
|
-
}, [
|
|
70
|
+
}, [issuer, subject]);
|
|
41
71
|
return useMemo(() => ({
|
|
42
|
-
isLoading,
|
|
72
|
+
isLoading: isAuthenticated ? false : isLoading,
|
|
43
73
|
isAuthenticated,
|
|
44
74
|
fetchAccessToken
|
|
45
75
|
}), [
|
|
@@ -48,6 +78,21 @@ function useUseAuthFromHercules() {
|
|
|
48
78
|
fetchAccessToken
|
|
49
79
|
]);
|
|
50
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* A wrapper React component which provides a {@link ConvexReactClient}
|
|
83
|
+
* authenticated with Hercules Auth.
|
|
84
|
+
*
|
|
85
|
+
* It must be wrapped by a configured `{@link HerculesAuthProvider}`.
|
|
86
|
+
*
|
|
87
|
+
* @public
|
|
88
|
+
*/
|
|
89
|
+
function ConvexProviderWithHerculesAuth({ children, client }) {
|
|
90
|
+
return /* @__PURE__ */ jsx(ConvexProviderWithAuth, {
|
|
91
|
+
client,
|
|
92
|
+
useAuth: useUseAuthFromHercules,
|
|
93
|
+
children
|
|
94
|
+
});
|
|
95
|
+
}
|
|
51
96
|
|
|
52
97
|
//#endregion
|
|
53
98
|
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\
|
|
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,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;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,SAAS,UAAU,YAAY;GAC7C,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"}
|
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,
|
|
@@ -26,8 +26,9 @@
|
|
|
26
26
|
"access": "public"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
+
"jwt-decode": "^4.0.0",
|
|
29
30
|
"oidc-client-ts": "^3.4.1",
|
|
30
|
-
"react-oidc-context": "^3.3.
|
|
31
|
+
"react-oidc-context": "^3.3.1",
|
|
31
32
|
"zod": "^4.3.6"
|
|
32
33
|
},
|
|
33
34
|
"peerDependencies": {
|
|
@@ -2,9 +2,16 @@ 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
|
|
|
9
|
+
function makeJwt(exp: number): string {
|
|
10
|
+
const header = btoa(JSON.stringify({ alg: "none" }));
|
|
11
|
+
const payload = btoa(JSON.stringify({ exp }));
|
|
12
|
+
return `${header}.${payload}.sig`;
|
|
13
|
+
}
|
|
14
|
+
|
|
8
15
|
const mockSigninSilent = vi.fn();
|
|
9
16
|
|
|
10
17
|
let mockAuthState: Record<string, unknown> = {};
|
|
@@ -36,11 +43,16 @@ vi.mock("convex/react", () => ({
|
|
|
36
43
|
},
|
|
37
44
|
}));
|
|
38
45
|
|
|
46
|
+
// Token expiring in 30 minutes (within the 1hr refresh threshold)
|
|
47
|
+
const EXPIRING_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 30 * 60);
|
|
48
|
+
// Token expiring in 2 hours (outside the 1hr refresh threshold)
|
|
49
|
+
const LONG_LIVED_TOKEN = makeJwt(Math.floor(Date.now() / 1000) + 2 * 60 * 60);
|
|
50
|
+
|
|
39
51
|
function setAuthState(overrides: Record<string, unknown>) {
|
|
40
52
|
mockAuthState = {
|
|
41
53
|
isLoading: false,
|
|
42
54
|
isAuthenticated: true,
|
|
43
|
-
user: { id_token:
|
|
55
|
+
user: { id_token: EXPIRING_TOKEN },
|
|
44
56
|
signinSilent: mockSigninSilent,
|
|
45
57
|
...overrides,
|
|
46
58
|
};
|
|
@@ -67,6 +79,26 @@ function renderUseAuth() {
|
|
|
67
79
|
return renderHook(() => captured());
|
|
68
80
|
}
|
|
69
81
|
|
|
82
|
+
describe("ConvexProviderWithHerculesAuth isLoading", () => {
|
|
83
|
+
it("reports isLoading false when isAuthenticated is true even if underlying isLoading is true", () => {
|
|
84
|
+
setAuthState({ isLoading: true, isAuthenticated: true });
|
|
85
|
+
|
|
86
|
+
const { result } = renderUseAuth();
|
|
87
|
+
|
|
88
|
+
expect(result.current.isLoading).toBe(false);
|
|
89
|
+
expect(result.current.isAuthenticated).toBe(true);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("reports isLoading true when not authenticated and still loading", () => {
|
|
93
|
+
setAuthState({ isLoading: true, isAuthenticated: false, user: null });
|
|
94
|
+
|
|
95
|
+
const { result } = renderUseAuth();
|
|
96
|
+
|
|
97
|
+
expect(result.current.isLoading).toBe(true);
|
|
98
|
+
expect(result.current.isAuthenticated).toBe(false);
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
70
102
|
describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
|
|
71
103
|
it("returns the cached id token when forceRefreshToken is false", async () => {
|
|
72
104
|
const { result } = renderUseAuth();
|
|
@@ -75,7 +107,20 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
|
|
|
75
107
|
forceRefreshToken: false,
|
|
76
108
|
});
|
|
77
109
|
|
|
78
|
-
expect(token).toBe(
|
|
110
|
+
expect(token).toBe(EXPIRING_TOKEN);
|
|
111
|
+
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it("skips refresh when token expires more than 1 hour from now", async () => {
|
|
115
|
+
setAuthState({ user: { id_token: LONG_LIVED_TOKEN } });
|
|
116
|
+
|
|
117
|
+
const { result } = renderUseAuth();
|
|
118
|
+
|
|
119
|
+
const token = await result.current.fetchAccessToken({
|
|
120
|
+
forceRefreshToken: true,
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
expect(token).toBe(LONG_LIVED_TOKEN);
|
|
79
124
|
expect(mockSigninSilent).not.toHaveBeenCalled();
|
|
80
125
|
});
|
|
81
126
|
|
|
@@ -193,4 +238,83 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
|
|
|
193
238
|
expect(secondToken).toBe("second-fresh");
|
|
194
239
|
expect(mockSigninSilent).toHaveBeenCalledTimes(2);
|
|
195
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
|
+
});
|
|
196
320
|
});
|
|
@@ -2,67 +2,153 @@
|
|
|
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
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
*
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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>(
|
|
25
|
+
key: string,
|
|
26
|
+
callback: () => Promise<T>,
|
|
27
|
+
): Promise<T> {
|
|
28
|
+
if (typeof navigator !== "undefined" && navigator.locks) {
|
|
29
|
+
return navigator.locks.request(key, callback);
|
|
30
|
+
}
|
|
31
|
+
return manualMutex(key, callback);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const mutexes = new Map<
|
|
35
|
+
string,
|
|
36
|
+
{ running: Promise<void> | null; waiting: Array<() => Promise<void>> }
|
|
37
|
+
>();
|
|
38
|
+
|
|
39
|
+
async function manualMutex<T>(
|
|
40
|
+
key: string,
|
|
41
|
+
callback: () => Promise<T>,
|
|
42
|
+
): Promise<T> {
|
|
43
|
+
return new Promise<T>((resolve, reject) => {
|
|
44
|
+
const wrapped = () =>
|
|
45
|
+
callback()
|
|
46
|
+
.then(resolve)
|
|
47
|
+
.catch(reject)
|
|
48
|
+
.finally(() => {
|
|
49
|
+
const mutex = mutexes.get(key)!;
|
|
50
|
+
const next = mutex.waiting.shift();
|
|
51
|
+
if (next) {
|
|
52
|
+
mutex.running = next();
|
|
53
|
+
} else {
|
|
54
|
+
mutex.running = null;
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
let mutex = mutexes.get(key);
|
|
59
|
+
if (!mutex) {
|
|
60
|
+
mutex = { running: null, waiting: [] };
|
|
61
|
+
mutexes.set(key, mutex);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (mutex.running === null) {
|
|
65
|
+
mutex.running = wrapped();
|
|
66
|
+
} else {
|
|
67
|
+
mutex.waiting.push(wrapped);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
29
70
|
}
|
|
30
71
|
|
|
31
72
|
function useUseAuthFromHercules() {
|
|
32
73
|
const { isAuthenticated, user, isLoading, signinSilent } = useAuth();
|
|
33
74
|
const idToken = user?.id_token;
|
|
75
|
+
const issuer = user?.profile?.iss;
|
|
76
|
+
const subject = user?.profile?.sub;
|
|
77
|
+
|
|
78
|
+
const idTokenRef = useRef(idToken);
|
|
79
|
+
idTokenRef.current = idToken;
|
|
80
|
+
|
|
81
|
+
const signinSilentRef = useRef(signinSilent);
|
|
82
|
+
signinSilentRef.current = signinSilent;
|
|
34
83
|
|
|
35
84
|
const inFlightRefresh = useRef<Promise<string | null> | null>(null);
|
|
36
85
|
|
|
37
86
|
const fetchAccessToken = useCallback(
|
|
38
87
|
async ({ forceRefreshToken }: { forceRefreshToken: boolean }) => {
|
|
88
|
+
const currentToken = idTokenRef.current;
|
|
39
89
|
if (!forceRefreshToken) {
|
|
40
|
-
return
|
|
90
|
+
return currentToken ?? null;
|
|
91
|
+
}
|
|
92
|
+
if (
|
|
93
|
+
currentToken != null &&
|
|
94
|
+
!tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
|
|
95
|
+
) {
|
|
96
|
+
return currentToken;
|
|
41
97
|
}
|
|
42
98
|
if (inFlightRefresh.current) {
|
|
43
99
|
return inFlightRefresh.current;
|
|
44
100
|
}
|
|
45
|
-
const refresh = (async () => {
|
|
101
|
+
const refresh = withLock(LOCK_KEY, async () => {
|
|
102
|
+
const tokenAfterLock = idTokenRef.current;
|
|
103
|
+
if (
|
|
104
|
+
tokenAfterLock != null &&
|
|
105
|
+
!tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)
|
|
106
|
+
) {
|
|
107
|
+
return tokenAfterLock;
|
|
108
|
+
}
|
|
46
109
|
try {
|
|
47
|
-
const refreshed = await
|
|
110
|
+
const refreshed = await signinSilentRef.current();
|
|
48
111
|
return refreshed?.id_token ?? null;
|
|
49
112
|
} catch {
|
|
50
113
|
return null;
|
|
51
|
-
} finally {
|
|
52
|
-
inFlightRefresh.current = null;
|
|
53
114
|
}
|
|
54
|
-
})()
|
|
115
|
+
}).finally(() => {
|
|
116
|
+
inFlightRefresh.current = null;
|
|
117
|
+
});
|
|
55
118
|
inFlightRefresh.current = refresh;
|
|
56
119
|
return refresh;
|
|
57
120
|
},
|
|
58
|
-
[
|
|
121
|
+
[issuer, subject],
|
|
59
122
|
);
|
|
123
|
+
|
|
60
124
|
return useMemo(
|
|
61
125
|
() => ({
|
|
62
|
-
isLoading,
|
|
126
|
+
isLoading: isAuthenticated ? false : isLoading,
|
|
63
127
|
isAuthenticated,
|
|
64
128
|
fetchAccessToken,
|
|
65
129
|
}),
|
|
66
130
|
[isLoading, isAuthenticated, fetchAccessToken],
|
|
67
131
|
);
|
|
68
132
|
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A wrapper React component which provides a {@link ConvexReactClient}
|
|
136
|
+
* authenticated with Hercules Auth.
|
|
137
|
+
*
|
|
138
|
+
* It must be wrapped by a configured `{@link HerculesAuthProvider}`.
|
|
139
|
+
*
|
|
140
|
+
* @public
|
|
141
|
+
*/
|
|
142
|
+
export function ConvexProviderWithHerculesAuth({
|
|
143
|
+
children,
|
|
144
|
+
client,
|
|
145
|
+
}: {
|
|
146
|
+
children: ReactNode;
|
|
147
|
+
client: ConvexReactClient;
|
|
148
|
+
}) {
|
|
149
|
+
return (
|
|
150
|
+
<ConvexProviderWithAuth client={client} useAuth={useUseAuthFromHercules}>
|
|
151
|
+
{children}
|
|
152
|
+
</ConvexProviderWithAuth>
|
|
153
|
+
);
|
|
154
|
+
}
|