@autional/shared 0.1.0-rc.68 → 0.1.0-rc.69

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autional/shared",
3
- "version": "0.1.0-rc.68",
3
+ "version": "0.1.0-rc.69",
4
4
  "description": "Autional shared layer — API client, auth, types, hooks, utils",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./src/index.ts",
@@ -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
+ });
@@ -60,6 +60,63 @@ export function withOAuthScopes(...extra: string[]): string {
60
60
  return out.join(' ');
61
61
  }
62
62
 
63
+ /**
64
+ * 第一方门户登录申请的**完整 scope 档**(基础档 + 业务写能力)。
65
+ *
66
+ * 2026-11-14 事故:用户门户「短信验证 → 验证并开启」返回 403
67
+ * `token scope does not allow this operation` —— 登录只申请了 `read`,而 MFA 写接口自
68
+ * 2026-11-06 起强制 `mfa:write`。同类受影响的还有通知流 stream-ticket(`write`)、
69
+ * 社交账号绑定/解绑与授权撤销(`oauth:write`)、钱包/积分/支付/账单写(`*:write`)。
70
+ *
71
+ * 服务端 `oauth_clients.scopes` 已为全部首方门户 client(9 个固定 client +
72
+ * 全部租户 Default Client)登记了这套 scope;缺的一直只是「登录时申请」这一步。
73
+ * 认证器 PWA 另有更窄的档位(`withOAuthScopes('write')`,见 ADR-027 D2),不得使用本常量。
74
+ */
75
+ export const PORTAL_LOGIN_SCOPES = withOAuthScopes(
76
+ 'write',
77
+ 'wallet:write',
78
+ 'point:write',
79
+ 'pay:write',
80
+ 'billing:write',
81
+ 'oauth:write',
82
+ 'mfa:write',
83
+ );
84
+
85
+ /** granted 是否覆盖 required 要求的全部 scope(空格分隔;`*` 通配覆盖一切)。 */
86
+ export function scopesCover(granted: string | null | undefined, required: string): boolean {
87
+ const have = new Set(
88
+ String(granted ?? '')
89
+ .trim()
90
+ .split(/\s+/)
91
+ .filter(Boolean),
92
+ );
93
+ if (have.has('*')) return true;
94
+ return String(required ?? '')
95
+ .trim()
96
+ .split(/\s+/)
97
+ .filter(Boolean)
98
+ .every((s) => have.has(s));
99
+ }
100
+
101
+ /**
102
+ * 现有令牌是否需要一次性 scope 升级(2026-11-14 前签发的令牌只带基础档)。
103
+ *
104
+ * 只对 **OAuth 令牌**(`custom.client_id` 存在)判定:会话 / SAML / identity 直签令牌
105
+ * 没有业务 scope 语义(`custom.scope` 含 `*` 或压根没有 client_id),不会被 scope 门禁拦。
106
+ * 模拟会话(`custom.is_imp`,平台→管理台交接)必须跳过——升级会把它换成本人令牌。
107
+ */
108
+ export function tokenNeedsPortalScopeUpgrade(token: string | null | undefined): boolean {
109
+ if (!token) return false;
110
+ const payload = decodeJwtPayload(token) as { custom?: Record<string, unknown> } | null;
111
+ const custom = payload?.custom;
112
+ if (!custom) return false;
113
+ if (typeof custom.client_id !== 'string' || !custom.client_id) return false;
114
+ if (custom.is_imp === true) return false;
115
+ const scope = typeof custom.scope === 'string' ? custom.scope : '';
116
+ if (scope.split(/\s+/).includes('*')) return false;
117
+ return !scopesCover(scope, PORTAL_LOGIN_SCOPES);
118
+ }
119
+
63
120
  export interface OAuthInitiateOptions {
64
121
  /** 「停留」取消本次跳转时回调(AUTH-03,调用方据此恢复 UI);内部已先清预置物 |
65
122
  * 与待重试定时器(AUTH-08),再次交互可全新发起。 */
@@ -73,6 +130,11 @@ export interface OAuthInitiateOptions {
73
130
  * 空串或纯空白视同未传。服务端仍会按 `oauth_clients.scopes` 校验,未登记项会被拒绝。
74
131
  */
75
132
  scope?: string;
133
+ /**
134
+ * 静默发起:流程内部步骤(如旧令牌的一次性 scope 升级),不弹「即将离开本页」
135
+ * 提示条,直接整页跳转(trace 记 funnel)。用户主动登录不要设置。
136
+ */
137
+ silent?: boolean;
76
138
  }
77
139
 
78
140
  /**
@@ -190,11 +252,10 @@ export async function initiateOAuthLogin(
190
252
  retryTimer = null;
191
253
  // scope 必须随重试带下去:否则自动重试会把调用方申请的额外 scope 丢掉
192
254
  // (表现为「登录成功但写接口 403」,且极难复现)。
193
- void initiateOAuthLogin(
194
- clientId,
195
- redirectTarget,
196
- opts?.scope ? { scope: opts.scope } : undefined,
197
- );
255
+ void initiateOAuthLogin(clientId, redirectTarget, {
256
+ ...(opts?.scope ? { scope: opts.scope } : {}),
257
+ ...(opts?.silent ? { silent: true } : {}),
258
+ });
198
259
  }, wait);
199
260
  }
200
261
  return;
@@ -233,6 +294,10 @@ export async function initiateOAuthLogin(
233
294
  opts?.onStay?.();
234
295
  };
235
296
 
297
+ // silent(流程内部步骤,如 scope 升级):静默整页跳,不弹「即将离开本页」提示条。
298
+ const traceKind = opts?.silent ? 'funnel' : 'interstitial';
299
+ const traceReason = opts?.silent ? 'oauth-scope-upgrade' : 'oauth-initiate';
300
+
236
301
  try {
237
302
  const pkce = await generatePKCE();
238
303
  sessionStorage.setItem(SK.PKCE, pkce.verifier);
@@ -247,8 +312,8 @@ export async function initiateOAuthLogin(
247
312
  });
248
313
  // interstitial:未认证深链被动弹去登录 → authTrace 提示(可停留)。
249
314
  traceRedirect(`${cfg.authorizeUrl}?${params}`, {
250
- reason: 'oauth-initiate',
251
- kind: 'interstitial',
315
+ reason: traceReason,
316
+ kind: traceKind,
252
317
  assign: true,
253
318
  onStay: handleStay,
254
319
  });
@@ -261,8 +326,8 @@ export async function initiateOAuthLogin(
261
326
  state,
262
327
  });
263
328
  traceRedirect(`${cfg.authorizeUrl}?${params}`, {
264
- reason: 'oauth-initiate',
265
- kind: 'interstitial',
329
+ reason: traceReason,
330
+ kind: traceKind,
266
331
  assign: true,
267
332
  onStay: handleStay,
268
333
  });
@@ -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 { initiateOAuthLogin } from '../auth/oauth-login';
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
- vi.mock('../../auth/oauth-login', () => ({
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
- vi.mock('../../auth/oauth-login', () => ({ initiateOAuthLogin: vi.fn() }));
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
- vi.mock('../../auth/oauth-login', () => ({ initiateOAuthLogin: vi.fn() }));
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
- vi.mock('../../auth/oauth-login', () => ({
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
- vi.mock('../../auth/oauth-login', () => ({
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
 
@@ -35,8 +35,17 @@ export interface AuthSnapshot {
35
35
  }
36
36
 
37
37
  export interface AuthActions {
38
- /** 跳转到 OAuth 登录页或 auth-pages */
39
- login: (params?: { clientId?: string; redirectUri?: string }) => Promise<void>;
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?: { clientId?: string; redirectUri?: string }): Promise<void> => {
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('../auth/oauth-login');
206
- return initiateOAuthLogin(params.clientId, params.redirectUri);
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';