@yhgale/shared 0.1.0 → 0.1.1

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