@yhgale/shared 0.1.1 → 0.1.3

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/dist/index.d.ts CHANGED
@@ -1,767 +1,6 @@
1
- /**
2
- * gale-js type contracts —— wire <-> resource 双层模型。
3
- *
4
- * **设计要点**
5
- * - `XxxJSON` 描述 fapi 实际产出的 wire 形态。规则:**所有 fapi/bapi 接口
6
- * 字段一律 camelCase**(与 DB snake_case 解耦,由 Prisma `@map` 桥接)。
7
- * wire 与 resource 的字段名、形状几乎一致;JSON → Resource 主要做:
8
- * - 时间字段从 ISO string / 秒 / 毫秒统一为 epoch ms(number)
9
- * - 把 nullable / optional 收敛成 SDK 消费侧更友好的 default
10
- * - 派生便利字段(如 `primaryEmail`、`primaryIdentity`)
11
- * 早期某些路由曾写过 snake_case,已统一收紧。
12
- * - `XxxResource` 是开发者拿到的 normalized 视图,全 camelCase + 强类型。
13
- *
14
- * **资源** vs **Wire** 的命名对照(与 Clerk 的资源体系类似但简化):
15
- * - SignInAttempt —— 鉴权过程中的"尝试"对象(status / factor 状态)
16
- * - Session —— 已建立的会话(userId / status / expiresAt / ...)
17
- * - User —— 平台用户视图(仅暴露公开字段,私密字段由 ZenStack 已过滤)
18
- * - Identity —— UserIdentity 子集(type=email/phone/oauth/web3_wallet)
19
- * - Organization —— 组织(dual-role:app_id=NULL 的 workspace 与
20
- * app_id=有值的端用户组)
21
- * - Token —— `/sessions/:id/tokens` 返回的 short-lived JWT 载体
22
- */
23
-
24
- /** 通用分页响应封装(BAPI 用;fapi 暂不分页) */
25
- interface PageJSON<T> {
26
- data: T[];
27
- total_count: number;
28
- }
29
- type IdentityType = 'email' | 'phone' | 'oauth' | 'web3_wallet' | 'passkey';
30
- /**
31
- * Wire form of UserIdentity 行(fapi `/me.identities[]`,Prisma camelCase)。
32
- * 字段名直接来自 zmodel 的 `@map` 之后的 Prisma model(camelCase)。
33
- */
34
- interface IdentityJSON {
35
- object: 'identity';
36
- id: GaleId;
37
- type: IdentityType;
38
- identifier: string;
39
- /** verified | unverified | transferable | failed | expired */
40
- verificationStatus: string | null;
41
- /** Legacy/current FAPI wire field. Normalized to verificationStatus by parsers. */
42
- isVerified?: boolean;
43
- isPrimary: boolean;
44
- createdAt: number | string;
45
- updatedAt: number | string;
46
- }
47
- /** SDK 消费者拿到的 Resource,全 camelCase + Date 已被规范化为 ms */
48
- interface IdentityResource {
49
- object: 'identity';
50
- id: GaleId;
51
- type: IdentityType;
52
- identifier: string;
53
- verificationStatus: string | null;
54
- isPrimary: boolean;
55
- createdAt: number;
56
- updatedAt: number;
57
- }
58
- interface UserJSON {
59
- object: 'user';
60
- id: GaleId;
61
- instanceId?: GaleId;
62
- username?: string | null;
63
- displayName?: string | null;
64
- imageUrl?: string | null;
65
- publicMetadata?: Record<string, unknown> | null;
66
- unsafeMetadata?: Record<string, unknown> | null;
67
- bannedAt?: number | string | null;
68
- lockedAt?: number | string | null;
69
- lastSignInAt?: number | string | null;
70
- createdAt: number | string;
71
- updatedAt: number | string;
72
- identities?: IdentityJSON[];
73
- }
74
- /**
75
- * `/v1/me` 响应:UserJSON + session 摘要。
76
- *
77
- * 把 sessionId 与 status 放在 `/v1/me` 的同一笔回包里 —— gale-js 启动期一次
78
- * RTT 拿到所有"当前态",dashboard / accounts 都能直接 useSession.getToken()
79
- * 不再额外维护 sessionId state。
80
- */
81
- interface MeJSON extends UserJSON {
82
- session?: {
83
- id: GaleId;
84
- status: SessionStatus;
85
- activeOrganizationId?: GaleId | null;
86
- };
87
- }
88
- interface UserResource {
89
- object: 'user';
90
- id: GaleId;
91
- username: string | null;
92
- displayName: string | null;
93
- imageUrl: string | null;
94
- publicMetadata: Record<string, unknown>;
95
- unsafeMetadata: Record<string, unknown>;
96
- bannedAt: number | null;
97
- lockedAt: number | null;
98
- lastSignInAt: number | null;
99
- createdAt: number;
100
- updatedAt: number;
101
- identities: IdentityResource[];
102
- /** 主 identity(isPrimary=true),便利 getter 形态 */
103
- primaryIdentity: IdentityResource | null;
104
- /** 主 email 字符串(若主 identity 是 email),界面常用 */
105
- primaryEmail: string | null;
106
- /** 主手机号字符串(若主 identity 是 phone),界面常用 */
107
- primaryPhone: string | null;
108
- }
109
- type SessionStatus = 'active' | 'ended' | 'expired' | 'removed' | 'abandoned' | 'replaced' | 'revoked';
110
- /** Wire form of Session(fapi 全 camelCase) */
111
- interface SessionJSON {
112
- object: 'session';
113
- id: GaleId;
114
- status: SessionStatus;
115
- userId: GaleId;
116
- clientId?: GaleId | null;
117
- activeOrganizationId?: GaleId | null;
118
- expiresAt: number | string;
119
- lastActiveAt?: number | string | null;
120
- }
121
- interface SessionResource {
122
- object: 'session';
123
- id: GaleId;
124
- status: SessionStatus;
125
- userId: GaleId;
126
- clientId: GaleId | null;
127
- activeOrganizationId: GaleId | null;
128
- expiresAt: number;
129
- lastActiveAt: number | null;
130
- }
131
- /** `/v1/client/sessions/:id/tokens` 响应 */
132
- interface TokenJSON {
133
- object: 'token';
134
- jwt: string;
135
- expiresIn: number;
136
- session: SessionJSON;
137
- }
138
- interface TokenResource {
139
- object: 'token';
140
- jwt: string;
141
- /** 秒级 TTL */
142
- expiresIn: number;
143
- session: SessionResource;
144
- }
145
- type SignInStatus = 'needs_identifier' | 'needs_first_factor' | 'needs_code_verification' | 'needs_second_factor' | 'complete' | 'failed';
146
- /**
147
- * Verification 子对象(与 fapi `firstFactorVerification` jsonb 对称)。
148
- *
149
- * status 取值:
150
- * - `unverified`/`pending` —— 等待用户在 provider 完成(OAuth 跳转中)
151
- * - `verified` —— 完成
152
- * - `transferable` —— OAuth 找不到对应 sign-in 账号 / sign-up 账号已存在;
153
- * FE 收到后调对侧 create({transfer:true,transferToken})
154
- * - `failed` —— provider 错 / token 交换失败 / profile 残缺
155
- */
156
- interface VerificationJSON {
157
- strategy: string;
158
- status: string;
159
- /** OAuth:`startOauthAuthorization` 后由后端拼好的 provider authorize URL */
160
- externalVerificationRedirectUrl?: string | null;
161
- /** transferable 时附带;FE 凭此调对侧 create({transfer:true,transferToken}) */
162
- transferToken?: string | null;
163
- /** failed/transferable 时可能附带 */
164
- error?: {
165
- code: string;
166
- message?: string;
167
- } | null;
168
- }
169
- /** Wire form of `/v1/client/sign_ins[/:id/...]` envelope */
170
- interface SignInAttemptJSON {
171
- object: 'sign_in_attempt';
172
- id: GaleId;
173
- status: SignInStatus;
174
- /** 已识别的 user(用于在 password 步骤显示头像/email) */
175
- userId?: GaleId | null;
176
- identifier?: string | null;
177
- supportedFirstFactors?: {
178
- strategy: string;
179
- }[];
180
- /** MFA / Client Trust 分支出现(needs_second_factor 状态)。 */
181
- supportedSecondFactors?: {
182
- strategy: string;
183
- }[];
184
- firstFactorVerification?: VerificationJSON | null;
185
- secondFactorVerification?: VerificationJSON | null;
186
- /** 命中并完成 → 落地 session id */
187
- createdSessionId?: GaleId | null;
188
- /** 仅 complete 响应里出现;前端用于在当前域名设置 cookie(dev 跨端口场景) */
189
- clientSafeRefreshToken?: string | null;
190
- }
191
- interface SignInAttemptResource {
192
- object: 'sign_in_attempt';
193
- id: GaleId;
194
- status: SignInStatus;
195
- userId: GaleId | null;
196
- identifier: string | null;
197
- supportedFirstFactors: {
198
- strategy: string;
199
- }[];
200
- supportedSecondFactors: {
201
- strategy: string;
202
- }[];
203
- firstFactorVerification: VerificationJSON | null;
204
- secondFactorVerification: VerificationJSON | null;
205
- createdSessionId: GaleId | null;
206
- }
207
- /** fapi `/v1/client/sign_ins` 响应外层 envelope */
208
- interface SignInResponseJSON {
209
- client?: {
210
- object: 'client';
211
- id: GaleId;
212
- };
213
- response: SignInAttemptJSON;
214
- }
215
- type SignUpStatus = 'missing_requirements' | 'complete' | 'abandoned';
216
- /**
217
- * Wire form of `/v1/client/sign_ups[/:id/...]` envelope。
218
- *
219
- * 与 SignInAttemptJSON 形态对称:missingFields/unverifiedFields 表达待补全因子;
220
- * `createdSessionId` 仅在 status=complete 的 attempt_verification 响应里出现
221
- * (fapi 路由层从 issueSession 结果回填)。
222
- */
223
- /**
224
- * SignUp verifications 容器(与 fapi `verifications` jsonb 对称)。
225
- * 字段命名与 clerk 一致:`externalAccount` 承载 OAuth 流程态。
226
- */
227
- interface SignUpVerificationsJSON {
228
- externalAccount?: VerificationJSON | null;
229
- emailAddress?: VerificationJSON | null;
230
- phoneNumber?: VerificationJSON | null;
231
- }
232
- interface SignUpAttemptJSON {
233
- object: 'sign_up_attempt';
234
- id: GaleId;
235
- status: SignUpStatus;
236
- emailAddress?: string | null;
237
- phoneNumber?: string | null;
238
- username?: string | null;
239
- missingFields?: string[];
240
- unverifiedFields?: string[];
241
- /** OAuth 路径才有 externalAccount;email_code 路径整个字段为 null/缺失 */
242
- verifications?: SignUpVerificationsJSON | null;
243
- abandonAt?: number | string;
244
- resultUserId?: GaleId | null;
245
- resultSessionId?: GaleId | null;
246
- createdAt?: number | string;
247
- updatedAt?: number | string;
248
- /** 仅 attempt_verification / oauth-transfer → complete 响应里有 */
249
- createdSessionId?: GaleId | null;
250
- /** 仅 complete 响应里出现;前端用于在当前域名设置 cookie(dev 跨端口场景) */
251
- clientSafeRefreshToken?: string | null;
252
- }
253
- interface SignUpAttemptResource {
254
- object: 'sign_up_attempt';
255
- id: GaleId;
256
- status: SignUpStatus;
257
- emailAddress: string | null;
258
- phoneNumber: string | null;
259
- username: string | null;
260
- missingFields: string[];
261
- unverifiedFields: string[];
262
- verifications: SignUpVerificationsJSON | null;
263
- /** epoch ms(与 SignInAttemptResource 时间字段同形态) */
264
- abandonAt: number;
265
- resultUserId: GaleId | null;
266
- resultSessionId: GaleId | null;
267
- createdAt: number;
268
- updatedAt: number;
269
- /** 仅 status=complete 的 attempt_verification 响应里非 null */
270
- createdSessionId: GaleId | null;
271
- }
272
- interface SignUpResponseJSON {
273
- client?: {
274
- object: 'client';
275
- id: GaleId;
276
- };
277
- response: SignUpAttemptJSON;
278
- }
279
- interface ClientJSON {
280
- object: 'client';
281
- id: GaleId;
282
- /** 设备 token 形态:与 `client.id` 同值(已对齐) */
283
- deviceToken?: string;
284
- }
285
- type OrgRole = string;
286
- /** Wire form of Organization(dual-role:workspace vs end-user org) */
287
- interface OrganizationJSON {
288
- object: 'organization';
289
- id: GaleId;
290
- applicationId?: GaleId | null;
291
- name: string;
292
- slug?: string | null;
293
- imageUrl?: string | null;
294
- publicMetadata?: Record<string, unknown> | null;
295
- createdAt: number | string;
296
- updatedAt: number | string;
297
- membersCount?: number;
298
- }
299
- interface OrganizationResource {
300
- object: 'organization';
301
- id: GaleId;
302
- /** null = workspace(开发者团队);非 null = 端用户组(属于该 application) */
303
- applicationId: GaleId | null;
304
- name: string;
305
- slug: string | null;
306
- imageUrl: string | null;
307
- publicMetadata: Record<string, unknown>;
308
- createdAt: number;
309
- updatedAt: number;
310
- membersCount: number | null;
311
- }
312
- interface OrganizationMembershipJSON {
313
- object: 'organization_membership';
314
- id: GaleId;
315
- organizationId: GaleId;
316
- userId: GaleId;
317
- role: OrgRole;
318
- createdAt: number | string;
319
- updatedAt: number | string;
320
- }
321
- interface OrganizationMembershipResource {
322
- object: 'organization_membership';
323
- id: GaleId;
324
- organizationId: GaleId;
325
- userId: GaleId;
326
- role: OrgRole;
327
- createdAt: number;
328
- updatedAt: number;
329
- }
330
- interface InstanceSummary {
331
- id: GaleId;
332
- environment: GaleEnvironment;
333
- frontendApiHost: string;
334
- }
335
- /**
336
- * `GET /v1/me/mfa` 响应内层(`{ response: MfaStatusJSON }`)。
337
- *
338
- * totp.verifiedAt 为 ISO 字符串或 null(DB updatedAt,未登记时 null)。
339
- * backupCodes 字段:用户已生成过备份码则 enrolled=true,total/unused 反映当前计数。
340
- */
341
- interface MfaStatusJSON {
342
- totp: {
343
- enrolled: boolean;
344
- verifiedAt: string | null;
345
- };
346
- backupCodes: {
347
- enrolled: boolean;
348
- total: number;
349
- unused: number;
350
- };
351
- /** passkey 身份统计(Instance 启用 passkey 时返回,否则字段缺失)。 */
352
- passkeys?: {
353
- enrolled: boolean;
354
- count: number;
355
- };
356
- }
357
- /** `POST /v1/me/totp/enroll` 响应内层(201)。 */
358
- interface TotpEnrollResultJSON {
359
- strategy: 'totp';
360
- status: 'pending';
361
- secretBase32: string;
362
- otpauthUri: string;
363
- }
364
- /** `POST /v1/me/totp/confirm` 响应内层。 */
365
- interface TotpConfirmResultJSON {
366
- strategy: 'totp';
367
- status: 'verified';
368
- }
369
- /** `DELETE /v1/me/totp` 响应内层。 */
370
- interface TotpDisableResultJSON {
371
- strategy: 'totp';
372
- status: 'disabled';
373
- deletedCount: number;
374
- /** TOTP 禁用时级联清理的 backup_code identity 数(无则 0)。 */
375
- cascadeDeletedBackupCodes: number;
376
- }
377
- /** `POST /v1/me/backup_codes/generate` 响应内层(201,返回明文一次)。 */
378
- interface BackupCodesGenerateResultJSON {
379
- /** 10 条格式化明文(如 'ABC-DEF-GHJ');再次调用 generate 后旧码全部失效。 */
380
- codes: string[];
381
- /** ISO 时间戳。 */
382
- generatedAt: string;
383
- }
384
- /** `GET /v1/me/backup_codes` 响应内层(永远不返回明文)。 */
385
- interface BackupCodesStatusJSON {
386
- enrolled: boolean;
387
- total: number;
388
- unused: number;
389
- }
390
- /** `DELETE /v1/me/backup_codes` 响应内层。 */
391
- interface BackupCodesDisableResultJSON {
392
- deletedCount: number;
393
- }
394
- /** MFA 端点通用外层 envelope:`{ response: T }`。 */
395
- interface MfaResponseJSON<T> {
396
- response: T;
397
- }
398
- /**
399
- * `GET /v1/me/passkeys` 响应内层 envelope。
400
- *
401
- * 每行对应一条 UserIdentity(type='passkey');credential(publicKey/counter)
402
- * 永远不离开服务器,这里仅暴露 UI 展示需要的字段。
403
- */
404
- interface PasskeyJSON {
405
- id: string;
406
- /** base64url 编码的 credentialId(WebAuthn 规范,length 由 authenticator 决定)。 */
407
- credentialId: string;
408
- /** 用户自定义名称("MacBook Touch ID" 等);enroll 时未传则用 server fallback。 */
409
- name: string;
410
- /** ISO 时间戳。 */
411
- createdAt: string;
412
- /** ISO 时间戳或 null(从未用过则 null)。 */
413
- lastUsedAt: string | null;
414
- /** authenticator 类型(platform/cross-platform);可能缺失。 */
415
- deviceType?: string | null;
416
- }
417
- interface ListPasskeysResponseJSON {
418
- data: PasskeyJSON[];
419
- }
420
- /** `POST /v1/me/passkeys/begin_enrollment` 响应内层(201)。 */
421
- interface BeginPasskeyEnrollmentResponseJSON {
422
- response: {
423
- /** PublicKeyCredentialCreationOptionsJSON,直接传给 startRegistration。 */
424
- options: Record<string, unknown>;
425
- challengeId: string;
426
- };
427
- }
428
- /** `POST /v1/me/passkeys/finish_enrollment` 响应内层(201)。 */
429
- interface FinishPasskeyEnrollmentResponseJSON {
430
- response: {
431
- identityId: string;
432
- credentialId: string;
433
- name: string;
434
- };
435
- }
436
- /** `DELETE /v1/me/passkeys/:id` 响应内层。 */
437
- interface DeletePasskeyResponseJSON {
438
- response: {
439
- deleted: boolean;
440
- };
441
- }
442
- /** `PATCH /v1/me/passkeys/:id` 响应内层。 */
443
- interface RenamePasskeyResponseJSON {
444
- response: {
445
- renamed: boolean;
446
- };
447
- }
448
- /** `POST /v1/client/sign_ins/passkey_options` 响应(无 attempt id,discoverable)。 */
449
- interface PasskeyLoginOptionsResponseJSON {
450
- response: SignInAttemptJSON;
451
- }
452
- /** `POST /v1/client/sign_ins/:id/prepare_second_factor {strategy:'passkey'}` 响应。 */
453
- interface PreparePasskeySecondFactorResponseJSON {
454
- response: SignInAttemptJSON;
455
- }
456
- /**
457
- * `GET /v1/me/invitations` 单行 + `POST /v1/me/invitations/:id/accept` 返回的 invitation 形状。
458
- *
459
- * fapi 返回的 wire 已是 camelCase + ISO 字符串;SDK 直接透传,不做时间转换
460
- * (与 Organization / User 等资源一致,这些"展示型"字段不做 epoch ms 转换)。
461
- */
462
- interface InvitationJSON {
463
- id: string;
464
- organizationId: string;
465
- emailAddress: string;
466
- role: string;
467
- status: 'pending' | 'accepted' | 'revoked' | 'expired';
468
- expiresAt: string;
469
- createdAt: string;
470
- /** 仅 list 端点返回(便于 UI 直接展示免去二次查 org);accept 不返回此字段 */
471
- organizationName?: string;
472
- /** 仅 accept 端点返回 */
473
- acceptedAt?: string | null;
474
- /** 仅 accept 端点返回 */
475
- acceptedByUserId?: string | null;
476
- }
477
- /** `GET /v1/me/invitations` 外层 envelope。 */
478
- interface ListMyInvitationsResponseJSON {
479
- data: InvitationJSON[];
480
- }
481
- /** `POST /v1/me/invitations/:id/accept` 返回的 membership 子对象。 */
482
- interface AcceptedMembershipJSON {
483
- id: string;
484
- organizationId: string;
485
- userId: string;
486
- role: string;
487
- }
488
- /** `POST /v1/me/invitations/:id/accept` 外层 envelope。 */
489
- interface AcceptInvitationResponseJSON {
490
- data: {
491
- invitation: InvitationJSON;
492
- membership: AcceptedMembershipJSON;
493
- /** false = 幂等(用户已是成员,仅 invitation 被标 accepted) */
494
- membershipCreated: boolean;
495
- };
496
- }
497
- interface FapiErrorPayload {
498
- code: string;
499
- message: string;
500
- longMessage?: string;
501
- meta?: Record<string, unknown>;
502
- }
503
- interface FapiErrorEnvelope {
504
- errors: FapiErrorPayload[];
505
- }
506
-
507
- /**
508
- * Instance 级认证策略配置 —— types + 默认值。
509
- *
510
- * zod schemas 留在 @yhgale/apicore(后端校验用),这里只放前后端共享的类型和常量。
511
- */
512
- interface AuthAttributeConfig {
513
- enabled: boolean;
514
- required: boolean;
515
- }
516
- interface AccountPortalRedirectConfig {
517
- afterSignUpFallback: string;
518
- afterSignInFallback: string;
519
- logoLink: string;
520
- }
521
- interface AccountPortalPathConfig {
522
- signIn: string;
523
- signUp: string;
524
- userProfile: string;
525
- organizationProfile: string;
526
- createOrganization: string;
527
- unauthorizedSignIn: string;
528
- }
529
- interface AccountPortalAppearanceConfig {
530
- mode: 'auto' | 'light' | 'dark';
531
- light: {
532
- primaryColor: string;
533
- backgroundColor: string;
534
- };
535
- dark: {
536
- primaryColor: string;
537
- backgroundColor: string;
538
- };
539
- }
540
- interface AccountPortalConfig {
541
- paths: AccountPortalPathConfig;
542
- redirects: AccountPortalRedirectConfig;
543
- appearance: AccountPortalAppearanceConfig;
544
- }
545
- interface PasswordPolicyConfig {
546
- minLength: number;
547
- requiredCharacterClasses: 0 | 2 | 3 | 4;
548
- rejectCompromised: boolean;
549
- }
550
- interface AvatarConfig {
551
- uploadEnabled: boolean;
552
- }
553
- interface AuthConfigData {
554
- signUp: {
555
- enabled: boolean;
556
- };
557
- firstFactor: string[];
558
- secondFactor: string[];
559
- identificationStrategies: string[];
560
- singleSessionMode: boolean;
561
- requireSecondFactor: boolean;
562
- clientTrustEnabled: boolean;
563
- deviceTrustDays: number;
564
- passwordPolicy: PasswordPolicyConfig;
565
- avatar?: AvatarConfig;
566
- attributes: {
567
- emailAddress: AuthAttributeConfig;
568
- password: AuthAttributeConfig;
569
- phoneNumber?: AuthAttributeConfig;
570
- username?: AuthAttributeConfig;
571
- passkey?: AuthAttributeConfig;
572
- };
573
- accountPortal?: AccountPortalConfig;
574
- }
575
- declare const DEFAULT_AUTH_CONFIG: AuthConfigData;
576
-
577
- /**
578
- * OAuth Provider Adapter —— 把 provider-specific 的 endpoint / scope 默认值 /
579
- * profile 字段映射统一到一个最小接口,service 层只跟接口打交道。
580
- *
581
- * 设计原则
582
- * ────────
583
- * - **零网络默认实现**:adapter 只暴露纯函数(构 authorize URL / 解析 token /
584
- * 解析 profile),HTTP 请求由 service 层用注入的 fetch 跑,便于单测 mock。
585
- * - **PKCE 总是启用**:所有 adapter 必须支持 `code_challenge` 参数,service 层
586
- * 生成 verifier,adapter 拼 URL 时塞进 query。
587
- * - **provider-specific 配置**:通过 `OauthProviderConfig.config` jsonb 透传
588
- * (如 GitHub Enterprise host、Google hd 等),adapter 自行解释。
589
- */
590
- /**
591
- * OAuth profile —— 跨 provider 的统一 profile shape,service 层用它来
592
- * upsert UserIdentity。具体 provider 字段差异由 adapter 在 mapProfile 里
593
- * 抹平。
594
- */
595
- interface OauthProfile {
596
- /** provider 内的 stable user id(即 sub),UserIdentity.identifier 的右半 */
597
- sub: string;
598
- /** primary email(若 provider 不返回则 null;后端可能据此找匹配 user 链账号) */
599
- email: string | null;
600
- /** 是否 provider 那边已 verified(link/创建 UserIdentity('email') 时透传) */
601
- emailVerified: boolean;
602
- /** 用于显示(可空) */
603
- displayName: string | null;
604
- /** 头像 URL(落入 metadata,避免 BAPI 后续每次都打 provider) */
605
- avatarUrl: string | null;
606
- /** provider 原始 profile 的子集(debug / 审计),存到 metadata */
607
- raw: Record<string, unknown>;
608
- }
609
- /** Token endpoint 返回的最小子集 —— refresh_token 可空(GitHub OAuth App 不发) */
610
- interface OauthTokenSet {
611
- accessToken: string;
612
- /** 单位秒,可空 */
613
- expiresInSec: number | null;
614
- refreshToken: string | null;
615
- tokenType: string;
616
- scopes: string[];
617
- /** provider-specific token response fields used by fetchProfile. */
618
- raw?: Record<string, unknown>;
619
- }
620
- /** authorize URL 构造参数 —— service 层填好交给 adapter */
621
- interface BuildAuthorizeUrlInput {
622
- clientId: string;
623
- redirectUri: string;
624
- state: string;
625
- /** PKCE code_challenge(S256),service 层生成并存 verifier */
626
- codeChallenge: string;
627
- /** 实际拼到 URL 的 scope 列表 */
628
- scopes: string[];
629
- /** provider config.config jsonb;adapter 可能要读 enterprise host 等 */
630
- extraConfig: Record<string, unknown>;
631
- }
632
- interface ExchangeCodeInput {
633
- clientId: string;
634
- clientSecret: string;
635
- redirectUri: string;
636
- code: string;
637
- /** PKCE code_verifier */
638
- codeVerifier: string;
639
- extraConfig: Record<string, unknown>;
640
- /** 注入 fetch;单测可换成 mock */
641
- fetcher: typeof fetch;
642
- }
643
- interface FetchProfileInput {
644
- tokenSet: OauthTokenSet;
645
- extraConfig: Record<string, unknown>;
646
- fetcher: typeof fetch;
647
- }
648
- interface OauthProviderAdapter {
649
- /** provider id,与 zmodel 的 oauthProviderSchema 一致 */
650
- readonly provider: string;
651
- /** 显示名(fallback;最终 UI 字典优先 environment.userSettings.social.<p>.name) */
652
- readonly displayName: string;
653
- /** 缺省 scope 列表(用户未在 dashboard 自定义时使用) */
654
- readonly defaultScopes: readonly string[];
655
- /** 拼 https://<provider>/authorize?...&state=... 的纯函数 */
656
- buildAuthorizeUrl(input: BuildAuthorizeUrlInput): string;
657
- /** code → access token */
658
- exchangeCode(input: ExchangeCodeInput): Promise<OauthTokenSet>;
659
- /** access token → 标准 profile */
660
- fetchProfile(input: FetchProfileInput): Promise<OauthProfile>;
661
- }
662
-
663
- /**
664
- * Captcha 类型 —— 移自 @yhgale/apicore/captcha/types.ts。
665
- */
666
- interface CaptchaVerifyParams {
667
- token: string;
668
- remoteIp?: string;
669
- }
670
- interface CaptchaVerifyResult {
671
- success: boolean;
672
- errorCode?: string;
673
- }
674
- type CaptchaProviderId = 'turnstile' | 'hcaptcha' | 'mock';
675
- type CaptchaWidgetType = 'smart' | 'invisible';
676
- interface CaptchaProvider {
677
- readonly id: CaptchaProviderId;
678
- readonly publicKey: string;
679
- readonly widgetType: CaptchaWidgetType;
680
- verify(p: CaptchaVerifyParams): Promise<CaptchaVerifyResult>;
681
- }
682
- interface CaptchaSettings {
683
- provider: 'turnstile' | 'hcaptcha' | 'mock' | 'none';
684
- publicKey: string | null;
685
- secretKey: string | null;
686
- widgetType: CaptchaWidgetType;
687
- protectedFlows: ('sign_up' | 'sign_in')[];
688
- oauthBypass: boolean;
689
- /**
690
- * 自动化测试旁路(env CAPTCHA_TEST_BYPASS_TOKEN,默认 null = 关闭):
691
- * 提交 captchaToken 与此值相等时跳过 provider 验证。仅用于 E2E 自动化
692
- * (真实浏览器能正常通过 Turnstile,自动化 Chrome 会被 CF 判定拦截)。
693
- * 生产不设该 env 时行为与未引入此字段前完全一致。
694
- */
695
- testBypassToken?: string | null;
696
- }
697
- declare const DEFAULT_CAPTCHA_SETTINGS: CaptchaSettings;
698
-
699
- type GaleEnvironment = 'development' | 'staging' | 'production';
700
- interface GaleResourceJSON {
701
- object: string;
702
- id: string;
703
- }
704
- /**
705
- * 全局 ID 形态:纯 UUID v7(RFC 9562)字符串。
706
- *
707
- * - 36 字符,含连字符,例:`018f5d6b-c7e2-7a8c-9b1f-3e2a4b5c6d7e`
708
- * - DB 列类型为原生 `uuid`(16 字节);wire format / TS 层是带连字符的字符串
709
- * - 不在 ID 中嵌入资源类型前缀;资源类型由路由 / DTO 的 `object` 字段表达
710
- */
711
- type GaleId = string;
712
- /** RFC 9562 UUID v7 字符串正则;用于 zod / runtime 校验 */
713
- declare const UUID_V7_REGEX: RegExp;
714
- declare function isUuidV7(value: string): value is GaleId;
715
-
716
- /**
717
- * 把 fapi 错误响应规范化成 `GaleError`(来自 `@yhgale/shared`)。
718
- *
719
- * fapi envelope: { errors: [{ code, message, longMessage?, meta? }, ...] }
720
- *
721
- * 设计取舍:
722
- * - 多个 error 时取第一个作为 `.code/.message`,其余放到 `.meta.additional`
723
- * - 透传 HTTP status,便于调用方区分 401 / 422 / 429 / 5xx
724
- * - 网络层 / JSON 解析失败 → `gale_network_error`
725
- */
726
-
727
- declare function isFapiErrorEnvelope(v: unknown): v is FapiErrorEnvelope;
728
- declare function fapiErrorToGaleError(status: number, body: unknown): GaleError;
729
- /** 网络层错误(fetch reject / dns / cors)封装 */
730
- declare function networkErrorToGaleError(cause: unknown): GaleError;
731
-
732
- interface GaleErrorPayload {
733
- code: string;
734
- message: string;
735
- longMessage?: string;
736
- meta?: Record<string, unknown>;
737
- }
738
- declare class GaleError extends Error {
739
- readonly code: string;
740
- readonly status: number;
741
- readonly longMessage?: string;
742
- readonly meta?: Record<string, unknown>;
743
- constructor(payload: GaleErrorPayload & {
744
- status?: number;
745
- });
746
- }
747
- declare class GaleValidationError extends GaleError {
748
- constructor(payload: GaleErrorPayload);
749
- }
750
- declare class GaleAuthError extends GaleError {
751
- constructor(payload: GaleErrorPayload);
752
- }
753
- declare class GalePermissionError extends GaleError {
754
- constructor(payload: GaleErrorPayload);
755
- }
756
- declare class GaleNotFoundError extends GaleError {
757
- constructor(payload: GaleErrorPayload);
758
- }
759
- declare class GaleConflictError extends GaleError {
760
- constructor(payload: GaleErrorPayload);
761
- }
762
- declare class GaleRateLimitError extends GaleError {
763
- constructor(payload: GaleErrorPayload);
764
- }
1
+ import { IdentityJSON, IdentityResource, MeJSON, UserResource, SessionResource, OrganizationJSON, OrganizationResource, OrganizationMembershipJSON, OrganizationMembershipResource, SessionJSON, SignInAttemptJSON, SignInAttemptResource, SignInResponseJSON, SignUpAttemptJSON, SignUpAttemptResource, SignUpResponseJSON, TokenJSON, TokenResource, UserJSON, OauthProviderAdapter } from './types/index.js';
2
+ export { AcceptInvitationResponseJSON, AcceptedMembershipJSON, AccountPortalAppearanceConfig, AccountPortalConfig, AccountPortalPathConfig, AccountPortalRedirectConfig, AuthAttributeConfig, AuthConfigData, AvatarConfig, BackupCodesDisableResultJSON, BackupCodesGenerateResultJSON, BackupCodesStatusJSON, BeginPasskeyEnrollmentResponseJSON, BuildAuthorizeUrlInput, CaptchaProvider, CaptchaProviderId, CaptchaSettings, CaptchaVerifyParams, CaptchaVerifyResult, CaptchaWidgetType, ClientJSON, DEFAULT_AUTH_CONFIG, DEFAULT_CAPTCHA_SETTINGS, DeletePasskeyResponseJSON, ExchangeCodeInput, FapiErrorEnvelope, FapiErrorPayload, FetchProfileInput, FinishPasskeyEnrollmentResponseJSON, GaleEnvironment, GaleId, GaleResourceJSON, IdentityType, InstanceSummary, InvitationJSON, ListMyInvitationsResponseJSON, ListPasskeysResponseJSON, MfaResponseJSON, MfaStatusJSON, OauthProfile, OauthTokenSet, OrgRole, PageJSON, PasskeyJSON, PasskeyLoginOptionsResponseJSON, PasswordPolicyConfig, PreparePasskeySecondFactorResponseJSON, RenamePasskeyResponseJSON, SessionStatus, SignInStatus, SignUpStatus, SignUpVerificationsJSON, TotpConfirmResultJSON, TotpDisableResultJSON, TotpEnrollResultJSON, UUID_V7_REGEX, VerificationJSON, isUuidV7 } from './types/index.js';
3
+ export { GaleAuthError, GaleConflictError, GaleError, GaleErrorPayload, GaleNotFoundError, GalePermissionError, GaleRateLimitError, GaleValidationError, fapiErrorToGaleError, isFapiErrorEnvelope, networkErrorToGaleError } from './errors/index.js';
765
4
 
766
5
  /**
767
6
  * 全栈共享默认值 — 整个项目的权威来源。
@@ -1230,4 +469,4 @@ declare function parseAiNavigationTarget(input: unknown): AiNavigationTarget | n
1230
469
 
1231
470
  declare const GALE_VERSION = "0.0.0";
1232
471
 
1233
- export { AI_GUIDE_MODES, AI_GUIDE_PAGES, AI_NAVIGATION_PAGE_KEYS, type AcceptInvitationResponseJSON, type AcceptedMembershipJSON, type AccountPortalAppearanceConfig, type AccountPortalConfig, type AccountPortalPathConfig, type AccountPortalRedirectConfig, type AiGuideDraft, type AiGuideFieldSpec, type AiGuideFieldType, type AiGuideMode, type AiGuidePageSpec, type AiGuideValue, type AiNavigationPageKey, type AiNavigationTarget, type AuthAttributeConfig, type AuthConfigData, type AvatarConfig, type BackupCodesDisableResultJSON, type BackupCodesGenerateResultJSON, type BackupCodesStatusJSON, type BeginPasskeyEnrollmentResponseJSON, type BuildAuthorizeUrlInput, type BuildPublishableKeyInput, type BuiltInEmailTemplate, type CaptchaProvider, type CaptchaProviderId, type CaptchaSettings, type CaptchaVerifyParams, type CaptchaVerifyResult, type CaptchaWidgetType, type ClientJSON, DEFAULT_AUTH_CONFIG, DEFAULT_BAPI_PORT, DEFAULT_CAPTCHA_SETTINGS, DEFAULT_DATABASE_URL, DEFAULT_EMAIL_FROM, DEFAULT_EMAIL_TEMPLATES, DEFAULT_FAPI_PORT, DEFAULT_JWT_AUDIENCE, DEFAULT_REDIS_URL, DEFAULT_ROOT_DOMAIN, type DefaultInstanceHostParts, type DeletePasskeyResponseJSON, EMAIL_TEMPLATE_SLUGS, type EmailTemplateSlug, type ExchangeCodeInput, type FapiErrorEnvelope, type FapiErrorPayload, type FetchProfileInput, type FinishPasskeyEnrollmentResponseJSON, GALE_VERSION, GaleAuthError, GaleConflictError, type GaleEnvironment, GaleError, type GaleErrorPayload, type GaleId, GaleNotFoundError, GalePermissionError, GaleRateLimitError, type GaleResourceJSON, GaleValidationError, IMPLEMENTED_OAUTH_PROVIDER_IDS, type IdentityJSON, type IdentityResource, type IdentityType, type ImplementedOauthProviderName, type InstanceSummary, type InvitationJSON, type ListMyInvitationsResponseJSON, type ListPasskeysResponseJSON, type MeJSON, type MfaResponseJSON, type MfaStatusJSON, OAUTH_PROVIDER_CATALOG, type OauthProfile, type OauthProviderAdapter, type OauthProviderCatalogEntry, type OauthProviderCategory, type OauthProviderFamily, type OauthProviderName, type OauthProviderStatus, type OauthTokenSet, type OrgRole, type OrganizationJSON, type OrganizationMembershipJSON, type OrganizationMembershipResource, type OrganizationResource, type PageJSON, type PasskeyJSON, type PasskeyLoginOptionsResponseJSON, type PasswordPolicyConfig, type PreparePasskeySecondFactorResponseJSON, type PublishableKey, type PublishableKeyPayloadV1, type PublishableKeyPayloadV2, type RenamePasskeyResponseJSON, SUPPORTED_OAUTH_PROVIDERS, type SessionJSON, type SessionResource, type SessionStatus, type SignInAttemptJSON, type SignInAttemptResource, type SignInResponseJSON, type SignInStatus, type SignUpAttemptJSON, type SignUpAttemptResource, type SignUpResponseJSON, type SignUpStatus, type SignUpVerificationsJSON, type TokenJSON, type TokenResource, type TotpConfirmResultJSON, type TotpDisableResultJSON, type TotpEnrollResultJSON, UUID_V7_REGEX, type UserJSON, type UserResource, type VerificationJSON, _resetDomainCache, baiduAdapter, buildBapiHost, buildDapiHost, buildDashboardFapiHost, buildDashboardHost, buildDevAccountsHost, buildDevAccountsPrefix, buildDevFapiHost, buildDevFapiPrefix, buildFapiHost, buildProdAccountsHost, buildProdAccountsPrefix, buildProdFapiHost, buildProdFapiPrefix, buildPublishableKey, clearWeComSuiteAccessTokenCacheForTests, dingtalkAdapter, escapeHtml, extractFapiPrefix, fapiErrorToGaleError, getAiGuidePageSpec, getDefaultBapiHost, getDefaultDapiHost, getDefaultEmailTemplate, getDefaultFapiHost, getDefaultRootDomain, getOauthProviderAdapter, getOauthProviderCatalogEntry, getRootDomain, giteeAdapter, githubAdapter, googleAdapter, isFapiErrorEnvelope, isImplementedOauthProvider, isPublishableKey, isUuidV7, larkAdapter, listAiGuideSensitiveFieldKeys, listOauthProviderCatalog, listSupportedOauthProviders, microsoftAdapter, networkErrorToGaleError, parseAiGuideDraft, parseAiNavigationTarget, parseDefaultInstanceHost, parseIdentity, parseMe, parseOrganization, parseOrganizationMembership, parsePublishableKey, parseSession, parseSignInAttempt, parseSignInResponse, parseSignUpAttempt, parseSignUpResponse, parseToken, parseUser, purposeToSlug, qqAdapter, wechatOfficialAccountAdapter, wechatWebAdapter, wecomAdapter, weiboAdapter };
472
+ export { AI_GUIDE_MODES, AI_GUIDE_PAGES, AI_NAVIGATION_PAGE_KEYS, type AiGuideDraft, type AiGuideFieldSpec, type AiGuideFieldType, type AiGuideMode, type AiGuidePageSpec, type AiGuideValue, type AiNavigationPageKey, type AiNavigationTarget, type BuildPublishableKeyInput, type BuiltInEmailTemplate, DEFAULT_BAPI_PORT, DEFAULT_DATABASE_URL, DEFAULT_EMAIL_FROM, DEFAULT_EMAIL_TEMPLATES, DEFAULT_FAPI_PORT, DEFAULT_JWT_AUDIENCE, DEFAULT_REDIS_URL, DEFAULT_ROOT_DOMAIN, type DefaultInstanceHostParts, EMAIL_TEMPLATE_SLUGS, type EmailTemplateSlug, GALE_VERSION, IMPLEMENTED_OAUTH_PROVIDER_IDS, IdentityJSON, IdentityResource, type ImplementedOauthProviderName, MeJSON, OAUTH_PROVIDER_CATALOG, OauthProviderAdapter, type OauthProviderCatalogEntry, type OauthProviderCategory, type OauthProviderFamily, type OauthProviderName, type OauthProviderStatus, OrganizationJSON, OrganizationMembershipJSON, OrganizationMembershipResource, OrganizationResource, type PublishableKey, type PublishableKeyPayloadV1, type PublishableKeyPayloadV2, SUPPORTED_OAUTH_PROVIDERS, SessionJSON, SessionResource, SignInAttemptJSON, SignInAttemptResource, SignInResponseJSON, SignUpAttemptJSON, SignUpAttemptResource, SignUpResponseJSON, TokenJSON, TokenResource, UserJSON, UserResource, _resetDomainCache, baiduAdapter, buildBapiHost, buildDapiHost, buildDashboardFapiHost, buildDashboardHost, buildDevAccountsHost, buildDevAccountsPrefix, buildDevFapiHost, buildDevFapiPrefix, buildFapiHost, buildProdAccountsHost, buildProdAccountsPrefix, buildProdFapiHost, buildProdFapiPrefix, buildPublishableKey, clearWeComSuiteAccessTokenCacheForTests, dingtalkAdapter, escapeHtml, extractFapiPrefix, getAiGuidePageSpec, getDefaultBapiHost, getDefaultDapiHost, getDefaultEmailTemplate, getDefaultFapiHost, getDefaultRootDomain, getOauthProviderAdapter, getOauthProviderCatalogEntry, getRootDomain, giteeAdapter, githubAdapter, googleAdapter, isImplementedOauthProvider, isPublishableKey, larkAdapter, listAiGuideSensitiveFieldKeys, listOauthProviderCatalog, listSupportedOauthProviders, microsoftAdapter, parseAiGuideDraft, parseAiNavigationTarget, parseDefaultInstanceHost, parseIdentity, parseMe, parseOrganization, parseOrganizationMembership, parsePublishableKey, parseSession, parseSignInAttempt, parseSignInResponse, parseSignUpAttempt, parseSignUpResponse, parseToken, parseUser, purposeToSlug, qqAdapter, wechatOfficialAccountAdapter, wechatWebAdapter, wecomAdapter, weiboAdapter };