@autional/shared 0.1.0-rc.61 → 0.1.0-rc.63

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autional/shared",
3
- "version": "0.1.0-rc.61",
3
+ "version": "0.1.0-rc.63",
4
4
  "description": "Autional shared layer — API client, auth, types, hooks, utils",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./src/index.ts",
@@ -11,6 +11,7 @@
11
11
  "./branding": "./src/branding/index.ts",
12
12
  "./slug-from-url": "./src/auth/slug-from-url.ts",
13
13
  "./portal": "./src/portal/registry.ts",
14
+ "./fetch": "./src/api/fetch-client.ts",
14
15
  "./generated/api": "./src/generated/api.ts",
15
16
  "./generated/types": "./src/generated/types.ts",
16
17
  "./generated/queries": "./src/generated/queries.ts",
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { FetchApiError, createFetchClient } from '@autional/shared/fetch';
3
+
4
+ /**
5
+ * 子路径导出 `@autional/shared/fetch` 的意义:**不把整包 index 拉进站点**。
6
+ *
7
+ * 实测教训(2026-11-11,密钥中心迁移):`import { createFetchClient } from '@autional/shared'`
8
+ * 会连带初始化 130 个模块(axios/react-query/zustand/生成类型…),在 vitest 的
9
+ * `vi.resetModules()` + 动态 import 场景下每个用例多花 5–20s,直接把 5s 超时的用例打红。
10
+ * 只引这个子路径后,模块图只有本文件(零依赖)。
11
+ */
12
+ describe('@autional/shared/fetch 子路径导出', () => {
13
+ it('可从包名子路径导入 createFetchClient / FetchApiError', () => {
14
+ expect(typeof createFetchClient).toBe('function');
15
+ expect(typeof FetchApiError).toBe('function');
16
+ });
17
+
18
+ it('模块本身不引入运行时依赖(源码级断言)', async () => {
19
+ const fs = await import('node:fs/promises');
20
+ const url = new URL('../fetch-client.ts', import.meta.url);
21
+ const src = await fs.readFile(url, 'utf8');
22
+ const imports = src
23
+ .split(/\r?\n/)
24
+ .filter((line) => /^\s*import\s/.test(line) || /^\s*\} from\s+['"]/.test(line));
25
+ expect(imports).toEqual([]);
26
+ });
27
+ });
@@ -0,0 +1,89 @@
1
+ // @vitest-environment jsdom
2
+ // ============================================================
3
+ // 会话心跳 hook 契约锁(2026-11-10 会话策略交接 §3.3):
4
+ // ① 端点由调用方给定(管理面 /admin/sessions/me/activity、用户面 /sessions/me/activity)
5
+ // ② getToken 可注入(config/secret 用本地 @/lib/auth,不复用 shared store)
6
+ // ③ 三道闸门:页面不可见不发 / 最近无交互不发 / 未到间隔不发
7
+ // ④ 缺 sid 不发(服务端按 token 归属,前端不拼 sid)
8
+ // ============================================================
9
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
10
+ import { renderHook } from '@testing-library/react';
11
+
12
+ import { useSessionActivity } from '../useSessionActivity';
13
+
14
+ /** 构造一个带 sid 的假 JWT(签名无关,只解码 payload)。 */
15
+ function fakeToken(payload: Record<string, unknown>): string {
16
+ const b64 = (obj: Record<string, unknown>) =>
17
+ Buffer.from(JSON.stringify(obj)).toString('base64url');
18
+ return `${b64({ alg: 'none' })}.${b64(payload)}.sig`;
19
+ }
20
+
21
+ const fetchMock = vi.fn(() => Promise.resolve({ ok: true } as Response));
22
+
23
+ beforeEach(() => {
24
+ vi.useFakeTimers();
25
+ vi.stubGlobal('fetch', fetchMock);
26
+ fetchMock.mockClear();
27
+ Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
28
+ });
29
+
30
+ afterEach(() => {
31
+ vi.useRealTimers();
32
+ vi.unstubAllGlobals();
33
+ });
34
+
35
+ describe('useSessionActivity', () => {
36
+ it('可见 + 有交互 + 到间隔 → 按调用方端点发一次心跳', () => {
37
+ const token = fakeToken({ custom: { sid: 'sid-1' }, tenant_id: 't-1' });
38
+ renderHook(() =>
39
+ useSessionActivity({ endpoint: '/bff/session/api/v1/admin/sessions/me/activity', getToken: () => token }),
40
+ );
41
+
42
+ vi.advanceTimersByTime(5 * 60_000);
43
+
44
+ expect(fetchMock).toHaveBeenCalledTimes(1);
45
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
46
+ expect(url).toBe('/bff/session/api/v1/admin/sessions/me/activity');
47
+ expect(init.method).toBe('POST');
48
+ expect((init.headers as Record<string, string>).Authorization).toBe('Bearer ' + token);
49
+ expect((init.headers as Record<string, string>)['X-Tenant-ID']).toBe('t-1');
50
+ });
51
+
52
+ it('页面不可见 → 不发', () => {
53
+ Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });
54
+ renderHook(() =>
55
+ useSessionActivity({ endpoint: '/x', getToken: () => fakeToken({ custom: { sid: 's' } }) }),
56
+ );
57
+ vi.advanceTimersByTime(10 * 60_000);
58
+ expect(fetchMock).not.toHaveBeenCalled();
59
+ });
60
+
61
+ it('没有 sid → 不发(服务端按 token 归属,前端不拼 sid)', () => {
62
+ renderHook(() =>
63
+ useSessionActivity({ endpoint: '/x', getToken: () => fakeToken({ sub: 'u-1' }) }),
64
+ );
65
+ vi.advanceTimersByTime(10 * 60_000);
66
+ expect(fetchMock).not.toHaveBeenCalled();
67
+ });
68
+
69
+ it('超过交互窗口无交互 → 停发(人不在就让会话自然过期)', () => {
70
+ renderHook(() =>
71
+ useSessionActivity({ endpoint: '/x', getToken: () => fakeToken({ custom: { sid: 'sid-1' } }) }),
72
+ );
73
+
74
+ vi.advanceTimersByTime(5 * 60_000);
75
+ expect(fetchMock).toHaveBeenCalledTimes(1);
76
+
77
+ // 之后 15 分钟无人交互(lastInteraction 停在挂载时刻)
78
+ vi.advanceTimersByTime(15 * 60_000);
79
+ expect(fetchMock).toHaveBeenCalledTimes(1);
80
+ });
81
+
82
+ it('disabled → 完全不发', () => {
83
+ renderHook(() =>
84
+ useSessionActivity({ endpoint: '/x', getToken: () => fakeToken({ custom: { sid: 's' } }), disabled: true }),
85
+ );
86
+ vi.advanceTimersByTime(10 * 60_000);
87
+ expect(fetchMock).not.toHaveBeenCalled();
88
+ });
89
+ });
@@ -0,0 +1,106 @@
1
+ import { useEffect, useRef } from 'react';
2
+
3
+ import { getAccessToken } from '../auth/store';
4
+ import { decodeJwtPayload } from '../auth/jwt-payload';
5
+
6
+ /** 心跳间隔:闲置 30 分钟的 1/6(业界常用 5 分钟)。 */
7
+ const DEFAULT_PING_INTERVAL = 5 * 60_000;
8
+ /** 检查节拍:每秒级太重,1 分钟一次足够(真正的间隔由 pingInterval 控制)。 */
9
+ const DEFAULT_TICK_INTERVAL = 60_000;
10
+ /** 交互新鲜度:超过这个时间没交互就不发心跳(人不在,让会话自然闲置过期)。 */
11
+ const DEFAULT_INTERACTION_FRESH = 5 * 60_000;
12
+
13
+ export interface UseSessionActivityOptions {
14
+ /**
15
+ * 心跳端点。管理面用 `/bff/session/api/v1/admin/sessions/me/activity`,
16
+ * 用户面用 `/bff/session/api/v1/sessions/me/activity`。
17
+ */
18
+ endpoint: string;
19
+ /**
20
+ * 取 access token。默认用 shared 的 `getAccessToken`;
21
+ * 门户若用本地 auth 模块(如 config/secret 的 `@/lib/auth`),可注入自己的实现。
22
+ */
23
+ getToken?: () => string | null;
24
+ /** 心跳最小间隔,默认 5 分钟。 */
25
+ pingIntervalMs?: number;
26
+ /** 检查节拍,默认 60 秒。 */
27
+ tickIntervalMs?: number;
28
+ /** 交互新鲜度窗口,默认 5 分钟。 */
29
+ interactionFreshMs?: number;
30
+ /** 关闭开关(灰度/测试用),默认 false。 */
31
+ disabled?: boolean;
32
+ }
33
+
34
+ function str(source: Record<string, unknown> | null | undefined, key: string): string {
35
+ const value = source?.[key];
36
+ return typeof value === 'string' ? value : '';
37
+ }
38
+
39
+ /**
40
+ * 会话活动心跳(NIST「activity resets inactivity」口径)。
41
+ *
42
+ * 只在「页面可见 + 最近 N 分钟有真实交互」时上报;失败静默,不影响业务请求。
43
+ * 服务端首次心跳把会话切到闲置策略(opt-in),未接心跳的客户端不受影响。
44
+ * 心跳只续闲置窗口,绝对上限由服务端固定,心跳无法突破。
45
+ */
46
+ export function useSessionActivity(options: UseSessionActivityOptions): void {
47
+ const {
48
+ endpoint,
49
+ getToken = getAccessToken,
50
+ pingIntervalMs = DEFAULT_PING_INTERVAL,
51
+ tickIntervalMs = DEFAULT_TICK_INTERVAL,
52
+ interactionFreshMs = DEFAULT_INTERACTION_FRESH,
53
+ disabled = false,
54
+ } = options;
55
+
56
+ const lastInteraction = useRef(Date.now());
57
+ const lastPing = useRef(0);
58
+
59
+ // 依赖项放在 ref 里,避免调用方每次渲染传新对象导致定时器重建。
60
+ const config = useRef({ endpoint, getToken, pingIntervalMs, tickIntervalMs, interactionFreshMs, disabled });
61
+ config.current = { endpoint, getToken, pingIntervalMs, tickIntervalMs, interactionFreshMs, disabled };
62
+
63
+ useEffect(() => {
64
+ const mark = () => {
65
+ lastInteraction.current = Date.now();
66
+ };
67
+ const events: Array<keyof WindowEventMap> = ['pointerdown', 'keydown', 'touchstart', 'wheel'];
68
+ events.forEach((name) => window.addEventListener(name, mark, { passive: true }));
69
+
70
+ const ping = () => {
71
+ const cfg = config.current;
72
+ if (cfg.disabled) return;
73
+ const token = cfg.getToken();
74
+ if (!token) return;
75
+ if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return;
76
+ const now = Date.now();
77
+ if (now - lastInteraction.current > cfg.interactionFreshMs) return;
78
+ if (now - lastPing.current < cfg.pingIntervalMs) return;
79
+ const claims = decodeJwtPayload(token);
80
+ const custom = (claims?.custom ?? null) as Record<string, unknown> | null;
81
+ const sid = str(custom, 'sid') || str(custom, 'session_id') || str(claims, 'session_id');
82
+ if (!sid) return;
83
+ lastPing.current = now;
84
+ const headers: Record<string, string> = {
85
+ Accept: 'application/json',
86
+ Authorization: 'Bearer ' + token,
87
+ };
88
+ const tenant = str(claims, 'tenant_id') || str(custom, 'tenant_id');
89
+ const app = str(claims, 'app_id') || str(custom, 'app_id');
90
+ if (tenant) headers['X-Tenant-ID'] = tenant;
91
+ if (app) headers['X-App-ID'] = app;
92
+ void fetch(cfg.endpoint, { method: 'POST', headers, credentials: 'omit' }).catch(() => undefined);
93
+ };
94
+
95
+ const timer = window.setInterval(ping, tickIntervalMs);
96
+ const onVisible = () => {
97
+ if (document.visibilityState === 'visible') ping();
98
+ };
99
+ document.addEventListener('visibilitychange', onVisible);
100
+ return () => {
101
+ events.forEach((name) => window.removeEventListener(name, mark));
102
+ window.clearInterval(timer);
103
+ document.removeEventListener('visibilitychange', onVisible);
104
+ };
105
+ }, [tickIntervalMs]);
106
+ }
package/src/index.ts CHANGED
@@ -97,6 +97,8 @@ export type { BootstrapState } from './hooks/useBootstrap';
97
97
  export { useSodMode, useIsAuditRestricted } from './hooks/useSodMode';
98
98
  export type { SodMode } from './hooks/useSodMode';
99
99
  export { useCurrentRole } from './hooks/useCurrentRole';
100
+ export { useSessionActivity } from './hooks/useSessionActivity';
101
+ export type { UseSessionActivityOptions } from './hooks/useSessionActivity';
100
102
  export {
101
103
  usePortalCatalog,
102
104
  isPortalVisible,