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

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,246 @@
1
+ /**
2
+ * 认证 store 工厂 —— **存储位置可选择**(配置中心需要 sessionStorage 的安全取舍)。
3
+ *
4
+ * 背景(docs/CONSOLE-KIT-DECISION.md §3-1):
5
+ * 认证态此前固定 `zustand/persist` 默认的 localStorage;配置中心出于「管理面降低长期驻留风险」
6
+ * 只落 sessionStorage(关标签即失效)。直接迁移到 shared 会把安全策略改回去 —— 不可接受。
7
+ * 因此把「存哪」变成**显式参数**,而不是让每个站复制一套 auth:
8
+ *
9
+ * // 应用入口(**推荐**):安装式单例,全部 shared 导出共用同一实例
10
+ * configureAuthStore({ storage: 'session' }); // 配置中心
11
+ * configureAuthStore({ storage: 'local' }); // 密钥中心(其余 9 个消费方不调用 = 默认 local)
12
+ *
13
+ * // 工厂本身只在两种场景直接用:测试、或一个进程里要多个独立实例
14
+ * const store = createAuthStore({ storage: 'session' });
15
+ *
16
+ * 默认 `local` ⇒ 现有消费方行为不变(纯增量)。注意:直接 `createAuthStore()` 造出的实例
17
+ * **不会**被 `useAuthStore` / `AuthService` 看到 —— 应用侧请用 `configureAuthStore()`。
18
+ */
19
+
20
+ import { create } from 'zustand';
21
+ import { createJSONStorage, persist } from 'zustand/middleware';
22
+ import type { StateStorage } from 'zustand/middleware';
23
+ import type { StoreApi } from 'zustand';
24
+ import type { User } from '../types';
25
+ import { decodeJwtPayload } from './jwt-payload';
26
+
27
+ /** 认证态持久化位置。 */
28
+ export type AuthStorageMode = 'local' | 'session';
29
+
30
+ export interface AuthState {
31
+ // State
32
+ user: User | null;
33
+ accessToken: string | null;
34
+ refreshToken: string | null;
35
+ tenants: Array<{ id: string; name: string; role: string }>;
36
+ currentTenantId: string | null;
37
+ permissions: string[];
38
+ isAuthenticated: boolean;
39
+
40
+ // Actions
41
+ setAuth: (accessToken: string, refreshToken: string, user: User) => void;
42
+ setTokens: (accessToken: string, refreshToken: string) => void;
43
+ setUser: (user: User) => void;
44
+ setTenants: (tenants: Array<{ id: string; name: string; role: string }>) => void;
45
+ setCurrentTenant: (tenantId: string) => void;
46
+ switchTenant: (tenantId: string) => void;
47
+ setPermissions: (permissions: string[]) => void;
48
+ clearAuth: () => void;
49
+ }
50
+
51
+ export interface CreateAuthStoreOptions {
52
+ /** 持久化位置,默认 `local`(与迁移前一致)。 */
53
+ storage?: AuthStorageMode;
54
+ /** persist key,默认 `autional-auth-v1`(与迁移前一致)。 */
55
+ name?: string;
56
+ /** persist version,默认 `1`。 */
57
+ version?: number;
58
+ }
59
+
60
+ /** 内存兜底:隐私模式 / 禁用存储时不抛到 UI,只是不持久化。 */
61
+ function createMemoryStorage(): StateStorage {
62
+ const map = new Map<string, string>();
63
+ return {
64
+ getItem: (key) => map.get(key) ?? null,
65
+ setItem: (key, value) => {
66
+ map.set(key, value);
67
+ },
68
+ removeItem: (key) => {
69
+ map.delete(key);
70
+ },
71
+ };
72
+ }
73
+
74
+ /**
75
+ * 按 mode 取浏览器存储。**每次调用惰性解析**(不在模块加载期读 window):
76
+ * - SSR / 单测无 window ⇒ 内存兜底
77
+ * - 隐私模式读 `window.localStorage` 本身会抛 ⇒ 内存兜底
78
+ */
79
+ export function resolveAuthStorage(mode: AuthStorageMode): StateStorage {
80
+ const fallback = createMemoryStorage();
81
+ try {
82
+ if (typeof window === 'undefined') return fallback;
83
+ const backing = mode === 'session' ? window.sessionStorage : window.localStorage;
84
+ if (!backing) return fallback;
85
+ return {
86
+ getItem: (key) => {
87
+ try {
88
+ return backing.getItem(key);
89
+ } catch {
90
+ return fallback.getItem(key) as string | null;
91
+ }
92
+ },
93
+ setItem: (key, value) => {
94
+ try {
95
+ backing.setItem(key, value);
96
+ } catch {
97
+ fallback.setItem(key, value);
98
+ }
99
+ },
100
+ removeItem: (key) => {
101
+ try {
102
+ backing.removeItem(key);
103
+ } catch {
104
+ fallback.removeItem(key);
105
+ }
106
+ },
107
+ };
108
+ } catch {
109
+ return fallback;
110
+ }
111
+ }
112
+
113
+ /** 认证 store 实例类型(zustand bound store 的 API 面)。 */
114
+ export type AuthStoreApi = StoreApi<AuthState>;
115
+
116
+ /**
117
+ * 创建认证 store(可选择持久化位置)。
118
+ *
119
+ * 与旧实现的差异仅在 `storage`;`name` / `version` / `merge` / `migrate` / `partialize` /
120
+ * `onRehydrateStorage` 逻辑逐行保留(坏数据自愈:有 token 无 isAuthenticated、无 token 有
121
+ * isAuthenticated、有 token 无 user 时从 JWT 回填)。
122
+ */
123
+ export function createAuthStore(options: CreateAuthStoreOptions = {}): AuthStoreApi {
124
+ const { storage = 'local', name = 'autional-auth-v1', version = 1 } = options;
125
+
126
+ // onRehydrateStorage 需要 api,但它在 persist 的 options 里(与 creator 平级)⇒ 用 ref 捕获。
127
+ let storeRef: AuthStoreApi | null = null;
128
+
129
+ const store = create<AuthState>()(
130
+ persist(
131
+ (set, _get, api) => {
132
+ storeRef = api;
133
+ return {
134
+ user: null,
135
+ accessToken: null,
136
+ refreshToken: null,
137
+ tenants: [],
138
+ currentTenantId: null,
139
+ permissions: [],
140
+ isAuthenticated: false,
141
+
142
+ setAuth: (accessToken, refreshToken, user) => {
143
+ if (!user) return;
144
+ const validToken = accessToken && accessToken !== 'undefined' && accessToken !== 'null';
145
+ set({
146
+ accessToken: validToken ? accessToken : null,
147
+ refreshToken: validToken ? refreshToken : null,
148
+ user,
149
+ isAuthenticated: true,
150
+ });
151
+ },
152
+
153
+ setTokens: (accessToken, refreshToken) => set({ accessToken, refreshToken }),
154
+
155
+ setUser: (user) => set({ user }),
156
+
157
+ setTenants: (tenants) => set({ tenants }),
158
+
159
+ setCurrentTenant: (tenantId) => set({ currentTenantId: tenantId }),
160
+
161
+ switchTenant: (tenantId) => set({ currentTenantId: tenantId }),
162
+
163
+ setPermissions: (permissions) => set({ permissions }),
164
+
165
+ clearAuth: () =>
166
+ set({
167
+ user: null,
168
+ accessToken: null,
169
+ refreshToken: null,
170
+ tenants: [],
171
+ currentTenantId: null,
172
+ permissions: [],
173
+ isAuthenticated: false,
174
+ }),
175
+ };
176
+ },
177
+ {
178
+ name,
179
+ version,
180
+ storage: createJSONStorage(() => resolveAuthStorage(storage)),
181
+ // Custom merge: validate persisted data integrity before merging into store.
182
+ // This prevents corrupted storage entries from silently breaking auth.
183
+ merge: (persisted, current) => {
184
+ if (!persisted || typeof persisted !== 'object') return current;
185
+ const state = { ...current, ...(persisted as Record<string, unknown>) } as AuthState;
186
+
187
+ // Fix: has accessToken but isAuthenticated is false
188
+ if (state.accessToken && !state.isAuthenticated) {
189
+ state.isAuthenticated = true;
190
+ }
191
+ // Fix: no accessToken but isAuthenticated is true (token was evicted)
192
+ if (!state.accessToken && state.isAuthenticated) {
193
+ state.isAuthenticated = false;
194
+ }
195
+ // Fix: has accessToken but user is missing — recover from JWT
196
+ if (state.accessToken && !state.user) {
197
+ const payload = decodeJwtPayload(state.accessToken);
198
+ if (payload) {
199
+ state.user = {
200
+ id: (payload.sub || payload.user_id) as string,
201
+ username: ((payload.custom as Record<string, unknown> | undefined)?.username ||
202
+ payload.username) as string,
203
+ email: (payload.email as string) || '',
204
+ status: 'active',
205
+ };
206
+ }
207
+ }
208
+
209
+ return state;
210
+ },
211
+ migrate: (persisted) => {
212
+ // v0 → v1: no structural changes, data is compatible
213
+ return persisted as unknown as AuthState;
214
+ },
215
+ partialize: (state) => {
216
+ return {
217
+ accessToken:
218
+ state.accessToken && state.accessToken !== 'undefined' && state.accessToken !== 'null'
219
+ ? state.accessToken
220
+ : null,
221
+ refreshToken:
222
+ state.refreshToken &&
223
+ state.refreshToken !== 'undefined' &&
224
+ state.refreshToken !== 'null'
225
+ ? state.refreshToken
226
+ : null,
227
+ user: state.user,
228
+ tenants: state.tenants,
229
+ currentTenantId: state.currentTenantId,
230
+ permissions: state.permissions,
231
+ isAuthenticated: state.isAuthenticated,
232
+ };
233
+ },
234
+ onRehydrateStorage: () => (state, error) => {
235
+ if (error || !state) return;
236
+ // merge already handles all fixups; this is a safety net
237
+ if (state.accessToken && !state.isAuthenticated) {
238
+ storeRef?.setState({ isAuthenticated: true });
239
+ }
240
+ },
241
+ },
242
+ ),
243
+ );
244
+
245
+ return store as AuthStoreApi;
246
+ }
package/src/auth/store.ts CHANGED
@@ -4,147 +4,126 @@
4
4
  *
5
5
  * 职责划分(AC-008):前端角色(tenants[].role 派生)仅用于 UX 呈现;
6
6
  * 安全判断由后端 rbac-backed 授权强制,前端不做凭角色放行的敏感操作。
7
+ *
8
+ * 存储位置(docs/CONSOLE-KIT-DECISION.md §4-1):
9
+ * 默认 localStorage(与迁移前完全一致);需要 sessionStorage 的站(配置中心)在**入口最早期**
10
+ * 调用 `configureAuthStore({ storage: 'session' })`,此后所有 shared 导出(含 AuthService、
11
+ * useAuth / usePermission / usePortalCatalog)都读同一个实例。
7
12
  */
8
13
 
9
- import { create } from 'zustand';
10
- import { persist } from 'zustand/middleware';
14
+ import { useStore } from 'zustand';
15
+ import type { StoreApi } from 'zustand';
11
16
  import type { User } from '../types';
12
17
  import { traceRedirect } from './auth-trace';
13
18
  import { decodeJwtPayload } from './jwt-payload';
19
+ import {
20
+ createAuthStore,
21
+ type AuthState,
22
+ type AuthStorageMode,
23
+ type CreateAuthStoreOptions,
24
+ } from './create-auth-store';
25
+
26
+ export type { AuthState, AuthStorageMode, CreateAuthStoreOptions } from './create-auth-store';
27
+
28
+ export type AuthStoreApi = StoreApi<AuthState>;
29
+
30
+ /**
31
+ * 当前生效实例 + 其存储模式。
32
+ * 惰性创建:首次访问时才实例化,保证 `configureAuthStore()` 能先于任何读取生效。
33
+ */
34
+ let activeStore: AuthStoreApi | null = null;
35
+ let activeStorageMode: AuthStorageMode | null = null;
14
36
 
15
- interface AuthState {
16
- // State
17
- user: User | null;
18
- accessToken: string | null;
19
- refreshToken: string | null;
20
- tenants: Array<{ id: string; name: string; role: string }>;
21
- currentTenantId: string | null;
22
- permissions: string[];
23
- isAuthenticated: boolean;
24
-
25
- // Actions
26
- setAuth: (accessToken: string, refreshToken: string, user: User) => void;
27
- setTokens: (accessToken: string, refreshToken: string) => void;
28
- setUser: (user: User) => void;
29
- setTenants: (tenants: Array<{ id: string; name: string; role: string }>) => void;
30
- setCurrentTenant: (tenantId: string) => void;
31
- switchTenant: (tenantId: string) => void;
32
- setPermissions: (permissions: string[]) => void;
33
- clearAuth: () => void;
37
+ /**
38
+ * 配置并返回认证 store(**幂等**:已创建则原样返回,不重复建实例)。
39
+ *
40
+ * 必须在应用入口、任何认证态读取之前调用;形态:
41
+ *
42
+ * configureAuthStore({ storage: 'session' }); // 配置中心
43
+ * // 其余站不调用即可 —— 默认 local,行为与迁移前一致
44
+ *
45
+ * 若在 store 已创建后再以不同 storage 调用:**生产也告警**并沿用已创建实例
46
+ * (避免"两套 auth 同时写 token"导致一半页面登出;静默降级等于悄悄退回 localStorage)。
47
+ */
48
+ export function configureAuthStore(options: CreateAuthStoreOptions = {}): AuthStoreApi {
49
+ const mode = options.storage ?? 'local';
50
+ if (activeStore) {
51
+ if (activeStorageMode !== mode) {
52
+ // **生产也告警**:静默降级等于把 sessionStorage 的安全取舍悄悄退回 localStorage
53
+ // (关标签仍存活),日志里必须留痕。
54
+ console.warn(
55
+ `[auth] configureAuthStore({ storage: '${mode}' }) 早于 store 创建才生效;` +
56
+ `当前实例已是 '${String(activeStorageMode)}',本次忽略。` +
57
+ '请在应用入口最早期调用。',
58
+ );
59
+ }
60
+ return activeStore;
61
+ }
62
+ activeStore = createAuthStore({ ...options, storage: mode });
63
+ activeStorageMode = mode;
64
+ return activeStore;
34
65
  }
35
66
 
36
- export const useAuthStore = create<AuthState>()(
37
- persist(
38
- (set) => ({
39
- user: null,
40
- accessToken: null,
41
- refreshToken: null,
42
- tenants: [],
43
- currentTenantId: null,
44
- permissions: [],
45
- isAuthenticated: false,
46
-
47
- setAuth: (accessToken, refreshToken, user) => {
48
- if (!user) return;
49
- const validToken = accessToken && accessToken !== 'undefined' && accessToken !== 'null';
50
- set({
51
- accessToken: validToken ? accessToken : null,
52
- refreshToken: validToken ? refreshToken : null,
53
- user,
54
- isAuthenticated: true,
55
- });
56
- },
57
-
58
- setTokens: (accessToken, refreshToken) => set({ accessToken, refreshToken }),
59
-
60
- setUser: (user) => set({ user }),
61
-
62
- setTenants: (tenants) => set({ tenants }),
63
-
64
- setCurrentTenant: (tenantId) => set({ currentTenantId: tenantId }),
65
-
66
- switchTenant: (tenantId) => set({ currentTenantId: tenantId }),
67
-
68
- setPermissions: (permissions) => set({ permissions }),
69
-
70
- clearAuth: () =>
71
- set({
72
- user: null,
73
- accessToken: null,
74
- refreshToken: null,
75
- tenants: [],
76
- currentTenantId: null,
77
- permissions: [],
78
- isAuthenticated: false,
79
- }),
80
- }),
81
- {
82
- name: 'autional-auth-v1',
83
- version: 1,
84
- // Custom merge: validate persisted data integrity before merging into store.
85
- // This prevents corrupted localStorage entries from silently breaking auth.
86
- merge: (persisted, current) => {
87
- if (!persisted || typeof persisted !== 'object') return current;
88
- const state = { ...current, ...persisted };
89
-
90
- // Fix: has accessToken but isAuthenticated is false
91
- if (state.accessToken && !state.isAuthenticated) {
92
- state.isAuthenticated = true;
93
- }
94
- // Fix: no accessToken but isAuthenticated is true (token was evicted)
95
- if (!state.accessToken && state.isAuthenticated) {
96
- state.isAuthenticated = false;
97
- }
98
- // Fix: has accessToken but user is missing — recover from JWT
99
- if (state.accessToken && !state.user) {
100
- const payload = decodeJwtPayload(state.accessToken);
101
- if (payload) {
102
- state.user = {
103
- id: (payload.sub || payload.user_id) as string,
104
- username: ((payload.custom as Record<string, unknown> | undefined)?.username ||
105
- payload.username) as string,
106
- email: (payload.email as string) || '',
107
- status: 'active',
108
- };
109
- }
110
- }
111
-
112
- return state;
113
- },
114
- migrate: (persisted) => {
115
- // v0 → v1: no structural changes, data is compatible
116
- return persisted as any;
117
- },
118
- partialize: (state) => {
119
- return {
120
- accessToken:
121
- state.accessToken && state.accessToken !== 'undefined' && state.accessToken !== 'null'
122
- ? state.accessToken
123
- : null,
124
- refreshToken:
125
- state.refreshToken &&
126
- state.refreshToken !== 'undefined' &&
127
- state.refreshToken !== 'null'
128
- ? state.refreshToken
129
- : null,
130
- user: state.user,
131
- tenants: state.tenants,
132
- currentTenantId: state.currentTenantId,
133
- permissions: state.permissions,
134
- isAuthenticated: state.isAuthenticated,
135
- };
136
- },
137
- onRehydrateStorage: () => (state, error) => {
138
- if (error || !state) return;
139
- // merge already handles all fixups; this is a safety net
140
- if (state.accessToken && !state.isAuthenticated) {
141
- useAuthStore.setState({ isAuthenticated: true });
142
- }
143
- },
144
- },
145
- ),
67
+ /** 当前生效 store(未配置则按默认 local 惰性创建)。 */
68
+ export function getAuthStore(): AuthStoreApi {
69
+ return activeStore ?? configureAuthStore();
70
+ }
71
+
72
+ /** 当前生效存储模式(测试与诊断用)。 */
73
+ export function getAuthStorageMode(): AuthStorageMode {
74
+ getAuthStore();
75
+ return activeStorageMode ?? 'local';
76
+ }
77
+
78
+ /** 丢弃当前实例(**仅测试**:隔离用例之间的存储/状态串扰)。 */
79
+ export function resetAuthStore(): void {
80
+ activeStore = null;
81
+ activeStorageMode = null;
82
+ }
83
+
84
+ /** 兼容旧调用点的 hook 形状:可当 hook 用,也可 `.getState()` / `.setState()` / `.subscribe()`。 */
85
+ export type AuthStoreHook = {
86
+ <T>(selector: (state: AuthState) => T): T;
87
+ (): AuthState;
88
+ getState: () => AuthState;
89
+ getInitialState: () => AuthState;
90
+ setState: AuthStoreApi['setState'];
91
+ subscribe: AuthStoreApi['subscribe'];
92
+ /** persist 中间件附加 API(rehydrate / hasHydrated …);未使用 persist 时为 undefined。 */
93
+ persist?: unknown;
94
+ };
95
+
96
+ const identity = (state: AuthState): AuthState => state;
97
+
98
+ const authStoreHook = Object.assign(
99
+ <T>(selector?: (state: AuthState) => T): T | AuthState => {
100
+ // 始终只调一次 useStore(同一 hook 位置),避免选择器有无变化导致 hook 顺序不一致
101
+ const store = getAuthStore();
102
+ const pick = (selector ?? identity) as (state: AuthState) => T | AuthState;
103
+ return useStore(store, pick);
104
+ },
105
+ {
106
+ getState: () => getAuthStore().getState(),
107
+ getInitialState: () => getAuthStore().getInitialState(),
108
+ setState: ((partial: unknown, replace?: boolean) =>
109
+ (0, getAuthStore().setState)(partial as never, replace as never)) as AuthStoreApi['setState'],
110
+ subscribe: ((listener: Parameters<AuthStoreApi['subscribe']>[0]) =>
111
+ getAuthStore().subscribe(listener)) as AuthStoreApi['subscribe'],
112
+ },
146
113
  );
147
114
 
115
+ // persist 中间件把 API 挂在 store api 上。
116
+ // **必须用 defineProperty 定义 getter** —— 若写成 `Object.assign(fn, { get persist() {…} })`,
117
+ // Object.assign 会在**模块求值期**读取该 getter,于是导入 store 就立刻创建了 store(默认 local),
118
+ // 之后站点再 `configureAuthStore({storage:'session'})` 只会命中"已建实例"分支 ⇒ sessionStorage 静默失效。
119
+ Object.defineProperty(authStoreHook, 'persist', {
120
+ configurable: true,
121
+ enumerable: false,
122
+ get: () => (getAuthStore() as unknown as { persist?: unknown }).persist,
123
+ });
124
+
125
+ export const useAuthStore: AuthStoreHook = authStoreHook as unknown as AuthStoreHook;
126
+
148
127
  /**
149
128
  * 获取 access token
150
129
  */
@@ -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);
@@ -1,7 +1,7 @@
1
1
  // GENERATED FILE — DO NOT EDIT.
2
2
  // Source: contracts/errors.semantics.json(@autional/shared 仓内镜像,源 = service-core base/error/testdata/errors.semantics.json)
3
3
  // Regenerate: pnpm gen:errors · Verify: pnpm gen:errors:check
4
- // rows: 802 · source sha256: d1d69d0eedc43e211b89c0efa5ade53b95a0d2ff31ea706800ba29b04c97f20f
4
+ // rows: 803 · source sha256: f4e10203c9d4a888df05ff40bf16d5b997c0606859a31e1ff1061bd12f791665
5
5
  //
6
6
  // 单一真源链:service-core/base/error/semantics.go(Go)→ errors.semantics.json → 本文件。
7
7
  // ⚠️ 禁止在本文件或页面里手抄错误码分支:请消费 ERROR_SEMANTICS / UNPROVISIONED_CODES。
@@ -292,6 +292,7 @@ export const ERROR_SEMANTICS: Readonly<Record<number, ErrorSemantics>> = {
292
292
  40800302: { code: 40800302, httpStatus: 404, class: 'not_found', absence: 'entity', uiObservation: 'not_found_page', retryable: false, docsPath: '/errors/40800302' },
293
293
  40800303: { code: 40800303, httpStatus: 401, class: 'unauthorized', absence: '', uiObservation: 'session_expired', retryable: false, docsPath: '/errors/40800303' },
294
294
  40800305: { code: 40800305, httpStatus: 409, class: 'conflict', absence: '', uiObservation: 'conflict', retryable: false, docsPath: '/errors/40800305' },
295
+ 40800306: { code: 40800306, httpStatus: 403, class: 'forbidden', absence: '', uiObservation: 'forbidden', retryable: false, docsPath: '/errors/40800306' },
295
296
  40800401: { code: 40800401, httpStatus: 404, class: 'not_found', absence: 'entity', uiObservation: 'not_found_page', retryable: false, docsPath: '/errors/40800401' },
296
297
  40800501: { code: 40800501, httpStatus: 429, class: 'limit', absence: '', uiObservation: 'rate_limited', retryable: true, docsPath: '/errors/40800501' },
297
298
  40800502: { code: 40800502, httpStatus: 403, class: 'forbidden', absence: '', uiObservation: 'forbidden', retryable: false, docsPath: '/errors/40800502' },
@@ -863,8 +864,8 @@ export const UNPROVISIONED_CODES: ReadonlySet<number> = new Set([]);
863
864
  export const EMPTY_STATE_CODES: ReadonlySet<number> = new Set([]);
864
865
 
865
866
  export const ERROR_SEMANTICS_META = {
866
- rowCount: 802,
867
- sourceSha256: 'd1d69d0eedc43e211b89c0efa5ade53b95a0d2ff31ea706800ba29b04c97f20f',
867
+ rowCount: 803,
868
+ sourceSha256: 'f4e10203c9d4a888df05ff40bf16d5b997c0606859a31e1ff1061bd12f791665',
868
869
  } as const;
869
870
 
870
871
  /** 具名错误码常量(契约 name → code)。页面只消费常量,不写数字字面量。 */