@autional/shared 0.1.0-rc.68 → 0.1.0-rc.70
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/auth/__tests__/oauth-callback-error-codes.test.ts +4 -1
- package/src/auth/__tests__/oauth-login-user-resolution.test.ts +4 -1
- package/src/auth/__tests__/oauth-login.handoff.test.ts +210 -0
- package/src/auth/__tests__/oauth-portal-scope-upgrade.test.ts +108 -0
- package/src/auth/oauth-login.ts +242 -19
- package/src/components/RequireAuth.tsx +31 -1
- package/src/components/__tests__/RequireAuth.adversarial.test.tsx +3 -1
- package/src/components/__tests__/RequireAuth.bootstrap-error.test.tsx +5 -1
- package/src/components/__tests__/RequireAuth.bootstrap-integration.test.tsx +5 -1
- package/src/components/__tests__/RequireAuth.scope-upgrade.test.tsx +157 -0
- package/src/components/__tests__/RequireAuth.stay.test.tsx +3 -1
- package/src/components/__tests__/RequireAuth.test.tsx +4 -1
- package/src/hooks/useAuth.ts +22 -5
- package/src/index.ts +3 -0
package/package.json
CHANGED
|
@@ -10,7 +10,10 @@ const { mockPost } = vi.hoisted(() => ({ mockPost: vi.fn() }));
|
|
|
10
10
|
vi.mock('../../api/client', () => ({ apiClient: { post: mockPost, get: vi.fn() } }));
|
|
11
11
|
vi.mock('../store', () => ({ loginWithTokens: vi.fn() }));
|
|
12
12
|
vi.mock('../service', () => ({ AuthService: { updateCurrentTenant: vi.fn() } }));
|
|
13
|
-
vi.mock('../oauth-client-id-store', () => ({
|
|
13
|
+
vi.mock('../oauth-client-id-store', () => ({
|
|
14
|
+
persistOAuthClientId: vi.fn(),
|
|
15
|
+
getPersistedOAuthClientId: () => '',
|
|
16
|
+
}));
|
|
14
17
|
vi.mock('../auth-trace', () => ({ traceRedirect: vi.fn() }));
|
|
15
18
|
vi.mock('../../config', () => ({ getPortalUrl: () => 'https://auth.example.com' }));
|
|
16
19
|
|
|
@@ -20,7 +20,10 @@ const { mockPost, mockGet, mockLoginWithTokens, mockUpdateCurrentTenant, mockPer
|
|
|
20
20
|
vi.mock('../../api/client', () => ({ apiClient: { post: mockPost, get: mockGet } }));
|
|
21
21
|
vi.mock('../store', () => ({ loginWithTokens: mockLoginWithTokens }));
|
|
22
22
|
vi.mock('../service', () => ({ AuthService: { updateCurrentTenant: mockUpdateCurrentTenant } }));
|
|
23
|
-
vi.mock('../oauth-client-id-store', () => ({
|
|
23
|
+
vi.mock('../oauth-client-id-store', () => ({
|
|
24
|
+
persistOAuthClientId: mockPersistCid,
|
|
25
|
+
getPersistedOAuthClientId: () => '',
|
|
26
|
+
}));
|
|
24
27
|
vi.mock('../auth-trace', () => ({ traceRedirect: mockTrace }));
|
|
25
28
|
vi.mock('../../config', () => ({ getPortalUrl: () => 'https://auth.example.com' }));
|
|
26
29
|
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
// ============================================================
|
|
3
|
+
// F-008 回归锁:OAuth 交棒(state + PKCE verifier)跨浏览上下文兜底
|
|
4
|
+
//
|
|
5
|
+
// 症状:交棒只写 sessionStorage → 回调页落在**另一个浏览上下文**(PWA standalone 被系统
|
|
6
|
+
// 浏览器接管 / 新标签 / 安卓 Custom Tab)时 sessionStorage 为空 ⇒ `oauth.state_mismatch`,
|
|
7
|
+
// 回调页不换码。修法:同时写 localStorage 兜底(≤5min TTL、origin 绑定、读后双删)。
|
|
8
|
+
// 本文件锁死:兜底能救回登录,但**不放松** CSRF 比对(不匹配照样抛 state_mismatch)。
|
|
9
|
+
// ============================================================
|
|
10
|
+
|
|
11
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
12
|
+
|
|
13
|
+
const {
|
|
14
|
+
mockPost,
|
|
15
|
+
mockGet,
|
|
16
|
+
mockLoginWithTokens,
|
|
17
|
+
mockUpdateCurrentTenant,
|
|
18
|
+
mockPersistCid,
|
|
19
|
+
mockTrace,
|
|
20
|
+
mockGeneratePKCE,
|
|
21
|
+
} = vi.hoisted(() => ({
|
|
22
|
+
mockPost: vi.fn(),
|
|
23
|
+
mockGet: vi.fn(),
|
|
24
|
+
mockLoginWithTokens: vi.fn(),
|
|
25
|
+
mockUpdateCurrentTenant: vi.fn(),
|
|
26
|
+
mockPersistCid: vi.fn(),
|
|
27
|
+
mockTrace: vi.fn(),
|
|
28
|
+
mockGeneratePKCE: vi.fn(() => Promise.resolve({ verifier: 'verifier-1', challenge: 'challenge-1' })),
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
vi.mock('../../api/client', () => ({ apiClient: { post: mockPost, get: mockGet } }));
|
|
32
|
+
vi.mock('../store', () => ({ loginWithTokens: mockLoginWithTokens }));
|
|
33
|
+
vi.mock('../service', () => ({ AuthService: { updateCurrentTenant: mockUpdateCurrentTenant } }));
|
|
34
|
+
vi.mock('../oauth-client-id-store', () => ({
|
|
35
|
+
persistOAuthClientId: mockPersistCid,
|
|
36
|
+
// 发起时已落 localStorage(跨上下文时 sessionStorage 里没有 client_id)
|
|
37
|
+
getPersistedOAuthClientId: () => 'cid-1',
|
|
38
|
+
}));
|
|
39
|
+
vi.mock('../auth-trace', () => ({ traceRedirect: mockTrace }));
|
|
40
|
+
vi.mock('../pkce', () => ({ generatePKCE: () => mockGeneratePKCE() }));
|
|
41
|
+
vi.mock('../../config', () => ({ getPortalUrl: () => 'https://auth.example.com' }));
|
|
42
|
+
|
|
43
|
+
import { initiateOAuthLogin, handleOAuthCallback, OAuthCallbackError } from '../oauth-login';
|
|
44
|
+
|
|
45
|
+
const HANDOFF_KEY = 'oauth_handoff';
|
|
46
|
+
const ORIGIN = window.location.origin;
|
|
47
|
+
const TTL_MS = 5 * 60 * 1000;
|
|
48
|
+
|
|
49
|
+
function jwt(payload: Record<string, unknown>): string {
|
|
50
|
+
return `h.${btoa(JSON.stringify(payload))}.s`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type StoredRecord = {
|
|
54
|
+
v?: number;
|
|
55
|
+
state?: string;
|
|
56
|
+
verifier?: string;
|
|
57
|
+
origin?: string;
|
|
58
|
+
exp?: number;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
function readRecord(): StoredRecord | null {
|
|
62
|
+
const raw = localStorage.getItem(HANDOFF_KEY);
|
|
63
|
+
return raw ? (JSON.parse(raw) as StoredRecord) : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function writeRecord(rec: StoredRecord): void {
|
|
67
|
+
localStorage.setItem(HANDOFF_KEY, JSON.stringify(rec));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function useCallbackUrl(params: { code?: string; state?: unknown }): void {
|
|
71
|
+
const q = new URLSearchParams();
|
|
72
|
+
if (params.code) q.set('code', params.code);
|
|
73
|
+
if (params.state !== undefined) q.set('state', JSON.stringify(params.state));
|
|
74
|
+
window.history.replaceState({}, '', `/?${q.toString()}`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function codeOf(promise: Promise<unknown>): Promise<string> {
|
|
78
|
+
try {
|
|
79
|
+
await promise;
|
|
80
|
+
throw new Error('expected rejection');
|
|
81
|
+
} catch (e) {
|
|
82
|
+
expect(e).toBeInstanceOf(OAuthCallbackError);
|
|
83
|
+
return (e as OAuthCallbackError).code;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function tokenBody(): URLSearchParams {
|
|
88
|
+
expect(mockPost).toHaveBeenCalledTimes(1);
|
|
89
|
+
return new URLSearchParams(String(mockPost.mock.calls[0][1]));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
beforeEach(() => {
|
|
93
|
+
vi.clearAllMocks();
|
|
94
|
+
sessionStorage.clear();
|
|
95
|
+
localStorage.clear();
|
|
96
|
+
window.history.replaceState({}, '', '/');
|
|
97
|
+
mockPost.mockResolvedValue({
|
|
98
|
+
data: { access_token: jwt({ sub: 'u-1', email: 'u@example.com' }), refresh_token: 'rt-1' },
|
|
99
|
+
});
|
|
100
|
+
mockGet.mockResolvedValue({ data: {} });
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
describe('F-008 交棒写入(sessionStorage 快路径 + localStorage 兜底)', () => {
|
|
104
|
+
it('发起时同时写两处:sessionStorage 保留 string,localStorage 记录带 exp(≤5min)+origin,无 token', async () => {
|
|
105
|
+
await initiateOAuthLogin('cid-1', 'https://user.example.com/x');
|
|
106
|
+
|
|
107
|
+
const csrf = sessionStorage.getItem('oauth_state');
|
|
108
|
+
expect(csrf).toBeTruthy();
|
|
109
|
+
expect(sessionStorage.getItem('oauth_pkce_verifier')).toBe('verifier-1');
|
|
110
|
+
|
|
111
|
+
const rec = readRecord();
|
|
112
|
+
expect(rec?.v).toBe(1);
|
|
113
|
+
expect(rec?.state).toBe(csrf);
|
|
114
|
+
expect(rec?.verifier).toBe('verifier-1');
|
|
115
|
+
expect(rec?.origin).toBe(ORIGIN);
|
|
116
|
+
// TTL ≤ 5 分钟(留 1s 余量吸收执行耗时)
|
|
117
|
+
expect(Number(rec?.exp) - Date.now()).toBeLessThanOrEqual(TTL_MS);
|
|
118
|
+
expect(Number(rec?.exp) - Date.now()).toBeGreaterThan(TTL_MS - 5000);
|
|
119
|
+
// 值里不得含任何令牌字段
|
|
120
|
+
expect(Object.keys(rec ?? {}).sort()).toEqual(['exp', 'origin', 'state', 'v', 'verifier']);
|
|
121
|
+
expect(JSON.stringify(rec)).not.toMatch(/token|access_token|refresh_token/i);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe('F-008 交棒读取(回调页)', () => {
|
|
126
|
+
it('同上下文:仅 sessionStorage 有值 → 兑换成功(既有行为不变)', async () => {
|
|
127
|
+
sessionStorage.setItem('oauth_state', 'csrf-A');
|
|
128
|
+
sessionStorage.setItem('oauth_pkce_verifier', 'verifier-1');
|
|
129
|
+
sessionStorage.setItem('oauth_client_id', 'cid-1');
|
|
130
|
+
useCallbackUrl({ code: 'c1', state: { csrf: 'csrf-A', redirect: '/dash' } });
|
|
131
|
+
|
|
132
|
+
await handleOAuthCallback();
|
|
133
|
+
|
|
134
|
+
const body = tokenBody();
|
|
135
|
+
expect(body.get('code_verifier')).toBe('verifier-1');
|
|
136
|
+
expect(body.get('client_id')).toBe('cid-1');
|
|
137
|
+
expect(mockLoginWithTokens).toHaveBeenCalledTimes(1);
|
|
138
|
+
expect(mockTrace.mock.calls.at(-1)?.[0]).toBe('/dash');
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('跨浏览上下文:sessionStorage 为空、localStorage 兜底未过期 → 兑换成功', async () => {
|
|
142
|
+
// 先在本上下文发起(两处都写),再清掉 sessionStorage 模拟「另一个浏览上下文」
|
|
143
|
+
await initiateOAuthLogin('cid-1', 'https://user.example.com/x');
|
|
144
|
+
const csrf = String(readRecord()?.state);
|
|
145
|
+
sessionStorage.clear();
|
|
146
|
+
|
|
147
|
+
useCallbackUrl({ code: 'c1', state: { csrf } });
|
|
148
|
+
await handleOAuthCallback();
|
|
149
|
+
|
|
150
|
+
const body = tokenBody();
|
|
151
|
+
expect(body.get('code_verifier')).toBe('verifier-1');
|
|
152
|
+
// client_id 跨上下文来自 localStorage 持久值(发起时 persistOAuthClientId)
|
|
153
|
+
expect(body.get('client_id')).toBe('cid-1');
|
|
154
|
+
expect(mockLoginWithTokens).toHaveBeenCalledTimes(1);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('兜底命中后两处都被清除(防重放)', async () => {
|
|
158
|
+
writeRecord({ v: 1, state: 'csrf-A', verifier: 'verifier-1', origin: ORIGIN, exp: Date.now() + TTL_MS });
|
|
159
|
+
useCallbackUrl({ code: 'c1', state: { csrf: 'csrf-A' } });
|
|
160
|
+
|
|
161
|
+
await handleOAuthCallback();
|
|
162
|
+
|
|
163
|
+
expect(sessionStorage.getItem('oauth_state')).toBeNull();
|
|
164
|
+
expect(sessionStorage.getItem('oauth_pkce_verifier')).toBeNull();
|
|
165
|
+
expect(localStorage.getItem(HANDOFF_KEY)).toBeNull();
|
|
166
|
+
|
|
167
|
+
// 二次兑换(同一 state 再来一次)→ 已无交棒可用,按不匹配拒绝
|
|
168
|
+
mockPost.mockClear();
|
|
169
|
+
useCallbackUrl({ code: 'c2', state: { csrf: 'csrf-A' } });
|
|
170
|
+
expect(await codeOf(handleOAuthCallback())).toBe('oauth.state_mismatch');
|
|
171
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
it('localStorage 记录已过期 → oauth.state_mismatch(不放行)', async () => {
|
|
175
|
+
writeRecord({
|
|
176
|
+
v: 1,
|
|
177
|
+
state: 'csrf-A',
|
|
178
|
+
verifier: 'verifier-1',
|
|
179
|
+
origin: ORIGIN,
|
|
180
|
+
exp: Date.now() - 1000,
|
|
181
|
+
});
|
|
182
|
+
useCallbackUrl({ code: 'c1', state: { csrf: 'csrf-A' } });
|
|
183
|
+
|
|
184
|
+
expect(await codeOf(handleOAuthCallback())).toBe('oauth.state_mismatch');
|
|
185
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('origin 不匹配 → 不认(oauth.state_mismatch),且不动别人的记录', async () => {
|
|
189
|
+
writeRecord({
|
|
190
|
+
v: 1,
|
|
191
|
+
state: 'csrf-A',
|
|
192
|
+
verifier: 'verifier-1',
|
|
193
|
+
origin: 'https://other.example.com',
|
|
194
|
+
exp: Date.now() + TTL_MS,
|
|
195
|
+
});
|
|
196
|
+
useCallbackUrl({ code: 'c1', state: { csrf: 'csrf-A' } });
|
|
197
|
+
|
|
198
|
+
expect(await codeOf(handleOAuthCallback())).toBe('oauth.state_mismatch');
|
|
199
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
200
|
+
expect(readRecord()?.origin).toBe('https://other.example.com');
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it('兜底记录有效但回调 state 不匹配 → 仍抛 oauth.state_mismatch(CSRF 未放松)', async () => {
|
|
204
|
+
writeRecord({ v: 1, state: 'csrf-A', verifier: 'verifier-1', origin: ORIGIN, exp: Date.now() + TTL_MS });
|
|
205
|
+
useCallbackUrl({ code: 'c1', state: { csrf: 'csrf-B' } });
|
|
206
|
+
|
|
207
|
+
expect(await codeOf(handleOAuthCallback())).toBe('oauth.state_mismatch');
|
|
208
|
+
expect(mockPost).not.toHaveBeenCalled();
|
|
209
|
+
});
|
|
210
|
+
});
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
OAUTH_LOGIN_SCOPES,
|
|
4
|
+
PORTAL_LOGIN_SCOPES,
|
|
5
|
+
scopesCover,
|
|
6
|
+
tokenNeedsPortalScopeUpgrade,
|
|
7
|
+
} from '../oauth-login';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 回归锁(2026-11-14):用户门户「短信验证 → 验证并开启」403
|
|
11
|
+
* `token scope does not allow this operation`。
|
|
12
|
+
*
|
|
13
|
+
* 根因:门户登录只申请基础档(read),而 MFA 写接口强制 `mfa:write`;服务端
|
|
14
|
+
* `oauth_clients.scopes` 早已为全部首方门户 client 登记完整 scope,缺的只是「申请」。
|
|
15
|
+
* 本文件钉住:① 门户档覆盖全部 enforced 写 scope;② 旧令牌(仅基础档)判定为需升级;
|
|
16
|
+
* ③ 会话/模拟令牌不得被升级流程误伤。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
function b64url(value: unknown): string {
|
|
20
|
+
return btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 构造只含载荷的测试 JWT(签名段不验签,解码侧只读载荷)。 */
|
|
24
|
+
function makeJwt(payload: Record<string, unknown>): string {
|
|
25
|
+
return `${b64url({ alg: 'RS256', typ: 'JWT' })}.${b64url(payload)}.sig`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** OAuth 访问令牌载荷形态(service-oauth createJWTAccessToken:scope/client_id 在 custom 内)。 */
|
|
29
|
+
function oauthToken(scope: string, extra: Record<string, unknown> = {}): string {
|
|
30
|
+
return makeJwt({
|
|
31
|
+
sub: 'user-1',
|
|
32
|
+
tenant_id: 'tenant-1',
|
|
33
|
+
type: 'access',
|
|
34
|
+
custom: { scope, client_id: '01AR0000000000000000000004', ...extra },
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
describe('PORTAL_LOGIN_SCOPES(门户档)', () => {
|
|
39
|
+
const base = OAUTH_LOGIN_SCOPES.split(' ').filter(Boolean);
|
|
40
|
+
const portal = PORTAL_LOGIN_SCOPES.split(' ').filter(Boolean);
|
|
41
|
+
|
|
42
|
+
it('保留基础档全部项(OIDC + read)', () => {
|
|
43
|
+
for (const s of base) expect(portal).toContain(s);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('覆盖服务端 enforced 的全部写 scope', () => {
|
|
47
|
+
for (const s of ['write', 'mfa:write', 'oauth:write', 'billing:write', 'wallet:write', 'point:write', 'pay:write']) {
|
|
48
|
+
expect(portal).toContain(s);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('无空项、无重复', () => {
|
|
53
|
+
expect(PORTAL_LOGIN_SCOPES.trim()).toBe(PORTAL_LOGIN_SCOPES);
|
|
54
|
+
expect(new Set(portal).size).toBe(portal.length);
|
|
55
|
+
expect(portal.every(Boolean)).toBe(true);
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('scopesCover', () => {
|
|
60
|
+
it('覆盖全部要求 → true;缺任一项 → false', () => {
|
|
61
|
+
expect(scopesCover('read write', 'read')).toBe(true);
|
|
62
|
+
expect(scopesCover('read write', 'read write')).toBe(true);
|
|
63
|
+
expect(scopesCover('read', 'read write')).toBe(false);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('`*` 通配覆盖一切(首方/session 令牌语义)', () => {
|
|
67
|
+
expect(scopesCover('read *', 'mfa:write')).toBe(true);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('空/缺省 granted 一律不覆盖', () => {
|
|
71
|
+
expect(scopesCover('', 'read')).toBe(false);
|
|
72
|
+
expect(scopesCover(null, 'read')).toBe(false);
|
|
73
|
+
expect(scopesCover(undefined, 'read')).toBe(false);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
describe('tokenNeedsPortalScopeUpgrade', () => {
|
|
78
|
+
it('无令牌 / 非 JWT → 不需要升级', () => {
|
|
79
|
+
expect(tokenNeedsPortalScopeUpgrade(null)).toBe(false);
|
|
80
|
+
expect(tokenNeedsPortalScopeUpgrade(undefined)).toBe(false);
|
|
81
|
+
expect(tokenNeedsPortalScopeUpgrade('token-xyz')).toBe(false);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('会话/SAML 直签令牌(无 OAuth client_id)→ 不参与升级', () => {
|
|
85
|
+
const sessionToken = makeJwt({ sub: 'u', type: 'access', custom: { scope: 'read *' } });
|
|
86
|
+
expect(tokenNeedsPortalScopeUpgrade(sessionToken)).toBe(false);
|
|
87
|
+
// 无 custom 段的令牌同理
|
|
88
|
+
expect(tokenNeedsPortalScopeUpgrade(makeJwt({ sub: 'u', type: 'access' }))).toBe(false);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('OAuth 令牌仅基础档 → 需要升级(2026-11-14 事故形态)', () => {
|
|
92
|
+
expect(tokenNeedsPortalScopeUpgrade(oauthToken(OAUTH_LOGIN_SCOPES))).toBe(true);
|
|
93
|
+
// 空 scope 的 OAuth 令牌同样需要(写接口必 403)
|
|
94
|
+
expect(tokenNeedsPortalScopeUpgrade(oauthToken(''))).toBe(true);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('OAuth 令牌已是门户档 → 不需要升级(升级后条件自然转假,不循环)', () => {
|
|
98
|
+
expect(tokenNeedsPortalScopeUpgrade(oauthToken(PORTAL_LOGIN_SCOPES))).toBe(false);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it('OAuth 令牌带 `*` 通配 → 不升级', () => {
|
|
102
|
+
expect(tokenNeedsPortalScopeUpgrade(oauthToken('read *'))).toBe(false);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('模拟会话(is_imp)→ 绝不升级(不得换成本人令牌)', () => {
|
|
106
|
+
expect(tokenNeedsPortalScopeUpgrade(oauthToken(OAUTH_LOGIN_SCOPES, { is_imp: true }))).toBe(false);
|
|
107
|
+
});
|
|
108
|
+
});
|
package/src/auth/oauth-login.ts
CHANGED
|
@@ -13,7 +13,7 @@ import { loginWithTokens } from './store';
|
|
|
13
13
|
import { AuthService } from './service';
|
|
14
14
|
import { generatePKCE } from './pkce';
|
|
15
15
|
import { getPortalUrl } from '../config';
|
|
16
|
-
import { persistOAuthClientId } from './oauth-client-id-store';
|
|
16
|
+
import { getPersistedOAuthClientId, persistOAuthClientId } from './oauth-client-id-store';
|
|
17
17
|
import { traceRedirect } from './auth-trace';
|
|
18
18
|
import { decodeJwtPayload } from './jwt-payload';
|
|
19
19
|
import type { User } from '../types';
|
|
@@ -32,6 +32,152 @@ const SK = {
|
|
|
32
32
|
CID: 'oauth_client_id',
|
|
33
33
|
};
|
|
34
34
|
|
|
35
|
+
// ============================================================
|
|
36
|
+
// F-008:OAuth 交棒(state + PKCE verifier)跨浏览上下文兜底
|
|
37
|
+
//
|
|
38
|
+
// 只写 sessionStorage 时,回调页一旦落在**另一个浏览上下文**就必然读到空值 ⇒
|
|
39
|
+
// `oauth.state_mismatch`(回调页不换码、停在错误页)。触发场景都是推送深链的常见形态:
|
|
40
|
+
// - PWA standalone(桌面/安卓 TWA)被系统浏览器打开
|
|
41
|
+
// - 登录链接在**新标签**打开(target=_blank / 系统「在浏览器中打开」)
|
|
42
|
+
// - 安卓 Custom Tab / iOS SFSafariViewController(独立 sessionStorage)
|
|
43
|
+
// sessionStorage 是 per-context 的,localStorage 才是同源跨上下文共享的。
|
|
44
|
+
//
|
|
45
|
+
// 因此:**同时**写两处 —— sessionStorage(快路径,既有行为不变)、localStorage(兜底);
|
|
46
|
+
// 兜底记录自带 `exp`(≤5 分钟)与 `origin` 绑定,读取时校验;**命中即双删**(防重放:
|
|
47
|
+
// 一条交棒只允许兑换一次 code)。值里只有 state/verifier + 时间戳,**不含任何 token**。
|
|
48
|
+
//
|
|
49
|
+
// 安全语义不变:state 仍与回调参数强比对,不匹配照样抛 `oauth.state_mismatch`;
|
|
50
|
+
// 兜底只解决「读不到」,不解决「不匹配」——严格性没有放松。
|
|
51
|
+
// ============================================================
|
|
52
|
+
|
|
53
|
+
/** localStorage 兜底记录的键(与 sessionStorage 的 SK.STATE/SK.PKCE 分离,便于整体校验/清理) */
|
|
54
|
+
const HANDOFF_KEY = 'oauth_handoff';
|
|
55
|
+
/** 兜底有效期:5 分钟(跳去认证中心 → 输密码/短信 → 回跳的合理上限) */
|
|
56
|
+
const HANDOFF_TTL_MS = 5 * 60 * 1000;
|
|
57
|
+
|
|
58
|
+
interface OAuthHandoff {
|
|
59
|
+
state: string;
|
|
60
|
+
verifier: string;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
interface StoredHandoff extends OAuthHandoff {
|
|
64
|
+
/** 记录版本,未来改结构时可直接判定旧记录无效 */
|
|
65
|
+
v: 1;
|
|
66
|
+
/** 发起方 origin(同源跨上下文才认;防止同 origin 其它部署/子应用的残留被误用) */
|
|
67
|
+
origin: string;
|
|
68
|
+
/** 过期时间戳(ms) */
|
|
69
|
+
exp: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseStoredHandoff(raw: string | null): StoredHandoff | null {
|
|
73
|
+
if (!raw) return null;
|
|
74
|
+
try {
|
|
75
|
+
const v = JSON.parse(raw) as Partial<StoredHandoff> | null;
|
|
76
|
+
if (!v || typeof v !== 'object') return null;
|
|
77
|
+
if (v.v !== 1) return null;
|
|
78
|
+
if (typeof v.state !== 'string' || typeof v.verifier !== 'string') return null;
|
|
79
|
+
if (typeof v.origin !== 'string' || typeof v.exp !== 'number') return null;
|
|
80
|
+
return { v: 1, state: v.state, verifier: v.verifier, origin: v.origin, exp: v.exp };
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 写入交棒:sessionStorage(快路径)+ localStorage(跨上下文兜底)。
|
|
88
|
+
* 存储不可用(隐私模式 / 配额满)时静默降级,绝不让登录流程抛错。
|
|
89
|
+
*/
|
|
90
|
+
function saveHandoff(origin: string, value: OAuthHandoff): void {
|
|
91
|
+
if (typeof window === 'undefined') return;
|
|
92
|
+
const state = value.state || '';
|
|
93
|
+
const verifier = value.verifier || '';
|
|
94
|
+
try {
|
|
95
|
+
if (state) sessionStorage.setItem(SK.STATE, state);
|
|
96
|
+
if (verifier) sessionStorage.setItem(SK.PKCE, verifier);
|
|
97
|
+
} catch {
|
|
98
|
+
/* ignore */
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const record: StoredHandoff = {
|
|
102
|
+
v: 1,
|
|
103
|
+
state,
|
|
104
|
+
verifier,
|
|
105
|
+
origin,
|
|
106
|
+
exp: Date.now() + HANDOFF_TTL_MS,
|
|
107
|
+
};
|
|
108
|
+
localStorage.setItem(HANDOFF_KEY, JSON.stringify(record));
|
|
109
|
+
} catch {
|
|
110
|
+
/* ignore */
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 读取交棒:先 sessionStorage(同上下文),未命中再读 localStorage 兜底
|
|
116
|
+
* (校验 exp 未过期 + origin 匹配)。**命中即双删**(防重放)。
|
|
117
|
+
* 永不抛错;读不到时返回空串,交由调用方按既有逻辑抛 `state_mismatch` / `pkce_cleared`。
|
|
118
|
+
*/
|
|
119
|
+
function loadHandoff(origin: string): OAuthHandoff {
|
|
120
|
+
if (typeof window === 'undefined') return { state: '', verifier: '' };
|
|
121
|
+
|
|
122
|
+
let state = '';
|
|
123
|
+
let verifier = '';
|
|
124
|
+
try {
|
|
125
|
+
state = sessionStorage.getItem(SK.STATE) || '';
|
|
126
|
+
verifier = sessionStorage.getItem(SK.PKCE) || '';
|
|
127
|
+
} catch {
|
|
128
|
+
/* ignore */
|
|
129
|
+
}
|
|
130
|
+
if (state || verifier) {
|
|
131
|
+
clearHandoff(origin);
|
|
132
|
+
return { state, verifier };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let raw: string | null = null;
|
|
136
|
+
try {
|
|
137
|
+
raw = localStorage.getItem(HANDOFF_KEY);
|
|
138
|
+
} catch {
|
|
139
|
+
raw = null;
|
|
140
|
+
}
|
|
141
|
+
if (!raw) return { state: '', verifier: '' };
|
|
142
|
+
|
|
143
|
+
const rec = parseStoredHandoff(raw);
|
|
144
|
+
if (!rec) {
|
|
145
|
+
// 坏记录:直接清掉,避免每次回调都重复解析
|
|
146
|
+
clearHandoff(origin);
|
|
147
|
+
return { state: '', verifier: '' };
|
|
148
|
+
}
|
|
149
|
+
if (rec.origin !== origin) {
|
|
150
|
+
// 同源其它部署(多站点共用 localhost / 多 BASE_PATH)留下的交棒:不用也不动
|
|
151
|
+
return { state: '', verifier: '' };
|
|
152
|
+
}
|
|
153
|
+
if (Date.now() > rec.exp) {
|
|
154
|
+
clearHandoff(origin);
|
|
155
|
+
return { state: '', verifier: '' };
|
|
156
|
+
}
|
|
157
|
+
clearHandoff(origin);
|
|
158
|
+
return { state: rec.state, verifier: rec.verifier };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 清除交棒:两处都删(state/verifier)。只清属于本 origin 的 localStorage 记录。 */
|
|
162
|
+
function clearHandoff(origin: string): void {
|
|
163
|
+
if (typeof window === 'undefined') return;
|
|
164
|
+
try {
|
|
165
|
+
sessionStorage.removeItem(SK.STATE);
|
|
166
|
+
sessionStorage.removeItem(SK.PKCE);
|
|
167
|
+
} catch {
|
|
168
|
+
/* ignore */
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
const raw = localStorage.getItem(HANDOFF_KEY);
|
|
172
|
+
if (!raw) return;
|
|
173
|
+
const rec = parseStoredHandoff(raw);
|
|
174
|
+
// 解析失败 = 坏记录,一并清掉;origin 不符(别的部署的进行中交棒)则保留
|
|
175
|
+
if (!rec || rec.origin === origin) localStorage.removeItem(HANDOFF_KEY);
|
|
176
|
+
} catch {
|
|
177
|
+
/* ignore */
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
35
181
|
/**
|
|
36
182
|
* 第一方门户登录申请的 scope —— **单一真源**。
|
|
37
183
|
*
|
|
@@ -60,6 +206,63 @@ export function withOAuthScopes(...extra: string[]): string {
|
|
|
60
206
|
return out.join(' ');
|
|
61
207
|
}
|
|
62
208
|
|
|
209
|
+
/**
|
|
210
|
+
* 第一方门户登录申请的**完整 scope 档**(基础档 + 业务写能力)。
|
|
211
|
+
*
|
|
212
|
+
* 2026-11-14 事故:用户门户「短信验证 → 验证并开启」返回 403
|
|
213
|
+
* `token scope does not allow this operation` —— 登录只申请了 `read`,而 MFA 写接口自
|
|
214
|
+
* 2026-11-06 起强制 `mfa:write`。同类受影响的还有通知流 stream-ticket(`write`)、
|
|
215
|
+
* 社交账号绑定/解绑与授权撤销(`oauth:write`)、钱包/积分/支付/账单写(`*:write`)。
|
|
216
|
+
*
|
|
217
|
+
* 服务端 `oauth_clients.scopes` 已为全部首方门户 client(9 个固定 client +
|
|
218
|
+
* 全部租户 Default Client)登记了这套 scope;缺的一直只是「登录时申请」这一步。
|
|
219
|
+
* 认证器 PWA 另有更窄的档位(`withOAuthScopes('write')`,见 ADR-027 D2),不得使用本常量。
|
|
220
|
+
*/
|
|
221
|
+
export const PORTAL_LOGIN_SCOPES = withOAuthScopes(
|
|
222
|
+
'write',
|
|
223
|
+
'wallet:write',
|
|
224
|
+
'point:write',
|
|
225
|
+
'pay:write',
|
|
226
|
+
'billing:write',
|
|
227
|
+
'oauth:write',
|
|
228
|
+
'mfa:write',
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
/** granted 是否覆盖 required 要求的全部 scope(空格分隔;`*` 通配覆盖一切)。 */
|
|
232
|
+
export function scopesCover(granted: string | null | undefined, required: string): boolean {
|
|
233
|
+
const have = new Set(
|
|
234
|
+
String(granted ?? '')
|
|
235
|
+
.trim()
|
|
236
|
+
.split(/\s+/)
|
|
237
|
+
.filter(Boolean),
|
|
238
|
+
);
|
|
239
|
+
if (have.has('*')) return true;
|
|
240
|
+
return String(required ?? '')
|
|
241
|
+
.trim()
|
|
242
|
+
.split(/\s+/)
|
|
243
|
+
.filter(Boolean)
|
|
244
|
+
.every((s) => have.has(s));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* 现有令牌是否需要一次性 scope 升级(2026-11-14 前签发的令牌只带基础档)。
|
|
249
|
+
*
|
|
250
|
+
* 只对 **OAuth 令牌**(`custom.client_id` 存在)判定:会话 / SAML / identity 直签令牌
|
|
251
|
+
* 没有业务 scope 语义(`custom.scope` 含 `*` 或压根没有 client_id),不会被 scope 门禁拦。
|
|
252
|
+
* 模拟会话(`custom.is_imp`,平台→管理台交接)必须跳过——升级会把它换成本人令牌。
|
|
253
|
+
*/
|
|
254
|
+
export function tokenNeedsPortalScopeUpgrade(token: string | null | undefined): boolean {
|
|
255
|
+
if (!token) return false;
|
|
256
|
+
const payload = decodeJwtPayload(token) as { custom?: Record<string, unknown> } | null;
|
|
257
|
+
const custom = payload?.custom;
|
|
258
|
+
if (!custom) return false;
|
|
259
|
+
if (typeof custom.client_id !== 'string' || !custom.client_id) return false;
|
|
260
|
+
if (custom.is_imp === true) return false;
|
|
261
|
+
const scope = typeof custom.scope === 'string' ? custom.scope : '';
|
|
262
|
+
if (scope.split(/\s+/).includes('*')) return false;
|
|
263
|
+
return !scopesCover(scope, PORTAL_LOGIN_SCOPES);
|
|
264
|
+
}
|
|
265
|
+
|
|
63
266
|
export interface OAuthInitiateOptions {
|
|
64
267
|
/** 「停留」取消本次跳转时回调(AUTH-03,调用方据此恢复 UI);内部已先清预置物 |
|
|
65
268
|
* 与待重试定时器(AUTH-08),再次交互可全新发起。 */
|
|
@@ -73,6 +276,11 @@ export interface OAuthInitiateOptions {
|
|
|
73
276
|
* 空串或纯空白视同未传。服务端仍会按 `oauth_clients.scopes` 校验,未登记项会被拒绝。
|
|
74
277
|
*/
|
|
75
278
|
scope?: string;
|
|
279
|
+
/**
|
|
280
|
+
* 静默发起:流程内部步骤(如旧令牌的一次性 scope 升级),不弹「即将离开本页」
|
|
281
|
+
* 提示条,直接整页跳转(trace 记 funnel)。用户主动登录不要设置。
|
|
282
|
+
*/
|
|
283
|
+
silent?: boolean;
|
|
76
284
|
}
|
|
77
285
|
|
|
78
286
|
/**
|
|
@@ -105,8 +313,8 @@ export function discardPendingOAuthLogin(): void {
|
|
|
105
313
|
clearTimeout(retryTimer);
|
|
106
314
|
retryTimer = null;
|
|
107
315
|
}
|
|
108
|
-
sessionStorage
|
|
109
|
-
|
|
316
|
+
// F-008:交棒可能在 sessionStorage(同上下文)或 localStorage(跨上下文兜底),两处都清
|
|
317
|
+
clearHandoff(window.location.origin);
|
|
110
318
|
sessionStorage.removeItem(SK.CID);
|
|
111
319
|
sessionStorage.removeItem(SK.INIT_TS);
|
|
112
320
|
}
|
|
@@ -190,11 +398,10 @@ export async function initiateOAuthLogin(
|
|
|
190
398
|
retryTimer = null;
|
|
191
399
|
// scope 必须随重试带下去:否则自动重试会把调用方申请的额外 scope 丢掉
|
|
192
400
|
// (表现为「登录成功但写接口 403」,且极难复现)。
|
|
193
|
-
void initiateOAuthLogin(
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
);
|
|
401
|
+
void initiateOAuthLogin(clientId, redirectTarget, {
|
|
402
|
+
...(opts?.scope ? { scope: opts.scope } : {}),
|
|
403
|
+
...(opts?.silent ? { silent: true } : {}),
|
|
404
|
+
});
|
|
198
405
|
}, wait);
|
|
199
406
|
}
|
|
200
407
|
return;
|
|
@@ -213,6 +420,8 @@ export async function initiateOAuthLogin(
|
|
|
213
420
|
const cfg = getConfig();
|
|
214
421
|
const cid = clientId || cfg.clientId;
|
|
215
422
|
if (!cid) throw new Error('OAuth client_id is not available');
|
|
423
|
+
/** 交棒记录的 origin 绑定:回调页必须在同一 origin(跨浏览上下文但同源)才认 */
|
|
424
|
+
const handoffOrigin = window.location.origin;
|
|
216
425
|
|
|
217
426
|
// 申请 scope:调用方显式传入则用之(含额外 scope),否则沿用基础 scope(零波及其它站点)
|
|
218
427
|
const requestedScope = opts?.scope?.trim() || cfg.scope;
|
|
@@ -221,7 +430,9 @@ export async function initiateOAuthLogin(
|
|
|
221
430
|
const csrf = randomState();
|
|
222
431
|
const state = JSON.stringify({ csrf, redirect: target });
|
|
223
432
|
|
|
224
|
-
sessionStorage
|
|
433
|
+
// 交棒(state):sessionStorage 快路径 + localStorage 跨上下文兜底(F-008)。
|
|
434
|
+
// 此处先落 state;verifier 需等 generatePKCE,稍后补齐整条记录。
|
|
435
|
+
saveHandoff(handoffOrigin, { state: csrf, verifier: '' });
|
|
225
436
|
sessionStorage.setItem(SK.CID, cid);
|
|
226
437
|
// 交棒时落持久层:刷新/登出在 React 上下文外,拿不到 slug 解析结果(TASK-09 / D8)
|
|
227
438
|
persistOAuthClientId(cid);
|
|
@@ -233,9 +444,14 @@ export async function initiateOAuthLogin(
|
|
|
233
444
|
opts?.onStay?.();
|
|
234
445
|
};
|
|
235
446
|
|
|
447
|
+
// silent(流程内部步骤,如 scope 升级):静默整页跳,不弹「即将离开本页」提示条。
|
|
448
|
+
const traceKind = opts?.silent ? 'funnel' : 'interstitial';
|
|
449
|
+
const traceReason = opts?.silent ? 'oauth-scope-upgrade' : 'oauth-initiate';
|
|
450
|
+
|
|
236
451
|
try {
|
|
237
452
|
const pkce = await generatePKCE();
|
|
238
|
-
|
|
453
|
+
// 补齐 verifier 后重写整条交棒(localStorage 兜底记录同时带上 verifier)
|
|
454
|
+
saveHandoff(handoffOrigin, { state: csrf, verifier: pkce.verifier });
|
|
239
455
|
const params = new URLSearchParams({
|
|
240
456
|
response_type: 'code',
|
|
241
457
|
client_id: cid,
|
|
@@ -247,8 +463,8 @@ export async function initiateOAuthLogin(
|
|
|
247
463
|
});
|
|
248
464
|
// interstitial:未认证深链被动弹去登录 → authTrace 提示(可停留)。
|
|
249
465
|
traceRedirect(`${cfg.authorizeUrl}?${params}`, {
|
|
250
|
-
reason:
|
|
251
|
-
kind:
|
|
466
|
+
reason: traceReason,
|
|
467
|
+
kind: traceKind,
|
|
252
468
|
assign: true,
|
|
253
469
|
onStay: handleStay,
|
|
254
470
|
});
|
|
@@ -261,8 +477,8 @@ export async function initiateOAuthLogin(
|
|
|
261
477
|
state,
|
|
262
478
|
});
|
|
263
479
|
traceRedirect(`${cfg.authorizeUrl}?${params}`, {
|
|
264
|
-
reason:
|
|
265
|
-
kind:
|
|
480
|
+
reason: traceReason,
|
|
481
|
+
kind: traceKind,
|
|
266
482
|
assign: true,
|
|
267
483
|
onStay: handleStay,
|
|
268
484
|
});
|
|
@@ -283,9 +499,16 @@ export async function handleOAuthCallback(): Promise<void> {
|
|
|
283
499
|
const code = q.get('code');
|
|
284
500
|
if (!code) throw new OAuthCallbackError('oauth.missing_code', 'Missing authorization code');
|
|
285
501
|
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
502
|
+
// F-008:交棒读取走 helper —— 先 sessionStorage(同上下文快路径),未命中再读
|
|
503
|
+
// localStorage 兜底(跨浏览上下文:PWA standalone → 外部浏览器 / 新标签 / Custom Tab)。
|
|
504
|
+
// 命中即双删(防重放);读不到仍是空串 ⇒ 下面照旧抛 state_mismatch / pkce_cleared。
|
|
505
|
+
const cbOrigin = window.location.origin;
|
|
506
|
+
const handoff = loadHandoff(cbOrigin);
|
|
507
|
+
const storedState = handoff.state;
|
|
508
|
+
const verifier = handoff.verifier;
|
|
509
|
+
// client_id:sessionStorage 优先,localStorage 持久值兜底(跨上下文时 session 里没有;
|
|
510
|
+
// 发起时 persistOAuthClientId 已落库,不含任何凭据)
|
|
511
|
+
const cid = sessionStorage.getItem(SK.CID) || getPersistedOAuthClientId();
|
|
289
512
|
|
|
290
513
|
// State is always JSON: { csrf, redirect }
|
|
291
514
|
let oauthRedirectTarget: string | null = null;
|
|
@@ -339,8 +562,8 @@ export async function handleOAuthCallback(): Promise<void> {
|
|
|
339
562
|
|
|
340
563
|
// 用毕即焚(AUTH-08):兑换请求已消费 code_verifier/state/client_id,立即清除;
|
|
341
564
|
// 原清理点在 userinfo、/auth/me 多次 await 之后,明文 verifier 驻留窗口被无谓拉长。
|
|
342
|
-
|
|
343
|
-
|
|
565
|
+
// F-008:state/verifier 通常已在 loadHandoff 命中时双删,这里再清一次(幂等兜底)。
|
|
566
|
+
clearHandoff(cbOrigin);
|
|
344
567
|
sessionStorage.removeItem(SK.CID);
|
|
345
568
|
|
|
346
569
|
const t = res.data as any;
|
|
@@ -2,7 +2,11 @@ import { useCallback, useEffect, useState } from 'react';
|
|
|
2
2
|
import { AuthService, setBootstrapLock } from '../auth/service';
|
|
3
3
|
import { buildLoginUrl } from '../auth/roles';
|
|
4
4
|
import { traceRedirect } from '../auth/auth-trace';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
initiateOAuthLogin,
|
|
7
|
+
PORTAL_LOGIN_SCOPES,
|
|
8
|
+
tokenNeedsPortalScopeUpgrade,
|
|
9
|
+
} from '../auth/oauth-login';
|
|
6
10
|
import {
|
|
7
11
|
useTenantRoute,
|
|
8
12
|
resolveEffectiveClientId,
|
|
@@ -192,6 +196,9 @@ export function RequireAuth({
|
|
|
192
196
|
void initiateOAuthLogin(effectiveClientId, undefined, {
|
|
193
197
|
onStay: () => setStayed(true),
|
|
194
198
|
force,
|
|
199
|
+
// 门户档 scope:写接口(MFA 开通 / 通知流 / 账号绑定 / 钱包…)需要
|
|
200
|
+
// 业务写 scope;只申请基础档会「登录成功、写操作 403」。
|
|
201
|
+
scope: PORTAL_LOGIN_SCOPES,
|
|
195
202
|
});
|
|
196
203
|
return;
|
|
197
204
|
}
|
|
@@ -235,6 +242,29 @@ export function RequireAuth({
|
|
|
235
242
|
if (!hasToken) setBootstrapLock(true);
|
|
236
243
|
}, []);
|
|
237
244
|
|
|
245
|
+
// 一次性 scope 升级(2026-11-14):历史 OAuth 令牌只申请了基础档(read),写接口
|
|
246
|
+
// 全部 403(MFA 开通 / 通知流 / 账号绑定…)。已登录且令牌缺门户写 scope 时,用
|
|
247
|
+
// 完整档**静默**重新授权一次——auth 侧已有会话与既有同意时 authorize 自动放行,
|
|
248
|
+
// 用户只看到一次回跳。每页面会话最多尝试一次(失败不循环);升级后令牌即带全
|
|
249
|
+
// scope,条件自然转假。会话/SAML 直签令牌(无 OAuth client_id)与模拟会话不参与。
|
|
250
|
+
const SCOPE_UPGRADE_FLAG = 'oauth_portal_scope_upgrade_tried';
|
|
251
|
+
useEffect(() => {
|
|
252
|
+
if (typeof window === 'undefined') return;
|
|
253
|
+
if (machine.status !== 'ready' && machine.status !== 'authenticated') return;
|
|
254
|
+
const cfg = (window as any).__APP_CONFIG__;
|
|
255
|
+
const envClientId = cfg?.VITE_OAUTH_CLIENT_ID || '';
|
|
256
|
+
const effectiveClientId = resolveEffectiveClientId(tenantRoute, envClientId);
|
|
257
|
+
if (!effectiveClientId) return;
|
|
258
|
+
if (!tokenNeedsPortalScopeUpgrade(AuthService.getAccessToken())) return;
|
|
259
|
+
if (sessionStorage.getItem(SCOPE_UPGRADE_FLAG)) return;
|
|
260
|
+
sessionStorage.setItem(SCOPE_UPGRADE_FLAG, '1');
|
|
261
|
+
void initiateOAuthLogin(effectiveClientId, undefined, {
|
|
262
|
+
scope: PORTAL_LOGIN_SCOPES,
|
|
263
|
+
force: true,
|
|
264
|
+
silent: true,
|
|
265
|
+
});
|
|
266
|
+
}, [machine.status, tenantRoute]);
|
|
267
|
+
|
|
238
268
|
// Redirect logic: only runs when machine says unauthenticated
|
|
239
269
|
useEffect(() => {
|
|
240
270
|
if (machine.status !== 'unauthenticated') return;
|
|
@@ -33,7 +33,9 @@ vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
|
33
33
|
}),
|
|
34
34
|
}));
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
// 部分 mock:保留真实 scope 常量/判定(RequireAuth 的 scope 升级 effect 依赖它们)。
|
|
37
|
+
vi.mock('../../auth/oauth-login', async (importOriginal) => ({
|
|
38
|
+
...(await importOriginal<typeof import('../../auth/oauth-login')>()),
|
|
37
39
|
initiateOAuthLogin: vi.fn(),
|
|
38
40
|
}));
|
|
39
41
|
|
|
@@ -37,7 +37,11 @@ vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
|
37
37
|
useTenantRoute: () => mockState.tenantRoute,
|
|
38
38
|
}));
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
// 部分 mock:保留真实 scope 常量/判定(RequireAuth 的 scope 升级 effect 依赖它们)。
|
|
41
|
+
vi.mock('../../auth/oauth-login', async (importOriginal) => ({
|
|
42
|
+
...(await importOriginal<typeof import('../../auth/oauth-login')>()),
|
|
43
|
+
initiateOAuthLogin: vi.fn(),
|
|
44
|
+
}));
|
|
41
45
|
|
|
42
46
|
vi.mock('../../auth/service', () => ({
|
|
43
47
|
AuthService: {
|
|
@@ -17,7 +17,11 @@ vi.mock('../../auth/auth-queries', () => ({
|
|
|
17
17
|
|
|
18
18
|
vi.mock('../../generated/api', () => ({ profileAvatar: vi.fn().mockResolvedValue({}) }));
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
// 部分 mock:保留真实 scope 常量/判定(RequireAuth 的 scope 升级 effect 依赖它们)。
|
|
21
|
+
vi.mock('../../auth/oauth-login', async (importOriginal) => ({
|
|
22
|
+
...(await importOriginal<typeof import('../../auth/oauth-login')>()),
|
|
23
|
+
initiateOAuthLogin: vi.fn(),
|
|
24
|
+
}));
|
|
21
25
|
|
|
22
26
|
vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
23
27
|
...(await importOriginal<typeof import('../../auth/tenant-route-middleware')>()),
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import '@testing-library/jest-dom/vitest';
|
|
3
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
4
|
+
import { render, cleanup, screen } from '@testing-library/react';
|
|
5
|
+
|
|
6
|
+
// ============================================================
|
|
7
|
+
// 2026-11-14 事故回归锁:用户门户「短信验证 → 验证并开启」
|
|
8
|
+
// 403 `token scope does not allow this operation`。
|
|
9
|
+
//
|
|
10
|
+
// 修复前:登录只申请基础档(read)⇒ MFA 等写接口全 403。
|
|
11
|
+
// 修复后:① 登录发起即申请门户档;② 已登录但令牌缺门户写 scope 时,挂载后
|
|
12
|
+
// 一次性静默重新授权(auth 侧有会话 + 既有同意 → 自动放行,用户只看到回跳)。
|
|
13
|
+
// 本文件钉住 ② 的触发面:OAuth 旧令牌触发;已升级/会话/模拟令牌不触发;每次
|
|
14
|
+
// 页面会话只尝试一次(失败不循环)。
|
|
15
|
+
// ============================================================
|
|
16
|
+
|
|
17
|
+
const { mockState } = vi.hoisted(() => ({
|
|
18
|
+
mockState: {
|
|
19
|
+
machineStatus: 'ready' as string,
|
|
20
|
+
tenantRoute: {
|
|
21
|
+
slug: 'platform' as string | null,
|
|
22
|
+
tenantId: 't1' as string | null,
|
|
23
|
+
oauthClientId: '01AR0000000000000000000004' as string | null,
|
|
24
|
+
loading: false,
|
|
25
|
+
notFound: false,
|
|
26
|
+
unknownSlug: false,
|
|
27
|
+
},
|
|
28
|
+
token: null as string | null,
|
|
29
|
+
initiate: vi.fn(),
|
|
30
|
+
},
|
|
31
|
+
}));
|
|
32
|
+
|
|
33
|
+
vi.mock('../../auth/auth-machine', () => ({
|
|
34
|
+
useAuthMachine: () => ({ status: mockState.machineStatus }),
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
38
|
+
...(await importOriginal<typeof import('../../auth/tenant-route-middleware')>()),
|
|
39
|
+
useTenantRoute: () => mockState.tenantRoute,
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
// 部分 mock:保留真实 scope 常量与判定函数(升级 effect 的判据来源)。
|
|
43
|
+
vi.mock('../../auth/oauth-login', async (importOriginal) => ({
|
|
44
|
+
...(await importOriginal<typeof import('../../auth/oauth-login')>()),
|
|
45
|
+
initiateOAuthLogin: (...args: any[]) => mockState.initiate(...args),
|
|
46
|
+
}));
|
|
47
|
+
|
|
48
|
+
vi.mock('../../auth/service', () => ({
|
|
49
|
+
AuthService: {
|
|
50
|
+
getAccessToken: () => mockState.token,
|
|
51
|
+
getCurrentRole: () => null,
|
|
52
|
+
getPermissions: () => [],
|
|
53
|
+
},
|
|
54
|
+
setBootstrapLock: vi.fn(),
|
|
55
|
+
}));
|
|
56
|
+
|
|
57
|
+
import { RequireAuth } from '../RequireAuth';
|
|
58
|
+
import { OAUTH_LOGIN_SCOPES, PORTAL_LOGIN_SCOPES } from '../../auth/oauth-login';
|
|
59
|
+
|
|
60
|
+
function b64url(value: unknown): string {
|
|
61
|
+
return btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** OAuth 访问令牌(scope/client_id 在 custom 内,与 service-oauth 签发形态一致)。 */
|
|
65
|
+
function oauthToken(scope: string, custom: Record<string, unknown> = {}): string {
|
|
66
|
+
const header = b64url({ alg: 'RS256', typ: 'JWT' });
|
|
67
|
+
const payload = b64url({
|
|
68
|
+
sub: 'user-1',
|
|
69
|
+
tenant_id: 't1',
|
|
70
|
+
type: 'access',
|
|
71
|
+
custom: { scope, client_id: '01AR0000000000000000000004', ...custom },
|
|
72
|
+
});
|
|
73
|
+
return `${header}.${payload}.sig`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function renderGuard() {
|
|
77
|
+
return render(
|
|
78
|
+
<RequireAuth>
|
|
79
|
+
<div data-testid="protected">protected</div>
|
|
80
|
+
</RequireAuth>,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
beforeEach(() => {
|
|
85
|
+
vi.clearAllMocks();
|
|
86
|
+
window.sessionStorage.clear();
|
|
87
|
+
mockState.machineStatus = 'ready';
|
|
88
|
+
mockState.token = null;
|
|
89
|
+
delete (window as any).__APP_CONFIG__;
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
afterEach(() => cleanup());
|
|
93
|
+
|
|
94
|
+
describe('RequireAuth 一次性 scope 升级', () => {
|
|
95
|
+
it('OAuth 旧令牌(仅基础档)→ 静默发起门户档重新授权,子路由照常渲染', () => {
|
|
96
|
+
mockState.token = oauthToken(OAUTH_LOGIN_SCOPES);
|
|
97
|
+
|
|
98
|
+
renderGuard();
|
|
99
|
+
|
|
100
|
+
expect(screen.getByTestId('protected')).toBeInTheDocument();
|
|
101
|
+
expect(mockState.initiate).toHaveBeenCalledTimes(1);
|
|
102
|
+
expect(mockState.initiate).toHaveBeenCalledWith(
|
|
103
|
+
'01AR0000000000000000000004',
|
|
104
|
+
undefined,
|
|
105
|
+
{ scope: PORTAL_LOGIN_SCOPES, force: true, silent: true },
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('每次页面会话只尝试一次(失败不循环)', () => {
|
|
110
|
+
mockState.token = oauthToken(OAUTH_LOGIN_SCOPES);
|
|
111
|
+
|
|
112
|
+
renderGuard();
|
|
113
|
+
expect(mockState.initiate).toHaveBeenCalledTimes(1);
|
|
114
|
+
cleanup();
|
|
115
|
+
|
|
116
|
+
// 同 tab 二次挂载:升级标记已在 ⇒ 不再发起
|
|
117
|
+
mockState.initiate.mockClear();
|
|
118
|
+
renderGuard();
|
|
119
|
+
expect(mockState.initiate).not.toHaveBeenCalled();
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
it('令牌已是门户档 → 不升级', () => {
|
|
123
|
+
mockState.token = oauthToken(PORTAL_LOGIN_SCOPES);
|
|
124
|
+
|
|
125
|
+
renderGuard();
|
|
126
|
+
|
|
127
|
+
expect(mockState.initiate).not.toHaveBeenCalled();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('会话直签令牌(无 OAuth client_id)→ 不升级', () => {
|
|
131
|
+
const header = b64url({ alg: 'RS256', typ: 'JWT' });
|
|
132
|
+
const payload = b64url({ sub: 'user-1', type: 'access', custom: { scope: 'read *' } });
|
|
133
|
+
mockState.token = `${header}.${payload}.sig`;
|
|
134
|
+
|
|
135
|
+
renderGuard();
|
|
136
|
+
|
|
137
|
+
expect(mockState.initiate).not.toHaveBeenCalled();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('模拟会话(is_imp)→ 不升级(不得换成本人令牌)', () => {
|
|
141
|
+
mockState.token = oauthToken(OAUTH_LOGIN_SCOPES, { is_imp: true });
|
|
142
|
+
|
|
143
|
+
renderGuard();
|
|
144
|
+
|
|
145
|
+
expect(mockState.initiate).not.toHaveBeenCalled();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it('未登录态不触发升级(交由原有登录漏斗:force=false、非 silent)', () => {
|
|
149
|
+
mockState.machineStatus = 'unauthenticated';
|
|
150
|
+
mockState.token = oauthToken(OAUTH_LOGIN_SCOPES);
|
|
151
|
+
|
|
152
|
+
renderGuard();
|
|
153
|
+
|
|
154
|
+
const upgradeCalls = mockState.initiate.mock.calls.filter((c) => c[2]?.silent === true);
|
|
155
|
+
expect(upgradeCalls).toHaveLength(0);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
@@ -33,7 +33,9 @@ vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
|
33
33
|
useTenantRoute: () => mockState.tenantRoute,
|
|
34
34
|
}));
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
// 部分 mock:保留真实 scope 常量/判定(RequireAuth 的 scope 升级 effect 依赖它们)。
|
|
37
|
+
vi.mock('../../auth/oauth-login', async (importOriginal) => ({
|
|
38
|
+
...(await importOriginal<typeof import('../../auth/oauth-login')>()),
|
|
37
39
|
initiateOAuthLogin: (...args: any[]) => mockInitiate(...args),
|
|
38
40
|
}));
|
|
39
41
|
|
|
@@ -37,7 +37,10 @@ vi.mock('../../auth/tenant-route-middleware', async (importOriginal) => ({
|
|
|
37
37
|
useTenantRoute: () => mockState.tenantRoute,
|
|
38
38
|
}));
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
// 部分 mock:保留真实 scope 常量/判定(RequireAuth 的 scope 升级 effect 依赖它们),
|
|
41
|
+
// 只替换发起函数。
|
|
42
|
+
vi.mock('../../auth/oauth-login', async (importOriginal) => ({
|
|
43
|
+
...(await importOriginal<typeof import('../../auth/oauth-login')>()),
|
|
41
44
|
initiateOAuthLogin: (...args: any[]) => mockState.initiate(...args),
|
|
42
45
|
}));
|
|
43
46
|
|
package/src/hooks/useAuth.ts
CHANGED
|
@@ -35,8 +35,17 @@ export interface AuthSnapshot {
|
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
export interface AuthActions {
|
|
38
|
-
/**
|
|
39
|
-
|
|
38
|
+
/**
|
|
39
|
+
* 跳转到 OAuth 登录页或 auth-pages。
|
|
40
|
+
* 指定 clientId 时走 OAuth PKCE:缺省申请门户档 scope(`PORTAL_LOGIN_SCOPES`,
|
|
41
|
+
* 含业务写 scope);窄权限调用方(如认证器类应用)显式传 `scope` 收窄。
|
|
42
|
+
*/
|
|
43
|
+
login: (params?: {
|
|
44
|
+
clientId?: string;
|
|
45
|
+
redirectUri?: string;
|
|
46
|
+
/** 覆盖登录 scope(缺省 = 门户档 `PORTAL_LOGIN_SCOPES`)。 */
|
|
47
|
+
scope?: string;
|
|
48
|
+
}) => Promise<void>;
|
|
40
49
|
/** 统一登出(清除所有状态 + 跳转登录页) */
|
|
41
50
|
logout: () => Promise<void>;
|
|
42
51
|
/** 设置当前租户 */
|
|
@@ -200,10 +209,18 @@ export function useTenants(): Array<{ id: string; name: string; role: string }>
|
|
|
200
209
|
*/
|
|
201
210
|
export function useAuthActions(): AuthActions {
|
|
202
211
|
const login = useCallback(
|
|
203
|
-
async (params?: {
|
|
212
|
+
async (params?: {
|
|
213
|
+
clientId?: string;
|
|
214
|
+
redirectUri?: string;
|
|
215
|
+
scope?: string;
|
|
216
|
+
}): Promise<void> => {
|
|
204
217
|
if (params?.clientId) {
|
|
205
|
-
const { initiateOAuthLogin } = await import(
|
|
206
|
-
|
|
218
|
+
const { initiateOAuthLogin, PORTAL_LOGIN_SCOPES } = await import(
|
|
219
|
+
'../auth/oauth-login'
|
|
220
|
+
);
|
|
221
|
+
return initiateOAuthLogin(params.clientId, params.redirectUri, {
|
|
222
|
+
scope: params.scope ?? PORTAL_LOGIN_SCOPES,
|
|
223
|
+
});
|
|
207
224
|
}
|
|
208
225
|
const { buildLoginUrl } = await import('../auth/roles');
|
|
209
226
|
window.location.href = buildLoginUrl(window.location.href);
|
package/src/index.ts
CHANGED
|
@@ -50,6 +50,9 @@ export {
|
|
|
50
50
|
isOAuthEnabled,
|
|
51
51
|
OAuthCallbackError,
|
|
52
52
|
withOAuthScopes,
|
|
53
|
+
PORTAL_LOGIN_SCOPES,
|
|
54
|
+
scopesCover,
|
|
55
|
+
tokenNeedsPortalScopeUpgrade,
|
|
53
56
|
} from './auth/oauth-login';
|
|
54
57
|
export { decodeJwtPayload } from './auth/jwt-payload';
|
|
55
58
|
export { buildLoginUrl } from './auth/roles';
|