@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/react.cjs ADDED
@@ -0,0 +1,1434 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+
5
+ // src/react.ts
6
+
7
+ // src/pkce.ts
8
+ function generateRandomString(length) {
9
+ const array = new Uint8Array(length);
10
+ crypto.getRandomValues(array);
11
+ return Array.from(array, (b) => b.toString(36).padStart(2, "0")).join("").slice(0, length);
12
+ }
13
+ async function sha256(plain) {
14
+ const encoder = new TextEncoder();
15
+ return crypto.subtle.digest("SHA-256", encoder.encode(plain));
16
+ }
17
+ function base64UrlEncode(buffer) {
18
+ const bytes = new Uint8Array(buffer);
19
+ let binary = "";
20
+ for (const byte of bytes) {
21
+ binary += String.fromCharCode(byte);
22
+ }
23
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
24
+ }
25
+ async function generatePKCEChallenge() {
26
+ const codeVerifier = generateRandomString(64);
27
+ const hash = await sha256(codeVerifier);
28
+ const codeChallenge = base64UrlEncode(hash);
29
+ return { codeVerifier, codeChallenge };
30
+ }
31
+ function generateState() {
32
+ return generateRandomString(32);
33
+ }
34
+
35
+ // src/browser.ts
36
+ var STORAGE_PREFIX = "hanzo_iam_";
37
+ var KEY_STATE = `${STORAGE_PREFIX}state`;
38
+ var KEY_CODE_VERIFIER = `${STORAGE_PREFIX}code_verifier`;
39
+ var KEY_ACCESS_TOKEN = `${STORAGE_PREFIX}access_token`;
40
+ var KEY_REFRESH_TOKEN = `${STORAGE_PREFIX}refresh_token`;
41
+ var KEY_ID_TOKEN = `${STORAGE_PREFIX}id_token`;
42
+ var KEY_EXPIRES_AT = `${STORAGE_PREFIX}expires_at`;
43
+ var IAM = class {
44
+ config;
45
+ storage;
46
+ discoveryCache = null;
47
+ constructor(config) {
48
+ this.config = config;
49
+ this.storage = config.storage ?? sessionStorage;
50
+ }
51
+ // -----------------------------------------------------------------------
52
+ // OIDC Discovery
53
+ // -----------------------------------------------------------------------
54
+ async getDiscovery() {
55
+ if (this.discoveryCache) return this.discoveryCache;
56
+ const baseUrl = this.config.serverUrl.replace(/\/+$/, "");
57
+ try {
58
+ const res = await fetch(`${baseUrl}/.well-known/openid-configuration`, {
59
+ headers: { Accept: "application/json" }
60
+ });
61
+ if (res.ok) {
62
+ this.discoveryCache = await res.json();
63
+ return this.discoveryCache;
64
+ }
65
+ } catch {
66
+ }
67
+ this.discoveryCache = {
68
+ issuer: baseUrl,
69
+ authorization_endpoint: `${baseUrl}/oauth/authorize`,
70
+ token_endpoint: `${baseUrl}/oauth/token`,
71
+ userinfo_endpoint: `${baseUrl}/oauth/userinfo`,
72
+ jwks_uri: `${baseUrl}/.well-known/jwks`,
73
+ response_types_supported: ["code", "token", "id_token"],
74
+ grant_types_supported: ["authorization_code", "implicit", "refresh_token"],
75
+ scopes_supported: ["openid", "email", "profile"]
76
+ };
77
+ return this.discoveryCache;
78
+ }
79
+ // -----------------------------------------------------------------------
80
+ // Login redirect (PKCE)
81
+ // -----------------------------------------------------------------------
82
+ /**
83
+ * Start the OAuth2 PKCE login flow by redirecting to the IAM authorize endpoint.
84
+ *
85
+ * Generates PKCE challenge and state, stores them in session storage,
86
+ * then redirects the browser.
87
+ */
88
+ async signinRedirect(params) {
89
+ const discovery = await this.getDiscovery();
90
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
91
+ const state = generateState();
92
+ this.storage.setItem(KEY_STATE, state);
93
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
94
+ const url = new URL(discovery.authorization_endpoint);
95
+ url.searchParams.set("client_id", this.config.clientId);
96
+ url.searchParams.set("response_type", "code");
97
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
98
+ url.searchParams.set("scope", this.config.scope ?? "openid profile email");
99
+ url.searchParams.set("state", state);
100
+ url.searchParams.set("code_challenge", codeChallenge);
101
+ url.searchParams.set("code_challenge_method", "S256");
102
+ if (params?.additionalParams) {
103
+ for (const [k, v] of Object.entries(params.additionalParams)) {
104
+ url.searchParams.set(k, v);
105
+ }
106
+ }
107
+ window.location.href = url.toString();
108
+ }
109
+ // -----------------------------------------------------------------------
110
+ // Callback handling
111
+ // -----------------------------------------------------------------------
112
+ /**
113
+ * Handle the OAuth2 callback after redirect. Exchanges the authorization code
114
+ * for tokens using PKCE.
115
+ *
116
+ * Call this on your callback page (e.g. /auth/callback).
117
+ * Returns the token response, or throws if the state doesn't match.
118
+ */
119
+ async handleCallback(callbackUrl) {
120
+ const url = new URL(callbackUrl ?? window.location.href);
121
+ const error = url.searchParams.get("error");
122
+ if (error) {
123
+ const desc = url.searchParams.get("error_description") ?? error;
124
+ throw new Error(`OAuth error: ${desc}`);
125
+ }
126
+ const state = url.searchParams.get("state");
127
+ const savedState = this.storage.getItem(KEY_STATE);
128
+ if (savedState && state !== savedState) {
129
+ throw new Error("OAuth state mismatch \u2014 possible CSRF attack");
130
+ }
131
+ const accessToken = url.searchParams.get("access_token");
132
+ if (accessToken) {
133
+ this.storage.removeItem(KEY_STATE);
134
+ this.storage.removeItem(KEY_CODE_VERIFIER);
135
+ const tokens2 = {
136
+ access_token: accessToken,
137
+ token_type: "Bearer",
138
+ refresh_token: url.searchParams.get("refresh_token") ?? void 0,
139
+ expires_in: 7200
140
+ };
141
+ this.storeTokens(tokens2);
142
+ return toIAMToken(tokens2);
143
+ }
144
+ const code = url.searchParams.get("code");
145
+ if (!code) {
146
+ throw new Error("Missing authorization code in callback URL");
147
+ }
148
+ const codeVerifier = this.storage.getItem(KEY_CODE_VERIFIER);
149
+ if (!codeVerifier) {
150
+ throw new Error("Missing PKCE code verifier \u2014 was signinRedirect() called?");
151
+ }
152
+ this.storage.removeItem(KEY_STATE);
153
+ this.storage.removeItem(KEY_CODE_VERIFIER);
154
+ const discovery = await this.getDiscovery();
155
+ const body = new URLSearchParams({
156
+ grant_type: "authorization_code",
157
+ client_id: this.config.clientId,
158
+ code,
159
+ redirect_uri: this.config.redirectUri,
160
+ code_verifier: codeVerifier
161
+ });
162
+ const tokenUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/token` : discovery.token_endpoint;
163
+ const res = await fetch(tokenUrl, {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
166
+ body: body.toString()
167
+ });
168
+ if (!res.ok) {
169
+ const text = await res.text().catch(() => "");
170
+ throw new Error(`Token exchange failed (${res.status}): ${text}`);
171
+ }
172
+ const tokens = await res.json();
173
+ this.storeTokens(tokens);
174
+ return toIAMToken(tokens);
175
+ }
176
+ // -----------------------------------------------------------------------
177
+ // Token refresh
178
+ // -----------------------------------------------------------------------
179
+ /** Refresh the access token using the stored refresh token. */
180
+ async refreshAccessToken() {
181
+ const refreshToken = this.storage.getItem(KEY_REFRESH_TOKEN);
182
+ if (!refreshToken) {
183
+ throw new Error("No refresh token available");
184
+ }
185
+ const discovery = await this.getDiscovery();
186
+ const body = new URLSearchParams({
187
+ grant_type: "refresh_token",
188
+ client_id: this.config.clientId,
189
+ refresh_token: refreshToken
190
+ });
191
+ const tokenUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/token` : discovery.token_endpoint;
192
+ const res = await fetch(tokenUrl, {
193
+ method: "POST",
194
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
195
+ body: body.toString()
196
+ });
197
+ if (!res.ok) {
198
+ const text = await res.text().catch(() => "");
199
+ throw new Error(`Token refresh failed (${res.status}): ${text}`);
200
+ }
201
+ const tokens = await res.json();
202
+ this.storeTokens(tokens);
203
+ return toIAMToken(tokens);
204
+ }
205
+ // -----------------------------------------------------------------------
206
+ // Popup signin
207
+ // -----------------------------------------------------------------------
208
+ /**
209
+ * Open the IAM login page in a popup window. Resolves when the popup
210
+ * completes the OAuth flow and returns tokens.
211
+ */
212
+ async signinPopup(params) {
213
+ const discovery = await this.getDiscovery();
214
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
215
+ const state = generateState();
216
+ this.storage.setItem(KEY_STATE, state);
217
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
218
+ const url = new URL(discovery.authorization_endpoint);
219
+ url.searchParams.set("client_id", this.config.clientId);
220
+ url.searchParams.set("response_type", "code");
221
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
222
+ url.searchParams.set("scope", this.config.scope ?? "openid profile email");
223
+ url.searchParams.set("state", state);
224
+ url.searchParams.set("code_challenge", codeChallenge);
225
+ url.searchParams.set("code_challenge_method", "S256");
226
+ if (params?.additionalParams) {
227
+ for (const [k, v] of Object.entries(params.additionalParams)) {
228
+ url.searchParams.set(k, v);
229
+ }
230
+ }
231
+ const width = params?.width ?? 600;
232
+ const height = params?.height ?? 700;
233
+ const left = window.screenX + (window.outerWidth - width) / 2;
234
+ const top = window.screenY + (window.outerHeight - height) / 2;
235
+ return new Promise((resolve, reject) => {
236
+ const popup = window.open(
237
+ url.toString(),
238
+ "hanzo_iam_login",
239
+ `width=${width},height=${height},left=${left},top=${top},menubar=no,toolbar=no`
240
+ );
241
+ if (!popup) {
242
+ reject(new Error("Failed to open login popup \u2014 blocked by browser?"));
243
+ return;
244
+ }
245
+ const interval = setInterval(() => {
246
+ try {
247
+ if (popup.closed) {
248
+ clearInterval(interval);
249
+ reject(new Error("Login popup was closed before completing"));
250
+ return;
251
+ }
252
+ const popupUrl = popup.location.href;
253
+ if (popupUrl.startsWith(this.config.redirectUri)) {
254
+ clearInterval(interval);
255
+ popup.close();
256
+ this.handleCallback(popupUrl).then(resolve, reject);
257
+ }
258
+ } catch {
259
+ }
260
+ }, 200);
261
+ });
262
+ }
263
+ // -----------------------------------------------------------------------
264
+ // Silent signin (iframe)
265
+ // -----------------------------------------------------------------------
266
+ /**
267
+ * Attempt silent authentication via a hidden iframe.
268
+ * Useful for checking if the user has an active IAM session.
269
+ * Returns null if silent auth fails (user needs to log in interactively).
270
+ */
271
+ async signinSilent(timeoutMs = 5e3) {
272
+ const discovery = await this.getDiscovery();
273
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
274
+ const state = generateState();
275
+ this.storage.setItem(KEY_STATE, state);
276
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
277
+ const url = new URL(discovery.authorization_endpoint);
278
+ url.searchParams.set("client_id", this.config.clientId);
279
+ url.searchParams.set("response_type", "code");
280
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
281
+ url.searchParams.set("scope", this.config.scope ?? "openid profile email");
282
+ url.searchParams.set("state", state);
283
+ url.searchParams.set("code_challenge", codeChallenge);
284
+ url.searchParams.set("code_challenge_method", "S256");
285
+ url.searchParams.set("prompt", "none");
286
+ return new Promise((resolve) => {
287
+ const iframe = document.createElement("iframe");
288
+ iframe.style.display = "none";
289
+ const timeout = setTimeout(() => {
290
+ cleanup();
291
+ resolve(null);
292
+ }, timeoutMs);
293
+ const cleanup = () => {
294
+ clearTimeout(timeout);
295
+ iframe.remove();
296
+ this.storage.removeItem(KEY_STATE);
297
+ this.storage.removeItem(KEY_CODE_VERIFIER);
298
+ };
299
+ iframe.addEventListener("load", () => {
300
+ try {
301
+ const iframeUrl = iframe.contentWindow?.location.href;
302
+ if (iframeUrl && iframeUrl.startsWith(this.config.redirectUri)) {
303
+ cleanup();
304
+ this.handleCallback(iframeUrl).then(
305
+ (tokens) => resolve(tokens),
306
+ () => resolve(null)
307
+ );
308
+ }
309
+ } catch {
310
+ cleanup();
311
+ resolve(null);
312
+ }
313
+ });
314
+ iframe.src = url.toString();
315
+ document.body.appendChild(iframe);
316
+ });
317
+ }
318
+ // -----------------------------------------------------------------------
319
+ // Token management
320
+ // -----------------------------------------------------------------------
321
+ storeTokens(tokens) {
322
+ this.storage.setItem(KEY_ACCESS_TOKEN, tokens.access_token);
323
+ if (tokens.refresh_token) {
324
+ this.storage.setItem(KEY_REFRESH_TOKEN, tokens.refresh_token);
325
+ }
326
+ if (tokens.id_token) {
327
+ this.storage.setItem(KEY_ID_TOKEN, tokens.id_token);
328
+ }
329
+ if (tokens.expires_in) {
330
+ const expiresAt = Date.now() + tokens.expires_in * 1e3;
331
+ this.storage.setItem(KEY_EXPIRES_AT, String(expiresAt));
332
+ }
333
+ }
334
+ /** Get the stored access token (may be expired). */
335
+ getAccessToken() {
336
+ return this.storage.getItem(KEY_ACCESS_TOKEN);
337
+ }
338
+ /** Get the stored refresh token. */
339
+ getRefreshToken() {
340
+ return this.storage.getItem(KEY_REFRESH_TOKEN);
341
+ }
342
+ /** Get the stored ID token. */
343
+ getIdToken() {
344
+ return this.storage.getItem(KEY_ID_TOKEN);
345
+ }
346
+ /** Check if the stored access token is expired. */
347
+ isTokenExpired() {
348
+ const expiresAt = this.storage.getItem(KEY_EXPIRES_AT);
349
+ if (!expiresAt) return true;
350
+ return Date.now() >= Number(expiresAt);
351
+ }
352
+ /**
353
+ * Get a valid access token — refreshes automatically if expired.
354
+ * Returns null if no token and no refresh token available.
355
+ */
356
+ async getValidAccessToken() {
357
+ const token = this.getAccessToken();
358
+ if (token && !this.isTokenExpired()) {
359
+ return token;
360
+ }
361
+ if (this.getRefreshToken()) {
362
+ try {
363
+ const tokens = await this.refreshAccessToken();
364
+ return tokens.accessToken;
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+ return null;
370
+ }
371
+ /** Clear all stored tokens (logout). */
372
+ clearTokens() {
373
+ this.storage.removeItem(KEY_ACCESS_TOKEN);
374
+ this.storage.removeItem(KEY_REFRESH_TOKEN);
375
+ this.storage.removeItem(KEY_ID_TOKEN);
376
+ this.storage.removeItem(KEY_EXPIRES_AT);
377
+ this.storage.removeItem(KEY_STATE);
378
+ this.storage.removeItem(KEY_CODE_VERIFIER);
379
+ }
380
+ // -----------------------------------------------------------------------
381
+ // User info
382
+ // -----------------------------------------------------------------------
383
+ /** Fetch user info from the OIDC userinfo endpoint using the stored access token. */
384
+ async getUserInfo() {
385
+ const token = await this.getValidAccessToken();
386
+ if (!token) {
387
+ throw new Error("No valid access token \u2014 user must log in");
388
+ }
389
+ const discovery = await this.getDiscovery();
390
+ const userinfoUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/userinfo` : discovery.userinfo_endpoint;
391
+ const res = await fetch(userinfoUrl, {
392
+ headers: { Authorization: `Bearer ${token}` }
393
+ });
394
+ if (!res.ok) {
395
+ throw new Error(`Userinfo fetch failed (${res.status})`);
396
+ }
397
+ return await res.json();
398
+ }
399
+ // -----------------------------------------------------------------------
400
+ // URL helpers
401
+ // -----------------------------------------------------------------------
402
+ /** Build the signup URL for the IAM server. */
403
+ getSignupUrl(params) {
404
+ const base = this.config.serverUrl.replace(/\/+$/, "");
405
+ const app = this.config.appName ?? "app";
406
+ this.config.orgName ?? "built-in";
407
+ let url = `${base}/signup/${app}`;
408
+ if (params?.enablePassword) {
409
+ url += "?enablePassword=true";
410
+ }
411
+ return url;
412
+ }
413
+ /** Build the user profile URL on the IAM server. */
414
+ getUserProfileUrl(username) {
415
+ const base = this.config.serverUrl.replace(/\/+$/, "");
416
+ const org = this.config.orgName ?? "built-in";
417
+ return `${base}/users/${org}/${username}`;
418
+ }
419
+ // -----------------------------------------------------------------------
420
+ // Casdoor REST surface (signup, OTP, REST login, phone lookup)
421
+ //
422
+ // The OIDC layer covers redirect/PKCE, token exchange, refresh, userinfo.
423
+ // These methods cover the Casdoor-native endpoints that don't have an OIDC
424
+ // analogue: phone/email OTP, custom signup with verification codes, and
425
+ // direct REST login that returns an authorization code in one round-trip
426
+ // (used as the bridge between OTP collection and `exchangeCode`).
427
+ //
428
+ // All paths are gateway-canonical (`/login`, `/signup`,
429
+ // `/send-verification-code`, `/get-phone-user`) — point `serverUrl` at the
430
+ // gateway prefix (e.g. `https://api.dev.satschel.com/v1/iam`) and the
431
+ // gateway proxies to Casdoor's `/api/*` internally.
432
+ // -----------------------------------------------------------------------
433
+ /**
434
+ * Send a verification code to a phone or email destination.
435
+ *
436
+ * @param contact `{ phone, countryCode }` for SMS, `{ email }` for email.
437
+ * @param method Casdoor method: `login`, `signup`, `forget`, `mfaSetup`, etc.
438
+ */
439
+ async sendVerificationCode(contact, method = "login") {
440
+ if (method === "reset") method = "forget";
441
+ const isPhone = "phone" in contact;
442
+ const dest = isPhone ? contact.phone : contact.email;
443
+ const params = {
444
+ applicationId: `admin/${this.config.appName ?? "app"}`,
445
+ dest,
446
+ type: isPhone ? "phone" : "email",
447
+ method,
448
+ captchaType: "none",
449
+ captchaToken: ""
450
+ };
451
+ if (isPhone) params.countryCode = contact.countryCode;
452
+ const url = `${this.config.serverUrl.replace(/\/+$/, "")}/send-verification-code`;
453
+ const res = await fetch(url, {
454
+ method: "POST",
455
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
456
+ body: new URLSearchParams(params).toString()
457
+ });
458
+ const data = await res.json().catch(() => ({}));
459
+ if (data.status === "ok") return { ok: true };
460
+ const msg = data.msg || `send-verification-code failed (${res.status})`;
461
+ if (msg.includes("SMS provider") || msg.includes("provider")) return { ok: true };
462
+ return { ok: false, error: msg };
463
+ }
464
+ /**
465
+ * Look up whether a phone number is registered. Returns `{ exists: false }`
466
+ * on 404 or unknown numbers; `{ exists: true }` when Casdoor confirms a user.
467
+ */
468
+ async lookupPhoneUser(phone, countryCode) {
469
+ const url = `${this.config.serverUrl.replace(/\/+$/, "")}/get-phone-user`;
470
+ const res = await fetch(url, {
471
+ method: "POST",
472
+ headers: { "Content-Type": "application/json" },
473
+ body: JSON.stringify({
474
+ application: this.config.appName ?? "app",
475
+ phone,
476
+ countryCode
477
+ })
478
+ });
479
+ if (res.status === 404) return { exists: false };
480
+ if (!res.ok) return { exists: false, error: `lookupPhoneUser failed (${res.status})` };
481
+ return { exists: true };
482
+ }
483
+ /**
484
+ * Casdoor REST signup. Returns the new user's id on success.
485
+ *
486
+ * Phone signup flow: send phoneCode via `sendVerificationCode`, then call
487
+ * this with the OTP in `phoneCode`. Casdoor verifies the code internally.
488
+ * Email signup flow: same with `email` + `emailCode`.
489
+ */
490
+ async signup(params) {
491
+ const username = params.username ?? params.name;
492
+ const password = params.password ?? `Liq${Date.now()}!`;
493
+ const body = {
494
+ application: this.config.appName ?? "app",
495
+ organization: this.config.orgName ?? "built-in",
496
+ name: params.name,
497
+ username,
498
+ password,
499
+ confirm: password,
500
+ agreement: true
501
+ };
502
+ if (params.method === "email") {
503
+ body.email = params.email;
504
+ if (params.emailCode) body.emailCode = params.emailCode;
505
+ } else {
506
+ body.phone = params.phone;
507
+ body.countryCode = params.countryCode;
508
+ if (params.phoneCode) body.phoneCode = params.phoneCode;
509
+ if (params.email) body.email = params.email;
510
+ if (params.emailCode) body.emailCode = params.emailCode;
511
+ }
512
+ const url = `${this.config.serverUrl.replace(/\/+$/, "")}/signup`;
513
+ const res = await fetch(url, {
514
+ method: "POST",
515
+ headers: { "Content-Type": "application/json" },
516
+ body: JSON.stringify(body)
517
+ });
518
+ const data = await res.json().catch(() => ({}));
519
+ if (data.status === "ok") return { ok: true, id: data.data2 || data.data };
520
+ return { ok: false, error: data.msg || `signup failed (${res.status})` };
521
+ }
522
+ /**
523
+ * REST login that returns an authorization code (Casdoor `/login`).
524
+ *
525
+ * Use this when you want the caller to drive the PKCE flow without a
526
+ * full redirect — collect credentials in your own UI, get a code back,
527
+ * then call `exchangeCodeForToken` to land tokens.
528
+ */
529
+ async loginWithCredentials(params) {
530
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
531
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
532
+ const url = new URL(`${this.config.serverUrl.replace(/\/+$/, "")}/login`);
533
+ url.searchParams.set("code_challenge", codeChallenge);
534
+ url.searchParams.set("code_challenge_method", "S256");
535
+ const res = await fetch(url.toString(), {
536
+ method: "POST",
537
+ headers: { "Content-Type": "application/json" },
538
+ body: JSON.stringify({
539
+ application: this.config.appName ?? "app",
540
+ organization: this.config.orgName ?? "built-in",
541
+ username: params.username,
542
+ password: params.password,
543
+ type: params.type ?? "code",
544
+ clientId: this.config.clientId,
545
+ redirectUri: params.redirectUri ?? this.config.redirectUri,
546
+ codeChallenge,
547
+ codeChallengeMethod: "S256",
548
+ autoSignin: true
549
+ })
550
+ });
551
+ const data = await res.json().catch(() => ({}));
552
+ if (data.status === "ok" && data.data) return { ok: true, code: data.data };
553
+ return { ok: false, error: data.msg || `login failed (${res.status})` };
554
+ }
555
+ /**
556
+ * Exchange an authorization code for tokens using the stored PKCE verifier.
557
+ * Pairs with `loginWithCredentials` for a code → tokens round-trip.
558
+ */
559
+ async exchangeCodeForToken(code, redirectUri) {
560
+ const codeVerifier = this.storage.getItem(KEY_CODE_VERIFIER);
561
+ if (!codeVerifier) {
562
+ throw new Error("Missing PKCE verifier \u2014 call loginWithCredentials() first");
563
+ }
564
+ this.storage.removeItem(KEY_CODE_VERIFIER);
565
+ const discovery = await this.getDiscovery();
566
+ const tokenUrl = this.config.proxyBaseUrl ? `${this.config.proxyBaseUrl.replace(/\/+$/, "")}/auth/token` : discovery.token_endpoint;
567
+ const body = new URLSearchParams({
568
+ grant_type: "authorization_code",
569
+ client_id: this.config.clientId,
570
+ code,
571
+ redirect_uri: redirectUri ?? this.config.redirectUri,
572
+ code_verifier: codeVerifier
573
+ });
574
+ const res = await fetch(tokenUrl, {
575
+ method: "POST",
576
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
577
+ body: body.toString()
578
+ });
579
+ if (!res.ok) {
580
+ const err = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
581
+ throw new Error(err.error_description || err.error || "Token exchange failed");
582
+ }
583
+ const tokens = await res.json();
584
+ this.storeTokens(tokens);
585
+ return toIAMToken(tokens);
586
+ }
587
+ /**
588
+ * Phone OTP login: tries the numbered username variants Casdoor accepts
589
+ * (`{phone}`, `{countryCode}{phone}`), exchanges the resulting code for
590
+ * tokens. Returns the token response, or throws on failure.
591
+ */
592
+ async loginWithPhoneOTP(params) {
593
+ const usernames = [params.phone, `${params.countryCode}${params.phone}`];
594
+ let lastError = "";
595
+ for (const username of usernames) {
596
+ const result = await this.loginWithCredentials({
597
+ username,
598
+ password: params.code,
599
+ redirectUri: params.redirectUri
600
+ });
601
+ if (result.ok && result.code) {
602
+ return this.exchangeCodeForToken(result.code, params.redirectUri);
603
+ }
604
+ lastError = result.error ?? lastError;
605
+ }
606
+ throw new Error(lastError || "Phone OTP login failed");
607
+ }
608
+ /**
609
+ * Logout via Casdoor REST `/logout` (clears server-side session) and
610
+ * the local storage.
611
+ */
612
+ async logout() {
613
+ const token = this.storage.getItem(KEY_ACCESS_TOKEN);
614
+ try {
615
+ await fetch(`${this.config.serverUrl.replace(/\/+$/, "")}/oauth/logout`, {
616
+ method: "POST",
617
+ headers: token ? { Authorization: `Bearer ${token}` } : {}
618
+ });
619
+ } catch {
620
+ }
621
+ this.clearTokens();
622
+ }
623
+ // -----------------------------------------------------------------------
624
+ // High-level helpers — normalize to ergonomic types so apps don't need
625
+ // their own adapters around the OIDC/Casdoor wire shapes.
626
+ // -----------------------------------------------------------------------
627
+ /**
628
+ * Build a social-login authorize URL. Used to navigate the user to
629
+ * Google/Apple/etc. — same as `signinRedirect` but returns the URL
630
+ * instead of issuing the redirect, so apps can `<a href="...">`.
631
+ */
632
+ async getSocialLoginUrl(provider, scope = "openid profile email") {
633
+ const { codeVerifier, codeChallenge } = await generatePKCEChallenge();
634
+ const state = generateState();
635
+ this.storage.setItem(KEY_STATE, state);
636
+ this.storage.setItem(KEY_CODE_VERIFIER, codeVerifier);
637
+ const discovery = await this.getDiscovery();
638
+ const url = new URL(discovery.authorization_endpoint);
639
+ url.searchParams.set("client_id", this.config.clientId);
640
+ url.searchParams.set("response_type", "code");
641
+ url.searchParams.set("redirect_uri", this.config.redirectUri);
642
+ url.searchParams.set("scope", scope);
643
+ url.searchParams.set("state", state);
644
+ url.searchParams.set("code_challenge", codeChallenge);
645
+ url.searchParams.set("code_challenge_method", "S256");
646
+ url.searchParams.set("provider", provider);
647
+ return url.toString();
648
+ }
649
+ /**
650
+ * Fetch the current user, shaped into the canonical `IAMUser` form
651
+ * (camelCase, no `_` keys). Returns null when no token is present.
652
+ */
653
+ async getUser() {
654
+ const token = await this.getValidAccessToken();
655
+ if (!token) return null;
656
+ const u = await this.getUserInfo();
657
+ return {
658
+ sub: u.sub ?? "",
659
+ email: u.email,
660
+ name: u.name,
661
+ givenName: u.given_name,
662
+ familyName: u.family_name,
663
+ phoneNumber: u.phone_number,
664
+ emailVerified: u.email_verified,
665
+ picture: u.picture,
666
+ owner: u.owner
667
+ };
668
+ }
669
+ };
670
+ function toIAMToken(t) {
671
+ return {
672
+ accessToken: t.access_token,
673
+ refreshToken: t.refresh_token,
674
+ idToken: t.id_token,
675
+ expiresIn: t.expires_in,
676
+ tokenType: t.token_type,
677
+ scope: t.scope
678
+ };
679
+ }
680
+
681
+ // src/client.ts
682
+ var DEFAULT_TIMEOUT_MS = 1e4;
683
+ var IamClient = class {
684
+ baseUrl;
685
+ clientId;
686
+ clientSecret;
687
+ orgName;
688
+ appName;
689
+ discoveryCache = null;
690
+ constructor(config) {
691
+ this.baseUrl = config.serverUrl.replace(/\/+$/, "");
692
+ this.clientId = config.clientId;
693
+ this.clientSecret = config.clientSecret;
694
+ this.orgName = config.orgName;
695
+ this.appName = config.appName;
696
+ }
697
+ // -----------------------------------------------------------------------
698
+ // Internal HTTP helpers
699
+ // -----------------------------------------------------------------------
700
+ async request(path, opts) {
701
+ const url = new URL(path, this.baseUrl);
702
+ if (opts?.params) {
703
+ for (const [k, v] of Object.entries(opts.params)) {
704
+ url.searchParams.set(k, v);
705
+ }
706
+ }
707
+ const controller = new AbortController();
708
+ const timer = setTimeout(
709
+ () => controller.abort(),
710
+ opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS
711
+ );
712
+ const headers = {
713
+ Accept: "application/json"
714
+ };
715
+ if (opts?.token) {
716
+ headers.Authorization = `Bearer ${opts.token}`;
717
+ }
718
+ if (opts?.body) {
719
+ headers["Content-Type"] = "application/json";
720
+ }
721
+ if (this.clientSecret && !opts?.token) {
722
+ const credentials = `${this.clientId}:${this.clientSecret}`;
723
+ const basic = typeof Buffer !== "undefined" ? Buffer.from(credentials).toString("base64") : btoa(credentials);
724
+ headers.Authorization = `Basic ${basic}`;
725
+ }
726
+ try {
727
+ const res = await fetch(url.toString(), {
728
+ method: opts?.method ?? "GET",
729
+ headers,
730
+ body: opts?.body ? JSON.stringify(opts.body) : void 0,
731
+ signal: controller.signal
732
+ });
733
+ if (!res.ok) {
734
+ const text = await res.text().catch(() => "");
735
+ throw new IamApiError(res.status, `${res.statusText}: ${text}`.trim());
736
+ }
737
+ return await res.json();
738
+ } finally {
739
+ clearTimeout(timer);
740
+ }
741
+ }
742
+ // -----------------------------------------------------------------------
743
+ // OIDC Discovery
744
+ // -----------------------------------------------------------------------
745
+ async getDiscovery() {
746
+ const CACHE_TTL_MS = 5 * 60 * 1e3;
747
+ if (this.discoveryCache && Date.now() - this.discoveryCache.fetchedAt < CACHE_TTL_MS) {
748
+ return this.discoveryCache.data;
749
+ }
750
+ const data = await this.request(
751
+ "/.well-known/openid-configuration"
752
+ );
753
+ this.discoveryCache = { data, fetchedAt: Date.now() };
754
+ return data;
755
+ }
756
+ /** Get JWKS URI from OIDC discovery (cached). */
757
+ async getJwksUri() {
758
+ const discovery = await this.getDiscovery();
759
+ return discovery.jwks_uri;
760
+ }
761
+ // -----------------------------------------------------------------------
762
+ // OAuth2 / Token
763
+ // -----------------------------------------------------------------------
764
+ /** Build the authorization URL for user login redirect. */
765
+ async getAuthorizationUrl(params) {
766
+ const discovery = await this.getDiscovery();
767
+ const url = new URL(discovery.authorization_endpoint);
768
+ url.searchParams.set("client_id", this.clientId);
769
+ url.searchParams.set("response_type", "code");
770
+ url.searchParams.set("redirect_uri", params.redirectUri);
771
+ url.searchParams.set("state", params.state);
772
+ url.searchParams.set("scope", params.scope ?? "openid profile email");
773
+ if (params.codeChallenge) {
774
+ url.searchParams.set("code_challenge", params.codeChallenge);
775
+ url.searchParams.set("code_challenge_method", params.codeChallengeMethod ?? "S256");
776
+ }
777
+ return url.toString();
778
+ }
779
+ /** Exchange authorization code for tokens. */
780
+ async exchangeCode(params) {
781
+ const discovery = await this.getDiscovery();
782
+ const body = new URLSearchParams({
783
+ grant_type: "authorization_code",
784
+ client_id: this.clientId,
785
+ code: params.code,
786
+ redirect_uri: params.redirectUri
787
+ });
788
+ if (this.clientSecret) {
789
+ body.set("client_secret", this.clientSecret);
790
+ }
791
+ if (params.codeVerifier) {
792
+ body.set("code_verifier", params.codeVerifier);
793
+ }
794
+ const controller = new AbortController();
795
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
796
+ try {
797
+ const res = await fetch(discovery.token_endpoint, {
798
+ method: "POST",
799
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
800
+ body: body.toString(),
801
+ signal: controller.signal
802
+ });
803
+ if (!res.ok) {
804
+ const text = await res.text().catch(() => "");
805
+ throw new IamApiError(res.status, `Token exchange failed: ${text}`);
806
+ }
807
+ return await res.json();
808
+ } finally {
809
+ clearTimeout(timer);
810
+ }
811
+ }
812
+ /**
813
+ * Resource Owner Password Credentials grant.
814
+ * Used for service-to-service auth, CLI login, and e2e tests.
815
+ */
816
+ async passwordGrant(params) {
817
+ const discovery = await this.getDiscovery();
818
+ const body = new URLSearchParams({
819
+ grant_type: "password",
820
+ client_id: this.clientId,
821
+ username: params.username,
822
+ password: params.password,
823
+ scope: params.scope ?? "openid profile email phone"
824
+ });
825
+ if (this.clientSecret) {
826
+ body.set("client_secret", this.clientSecret);
827
+ }
828
+ const controller = new AbortController();
829
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
830
+ try {
831
+ const res = await fetch(discovery.token_endpoint, {
832
+ method: "POST",
833
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
834
+ body: body.toString(),
835
+ signal: controller.signal
836
+ });
837
+ if (!res.ok) {
838
+ const text = await res.text().catch(() => "");
839
+ throw new IamApiError(res.status, `Password grant failed: ${text}`);
840
+ }
841
+ return await res.json();
842
+ } finally {
843
+ clearTimeout(timer);
844
+ }
845
+ }
846
+ /** Refresh an access token. */
847
+ async refreshToken(refreshToken) {
848
+ const discovery = await this.getDiscovery();
849
+ const body = new URLSearchParams({
850
+ grant_type: "refresh_token",
851
+ client_id: this.clientId,
852
+ refresh_token: refreshToken
853
+ });
854
+ if (this.clientSecret) {
855
+ body.set("client_secret", this.clientSecret);
856
+ }
857
+ const controller = new AbortController();
858
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
859
+ try {
860
+ const res = await fetch(discovery.token_endpoint, {
861
+ method: "POST",
862
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
863
+ body: body.toString(),
864
+ signal: controller.signal
865
+ });
866
+ if (!res.ok) {
867
+ const text = await res.text().catch(() => "");
868
+ throw new IamApiError(res.status, `Token refresh failed: ${text}`);
869
+ }
870
+ return await res.json();
871
+ } finally {
872
+ clearTimeout(timer);
873
+ }
874
+ }
875
+ // -----------------------------------------------------------------------
876
+ // User
877
+ // -----------------------------------------------------------------------
878
+ /** Get user info from access token (OIDC userinfo endpoint). */
879
+ async getUserInfo(accessToken) {
880
+ const discovery = await this.getDiscovery();
881
+ const controller = new AbortController();
882
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
883
+ try {
884
+ const res = await fetch(discovery.userinfo_endpoint, {
885
+ headers: { Authorization: `Bearer ${accessToken}` },
886
+ signal: controller.signal
887
+ });
888
+ if (!res.ok) {
889
+ throw new IamApiError(res.status, "Failed to fetch userinfo");
890
+ }
891
+ return await res.json();
892
+ } finally {
893
+ clearTimeout(timer);
894
+ }
895
+ }
896
+ /** Get a user by ID ("org/username" format). */
897
+ async getUser(userId, token) {
898
+ const resp = await this.request("/api/get-user", {
899
+ params: { id: userId },
900
+ token
901
+ });
902
+ return resp.data ?? null;
903
+ }
904
+ // -----------------------------------------------------------------------
905
+ // Organization
906
+ // -----------------------------------------------------------------------
907
+ /** List organizations (for the configured owner). */
908
+ async getOrganizations(token) {
909
+ const owner = this.orgName ?? "admin";
910
+ const resp = await this.request(
911
+ "/api/get-organizations",
912
+ { params: { owner }, token }
913
+ );
914
+ return resp.data ?? [];
915
+ }
916
+ /** Get a specific organization. */
917
+ async getOrganization(id, token) {
918
+ const resp = await this.request(
919
+ "/api/get-organization",
920
+ { params: { id }, token }
921
+ );
922
+ return resp.data ?? null;
923
+ }
924
+ /** Get organizations a user belongs to. */
925
+ async getUserOrganizations(userId, token) {
926
+ const user = await this.getUser(userId, token);
927
+ if (!user) return [];
928
+ const org = await this.getOrganization(
929
+ `admin/${user.owner}`,
930
+ token
931
+ );
932
+ return org ? [org] : [];
933
+ }
934
+ // -----------------------------------------------------------------------
935
+ // Project
936
+ // -----------------------------------------------------------------------
937
+ /** List projects (for the configured owner). */
938
+ async getProjects(token) {
939
+ const owner = this.orgName ?? "admin";
940
+ const resp = await this.request(
941
+ "/api/get-projects",
942
+ { params: { owner }, token }
943
+ );
944
+ return resp.data ?? [];
945
+ }
946
+ /** Get a specific project by ID ("owner/name" format). */
947
+ async getProject(id, token) {
948
+ const resp = await this.request(
949
+ "/api/get-project",
950
+ { params: { id }, token }
951
+ );
952
+ return resp.data ?? null;
953
+ }
954
+ /** Get all projects for an organization. */
955
+ async getOrganizationProjects(organization, token) {
956
+ const resp = await this.request(
957
+ "/api/get-organization-projects",
958
+ { params: { organization }, token }
959
+ );
960
+ return resp.data ?? [];
961
+ }
962
+ // -----------------------------------------------------------------------
963
+ // Raw request (for extending)
964
+ // -----------------------------------------------------------------------
965
+ /** Make an arbitrary authenticated request to the IAM API. */
966
+ async apiRequest(path, opts) {
967
+ return this.request(path, opts);
968
+ }
969
+ };
970
+ var IamApiError = class extends Error {
971
+ status;
972
+ constructor(status, message) {
973
+ super(message);
974
+ this.name = "IamApiError";
975
+ this.status = status;
976
+ }
977
+ };
978
+
979
+ // src/react.ts
980
+ var IamContext = react.createContext(null);
981
+ IamContext.displayName = "HanzoIamContext";
982
+ var STORAGE_ORG_KEY = "hanzo_iam_current_org";
983
+ var STORAGE_PROJECT_KEY = "hanzo_iam_current_project";
984
+ var STORAGE_EXPIRES_KEY = "hanzo_iam_expires_at";
985
+ function IamProvider(props) {
986
+ const { config, autoInit = true, onAuthChange, children } = props;
987
+ const sdk = react.useMemo(
988
+ () => new IAM(config),
989
+ // eslint-disable-next-line react-hooks/exhaustive-deps
990
+ [config.serverUrl, config.clientId, config.redirectUri]
991
+ );
992
+ const [user, setUser] = react.useState(null);
993
+ const [isAuthenticated, setIsAuthenticated] = react.useState(false);
994
+ const [isLoading, setIsLoading] = react.useState(autoInit);
995
+ const [accessToken, setAccessToken] = react.useState(
996
+ sdk.getAccessToken()
997
+ );
998
+ const [error, setError] = react.useState(null);
999
+ const refreshTimerRef = react.useRef(null);
1000
+ const scheduleRefresh = react.useCallback(() => {
1001
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
1002
+ if (sdk.isTokenExpired()) return;
1003
+ const storage = config.storage ?? sessionStorage;
1004
+ const expiresAtStr = storage.getItem(STORAGE_EXPIRES_KEY);
1005
+ if (!expiresAtStr) return;
1006
+ const msUntilRefresh = Number(expiresAtStr) - Date.now() - 6e4;
1007
+ if (msUntilRefresh <= 0) {
1008
+ sdk.refreshAccessToken().then((tokens) => {
1009
+ setAccessToken(tokens.accessToken);
1010
+ scheduleRefresh();
1011
+ }).catch(() => {
1012
+ setIsAuthenticated(false);
1013
+ setUser(null);
1014
+ setAccessToken(null);
1015
+ });
1016
+ return;
1017
+ }
1018
+ refreshTimerRef.current = setTimeout(async () => {
1019
+ try {
1020
+ const tokens = await sdk.refreshAccessToken();
1021
+ setAccessToken(tokens.accessToken);
1022
+ scheduleRefresh();
1023
+ } catch {
1024
+ setIsAuthenticated(false);
1025
+ setUser(null);
1026
+ setAccessToken(null);
1027
+ }
1028
+ }, msUntilRefresh);
1029
+ }, [sdk, config.storage]);
1030
+ react.useEffect(() => {
1031
+ if (!autoInit) {
1032
+ setIsLoading(false);
1033
+ return;
1034
+ }
1035
+ let cancelled = false;
1036
+ const init = async () => {
1037
+ try {
1038
+ const token = await sdk.getValidAccessToken();
1039
+ if (cancelled) return;
1040
+ if (token) {
1041
+ setAccessToken(token);
1042
+ setIsAuthenticated(true);
1043
+ try {
1044
+ const info = await sdk.getUserInfo();
1045
+ if (!cancelled) setUser(info);
1046
+ } catch {
1047
+ }
1048
+ scheduleRefresh();
1049
+ onAuthChange?.(true);
1050
+ } else {
1051
+ onAuthChange?.(false);
1052
+ }
1053
+ } catch (err) {
1054
+ if (!cancelled) {
1055
+ setError(err instanceof Error ? err : new Error(String(err)));
1056
+ onAuthChange?.(false);
1057
+ }
1058
+ } finally {
1059
+ if (!cancelled) setIsLoading(false);
1060
+ }
1061
+ };
1062
+ init();
1063
+ return () => {
1064
+ cancelled = true;
1065
+ };
1066
+ }, [sdk, autoInit]);
1067
+ react.useEffect(() => {
1068
+ return () => {
1069
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
1070
+ };
1071
+ }, []);
1072
+ const completeAuth = react.useCallback(
1073
+ async (tokens) => {
1074
+ setAccessToken(tokens.accessToken);
1075
+ setIsAuthenticated(true);
1076
+ try {
1077
+ const info = await sdk.getUserInfo();
1078
+ setUser(info);
1079
+ } catch {
1080
+ }
1081
+ scheduleRefresh();
1082
+ onAuthChange?.(true);
1083
+ },
1084
+ [sdk, scheduleRefresh, onAuthChange]
1085
+ );
1086
+ const login = react.useCallback(
1087
+ async (params) => {
1088
+ setError(null);
1089
+ await sdk.signinRedirect(params);
1090
+ },
1091
+ [sdk]
1092
+ );
1093
+ const loginPopup = react.useCallback(
1094
+ async (params) => {
1095
+ setError(null);
1096
+ try {
1097
+ const tokens = await sdk.signinPopup(params);
1098
+ await completeAuth(tokens);
1099
+ } catch (err) {
1100
+ const e = err instanceof Error ? err : new Error(String(err));
1101
+ setError(e);
1102
+ throw e;
1103
+ }
1104
+ },
1105
+ [sdk, completeAuth]
1106
+ );
1107
+ const handleCallback = react.useCallback(
1108
+ async (callbackUrl) => {
1109
+ setError(null);
1110
+ try {
1111
+ const tokens = await sdk.handleCallback(callbackUrl);
1112
+ await completeAuth(tokens);
1113
+ return tokens;
1114
+ } catch (err) {
1115
+ const e = err instanceof Error ? err : new Error(String(err));
1116
+ setError(e);
1117
+ throw e;
1118
+ }
1119
+ },
1120
+ [sdk, completeAuth]
1121
+ );
1122
+ const logout = react.useCallback(() => {
1123
+ sdk.clearTokens();
1124
+ setUser(null);
1125
+ setIsAuthenticated(false);
1126
+ setAccessToken(null);
1127
+ setError(null);
1128
+ if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current);
1129
+ try {
1130
+ localStorage.removeItem(STORAGE_ORG_KEY);
1131
+ localStorage.removeItem(STORAGE_PROJECT_KEY);
1132
+ } catch {
1133
+ }
1134
+ onAuthChange?.(false);
1135
+ }, [sdk, onAuthChange]);
1136
+ const value = react.useMemo(
1137
+ () => ({
1138
+ sdk,
1139
+ config,
1140
+ user,
1141
+ isAuthenticated,
1142
+ isLoading,
1143
+ accessToken,
1144
+ login,
1145
+ loginPopup,
1146
+ handleCallback,
1147
+ logout,
1148
+ error
1149
+ }),
1150
+ [
1151
+ sdk,
1152
+ config,
1153
+ user,
1154
+ isAuthenticated,
1155
+ isLoading,
1156
+ accessToken,
1157
+ login,
1158
+ loginPopup,
1159
+ handleCallback,
1160
+ logout,
1161
+ error
1162
+ ]
1163
+ );
1164
+ return react.createElement(IamContext.Provider, { value }, children);
1165
+ }
1166
+ function useIam() {
1167
+ const ctx = react.useContext(IamContext);
1168
+ if (!ctx) {
1169
+ throw new Error("useIam() must be used within an <IamProvider>");
1170
+ }
1171
+ return ctx;
1172
+ }
1173
+ function useOrganizations() {
1174
+ const { config, isAuthenticated, accessToken } = useIam();
1175
+ const [organizations, setOrganizations] = react.useState([]);
1176
+ const [projects, setProjects] = react.useState([]);
1177
+ const [isLoading, setIsLoading] = react.useState(false);
1178
+ const [currentOrgId, setCurrentOrgId] = react.useState(() => {
1179
+ try {
1180
+ return localStorage.getItem(STORAGE_ORG_KEY);
1181
+ } catch {
1182
+ return null;
1183
+ }
1184
+ });
1185
+ const [currentProjectId, setCurrentProjectId] = react.useState(
1186
+ () => {
1187
+ try {
1188
+ return localStorage.getItem(STORAGE_PROJECT_KEY);
1189
+ } catch {
1190
+ return null;
1191
+ }
1192
+ }
1193
+ );
1194
+ react.useEffect(() => {
1195
+ if (!isAuthenticated || !accessToken) {
1196
+ setOrganizations([]);
1197
+ setProjects([]);
1198
+ return;
1199
+ }
1200
+ let cancelled = false;
1201
+ const fetchOrgs = async () => {
1202
+ setIsLoading(true);
1203
+ try {
1204
+ const payload = JSON.parse(atob(accessToken.split(".")[1]));
1205
+ const sub = payload.sub;
1206
+ if (sub?.includes("/")) {
1207
+ const primaryOrg = sub.split("/")[0];
1208
+ if (!cancelled) {
1209
+ const syntheticOrg = {
1210
+ owner: "admin",
1211
+ name: primaryOrg,
1212
+ displayName: primaryOrg
1213
+ };
1214
+ setOrganizations([syntheticOrg]);
1215
+ if (!currentOrgId) {
1216
+ setCurrentOrgId(primaryOrg);
1217
+ try {
1218
+ localStorage.setItem(STORAGE_ORG_KEY, primaryOrg);
1219
+ } catch {
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ } catch {
1225
+ }
1226
+ try {
1227
+ const client = new IamClient({
1228
+ serverUrl: config.serverUrl,
1229
+ clientId: config.clientId
1230
+ });
1231
+ const orgs = await client.getOrganizations(accessToken);
1232
+ if (!cancelled && orgs.length > 0) {
1233
+ setOrganizations(orgs);
1234
+ if (!currentOrgId && orgs.length > 0) {
1235
+ const firstOrg = orgs[0].name;
1236
+ setCurrentOrgId(firstOrg);
1237
+ try {
1238
+ localStorage.setItem(STORAGE_ORG_KEY, firstOrg);
1239
+ } catch {
1240
+ }
1241
+ }
1242
+ }
1243
+ } catch {
1244
+ } finally {
1245
+ if (!cancelled) setIsLoading(false);
1246
+ }
1247
+ };
1248
+ fetchOrgs();
1249
+ return () => {
1250
+ cancelled = true;
1251
+ };
1252
+ }, [isAuthenticated, accessToken, config.serverUrl, config.clientId]);
1253
+ react.useEffect(() => {
1254
+ if (!isAuthenticated || !accessToken || !currentOrgId) {
1255
+ setProjects([]);
1256
+ return;
1257
+ }
1258
+ let cancelled = false;
1259
+ const fetchProjects = async () => {
1260
+ try {
1261
+ const client = new IamClient({
1262
+ serverUrl: config.serverUrl,
1263
+ clientId: config.clientId
1264
+ });
1265
+ const orgProjects = await client.getOrganizationProjects(
1266
+ currentOrgId,
1267
+ accessToken
1268
+ );
1269
+ if (!cancelled) {
1270
+ setProjects(orgProjects);
1271
+ if (!currentProjectId && orgProjects.length > 0) {
1272
+ const defaultProject = orgProjects.find((p) => p.isDefault) ?? orgProjects[0];
1273
+ setCurrentProjectId(defaultProject.name);
1274
+ try {
1275
+ localStorage.setItem(STORAGE_PROJECT_KEY, defaultProject.name);
1276
+ } catch {
1277
+ }
1278
+ }
1279
+ }
1280
+ } catch {
1281
+ if (!cancelled) setProjects([]);
1282
+ }
1283
+ };
1284
+ fetchProjects();
1285
+ return () => {
1286
+ cancelled = true;
1287
+ };
1288
+ }, [isAuthenticated, accessToken, currentOrgId, config.serverUrl, config.clientId]);
1289
+ const currentOrg = react.useMemo(
1290
+ () => organizations.find((o) => o.name === currentOrgId) ?? null,
1291
+ [organizations, currentOrgId]
1292
+ );
1293
+ const currentProject = react.useMemo(
1294
+ () => projects.find((p) => p.name === currentProjectId) ?? null,
1295
+ [projects, currentProjectId]
1296
+ );
1297
+ const switchOrg = react.useCallback((orgId) => {
1298
+ setCurrentOrgId(orgId);
1299
+ setCurrentProjectId(null);
1300
+ setProjects([]);
1301
+ try {
1302
+ localStorage.setItem(STORAGE_ORG_KEY, orgId);
1303
+ localStorage.removeItem(STORAGE_PROJECT_KEY);
1304
+ } catch {
1305
+ }
1306
+ }, []);
1307
+ const switchProject = react.useCallback((projectId) => {
1308
+ setCurrentProjectId(projectId);
1309
+ try {
1310
+ if (projectId) {
1311
+ localStorage.setItem(STORAGE_PROJECT_KEY, projectId);
1312
+ } else {
1313
+ localStorage.removeItem(STORAGE_PROJECT_KEY);
1314
+ }
1315
+ } catch {
1316
+ }
1317
+ }, []);
1318
+ return {
1319
+ organizations,
1320
+ currentOrg,
1321
+ currentOrgId,
1322
+ switchOrg,
1323
+ projects,
1324
+ currentProject,
1325
+ currentProjectId,
1326
+ switchProject,
1327
+ isLoading
1328
+ };
1329
+ }
1330
+ function useIamToken() {
1331
+ const { sdk, accessToken, isAuthenticated } = useIam();
1332
+ const refresh = react.useCallback(async () => {
1333
+ try {
1334
+ return await sdk.getValidAccessToken();
1335
+ } catch {
1336
+ return null;
1337
+ }
1338
+ }, [sdk]);
1339
+ return {
1340
+ token: accessToken,
1341
+ isValid: isAuthenticated && !!accessToken && !sdk.isTokenExpired(),
1342
+ refresh
1343
+ };
1344
+ }
1345
+ function OrgProjectSwitcher({
1346
+ organizations,
1347
+ currentOrgId,
1348
+ switchOrg,
1349
+ projects = [],
1350
+ currentProjectId = null,
1351
+ switchProject,
1352
+ onTenantChange,
1353
+ environment,
1354
+ className = "",
1355
+ alwaysShow = false
1356
+ }) {
1357
+ react.useEffect(() => {
1358
+ onTenantChange?.(currentOrgId, currentProjectId ?? null);
1359
+ }, [currentOrgId, currentProjectId, onTenantChange]);
1360
+ const handleOrgChange = react.useCallback(
1361
+ (e) => switchOrg(e.target.value),
1362
+ [switchOrg]
1363
+ );
1364
+ const handleProjectChange = react.useCallback(
1365
+ (e) => switchProject?.(e.target.value || null),
1366
+ [switchProject]
1367
+ );
1368
+ if (!alwaysShow && organizations.length <= 1 && projects.length <= 1) {
1369
+ if (organizations.length === 1) {
1370
+ const org = organizations[0];
1371
+ return react.createElement(
1372
+ "div",
1373
+ { className: `flex items-center gap-2 text-sm ${className}` },
1374
+ react.createElement("span", { className: "font-medium" }, org.displayName || org.name),
1375
+ projects.length === 1 ? [
1376
+ react.createElement("span", { className: "text-muted-foreground", key: "sep" }, "/"),
1377
+ react.createElement("span", { key: "proj" }, projects[0].displayName || projects[0].name)
1378
+ ] : null,
1379
+ environment ? react.createElement(
1380
+ "span",
1381
+ { className: "rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground" },
1382
+ environment
1383
+ ) : null
1384
+ );
1385
+ }
1386
+ return null;
1387
+ }
1388
+ return react.createElement(
1389
+ "div",
1390
+ { className: `flex items-center gap-2 ${className}` },
1391
+ react.createElement(
1392
+ "select",
1393
+ {
1394
+ value: currentOrgId ?? "",
1395
+ onChange: handleOrgChange,
1396
+ className: "h-8 rounded-md border border-border bg-background px-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-ring",
1397
+ "aria-label": "Switch organization"
1398
+ },
1399
+ ...organizations.map(
1400
+ (org) => react.createElement("option", { key: org.name, value: org.name }, org.displayName || org.name)
1401
+ )
1402
+ ),
1403
+ projects.length > 0 && switchProject ? [
1404
+ react.createElement("span", { className: "text-muted-foreground", key: "sep" }, "/"),
1405
+ react.createElement(
1406
+ "select",
1407
+ {
1408
+ key: "proj-select",
1409
+ value: currentProjectId ?? "",
1410
+ onChange: handleProjectChange,
1411
+ className: "h-8 rounded-md border border-border bg-background px-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-ring",
1412
+ "aria-label": "Switch project"
1413
+ },
1414
+ ...projects.map(
1415
+ (proj) => react.createElement("option", { key: proj.name, value: proj.name }, proj.displayName || proj.name)
1416
+ )
1417
+ )
1418
+ ] : null,
1419
+ environment ? react.createElement(
1420
+ "span",
1421
+ { className: "rounded-full bg-muted px-2 py-0.5 text-xs text-muted-foreground" },
1422
+ environment
1423
+ ) : null
1424
+ );
1425
+ }
1426
+
1427
+ exports.IamContext = IamContext;
1428
+ exports.IamProvider = IamProvider;
1429
+ exports.OrgProjectSwitcher = OrgProjectSwitcher;
1430
+ exports.useIam = useIam;
1431
+ exports.useIamToken = useIamToken;
1432
+ exports.useOrganizations = useOrganizations;
1433
+ //# sourceMappingURL=react.cjs.map
1434
+ //# sourceMappingURL=react.cjs.map