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

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.67",
3
+ "version": "0.1.0-rc.68",
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,102 @@
1
+ // @vitest-environment jsdom
2
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
3
+
4
+ // ============================================================
5
+ // OAuth 登录「可追加 scope」(2026-11-14)
6
+ // - 缺省行为不变:不传 opts.scope ⇒ 申请 OAUTH_LOGIN_SCOPES
7
+ // - withOAuthScopes('write') ⇒ URL 的 scope 含 write、无重复
8
+ // - 空数组 / 空串 ⇒ 不改变基础 scope
9
+ // ============================================================
10
+
11
+ const { mockTrace, mockPersistCid } = vi.hoisted(() => ({
12
+ mockTrace: vi.fn(),
13
+ mockPersistCid: vi.fn(),
14
+ }));
15
+
16
+ vi.mock('../../api/client', () => ({ apiClient: { post: vi.fn(), get: vi.fn() } }));
17
+ vi.mock('../store', () => ({ loginWithTokens: vi.fn() }));
18
+ vi.mock('../service', () => ({ AuthService: { updateCurrentTenant: vi.fn() } }));
19
+ vi.mock('../oauth-client-id-store', () => ({ persistOAuthClientId: mockPersistCid }));
20
+ vi.mock('../auth-trace', () => ({ traceRedirect: mockTrace }));
21
+ vi.mock('../pkce', () => ({
22
+ generatePKCE: () => Promise.resolve({ verifier: 'v-1', challenge: 'c-1' }),
23
+ }));
24
+ vi.mock('../../config', () => ({ getPortalUrl: () => 'https://auth.example.com' }));
25
+
26
+ import { initiateOAuthLogin, OAUTH_LOGIN_SCOPES, withOAuthScopes } from '../oauth-login';
27
+
28
+ function scopeFromLastTrace(): string {
29
+ expect(mockTrace).toHaveBeenCalledTimes(1);
30
+ const url = new URL(mockTrace.mock.calls[0][0] as string);
31
+ return url.searchParams.get('scope') || '';
32
+ }
33
+
34
+ beforeEach(() => {
35
+ vi.clearAllMocks();
36
+ sessionStorage.clear();
37
+ });
38
+
39
+ afterEach(() => {
40
+ vi.useRealTimers();
41
+ });
42
+
43
+ describe('withOAuthScopes', () => {
44
+ it('不传额外项 ⇒ 与基础 scope 完全一致', () => {
45
+ expect(withOAuthScopes()).toBe(OAUTH_LOGIN_SCOPES);
46
+ });
47
+
48
+ it('空数组 / 空串 / 纯空白 ⇒ 不改变基础 scope', () => {
49
+ expect(withOAuthScopes('')).toBe(OAUTH_LOGIN_SCOPES);
50
+ expect(withOAuthScopes(' ')).toBe(OAUTH_LOGIN_SCOPES);
51
+ expect(withOAuthScopes(...[])).toBe(OAUTH_LOGIN_SCOPES);
52
+ });
53
+
54
+ it("追加 write ⇒ 基础项在前、write 在后", () => {
55
+ expect(withOAuthScopes('write')).toBe(`${OAUTH_LOGIN_SCOPES} write`);
56
+ });
57
+
58
+ it('重复项去重(含基础里已有的项与多次传入)', () => {
59
+ const once = withOAuthScopes('write', 'write', 'read', 'mfa:write');
60
+ const scopes = once.split(' ').filter(Boolean);
61
+ expect(new Set(scopes).size).toBe(scopes.length);
62
+ expect(scopes.filter((s) => s === 'read')).toHaveLength(1);
63
+ expect(scopes.filter((s) => s === 'write')).toHaveLength(1);
64
+ expect(scopes).toContain('mfa:write');
65
+ });
66
+
67
+ it('多项一次传入按传入次序追加', () => {
68
+ const scopes = withOAuthScopes('write', 'mfa:write').split(' ');
69
+ expect(scopes.indexOf('write')).toBeLessThan(scopes.indexOf('mfa:write'));
70
+ });
71
+ });
72
+
73
+ describe('initiateOAuthLogin 的 scope 传参', () => {
74
+ it('不传 opts.scope ⇒ URL 里仍是最初的基础 scope(零波及)', async () => {
75
+ await initiateOAuthLogin('cid-1');
76
+ expect(scopeFromLastTrace()).toBe(OAUTH_LOGIN_SCOPES);
77
+ });
78
+
79
+ it('opts.scope = withOAuthScopes("write") ⇒ URL scope 含 write 且无重复', async () => {
80
+ await initiateOAuthLogin('cid-1', undefined, { scope: withOAuthScopes('write') });
81
+ const scopes = scopeFromLastTrace().split(' ').filter(Boolean);
82
+ expect(scopes).toContain('write');
83
+ expect(new Set(scopes).size).toBe(scopes.length);
84
+ });
85
+
86
+ it('opts.scope = 空串 ⇒ 回落到基础 scope', async () => {
87
+ await initiateOAuthLogin('cid-1', undefined, { scope: '' });
88
+ expect(scopeFromLastTrace()).toBe(OAUTH_LOGIN_SCOPES);
89
+ });
90
+
91
+ it('防重入自动重试也带住追加的 scope(否则重试会丢掉 write)', async () => {
92
+ vi.useFakeTimers();
93
+ sessionStorage.setItem('oauth_init_ts', String(Date.now()));
94
+
95
+ await initiateOAuthLogin('cid-1', undefined, { scope: withOAuthScopes('write') });
96
+ expect(mockTrace).not.toHaveBeenCalled();
97
+
98
+ await vi.advanceTimersByTimeAsync(10200);
99
+ const scopes = scopeFromLastTrace().split(' ');
100
+ expect(scopes).toContain('write');
101
+ });
102
+ });
@@ -43,12 +43,36 @@ const SK = {
43
43
  */
44
44
  export const OAUTH_LOGIN_SCOPES = 'openid profile email offline_access read';
45
45
 
46
+ /** 把 `extra` 并入基础登录 scope:去重、保持顺序(基础项在前,新增项按传入次序追加)。 */
47
+ export function withOAuthScopes(...extra: string[]): string {
48
+ const seen = new Set<string>();
49
+ const out: string[] = [];
50
+ for (const raw of [OAUTH_LOGIN_SCOPES, ...extra]) {
51
+ for (const s of String(raw ?? '')
52
+ .trim()
53
+ .split(/\s+/)
54
+ .filter(Boolean)) {
55
+ if (seen.has(s)) continue;
56
+ seen.add(s);
57
+ out.push(s);
58
+ }
59
+ }
60
+ return out.join(' ');
61
+ }
62
+
46
63
  export interface OAuthInitiateOptions {
47
64
  /** 「停留」取消本次跳转时回调(AUTH-03,调用方据此恢复 UI);内部已先清预置物 |
48
65
  * 与待重试定时器(AUTH-08),再次交互可全新发起。 */
49
66
  onStay?: () => void;
50
67
  /** 跳过 10s 防重入窗口(用户显式点「前往登录」重试时用,AUTH-03)。 */
51
68
  force?: boolean;
69
+ /**
70
+ * 本次登录申请的 scope(缺省 = `OAUTH_LOGIN_SCOPES`,即既有行为)。
71
+ * 用 `withOAuthScopes('write')` 生成,供需要写 scope 的第一方客户端使用
72
+ * (例:authenticator-app 的推送登记 / stream-ticket 需 `write`)。
73
+ * 空串或纯空白视同未传。服务端仍会按 `oauth_clients.scopes` 校验,未登记项会被拒绝。
74
+ */
75
+ scope?: string;
52
76
  }
53
77
 
54
78
  /**
@@ -164,7 +188,13 @@ export async function initiateOAuthLogin(
164
188
  if (!retryTimer) {
165
189
  retryTimer = setTimeout(() => {
166
190
  retryTimer = null;
167
- void initiateOAuthLogin(clientId, redirectTarget);
191
+ // scope 必须随重试带下去:否则自动重试会把调用方申请的额外 scope 丢掉
192
+ // (表现为「登录成功但写接口 403」,且极难复现)。
193
+ void initiateOAuthLogin(
194
+ clientId,
195
+ redirectTarget,
196
+ opts?.scope ? { scope: opts.scope } : undefined,
197
+ );
168
198
  }, wait);
169
199
  }
170
200
  return;
@@ -184,6 +214,9 @@ export async function initiateOAuthLogin(
184
214
  const cid = clientId || cfg.clientId;
185
215
  if (!cid) throw new Error('OAuth client_id is not available');
186
216
 
217
+ // 申请 scope:调用方显式传入则用之(含额外 scope),否则沿用基础 scope(零波及其它站点)
218
+ const requestedScope = opts?.scope?.trim() || cfg.scope;
219
+
187
220
  // Always encode state as JSON with CSRF token + redirect target
188
221
  const csrf = randomState();
189
222
  const state = JSON.stringify({ csrf, redirect: target });
@@ -207,7 +240,7 @@ export async function initiateOAuthLogin(
207
240
  response_type: 'code',
208
241
  client_id: cid,
209
242
  redirect_uri: cfg.redirectUri,
210
- scope: cfg.scope,
243
+ scope: requestedScope,
211
244
  code_challenge: pkce.challenge,
212
245
  code_challenge_method: 'S256',
213
246
  state,
@@ -224,7 +257,7 @@ export async function initiateOAuthLogin(
224
257
  response_type: 'code',
225
258
  client_id: cid,
226
259
  redirect_uri: cfg.redirectUri,
227
- scope: cfg.scope,
260
+ scope: requestedScope,
228
261
  state,
229
262
  });
230
263
  traceRedirect(`${cfg.authorizeUrl}?${params}`, {
package/src/index.ts CHANGED
@@ -49,6 +49,7 @@ export {
49
49
  handleOAuthCallback,
50
50
  isOAuthEnabled,
51
51
  OAuthCallbackError,
52
+ withOAuthScopes,
52
53
  } from './auth/oauth-login';
53
54
  export { decodeJwtPayload } from './auth/jwt-payload';
54
55
  export { buildLoginUrl } from './auth/roles';