@autional/shared 0.1.0-rc.57 → 0.1.0-rc.59

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.57",
3
+ "version": "0.1.0-rc.59",
4
4
  "description": "Autional shared layer — API client, auth, types, hooks, utils",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./src/index.ts",
@@ -16,6 +16,9 @@
16
16
  "./generated/queries": "./src/generated/queries.ts",
17
17
  "./package.json": "./package.json"
18
18
  },
19
+ "bin": {
20
+ "autional-check-portal-literals": "./src/portal/check-literals.mjs"
21
+ },
19
22
  "files": [
20
23
  "src"
21
24
  ],
@@ -257,6 +257,25 @@ describe('createFetchClient', () => {
257
257
  await expect(client.get('/x')).rejects.toMatchObject({ status: 200, code: 'invalid_json' });
258
258
  });
259
259
 
260
+
261
+ it('responseType=text:原样返回字符串(导出文件体),不解析 JSON', async () => {
262
+ const body = 'key: value' + String.fromCharCode(10) + 'other: 1' + String.fromCharCode(10);
263
+ stubFetch(() => textResponse(body));
264
+ const client = createFetchClient({ baseUrl: '/api' });
265
+
266
+ await expect(client.get('/export', { responseType: 'text' })).resolves.toBe(body);
267
+ });
268
+
269
+ it('responseType=text 时非 2xx 仍归一为 FetchApiError(错误体为文本)', async () => {
270
+ stubFetch(() => textResponse('upstream unavailable', 503));
271
+ const client = createFetchClient({ baseUrl: '/api' });
272
+
273
+ await expect(client.get('/export', { responseType: 'text' })).rejects.toMatchObject({
274
+ status: 503,
275
+ body: 'upstream unavailable',
276
+ });
277
+ });
278
+
260
279
  it('空响应体 ⇒ null(删除成功类)', async () => {
261
280
  stubFetch(() => textResponse('', 204));
262
281
  const client = createFetchClient({ baseUrl: '/api' });
@@ -40,6 +40,8 @@ export interface FetchRequestOptions {
40
40
  headers?: Record<string, string>;
41
41
  /** 单次覆盖超时(ms)。 */
42
42
  timeoutMs?: number;
43
+ /** 响应解析方式:`text` = 原样返回字符串(导出 JSON/YAML 文件体用)。默认 `json`。 */
44
+ responseType?: 'json' | 'text';
43
45
  signal?: AbortSignal;
44
46
  }
45
47
 
@@ -260,8 +262,12 @@ export function createFetchClient(options: FetchClientOptions): FetchClient {
260
262
  }
261
263
 
262
264
  const raw = await safeText(response);
265
+ const isText = init.responseType === 'text';
263
266
  let parsed: unknown = null;
264
- if (raw !== '') {
267
+ if (isText) {
268
+ // 文本模式:不解析 JSON(导出接口返回文件体);错误仍按 text 承载
269
+ parsed = raw;
270
+ } else if (raw !== '') {
265
271
  try {
266
272
  parsed = JSON.parse(raw);
267
273
  } catch {
@@ -277,7 +283,7 @@ export function createFetchClient(options: FetchClientOptions): FetchClient {
277
283
  }
278
284
 
279
285
  let result: unknown = parsed;
280
- if (unwrap && parsed && typeof parsed === 'object') {
286
+ if (unwrap && !isText && parsed && typeof parsed === 'object') {
281
287
  const envelope = parsed as { code?: unknown; data?: unknown; items?: unknown; message?: string };
282
288
  // 业务码:number 0 / 字符串 '0' 视为成功;其余非空值为错误(部分服务把 code 序列化成字符串)
283
289
  const code = envelope.code;
@@ -293,7 +299,7 @@ export function createFetchClient(options: FetchClientOptions): FetchClient {
293
299
  // 列表信封(`{items,total,pagination}`):保持原形,由调用方取 items
294
300
  }
295
301
 
296
- return (caseConversion === 'camel' ? camelizeKeys<T>(result) : result) as T;
302
+ return (caseConversion === 'camel' && !isText ? camelizeKeys<T>(result) : result) as T;
297
303
  }
298
304
 
299
305
  const request = <T,>(path: string, init: FetchRequestOptions = {}): Promise<T> =>
@@ -33,6 +33,7 @@ export const ROLE_SECURITY_FULL = ['super_admin', 'security_admin'] as const;
33
33
  * Portal Guard 配置。
34
34
  * 如需新增 Guard,在此添加 role 集即可。
35
35
  */
36
+ /** @deprecated 与命名 Guard 同属死面(17 仓 0 消费);角色集请就近声明或走 RBAC。下个 minor 删除(ADR §9-3)。 */
36
37
  export const ADMIN_GUARDS = {
37
38
  admin: { roles: ROLE_SUPER_ADMIN },
38
39
  userMgmt: { roles: ROLE_USER_MGMT },
@@ -41,10 +42,12 @@ export const ADMIN_GUARDS = {
41
42
  securityAdmin: { roles: ROLE_SECURITY_FULL }, // admin-console 安全配置管理
42
43
  } as const;
43
44
 
45
+ /** @deprecated 与命名 Guard 同属死面(17 仓 0 消费);角色集请就近声明或走 RBAC。下个 minor 删除(ADR §9-3)。 */
44
46
  export const PLATFORM_GUARDS = {
45
47
  superAdmin: { roles: ROLE_SUPER_ADMIN },
46
48
  } as const;
47
49
 
50
+ /** @deprecated 与命名 Guard 同属死面(17 仓 0 消费);角色集请就近声明或走 RBAC。下个 minor 删除(ADR §9-3)。 */
48
51
  export const SECURITY_GUARDS = {
49
52
  security: { roles: ROLE_SECURITY_ENTRY }, // 基础准入(不含 admin)
50
53
  auditRead: { roles: ROLE_AUDIT_READ }, // 审计证据页(auditor 只读)
@@ -55,6 +58,7 @@ export const SECURITY_GUARDS = {
55
58
  // ============ Portal Config ============
56
59
 
57
60
  /** 所有 Portal 的认证配置映射 */
61
+ /** @deprecated 与命名 Guard 同属死面(17 仓 0 消费);角色集请就近声明或走 RBAC。下个 minor 删除(ADR §9-3)。 */
58
62
  export const PORTAL_AUTH_CONFIG = {
59
63
  'admin-console': { guards: ADMIN_GUARDS },
60
64
  'platform-console': { guards: PLATFORM_GUARDS },
@@ -12,6 +12,9 @@
12
12
  * <AdminGuard allowedRoles={['user_mgmt']}><UsersPage /></AdminGuard> // 覆盖默认角色
13
13
  *
14
14
  * @see portal-config.ts
15
+ *
16
+ * @deprecated 整个模块已无消费方(17 仓实测 0 处)。角色准入请直接用 `<RequireAuth allowedRoles>`。
17
+ * 下个 minor 删除;见 docs/CONSOLE-KIT-DECISION.md §9-3。
15
18
  */
16
19
 
17
20
  'use client';
@@ -32,6 +35,7 @@ interface PortalGuardProps {
32
35
  /**
33
36
  * Admin Console Guard — 默认 roles: ['super_admin', 'admin']
34
37
  */
38
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
35
39
  export function AdminGuard({ children, allowedRoles, ...rest }: PortalGuardProps) {
36
40
  return (
37
41
  <RequireAuth allowedRoles={allowedRoles || ADMIN_GUARDS.admin.roles} {...rest}>
@@ -43,6 +47,7 @@ export function AdminGuard({ children, allowedRoles, ...rest }: PortalGuardProps
43
47
  /**
44
48
  * 用户管理 Guard — roles: ['super_admin', 'admin', 'user_manager']
45
49
  */
50
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
46
51
  export function UserMgmtGuard({ children, allowedRoles, ...rest }: PortalGuardProps) {
47
52
  return (
48
53
  <RequireAuth allowedRoles={allowedRoles || ADMIN_GUARDS.userMgmt.roles} {...rest}>
@@ -54,6 +59,7 @@ export function UserMgmtGuard({ children, allowedRoles, ...rest }: PortalGuardPr
54
59
  /**
55
60
  * 安全只读 Guard — roles: ['super_admin', 'admin', 'security_admin']
56
61
  */
62
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
57
63
  export function SecurityGuard({ children, allowedRoles, ...rest }: PortalGuardProps) {
58
64
  return (
59
65
  <RequireAuth allowedRoles={allowedRoles || SECURITY_GUARDS.security.roles} {...rest}>
@@ -65,6 +71,7 @@ export function SecurityGuard({ children, allowedRoles, ...rest }: PortalGuardPr
65
71
  /**
66
72
  * Platform Console Guard — roles: ['super_admin', 'admin']
67
73
  */
74
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
68
75
  export function PlatformGuard({ children, allowedRoles, ...rest }: PortalGuardProps) {
69
76
  return (
70
77
  <RequireAuth allowedRoles={allowedRoles || PLATFORM_GUARDS.superAdmin.roles} {...rest}>
@@ -77,6 +84,7 @@ export function PlatformGuard({ children, allowedRoles, ...rest }: PortalGuardPr
77
84
  * Security Admin Guard — roles: ['super_admin', 'security_admin']
78
85
  * 用于 security-dashboard 中仅 security_admin 可访问的平台级页面
79
86
  */
87
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
80
88
  export function SecurityAdminGuard({ children, allowedRoles, ...rest }: PortalGuardProps) {
81
89
  return (
82
90
  <RequireAuth allowedRoles={allowedRoles || SECURITY_GUARDS.securityAdmin.roles} {...rest}>
@@ -89,6 +97,7 @@ export function SecurityAdminGuard({ children, allowedRoles, ...rest }: PortalGu
89
97
  * Auditor Guard — roles: ['auditor']
90
98
  * 仅 auditor 可访问的纯审计页面(只读)
91
99
  */
100
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
92
101
  export function AuditorGuard({ children, allowedRoles, ...rest }: PortalGuardProps) {
93
102
  return (
94
103
  <RequireAuth allowedRoles={allowedRoles || SECURITY_GUARDS.auditor.roles} {...rest}>
@@ -100,6 +109,7 @@ export function AuditorGuard({ children, allowedRoles, ...rest }: PortalGuardPro
100
109
  /**
101
110
  * Token-only Guard — 仅需登录,无角色限制
102
111
  */
112
+ /** @deprecated 全站 0 消费(17 仓实测);用 `<RequireAuth allowedRoles={...}>` 代替,下个 minor 删除(ADR §9-3)。 */
103
113
  export function AuthGuard({ children, ...rest }: PortalGuardProps) {
104
114
  return <RequireAuth {...rest}>{children}</RequireAuth>;
105
115
  }
@@ -275,6 +275,80 @@ describe('usePortalCatalog', () => {
275
275
  expect(result.current.portals[0]!.code).toBe('user');
276
276
  });
277
277
 
278
+ // 数据驱动可见性:服务端目录带 config.portal.audience 时**优先于**注册表
279
+ // (ADR §9-1:后端把受众写进目录后,加/调门户不再需要前端发版)。
280
+ it('目录自带 audience=admin → member 看不见(即使注册表里该 code 是 public)', async () => {
281
+ getMock.mockResolvedValue({
282
+ data: {
283
+ items: [
284
+ { code: 'user', name: '用户门户', order: 1, config: { portal: { audience: 'admin' } } },
285
+ ],
286
+ },
287
+ });
288
+ const { result } = renderHook(() => usePortalCatalog({ tenantId: 't1', role: 'member' }), {
289
+ wrapper: makeWrapper(),
290
+ });
291
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
292
+ expect(result.current.portals).toEqual([]);
293
+ });
294
+
295
+ it('目录自带 audience=public → member 也看得见(覆盖注册表的 admin 判定)', async () => {
296
+ getMock.mockResolvedValue({
297
+ data: {
298
+ items: [
299
+ { code: 'config', name: '配置中心', order: 1, config: { portal: { audience: 'public' } } },
300
+ ],
301
+ },
302
+ });
303
+ const { result } = renderHook(() => usePortalCatalog({ tenantId: 't1', role: 'member' }), {
304
+ wrapper: makeWrapper(),
305
+ });
306
+ await waitFor(() => expect(result.current.portals).toHaveLength(1));
307
+ expect(result.current.portals[0]!.code).toBe('config');
308
+ });
309
+
310
+ it('目录自带 audience=platform → 非平台租户成员看不见', async () => {
311
+ getMock.mockResolvedValue({
312
+ data: {
313
+ items: [
314
+ { code: 'platform', name: '平台控制台', order: 1, config: { portal: { audience: 'platform' } } },
315
+ ],
316
+ },
317
+ });
318
+ const { result } = renderHook(() => usePortalCatalog({ tenantId: 't1', role: 'super_admin' }), {
319
+ wrapper: makeWrapper(),
320
+ });
321
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
322
+ expect(result.current.portals).toEqual([]);
323
+ });
324
+
325
+ it('目录 audience 是脏值(未知字符串)→ 回落注册表判定', async () => {
326
+ getMock.mockResolvedValue({
327
+ data: {
328
+ items: [
329
+ { code: 'config', name: '配置中心', order: 1, config: { portal: { audience: 'root' } } },
330
+ ],
331
+ },
332
+ });
333
+ const { result } = renderHook(() => usePortalCatalog({ tenantId: 't1', role: 'member' }), {
334
+ wrapper: makeWrapper(),
335
+ });
336
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
337
+ // 注册表里 config 属管理面 ⇒ member 不可见
338
+ expect(result.current.portals).toEqual([]);
339
+ });
340
+
341
+ it('目录无 config → 完全按注册表(向后兼容旧后端)', async () => {
342
+ getMock.mockResolvedValue({
343
+ data: { items: [{ code: 'config', name: '配置中心', order: 1 }] },
344
+ });
345
+ const { result } = renderHook(() => usePortalCatalog({ tenantId: 't1', role: 'member' }), {
346
+ wrapper: makeWrapper(),
347
+ });
348
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
349
+ expect(result.current.portals).toEqual([]);
350
+ });
351
+
278
352
  it('role 缺省回退 store 当前角色(useCurrentRole),平台租户成员判定不依赖当前租户', async () => {
279
353
  useAuthStore.setState({
280
354
  tenants: [
@@ -8,6 +8,7 @@ import { getPortalUrl } from '../config';
8
8
  import {
9
9
  ADMIN_PLANE_ROLES as ADMIN_PLANE_ROLES_REGISTRY,
10
10
  getSwitcherExcludedCodes,
11
+ isPortalVisibleByAudience,
11
12
  isPortalVisibleForAudience,
12
13
  } from '../portal/registry';
13
14
  import { useCurrentRole } from './useCurrentRole';
@@ -89,12 +90,25 @@ interface RawPortalApplication {
89
90
  name: string;
90
91
  description?: string;
91
92
  order?: number;
92
- /** allowedRoles 为 apiClient camelCase 归一后的键(snake 形态兼容后端透出前的原始键) */
93
+ /**
94
+ * 服务端目录里的门户元数据(tenant-service `ApplicationResponse.config.portal`,2026-11 起透出)。
95
+ * `audience` 存在时**优先于**前端注册表;缺失回落注册表(新旧后端都能跑)。
96
+ * allowedRoles 为 apiClient camelCase 归一后的键(snake 形态兼容原始键)。
97
+ */
93
98
  config?: {
94
- portal?: { allowedRoles?: readonly string[]; allowed_roles?: readonly string[] };
99
+ portal?: {
100
+ audience?: string;
101
+ allowedRoles?: readonly string[];
102
+ allowed_roles?: readonly string[];
103
+ };
95
104
  } | null;
96
105
  }
97
106
 
107
+ /** 只认白名单内的受众值;脏值/缺失 ⇒ undefined(回落注册表)。 */
108
+ function toKnownAudience(raw: string | undefined | null): 'public' | 'admin' | 'platform' | undefined {
109
+ return raw === 'public' || raw === 'admin' || raw === 'platform' ? raw : undefined;
110
+ }
111
+
98
112
  function toEntry(app: RawPortalApplication, slug?: string): PortalCatalogEntry {
99
113
  return {
100
114
  code: app.code,
@@ -164,13 +178,18 @@ export function usePortalCatalog(options: UsePortalCatalogOptions = {}): UsePort
164
178
  return (query.data ?? []).filter((app) => !excluded.has(app.code));
165
179
  }, [query.data, exclude]);
166
180
 
167
- // 可见性(入口门禁镜像)+ allowed_roles 叠加
168
- // (allowed_roles 数据通路后端尚未透出——tenant-service 列表 DTO 无 config 字段;
169
- // 存在时叠加生效,见 usePortalCatalog 审计记录)
181
+ // 可见性 = 受众判定 + allowed_roles 叠加。
182
+ // 受众来源**优先数据**(服务端 `config.portal.audience`),缺失才回落注册表 ——
183
+ // 这样后端把受众写进目录后,加门户/调可见性不再需要前端发版(ADR §9-1)。
170
184
  const visiblePortals = useMemo(
171
185
  () =>
172
186
  excludedPortals.filter((app) => {
173
- if (!isPortalVisible(app.code, { role, isPlatformMember })) return false;
187
+ const ctx = { role, isPlatformMember };
188
+ const dataAudience = toKnownAudience(app.config?.portal?.audience);
189
+ const visible = dataAudience
190
+ ? isPortalVisibleByAudience(dataAudience, ctx)
191
+ : isPortalVisible(app.code, ctx);
192
+ if (!visible) return false;
174
193
  const allowedRoles =
175
194
  app.config?.portal?.allowedRoles ?? app.config?.portal?.allowed_roles;
176
195
  return !allowedRoles || allowedRoles.includes(role ?? '');
@@ -0,0 +1,341 @@
1
+ #!/usr/bin/env node
2
+ // check-portal-literals —— 门户清单回潮门(第 N 道)
3
+ //
4
+ // 背景:门户 code 过去被写了十几次(PORTAL_DEFAULTS / SLUG_PORTALS / 重定向白名单 /
5
+ // isPortalVisible 角色集 / DEFAULT_EXCLUDE / PORTAL_KEY_MAP + 6 个站点各一份 CONSOLE_PORTALS)。
6
+ // 现在唯一真源是 packages/shared/src/portal/registry.ts(`PORTALS`)。
7
+ //
8
+ // 本闸门扫 packages/*/src(跳过测试与 registry.ts),禁止再出现「≥2 个门户 code」的字面量数组 / Set:
9
+ //
10
+ // const CONSOLE_PORTALS = new Set(['config', 'secret', 'admin', ...]); ❌
11
+ // const DEFAULT_EXCLUDE = ['auth', 'landing']; ❌
12
+ //
13
+ // 允许:
14
+ // • registry.ts 自身(真源)
15
+ // • 单门户字面量(getPortalUrl('admin') / code === 'config' 之类)
16
+ // • 测试文件(oracle 断言需要原文拷贝)
17
+ //
18
+ // 已知边界(有意接受,别当它是形式化证明):
19
+ // • 只认「数组 / Set 字面量」;字符串拼接、模板串、`push('admin')`、对象键清单不在扫描面
20
+ // • 只扫本仓 `packages/*/src`(站点仓在各自主仓,由各自的 CI 跑同名脚本)
21
+ // 因此它是「回潮早报警」,不是「不可能绕过」;绕过本身要写得刻意,评审时肉眼可见。
22
+ //
23
+ // 用法(**单文件自足**,可直接复制进站点仓,不依赖 scripts/lib/*):
24
+ // node scripts/check-portal-literals.mjs # 扫本仓(自动识别 packages/ / apps/ / src/)
25
+ // node scripts/check-portal-literals.mjs --root <dir> # 扫指定目录(站点仓:--root .)
26
+ // node scripts/check-portal-literals.mjs --json
27
+ //
28
+ // 门户 code 的取法(按序回退):
29
+ // 1. --codes <file> 指定
30
+ // 2. <root>/packages/shared/src/portal/registry.ts(ui 仓)
31
+ // 3. <root>/node_modules/@autional/shared/src/portal/registry.ts(站点仓,装了 shared 之后)
32
+ // 4. <root>/node_modules/@autional/shared/dist/portal/registry.js(将来若出 dist)
33
+
34
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
35
+ import { join, relative, resolve } from 'node:path';
36
+
37
+ /**
38
+ * 默认扫描根 = 当前工作目录(作为包内 `bin` 分发时,脚本位置在 node_modules 里,不能用它推仓库根)。
39
+ * ui 仓内部调用由 `scripts/check-portal-literals.mjs` 包装,cwd 即仓根。
40
+ */
41
+ const SCRIPT_ROOT = process.cwd();
42
+
43
+ function argValue(flag) {
44
+ const i = process.argv.indexOf(flag);
45
+ return i >= 0 ? process.argv[i + 1] : undefined;
46
+ }
47
+
48
+ const ROOT = resolve(argValue('--root') ?? SCRIPT_ROOT);
49
+ /** 待扫目录:显式 --scan(逗号分隔)> 仓库里存在的 packages/apps/src。 */
50
+ const SCAN_DIRS = (() => {
51
+ const explicit = argValue('--scan');
52
+ if (explicit) return explicit.split(',').map((s) => s.trim()).filter(Boolean).map((d) => resolve(ROOT, d));
53
+ const candidates = ['packages', 'apps', 'src'].filter((d) => existsSync(join(ROOT, d)));
54
+ return candidates.length > 0 ? candidates.map((d) => join(ROOT, d)) : [ROOT];
55
+ })();
56
+ const SKIP_DIR = new Set(['node_modules', 'dist', '__tests__', 'test', 'generated']);
57
+ const SKIP_FILE = /(\.test\.|\.spec\.|\.d\.ts$)/;
58
+
59
+ /**
60
+ * shared 的注册表可能落在:ui 仓自身源码 / 站点仓根 node_modules(pnpm 提升)/
61
+ * 站点仓 apps/<app>/node_modules(pnpm workspace 的常规位置)/ 将来若出 dist。
62
+ */
63
+ function installedCandidates() {
64
+ const out = [];
65
+ const rel = join('@autional', 'shared');
66
+ const variants = [join('src', 'portal', 'registry.ts'), join('dist', 'portal', 'registry.js')];
67
+ const bundlers = [
68
+ join(ROOT, 'node_modules'),
69
+ ...(existsSync(join(ROOT, 'apps')) ? readdirSync(join(ROOT, 'apps')).map((d) => join(ROOT, 'apps', d, 'node_modules')) : []),
70
+ ...(existsSync(join(ROOT, 'packages')) ? readdirSync(join(ROOT, 'packages')).map((d) => join(ROOT, 'packages', d, 'node_modules')) : []),
71
+ ];
72
+ for (const base of bundlers) for (const v of variants) out.push(join(base, rel, v));
73
+ return out;
74
+ }
75
+
76
+ const REGISTRY_CANDIDATES = [
77
+ argValue('--codes'),
78
+ join(ROOT, 'packages', 'shared', 'src', 'portal', 'registry.ts'),
79
+ ...installedCandidates(),
80
+ ].filter(Boolean);
81
+
82
+ /** 从 registry 提取门户 code(避免本脚本自己维护第二份清单)。 */
83
+ function readPortalCodes() {
84
+ const found = REGISTRY_CANDIDATES.find((p) => existsSync(p));
85
+ if (!found) return { codes: [], registry: null };
86
+ const src = readFileSync(found, 'utf8');
87
+ const codes = [...src.matchAll(/code:\s*['"]([a-z0-9-]+)['"]/g)].map((m) => m[1]);
88
+ return { codes: [...new Set(codes)], registry: found };
89
+ }
90
+
91
+ function walk(dir, out = []) {
92
+ for (const entry of readdirSync(dir)) {
93
+ const full = join(dir, entry);
94
+ const stat = statSync(full);
95
+ if (stat.isDirectory()) {
96
+ if (SKIP_DIR.has(entry)) continue;
97
+ walk(full, out);
98
+ } else if (/\.(ts|tsx)$/.test(entry) && !SKIP_FILE.test(entry)) {
99
+ out.push(full);
100
+ }
101
+ }
102
+ return out;
103
+ }
104
+
105
+ /**
106
+ * 只在「数组字面量 / Set 字面量」上判定(`['a','b']` / `new Set([...])`)。
107
+ * 单门户字面量(`code === 'admin'`、`getPortalUrl('admin')`、类型联合)不算清单,不报。
108
+ */
109
+ /**
110
+ * 去注释(保留字符串原样、保留换行以维持行号)。
111
+ *
112
+ * 不能用正则一把梭:`'https://…'` 里的 `//` 会把整行截断成"已剥离",
113
+ * `'src/*.ts'` 里的 `/*` 会开一个幽灵块注释吞掉后面的真代码 —— 两者都会造成**漏报**。
114
+ * 所以走一次字符级状态机(code / line-comment / block-comment / string / template)。
115
+ * 已知边界:正则字面量(如 `/\/\//`)按代码处理,若其中含 `//` 仍可能误判(本仓无此写法)。
116
+ */
117
+ function stripComments(src) {
118
+ let out = '';
119
+ let state = 'code';
120
+ for (let i = 0; i < src.length; i += 1) {
121
+ const ch = src[i];
122
+ const next = src[i + 1];
123
+ if (state === 'code') {
124
+ if (ch === '/' && next === '/') {
125
+ state = 'line';
126
+ i += 1;
127
+ continue;
128
+ }
129
+ if (ch === '/' && next === '*') {
130
+ state = 'block';
131
+ i += 1;
132
+ continue;
133
+ }
134
+ if (ch === "'" || ch === '"' || ch === '`') {
135
+ state = ch;
136
+ out += ch;
137
+ continue;
138
+ }
139
+ out += ch;
140
+ continue;
141
+ }
142
+ if (state === 'line') {
143
+ if (ch === '\n') {
144
+ state = 'code';
145
+ out += '\n';
146
+ }
147
+ continue;
148
+ }
149
+ if (state === 'block') {
150
+ if (ch === '*' && next === '/') {
151
+ state = 'code';
152
+ i += 1;
153
+ continue;
154
+ }
155
+ if (ch === '\n') out += '\n';
156
+ continue;
157
+ }
158
+ // 字符串 / 模板串内部:原样保留(含转义)
159
+ if (ch === '\\') {
160
+ out += ch + (next ?? '');
161
+ i += 1;
162
+ continue;
163
+ }
164
+ // 单/双引号字符串不跨行:遇到换行仍未闭合 ⇒ 说明前面把 JSX 撇号 / 正则引号当成了字符串起点。
165
+ // 回到 code 态(fail-closed:宁可多剥注释,也不要因状态带偏而漏报或误报)。
166
+ if (ch === '\n' && state !== '`') {
167
+ state = 'code';
168
+ out += ch;
169
+ continue;
170
+ }
171
+ if (ch === state) state = 'code';
172
+ out += ch;
173
+ }
174
+ return out;
175
+ }
176
+
177
+ function findViolations(file, codes, exemptions) {
178
+ const rawSrc = readFileSync(file, 'utf8');
179
+ const src = stripComments(rawSrc); // 扫描用:注释已剥离
180
+ const violations = [];
181
+ const blocks = [
182
+ ...src.matchAll(/new Set\(\s*\[[\s\S]{0,4000}?\]\s*\)/g),
183
+ ...src.matchAll(/\[[^[\]]{0,4000}\]/g),
184
+ ];
185
+ for (const block of blocks) {
186
+ // 取块内所有字符串字面量:**全部**都是门户 code 才算「门户清单」。
187
+ // 只要求「含 ≥2 个 code」会在站点仓大量误报('status'/'secret'/'user'/'admin' 也是业务名词:
188
+ // 服务名清单、用户菜单项都会命中)。全量匹配才能区分「门户清单」与「恰好撞词的业务枚举」。
189
+ const strings = [...block[0].matchAll(/['"]([^'"]*)['"]/g)].map((m) => m[1]);
190
+ const hits = strings.filter((s) => codes.includes(s));
191
+ if (hits.length < 2) continue;
192
+ if (strings.some((s) => !codes.includes(s))) continue;
193
+ const upTo = (block.index ?? 0) + block[0].length;
194
+ const line = src.slice(0, upTo).split(/\r?\n/).length;
195
+ // 显式豁免:块起始行前 4 行内写 `portal-literals-ok: <理由>`。
196
+ // 只给「不是可见性策略、但确实要写死几条门户」的场景(如目录失败时的静态兜底);
197
+ // 与 eslint-disable 同性质:理由在代码里、评审可见,豁免数在输出里单独报。
198
+ const allLines = rawSrc.split(/\r?\n/); // 豁免标记在注释里 ⇒ 必须查原文
199
+ const startLine = src.slice(0, block.index ?? 0).split(/\r?\n/).length;
200
+ const exempt = allLines
201
+ .slice(Math.max(0, startLine - 4), startLine)
202
+ .some((l) => /portal-literals-ok/.test(l));
203
+ if (exempt) {
204
+ exemptions.push({ line, codes: hits });
205
+ continue;
206
+ }
207
+ violations.push({
208
+ line,
209
+ codes: hits,
210
+ text: block[0].replace(/\s+/g, ' ').slice(0, 120),
211
+ });
212
+ }
213
+ // Set 字面量会同时命中内层数组 ⇒ 按 (行, code 集) 去重
214
+ const seen = new Set();
215
+ return violations.filter((v) => {
216
+ const key = `${v.line}:${[...v.codes].sort().join(',')}`;
217
+ if (seen.has(key)) return false;
218
+ seen.add(key);
219
+ return true;
220
+ });
221
+ }
222
+
223
+ const { codes, registry } = readPortalCodes();
224
+ if (codes.length === 0) {
225
+ console.error(
226
+ 'check-portal-literals:取不到门户 code 清单。已找过:\n ' +
227
+ REGISTRY_CANDIDATES.join('\n ') +
228
+ '\n(站点仓请先安装 @autional/shared,或用 --codes 指向 registry 文件)',
229
+ );
230
+ process.exit(1);
231
+ }
232
+
233
+ const registryAbs = registry ? resolve(registry) : null;
234
+ const files = SCAN_DIRS.flatMap((dir) => walk(dir)).filter((f) => resolve(f) !== registryAbs);
235
+ const results = [];
236
+ const exemptions = [];
237
+ for (const file of files) {
238
+ const violations = findViolations(file, codes, exemptions);
239
+ if (violations.length > 0) results.push({ file: relative(ROOT, file), violations });
240
+ }
241
+
242
+ /**
243
+ * 站点面:ui 仓的 verify 在**舰队机器**上要连带扫 6 个站点仓,
244
+ * 否则「各站自己扫」又会变成 6 份实现(正是本门要消灭的东西)。
245
+ * 站点清单优先取 AUTIONAL_SITES_DIR,回退 <ui>/../sites;不存在就跳过(与其它闸门同约定:
246
+ * 跳过必须在输出里看得见)。
247
+ */
248
+ function scanSites() {
249
+ const sitesDir =
250
+ process.env.AUTIONAL_SITES_DIR || resolve(ROOT, '..', 'sites');
251
+ if (!existsSync(sitesDir)) return null;
252
+ const out = [];
253
+ for (const entry of readdirSync(sitesDir, { withFileTypes: true })) {
254
+ const siteRoot = join(sitesDir, entry.name);
255
+ // 舰队树里各站常是 junction / symlink ⇒ Dirent.isDirectory() 为 false,必须再 stat 一次
256
+ const isDir = entry.isDirectory() || (entry.isSymbolicLink() && statSync(siteRoot).isDirectory());
257
+ if (!isDir) continue;
258
+ if (!existsSync(join(siteRoot, 'apps')) && !existsSync(join(siteRoot, 'src'))) continue;
259
+ const siteCodes = readPortalCodesFor(siteRoot) ?? codes;
260
+ const dirs = ['packages', 'apps', 'src']
261
+ .filter((d) => existsSync(join(siteRoot, d)))
262
+ .map((d) => join(siteRoot, d));
263
+ const siteFiles = dirs.flatMap((d) => walk(d));
264
+ const siteExemptions = [];
265
+ const siteViolations = [];
266
+ for (const file of siteFiles) {
267
+ const v = findViolations(file, siteCodes, siteExemptions);
268
+ if (v.length) siteViolations.push({ file: relative(siteRoot, file), violations: v });
269
+ }
270
+ out.push({
271
+ site: entry.name,
272
+ files: siteFiles.length,
273
+ exemptions: siteExemptions.length,
274
+ results: siteViolations,
275
+ });
276
+ }
277
+ return out;
278
+ }
279
+
280
+ /** 站点自己的 shared 安装(pnpm workspace 常在 apps/<app>/node_modules)。 */
281
+ function readPortalCodesFor(siteRoot) {
282
+ const candidates = [
283
+ join(siteRoot, 'node_modules', '@autional', 'shared', 'src', 'portal', 'registry.ts'),
284
+ ...(existsSync(join(siteRoot, 'apps'))
285
+ ? readdirSync(join(siteRoot, 'apps')).map((d) =>
286
+ join(siteRoot, 'apps', d, 'node_modules', '@autional', 'shared', 'src', 'portal', 'registry.ts'),
287
+ )
288
+ : []),
289
+ ];
290
+ const found = candidates.find((p) => existsSync(p));
291
+ if (!found) return null;
292
+ const src = readFileSync(found, 'utf8');
293
+ return [...new Set([...src.matchAll(/code:\s*['"]([a-z0-9-]+)['"]/g)].map((m) => m[1]))];
294
+ }
295
+
296
+ const sites = scanSites();
297
+ const siteFailures = (sites ?? []).filter((s) => s.results.length > 0);
298
+
299
+ if (process.argv.includes('--json')) {
300
+ console.log(JSON.stringify({ codes, results, exemptions, sites }, null, 2));
301
+ } else {
302
+ if (results.length === 0) {
303
+ console.log(
304
+ `check-portal-literals:PASS(${files.length} 个文件,门户 code 字面量 0 处` +
305
+ `${exemptions.length ? `;显式豁免 ${exemptions.length} 处` : ''})`,
306
+ );
307
+ } else {
308
+ console.error(`check-portal-literals:FAIL(${results.length} 个文件仍持有门户字面量清单)`);
309
+ if (exemptions.length) console.error(` (另有显式豁免 ${exemptions.length} 处)`);
310
+ for (const { file, violations } of results) {
311
+ for (const v of violations) {
312
+ console.error(` ${file}:${v.line} [${v.codes.join(', ')}] ${v.text}`);
313
+ }
314
+ }
315
+ console.error(' 修法:改用 @autional/shared[/portal] 的派生函数' +
316
+ '(isConsolePortal / getConsolePortalCodes / getSwitcherExcludedCodes / ADMIN_PLANE_ROLES)');
317
+ }
318
+
319
+ if (sites === null) {
320
+ console.log('check-portal-literals:站点面跳过(本机无 sites/;舰队机器上会连带扫 6 站)');
321
+ } else {
322
+ for (const s of sites) {
323
+ const suffix = s.exemptions ? `;显式豁免 ${s.exemptions} 处` : '';
324
+ if (s.results.length === 0) {
325
+ console.log(` [${s.site}] PASS(${s.files} 个文件,0 处${suffix})`);
326
+ continue;
327
+ }
328
+ console.error(` [${s.site}] FAIL(${s.results.length} 个文件)${suffix}`);
329
+ for (const { file, violations } of s.results) {
330
+ for (const v of violations) {
331
+ console.error(` ${file}:${v.line} [${v.codes.join(', ')}] ${v.text}`);
332
+ }
333
+ }
334
+ }
335
+ console.log(
336
+ `check-portal-literals:站点面 ${sites.length} 站,${siteFailures.length ? `${siteFailures.length} 站有清单` : '全部 0 处'}`,
337
+ );
338
+ }
339
+ }
340
+
341
+ process.exit(results.length === 0 && siteFailures.length === 0 ? 0 : 1);
@@ -325,13 +325,25 @@ export function getLegacyEnvKey(code: string): string | undefined {
325
325
  return BY_CODE.get(code)?.legacyEnvKey;
326
326
  }
327
327
 
328
- /** 门户可见性(入口门禁镜像):未登记的门户默认放行(叠加原则,不误伤)。 */
329
- export function isPortalVisibleForAudience(
330
- code: string,
328
+ /**
329
+ * 按**受众**判定可见性(入口门禁镜像)。
330
+ *
331
+ * 同一函数服务两个数据源:注册表的 `audience` 与服务端目录里的 `config.portal.audience`。
332
+ * 未知/缺失受众一律按 `public`(叠加原则,不误伤新门户)。
333
+ */
334
+ export function isPortalVisibleByAudience(
335
+ audience: string | null | undefined,
331
336
  ctx: { role: string | null; isPlatformMember: boolean },
332
337
  ): boolean {
333
- const audience = BY_CODE.get(code)?.audience ?? 'public';
334
338
  if (audience === 'platform') return ctx.isPlatformMember;
335
339
  if (audience === 'admin') return ctx.role !== null && ADMIN_PLANE_ROLES.includes(ctx.role);
336
340
  return true;
337
341
  }
342
+
343
+ /** 未登记的门户默认放行(叠加原则,不误伤)。 */
344
+ export function isPortalVisibleForAudience(
345
+ code: string,
346
+ ctx: { role: string | null; isPlatformMember: boolean },
347
+ ): boolean {
348
+ return isPortalVisibleByAudience(BY_CODE.get(code)?.audience, ctx);
349
+ }