@autional/shared 0.1.0-rc.51 → 0.1.0-rc.53
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 +1 -1
- package/src/components/RequireAuth.tsx +78 -0
- package/src/components/__tests__/RequireAuth.bootstrap-error.test.tsx +96 -0
- package/src/components/__tests__/RequireAuth.bootstrap-integration.test.tsx +83 -0
- package/src/generated/error-semantics.ts +5 -3
- package/src/hooks/__tests__/useBootstrap.test.tsx +62 -1
- package/src/hooks/useBootstrap.ts +23 -8
package/package.json
CHANGED
|
@@ -17,8 +17,13 @@ interface RequireAuthProps {
|
|
|
17
17
|
loadingFallback?: React.ReactNode;
|
|
18
18
|
/** 确定性未知 slug(by-slug HTTP 404)时渲染的 404 页;缺省用内置极简 404 兜底 */
|
|
19
19
|
notFound?: React.ReactNode;
|
|
20
|
+
/** 启动数据(权限/租户)加载失败或超时时的错误页;缺省用内置可恢复错误页兜底 */
|
|
21
|
+
bootstrapError?: React.ReactNode;
|
|
20
22
|
}
|
|
21
23
|
|
|
24
|
+
/** 启动等待上限:超过即认定「卡住」,降级到可恢复错误页(P1-2)。 */
|
|
25
|
+
const BOOTSTRAP_TIMEOUT_MS = 10_000;
|
|
26
|
+
|
|
22
27
|
/**
|
|
23
28
|
* 内置极简 404(零依赖,供未注入 notFound 的站点兜底 —— shared 不能 import 各
|
|
24
29
|
* app 的 not-found/page)。样式用 CSS 变量 var(--color-*),.dark 下自动反转。
|
|
@@ -96,18 +101,84 @@ function DefaultSignInRequired({ onSignIn }: { onSignIn: () => void }) {
|
|
|
96
101
|
);
|
|
97
102
|
}
|
|
98
103
|
|
|
104
|
+
/**
|
|
105
|
+
* P1-2(2026-11-08 线上复现):启动数据(权限/租户)加载失败或超时时,原实现
|
|
106
|
+
* 恒 render null ⇒ 后端任一 5xx 就让整站变成空白页(无提示、无重试、不跳登录)。
|
|
107
|
+
* 此组件给最小可恢复 UI:说明 + 重试(整页重载,重建查询与状态机)。
|
|
108
|
+
* 零依赖、CSS 变量主题;按钮固定 #2563eb(白字 5.17:1 过 AA),不引品牌色。
|
|
109
|
+
*/
|
|
110
|
+
function DefaultBootstrapError({ onRetry }: { onRetry: () => void }) {
|
|
111
|
+
const zh =
|
|
112
|
+
typeof document !== 'undefined' &&
|
|
113
|
+
(document.documentElement.lang || '').toLowerCase().startsWith('zh');
|
|
114
|
+
return (
|
|
115
|
+
<div
|
|
116
|
+
role="alert"
|
|
117
|
+
style={{
|
|
118
|
+
display: 'flex',
|
|
119
|
+
flexDirection: 'column',
|
|
120
|
+
alignItems: 'center',
|
|
121
|
+
justifyContent: 'center',
|
|
122
|
+
minHeight: '40vh',
|
|
123
|
+
gap: '0.75rem',
|
|
124
|
+
width: '100%',
|
|
125
|
+
}}
|
|
126
|
+
>
|
|
127
|
+
<h1 style={{ fontSize: '1.25rem', fontWeight: 600, color: 'var(--color-text-primary)' }}>
|
|
128
|
+
{zh ? '加载失败' : 'Failed to load'}
|
|
129
|
+
</h1>
|
|
130
|
+
<p style={{ color: 'var(--color-text-secondary)', fontSize: '0.875rem', margin: 0 }}>
|
|
131
|
+
{zh ? '无法加载账号信息,请检查网络后重试' : 'Could not load your account. Check your connection and retry.'}
|
|
132
|
+
</p>
|
|
133
|
+
<button
|
|
134
|
+
type="button"
|
|
135
|
+
onClick={onRetry}
|
|
136
|
+
style={{
|
|
137
|
+
border: 0,
|
|
138
|
+
borderRadius: 6,
|
|
139
|
+
padding: '8px 18px',
|
|
140
|
+
fontSize: '0.875rem',
|
|
141
|
+
cursor: 'pointer',
|
|
142
|
+
background: '#2563eb',
|
|
143
|
+
color: '#fff',
|
|
144
|
+
}}
|
|
145
|
+
>
|
|
146
|
+
{zh ? '重试' : 'Retry'}
|
|
147
|
+
</button>
|
|
148
|
+
</div>
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
99
152
|
export function RequireAuth({
|
|
100
153
|
children,
|
|
101
154
|
allowedRoles,
|
|
102
155
|
fallback,
|
|
103
156
|
loadingFallback,
|
|
104
157
|
notFound,
|
|
158
|
+
bootstrapError,
|
|
105
159
|
}: RequireAuthProps) {
|
|
106
160
|
const machine = useAuthMachine();
|
|
107
161
|
const tenantRoute = useTenantRoute();
|
|
108
162
|
// 「停留」已选(被动登录跳转被用户取消)——渲染恢复态而非空白(AUTH-03)
|
|
109
163
|
const [stayed, setStayed] = useState(false);
|
|
110
164
|
|
|
165
|
+
// P1-2:启动数据加载失败/卡住时不得 render null(整站白屏)。
|
|
166
|
+
// ① bootstrapState==='error'(两个查询都失败)立即给错误页;
|
|
167
|
+
// ② checking/bootstrap 超过 10s 视为卡住(单查询挂起等),同样降级。
|
|
168
|
+
const [bootstrapTimedOut, setBootstrapTimedOut] = useState(false);
|
|
169
|
+
const waitingBootstrap = machine.status === 'checking' || machine.status === 'bootstrap';
|
|
170
|
+
useEffect(() => {
|
|
171
|
+
if (!waitingBootstrap) {
|
|
172
|
+
setBootstrapTimedOut(false);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const timer = setTimeout(() => setBootstrapTimedOut(true), BOOTSTRAP_TIMEOUT_MS);
|
|
176
|
+
return () => clearTimeout(timer);
|
|
177
|
+
}, [waitingBootstrap]);
|
|
178
|
+
const retryBootstrap = useCallback(() => {
|
|
179
|
+
if (typeof window !== 'undefined') window.location.reload();
|
|
180
|
+
}, []);
|
|
181
|
+
|
|
111
182
|
// 登录跳转的单一出口:effect(进入未认证态)与恢复态「前往登录」按钮共用。
|
|
112
183
|
// force=true 跳过 OAuth 10s 防重入窗口(用户显式重试)。
|
|
113
184
|
const triggerLogin = useCallback(
|
|
@@ -179,6 +250,13 @@ export function RequireAuth({
|
|
|
179
250
|
triggerLogin(false);
|
|
180
251
|
}, [machine.status, tenantRoute, triggerLogin]);
|
|
181
252
|
|
|
253
|
+
// P1-2:启动数据失败 / 等待超时 → 可恢复错误页(不得空白)。
|
|
254
|
+
// 放在所有 status 分支之前:机器在 BOOTSTRAP_ERROR 时会降级到 ready,
|
|
255
|
+
// 此时仍是「启动失败」语义,不能直接放行子路由。
|
|
256
|
+
if (machine.bootstrapState === 'error' || bootstrapTimedOut) {
|
|
257
|
+
return bootstrapError ? <>{bootstrapError}</> : <DefaultBootstrapError onRetry={retryBootstrap} />;
|
|
258
|
+
}
|
|
259
|
+
|
|
182
260
|
if (machine.status === 'checking' || machine.status === 'bootstrap') {
|
|
183
261
|
return loadingFallback ? <>{loadingFallback}</> : null;
|
|
184
262
|
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import '@testing-library/jest-dom/vitest';
|
|
3
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
4
|
+
import { render, screen, cleanup } from '@testing-library/react';
|
|
5
|
+
|
|
6
|
+
// ============================================================
|
|
7
|
+
// P1-2 回归锁(2026-11-08 用户门户线上复现)
|
|
8
|
+
// 后端 bootstrap 接口全 5xx 时,useBootstrap 曾返回 'loading' ⇒ 状态机永停
|
|
9
|
+
// bootstrap ⇒ RequireAuth 恒 render null ⇒ 整站白屏(无提示/无重试/不跳登录)。
|
|
10
|
+
// 修复后:bootstrapState==='error' 必须渲染可恢复错误页,且不得渲染子路由。
|
|
11
|
+
// ============================================================
|
|
12
|
+
|
|
13
|
+
const { mockState } = vi.hoisted(() => ({
|
|
14
|
+
mockState: {
|
|
15
|
+
machineStatus: 'ready' as string,
|
|
16
|
+
bootstrapState: 'error' as string,
|
|
17
|
+
tenantRoute: {
|
|
18
|
+
slug: 'acme-corp',
|
|
19
|
+
tenantId: 't1',
|
|
20
|
+
oauthClientId: null as string | null,
|
|
21
|
+
loading: false,
|
|
22
|
+
notFound: false,
|
|
23
|
+
unknownSlug: false,
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
}));
|
|
27
|
+
|
|
28
|
+
vi.mock('../../auth/auth-machine', () => ({
|
|
29
|
+
useAuthMachine: () => ({
|
|
30
|
+
status: mockState.machineStatus,
|
|
31
|
+
bootstrapState: mockState.bootstrapState,
|
|
32
|
+
}),
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
36
|
+
...(await importOriginal<typeof import('../../auth/tenant-route-middleware')>()),
|
|
37
|
+
useTenantRoute: () => mockState.tenantRoute,
|
|
38
|
+
}));
|
|
39
|
+
|
|
40
|
+
vi.mock('../../auth/oauth-login', () => ({ initiateOAuthLogin: vi.fn() }));
|
|
41
|
+
|
|
42
|
+
vi.mock('../../auth/service', () => ({
|
|
43
|
+
AuthService: {
|
|
44
|
+
getAccessToken: () => 'token-xyz',
|
|
45
|
+
getCurrentRole: () => 'member',
|
|
46
|
+
getPermissions: () => ['user.read'],
|
|
47
|
+
},
|
|
48
|
+
setBootstrapLock: vi.fn(),
|
|
49
|
+
}));
|
|
50
|
+
|
|
51
|
+
import { RequireAuth } from '../RequireAuth';
|
|
52
|
+
|
|
53
|
+
describe('RequireAuth(P1-2 启动失败不得白屏)', () => {
|
|
54
|
+
beforeEach(() => {
|
|
55
|
+
mockState.machineStatus = 'ready';
|
|
56
|
+
mockState.bootstrapState = 'error';
|
|
57
|
+
document.documentElement.lang = 'zh-CN';
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
afterEach(() => cleanup());
|
|
61
|
+
|
|
62
|
+
it('bootstrapState=error → 渲染错误页 + 重试按钮,且不渲染子路由', () => {
|
|
63
|
+
render(
|
|
64
|
+
<RequireAuth>
|
|
65
|
+
<div data-testid="protected">受保护内容</div>
|
|
66
|
+
</RequireAuth>,
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
expect(screen.getByRole('alert')).toBeInTheDocument();
|
|
70
|
+
expect(screen.getByText('加载失败')).toBeInTheDocument();
|
|
71
|
+
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument();
|
|
72
|
+
expect(screen.queryByTestId('protected')).not.toBeInTheDocument();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('英文界面错误页文案(<html lang="en">)', () => {
|
|
76
|
+
document.documentElement.lang = 'en-US';
|
|
77
|
+
render(
|
|
78
|
+
<RequireAuth>
|
|
79
|
+
<div data-testid="protected">protected</div>
|
|
80
|
+
</RequireAuth>,
|
|
81
|
+
);
|
|
82
|
+
expect(screen.getByText('Failed to load')).toBeInTheDocument();
|
|
83
|
+
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('bootstrapState=ready → 正常渲染子路由(修复不得误伤正常路径)', () => {
|
|
87
|
+
mockState.bootstrapState = 'ready';
|
|
88
|
+
render(
|
|
89
|
+
<RequireAuth>
|
|
90
|
+
<div data-testid="protected">受保护内容</div>
|
|
91
|
+
</RequireAuth>,
|
|
92
|
+
);
|
|
93
|
+
expect(screen.getByTestId('protected')).toBeInTheDocument();
|
|
94
|
+
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
|
95
|
+
});
|
|
96
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import '@testing-library/jest-dom/vitest';
|
|
3
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
4
|
+
import { render, screen, cleanup } from '@testing-library/react';
|
|
5
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
6
|
+
|
|
7
|
+
// ============================================================
|
|
8
|
+
// P1-2 集成回归锁:真实 useAuthMachine + useBootstrap 链路
|
|
9
|
+
// 两个 bootstrap 查询都失败 → 机器曾永停 bootstrap → RequireAuth 渲染 null → 白屏。
|
|
10
|
+
// 本用例不 mock 状态机,只 mock「查询返回错误」,验证端到端落到错误页。
|
|
11
|
+
// ============================================================
|
|
12
|
+
|
|
13
|
+
vi.mock('../../auth/auth-queries', () => ({
|
|
14
|
+
usePermissionsQuery: () => ({ data: undefined, isError: true, isError2: true }),
|
|
15
|
+
useTenantsQuery: () => ({ data: undefined, isError: true }),
|
|
16
|
+
}));
|
|
17
|
+
|
|
18
|
+
vi.mock('../../generated/api', () => ({ profileAvatar: vi.fn().mockResolvedValue({}) }));
|
|
19
|
+
|
|
20
|
+
vi.mock('../../auth/oauth-login', () => ({ initiateOAuthLogin: vi.fn() }));
|
|
21
|
+
|
|
22
|
+
vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
23
|
+
...(await importOriginal<typeof import('../../auth/tenant-route-middleware')>()),
|
|
24
|
+
useTenantRoute: () => ({
|
|
25
|
+
slug: 'acme-corp',
|
|
26
|
+
tenantId: 't1',
|
|
27
|
+
oauthClientId: null,
|
|
28
|
+
loading: false,
|
|
29
|
+
notFound: false,
|
|
30
|
+
unknownSlug: false,
|
|
31
|
+
}),
|
|
32
|
+
}));
|
|
33
|
+
|
|
34
|
+
import { RequireAuth } from '../RequireAuth';
|
|
35
|
+
import { useAuthStore } from '../../auth/store';
|
|
36
|
+
|
|
37
|
+
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
|
38
|
+
function wrapper({ children }: { children: React.ReactNode }) {
|
|
39
|
+
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
describe('RequireAuth × useAuthMachine(bootstrap 失败链路)', () => {
|
|
43
|
+
beforeEach(() => {
|
|
44
|
+
document.documentElement.lang = 'zh-CN';
|
|
45
|
+
window.localStorage.clear();
|
|
46
|
+
useAuthStore.setState({
|
|
47
|
+
user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
|
|
48
|
+
accessToken: 'token-xyz',
|
|
49
|
+
refreshToken: 'refresh-xyz',
|
|
50
|
+
tenants: [],
|
|
51
|
+
currentTenantId: 't1',
|
|
52
|
+
permissions: [],
|
|
53
|
+
isAuthenticated: true,
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
afterEach(() => {
|
|
58
|
+
cleanup();
|
|
59
|
+
useAuthStore.setState({
|
|
60
|
+
user: null,
|
|
61
|
+
accessToken: null,
|
|
62
|
+
refreshToken: null,
|
|
63
|
+
tenants: [],
|
|
64
|
+
currentTenantId: null,
|
|
65
|
+
permissions: [],
|
|
66
|
+
isAuthenticated: false,
|
|
67
|
+
});
|
|
68
|
+
window.localStorage.clear();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('权限/租户查询都失败 → 渲染「加载失败」而非空白,且不放行子路由', async () => {
|
|
72
|
+
render(
|
|
73
|
+
<RequireAuth>
|
|
74
|
+
<div data-testid="protected">受保护内容</div>
|
|
75
|
+
</RequireAuth>,
|
|
76
|
+
{ wrapper },
|
|
77
|
+
);
|
|
78
|
+
|
|
79
|
+
expect(await screen.findByText('加载失败')).toBeInTheDocument();
|
|
80
|
+
expect(screen.getByRole('button', { name: '重试' })).toBeInTheDocument();
|
|
81
|
+
expect(screen.queryByTestId('protected')).not.toBeInTheDocument();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -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:
|
|
4
|
+
// rows: 802 · source sha256: d1d69d0eedc43e211b89c0efa5ade53b95a0d2ff31ea706800ba29b04c97f20f
|
|
5
5
|
//
|
|
6
6
|
// 单一真源链:service-core/base/error/semantics.go(Go)→ errors.semantics.json → 本文件。
|
|
7
7
|
// ⚠️ 禁止在本文件或页面里手抄错误码分支:请消费 ERROR_SEMANTICS / UNPROVISIONED_CODES。
|
|
@@ -393,6 +393,7 @@ export const ERROR_SEMANTICS: Readonly<Record<number, ErrorSemantics>> = {
|
|
|
393
393
|
61000902: { code: 61000902, httpStatus: 410, class: 'gone', absence: '', uiObservation: 'expired', retryable: false, docsPath: '/errors/61000902' },
|
|
394
394
|
61000903: { code: 61000903, httpStatus: 409, class: 'conflict', absence: '', uiObservation: 'conflict', retryable: false, docsPath: '/errors/61000903' },
|
|
395
395
|
61000904: { code: 61000904, httpStatus: 400, class: 'invalid', absence: '', uiObservation: 'form_error', retryable: false, docsPath: '/errors/61000904' },
|
|
396
|
+
61000905: { code: 61000905, httpStatus: 403, class: 'forbidden', absence: '', uiObservation: 'forbidden', name: 'QR_LOGIN_TENANT_MISMATCH', retryable: false, docsPath: '/errors/61000905' },
|
|
396
397
|
61001001: { code: 61001001, httpStatus: 401, class: 'unauthorized', absence: '', uiObservation: 'session_expired', retryable: false, docsPath: '/errors/61001001' },
|
|
397
398
|
61001002: { code: 61001002, httpStatus: 429, class: 'limit', absence: '', uiObservation: 'rate_limited', retryable: true, docsPath: '/errors/61001002' },
|
|
398
399
|
61001003: { code: 61001003, httpStatus: 409, class: 'conflict', absence: '', uiObservation: 'conflict', retryable: false, docsPath: '/errors/61001003' },
|
|
@@ -862,8 +863,8 @@ export const UNPROVISIONED_CODES: ReadonlySet<number> = new Set([]);
|
|
|
862
863
|
export const EMPTY_STATE_CODES: ReadonlySet<number> = new Set([]);
|
|
863
864
|
|
|
864
865
|
export const ERROR_SEMANTICS_META = {
|
|
865
|
-
rowCount:
|
|
866
|
-
sourceSha256: '
|
|
866
|
+
rowCount: 802,
|
|
867
|
+
sourceSha256: 'd1d69d0eedc43e211b89c0efa5ade53b95a0d2ff31ea706800ba29b04c97f20f',
|
|
867
868
|
} as const;
|
|
868
869
|
|
|
869
870
|
/** 具名错误码常量(契约 name → code)。页面只消费常量,不写数字字面量。 */
|
|
@@ -875,6 +876,7 @@ export const ERROR_CODES = {
|
|
|
875
876
|
MFA_CODE_ALREADY_USED: 61000409,
|
|
876
877
|
MFA_ATTEMPTS_THROTTLED: 61000410,
|
|
877
878
|
MFA_AUTHENTICATOR_DISABLED: 61000411,
|
|
879
|
+
QR_LOGIN_TENANT_MISMATCH: 61000905,
|
|
878
880
|
} as const;
|
|
879
881
|
|
|
880
882
|
export type ErrorCodeName = keyof typeof ERROR_CODES;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @vitest-environment jsdom
|
|
2
2
|
import React from 'react';
|
|
3
3
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
4
|
-
import { renderHook, cleanup, waitFor } from '@testing-library/react';
|
|
4
|
+
import { renderHook, cleanup, waitFor, act } from '@testing-library/react';
|
|
5
5
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
6
6
|
|
|
7
7
|
// ============================================================
|
|
@@ -54,6 +54,7 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
|
|
|
54
54
|
beforeEach(() => {
|
|
55
55
|
vi.clearAllMocks();
|
|
56
56
|
resetAuthStore();
|
|
57
|
+
queryClient.clear();
|
|
57
58
|
mockQueries.perms = { data: undefined, isError: false };
|
|
58
59
|
mockQueries.tenants = { data: undefined, isError: false };
|
|
59
60
|
mockProfileAvatar.mockReset();
|
|
@@ -62,6 +63,7 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
|
|
|
62
63
|
|
|
63
64
|
afterEach(() => {
|
|
64
65
|
cleanup();
|
|
66
|
+
queryClient.clear();
|
|
65
67
|
resetAuthStore();
|
|
66
68
|
});
|
|
67
69
|
|
|
@@ -97,6 +99,18 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
|
|
|
97
99
|
expect(result.current).toBe('loading');
|
|
98
100
|
});
|
|
99
101
|
|
|
102
|
+
// P1-2 回归锁(2026-11-08 线上复现):权限/租户两个查询都失败时,
|
|
103
|
+
// 旧实现返回 'loading' ⇒ 状态机永停 bootstrap ⇒ RequireAuth 恒 render null
|
|
104
|
+
// ⇒ 后端 5xx 时整站白屏。必须返回 'error' 让守卫渲染可恢复错误页。
|
|
105
|
+
it('两个 bootstrap 查询都失败 → error(不得 loading)', () => {
|
|
106
|
+
useAuthStore.setState({ accessToken: 'token-xyz' });
|
|
107
|
+
mockQueries.perms = { data: undefined, isError: true };
|
|
108
|
+
mockQueries.tenants = { data: undefined, isError: true };
|
|
109
|
+
const { result } = renderHook(() => useBootstrap(), { wrapper });
|
|
110
|
+
expect(result.current).toBe('error');
|
|
111
|
+
expect(result.current).not.toBe('loading');
|
|
112
|
+
});
|
|
113
|
+
|
|
100
114
|
// U447:登录响应与 /auth/me 都不含 avatarUrl —— 启动必须补读一次 profile 头像,
|
|
101
115
|
// 否则换浏览器/新登录后顶栏头像恒为首字母。
|
|
102
116
|
it('U447:有会话 → 补读 /profile/avatar 并写回认证快照', async () => {
|
|
@@ -125,4 +139,51 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
|
|
|
125
139
|
await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalled());
|
|
126
140
|
expect(useAuthStore.getState().user?.avatarUrl).toBeUndefined();
|
|
127
141
|
});
|
|
142
|
+
|
|
143
|
+
// 首屏 avatar 3 次请求的回归锁:多个消费组件同时调 useBootstrap 时,
|
|
144
|
+
// 同一 userId+tenantId 只允许发一次 GET /profile/avatar。
|
|
145
|
+
it('U447:多个消费组件并发启动 → 头像只请求一次', async () => {
|
|
146
|
+
useAuthStore.setState({
|
|
147
|
+
accessToken: 'token-xyz',
|
|
148
|
+
user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
|
|
149
|
+
permissions: ['user.read'],
|
|
150
|
+
tenants: [{ id: 't1', name: 'demo', role: 'member' }],
|
|
151
|
+
});
|
|
152
|
+
let resolveAvatar!: (v: { avatarUrl: string }) => void;
|
|
153
|
+
mockProfileAvatar.mockImplementation(
|
|
154
|
+
() =>
|
|
155
|
+
new Promise<{ avatarUrl: string }>((resolve) => {
|
|
156
|
+
resolveAvatar = resolve;
|
|
157
|
+
}),
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
renderHook(() => useBootstrap(), { wrapper });
|
|
161
|
+
renderHook(() => useBootstrap(), { wrapper });
|
|
162
|
+
|
|
163
|
+
await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalledTimes(1));
|
|
164
|
+
resolveAvatar({ avatarUrl: 'https://cdn.example.com/b.png' });
|
|
165
|
+
await waitFor(() =>
|
|
166
|
+
expect(useAuthStore.getState().user?.avatarUrl).toBe('https://cdn.example.com/b.png'),
|
|
167
|
+
);
|
|
168
|
+
expect(mockProfileAvatar).toHaveBeenCalledTimes(1);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('切换租户 → 头像重新补读(缓存按 userId+tenantId 隔离)', async () => {
|
|
172
|
+
useAuthStore.setState({
|
|
173
|
+
accessToken: 'token-xyz',
|
|
174
|
+
user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
|
|
175
|
+
currentTenantId: 't1',
|
|
176
|
+
permissions: ['user.read'],
|
|
177
|
+
tenants: [{ id: 't1', name: 'demo', role: 'member' }],
|
|
178
|
+
});
|
|
179
|
+
mockProfileAvatar.mockResolvedValue({ avatarUrl: 'https://cdn.example.com/c.png' });
|
|
180
|
+
|
|
181
|
+
renderHook(() => useBootstrap(), { wrapper });
|
|
182
|
+
await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalledTimes(1));
|
|
183
|
+
|
|
184
|
+
act(() => {
|
|
185
|
+
useAuthStore.setState({ currentTenantId: 't2' });
|
|
186
|
+
});
|
|
187
|
+
await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalledTimes(2));
|
|
188
|
+
});
|
|
128
189
|
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
import { useEffect } from 'react';
|
|
4
|
+
import { useQueryClient } from '@tanstack/react-query';
|
|
4
5
|
import { useAuthStore } from '../auth/store';
|
|
5
6
|
import { AuthService } from '../auth/service';
|
|
6
7
|
import { usePermissionsQuery, useTenantsQuery } from '../auth/auth-queries';
|
|
@@ -52,13 +53,24 @@ export function useBootstrap(): BootstrapState {
|
|
|
52
53
|
// 失败静默(展示层回落首字母,不影响任何业务流程)。
|
|
53
54
|
// 用动态 import 引生成客户端:generated/api 反向 import '@autional/shared',
|
|
54
55
|
// 静态导入会在包入口形成循环,动态导入等入口初始化完再求值。
|
|
56
|
+
// React Query 负责去重与缓存:同一 userId+tenantId 并发/重复挂载只发一次请求(5 分钟缓存)。
|
|
57
|
+
const queryClient = useQueryClient();
|
|
58
|
+
const userId = useAuthStore((s) => s.user?.id);
|
|
55
59
|
useEffect(() => {
|
|
56
60
|
if (!hasToken) return;
|
|
57
61
|
let cancelled = false;
|
|
58
|
-
void
|
|
59
|
-
.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
+
void queryClient
|
|
63
|
+
.fetchQuery({
|
|
64
|
+
queryKey: ['profile-avatar', userId ?? '', currentTenantId ?? ''],
|
|
65
|
+
queryFn: async () => {
|
|
66
|
+
const { profileAvatar } = await import('../generated/api');
|
|
67
|
+
const res = await profileAvatar();
|
|
68
|
+
return ((res as { avatarUrl?: string } | undefined)?.avatarUrl ?? '').trim() || null;
|
|
69
|
+
},
|
|
70
|
+
staleTime: 5 * 60_000,
|
|
71
|
+
retry: false, // 头像失败静默,不重试
|
|
72
|
+
})
|
|
73
|
+
.then((avatarUrl) => {
|
|
62
74
|
if (cancelled || !avatarUrl) return;
|
|
63
75
|
const current = useAuthStore.getState().user;
|
|
64
76
|
if (current && current.avatarUrl !== avatarUrl) {
|
|
@@ -71,7 +83,7 @@ export function useBootstrap(): BootstrapState {
|
|
|
71
83
|
return () => {
|
|
72
84
|
cancelled = true;
|
|
73
85
|
};
|
|
74
|
-
}, [hasToken]);
|
|
86
|
+
}, [hasToken, userId, currentTenantId, queryClient]);
|
|
75
87
|
|
|
76
88
|
// 无会话 = 无数据可引导:返回 'idle',登录交棒由 RequireAuth/守卫决策(见上)。
|
|
77
89
|
// 不得返回 'loading':Layout 消费者(platform-console)以 bootstrap==='loading'
|
|
@@ -90,10 +102,13 @@ export function useBootstrap(): BootstrapState {
|
|
|
90
102
|
return 'ready';
|
|
91
103
|
}
|
|
92
104
|
|
|
93
|
-
// 两个请求都失败
|
|
94
|
-
//
|
|
105
|
+
// 两个请求都失败 —— 语义是「启动失败」,不是「仍在加载」。
|
|
106
|
+
// 旧实现返回 'loading'(原注释:防重渲染循环),使状态机永停 bootstrap、
|
|
107
|
+
// RequireAuth 恒 render null ⇒ 后端 5xx 时整站白屏(P1-2,2026-11-08 线上复现:
|
|
108
|
+
// 四个 bootstrap 接口全 500 → #root 只剩空容器,无提示/无重试)。
|
|
109
|
+
// 返回 'error' 是稳定值(不会抖动),由 RequireAuth 渲染可恢复错误页。
|
|
95
110
|
if (permsQuery.isError && tentsQuery.isError) {
|
|
96
|
-
return '
|
|
111
|
+
return 'error';
|
|
97
112
|
}
|
|
98
113
|
|
|
99
114
|
// 等待中
|