@taicode/common-web 3.7.11 → 3.7.12

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.
@@ -0,0 +1,18 @@
1
+ import type { ReactNode } from 'react';
2
+ export type CanProps = {
3
+ /** 服务名,即 account 中注册的操作所属 service */
4
+ service: string;
5
+ /** 操作名,即路由的 operationId */
6
+ operation: string;
7
+ /** 无权时渲染的内容,默认什么都不渲染 */
8
+ fallback?: ReactNode;
9
+ children?: ReactNode;
10
+ };
11
+ /**
12
+ * 按 API 权限控制界面元素显隐。
13
+ *
14
+ * 判定 key 与后端完全一致(service + operation),不存在第二份权限事实。
15
+ * 这里只负责减少不可用操作,不承担安全职责——服务端网关仍会拦截。
16
+ */
17
+ export declare const Can: import("react").FunctionComponent<CanProps>;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../source/components/can/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAItC,MAAM,MAAM,QAAQ,GAAG;IACrB,qCAAqC;IACrC,OAAO,EAAE,MAAM,CAAA;IACf,2BAA2B;IAC3B,SAAS,EAAE,MAAM,CAAA;IACjB,wBAAwB;IACxB,QAAQ,CAAC,EAAE,SAAS,CAAA;IACpB,QAAQ,CAAC,EAAE,SAAS,CAAA;CACrB,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,GAAG,6CAQd,CAAA"}
@@ -0,0 +1,17 @@
1
+ import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
2
+ import { observer } from 'mobx-react-lite';
3
+ import { useAccessControl } from '../../services/access-control/index.js';
4
+ /**
5
+ * 按 API 权限控制界面元素显隐。
6
+ *
7
+ * 判定 key 与后端完全一致(service + operation),不存在第二份权限事实。
8
+ * 这里只负责减少不可用操作,不承担安全职责——服务端网关仍会拦截。
9
+ */
10
+ export const Can = observer(function Can(props) {
11
+ var _a;
12
+ const accessControl = useAccessControl();
13
+ if (!accessControl.can(props.service, props.operation)) {
14
+ return _jsx(_Fragment, { children: (_a = props.fallback) !== null && _a !== void 0 ? _a : null });
15
+ }
16
+ return _jsx(_Fragment, { children: props.children });
17
+ });
@@ -5,6 +5,7 @@ export * from './badge.js';
5
5
  export * from './button.js';
6
6
  export * from './card.js';
7
7
  export * from './calendar.js';
8
+ export * from './can/index.js';
8
9
  export * from './chart.js';
9
10
  export * from './checkbox.js';
10
11
  export * from './command.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/components/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA;AAC1B,cAAc,mBAAmB,CAAA;AACjC,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,aAAa,CAAA;AAC3B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,kBAAkB,CAAA;AAChC,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,UAAU,CAAA;AACxB,cAAc,YAAY,CAAA;AAC1B,cAAc,yBAAyB,CAAA;AACvC,cAAc,oBAAoB,CAAA;AAClC,cAAc,6BAA6B,CAAA;AAC3C,cAAc,iBAAiB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,cAAc,cAAc,CAAA;AAC5B,cAAc,eAAe,CAAA;AAC7B,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,qBAAqB,CAAA;AACnC,cAAc,aAAa,CAAA;AAC3B,cAAc,mBAAmB,CAAA;AACjC,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../source/components/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA;AAC1B,cAAc,mBAAmB,CAAA;AACjC,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,aAAa,CAAA;AAC3B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,oBAAoB,CAAA;AAClC,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,kBAAkB,CAAA;AAChC,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,UAAU,CAAA;AACxB,cAAc,YAAY,CAAA;AAC1B,cAAc,yBAAyB,CAAA;AACvC,cAAc,oBAAoB,CAAA;AAClC,cAAc,6BAA6B,CAAA;AAC3C,cAAc,iBAAiB,CAAA;AAC/B,cAAc,uBAAuB,CAAA;AACrC,cAAc,cAAc,CAAA;AAC5B,cAAc,eAAe,CAAA;AAC7B,cAAc,kBAAkB,CAAA;AAChC,cAAc,kBAAkB,CAAA;AAChC,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,cAAc,YAAY,CAAA;AAC1B,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,cAAc,aAAa,CAAA;AAC3B,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA;AACzB,cAAc,eAAe,CAAA;AAC7B,cAAc,qBAAqB,CAAA;AACnC,cAAc,aAAa,CAAA;AAC3B,cAAc,mBAAmB,CAAA;AACjC,cAAc,cAAc,CAAA;AAC5B,cAAc,cAAc,CAAA"}
@@ -5,6 +5,7 @@ export * from './badge.js';
5
5
  export * from './button.js';
6
6
  export * from './card.js';
7
7
  export * from './calendar.js';
8
+ export * from './can/index.js';
8
9
  export * from './chart.js';
9
10
  export * from './checkbox.js';
10
11
  export * from './command.js';
@@ -0,0 +1,94 @@
1
+ /**
2
+ * 访问控制(界面权限)原语。
3
+ *
4
+ * 设计前提:界面权限不另立一套 key,而是**由 API 权限派生**。
5
+ * account 的权限原子单位就是路由的 operationId(service + operation),
6
+ * 各业务服务启动时会把自己的操作目录自注册到 account;
7
+ * 因此「页面/按钮是否可见」与「接口是否放行」指向同一个 key,不存在第二份事实。
8
+ *
9
+ * 数据来源是 account 的 `listCurrentUserPermissionOperation` 批量接口:
10
+ * 一次拉取当前用户的全部允许项,之后所有判定都在本地查表完成。
11
+ * 接口只返回“被允许的操作”,不返回任何身份概念,因此前端也不需要区分
12
+ * 管理员与普通用户 —— 它只是权限模型的一个视图。
13
+ *
14
+ * 安全边界不在这里 —— 前端判定只决定「显示什么」,
15
+ * 真正的拦截始终由服务端网关(plugins/auth.ts -> gateway/verify)负责。
16
+ *
17
+ * 本模块只提供状态机与判定逻辑,不注册任何全局状态;
18
+ * 实例由调用方(业务应用)创建并持有,因此同一实例可以同时被
19
+ * 路由守卫、侧边栏与按钮读取。
20
+ */
21
+ /** 权限判定结果,与服务端 PermissionEffect 一致 */
22
+ export type AccessEffect = 'Allow' | 'Deny' | 'AllowWithApiKey';
23
+ export type AccessDecision = {
24
+ service: string;
25
+ operation: string;
26
+ effect: AccessEffect;
27
+ };
28
+ /** 由业务应用提供,负责用各自的 API 客户端调用 account 拉取允许的操作清单 */
29
+ export type AccessSnapshotLoader = () => Promise<AccessDecision[]>;
30
+ export type AccessControlOptions = {
31
+ loader: AccessSnapshotLoader;
32
+ /** 快照有效期,默认 5 分钟 */
33
+ ttlMs?: number;
34
+ };
35
+ /** 拼接判定键,与 account 的匹配规则一致 */
36
+ export declare function createAccessKey(service: string, operation: string): string;
37
+ export declare class AccessControl {
38
+ private readonly loader;
39
+ private readonly ttlMs;
40
+ private expiresAt;
41
+ private inFlight;
42
+ /** 重置代数:登出/切换用户后用于丢弃迟到的响应 */
43
+ private generation;
44
+ /** 是否已完成过一次成功加载 */
45
+ accessor inited: boolean;
46
+ /** 是否正在加载 */
47
+ accessor loading: boolean;
48
+ /**
49
+ * 允许项索引。
50
+ * 这里刻意用 observable.map:组件在 render 中调用 can()/canAnyInService()
51
+ * 时会自动建立依赖,加载完成后无需额外的订阅机制即可重新渲染。
52
+ */
53
+ private readonly effects;
54
+ constructor(options: AccessControlOptions);
55
+ /** 已加载的允许项数量 */
56
+ get size(): number;
57
+ /**
58
+ * 查询单个操作的效果。
59
+ * @returns 'Allow' | 'AllowWithApiKey' | 'Deny';尚未加载完成时返回 null
60
+ */
61
+ effect(service: string, operation: string): AccessEffect | null;
62
+ /**
63
+ * 是否允许该操作。
64
+ * AllowWithApiKey 同样视为「允许」——它表示需要携带 API Key 调用,
65
+ * 而不是不可用;需要区分时用 needsApiKey。
66
+ */
67
+ can(service: string, operation: string): boolean;
68
+ /** 是否需要携带 API Key 才能调用(应在界面上提示而非隐藏入口) */
69
+ needsApiKey(service: string, operation: string): boolean;
70
+ /** 是否已被明确拒绝 */
71
+ isDenied(service: string, operation: string): boolean;
72
+ /**
73
+ * 该服务下是否存在任意一个被允许的操作。
74
+ * 用于「管理控制台」这类聚合入口的显隐:只要服务内有任何可用操作就值得进入,
75
+ * 避免出现「能进后台但什么都干不了」的空入口。
76
+ */
77
+ canAnyInService(service: string): boolean;
78
+ /** 给定的一组操作中是否至少允许一个 */
79
+ canAny(keys: Array<{
80
+ service: string;
81
+ operation: string;
82
+ }>): boolean;
83
+ /**
84
+ * 加载快照。
85
+ * 命中有效期内的缓存或已有在途请求时直接复用,因此可以在守卫里放心调用。
86
+ */
87
+ load(force?: boolean): Promise<void>;
88
+ /** 强制刷新,忽略缓存 */
89
+ refresh(): Promise<void>;
90
+ /** 清空状态(登出、切换用户时调用),并丢弃在途响应 */
91
+ reset(): void;
92
+ private fetch;
93
+ }
94
+ //# sourceMappingURL=access-control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access-control.d.ts","sourceRoot":"","sources":["../../../source/services/access-control/access-control.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,sCAAsC;AACtC,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,MAAM,GAAG,iBAAiB,CAAA;AAE/D,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,YAAY,CAAA;CACrB,CAAA;AAED,iDAAiD;AACjD,MAAM,MAAM,oBAAoB,GAAG,MAAM,OAAO,CAAC,cAAc,EAAE,CAAC,CAAA;AAElE,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,oBAAoB,CAAA;IAC5B,oBAAoB;IACpB,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAID,8BAA8B;AAC9B,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAE1E;AAED,qBAAa,aAAa;IAExB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsB;IAE7C,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAQ;IAE9B,OAAO,CAAC,SAAS,CAAI;IAErB,OAAO,CAAC,QAAQ,CAA6B;IAE7C,6BAA6B;IAC7B,OAAO,CAAC,UAAU,CAAI;IAEtB,mBAAmB;IACnB,SACgB,MAAM,EAAE,OAAO,CAAQ;IAEvC,aAAa;IACb,SACgB,OAAO,EAAE,OAAO,CAAQ;IAExC;;;;OAIG;IACH,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyC;gBAErD,OAAO,EAAE,oBAAoB;IAKzC,gBAAgB;IAChB,IACI,IAAI,IAAI,MAAM,CAEjB;IAED;;;OAGG;IACI,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI;IAKtE;;;;OAIG;IACI,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAKvD,yCAAyC;IAClC,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAI/D,eAAe;IACR,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO;IAI5D;;;;OAIG;IACI,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO;IAYhD,uBAAuB;IAChB,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG,OAAO;IAI3E;;;OAGG;IACU,IAAI,CAAC,KAAK,GAAE,OAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAkBxD,gBAAgB;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAIrC,+BAA+B;IAExB,KAAK,IAAI,IAAI;YASN,KAAK;CAwBpB"}
@@ -0,0 +1,218 @@
1
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
2
+ var useValue = arguments.length > 2;
3
+ for (var i = 0; i < initializers.length; i++) {
4
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5
+ }
6
+ return useValue ? value : void 0;
7
+ };
8
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
9
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
10
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
11
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
12
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
13
+ var _, done = false;
14
+ for (var i = decorators.length - 1; i >= 0; i--) {
15
+ var context = {};
16
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
17
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
18
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
19
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
20
+ if (kind === "accessor") {
21
+ if (result === void 0) continue;
22
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
23
+ if (_ = accept(result.get)) descriptor.get = _;
24
+ if (_ = accept(result.set)) descriptor.set = _;
25
+ if (_ = accept(result.init)) initializers.unshift(_);
26
+ }
27
+ else if (_ = accept(result)) {
28
+ if (kind === "field") initializers.unshift(_);
29
+ else descriptor[key] = _;
30
+ }
31
+ }
32
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
33
+ done = true;
34
+ };
35
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
36
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
37
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
38
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
39
+ };
40
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
41
+ if (kind === "m") throw new TypeError("Private method is not writable");
42
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
43
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
44
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
45
+ };
46
+ import { action, computed, observable, runInAction } from 'mobx';
47
+ import { catchIt } from '@taicode/common-base';
48
+ const DEFAULT_TTL_MS = 5 * 60000;
49
+ /** 拼接判定键,与 account 的匹配规则一致 */
50
+ export function createAccessKey(service, operation) {
51
+ return `${service}:${operation}`;
52
+ }
53
+ let AccessControl = (() => {
54
+ var _a, _AccessControl_inited_accessor_storage, _AccessControl_loading_accessor_storage;
55
+ let _instanceExtraInitializers = [];
56
+ let _inited_decorators;
57
+ let _inited_initializers = [];
58
+ let _inited_extraInitializers = [];
59
+ let _loading_decorators;
60
+ let _loading_initializers = [];
61
+ let _loading_extraInitializers = [];
62
+ let _get_size_decorators;
63
+ let _reset_decorators;
64
+ return _a = class AccessControl {
65
+ /** 是否已完成过一次成功加载 */
66
+ get inited() { return __classPrivateFieldGet(this, _AccessControl_inited_accessor_storage, "f"); }
67
+ set inited(value) { __classPrivateFieldSet(this, _AccessControl_inited_accessor_storage, value, "f"); }
68
+ /** 是否正在加载 */
69
+ get loading() { return __classPrivateFieldGet(this, _AccessControl_loading_accessor_storage, "f"); }
70
+ set loading(value) { __classPrivateFieldSet(this, _AccessControl_loading_accessor_storage, value, "f"); }
71
+ constructor(options) {
72
+ var _b;
73
+ this.loader = __runInitializers(this, _instanceExtraInitializers);
74
+ this.expiresAt = 0;
75
+ this.inFlight = null;
76
+ /** 重置代数:登出/切换用户后用于丢弃迟到的响应 */
77
+ this.generation = 0;
78
+ _AccessControl_inited_accessor_storage.set(this, __runInitializers(this, _inited_initializers, false
79
+ /** 是否正在加载 */
80
+ ));
81
+ _AccessControl_loading_accessor_storage.set(this, (__runInitializers(this, _inited_extraInitializers), __runInitializers(this, _loading_initializers, false
82
+ /**
83
+ * 允许项索引。
84
+ * 这里刻意用 observable.map:组件在 render 中调用 can()/canAnyInService()
85
+ * 时会自动建立依赖,加载完成后无需额外的订阅机制即可重新渲染。
86
+ */
87
+ )));
88
+ /**
89
+ * 允许项索引。
90
+ * 这里刻意用 observable.map:组件在 render 中调用 can()/canAnyInService()
91
+ * 时会自动建立依赖,加载完成后无需额外的订阅机制即可重新渲染。
92
+ */
93
+ this.effects = (__runInitializers(this, _loading_extraInitializers), observable.map());
94
+ this.loader = options.loader;
95
+ this.ttlMs = (_b = options.ttlMs) !== null && _b !== void 0 ? _b : DEFAULT_TTL_MS;
96
+ }
97
+ /** 已加载的允许项数量 */
98
+ get size() {
99
+ return this.effects.size;
100
+ }
101
+ /**
102
+ * 查询单个操作的效果。
103
+ * @returns 'Allow' | 'AllowWithApiKey' | 'Deny';尚未加载完成时返回 null
104
+ */
105
+ effect(service, operation) {
106
+ var _b;
107
+ if (!this.inited)
108
+ return null;
109
+ return (_b = this.effects.get(createAccessKey(service, operation))) !== null && _b !== void 0 ? _b : 'Deny';
110
+ }
111
+ /**
112
+ * 是否允许该操作。
113
+ * AllowWithApiKey 同样视为「允许」——它表示需要携带 API Key 调用,
114
+ * 而不是不可用;需要区分时用 needsApiKey。
115
+ */
116
+ can(service, operation) {
117
+ const effect = this.effect(service, operation);
118
+ return effect === 'Allow' || effect === 'AllowWithApiKey';
119
+ }
120
+ /** 是否需要携带 API Key 才能调用(应在界面上提示而非隐藏入口) */
121
+ needsApiKey(service, operation) {
122
+ return this.effect(service, operation) === 'AllowWithApiKey';
123
+ }
124
+ /** 是否已被明确拒绝 */
125
+ isDenied(service, operation) {
126
+ return this.effect(service, operation) === 'Deny';
127
+ }
128
+ /**
129
+ * 该服务下是否存在任意一个被允许的操作。
130
+ * 用于「管理控制台」这类聚合入口的显隐:只要服务内有任何可用操作就值得进入,
131
+ * 避免出现「能进后台但什么都干不了」的空入口。
132
+ */
133
+ canAnyInService(service) {
134
+ if (!this.inited)
135
+ return false;
136
+ const prefix = `${service}:`;
137
+ for (const [key, effect] of this.effects) {
138
+ if (key.startsWith(prefix) && (effect === 'Allow' || effect === 'AllowWithApiKey')) {
139
+ return true;
140
+ }
141
+ }
142
+ return false;
143
+ }
144
+ /** 给定的一组操作中是否至少允许一个 */
145
+ canAny(keys) {
146
+ return keys.some(key => this.can(key.service, key.operation));
147
+ }
148
+ /**
149
+ * 加载快照。
150
+ * 命中有效期内的缓存或已有在途请求时直接复用,因此可以在守卫里放心调用。
151
+ */
152
+ async load(force = false) {
153
+ if (!force && this.inited && this.expiresAt > Date.now())
154
+ return;
155
+ if (this.inFlight !== null) {
156
+ await this.inFlight;
157
+ return;
158
+ }
159
+ const task = this.fetch(this.generation);
160
+ this.inFlight = task;
161
+ await task;
162
+ // 只清理自己这一次的请求:reset() 之后发起的请求不能被旧请求的收尾逻辑顶掉
163
+ if (this.inFlight === task) {
164
+ this.inFlight = null;
165
+ }
166
+ }
167
+ /** 强制刷新,忽略缓存 */
168
+ async refresh() {
169
+ await this.load(true);
170
+ }
171
+ /** 清空状态(登出、切换用户时调用),并丢弃在途响应 */
172
+ reset() {
173
+ this.generation++;
174
+ this.inFlight = null;
175
+ this.effects.clear();
176
+ this.inited = false;
177
+ this.loading = false;
178
+ this.expiresAt = 0;
179
+ }
180
+ async fetch(generation) {
181
+ runInAction(() => {
182
+ this.loading = true;
183
+ });
184
+ const result = await catchIt(() => this.loader());
185
+ // 加载失败不覆盖已有结果:宁可沿用旧快照,也不要让界面整片消失
186
+ if (!result.isError() && generation === this.generation) {
187
+ const list = result.value;
188
+ runInAction(() => {
189
+ this.effects.replace(list.map((item) => [
190
+ createAccessKey(item.service, item.operation),
191
+ item.effect,
192
+ ]));
193
+ this.inited = true;
194
+ this.expiresAt = Date.now() + this.ttlMs;
195
+ });
196
+ }
197
+ runInAction(() => {
198
+ this.loading = false;
199
+ });
200
+ }
201
+ },
202
+ _AccessControl_inited_accessor_storage = new WeakMap(),
203
+ _AccessControl_loading_accessor_storage = new WeakMap(),
204
+ (() => {
205
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
206
+ _inited_decorators = [observable];
207
+ _loading_decorators = [observable];
208
+ _get_size_decorators = [computed];
209
+ _reset_decorators = [action];
210
+ __esDecorate(_a, null, _inited_decorators, { kind: "accessor", name: "inited", static: false, private: false, access: { has: obj => "inited" in obj, get: obj => obj.inited, set: (obj, value) => { obj.inited = value; } }, metadata: _metadata }, _inited_initializers, _inited_extraInitializers);
211
+ __esDecorate(_a, null, _loading_decorators, { kind: "accessor", name: "loading", static: false, private: false, access: { has: obj => "loading" in obj, get: obj => obj.loading, set: (obj, value) => { obj.loading = value; } }, metadata: _metadata }, _loading_initializers, _loading_extraInitializers);
212
+ __esDecorate(_a, null, _get_size_decorators, { kind: "getter", name: "size", static: false, private: false, access: { has: obj => "size" in obj, get: obj => obj.size }, metadata: _metadata }, null, _instanceExtraInitializers);
213
+ __esDecorate(_a, null, _reset_decorators, { kind: "method", name: "reset", static: false, private: false, access: { has: obj => "reset" in obj, get: obj => obj.reset }, metadata: _metadata }, null, _instanceExtraInitializers);
214
+ if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
215
+ })(),
216
+ _a;
217
+ })();
218
+ export { AccessControl };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=access-control.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access-control.test.d.ts","sourceRoot":"","sources":["../../../source/services/access-control/access-control.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,190 @@
1
+ import { describe, it, expect, vi, afterEach } from 'vitest';
2
+ import { configure } from 'mobx';
3
+ import { AccessControl, createAccessKey } from './access-control.js';
4
+ configure({
5
+ enforceActions: 'never',
6
+ computedRequiresReaction: false,
7
+ reactionRequiresObservable: false,
8
+ observableRequiresReaction: false,
9
+ disableErrorBoundaries: true,
10
+ });
11
+ function createSnapshot(items) {
12
+ return items.map(([service, operation, effect]) => ({ service, operation, effect }));
13
+ }
14
+ function createDeferred() {
15
+ let resolve;
16
+ let reject;
17
+ const promise = new Promise((resolvePromise, rejectPromise) => {
18
+ resolve = resolvePromise;
19
+ reject = rejectPromise;
20
+ });
21
+ return { promise, resolve, reject };
22
+ }
23
+ describe('createAccessKey', () => {
24
+ it('用冒号拼接 service 和 operation', () => {
25
+ expect(createAccessKey('expense', 'queryDetail')).toBe('expense:queryDetail');
26
+ });
27
+ });
28
+ describe('AccessControl', () => {
29
+ afterEach(() => {
30
+ vi.useRealTimers();
31
+ vi.restoreAllMocks();
32
+ });
33
+ describe('加载前', () => {
34
+ it('不给出确定结论,区分「未知」与「拒绝」', async () => {
35
+ const control = new AccessControl({ loader: async () => createSnapshot([]) });
36
+ expect(control.inited).toBe(false);
37
+ expect(control.size).toBe(0);
38
+ expect(control.effect('expense', 'queryDetail')).toBeNull();
39
+ expect(control.can('expense', 'queryDetail')).toBe(false);
40
+ expect(control.canAnyInService('expense')).toBe(false);
41
+ });
42
+ });
43
+ describe('加载后', () => {
44
+ it('列表中的操作允许,未列出的操作默认拒绝', async () => {
45
+ const control = new AccessControl({
46
+ loader: async () => createSnapshot([['expense', 'queryDetail', 'Allow']]),
47
+ });
48
+ await control.load();
49
+ expect(control.inited).toBe(true);
50
+ expect(control.size).toBe(1);
51
+ expect(control.can('expense', 'queryDetail')).toBe(true);
52
+ expect(control.effect('expense', 'queryDetail')).toBe('Allow');
53
+ // 未出现在允许列表中的操作一律拒绝,与服务端「无命中即拒绝」一致
54
+ expect(control.can('expense', 'createDetail')).toBe(false);
55
+ expect(control.effect('expense', 'createDetail')).toBe('Deny');
56
+ expect(control.isDenied('expense', 'createDetail')).toBe(true);
57
+ });
58
+ it('AllowWithApiKey 视为允许,但标记需要 API Key', async () => {
59
+ const control = new AccessControl({
60
+ loader: async () => createSnapshot([['notice', 'sendNotice', 'AllowWithApiKey']]),
61
+ });
62
+ await control.load();
63
+ expect(control.can('notice', 'sendNotice')).toBe(true);
64
+ expect(control.needsApiKey('notice', 'sendNotice')).toBe(true);
65
+ expect(control.isDenied('notice', 'sendNotice')).toBe(false);
66
+ });
67
+ it('Deny 不会被当作允许', async () => {
68
+ const control = new AccessControl({
69
+ loader: async () => createSnapshot([['notice', 'sendNotice', 'Deny']]),
70
+ });
71
+ await control.load();
72
+ expect(control.can('notice', 'sendNotice')).toBe(false);
73
+ });
74
+ it('canAnyInService 只看同一 service 前缀', async () => {
75
+ const control = new AccessControl({
76
+ loader: async () => createSnapshot([
77
+ ['notice', 'queryNotice', 'Allow'],
78
+ ['expense', 'queryDetail', 'Deny'],
79
+ ]),
80
+ });
81
+ await control.load();
82
+ expect(control.canAnyInService('notice')).toBe(true);
83
+ expect(control.canAnyInService('expense')).toBe(false);
84
+ expect(control.canAnyInService('release')).toBe(false);
85
+ });
86
+ it('canAny 命中任意一项即为真', async () => {
87
+ const control = new AccessControl({
88
+ loader: async () => createSnapshot([['notice', 'queryNotice', 'Allow']]),
89
+ });
90
+ await control.load();
91
+ expect(control.canAny([
92
+ { service: 'notice', operation: 'createNotice' },
93
+ { service: 'notice', operation: 'queryNotice' },
94
+ ])).toBe(true);
95
+ expect(control.canAny([
96
+ { service: 'notice', operation: 'createNotice' },
97
+ ])).toBe(false);
98
+ });
99
+ });
100
+ describe('缓存与并发', () => {
101
+ it('有效期内的重复调用不会再次请求', async () => {
102
+ const loader = vi.fn(async () => createSnapshot([['expense', 'queryDetail', 'Allow']]));
103
+ const control = new AccessControl({ loader, ttlMs: 60000 });
104
+ await control.load();
105
+ await control.load();
106
+ expect(loader).toHaveBeenCalledTimes(1);
107
+ });
108
+ it('超过有效期后重新请求', async () => {
109
+ vi.useFakeTimers();
110
+ const loader = vi.fn(async () => createSnapshot([['expense', 'queryDetail', 'Allow']]));
111
+ const control = new AccessControl({ loader, ttlMs: 60000 });
112
+ await control.load();
113
+ vi.advanceTimersByTime(60001);
114
+ await control.load();
115
+ expect(loader).toHaveBeenCalledTimes(2);
116
+ });
117
+ it('force 为 true 时忽略有效期', async () => {
118
+ const loader = vi.fn(async () => createSnapshot([['expense', 'queryDetail', 'Allow']]));
119
+ const control = new AccessControl({ loader, ttlMs: 60000 });
120
+ await control.load();
121
+ await control.refresh();
122
+ expect(loader).toHaveBeenCalledTimes(2);
123
+ });
124
+ it('并发调用共享同一个在途请求', async () => {
125
+ const deferred = createDeferred();
126
+ const loader = vi.fn(() => deferred.promise);
127
+ const control = new AccessControl({ loader });
128
+ const first = control.load();
129
+ const second = control.load();
130
+ deferred.resolve(createSnapshot([['expense', 'queryDetail', 'Allow']]));
131
+ await Promise.all([first, second]);
132
+ expect(loader).toHaveBeenCalledTimes(1);
133
+ expect(control.can('expense', 'queryDetail')).toBe(true);
134
+ });
135
+ it('加载失败时保留已有快照,不让界面整片消失', async () => {
136
+ let shouldFail = false;
137
+ const control = new AccessControl({
138
+ loader: async () => {
139
+ if (shouldFail)
140
+ throw new Error('network down');
141
+ return createSnapshot([['expense', 'queryDetail', 'Allow']]);
142
+ },
143
+ ttlMs: 0,
144
+ });
145
+ await control.load();
146
+ expect(control.can('expense', 'queryDetail')).toBe(true);
147
+ shouldFail = true;
148
+ await control.load(true);
149
+ expect(control.can('expense', 'queryDetail')).toBe(true);
150
+ expect(control.loading).toBe(false);
151
+ });
152
+ });
153
+ describe('reset', () => {
154
+ it('清空快照并回到未加载状态', async () => {
155
+ const control = new AccessControl({
156
+ loader: async () => createSnapshot([['expense', 'queryDetail', 'Allow']]),
157
+ });
158
+ await control.load();
159
+ control.reset();
160
+ expect(control.inited).toBe(false);
161
+ expect(control.size).toBe(0);
162
+ expect(control.effect('expense', 'queryDetail')).toBeNull();
163
+ expect(control.canAnyInService('expense')).toBe(false);
164
+ });
165
+ it('丢弃 reset 之前发起的在途响应', async () => {
166
+ const deferred = createDeferred();
167
+ const control = new AccessControl({ loader: () => deferred.promise });
168
+ const pending = control.load();
169
+ control.reset();
170
+ deferred.resolve(createSnapshot([['expense', 'queryDetail', 'Allow']]));
171
+ await pending;
172
+ // 迟到的响应属于上一个身份,不能写回
173
+ expect(control.inited).toBe(false);
174
+ expect(control.size).toBe(0);
175
+ });
176
+ it('reset 后重新加载可以拿到新身份的权限', async () => {
177
+ const items = [['expense', 'queryDetail', 'Allow']];
178
+ const control = new AccessControl({
179
+ loader: async () => createSnapshot(items),
180
+ });
181
+ await control.load();
182
+ expect(control.can('expense', 'queryDetail')).toBe(true);
183
+ control.reset();
184
+ items.splice(0, items.length, ['expense', 'createDetail', 'Allow']);
185
+ await control.load();
186
+ expect(control.can('expense', 'queryDetail')).toBe(false);
187
+ expect(control.can('expense', 'createDetail')).toBe(true);
188
+ });
189
+ });
190
+ });
@@ -0,0 +1,15 @@
1
+ import type { ReactNode } from 'react';
2
+ import type { AccessControl } from './access-control.js';
3
+ export type AccessControlProviderProps = {
4
+ /** 应用自己持有并配置好的实例;守卫与组件必须拿到同一个对象 */
5
+ control: AccessControl;
6
+ children?: ReactNode;
7
+ };
8
+ /**
9
+ * 把访问控制实例注入 React 树。
10
+ * 实例由应用创建(其中包含 loader 配置),common-web 不注册任何全局单例。
11
+ */
12
+ export declare function AccessControlProvider(props: AccessControlProviderProps): import("react").JSX.Element;
13
+ /** 读取当前应用的访问控制实例;读取 observable 字段即可获得自动重渲染 */
14
+ export declare function useAccessControl(): AccessControl;
15
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../source/services/access-control/context.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAEtC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAIxD,MAAM,MAAM,0BAA0B,GAAG;IACvC,mCAAmC;IACnC,OAAO,EAAE,aAAa,CAAA;IACtB,QAAQ,CAAC,EAAE,SAAS,CAAA;CACrB,CAAA;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,0BAA0B,+BAMtE;AAED,8CAA8C;AAC9C,wBAAgB,gBAAgB,IAAI,aAAa,CAQhD"}
@@ -0,0 +1,18 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext } from 'react';
3
+ const AccessControlContext = createContext(null);
4
+ /**
5
+ * 把访问控制实例注入 React 树。
6
+ * 实例由应用创建(其中包含 loader 配置),common-web 不注册任何全局单例。
7
+ */
8
+ export function AccessControlProvider(props) {
9
+ return (_jsx(AccessControlContext.Provider, { value: props.control, children: props.children }));
10
+ }
11
+ /** 读取当前应用的访问控制实例;读取 observable 字段即可获得自动重渲染 */
12
+ export function useAccessControl() {
13
+ const control = useContext(AccessControlContext);
14
+ if (control === null) {
15
+ throw new Error('useAccessControl 必须在 AccessControlProvider 内部使用');
16
+ }
17
+ return control;
18
+ }
@@ -0,0 +1,5 @@
1
+ export { AccessControl, createAccessKey } from './access-control.js';
2
+ export type { AccessControlOptions, AccessDecision, AccessEffect, AccessSnapshotLoader, } from './access-control.js';
3
+ export { AccessControlProvider, useAccessControl } from './context.js';
4
+ export type { AccessControlProviderProps } from './context.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../source/services/access-control/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAA;AACpE,YAAY,EACV,oBAAoB,EACpB,cAAc,EACd,YAAY,EACZ,oBAAoB,GACrB,MAAM,qBAAqB,CAAA;AAE5B,OAAO,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAA;AACtE,YAAY,EAAE,0BAA0B,EAAE,MAAM,cAAc,CAAA"}
@@ -0,0 +1,2 @@
1
+ export { AccessControl, createAccessKey } from './access-control.js';
2
+ export { AccessControlProvider, useAccessControl } from './context.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taicode/common-web",
3
- "version": "3.7.11",
3
+ "version": "3.7.12",
4
4
  "author": "Alain",
5
5
  "license": "ISC",
6
6
  "description": "",
@@ -54,7 +54,7 @@
54
54
  "mobx": ">=6",
55
55
  "mobx-react-lite": "^4.1.1",
56
56
  "react": ">=18",
57
- "@taicode/common-base": "^3.7.11"
57
+ "@taicode/common-base": "^3.7.12"
58
58
  },
59
59
  "dependencies": {
60
60
  "@headlessui/react": "^2.2.9",
@@ -100,7 +100,7 @@
100
100
  "vite-plugin-svgr": "^4.5.0",
101
101
  "vite-tsconfig-paths": "^5.1.4",
102
102
  "vitest": "^3.2.7",
103
- "@taicode/common-base": "^3.7.11"
103
+ "@taicode/common-base": "^3.7.12"
104
104
  },
105
105
  "scripts": {
106
106
  "test": "vitest",