@autional/shared 0.1.0-rc.56 → 0.1.0-rc.58

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.
@@ -3,6 +3,13 @@
3
3
 
4
4
  /* eslint-disable @typescript-eslint/no-explicit-any */
5
5
 
6
+ import {
7
+ PORTALS,
8
+ getLegacyEnvKey,
9
+ getRouterPortalCodes,
10
+ isSlugScopedPortal,
11
+ } from '../portal/registry';
12
+
6
13
  // ─── Runtime Config ───
7
14
  function getRuntimeConfig(): Record<string, string> | undefined {
8
15
  try {
@@ -50,8 +57,8 @@ const getEnv = (key: string, fallback: string): string => {
50
57
  // ─── Base Path ───
51
58
  export const BASE_PATH = getEnv('BASE_PATH', '/');
52
59
 
53
- const APP_PORTAL_SLUGS = ['admin', 'developer', 'security', 'platform', 'status', 'trust'] as const;
54
- void APP_PORTAL_SLUGS;
60
+ // `/<tenant>/<portal>` 路由 basename 解析用的门户表 —— 派生自注册表(勿再写字面量)。
61
+ const APP_PORTAL_SLUGS: readonly string[] = getRouterPortalCodes();
55
62
 
56
63
  export function getRouterBasename(): string {
57
64
  const base = BASE_PATH.replace(/\/$/, '') || '/';
@@ -80,21 +87,13 @@ export interface PortalEntry {
80
87
  base: string;
81
88
  }
82
89
 
83
- const PORTAL_DEFAULTS: Record<string, PortalEntry> = {
84
- auth: { host: 'auth', base: '' },
85
- admin: { host: 'admin', base: '' },
86
- developer: { host: 'developer', base: '' },
87
- user: { host: 'user', base: '' },
88
- security: { host: 'security', base: '' },
89
- status: { host: 'status', base: '' },
90
- landing: { host: '', base: '' },
91
- authenticator: { host: 'authenticator', base: '' },
92
- trust: { host: 'trust', base: '' },
93
- platform: { host: 'platform', base: '' },
94
- brand: { host: 'brand', base: '' },
95
- secret: { host: 'secret', base: '' },
96
- config: { host: 'config', base: '' },
97
- };
90
+ /**
91
+ * 门户 host/base 默认值 —— 派生自注册表(`src/portal/registry.ts`)。
92
+ * 顺序与内容与迁移前字面量逐项等价(oracle 测试锁定),env / 运行时 API 仍可覆盖。
93
+ */
94
+ const PORTAL_DEFAULTS: Record<string, PortalEntry> = Object.fromEntries(
95
+ PORTALS.map((p) => [p.code, { host: p.host, base: p.base }] as const),
96
+ );
98
97
 
99
98
  let portalConfig: Record<string, PortalEntry> | null = null;
100
99
 
@@ -130,19 +129,13 @@ export async function initPortalConfig(
130
129
  portalConfig = PORTAL_DEFAULTS;
131
130
  }
132
131
 
133
- // 旧 env.js 直连 URL 键(VITE_*_URL)→ portalId 映射(向后兼容)
134
- const PORTAL_KEY_MAP: Record<string, string> = {
135
- auth: 'VITE_AUTH_PAGES_URL',
136
- admin: 'VITE_ADMIN_CONSOLE_URL',
137
- developer: 'VITE_DEVELOPER_PORTAL_URL',
138
- user: 'VITE_END_USER_PORTAL_URL',
139
- security: 'VITE_SECURITY_DASHBOARD_URL',
140
- status: 'VITE_STATUS_PAGE_URL',
141
- landing: 'VITE_LANDING_SITE_URL',
142
- authenticator: 'VITE_AUTHENTICATOR_APP_URL',
143
- trust: 'VITE_TRUST_CENTER_URL',
144
- platform: 'VITE_PLATFORM_CONSOLE_URL',
145
- };
132
+ // 旧 env.js 直连 URL 键(VITE_*_URL)→ portalId 映射(向后兼容)—— 派生自注册表 legacyEnvKey。
133
+ const PORTAL_KEY_MAP: Record<string, string> = Object.fromEntries(
134
+ PORTALS.flatMap((p) => {
135
+ const key = getLegacyEnvKey(p.code);
136
+ return key ? [[p.code, key] as const] : [];
137
+ }),
138
+ );
146
139
 
147
140
  /**
148
141
  * 读取构建期注入的 VITE_PORTAL_CONFIG(env.js → window.__APP_CONFIG__)。
@@ -191,15 +184,10 @@ function resolvePortalUrl(entry: PortalEntry, hostname: string, slug?: string):
191
184
  // (legacy seed 049 requires_slug:true),且 OAuth client 按 slug 解析 —— 不拼租户段时
192
185
  // 控制台拿不到 client,裸根入口退化为登录死循环。其余门户(status/trust/developer/
193
186
  // brand/landing)是域根应用,拼租户段会命中不存在的路由 ⇒ 空白/404。
194
- // 新增租户段门户时须同步在此登记。
195
- const SLUG_PORTALS: ReadonlySet<string> = new Set([
196
- 'auth',
197
- 'admin',
198
- 'user',
199
- 'security',
200
- 'authenticator',
201
- 'platform',
202
- ]);
187
+ // 登记处 = 注册表 `slugScoped` 字段(本集合由它派生,勿再写字面量)。
188
+ const SLUG_PORTALS: ReadonlySet<string> = new Set(
189
+ PORTALS.filter((p) => isSlugScopedPortal(p.code)).map((p) => p.code),
190
+ );
203
191
 
204
192
  export function getPortalUrl(portalId: string, slug?: string): string {
205
193
  if (typeof window === 'undefined') return '';
@@ -251,7 +239,8 @@ function getPortalEntries(): Record<string, PortalEntry> {
251
239
  }
252
240
 
253
241
  export function getAppPortalSlugs(): string[] {
254
- return ['admin', 'developer', 'security', 'platform', 'status', 'trust'];
242
+ // 派生自注册表 routerSlug(勿再写字面量);顺序与迁移前一致。
243
+ return [...APP_PORTAL_SLUGS];
255
244
  }
256
245
 
257
246
  export function getRootDomain(hostname: string, _rootParts?: number): string {
@@ -306,24 +295,14 @@ export function getRootDomain(hostname: string, _rootParts?: number): string {
306
295
  return hostname;
307
296
  }
308
297
 
309
- /** Resolve all portal URLs for redirect origin validation. */
298
+ /**
299
+ * Resolve all portal URLs for redirect origin validation.
300
+ *
301
+ * 白名单 = 注册表全部门户(新增门户自动获得 redirect 合法性)。
302
+ * 迁移前是手写 13 项;现为派生,且补齐了此前漏登记的 4 个内容站。
303
+ */
310
304
  function getAllowedRedirectOrigins(): string[] {
311
- const portalIds = [
312
- 'auth',
313
- 'admin',
314
- 'developer',
315
- 'user',
316
- 'security',
317
- 'status',
318
- 'landing',
319
- 'authenticator',
320
- 'trust',
321
- 'platform',
322
- 'brand',
323
- 'secret',
324
- 'config',
325
- ];
326
- return portalIds
305
+ return PORTALS.map((p) => p.code)
327
306
  .map((id) => {
328
307
  try {
329
308
  return getPortalUrl(id);
@@ -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: [
@@ -5,34 +5,36 @@ import { useQuery } from '@tanstack/react-query';
5
5
  import { getAccessToken, useAuthStore } from '../auth/store';
6
6
  import { apiClient } from '../api/client';
7
7
  import { getPortalUrl } from '../config';
8
+ import {
9
+ ADMIN_PLANE_ROLES as ADMIN_PLANE_ROLES_REGISTRY,
10
+ getSwitcherExcludedCodes,
11
+ isPortalVisibleByAudience,
12
+ isPortalVisibleForAudience,
13
+ } from '../portal/registry';
8
14
  import { useCurrentRole } from './useCurrentRole';
9
15
 
10
16
  /** 平台租户 well-known ULID(service-core base/constant TenantPlatformID,全环境同值) */
11
17
  export const PLATFORM_TENANT_ID = '01KSQCBNVMS6SX64PJS937CE33';
12
18
 
13
- /** 管理面平面角色集(admin/security 门户)——与登录入口门禁同集:member/guest 登录被拒 40000503 */
14
- export const ADMIN_PLANE_ROLES: readonly string[] = [
15
- 'super_admin',
16
- 'admin',
17
- 'security_admin',
18
- 'user_manager',
19
- ];
19
+ /**
20
+ * 管理面平面角色集(admin/security/config/secret 门户)——与登录入口门禁同集:
21
+ * member/guest 登录被拒 40000503。定义在注册表(单一真源),此处保留导出以兼容既有 import。
22
+ */
23
+ export const ADMIN_PLANE_ROLES: readonly string[] = ADMIN_PLANE_ROLES_REGISTRY;
20
24
 
21
25
  /**
22
26
  * 门户可见性 = 入口门禁的镜像(谁能登录谁才看见):
23
- * - platform:仅平台租户成员
24
- * - admin / security / secret / config:仅管理面角色
25
- * - 其余 code:不限制(叠加原则,未知门户不误伤)
27
+ * - `audience: 'platform'`:仅平台租户成员
28
+ * - `audience: 'admin'`:仅管理面角色(admin / security / config / secret …)
29
+ * - 其余(含未登记 code):不限制(叠加原则,未知门户不误伤)
30
+ *
31
+ * 判定数据源 = 注册表 `audience`;本函数不再持有门户 code 字面量。
26
32
  */
27
33
  export function isPortalVisible(
28
34
  code: string,
29
35
  ctx: { role: string | null; isPlatformMember: boolean },
30
36
  ): boolean {
31
- if (code === 'platform') return ctx.isPlatformMember;
32
- if (code === 'admin' || code === 'security' || code === 'secret' || code === 'config') {
33
- return ctx.role !== null && ADMIN_PLANE_ROLES.includes(ctx.role);
34
- }
35
- return true;
37
+ return isPortalVisibleForAudience(code, ctx);
36
38
  }
37
39
 
38
40
  /** 平台门户目录项(映射自 tenant-service 应用列表响应,is_platform=true) */
@@ -77,9 +79,10 @@ export interface UsePortalCatalogResult {
77
79
  refetch: () => void;
78
80
  }
79
81
 
80
- // 「切换门户」清单默认排除:auth/landing 非切换目标;authenticator 为移动 App 形态
81
- // (TOTP/push),与其他门户功能形态不同,不列入桌面门户清单
82
- const DEFAULT_EXCLUDE: readonly string[] = ['auth', 'landing', 'authenticator'];
82
+ // 「切换门户」清单默认排除 = 注册表 `inSwitcher === false` 的门户
83
+ // (auth/landing 非切换目标;authenticator 为移动 App 形态 TOTP/push,不列入桌面清单)。
84
+ // 派生结果与迁移前字面量逐项等价(oracle 测试锁定)。
85
+ const DEFAULT_EXCLUDE: readonly string[] = getSwitcherExcludedCodes();
83
86
  const PORTAL_CATALOG_STALE_TIME = 60_000;
84
87
 
85
88
  interface RawPortalApplication {
@@ -87,12 +90,25 @@ interface RawPortalApplication {
87
90
  name: string;
88
91
  description?: string;
89
92
  order?: number;
90
- /** allowedRoles 为 apiClient camelCase 归一后的键(snake 形态兼容后端透出前的原始键) */
93
+ /**
94
+ * 服务端目录里的门户元数据(tenant-service `ApplicationResponse.config.portal`,2026-11 起透出)。
95
+ * `audience` 存在时**优先于**前端注册表;缺失回落注册表(新旧后端都能跑)。
96
+ * allowedRoles 为 apiClient camelCase 归一后的键(snake 形态兼容原始键)。
97
+ */
91
98
  config?: {
92
- portal?: { allowedRoles?: readonly string[]; allowed_roles?: readonly string[] };
99
+ portal?: {
100
+ audience?: string;
101
+ allowedRoles?: readonly string[];
102
+ allowed_roles?: readonly string[];
103
+ };
93
104
  } | null;
94
105
  }
95
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
+
96
112
  function toEntry(app: RawPortalApplication, slug?: string): PortalCatalogEntry {
97
113
  return {
98
114
  code: app.code,
@@ -162,13 +178,18 @@ export function usePortalCatalog(options: UsePortalCatalogOptions = {}): UsePort
162
178
  return (query.data ?? []).filter((app) => !excluded.has(app.code));
163
179
  }, [query.data, exclude]);
164
180
 
165
- // 可见性(入口门禁镜像)+ allowed_roles 叠加
166
- // (allowed_roles 数据通路后端尚未透出——tenant-service 列表 DTO 无 config 字段;
167
- // 存在时叠加生效,见 usePortalCatalog 审计记录)
181
+ // 可见性 = 受众判定 + allowed_roles 叠加。
182
+ // 受众来源**优先数据**(服务端 `config.portal.audience`),缺失才回落注册表 ——
183
+ // 这样后端把受众写进目录后,加门户/调可见性不再需要前端发版(ADR §9-1)。
168
184
  const visiblePortals = useMemo(
169
185
  () =>
170
186
  excludedPortals.filter((app) => {
171
- 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;
172
193
  const allowedRoles =
173
194
  app.config?.portal?.allowedRoles ?? app.config?.portal?.allowed_roles;
174
195
  return !allowedRoles || allowedRoles.includes(role ?? '');
package/src/index.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  // API
2
2
  export { apiClient, createApiClient } from './api/client';
3
+ // fetch 版传输层(与 axios client 并存;默认透传,供零依赖控制台用)
4
+ export { createFetchClient, FetchApiError } from './api/fetch-client';
5
+ export type {
6
+ FetchClient,
7
+ FetchClientOptions,
8
+ FetchRequestOptions,
9
+ FetchQueryValue,
10
+ } from './api/fetch-client';
3
11
  export {
4
12
  setTraceParentProvider,
5
13
  getTraceParentHeader,
@@ -19,6 +27,19 @@ export {
19
27
  logout,
20
28
  isTokenExpired,
21
29
  refreshAccessToken,
30
+ // 存储位置可选(默认 local ⇒ 既有 9 个消费方行为不变)
31
+ configureAuthStore,
32
+ getAuthStore,
33
+ getAuthStorageMode,
34
+ resetAuthStore,
35
+ } from './auth/store';
36
+ export { createAuthStore } from './auth/create-auth-store';
37
+ export type {
38
+ AuthState,
39
+ AuthStorageMode,
40
+ CreateAuthStoreOptions,
41
+ AuthStoreApi,
42
+ AuthStoreHook,
22
43
  } from './auth/store';
23
44
  export { AuthService } from './auth/service';
24
45
  export { generatePKCE, generateCodeChallenge } from './auth/pkce';
@@ -88,6 +109,23 @@ export type {
88
109
  UsePortalCatalogOptions,
89
110
  UsePortalCatalogResult,
90
111
  } from './hooks/usePortalCatalog';
112
+ // 门户注册表(单一真源)——各站据此替代本地 CONSOLE_PORTALS 白名单
113
+ export {
114
+ PORTALS,
115
+ PORTAL_CODES,
116
+ getPortalDefinition,
117
+ isConsolePortal,
118
+ isSlugScopedPortal,
119
+ getConsolePortalCodes,
120
+ getSwitcherIncludedCodes,
121
+ getSwitcherExcludedCodes,
122
+ isPortalVisibleForAudience,
123
+ } from './portal/registry';
124
+ export type {
125
+ PortalAudience,
126
+ PortalDefinition,
127
+ PortalFamily,
128
+ } from './portal/registry';
91
129
 
92
130
  // Constants
93
131
  export { API as API_PATHS } from './constants/api-paths';
@@ -0,0 +1,47 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { getPortalUrl } from '../../config';
3
+ import { PORTALS, isSlugScopedPortal } from '../registry';
4
+
5
+ /**
6
+ * 注册表 → `getPortalUrl()` 的接线测试:
7
+ * 注册表里 `host` / `slugScoped` 改了却没生效(或写错字段),这里会红。
8
+ */
9
+ describe('registry → getPortalUrl 接线', () => {
10
+ beforeEach(() => {
11
+ vi.stubGlobal('window', {
12
+ location: {
13
+ hostname: 'config.autional.cn',
14
+ protocol: 'https:',
15
+ origin: 'https://config.autional.cn',
16
+ },
17
+ });
18
+ });
19
+
20
+ afterEach(() => {
21
+ vi.unstubAllGlobals();
22
+ });
23
+
24
+ it.each([
25
+ ['docs', 'https://docs.autional.cn'],
26
+ ['wiki', 'https://wiki.autional.cn'],
27
+ ['reference', 'https://reference.autional.cn'],
28
+ ['consent', 'https://consent.autional.cn'],
29
+ ])('此前漏登记的内容站 %s 现在能拼出子域 URL', (code, expected) => {
30
+ expect(getPortalUrl(code)).toBe(expected);
31
+ });
32
+
33
+ it('landing 落根域(host 为空)', () => {
34
+ expect(getPortalUrl('landing')).toBe('https://autional.cn');
35
+ });
36
+
37
+ it('租户段门户才吃 slug,其余忽略(防拼出 404 路由)', () => {
38
+ for (const portal of PORTALS) {
39
+ const url = getPortalUrl(portal.code, 'acme');
40
+ if (isSlugScopedPortal(portal.code)) {
41
+ expect(url.endsWith('/acme'), `${portal.code} 应拼租户段`).toBe(true);
42
+ } else {
43
+ expect(url.endsWith('/acme'), `${portal.code} 不应拼租户段`).toBe(false);
44
+ }
45
+ }
46
+ });
47
+ });
@@ -0,0 +1,186 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ ADMIN_PLANE_ROLES,
4
+ PORTALS,
5
+ PORTAL_CODES,
6
+ getConsolePortalCodes,
7
+ getLegacyEnvKey,
8
+ getRouterPortalCodes,
9
+ getSwitcherExcludedCodes,
10
+ getSwitcherIncludedCodes,
11
+ isConsolePortal,
12
+ isPortalVisibleForAudience,
13
+ isSlugScopedPortal,
14
+ } from '../registry';
15
+
16
+ /**
17
+ * Oracle 等价测试:注册表派生值必须与「迁移前的字面量」逐项相等。
18
+ * 只要有一项不等,就是行为变化(首页 URL / 路由 basename / 切换器清单 / 可见性)。
19
+ * 下面每个常量都是迁移前源码里的原文拷贝,**不要**跟着实现改。
20
+ */
21
+
22
+ /** 迁移前 `config/index.ts` 的 `PORTAL_DEFAULTS`(顺序 + host/base) */
23
+ const ORACLE_PORTAL_DEFAULTS: Record<string, { host: string; base: string }> = {
24
+ auth: { host: 'auth', base: '' },
25
+ admin: { host: 'admin', base: '' },
26
+ developer: { host: 'developer', base: '' },
27
+ user: { host: 'user', base: '' },
28
+ security: { host: 'security', base: '' },
29
+ status: { host: 'status', base: '' },
30
+ landing: { host: '', base: '' },
31
+ authenticator: { host: 'authenticator', base: '' },
32
+ trust: { host: 'trust', base: '' },
33
+ platform: { host: 'platform', base: '' },
34
+ brand: { host: 'brand', base: '' },
35
+ secret: { host: 'secret', base: '' },
36
+ config: { host: 'config', base: '' },
37
+ };
38
+
39
+ /** 迁移前 `SLUG_PORTALS` */
40
+ const ORACLE_SLUG_PORTALS = ['auth', 'admin', 'user', 'security', 'authenticator', 'platform'];
41
+
42
+ /** 迁移前 `getAppPortalSlugs()` */
43
+ const ORACLE_APP_PORTAL_SLUGS = ['admin', 'developer', 'security', 'platform', 'status', 'trust'];
44
+
45
+ /** 迁移前 `usePortalCatalog` 的 `DEFAULT_EXCLUDE` */
46
+ const ORACLE_DEFAULT_EXCLUDE = ['auth', 'landing', 'authenticator'];
47
+
48
+ /** 迁移前 `isValidRedirect` 的门户白名单顺序 */
49
+ const ORACLE_REDIRECT_ORDER = [
50
+ 'auth',
51
+ 'admin',
52
+ 'developer',
53
+ 'user',
54
+ 'security',
55
+ 'status',
56
+ 'landing',
57
+ 'authenticator',
58
+ 'trust',
59
+ 'platform',
60
+ 'brand',
61
+ 'secret',
62
+ 'config',
63
+ ];
64
+
65
+ /** 6 个站点各自的 `CONSOLE_PORTALS` 字面量(值完全一致) */
66
+ const ORACLE_CONSOLE_PORTALS = ['admin', 'config', 'secret', 'security', 'user', 'platform'];
67
+
68
+ /** 迁移前 `PORTAL_KEY_MAP` */
69
+ const ORACLE_LEGACY_ENV: Record<string, string> = {
70
+ auth: 'VITE_AUTH_PAGES_URL',
71
+ admin: 'VITE_ADMIN_CONSOLE_URL',
72
+ developer: 'VITE_DEVELOPER_PORTAL_URL',
73
+ user: 'VITE_END_USER_PORTAL_URL',
74
+ security: 'VITE_SECURITY_DASHBOARD_URL',
75
+ status: 'VITE_STATUS_PAGE_URL',
76
+ landing: 'VITE_LANDING_SITE_URL',
77
+ authenticator: 'VITE_AUTHENTICATOR_APP_URL',
78
+ trust: 'VITE_TRUST_CENTER_URL',
79
+ platform: 'VITE_PLATFORM_CONSOLE_URL',
80
+ };
81
+
82
+ /** 迁移前 `isPortalVisible` 的实现(作为 oracle) */
83
+ function oracleIsPortalVisible(
84
+ code: string,
85
+ ctx: { role: string | null; isPlatformMember: boolean },
86
+ ): boolean {
87
+ if (code === 'platform') return ctx.isPlatformMember;
88
+ if (code === 'admin' || code === 'security' || code === 'secret' || code === 'config') {
89
+ return ctx.role !== null && ['super_admin', 'admin', 'security_admin', 'user_manager'].includes(ctx.role);
90
+ }
91
+ return true;
92
+ }
93
+
94
+ describe('portal registry —— 与迁移前字面量等价', () => {
95
+ it('host/base 与 PORTAL_DEFAULTS 逐项一致(前 13 项)', () => {
96
+ for (const [code, expectEntry] of Object.entries(ORACLE_PORTAL_DEFAULTS)) {
97
+ const def = PORTALS.find((p) => p.code === code);
98
+ expect(def, `缺门户 ${code}`).toBeTruthy();
99
+ expect({ host: def?.host, base: def?.base }).toEqual(expectEntry);
100
+ }
101
+ });
102
+
103
+ it('portal code 顺序保持(前 13 项 = redirect 白名单原顺序)', () => {
104
+ expect(PORTAL_CODES.slice(0, ORACLE_REDIRECT_ORDER.length)).toEqual(ORACLE_REDIRECT_ORDER);
105
+ });
106
+
107
+ it('新增 4 个内容站(此前漏登记)', () => {
108
+ expect(PORTAL_CODES).toEqual(expect.arrayContaining(['docs', 'wiki', 'reference', 'consent']));
109
+ });
110
+
111
+ it('SLUG_PORTALS 等价(租户段门户集合)', () => {
112
+ const derived = PORTALS.filter((p) => isSlugScopedPortal(p.code)).map((p) => p.code);
113
+ expect(derived.sort()).toEqual([...ORACLE_SLUG_PORTALS].sort());
114
+ });
115
+
116
+ it('getAppPortalSlugs 等价(且保持原顺序)', () => {
117
+ expect(getRouterPortalCodes()).toEqual(ORACLE_APP_PORTAL_SLUGS);
118
+ });
119
+
120
+ it('DEFAULT_EXCLUDE 等价(顺序也一致)', () => {
121
+ expect(getSwitcherExcludedCodes()).toEqual(ORACLE_DEFAULT_EXCLUDE);
122
+ });
123
+
124
+ it('切换器清单 = 全部门户减 3 个排除项(逐项列出,别只做同义反复)', () => {
125
+ expect(getSwitcherIncludedCodes().slice().sort()).toEqual(
126
+ [
127
+ 'admin',
128
+ 'brand',
129
+ 'config',
130
+ 'consent',
131
+ 'developer',
132
+ 'docs',
133
+ 'platform',
134
+ 'reference',
135
+ 'secret',
136
+ 'security',
137
+ 'status',
138
+ 'trust',
139
+ 'user',
140
+ 'wiki',
141
+ ].sort(),
142
+ );
143
+ expect(getSwitcherIncludedCodes()).not.toContain('authenticator');
144
+ expect(getSwitcherIncludedCodes()).not.toContain('auth');
145
+ expect(getSwitcherIncludedCodes()).not.toContain('landing');
146
+ });
147
+
148
+ it('redirect 白名单顺序 = 注册表表序(前 13 = 迁移前原顺序)', () => {
149
+ expect(PORTAL_CODES.slice(0, 13)).toEqual(ORACLE_REDIRECT_ORDER);
150
+ expect(PORTAL_CODES).toEqual([...ORACLE_REDIRECT_ORDER, 'docs', 'wiki', 'reference', 'consent']);
151
+ });
152
+
153
+ it('控制台族 code 集合与 6 站 CONSOLE_PORTALS 字面量等价', () => {
154
+ expect(getConsolePortalCodes().slice().sort()).toEqual([...ORACLE_CONSOLE_PORTALS].sort());
155
+ expect(isConsolePortal('config')).toBe(true);
156
+ expect(isConsolePortal('docs')).toBe(false);
157
+ });
158
+
159
+ it('旧 env 键映射等价', () => {
160
+ for (const [code, key] of Object.entries(ORACLE_LEGACY_ENV)) {
161
+ expect(getLegacyEnvKey(code)).toBe(key);
162
+ }
163
+ expect(getLegacyEnvKey('brand')).toBeUndefined();
164
+ });
165
+
166
+ it('可见性矩阵与迁移前实现逐格一致', () => {
167
+ const roles = [null, 'member', 'guest', 'super_admin', 'admin', 'security_admin', 'user_manager', 'auditor'];
168
+ const codes = [...ORACLE_REDIRECT_ORDER, 'docs', 'wiki', 'reference', 'consent', 'unknown-portal'];
169
+ for (const code of codes) {
170
+ for (const role of roles) {
171
+ for (const isPlatformMember of [true, false]) {
172
+ expect(
173
+ isPortalVisibleForAudience(code, { role, isPlatformMember }),
174
+ `code=${code} role=${String(role)} platform=${isPlatformMember}`,
175
+ ).toBe(oracleIsPortalVisible(code, { role, isPlatformMember }));
176
+ }
177
+ }
178
+ }
179
+ });
180
+
181
+ it('管理面角色集与迁移前一致(4 个)', () => {
182
+ expect([...ADMIN_PLANE_ROLES].sort()).toEqual(
183
+ ['admin', 'security_admin', 'super_admin', 'user_manager'].sort(),
184
+ );
185
+ });
186
+ });
@@ -0,0 +1,48 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ ADMIN_PLANE_ROLES,
4
+ PORTALS,
5
+ getConsolePortalCodes,
6
+ getSwitcherExcludedCodes,
7
+ isConsolePortal,
8
+ } from '@autional/shared/portal';
9
+
10
+ /**
11
+ * 子路径导出 `@autional/shared/portal` 必须**自足**:
12
+ * 注册表模块不 import 任何东西(无 axios / react-query / zustand / react),
13
+ * 零运行时依赖的控制台(配置中心 / 密钥中心)才能只引这一小块。
14
+ *
15
+ * 这里用"包名自引用"走 package.json exports,验证发布后的解析路径真实可用。
16
+ */
17
+ describe('@autional/shared/portal 子路径导出', () => {
18
+ it('可从包名子路径导入(发布后两站这样引用)', () => {
19
+ expect(Array.isArray(PORTALS)).toBe(true);
20
+ expect(PORTALS.length).toBeGreaterThan(10);
21
+ });
22
+
23
+ it('提供控制台族与可见性所需的派生函数', () => {
24
+ expect(getConsolePortalCodes().slice().sort()).toEqual(
25
+ ['admin', 'config', 'platform', 'secret', 'security', 'user'].sort(),
26
+ );
27
+ expect(isConsolePortal('config')).toBe(true);
28
+ expect(isConsolePortal('docs')).toBe(false);
29
+ });
30
+
31
+ // 交接件(site-migration.md)两站要用这两个符号;改名而测试不红 ⇒ 两站上线才炸
32
+ it('导出两站迁移所需的常量(ADMIN_PLANE_ROLES / getSwitcherExcludedCodes)', () => {
33
+ expect([...ADMIN_PLANE_ROLES].sort()).toEqual(
34
+ ['admin', 'security_admin', 'super_admin', 'user_manager'].sort(),
35
+ );
36
+ expect(getSwitcherExcludedCodes()).toEqual(['auth', 'landing', 'authenticator']);
37
+ });
38
+
39
+ it('模块本身不引入任何运行时依赖(源码级断言)', async () => {
40
+ const fs = await import('node:fs/promises');
41
+ const url = new URL('../registry.ts', import.meta.url);
42
+ const src = await fs.readFile(url, 'utf8');
43
+ const importLines = src
44
+ .split(/\r?\n/)
45
+ .filter((line) => /^\s*import\s/.test(line) || /\bfrom\s+['"]/.test(line));
46
+ expect(importLines).toEqual([]);
47
+ });
48
+ });