@autional/shared 0.1.0-rc.41 → 0.1.0-rc.43

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.41",
3
+ "version": "0.1.0-rc.43",
4
4
  "description": "Autional shared layer — API client, auth, types, hooks, utils",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./src/index.ts",
@@ -43,6 +43,11 @@ function expiredJwt(): string {
43
43
  return `eyJhbGciOiJIUzI1NiJ9.${payload}.sig`;
44
44
  }
45
45
 
46
+ function liveJwt(): string {
47
+ const payload = btoa(JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 }));
48
+ return `eyJhbGciOiJIUzI1NiJ9.${payload}.sig`;
49
+ }
50
+
46
51
  describe('U352: 预刷新成功后注入链完整性', () => {
47
52
  beforeEach(() => {
48
53
  captured = [];
@@ -87,3 +92,37 @@ describe('U352: 预刷新成功后注入链完整性', () => {
87
92
  expect(captured[0].headers['X-Tenant-ID']).toBe('tenant-abc');
88
93
  });
89
94
  });
95
+
96
+ // 地址栏唯一权威(Wave 2):无 token 的公开认证入口不得被 localStorage 残留租户污染。
97
+ describe('无 token 不注入 X-Tenant-ID', () => {
98
+ beforeEach(() => {
99
+ captured = [];
100
+ installCaptureAdapter();
101
+ useAuthStore.getState().clearAuth();
102
+ useAuthStore.getState().setCurrentTenant('tenant-stale');
103
+ });
104
+
105
+ afterEach(() => {
106
+ apiClient.defaults.adapter = originalAdapter as any;
107
+ vi.restoreAllMocks();
108
+ useAuthStore.getState().clearAuth();
109
+ });
110
+
111
+ it('无 token:残留租户不注入 header', async () => {
112
+ await apiClient.get('/probe/public');
113
+ expect(captured[0].headers['X-Tenant-ID']).toBeUndefined();
114
+ expect(captured[0].headers['Authorization']).toBeUndefined();
115
+ });
116
+
117
+ it('调用方显式 X-Tenant-ID 原样保留(不注入也不清除)', async () => {
118
+ await apiClient.get('/probe/public', { headers: { 'X-Tenant-ID': 'explicit-tenant' } });
119
+ expect(captured[0].headers['X-Tenant-ID']).toBe('explicit-tenant');
120
+ });
121
+
122
+ it('有 token:仍注入当前租户(内部调用链回归)', async () => {
123
+ useAuthStore.getState().setAuth(liveJwt(), 'rt-live', { id: 'u-1', username: 'demo' } as any);
124
+ await apiClient.get('/probe/authed');
125
+ expect(captured[0].headers['X-Tenant-ID']).toBe('tenant-stale');
126
+ expect(String(captured[0].headers['Authorization'])).toMatch(/^Bearer /);
127
+ });
128
+ });
package/src/api/client.ts CHANGED
@@ -35,8 +35,11 @@ function setupInterceptors(instance: AxiosInstance) {
35
35
  config.headers.Authorization = `Bearer ${bearer}`;
36
36
  }
37
37
 
38
+ // 无 token 的公开认证入口(登录/OAuth/QR/恢复)以地址栏租户为唯一权威:
39
+ // 此时 localStorage 里的 currentTenantId 可能是上次会话残留,注入会覆盖显式租户。
40
+ // 有 token 才注入(内部调用链沿用它);调用方显式设置的 X-Tenant-ID 不受影响。
38
41
  const tenantId = AuthService.getCurrentTenantId();
39
- if (tenantId) {
42
+ if (bearer && tenantId) {
40
43
  config.headers['X-Tenant-ID'] = tenantId;
41
44
  }
42
45
 
@@ -179,6 +182,10 @@ export function createApiClient(baseUrl: string): AxiosInstance {
179
182
  const instance = axios.create({
180
183
  baseURL: baseUrl,
181
184
  timeout: 30000,
185
+ // 平台跨源只认 Authorization 头(网关 cors.allow_credentials=false):
186
+ // 显式关闭凭证,避免将来默认值/调用方改动把 cookie 带进跨源请求
187
+ // (带凭证的跨源要求网关回写 ACAC,而动态租户 origin 永不回写)。
188
+ withCredentials: false,
182
189
  headers: { 'Content-Type': 'application/json' },
183
190
  });
184
191
  setupInterceptors(instance);
@@ -5664,8 +5664,10 @@ export async function authOauthAccounts() {
5664
5664
  * 获取OAuth提供商列表
5665
5665
  * 获取系统支持的所有OAuth登录提供者列表
5666
5666
  */
5667
- export async function authOauthProviders() {
5668
- const res = await api.get(`/identity/api/v1/auth/oauth/providers`);
5667
+ export async function authOauthProviders(params?: {
5668
+ tenantId?: string; // 显式租户(地址栏/slug 优先于 localStorage 残留)
5669
+ }) {
5670
+ const res = await api.get(`/identity/api/v1/auth/oauth/providers`, { params });
5669
5671
  return res.data;
5670
5672
  }
5671
5673
 
@@ -5770,8 +5772,8 @@ export async function authQrLoginConfirmPost(data: QrLoginConfirmRequest) {
5770
5772
  * 发起二维码登录
5771
5773
  * 生成一个新的二维码登录会话,返回会话令牌和数字匹配码供用户扫描
5772
5774
  */
5773
- export async function authQrLoginInitiatePost() {
5774
- const res = await api.post(`/identity/api/v1/auth/qr-login/initiate`);
5775
+ export async function authQrLoginInitiatePost(data?: QrLoginInitiateRequest) {
5776
+ const res = await api.post(`/identity/api/v1/auth/qr-login/initiate`, data);
5775
5777
  return res.data;
5776
5778
  }
5777
5779
 
@@ -3196,6 +3196,25 @@ export interface PublicCertificationListResponse {
3196
3196
  total?: number; // 总条数(平铺,便于直接读取)
3197
3197
  }
3198
3198
 
3199
+ // P2 四态评估(2026-10-27)—— 手改 additive:本源生成器 scripts/generate_api_ts.py
3200
+ // 仍在旧 monorepo(D:/go/auth_ms_new),多仓工作区不可用;字段与 compliance-service
3201
+ // swagger(PublicComplianceStatusResponse / SecurityScore)逐字段对齐,重生成前勿改形状。
3202
+ export interface AssessmentCoveragePublic {
3203
+ assessed?: number; // @example 7
3204
+ percent?: number; // @example 70
3205
+ total?: number; // @example 10
3206
+ }
3207
+
3208
+ export interface FrameworkAssessmentPublic {
3209
+ controlsAssessed?: number; // @example 7
3210
+ controlsTotal?: number; // @example 10
3211
+ controlsUnknown?: number; // @example 3
3212
+ displayName?: string; // @example ISO/IEC 27001:2022
3213
+ framework?: string; // 门禁键;独立标准为空 | @example iso27001
3214
+ standardId?: string; // @example iso27001_2022
3215
+ status?: string; // compliant / non_compliant / not_assessed / evaluation_error | @example not_assessed
3216
+ }
3217
+
3199
3218
  export interface PublicComplianceStatusDetailResponse {
3200
3219
  code?: number;
3201
3220
  data?: PublicComplianceStatusResponse;
@@ -3204,13 +3223,17 @@ export interface PublicComplianceStatusDetailResponse {
3204
3223
  }
3205
3224
 
3206
3225
  export interface PublicComplianceStatusResponse {
3226
+ assessmentCoverage?: AssessmentCoveragePublic;
3227
+ assessmentVersion?: string; // @example assessment-v2
3228
+ evaluationError?: boolean; // 只表示"是否发生评估异常",不含内部错误串 | @example False
3229
+ frameworkAssessments?: FrameworkAssessmentPublic[]; // 已启用门禁的评估结果(四态 + 覆盖度)
3207
3230
  frameworksEnabled?: string[]; // @example ['["gdpr"', '"iso27001"', '"sox"]']
3208
- gdprCompliant?: boolean; // @example True
3231
+ gdprCompliant?: boolean; // legacy:gate 已启用且状态为 compliant 才为 true | @example True
3209
3232
  iso27001Compliant?: boolean; // @example True
3210
3233
  lastAuditDate?: string; // @example 2026-03-15
3211
3234
  nextAuditDate?: string; // @example 2026-09-15
3212
3235
  openIssuesRange?: string; // @example 1-5
3213
- overallStatus?: string; // @example compliant
3236
+ overallStatus?: string; // compliant / non_compliant / not_assessed / evaluation_error | @example compliant
3214
3237
  soxCompliant?: boolean; // @example True
3215
3238
  }
3216
3239
 
@@ -3565,12 +3588,14 @@ export interface ScoreSnapshotItem {
3565
3588
  }
3566
3589
 
3567
3590
  export interface SecurityScore {
3591
+ assessmentCoverage?: AssessmentCoveragePublic;
3568
3592
  calculatedAt?: string; // @example 2026-05-09T12:00:00Z
3569
3593
  dimensions?: SecurityScoreDim[];
3570
3594
  grade?: string; // @example A
3571
3595
  maxScore?: number; // @example 100
3572
- methodologyVersion?: string; // @example v1.0
3596
+ methodologyVersion?: string; // @example assessment-v2
3573
3597
  overallScore?: number; // @example 94
3598
+ scoreAvailable?: boolean; // false = 无任何框架完成评估,overallScore 无意义 | @example True
3574
3599
  }
3575
3600
 
3576
3601
  export interface SecurityScoreDim {
@@ -4760,6 +4785,7 @@ export interface CompleteAccountRecoveryRequest {
4760
4785
  newPassword: string; // 新密码
4761
4786
  passwordTransmission?: string; // plain|hash|symmetric|asymmetric
4762
4787
  recoveryToken: string; // 恢复令牌
4788
+ tenantId?: string; // 显式租户(非空时必须与恢复令牌租户一致)
4763
4789
  }
4764
4790
 
4765
4791
  export interface CompleteAccountRecoveryResponse {
@@ -5656,6 +5682,10 @@ export interface QrLoginConfirmRequest {
5656
5682
  token: string;
5657
5683
  }
5658
5684
 
5685
+ export interface QrLoginInitiateRequest {
5686
+ tenantId?: string; // 显式租户(地址栏/slug 优先)
5687
+ }
5688
+
5659
5689
  export interface QrLoginInitiateResponse {
5660
5690
  expiresIn?: number;
5661
5691
  numberMatching?: string;
@@ -5831,6 +5861,7 @@ export interface RegisterResponse {
5831
5861
  export interface RequestAccountRecoveryRequest {
5832
5862
  identity: string; // 已知的身份标识 | @example john@example.com
5833
5863
  method: "backup_email" | "security_qa" | "trusted_device" | "sms"; // 恢复方法
5864
+ tenantId?: string; // 显式租户(地址栏/slug 优先)
5834
5865
  }
5835
5866
 
5836
5867
  export interface RequestAccountRecoveryResponseWrapper {
@@ -6283,6 +6314,7 @@ export interface VerificationTrackingQueryResponse {
6283
6314
  export interface VerifyAccountRecoveryRequest {
6284
6315
  code: string; // 验证码
6285
6316
  recoveryToken: string; // 恢复令牌
6317
+ tenantId?: string; // 显式租户(非空时必须与恢复令牌租户一致)
6286
6318
  }
6287
6319
 
6288
6320
  /** 验证邮箱/手机号变更 */
@@ -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 } from '@testing-library/react';
4
+ import { renderHook, cleanup, waitFor } from '@testing-library/react';
5
5
  import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
6
6
 
7
7
  // ============================================================
@@ -10,11 +10,12 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
10
10
  // 而 RequireAuth(唯一登录交棒点)在 Outlet 内 ⇒ 无会话冷启动永停 Spin。
11
11
  // ============================================================
12
12
 
13
- const { mockQueries } = vi.hoisted(() => ({
13
+ const { mockQueries, mockProfileAvatar } = vi.hoisted(() => ({
14
14
  mockQueries: {
15
15
  perms: { data: undefined as unknown, isError: false },
16
16
  tenants: { data: undefined as unknown, isError: false },
17
17
  },
18
+ mockProfileAvatar: vi.fn(),
18
19
  }));
19
20
 
20
21
  vi.mock('../../auth/auth-queries', () => ({
@@ -22,6 +23,11 @@ vi.mock('../../auth/auth-queries', () => ({
22
23
  useTenantsQuery: () => mockQueries.tenants,
23
24
  }));
24
25
 
26
+ // U447:启动补读头像走生成客户端(动态 import);此处拦截模块,避免测试打真实网络。
27
+ vi.mock('../../generated/api', () => ({
28
+ profileAvatar: mockProfileAvatar,
29
+ }));
30
+
25
31
  import { useBootstrap } from '../useBootstrap';
26
32
  import { useAuthStore } from '../../auth/store';
27
33
 
@@ -50,6 +56,8 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
50
56
  resetAuthStore();
51
57
  mockQueries.perms = { data: undefined, isError: false };
52
58
  mockQueries.tenants = { data: undefined, isError: false };
59
+ mockProfileAvatar.mockReset();
60
+ mockProfileAvatar.mockResolvedValue({});
53
61
  });
54
62
 
55
63
  afterEach(() => {
@@ -88,4 +96,33 @@ describe('useBootstrap(F-W5b 无会话语义)', () => {
88
96
  const { result } = renderHook(() => useBootstrap(), { wrapper });
89
97
  expect(result.current).toBe('loading');
90
98
  });
99
+
100
+ // U447:登录响应与 /auth/me 都不含 avatarUrl —— 启动必须补读一次 profile 头像,
101
+ // 否则换浏览器/新登录后顶栏头像恒为首字母。
102
+ it('U447:有会话 → 补读 /profile/avatar 并写回认证快照', async () => {
103
+ useAuthStore.setState({
104
+ accessToken: 'token-xyz',
105
+ user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
106
+ permissions: ['user.read'],
107
+ tenants: [{ id: 't1', name: 'demo', role: 'member' }],
108
+ });
109
+ mockProfileAvatar.mockResolvedValue({ avatarUrl: 'https://cdn.example.com/a.png' });
110
+ renderHook(() => useBootstrap(), { wrapper });
111
+ await waitFor(() =>
112
+ expect(useAuthStore.getState().user?.avatarUrl).toBe('https://cdn.example.com/a.png'),
113
+ );
114
+ });
115
+
116
+ it('U447:头像接口失败/为空 → 快照保持原样(展示层回落首字母)', async () => {
117
+ useAuthStore.setState({
118
+ accessToken: 'token-xyz',
119
+ user: { id: 'u-1', username: 'demo', email: 'demo@example.com', status: 'active' },
120
+ permissions: ['user.read'],
121
+ tenants: [{ id: 't1', name: 'demo', role: 'member' }],
122
+ });
123
+ mockProfileAvatar.mockRejectedValue(new Error('profile down'));
124
+ renderHook(() => useBootstrap(), { wrapper });
125
+ await waitFor(() => expect(mockProfileAvatar).toHaveBeenCalled());
126
+ expect(useAuthStore.getState().user?.avatarUrl).toBeUndefined();
127
+ });
91
128
  });
@@ -59,6 +59,10 @@ function shallowEqual(a: AuthSnapshot, b: AuthSnapshot): boolean {
59
59
  if (a.currentTenantId !== b.currentTenantId) return false;
60
60
  if (a.user?.username !== b.user?.username) return false;
61
61
  if (a.user?.email !== b.user?.email) return false;
62
+ // 头像/展示名可在登录后原地更新(个人资料页上传头像、magic-link 补全资料):
63
+ // 不参与比较时快照被判定"未变化",顶部头像会停在旧值直到刷新页面。
64
+ if (a.user?.avatarUrl !== b.user?.avatarUrl) return false;
65
+ if (a.user?.displayName !== b.user?.displayName) return false;
62
66
  if (a.permissions.length !== b.permissions.length) return false;
63
67
  if (a.tenants.length !== b.tenants.length) return false;
64
68
  // 简化的数组比较:内容变更时下个事件循环会触发重新计算
@@ -46,6 +46,33 @@ export function useBootstrap(): BootstrapState {
46
46
  }
47
47
  }, [tentsQuery.data]);
48
48
 
49
+ // U447:头像补读 —— 登录响应与 /auth/me 都不含 avatarUrl(头像存在 profile 服务),
50
+ // 认证快照里的头像只在上传当次或同浏览器持久化后才有值。启动时补读一次
51
+ // GET /profile/avatar 并写回快照,顶栏 UserMenu 才能显示账号真实头像;
52
+ // 失败静默(展示层回落首字母,不影响任何业务流程)。
53
+ // 用动态 import 引生成客户端:generated/api 反向 import '@autional/shared',
54
+ // 静态导入会在包入口形成循环,动态导入等入口初始化完再求值。
55
+ useEffect(() => {
56
+ if (!hasToken) return;
57
+ let cancelled = false;
58
+ void import('../generated/api')
59
+ .then(({ profileAvatar }) => profileAvatar())
60
+ .then((res) => {
61
+ const avatarUrl = ((res as { avatarUrl?: string } | undefined)?.avatarUrl ?? '').trim();
62
+ if (cancelled || !avatarUrl) return;
63
+ const current = useAuthStore.getState().user;
64
+ if (current && current.avatarUrl !== avatarUrl) {
65
+ useAuthStore.getState().setUser({ ...current, avatarUrl });
66
+ }
67
+ })
68
+ .catch(() => {
69
+ /* 忽略:缺头像不影响启动 */
70
+ });
71
+ return () => {
72
+ cancelled = true;
73
+ };
74
+ }, [hasToken]);
75
+
49
76
  // 无会话 = 无数据可引导:返回 'idle',登录交棒由 RequireAuth/守卫决策(见上)。
50
77
  // 不得返回 'loading':Layout 消费者(platform-console)以 bootstrap==='loading'
51
78
  // 挡 Outlet,而 RequireAuth 在 Outlet 里 ⇒ 无会话冷启动永停 Spin、守卫永不挂载(F-W5b)。