@autional/shared 0.1.0-rc.50 → 0.1.0-rc.52

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.50",
3
+ "version": "0.1.0-rc.52",
4
4
  "description": "Autional shared layer — API client, auth, types, hooks, utils",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./src/index.ts",
@@ -4552,15 +4552,6 @@ export async function adminRoleActivations(params?: {
4552
4552
  return res.data;
4553
4553
  }
4554
4554
 
4555
- /**
4556
- * 批准角色激活
4557
- * 管理员批准待处理的角色激活请求
4558
- */
4559
- export async function adminRoleActivationsApproveByRoleActivationsPost(roleActivationId: string) {
4560
- const res = await api.post(`/identity/api/v1/admin/role-activations/${roleActivationId}/approve`);
4561
- return res.data;
4562
- }
4563
-
4564
4555
  /**
4565
4556
  * 撤销角色激活
4566
4557
  * 管理员撤销正在生效的角色激活,立即移除用户的提权权限
@@ -5151,15 +5142,6 @@ export async function authLogoutPost() {
5151
5142
  return res.data;
5152
5143
  }
5153
5144
 
5154
- /**
5155
- * 发送魔法链接
5156
- * 接收邮箱,生成一次性 magic link token 并发送到用户邮箱(dev模式打印到日志)
5157
- */
5158
- export async function authMagicLinkPost(data: MagicLinkRequest) {
5159
- const res = await api.post(`/identity/api/v1/auth/magic-link`, data);
5160
- return res.data;
5161
- }
5162
-
5163
5145
  /**
5164
5146
  * 魔法链接回调 (GET→POST 双步跳转)
5165
5147
  * GET: 渲染中转HTML页面 (无泄露), POST: 验证token生成JWT
@@ -5182,17 +5164,6 @@ export async function authMagicLinkCallbackPost(params?: {
5182
5164
  return res.data;
5183
5165
  }
5184
5166
 
5185
- /**
5186
- * 验证魔法链接
5187
- * 验证 token 有效性,返回 JWT 令牌和用户信息
5188
- */
5189
- export async function authMagicLinkConfirm(params?: {
5190
- token: string; // 魔法链接令牌
5191
- }) {
5192
- const res = await api.get(`/identity/api/v1/auth/magic-link/confirm`, { params });
5193
- return res.data;
5194
- }
5195
-
5196
5167
  /**
5197
5168
  * 请求发送魔法链接
5198
5169
  * 验证邮箱并发送包含魔法链接的邮件。无论邮箱是否注册均返回成功(防枚举)。
@@ -6970,62 +6941,6 @@ export async function mfaTrustedDevicesByTrustedDevices(trustedDeviceId: string)
6970
6941
  return res.data;
6971
6942
  }
6972
6943
 
6973
- /**
6974
- * 列出WebAuthn凭证
6975
- * 列出用户所有已注册的WebAuthn/通行密钥凭证,包含名称和最后使用时间。参考:W3C WebAuthn Level 2、FIDO2 CTAP 2.1。
6976
- */
6977
- export async function mfaWebauthnCredentials(params?: {
6978
- page?: number; // 页码
6979
- page_size?: number; // 每页条数
6980
- }) {
6981
- const res = await api.get(`/mfa/api/v1/mfa/webauthn/credentials`, { params });
6982
- return res.data;
6983
- }
6984
-
6985
- /**
6986
- * 开始WebAuthn凭证注册
6987
- * 生成 WebAuthn credential creation options (challenge, rp, user, pubKeyCredParams)
6988
- */
6989
- export async function mfaWebauthnCredentialsRegisterPost(data: BeginWebAuthnRegistrationRequest) {
6990
- const res = await api.post(`/mfa/api/v1/mfa/webauthn/credentials/register`, data);
6991
- return res.data;
6992
- }
6993
-
6994
- /**
6995
- * 完成WebAuthn凭证注册
6996
- * 验证 attestation 响应并存储凭证。需要先调用 /mfa/webauthn/credentials/register 获取 creation options。
6997
- */
6998
- export async function mfaWebauthnCredentialsRegisterVerifyPost(data: FinishWebAuthnRegistrationRequest) {
6999
- const res = await api.post(`/mfa/api/v1/mfa/webauthn/credentials/register/verify`, data);
7000
- return res.data;
7001
- }
7002
-
7003
- /**
7004
- * 删除WebAuthn凭证
7005
- * 删除指定WebAuthn凭证。参考:W3C WebAuthn Level 2、FIDO2 CTAP 2.1。
7006
- */
7007
- export async function mfaWebauthnCredentialsByCredentialsDelete(webauthnCredentialId: string) {
7008
- await api.delete(`/mfa/api/v1/mfa/webauthn/credentials/${webauthnCredentialId}`);
7009
- }
7010
-
7011
- /**
7012
- * 获取WebAuthn凭证详情
7013
- * 根据ID获取指定WebAuthn凭证的详细信息。参考:W3C WebAuthn Level 2、FIDO2 CTAP 2.1。
7014
- */
7015
- export async function mfaWebauthnCredentialsByCredentials(webauthnCredentialId: string) {
7016
- const res = await api.get(`/mfa/api/v1/mfa/webauthn/credentials/${webauthnCredentialId}`);
7017
- return res.data;
7018
- }
7019
-
7020
- /**
7021
- * 重命名WebAuthn凭证
7022
- * 重命名指定WebAuthn凭证的设备名称。参考:W3C WebAuthn Level 2、FIDO2 CTAP 2.1。
7023
- */
7024
- export async function mfaWebauthnCredentialsByCredentialsPut(webauthnCredentialId: string, data: UpdateWebAuthnCredentialRequest) {
7025
- const res = await api.put(`/mfa/api/v1/mfa/webauthn/credentials/${webauthnCredentialId}`, data);
7026
- return res.data;
7027
- }
7028
-
7029
6944
  // ============================================================
7030
6945
  // Notification Service
7031
6946
  // ============================================================
@@ -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: 798 · source sha256: e82f038da18dc0935623718a7516ede07d741ed071275aad4ca1610db00a8d5d
4
+ // rows: 801 · source sha256: 812f1ec64dade2b940ae6f12af43fb170e9f0f7f658b707fc29f1f0fd48c50b5
5
5
  //
6
6
  // 单一真源链:service-core/base/error/semantics.go(Go)→ errors.semantics.json → 本文件。
7
7
  // ⚠️ 禁止在本文件或页面里手抄错误码分支:请消费 ERROR_SEMANTICS / UNPROVISIONED_CODES。
@@ -177,6 +177,9 @@ export const ERROR_SEMANTICS: Readonly<Record<number, ErrorSemantics>> = {
177
177
  20600007: { code: 20600007, httpStatus: 400, class: 'invalid', absence: '', uiObservation: 'form_error', retryable: false, docsPath: '/errors/20600007' },
178
178
  20600008: { code: 20600008, httpStatus: 400, class: 'invalid', absence: '', uiObservation: 'form_error', retryable: false, docsPath: '/errors/20600008' },
179
179
  20800004: { code: 20800004, httpStatus: 404, class: 'not_found', absence: 'entity', uiObservation: 'not_found_page', retryable: false, docsPath: '/errors/20800004' },
180
+ 20900001: { code: 20900001, httpStatus: 503, class: 'unavailable', absence: '', uiObservation: 'transient', retryable: true, docsPath: '/errors/20900001' },
181
+ 20900002: { code: 20900002, httpStatus: 503, class: 'unavailable', absence: '', uiObservation: 'transient', retryable: true, docsPath: '/errors/20900002' },
182
+ 21000002: { code: 21000002, httpStatus: 503, class: 'unavailable', absence: '', uiObservation: 'transient', retryable: true, docsPath: '/errors/21000002' },
180
183
  21000004: { code: 21000004, httpStatus: 503, class: 'unavailable', absence: '', uiObservation: 'transient', retryable: true, docsPath: '/errors/21000004' },
181
184
  21100004: { code: 21100004, httpStatus: 500, class: 'internal', absence: '', uiObservation: 'unexpected', retryable: false, docsPath: '/errors/21100004' },
182
185
  21100006: { code: 21100006, httpStatus: 404, class: 'not_found', absence: 'entity', uiObservation: 'not_found_page', retryable: false, docsPath: '/errors/21100006' },
@@ -859,8 +862,8 @@ export const UNPROVISIONED_CODES: ReadonlySet<number> = new Set([]);
859
862
  export const EMPTY_STATE_CODES: ReadonlySet<number> = new Set([]);
860
863
 
861
864
  export const ERROR_SEMANTICS_META = {
862
- rowCount: 798,
863
- sourceSha256: 'e82f038da18dc0935623718a7516ede07d741ed071275aad4ca1610db00a8d5d',
865
+ rowCount: 801,
866
+ sourceSha256: '812f1ec64dade2b940ae6f12af43fb170e9f0f7f658b707fc29f1f0fd48c50b5',
864
867
  } as const;
865
868
 
866
869
  /** 具名错误码常量(契约 name → code)。页面只消费常量,不写数字字面量。 */
@@ -2157,14 +2157,6 @@ export function useAuthMagic_linkCallback(params?: any) {
2157
2157
  });
2158
2158
  }
2159
2159
 
2160
- /** 验证魔法链接 */
2161
- export function useAuthMagic_linkConfirm(params?: any) {
2162
- return useQuery({
2163
- queryKey: ['identity-service', params] as const,
2164
- queryFn: () => api.authMagicLinkConfirm(params),
2165
- });
2166
- }
2167
-
2168
2160
  /** 获取当前登录用户信息 */
2169
2161
  export function useAuthMe() {
2170
2162
  return useQuery({
@@ -2693,22 +2685,6 @@ export function useMfaTrusted_devicesByTrustedDevices(trustedDeviceId: string) {
2693
2685
  });
2694
2686
  }
2695
2687
 
2696
- /** 列出WebAuthn凭证 */
2697
- export function useMfaWebauthnCredentials(params?: any) {
2698
- return useQuery({
2699
- queryKey: ['mfa-service', params] as const,
2700
- queryFn: () => api.mfaWebauthnCredentials(params),
2701
- });
2702
- }
2703
-
2704
- /** 获取WebAuthn凭证详情 */
2705
- export function useMfaWebauthnCredentialsByCredentials(webauthnCredentialId: string) {
2706
- return useQuery({
2707
- queryKey: ['mfa-service', 'by_' + webauthnCredentialId] as const,
2708
- queryFn: () => api.mfaWebauthnCredentialsByCredentials(webauthnCredentialId),
2709
- });
2710
- }
2711
-
2712
2688
  // --- notification-service ---
2713
2689
 
2714
2690
  /** 管理端列出公告 */
@@ -7213,17 +7189,6 @@ export function usePostAdminRobotsIntentRevokeByRobots() {
7213
7189
  });
7214
7190
  }
7215
7191
 
7216
- /** 批准角色激活 */
7217
- export function usePostAdminRole_activationsApproveByRoleActivations() {
7218
- const qc = useQueryClient();
7219
- return useMutation({
7220
- mutationFn: (roleActivationId: string) => api.adminRoleActivationsApproveByRoleActivationsPost(roleActivationId),
7221
- onSuccess: () => {
7222
- qc.invalidateQueries({ queryKey: ['identity-service'] });
7223
- },
7224
- });
7225
- }
7226
-
7227
7192
  /** 撤销角色激活 */
7228
7193
  export function usePostAdminRole_activationsRevokeByRoleActivations() {
7229
7194
  const qc = useQueryClient();
@@ -7675,17 +7640,6 @@ export function usePostAuthLogout() {
7675
7640
  });
7676
7641
  }
7677
7642
 
7678
- /** 发送魔法链接 */
7679
- export function usePostAuthMagic_link() {
7680
- const qc = useQueryClient();
7681
- return useMutation({
7682
- mutationFn: (data: any) => api.authMagicLinkPost(data),
7683
- onSuccess: () => {
7684
- qc.invalidateQueries({ queryKey: ['identity-service'] });
7685
- },
7686
- });
7687
- }
7688
-
7689
7643
  /** 魔法链接回调 (GET→POST 双步跳转) */
7690
7644
  export function usePostAuthMagic_linkCallback() {
7691
7645
  const qc = useQueryClient();
@@ -9083,50 +9037,6 @@ export function useDeleteMfaTrusted_devicesByTrustedDevices() {
9083
9037
  });
9084
9038
  }
9085
9039
 
9086
- /** 开始WebAuthn凭证注册 */
9087
- export function usePostMfaWebauthnCredentialsRegister() {
9088
- const qc = useQueryClient();
9089
- return useMutation({
9090
- mutationFn: (data: any) => api.mfaWebauthnCredentialsRegisterPost(data),
9091
- onSuccess: () => {
9092
- qc.invalidateQueries({ queryKey: ['mfa-service'] });
9093
- },
9094
- });
9095
- }
9096
-
9097
- /** 完成WebAuthn凭证注册 */
9098
- export function usePostMfaWebauthnCredentialsRegisterVerify() {
9099
- const qc = useQueryClient();
9100
- return useMutation({
9101
- mutationFn: (data: any) => api.mfaWebauthnCredentialsRegisterVerifyPost(data),
9102
- onSuccess: () => {
9103
- qc.invalidateQueries({ queryKey: ['mfa-service'] });
9104
- },
9105
- });
9106
- }
9107
-
9108
- /** 删除WebAuthn凭证 */
9109
- export function useDeleteMfaWebauthnCredentialsByCredentials() {
9110
- const qc = useQueryClient();
9111
- return useMutation({
9112
- mutationFn: (webauthnCredentialId: string) => api.mfaWebauthnCredentialsByCredentialsDelete(webauthnCredentialId),
9113
- onSuccess: () => {
9114
- qc.invalidateQueries({ queryKey: ['mfa-service'] });
9115
- },
9116
- });
9117
- }
9118
-
9119
- /** 重命名WebAuthn凭证 */
9120
- export function usePutMfaWebauthnCredentialsByCredentials() {
9121
- const qc = useQueryClient();
9122
- return useMutation({
9123
- mutationFn: ({ webauthnCredentialId, data }: { webauthnCredentialId: string, data: any }) => api.mfaWebauthnCredentialsByCredentialsPut(webauthnCredentialId, data),
9124
- onSuccess: () => {
9125
- qc.invalidateQueries({ queryKey: ['mfa-service'] });
9126
- },
9127
- });
9128
- }
9129
-
9130
9040
  // --- notification-service ---
9131
9041
 
9132
9042
  /** 创建公告 */
@@ -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 import('../generated/api')
59
- .then(({ profileAvatar }) => profileAvatar())
60
- .then((res) => {
61
- const avatarUrl = ((res as { avatarUrl?: string } | undefined)?.avatarUrl ?? '').trim();
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
- // 两个请求都失败 — keep reporting loading to prevent re-render loops
94
- // (OAuth PKCE or BFF redirect will resolve the page before error matters)
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 'loading';
111
+ return 'error';
97
112
  }
98
113
 
99
114
  // 等待中