@hanzo/iam 0.8.0 → 0.9.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 (73) hide show
  1. package/dist/auth.cjs +111 -0
  2. package/dist/auth.cjs.map +1 -0
  3. package/dist/auth.d.cts +19 -0
  4. package/dist/auth.d.ts +7 -4
  5. package/dist/auth.js +94 -121
  6. package/dist/auth.js.map +1 -1
  7. package/dist/betterauth.cjs +34 -0
  8. package/dist/betterauth.cjs.map +1 -0
  9. package/dist/betterauth.d.cts +64 -0
  10. package/dist/betterauth.d.ts +7 -10
  11. package/dist/betterauth.js +28 -62
  12. package/dist/betterauth.js.map +1 -1
  13. package/dist/billing.cjs +8 -0
  14. package/dist/billing.cjs.map +1 -0
  15. package/dist/billing.d.cts +2 -0
  16. package/dist/billing.d.ts +2 -16
  17. package/dist/billing.js +5 -17
  18. package/dist/billing.js.map +1 -1
  19. package/dist/browser.cjs +680 -0
  20. package/dist/browser.cjs.map +1 -0
  21. package/dist/browser.d.cts +217 -0
  22. package/dist/browser.d.ts +16 -13
  23. package/dist/browser.js +645 -663
  24. package/dist/browser.js.map +1 -1
  25. package/dist/index.cjs +1087 -0
  26. package/dist/index.cjs.map +1 -0
  27. package/dist/{client.d.ts → index.d.cts} +23 -4
  28. package/dist/index.d.ts +86 -23
  29. package/dist/index.js +1077 -29
  30. package/dist/index.js.map +1 -1
  31. package/dist/nextauth.cjs +35 -0
  32. package/dist/nextauth.cjs.map +1 -0
  33. package/dist/nextauth.d.cts +55 -0
  34. package/dist/nextauth.d.ts +4 -7
  35. package/dist/nextauth.js +30 -66
  36. package/dist/nextauth.js.map +1 -1
  37. package/dist/passport.cjs +49 -0
  38. package/dist/passport.cjs.map +1 -0
  39. package/dist/passport.d.cts +47 -0
  40. package/dist/passport.d.ts +8 -5
  41. package/dist/passport.js +45 -65
  42. package/dist/passport.js.map +1 -1
  43. package/dist/react.cjs +1434 -0
  44. package/dist/react.cjs.map +1 -0
  45. package/dist/react.d.cts +133 -0
  46. package/dist/react.d.ts +19 -50
  47. package/dist/react.js +1399 -494
  48. package/dist/react.js.map +1 -1
  49. package/dist/types.cjs +4 -0
  50. package/dist/types.cjs.map +1 -0
  51. package/dist/types.d.cts +219 -0
  52. package/dist/types.d.ts +25 -24
  53. package/dist/types.js +2 -5
  54. package/dist/types.js.map +1 -1
  55. package/package.json +24 -13
  56. package/src/browser.ts +13 -13
  57. package/src/react.ts +7 -6
  58. package/dist/auth.d.ts.map +0 -1
  59. package/dist/betterauth.d.ts.map +0 -1
  60. package/dist/billing.d.ts.map +0 -1
  61. package/dist/browser.d.ts.map +0 -1
  62. package/dist/client.d.ts.map +0 -1
  63. package/dist/client.js +0 -292
  64. package/dist/client.js.map +0 -1
  65. package/dist/index.d.ts.map +0 -1
  66. package/dist/nextauth.d.ts.map +0 -1
  67. package/dist/passport.d.ts.map +0 -1
  68. package/dist/pkce.d.ts +0 -13
  69. package/dist/pkce.d.ts.map +0 -1
  70. package/dist/pkce.js +0 -36
  71. package/dist/pkce.js.map +0 -1
  72. package/dist/react.d.ts.map +0 -1
  73. package/dist/types.d.ts.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1087 @@
1
+ 'use strict';
2
+
3
+ var jose = require('jose');
4
+
5
+ // src/client.ts
6
+ var DEFAULT_TIMEOUT_MS = 1e4;
7
+ var IamClient = class {
8
+ baseUrl;
9
+ clientId;
10
+ clientSecret;
11
+ orgName;
12
+ appName;
13
+ discoveryCache = null;
14
+ constructor(config) {
15
+ this.baseUrl = config.serverUrl.replace(/\/+$/, "");
16
+ this.clientId = config.clientId;
17
+ this.clientSecret = config.clientSecret;
18
+ this.orgName = config.orgName;
19
+ this.appName = config.appName;
20
+ }
21
+ // -----------------------------------------------------------------------
22
+ // Internal HTTP helpers
23
+ // -----------------------------------------------------------------------
24
+ async request(path, opts) {
25
+ const url = new URL(path, this.baseUrl);
26
+ if (opts?.params) {
27
+ for (const [k, v] of Object.entries(opts.params)) {
28
+ url.searchParams.set(k, v);
29
+ }
30
+ }
31
+ const controller = new AbortController();
32
+ const timer = setTimeout(
33
+ () => controller.abort(),
34
+ opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS
35
+ );
36
+ const headers = {
37
+ Accept: "application/json"
38
+ };
39
+ if (opts?.token) {
40
+ headers.Authorization = `Bearer ${opts.token}`;
41
+ }
42
+ if (opts?.body) {
43
+ headers["Content-Type"] = "application/json";
44
+ }
45
+ if (this.clientSecret && !opts?.token) {
46
+ const credentials = `${this.clientId}:${this.clientSecret}`;
47
+ const basic = typeof Buffer !== "undefined" ? Buffer.from(credentials).toString("base64") : btoa(credentials);
48
+ headers.Authorization = `Basic ${basic}`;
49
+ }
50
+ try {
51
+ const res = await fetch(url.toString(), {
52
+ method: opts?.method ?? "GET",
53
+ headers,
54
+ body: opts?.body ? JSON.stringify(opts.body) : void 0,
55
+ signal: controller.signal
56
+ });
57
+ if (!res.ok) {
58
+ const text = await res.text().catch(() => "");
59
+ throw new IamApiError(res.status, `${res.statusText}: ${text}`.trim());
60
+ }
61
+ return await res.json();
62
+ } finally {
63
+ clearTimeout(timer);
64
+ }
65
+ }
66
+ // -----------------------------------------------------------------------
67
+ // OIDC Discovery
68
+ // -----------------------------------------------------------------------
69
+ async getDiscovery() {
70
+ const CACHE_TTL_MS = 5 * 60 * 1e3;
71
+ if (this.discoveryCache && Date.now() - this.discoveryCache.fetchedAt < CACHE_TTL_MS) {
72
+ return this.discoveryCache.data;
73
+ }
74
+ const data = await this.request(
75
+ "/.well-known/openid-configuration"
76
+ );
77
+ this.discoveryCache = { data, fetchedAt: Date.now() };
78
+ return data;
79
+ }
80
+ /** Get JWKS URI from OIDC discovery (cached). */
81
+ async getJwksUri() {
82
+ const discovery = await this.getDiscovery();
83
+ return discovery.jwks_uri;
84
+ }
85
+ // -----------------------------------------------------------------------
86
+ // OAuth2 / Token
87
+ // -----------------------------------------------------------------------
88
+ /** Build the authorization URL for user login redirect. */
89
+ async getAuthorizationUrl(params) {
90
+ const discovery = await this.getDiscovery();
91
+ const url = new URL(discovery.authorization_endpoint);
92
+ url.searchParams.set("client_id", this.clientId);
93
+ url.searchParams.set("response_type", "code");
94
+ url.searchParams.set("redirect_uri", params.redirectUri);
95
+ url.searchParams.set("state", params.state);
96
+ url.searchParams.set("scope", params.scope ?? "openid profile email");
97
+ if (params.codeChallenge) {
98
+ url.searchParams.set("code_challenge", params.codeChallenge);
99
+ url.searchParams.set("code_challenge_method", params.codeChallengeMethod ?? "S256");
100
+ }
101
+ return url.toString();
102
+ }
103
+ /** Exchange authorization code for tokens. */
104
+ async exchangeCode(params) {
105
+ const discovery = await this.getDiscovery();
106
+ const body = new URLSearchParams({
107
+ grant_type: "authorization_code",
108
+ client_id: this.clientId,
109
+ code: params.code,
110
+ redirect_uri: params.redirectUri
111
+ });
112
+ if (this.clientSecret) {
113
+ body.set("client_secret", this.clientSecret);
114
+ }
115
+ if (params.codeVerifier) {
116
+ body.set("code_verifier", params.codeVerifier);
117
+ }
118
+ const controller = new AbortController();
119
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
120
+ try {
121
+ const res = await fetch(discovery.token_endpoint, {
122
+ method: "POST",
123
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
124
+ body: body.toString(),
125
+ signal: controller.signal
126
+ });
127
+ if (!res.ok) {
128
+ const text = await res.text().catch(() => "");
129
+ throw new IamApiError(res.status, `Token exchange failed: ${text}`);
130
+ }
131
+ return await res.json();
132
+ } finally {
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+ /**
137
+ * Resource Owner Password Credentials grant.
138
+ * Used for service-to-service auth, CLI login, and e2e tests.
139
+ */
140
+ async passwordGrant(params) {
141
+ const discovery = await this.getDiscovery();
142
+ const body = new URLSearchParams({
143
+ grant_type: "password",
144
+ client_id: this.clientId,
145
+ username: params.username,
146
+ password: params.password,
147
+ scope: params.scope ?? "openid profile email phone"
148
+ });
149
+ if (this.clientSecret) {
150
+ body.set("client_secret", this.clientSecret);
151
+ }
152
+ const controller = new AbortController();
153
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
154
+ try {
155
+ const res = await fetch(discovery.token_endpoint, {
156
+ method: "POST",
157
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
158
+ body: body.toString(),
159
+ signal: controller.signal
160
+ });
161
+ if (!res.ok) {
162
+ const text = await res.text().catch(() => "");
163
+ throw new IamApiError(res.status, `Password grant failed: ${text}`);
164
+ }
165
+ return await res.json();
166
+ } finally {
167
+ clearTimeout(timer);
168
+ }
169
+ }
170
+ /** Refresh an access token. */
171
+ async refreshToken(refreshToken) {
172
+ const discovery = await this.getDiscovery();
173
+ const body = new URLSearchParams({
174
+ grant_type: "refresh_token",
175
+ client_id: this.clientId,
176
+ refresh_token: refreshToken
177
+ });
178
+ if (this.clientSecret) {
179
+ body.set("client_secret", this.clientSecret);
180
+ }
181
+ const controller = new AbortController();
182
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
183
+ try {
184
+ const res = await fetch(discovery.token_endpoint, {
185
+ method: "POST",
186
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
187
+ body: body.toString(),
188
+ signal: controller.signal
189
+ });
190
+ if (!res.ok) {
191
+ const text = await res.text().catch(() => "");
192
+ throw new IamApiError(res.status, `Token refresh failed: ${text}`);
193
+ }
194
+ return await res.json();
195
+ } finally {
196
+ clearTimeout(timer);
197
+ }
198
+ }
199
+ // -----------------------------------------------------------------------
200
+ // User
201
+ // -----------------------------------------------------------------------
202
+ /** Get user info from access token (OIDC userinfo endpoint). */
203
+ async getUserInfo(accessToken) {
204
+ const discovery = await this.getDiscovery();
205
+ const controller = new AbortController();
206
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
207
+ try {
208
+ const res = await fetch(discovery.userinfo_endpoint, {
209
+ headers: { Authorization: `Bearer ${accessToken}` },
210
+ signal: controller.signal
211
+ });
212
+ if (!res.ok) {
213
+ throw new IamApiError(res.status, "Failed to fetch userinfo");
214
+ }
215
+ return await res.json();
216
+ } finally {
217
+ clearTimeout(timer);
218
+ }
219
+ }
220
+ /** Get a user by ID ("org/username" format). */
221
+ async getUser(userId, token) {
222
+ const resp = await this.request("/api/get-user", {
223
+ params: { id: userId },
224
+ token
225
+ });
226
+ return resp.data ?? null;
227
+ }
228
+ // -----------------------------------------------------------------------
229
+ // Organization
230
+ // -----------------------------------------------------------------------
231
+ /** List organizations (for the configured owner). */
232
+ async getOrganizations(token) {
233
+ const owner = this.orgName ?? "admin";
234
+ const resp = await this.request(
235
+ "/api/get-organizations",
236
+ { params: { owner }, token }
237
+ );
238
+ return resp.data ?? [];
239
+ }
240
+ /** Get a specific organization. */
241
+ async getOrganization(id, token) {
242
+ const resp = await this.request(
243
+ "/api/get-organization",
244
+ { params: { id }, token }
245
+ );
246
+ return resp.data ?? null;
247
+ }
248
+ /** Get organizations a user belongs to. */
249
+ async getUserOrganizations(userId, token) {
250
+ const user = await this.getUser(userId, token);
251
+ if (!user) return [];
252
+ const org = await this.getOrganization(
253
+ `admin/${user.owner}`,
254
+ token
255
+ );
256
+ return org ? [org] : [];
257
+ }
258
+ // -----------------------------------------------------------------------
259
+ // Project
260
+ // -----------------------------------------------------------------------
261
+ /** List projects (for the configured owner). */
262
+ async getProjects(token) {
263
+ const owner = this.orgName ?? "admin";
264
+ const resp = await this.request(
265
+ "/api/get-projects",
266
+ { params: { owner }, token }
267
+ );
268
+ return resp.data ?? [];
269
+ }
270
+ /** Get a specific project by ID ("owner/name" format). */
271
+ async getProject(id, token) {
272
+ const resp = await this.request(
273
+ "/api/get-project",
274
+ { params: { id }, token }
275
+ );
276
+ return resp.data ?? null;
277
+ }
278
+ /** Get all projects for an organization. */
279
+ async getOrganizationProjects(organization, token) {
280
+ const resp = await this.request(
281
+ "/api/get-organization-projects",
282
+ { params: { organization }, token }
283
+ );
284
+ return resp.data ?? [];
285
+ }
286
+ // -----------------------------------------------------------------------
287
+ // Raw request (for extending)
288
+ // -----------------------------------------------------------------------
289
+ /** Make an arbitrary authenticated request to the IAM API. */
290
+ async apiRequest(path, opts) {
291
+ return this.request(path, opts);
292
+ }
293
+ };
294
+ var IamApiError = class extends Error {
295
+ status;
296
+ constructor(status, message) {
297
+ super(message);
298
+ this.name = "IamApiError";
299
+ this.status = status;
300
+ }
301
+ };
302
+ var jwksSets = /* @__PURE__ */ new Map();
303
+ function getJwksKeySet(jwksUri) {
304
+ let keySet = jwksSets.get(jwksUri);
305
+ if (!keySet) {
306
+ keySet = jose.createRemoteJWKSet(new URL(jwksUri));
307
+ jwksSets.set(jwksUri, keySet);
308
+ }
309
+ return keySet;
310
+ }
311
+ function clearJwksCache() {
312
+ jwksSets.clear();
313
+ }
314
+ var discoveryCache = /* @__PURE__ */ new Map();
315
+ var DISCOVERY_TTL_MS = 5 * 60 * 1e3;
316
+ async function resolveJwksUri(serverUrl) {
317
+ const baseUrl = serverUrl.replace(/\/+$/, "");
318
+ const cached = discoveryCache.get(baseUrl);
319
+ if (cached && Date.now() - cached.fetchedAt < DISCOVERY_TTL_MS) {
320
+ return { jwksUri: cached.jwksUri, issuer: cached.issuer };
321
+ }
322
+ const controller = new AbortController();
323
+ const timer = setTimeout(() => controller.abort(), 8e3);
324
+ try {
325
+ const res = await fetch(`${baseUrl}/.well-known/openid-configuration`, {
326
+ signal: controller.signal,
327
+ headers: { Accept: "application/json" }
328
+ });
329
+ if (!res.ok) {
330
+ throw new Error(`OIDC discovery failed: ${res.status}`);
331
+ }
332
+ const body = await res.json();
333
+ const jwksUri = body.jwks_uri;
334
+ const issuer = body.issuer ?? baseUrl;
335
+ if (!jwksUri) {
336
+ throw new Error("OIDC discovery response missing jwks_uri");
337
+ }
338
+ discoveryCache.set(baseUrl, { jwksUri, issuer, fetchedAt: Date.now() });
339
+ return { jwksUri, issuer };
340
+ } finally {
341
+ clearTimeout(timer);
342
+ }
343
+ }
344
+ async function validateToken(token, config) {
345
+ if (!token || typeof token !== "string") {
346
+ return { ok: false, reason: "iam_token_missing" };
347
+ }
348
+ let jwksUri;
349
+ let issuer;
350
+ try {
351
+ const discovery = await resolveJwksUri(config.serverUrl);
352
+ jwksUri = discovery.jwksUri;
353
+ issuer = discovery.issuer;
354
+ } catch {
355
+ return { ok: false, reason: "iam_discovery_failed" };
356
+ }
357
+ const keySet = getJwksKeySet(jwksUri);
358
+ let payload;
359
+ try {
360
+ const result = await jose.jwtVerify(token, keySet, {
361
+ issuer,
362
+ audience: config.clientId,
363
+ clockTolerance: 30
364
+ // 30s clock skew
365
+ });
366
+ payload = result.payload;
367
+ } catch (err) {
368
+ const message = err instanceof Error ? err.message : String(err);
369
+ if (message.includes("expired")) {
370
+ return { ok: false, reason: "iam_token_expired" };
371
+ }
372
+ if (message.includes("audience")) {
373
+ try {
374
+ const result = await jose.jwtVerify(token, keySet, {
375
+ issuer,
376
+ clockTolerance: 30
377
+ });
378
+ payload = result.payload;
379
+ } catch {
380
+ return { ok: false, reason: "iam_signature_invalid" };
381
+ }
382
+ } else {
383
+ return { ok: false, reason: "iam_signature_invalid" };
384
+ }
385
+ }
386
+ const claims = payload;
387
+ const sub = claims.sub || (typeof claims.owner === "string" && typeof claims.name === "string" ? `${claims.owner}/${claims.name}` : void 0);
388
+ if (!sub) {
389
+ return { ok: false, reason: "iam_subject_missing" };
390
+ }
391
+ const parts = sub.split("/");
392
+ const owner = parts.length > 1 ? parts[0] : config.orgName ?? "unknown";
393
+ return {
394
+ ok: true,
395
+ userId: sub,
396
+ email: typeof claims.email === "string" ? claims.email : void 0,
397
+ name: typeof claims.name === "string" ? claims.name : typeof claims.preferred_username === "string" ? claims.preferred_username : void 0,
398
+ avatar: typeof claims.picture === "string" ? claims.picture : void 0,
399
+ owner,
400
+ claims
401
+ };
402
+ }
403
+
404
+ // src/pkce.ts
405
+ function generateRandomString(length) {
406
+ const array = new Uint8Array(length);
407
+ crypto.getRandomValues(array);
408
+ return Array.from(array, (b) => b.toString(36).padStart(2, "0")).join("").slice(0, length);
409
+ }
410
+ async function sha256(plain) {
411
+ const encoder = new TextEncoder();
412
+ return crypto.subtle.digest("SHA-256", encoder.encode(plain));
413
+ }
414
+ function base64UrlEncode(buffer) {
415
+ const bytes = new Uint8Array(buffer);
416
+ let binary = "";
417
+ for (const byte of bytes) {
418
+ binary += String.fromCharCode(byte);
419
+ }
420
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
421
+ }
422
+ async function generatePKCEChallenge() {
423
+ const codeVerifier = generateRandomString(64);
424
+ const hash = await sha256(codeVerifier);
425
+ const codeChallenge = base64UrlEncode(hash);
426
+ return { codeVerifier, codeChallenge };
427
+ }
428
+ function generateState() {
429
+ return generateRandomString(32);
430
+ }
431
+
432
+ // src/browser.ts
433
+ var STORAGE_PREFIX = "hanzo_iam_";
434
+ var KEY_STATE = `${STORAGE_PREFIX}state`;
435
+ var KEY_CODE_VERIFIER = `${STORAGE_PREFIX}code_verifier`;
436
+ var KEY_ACCESS_TOKEN = `${STORAGE_PREFIX}access_token`;
437
+ var KEY_REFRESH_TOKEN = `${STORAGE_PREFIX}refresh_token`;
438
+ var KEY_ID_TOKEN = `${STORAGE_PREFIX}id_token`;
439
+ var KEY_EXPIRES_AT = `${STORAGE_PREFIX}expires_at`;
440
+ var IAM = class {
441
+ config;
442
+ storage;
443
+ discoveryCache = null;
444
+ constructor(config) {
445
+ this.config = config;
446
+ this.storage = config.storage ?? sessionStorage;
447
+ }
448
+ // -----------------------------------------------------------------------
449
+ // OIDC Discovery
450
+ // -----------------------------------------------------------------------
451
+ async getDiscovery() {
452
+ if (this.discoveryCache) return this.discoveryCache;
453
+ const baseUrl = this.config.serverUrl.replace(/\/+$/, "");
454
+ try {
455
+ const res = await fetch(`${baseUrl}/.well-known/openid-configuration`, {
456
+ headers: { Accept: "application/json" }
457
+ });
458
+ if (res.ok) {
459
+ this.discoveryCache = await res.json();
460
+ return this.discoveryCache;
461
+ }
462
+ } catch {
463
+ }
464
+ this.discoveryCache = {
465
+ issuer: baseUrl,
466
+ authorization_endpoint: `${baseUrl}/oauth/authorize`,
467
+ token_endpoint: `${baseUrl}/oauth/token`,
468
+ userinfo_endpoint: `${baseUrl}/oauth/userinfo`,
469
+ jwks_uri: `${baseUrl}/.well-known/jwks`,
470
+ response_types_supported: ["code", "token", "id_token"],
471
+ grant_types_supported: ["authorization_code", "implicit", "refresh_token"],
472
+ scopes_supported: ["openid", "email", "profile"]
473
+ };
474
+ return this.discoveryCache;
475
+ }
476
+ // -----------------------------------------------------------------------
477
+ // Login redirect (PKCE)
478
+ // -----------------------------------------------------------------------
479
+ /**
480
+ * Start the OAuth2 PKCE login flow by redirecting to the IAM authorize endpoint.
481
+ *
482
+ * Generates PKCE challenge and state, stores them in session storage,
483
+ * then redirects the browser.
484
+ */
485
+ async signinRedirect(params) {
486
+ const discovery = await this.getDiscovery();
487
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
488
+ const state = generateState();
489
+ this.storage.setItem(KEY_STATE, state);
490
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
491
+ const url = new URL(discovery.authorization_endpoint);
492
+ url.searchParams.set("client_id", this.config.clientId);
493
+ url.searchParams.set("response_type", "code");
494
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
495
+ url.searchParams.set("scope", this.config.scope ?? "openid profile email");
496
+ url.searchParams.set("state", state);
497
+ url.searchParams.set("code_challenge", codeChallenge);
498
+ url.searchParams.set("code_challenge_method", "S256");
499
+ if (params?.additionalParams) {
500
+ for (const [k, v] of Object.entries(params.additionalParams)) {
501
+ url.searchParams.set(k, v);
502
+ }
503
+ }
504
+ window.location.href = url.toString();
505
+ }
506
+ // -----------------------------------------------------------------------
507
+ // Callback handling
508
+ // -----------------------------------------------------------------------
509
+ /**
510
+ * Handle the OAuth2 callback after redirect. Exchanges the authorization code
511
+ * for tokens using PKCE.
512
+ *
513
+ * Call this on your callback page (e.g. /auth/callback).
514
+ * Returns the token response, or throws if the state doesn't match.
515
+ */
516
+ async handleCallback(callbackUrl) {
517
+ const url = new URL(callbackUrl ?? window.location.href);
518
+ const error = url.searchParams.get("error");
519
+ if (error) {
520
+ const desc = url.searchParams.get("error_description") ?? error;
521
+ throw new Error(`OAuth error: ${desc}`);
522
+ }
523
+ const state = url.searchParams.get("state");
524
+ const savedState = this.storage.getItem(KEY_STATE);
525
+ if (savedState && state !== savedState) {
526
+ throw new Error("OAuth state mismatch \u2014 possible CSRF attack");
527
+ }
528
+ const accessToken = url.searchParams.get("access_token");
529
+ if (accessToken) {
530
+ this.storage.removeItem(KEY_STATE);
531
+ this.storage.removeItem(KEY_CODE_VERIFIER);
532
+ const tokens2 = {
533
+ access_token: accessToken,
534
+ token_type: "Bearer",
535
+ refresh_token: url.searchParams.get("refresh_token") ?? void 0,
536
+ expires_in: 7200
537
+ };
538
+ this.storeTokens(tokens2);
539
+ return toIAMToken(tokens2);
540
+ }
541
+ const code = url.searchParams.get("code");
542
+ if (!code) {
543
+ throw new Error("Missing authorization code in callback URL");
544
+ }
545
+ const codeVerifier = this.storage.getItem(KEY_CODE_VERIFIER);
546
+ if (!codeVerifier) {
547
+ throw new Error("Missing PKCE code verifier \u2014 was signinRedirect() called?");
548
+ }
549
+ this.storage.removeItem(KEY_STATE);
550
+ this.storage.removeItem(KEY_CODE_VERIFIER);
551
+ const discovery = await this.getDiscovery();
552
+ const body = new URLSearchParams({
553
+ grant_type: "authorization_code",
554
+ client_id: this.config.clientId,
555
+ code,
556
+ redirect_uri: this.config.redirectUri,
557
+ code_verifier: codeVerifier
558
+ });
559
+ const tokenUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/token` : discovery.token_endpoint;
560
+ const res = await fetch(tokenUrl, {
561
+ method: "POST",
562
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
563
+ body: body.toString()
564
+ });
565
+ if (!res.ok) {
566
+ const text = await res.text().catch(() => "");
567
+ throw new Error(`Token exchange failed (${res.status}): ${text}`);
568
+ }
569
+ const tokens = await res.json();
570
+ this.storeTokens(tokens);
571
+ return toIAMToken(tokens);
572
+ }
573
+ // -----------------------------------------------------------------------
574
+ // Token refresh
575
+ // -----------------------------------------------------------------------
576
+ /** Refresh the access token using the stored refresh token. */
577
+ async refreshAccessToken() {
578
+ const refreshToken = this.storage.getItem(KEY_REFRESH_TOKEN);
579
+ if (!refreshToken) {
580
+ throw new Error("No refresh token available");
581
+ }
582
+ const discovery = await this.getDiscovery();
583
+ const body = new URLSearchParams({
584
+ grant_type: "refresh_token",
585
+ client_id: this.config.clientId,
586
+ refresh_token: refreshToken
587
+ });
588
+ const tokenUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/token` : discovery.token_endpoint;
589
+ const res = await fetch(tokenUrl, {
590
+ method: "POST",
591
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
592
+ body: body.toString()
593
+ });
594
+ if (!res.ok) {
595
+ const text = await res.text().catch(() => "");
596
+ throw new Error(`Token refresh failed (${res.status}): ${text}`);
597
+ }
598
+ const tokens = await res.json();
599
+ this.storeTokens(tokens);
600
+ return toIAMToken(tokens);
601
+ }
602
+ // -----------------------------------------------------------------------
603
+ // Popup signin
604
+ // -----------------------------------------------------------------------
605
+ /**
606
+ * Open the IAM login page in a popup window. Resolves when the popup
607
+ * completes the OAuth flow and returns tokens.
608
+ */
609
+ async signinPopup(params) {
610
+ const discovery = await this.getDiscovery();
611
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
612
+ const state = generateState();
613
+ this.storage.setItem(KEY_STATE, state);
614
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
615
+ const url = new URL(discovery.authorization_endpoint);
616
+ url.searchParams.set("client_id", this.config.clientId);
617
+ url.searchParams.set("response_type", "code");
618
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
619
+ url.searchParams.set("scope", this.config.scope ?? "openid profile email");
620
+ url.searchParams.set("state", state);
621
+ url.searchParams.set("code_challenge", codeChallenge);
622
+ url.searchParams.set("code_challenge_method", "S256");
623
+ if (params?.additionalParams) {
624
+ for (const [k, v] of Object.entries(params.additionalParams)) {
625
+ url.searchParams.set(k, v);
626
+ }
627
+ }
628
+ const width = params?.width ?? 600;
629
+ const height = params?.height ?? 700;
630
+ const left = window.screenX + (window.outerWidth - width) / 2;
631
+ const top = window.screenY + (window.outerHeight - height) / 2;
632
+ return new Promise((resolve, reject) => {
633
+ const popup = window.open(
634
+ url.toString(),
635
+ "hanzo_iam_login",
636
+ `width=${width},height=${height},left=${left},top=${top},menubar=no,toolbar=no`
637
+ );
638
+ if (!popup) {
639
+ reject(new Error("Failed to open login popup \u2014 blocked by browser?"));
640
+ return;
641
+ }
642
+ const interval = setInterval(() => {
643
+ try {
644
+ if (popup.closed) {
645
+ clearInterval(interval);
646
+ reject(new Error("Login popup was closed before completing"));
647
+ return;
648
+ }
649
+ const popupUrl = popup.location.href;
650
+ if (popupUrl.startsWith(this.config.redirectUri)) {
651
+ clearInterval(interval);
652
+ popup.close();
653
+ this.handleCallback(popupUrl).then(resolve, reject);
654
+ }
655
+ } catch {
656
+ }
657
+ }, 200);
658
+ });
659
+ }
660
+ // -----------------------------------------------------------------------
661
+ // Silent signin (iframe)
662
+ // -----------------------------------------------------------------------
663
+ /**
664
+ * Attempt silent authentication via a hidden iframe.
665
+ * Useful for checking if the user has an active IAM session.
666
+ * Returns null if silent auth fails (user needs to log in interactively).
667
+ */
668
+ async signinSilent(timeoutMs = 5e3) {
669
+ const discovery = await this.getDiscovery();
670
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
671
+ const state = generateState();
672
+ this.storage.setItem(KEY_STATE, state);
673
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
674
+ const url = new URL(discovery.authorization_endpoint);
675
+ url.searchParams.set("client_id", this.config.clientId);
676
+ url.searchParams.set("response_type", "code");
677
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
678
+ url.searchParams.set("scope", this.config.scope ?? "openid profile email");
679
+ url.searchParams.set("state", state);
680
+ url.searchParams.set("code_challenge", codeChallenge);
681
+ url.searchParams.set("code_challenge_method", "S256");
682
+ url.searchParams.set("prompt", "none");
683
+ return new Promise((resolve) => {
684
+ const iframe = document.createElement("iframe");
685
+ iframe.style.display = "none";
686
+ const timeout = setTimeout(() => {
687
+ cleanup();
688
+ resolve(null);
689
+ }, timeoutMs);
690
+ const cleanup = () => {
691
+ clearTimeout(timeout);
692
+ iframe.remove();
693
+ this.storage.removeItem(KEY_STATE);
694
+ this.storage.removeItem(KEY_CODE_VERIFIER);
695
+ };
696
+ iframe.addEventListener("load", () => {
697
+ try {
698
+ const iframeUrl = iframe.contentWindow?.location.href;
699
+ if (iframeUrl && iframeUrl.startsWith(this.config.redirectUri)) {
700
+ cleanup();
701
+ this.handleCallback(iframeUrl).then(
702
+ (tokens) => resolve(tokens),
703
+ () => resolve(null)
704
+ );
705
+ }
706
+ } catch {
707
+ cleanup();
708
+ resolve(null);
709
+ }
710
+ });
711
+ iframe.src = url.toString();
712
+ document.body.appendChild(iframe);
713
+ });
714
+ }
715
+ // -----------------------------------------------------------------------
716
+ // Token management
717
+ // -----------------------------------------------------------------------
718
+ storeTokens(tokens) {
719
+ this.storage.setItem(KEY_ACCESS_TOKEN, tokens.access_token);
720
+ if (tokens.refresh_token) {
721
+ this.storage.setItem(KEY_REFRESH_TOKEN, tokens.refresh_token);
722
+ }
723
+ if (tokens.id_token) {
724
+ this.storage.setItem(KEY_ID_TOKEN, tokens.id_token);
725
+ }
726
+ if (tokens.expires_in) {
727
+ const expiresAt = Date.now() + tokens.expires_in * 1e3;
728
+ this.storage.setItem(KEY_EXPIRES_AT, String(expiresAt));
729
+ }
730
+ }
731
+ /** Get the stored access token (may be expired). */
732
+ getAccessToken() {
733
+ return this.storage.getItem(KEY_ACCESS_TOKEN);
734
+ }
735
+ /** Get the stored refresh token. */
736
+ getRefreshToken() {
737
+ return this.storage.getItem(KEY_REFRESH_TOKEN);
738
+ }
739
+ /** Get the stored ID token. */
740
+ getIdToken() {
741
+ return this.storage.getItem(KEY_ID_TOKEN);
742
+ }
743
+ /** Check if the stored access token is expired. */
744
+ isTokenExpired() {
745
+ const expiresAt = this.storage.getItem(KEY_EXPIRES_AT);
746
+ if (!expiresAt) return true;
747
+ return Date.now() >= Number(expiresAt);
748
+ }
749
+ /**
750
+ * Get a valid access token — refreshes automatically if expired.
751
+ * Returns null if no token and no refresh token available.
752
+ */
753
+ async getValidAccessToken() {
754
+ const token = this.getAccessToken();
755
+ if (token && !this.isTokenExpired()) {
756
+ return token;
757
+ }
758
+ if (this.getRefreshToken()) {
759
+ try {
760
+ const tokens = await this.refreshAccessToken();
761
+ return tokens.accessToken;
762
+ } catch {
763
+ return null;
764
+ }
765
+ }
766
+ return null;
767
+ }
768
+ /** Clear all stored tokens (logout). */
769
+ clearTokens() {
770
+ this.storage.removeItem(KEY_ACCESS_TOKEN);
771
+ this.storage.removeItem(KEY_REFRESH_TOKEN);
772
+ this.storage.removeItem(KEY_ID_TOKEN);
773
+ this.storage.removeItem(KEY_EXPIRES_AT);
774
+ this.storage.removeItem(KEY_STATE);
775
+ this.storage.removeItem(KEY_CODE_VERIFIER);
776
+ }
777
+ // -----------------------------------------------------------------------
778
+ // User info
779
+ // -----------------------------------------------------------------------
780
+ /** Fetch user info from the OIDC userinfo endpoint using the stored access token. */
781
+ async getUserInfo() {
782
+ const token = await this.getValidAccessToken();
783
+ if (!token) {
784
+ throw new Error("No valid access token \u2014 user must log in");
785
+ }
786
+ const discovery = await this.getDiscovery();
787
+ const userinfoUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/userinfo` : discovery.userinfo_endpoint;
788
+ const res = await fetch(userinfoUrl, {
789
+ headers: { Authorization: `Bearer ${token}` }
790
+ });
791
+ if (!res.ok) {
792
+ throw new Error(`Userinfo fetch failed (${res.status})`);
793
+ }
794
+ return await res.json();
795
+ }
796
+ // -----------------------------------------------------------------------
797
+ // URL helpers
798
+ // -----------------------------------------------------------------------
799
+ /** Build the signup URL for the IAM server. */
800
+ getSignupUrl(params) {
801
+ const base = this.config.serverUrl.replace(/\/+$/, "");
802
+ const app = this.config.appName ?? "app";
803
+ this.config.orgName ?? "built-in";
804
+ let url = `${base}/signup/${app}`;
805
+ if (params?.enablePassword) {
806
+ url += "?enablePassword=true";
807
+ }
808
+ return url;
809
+ }
810
+ /** Build the user profile URL on the IAM server. */
811
+ getUserProfileUrl(username) {
812
+ const base = this.config.serverUrl.replace(/\/+$/, "");
813
+ const org = this.config.orgName ?? "built-in";
814
+ return `${base}/users/${org}/${username}`;
815
+ }
816
+ // -----------------------------------------------------------------------
817
+ // Casdoor REST surface (signup, OTP, REST login, phone lookup)
818
+ //
819
+ // The OIDC layer covers redirect/PKCE, token exchange, refresh, userinfo.
820
+ // These methods cover the Casdoor-native endpoints that don't have an OIDC
821
+ // analogue: phone/email OTP, custom signup with verification codes, and
822
+ // direct REST login that returns an authorization code in one round-trip
823
+ // (used as the bridge between OTP collection and `exchangeCode`).
824
+ //
825
+ // All paths are gateway-canonical (`/login`, `/signup`,
826
+ // `/send-verification-code`, `/get-phone-user`) — point `serverUrl` at the
827
+ // gateway prefix (e.g. `https://api.dev.satschel.com/v1/iam`) and the
828
+ // gateway proxies to Casdoor's `/api/*` internally.
829
+ // -----------------------------------------------------------------------
830
+ /**
831
+ * Send a verification code to a phone or email destination.
832
+ *
833
+ * @param contact `{ phone, countryCode }` for SMS, `{ email }` for email.
834
+ * @param method Casdoor method: `login`, `signup`, `forget`, `mfaSetup`, etc.
835
+ */
836
+ async sendVerificationCode(contact, method = "login") {
837
+ if (method === "reset") method = "forget";
838
+ const isPhone = "phone" in contact;
839
+ const dest = isPhone ? contact.phone : contact.email;
840
+ const params = {
841
+ applicationId: `admin/${this.config.appName ?? "app"}`,
842
+ dest,
843
+ type: isPhone ? "phone" : "email",
844
+ method,
845
+ captchaType: "none",
846
+ captchaToken: ""
847
+ };
848
+ if (isPhone) params.countryCode = contact.countryCode;
849
+ const url = `${this.config.serverUrl.replace(/\/+$/, "")}/send-verification-code`;
850
+ const res = await fetch(url, {
851
+ method: "POST",
852
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
853
+ body: new URLSearchParams(params).toString()
854
+ });
855
+ const data = await res.json().catch(() => ({}));
856
+ if (data.status === "ok") return { ok: true };
857
+ const msg = data.msg || `send-verification-code failed (${res.status})`;
858
+ if (msg.includes("SMS provider") || msg.includes("provider")) return { ok: true };
859
+ return { ok: false, error: msg };
860
+ }
861
+ /**
862
+ * Look up whether a phone number is registered. Returns `{ exists: false }`
863
+ * on 404 or unknown numbers; `{ exists: true }` when Casdoor confirms a user.
864
+ */
865
+ async lookupPhoneUser(phone, countryCode) {
866
+ const url = `${this.config.serverUrl.replace(/\/+$/, "")}/get-phone-user`;
867
+ const res = await fetch(url, {
868
+ method: "POST",
869
+ headers: { "Content-Type": "application/json" },
870
+ body: JSON.stringify({
871
+ application: this.config.appName ?? "app",
872
+ phone,
873
+ countryCode
874
+ })
875
+ });
876
+ if (res.status === 404) return { exists: false };
877
+ if (!res.ok) return { exists: false, error: `lookupPhoneUser failed (${res.status})` };
878
+ return { exists: true };
879
+ }
880
+ /**
881
+ * Casdoor REST signup. Returns the new user's id on success.
882
+ *
883
+ * Phone signup flow: send phoneCode via `sendVerificationCode`, then call
884
+ * this with the OTP in `phoneCode`. Casdoor verifies the code internally.
885
+ * Email signup flow: same with `email` + `emailCode`.
886
+ */
887
+ async signup(params) {
888
+ const username = params.username ?? params.name;
889
+ const password = params.password ?? `Liq${Date.now()}!`;
890
+ const body = {
891
+ application: this.config.appName ?? "app",
892
+ organization: this.config.orgName ?? "built-in",
893
+ name: params.name,
894
+ username,
895
+ password,
896
+ confirm: password,
897
+ agreement: true
898
+ };
899
+ if (params.method === "email") {
900
+ body.email = params.email;
901
+ if (params.emailCode) body.emailCode = params.emailCode;
902
+ } else {
903
+ body.phone = params.phone;
904
+ body.countryCode = params.countryCode;
905
+ if (params.phoneCode) body.phoneCode = params.phoneCode;
906
+ if (params.email) body.email = params.email;
907
+ if (params.emailCode) body.emailCode = params.emailCode;
908
+ }
909
+ const url = `${this.config.serverUrl.replace(/\/+$/, "")}/signup`;
910
+ const res = await fetch(url, {
911
+ method: "POST",
912
+ headers: { "Content-Type": "application/json" },
913
+ body: JSON.stringify(body)
914
+ });
915
+ const data = await res.json().catch(() => ({}));
916
+ if (data.status === "ok") return { ok: true, id: data.data2 || data.data };
917
+ return { ok: false, error: data.msg || `signup failed (${res.status})` };
918
+ }
919
+ /**
920
+ * REST login that returns an authorization code (Casdoor `/login`).
921
+ *
922
+ * Use this when you want the caller to drive the PKCE flow without a
923
+ * full redirect — collect credentials in your own UI, get a code back,
924
+ * then call `exchangeCodeForToken` to land tokens.
925
+ */
926
+ async loginWithCredentials(params) {
927
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
928
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
929
+ const url = new URL(`${this.config.serverUrl.replace(/\/+$/, "")}/login`);
930
+ url.searchParams.set("code_challenge", codeChallenge);
931
+ url.searchParams.set("code_challenge_method", "S256");
932
+ const res = await fetch(url.toString(), {
933
+ method: "POST",
934
+ headers: { "Content-Type": "application/json" },
935
+ body: JSON.stringify({
936
+ application: this.config.appName ?? "app",
937
+ organization: this.config.orgName ?? "built-in",
938
+ username: params.username,
939
+ password: params.password,
940
+ type: params.type ?? "code",
941
+ clientId: this.config.clientId,
942
+ redirectUri: params.redirectUri ?? this.config.redirectUri,
943
+ codeChallenge,
944
+ codeChallengeMethod: "S256",
945
+ autoSignin: true
946
+ })
947
+ });
948
+ const data = await res.json().catch(() => ({}));
949
+ if (data.status === "ok" && data.data) return { ok: true, code: data.data };
950
+ return { ok: false, error: data.msg || `login failed (${res.status})` };
951
+ }
952
+ /**
953
+ * Exchange an authorization code for tokens using the stored PKCE verifier.
954
+ * Pairs with `loginWithCredentials` for a code → tokens round-trip.
955
+ */
956
+ async exchangeCodeForToken(code, redirectUri) {
957
+ const codeVerifier = this.storage.getItem(KEY_CODE_VERIFIER);
958
+ if (!codeVerifier) {
959
+ throw new Error("Missing PKCE verifier \u2014 call loginWithCredentials() first");
960
+ }
961
+ this.storage.removeItem(KEY_CODE_VERIFIER);
962
+ const discovery = await this.getDiscovery();
963
+ const tokenUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/token` : discovery.token_endpoint;
964
+ const body = new URLSearchParams({
965
+ grant_type: "authorization_code",
966
+ client_id: this.config.clientId,
967
+ code,
968
+ redirect_uri: redirectUri ?? this.config.redirectUri,
969
+ code_verifier: codeVerifier
970
+ });
971
+ const res = await fetch(tokenUrl, {
972
+ method: "POST",
973
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
974
+ body: body.toString()
975
+ });
976
+ if (!res.ok) {
977
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
978
+ throw new Error(err.error_description || err.error || "Token exchange failed");
979
+ }
980
+ const tokens = await res.json();
981
+ this.storeTokens(tokens);
982
+ return toIAMToken(tokens);
983
+ }
984
+ /**
985
+ * Phone OTP login: tries the numbered username variants Casdoor accepts
986
+ * (`{phone}`, `{countryCode}{phone}`), exchanges the resulting code for
987
+ * tokens. Returns the token response, or throws on failure.
988
+ */
989
+ async loginWithPhoneOTP(params) {
990
+ const usernames = [params.phone, `${params.countryCode}${params.phone}`];
991
+ let lastError = "";
992
+ for (const username of usernames) {
993
+ const result = await this.loginWithCredentials({
994
+ username,
995
+ password: params.code,
996
+ redirectUri: params.redirectUri
997
+ });
998
+ if (result.ok && result.code) {
999
+ return this.exchangeCodeForToken(result.code, params.redirectUri);
1000
+ }
1001
+ lastError = result.error ?? lastError;
1002
+ }
1003
+ throw new Error(lastError || "Phone OTP login failed");
1004
+ }
1005
+ /**
1006
+ * Logout via Casdoor REST `/logout` (clears server-side session) and
1007
+ * the local storage.
1008
+ */
1009
+ async logout() {
1010
+ const token = this.storage.getItem(KEY_ACCESS_TOKEN);
1011
+ try {
1012
+ await fetch(`${this.config.serverUrl.replace(/\/+$/, "")}/oauth/logout`, {
1013
+ method: "POST",
1014
+ headers: token ? { Authorization: `Bearer ${token}` } : {}
1015
+ });
1016
+ } catch {
1017
+ }
1018
+ this.clearTokens();
1019
+ }
1020
+ // -----------------------------------------------------------------------
1021
+ // High-level helpers — normalize to ergonomic types so apps don't need
1022
+ // their own adapters around the OIDC/Casdoor wire shapes.
1023
+ // -----------------------------------------------------------------------
1024
+ /**
1025
+ * Build a social-login authorize URL. Used to navigate the user to
1026
+ * Google/Apple/etc. — same as `signinRedirect` but returns the URL
1027
+ * instead of issuing the redirect, so apps can `<a href="...">`.
1028
+ */
1029
+ async getSocialLoginUrl(provider, scope = "openid profile email") {
1030
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
1031
+ const state = generateState();
1032
+ this.storage.setItem(KEY_STATE, state);
1033
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
1034
+ const discovery = await this.getDiscovery();
1035
+ const url = new URL(discovery.authorization_endpoint);
1036
+ url.searchParams.set("client_id", this.config.clientId);
1037
+ url.searchParams.set("response_type", "code");
1038
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
1039
+ url.searchParams.set("scope", scope);
1040
+ url.searchParams.set("state", state);
1041
+ url.searchParams.set("code_challenge", codeChallenge);
1042
+ url.searchParams.set("code_challenge_method", "S256");
1043
+ url.searchParams.set("provider", provider);
1044
+ return url.toString();
1045
+ }
1046
+ /**
1047
+ * Fetch the current user, shaped into the canonical `IAMUser` form
1048
+ * (camelCase, no `_` keys). Returns null when no token is present.
1049
+ */
1050
+ async getUser() {
1051
+ const token = await this.getValidAccessToken();
1052
+ if (!token) return null;
1053
+ const u = await this.getUserInfo();
1054
+ return {
1055
+ sub: u.sub ?? "",
1056
+ email: u.email,
1057
+ name: u.name,
1058
+ givenName: u.given_name,
1059
+ familyName: u.family_name,
1060
+ phoneNumber: u.phone_number,
1061
+ emailVerified: u.email_verified,
1062
+ picture: u.picture,
1063
+ owner: u.owner
1064
+ };
1065
+ }
1066
+ };
1067
+ function toIAMToken(t) {
1068
+ return {
1069
+ accessToken: t.access_token,
1070
+ refreshToken: t.refresh_token,
1071
+ idToken: t.id_token,
1072
+ expiresIn: t.expires_in,
1073
+ tokenType: t.token_type,
1074
+ scope: t.scope
1075
+ };
1076
+ }
1077
+
1078
+ exports.IAM = IAM;
1079
+ exports.IamApiError = IamApiError;
1080
+ exports.IamClient = IamClient;
1081
+ exports.clearJwksCache = clearJwksCache;
1082
+ exports.generatePKCEChallenge = generatePKCEChallenge;
1083
+ exports.generateState = generateState;
1084
+ exports.toIAMToken = toIAMToken;
1085
+ exports.validateToken = validateToken;
1086
+ //# sourceMappingURL=index.cjs.map
1087
+ //# sourceMappingURL=index.cjs.map