@hanzo/iam 0.9.0 → 0.9.2

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