@ahoo-wang/cosec-react 8.0.0-beta.3 → 8.0.0-beta.4
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.
- package/README.md +29 -8
- package/README.zh-CN.md +18 -5
- package/dist/cosec/useSecurity.d.cts +27 -4
- package/dist/cosec/useSecurity.d.cts.map +1 -1
- package/dist/cosec/useSecurity.d.ts +27 -4
- package/dist/cosec/useSecurity.d.ts.map +1 -1
- package/dist/index.es.js +60 -46
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.cjs +1 -1
- package/dist/index.umd.cjs.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -13,13 +13,13 @@ needs the hooks of `@ahoo-wang/fetcher-react` 6.x. Moving from those:
|
|
|
13
13
|
|
|
14
14
|
```bash
|
|
15
15
|
pnpm add react @ahoo-wang/fetcher @ahoo-wang/fetcher-eventbus \
|
|
16
|
-
@ahoo-wang/fetcher-storage @ahoo-wang/cosec-fetcher @ahoo-wang/cosec-react
|
|
16
|
+
@ahoo-wang/fetcher-storage @ahoo-wang/cosec-fetcher@beta @ahoo-wang/cosec-react@beta
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
Until CoSec 8.0 is released
|
|
20
|
-
|
|
21
|
-
`@
|
|
22
|
-
version of CoSec.
|
|
19
|
+
Until CoSec 8.0 is released, the `latest` tag of both packages points at a `0.0.0`
|
|
20
|
+
placeholder that is marked deprecated, so an install without a tag gets the
|
|
21
|
+
placeholder and a deprecation notice, not the client. Install the tag of the CoSec release you run: `@beta` for `8.0.0-beta.n` (as above), `@rc` for a release candidate, no tag once 8.0 is released; or an exact version, which stays right through all of them. A tag does not move past its line: once release candidates are out, `@beta` is still the last beta, which does not match an RC server. They are published with each
|
|
22
|
+
CoSec release, at the version of CoSec.
|
|
23
23
|
|
|
24
24
|
Peer dependencies: `react` (19) and `@ahoo-wang/cosec-fetcher`; the fetcher
|
|
25
25
|
packages are the client's (`cosec-fetcher`'s peers), and nothing else comes
|
|
@@ -31,18 +31,27 @@ Requires Node `^22.12.0 || ^24.0.0 || >=26.0.0` to build.
|
|
|
31
31
|
|
|
32
32
|
## Example
|
|
33
33
|
|
|
34
|
+
```ts
|
|
35
|
+
// tokenStorage.ts: the module the example below imports.
|
|
36
|
+
import { cosec } from './cosec'; // the module that creates and applies the CoSecConfigurer (see the fetcher package's README)
|
|
37
|
+
|
|
38
|
+
export const tokenStorage = cosec.tokenStorage;
|
|
39
|
+
export const tokenManager = cosec.tokenManager;
|
|
40
|
+
```
|
|
41
|
+
|
|
34
42
|
```tsx
|
|
35
43
|
import {
|
|
36
44
|
RouteGuard,
|
|
37
45
|
SecurityProvider,
|
|
38
46
|
useSecurityContext,
|
|
39
47
|
} from '@ahoo-wang/cosec-react';
|
|
40
|
-
import { tokenStorage } from './tokenStorage';
|
|
48
|
+
import { tokenManager, tokenStorage } from './tokenStorage';
|
|
41
49
|
|
|
42
50
|
function App() {
|
|
43
51
|
return (
|
|
44
52
|
<SecurityProvider
|
|
45
53
|
tokenStorage={tokenStorage}
|
|
54
|
+
tokenManager={tokenManager}
|
|
46
55
|
onSignOut={() => window.location.assign('/login')}
|
|
47
56
|
>
|
|
48
57
|
<RouteGuard
|
|
@@ -56,8 +65,11 @@ function App() {
|
|
|
56
65
|
}
|
|
57
66
|
|
|
58
67
|
function Profile() {
|
|
59
|
-
const { currentUser,
|
|
60
|
-
|
|
68
|
+
const { currentUser, logout } = useSecurityContext();
|
|
69
|
+
// The pair is gone here either way; a rejection says the server did not confirm.
|
|
70
|
+
const onLogout = () =>
|
|
71
|
+
logout().catch(() => alert('Signed out here; the server did not confirm.'));
|
|
72
|
+
return <button onClick={onLogout}>Log out {currentUser.sub}</button>;
|
|
61
73
|
}
|
|
62
74
|
```
|
|
63
75
|
|
|
@@ -66,6 +78,15 @@ function Profile() {
|
|
|
66
78
|
- `SecurityProvider`, `useSecurityContext`, `SecurityContext`: the security
|
|
67
79
|
state of the page, from one `TokenStorage`.
|
|
68
80
|
- `useSecurity`: the same without the context.
|
|
81
|
+
- `logout` and `signOut`: `logout` is the user's "Log out": it ends the session at
|
|
82
|
+
the server through the `tokenManager` option (`JwtTokenManager.logout()`, which
|
|
83
|
+
needs a `tokenRevoker`), then removes the pair here. Until the server answers,
|
|
84
|
+
the session is unchanged. It resolves on `204` or `401`, and rejects with
|
|
85
|
+
`LogoutUnconfirmedError` otherwise (and without a `tokenManager`); the pair is
|
|
86
|
+
gone here either way, and `onSignOut` fires unless a newer sign-in replaced the
|
|
87
|
+
session. `signOut` removes the pair here only, at once: for a session known to
|
|
88
|
+
be over. The `tokenManager` must be the manager of the hook's `tokenStorage`,
|
|
89
|
+
or the hook throws.
|
|
69
90
|
- `RouteGuard`: renders its children for a signed-in user, otherwise the
|
|
70
91
|
`fallback`. `onUnauthorized` runs after the render commits, once each time the
|
|
71
92
|
user becomes (or starts out) not signed in.
|
package/README.zh-CN.md
CHANGED
|
@@ -9,10 +9,10 @@
|
|
|
9
9
|
|
|
10
10
|
```bash
|
|
11
11
|
pnpm add react @ahoo-wang/fetcher @ahoo-wang/fetcher-eventbus \
|
|
12
|
-
@ahoo-wang/fetcher-storage @ahoo-wang/cosec-fetcher @ahoo-wang/cosec-react
|
|
12
|
+
@ahoo-wang/fetcher-storage @ahoo-wang/cosec-fetcher@beta @ahoo-wang/cosec-react@beta
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
CoSec 8.0
|
|
15
|
+
CoSec 8.0 发布之前,这两个包的 `latest` 标签指向一个标为已弃用的 `0.0.0` 占位版本,所以不带标签安装得到的是占位版本和一条弃用提示,而不是客户端。安装你所运行的 CoSec 版本对应的标签:`8.0.0-beta.n` 用 `@beta`(如上),候选发布版用 `@rc`,8.0 正式发布之后不带标签;也可以写明确切版本,它在所有这些阶段都正确。标签不会越过它所指的版本线:候选发布版出现之后,`@beta` 仍是最后一个 beta,与 RC 的服务端不匹配。
|
|
16
16
|
它们随每次 CoSec 发布而发布,版本与 CoSec 相同。
|
|
17
17
|
|
|
18
18
|
对等依赖:`react`(19)和 `@ahoo-wang/cosec-fetcher`;fetcher 的各个包是客户端(`cosec-fetcher` 的对等依赖)的,除此之外它不带任何别的东西。特别是它不会带上
|
|
@@ -23,18 +23,27 @@ CoSec 8.0 发布之前它们是预发布版本,npm 默认不会安装:用 di
|
|
|
23
23
|
|
|
24
24
|
## 示例
|
|
25
25
|
|
|
26
|
+
```ts
|
|
27
|
+
// tokenStorage.ts:下面的示例导入的模块。
|
|
28
|
+
import { cosec } from './cosec'; // 创建并应用 CoSecConfigurer 的模块(见 fetcher 包的 README)
|
|
29
|
+
|
|
30
|
+
export const tokenStorage = cosec.tokenStorage;
|
|
31
|
+
export const tokenManager = cosec.tokenManager;
|
|
32
|
+
```
|
|
33
|
+
|
|
26
34
|
```tsx
|
|
27
35
|
import {
|
|
28
36
|
RouteGuard,
|
|
29
37
|
SecurityProvider,
|
|
30
38
|
useSecurityContext,
|
|
31
39
|
} from '@ahoo-wang/cosec-react';
|
|
32
|
-
import { tokenStorage } from './tokenStorage';
|
|
40
|
+
import { tokenManager, tokenStorage } from './tokenStorage';
|
|
33
41
|
|
|
34
42
|
function App() {
|
|
35
43
|
return (
|
|
36
44
|
<SecurityProvider
|
|
37
45
|
tokenStorage={tokenStorage}
|
|
46
|
+
tokenManager={tokenManager}
|
|
38
47
|
onSignOut={() => window.location.assign('/login')}
|
|
39
48
|
>
|
|
40
49
|
<RouteGuard
|
|
@@ -48,8 +57,11 @@ function App() {
|
|
|
48
57
|
}
|
|
49
58
|
|
|
50
59
|
function Profile() {
|
|
51
|
-
const { currentUser,
|
|
52
|
-
|
|
60
|
+
const { currentUser, logout } = useSecurityContext();
|
|
61
|
+
// 无论如何令牌对在这里都已删除;拒绝说明服务端没有确认。
|
|
62
|
+
const onLogout = () =>
|
|
63
|
+
logout().catch(() => alert('已在本设备退出;服务端没有确认。'));
|
|
64
|
+
return <button onClick={onLogout}>退出 {currentUser.sub}</button>;
|
|
53
65
|
}
|
|
54
66
|
```
|
|
55
67
|
|
|
@@ -57,6 +69,7 @@ function Profile() {
|
|
|
57
69
|
|
|
58
70
|
- `SecurityProvider`、`useSecurityContext`、`SecurityContext`:页面的安全状态,来自一个 `TokenStorage`。
|
|
59
71
|
- `useSecurity`:不经过 context 的同一个 hook。
|
|
72
|
+
- `logout` 和 `signOut`:`logout` 是用户的"退出":通过 `tokenManager` 选项(`JwtTokenManager.logout()`,需要 `tokenRevoker`)在服务端结束会话,然后删除这里的令牌对。服务端回答之前,会话不变。`204` 或 `401` 时 resolve,其他情况(以及没有 `tokenManager` 时)以 `LogoutUnconfirmedError` reject;无论哪种情况,令牌对在这里都已删除,`onSignOut` 会触发,除非更新的登录替换了会话。`signOut` 只在这里立即删除令牌对:用于已知已经结束的会话。`tokenManager` 必须是该 hook 的 `tokenStorage` 的管理器,否则 hook 会抛出。
|
|
60
73
|
- `RouteGuard`:用户已登录时渲染子节点,否则渲染 `fallback`。`onUnauthorized` 在渲染提交之后运行,用户每次变为(或一开始就是)未登录时调用一次。
|
|
61
74
|
- `RefreshableRouteGuard`:用于 `JwtTokenManager` 能刷新的会话:它自己发起刷新,刷新期间渲染 `refreshing`,刷新失败时渲染 `fallback`。
|
|
62
75
|
- `ANONYMOUS_USER`:未登录访客的 `currentUser`。
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TokenStorage, CompositeToken, CoSecJwtPayload } from '@ahoo-wang/cosec-fetcher';
|
|
1
|
+
import { TokenStorage, CompositeToken, CoSecJwtPayload, JwtTokenManager } from '@ahoo-wang/cosec-fetcher';
|
|
2
2
|
/**
|
|
3
3
|
* Type representing a composite token provider.
|
|
4
4
|
* Can be either a direct composite token or a function that returns a promise of a composite token.
|
|
@@ -16,9 +16,16 @@ export interface UseSecurityOptions {
|
|
|
16
16
|
onSignIn?: () => void;
|
|
17
17
|
/**
|
|
18
18
|
* Callback function invoked when sign out occurs.
|
|
19
|
-
* This is called after the token has been removed.
|
|
19
|
+
* This is called after the token has been removed: by {@link UseSecurityReturn.signOut}, and by
|
|
20
|
+
* {@link UseSecurityReturn.logout} unless a newer sign-in replaced the session meanwhile.
|
|
20
21
|
*/
|
|
21
22
|
onSignOut?: () => void;
|
|
23
|
+
/**
|
|
24
|
+
* The JwtTokenManager whose `logout()` {@link UseSecurityReturn.logout} calls: it ends the session at the server
|
|
25
|
+
* (its `tokenRevoker`, CoSec's logout route). It must be the manager of this hook's `tokenStorage`; the hook
|
|
26
|
+
* throws otherwise, since a logout would end one session while the hook shows another.
|
|
27
|
+
*/
|
|
28
|
+
tokenManager?: JwtTokenManager;
|
|
22
29
|
}
|
|
23
30
|
/**
|
|
24
31
|
* Return type for the useSecurity hook.
|
|
@@ -42,9 +49,23 @@ export interface UseSecurityReturn {
|
|
|
42
49
|
*/
|
|
43
50
|
signIn: (compositeTokenProvider: CompositeTokenProvider) => Promise<void>;
|
|
44
51
|
/**
|
|
45
|
-
*
|
|
52
|
+
* Signs out here only: removes the stored pair, at once. The session lives on at the server until its refresh token
|
|
53
|
+
* expires, so use it for a session known to be over (after a `token-revoked`, say), and {@link logout} for the
|
|
54
|
+
* user's "Log out".
|
|
46
55
|
*/
|
|
47
56
|
signOut: () => void;
|
|
57
|
+
/**
|
|
58
|
+
* Logs out: ends the session at the server, then signs out here (`JwtTokenManager.logout()` of the
|
|
59
|
+
* `tokenManager` option). Until the server answers, the session is unchanged. The pair is removed whatever the
|
|
60
|
+
* server answered, so the hook shows the anonymous user and `onSignOut` fires, unless a newer sign-in replaced the
|
|
61
|
+
* session meanwhile.
|
|
62
|
+
*
|
|
63
|
+
* - Resolves when the server ended the session (`204`), or answered `401`: there was nothing left to end.
|
|
64
|
+
* - Rejects with `LogoutUnconfirmedError` for anything else (`503`, `500`, a network failure, a timeout), and
|
|
65
|
+
* without a `tokenManager`: the pair is gone here, and the session may live on at the server until its refresh
|
|
66
|
+
* token expires. Nothing is retried, and the pair is never stored again.
|
|
67
|
+
*/
|
|
68
|
+
logout: () => Promise<void>;
|
|
48
69
|
}
|
|
49
70
|
/**
|
|
50
71
|
* Hook for managing authentication state and operations using CoSec tokens.
|
|
@@ -59,13 +80,15 @@ export interface UseSecurityReturn {
|
|
|
59
80
|
* @param options - Optional configuration object containing lifecycle callbacks.
|
|
60
81
|
* @param options.onSignIn - Callback function invoked when sign in is successful.
|
|
61
82
|
* @param options.onSignOut - Callback function invoked when sign out occurs.
|
|
83
|
+
* @param options.tokenManager - The JwtTokenManager of `tokenStorage`, whose server logout `logout` calls.
|
|
62
84
|
* @returns An object containing:
|
|
63
85
|
* - currentUser: The stored access token's JWT payload (even if expired), or ANONYMOUS_USER when no token is stored.
|
|
64
86
|
* - authenticated: Boolean indicating whether the user is currently authenticated
|
|
65
87
|
* (the access token is unexpired). Computed at render; the hook also
|
|
66
88
|
* re-renders when the refresh token expires, so an idle page signs out then.
|
|
67
89
|
* - signIn: Function to authenticate with a composite token.
|
|
68
|
-
* - signOut:
|
|
90
|
+
* - signOut: Signs out here only, at once.
|
|
91
|
+
* - logout: Ends the session at the server, then signs out here (needs `options.tokenManager`).
|
|
69
92
|
* @throws {Error} May throw errors if tokenStorage operations fail, such as invalid tokens
|
|
70
93
|
* or storage access issues (implementation dependent).
|
|
71
94
|
* @example
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSecurity.d.cts","sourceRoot":"","sources":["../../src/cosec/useSecurity.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useSecurity.d.cts","sourceRoot":"","sources":["../../src/cosec/useSecurity.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,eAAe,EACf,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;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IAEvB;;;;OAIG;IACH,YAAY,CAAC,EAAE,eAAe,CAAC;CAChC;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;;;;OAIG;IACH,OAAO,EAAE,MAAM,IAAI,CAAC;IAEpB;;;;;;;;;;OAUG;IACH,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAgBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,wBAAgB,WAAW,CACzB,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,kBAAuB,GAC/B,iBAAiB,CAwFnB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TokenStorage, CompositeToken, CoSecJwtPayload } from '@ahoo-wang/cosec-fetcher';
|
|
1
|
+
import { TokenStorage, CompositeToken, CoSecJwtPayload, JwtTokenManager } from '@ahoo-wang/cosec-fetcher';
|
|
2
2
|
/**
|
|
3
3
|
* Type representing a composite token provider.
|
|
4
4
|
* Can be either a direct composite token or a function that returns a promise of a composite token.
|
|
@@ -16,9 +16,16 @@ export interface UseSecurityOptions {
|
|
|
16
16
|
onSignIn?: () => void;
|
|
17
17
|
/**
|
|
18
18
|
* Callback function invoked when sign out occurs.
|
|
19
|
-
* This is called after the token has been removed.
|
|
19
|
+
* This is called after the token has been removed: by {@link UseSecurityReturn.signOut}, and by
|
|
20
|
+
* {@link UseSecurityReturn.logout} unless a newer sign-in replaced the session meanwhile.
|
|
20
21
|
*/
|
|
21
22
|
onSignOut?: () => void;
|
|
23
|
+
/**
|
|
24
|
+
* The JwtTokenManager whose `logout()` {@link UseSecurityReturn.logout} calls: it ends the session at the server
|
|
25
|
+
* (its `tokenRevoker`, CoSec's logout route). It must be the manager of this hook's `tokenStorage`; the hook
|
|
26
|
+
* throws otherwise, since a logout would end one session while the hook shows another.
|
|
27
|
+
*/
|
|
28
|
+
tokenManager?: JwtTokenManager;
|
|
22
29
|
}
|
|
23
30
|
/**
|
|
24
31
|
* Return type for the useSecurity hook.
|
|
@@ -42,9 +49,23 @@ export interface UseSecurityReturn {
|
|
|
42
49
|
*/
|
|
43
50
|
signIn: (compositeTokenProvider: CompositeTokenProvider) => Promise<void>;
|
|
44
51
|
/**
|
|
45
|
-
*
|
|
52
|
+
* Signs out here only: removes the stored pair, at once. The session lives on at the server until its refresh token
|
|
53
|
+
* expires, so use it for a session known to be over (after a `token-revoked`, say), and {@link logout} for the
|
|
54
|
+
* user's "Log out".
|
|
46
55
|
*/
|
|
47
56
|
signOut: () => void;
|
|
57
|
+
/**
|
|
58
|
+
* Logs out: ends the session at the server, then signs out here (`JwtTokenManager.logout()` of the
|
|
59
|
+
* `tokenManager` option). Until the server answers, the session is unchanged. The pair is removed whatever the
|
|
60
|
+
* server answered, so the hook shows the anonymous user and `onSignOut` fires, unless a newer sign-in replaced the
|
|
61
|
+
* session meanwhile.
|
|
62
|
+
*
|
|
63
|
+
* - Resolves when the server ended the session (`204`), or answered `401`: there was nothing left to end.
|
|
64
|
+
* - Rejects with `LogoutUnconfirmedError` for anything else (`503`, `500`, a network failure, a timeout), and
|
|
65
|
+
* without a `tokenManager`: the pair is gone here, and the session may live on at the server until its refresh
|
|
66
|
+
* token expires. Nothing is retried, and the pair is never stored again.
|
|
67
|
+
*/
|
|
68
|
+
logout: () => Promise<void>;
|
|
48
69
|
}
|
|
49
70
|
/**
|
|
50
71
|
* Hook for managing authentication state and operations using CoSec tokens.
|
|
@@ -59,13 +80,15 @@ export interface UseSecurityReturn {
|
|
|
59
80
|
* @param options - Optional configuration object containing lifecycle callbacks.
|
|
60
81
|
* @param options.onSignIn - Callback function invoked when sign in is successful.
|
|
61
82
|
* @param options.onSignOut - Callback function invoked when sign out occurs.
|
|
83
|
+
* @param options.tokenManager - The JwtTokenManager of `tokenStorage`, whose server logout `logout` calls.
|
|
62
84
|
* @returns An object containing:
|
|
63
85
|
* - currentUser: The stored access token's JWT payload (even if expired), or ANONYMOUS_USER when no token is stored.
|
|
64
86
|
* - authenticated: Boolean indicating whether the user is currently authenticated
|
|
65
87
|
* (the access token is unexpired). Computed at render; the hook also
|
|
66
88
|
* re-renders when the refresh token expires, so an idle page signs out then.
|
|
67
89
|
* - signIn: Function to authenticate with a composite token.
|
|
68
|
-
* - signOut:
|
|
90
|
+
* - signOut: Signs out here only, at once.
|
|
91
|
+
* - logout: Ends the session at the server, then signs out here (needs `options.tokenManager`).
|
|
69
92
|
* @throws {Error} May throw errors if tokenStorage operations fail, such as invalid tokens
|
|
70
93
|
* or storage access issues (implementation dependent).
|
|
71
94
|
* @example
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useSecurity.d.ts","sourceRoot":"","sources":["../../src/cosec/useSecurity.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"useSecurity.d.ts","sourceRoot":"","sources":["../../src/cosec/useSecurity.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EACV,YAAY,EACZ,cAAc,EACd,eAAe,EACf,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;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,IAAI,CAAC;IAEvB;;;;OAIG;IACH,YAAY,CAAC,EAAE,eAAe,CAAC;CAChC;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;;;;OAIG;IACH,OAAO,EAAE,MAAM,IAAI,CAAC;IAEpB;;;;;;;;;;OAUG;IACH,MAAM,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AAgBD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,wBAAgB,WAAW,CACzB,YAAY,EAAE,YAAY,EAC1B,OAAO,GAAE,kBAAuB,GAC/B,iBAAiB,CAwFnB"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { c as e } from "react/compiler-runtime";
|
|
2
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 {
|
|
3
|
+
import { LogoutUnconfirmedError as u } from "@ahoo-wang/cosec-fetcher";
|
|
4
|
+
import { Fragment as d, jsx as f } from "react/jsx-runtime";
|
|
4
5
|
// src/internal/useLatest.ts
|
|
5
6
|
function useLatest(t) {
|
|
6
7
|
let n = e(2), r = s(t), t0;
|
|
@@ -9,72 +10,85 @@ function useLatest(t) {
|
|
|
9
10
|
}, n[0] = t, n[1] = t0), a(t0), r;
|
|
10
11
|
}
|
|
11
12
|
// src/internal/useStoredToken.ts
|
|
12
|
-
var
|
|
13
|
+
var p = 0, NO_TOKEN = () => null;
|
|
13
14
|
function useStoredToken(e) {
|
|
14
15
|
let t = n((t) => e.addListener({
|
|
15
|
-
name: `cosec-react:useStoredToken:${
|
|
16
|
+
name: `cosec-react:useStoredToken:${p++}`,
|
|
16
17
|
handle: t
|
|
17
18
|
}), [e]), r = n(() => e.get(), [e]);
|
|
18
19
|
return l(t, r, NO_TOKEN);
|
|
19
20
|
}
|
|
20
21
|
// src/cosec/useSecurity.ts
|
|
21
|
-
var
|
|
22
|
+
var m = {
|
|
22
23
|
jti: "",
|
|
23
24
|
sub: "anonymous",
|
|
24
25
|
iat: 0,
|
|
25
26
|
exp: 0
|
|
26
|
-
},
|
|
27
|
+
}, h = 2147483647, g = /* @__PURE__ */ new WeakMap();
|
|
27
28
|
function nextSessionGeneration(e) {
|
|
28
|
-
let t = (
|
|
29
|
-
return
|
|
29
|
+
let t = (g.get(e) ?? 0) + 1;
|
|
30
|
+
return g.set(e, t), t;
|
|
30
31
|
}
|
|
31
32
|
function useSecurity(t, n) {
|
|
32
|
-
let r = e(
|
|
33
|
+
let r = e(25), a;
|
|
33
34
|
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),
|
|
35
|
-
r[2] !==
|
|
36
|
-
if (typeof
|
|
37
|
-
let e = (
|
|
35
|
+
let s = a, c = useStoredToken(t), [, l] = o(_temp, 0), d = c?.refresh.payload?.exp, f = t.earlyPeriod, t2;
|
|
36
|
+
r[2] !== f || r[3] !== d || r[4] !== l ? (t2 = () => {
|
|
37
|
+
if (typeof d != "number") return;
|
|
38
|
+
let e = (d - f) * 1e3, t, arm = () => {
|
|
38
39
|
let n = e - Date.now();
|
|
39
|
-
n <= 0 ? l() : t = setTimeout(arm, Math.min(n,
|
|
40
|
+
n <= 0 ? l() : t = setTimeout(arm, Math.min(n, h));
|
|
40
41
|
};
|
|
41
42
|
return arm(), () => clearTimeout(t);
|
|
42
|
-
}, r[2] =
|
|
43
|
-
let
|
|
44
|
-
r[6] !==
|
|
45
|
-
let
|
|
46
|
-
r[9] !==
|
|
43
|
+
}, r[2] = f, r[3] = d, r[4] = l, r[5] = t2) : t2 = r[5];
|
|
44
|
+
let p;
|
|
45
|
+
r[6] !== f || r[7] !== d ? (p = [d, f], r[6] = f, r[7] = d, r[8] = p) : p = r[8], i(t2, p);
|
|
46
|
+
let _ = useLatest(s), t4;
|
|
47
|
+
r[9] !== _ || r[10] !== t ? (t4 = async (e) => {
|
|
47
48
|
let n = nextSessionGeneration(t), r = typeof e == "function" ? await e() : e;
|
|
48
|
-
|
|
49
|
-
}, r[9] =
|
|
50
|
-
let
|
|
51
|
-
r[12] !==
|
|
52
|
-
nextSessionGeneration(t), t.remove(),
|
|
53
|
-
}, r[12] =
|
|
54
|
-
let
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
49
|
+
g.get(t) === n && (t.signIn(r), _.current.onSignIn?.());
|
|
50
|
+
}, r[9] = _, r[10] = t, r[11] = t4) : t4 = r[11];
|
|
51
|
+
let v = t4, t5;
|
|
52
|
+
r[12] !== _ || r[13] !== t ? (t5 = () => {
|
|
53
|
+
nextSessionGeneration(t), t.remove(), _.current.onSignOut?.();
|
|
54
|
+
}, r[12] = _, r[13] = t, r[14] = t5) : t5 = r[14];
|
|
55
|
+
let y = t5, b = s.tokenManager;
|
|
56
|
+
if (b && b.tokenStorage !== t) throw Error("useSecurity: the tokenManager option manages another TokenStorage than the hook's: give it the manager of this one.");
|
|
57
|
+
let t6;
|
|
58
|
+
r[15] !== _ || r[16] !== b || r[17] !== t ? (t6 = async () => {
|
|
59
|
+
let e = nextSessionGeneration(t), n;
|
|
60
|
+
try {
|
|
61
|
+
b ? await b.logout() : (t.remove(), n = new u(/* @__PURE__ */ Error("No tokenManager: give useSecurity the JwtTokenManager of the server's logout route.")));
|
|
62
|
+
} catch (e) {
|
|
63
|
+
n = e;
|
|
64
|
+
}
|
|
65
|
+
if (g.get(t) === e && !t.get() && _.current.onSignOut?.(), n !== void 0) throw n;
|
|
66
|
+
}, r[15] = _, r[16] = b, r[17] = t, r[18] = t6) : t6 = r[18];
|
|
67
|
+
let x = t6, S = c?.access?.payload ?? m, C = c?.authenticated ?? !1, w;
|
|
68
|
+
return r[19] !== x || r[20] !== v || r[21] !== y || r[22] !== S || r[23] !== C ? (w = {
|
|
69
|
+
currentUser: S,
|
|
70
|
+
authenticated: C,
|
|
71
|
+
signIn: v,
|
|
72
|
+
signOut: y,
|
|
73
|
+
logout: x
|
|
74
|
+
}, r[19] = x, r[20] = v, r[21] = y, r[22] = S, r[23] = C, r[24] = w) : w = r[24], w;
|
|
61
75
|
}
|
|
62
76
|
function _temp(e) {
|
|
63
77
|
return e + 1;
|
|
64
78
|
}
|
|
65
79
|
// src/cosec/SecurityContext.tsx
|
|
66
|
-
var
|
|
80
|
+
var _ = t(void 0);
|
|
67
81
|
function SecurityProvider(t) {
|
|
68
82
|
let n = e(7), r, i, a;
|
|
69
83
|
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
84
|
let o = useSecurity(i, a), s;
|
|
71
|
-
return n[4] !== r || n[5] !== o ? (s = /* @__PURE__ */
|
|
85
|
+
return n[4] !== r || n[5] !== o ? (s = /* @__PURE__ */ f(_.Provider, {
|
|
72
86
|
value: o,
|
|
73
87
|
children: r
|
|
74
88
|
}), n[4] = r, n[5] = o, n[6] = s) : s = n[6], s;
|
|
75
89
|
}
|
|
76
90
|
function useSecurityContext() {
|
|
77
|
-
let e = r(
|
|
91
|
+
let e = r(_);
|
|
78
92
|
if (!e) throw Error("useSecurityContext must be used within a SecurityProvider");
|
|
79
93
|
return e;
|
|
80
94
|
}
|
|
@@ -85,34 +99,34 @@ function RouteGuard(t) {
|
|
|
85
99
|
s || c.current?.();
|
|
86
100
|
}, 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
101
|
let e;
|
|
88
|
-
return n[4] === r ? e = n[5] : (e = /* @__PURE__ */ d
|
|
102
|
+
return n[4] === r ? e = n[5] : (e = /* @__PURE__ */ f(d, { children: r }), n[4] = r, n[5] = e), e;
|
|
89
103
|
}
|
|
90
104
|
return a;
|
|
91
105
|
}
|
|
92
106
|
// src/cosec/RefreshableRouteGuard.tsx
|
|
93
107
|
function RefreshableRouteGuard(t) {
|
|
94
|
-
let n = e(12), { children: r, fallback: a, refreshing: o, tokenManager: s } = t, { authenticated: l } = useSecurityContext(),
|
|
95
|
-
if (n[0] !==
|
|
96
|
-
if (!
|
|
108
|
+
let n = e(12), { children: r, fallback: a, refreshing: o, tokenManager: s } = t, { authenticated: l } = useSecurityContext(), u = s.isRefreshNeeded && s.isRefreshable ? s.currentToken : null, [p, m] = c(null), h = u !== null && p === u, t1, g;
|
|
109
|
+
if (n[0] !== u || n[1] !== s ? (t1 = () => {
|
|
110
|
+
if (!u) return;
|
|
97
111
|
let e = !0;
|
|
98
112
|
return s.refresh().catch((t) => {
|
|
99
|
-
e && (console.error(t), m(
|
|
113
|
+
e && (console.error(t), m(u));
|
|
100
114
|
}), () => {
|
|
101
115
|
e = !1;
|
|
102
116
|
};
|
|
103
|
-
}, g = [
|
|
117
|
+
}, g = [u, s], n[0] = u, n[1] = s, n[2] = t1, n[3] = g) : (t1 = n[2], g = n[3]), i(t1, g), l) {
|
|
104
118
|
let e;
|
|
105
|
-
return n[4] === r ? e = n[5] : (e = /* @__PURE__ */ d
|
|
119
|
+
return n[4] === r ? e = n[5] : (e = /* @__PURE__ */ f(d, { children: r }), n[4] = r, n[5] = e), e;
|
|
106
120
|
}
|
|
107
|
-
if (!
|
|
121
|
+
if (!u || h) {
|
|
108
122
|
let e;
|
|
109
|
-
return n[6] === a ? e = n[7] : (e = /* @__PURE__ */ d
|
|
123
|
+
return n[6] === a ? e = n[7] : (e = /* @__PURE__ */ f(d, { children: a }), n[6] = a, n[7] = e), e;
|
|
110
124
|
}
|
|
111
125
|
let _;
|
|
112
|
-
n[8] === o ? _ = n[9] : (_ = o ?? /* @__PURE__ */
|
|
126
|
+
n[8] === o ? _ = n[9] : (_ = o ?? /* @__PURE__ */ f("p", { children: "Refreshing..." }), n[8] = o, n[9] = _);
|
|
113
127
|
let v = _, y;
|
|
114
|
-
return n[10] === v ? y = n[11] : (y = /* @__PURE__ */ d
|
|
128
|
+
return n[10] === v ? y = n[11] : (y = /* @__PURE__ */ f(d, { children: v }), n[10] = v, n[11] = y), y;
|
|
115
129
|
}
|
|
116
|
-
export {
|
|
130
|
+
export { m as ANONYMOUS_USER, RefreshableRouteGuard, RouteGuard, _ as SecurityContext, SecurityProvider, useSecurity, useSecurityContext };
|
|
117
131
|
|
|
118
132
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +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,EAAOE,CAAK,GAAEI;CAGxB,OAHwBH,EAAA,OAAAD,IAGzBI,KAAAH,EAAA,MAFkBG,WAAA;EACjBD,EAAGE,UAAWL;CAAH,GACZC,EAAA,KAAAD,GAAAC,EAAA,KAAAG,KAFDP,EAAmBO,EAElB,GACMD;AAAG;;AChBZ,IAAIK,IAAY,GAEVC,iBAAuB;AAc7B,SAAgBC,eACdC,GAC0B;CAC1B,IAAMC,IAAYN,GACfO,MACCF,EAAaG,YAAY;EACvBC,MAAM,8BAA8BP;EACpCQ,QAAQH;CACV,CAAC,GACH,CAACF,CAAY,CACf,GACMM,IAAcX,QAAkBK,EAAaO,IAAI,GAAG,CAACP,CAAY,CAAC;CACxE,OAAOJ,EAAqBK,GAAWK,GAAaR,QAAQ;AAC9D;;AChBA,IAAac,IAAkC;CAC7CC,KAAK;CACLC,KAAK;CACLC,KAAK;CACLC,KAAK;AACP,GAkDMQ,IAAc,YAKdC,oBAAqB,IAAIC,QAA8B;AAE7D,SA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DuB,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"}
|
|
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","LogoutUnconfirmedError","ANONYMOUS_USER","jti","sub","iat","exp","onSignIn","onSignOut","tokenManager","currentUser","authenticated","signIn","compositeTokenProvider","signOut","logout","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","Error","t6","generation_0","failure","t7","error","access","t8","t9","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","tokenManager","generation_0","failure","LogoutUnconfirmedError","t7","logout","t8","t9","count","SecurityContext","createContext","children","useSecurityOptions","context","useContext","latestOnUnauthorized","onUnauthorized","t2","authenticated","Fragment","fallback","refreshToken","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 { LogoutUnconfirmedError } from '@ahoo-wang/cosec-fetcher';\nimport type {\n TokenStorage,\n CompositeToken,\n CoSecJwtPayload,\n JwtTokenManager,\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: by {@link UseSecurityReturn.signOut}, and by\n * {@link UseSecurityReturn.logout} unless a newer sign-in replaced the session meanwhile.\n */\n onSignOut?: () => void;\n\n /**\n * The JwtTokenManager whose `logout()` {@link UseSecurityReturn.logout} calls: it ends the session at the server\n * (its `tokenRevoker`, CoSec's logout route). It must be the manager of this hook's `tokenStorage`; the hook\n * throws otherwise, since a logout would end one session while the hook shows another.\n */\n tokenManager?: JwtTokenManager;\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 * Signs out here only: removes the stored pair, at once. The session lives on at the server until its refresh token\n * expires, so use it for a session known to be over (after a `token-revoked`, say), and {@link logout} for the\n * user's \"Log out\".\n */\n signOut: () => void;\n\n /**\n * Logs out: ends the session at the server, then signs out here (`JwtTokenManager.logout()` of the\n * `tokenManager` option). Until the server answers, the session is unchanged. The pair is removed whatever the\n * server answered, so the hook shows the anonymous user and `onSignOut` fires, unless a newer sign-in replaced the\n * session meanwhile.\n *\n * - Resolves when the server ended the session (`204`), or answered `401`: there was nothing left to end.\n * - Rejects with `LogoutUnconfirmedError` for anything else (`503`, `500`, a network failure, a timeout), and\n * without a `tokenManager`: the pair is gone here, and the session may live on at the server until its refresh\n * token expires. Nothing is retried, and the pair is never stored again.\n */\n logout: () => Promise<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 * @param options.tokenManager - The JwtTokenManager of `tokenStorage`, whose server logout `logout` calls.\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: Signs out here only, at once.\n * - logout: Ends the session at the server, then signs out here (needs `options.tokenManager`).\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 const tokenManager = options.tokenManager;\n if (tokenManager && tokenManager.tokenStorage !== tokenStorage) {\n throw new Error(\n \"useSecurity: the tokenManager option manages another TokenStorage than the hook's: give it the manager of this one.\",\n );\n }\n const logout = useCallback(async () => {\n // A signIn whose provider is still pending is superseded, as by signOut.\n const generation = nextSessionGeneration(tokenStorage);\n let failure: unknown;\n try {\n if (tokenManager) {\n await tokenManager.logout();\n } else {\n tokenStorage.remove();\n failure = new LogoutUnconfirmedError(\n new Error(\n \"No tokenManager: give useSecurity the JwtTokenManager of the server's logout route.\",\n ),\n );\n }\n } catch (error) {\n failure = error;\n }\n // Signed out here, unless a signIn or signOut started meanwhile, or another tab signed in: that session stands.\n if (\n sessionGenerations.get(tokenStorage) === generation &&\n !tokenStorage.get()\n ) {\n optionsRef.current.onSignOut?.();\n }\n if (failure !== undefined) throw failure;\n }, [tokenStorage, tokenManager, optionsRef]);\n\n return {\n currentUser: token?.access?.payload ?? ANONYMOUS_USER,\n authenticated: token?.authenticated ?? false,\n signIn,\n signOut,\n logout,\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,EAAOE,CAAK,GAAEI;CAGxB,OAHwBH,EAAA,OAAAD,IAGzBI,KAAAH,EAAA,MAFkBG,WAAA;EACjBD,EAAGE,UAAWL;CAAH,GACZC,EAAA,KAAAD,GAAAC,EAAA,KAAAG,KAFDP,EAAmBO,EAElB,GACMD;AAAG;;AChBZ,IAAIK,IAAY,GAEVC,iBAAuB;AAc7B,SAAgBC,eACdC,GAC0B;CAC1B,IAAMC,IAAYN,GACfO,MACCF,EAAaG,YAAY;EACvBC,MAAM,8BAA8BP;EACpCQ,QAAQH;CACV,CAAC,GACH,CAACF,CAAY,CACf,GACMM,IAAcX,QAAkBK,EAAaO,IAAI,GAAG,CAACP,CAAY,CAAC;CACxE,OAAOJ,EAAqBK,GAAWK,GAAaR,QAAQ;AAC9D;;ACdA,IAAae,IAAkC;CAC7CC,KAAK;CACLC,KAAK;CACLC,KAAK;CACLC,KAAK;AACP,GAyEMU,IAAc,YAKdC,oBAAqB,IAAIC,QAA8B;AAE7D,SAASC,sBAAsBC,GAAoC;CACjE,IAAMC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B,AAAKH,MACLI,QAAOD,MAAOA,CAAK,GACnBP,EAAeH,CAAY;EAAC,CAC7B,SACM;GACLO,IAAUA;EAAH;CACR,GACAD,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"}
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1,2 +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
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("react/compiler-runtime"),require("react"),require("@ahoo-wang/cosec-fetcher"),require("react/jsx-runtime")):typeof define==`function`&&define.amd?define([`exports`,`react/compiler-runtime`,`react`,`@ahoo-wang/cosec-fetcher`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CoSecReact={},e.ReactCompilerRuntime,e.React,e.FetcherCoSec,e.ReactJSXRuntime))})(this,function(e,t,n,r,i){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 a=0,NO_TOKEN=()=>null;function useStoredToken(e){let t=(0,n.useCallback)(t=>e.addListener({name:`cosec-react:useStoredToken:${a++}`,handle:t}),[e]),r=(0,n.useCallback)(()=>e.get(),[e]);return(0,n.useSyncExternalStore)(t,r,NO_TOKEN)}var o={jti:``,sub:`anonymous`,iat:0,exp:0},s=2147483647,c=new WeakMap;function nextSessionGeneration(e){let t=(c.get(e)??0)+1;return c.set(e,t),t}function useSecurity(e,i){let a=(0,t.c)(25),l;a[0]===i?l=a[1]:(l=i===void 0?{}:i,a[0]=i,a[1]=l);let u=l,d=useStoredToken(e),[,f]=(0,n.useReducer)(_temp,0),p=d?.refresh.payload?.exp,m=e.earlyPeriod,t2;a[2]!==m||a[3]!==p||a[4]!==f?(t2=()=>{if(typeof p!=`number`)return;let e=(p-m)*1e3,t,arm=()=>{let n=e-Date.now();n<=0?f():t=setTimeout(arm,Math.min(n,s))};return arm(),()=>clearTimeout(t)},a[2]=m,a[3]=p,a[4]=f,a[5]=t2):t2=a[5];let h;a[6]!==m||a[7]!==p?(h=[p,m],a[6]=m,a[7]=p,a[8]=h):h=a[8],(0,n.useEffect)(t2,h);let g=useLatest(u),t4;a[9]!==g||a[10]!==e?(t4=async t=>{let n=nextSessionGeneration(e),r=typeof t==`function`?await t():t;c.get(e)===n&&(e.signIn(r),g.current.onSignIn?.())},a[9]=g,a[10]=e,a[11]=t4):t4=a[11];let _=t4,t5;a[12]!==g||a[13]!==e?(t5=()=>{nextSessionGeneration(e),e.remove(),g.current.onSignOut?.()},a[12]=g,a[13]=e,a[14]=t5):t5=a[14];let v=t5,y=u.tokenManager;if(y&&y.tokenStorage!==e)throw Error(`useSecurity: the tokenManager option manages another TokenStorage than the hook's: give it the manager of this one.`);let t6;a[15]!==g||a[16]!==y||a[17]!==e?(t6=async()=>{let t=nextSessionGeneration(e),n;try{y?await y.logout():(e.remove(),n=new r.LogoutUnconfirmedError(Error(`No tokenManager: give useSecurity the JwtTokenManager of the server's logout route.`)))}catch(e){n=e}if(c.get(e)===t&&!e.get()&&g.current.onSignOut?.(),n!==void 0)throw n},a[15]=g,a[16]=y,a[17]=e,a[18]=t6):t6=a[18];let b=t6,x=d?.access?.payload??o,S=d?.authenticated??!1,C;return a[19]!==b||a[20]!==_||a[21]!==v||a[22]!==x||a[23]!==S?(C={currentUser:x,authenticated:S,signIn:_,signOut:v,logout:b},a[19]=b,a[20]=_,a[21]=v,a[22]=x,a[23]=S,a[24]=C):C=a[24],C}function _temp(e){return e+1}var l=(0,n.createContext)(void 0);function SecurityProvider(e){let n=(0,t.c)(7),r,a,o;n[0]===e?(r=n[1],a=n[2],o=n[3]):({tokenStorage:a,children:r,...o}=e,n[0]=e,n[1]=r,n[2]=a,n[3]=o);let s=useSecurity(a,o),c;return n[4]!==r||n[5]!==s?(c=(0,i.jsx)(l.Provider,{value:s,children:r}),n[4]=r,n[5]=s,n[6]=c):c=n[6],c}function useSecurityContext(){let e=(0,n.useContext)(l);if(!e)throw Error(`useSecurityContext must be used within a SecurityProvider`);return e}function RouteGuard(e){let r=(0,t.c)(6),{children:a,fallback:o,onUnauthorized:s}=e,{authenticated:c}=useSecurityContext(),l=useLatest(s),t1,u;if(r[0]!==c||r[1]!==l?(t1=()=>{c||l.current?.()},u=[c,l],r[0]=c,r[1]=l,r[2]=t1,r[3]=u):(t1=r[2],u=r[3]),(0,n.useEffect)(t1,u),c){let e;return r[4]===a?e=r[5]:(e=(0,i.jsx)(i.Fragment,{children:a}),r[4]=a,r[5]=e),e}return o}function RefreshableRouteGuard(e){let r=(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(r[0]!==u||r[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],r[0]=u,r[1]=c,r[2]=t1,r[3]=m):(t1=r[2],m=r[3]),(0,n.useEffect)(t1,m),l){let e;return r[4]===a?e=r[5]:(e=(0,i.jsx)(i.Fragment,{children:a}),r[4]=a,r[5]=e),e}if(!u||p){let e;return r[6]===o?e=r[7]:(e=(0,i.jsx)(i.Fragment,{children:o}),r[6]=o,r[7]=e),e}let h;r[8]===s?h=r[9]:(h=s??(0,i.jsx)(`p`,{children:`Refreshing...`}),r[8]=s,r[9]=h);let g=h,_;return r[10]===g?_=r[11]:(_=(0,i.jsx)(i.Fragment,{children:g}),r[10]=g,r[11]=_),_}e.ANONYMOUS_USER=o,e.RefreshableRouteGuard=RefreshableRouteGuard,e.RouteGuard=RouteGuard,e.SecurityContext=l,e.SecurityProvider=SecurityProvider,e.useSecurity=useSecurity,e.useSecurityContext=useSecurityContext});
|
|
2
2
|
//# sourceMappingURL=index.umd.cjs.map
|
package/dist/index.umd.cjs.map
CHANGED
|
@@ -1 +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"],"m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AuBD,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"}
|
|
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","LogoutUnconfirmedError","ANONYMOUS_USER","jti","sub","iat","exp","onSignIn","onSignOut","tokenManager","currentUser","authenticated","signIn","compositeTokenProvider","signOut","logout","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","Error","t6","generation_0","failure","t7","error","access","t8","t9","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","tokenManager","generation_0","failure","_ahoo_wang_cosec_fetcher","t7","logout","t8","t9","count","SecurityContext","children","useSecurityOptions","react_jsx_runtime","context","latestOnUnauthorized","onUnauthorized","t2","authenticated","fallback","refreshToken","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 { LogoutUnconfirmedError } from '@ahoo-wang/cosec-fetcher';\nimport type {\n TokenStorage,\n CompositeToken,\n CoSecJwtPayload,\n JwtTokenManager,\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: by {@link UseSecurityReturn.signOut}, and by\n * {@link UseSecurityReturn.logout} unless a newer sign-in replaced the session meanwhile.\n */\n onSignOut?: () => void;\n\n /**\n * The JwtTokenManager whose `logout()` {@link UseSecurityReturn.logout} calls: it ends the session at the server\n * (its `tokenRevoker`, CoSec's logout route). It must be the manager of this hook's `tokenStorage`; the hook\n * throws otherwise, since a logout would end one session while the hook shows another.\n */\n tokenManager?: JwtTokenManager;\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 * Signs out here only: removes the stored pair, at once. The session lives on at the server until its refresh token\n * expires, so use it for a session known to be over (after a `token-revoked`, say), and {@link logout} for the\n * user's \"Log out\".\n */\n signOut: () => void;\n\n /**\n * Logs out: ends the session at the server, then signs out here (`JwtTokenManager.logout()` of the\n * `tokenManager` option). Until the server answers, the session is unchanged. The pair is removed whatever the\n * server answered, so the hook shows the anonymous user and `onSignOut` fires, unless a newer sign-in replaced the\n * session meanwhile.\n *\n * - Resolves when the server ended the session (`204`), or answered `401`: there was nothing left to end.\n * - Rejects with `LogoutUnconfirmedError` for anything else (`503`, `500`, a network failure, a timeout), and\n * without a `tokenManager`: the pair is gone here, and the session may live on at the server until its refresh\n * token expires. Nothing is retried, and the pair is never stored again.\n */\n logout: () => Promise<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 * @param options.tokenManager - The JwtTokenManager of `tokenStorage`, whose server logout `logout` calls.\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: Signs out here only, at once.\n * - logout: Ends the session at the server, then signs out here (needs `options.tokenManager`).\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 const tokenManager = options.tokenManager;\n if (tokenManager && tokenManager.tokenStorage !== tokenStorage) {\n throw new Error(\n \"useSecurity: the tokenManager option manages another TokenStorage than the hook's: give it the manager of this one.\",\n );\n }\n const logout = useCallback(async () => {\n // A signIn whose provider is still pending is superseded, as by signOut.\n const generation = nextSessionGeneration(tokenStorage);\n let failure: unknown;\n try {\n if (tokenManager) {\n await tokenManager.logout();\n } else {\n tokenStorage.remove();\n failure = new LogoutUnconfirmedError(\n new Error(\n \"No tokenManager: give useSecurity the JwtTokenManager of the server's logout route.\",\n ),\n );\n }\n } catch (error) {\n failure = error;\n }\n // Signed out here, unless a signIn or signOut started meanwhile, or another tab signed in: that session stands.\n if (\n sessionGenerations.get(tokenStorage) === generation &&\n !tokenStorage.get()\n ) {\n optionsRef.current.onSignOut?.();\n }\n if (failure !== undefined) throw failure;\n }, [tokenStorage, tokenManager, optionsRef]);\n\n return {\n currentUser: token?.access?.payload ?? ANONYMOUS_USER,\n authenticated: token?.authenticated ?? false,\n signIn,\n signOut,\n logout,\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,6hBA2BA,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,CCdA,IAAae,EAAkC,CAC7CC,IAAK,GACLC,IAAK,YACLC,IAAK,EACLC,IAAK,CACP,EAyEMU,EAAc,WAKdC,EAAqB,IAAIC,QAE/B,SAASC,sBAAsBC,EAAoC,CACjE,IAAMC,GAAcJ,EAAmB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,CAAA,SAAGF,CAAc,CAAA,EAAIpB,EAAA,IAAAoB,EAAApB,EAAA,IAAAqB,GAArBA,CAAqB,C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/cosec-react",
|
|
3
|
-
"version": "8.0.0-beta.
|
|
3
|
+
"version": "8.0.0-beta.4",
|
|
4
4
|
"description": "React hooks and components for a CoSec application: the security context, the signed-in state and route guards, on top of @ahoo-wang/cosec-fetcher.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -47,11 +47,11 @@
|
|
|
47
47
|
],
|
|
48
48
|
"sideEffects": false,
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@ahoo-wang/cosec-fetcher": "~8.0.0-beta.
|
|
50
|
+
"@ahoo-wang/cosec-fetcher": "~8.0.0-beta.4",
|
|
51
51
|
"react": "^19.0.0"
|
|
52
52
|
},
|
|
53
53
|
"devDependencies": {
|
|
54
|
-
"@ahoo-wang/cosec-fetcher": "8.0.0-beta.
|
|
54
|
+
"@ahoo-wang/cosec-fetcher": "8.0.0-beta.4",
|
|
55
55
|
"@ahoo-wang/fetcher": "^6.1.0",
|
|
56
56
|
"@ahoo-wang/fetcher-eventbus": "^6.1.0",
|
|
57
57
|
"@ahoo-wang/fetcher-storage": "^6.1.0",
|