@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.
- package/package.json +2 -1
- package/src/__tests__/console-kit.contract.test.ts +141 -0
- package/src/api/__tests__/fetch-client.test.ts +266 -0
- package/src/api/fetch-client.ts +328 -0
- package/src/auth/__tests__/create-auth-store.test.ts +144 -0
- package/src/auth/create-auth-store.ts +246 -0
- package/src/auth/portal-config.ts +4 -0
- package/src/auth/store.ts +110 -131
- package/src/components/PortalGuard.tsx +10 -0
- package/src/config/index.ts +36 -57
- package/src/hooks/__tests__/usePortalCatalog.test.tsx +74 -0
- package/src/hooks/usePortalCatalog.ts +45 -24
- package/src/index.ts +38 -0
- package/src/portal/__tests__/registry-url.test.ts +47 -0
- package/src/portal/__tests__/registry.test.ts +186 -0
- package/src/portal/__tests__/subpath-export.test.ts +48 -0
- package/src/portal/registry.ts +349 -0
|
@@ -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
|
+
}
|
|
@@ -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 },
|
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 {
|
|
10
|
-
import {
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
*/
|
|
@@ -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
|
}
|