@ahoo-wang/cosec-react 0.0.0 → 8.0.0-beta.1

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.
Files changed (39) hide show
  1. package/README.md +89 -2
  2. package/README.zh-CN.md +71 -0
  3. package/dist/cosec/RefreshableRouteGuard.d.cts +9 -0
  4. package/dist/cosec/RefreshableRouteGuard.d.cts.map +1 -0
  5. package/dist/cosec/RefreshableRouteGuard.d.ts +9 -0
  6. package/dist/cosec/RefreshableRouteGuard.d.ts.map +1 -0
  7. package/dist/cosec/RouteGuard.d.cts +51 -0
  8. package/dist/cosec/RouteGuard.d.cts.map +1 -0
  9. package/dist/cosec/RouteGuard.d.ts +51 -0
  10. package/dist/cosec/RouteGuard.d.ts.map +1 -0
  11. package/dist/cosec/SecurityContext.d.cts +113 -0
  12. package/dist/cosec/SecurityContext.d.cts.map +1 -0
  13. package/dist/cosec/SecurityContext.d.ts +113 -0
  14. package/dist/cosec/SecurityContext.d.ts.map +1 -0
  15. package/dist/cosec/index.d.cts +5 -0
  16. package/dist/cosec/index.d.cts.map +1 -0
  17. package/dist/cosec/index.d.ts +5 -0
  18. package/dist/cosec/index.d.ts.map +1 -0
  19. package/dist/cosec/useSecurity.d.cts +119 -0
  20. package/dist/cosec/useSecurity.d.cts.map +1 -0
  21. package/dist/cosec/useSecurity.d.ts +119 -0
  22. package/dist/cosec/useSecurity.d.ts.map +1 -0
  23. package/dist/index.d.cts +2 -0
  24. package/dist/index.d.cts.map +1 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.es.js +118 -0
  28. package/dist/index.es.js.map +1 -0
  29. package/dist/index.umd.cjs +2 -0
  30. package/dist/index.umd.cjs.map +1 -0
  31. package/dist/internal/useLatest.d.cts +14 -0
  32. package/dist/internal/useLatest.d.cts.map +1 -0
  33. package/dist/internal/useLatest.d.ts +14 -0
  34. package/dist/internal/useLatest.d.ts.map +1 -0
  35. package/dist/internal/useStoredToken.d.cts +15 -0
  36. package/dist/internal/useStoredToken.d.cts.map +1 -0
  37. package/dist/internal/useStoredToken.d.ts +15 -0
  38. package/dist/internal/useStoredToken.d.ts.map +1 -0
  39. package/package.json +91 -4
@@ -0,0 +1,119 @@
1
+ import { TokenStorage, CompositeToken, CoSecJwtPayload } from '@ahoo-wang/cosec-fetcher';
2
+ /**
3
+ * Type representing a composite token provider.
4
+ * Can be either a direct composite token or a function that returns a promise of a composite token.
5
+ */
6
+ export type CompositeTokenProvider = CompositeToken | (() => Promise<CompositeToken>);
7
+ export declare const ANONYMOUS_USER: CoSecJwtPayload;
8
+ /**
9
+ * Options for configuring the useSecurity hook.
10
+ */
11
+ export interface UseSecurityOptions {
12
+ /**
13
+ * Callback function invoked when sign in is successful.
14
+ * This is called after the token has been successfully stored.
15
+ */
16
+ onSignIn?: () => void;
17
+ /**
18
+ * Callback function invoked when sign out occurs.
19
+ * This is called after the token has been removed.
20
+ */
21
+ onSignOut?: () => void;
22
+ }
23
+ /**
24
+ * Return type for the useSecurity hook.
25
+ */
26
+ export interface UseSecurityReturn {
27
+ /**
28
+ * The stored access token's JWT payload, even once it has expired (check
29
+ * `authenticated`), or ANONYMOUS_USER when no token is stored.
30
+ */
31
+ currentUser: CoSecJwtPayload;
32
+ /**
33
+ * Boolean indicating whether the user is currently authenticated.
34
+ * True if a valid token exists and the user is signed in, false otherwise.
35
+ */
36
+ authenticated: boolean;
37
+ /**
38
+ * Function to sign in with a composite token or a function that returns a promise of composite token.
39
+ * @param compositeTokenProvider - Either a composite token containing access and refresh tokens,
40
+ * or a function that returns a promise resolving to a composite token.
41
+ * @returns A promise that resolves when the sign-in operation is complete.
42
+ */
43
+ signIn: (compositeTokenProvider: CompositeTokenProvider) => Promise<void>;
44
+ /**
45
+ * Function to sign out the current user.
46
+ */
47
+ signOut: () => void;
48
+ }
49
+ /**
50
+ * Hook for managing authentication state and operations using CoSec tokens.
51
+ *
52
+ * This hook provides reactive access to the current user information, authentication status,
53
+ * and methods to sign in and sign out. It integrates with the TokenStorage to persist tokens
54
+ * and updates the state reactively when tokens change.
55
+ *
56
+ * @param tokenStorage - The token storage instance used to manage authentication tokens.
57
+ * This should be a valid TokenStorage implementation that handles
58
+ * token persistence and retrieval.
59
+ * @param options - Optional configuration object containing lifecycle callbacks.
60
+ * @param options.onSignIn - Callback function invoked when sign in is successful.
61
+ * @param options.onSignOut - Callback function invoked when sign out occurs.
62
+ * @returns An object containing:
63
+ * - currentUser: The stored access token's JWT payload (even if expired), or ANONYMOUS_USER when no token is stored.
64
+ * - authenticated: Boolean indicating whether the user is currently authenticated
65
+ * (the access token is unexpired). Computed at render; the hook also
66
+ * re-renders when the refresh token expires, so an idle page signs out then.
67
+ * - signIn: Function to authenticate with a composite token.
68
+ * - signOut: Function to sign out the current user.
69
+ * @throws {Error} May throw errors if tokenStorage operations fail, such as invalid tokens
70
+ * or storage access issues (implementation dependent).
71
+ * @example
72
+ * ```typescript
73
+ * import { useSecurity } from '@ahoo-wang/cosec-react';
74
+ * import { tokenStorage } from './tokenStorage';
75
+ * import { useNavigate } from 'react-router-dom';
76
+ *
77
+ * function App() {
78
+ * const navigate = useNavigate();
79
+ *
80
+ * const { currentUser, authenticated, signIn, signOut } = useSecurity(tokenStorage, {
81
+ * onSignIn: () => {
82
+ * // Redirect to dashboard after successful login
83
+ * navigate('/dashboard');
84
+ * },
85
+ * onSignOut: () => {
86
+ * // Redirect to login page after logout
87
+ * navigate('/login');
88
+ * }
89
+ * });
90
+ *
91
+ * const handleSignIn = async () => {
92
+ * // Direct token
93
+ * await signIn(compositeToken);
94
+ *
95
+ * // Or async function
96
+ * await signIn(async () => {
97
+ * const response = await fetch('/api/auth/login', {
98
+ * method: 'POST',
99
+ * body: JSON.stringify({ username, password })
100
+ * });
101
+ * return response.json();
102
+ * });
103
+ * };
104
+ *
105
+ * if (!authenticated) {
106
+ * return <button onClick={handleSignIn}>Sign In</button>;
107
+ * }
108
+ *
109
+ * return (
110
+ * <div>
111
+ * <p>Welcome, {currentUser?.sub}!</p>
112
+ * <button onClick={signOut}>Sign Out</button>
113
+ * </div>
114
+ * );
115
+ * }
116
+ * ```
117
+ */
118
+ export declare function useSecurity(tokenStorage: TokenStorage, options?: UseSecurityOptions): UseSecurityReturn;
119
+ //# sourceMappingURL=useSecurity.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSecurity.d.cts","sourceRoot":"","sources":["../../src/cosec/useSecurity.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAElC;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAChC,cAAc,GAAG,CAAC,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC;AAEnD,eAAO,MAAM,cAAc,EAAE,eAK5B,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IAEtB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,WAAW,EAAE,eAAe,CAAC;IAE7B;;;OAGG;IACH,aAAa,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,MAAM,EAAE,CAAC,sBAAsB,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1E;;OAEG;IACH,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAgBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,wBAAgB,WAAW,CACzB,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,kBAAuB,GAC/B,iBAAiB,CAsDnB"}
@@ -0,0 +1,119 @@
1
+ import { TokenStorage, CompositeToken, CoSecJwtPayload } from '@ahoo-wang/cosec-fetcher';
2
+ /**
3
+ * Type representing a composite token provider.
4
+ * Can be either a direct composite token or a function that returns a promise of a composite token.
5
+ */
6
+ export type CompositeTokenProvider = CompositeToken | (() => Promise<CompositeToken>);
7
+ export declare const ANONYMOUS_USER: CoSecJwtPayload;
8
+ /**
9
+ * Options for configuring the useSecurity hook.
10
+ */
11
+ export interface UseSecurityOptions {
12
+ /**
13
+ * Callback function invoked when sign in is successful.
14
+ * This is called after the token has been successfully stored.
15
+ */
16
+ onSignIn?: () => void;
17
+ /**
18
+ * Callback function invoked when sign out occurs.
19
+ * This is called after the token has been removed.
20
+ */
21
+ onSignOut?: () => void;
22
+ }
23
+ /**
24
+ * Return type for the useSecurity hook.
25
+ */
26
+ export interface UseSecurityReturn {
27
+ /**
28
+ * The stored access token's JWT payload, even once it has expired (check
29
+ * `authenticated`), or ANONYMOUS_USER when no token is stored.
30
+ */
31
+ currentUser: CoSecJwtPayload;
32
+ /**
33
+ * Boolean indicating whether the user is currently authenticated.
34
+ * True if a valid token exists and the user is signed in, false otherwise.
35
+ */
36
+ authenticated: boolean;
37
+ /**
38
+ * Function to sign in with a composite token or a function that returns a promise of composite token.
39
+ * @param compositeTokenProvider - Either a composite token containing access and refresh tokens,
40
+ * or a function that returns a promise resolving to a composite token.
41
+ * @returns A promise that resolves when the sign-in operation is complete.
42
+ */
43
+ signIn: (compositeTokenProvider: CompositeTokenProvider) => Promise<void>;
44
+ /**
45
+ * Function to sign out the current user.
46
+ */
47
+ signOut: () => void;
48
+ }
49
+ /**
50
+ * Hook for managing authentication state and operations using CoSec tokens.
51
+ *
52
+ * This hook provides reactive access to the current user information, authentication status,
53
+ * and methods to sign in and sign out. It integrates with the TokenStorage to persist tokens
54
+ * and updates the state reactively when tokens change.
55
+ *
56
+ * @param tokenStorage - The token storage instance used to manage authentication tokens.
57
+ * This should be a valid TokenStorage implementation that handles
58
+ * token persistence and retrieval.
59
+ * @param options - Optional configuration object containing lifecycle callbacks.
60
+ * @param options.onSignIn - Callback function invoked when sign in is successful.
61
+ * @param options.onSignOut - Callback function invoked when sign out occurs.
62
+ * @returns An object containing:
63
+ * - currentUser: The stored access token's JWT payload (even if expired), or ANONYMOUS_USER when no token is stored.
64
+ * - authenticated: Boolean indicating whether the user is currently authenticated
65
+ * (the access token is unexpired). Computed at render; the hook also
66
+ * re-renders when the refresh token expires, so an idle page signs out then.
67
+ * - signIn: Function to authenticate with a composite token.
68
+ * - signOut: Function to sign out the current user.
69
+ * @throws {Error} May throw errors if tokenStorage operations fail, such as invalid tokens
70
+ * or storage access issues (implementation dependent).
71
+ * @example
72
+ * ```typescript
73
+ * import { useSecurity } from '@ahoo-wang/cosec-react';
74
+ * import { tokenStorage } from './tokenStorage';
75
+ * import { useNavigate } from 'react-router-dom';
76
+ *
77
+ * function App() {
78
+ * const navigate = useNavigate();
79
+ *
80
+ * const { currentUser, authenticated, signIn, signOut } = useSecurity(tokenStorage, {
81
+ * onSignIn: () => {
82
+ * // Redirect to dashboard after successful login
83
+ * navigate('/dashboard');
84
+ * },
85
+ * onSignOut: () => {
86
+ * // Redirect to login page after logout
87
+ * navigate('/login');
88
+ * }
89
+ * });
90
+ *
91
+ * const handleSignIn = async () => {
92
+ * // Direct token
93
+ * await signIn(compositeToken);
94
+ *
95
+ * // Or async function
96
+ * await signIn(async () => {
97
+ * const response = await fetch('/api/auth/login', {
98
+ * method: 'POST',
99
+ * body: JSON.stringify({ username, password })
100
+ * });
101
+ * return response.json();
102
+ * });
103
+ * };
104
+ *
105
+ * if (!authenticated) {
106
+ * return <button onClick={handleSignIn}>Sign In</button>;
107
+ * }
108
+ *
109
+ * return (
110
+ * <div>
111
+ * <p>Welcome, {currentUser?.sub}!</p>
112
+ * <button onClick={signOut}>Sign Out</button>
113
+ * </div>
114
+ * );
115
+ * }
116
+ * ```
117
+ */
118
+ export declare function useSecurity(tokenStorage: TokenStorage, options?: UseSecurityOptions): UseSecurityReturn;
119
+ //# sourceMappingURL=useSecurity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSecurity.d.ts","sourceRoot":"","sources":["../../src/cosec/useSecurity.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAElC;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAChC,cAAc,GAAG,CAAC,MAAM,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC;AAEnD,eAAO,MAAM,cAAc,EAAE,eAK5B,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IAEtB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,WAAW,EAAE,eAAe,CAAC;IAE7B;;;OAGG;IACH,aAAa,EAAE,OAAO,CAAC;IAEvB;;;;;OAKG;IACH,MAAM,EAAE,CAAC,sBAAsB,EAAE,sBAAsB,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAE1E;;OAEG;IACH,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAgBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,wBAAgB,WAAW,CACzB,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,kBAAuB,GAC/B,iBAAiB,CAsDnB"}
@@ -0,0 +1,2 @@
1
+ export * from './cosec/index.cjs';
2
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,cAAc,kBAAkB,CAAC"}
@@ -0,0 +1,2 @@
1
+ export * from './cosec/index.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAYA,cAAc,kBAAkB,CAAC"}
@@ -0,0 +1,118 @@
1
+ import { c as e } from "react/compiler-runtime";
2
+ import { createContext as t, useCallback as n, useContext as r, useEffect as i, useInsertionEffect as a, useReducer as o, useRef as s, useState as c, useSyncExternalStore as l } from "react";
3
+ import { Fragment as u, jsx as d } from "react/jsx-runtime";
4
+ // src/internal/useLatest.ts
5
+ function useLatest(t) {
6
+ let n = e(2), r = s(t), t0;
7
+ return n[0] === t ? t0 = n[1] : (t0 = () => {
8
+ r.current = t;
9
+ }, n[0] = t, n[1] = t0), a(t0), r;
10
+ }
11
+ // src/internal/useStoredToken.ts
12
+ var f = 0, NO_TOKEN = () => null;
13
+ function useStoredToken(e) {
14
+ let t = n((t) => e.addListener({
15
+ name: `cosec-react:useStoredToken:${f++}`,
16
+ handle: t
17
+ }), [e]), r = n(() => e.get(), [e]);
18
+ return l(t, r, NO_TOKEN);
19
+ }
20
+ // src/cosec/useSecurity.ts
21
+ var p = {
22
+ jti: "",
23
+ sub: "anonymous",
24
+ iat: 0,
25
+ exp: 0
26
+ }, m = 2147483647, h = /* @__PURE__ */ new WeakMap();
27
+ function nextSessionGeneration(e) {
28
+ let t = (h.get(e) ?? 0) + 1;
29
+ return h.set(e, t), t;
30
+ }
31
+ function useSecurity(t, n) {
32
+ let r = e(20), a;
33
+ r[0] === n ? a = r[1] : (a = n === void 0 ? {} : n, r[0] = n, r[1] = a);
34
+ let s = a, c = useStoredToken(t), [, l] = o(_temp, 0), u = c?.refresh.payload?.exp, d = t.earlyPeriod, t2;
35
+ r[2] !== d || r[3] !== u || r[4] !== l ? (t2 = () => {
36
+ if (typeof u != "number") return;
37
+ let e = (u - d) * 1e3, t, arm = () => {
38
+ let n = e - Date.now();
39
+ n <= 0 ? l() : t = setTimeout(arm, Math.min(n, m));
40
+ };
41
+ return arm(), () => clearTimeout(t);
42
+ }, r[2] = d, r[3] = u, r[4] = l, r[5] = t2) : t2 = r[5];
43
+ let f;
44
+ r[6] !== d || r[7] !== u ? (f = [u, d], r[6] = d, r[7] = u, r[8] = f) : f = r[8], i(t2, f);
45
+ let g = useLatest(s), t4;
46
+ r[9] !== g || r[10] !== t ? (t4 = async (e) => {
47
+ let n = nextSessionGeneration(t), r = typeof e == "function" ? await e() : e;
48
+ h.get(t) === n && (t.signIn(r), g.current.onSignIn?.());
49
+ }, r[9] = g, r[10] = t, r[11] = t4) : t4 = r[11];
50
+ let _ = t4, t5;
51
+ r[12] !== g || r[13] !== t ? (t5 = () => {
52
+ nextSessionGeneration(t), t.remove(), g.current.onSignOut?.();
53
+ }, r[12] = g, r[13] = t, r[14] = t5) : t5 = r[14];
54
+ let v = t5, y = c?.access?.payload ?? p, b = c?.authenticated ?? !1, x;
55
+ return r[15] !== _ || r[16] !== v || r[17] !== y || r[18] !== b ? (x = {
56
+ currentUser: y,
57
+ authenticated: b,
58
+ signIn: _,
59
+ signOut: v
60
+ }, r[15] = _, r[16] = v, r[17] = y, r[18] = b, r[19] = x) : x = r[19], x;
61
+ }
62
+ function _temp(e) {
63
+ return e + 1;
64
+ }
65
+ // src/cosec/SecurityContext.tsx
66
+ var g = t(void 0);
67
+ function SecurityProvider(t) {
68
+ let n = e(7), r, i, a;
69
+ n[0] === t ? (r = n[1], i = n[2], a = n[3]) : ({tokenStorage: i, children: r, ...a} = t, n[0] = t, n[1] = r, n[2] = i, n[3] = a);
70
+ let o = useSecurity(i, a), s;
71
+ return n[4] !== r || n[5] !== o ? (s = /* @__PURE__ */ d(g.Provider, {
72
+ value: o,
73
+ children: r
74
+ }), n[4] = r, n[5] = o, n[6] = s) : s = n[6], s;
75
+ }
76
+ function useSecurityContext() {
77
+ let e = r(g);
78
+ if (!e) throw Error("useSecurityContext must be used within a SecurityProvider");
79
+ return e;
80
+ }
81
+ // src/cosec/RouteGuard.tsx
82
+ function RouteGuard(t) {
83
+ let n = e(6), { children: r, fallback: a, onUnauthorized: o } = t, { authenticated: s } = useSecurityContext(), c = useLatest(o), t1, l;
84
+ if (n[0] !== s || n[1] !== c ? (t1 = () => {
85
+ s || c.current?.();
86
+ }, l = [s, c], n[0] = s, n[1] = c, n[2] = t1, n[3] = l) : (t1 = n[2], l = n[3]), i(t1, l), s) {
87
+ let e;
88
+ return n[4] === r ? e = n[5] : (e = /* @__PURE__ */ d(u, { children: r }), n[4] = r, n[5] = e), e;
89
+ }
90
+ return a;
91
+ }
92
+ // src/cosec/RefreshableRouteGuard.tsx
93
+ function RefreshableRouteGuard(t) {
94
+ let n = e(12), { children: r, fallback: a, refreshing: o, tokenManager: s } = t, { authenticated: l } = useSecurityContext(), f = s.isRefreshNeeded && s.isRefreshable ? s.currentToken : null, [p, m] = c(null), h = f !== null && p === f, t1, g;
95
+ if (n[0] !== f || n[1] !== s ? (t1 = () => {
96
+ if (!f) return;
97
+ let e = !0;
98
+ return s.refresh().catch((t) => {
99
+ e && (console.error(t), m(f));
100
+ }), () => {
101
+ e = !1;
102
+ };
103
+ }, g = [f, s], n[0] = f, n[1] = s, n[2] = t1, n[3] = g) : (t1 = n[2], g = n[3]), i(t1, g), l) {
104
+ let e;
105
+ return n[4] === r ? e = n[5] : (e = /* @__PURE__ */ d(u, { children: r }), n[4] = r, n[5] = e), e;
106
+ }
107
+ if (!f || h) {
108
+ let e;
109
+ return n[6] === a ? e = n[7] : (e = /* @__PURE__ */ d(u, { children: a }), n[6] = a, n[7] = e), e;
110
+ }
111
+ let _;
112
+ n[8] === o ? _ = n[9] : (_ = o ?? /* @__PURE__ */ d("p", { children: "Refreshing..." }), n[8] = o, n[9] = _);
113
+ let v = _, y;
114
+ return n[10] === v ? y = n[11] : (y = /* @__PURE__ */ d(u, { children: v }), n[10] = v, n[11] = y), y;
115
+ }
116
+ export { p as ANONYMOUS_USER, RefreshableRouteGuard, RouteGuard, g as SecurityContext, SecurityProvider, useSecurity, useSecurityContext };
117
+
118
+ //# sourceMappingURL=index.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.es.js","names":["useInsertionEffect","useRef","useLatest","value","$","_c","ref","t0","current","useCallback","useSyncExternalStore","listeners","NO_TOKEN","useStoredToken","tokenStorage","subscribe","onChange","addListener","name","handle","getSnapshot","get","useEffect","useReducer","useLatest","useStoredToken","ANONYMOUS_USER","jti","sub","iat","exp","onSignIn","onSignOut","currentUser","authenticated","signIn","compositeTokenProvider","signOut","MAX_TIMEOUT","sessionGenerations","WeakMap","nextSessionGeneration","tokenStorage","generation","get","set","useSecurity","t0","$","_c","t1","undefined","options","token","rerender","_temp","refreshExpiresAt","refresh","payload","earlyPeriod","t2","deadline","timer","arm","remaining","Date","now","setTimeout","Math","min","clearTimeout","t3","optionsRef","t4","compositeToken","current","t5","remove","t6","access","t7","t8","count","useSecurity","createContext","useContext","SecurityContext","undefined","tokenStorage","children","SecurityProvider","t0","$","_c","useSecurityOptions","value","t1","useSecurityContext","context","Error","useEffect","useLatest","useSecurityContext","children","fallback","onUnauthorized","RouteGuard","t0","$","_c","authenticated","latestOnUnauthorized","t1","t2","current","t3","_Fragment","useEffect","useState","useSecurityContext","refreshing","tokenManager","RefreshableRouteGuard","t0","$","_c","children","fallback","authenticated","isRefreshNeeded","isRefreshable","refreshToken","currentToken","failedToken","setFailedToken","refreshFailed","t1","t2","current","refresh","catch","error","console","t3","refreshingNode","t4","_Fragment","$","c","ref","useRef","value","useInsertionEffect","listeners","subscribe","useCallback","tokenStorage","onChange","getSnapshot","useSyncExternalStore","ANONYMOUS_USER","MAX_TIMEOUT","sessionGenerations","generation","t1","t0","options","token","rerender","useReducer","refreshExpiresAt","earlyPeriod","deadline","timer","remaining","t3","useEffect","optionsRef","compositeToken","compositeTokenProvider","signIn","signOut","t6","t7","t8","count","SecurityContext","createContext","children","useSecurityOptions","context","useContext","latestOnUnauthorized","onUnauthorized","t2","authenticated","Fragment","fallback","refreshToken","tokenManager","failedToken","setFailedToken","useState","refreshFailed","current","error","refreshing","refreshingNode","t4"],"sources":["../src/internal/useLatest.ts","../src/internal/useStoredToken.ts","../src/cosec/useSecurity.ts","../src/cosec/SecurityContext.tsx","../src/cosec/RouteGuard.tsx","../src/cosec/RefreshableRouteGuard.tsx"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RefObject } from 'react';\nimport { useInsertionEffect, useRef } from 'react';\n\n/**\n * A ref holding the latest value, for callbacks that outlive a render\n * (an async `signIn`, a listener).\n *\n * It is updated once the render commits, not during it: a render React\n * discards (a concurrent or suspended one) must not leave its props in the\n * ref. Insertion effects run before every layout effect and effect, so those\n * already read the new value.\n *\n * Internal: not exported from the package.\n */\nexport function useLatest<T>(value: T): RefObject<T> {\n const ref = useRef(value);\n useInsertionEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport type { JwtCompositeToken, TokenStorage } from '@ahoo-wang/cosec-fetcher';\n\nlet listeners = 0;\n\nconst NO_TOKEN = (): null => null;\n\n/**\n * The token pair a `TokenStorage` holds, as React state: `null` while there is\n * none.\n *\n * The snapshot is the stored value itself (`TokenStorage.get()` answers the\n * same object until the pair changes), so a render in which nothing changed\n * does not re-render. The server has no browser storage and renders `null`:\n * hydration starts from the same value, and the stored pair follows right\n * after.\n *\n * Internal: not exported from the package.\n */\nexport function useStoredToken(\n tokenStorage: TokenStorage,\n): JwtCompositeToken | null {\n const subscribe = useCallback(\n (onChange: () => void) =>\n tokenStorage.addListener({\n name: `cosec-react:useStoredToken:${listeners++}`,\n handle: onChange,\n }),\n [tokenStorage],\n );\n const getSnapshot = useCallback(() => tokenStorage.get(), [tokenStorage]);\n return useSyncExternalStore(subscribe, getSnapshot, NO_TOKEN);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useEffect, useReducer } from 'react';\nimport { useLatest } from '../internal/useLatest.js';\nimport { useStoredToken } from '../internal/useStoredToken.js';\nimport type {\n TokenStorage,\n CompositeToken,\n CoSecJwtPayload,\n} from '@ahoo-wang/cosec-fetcher';\n\n/**\n * Type representing a composite token provider.\n * Can be either a direct composite token or a function that returns a promise of a composite token.\n */\nexport type CompositeTokenProvider =\n CompositeToken | (() => Promise<CompositeToken>);\n\nexport const ANONYMOUS_USER: CoSecJwtPayload = {\n jti: '',\n sub: 'anonymous',\n iat: 0,\n exp: 0,\n};\n\n/**\n * Options for configuring the useSecurity hook.\n */\nexport interface UseSecurityOptions {\n /**\n * Callback function invoked when sign in is successful.\n * This is called after the token has been successfully stored.\n */\n onSignIn?: () => void;\n\n /**\n * Callback function invoked when sign out occurs.\n * This is called after the token has been removed.\n */\n onSignOut?: () => void;\n}\n\n/**\n * Return type for the useSecurity hook.\n */\nexport interface UseSecurityReturn {\n /**\n * The stored access token's JWT payload, even once it has expired (check\n * `authenticated`), or ANONYMOUS_USER when no token is stored.\n */\n currentUser: CoSecJwtPayload;\n\n /**\n * Boolean indicating whether the user is currently authenticated.\n * True if a valid token exists and the user is signed in, false otherwise.\n */\n authenticated: boolean;\n\n /**\n * Function to sign in with a composite token or a function that returns a promise of composite token.\n * @param compositeTokenProvider - Either a composite token containing access and refresh tokens,\n * or a function that returns a promise resolving to a composite token.\n * @returns A promise that resolves when the sign-in operation is complete.\n */\n signIn: (compositeTokenProvider: CompositeTokenProvider) => Promise<void>;\n\n /**\n * Function to sign out the current user.\n */\n signOut: () => void;\n}\n\n/** The longest delay setTimeout accepts (2^31 - 1 ms). */\nconst MAX_TIMEOUT = 2_147_483_647;\n\n// Session actions started through useSecurity, per storage: shared by every\n// hook on that storage, so a later signIn or signOut from any of them\n// supersedes a signIn whose provider is still pending.\nconst sessionGenerations = new WeakMap<TokenStorage, number>();\n\nfunction nextSessionGeneration(tokenStorage: TokenStorage): number {\n const generation = (sessionGenerations.get(tokenStorage) ?? 0) + 1;\n sessionGenerations.set(tokenStorage, generation);\n return generation;\n}\n\n/**\n * Hook for managing authentication state and operations using CoSec tokens.\n *\n * This hook provides reactive access to the current user information, authentication status,\n * and methods to sign in and sign out. It integrates with the TokenStorage to persist tokens\n * and updates the state reactively when tokens change.\n *\n * @param tokenStorage - The token storage instance used to manage authentication tokens.\n * This should be a valid TokenStorage implementation that handles\n * token persistence and retrieval.\n * @param options - Optional configuration object containing lifecycle callbacks.\n * @param options.onSignIn - Callback function invoked when sign in is successful.\n * @param options.onSignOut - Callback function invoked when sign out occurs.\n * @returns An object containing:\n * - currentUser: The stored access token's JWT payload (even if expired), or ANONYMOUS_USER when no token is stored.\n * - authenticated: Boolean indicating whether the user is currently authenticated\n * (the access token is unexpired). Computed at render; the hook also\n * re-renders when the refresh token expires, so an idle page signs out then.\n * - signIn: Function to authenticate with a composite token.\n * - signOut: Function to sign out the current user.\n * @throws {Error} May throw errors if tokenStorage operations fail, such as invalid tokens\n * or storage access issues (implementation dependent).\n * @example\n * ```typescript\n * import { useSecurity } from '@ahoo-wang/cosec-react';\n * import { tokenStorage } from './tokenStorage';\n * import { useNavigate } from 'react-router-dom';\n *\n * function App() {\n * const navigate = useNavigate();\n *\n * const { currentUser, authenticated, signIn, signOut } = useSecurity(tokenStorage, {\n * onSignIn: () => {\n * // Redirect to dashboard after successful login\n * navigate('/dashboard');\n * },\n * onSignOut: () => {\n * // Redirect to login page after logout\n * navigate('/login');\n * }\n * });\n *\n * const handleSignIn = async () => {\n * // Direct token\n * await signIn(compositeToken);\n *\n * // Or async function\n * await signIn(async () => {\n * const response = await fetch('/api/auth/login', {\n * method: 'POST',\n * body: JSON.stringify({ username, password })\n * });\n * return response.json();\n * });\n * };\n *\n * if (!authenticated) {\n * return <button onClick={handleSignIn}>Sign In</button>;\n * }\n *\n * return (\n * <div>\n * <p>Welcome, {currentUser?.sub}!</p>\n * <button onClick={signOut}>Sign Out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useSecurity(\n tokenStorage: TokenStorage,\n options: UseSecurityOptions = {},\n): UseSecurityReturn {\n // Reactive updates when the stored token changes\n const token = useStoredToken(tokenStorage);\n\n // `authenticated` is computed at render. Re-render when the session can no\n // longer be renewed (the refresh token expires), so a page left open signs\n // out then; an expired access token that can still be refreshed is renewed\n // by the next request instead of sending the user to sign in.\n const [, rerender] = useReducer((count: number) => count + 1, 0);\n const refreshExpiresAt = token?.refresh.payload?.exp;\n const earlyPeriod = tokenStorage.earlyPeriod;\n useEffect(() => {\n if (typeof refreshExpiresAt !== 'number') return;\n const deadline = (refreshExpiresAt - earlyPeriod) * 1000;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = () => {\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n rerender();\n return;\n }\n // setTimeout overflows past ~24.8 days: wait in steps.\n timer = setTimeout(arm, Math.min(remaining, MAX_TIMEOUT));\n };\n arm();\n return () => clearTimeout(timer);\n }, [refreshExpiresAt, earlyPeriod]);\n const optionsRef = useLatest(options);\n const signIn = useCallback(\n async (compositeTokenProvider: CompositeTokenProvider) => {\n const generation = nextSessionGeneration(tokenStorage);\n const compositeToken =\n typeof compositeTokenProvider === 'function'\n ? await compositeTokenProvider()\n : compositeTokenProvider;\n // A signIn or signOut started meanwhile replaced this one.\n if (sessionGenerations.get(tokenStorage) !== generation) return;\n tokenStorage.signIn(compositeToken);\n optionsRef.current.onSignIn?.();\n },\n [tokenStorage, optionsRef],\n );\n const signOut = useCallback(() => {\n nextSessionGeneration(tokenStorage);\n tokenStorage.remove();\n optionsRef.current.onSignOut?.();\n }, [tokenStorage, optionsRef]);\n\n return {\n currentUser: token?.access?.payload ?? ANONYMOUS_USER,\n authenticated: token?.authenticated ?? false,\n signIn,\n signOut,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { UseSecurityOptions, UseSecurityReturn } from './useSecurity.js';\nimport { useSecurity } from './useSecurity.js';\nimport type { ReactNode } from 'react';\nimport { createContext, useContext } from 'react';\nimport type { TokenStorage } from '@ahoo-wang/cosec-fetcher';\n\n/**\n * Type alias for the security context value, representing the authentication state and methods.\n * This is equivalent to the return type of the useSecurity hook, providing reactive access to:\n * - Current authenticated user information (JWT payload)\n * - Authentication status (boolean flag)\n * - Sign-in method for authenticating users\n * - Sign-out method for clearing authentication\n *\n * Used internally by the SecurityContext to type the context value.\n */\nexport type SecurityContextValue = UseSecurityReturn;\n\n/**\n * React context for managing authentication state across the component tree.\n * This context enables sharing of authentication state and methods between components\n * without prop drilling. Components can access authentication data and methods through\n * the useSecurityContext hook when wrapped by the SecurityProvider.\n *\n * The context value is undefined by default, requiring components to be wrapped by\n * SecurityProvider to access authentication functionality.\n */\nexport const SecurityContext = createContext<SecurityContextValue | undefined>(\n undefined,\n);\n\n/**\n * Configuration options for the SecurityProvider component.\n * Extends UseSecurityOptions to include provider-specific settings like token storage and children.\n */\nexport interface SecurityContextOptions extends UseSecurityOptions {\n /**\n * The token storage instance used to manage authentication tokens.\n * This should be a valid TokenStorage implementation that handles token persistence,\n * retrieval, and lifecycle management across different storage backends (localStorage,\n * sessionStorage, memory, etc.).\n */\n tokenStorage: TokenStorage;\n\n /**\n * The child components that will have access to the security context.\n * These components can use the useSecurityContext hook to access authentication state and methods.\n */\n children: ReactNode;\n}\n\n/**\n * Provider component that supplies authentication state and methods to its child components.\n * This component wraps the application or a portion of it to provide access to authentication\n * functionality through the useSecurityContext hook. It internally uses the useSecurity hook\n * to manage authentication state and makes it available via React context.\n *\n * @param tokenStorage - The token storage instance for managing authentication tokens.\n * This should be a valid TokenStorage implementation that handles\n * token persistence, retrieval, and lifecycle management across different\n * storage backends (localStorage, sessionStorage, memory, etc.).\n * @param children - The child components that will have access to the security context.\n * These components can use the useSecurityContext hook to access authentication\n * state and methods without prop drilling.\n * @param useSecurityOptions - Optional configuration object containing lifecycle callbacks\n * for sign-in and sign-out events. Extends UseSecurityOptions interface.\n * @param useSecurityOptions.onSignIn - Callback function invoked when sign in is successful.\n * @param useSecurityOptions.onSignOut - Callback function invoked when sign out occurs.\n * @returns A React element that provides the security context to its children.\n * The context value includes currentUser, authenticated status, signIn, and signOut methods.\n * @throws {Error} May throw errors if tokenStorage operations fail during initialization,\n * such as invalid tokens or storage access issues (implementation dependent).\n * @example\n * ```tsx\n * import { SecurityProvider } from '@ahoo-wang/cosec-react';\n * import { tokenStorage } from './tokenStorage';\n * import { useNavigate } from 'react-router-dom';\n *\n * function App() {\n * const navigate = useNavigate();\n *\n * return (\n * <SecurityProvider\n * tokenStorage={tokenStorage}\n * onSignIn={() => navigate('/dashboard')}\n * onSignOut={() => navigate('/login')}\n * >\n * <MyApp />\n * </SecurityProvider>\n * );\n * }\n * ```\n */\nexport function SecurityProvider({\n tokenStorage,\n children,\n ...useSecurityOptions\n}: SecurityContextOptions) {\n const value = useSecurity(tokenStorage, useSecurityOptions);\n return (\n <SecurityContext.Provider value={value}>\n {children}\n </SecurityContext.Provider>\n );\n}\n\n/**\n * Hook to access the security context within components wrapped by SecurityProvider.\n * This hook provides reactive access to authentication state and methods throughout the component tree.\n *\n * @returns The security context containing currentUser, authenticated status, signIn, and signOut methods.\n * @throws {Error} Throws an error if used outside of a SecurityProvider component.\n * @example\n * ```tsx\n * import { useSecurityContext } from '@ahoo-wang/cosec-react';\n *\n * function UserProfile() {\n * const { currentUser, authenticated, signOut } = useSecurityContext();\n *\n * if (!authenticated) {\n * return <div>Please sign in</div>;\n * }\n *\n * return (\n * <div>\n * <p>Welcome, {currentUser?.sub}!</p>\n * <button onClick={signOut}>Sign Out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useSecurityContext(): SecurityContextValue {\n const context = useContext(SecurityContext);\n if (!context) {\n throw new Error(\n 'useSecurityContext must be used within a SecurityProvider',\n );\n }\n return context;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useEffect, type ReactNode } from 'react';\nimport { useLatest } from '../internal/useLatest.js';\nimport { useSecurityContext } from './SecurityContext.js';\n\n/**\n * Props for the RouteGuard component.\n */\nexport interface RouteGuardProps {\n /**\n * The content to render when the user is authenticated.\n */\n children: ReactNode;\n\n /**\n * The fallback content to render when the user is not authenticated.\n * If not provided, nothing will be rendered.\n */\n fallback?: ReactNode;\n\n /**\n * Optional redirect function to call when user is not authenticated.\n * This can be used to programmatically navigate to a login page. It runs\n * after the render commits, once each time the user becomes (or starts\n * out) unauthenticated — not during rendering.\n */\n onUnauthorized?: () => void;\n}\n\n/**\n * Route guard component that conditionally renders content based on authentication status.\n *\n * This component uses the SecurityContext to check if the user is authenticated.\n * If authenticated, it renders the children. If not authenticated, it renders the fallback\n * content (if provided) and optionally calls the onUnauthorized callback.\n *\n * @param children - The protected content to render when authenticated.\n * @param fallback - Optional fallback content to render when not authenticated.\n * @param onUnauthorized - Optional callback to execute when user is not authenticated.\n * @returns The children if authenticated, fallback if provided, or null otherwise.\n * @example\n * ```tsx\n * import { RouteGuard } from '@ahoo-wang/cosec-react';\n *\n * function ProtectedPage() {\n * return (\n * <RouteGuard\n * fallback={<div>Please log in to access this page.</div>}\n * onUnauthorized={() => navigate('/login')}\n * >\n * <div>Protected content</div>\n * </RouteGuard>\n * );\n * }\n * ```\n */\nexport function RouteGuard({\n children,\n fallback,\n onUnauthorized,\n}: RouteGuardProps): ReactNode {\n const { authenticated } = useSecurityContext();\n const latestOnUnauthorized = useLatest(onUnauthorized);\n\n // A side effect such as navigate() belongs after commit, not in render.\n useEffect(() => {\n if (!authenticated) {\n latestOnUnauthorized.current?.();\n }\n }, [authenticated, latestOnUnauthorized]);\n\n if (authenticated) {\n return <>{children}</>;\n }\n\n // Return fallback if provided, otherwise return null\n return fallback;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RouteGuardProps } from './RouteGuard.js';\nimport type { ReactNode } from 'react';\nimport { useEffect, useState } from 'react';\nimport type { JwtTokenManager } from '@ahoo-wang/cosec-fetcher';\nimport { useSecurityContext } from './SecurityContext.js';\n\nexport interface RefreshableRouteGuardProps extends Omit<\n RouteGuardProps,\n 'onUnauthorized'\n> {\n refreshing?: ReactNode;\n tokenManager: JwtTokenManager;\n}\n\nexport function RefreshableRouteGuard({\n children,\n fallback,\n refreshing,\n tokenManager,\n}: RefreshableRouteGuardProps): ReactNode {\n const { authenticated } = useSecurityContext();\n const refreshable =\n tokenManager.isRefreshNeeded && tokenManager.isRefreshable;\n // The token being refreshed: a session that replaces it gets a refresh of\n // its own, even when both need one.\n const refreshToken = refreshable ? tokenManager.currentToken : null;\n // A failed refresh that leaves the token in storage (a network failure or\n // a 5xx keeps the session: RefreshUnavailableError) changes nothing the\n // guard re-renders on, so without this it would show `refreshing` forever.\n // It is recorded for its token only: a later session is not failed by it.\n const [failedToken, setFailedToken] = useState<object | null>(null);\n const refreshFailed = refreshToken !== null && failedToken === refreshToken;\n\n useEffect(() => {\n if (!refreshToken) {\n return;\n }\n let current = true;\n tokenManager.refresh().catch(error => {\n // The refresh of a session that is no longer the guard's.\n if (!current) return;\n console.error(error);\n setFailedToken(refreshToken);\n });\n return () => {\n current = false;\n };\n }, [refreshToken, tokenManager]);\n\n if (authenticated) {\n return <>{children}</>;\n }\n\n if (!refreshToken || refreshFailed) {\n return <>{fallback}</>;\n }\n const refreshingNode = refreshing ?? <p>Refreshing...</p>;\n return <>{refreshingNode}</>;\n}\n"],"mappings":";;;;AA2BA,SAAOE,UAAAC,GAAA;CAAA,IAAAC,IAAAC,EAAA,CAAA,GACLC,IAAYL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IAAA,CAACN,GAAcV,CAAY,GAACG,EAAA,KAAAO,GAAAP,EAAA,KAAAH,GAAAG,EAAA,KAAAY,IAAAZ,EAAA,KAAAa,MAAAD,KAAAZ,EAAA,IAAAa,IAAAb,EAAA,KAd/BP,EAAUmB,IAcPC,CAA4B,GAE3BT,GAAa;EAAA,IAAAe;EACO,OADPnB,EAAA,OAAAE,IACOiB,IAAAnB,EAAA,MAAfmB,IAAA,kBAAAG,GAAA,EAAGpB,YAAQ,CAAA,GAAIF,EAAA,KAAAE,GAAAF,EAAA,KAAAmB,IAAfA;CAAe;CAGxB,IAAI,CAACZ,KAADI,GAA8B;EAAA,IAAAQ;EACV,OADUnB,EAAA,OAAAG,IACVgB,IAAAnB,EAAA,MAAfmB,IAAA,kBAAAG,GAAA,EAAA,UAAGnB,EAAQ,CAAA,GAAIH,EAAA,KAAAG,GAAAH,EAAA,KAAAmB,IAAfA;CAAe;CACvB,IAAAA;CAAA,AAAAnB,EAAA,OAAAJ,IACwDuB,IAAAnB,EAAA,MAAlCmB,IAAAvB,KAAc,kBAAA,KAAA,EAAA,UAAG,gBAAiB,CAAA,GAAAI,EAAA,KAAAJ,GAAAI,EAAA,KAAAmB;CAAzD,IAAAC,IAAuBD,GAAmCE;CAC9B,OAD8BrB,EAAA,QAAAoB,IAC9BC,IAAArB,EAAA,OAArBqB,IAAA,kBAAAC,GAAA,EAAA,UAAGF,EAAc,CAAA,GAAIpB,EAAA,MAAAoB,GAAApB,EAAA,MAAAqB,IAArBA;AAAqB"}
@@ -0,0 +1,2 @@
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("react/compiler-runtime"),require("react"),require("react/jsx-runtime")):typeof define==`function`&&define.amd?define([`exports`,`react/compiler-runtime`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CoSecReact={},e.ReactCompilerRuntime,e.React,e.ReactJSXRuntime))})(this,function(e,t,n,r){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function useLatest(e){let r=(0,t.c)(2),i=(0,n.useRef)(e),t0;return r[0]===e?t0=r[1]:(t0=()=>{i.current=e},r[0]=e,r[1]=t0),(0,n.useInsertionEffect)(t0),i}var i=0,NO_TOKEN=()=>null;function useStoredToken(e){let t=(0,n.useCallback)(t=>e.addListener({name:`cosec-react:useStoredToken:${i++}`,handle:t}),[e]),r=(0,n.useCallback)(()=>e.get(),[e]);return(0,n.useSyncExternalStore)(t,r,NO_TOKEN)}var a={jti:``,sub:`anonymous`,iat:0,exp:0},o=2147483647,s=new WeakMap;function nextSessionGeneration(e){let t=(s.get(e)??0)+1;return s.set(e,t),t}function useSecurity(e,r){let i=(0,t.c)(20),c;i[0]===r?c=i[1]:(c=r===void 0?{}:r,i[0]=r,i[1]=c);let l=c,u=useStoredToken(e),[,d]=(0,n.useReducer)(_temp,0),f=u?.refresh.payload?.exp,p=e.earlyPeriod,t2;i[2]!==p||i[3]!==f||i[4]!==d?(t2=()=>{if(typeof f!=`number`)return;let e=(f-p)*1e3,t,arm=()=>{let n=e-Date.now();n<=0?d():t=setTimeout(arm,Math.min(n,o))};return arm(),()=>clearTimeout(t)},i[2]=p,i[3]=f,i[4]=d,i[5]=t2):t2=i[5];let m;i[6]!==p||i[7]!==f?(m=[f,p],i[6]=p,i[7]=f,i[8]=m):m=i[8],(0,n.useEffect)(t2,m);let h=useLatest(l),t4;i[9]!==h||i[10]!==e?(t4=async t=>{let n=nextSessionGeneration(e),r=typeof t==`function`?await t():t;s.get(e)===n&&(e.signIn(r),h.current.onSignIn?.())},i[9]=h,i[10]=e,i[11]=t4):t4=i[11];let g=t4,t5;i[12]!==h||i[13]!==e?(t5=()=>{nextSessionGeneration(e),e.remove(),h.current.onSignOut?.()},i[12]=h,i[13]=e,i[14]=t5):t5=i[14];let _=t5,v=u?.access?.payload??a,y=u?.authenticated??!1,b;return i[15]!==g||i[16]!==_||i[17]!==v||i[18]!==y?(b={currentUser:v,authenticated:y,signIn:g,signOut:_},i[15]=g,i[16]=_,i[17]=v,i[18]=y,i[19]=b):b=i[19],b}function _temp(e){return e+1}var c=(0,n.createContext)(void 0);function SecurityProvider(e){let n=(0,t.c)(7),i,a,o;n[0]===e?(i=n[1],a=n[2],o=n[3]):({tokenStorage:a,children:i,...o}=e,n[0]=e,n[1]=i,n[2]=a,n[3]=o);let s=useSecurity(a,o),l;return n[4]!==i||n[5]!==s?(l=(0,r.jsx)(c.Provider,{value:s,children:i}),n[4]=i,n[5]=s,n[6]=l):l=n[6],l}function useSecurityContext(){let e=(0,n.useContext)(c);if(!e)throw Error(`useSecurityContext must be used within a SecurityProvider`);return e}function RouteGuard(e){let i=(0,t.c)(6),{children:a,fallback:o,onUnauthorized:s}=e,{authenticated:c}=useSecurityContext(),l=useLatest(s),t1,u;if(i[0]!==c||i[1]!==l?(t1=()=>{c||l.current?.()},u=[c,l],i[0]=c,i[1]=l,i[2]=t1,i[3]=u):(t1=i[2],u=i[3]),(0,n.useEffect)(t1,u),c){let e;return i[4]===a?e=i[5]:(e=(0,r.jsx)(r.Fragment,{children:a}),i[4]=a,i[5]=e),e}return o}function RefreshableRouteGuard(e){let i=(0,t.c)(12),{children:a,fallback:o,refreshing:s,tokenManager:c}=e,{authenticated:l}=useSecurityContext(),u=c.isRefreshNeeded&&c.isRefreshable?c.currentToken:null,[d,f]=(0,n.useState)(null),p=u!==null&&d===u,t1,m;if(i[0]!==u||i[1]!==c?(t1=()=>{if(!u)return;let e=!0;return c.refresh().catch(t=>{e&&(console.error(t),f(u))}),()=>{e=!1}},m=[u,c],i[0]=u,i[1]=c,i[2]=t1,i[3]=m):(t1=i[2],m=i[3]),(0,n.useEffect)(t1,m),l){let e;return i[4]===a?e=i[5]:(e=(0,r.jsx)(r.Fragment,{children:a}),i[4]=a,i[5]=e),e}if(!u||p){let e;return i[6]===o?e=i[7]:(e=(0,r.jsx)(r.Fragment,{children:o}),i[6]=o,i[7]=e),e}let h;i[8]===s?h=i[9]:(h=s??(0,r.jsx)(`p`,{children:`Refreshing...`}),i[8]=s,i[9]=h);let g=h,_;return i[10]===g?_=i[11]:(_=(0,r.jsx)(r.Fragment,{children:g}),i[10]=g,i[11]=_),_}e.ANONYMOUS_USER=a,e.RefreshableRouteGuard=RefreshableRouteGuard,e.RouteGuard=RouteGuard,e.SecurityContext=c,e.SecurityProvider=SecurityProvider,e.useSecurity=useSecurity,e.useSecurityContext=useSecurityContext});
2
+ //# sourceMappingURL=index.umd.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.cjs","names":["useInsertionEffect","useRef","useLatest","value","$","_c","ref","t0","current","useCallback","useSyncExternalStore","listeners","NO_TOKEN","useStoredToken","tokenStorage","subscribe","onChange","addListener","name","handle","getSnapshot","get","useEffect","useReducer","useLatest","useStoredToken","ANONYMOUS_USER","jti","sub","iat","exp","onSignIn","onSignOut","currentUser","authenticated","signIn","compositeTokenProvider","signOut","MAX_TIMEOUT","sessionGenerations","WeakMap","nextSessionGeneration","tokenStorage","generation","get","set","useSecurity","t0","$","_c","t1","undefined","options","token","rerender","_temp","refreshExpiresAt","refresh","payload","earlyPeriod","t2","deadline","timer","arm","remaining","Date","now","setTimeout","Math","min","clearTimeout","t3","optionsRef","t4","compositeToken","current","t5","remove","t6","access","t7","t8","count","useSecurity","createContext","useContext","SecurityContext","undefined","tokenStorage","children","SecurityProvider","t0","$","_c","useSecurityOptions","value","t1","useSecurityContext","context","Error","useEffect","useLatest","useSecurityContext","children","fallback","onUnauthorized","RouteGuard","t0","$","_c","authenticated","latestOnUnauthorized","t1","t2","current","t3","_Fragment","useEffect","useState","useSecurityContext","refreshing","tokenManager","RefreshableRouteGuard","t0","$","_c","children","fallback","authenticated","isRefreshNeeded","isRefreshable","refreshToken","currentToken","failedToken","setFailedToken","refreshFailed","t1","t2","current","refresh","catch","error","console","t3","refreshingNode","t4","_Fragment","factory","global","exports","$","react_compiler_runtime","ref","react","value","listeners","subscribe","tokenStorage","onChange","getSnapshot","ANONYMOUS_USER","MAX_TIMEOUT","sessionGenerations","generation","t1","t0","options","token","rerender","refreshExpiresAt","earlyPeriod","deadline","timer","remaining","t3","optionsRef","compositeToken","compositeTokenProvider","signIn","signOut","t6","t7","t8","count","SecurityContext","children","useSecurityOptions","react_jsx_runtime","context","latestOnUnauthorized","onUnauthorized","t2","authenticated","fallback","refreshToken","tokenManager","failedToken","setFailedToken","refreshFailed","current","error","refreshing","refreshingNode","t4"],"sources":["../src/internal/useLatest.ts","../src/internal/useStoredToken.ts","../src/cosec/useSecurity.ts","../src/cosec/SecurityContext.tsx","../src/cosec/RouteGuard.tsx","../src/cosec/RefreshableRouteGuard.tsx"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RefObject } from 'react';\nimport { useInsertionEffect, useRef } from 'react';\n\n/**\n * A ref holding the latest value, for callbacks that outlive a render\n * (an async `signIn`, a listener).\n *\n * It is updated once the render commits, not during it: a render React\n * discards (a concurrent or suspended one) must not leave its props in the\n * ref. Insertion effects run before every layout effect and effect, so those\n * already read the new value.\n *\n * Internal: not exported from the package.\n */\nexport function useLatest<T>(value: T): RefObject<T> {\n const ref = useRef(value);\n useInsertionEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport type { JwtCompositeToken, TokenStorage } from '@ahoo-wang/cosec-fetcher';\n\nlet listeners = 0;\n\nconst NO_TOKEN = (): null => null;\n\n/**\n * The token pair a `TokenStorage` holds, as React state: `null` while there is\n * none.\n *\n * The snapshot is the stored value itself (`TokenStorage.get()` answers the\n * same object until the pair changes), so a render in which nothing changed\n * does not re-render. The server has no browser storage and renders `null`:\n * hydration starts from the same value, and the stored pair follows right\n * after.\n *\n * Internal: not exported from the package.\n */\nexport function useStoredToken(\n tokenStorage: TokenStorage,\n): JwtCompositeToken | null {\n const subscribe = useCallback(\n (onChange: () => void) =>\n tokenStorage.addListener({\n name: `cosec-react:useStoredToken:${listeners++}`,\n handle: onChange,\n }),\n [tokenStorage],\n );\n const getSnapshot = useCallback(() => tokenStorage.get(), [tokenStorage]);\n return useSyncExternalStore(subscribe, getSnapshot, NO_TOKEN);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useEffect, useReducer } from 'react';\nimport { useLatest } from '../internal/useLatest.js';\nimport { useStoredToken } from '../internal/useStoredToken.js';\nimport type {\n TokenStorage,\n CompositeToken,\n CoSecJwtPayload,\n} from '@ahoo-wang/cosec-fetcher';\n\n/**\n * Type representing a composite token provider.\n * Can be either a direct composite token or a function that returns a promise of a composite token.\n */\nexport type CompositeTokenProvider =\n CompositeToken | (() => Promise<CompositeToken>);\n\nexport const ANONYMOUS_USER: CoSecJwtPayload = {\n jti: '',\n sub: 'anonymous',\n iat: 0,\n exp: 0,\n};\n\n/**\n * Options for configuring the useSecurity hook.\n */\nexport interface UseSecurityOptions {\n /**\n * Callback function invoked when sign in is successful.\n * This is called after the token has been successfully stored.\n */\n onSignIn?: () => void;\n\n /**\n * Callback function invoked when sign out occurs.\n * This is called after the token has been removed.\n */\n onSignOut?: () => void;\n}\n\n/**\n * Return type for the useSecurity hook.\n */\nexport interface UseSecurityReturn {\n /**\n * The stored access token's JWT payload, even once it has expired (check\n * `authenticated`), or ANONYMOUS_USER when no token is stored.\n */\n currentUser: CoSecJwtPayload;\n\n /**\n * Boolean indicating whether the user is currently authenticated.\n * True if a valid token exists and the user is signed in, false otherwise.\n */\n authenticated: boolean;\n\n /**\n * Function to sign in with a composite token or a function that returns a promise of composite token.\n * @param compositeTokenProvider - Either a composite token containing access and refresh tokens,\n * or a function that returns a promise resolving to a composite token.\n * @returns A promise that resolves when the sign-in operation is complete.\n */\n signIn: (compositeTokenProvider: CompositeTokenProvider) => Promise<void>;\n\n /**\n * Function to sign out the current user.\n */\n signOut: () => void;\n}\n\n/** The longest delay setTimeout accepts (2^31 - 1 ms). */\nconst MAX_TIMEOUT = 2_147_483_647;\n\n// Session actions started through useSecurity, per storage: shared by every\n// hook on that storage, so a later signIn or signOut from any of them\n// supersedes a signIn whose provider is still pending.\nconst sessionGenerations = new WeakMap<TokenStorage, number>();\n\nfunction nextSessionGeneration(tokenStorage: TokenStorage): number {\n const generation = (sessionGenerations.get(tokenStorage) ?? 0) + 1;\n sessionGenerations.set(tokenStorage, generation);\n return generation;\n}\n\n/**\n * Hook for managing authentication state and operations using CoSec tokens.\n *\n * This hook provides reactive access to the current user information, authentication status,\n * and methods to sign in and sign out. It integrates with the TokenStorage to persist tokens\n * and updates the state reactively when tokens change.\n *\n * @param tokenStorage - The token storage instance used to manage authentication tokens.\n * This should be a valid TokenStorage implementation that handles\n * token persistence and retrieval.\n * @param options - Optional configuration object containing lifecycle callbacks.\n * @param options.onSignIn - Callback function invoked when sign in is successful.\n * @param options.onSignOut - Callback function invoked when sign out occurs.\n * @returns An object containing:\n * - currentUser: The stored access token's JWT payload (even if expired), or ANONYMOUS_USER when no token is stored.\n * - authenticated: Boolean indicating whether the user is currently authenticated\n * (the access token is unexpired). Computed at render; the hook also\n * re-renders when the refresh token expires, so an idle page signs out then.\n * - signIn: Function to authenticate with a composite token.\n * - signOut: Function to sign out the current user.\n * @throws {Error} May throw errors if tokenStorage operations fail, such as invalid tokens\n * or storage access issues (implementation dependent).\n * @example\n * ```typescript\n * import { useSecurity } from '@ahoo-wang/cosec-react';\n * import { tokenStorage } from './tokenStorage';\n * import { useNavigate } from 'react-router-dom';\n *\n * function App() {\n * const navigate = useNavigate();\n *\n * const { currentUser, authenticated, signIn, signOut } = useSecurity(tokenStorage, {\n * onSignIn: () => {\n * // Redirect to dashboard after successful login\n * navigate('/dashboard');\n * },\n * onSignOut: () => {\n * // Redirect to login page after logout\n * navigate('/login');\n * }\n * });\n *\n * const handleSignIn = async () => {\n * // Direct token\n * await signIn(compositeToken);\n *\n * // Or async function\n * await signIn(async () => {\n * const response = await fetch('/api/auth/login', {\n * method: 'POST',\n * body: JSON.stringify({ username, password })\n * });\n * return response.json();\n * });\n * };\n *\n * if (!authenticated) {\n * return <button onClick={handleSignIn}>Sign In</button>;\n * }\n *\n * return (\n * <div>\n * <p>Welcome, {currentUser?.sub}!</p>\n * <button onClick={signOut}>Sign Out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useSecurity(\n tokenStorage: TokenStorage,\n options: UseSecurityOptions = {},\n): UseSecurityReturn {\n // Reactive updates when the stored token changes\n const token = useStoredToken(tokenStorage);\n\n // `authenticated` is computed at render. Re-render when the session can no\n // longer be renewed (the refresh token expires), so a page left open signs\n // out then; an expired access token that can still be refreshed is renewed\n // by the next request instead of sending the user to sign in.\n const [, rerender] = useReducer((count: number) => count + 1, 0);\n const refreshExpiresAt = token?.refresh.payload?.exp;\n const earlyPeriod = tokenStorage.earlyPeriod;\n useEffect(() => {\n if (typeof refreshExpiresAt !== 'number') return;\n const deadline = (refreshExpiresAt - earlyPeriod) * 1000;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const arm = () => {\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n rerender();\n return;\n }\n // setTimeout overflows past ~24.8 days: wait in steps.\n timer = setTimeout(arm, Math.min(remaining, MAX_TIMEOUT));\n };\n arm();\n return () => clearTimeout(timer);\n }, [refreshExpiresAt, earlyPeriod]);\n const optionsRef = useLatest(options);\n const signIn = useCallback(\n async (compositeTokenProvider: CompositeTokenProvider) => {\n const generation = nextSessionGeneration(tokenStorage);\n const compositeToken =\n typeof compositeTokenProvider === 'function'\n ? await compositeTokenProvider()\n : compositeTokenProvider;\n // A signIn or signOut started meanwhile replaced this one.\n if (sessionGenerations.get(tokenStorage) !== generation) return;\n tokenStorage.signIn(compositeToken);\n optionsRef.current.onSignIn?.();\n },\n [tokenStorage, optionsRef],\n );\n const signOut = useCallback(() => {\n nextSessionGeneration(tokenStorage);\n tokenStorage.remove();\n optionsRef.current.onSignOut?.();\n }, [tokenStorage, optionsRef]);\n\n return {\n currentUser: token?.access?.payload ?? ANONYMOUS_USER,\n authenticated: token?.authenticated ?? false,\n signIn,\n signOut,\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { UseSecurityOptions, UseSecurityReturn } from './useSecurity.js';\nimport { useSecurity } from './useSecurity.js';\nimport type { ReactNode } from 'react';\nimport { createContext, useContext } from 'react';\nimport type { TokenStorage } from '@ahoo-wang/cosec-fetcher';\n\n/**\n * Type alias for the security context value, representing the authentication state and methods.\n * This is equivalent to the return type of the useSecurity hook, providing reactive access to:\n * - Current authenticated user information (JWT payload)\n * - Authentication status (boolean flag)\n * - Sign-in method for authenticating users\n * - Sign-out method for clearing authentication\n *\n * Used internally by the SecurityContext to type the context value.\n */\nexport type SecurityContextValue = UseSecurityReturn;\n\n/**\n * React context for managing authentication state across the component tree.\n * This context enables sharing of authentication state and methods between components\n * without prop drilling. Components can access authentication data and methods through\n * the useSecurityContext hook when wrapped by the SecurityProvider.\n *\n * The context value is undefined by default, requiring components to be wrapped by\n * SecurityProvider to access authentication functionality.\n */\nexport const SecurityContext = createContext<SecurityContextValue | undefined>(\n undefined,\n);\n\n/**\n * Configuration options for the SecurityProvider component.\n * Extends UseSecurityOptions to include provider-specific settings like token storage and children.\n */\nexport interface SecurityContextOptions extends UseSecurityOptions {\n /**\n * The token storage instance used to manage authentication tokens.\n * This should be a valid TokenStorage implementation that handles token persistence,\n * retrieval, and lifecycle management across different storage backends (localStorage,\n * sessionStorage, memory, etc.).\n */\n tokenStorage: TokenStorage;\n\n /**\n * The child components that will have access to the security context.\n * These components can use the useSecurityContext hook to access authentication state and methods.\n */\n children: ReactNode;\n}\n\n/**\n * Provider component that supplies authentication state and methods to its child components.\n * This component wraps the application or a portion of it to provide access to authentication\n * functionality through the useSecurityContext hook. It internally uses the useSecurity hook\n * to manage authentication state and makes it available via React context.\n *\n * @param tokenStorage - The token storage instance for managing authentication tokens.\n * This should be a valid TokenStorage implementation that handles\n * token persistence, retrieval, and lifecycle management across different\n * storage backends (localStorage, sessionStorage, memory, etc.).\n * @param children - The child components that will have access to the security context.\n * These components can use the useSecurityContext hook to access authentication\n * state and methods without prop drilling.\n * @param useSecurityOptions - Optional configuration object containing lifecycle callbacks\n * for sign-in and sign-out events. Extends UseSecurityOptions interface.\n * @param useSecurityOptions.onSignIn - Callback function invoked when sign in is successful.\n * @param useSecurityOptions.onSignOut - Callback function invoked when sign out occurs.\n * @returns A React element that provides the security context to its children.\n * The context value includes currentUser, authenticated status, signIn, and signOut methods.\n * @throws {Error} May throw errors if tokenStorage operations fail during initialization,\n * such as invalid tokens or storage access issues (implementation dependent).\n * @example\n * ```tsx\n * import { SecurityProvider } from '@ahoo-wang/cosec-react';\n * import { tokenStorage } from './tokenStorage';\n * import { useNavigate } from 'react-router-dom';\n *\n * function App() {\n * const navigate = useNavigate();\n *\n * return (\n * <SecurityProvider\n * tokenStorage={tokenStorage}\n * onSignIn={() => navigate('/dashboard')}\n * onSignOut={() => navigate('/login')}\n * >\n * <MyApp />\n * </SecurityProvider>\n * );\n * }\n * ```\n */\nexport function SecurityProvider({\n tokenStorage,\n children,\n ...useSecurityOptions\n}: SecurityContextOptions) {\n const value = useSecurity(tokenStorage, useSecurityOptions);\n return (\n <SecurityContext.Provider value={value}>\n {children}\n </SecurityContext.Provider>\n );\n}\n\n/**\n * Hook to access the security context within components wrapped by SecurityProvider.\n * This hook provides reactive access to authentication state and methods throughout the component tree.\n *\n * @returns The security context containing currentUser, authenticated status, signIn, and signOut methods.\n * @throws {Error} Throws an error if used outside of a SecurityProvider component.\n * @example\n * ```tsx\n * import { useSecurityContext } from '@ahoo-wang/cosec-react';\n *\n * function UserProfile() {\n * const { currentUser, authenticated, signOut } = useSecurityContext();\n *\n * if (!authenticated) {\n * return <div>Please sign in</div>;\n * }\n *\n * return (\n * <div>\n * <p>Welcome, {currentUser?.sub}!</p>\n * <button onClick={signOut}>Sign Out</button>\n * </div>\n * );\n * }\n * ```\n */\nexport function useSecurityContext(): SecurityContextValue {\n const context = useContext(SecurityContext);\n if (!context) {\n throw new Error(\n 'useSecurityContext must be used within a SecurityProvider',\n );\n }\n return context;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useEffect, type ReactNode } from 'react';\nimport { useLatest } from '../internal/useLatest.js';\nimport { useSecurityContext } from './SecurityContext.js';\n\n/**\n * Props for the RouteGuard component.\n */\nexport interface RouteGuardProps {\n /**\n * The content to render when the user is authenticated.\n */\n children: ReactNode;\n\n /**\n * The fallback content to render when the user is not authenticated.\n * If not provided, nothing will be rendered.\n */\n fallback?: ReactNode;\n\n /**\n * Optional redirect function to call when user is not authenticated.\n * This can be used to programmatically navigate to a login page. It runs\n * after the render commits, once each time the user becomes (or starts\n * out) unauthenticated — not during rendering.\n */\n onUnauthorized?: () => void;\n}\n\n/**\n * Route guard component that conditionally renders content based on authentication status.\n *\n * This component uses the SecurityContext to check if the user is authenticated.\n * If authenticated, it renders the children. If not authenticated, it renders the fallback\n * content (if provided) and optionally calls the onUnauthorized callback.\n *\n * @param children - The protected content to render when authenticated.\n * @param fallback - Optional fallback content to render when not authenticated.\n * @param onUnauthorized - Optional callback to execute when user is not authenticated.\n * @returns The children if authenticated, fallback if provided, or null otherwise.\n * @example\n * ```tsx\n * import { RouteGuard } from '@ahoo-wang/cosec-react';\n *\n * function ProtectedPage() {\n * return (\n * <RouteGuard\n * fallback={<div>Please log in to access this page.</div>}\n * onUnauthorized={() => navigate('/login')}\n * >\n * <div>Protected content</div>\n * </RouteGuard>\n * );\n * }\n * ```\n */\nexport function RouteGuard({\n children,\n fallback,\n onUnauthorized,\n}: RouteGuardProps): ReactNode {\n const { authenticated } = useSecurityContext();\n const latestOnUnauthorized = useLatest(onUnauthorized);\n\n // A side effect such as navigate() belongs after commit, not in render.\n useEffect(() => {\n if (!authenticated) {\n latestOnUnauthorized.current?.();\n }\n }, [authenticated, latestOnUnauthorized]);\n\n if (authenticated) {\n return <>{children}</>;\n }\n\n // Return fallback if provided, otherwise return null\n return fallback;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RouteGuardProps } from './RouteGuard.js';\nimport type { ReactNode } from 'react';\nimport { useEffect, useState } from 'react';\nimport type { JwtTokenManager } from '@ahoo-wang/cosec-fetcher';\nimport { useSecurityContext } from './SecurityContext.js';\n\nexport interface RefreshableRouteGuardProps extends Omit<\n RouteGuardProps,\n 'onUnauthorized'\n> {\n refreshing?: ReactNode;\n tokenManager: JwtTokenManager;\n}\n\nexport function RefreshableRouteGuard({\n children,\n fallback,\n refreshing,\n tokenManager,\n}: RefreshableRouteGuardProps): ReactNode {\n const { authenticated } = useSecurityContext();\n const refreshable =\n tokenManager.isRefreshNeeded && tokenManager.isRefreshable;\n // The token being refreshed: a session that replaces it gets a refresh of\n // its own, even when both need one.\n const refreshToken = refreshable ? tokenManager.currentToken : null;\n // A failed refresh that leaves the token in storage (a network failure or\n // a 5xx keeps the session: RefreshUnavailableError) changes nothing the\n // guard re-renders on, so without this it would show `refreshing` forever.\n // It is recorded for its token only: a later session is not failed by it.\n const [failedToken, setFailedToken] = useState<object | null>(null);\n const refreshFailed = refreshToken !== null && failedToken === refreshToken;\n\n useEffect(() => {\n if (!refreshToken) {\n return;\n }\n let current = true;\n tokenManager.refresh().catch(error => {\n // The refresh of a session that is no longer the guard's.\n if (!current) return;\n console.error(error);\n setFailedToken(refreshToken);\n });\n return () => {\n current = false;\n };\n }, [refreshToken, tokenManager]);\n\n if (authenticated) {\n return <>{children}</>;\n }\n\n if (!refreshToken || refreshFailed) {\n return <>{fallback}</>;\n }\n const refreshingNode = refreshing ?? <p>Refreshing...</p>;\n return <>{refreshingNode}</>;\n}\n"],"mappings":"C,6cA2BA,SAAOE,UAAAC,EAAA,CAAA,IAAAC,GAAAA,EAAAC,EAAAA,EAAAA,CAAA,CAAA,EACLC,GAAAA,EAAYL,EAAAA,OAAAA,CAAOE,CAAK,EAAEI,GAGxB,OAHwBH,EAAA,KAAAD,EAGzBI,GAAAH,EAAA,IAFkBG,OAAA,CACjBD,EAAGE,QAAWL,CAAH,EACZC,EAAA,GAAAD,EAAAC,EAAA,GAAAG,KAFDP,EAAAA,EAAAA,mBAAAA,CAAmBO,EAElB,EACMD,CAAG,CChBZ,IAAIK,EAAY,EAEVC,aAAuB,KAc7B,SAAgBC,eACdC,EAC0B,CAC1B,IAAMC,GAAAA,EAAYN,EAAAA,YAAAA,CACfO,GACCF,EAAaG,YAAY,CACvBC,KAAM,8BAA8BP,MACpCQ,OAAQH,CACV,CAAC,EACH,CAACF,CAAY,CACf,EACMM,GAAAA,EAAcX,EAAAA,YAAAA,KAAkBK,EAAaO,IAAI,EAAG,CAACP,CAAY,CAAC,EACxE,OAAA,EAAOJ,EAAAA,qBAAAA,CAAqBK,EAAWK,EAAaR,QAAQ,CAC9D,CChBA,IAAac,EAAkC,CAC7CC,IAAK,GACLC,IAAK,YACLC,IAAK,EACLC,IAAK,CACP,EAkDMQ,EAAc,WAKdC,EAAqB,IAAIC,QAE/B,SAASC,sBAAsBC,EAAoC,CACjE,IAAMC,GAAcJ,EAAmBK,IAAIF,CAAY,GAAK,GAAK,EAEjE,OADAH,EAAmBM,IAAIH,EAAcC,CAAU,EACxCA,CACT,CAuEA,SAAOG,YAAAJ,EAAAK,EAAA,CAAA,IAAAC,GAAAA,EAAAC,EAAAA,EAAAA,CAAA,EAAA,EAAAC,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A,EAAAnB,EAAA,KAAAJ,EACwDuB,EAAAnB,EAAA,IAAlCmB,EAAAvB,IAAc,EAAAmE,EAAA,IAAA,CAAA,IAAA,CAAA,SAAG,eAAiB,CAAA,EAAA/D,EAAA,GAAAJ,EAAAI,EAAA,GAAAmB,GAAzD,IAAAC,EAAuBD,EAAmCE,EAC9B,OAD8BrB,EAAA,MAAAoB,EAC9BC,EAAArB,EAAA,KAArBqB,GAAA,EAAA0C,EAAA,IAAA,CAAAzC,EAAAA,SAAA,CAAA,SAAGF,CAAc,CAAA,EAAIpB,EAAA,IAAAoB,EAAApB,EAAA,IAAAqB,GAArBA,CAAqB,C"}
@@ -0,0 +1,14 @@
1
+ import { RefObject } from 'react';
2
+ /**
3
+ * A ref holding the latest value, for callbacks that outlive a render
4
+ * (an async `signIn`, a listener).
5
+ *
6
+ * It is updated once the render commits, not during it: a render React
7
+ * discards (a concurrent or suspended one) must not leave its props in the
8
+ * ref. Insertion effects run before every layout effect and effect, so those
9
+ * already read the new value.
10
+ *
11
+ * Internal: not exported from the package.
12
+ */
13
+ export declare function useLatest<T>(value: T): RefObject<T>;
14
+ //# sourceMappingURL=useLatest.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLatest.d.cts","sourceRoot":"","sources":["../../src/internal/useLatest.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGvC;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAMnD"}
@@ -0,0 +1,14 @@
1
+ import { RefObject } from 'react';
2
+ /**
3
+ * A ref holding the latest value, for callbacks that outlive a render
4
+ * (an async `signIn`, a listener).
5
+ *
6
+ * It is updated once the render commits, not during it: a render React
7
+ * discards (a concurrent or suspended one) must not leave its props in the
8
+ * ref. Insertion effects run before every layout effect and effect, so those
9
+ * already read the new value.
10
+ *
11
+ * Internal: not exported from the package.
12
+ */
13
+ export declare function useLatest<T>(value: T): RefObject<T>;
14
+ //# sourceMappingURL=useLatest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLatest.d.ts","sourceRoot":"","sources":["../../src/internal/useLatest.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAGvC;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAMnD"}
@@ -0,0 +1,15 @@
1
+ import { JwtCompositeToken, TokenStorage } from '@ahoo-wang/cosec-fetcher';
2
+ /**
3
+ * The token pair a `TokenStorage` holds, as React state: `null` while there is
4
+ * none.
5
+ *
6
+ * The snapshot is the stored value itself (`TokenStorage.get()` answers the
7
+ * same object until the pair changes), so a render in which nothing changed
8
+ * does not re-render. The server has no browser storage and renders `null`:
9
+ * hydration starts from the same value, and the stored pair follows right
10
+ * after.
11
+ *
12
+ * Internal: not exported from the package.
13
+ */
14
+ export declare function useStoredToken(tokenStorage: TokenStorage): JwtCompositeToken | null;
15
+ //# sourceMappingURL=useStoredToken.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStoredToken.d.cts","sourceRoot":"","sources":["../../src/internal/useStoredToken.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAMhF;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAC5B,YAAY,EAAE,YAAY,GACzB,iBAAiB,GAAG,IAAI,CAW1B"}
@@ -0,0 +1,15 @@
1
+ import { JwtCompositeToken, TokenStorage } from '@ahoo-wang/cosec-fetcher';
2
+ /**
3
+ * The token pair a `TokenStorage` holds, as React state: `null` while there is
4
+ * none.
5
+ *
6
+ * The snapshot is the stored value itself (`TokenStorage.get()` answers the
7
+ * same object until the pair changes), so a render in which nothing changed
8
+ * does not re-render. The server has no browser storage and renders `null`:
9
+ * hydration starts from the same value, and the stored pair follows right
10
+ * after.
11
+ *
12
+ * Internal: not exported from the package.
13
+ */
14
+ export declare function useStoredToken(tokenStorage: TokenStorage): JwtCompositeToken | null;
15
+ //# sourceMappingURL=useStoredToken.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStoredToken.d.ts","sourceRoot":"","sources":["../../src/internal/useStoredToken.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAMhF;;;;;;;;;;;GAWG;AACH,wBAAgB,cAAc,CAC5B,YAAY,EAAE,YAAY,GACzB,iBAAiB,GAAG,IAAI,CAW1B"}