@yhgale/shared 0.1.0 → 0.1.2

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.
Files changed (123) hide show
  1. package/dist/chunk-DWPSHK7F.js +68 -0
  2. package/dist/chunk-Y75EVVGQ.js +108 -0
  3. package/dist/errors/index.d.ts +29 -10
  4. package/dist/errors/index.js +24 -52
  5. package/dist/index.d.ts +472 -14
  6. package/dist/index.js +2295 -14
  7. package/dist/react/index.d.ts +2 -1
  8. package/dist/react/index.js +0 -4
  9. package/dist/types/index.d.ts +705 -10
  10. package/dist/types/index.js +12 -10
  11. package/package.json +20 -39
  12. package/dist/__tests__/aiGuide.spec.d.ts +0 -2
  13. package/dist/__tests__/aiGuide.spec.d.ts.map +0 -1
  14. package/dist/__tests__/aiGuide.spec.js +0 -93
  15. package/dist/__tests__/aiGuide.spec.js.map +0 -1
  16. package/dist/__tests__/aiNavigation.spec.d.ts +0 -2
  17. package/dist/__tests__/aiNavigation.spec.d.ts.map +0 -1
  18. package/dist/__tests__/aiNavigation.spec.js +0 -20
  19. package/dist/__tests__/aiNavigation.spec.js.map +0 -1
  20. package/dist/__tests__/keys.spec.d.ts +0 -2
  21. package/dist/__tests__/keys.spec.d.ts.map +0 -1
  22. package/dist/__tests__/keys.spec.js +0 -29
  23. package/dist/__tests__/keys.spec.js.map +0 -1
  24. package/dist/aiGuide.d.ts +0 -50
  25. package/dist/aiGuide.d.ts.map +0 -1
  26. package/dist/aiGuide.js +0 -123
  27. package/dist/aiGuide.js.map +0 -1
  28. package/dist/aiNavigation.d.ts +0 -7
  29. package/dist/aiNavigation.d.ts.map +0 -1
  30. package/dist/aiNavigation.js +0 -34
  31. package/dist/aiNavigation.js.map +0 -1
  32. package/dist/defaults.d.ts +0 -19
  33. package/dist/defaults.d.ts.map +0 -1
  34. package/dist/defaults.js +0 -45
  35. package/dist/defaults.js.map +0 -1
  36. package/dist/domain.d.ts +0 -27
  37. package/dist/domain.d.ts.map +0 -1
  38. package/dist/domain.js +0 -77
  39. package/dist/domain.js.map +0 -1
  40. package/dist/email/defaults.d.ts +0 -13
  41. package/dist/email/defaults.d.ts.map +0 -1
  42. package/dist/email/defaults.js +0 -52
  43. package/dist/email/defaults.js.map +0 -1
  44. package/dist/email/markdown.d.ts +0 -6
  45. package/dist/email/markdown.d.ts.map +0 -1
  46. package/dist/email/markdown.js +0 -14
  47. package/dist/email/markdown.js.map +0 -1
  48. package/dist/email/slugs.d.ts +0 -17
  49. package/dist/email/slugs.d.ts.map +0 -1
  50. package/dist/email/slugs.js +0 -28
  51. package/dist/email/slugs.js.map +0 -1
  52. package/dist/errors/fapi.d.ts +0 -18
  53. package/dist/errors/fapi.d.ts.map +0 -1
  54. package/dist/errors/fapi.js +0 -62
  55. package/dist/errors/fapi.js.map +0 -1
  56. package/dist/errors/index.d.ts.map +0 -1
  57. package/dist/errors/index.js.map +0 -1
  58. package/dist/index.d.ts.map +0 -1
  59. package/dist/index.js.map +0 -1
  60. package/dist/keys.d.ts +0 -35
  61. package/dist/keys.d.ts.map +0 -1
  62. package/dist/keys.js +0 -128
  63. package/dist/keys.js.map +0 -1
  64. package/dist/oauth/catalog.d.ts +0 -141
  65. package/dist/oauth/catalog.d.ts.map +0 -1
  66. package/dist/oauth/catalog.js +0 -166
  67. package/dist/oauth/catalog.js.map +0 -1
  68. package/dist/oauth/china.d.ts +0 -7
  69. package/dist/oauth/china.d.ts.map +0 -1
  70. package/dist/oauth/china.js +0 -487
  71. package/dist/oauth/china.js.map +0 -1
  72. package/dist/oauth/gitee.d.ts +0 -21
  73. package/dist/oauth/gitee.d.ts.map +0 -1
  74. package/dist/oauth/gitee.js +0 -156
  75. package/dist/oauth/gitee.js.map +0 -1
  76. package/dist/oauth/github.d.ts +0 -21
  77. package/dist/oauth/github.d.ts.map +0 -1
  78. package/dist/oauth/github.js +0 -140
  79. package/dist/oauth/github.js.map +0 -1
  80. package/dist/oauth/google.d.ts +0 -17
  81. package/dist/oauth/google.d.ts.map +0 -1
  82. package/dist/oauth/google.js +0 -108
  83. package/dist/oauth/google.js.map +0 -1
  84. package/dist/oauth/index.d.ts +0 -28
  85. package/dist/oauth/index.d.ts.map +0 -1
  86. package/dist/oauth/index.js +0 -53
  87. package/dist/oauth/index.js.map +0 -1
  88. package/dist/oauth/microsoft.d.ts +0 -17
  89. package/dist/oauth/microsoft.d.ts.map +0 -1
  90. package/dist/oauth/microsoft.js +0 -118
  91. package/dist/oauth/microsoft.js.map +0 -1
  92. package/dist/oauth/wechat.d.ts +0 -4
  93. package/dist/oauth/wechat.d.ts.map +0 -1
  94. package/dist/oauth/wechat.js +0 -161
  95. package/dist/oauth/wechat.js.map +0 -1
  96. package/dist/oauth/wecom.d.ts +0 -4
  97. package/dist/oauth/wecom.d.ts.map +0 -1
  98. package/dist/oauth/wecom.js +0 -250
  99. package/dist/oauth/wecom.js.map +0 -1
  100. package/dist/parsers.d.ts +0 -44
  101. package/dist/parsers.d.ts.map +0 -1
  102. package/dist/parsers.js +0 -188
  103. package/dist/parsers.js.map +0 -1
  104. package/dist/react/index.d.ts.map +0 -1
  105. package/dist/react/index.js.map +0 -1
  106. package/dist/types/authConfig.d.ts +0 -70
  107. package/dist/types/authConfig.d.ts.map +0 -1
  108. package/dist/types/authConfig.js +0 -49
  109. package/dist/types/authConfig.js.map +0 -1
  110. package/dist/types/captcha.d.ts +0 -36
  111. package/dist/types/captcha.d.ts.map +0 -1
  112. package/dist/types/captcha.js +0 -13
  113. package/dist/types/captcha.js.map +0 -1
  114. package/dist/types/fapi.d.ts +0 -506
  115. package/dist/types/fapi.d.ts.map +0 -1
  116. package/dist/types/fapi.js +0 -24
  117. package/dist/types/fapi.js.map +0 -1
  118. package/dist/types/index.d.ts.map +0 -1
  119. package/dist/types/index.js.map +0 -1
  120. package/dist/types/oauthProviders.d.ts +0 -86
  121. package/dist/types/oauthProviders.d.ts.map +0 -1
  122. package/dist/types/oauthProviders.js +0 -15
  123. package/dist/types/oauthProviders.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,14 +1,2295 @@
1
- export * from './types/index';
2
- export * from './errors/index';
3
- export * from './defaults';
4
- export * from './domain';
5
- export * from './parsers';
6
- export * from './oauth/index';
7
- export * from './email/slugs';
8
- export * from './email/defaults';
9
- export * from './email/markdown';
10
- export const GALE_VERSION = '0.0.0';
11
- export * from './keys';
12
- export * from './aiGuide';
13
- export * from './aiNavigation';
14
- //# sourceMappingURL=index.js.map
1
+ import {
2
+ DEFAULT_AUTH_CONFIG,
3
+ DEFAULT_CAPTCHA_SETTINGS,
4
+ UUID_V7_REGEX,
5
+ isUuidV7
6
+ } from "./chunk-DWPSHK7F.js";
7
+ import {
8
+ GaleAuthError,
9
+ GaleConflictError,
10
+ GaleError,
11
+ GaleNotFoundError,
12
+ GalePermissionError,
13
+ GaleRateLimitError,
14
+ GaleValidationError,
15
+ fapiErrorToGaleError,
16
+ isFapiErrorEnvelope,
17
+ networkErrorToGaleError
18
+ } from "./chunk-Y75EVVGQ.js";
19
+
20
+ // src/defaults.ts
21
+ var DEFAULT_ROOT_DOMAIN = "onered.net";
22
+ function getDefaultRootDomain() {
23
+ if (typeof process !== "undefined" && process.env?.GALE_ROOT_DOMAIN) {
24
+ return process.env.GALE_ROOT_DOMAIN;
25
+ }
26
+ try {
27
+ const vite = import.meta.env?.VITE_GALE_ROOT_DOMAIN;
28
+ if (vite) return vite;
29
+ } catch {
30
+ }
31
+ return DEFAULT_ROOT_DOMAIN;
32
+ }
33
+ var DEFAULT_FAPI_PORT = 3001;
34
+ var DEFAULT_BAPI_PORT = 3002;
35
+ var DEFAULT_DATABASE_URL = "postgresql://gale:gale@localhost:5432/gale";
36
+ var DEFAULT_REDIS_URL = "redis://localhost:6379";
37
+ var DEFAULT_JWT_AUDIENCE = "gale";
38
+ var DEFAULT_EMAIL_FROM = "noreply@onered.net";
39
+ function getDefaultFapiHost() {
40
+ return `fapi.${getDefaultRootDomain()}`;
41
+ }
42
+ function getDefaultBapiHost() {
43
+ return `bapi.${getDefaultRootDomain()}`;
44
+ }
45
+ function getDefaultDapiHost() {
46
+ return `dapi.${getDefaultRootDomain()}`;
47
+ }
48
+
49
+ // src/domain.ts
50
+ var _rootDomainCache;
51
+ function getRootDomain() {
52
+ if (_rootDomainCache) return _rootDomainCache;
53
+ const raw = getDefaultRootDomain();
54
+ const cleaned = raw.replace(/^https?:\/\//, "").replace(/\/$/, "");
55
+ _rootDomainCache = cleaned;
56
+ return _rootDomainCache;
57
+ }
58
+ function extractFapiPrefix(hostname) {
59
+ const rootDomain = getRootDomain();
60
+ if (!hostname.endsWith("." + rootDomain)) return null;
61
+ return hostname.slice(0, -(rootDomain.length + 1));
62
+ }
63
+ function parseDefaultInstanceHost(hostname) {
64
+ const prefix = extractFapiPrefix(hostname.toLowerCase());
65
+ if (!prefix) return null;
66
+ const service = prefix.endsWith("-accounts") ? "accounts" : "fapi";
67
+ const servicePrefix = service === "accounts" ? prefix.slice(0, -"-accounts".length) : prefix;
68
+ const environmentType = servicePrefix.endsWith("-dev") ? "development" : "production";
69
+ const slug = environmentType === "development" ? servicePrefix.slice(0, -"-dev".length) : servicePrefix;
70
+ if (!/^[a-z0-9]+$/.test(slug)) return null;
71
+ return { slug, environmentType, service };
72
+ }
73
+ function buildFapiHost(prefix) {
74
+ return `${prefix}.${getRootDomain()}`;
75
+ }
76
+ function buildDevFapiPrefix(slug) {
77
+ return `${slug}-dev`;
78
+ }
79
+ function buildProdFapiPrefix(slug) {
80
+ return slug;
81
+ }
82
+ function buildDevFapiHost(slug) {
83
+ return buildFapiHost(buildDevFapiPrefix(slug));
84
+ }
85
+ function buildProdFapiHost(slug) {
86
+ return buildFapiHost(buildProdFapiPrefix(slug));
87
+ }
88
+ function buildDevAccountsPrefix(slug) {
89
+ return `${slug}-dev-accounts`;
90
+ }
91
+ function buildProdAccountsPrefix(slug) {
92
+ return `${slug}-accounts`;
93
+ }
94
+ function buildDevAccountsHost(slug) {
95
+ return buildFapiHost(buildDevAccountsPrefix(slug));
96
+ }
97
+ function buildProdAccountsHost(slug) {
98
+ return buildFapiHost(buildProdAccountsPrefix(slug));
99
+ }
100
+ function buildBapiHost() {
101
+ return `bapi.${getRootDomain()}`;
102
+ }
103
+ function buildDashboardHost() {
104
+ return `dashboard.${getRootDomain()}`;
105
+ }
106
+ function buildDashboardFapiHost() {
107
+ return `dashboard.${getRootDomain()}`;
108
+ }
109
+ function buildDapiHost() {
110
+ return `dapi.${getRootDomain()}`;
111
+ }
112
+ function _resetDomainCache() {
113
+ _rootDomainCache = void 0;
114
+ }
115
+
116
+ // src/parsers.ts
117
+ var SECONDS_THRESHOLD = 1e11;
118
+ function toEpochMs(v) {
119
+ if (v === null || v === void 0) return null;
120
+ if (typeof v === "number") {
121
+ if (!Number.isFinite(v)) return null;
122
+ return v < SECONDS_THRESHOLD ? Math.floor(v * 1e3) : Math.floor(v);
123
+ }
124
+ const parsed = Date.parse(v);
125
+ return Number.isNaN(parsed) ? null : parsed;
126
+ }
127
+ function toEpochMsRequired(v, fieldName) {
128
+ const ms = toEpochMs(v);
129
+ if (ms === null) {
130
+ throw new Error(`expected non-null timestamp for ${fieldName}`);
131
+ }
132
+ return ms;
133
+ }
134
+ function parseIdentity(json) {
135
+ return {
136
+ object: "identity",
137
+ id: json.id,
138
+ type: json.type,
139
+ identifier: json.identifier,
140
+ verificationStatus: json.verificationStatus ?? (json.isVerified === void 0 ? null : json.isVerified ? "verified" : "unverified"),
141
+ isPrimary: Boolean(json.isPrimary),
142
+ createdAt: toEpochMsRequired(json.createdAt, "identity.createdAt"),
143
+ updatedAt: toEpochMsRequired(json.updatedAt, "identity.updatedAt")
144
+ };
145
+ }
146
+ function parseUser(json) {
147
+ const identities = (json.identities ?? []).map(parseIdentity);
148
+ const primary = identities.find((i) => i.isPrimary) ?? identities[0] ?? null;
149
+ return {
150
+ object: "user",
151
+ id: json.id,
152
+ username: json.username ?? null,
153
+ displayName: json.displayName ?? null,
154
+ imageUrl: json.imageUrl ?? null,
155
+ publicMetadata: json.publicMetadata ?? {},
156
+ unsafeMetadata: json.unsafeMetadata ?? {},
157
+ bannedAt: toEpochMs(json.bannedAt),
158
+ lockedAt: toEpochMs(json.lockedAt),
159
+ lastSignInAt: toEpochMs(json.lastSignInAt),
160
+ createdAt: toEpochMsRequired(json.createdAt, "user.createdAt"),
161
+ updatedAt: toEpochMsRequired(json.updatedAt, "user.updatedAt"),
162
+ identities,
163
+ primaryIdentity: primary,
164
+ primaryEmail: primary?.type === "email" ? primary.identifier : null,
165
+ primaryPhone: primary?.type === "phone" ? primary.identifier : null
166
+ };
167
+ }
168
+ function parseMe(json) {
169
+ return {
170
+ user: parseUser(json),
171
+ session: json.session ? {
172
+ object: "session",
173
+ id: json.session.id,
174
+ status: json.session.status,
175
+ activeOrganizationId: json.session.activeOrganizationId ?? null
176
+ } : null
177
+ };
178
+ }
179
+ function parseSession(json) {
180
+ return {
181
+ object: "session",
182
+ id: json.id,
183
+ status: json.status,
184
+ userId: json.userId,
185
+ clientId: json.clientId ?? null,
186
+ activeOrganizationId: json.activeOrganizationId ?? null,
187
+ expiresAt: toEpochMsRequired(json.expiresAt, "session.expiresAt"),
188
+ lastActiveAt: toEpochMs(json.lastActiveAt ?? null)
189
+ };
190
+ }
191
+ function parseToken(json) {
192
+ return {
193
+ object: "token",
194
+ jwt: json.jwt,
195
+ expiresIn: json.expiresIn,
196
+ session: parseSession(json.session)
197
+ };
198
+ }
199
+ function parseSignInAttempt(json) {
200
+ return {
201
+ object: "sign_in_attempt",
202
+ id: json.id,
203
+ status: json.status,
204
+ userId: json.userId ?? null,
205
+ identifier: json.identifier ?? null,
206
+ supportedFirstFactors: json.supportedFirstFactors ?? [],
207
+ supportedSecondFactors: json.supportedSecondFactors ?? [],
208
+ firstFactorVerification: json.firstFactorVerification ?? null,
209
+ secondFactorVerification: json.secondFactorVerification ?? null,
210
+ createdSessionId: json.createdSessionId ?? null
211
+ };
212
+ }
213
+ function parseSignInResponse(json) {
214
+ return {
215
+ clientId: json.client?.id ?? null,
216
+ attempt: parseSignInAttempt(json.response),
217
+ clientSafeRefreshToken: json.response.clientSafeRefreshToken ?? null
218
+ };
219
+ }
220
+ function parseSignUpAttempt(json) {
221
+ return {
222
+ object: "sign_up_attempt",
223
+ id: json.id,
224
+ status: json.status,
225
+ emailAddress: json.emailAddress ?? null,
226
+ phoneNumber: json.phoneNumber ?? null,
227
+ username: json.username ?? null,
228
+ missingFields: json.missingFields ?? [],
229
+ unverifiedFields: json.unverifiedFields ?? [],
230
+ verifications: json.verifications ?? null,
231
+ abandonAt: toEpochMs(json.abandonAt) ?? 0,
232
+ resultUserId: json.resultUserId ?? null,
233
+ resultSessionId: json.resultSessionId ?? null,
234
+ createdAt: toEpochMs(json.createdAt) ?? 0,
235
+ updatedAt: toEpochMs(json.updatedAt) ?? 0,
236
+ createdSessionId: json.createdSessionId ?? null
237
+ };
238
+ }
239
+ function parseSignUpResponse(json) {
240
+ return {
241
+ clientId: json.client?.id ?? null,
242
+ attempt: parseSignUpAttempt(json.response),
243
+ clientSafeRefreshToken: json.response.clientSafeRefreshToken ?? null
244
+ };
245
+ }
246
+ function parseOrganization(json) {
247
+ return {
248
+ object: "organization",
249
+ id: json.id,
250
+ applicationId: json.applicationId ?? null,
251
+ name: json.name,
252
+ slug: json.slug ?? null,
253
+ imageUrl: json.imageUrl ?? null,
254
+ publicMetadata: json.publicMetadata ?? {},
255
+ createdAt: toEpochMsRequired(json.createdAt, "organization.createdAt"),
256
+ updatedAt: toEpochMsRequired(json.updatedAt, "organization.updatedAt"),
257
+ membersCount: json.membersCount ?? null
258
+ };
259
+ }
260
+ function parseOrganizationMembership(json) {
261
+ return {
262
+ object: "organization_membership",
263
+ id: json.id,
264
+ organizationId: json.organizationId,
265
+ userId: json.userId,
266
+ role: json.role,
267
+ createdAt: toEpochMsRequired(json.createdAt, "organization_membership.createdAt"),
268
+ updatedAt: toEpochMsRequired(json.updatedAt, "organization_membership.updatedAt")
269
+ };
270
+ }
271
+
272
+ // src/oauth/github.ts
273
+ var GITHUB_DEFAULT_SCOPES = ["read:user", "user:email"];
274
+ function resolveHosts(extraConfig) {
275
+ const ent = typeof extraConfig.enterpriseHost === "string" ? extraConfig.enterpriseHost : null;
276
+ if (ent) {
277
+ return {
278
+ oauthBase: `https://${ent}/login/oauth`,
279
+ apiBase: `https://${ent}/api/v3`
280
+ };
281
+ }
282
+ return {
283
+ oauthBase: "https://github.com/login/oauth",
284
+ apiBase: "https://api.github.com"
285
+ };
286
+ }
287
+ var githubAdapter = {
288
+ provider: "github",
289
+ displayName: "GitHub",
290
+ defaultScopes: GITHUB_DEFAULT_SCOPES,
291
+ buildAuthorizeUrl({
292
+ clientId,
293
+ redirectUri,
294
+ state,
295
+ codeChallenge,
296
+ scopes,
297
+ extraConfig
298
+ }) {
299
+ const { oauthBase } = resolveHosts(extraConfig);
300
+ const params = new URLSearchParams({
301
+ client_id: clientId,
302
+ redirect_uri: redirectUri,
303
+ scope: scopes.join(" "),
304
+ state,
305
+ response_type: "code",
306
+ // GitHub 支持 PKCE(2024 起)—— 即便不强制,统一带上保持 adapter 同形
307
+ code_challenge: codeChallenge,
308
+ code_challenge_method: "S256",
309
+ // 强制每次都问,避免 dev 期切账号体验问题
310
+ allow_signup: "true"
311
+ });
312
+ return `${oauthBase}/authorize?${params.toString()}`;
313
+ },
314
+ async exchangeCode({
315
+ clientId,
316
+ clientSecret,
317
+ redirectUri,
318
+ code,
319
+ codeVerifier,
320
+ extraConfig,
321
+ fetcher
322
+ }) {
323
+ const { oauthBase } = resolveHosts(extraConfig);
324
+ const body = new URLSearchParams({
325
+ client_id: clientId,
326
+ client_secret: clientSecret,
327
+ code,
328
+ redirect_uri: redirectUri,
329
+ code_verifier: codeVerifier
330
+ });
331
+ const res = await fetcher(`${oauthBase}/access_token`, {
332
+ method: "POST",
333
+ headers: {
334
+ "content-type": "application/x-www-form-urlencoded",
335
+ accept: "application/json"
336
+ },
337
+ body: body.toString()
338
+ });
339
+ if (!res.ok) {
340
+ throw new GaleError({
341
+ code: "oauth_token_exchange_failed",
342
+ message: `GitHub token endpoint ${res.status}`,
343
+ status: 502
344
+ });
345
+ }
346
+ const json = await res.json();
347
+ if (json.error || !json.access_token) {
348
+ throw new GaleError({
349
+ code: "oauth_token_exchange_failed",
350
+ message: json.error_description || json.error || "no access_token",
351
+ status: 400
352
+ });
353
+ }
354
+ return {
355
+ accessToken: json.access_token,
356
+ expiresInSec: null,
357
+ refreshToken: null,
358
+ tokenType: json.token_type || "bearer",
359
+ scopes: typeof json.scope === "string" ? json.scope.split(/[\s,]+/).filter(Boolean) : []
360
+ };
361
+ },
362
+ async fetchProfile({ tokenSet, extraConfig, fetcher }) {
363
+ const { apiBase } = resolveHosts(extraConfig);
364
+ const headers = {
365
+ authorization: `Bearer ${tokenSet.accessToken}`,
366
+ accept: "application/vnd.github+json",
367
+ "user-agent": "gale"
368
+ };
369
+ const [profileRes, emailsRes] = await Promise.all([
370
+ fetcher(`${apiBase}/user`, { headers }),
371
+ fetcher(`${apiBase}/user/emails`, { headers })
372
+ ]);
373
+ if (!profileRes.ok) {
374
+ throw new GaleError({
375
+ code: "oauth_profile_fetch_failed",
376
+ message: `GitHub /user ${profileRes.status}`,
377
+ status: 502
378
+ });
379
+ }
380
+ const profile = await profileRes.json();
381
+ if (!profile.id) {
382
+ throw new GaleError({
383
+ code: "oauth_profile_malformed",
384
+ message: "GitHub /user missing id",
385
+ status: 502
386
+ });
387
+ }
388
+ let email = profile.email ?? null;
389
+ let emailVerified = false;
390
+ if (emailsRes.ok) {
391
+ const emails = await emailsRes.json();
392
+ const primary = emails.find((e) => e.primary) ?? emails[0];
393
+ if (primary) {
394
+ email = primary.email;
395
+ emailVerified = !!primary.verified;
396
+ }
397
+ }
398
+ return {
399
+ sub: String(profile.id),
400
+ email,
401
+ emailVerified,
402
+ displayName: profile.name ?? profile.login ?? null,
403
+ avatarUrl: profile.avatar_url ?? null,
404
+ raw: { ...profile }
405
+ };
406
+ }
407
+ };
408
+
409
+ // src/oauth/gitee.ts
410
+ var GITEE_DEFAULT_SCOPES = ["user_info", "emails"];
411
+ function resolveHosts2(extraConfig) {
412
+ const ent = typeof extraConfig.enterpriseHost === "string" ? extraConfig.enterpriseHost : null;
413
+ if (ent) {
414
+ return {
415
+ oauthBase: `https://${ent}/oauth`,
416
+ apiBase: `https://${ent}/api/v5`
417
+ };
418
+ }
419
+ return {
420
+ oauthBase: "https://gitee.com/oauth",
421
+ apiBase: "https://gitee.com/api/v5"
422
+ };
423
+ }
424
+ var giteeAdapter = {
425
+ provider: "gitee",
426
+ displayName: "Gitee",
427
+ defaultScopes: GITEE_DEFAULT_SCOPES,
428
+ buildAuthorizeUrl({
429
+ clientId,
430
+ redirectUri,
431
+ state,
432
+ codeChallenge,
433
+ scopes,
434
+ extraConfig
435
+ }) {
436
+ const { oauthBase } = resolveHosts2(extraConfig);
437
+ const params = new URLSearchParams({
438
+ client_id: clientId,
439
+ redirect_uri: redirectUri,
440
+ scope: scopes.join(" "),
441
+ state,
442
+ response_type: "code"
443
+ });
444
+ if (codeChallenge) {
445
+ params.set("code_challenge", codeChallenge);
446
+ params.set("code_challenge_method", "S256");
447
+ }
448
+ return `${oauthBase}/authorize?${params.toString()}`;
449
+ },
450
+ async exchangeCode({
451
+ clientId,
452
+ clientSecret,
453
+ redirectUri,
454
+ code,
455
+ extraConfig,
456
+ fetcher
457
+ }) {
458
+ const { oauthBase } = resolveHosts2(extraConfig);
459
+ const body = new URLSearchParams({
460
+ grant_type: "authorization_code",
461
+ code,
462
+ client_id: clientId,
463
+ client_secret: clientSecret,
464
+ redirect_uri: redirectUri
465
+ });
466
+ const res = await fetcher(`${oauthBase}/token`, {
467
+ method: "POST",
468
+ headers: {
469
+ "content-type": "application/x-www-form-urlencoded",
470
+ accept: "application/json"
471
+ },
472
+ body: body.toString()
473
+ });
474
+ if (!res.ok) {
475
+ throw new GaleError({
476
+ code: "oauth_token_exchange_failed",
477
+ message: `Gitee token endpoint ${res.status}`,
478
+ status: 502
479
+ });
480
+ }
481
+ const json = await res.json();
482
+ if (json.error || !json.access_token) {
483
+ throw new GaleError({
484
+ code: "oauth_token_exchange_failed",
485
+ message: json.error_description || json.error || "no access_token",
486
+ status: 400
487
+ });
488
+ }
489
+ return {
490
+ accessToken: json.access_token,
491
+ expiresInSec: json.expires_in ?? null,
492
+ refreshToken: json.refresh_token ?? null,
493
+ tokenType: json.token_type || "bearer",
494
+ scopes: typeof json.scope === "string" ? json.scope.split(/[\s,]+/).filter(Boolean) : []
495
+ };
496
+ },
497
+ async fetchProfile({ tokenSet, extraConfig, fetcher }) {
498
+ const { apiBase } = resolveHosts2(extraConfig);
499
+ const res = await fetcher(`${apiBase}/user?access_token=${tokenSet.accessToken}`, {
500
+ headers: {
501
+ accept: "application/json",
502
+ "user-agent": "gale"
503
+ }
504
+ });
505
+ if (!res.ok) {
506
+ throw new GaleError({
507
+ code: "oauth_profile_fetch_failed",
508
+ message: `Gitee /user ${res.status}`,
509
+ status: 502
510
+ });
511
+ }
512
+ const rawText = await res.text();
513
+ let profile;
514
+ try {
515
+ profile = JSON.parse(rawText);
516
+ } catch {
517
+ throw new GaleError({
518
+ code: "oauth_profile_malformed",
519
+ message: "Gitee /user invalid JSON",
520
+ status: 502
521
+ });
522
+ }
523
+ if (!profile.id) {
524
+ throw new GaleError({
525
+ code: "oauth_profile_malformed",
526
+ message: "Gitee /user missing id",
527
+ status: 502
528
+ });
529
+ }
530
+ let email = profile.email ?? null;
531
+ let emailVerified = false;
532
+ if (!email) {
533
+ const emailsRes = await fetcher(`${apiBase}/emails?access_token=${tokenSet.accessToken}`, {
534
+ headers: { accept: "application/json", "user-agent": "gale" }
535
+ });
536
+ if (emailsRes.ok) {
537
+ const emails = await emailsRes.json();
538
+ const primary = emails.find((e) => e.state === "confirmed") ?? emails[0];
539
+ if (primary?.email) {
540
+ email = primary.email;
541
+ emailVerified = primary.state === "confirmed";
542
+ }
543
+ }
544
+ } else {
545
+ emailVerified = true;
546
+ }
547
+ return {
548
+ sub: String(profile.id),
549
+ email,
550
+ emailVerified,
551
+ displayName: profile.name ?? profile.login ?? null,
552
+ avatarUrl: profile.avatar_url ?? null,
553
+ raw: { ...profile }
554
+ };
555
+ }
556
+ };
557
+
558
+ // src/oauth/google.ts
559
+ var GOOGLE_DEFAULT_SCOPES = ["openid", "email", "profile"];
560
+ var googleAdapter = {
561
+ provider: "google",
562
+ displayName: "Google",
563
+ defaultScopes: GOOGLE_DEFAULT_SCOPES,
564
+ buildAuthorizeUrl({
565
+ clientId,
566
+ redirectUri,
567
+ state,
568
+ codeChallenge,
569
+ scopes,
570
+ extraConfig: _extraConfig
571
+ }) {
572
+ const params = new URLSearchParams({
573
+ client_id: clientId,
574
+ redirect_uri: redirectUri,
575
+ scope: scopes.join(" "),
576
+ state,
577
+ response_type: "code",
578
+ code_challenge: codeChallenge,
579
+ code_challenge_method: "S256",
580
+ // 确保每次都返回 refresh_token(即使用户之前授权过)
581
+ access_type: "offline",
582
+ prompt: "consent"
583
+ });
584
+ return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
585
+ },
586
+ async exchangeCode({
587
+ clientId,
588
+ clientSecret,
589
+ redirectUri,
590
+ code,
591
+ codeVerifier,
592
+ extraConfig: _extraConfig,
593
+ fetcher
594
+ }) {
595
+ const body = new URLSearchParams({
596
+ client_id: clientId,
597
+ client_secret: clientSecret,
598
+ code,
599
+ redirect_uri: redirectUri,
600
+ grant_type: "authorization_code",
601
+ code_verifier: codeVerifier
602
+ });
603
+ const res = await fetcher("https://oauth2.googleapis.com/token", {
604
+ method: "POST",
605
+ headers: {
606
+ "content-type": "application/x-www-form-urlencoded",
607
+ accept: "application/json"
608
+ },
609
+ body: body.toString()
610
+ });
611
+ if (!res.ok) {
612
+ throw new GaleError({
613
+ code: "oauth_token_exchange_failed",
614
+ message: `Google token endpoint ${res.status}`,
615
+ status: 502
616
+ });
617
+ }
618
+ const json = await res.json();
619
+ if (json.error || !json.access_token) {
620
+ throw new GaleError({
621
+ code: "oauth_token_exchange_failed",
622
+ message: json.error_description || json.error || "no access_token",
623
+ status: 400
624
+ });
625
+ }
626
+ return {
627
+ accessToken: json.access_token,
628
+ expiresInSec: json.expires_in ?? null,
629
+ refreshToken: json.refresh_token ?? null,
630
+ tokenType: json.token_type || "bearer",
631
+ scopes: typeof json.scope === "string" ? json.scope.split(/[\s,]+/).filter(Boolean) : []
632
+ };
633
+ },
634
+ async fetchProfile({
635
+ tokenSet,
636
+ extraConfig: _extraConfig,
637
+ fetcher
638
+ }) {
639
+ const res = await fetcher("https://openidconnect.googleapis.com/v1/userinfo", {
640
+ headers: {
641
+ authorization: `Bearer ${tokenSet.accessToken}`,
642
+ "user-agent": "gale"
643
+ }
644
+ });
645
+ if (!res.ok) {
646
+ throw new GaleError({
647
+ code: "oauth_profile_fetch_failed",
648
+ message: `Google userinfo ${res.status}`,
649
+ status: 502
650
+ });
651
+ }
652
+ const json = await res.json();
653
+ if (!json.sub) {
654
+ throw new GaleError({
655
+ code: "oauth_profile_malformed",
656
+ message: "Google userinfo missing sub",
657
+ status: 502
658
+ });
659
+ }
660
+ return {
661
+ sub: json.sub,
662
+ email: json.email ?? null,
663
+ emailVerified: json.email_verified === true,
664
+ displayName: json.name ?? null,
665
+ avatarUrl: json.picture ?? null,
666
+ raw: { sub: json.sub, email: json.email, name: json.name }
667
+ };
668
+ }
669
+ };
670
+
671
+ // src/oauth/microsoft.ts
672
+ var MICROSOFT_DEFAULT_SCOPES = ["openid", "email", "profile", "User.Read"];
673
+ var AUTHORIZE = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
674
+ var TOKEN = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
675
+ var GRAPH_ME = "https://graph.microsoft.com/v1.0/me";
676
+ function resolveEmail(mail, upn) {
677
+ if (mail) return { email: mail, emailVerified: true };
678
+ if (upn && upn.includes("@")) {
679
+ return { email: upn, emailVerified: true };
680
+ }
681
+ return { email: null, emailVerified: false };
682
+ }
683
+ var microsoftAdapter = {
684
+ provider: "microsoft",
685
+ displayName: "Microsoft",
686
+ defaultScopes: MICROSOFT_DEFAULT_SCOPES,
687
+ buildAuthorizeUrl({
688
+ clientId,
689
+ redirectUri,
690
+ state,
691
+ codeChallenge,
692
+ scopes,
693
+ extraConfig: _extraConfig
694
+ }) {
695
+ const params = new URLSearchParams({
696
+ client_id: clientId,
697
+ redirect_uri: redirectUri,
698
+ scope: scopes.join(" "),
699
+ state,
700
+ response_type: "code",
701
+ code_challenge: codeChallenge,
702
+ code_challenge_method: "S256"
703
+ });
704
+ return `${AUTHORIZE}?${params.toString()}`;
705
+ },
706
+ async exchangeCode({
707
+ clientId,
708
+ clientSecret,
709
+ redirectUri,
710
+ code,
711
+ codeVerifier,
712
+ extraConfig: _extraConfig,
713
+ fetcher
714
+ }) {
715
+ const body = new URLSearchParams({
716
+ client_id: clientId,
717
+ client_secret: clientSecret,
718
+ code,
719
+ redirect_uri: redirectUri,
720
+ grant_type: "authorization_code",
721
+ code_verifier: codeVerifier
722
+ });
723
+ const res = await fetcher(TOKEN, {
724
+ method: "POST",
725
+ headers: {
726
+ "content-type": "application/x-www-form-urlencoded",
727
+ accept: "application/json"
728
+ },
729
+ body: body.toString()
730
+ });
731
+ if (!res.ok) {
732
+ throw new GaleError({
733
+ code: "oauth_token_exchange_failed",
734
+ message: `Microsoft token endpoint ${res.status}`,
735
+ status: 502
736
+ });
737
+ }
738
+ const json = await res.json();
739
+ if (json.error || !json.access_token) {
740
+ throw new GaleError({
741
+ code: "oauth_token_exchange_failed",
742
+ message: json.error_description || json.error || "no access_token",
743
+ status: 400
744
+ });
745
+ }
746
+ return {
747
+ accessToken: json.access_token,
748
+ expiresInSec: json.expires_in ?? null,
749
+ refreshToken: json.refresh_token ?? null,
750
+ tokenType: json.token_type || "bearer",
751
+ scopes: typeof json.scope === "string" ? json.scope.split(/[\s,]+/).filter(Boolean) : []
752
+ };
753
+ },
754
+ async fetchProfile({
755
+ tokenSet,
756
+ extraConfig: _extraConfig,
757
+ fetcher
758
+ }) {
759
+ const res = await fetcher(GRAPH_ME, {
760
+ headers: {
761
+ authorization: `Bearer ${tokenSet.accessToken}`,
762
+ "user-agent": "gale"
763
+ }
764
+ });
765
+ if (!res.ok) {
766
+ throw new GaleError({
767
+ code: "oauth_profile_fetch_failed",
768
+ message: `Microsoft Graph /me ${res.status}`,
769
+ status: 502
770
+ });
771
+ }
772
+ const json = await res.json();
773
+ if (!json.id) {
774
+ throw new GaleError({
775
+ code: "oauth_profile_malformed",
776
+ message: "Microsoft Graph /me missing id",
777
+ status: 502
778
+ });
779
+ }
780
+ const { email, emailVerified } = resolveEmail(json.mail, json.userPrincipalName);
781
+ return {
782
+ sub: json.id,
783
+ email,
784
+ emailVerified,
785
+ displayName: json.displayName ?? null,
786
+ avatarUrl: null,
787
+ raw: { id: json.id, displayName: json.displayName, mail: json.mail }
788
+ };
789
+ }
790
+ };
791
+
792
+ // src/oauth/wechat.ts
793
+ var WECHAT_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
794
+ var WECHAT_USERINFO = "https://api.weixin.qq.com/sns/userinfo";
795
+ function scopeFromConfig(scopes, extraConfig, fallback) {
796
+ if (scopes.length > 0) return scopes[0] ?? fallback;
797
+ return typeof extraConfig.scope === "string" ? extraConfig.scope : fallback;
798
+ }
799
+ function buildWechatAuthorizeUrl(input, mode, fallbackScope) {
800
+ const endpoint = mode === "web" ? "https://open.weixin.qq.com/connect/qrconnect" : "https://open.weixin.qq.com/connect/oauth2/authorize";
801
+ const params = new URLSearchParams({
802
+ appid: input.clientId,
803
+ redirect_uri: input.redirectUri,
804
+ response_type: "code",
805
+ scope: scopeFromConfig(input.scopes, input.extraConfig, fallbackScope),
806
+ state: input.state
807
+ });
808
+ return `${endpoint}?${params.toString()}#wechat_redirect`;
809
+ }
810
+ function splitScopes(scope) {
811
+ return typeof scope === "string" ? scope.split(/[\s,]+/).filter(Boolean) : [];
812
+ }
813
+ async function exchangeWechatCode(input, label) {
814
+ const params = new URLSearchParams({
815
+ appid: input.clientId,
816
+ secret: input.clientSecret,
817
+ code: input.code,
818
+ grant_type: "authorization_code"
819
+ });
820
+ const res = await input.fetcher(`${WECHAT_TOKEN}?${params.toString()}`, {
821
+ headers: { accept: "application/json", "user-agent": "gale" }
822
+ });
823
+ if (!res.ok) {
824
+ throw new GaleError({
825
+ code: "oauth_token_exchange_failed",
826
+ message: `${label} token endpoint ${res.status}`,
827
+ status: 502
828
+ });
829
+ }
830
+ const json = await res.json();
831
+ if (json.errcode || !json.access_token || !json.openid) {
832
+ throw new GaleError({
833
+ code: "oauth_token_exchange_failed",
834
+ message: json.errmsg || `WeChat token error ${json.errcode ?? "missing access_token"}`,
835
+ status: 400
836
+ });
837
+ }
838
+ return {
839
+ accessToken: json.access_token,
840
+ expiresInSec: json.expires_in ?? null,
841
+ refreshToken: json.refresh_token ?? null,
842
+ tokenType: "bearer",
843
+ scopes: splitScopes(json.scope),
844
+ raw: {
845
+ openid: json.openid,
846
+ unionid: json.unionid,
847
+ scope: json.scope,
848
+ appid: input.clientId
849
+ }
850
+ };
851
+ }
852
+ function profileFromWechatRaw(raw, extra) {
853
+ const unionid = typeof raw.unionid === "string" ? raw.unionid : null;
854
+ const openid = typeof raw.openid === "string" ? raw.openid : null;
855
+ const preferOpenId = extra.useUnionId === false;
856
+ const sub = preferOpenId ? openid : unionid ?? openid;
857
+ if (!sub) {
858
+ throw new GaleError({
859
+ code: "oauth_profile_malformed",
860
+ message: "WeChat profile missing openid",
861
+ status: 502
862
+ });
863
+ }
864
+ return { sub, openid, unionid };
865
+ }
866
+ async function fetchWechatProfile(input, label) {
867
+ const rawToken = input.tokenSet.raw ?? {};
868
+ const openid = typeof rawToken.openid === "string" ? rawToken.openid : null;
869
+ if (!openid) {
870
+ throw new GaleError({
871
+ code: "oauth_profile_malformed",
872
+ message: "WeChat token missing openid",
873
+ status: 502
874
+ });
875
+ }
876
+ if (input.tokenSet.scopes.includes("snsapi_base")) {
877
+ const { sub: sub2, unionid } = profileFromWechatRaw(rawToken, input.extraConfig);
878
+ return {
879
+ sub: sub2,
880
+ email: null,
881
+ emailVerified: false,
882
+ displayName: null,
883
+ avatarUrl: null,
884
+ raw: { ...rawToken, unionid, mode: input.extraConfig.mode }
885
+ };
886
+ }
887
+ const params = new URLSearchParams({
888
+ access_token: input.tokenSet.accessToken,
889
+ openid,
890
+ lang: typeof input.extraConfig.lang === "string" ? input.extraConfig.lang : "zh_CN"
891
+ });
892
+ const res = await input.fetcher(`${WECHAT_USERINFO}?${params.toString()}`, {
893
+ headers: { accept: "application/json", "user-agent": "gale" }
894
+ });
895
+ if (!res.ok) {
896
+ throw new GaleError({
897
+ code: "oauth_profile_fetch_failed",
898
+ message: `${label} userinfo ${res.status}`,
899
+ status: 502
900
+ });
901
+ }
902
+ const json = await res.json();
903
+ if (json.errcode) {
904
+ throw new GaleError({
905
+ code: "oauth_profile_fetch_failed",
906
+ message: json.errmsg || `WeChat userinfo error ${json.errcode}`,
907
+ status: 502
908
+ });
909
+ }
910
+ const merged = { ...rawToken, ...json };
911
+ const { sub } = profileFromWechatRaw(merged, input.extraConfig);
912
+ return {
913
+ sub,
914
+ email: null,
915
+ emailVerified: false,
916
+ displayName: json.nickname ?? null,
917
+ avatarUrl: json.headimgurl ?? null,
918
+ raw: { ...merged, mode: input.extraConfig.mode }
919
+ };
920
+ }
921
+ var wechatWebAdapter = {
922
+ provider: "wechat_web",
923
+ displayName: "WeChat Web",
924
+ defaultScopes: ["snsapi_login"],
925
+ buildAuthorizeUrl(input) {
926
+ return buildWechatAuthorizeUrl(input, "web", "snsapi_login");
927
+ },
928
+ exchangeCode(input) {
929
+ return exchangeWechatCode(input, "WeChat Web");
930
+ },
931
+ fetchProfile(input) {
932
+ return fetchWechatProfile(input, "WeChat Web");
933
+ }
934
+ };
935
+ var wechatOfficialAccountAdapter = {
936
+ provider: "wechat_official_account",
937
+ displayName: "WeChat Official Account",
938
+ defaultScopes: ["snsapi_userinfo"],
939
+ buildAuthorizeUrl(input) {
940
+ return buildWechatAuthorizeUrl(input, "official_account", "snsapi_userinfo");
941
+ },
942
+ exchangeCode(input) {
943
+ return exchangeWechatCode(input, "WeChat Official Account");
944
+ },
945
+ fetchProfile(input) {
946
+ return fetchWechatProfile(input, "WeChat Official Account");
947
+ }
948
+ };
949
+
950
+ // src/oauth/wecom.ts
951
+ var AUTHORIZE2 = "https://open.weixin.qq.com/connect/oauth2/authorize";
952
+ var API_BASE = "https://qyapi.weixin.qq.com/cgi-bin";
953
+ var suiteAccessTokenCache = /* @__PURE__ */ new Map();
954
+ var SUITE_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1e3;
955
+ function firstScope(scopes, extraConfig) {
956
+ if (scopes.length > 0) return scopes[0] ?? "snsapi_privateinfo";
957
+ return typeof extraConfig.scope === "string" ? extraConfig.scope : "snsapi_privateinfo";
958
+ }
959
+ function isThirdPartyMode(extraConfig) {
960
+ return extraConfig.mode === "third_party";
961
+ }
962
+ function stringConfig(extraConfig, key) {
963
+ const value = extraConfig[key];
964
+ return typeof value === "string" && value.trim() ? value.trim() : null;
965
+ }
966
+ function suiteTokenCacheKey(input) {
967
+ return `${input.suiteId}:${input.suiteSecret}:${input.suiteTicket}`;
968
+ }
969
+ function clearWeComSuiteAccessTokenCacheForTests() {
970
+ suiteAccessTokenCache.clear();
971
+ }
972
+ async function getSuiteAccessToken(input) {
973
+ const configuredToken = stringConfig(input.extraConfig, "suiteAccessToken");
974
+ if (configuredToken) {
975
+ return { accessToken: configuredToken, expiresInSec: null };
976
+ }
977
+ const suiteTicket = stringConfig(input.extraConfig, "suiteTicket");
978
+ if (!suiteTicket) {
979
+ throw new GaleError({
980
+ code: "oauth_provider_misconfigured",
981
+ message: "WeCom third-party mode requires suiteAccessToken or suiteTicket",
982
+ status: 422
983
+ });
984
+ }
985
+ const cacheKey = suiteTokenCacheKey({
986
+ suiteId: input.suiteId,
987
+ suiteSecret: input.suiteSecret,
988
+ suiteTicket
989
+ });
990
+ const cached = suiteAccessTokenCache.get(cacheKey);
991
+ if (cached && cached.expiresAtMs - SUITE_TOKEN_REFRESH_SKEW_MS > Date.now()) {
992
+ return { accessToken: cached.accessToken, expiresInSec: null };
993
+ }
994
+ const res = await input.fetcher(`${API_BASE}/service/get_suite_token`, {
995
+ method: "POST",
996
+ headers: {
997
+ accept: "application/json",
998
+ "content-type": "application/json",
999
+ "user-agent": "gale"
1000
+ },
1001
+ body: JSON.stringify({
1002
+ suite_id: input.suiteId,
1003
+ suite_secret: input.suiteSecret,
1004
+ suite_ticket: suiteTicket
1005
+ })
1006
+ });
1007
+ if (!res.ok) {
1008
+ throw new GaleError({
1009
+ code: "oauth_token_exchange_failed",
1010
+ message: `WeCom get_suite_token ${res.status}`,
1011
+ status: 502
1012
+ });
1013
+ }
1014
+ const token = await res.json();
1015
+ if (token.errcode || !token.suite_access_token) {
1016
+ throw new GaleError({
1017
+ code: "oauth_token_exchange_failed",
1018
+ message: token.errmsg || `WeCom get_suite_token error ${token.errcode ?? "missing access_token"}`,
1019
+ status: 400
1020
+ });
1021
+ }
1022
+ if (token.expires_in && token.expires_in > 0) {
1023
+ suiteAccessTokenCache.set(cacheKey, {
1024
+ accessToken: token.suite_access_token,
1025
+ expiresAtMs: Date.now() + token.expires_in * 1e3
1026
+ });
1027
+ }
1028
+ return {
1029
+ accessToken: token.suite_access_token,
1030
+ expiresInSec: token.expires_in ?? null
1031
+ };
1032
+ }
1033
+ var wecomAdapter = {
1034
+ provider: "wecom",
1035
+ displayName: "WeCom",
1036
+ defaultScopes: ["snsapi_privateinfo"],
1037
+ buildAuthorizeUrl({ clientId, redirectUri, state, scopes, extraConfig }) {
1038
+ const params = new URLSearchParams({
1039
+ appid: clientId,
1040
+ redirect_uri: redirectUri,
1041
+ response_type: "code",
1042
+ scope: firstScope(scopes, extraConfig),
1043
+ state
1044
+ });
1045
+ if (!isThirdPartyMode(extraConfig)) {
1046
+ const agentId = typeof extraConfig.agentId === "string" || typeof extraConfig.agentId === "number" ? String(extraConfig.agentId) : null;
1047
+ if (agentId) params.set("agentid", agentId);
1048
+ }
1049
+ return `${AUTHORIZE2}?${params.toString()}#wechat_redirect`;
1050
+ },
1051
+ async exchangeCode({
1052
+ clientId,
1053
+ clientSecret,
1054
+ code,
1055
+ extraConfig,
1056
+ fetcher
1057
+ }) {
1058
+ if (isThirdPartyMode(extraConfig)) {
1059
+ const suiteToken = await getSuiteAccessToken({
1060
+ suiteId: clientId,
1061
+ suiteSecret: clientSecret,
1062
+ extraConfig,
1063
+ fetcher
1064
+ });
1065
+ const userParams2 = new URLSearchParams({ access_token: suiteToken.accessToken, code });
1066
+ const userRes2 = await fetcher(`${API_BASE}/service/getuserinfo3rd?${userParams2.toString()}`, {
1067
+ headers: { accept: "application/json", "user-agent": "gale" }
1068
+ });
1069
+ if (!userRes2.ok) {
1070
+ throw new GaleError({
1071
+ code: "oauth_token_exchange_failed",
1072
+ message: `WeCom getuserinfo3rd ${userRes2.status}`,
1073
+ status: 502
1074
+ });
1075
+ }
1076
+ const user2 = await userRes2.json();
1077
+ if (user2.errcode || !user2.UserId && !user2.OpenId) {
1078
+ throw new GaleError({
1079
+ code: "oauth_token_exchange_failed",
1080
+ message: user2.errmsg || `WeCom getuserinfo3rd error ${user2.errcode ?? "missing userid"}`,
1081
+ status: 400
1082
+ });
1083
+ }
1084
+ return {
1085
+ accessToken: suiteToken.accessToken,
1086
+ expiresInSec: suiteToken.expiresInSec,
1087
+ refreshToken: null,
1088
+ tokenType: "bearer",
1089
+ scopes: [],
1090
+ raw: {
1091
+ mode: "third_party",
1092
+ userId: user2.UserId,
1093
+ openId: user2.OpenId,
1094
+ userTicket: user2.user_ticket,
1095
+ corpId: user2.CorpId,
1096
+ deviceId: user2.DeviceId,
1097
+ suiteId: clientId
1098
+ }
1099
+ };
1100
+ }
1101
+ const tokenParams = new URLSearchParams({ corpid: clientId, corpsecret: clientSecret });
1102
+ const tokenRes = await fetcher(`${API_BASE}/gettoken?${tokenParams.toString()}`, {
1103
+ headers: { accept: "application/json", "user-agent": "gale" }
1104
+ });
1105
+ if (!tokenRes.ok) {
1106
+ throw new GaleError({
1107
+ code: "oauth_token_exchange_failed",
1108
+ message: `WeCom gettoken ${tokenRes.status}`,
1109
+ status: 502
1110
+ });
1111
+ }
1112
+ const token = await tokenRes.json();
1113
+ if (token.errcode || !token.access_token) {
1114
+ throw new GaleError({
1115
+ code: "oauth_token_exchange_failed",
1116
+ message: token.errmsg || `WeCom gettoken error ${token.errcode ?? "missing access_token"}`,
1117
+ status: 400
1118
+ });
1119
+ }
1120
+ const userParams = new URLSearchParams({ access_token: token.access_token, code });
1121
+ const userRes = await fetcher(`${API_BASE}/auth/getuserinfo?${userParams.toString()}`, {
1122
+ headers: { accept: "application/json", "user-agent": "gale" }
1123
+ });
1124
+ if (!userRes.ok) {
1125
+ throw new GaleError({
1126
+ code: "oauth_token_exchange_failed",
1127
+ message: `WeCom getuserinfo ${userRes.status}`,
1128
+ status: 502
1129
+ });
1130
+ }
1131
+ const user = await userRes.json();
1132
+ if (user.errcode || !user.UserId && !user.OpenId) {
1133
+ throw new GaleError({
1134
+ code: "oauth_token_exchange_failed",
1135
+ message: user.errmsg || `WeCom getuserinfo error ${user.errcode ?? "missing userid"}`,
1136
+ status: 400
1137
+ });
1138
+ }
1139
+ return {
1140
+ accessToken: token.access_token,
1141
+ expiresInSec: token.expires_in ?? null,
1142
+ refreshToken: null,
1143
+ tokenType: "bearer",
1144
+ scopes: [],
1145
+ raw: {
1146
+ userId: user.UserId,
1147
+ openId: user.OpenId,
1148
+ userTicket: user.user_ticket,
1149
+ corpId: clientId
1150
+ }
1151
+ };
1152
+ },
1153
+ async fetchProfile({ tokenSet, extraConfig, fetcher }) {
1154
+ const raw = tokenSet.raw ?? {};
1155
+ const userId = typeof raw.userId === "string" ? raw.userId : null;
1156
+ const openId = typeof raw.openId === "string" ? raw.openId : null;
1157
+ const userTicket = typeof raw.userTicket === "string" ? raw.userTicket : null;
1158
+ const thirdParty = raw.mode === "third_party" || isThirdPartyMode(extraConfig);
1159
+ const sub = userId ?? openId;
1160
+ if (!sub) {
1161
+ throw new GaleError({
1162
+ code: "oauth_profile_malformed",
1163
+ message: "WeCom profile missing userid/openid",
1164
+ status: 502
1165
+ });
1166
+ }
1167
+ let detail = null;
1168
+ if (userTicket) {
1169
+ const path = thirdParty ? "service/getuserdetail3rd" : "auth/getuserdetail";
1170
+ const res = await fetcher(`${API_BASE}/${path}?access_token=${tokenSet.accessToken}`, {
1171
+ method: "POST",
1172
+ headers: {
1173
+ accept: "application/json",
1174
+ "content-type": "application/json",
1175
+ "user-agent": "gale"
1176
+ },
1177
+ body: JSON.stringify({ user_ticket: userTicket })
1178
+ });
1179
+ if (res.ok) {
1180
+ const json = await res.json();
1181
+ if (!json.errcode) detail = json;
1182
+ }
1183
+ }
1184
+ const email = detail?.email ?? detail?.biz_mail ?? null;
1185
+ return {
1186
+ sub,
1187
+ email,
1188
+ emailVerified: !!email,
1189
+ displayName: detail?.name ?? null,
1190
+ avatarUrl: detail?.avatar ?? null,
1191
+ raw: {
1192
+ ...raw,
1193
+ ...detail,
1194
+ mode: thirdParty ? "third_party" : "internal",
1195
+ agentId: extraConfig.agentId
1196
+ }
1197
+ };
1198
+ }
1199
+ };
1200
+
1201
+ // src/oauth/china.ts
1202
+ function splitScopes2(scope) {
1203
+ return typeof scope === "string" ? scope.split(/[\s,]+/).filter(Boolean) : [];
1204
+ }
1205
+ async function readJson(res, label) {
1206
+ try {
1207
+ return await res.json();
1208
+ } catch {
1209
+ throw new GaleError({
1210
+ code: "oauth_response_malformed",
1211
+ message: `${label} invalid JSON`,
1212
+ status: 502
1213
+ });
1214
+ }
1215
+ }
1216
+ function jsonRecord(value) {
1217
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1218
+ }
1219
+ function stringValue(value) {
1220
+ return typeof value === "string" && value.length > 0 ? value : null;
1221
+ }
1222
+ function numberValue(value) {
1223
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
1224
+ }
1225
+ function buildStandardAuthorizeUrl(endpoint, input, scopeSeparator = " ") {
1226
+ const params = new URLSearchParams({
1227
+ response_type: "code",
1228
+ client_id: input.clientId,
1229
+ redirect_uri: input.redirectUri,
1230
+ state: input.state
1231
+ });
1232
+ if (input.scopes.length > 0) params.set("scope", input.scopes.join(scopeSeparator));
1233
+ return `${endpoint}?${params.toString()}`;
1234
+ }
1235
+ var qqAdapter = {
1236
+ provider: "qq",
1237
+ displayName: "QQ",
1238
+ defaultScopes: ["get_user_info"],
1239
+ buildAuthorizeUrl(input) {
1240
+ return buildStandardAuthorizeUrl("https://graph.qq.com/oauth2.0/authorize", input, ",");
1241
+ },
1242
+ async exchangeCode({
1243
+ clientId,
1244
+ clientSecret,
1245
+ redirectUri,
1246
+ code,
1247
+ fetcher
1248
+ }) {
1249
+ const params = new URLSearchParams({
1250
+ grant_type: "authorization_code",
1251
+ client_id: clientId,
1252
+ client_secret: clientSecret,
1253
+ code,
1254
+ redirect_uri: redirectUri,
1255
+ fmt: "json"
1256
+ });
1257
+ const res = await fetcher(`https://graph.qq.com/oauth2.0/token?${params.toString()}`, {
1258
+ headers: { accept: "application/json", "user-agent": "gale" }
1259
+ });
1260
+ if (!res.ok) {
1261
+ throw new GaleError({
1262
+ code: "oauth_token_exchange_failed",
1263
+ message: `QQ token endpoint ${res.status}`,
1264
+ status: 502
1265
+ });
1266
+ }
1267
+ const json = await readJson(res, "QQ token");
1268
+ if (json.error || !json.access_token) {
1269
+ throw new GaleError({
1270
+ code: "oauth_token_exchange_failed",
1271
+ message: json.error_description ?? json.msg ?? String(json.error ?? "no access_token"),
1272
+ status: 400
1273
+ });
1274
+ }
1275
+ return {
1276
+ accessToken: json.access_token,
1277
+ expiresInSec: json.expires_in ?? null,
1278
+ refreshToken: json.refresh_token ?? null,
1279
+ tokenType: "bearer",
1280
+ scopes: []
1281
+ };
1282
+ },
1283
+ async fetchProfile({ tokenSet, fetcher }) {
1284
+ const meParams = new URLSearchParams({ access_token: tokenSet.accessToken, fmt: "json" });
1285
+ const meRes = await fetcher(`https://graph.qq.com/oauth2.0/me?${meParams.toString()}`, {
1286
+ headers: { accept: "application/json", "user-agent": "gale" }
1287
+ });
1288
+ if (!meRes.ok) {
1289
+ throw new GaleError({
1290
+ code: "oauth_profile_fetch_failed",
1291
+ message: `QQ openid endpoint ${meRes.status}`,
1292
+ status: 502
1293
+ });
1294
+ }
1295
+ const me = await readJson(meRes, "QQ openid");
1296
+ if (me.error || !me.openid) {
1297
+ throw new GaleError({
1298
+ code: "oauth_profile_malformed",
1299
+ message: me.error_description ?? String(me.error ?? "QQ openid missing"),
1300
+ status: 502
1301
+ });
1302
+ }
1303
+ const userParams = new URLSearchParams({
1304
+ access_token: tokenSet.accessToken,
1305
+ oauth_consumer_key: me.client_id ?? "",
1306
+ openid: me.openid,
1307
+ fmt: "json"
1308
+ });
1309
+ const userRes = await fetcher(`https://graph.qq.com/user/get_user_info?${userParams}`, {
1310
+ headers: { accept: "application/json", "user-agent": "gale" }
1311
+ });
1312
+ if (!userRes.ok) {
1313
+ throw new GaleError({
1314
+ code: "oauth_profile_fetch_failed",
1315
+ message: `QQ get_user_info ${userRes.status}`,
1316
+ status: 502
1317
+ });
1318
+ }
1319
+ const user = await readJson(userRes, "QQ userinfo");
1320
+ if (user.ret && user.ret !== 0) {
1321
+ throw new GaleError({
1322
+ code: "oauth_profile_fetch_failed",
1323
+ message: user.msg ?? `QQ get_user_info error ${user.ret}`,
1324
+ status: 502
1325
+ });
1326
+ }
1327
+ return {
1328
+ sub: me.openid,
1329
+ email: null,
1330
+ emailVerified: false,
1331
+ displayName: user.nickname ?? null,
1332
+ avatarUrl: user.figureurl_qq_2 ?? user.figureurl_qq_1 ?? null,
1333
+ raw: { ...me, ...user }
1334
+ };
1335
+ }
1336
+ };
1337
+ var weiboAdapter = {
1338
+ provider: "weibo",
1339
+ displayName: "Weibo",
1340
+ defaultScopes: [],
1341
+ buildAuthorizeUrl(input) {
1342
+ return buildStandardAuthorizeUrl("https://api.weibo.com/oauth2/authorize", input, ",");
1343
+ },
1344
+ async exchangeCode({
1345
+ clientId,
1346
+ clientSecret,
1347
+ redirectUri,
1348
+ code,
1349
+ fetcher
1350
+ }) {
1351
+ const body = new URLSearchParams({
1352
+ grant_type: "authorization_code",
1353
+ client_id: clientId,
1354
+ client_secret: clientSecret,
1355
+ code,
1356
+ redirect_uri: redirectUri
1357
+ });
1358
+ const res = await fetcher("https://api.weibo.com/oauth2/access_token", {
1359
+ method: "POST",
1360
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
1361
+ body: body.toString()
1362
+ });
1363
+ if (!res.ok) {
1364
+ throw new GaleError({
1365
+ code: "oauth_token_exchange_failed",
1366
+ message: `Weibo token endpoint ${res.status}`,
1367
+ status: 502
1368
+ });
1369
+ }
1370
+ const json = await readJson(res, "Weibo token");
1371
+ if (json.error || !json.access_token || !json.uid) {
1372
+ throw new GaleError({
1373
+ code: "oauth_token_exchange_failed",
1374
+ message: json.error_description ?? json.error ?? "missing access_token",
1375
+ status: 400
1376
+ });
1377
+ }
1378
+ return {
1379
+ accessToken: json.access_token,
1380
+ expiresInSec: json.expires_in ?? null,
1381
+ refreshToken: json.refresh_token ?? null,
1382
+ tokenType: "bearer",
1383
+ scopes: [],
1384
+ raw: { uid: json.uid }
1385
+ };
1386
+ },
1387
+ async fetchProfile({ tokenSet, fetcher }) {
1388
+ const uid = stringValue(tokenSet.raw?.uid);
1389
+ if (!uid) {
1390
+ throw new GaleError({
1391
+ code: "oauth_profile_malformed",
1392
+ message: "Weibo token missing uid",
1393
+ status: 502
1394
+ });
1395
+ }
1396
+ const params = new URLSearchParams({ access_token: tokenSet.accessToken, uid });
1397
+ const res = await fetcher(`https://api.weibo.com/2/users/show.json?${params.toString()}`, {
1398
+ headers: { accept: "application/json", "user-agent": "gale" }
1399
+ });
1400
+ if (!res.ok) {
1401
+ throw new GaleError({
1402
+ code: "oauth_profile_fetch_failed",
1403
+ message: `Weibo users/show ${res.status}`,
1404
+ status: 502
1405
+ });
1406
+ }
1407
+ const user = await readJson(res, "Weibo userinfo");
1408
+ if (user.error || user.error_code) {
1409
+ throw new GaleError({
1410
+ code: "oauth_profile_fetch_failed",
1411
+ message: user.error ?? `Weibo users/show error ${user.error_code}`,
1412
+ status: 502
1413
+ });
1414
+ }
1415
+ const sub = user.idstr ?? (typeof user.id === "number" ? String(user.id) : uid);
1416
+ return {
1417
+ sub,
1418
+ email: null,
1419
+ emailVerified: false,
1420
+ displayName: user.screen_name ?? user.name ?? null,
1421
+ avatarUrl: user.avatar_large ?? user.profile_image_url ?? null,
1422
+ raw: { ...user, uid }
1423
+ };
1424
+ }
1425
+ };
1426
+ var baiduAdapter = {
1427
+ provider: "baidu",
1428
+ displayName: "Baidu",
1429
+ defaultScopes: ["basic"],
1430
+ buildAuthorizeUrl(input) {
1431
+ return buildStandardAuthorizeUrl("https://openapi.baidu.com/oauth/2.0/authorize", input);
1432
+ },
1433
+ async exchangeCode({
1434
+ clientId,
1435
+ clientSecret,
1436
+ redirectUri,
1437
+ code,
1438
+ fetcher
1439
+ }) {
1440
+ const params = new URLSearchParams({
1441
+ grant_type: "authorization_code",
1442
+ code,
1443
+ client_id: clientId,
1444
+ client_secret: clientSecret,
1445
+ redirect_uri: redirectUri
1446
+ });
1447
+ const res = await fetcher(`https://openapi.baidu.com/oauth/2.0/token?${params.toString()}`, {
1448
+ headers: { accept: "application/json", "user-agent": "gale" }
1449
+ });
1450
+ if (!res.ok) {
1451
+ throw new GaleError({
1452
+ code: "oauth_token_exchange_failed",
1453
+ message: `Baidu token endpoint ${res.status}`,
1454
+ status: 502
1455
+ });
1456
+ }
1457
+ const json = await readJson(res, "Baidu token");
1458
+ if (json.error || !json.access_token) {
1459
+ throw new GaleError({
1460
+ code: "oauth_token_exchange_failed",
1461
+ message: json.error_description ?? json.error ?? "missing access_token",
1462
+ status: 400
1463
+ });
1464
+ }
1465
+ return {
1466
+ accessToken: json.access_token,
1467
+ expiresInSec: json.expires_in ?? null,
1468
+ refreshToken: json.refresh_token ?? null,
1469
+ tokenType: "bearer",
1470
+ scopes: splitScopes2(json.scope)
1471
+ };
1472
+ },
1473
+ async fetchProfile({ tokenSet, fetcher }) {
1474
+ const params = new URLSearchParams({ access_token: tokenSet.accessToken });
1475
+ const res = await fetcher(
1476
+ `https://openapi.baidu.com/rest/2.0/passport/users/getInfo?${params.toString()}`,
1477
+ { headers: { accept: "application/json", "user-agent": "gale" } }
1478
+ );
1479
+ if (!res.ok) {
1480
+ throw new GaleError({
1481
+ code: "oauth_profile_fetch_failed",
1482
+ message: `Baidu getInfo ${res.status}`,
1483
+ status: 502
1484
+ });
1485
+ }
1486
+ const user = await readJson(res, "Baidu userinfo");
1487
+ if (user.error) {
1488
+ throw new GaleError({
1489
+ code: "oauth_profile_fetch_failed",
1490
+ message: user.error_description ?? user.error,
1491
+ status: 502
1492
+ });
1493
+ }
1494
+ const sub = user.openid ?? user.userid ?? user.uid;
1495
+ if (!sub) {
1496
+ throw new GaleError({
1497
+ code: "oauth_profile_malformed",
1498
+ message: "Baidu profile missing id",
1499
+ status: 502
1500
+ });
1501
+ }
1502
+ return {
1503
+ sub,
1504
+ email: null,
1505
+ emailVerified: false,
1506
+ displayName: user.displayname ?? user.username ?? null,
1507
+ avatarUrl: user.portrait ? `https://himg.bdimg.com/sys/portrait/item/${user.portrait}` : null,
1508
+ raw: { ...user }
1509
+ };
1510
+ }
1511
+ };
1512
+ var dingtalkAdapter = {
1513
+ provider: "dingtalk",
1514
+ displayName: "DingTalk",
1515
+ defaultScopes: ["openid"],
1516
+ buildAuthorizeUrl(input) {
1517
+ return buildStandardAuthorizeUrl("https://login.dingtalk.com/oauth2/auth", input, " ");
1518
+ },
1519
+ async exchangeCode({ clientId, clientSecret, code, fetcher }) {
1520
+ const res = await fetcher("https://api.dingtalk.com/v1.0/oauth2/userAccessToken", {
1521
+ method: "POST",
1522
+ headers: { "content-type": "application/json", accept: "application/json" },
1523
+ body: JSON.stringify({
1524
+ clientId,
1525
+ clientSecret,
1526
+ code,
1527
+ grantType: "authorization_code"
1528
+ })
1529
+ });
1530
+ if (!res.ok) {
1531
+ throw new GaleError({
1532
+ code: "oauth_token_exchange_failed",
1533
+ message: `DingTalk userAccessToken ${res.status}`,
1534
+ status: 502
1535
+ });
1536
+ }
1537
+ const json = await readJson(res, "DingTalk token");
1538
+ if (json.code || !json.accessToken) {
1539
+ throw new GaleError({
1540
+ code: "oauth_token_exchange_failed",
1541
+ message: json.message ?? json.code ?? "missing accessToken",
1542
+ status: 400
1543
+ });
1544
+ }
1545
+ return {
1546
+ accessToken: json.accessToken,
1547
+ expiresInSec: json.expireIn ?? null,
1548
+ refreshToken: json.refreshToken ?? null,
1549
+ tokenType: "bearer",
1550
+ scopes: [],
1551
+ raw: { openId: json.openId, unionId: json.unionId }
1552
+ };
1553
+ },
1554
+ async fetchProfile({ tokenSet, fetcher }) {
1555
+ const res = await fetcher("https://api.dingtalk.com/v1.0/contact/users/me", {
1556
+ headers: { accept: "application/json", authorization: `Bearer ${tokenSet.accessToken}` }
1557
+ });
1558
+ if (!res.ok) {
1559
+ throw new GaleError({
1560
+ code: "oauth_profile_fetch_failed",
1561
+ message: `DingTalk users/me ${res.status}`,
1562
+ status: 502
1563
+ });
1564
+ }
1565
+ const user = await readJson(res, "DingTalk userinfo");
1566
+ if (user.code) {
1567
+ throw new GaleError({
1568
+ code: "oauth_profile_fetch_failed",
1569
+ message: user.message ?? user.code,
1570
+ status: 502
1571
+ });
1572
+ }
1573
+ const sub = user.unionId ?? user.openId ?? stringValue(tokenSet.raw?.unionId) ?? stringValue(tokenSet.raw?.openId);
1574
+ if (!sub) {
1575
+ throw new GaleError({
1576
+ code: "oauth_profile_malformed",
1577
+ message: "DingTalk profile missing openId/unionId",
1578
+ status: 502
1579
+ });
1580
+ }
1581
+ return {
1582
+ sub,
1583
+ email: user.email ?? null,
1584
+ emailVerified: !!user.email,
1585
+ displayName: user.nick ?? null,
1586
+ avatarUrl: user.avatarUrl ?? null,
1587
+ raw: { ...jsonRecord(tokenSet.raw), ...user }
1588
+ };
1589
+ }
1590
+ };
1591
+ function larkBase(extraConfig) {
1592
+ if (typeof extraConfig.apiBase === "string") return extraConfig.apiBase.replace(/\/+$/, "");
1593
+ return extraConfig.region === "global" ? "https://open.larksuite.com" : "https://open.feishu.cn";
1594
+ }
1595
+ var larkAdapter = {
1596
+ provider: "lark",
1597
+ displayName: "Lark",
1598
+ defaultScopes: ["contact:user.base:readonly"],
1599
+ buildAuthorizeUrl(input) {
1600
+ const base = larkBase(input.extraConfig);
1601
+ const endpoint = typeof input.extraConfig.authorizeEndpoint === "string" ? input.extraConfig.authorizeEndpoint : `${base}/open-apis/authen/v1/authorize`;
1602
+ const params = new URLSearchParams({
1603
+ app_id: input.clientId,
1604
+ redirect_uri: input.redirectUri,
1605
+ state: input.state
1606
+ });
1607
+ if (input.scopes.length > 0) params.set("scope", input.scopes.join(" "));
1608
+ return `${endpoint}?${params.toString()}`;
1609
+ },
1610
+ async exchangeCode({
1611
+ clientId,
1612
+ clientSecret,
1613
+ redirectUri,
1614
+ code,
1615
+ extraConfig,
1616
+ fetcher
1617
+ }) {
1618
+ const base = larkBase(extraConfig);
1619
+ const endpoint = typeof extraConfig.tokenEndpoint === "string" ? extraConfig.tokenEndpoint : `${base}/open-apis/authen/v2/oauth/token`;
1620
+ const res = await fetcher(endpoint, {
1621
+ method: "POST",
1622
+ headers: { "content-type": "application/json", accept: "application/json" },
1623
+ body: JSON.stringify({
1624
+ grant_type: "authorization_code",
1625
+ code,
1626
+ client_id: clientId,
1627
+ client_secret: clientSecret,
1628
+ redirect_uri: redirectUri
1629
+ })
1630
+ });
1631
+ if (!res.ok) {
1632
+ throw new GaleError({
1633
+ code: "oauth_token_exchange_failed",
1634
+ message: `Lark token endpoint ${res.status}`,
1635
+ status: 502
1636
+ });
1637
+ }
1638
+ const json = await readJson(res, "Lark token");
1639
+ const data = jsonRecord(json.data);
1640
+ const accessToken = stringValue(data.access_token) ?? stringValue(data.user_access_token) ?? json.access_token ?? json.user_access_token;
1641
+ if (json.error || json.code || !accessToken) {
1642
+ throw new GaleError({
1643
+ code: "oauth_token_exchange_failed",
1644
+ message: json.error_description ?? json.msg ?? json.error ?? "missing access_token",
1645
+ status: 400
1646
+ });
1647
+ }
1648
+ return {
1649
+ accessToken,
1650
+ expiresInSec: numberValue(data.expires_in) ?? json.expires_in ?? null,
1651
+ refreshToken: stringValue(data.refresh_token) ?? json.refresh_token ?? null,
1652
+ tokenType: "bearer",
1653
+ scopes: []
1654
+ };
1655
+ },
1656
+ async fetchProfile({ tokenSet, extraConfig, fetcher }) {
1657
+ const base = larkBase(extraConfig);
1658
+ const endpoint = typeof extraConfig.userInfoEndpoint === "string" ? extraConfig.userInfoEndpoint : `${base}/open-apis/authen/v1/user_info`;
1659
+ const res = await fetcher(endpoint, {
1660
+ headers: { accept: "application/json", authorization: `Bearer ${tokenSet.accessToken}` }
1661
+ });
1662
+ if (!res.ok) {
1663
+ throw new GaleError({
1664
+ code: "oauth_profile_fetch_failed",
1665
+ message: `Lark user_info ${res.status}`,
1666
+ status: 502
1667
+ });
1668
+ }
1669
+ const json = await readJson(res, "Lark userinfo");
1670
+ if (json.error || json.code) {
1671
+ throw new GaleError({
1672
+ code: "oauth_profile_fetch_failed",
1673
+ message: json.error_description ?? json.msg ?? json.error ?? `Lark user_info ${json.code}`,
1674
+ status: 502
1675
+ });
1676
+ }
1677
+ const data = jsonRecord(json.data);
1678
+ const sub = stringValue(data.union_id) ?? stringValue(data.open_id) ?? stringValue(data.user_id);
1679
+ if (!sub) {
1680
+ throw new GaleError({
1681
+ code: "oauth_profile_malformed",
1682
+ message: "Lark profile missing user id",
1683
+ status: 502
1684
+ });
1685
+ }
1686
+ const email = stringValue(data.email);
1687
+ return {
1688
+ sub,
1689
+ email,
1690
+ emailVerified: !!email,
1691
+ displayName: stringValue(data.name) ?? stringValue(data.en_name),
1692
+ avatarUrl: stringValue(data.avatar_url) ?? stringValue(data.avatar_big),
1693
+ raw: { ...data }
1694
+ };
1695
+ }
1696
+ };
1697
+
1698
+ // src/oauth/catalog.ts
1699
+ var IMPLEMENTED_OAUTH_PROVIDER_IDS = [
1700
+ "github",
1701
+ "gitee",
1702
+ "google",
1703
+ "microsoft",
1704
+ "wechat_web",
1705
+ "wechat_official_account",
1706
+ "wechat_miniprogram",
1707
+ "wecom",
1708
+ "alipay",
1709
+ "qq",
1710
+ "dingtalk",
1711
+ "lark",
1712
+ "weibo",
1713
+ "baidu"
1714
+ ];
1715
+ var OAUTH_PROVIDER_CATALOG = [
1716
+ {
1717
+ provider: "github",
1718
+ displayName: "GitHub",
1719
+ family: "github",
1720
+ category: "global",
1721
+ status: "implemented",
1722
+ defaultScopes: ["user:email"],
1723
+ browserVisible: true
1724
+ },
1725
+ {
1726
+ provider: "gitee",
1727
+ displayName: "Gitee",
1728
+ family: "gitee",
1729
+ category: "china",
1730
+ status: "implemented",
1731
+ defaultScopes: [],
1732
+ browserVisible: true
1733
+ },
1734
+ {
1735
+ provider: "google",
1736
+ displayName: "Google",
1737
+ family: "google",
1738
+ category: "global",
1739
+ status: "implemented",
1740
+ defaultScopes: ["openid", "email", "profile"],
1741
+ browserVisible: true
1742
+ },
1743
+ {
1744
+ provider: "microsoft",
1745
+ displayName: "Microsoft",
1746
+ family: "microsoft",
1747
+ category: "global",
1748
+ status: "implemented",
1749
+ defaultScopes: ["openid", "email", "profile"],
1750
+ browserVisible: true
1751
+ },
1752
+ {
1753
+ provider: "wechat_web",
1754
+ displayName: "WeChat Web",
1755
+ family: "wechat",
1756
+ category: "china",
1757
+ status: "implemented",
1758
+ defaultScopes: ["snsapi_login"],
1759
+ browserVisible: true,
1760
+ notes: "WeChat Open Platform website QR login."
1761
+ },
1762
+ {
1763
+ provider: "wechat_official_account",
1764
+ displayName: "WeChat Official Account",
1765
+ family: "wechat",
1766
+ category: "china",
1767
+ status: "implemented",
1768
+ defaultScopes: ["snsapi_userinfo"],
1769
+ browserVisible: true,
1770
+ notes: "Visible only in WeChat in-app browser once implemented."
1771
+ },
1772
+ {
1773
+ provider: "wechat_miniprogram",
1774
+ displayName: "WeChat Mini Program",
1775
+ family: "wechat",
1776
+ category: "china",
1777
+ status: "implemented",
1778
+ defaultScopes: [],
1779
+ browserVisible: false,
1780
+ notes: "Native wx.login code-to-session flow; not shown in browser OAuth UI."
1781
+ },
1782
+ {
1783
+ provider: "wecom",
1784
+ displayName: "WeCom",
1785
+ family: "wecom",
1786
+ category: "enterprise",
1787
+ status: "implemented",
1788
+ defaultScopes: ["snsapi_privateinfo"],
1789
+ browserVisible: true,
1790
+ notes: "Supports internal app OAuth and third-party suite member OAuth."
1791
+ },
1792
+ {
1793
+ provider: "alipay",
1794
+ displayName: "Alipay",
1795
+ family: "alipay",
1796
+ category: "china",
1797
+ status: "implemented",
1798
+ defaultScopes: ["auth_user"],
1799
+ browserVisible: true,
1800
+ notes: "Server-side adapter lives in @yhgale/apicore because RSA2 signing is server-only."
1801
+ },
1802
+ {
1803
+ provider: "qq",
1804
+ displayName: "QQ",
1805
+ family: "qq",
1806
+ category: "china",
1807
+ status: "implemented",
1808
+ defaultScopes: ["get_user_info"],
1809
+ browserVisible: true
1810
+ },
1811
+ {
1812
+ provider: "dingtalk",
1813
+ displayName: "DingTalk",
1814
+ family: "dingtalk",
1815
+ category: "enterprise",
1816
+ status: "implemented",
1817
+ defaultScopes: ["openid"],
1818
+ browserVisible: true
1819
+ },
1820
+ {
1821
+ provider: "lark",
1822
+ displayName: "Lark",
1823
+ family: "lark",
1824
+ category: "enterprise",
1825
+ status: "implemented",
1826
+ defaultScopes: ["contact:user.base:readonly"],
1827
+ browserVisible: true
1828
+ },
1829
+ {
1830
+ provider: "weibo",
1831
+ displayName: "Weibo",
1832
+ family: "weibo",
1833
+ category: "china",
1834
+ status: "implemented",
1835
+ defaultScopes: [],
1836
+ browserVisible: true
1837
+ },
1838
+ {
1839
+ provider: "baidu",
1840
+ displayName: "Baidu",
1841
+ family: "baidu",
1842
+ category: "china",
1843
+ status: "implemented",
1844
+ defaultScopes: ["basic"],
1845
+ browserVisible: true
1846
+ }
1847
+ ];
1848
+ var CATALOG_BY_PROVIDER = new Map(
1849
+ OAUTH_PROVIDER_CATALOG.map((entry) => [entry.provider, entry])
1850
+ );
1851
+ function getOauthProviderCatalogEntry(provider) {
1852
+ return CATALOG_BY_PROVIDER.get(provider);
1853
+ }
1854
+ function listOauthProviderCatalog(options) {
1855
+ return OAUTH_PROVIDER_CATALOG.filter((entry) => {
1856
+ if (options?.implementedOnly && entry.status !== "implemented") return false;
1857
+ if (options?.browserVisibleOnly && !entry.browserVisible) return false;
1858
+ return true;
1859
+ });
1860
+ }
1861
+ function isImplementedOauthProvider(provider) {
1862
+ return IMPLEMENTED_OAUTH_PROVIDER_IDS.includes(provider);
1863
+ }
1864
+
1865
+ // src/oauth/index.ts
1866
+ var REGISTRY = {
1867
+ github: githubAdapter,
1868
+ gitee: giteeAdapter,
1869
+ google: googleAdapter,
1870
+ microsoft: microsoftAdapter,
1871
+ wechat_web: wechatWebAdapter,
1872
+ wechat_official_account: wechatOfficialAccountAdapter,
1873
+ wecom: wecomAdapter,
1874
+ qq: qqAdapter,
1875
+ dingtalk: dingtalkAdapter,
1876
+ lark: larkAdapter,
1877
+ weibo: weiboAdapter,
1878
+ baidu: baiduAdapter
1879
+ };
1880
+ function getOauthProviderAdapter(provider) {
1881
+ const a = REGISTRY[provider];
1882
+ if (!a) {
1883
+ throw new GaleError({
1884
+ code: "oauth_provider_unsupported",
1885
+ message: `oauth provider ${provider} is not supported`,
1886
+ status: 422
1887
+ });
1888
+ }
1889
+ return a;
1890
+ }
1891
+ function listSupportedOauthProviders() {
1892
+ return Object.values(REGISTRY);
1893
+ }
1894
+ var SUPPORTED_OAUTH_PROVIDERS = Object.keys(REGISTRY);
1895
+
1896
+ // src/email/slugs.ts
1897
+ var EMAIL_TEMPLATE_SLUGS = {
1898
+ signUpVerification: "sign_up_verification_code",
1899
+ signInCode: "sign_in_code",
1900
+ resetPassword: "reset_password_code",
1901
+ emailChange: "email_change_code",
1902
+ organizationInvitation: "organization_invitation",
1903
+ emailVerification: "email_verification"
1904
+ };
1905
+ function purposeToSlug(purpose) {
1906
+ switch (purpose) {
1907
+ case "sign_up":
1908
+ return EMAIL_TEMPLATE_SLUGS.signUpVerification;
1909
+ case "sign_in":
1910
+ return EMAIL_TEMPLATE_SLUGS.signInCode;
1911
+ case "reset_password":
1912
+ return EMAIL_TEMPLATE_SLUGS.resetPassword;
1913
+ case "verify_email_change":
1914
+ return EMAIL_TEMPLATE_SLUGS.emailChange;
1915
+ }
1916
+ return null;
1917
+ }
1918
+
1919
+ // src/email/defaults.ts
1920
+ var verificationBody = (leadIn) => [
1921
+ `${leadIn}: **{{code}}**`,
1922
+ "",
1923
+ "This code is valid for 10 minutes.",
1924
+ "If you didn't request this, you can safely ignore this email."
1925
+ ].join("\n");
1926
+ var DEFAULT_EMAIL_TEMPLATES = {
1927
+ [EMAIL_TEMPLATE_SLUGS.signUpVerification]: {
1928
+ subject: "Verify your email address",
1929
+ bodyMarkdown: verificationBody("Your verification code is")
1930
+ },
1931
+ [EMAIL_TEMPLATE_SLUGS.signInCode]: {
1932
+ subject: "Sign-in verification code",
1933
+ bodyMarkdown: verificationBody("Your sign-in verification code is")
1934
+ },
1935
+ [EMAIL_TEMPLATE_SLUGS.resetPassword]: {
1936
+ subject: "Reset your password",
1937
+ bodyMarkdown: verificationBody("Your password reset code is")
1938
+ },
1939
+ [EMAIL_TEMPLATE_SLUGS.emailChange]: {
1940
+ subject: "Confirm email change",
1941
+ bodyMarkdown: verificationBody("Your email change confirmation code is")
1942
+ },
1943
+ [EMAIL_TEMPLATE_SLUGS.organizationInvitation]: {
1944
+ subject: "{{inviter_name}} invited you to join {{organization_name}}",
1945
+ bodyMarkdown: [
1946
+ "Hi {{to}},",
1947
+ "",
1948
+ "{{inviter_name}} has invited you to join **{{organization_name}}** as **{{role}}**.",
1949
+ "",
1950
+ "{{accept_url}}",
1951
+ "",
1952
+ "If you did not expect this invitation, you can safely ignore this email."
1953
+ ].join("\n")
1954
+ },
1955
+ [EMAIL_TEMPLATE_SLUGS.emailVerification]: {
1956
+ subject: "Verify your email address",
1957
+ bodyMarkdown: verificationBody("Your verification code is")
1958
+ }
1959
+ };
1960
+ function getDefaultEmailTemplate(slug) {
1961
+ return DEFAULT_EMAIL_TEMPLATES[slug] ?? DEFAULT_EMAIL_TEMPLATES[EMAIL_TEMPLATE_SLUGS.signUpVerification];
1962
+ }
1963
+
1964
+ // src/email/markdown.ts
1965
+ function escapeHtml(value) {
1966
+ return value.replace(
1967
+ /[&<>"']/g,
1968
+ (ch) => ({
1969
+ "&": "&amp;",
1970
+ "<": "&lt;",
1971
+ ">": "&gt;",
1972
+ '"': "&quot;",
1973
+ "'": "&#39;"
1974
+ })[ch] ?? ch
1975
+ );
1976
+ }
1977
+
1978
+ // src/keys.ts
1979
+ var LIVE_PREFIX = "ak_live_";
1980
+ var TEST_PREFIX = "ak_test_";
1981
+ var CURRENT_KEY_VERSION = 1;
1982
+ function base64urlEncode(input) {
1983
+ const binary = encodeURIComponent(input).replace(
1984
+ /%([0-9A-F]{2})/g,
1985
+ (_, p1) => String.fromCharCode(Number("0x" + p1))
1986
+ );
1987
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1988
+ }
1989
+ function base64urlDecode(input) {
1990
+ let base64 = input.replace(/-/g, "+").replace(/_/g, "/");
1991
+ while (base64.length % 4 !== 0) base64 += "=";
1992
+ const binary = atob(base64);
1993
+ return binary.split("").map((c) => "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)).join("");
1994
+ }
1995
+ function buildPublishableKey(input, instanceType) {
1996
+ if (typeof input === "string") {
1997
+ const env = instanceType ?? "production";
1998
+ const prefix2 = env === "production" ? LIVE_PREFIX : TEST_PREFIX;
1999
+ return `${prefix2}${base64urlEncode(`${input}$`)}`;
2000
+ }
2001
+ const prefix = input.environmentType === "production" ? LIVE_PREFIX : TEST_PREFIX;
2002
+ const payload = {
2003
+ v: CURRENT_KEY_VERSION,
2004
+ instanceId: input.instanceId,
2005
+ ...input.slug ? { slug: input.slug.toLowerCase() } : {},
2006
+ ...input.frontendApiHost ? { fapiHost: input.frontendApiHost } : {}
2007
+ };
2008
+ return `${prefix}${base64urlEncode(JSON.stringify(payload))}`;
2009
+ }
2010
+ function parsePublishableKey(key) {
2011
+ if (!key) return null;
2012
+ if (!key.startsWith(LIVE_PREFIX) && !key.startsWith(TEST_PREFIX)) return null;
2013
+ const instanceType = key.startsWith(LIVE_PREFIX) ? "production" : "development";
2014
+ const encoded = key.startsWith(LIVE_PREFIX) ? key.slice(LIVE_PREFIX.length) : key.slice(TEST_PREFIX.length);
2015
+ if (!encoded) return null;
2016
+ let text;
2017
+ try {
2018
+ text = decodeURIComponent(base64urlDecode(encoded));
2019
+ } catch {
2020
+ return null;
2021
+ }
2022
+ const parsedV1 = parsePayloadV1(text, instanceType);
2023
+ if (parsedV1) return parsedV1;
2024
+ const parsedV2 = parsePayloadV2(text, instanceType);
2025
+ if (parsedV2) return parsedV2;
2026
+ if (!text.endsWith("$")) return null;
2027
+ const frontendApiHost = text.slice(0, -1);
2028
+ if (!frontendApiHost) return null;
2029
+ return {
2030
+ frontendApiHost,
2031
+ instanceType,
2032
+ environmentType: instanceType,
2033
+ keyVersion: 1
2034
+ };
2035
+ }
2036
+ function isPublishableKey(key) {
2037
+ return parsePublishableKey(key) !== null;
2038
+ }
2039
+ function parsePayloadV1(text, prefixEnvironment) {
2040
+ let payload;
2041
+ try {
2042
+ payload = JSON.parse(text);
2043
+ } catch {
2044
+ return null;
2045
+ }
2046
+ if (!payload || typeof payload !== "object") return null;
2047
+ const p = payload;
2048
+ if (p.v !== CURRENT_KEY_VERSION) return null;
2049
+ if (!p.instanceId || typeof p.instanceId !== "string") return null;
2050
+ if (p.slug !== void 0 && (typeof p.slug !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(p.slug))) {
2051
+ return null;
2052
+ }
2053
+ return {
2054
+ frontendApiHost: typeof p.fapiHost === "string" ? p.fapiHost : "",
2055
+ instanceType: prefixEnvironment,
2056
+ instanceId: p.instanceId,
2057
+ environmentType: prefixEnvironment,
2058
+ keyVersion: p.v,
2059
+ slug: p.slug
2060
+ };
2061
+ }
2062
+ function parsePayloadV2(text, prefixEnvironment) {
2063
+ let payload;
2064
+ try {
2065
+ payload = JSON.parse(text);
2066
+ } catch {
2067
+ return null;
2068
+ }
2069
+ if (!payload || typeof payload !== "object") return null;
2070
+ const p = payload;
2071
+ if (p.keyVersion !== 2) return null;
2072
+ if (!p.instanceId || typeof p.instanceId !== "string") return null;
2073
+ if (p.environmentType !== "development" && p.environmentType !== "production") return null;
2074
+ if (p.environmentType !== prefixEnvironment) return null;
2075
+ return {
2076
+ frontendApiHost: typeof p.frontendApiHost === "string" ? p.frontendApiHost : "",
2077
+ instanceType: p.environmentType,
2078
+ instanceId: p.instanceId,
2079
+ environmentType: p.environmentType,
2080
+ keyVersion: p.keyVersion,
2081
+ publicPrefix: typeof p.publicPrefix === "string" ? p.publicPrefix : void 0
2082
+ };
2083
+ }
2084
+
2085
+ // src/aiGuide.ts
2086
+ var AI_GUIDE_MODES = ["guide", "fill"];
2087
+ var INSTANCE_SMS_FIELDS = [
2088
+ { key: "provider", type: "string" },
2089
+ { key: "accessKeyId", type: "string" },
2090
+ { key: "accessKeySecret", type: "string", sensitive: true },
2091
+ { key: "signName", type: "string" },
2092
+ { key: "providerAppId", type: "string" },
2093
+ { key: "providerRegion", type: "string" },
2094
+ { key: "templateCodeSignup", type: "string" },
2095
+ { key: "templateCodeSignin", type: "string" },
2096
+ { key: "templateCodeSecondFactor", type: "string" },
2097
+ { key: "templateCodeVerifyPhoneChange", type: "string" },
2098
+ { key: "templateCodeResetPwd", type: "string" },
2099
+ { key: "enabled", type: "boolean" }
2100
+ ];
2101
+ var AI_GUIDE_PAGES = [
2102
+ { pageKey: "instance.sms", fields: INSTANCE_SMS_FIELDS }
2103
+ ];
2104
+ function getAiGuidePageSpec(pageKey) {
2105
+ return AI_GUIDE_PAGES.find((p) => p.pageKey === pageKey);
2106
+ }
2107
+ function listAiGuideSensitiveFieldKeys(pageKey) {
2108
+ const spec = getAiGuidePageSpec(pageKey);
2109
+ if (!spec) return [];
2110
+ return spec.fields.filter((f) => f.sensitive).map((f) => f.key);
2111
+ }
2112
+ var MAX_GUIDE_VALUES = 32;
2113
+ var MAX_GUIDE_VALUE_CHARS = 256;
2114
+ var MAX_GUIDE_NOTE_CHARS = 500;
2115
+ var MAX_GUIDE_FOCUS_FIELDS = 32;
2116
+ function isPlainObject(v) {
2117
+ return typeof v === "object" && v !== null && !Array.isArray(v);
2118
+ }
2119
+ function parseAiGuideDraft(input) {
2120
+ if (!isPlainObject(input)) return null;
2121
+ if (typeof input.pageKey !== "string") return null;
2122
+ const spec = getAiGuidePageSpec(input.pageKey);
2123
+ if (!spec) return null;
2124
+ if (typeof input.mode !== "string" || !AI_GUIDE_MODES.includes(input.mode)) {
2125
+ return null;
2126
+ }
2127
+ if (!isPlainObject(input.values)) return null;
2128
+ const fillable = new Map(spec.fields.filter((f) => !f.sensitive).map((f) => [f.key, f.type]));
2129
+ const entries = Object.entries(input.values);
2130
+ if (entries.length > MAX_GUIDE_VALUES) return null;
2131
+ const values = {};
2132
+ for (const [key, value] of entries) {
2133
+ const fieldType = fillable.get(key);
2134
+ if (!fieldType) return null;
2135
+ if (fieldType === "boolean") {
2136
+ if (typeof value !== "boolean") return null;
2137
+ values[key] = value;
2138
+ } else {
2139
+ if (typeof value !== "string" || value.length > MAX_GUIDE_VALUE_CHARS) return null;
2140
+ values[key] = value;
2141
+ }
2142
+ }
2143
+ if (input.mode === "fill" && entries.length === 0) return null;
2144
+ let focusFields;
2145
+ if (input.focusFields !== void 0) {
2146
+ if (!Array.isArray(input.focusFields) || input.focusFields.length > MAX_GUIDE_FOCUS_FIELDS) {
2147
+ return null;
2148
+ }
2149
+ focusFields = [];
2150
+ for (const raw of input.focusFields) {
2151
+ if (typeof raw !== "string" || !fillable.has(raw)) return null;
2152
+ focusFields.push(raw);
2153
+ }
2154
+ }
2155
+ let note;
2156
+ if (input.note !== void 0) {
2157
+ if (typeof input.note !== "string" || input.note.length > MAX_GUIDE_NOTE_CHARS) return null;
2158
+ note = input.note;
2159
+ }
2160
+ return {
2161
+ pageKey: input.pageKey,
2162
+ mode: input.mode,
2163
+ values,
2164
+ ...focusFields ? { focusFields } : {},
2165
+ ...note !== void 0 ? { note } : {}
2166
+ };
2167
+ }
2168
+
2169
+ // src/aiNavigation.ts
2170
+ var AI_NAVIGATION_PAGE_KEYS = [
2171
+ "workspace.workspaces",
2172
+ "workspace.applications",
2173
+ "workspace.team",
2174
+ "workspace.settings",
2175
+ "application.instances",
2176
+ "application.settings",
2177
+ "instance.overview",
2178
+ "instance.users",
2179
+ "instance.organizations",
2180
+ "instance.logs",
2181
+ "instance.settings",
2182
+ "instance.auth",
2183
+ "instance.multiFactor",
2184
+ "instance.sso",
2185
+ "instance.sms",
2186
+ "instance.smtp",
2187
+ "instance.apiKeys",
2188
+ "instance.domains",
2189
+ "instance.webhooks",
2190
+ "instance.sessions",
2191
+ "instance.accountPortal"
2192
+ ];
2193
+ function parseAiNavigationTarget(input) {
2194
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return null;
2195
+ const pageKey = input.pageKey;
2196
+ if (typeof pageKey !== "string" || !AI_NAVIGATION_PAGE_KEYS.includes(pageKey)) {
2197
+ return null;
2198
+ }
2199
+ return { pageKey };
2200
+ }
2201
+
2202
+ // src/index.ts
2203
+ var GALE_VERSION = "0.0.0";
2204
+ export {
2205
+ AI_GUIDE_MODES,
2206
+ AI_GUIDE_PAGES,
2207
+ AI_NAVIGATION_PAGE_KEYS,
2208
+ DEFAULT_AUTH_CONFIG,
2209
+ DEFAULT_BAPI_PORT,
2210
+ DEFAULT_CAPTCHA_SETTINGS,
2211
+ DEFAULT_DATABASE_URL,
2212
+ DEFAULT_EMAIL_FROM,
2213
+ DEFAULT_EMAIL_TEMPLATES,
2214
+ DEFAULT_FAPI_PORT,
2215
+ DEFAULT_JWT_AUDIENCE,
2216
+ DEFAULT_REDIS_URL,
2217
+ DEFAULT_ROOT_DOMAIN,
2218
+ EMAIL_TEMPLATE_SLUGS,
2219
+ GALE_VERSION,
2220
+ GaleAuthError,
2221
+ GaleConflictError,
2222
+ GaleError,
2223
+ GaleNotFoundError,
2224
+ GalePermissionError,
2225
+ GaleRateLimitError,
2226
+ GaleValidationError,
2227
+ IMPLEMENTED_OAUTH_PROVIDER_IDS,
2228
+ OAUTH_PROVIDER_CATALOG,
2229
+ SUPPORTED_OAUTH_PROVIDERS,
2230
+ UUID_V7_REGEX,
2231
+ _resetDomainCache,
2232
+ baiduAdapter,
2233
+ buildBapiHost,
2234
+ buildDapiHost,
2235
+ buildDashboardFapiHost,
2236
+ buildDashboardHost,
2237
+ buildDevAccountsHost,
2238
+ buildDevAccountsPrefix,
2239
+ buildDevFapiHost,
2240
+ buildDevFapiPrefix,
2241
+ buildFapiHost,
2242
+ buildProdAccountsHost,
2243
+ buildProdAccountsPrefix,
2244
+ buildProdFapiHost,
2245
+ buildProdFapiPrefix,
2246
+ buildPublishableKey,
2247
+ clearWeComSuiteAccessTokenCacheForTests,
2248
+ dingtalkAdapter,
2249
+ escapeHtml,
2250
+ extractFapiPrefix,
2251
+ fapiErrorToGaleError,
2252
+ getAiGuidePageSpec,
2253
+ getDefaultBapiHost,
2254
+ getDefaultDapiHost,
2255
+ getDefaultEmailTemplate,
2256
+ getDefaultFapiHost,
2257
+ getDefaultRootDomain,
2258
+ getOauthProviderAdapter,
2259
+ getOauthProviderCatalogEntry,
2260
+ getRootDomain,
2261
+ giteeAdapter,
2262
+ githubAdapter,
2263
+ googleAdapter,
2264
+ isFapiErrorEnvelope,
2265
+ isImplementedOauthProvider,
2266
+ isPublishableKey,
2267
+ isUuidV7,
2268
+ larkAdapter,
2269
+ listAiGuideSensitiveFieldKeys,
2270
+ listOauthProviderCatalog,
2271
+ listSupportedOauthProviders,
2272
+ microsoftAdapter,
2273
+ networkErrorToGaleError,
2274
+ parseAiGuideDraft,
2275
+ parseAiNavigationTarget,
2276
+ parseDefaultInstanceHost,
2277
+ parseIdentity,
2278
+ parseMe,
2279
+ parseOrganization,
2280
+ parseOrganizationMembership,
2281
+ parsePublishableKey,
2282
+ parseSession,
2283
+ parseSignInAttempt,
2284
+ parseSignInResponse,
2285
+ parseSignUpAttempt,
2286
+ parseSignUpResponse,
2287
+ parseToken,
2288
+ parseUser,
2289
+ purposeToSlug,
2290
+ qqAdapter,
2291
+ wechatOfficialAccountAdapter,
2292
+ wechatWebAdapter,
2293
+ wecomAdapter,
2294
+ weiboAdapter
2295
+ };