@iqauth/sdk 2.6.3 → 2.7.0

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 (112) hide show
  1. package/README.md +173 -1
  2. package/dist/browser-session.d.mts +4 -4
  3. package/dist/browser-session.d.ts +4 -4
  4. package/dist/browser-session.js +181 -41
  5. package/dist/browser-session.mjs +3 -3
  6. package/dist/browser.d.mts +5 -5
  7. package/dist/browser.d.ts +5 -5
  8. package/dist/browser.js +271 -32
  9. package/dist/browser.mjs +10 -8
  10. package/dist/{chunk-6I6RM4MN.mjs → chunk-6PJRLRB4.mjs} +33 -3
  11. package/dist/chunk-C2ZTBOAC.mjs +36 -0
  12. package/dist/{chunk-LIZYFXH7.mjs → chunk-DFWHSDYQ.mjs} +1 -1
  13. package/dist/chunk-GLXSIGVS.mjs +66 -0
  14. package/dist/{chunk-TKZTCPEK.mjs → chunk-GN37E64I.mjs} +32 -40
  15. package/dist/{chunk-WQWBJSSS.mjs → chunk-HVHNYPDC.mjs} +6 -6
  16. package/dist/{chunk-W3F4JYGP.mjs → chunk-JXQI62A7.mjs} +108 -18
  17. package/dist/{chunk-UNYDG2L4.mjs → chunk-NUO2I65G.mjs} +56 -23
  18. package/dist/chunk-PMAFENVI.mjs +229 -0
  19. package/dist/chunk-RR2MGPTK.mjs +2724 -0
  20. package/dist/{chunk-76W5TLQQ.mjs → chunk-RTJAIBXY.mjs} +220 -20
  21. package/dist/{chunk-6TDJJER7.mjs → chunk-RUJXRTEW.mjs} +164 -5
  22. package/dist/{chunk-3JULWS6F.mjs → chunk-WCELYTJ3.mjs} +3 -3
  23. package/dist/{chunk-MKKZULZR.mjs → chunk-WIFG74IK.mjs} +1 -1
  24. package/dist/{chunk-BVV54LPI.mjs → chunk-YVALAG3B.mjs} +10 -4
  25. package/dist/cli/index.js +2 -2
  26. package/dist/cli/index.mjs +2 -2
  27. package/dist/{client-kYlJFgPv.d.mts → client-BGFnBpfc.d.mts} +47 -4
  28. package/dist/{client-BNQe3AgF.d.ts → client-CDQ21LvW.d.ts} +47 -4
  29. package/dist/{doctor-YYNHNMLD.mjs → doctor-JAFXWU3X.mjs} +2 -2
  30. package/dist/errors-Jl1Jtm-6.d.mts +107 -0
  31. package/dist/errors-Jl1Jtm-6.d.ts +107 -0
  32. package/dist/{express-B6_1vBYZ.d.mts → express-CVNQEkOr.d.mts} +2 -2
  33. package/dist/{express-CHpfa7D_.d.ts → express-Piv2WhWM.d.ts} +2 -2
  34. package/dist/express.d.mts +7 -6
  35. package/dist/express.d.ts +7 -6
  36. package/dist/express.js +349 -52
  37. package/dist/express.mjs +39 -12
  38. package/dist/fastify.d.mts +2 -0
  39. package/dist/fastify.d.ts +2 -0
  40. package/dist/fastify.js +332 -52
  41. package/dist/fastify.mjs +23 -8
  42. package/dist/hono.d.mts +2 -0
  43. package/dist/hono.d.ts +2 -0
  44. package/dist/hono.js +329 -52
  45. package/dist/hono.mjs +20 -8
  46. package/dist/index-5KSZEnDe.d.ts +1626 -0
  47. package/dist/index-CKoZHAoc.d.mts +1626 -0
  48. package/dist/index.d.mts +56 -8
  49. package/dist/index.d.ts +56 -8
  50. package/dist/index.js +565 -69
  51. package/dist/index.mjs +29 -9
  52. package/dist/{keys-NLWFAOEM.mjs → keys-6Y776TG2.mjs} +2 -2
  53. package/dist/locales.d.mts +1 -1
  54. package/dist/locales.d.ts +1 -1
  55. package/dist/mobile.d.mts +77 -7
  56. package/dist/mobile.d.ts +77 -7
  57. package/dist/mobile.js +276 -41
  58. package/dist/mobile.mjs +98 -3
  59. package/dist/next.d.mts +2 -1
  60. package/dist/next.d.ts +2 -1
  61. package/dist/next.js +391 -201
  62. package/dist/next.mjs +22 -7
  63. package/dist/pkce-7WKV4OIN.mjs +11 -0
  64. package/dist/{provisioningBridge-DnTfzdZK.d.ts → provisioningBridge-CGpMRie4.d.ts} +1 -1
  65. package/dist/{provisioningBridge-88xjOS2n.d.mts → provisioningBridge-M5G47LWO.d.mts} +1 -1
  66. package/dist/{publishableKey-BaR0HoAH.d.ts → publishableKey-f2kq-rKw.d.mts} +1 -1
  67. package/dist/{publishableKey-BaR0HoAH.d.mts → publishableKey-f2kq-rKw.d.ts} +1 -1
  68. package/dist/react-permissions.d.mts +52 -0
  69. package/dist/react-permissions.d.ts +52 -0
  70. package/dist/react-permissions.js +239 -0
  71. package/dist/react-permissions.mjs +97 -0
  72. package/dist/react.d.mts +9 -1624
  73. package/dist/react.d.ts +9 -1624
  74. package/dist/react.js +343 -36
  75. package/dist/react.mjs +59 -2611
  76. package/dist/{reverify-4UEJXUS6.mjs → reverify-C64QXKJO.mjs} +2 -2
  77. package/dist/server/handlers.d.mts +148 -3
  78. package/dist/server/handlers.d.ts +148 -3
  79. package/dist/server/handlers.js +410 -11
  80. package/dist/server/handlers.mjs +12 -3
  81. package/dist/server.d.mts +151 -8
  82. package/dist/server.d.ts +151 -8
  83. package/dist/server.js +406 -50
  84. package/dist/server.mjs +93 -11
  85. package/dist/service.d.mts +4 -4
  86. package/dist/service.d.ts +4 -4
  87. package/dist/service.js +181 -41
  88. package/dist/service.mjs +3 -3
  89. package/dist/{signIn-CiIBTJIh.d.mts → signIn-BLFnz8SV.d.ts} +78 -3
  90. package/dist/{signIn-CCY4JE5G.mjs → signIn-SHBW6Z4T.mjs} +2 -1
  91. package/dist/{signIn-OCr88Zf8.d.ts → signIn-T-CZ6t6r.d.mts} +78 -3
  92. package/dist/test.mjs +3 -3
  93. package/dist/{tokens-DCyzzn8L.d.mts → tokens-Bqhmqq_R.d.ts} +9 -2
  94. package/dist/{tokens-aHiGFr_E.d.ts → tokens-CITeoG6P.d.mts} +9 -2
  95. package/dist/{types-6bNdxesb.d.ts → types-BdQ2lqfT.d.mts} +1 -1
  96. package/dist/{types-6bNdxesb.d.mts → types-BdQ2lqfT.d.ts} +1 -1
  97. package/dist/{types-DZAflmmq.d.mts → types-XOV9XPVi.d.mts} +99 -10
  98. package/dist/{types-DZAflmmq.d.ts → types-XOV9XPVi.d.ts} +99 -10
  99. package/dist/webhooks.d.mts +100 -17
  100. package/dist/webhooks.d.ts +100 -17
  101. package/dist/webhooks.js +164 -15
  102. package/dist/webhooks.mjs +7 -1
  103. package/dist/ws.d.mts +2 -2
  104. package/dist/ws.d.ts +2 -2
  105. package/dist/ws.js +80 -30
  106. package/dist/ws.mjs +4 -4
  107. package/docs/error-handling.md +101 -0
  108. package/docs/guides/effective-permissions.md +171 -0
  109. package/package.json +13 -3
  110. package/dist/chunk-UKZLOHZG.mjs +0 -83
  111. package/dist/errors-CDdl24MP.d.mts +0 -52
  112. package/dist/errors-CDdl24MP.d.ts +0 -52
package/dist/react.mjs CHANGED
@@ -1,2616 +1,63 @@
1
1
  import {
2
- AccountRegistry,
3
- MultiAccountTokenStore,
4
- SessionManager,
5
- defaultCookieStore,
6
- enrollPasskey,
7
- linkProvider,
8
- listLinkedIdentities,
9
- requestMagicLink,
10
- signInWithPasskey,
11
- unlinkProvider
12
- } from "./chunk-76W5TLQQ.mjs";
13
- import {
14
- handleAuthCallback,
15
- redirectToSignIn,
16
- signIn,
17
- signOut
18
- } from "./chunk-TKZTCPEK.mjs";
19
- import "./chunk-WQWBJSSS.mjs";
20
- import {
21
- defaultBundle,
22
- localizeErrorCode,
23
- resolveBundle,
24
- t
25
- } from "./chunk-5T7GHBX6.mjs";
26
- import "./chunk-6I6RM4MN.mjs";
2
+ AuthCallback,
3
+ CreateOrganization,
4
+ IQAuthLoaded,
5
+ IQAuthLoading,
6
+ IQAuthProvider,
7
+ IQAuthReturnToBouncer,
8
+ ImpersonationBanner,
9
+ LinkedAccounts,
10
+ MagicLinkSignInForm,
11
+ MultisessionAppSupport,
12
+ OrganizationList,
13
+ OrganizationProfile,
14
+ OrganizationSwitcher,
15
+ PasskeySignInButton,
16
+ Protect,
17
+ RedirectToSignIn,
18
+ RedirectToSignedIn,
19
+ SignIn,
20
+ SignUp,
21
+ SignedIn,
22
+ SignedOut,
23
+ UserButton,
24
+ UserProfile,
25
+ Waitlist,
26
+ __useIQAuthInternal,
27
+ __version__,
28
+ isReturnToAllowed,
29
+ isSilentSsoEligible,
30
+ preflightReturnTo,
31
+ revokeSession,
32
+ sanitizeBrandCss,
33
+ sanitizeReturnTo,
34
+ slugify,
35
+ useAccountList,
36
+ useAccountSwitcher,
37
+ useAuth,
38
+ useAuthFetch,
39
+ useIQAuthSignInContext,
40
+ useImpersonation,
41
+ useLinkedIdentities,
42
+ useLocale,
43
+ useMagicLink,
44
+ useOrganization,
45
+ usePasskey,
46
+ useResolvedSdkBranding,
47
+ useReturnTo,
48
+ useReverification,
49
+ useSession,
50
+ useSessionList,
51
+ useT,
52
+ useUser
53
+ } from "./chunk-RR2MGPTK.mjs";
54
+ import "./chunk-RTJAIBXY.mjs";
55
+ import "./chunk-GN37E64I.mjs";
56
+ import "./chunk-C2ZTBOAC.mjs";
57
+ import "./chunk-HVHNYPDC.mjs";
58
+ import "./chunk-5T7GHBX6.mjs";
59
+ import "./chunk-6PJRLRB4.mjs";
27
60
  import "./chunk-Y6FXYEAI.mjs";
28
-
29
- // src/react/index.tsx
30
- import {
31
- createContext,
32
- createElement,
33
- Fragment,
34
- useCallback,
35
- useContext,
36
- useEffect,
37
- useMemo,
38
- useRef,
39
- useState,
40
- useSyncExternalStore
41
- } from "react";
42
-
43
- // src/browser/returnTo.ts
44
- function normalizeOrigin(o) {
45
- try {
46
- return new URL(o).origin;
47
- } catch {
48
- return o.replace(/\/+$/, "");
49
- }
50
- }
51
- function sanitizeReturnTo(input, options = {}) {
52
- const fallback = options.fallback ?? "/";
53
- if (!input || typeof input !== "string") return fallback;
54
- const trimmed = input.trim();
55
- if (!trimmed) return fallback;
56
- if (trimmed.startsWith("//")) return fallback;
57
- if (trimmed.startsWith("/") || trimmed.startsWith("#") || trimmed.startsWith("?")) {
58
- return trimmed;
59
- }
60
- if (!/^[a-z][a-z0-9+\-.]*:/i.test(trimmed)) {
61
- return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
62
- }
63
- let parsed;
64
- try {
65
- parsed = new URL(trimmed);
66
- } catch {
67
- return fallback;
68
- }
69
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return fallback;
70
- const currentOrigin = options.currentOrigin ?? (typeof window !== "undefined" ? window.location.origin : "");
71
- const allowed = /* @__PURE__ */ new Set();
72
- if (currentOrigin) allowed.add(normalizeOrigin(currentOrigin));
73
- for (const o of options.allowedOrigins ?? []) allowed.add(normalizeOrigin(o));
74
- if (allowed.has(parsed.origin)) return parsed.toString();
75
- return fallback;
76
- }
77
- function isReturnToAllowed(input, options = {}) {
78
- const fallback = options.fallback ?? "/";
79
- const out = sanitizeReturnTo(input, options);
80
- if (!input) return false;
81
- return out !== fallback || input === fallback;
82
- }
83
-
84
- // src/react/index.tsx
85
- import { Fragment as Fragment2, jsx, jsxs } from "react/jsx-runtime";
86
- var globalManager = null;
87
- function setGlobalManager(m) {
88
- globalManager = m;
89
- }
90
- function getGlobalManager() {
91
- return globalManager;
92
- }
93
- var IQAuthContext = createContext(null);
94
- function IQAuthProvider({
95
- publishableKey,
96
- issuer,
97
- channelName,
98
- proactiveRefresh,
99
- manager: externalManager,
100
- allowedReturnOrigins,
101
- appearance,
102
- roleMapper,
103
- cookieNames,
104
- localization,
105
- silentSso,
106
- children
107
- }) {
108
- const managerRef = useRef(null);
109
- if (!managerRef.current) {
110
- managerRef.current = externalManager ?? new SessionManager({
111
- publishableKey,
112
- issuer,
113
- channelName,
114
- proactiveRefresh,
115
- cookieNames
116
- });
117
- setGlobalManager(managerRef.current);
118
- }
119
- const manager = managerRef.current;
120
- const subscribe = useCallback(
121
- (cb) => manager.subscribe(() => cb()),
122
- [manager]
123
- );
124
- const getSnapshot = useCallback(() => manager.getSnapshot(), [manager]);
125
- const getServerSnapshot = useCallback(() => manager.getSnapshot(), [manager]);
126
- const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
127
- useEffect(() => {
128
- void manager.bootstrap();
129
- const onVisible = () => {
130
- if (typeof document !== "undefined" && document.visibilityState === "visible") {
131
- void manager.refresh();
132
- }
133
- };
134
- if (typeof document !== "undefined") {
135
- document.addEventListener("visibilitychange", onVisible);
136
- }
137
- return () => {
138
- if (typeof document !== "undefined") {
139
- document.removeEventListener("visibilitychange", onVisible);
140
- }
141
- };
142
- }, [manager]);
143
- const resolvedLocalization = useMemo(
144
- () => resolveBundle(localization),
145
- [localization]
146
- );
147
- const value = useMemo(
148
- () => ({
149
- manager,
150
- snapshot,
151
- allowedReturnOrigins: allowedReturnOrigins ?? [],
152
- appearance: appearance ?? null,
153
- roleMapper: roleMapper ?? null,
154
- localization: resolvedLocalization,
155
- silentSso: silentSso ?? false
156
- }),
157
- [manager, snapshot, allowedReturnOrigins, appearance, roleMapper, resolvedLocalization, silentSso]
158
- );
159
- return createElement(IQAuthContext.Provider, { value }, children);
160
- }
161
- function useCtx() {
162
- const ctx = useContext(IQAuthContext);
163
- if (!ctx) throw new Error("IQAuth hooks must be used inside <IQAuthProvider>");
164
- return ctx;
165
- }
166
- function useLocale() {
167
- const ctx = useContext(IQAuthContext);
168
- return ctx?.localization ?? defaultBundle;
169
- }
170
- function useT() {
171
- const bundle = useLocale();
172
- return useMemo(
173
- () => (key, vars) => t(bundle, key, vars),
174
- [bundle]
175
- );
176
- }
177
- function localizeError(bundle, raw) {
178
- if (!raw) return t(bundle, "errors.generic");
179
- if (typeof raw === "string") {
180
- if (/^[A-Z][A-Z0-9_]+$/.test(raw)) return localizeErrorCode(bundle, raw);
181
- return raw;
182
- }
183
- if (raw.code) return localizeErrorCode(bundle, raw.code);
184
- return raw.message || t(bundle, "errors.generic");
185
- }
186
- function useUser() {
187
- const { snapshot, roleMapper } = useCtx();
188
- return useMemo(
189
- () => {
190
- const user = snapshot.user ? {
191
- ...snapshot.user,
192
- // F13 — derive `role` via roleMapper, falling back to a sensible default
193
- role: (() => {
194
- if (roleMapper) {
195
- try {
196
- return roleMapper(snapshot.claims);
197
- } catch {
198
- return null;
199
- }
200
- }
201
- const c = snapshot.claims;
202
- if (!c) return null;
203
- if (typeof c.role === "string" && c.role) return c.role;
204
- if (Array.isArray(c.roles) && c.roles.length > 0 && typeof c.roles[0] === "string") return c.roles[0];
205
- return null;
206
- })()
207
- } : null;
208
- return {
209
- isLoaded: snapshot.status !== "loading",
210
- isSignedIn: snapshot.status === "authenticated" && !!snapshot.user,
211
- user,
212
- error: snapshot.error
213
- };
214
- },
215
- [snapshot.status, snapshot.user, snapshot.claims, snapshot.error, snapshot.version, roleMapper]
216
- );
217
- }
218
- function useSession() {
219
- const { snapshot } = useCtx();
220
- return useMemo(
221
- () => ({
222
- isLoaded: snapshot.status !== "loading",
223
- isSignedIn: snapshot.status === "authenticated",
224
- claims: snapshot.claims,
225
- accessToken: snapshot.accessToken,
226
- error: snapshot.error
227
- }),
228
- [snapshot.status, snapshot.claims, snapshot.accessToken, snapshot.error, snapshot.version]
229
- );
230
- }
231
- function useAuth() {
232
- const { manager, snapshot } = useCtx();
233
- return useMemo(
234
- () => ({
235
- isLoaded: snapshot.status !== "loading",
236
- isSignedIn: snapshot.status === "authenticated",
237
- userId: snapshot.user?.sub ?? null,
238
- tenantId: snapshot.tenantId,
239
- error: snapshot.error,
240
- signIn: (opts) => signIn(manager, opts),
241
- signOut: (opts) => signOut(manager, opts),
242
- redirectToSignIn: (opts) => redirectToSignIn(manager, opts),
243
- getToken: () => manager.getToken(),
244
- fetch: (input, init) => manager.fetch(input, init)
245
- }),
246
- [manager, snapshot.status, snapshot.user, snapshot.tenantId, snapshot.error, snapshot.version]
247
- );
248
- }
249
- function useOrganization() {
250
- const { snapshot } = useCtx();
251
- return useMemo(
252
- () => ({
253
- isLoaded: snapshot.status !== "loading",
254
- organization: snapshot.tenantId ? { id: snapshot.tenantId, tenantId: snapshot.tenantId } : null,
255
- error: snapshot.error
256
- }),
257
- [snapshot.status, snapshot.tenantId, snapshot.error, snapshot.version]
258
- );
259
- }
260
- function useAuthFetch() {
261
- const { manager } = useCtx();
262
- return useCallback(
263
- (input, init) => manager.fetch(input, init),
264
- [manager]
265
- );
266
- }
267
- function useSessionList() {
268
- const { manager } = useCtx();
269
- const [sessions, setSessions] = useState([]);
270
- const [loading, setLoading] = useState(true);
271
- const [error, setError] = useState(null);
272
- const base = manager.issuerUrl.replace(/\/$/, "");
273
- const refresh = useCallback(async () => {
274
- setLoading(true);
275
- setError(null);
276
- try {
277
- const res = await manager.fetch(`${base}/api/v1/users/me/sessions`);
278
- const json = await res.json().catch(() => ({}));
279
- if (!res.ok) throw new Error(json?.error?.message || `HTTP ${res.status}`);
280
- setSessions(json?.data?.sessions || []);
281
- } catch (err) {
282
- setError(err.message);
283
- } finally {
284
- setLoading(false);
285
- }
286
- }, [manager, base]);
287
- useEffect(() => {
288
- void refresh();
289
- }, [refresh]);
290
- const revoke = useCallback(async (sessionId) => {
291
- const res = await manager.fetch(`${base}/api/v1/users/me/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });
292
- if (!res.ok) {
293
- const j = await res.json().catch(() => ({}));
294
- throw new Error(j?.error?.message || `HTTP ${res.status}`);
295
- }
296
- setSessions((prev) => prev.filter((s) => s.id !== sessionId));
297
- }, [manager, base]);
298
- const revokeAllOthers = useCallback(async () => {
299
- const res = await manager.fetch(`${base}/api/v1/users/me/sessions/revoke-all-others`, { method: "POST" });
300
- const json = await res.json().catch(() => ({}));
301
- if (!res.ok) throw new Error(json?.error?.message || `HTTP ${res.status}`);
302
- setSessions((prev) => prev.filter((s) => s.isCurrent));
303
- return { terminatedCount: json?.data?.terminatedCount ?? 0 };
304
- }, [manager, base]);
305
- return { sessions, loading, error, refresh, revoke, revokeAllOthers };
306
- }
307
- async function revokeSession(sessionId) {
308
- const mgr = getGlobalManager();
309
- if (!mgr) throw new Error("revokeSession() requires <IQAuthProvider> mounted");
310
- const base = mgr.issuerUrl.replace(/\/$/, "");
311
- const res = await mgr.fetch(`${base}/api/v1/users/me/sessions/${encodeURIComponent(sessionId)}`, { method: "DELETE" });
312
- if (!res.ok) {
313
- const j = await res.json().catch(() => ({}));
314
- throw new Error(j?.error?.message || `HTTP ${res.status}`);
315
- }
316
- }
317
- var MultisessionContext = createContext(null);
318
- function MultisessionAppSupport({ children }) {
319
- const { manager, snapshot } = useCtx();
320
- const registryRef = useRef(null);
321
- if (!registryRef.current) {
322
- registryRef.current = new AccountRegistry(manager.appKey);
323
- }
324
- const registry = registryRef.current;
325
- const [version, setVersion] = useState(0);
326
- useEffect(() => {
327
- const store = new MultiAccountTokenStore(registry, defaultCookieStore());
328
- manager.setTokenStore(store);
329
- const unsub = registry.subscribe(() => setVersion((v) => v + 1));
330
- return () => {
331
- unsub();
332
- registry.destroy();
333
- };
334
- }, [manager]);
335
- useEffect(() => {
336
- if (snapshot.status !== "authenticated" || !snapshot.user) return;
337
- const claims = snapshot.claims;
338
- const rec = {
339
- accountId: snapshot.user.sub,
340
- userId: snapshot.user.sub,
341
- email: snapshot.user.email,
342
- name: snapshot.user.name,
343
- tenantId: snapshot.tenantId ?? claims?.tenantId ?? null,
344
- addedAt: Date.now()
345
- };
346
- registry.upsert(rec);
347
- if (registry.active() !== rec.accountId) {
348
- registry.setActive(rec.accountId);
349
- }
350
- }, [snapshot.user?.sub, snapshot.tenantId, snapshot.status]);
351
- const value = useMemo(
352
- () => ({ registry, version }),
353
- [registry, version]
354
- );
355
- return createElement(MultisessionContext.Provider, { value }, children);
356
- }
357
- function useMultiCtx() {
358
- const ctx = useContext(MultisessionContext);
359
- if (!ctx) throw new Error("F22 hooks must be used inside <MultisessionAppSupport>");
360
- return ctx;
361
- }
362
- function useAccountList() {
363
- const { registry, version } = useMultiCtx();
364
- const { isLoaded } = useUser();
365
- const accounts = useMemo(() => {
366
- const active = registry.active();
367
- return registry.list().map((a) => ({
368
- accountId: a.accountId,
369
- userId: a.userId,
370
- email: a.email,
371
- name: a.name,
372
- tenantId: a.tenantId,
373
- isActive: a.accountId === active
374
- }));
375
- }, [registry, version]);
376
- return { accounts, loading: !isLoaded };
377
- }
378
- function useAccountSwitcher() {
379
- const { manager } = useCtx();
380
- const { registry } = useMultiCtx();
381
- const addAccount = useCallback(
382
- async (opts = {}) => {
383
- registry.setActive(null);
384
- await signIn(manager, { ...opts, prompt: "login" });
385
- },
386
- [manager, registry]
387
- );
388
- const switchTo = useCallback(
389
- async (accountId) => {
390
- const target = registry.get(accountId);
391
- if (!target) throw new Error(`Unknown accountId: ${accountId}`);
392
- registry.setActive(accountId);
393
- const ok = await manager.refresh();
394
- if (!ok) {
395
- registry.remove(accountId);
396
- throw new Error("Could not switch account; session may have been revoked");
397
- }
398
- },
399
- [manager, registry]
400
- );
401
- const removeAccount = useCallback(
402
- (accountId) => {
403
- registry.remove(accountId);
404
- },
405
- [registry]
406
- );
407
- return { addAccount, switchTo, removeAccount };
408
- }
409
- function SignedIn({ children }) {
410
- const { isSignedIn, isLoaded } = useUser();
411
- if (!isLoaded || !isSignedIn) return null;
412
- return createElement(Fragment, null, children);
413
- }
414
- function SignedOut({ children }) {
415
- const { isSignedIn, isLoaded } = useUser();
416
- if (!isLoaded || isSignedIn) return null;
417
- return createElement(Fragment, null, children);
418
- }
419
- function IQAuthLoading({ children }) {
420
- const { isLoaded } = useAuth();
421
- if (isLoaded) return null;
422
- return createElement(Fragment, null, children);
423
- }
424
- function IQAuthLoaded({ children }) {
425
- const { isLoaded } = useAuth();
426
- if (!isLoaded) return null;
427
- return createElement(Fragment, null, children);
428
- }
429
- function RedirectToSignIn(props = {}) {
430
- const { manager, snapshot } = useCtx();
431
- const [error, setError] = useState(null);
432
- useEffect(() => {
433
- if (snapshot.status === "unauthenticated") {
434
- redirectToSignIn(manager, props).catch((err) => {
435
- const message = err instanceof Error ? err.message : String(err);
436
- console.error("[IQAuth] RedirectToSignIn failed:", err, {
437
- issuer: manager.issuerUrl,
438
- appKey: manager.appKey
439
- });
440
- setError(message);
441
- });
442
- }
443
- }, [manager, snapshot.status]);
444
- if (error) {
445
- return createElement(
446
- "div",
447
- {
448
- role: "alert",
449
- style: {
450
- maxWidth: 520,
451
- margin: "48px auto",
452
- padding: 16,
453
- border: "1px solid #f0c0c0",
454
- background: "#fff5f5",
455
- borderRadius: 8,
456
- fontFamily: "system-ui, sans-serif",
457
- fontSize: 14,
458
- color: "#7a1f1f"
459
- }
460
- },
461
- createElement("strong", null, "IQAuth: sign-in redirect failed"),
462
- createElement("div", { style: { marginTop: 8, fontSize: 13 } }, error),
463
- createElement(
464
- "div",
465
- { style: { marginTop: 12, fontSize: 12, color: "#5a4a4a" } },
466
- `Issuer: ${manager.issuerUrl} \xB7 App: ${manager.appKey}. Check browser console for details.`
467
- )
468
- );
469
- }
470
- return null;
471
- }
472
- function asArray(v) {
473
- if (v == null) return [];
474
- return Array.isArray(v) ? v : [v];
475
- }
476
- function claimRoles(c) {
477
- if (!c) return [];
478
- const x = c;
479
- if (Array.isArray(x.roles)) return x.roles.filter((r) => typeof r === "string");
480
- if (typeof x.role === "string") return [x.role];
481
- return [];
482
- }
483
- function claimPermissions(c) {
484
- if (!c) return [];
485
- const x = c;
486
- const out = /* @__PURE__ */ new Set();
487
- if (Array.isArray(x.permissions)) {
488
- for (const p of x.permissions) if (typeof p === "string") out.add(p);
489
- }
490
- if (Array.isArray(x.entitlements)) {
491
- for (const p of x.entitlements) if (typeof p === "string") out.add(p);
492
- }
493
- if (typeof x.scope === "string") {
494
- for (const s of x.scope.split(/\s+/)) if (s) out.add(s);
495
- }
496
- return Array.from(out);
497
- }
498
- function Protect({ role, permission, condition, fallback = null, children }) {
499
- const { snapshot } = useCtx();
500
- if (snapshot.status !== "authenticated") return createElement(Fragment, null, fallback);
501
- const wantedRoles = asArray(role);
502
- const wantedPerms = asArray(permission);
503
- if (wantedRoles.length) {
504
- const have = new Set(claimRoles(snapshot.claims));
505
- if (!wantedRoles.some((r) => have.has(r))) return createElement(Fragment, null, fallback);
506
- }
507
- if (wantedPerms.length) {
508
- const have = new Set(claimPermissions(snapshot.claims));
509
- if (!wantedPerms.some((p) => have.has(p))) return createElement(Fragment, null, fallback);
510
- }
511
- if (condition && !condition(snapshot.claims)) return createElement(Fragment, null, fallback);
512
- return createElement(Fragment, null, children);
513
- }
514
- function RedirectToSignedIn({ to = "/", replace = true } = {}) {
515
- const { snapshot, allowedReturnOrigins } = useCtx();
516
- useEffect(() => {
517
- if (snapshot.status !== "authenticated") return;
518
- if (typeof window === "undefined") return;
519
- const safe = sanitizeReturnTo(to, { allowedOrigins: allowedReturnOrigins, fallback: "/" });
520
- if (replace) window.location.replace(safe);
521
- else window.location.assign(safe);
522
- }, [snapshot.status, to, replace, allowedReturnOrigins]);
523
- return null;
524
- }
525
- function useReturnTo(options = {}) {
526
- const { allowedReturnOrigins } = useCtx();
527
- const paramName = options.paramName ?? "return_to";
528
- const storageKey = options.storageKey ?? "iqauth_return_to";
529
- const fallback = options.fallback ?? "/";
530
- return useMemo(() => {
531
- if (typeof window === "undefined") return fallback;
532
- let raw = null;
533
- try {
534
- const params = new URLSearchParams(window.location.search);
535
- raw = params.get(paramName) || params.get("next");
536
- } catch {
537
- }
538
- if (!raw) {
539
- try {
540
- raw = window.sessionStorage.getItem(storageKey);
541
- } catch {
542
- }
543
- }
544
- const safe = sanitizeReturnTo(raw, { allowedOrigins: allowedReturnOrigins, fallback });
545
- if (safe !== fallback) {
546
- try {
547
- window.sessionStorage.setItem(storageKey, safe);
548
- } catch {
549
- }
550
- }
551
- return safe;
552
- }, [paramName, storageKey, fallback, allowedReturnOrigins]);
553
- }
554
- function IQAuthReturnToBouncer({ children, ...opts }) {
555
- const { snapshot } = useCtx();
556
- const returnTo = useReturnTo(opts);
557
- useEffect(() => {
558
- if (snapshot.status !== "authenticated") return;
559
- if (typeof window === "undefined") return;
560
- window.location.replace(returnTo);
561
- }, [snapshot.status, returnTo]);
562
- if (snapshot.status === "authenticated") return null;
563
- return createElement(Fragment, null, children);
564
- }
565
- async function preflightReturnTo(args) {
566
- const f = args.fetchImpl ?? fetch;
567
- const url = `${args.iqAuthBaseUrl.replace(/\/$/, "")}/api/public/apps/${encodeURIComponent(args.appKey)}/sign-in-context?return_to=${encodeURIComponent(args.returnTo)}`;
568
- try {
569
- const r = await f(url, { credentials: "include" });
570
- const body = await r.json().catch(() => null);
571
- if (!r.ok || !body?.success || !body.data) {
572
- return { ok: false, allowedOrigins: [], reason: body?.error?.message || `HTTP ${r.status}` };
573
- }
574
- return { ok: !!body.data.returnAllowed, allowedOrigins: body.data.allowedOrigins ?? [], reason: body.data.returnAllowed ? void 0 : "returnTo not in app allowedOrigins" };
575
- } catch (err) {
576
- return { ok: false, allowedOrigins: [], reason: err.message };
577
- }
578
- }
579
- function AuthCallback({ onComplete, fallback } = {}) {
580
- const { manager } = useCtx();
581
- useEffect(() => {
582
- let cancelled = false;
583
- void handleAuthCallback(manager).then((result) => {
584
- if (cancelled) return;
585
- if (onComplete) onComplete(result);
586
- else if (typeof window !== "undefined") {
587
- window.location.replace(result.returnTo || "/");
588
- }
589
- });
590
- return () => {
591
- cancelled = true;
592
- };
593
- }, [manager, onComplete]);
594
- return createElement(Fragment, null, fallback ?? null);
595
- }
596
- function brandStyle(branding) {
597
- if (!branding) return {};
598
- const s = {};
599
- if (branding.primaryColor) s["--brand-primary"] = branding.primaryColor;
600
- if (branding.accentColor) s["--brand-accent"] = branding.accentColor;
601
- if (branding.backgroundColor) s["--brand-bg"] = branding.backgroundColor;
602
- if (branding.surfaceColor) s["--brand-surface"] = branding.surfaceColor;
603
- if (branding.textColor) s["--brand-text"] = branding.textColor;
604
- if (branding.borderRadius != null && branding.borderRadius !== "") {
605
- const n = typeof branding.borderRadius === "number" ? `${branding.borderRadius}px` : String(branding.borderRadius);
606
- s["--brand-radius"] = n;
607
- }
608
- if (branding.fontFamilyBody) s["--brand-font-body"] = branding.fontFamilyBody;
609
- if (branding.fontFamilyHeading) s["--brand-font-heading"] = branding.fontFamilyHeading;
610
- return s;
611
- }
612
- async function jsonFetch(url, init) {
613
- const res = await fetch(url, { ...init, credentials: init?.credentials || "include" });
614
- const payload = await res.json().catch(() => ({}));
615
- if (!res.ok && payload?.success !== true) {
616
- const message = payload?.error?.message || payload?.error_description || payload?.error || `HTTP ${res.status}`;
617
- throw new Error(typeof message === "string" ? message : "Request failed");
618
- }
619
- return payload;
620
- }
621
- function useIQAuthSignInContext(iqAuthBaseUrl, appKey, returnTo) {
622
- const [ctx, setCtx] = useState(null);
623
- const [loading, setLoading] = useState(true);
624
- const [error, setError] = useState(null);
625
- useEffect(() => {
626
- if (!appKey) {
627
- setLoading(false);
628
- setError("appKey is required");
629
- return;
630
- }
631
- let cancelled = false;
632
- setLoading(true);
633
- const url = `${iqAuthBaseUrl.replace(/\/$/, "")}/api/public/apps/${encodeURIComponent(appKey)}/sign-in-context?return_to=${encodeURIComponent(returnTo)}`;
634
- fetch(url, { credentials: "include" }).then(async (r) => {
635
- const contentType = r.headers.get("content-type") || "";
636
- if (!r.ok || !contentType.includes("json")) {
637
- const bodyPreview = await r.text().then((t2) => t2.slice(0, 160)).catch(() => "");
638
- console.error(
639
- `[IQAuth] sign-in-context request failed: ${r.status} ${r.statusText} (content-type: ${contentType || "\u2014"}). URL: ${url}. Common causes: (1) iqAuthBaseUrl points at the wrong host (it should be your IQAuth issuer, e.g. https://auth.dispositioniq.com \u2014 NOT your own app's domain); (2) the app key "${appKey}" is wrong or revoked; (3) CORS preflight is blocked because this origin isn't in the app's allowed-origins list. Response body preview: ${bodyPreview}`
640
- );
641
- throw new Error(
642
- r.status >= 500 ? "Failed to load sign-in context (server error)" : `Failed to load sign-in context (HTTP ${r.status})`
643
- );
644
- }
645
- return r.json();
646
- }).then((payload) => {
647
- if (cancelled) return;
648
- if (payload?.success === false) throw new Error(payload?.error?.message || "Failed to load sign-in context");
649
- setCtx(payload.data);
650
- }).catch((err) => {
651
- if (!cancelled) setError(err.message);
652
- }).finally(() => {
653
- if (!cancelled) setLoading(false);
654
- });
655
- return () => {
656
- cancelled = true;
657
- };
658
- }, [iqAuthBaseUrl, appKey, returnTo]);
659
- return { ctx, loading, error };
660
- }
661
- var SHELL_CSS = `
662
- .iqauth-sdk-shell {
663
- min-height: 100vh;
664
- width: 100%;
665
- display: grid;
666
- grid-template-columns: 1fr;
667
- background: var(--brand-bg, #f7f7f6);
668
- color: var(--brand-text, #0f172a);
669
- /* Container queries so the two-pane layout responds to the SDK's
670
- RENDERED width, not the viewport. This keeps the form usable when
671
- a host app embeds <SignIn/> inside a narrower card or sidebar
672
- instead of full-screen \u2014 the previous viewport @media query would
673
- happily render the side-by-side hero+form into a 200px container
674
- and wrap text one character per line. */
675
- container-type: inline-size;
676
- container-name: iqauth-sdk;
677
- }
678
- .iqauth-sdk-hero { display: none; }
679
- .iqauth-sdk-pane {
680
- display: flex; flex-direction: column; align-items: center; justify-content: center;
681
- padding: 32px 20px;
682
- /* 2.6.1 \u2014 Default to natural height so embedded usage (inside a card,
683
- modal, or sidebar) sizes to its content instead of forcing a full
684
- viewport. The hosted/full-page layout re-introduces 100vh below the
685
- 768px container-query threshold for the side-by-side hero variant. */
686
- min-height: auto;
687
- box-sizing: border-box;
688
- }
689
- .iqauth-sdk-card {
690
- width: 100%; max-width: 480px;
691
- background: var(--brand-surface, #ffffff);
692
- border: 1px solid rgba(15,23,42,0.08);
693
- border-radius: var(--brand-radius, 16px);
694
- box-shadow: 0 1px 2px rgba(0,0,0,0.04), 0 12px 32px rgba(15,23,42,0.06);
695
- overflow: hidden;
696
- }
697
- .iqauth-sdk-shell, .iqauth-sdk-shell input, .iqauth-sdk-shell button { font-family: var(--brand-font-body, inherit); }
698
- .iqauth-sdk-shell h1, .iqauth-sdk-shell h2, .iqauth-sdk-shell h3 { font-family: var(--brand-font-heading, var(--brand-font-body, inherit)); }
699
- .iqauth-sdk-shell[data-layout="centered_card"] { grid-template-columns: 1fr; }
700
- .iqauth-sdk-shell[data-layout="centered_card"] .iqauth-sdk-hero { display: none; }
701
- .iqauth-sdk-shell[data-layout="full_bleed"] { background-size: cover; background-position: center; background-repeat: no-repeat; }
702
- .iqauth-sdk-shell[data-layout="full_bleed"] .iqauth-sdk-hero { display: none; }
703
- .iqauth-sdk-shell[data-layout="full_bleed"] .iqauth-sdk-pane { background: rgba(15,23,42,0.30); }
704
- .iqauth-sdk-shell[data-social-style="outline"] .iqauth-sdk-google-btn { background: transparent; border-color: var(--brand-primary, rgba(15,23,42,0.18)); color: var(--brand-text, inherit); }
705
- .iqauth-sdk-shell[data-social-style="ghost"] .iqauth-sdk-google-btn { background: transparent; border-color: transparent; color: var(--brand-text, inherit); }
706
- .iqauth-sdk-shell[data-social-style="solid"] .iqauth-sdk-google-btn { background: var(--brand-primary, #3b82f6); border-color: transparent; color: #fff; }
707
- .iqauth-sdk-shell[data-social-style="solid"] .iqauth-sdk-google-btn:hover { background: var(--brand-primary, #3b82f6); opacity: 0.92; }
708
- .iqauth-sdk-card-header { padding: 32px 36px 0; }
709
- .iqauth-sdk-card-header h1 { font-size: 24px; font-weight: 600; margin: 0; line-height: 1.2; letter-spacing: -0.01em; }
710
- .iqauth-sdk-card-header p { margin: 8px 0 0; font-size: 14px; color: rgba(15,23,42,0.65); line-height: 1.5; }
711
- .iqauth-sdk-card-body { padding: 32px 36px 28px; display: flex; flex-direction: column; gap: 18px; }
712
- .iqauth-sdk-mobile-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 20px; }
713
- .iqauth-sdk-mobile-brand img { height: 36px; width: auto; }
714
- .iqauth-sdk-mobile-brand span { font-size: 16px; font-weight: 600; }
715
- .iqauth-sdk-footer { margin-top: 20px; text-align: center; font-size: 13px; color: rgba(15,23,42,0.55); display: flex; flex-direction: column; gap: 8px; align-items: center; }
716
- .iqauth-sdk-footer-links { display: flex; gap: 14px; flex-wrap: wrap; justify-content: center; }
717
- .iqauth-sdk-footer-links a { color: inherit; opacity: 0.75; text-decoration: none; }
718
- .iqauth-sdk-footer-links a:hover { opacity: 1; text-decoration: underline; }
719
- .iqauth-sdk-divider { display: flex; align-items: center; gap: 10px; font-size: 12px; color: rgba(15,23,42,0.45); text-transform: uppercase; letter-spacing: 0.08em; }
720
- .iqauth-sdk-divider::before, .iqauth-sdk-divider::after { content: ""; flex: 1; height: 1px; background: rgba(15,23,42,0.1); }
721
- .iqauth-sdk-google-btn {
722
- display: inline-flex; align-items: center; justify-content: center; gap: 10px;
723
- width: 100%; padding: 10px 16px; border-radius: 8px;
724
- background: #fff; color: #0f172a;
725
- border: 1px solid rgba(15,23,42,0.18);
726
- font-size: 14px; font-weight: 500; cursor: pointer;
727
- transition: background 120ms ease, border-color 120ms ease;
728
- }
729
- .iqauth-sdk-google-btn:hover { background: #f8fafc; border-color: rgba(15,23,42,0.28); }
730
- .iqauth-sdk-google-btn[disabled] { opacity: 0.6; cursor: not-allowed; }
731
-
732
- @container iqauth-sdk (min-width: 768px) {
733
- .iqauth-sdk-shell:not([data-layout="centered_card"]):not([data-layout="full_bleed"]) { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
734
- /* 2.6.1 \u2014 Restore 100vh ONLY for the wide side-by-side layout where
735
- hero+pane need height parity. Embedded narrow uses keep natural height. */
736
- .iqauth-sdk-pane { padding: 48px 24px; min-height: 100vh; }
737
- /* 2.6.2 \u2014 Let the card breathe on desktop. The 480px mobile cap looks
738
- phone-sized on a 720px+ pane; bump to 540px and grow the inner padding
739
- so the form fills its half of the split layout. */
740
- .iqauth-sdk-card { max-width: 540px; }
741
- .iqauth-sdk-card-header { padding: 40px 44px 0; }
742
- .iqauth-sdk-card-body { padding: 32px 44px 32px; }
743
- .iqauth-sdk-card-header h1 { font-size: 26px; }
744
- .iqauth-sdk-hero {
745
- display: flex; flex-direction: column; justify-content: space-between;
746
- padding: clamp(32px, 4vw, 56px); color: #ffffff;
747
- background: linear-gradient(135deg, var(--brand-primary, #3b82f6) 0%, var(--brand-accent, #6366f1) 100%);
748
- background-size: cover; background-position: center;
749
- position: relative; overflow: hidden; min-height: 100vh;
750
- }
751
- .iqauth-sdk-hero[data-bg-image="true"] {
752
- background-image: var(--iqauth-sdk-hero-image), linear-gradient(135deg, var(--brand-primary, #3b82f6), var(--brand-accent, #6366f1));
753
- background-blend-mode: multiply;
754
- }
755
- .iqauth-sdk-hero-brand img { height: 40px; width: auto; filter: brightness(0) invert(1); opacity: 0.96; }
756
- .iqauth-sdk-hero-brand .iqauth-sdk-hero-name { font-size: 20px; font-weight: 600; letter-spacing: -0.01em; }
757
- .iqauth-sdk-hero-content { max-width: 520px; }
758
- .iqauth-sdk-hero-content h2 { font-size: clamp(24px, 2.4vw, 34px); font-weight: 600; line-height: 1.2; margin: 0 0 14px; letter-spacing: -0.015em; word-wrap: break-word; overflow-wrap: break-word; hyphens: auto; }
759
- .iqauth-sdk-hero-content p { font-size: 15px; line-height: 1.6; opacity: 0.92; margin: 0; white-space: pre-wrap; }
760
- .iqauth-sdk-hero-foot { font-size: 12px; opacity: 0.7; }
761
- .iqauth-sdk-mobile-brand { display: none; }
762
- }
763
- @container iqauth-sdk (min-width: 1280px) {
764
- .iqauth-sdk-shell:not([data-layout="centered_card"]):not([data-layout="full_bleed"]) { grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); }
765
- /* 2.6.2 \u2014 Extra-wide screens: card grows once more so the form keeps
766
- pace with the hero pane on 1440px+ monitors. */
767
- .iqauth-sdk-card { max-width: 580px; }
768
- }
769
- `;
770
- var sdkShellStylesInjected = false;
771
- var SDK_CSS_MAX_LEN = 50 * 1024;
772
- var SDK_CSS_FORBIDDEN = [
773
- /<\/?\s*style[^>]*>/gi,
774
- /<\/?\s*script[^>]*>/gi,
775
- /<!--[\s\S]*?-->/g,
776
- /@import\s+[^;]*;?/gi,
777
- /expression\s*\(/gi,
778
- /behavior\s*:/gi,
779
- /-moz-binding\s*:/gi,
780
- /javascript\s*:/gi,
781
- /vbscript\s*:/gi
782
- ];
783
- var SDK_URL_DATA_RE = /url\s*\(\s*(['"]?)\s*data\s*:[^)]*\)/gi;
784
- function sanitizeBrandCss(input) {
785
- if (!input) return "";
786
- let out = String(input);
787
- if (out.length > SDK_CSS_MAX_LEN) out = out.slice(0, SDK_CSS_MAX_LEN);
788
- out = out.replace(/</g, "");
789
- for (const re of SDK_CSS_FORBIDDEN) out = out.replace(re, "");
790
- out = out.replace(SDK_URL_DATA_RE, "url()");
791
- return out;
792
- }
793
- function SdkBrandLogo({ branding, alt, fallback }) {
794
- const light = branding?.logoLightUrl || branding?.logoUrl || null;
795
- const dark = branding?.logoDarkUrl || null;
796
- if (!light && !dark) return /* @__PURE__ */ jsx(Fragment2, { children: fallback });
797
- const fallbackSrc = light || dark;
798
- return /* @__PURE__ */ jsxs("picture", { "data-iqauth-sdk-logo": "", children: [
799
- dark ? /* @__PURE__ */ jsx("source", { srcSet: dark, media: "(prefers-color-scheme: dark)" }) : null,
800
- light ? /* @__PURE__ */ jsx("source", { srcSet: light, media: "(prefers-color-scheme: light)" }) : null,
801
- /* @__PURE__ */ jsx("img", { src: fallbackSrc, alt })
802
- ] });
803
- }
804
- var sdkBrandingCache = /* @__PURE__ */ new Map();
805
- var SDK_BRANDING_TTL_MS = 6e4;
806
- function flattenBrandingPayload(data) {
807
- const e = data && data.effective || {};
808
- const meta = data && data.meta || {};
809
- return {
810
- brandName: e.brandName ?? data?.brandName ?? null,
811
- logoUrl: e.logoLightUrl ?? data?.logoUrl ?? null,
812
- logoLightUrl: e.logoLightUrl ?? data?.logoLightUrl ?? null,
813
- logoDarkUrl: e.logoDarkUrl ?? data?.logoDarkUrl ?? null,
814
- faviconUrl: e.faviconUrl ?? data?.faviconUrl ?? null,
815
- primaryColor: e.primaryColor ?? data?.primaryColor ?? null,
816
- accentColor: e.accentColor ?? data?.accentColor ?? null,
817
- backgroundColor: e.backgroundColor ?? data?.backgroundColor ?? null,
818
- surfaceColor: e.surfaceColor ?? data?.surfaceColor ?? null,
819
- textColor: e.textColor ?? data?.textColor ?? null,
820
- fontFamilyBody: e.fontFamilyBody ?? data?.fontFamilyBody ?? null,
821
- fontFamilyHeading: e.fontFamilyHeading ?? data?.fontFamilyHeading ?? null,
822
- customFontUrl: e.customFontUrl ?? data?.customFontUrl ?? null,
823
- borderRadius: e.borderRadius ?? data?.borderRadius ?? null,
824
- backgroundImageUrl: e.backgroundImageUrl ?? data?.backgroundImageUrl ?? null,
825
- customCss: e.customCss ?? data?.customCss ?? null,
826
- loginLayout: e.loginLayout ?? data?.loginLayout ?? null,
827
- socialButtonStyle: e.socialButtonStyle ?? data?.socialButtonStyle ?? null,
828
- footerText: e.footerText ?? data?.footerText ?? null,
829
- brandingRev: meta.brandingRev ?? data?.brandingRev ?? null
830
- };
831
- }
832
- function useResolvedSdkBranding(iqAuthBaseUrl, appId) {
833
- const ctx = useContext(IQAuthContext);
834
- const resolvedAppId = appId ?? ctx?.manager?.appKey ?? null;
835
- const url = `${iqAuthBaseUrl.replace(/\/$/, "")}/api/public/branding${resolvedAppId ? `?appId=${encodeURIComponent(resolvedAppId)}` : ""}`;
836
- const cached = sdkBrandingCache.get(url);
837
- const fresh = cached && Date.now() - cached.ts < SDK_BRANDING_TTL_MS ? cached.data : null;
838
- const [b, setB] = useState(fresh);
839
- useEffect(() => {
840
- let cancelled = false;
841
- const entry = sdkBrandingCache.get(url);
842
- const headers = {};
843
- if (entry?.rev) headers["If-None-Match"] = `W/"brand-${entry.rev}"`;
844
- if (entry) setB(entry.data);
845
- fetch(url, { credentials: "include", headers }).then(async (r) => {
846
- if (cancelled) return;
847
- if (r.status === 304 && entry) {
848
- sdkBrandingCache.set(url, { ...entry, ts: Date.now() });
849
- return;
850
- }
851
- if (!r.ok) return;
852
- const p = await r.json().catch(() => null);
853
- if (!p?.data) return;
854
- const flat = flattenBrandingPayload(p.data);
855
- sdkBrandingCache.set(url, { ts: Date.now(), rev: flat.brandingRev || "", data: flat });
856
- setB(flat);
857
- }).catch(() => {
858
- });
859
- return () => {
860
- cancelled = true;
861
- };
862
- }, [url]);
863
- return b;
864
- }
865
- function ensureSdkShellStyles() {
866
- if (typeof document === "undefined" || sdkShellStylesInjected) return;
867
- const tag = document.createElement("style");
868
- tag.setAttribute("data-iqauth-sdk-shell", "");
869
- tag.textContent = SHELL_CSS;
870
- document.head.appendChild(tag);
871
- sdkShellStylesInjected = true;
872
- }
873
- function useDocumentBranding(branding, fallbackTitle) {
874
- useEffect(() => {
875
- if (typeof document === "undefined") return;
876
- const prevTitle = document.title;
877
- const brandName = branding?.brandName || "IQAuth";
878
- document.title = `${fallbackTitle} \xB7 ${brandName}`;
879
- let linkEl = null;
880
- let prevHref = null;
881
- if (branding?.faviconUrl) {
882
- linkEl = document.querySelector("link[rel='icon']");
883
- if (!linkEl) {
884
- linkEl = document.createElement("link");
885
- linkEl.rel = "icon";
886
- document.head.appendChild(linkEl);
887
- } else {
888
- prevHref = linkEl.href;
889
- }
890
- linkEl.href = branding.faviconUrl;
891
- }
892
- return () => {
893
- document.title = prevTitle;
894
- if (linkEl && prevHref !== null) linkEl.href = prevHref;
895
- };
896
- }, [branding?.brandName, branding?.faviconUrl, fallbackTitle]);
897
- }
898
- function Shell({
899
- branding,
900
- className,
901
- children,
902
- title,
903
- subtitle,
904
- appearance
905
- }) {
906
- ensureSdkShellStyles();
907
- const t2 = useT();
908
- useDocumentBranding(branding, title || t2("signIn.title"));
909
- const brandVars = brandStyle(branding);
910
- const brandName = branding?.brandName || "IQAuth";
911
- const heroImage = branding?.heroImageUrl || null;
912
- const layout = (branding?.loginLayout || "split_screen").toString();
913
- const bgImage = branding?.backgroundImageUrl || null;
914
- const fontUrl = branding?.customFontUrl || null;
915
- const socialStyle = (branding?.socialButtonStyle || "").toString();
916
- const heroStyle = heroImage ? { ["--iqauth-sdk-hero-image"]: `url("${heroImage.replace(/"/g, '\\"')}")` } : {};
917
- const shellStyle = {
918
- ...brandVars,
919
- ...layout === "full_bleed" && bgImage ? { backgroundImage: `linear-gradient(rgba(15,23,42,0.35), rgba(15,23,42,0.45)), url("${bgImage.replace(/"/g, '\\"')}")` } : {},
920
- ...appearance?.elements?.rootBox?.style || {}
921
- };
922
- const ap = appearance?.elements;
923
- const supportLink = branding?.supportUrl ? branding.supportUrl : branding?.supportEmail ? `mailto:${branding.supportEmail}` : null;
924
- const hasFooterLinks = !!(branding?.termsUrl || branding?.privacyUrl || supportLink);
925
- return /* @__PURE__ */ jsxs(
926
- "div",
927
- {
928
- className: `iqauth-sdk-shell${className ? ` ${className}` : ""}${ap?.rootBox?.className ? ` ${ap.rootBox.className}` : ""}`,
929
- "data-layout": layout,
930
- "data-social-style": socialStyle || void 0,
931
- style: shellStyle,
932
- "data-iqauth-shell": "",
933
- "data-branding-rev": branding?.brandingRev || "",
934
- children: [
935
- /* @__PURE__ */ jsx("style", { "data-brand": true, children: [
936
- fontUrl ? `@font-face{font-family:"${(branding?.fontFamilyBody || "Brand").replace(/"/g, "")}";src:url("${fontUrl.replace(/"/g, '\\"')}");font-display:swap;}` : "",
937
- sanitizeBrandCss(branding?.customCss)
938
- ].filter(Boolean).join("\n") }),
939
- /* @__PURE__ */ jsxs("aside", { className: "iqauth-sdk-hero", "data-bg-image": heroImage ? "true" : "false", style: heroStyle, "aria-hidden": "true", children: [
940
- /* @__PURE__ */ jsx("div", { className: "iqauth-sdk-hero-brand", style: { display: "flex", alignItems: "center", gap: 12 }, children: /* @__PURE__ */ jsx(SdkBrandLogo, { branding, alt: "", fallback: /* @__PURE__ */ jsx("span", { className: "iqauth-sdk-hero-name", children: brandName }) }) }),
941
- /* @__PURE__ */ jsxs("div", { className: "iqauth-sdk-hero-content", children: [
942
- /* @__PURE__ */ jsx("h2", { children: branding?.tagline || `Welcome to ${brandName}` }),
943
- /* @__PURE__ */ jsx("p", { children: branding?.loginSideCopy || branding?.loginSubheadline || `Sign in to continue to your ${brandName} workspace.` })
944
- ] }),
945
- /* @__PURE__ */ jsx("div", { className: "iqauth-sdk-hero-foot", children: `\xA9 ${(/* @__PURE__ */ new Date()).getFullYear()} ${brandName}` })
946
- ] }),
947
- /* @__PURE__ */ jsx("div", { className: "iqauth-sdk-pane", children: /* @__PURE__ */ jsxs("main", { style: { width: "100%", maxWidth: 420 }, children: [
948
- /* @__PURE__ */ jsx("div", { className: "iqauth-sdk-mobile-brand", children: /* @__PURE__ */ jsx(SdkBrandLogo, { branding, alt: `${brandName} logo`, fallback: /* @__PURE__ */ jsx("span", { children: brandName }) }) }),
949
- /* @__PURE__ */ jsxs(
950
- "section",
951
- {
952
- className: `iqauth-sdk-card${ap?.card?.className ? ` ${ap.card.className}` : ""}`,
953
- style: ap?.card?.style,
954
- children: [
955
- title || subtitle ? /* @__PURE__ */ jsxs(
956
- "div",
957
- {
958
- className: `iqauth-sdk-card-header${ap?.cardHeader?.className ? ` ${ap.cardHeader.className}` : ""}`,
959
- style: ap?.cardHeader?.style,
960
- children: [
961
- title ? /* @__PURE__ */ jsx("h1", { className: ap?.headerTitle?.className, style: ap?.headerTitle?.style, children: title }) : null,
962
- subtitle ? /* @__PURE__ */ jsx("p", { className: ap?.headerSubtitle?.className, style: ap?.headerSubtitle?.style, children: subtitle }) : null
963
- ]
964
- }
965
- ) : null,
966
- /* @__PURE__ */ jsx(
967
- "div",
968
- {
969
- className: `iqauth-sdk-card-body${ap?.cardBody?.className ? ` ${ap.cardBody.className}` : ""}`,
970
- style: ap?.cardBody?.style,
971
- children
972
- }
973
- )
974
- ]
975
- }
976
- ),
977
- hasFooterLinks || branding?.footerText ? /* @__PURE__ */ jsxs("footer", { className: "iqauth-sdk-footer", children: [
978
- branding?.footerText ? /* @__PURE__ */ jsx("div", { "data-testid": "text-brand-footer-sdk", style: { fontSize: 12, opacity: 0.75 }, children: branding.footerText }) : null,
979
- hasFooterLinks ? /* @__PURE__ */ jsxs("div", { className: "iqauth-sdk-footer-links", children: [
980
- branding?.termsUrl ? /* @__PURE__ */ jsx("a", { href: branding.termsUrl, target: "_blank", rel: "noreferrer noopener", children: "Terms" }) : null,
981
- branding?.privacyUrl ? /* @__PURE__ */ jsx("a", { href: branding.privacyUrl, target: "_blank", rel: "noreferrer noopener", children: "Privacy" }) : null,
982
- supportLink ? /* @__PURE__ */ jsx("a", { href: supportLink, target: "_blank", rel: "noreferrer noopener", children: "Support" }) : null
983
- ] }) : null
984
- ] }) : null
985
- ] }) })
986
- ]
987
- },
988
- branding?.brandingRev || void 0
989
- );
990
- }
991
- function Field({ label, children }) {
992
- return /* @__PURE__ */ jsxs("label", { style: { display: "flex", flexDirection: "column", gap: 6, fontSize: 13 }, children: [
993
- /* @__PURE__ */ jsx("span", { style: { fontWeight: 500 }, children: label }),
994
- children
995
- ] });
996
- }
997
- function inputStyle() {
998
- return {
999
- padding: "8px 12px",
1000
- border: "1px solid rgba(15,23,42,0.15)",
1001
- borderRadius: 6,
1002
- fontSize: 14,
1003
- width: "100%",
1004
- background: "transparent",
1005
- color: "inherit"
1006
- };
1007
- }
1008
- function PrimaryButton(props) {
1009
- return /* @__PURE__ */ jsx(
1010
- "button",
1011
- {
1012
- ...props,
1013
- style: {
1014
- background: "var(--brand-primary, #3b82f6)",
1015
- color: "#fff",
1016
- border: "none",
1017
- padding: "10px 16px",
1018
- borderRadius: 8,
1019
- fontSize: 14,
1020
- fontWeight: 500,
1021
- cursor: props.disabled ? "not-allowed" : "pointer",
1022
- opacity: props.disabled ? 0.6 : 1,
1023
- width: "100%",
1024
- ...props.style
1025
- }
1026
- }
1027
- );
1028
- }
1029
- function GhostButton(props) {
1030
- return /* @__PURE__ */ jsx(
1031
- "button",
1032
- {
1033
- ...props,
1034
- style: {
1035
- background: "transparent",
1036
- color: "inherit",
1037
- border: "1px solid rgba(15,23,42,0.15)",
1038
- padding: "10px 16px",
1039
- borderRadius: 8,
1040
- fontSize: 14,
1041
- fontWeight: 500,
1042
- cursor: props.disabled ? "not-allowed" : "pointer",
1043
- width: "100%",
1044
- ...props.style
1045
- }
1046
- }
1047
- );
1048
- }
1049
- function ErrorBanner({ message }) {
1050
- return /* @__PURE__ */ jsx("div", { role: "alert", style: {
1051
- borderLeft: "3px solid #dc2626",
1052
- background: "rgba(220,38,38,0.08)",
1053
- padding: "10px 14px",
1054
- borderRadius: "0 6px 6px 0",
1055
- fontSize: 13,
1056
- color: "#b91c1c"
1057
- }, children: message });
1058
- }
1059
- function isSilentSsoEligible(ctx, effectivePrompt) {
1060
- if (!ctx) return false;
1061
- if (effectivePrompt === "login") return false;
1062
- if (!ctx.session) return false;
1063
- if (!ctx.app.defaultClientId) return false;
1064
- if (!ctx.returnAllowed) return false;
1065
- return true;
1066
- }
1067
- function SignIn(props) {
1068
- const providerCtx = useContext(IQAuthContext);
1069
- const iqAuthBaseUrl = props.iqAuthBaseUrl ?? providerCtx?.manager.issuerUrl ?? "";
1070
- const appKey = props.appKey ?? providerCtx?.manager.appKey ?? "";
1071
- const returnTo = props.returnTo ?? (typeof window !== "undefined" ? `${window.location.origin}/api/iqauth/callback` : "");
1072
- const { onRedirect, className, prompt, appearance: instanceAppearance, silentSso: instanceSilentSso } = props;
1073
- const silentSsoEnabled = instanceSilentSso ?? providerCtx?.silentSso ?? false;
1074
- const appearance = instanceAppearance && providerCtx?.appearance ? { elements: { ...providerCtx.appearance.elements, ...instanceAppearance.elements } } : instanceAppearance ?? providerCtx?.appearance ?? null;
1075
- if (!iqAuthBaseUrl || !appKey) {
1076
- console.error(
1077
- "[IQAuth] <SignIn /> could not determine iqAuthBaseUrl/appKey. Either pass them explicitly OR wrap the component in <IQAuthProvider publishableKey=\u2026/>."
1078
- );
1079
- }
1080
- const t2 = useT();
1081
- const localeBundle = useLocale();
1082
- const { ctx, loading, error } = useIQAuthSignInContext(iqAuthBaseUrl, appKey, returnTo);
1083
- const preflightLoggedRef = useRef(false);
1084
- useEffect(() => {
1085
- if (!ctx || preflightLoggedRef.current) return;
1086
- if (ctx.returnAllowed) return;
1087
- preflightLoggedRef.current = true;
1088
- console.error(
1089
- `[IQAuth] returnTo "${returnTo}" is NOT in the app's allowed origins. Add it via the IQAuth admin console: Apps \u2192 ${ctx.app.key} \u2192 Allowed Origins. Currently allowed: [${ctx.allowedOrigins.join(", ") || "\u2014"}].`
1090
- );
1091
- }, [ctx, returnTo]);
1092
- const [email, setEmail] = useState("");
1093
- const [password, setPassword] = useState("");
1094
- const [submitting, setSubmitting] = useState(false);
1095
- const [formError, setFormError] = useState("");
1096
- const [mfa, setMfa] = useState(null);
1097
- const [tenantSel, setTenantSel] = useState(null);
1098
- const [oauthExchanging, setOauthExchanging] = useState(false);
1099
- const [silent, setSilent] = useState("idle");
1100
- const [forcePrompt, setForcePrompt] = useState(false);
1101
- const effectivePrompt = useMemo(() => {
1102
- if (prompt === "login" || forcePrompt) return "login";
1103
- if (!silentSsoEnabled) return "login";
1104
- if (typeof window !== "undefined") {
1105
- try {
1106
- if (new URLSearchParams(window.location.search).get("prompt") === "login") return "login";
1107
- } catch {
1108
- }
1109
- }
1110
- return void 0;
1111
- }, [prompt, forcePrompt, silentSsoEnabled]);
1112
- const oidcPayload = () => ({
1113
- client_id: ctx?.app.defaultClientId,
1114
- redirect_uri: returnTo,
1115
- scope: "openid"
1116
- });
1117
- const handlePayload = (payload) => {
1118
- if (payload.type === "redirect" && payload.redirectUrl) {
1119
- (onRedirect || ((u) => {
1120
- window.location.href = u;
1121
- }))(payload.redirectUrl);
1122
- return true;
1123
- }
1124
- if (payload.type === "tenant_selection") {
1125
- setTenantSel({ token: payload.tenantSelectionToken, tenants: payload.tenants || [] });
1126
- return true;
1127
- }
1128
- if (payload.type === "mfa_required") {
1129
- const methods = payload.availableMethods || ["totp"];
1130
- setMfa({ token: payload.mfaChallengeToken, methods, selected: methods[0], code: "", backup: false });
1131
- return true;
1132
- }
1133
- return false;
1134
- };
1135
- const submitLogin = async (e) => {
1136
- e.preventDefault();
1137
- if (!ctx?.app.defaultClientId) {
1138
- setFormError("Application is not configured for hosted sign-in.");
1139
- return;
1140
- }
1141
- setSubmitting(true);
1142
- setFormError("");
1143
- try {
1144
- const r = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/oidc/sso-login`, {
1145
- method: "POST",
1146
- headers: { "Content-Type": "application/json" },
1147
- credentials: "include",
1148
- body: JSON.stringify({ email, password, ...oidcPayload() })
1149
- });
1150
- const payload = await r.json().catch(() => ({}));
1151
- if (!handlePayload(payload)) setFormError(localizeError(localeBundle, { code: payload.error, message: payload.error_description }));
1152
- } catch (err) {
1153
- setFormError(err.message || t(localeBundle, "errors.network"));
1154
- }
1155
- setSubmitting(false);
1156
- };
1157
- const submitMfa = async (e) => {
1158
- e.preventDefault();
1159
- if (!mfa) return;
1160
- setSubmitting(true);
1161
- setFormError("");
1162
- const r = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/oidc/sso-mfa-complete`, {
1163
- method: "POST",
1164
- headers: { "Content-Type": "application/json" },
1165
- credentials: "include",
1166
- body: JSON.stringify({
1167
- mfaChallengeToken: mfa.token,
1168
- code: mfa.code,
1169
- method: mfa.selected,
1170
- useBackup: mfa.backup,
1171
- ...oidcPayload()
1172
- })
1173
- });
1174
- const payload = await r.json().catch(() => ({}));
1175
- if (!handlePayload(payload)) setFormError(localizeError(localeBundle, { code: payload.error, message: payload.error_description }));
1176
- setSubmitting(false);
1177
- };
1178
- const submitTenant = async (tenantId) => {
1179
- if (!tenantSel) return;
1180
- setSubmitting(true);
1181
- setFormError("");
1182
- const r = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/oidc/sso-tenant-select`, {
1183
- method: "POST",
1184
- headers: { "Content-Type": "application/json" },
1185
- credentials: "include",
1186
- body: JSON.stringify({ tenantSelectionToken: tenantSel.token, tenantId, ...oidcPayload() })
1187
- });
1188
- const payload = await r.json().catch(() => ({}));
1189
- if (!handlePayload(payload)) setFormError(localizeError(localeBundle, { code: payload.error, message: payload.error_description }));
1190
- setSubmitting(false);
1191
- };
1192
- const startGoogleLogin = () => {
1193
- if (!ctx?.app.defaultClientId) {
1194
- setFormError("Application is not configured for hosted sign-in.");
1195
- return;
1196
- }
1197
- const bridgeUrl = window.location.href;
1198
- const url = `${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/google?redirect_uri=${encodeURIComponent(bridgeUrl)}&client_id=${encodeURIComponent(ctx.app.defaultClientId)}`;
1199
- window.location.href = url;
1200
- };
1201
- useEffect(() => {
1202
- if (loading || error || !ctx) return;
1203
- if (effectivePrompt === "login") {
1204
- setSilent("skipped");
1205
- return;
1206
- }
1207
- if (silent !== "idle") return;
1208
- if (!ctx.session || !ctx.app.defaultClientId || !ctx.returnAllowed) {
1209
- setSilent("skipped");
1210
- return;
1211
- }
1212
- setSilent("trying");
1213
- (async () => {
1214
- try {
1215
- const r = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/oidc/sso-resume`, {
1216
- method: "POST",
1217
- headers: { "Content-Type": "application/json" },
1218
- credentials: "include",
1219
- body: JSON.stringify(oidcPayload())
1220
- });
1221
- const payload = await r.json().catch(() => ({}));
1222
- if (payload?.type === "redirect" && payload.redirectUrl) {
1223
- (onRedirect || ((u) => {
1224
- window.location.replace(u);
1225
- }))(payload.redirectUrl);
1226
- return;
1227
- }
1228
- if (payload?.type === "tenant_selection") {
1229
- setTenantSel({ token: payload.tenantSelectionToken, tenants: payload.tenants || [] });
1230
- setSilent("failed");
1231
- return;
1232
- }
1233
- setSilent("failed");
1234
- } catch {
1235
- setSilent("failed");
1236
- }
1237
- })();
1238
- }, [loading, error, ctx, effectivePrompt]);
1239
- const switchAccount = (e) => {
1240
- if (e) e.preventDefault();
1241
- setForcePrompt(true);
1242
- setSilent("skipped");
1243
- setTenantSel(null);
1244
- if (typeof window !== "undefined") {
1245
- try {
1246
- const u = new URL(window.location.href);
1247
- u.searchParams.set("prompt", "login");
1248
- window.history.replaceState({}, "", u.toString());
1249
- } catch {
1250
- }
1251
- }
1252
- };
1253
- useEffect(() => {
1254
- if (!ctx?.app.defaultClientId) return;
1255
- const params = new URLSearchParams(window.location.search);
1256
- const oauthCode = params.get("code");
1257
- if (!oauthCode) return;
1258
- const u = new URL(window.location.href);
1259
- u.searchParams.delete("code");
1260
- const codeRedirectUri = u.toString();
1261
- setOauthExchanging(true);
1262
- setFormError("");
1263
- (async () => {
1264
- try {
1265
- const r = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/oidc/sso-complete-oauth`, {
1266
- method: "POST",
1267
- headers: { "Content-Type": "application/json" },
1268
- credentials: "include",
1269
- body: JSON.stringify({
1270
- authCode: oauthCode,
1271
- code_redirect_uri: codeRedirectUri,
1272
- ...oidcPayload()
1273
- })
1274
- });
1275
- const payload = await r.json().catch(() => ({}));
1276
- try {
1277
- window.history.replaceState({}, "", u.pathname + (u.search ? u.search : "") + u.hash);
1278
- } catch {
1279
- }
1280
- if (!handlePayload(payload)) setFormError(payload.error_description || payload.error || "Authorization code exchange failed");
1281
- } catch (err) {
1282
- setFormError(err.message || "Authorization code exchange failed");
1283
- }
1284
- setOauthExchanging(false);
1285
- })();
1286
- }, [ctx?.app.defaultClientId]);
1287
- if (loading || oauthExchanging) return /* @__PURE__ */ jsx(Shell, { appearance, branding: ctx?.branding || null, className, title: oauthExchanging ? t2("signIn.submitting") : t2("common.loading"), children: /* @__PURE__ */ jsx("p", { children: oauthExchanging ? t2("signIn.submitting") : t2("common.loading") }) });
1288
- if (error || !ctx) return /* @__PURE__ */ jsx(Shell, { appearance, branding: null, className, title: t2("errors.serverError"), children: /* @__PURE__ */ jsx(ErrorBanner, { message: error || t2("errors.serverError") }) });
1289
- if (!ctx.returnAllowed) return /* @__PURE__ */ jsx(Shell, { appearance, branding: ctx.branding, className, title: t2("errors.generic"), children: /* @__PURE__ */ jsx(ErrorBanner, { message: `returnTo "${returnTo}" is not in this app's allowed origins.` }) });
1290
- const silentEligible = isSilentSsoEligible(ctx, effectivePrompt);
1291
- if (silentEligible && silent !== "failed") {
1292
- return /* @__PURE__ */ jsxs(Shell, { appearance, branding: ctx.branding, className, title: t2("signIn.resumingSession"), subtitle: ctx.session ? `${t2("signIn.subtitle")}, ${ctx.session.name || ctx.session.email}.` : void 0, children: [
1293
- /* @__PURE__ */ jsx("p", { "data-testid": "text-silent-resume", style: { fontSize: 14, opacity: 0.8 }, children: t2("signIn.resumingSession") }),
1294
- /* @__PURE__ */ jsx("a", { href: "#", onClick: switchAccount, "data-testid": "link-switch-account", style: { fontSize: 13 }, children: t2("signIn.useDifferentAccount") })
1295
- ] });
1296
- }
1297
- const cardTitle = ctx.branding?.loginHeadline || t2("signIn.titleWithApp", { appName: ctx.app.name });
1298
- const cardSubtitle = ctx.branding?.loginSubheadline || void 0;
1299
- return /* @__PURE__ */ jsxs(Shell, { appearance, branding: ctx.branding, className, title: cardTitle, subtitle: cardSubtitle, children: [
1300
- formError ? /* @__PURE__ */ jsx(ErrorBanner, { message: formError }) : null,
1301
- tenantSel ? /* @__PURE__ */ jsx("div", { role: "radiogroup", "aria-label": t2("signIn.selectTenant"), style: { display: "flex", flexDirection: "column", gap: 8 }, children: tenantSel.tenants.map((tn) => /* @__PURE__ */ jsxs(
1302
- "button",
1303
- {
1304
- type: "button",
1305
- "data-iqauth-tenant": tn.tenantId,
1306
- onClick: () => submitTenant(tn.tenantId),
1307
- style: { textAlign: "left", padding: "10px 14px", border: "1px solid rgba(15,23,42,0.15)", borderRadius: 8, background: "transparent", color: "inherit", cursor: "pointer" },
1308
- children: [
1309
- /* @__PURE__ */ jsx("p", { style: { margin: 0, fontWeight: 500 }, children: tn.tenantName || tn.tenantSlug || tn.tenantId }),
1310
- /* @__PURE__ */ jsx("p", { style: { margin: 0, fontSize: 12, opacity: 0.6 }, children: tn.roles.join(", ") })
1311
- ]
1312
- },
1313
- tn.tenantId
1314
- )) }) : mfa ? /* @__PURE__ */ jsxs("form", { onSubmit: submitMfa, style: { display: "flex", flexDirection: "column", gap: 12 }, "aria-label": t2("mfa.title"), children: [
1315
- !mfa.backup && mfa.methods.length > 1 ? /* @__PURE__ */ jsx(Field, { label: t2("mfa.title"), children: /* @__PURE__ */ jsx("select", { style: inputStyle(), value: mfa.selected, onChange: (e) => setMfa({ ...mfa, selected: e.target.value }), children: mfa.methods.map((m) => /* @__PURE__ */ jsx("option", { value: m, children: m.toUpperCase() }, m)) }) }) : null,
1316
- /* @__PURE__ */ jsx(Field, { label: mfa.backup ? t2("mfa.backupCodeLabel") : t2("mfa.totpLabel"), children: /* @__PURE__ */ jsx(
1317
- "input",
1318
- {
1319
- style: { ...inputStyle(), fontFamily: "monospace", textAlign: mfa.backup ? "left" : "center", letterSpacing: mfa.backup ? "0.04em" : "0.3em" },
1320
- value: mfa.code,
1321
- onChange: (e) => setMfa({ ...mfa, code: e.target.value }),
1322
- autoComplete: "one-time-code",
1323
- inputMode: mfa.backup ? "text" : "numeric"
1324
- }
1325
- ) }),
1326
- /* @__PURE__ */ jsx(PrimaryButton, { type: "submit", disabled: submitting || !mfa.code, children: submitting ? t2("mfa.submitting") : t2("mfa.submit") }),
1327
- /* @__PURE__ */ jsx(GhostButton, { type: "button", onClick: () => setMfa({ ...mfa, backup: !mfa.backup, code: "" }), children: mfa.backup ? t2("mfa.useAuthenticator") : t2("mfa.useBackupCode") })
1328
- ] }) : /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
1329
- ctx.providers?.google ? /* @__PURE__ */ jsxs(Fragment2, { children: [
1330
- /* @__PURE__ */ jsxs("button", { type: "button", className: "iqauth-sdk-google-btn", onClick: startGoogleLogin, disabled: submitting, "aria-label": ctx.branding?.googleButtonLabel || t2("signIn.continueWithGoogle"), children: [
1331
- /* @__PURE__ */ jsxs("svg", { width: "18", height: "18", viewBox: "0 0 18 18", "aria-hidden": "true", children: [
1332
- /* @__PURE__ */ jsx("path", { fill: "#4285F4", d: "M17.64 9.2c0-.64-.06-1.25-.17-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.71v2.26h2.92a8.78 8.78 0 0 0 2.68-6.61z" }),
1333
- /* @__PURE__ */ jsx("path", { fill: "#34A853", d: "M9 18c2.43 0 4.47-.81 5.96-2.18l-2.92-2.26a5.4 5.4 0 0 1-8.04-2.83H.96v2.33A9 9 0 0 0 9 18z" }),
1334
- /* @__PURE__ */ jsx("path", { fill: "#FBBC05", d: "M3.96 10.71A5.41 5.41 0 0 1 3.68 9c0-.59.1-1.17.29-1.71V4.96H.96a9 9 0 0 0 0 8.08l3-2.33z" }),
1335
- /* @__PURE__ */ jsx("path", { fill: "#EA4335", d: "M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.59A9 9 0 0 0 .96 4.96l3 2.33A5.4 5.4 0 0 1 9 3.58z" })
1336
- ] }),
1337
- ctx.branding?.googleButtonLabel || t2("signIn.continueWithGoogle")
1338
- ] }),
1339
- /* @__PURE__ */ jsx("div", { role: "separator", "aria-label": t2("common.or"), className: "iqauth-sdk-divider", children: t2("signIn.dividerOr").toUpperCase() })
1340
- ] }) : null,
1341
- /* @__PURE__ */ jsxs("form", { onSubmit: submitLogin, style: { display: "flex", flexDirection: "column", gap: 12 }, "aria-label": t2("signIn.titleWithApp", { appName: ctx.app.name }), children: [
1342
- /* @__PURE__ */ jsx(Field, { label: t2("signIn.emailLabel"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), type: "email", autoComplete: "email", required: true, value: email, onChange: (e) => setEmail(e.target.value) }) }),
1343
- /* @__PURE__ */ jsx(Field, { label: t2("signIn.passwordLabel"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), type: "password", autoComplete: "current-password", required: true, value: password, onChange: (e) => setPassword(e.target.value) }) }),
1344
- /* @__PURE__ */ jsx(PrimaryButton, { type: "submit", disabled: submitting || !email || !password, children: submitting ? t2("signIn.submitting") : t2("signIn.submit") })
1345
- ] })
1346
- ] }),
1347
- (silent === "failed" || effectivePrompt === "login" && ctx.session) && !mfa ? /* @__PURE__ */ jsx("p", { style: { marginTop: 12, fontSize: 13, opacity: 0.75 }, children: /* @__PURE__ */ jsx("a", { href: "#", onClick: switchAccount, "data-testid": "link-switch-account", children: t2("signIn.useDifferentAccount") }) }) : null
1348
- ] });
1349
- }
1350
- function SignUp({ iqAuthBaseUrl, appKey, returnTo, onSuccess, className }) {
1351
- const t2 = useT();
1352
- const localeBundle = useLocale();
1353
- const { ctx, loading } = useIQAuthSignInContext(iqAuthBaseUrl, appKey, returnTo || "");
1354
- const [name, setName] = useState("");
1355
- const [email, setEmail] = useState("");
1356
- const [password, setPassword] = useState("");
1357
- const [organizationName, setOrganizationName] = useState("");
1358
- const [submitting, setSubmitting] = useState(false);
1359
- const [error, setError] = useState("");
1360
- const [done, setDone] = useState(false);
1361
- const submit = async (e) => {
1362
- e.preventDefault();
1363
- setSubmitting(true);
1364
- setError("");
1365
- try {
1366
- await jsonFetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/signup`, {
1367
- method: "POST",
1368
- headers: { "Content-Type": "application/json" },
1369
- body: JSON.stringify({ email, name, password, organizationName: organizationName || void 0 })
1370
- });
1371
- setDone(true);
1372
- onSuccess?.();
1373
- } catch (err) {
1374
- setError(localizeError(localeBundle, err.message));
1375
- }
1376
- setSubmitting(false);
1377
- };
1378
- if (loading) return /* @__PURE__ */ jsx(Shell, { branding: null, className, children: /* @__PURE__ */ jsx("p", { children: t2("common.loading") }) });
1379
- return /* @__PURE__ */ jsx(Shell, { branding: ctx?.branding || null, className, title: t2("signUp.title"), children: done ? /* @__PURE__ */ jsx("div", { role: "status", children: /* @__PURE__ */ jsx("p", { children: t2("magicLink.subtitle", { email }) }) }) : /* @__PURE__ */ jsxs("form", { onSubmit: submit, style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
1380
- error ? /* @__PURE__ */ jsx(ErrorBanner, { message: error }) : null,
1381
- /* @__PURE__ */ jsx(Field, { label: t2("signUp.nameLabel"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), value: name, onChange: (e) => setName(e.target.value), required: true }) }),
1382
- /* @__PURE__ */ jsx(Field, { label: t2("signUp.emailLabel"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), type: "email", autoComplete: "email", value: email, onChange: (e) => setEmail(e.target.value), required: true }) }),
1383
- /* @__PURE__ */ jsx(Field, { label: `${t2("signUp.tenantNameLabel")} (${t2("common.optional")})`, children: /* @__PURE__ */ jsx("input", { style: inputStyle(), value: organizationName, onChange: (e) => setOrganizationName(e.target.value) }) }),
1384
- /* @__PURE__ */ jsx(Field, { label: t2("signUp.passwordLabel"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), type: "password", autoComplete: "new-password", minLength: 8, value: password, onChange: (e) => setPassword(e.target.value), required: true }) }),
1385
- /* @__PURE__ */ jsx(PrimaryButton, { type: "submit", disabled: submitting || !email || !password || !name, children: submitting ? t2("signUp.submitting") : t2("signUp.submit") })
1386
- ] }) });
1387
- }
1388
- function initialsOf(name, email) {
1389
- const src = name || email || "?";
1390
- const parts = src.split(/[\s@]+/).filter(Boolean);
1391
- if (parts.length >= 2) return (parts[0][0] + parts[1][0]).toUpperCase();
1392
- return src.substring(0, 2).toUpperCase();
1393
- }
1394
- function UserButton({ iqAuthBaseUrl, accountUrl, onSignOut, className }) {
1395
- const t2 = useT();
1396
- const [user, setUser] = useState(null);
1397
- const [open, setOpen] = useState(false);
1398
- const branding = useResolvedSdkBranding(iqAuthBaseUrl);
1399
- const accent = branding?.accentColor || "#6366f1";
1400
- const primary = branding?.primaryColor || "#0f172a";
1401
- useEffect(() => {
1402
- let cancelled = false;
1403
- fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/me`, { credentials: "include" }).then((r) => r.json()).then((p) => {
1404
- if (!cancelled && p?.data) setUser(p.data);
1405
- }).catch(() => {
1406
- });
1407
- return () => {
1408
- cancelled = true;
1409
- };
1410
- }, [iqAuthBaseUrl]);
1411
- const signOut2 = async () => {
1412
- try {
1413
- await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/logout`, { method: "POST", credentials: "include" });
1414
- } catch {
1415
- }
1416
- if (onSignOut) onSignOut();
1417
- else window.location.reload();
1418
- };
1419
- if (!user) return null;
1420
- const target = accountUrl || `${iqAuthBaseUrl.replace(/\/$/, "")}/account`;
1421
- return /* @__PURE__ */ jsxs(
1422
- "div",
1423
- {
1424
- className,
1425
- style: { position: "relative", display: "inline-block", ...brandStyle(branding) },
1426
- "data-iqauth-sdk-userbutton": "",
1427
- "data-branding-rev": branding?.brandingRev || "",
1428
- children: [
1429
- /* @__PURE__ */ jsx(
1430
- "button",
1431
- {
1432
- type: "button",
1433
- "aria-haspopup": "menu",
1434
- "aria-expanded": open,
1435
- onClick: () => setOpen((o) => !o),
1436
- style: {
1437
- width: 32,
1438
- height: 32,
1439
- borderRadius: "50%",
1440
- background: accent,
1441
- color: "#fff",
1442
- border: "none",
1443
- cursor: "pointer",
1444
- fontSize: 12,
1445
- fontWeight: 600
1446
- },
1447
- children: user.picture ? /* @__PURE__ */ jsx("img", { src: user.picture, alt: user.name, style: { width: "100%", height: "100%", borderRadius: "50%" } }) : initialsOf(user.name, user.email)
1448
- }
1449
- ),
1450
- open ? /* @__PURE__ */ jsxs("div", { role: "menu", style: {
1451
- position: "absolute",
1452
- right: 0,
1453
- top: 40,
1454
- minWidth: 200,
1455
- background: "#fff",
1456
- border: "1px solid rgba(15,23,42,0.12)",
1457
- borderRadius: 8,
1458
- boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
1459
- padding: 8,
1460
- zIndex: 100
1461
- }, children: [
1462
- /* @__PURE__ */ jsxs("div", { style: { padding: "8px 10px", fontSize: 12, opacity: 0.7, borderBottom: "1px solid rgba(15,23,42,0.06)" }, children: [
1463
- /* @__PURE__ */ jsx("div", { style: { fontWeight: 500, color: "#0f172a" }, children: user.name }),
1464
- /* @__PURE__ */ jsx("div", { children: user.email })
1465
- ] }),
1466
- /* @__PURE__ */ jsx("a", { href: target, role: "menuitem", style: { display: "block", padding: "8px 10px", fontSize: 13, color: primary, textDecoration: "none" }, children: t2("userButton.manageAccount") }),
1467
- /* @__PURE__ */ jsx(
1468
- "button",
1469
- {
1470
- role: "menuitem",
1471
- type: "button",
1472
- onClick: signOut2,
1473
- style: { display: "block", width: "100%", textAlign: "left", padding: "8px 10px", fontSize: 13, background: "transparent", border: "none", cursor: "pointer", color: "#b91c1c" },
1474
- children: t2("userButton.signOut")
1475
- }
1476
- )
1477
- ] }) : null
1478
- ]
1479
- }
1480
- );
1481
- }
1482
- function UserProfile({ iqAuthBaseUrl, className }) {
1483
- const t2 = useT();
1484
- const localeBundle = useLocale();
1485
- const branding = useResolvedSdkBranding(iqAuthBaseUrl);
1486
- const [user, setUser] = useState(null);
1487
- const [oldPassword, setOldPassword] = useState("");
1488
- const [newPassword, setNewPassword] = useState("");
1489
- const [pwState, setPwState] = useState({ submitting: false, message: "", error: "" });
1490
- const [sessions, setSessions] = useState([]);
1491
- const [revokeAllBusy, setRevokeAllBusy] = useState(false);
1492
- const loadSessions = () => {
1493
- fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/users/me/sessions`, { credentials: "include" }).then((r) => r.ok ? r.json() : Promise.reject(r)).then((p) => setSessions(p?.data?.sessions || [])).catch(() => {
1494
- fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/sessions`, { credentials: "include" }).then((r) => r.json()).then((p) => setSessions(p?.data?.sessions || p?.data || [])).catch(() => {
1495
- });
1496
- });
1497
- };
1498
- useEffect(() => {
1499
- fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/me`, { credentials: "include" }).then((r) => r.json()).then((p) => {
1500
- if (p?.data) setUser(p.data);
1501
- }).catch(() => {
1502
- });
1503
- loadSessions();
1504
- }, [iqAuthBaseUrl]);
1505
- const changePassword = async (e) => {
1506
- e.preventDefault();
1507
- setPwState({ submitting: true, message: "", error: "" });
1508
- try {
1509
- await jsonFetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/password/change`, {
1510
- method: "POST",
1511
- headers: { "Content-Type": "application/json" },
1512
- body: JSON.stringify({ oldPassword, newPassword })
1513
- });
1514
- setPwState({ submitting: false, message: t(localeBundle, "userProfile.passwordUpdated"), error: "" });
1515
- setOldPassword("");
1516
- setNewPassword("");
1517
- } catch (err) {
1518
- setPwState({ submitting: false, message: "", error: localizeError(localeBundle, err.message) });
1519
- }
1520
- };
1521
- const revoke = async (sessionId) => {
1522
- const newRes = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/users/me/sessions/${sessionId}`, { method: "DELETE", credentials: "include" });
1523
- if (!newRes.ok && newRes.status === 404) {
1524
- await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/sessions/${sessionId}`, { method: "DELETE", credentials: "include" });
1525
- }
1526
- setSessions((prev) => prev.filter((s) => s.id !== sessionId));
1527
- };
1528
- const revokeAllOthers = async () => {
1529
- setRevokeAllBusy(true);
1530
- try {
1531
- await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/users/me/sessions/revoke-all-others`, { method: "POST", credentials: "include" });
1532
- setSessions((prev) => prev.filter((s) => s.isCurrent));
1533
- } finally {
1534
- setRevokeAllBusy(false);
1535
- }
1536
- };
1537
- if (!user) return /* @__PURE__ */ jsx(Shell, { branding, className, children: /* @__PURE__ */ jsx("p", { children: t2("common.loading") }) });
1538
- return /* @__PURE__ */ jsxs(Shell, { branding, className, title: t2("userProfile.title"), children: [
1539
- /* @__PURE__ */ jsxs("section", { "aria-labelledby": "iqauth-profile", style: { marginBottom: 20 }, children: [
1540
- /* @__PURE__ */ jsx("h3", { id: "iqauth-profile", style: { fontSize: 14, fontWeight: 600 }, children: t2("userProfile.profileTab") }),
1541
- /* @__PURE__ */ jsxs("p", { style: { fontSize: 13, margin: "4px 0" }, children: [
1542
- /* @__PURE__ */ jsxs("strong", { children: [
1543
- t2("common.name"),
1544
- ":"
1545
- ] }),
1546
- " ",
1547
- user.name
1548
- ] }),
1549
- /* @__PURE__ */ jsxs("p", { style: { fontSize: 13, margin: "4px 0" }, children: [
1550
- /* @__PURE__ */ jsxs("strong", { children: [
1551
- t2("common.email"),
1552
- ":"
1553
- ] }),
1554
- " ",
1555
- user.email
1556
- ] })
1557
- ] }),
1558
- /* @__PURE__ */ jsxs("section", { "aria-labelledby": "iqauth-pw", style: { marginBottom: 20 }, children: [
1559
- /* @__PURE__ */ jsx("h3", { id: "iqauth-pw", style: { fontSize: 14, fontWeight: 600 }, children: t2("userProfile.changePassword") }),
1560
- pwState.error ? /* @__PURE__ */ jsx(ErrorBanner, { message: pwState.error }) : null,
1561
- pwState.message ? /* @__PURE__ */ jsx("div", { role: "status", style: { fontSize: 13, color: "#047857" }, children: pwState.message }) : null,
1562
- /* @__PURE__ */ jsxs("form", { onSubmit: changePassword, style: { display: "flex", flexDirection: "column", gap: 10 }, children: [
1563
- /* @__PURE__ */ jsx(Field, { label: t2("userProfile.currentPassword"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), type: "password", autoComplete: "current-password", value: oldPassword, onChange: (e) => setOldPassword(e.target.value), required: true }) }),
1564
- /* @__PURE__ */ jsx(Field, { label: t2("userProfile.newPassword"), children: /* @__PURE__ */ jsx("input", { style: inputStyle(), type: "password", autoComplete: "new-password", minLength: 8, value: newPassword, onChange: (e) => setNewPassword(e.target.value), required: true }) }),
1565
- /* @__PURE__ */ jsx(PrimaryButton, { type: "submit", disabled: pwState.submitting || !oldPassword || !newPassword, children: pwState.submitting ? t2("common.saving") : t2("userProfile.changePassword") })
1566
- ] })
1567
- ] }),
1568
- /* @__PURE__ */ jsxs("section", { "aria-labelledby": "iqauth-sessions", children: [
1569
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between" }, children: [
1570
- /* @__PURE__ */ jsx("h3", { id: "iqauth-sessions", style: { fontSize: 14, fontWeight: 600, margin: 0 }, children: t2("userProfile.sessionsTab") }),
1571
- sessions.some((s) => !s.isCurrent) && /* @__PURE__ */ jsx(
1572
- "button",
1573
- {
1574
- type: "button",
1575
- disabled: revokeAllBusy,
1576
- onClick: revokeAllOthers,
1577
- style: { fontSize: 12, color: "#b91c1c", background: "transparent", border: "1px solid #fecaca", borderRadius: 4, padding: "4px 10px", cursor: "pointer" },
1578
- children: revokeAllBusy ? t2("common.submitting") : t2("userProfile.revokeAllOthers")
1579
- }
1580
- )
1581
- ] }),
1582
- sessions.length === 0 ? /* @__PURE__ */ jsx("p", { style: { fontSize: 13, opacity: 0.6 }, children: t2("userProfile.sessionsEmpty") }) : /* @__PURE__ */ jsx("ul", { style: { listStyle: "none", padding: 0, margin: "8px 0 0", display: "flex", flexDirection: "column", gap: 6 }, children: sessions.map((s) => /* @__PURE__ */ jsxs("li", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 13, padding: "8px 10px", background: s.isCurrent ? "#ecfdf5" : "#f8fafc", borderRadius: 6, border: s.isCurrent ? "1px solid #a7f3d0" : "1px solid transparent" }, children: [
1583
- /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 2 }, children: [
1584
- /* @__PURE__ */ jsxs("span", { style: { fontWeight: 500 }, children: [
1585
- s.device || s.userAgent || s.deviceName || "\u2014",
1586
- s.isCurrent && /* @__PURE__ */ jsxs("span", { style: { marginLeft: 8, fontSize: 11, color: "#047857" }, children: [
1587
- "(",
1588
- t2("userProfile.thisDevice"),
1589
- ")"
1590
- ] })
1591
- ] }),
1592
- /* @__PURE__ */ jsxs("span", { style: { fontSize: 11, opacity: 0.65 }, children: [
1593
- s.ip || "\u2014",
1594
- s.lastActiveAt ? ` \xB7 ${new Date(s.lastActiveAt).toLocaleString()}` : ""
1595
- ] })
1596
- ] }),
1597
- !s.isCurrent && /* @__PURE__ */ jsx("button", { type: "button", onClick: () => revoke(s.id), style: { fontSize: 12, color: "#b91c1c", background: "transparent", border: "1px solid #fecaca", borderRadius: 4, padding: "2px 8px", cursor: "pointer" }, children: t2("userProfile.revokeSession") })
1598
- ] }, s.id)) })
1599
- ] })
1600
- ] });
1601
- }
1602
- function OrganizationSwitcher({ iqAuthBaseUrl, onSwitched, appearance: _appearance, className }) {
1603
- const t2 = useT();
1604
- const branding = useResolvedSdkBranding(iqAuthBaseUrl);
1605
- const accent = branding?.accentColor || "#6366f1";
1606
- const [memberships, setMemberships] = useState([]);
1607
- const [activeTenantId, setActiveTenantId] = useState(null);
1608
- const [open, setOpen] = useState(false);
1609
- useEffect(() => {
1610
- fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/me`, { credentials: "include" }).then((r) => r.json()).then((p) => {
1611
- if (p?.data?.tenantId) setActiveTenantId(p.data.tenantId);
1612
- }).catch(() => {
1613
- });
1614
- fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/tenants/memberships`, { credentials: "include" }).then((r) => r.json()).then((p) => setMemberships(p?.data?.memberships || p?.data || [])).catch(() => {
1615
- });
1616
- }, [iqAuthBaseUrl]);
1617
- const switchTo = async (tenantId) => {
1618
- try {
1619
- await jsonFetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/auth/select-tenant`, {
1620
- method: "POST",
1621
- headers: { "Content-Type": "application/json" },
1622
- body: JSON.stringify({ tenantId })
1623
- });
1624
- setActiveTenantId(tenantId);
1625
- setOpen(false);
1626
- onSwitched?.(tenantId);
1627
- } catch {
1628
- }
1629
- };
1630
- const active = memberships.find((m) => m.tenantId === activeTenantId);
1631
- return /* @__PURE__ */ jsxs(
1632
- "div",
1633
- {
1634
- className,
1635
- style: { position: "relative", display: "inline-block", ...brandStyle(branding) },
1636
- "data-iqauth-sdk-orgswitcher": "",
1637
- "data-branding-rev": branding?.brandingRev || "",
1638
- children: [
1639
- /* @__PURE__ */ jsx(
1640
- "button",
1641
- {
1642
- type: "button",
1643
- "aria-haspopup": "menu",
1644
- "aria-expanded": open,
1645
- onClick: () => setOpen((o) => !o),
1646
- style: { background: "transparent", border: `1px solid ${accent}55`, color: branding?.primaryColor || "#0f172a", padding: "6px 12px", borderRadius: 6, cursor: "pointer", fontSize: 13 },
1647
- children: active?.tenantName || active?.tenantSlug || t2("orgSwitcher.label")
1648
- }
1649
- ),
1650
- open ? /* @__PURE__ */ jsx("div", { role: "menu", style: {
1651
- position: "absolute",
1652
- left: 0,
1653
- top: 36,
1654
- minWidth: 220,
1655
- background: "#fff",
1656
- border: "1px solid rgba(15,23,42,0.12)",
1657
- borderRadius: 8,
1658
- boxShadow: "0 4px 12px rgba(0,0,0,0.08)",
1659
- padding: 8,
1660
- zIndex: 100
1661
- }, children: memberships.length === 0 ? /* @__PURE__ */ jsx("p", { style: { fontSize: 13, opacity: 0.6, padding: "4px 6px" }, children: t2("orgSwitcher.noOrgs") }) : memberships.map((m) => /* @__PURE__ */ jsxs(
1662
- "button",
1663
- {
1664
- role: "menuitem",
1665
- type: "button",
1666
- onClick: () => switchTo(m.tenantId),
1667
- style: {
1668
- display: "block",
1669
- width: "100%",
1670
- textAlign: "left",
1671
- padding: "8px 10px",
1672
- background: m.tenantId === activeTenantId ? `${accent}14` : "transparent",
1673
- border: "none",
1674
- borderRadius: 4,
1675
- cursor: "pointer",
1676
- fontSize: 13,
1677
- color: "#0f172a"
1678
- },
1679
- children: [
1680
- /* @__PURE__ */ jsx("div", { style: { fontWeight: 500 }, children: m.tenantName || m.tenantSlug || m.tenantId }),
1681
- /* @__PURE__ */ jsx("div", { style: { fontSize: 11, opacity: 0.6 }, children: m.roles.join(", ") })
1682
- ]
1683
- },
1684
- m.tenantId
1685
- )) }) : null
1686
- ]
1687
- }
1688
- );
1689
- }
1690
- function useImpersonation() {
1691
- const { snapshot } = useCtx();
1692
- return useMemo(() => {
1693
- const claims = snapshot.claims;
1694
- const isImpersonating = claims?.purpose === "impersonation" && !!claims?.act?.sub;
1695
- return {
1696
- isImpersonating,
1697
- actor: isImpersonating ? claims.act : null,
1698
- target: isImpersonating ? snapshot.user : null
1699
- };
1700
- }, [snapshot]);
1701
- }
1702
- function ImpersonationBanner({ render, onExit, className, style } = {}) {
1703
- const t2 = useT();
1704
- const info = useImpersonation();
1705
- const { manager } = useCtx();
1706
- const exit = useCallback(async () => {
1707
- if (onExit) return void onExit();
1708
- const { exitImpersonation } = await import("./reverify-4UEJXUS6.mjs");
1709
- const restored = exitImpersonation(manager);
1710
- if (restored) return;
1711
- const { signOut: signOut2 } = await import("./signIn-CCY4JE5G.mjs");
1712
- await signOut2(manager);
1713
- }, [manager, onExit]);
1714
- if (!info.isImpersonating) return null;
1715
- if (render) return createElement(Fragment, null, render({ ...info, exit }));
1716
- const targetLabel = info.target?.email || info.target?.name || info.target?.sub || "user";
1717
- const _actorLabel = info.actor?.email || info.actor?.name || info.actor?.sub || "admin";
1718
- void _actorLabel;
1719
- return createElement(
1720
- "div",
1721
- {
1722
- role: "alert",
1723
- className,
1724
- style: {
1725
- position: "sticky",
1726
- top: 0,
1727
- left: 0,
1728
- right: 0,
1729
- zIndex: 9999,
1730
- background: "#b91c1c",
1731
- color: "#fff",
1732
- padding: "8px 16px",
1733
- display: "flex",
1734
- alignItems: "center",
1735
- justifyContent: "space-between",
1736
- fontSize: 13,
1737
- fontFamily: "system-ui, sans-serif",
1738
- ...style
1739
- }
1740
- },
1741
- createElement(
1742
- "span",
1743
- null,
1744
- t2("impersonation.banner", { targetEmail: targetLabel })
1745
- ),
1746
- createElement(
1747
- "button",
1748
- {
1749
- type: "button",
1750
- onClick: exit,
1751
- style: {
1752
- background: "rgba(255,255,255,0.18)",
1753
- color: "#fff",
1754
- border: "1px solid rgba(255,255,255,0.4)",
1755
- borderRadius: 4,
1756
- padding: "4px 10px",
1757
- cursor: "pointer",
1758
- fontSize: 12
1759
- }
1760
- },
1761
- t2("impersonation.exit")
1762
- )
1763
- );
1764
- }
1765
- function useReverification(fn, opts = {}) {
1766
- const { manager } = useCtx();
1767
- const level = opts.level ?? "password";
1768
- return (async (...args) => {
1769
- let token = null;
1770
- let res = await fn(token)(...args);
1771
- const code = await peekErrorCode(res);
1772
- const isReverifyError = res.status === 401 && code && (code === "REVERIFICATION_REQUIRED" || code === "REVERIFICATION_EXPIRED" || code === "REVERIFICATION_INVALID" || code === "REVERIFICATION_USED" || code === "REVERIFICATION_LEVEL_INSUFFICIENT");
1773
- if (!isReverifyError) return res;
1774
- const prompt = opts.prompt ?? defaultReverifyPrompt;
1775
- const credentials = await prompt(level);
1776
- if (!credentials) {
1777
- throw new Error("Reverification cancelled");
1778
- }
1779
- const { reverify } = await import("./reverify-4UEJXUS6.mjs");
1780
- const minted = await reverify(manager, { level, ...credentials });
1781
- token = minted.token;
1782
- res = await fn(token)(...args);
1783
- return res;
1784
- });
1785
- }
1786
- async function peekErrorCode(res) {
1787
- try {
1788
- const cloned = res.clone();
1789
- const body = await cloned.json();
1790
- return body?.error?.code ?? null;
1791
- } catch {
1792
- return null;
1793
- }
1794
- }
1795
- async function defaultReverifyPrompt(level) {
1796
- if (typeof window === "undefined") return null;
1797
- if (level === "password") {
1798
- const password = window.prompt("Confirm your password to continue");
1799
- if (!password) return null;
1800
- return { password };
1801
- }
1802
- const totp = window.prompt("Enter your MFA code to continue");
1803
- if (!totp) return null;
1804
- return { totp, method: "totp" };
1805
- }
1806
- function slugify(input) {
1807
- return input.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64);
1808
- }
1809
- function CreateOrganization({ iqAuthBaseUrl, onCreated, redirectUrl, unstyled, appearance, className }) {
1810
- const branding = useResolvedSdkBranding(iqAuthBaseUrl);
1811
- const [name, setName] = useState("");
1812
- const [slug, setSlug] = useState("");
1813
- const [slugTouched, setSlugTouched] = useState(false);
1814
- const [submitting, setSubmitting] = useState(false);
1815
- const [error, setError] = useState(null);
1816
- const [created, setCreated] = useState(null);
1817
- const [slugCheck, setSlugCheck] = useState({ status: "idle" });
1818
- useEffect(() => {
1819
- if (!slugTouched) setSlug(slugify(name));
1820
- }, [name, slugTouched]);
1821
- useEffect(() => {
1822
- const s = slug.trim().toLowerCase();
1823
- if (!s) {
1824
- setSlugCheck({ status: "idle" });
1825
- return;
1826
- }
1827
- if (!/^[a-z0-9-]{2,64}$/.test(s)) {
1828
- setSlugCheck({ status: "invalid", checked: s });
1829
- return;
1830
- }
1831
- setSlugCheck({ status: "checking", checked: s });
1832
- const handle = setTimeout(async () => {
1833
- try {
1834
- const res = await fetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/tenants/check-slug?slug=${encodeURIComponent(s)}`, {
1835
- credentials: "include",
1836
- headers: { Accept: "application/json" }
1837
- });
1838
- const body = await res.json().catch(() => ({}));
1839
- const data = body.data;
1840
- if (!data) {
1841
- setSlugCheck({ status: "idle", checked: s });
1842
- return;
1843
- }
1844
- if (data.reason === "INVALID_FORMAT") {
1845
- setSlugCheck({ status: "invalid", checked: s });
1846
- return;
1847
- }
1848
- setSlugCheck({ status: data.available ? "available" : "taken", checked: s });
1849
- } catch {
1850
- setSlugCheck({ status: "idle", checked: s });
1851
- }
1852
- }, 350);
1853
- return () => clearTimeout(handle);
1854
- }, [slug, iqAuthBaseUrl]);
1855
- const submit = async (e) => {
1856
- e.preventDefault();
1857
- setSubmitting(true);
1858
- setError(null);
1859
- try {
1860
- const res = await jsonFetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/tenants`, {
1861
- method: "POST",
1862
- headers: { "Content-Type": "application/json" },
1863
- credentials: "include",
1864
- body: JSON.stringify({ name: name.trim(), slug: slug.trim() })
1865
- });
1866
- const payload = res;
1867
- const tenant = payload.data ?? payload;
1868
- const next = { id: tenant.id, name: tenant.name, slug: tenant.slug };
1869
- setCreated(next);
1870
- onCreated?.(next);
1871
- setName("");
1872
- setSlug("");
1873
- setSlugTouched(false);
1874
- if (redirectUrl && typeof window !== "undefined") {
1875
- const url = typeof redirectUrl === "function" ? redirectUrl(next) : redirectUrl;
1876
- if (url) window.location.assign(url);
1877
- }
1878
- } catch (err) {
1879
- setError(err instanceof Error ? err.message : "Failed to create organization");
1880
- } finally {
1881
- setSubmitting(false);
1882
- }
1883
- };
1884
- const form = /* @__PURE__ */ jsxs("form", { onSubmit: submit, style: { display: "flex", flexDirection: "column", gap: 12 }, "data-iqauth-sdk-create-org": "", "aria-labelledby": "iqauth-create-org-heading", children: [
1885
- error ? /* @__PURE__ */ jsx(ErrorBanner, { message: error }) : null,
1886
- created ? /* @__PURE__ */ jsxs("p", { role: "status", style: { fontSize: 13, color: "#047857" }, children: [
1887
- "Organization \u201C",
1888
- created.name,
1889
- "\u201D created."
1890
- ] }) : null,
1891
- /* @__PURE__ */ jsx(Field, { label: "Organization name", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-create-org-name", autoFocus: true, style: inputStyle(), value: name, onChange: (e) => setName(e.target.value), required: true, minLength: 2, "aria-required": "true" }) }),
1892
- /* @__PURE__ */ jsxs(Field, { label: "Organization slug", children: [
1893
- /* @__PURE__ */ jsx(
1894
- "input",
1895
- {
1896
- "data-testid": "input-create-org-slug",
1897
- style: { ...inputStyle(), fontFamily: "monospace" },
1898
- value: slug,
1899
- onChange: (e) => {
1900
- setSlugTouched(true);
1901
- setSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-"));
1902
- },
1903
- required: true,
1904
- pattern: "[a-z0-9-]+",
1905
- minLength: 2,
1906
- "aria-required": "true",
1907
- "aria-describedby": "iqauth-create-org-slug-hint",
1908
- "aria-invalid": slugCheck.status === "taken" || slugCheck.status === "invalid"
1909
- }
1910
- ),
1911
- /* @__PURE__ */ jsx(
1912
- "p",
1913
- {
1914
- id: "iqauth-create-org-slug-hint",
1915
- "data-testid": "text-create-org-slug-status",
1916
- role: "status",
1917
- "aria-live": "polite",
1918
- style: { fontSize: 12, marginTop: 4, color: slugCheck.status === "taken" || slugCheck.status === "invalid" ? "#b91c1c" : slugCheck.status === "available" ? "#047857" : "inherit", opacity: slugCheck.status === "checking" ? 0.6 : 1 },
1919
- children: slugCheck.status === "checking" ? "Checking availability\u2026" : slugCheck.status === "available" ? "Slug is available." : slugCheck.status === "taken" ? "That slug is taken." : slugCheck.status === "invalid" ? "Slugs must be 2\u201364 chars, lowercase letters/numbers/hyphens." : "We'll auto-generate a slug from the name; you can override it."
1920
- }
1921
- )
1922
- ] }),
1923
- /* @__PURE__ */ jsx(
1924
- PrimaryButton,
1925
- {
1926
- "data-testid": "button-create-org-submit",
1927
- type: "submit",
1928
- disabled: submitting || !name.trim() || !slug.trim() || slugCheck.status === "taken" || slugCheck.status === "invalid" || slugCheck.status === "checking",
1929
- children: submitting ? "Creating\u2026" : "Create organization"
1930
- }
1931
- )
1932
- ] });
1933
- if (unstyled) {
1934
- return /* @__PURE__ */ jsxs("div", { className, "data-iqauth-sdk-create-org-bare": "", children: [
1935
- /* @__PURE__ */ jsx("h3", { id: "iqauth-create-org-heading", style: { fontSize: 14, fontWeight: 600, margin: "0 0 12px" }, children: "Create organization" }),
1936
- form
1937
- ] });
1938
- }
1939
- return /* @__PURE__ */ jsx(Shell, { appearance, branding, className, title: "Create organization", subtitle: "Spin up a new tenant for this app.", children: form });
1940
- }
1941
- function OrganizationProfile({ iqAuthBaseUrl, tenantId: tenantIdProp, tabs, onDeleted, appearance, className }) {
1942
- const branding = useResolvedSdkBranding(iqAuthBaseUrl);
1943
- const baseUrl = iqAuthBaseUrl.replace(/\/$/, "");
1944
- const visibleTabs = tabs && tabs.length > 0 ? tabs : ["general", "members", "invitations", "danger"];
1945
- const [activeTab, setActiveTab] = useState(visibleTabs[0]);
1946
- const [tenantId, setTenantId] = useState(tenantIdProp || null);
1947
- const [tenant, setTenant] = useState(null);
1948
- const [members, setMembers] = useState([]);
1949
- const [pendingInvites, setPendingInvites] = useState([]);
1950
- const [loading, setLoading] = useState(true);
1951
- const [invitesLoading, setInvitesLoading] = useState(false);
1952
- const [error, setError] = useState(null);
1953
- const [renameValue, setRenameValue] = useState("");
1954
- const [slugValue, setSlugValue] = useState("");
1955
- const [renameSubmitting, setRenameSubmitting] = useState(false);
1956
- const [inviteEmail, setInviteEmail] = useState("");
1957
- const [inviteRole, setInviteRole] = useState("tenant_member");
1958
- const [inviteSubmitting, setInviteSubmitting] = useState(false);
1959
- const [actionMessage, setActionMessage] = useState(null);
1960
- const [confirmDeleteText, setConfirmDeleteText] = useState("");
1961
- const [confirmDeletePassword, setConfirmDeletePassword] = useState("");
1962
- const [deleteSubmitting, setDeleteSubmitting] = useState(false);
1963
- const { user } = useUser();
1964
- const callerRole = user?.role || null;
1965
- const callerIsAdmin = callerRole === "tenant_admin" || callerRole === "platform_admin";
1966
- const visibleTabsFiltered = visibleTabs.filter((t2) => t2 !== "danger" || callerIsAdmin);
1967
- useEffect(() => {
1968
- let cancelled = false;
1969
- (async () => {
1970
- try {
1971
- let tid = tenantIdProp || null;
1972
- if (!tid) {
1973
- const me = await fetch(`${baseUrl}/api/v1/auth/me`, { credentials: "include" }).then((r) => r.json());
1974
- tid = me?.data?.tenantId || null;
1975
- }
1976
- if (!tid) {
1977
- if (!cancelled) {
1978
- setError("No active tenant");
1979
- setLoading(false);
1980
- }
1981
- return;
1982
- }
1983
- const t2 = await fetch(`${baseUrl}/api/v1/tenants/${tid}`, { credentials: "include" }).then((r) => r.json());
1984
- const m = await fetch(`${baseUrl}/api/v1/tenants/${tid}/users`, { credentials: "include" }).then((r) => r.json());
1985
- if (cancelled) return;
1986
- setTenantId(tid);
1987
- setTenant(t2?.data ? { id: t2.data.id, name: t2.data.name, slug: t2.data.slug } : null);
1988
- setRenameValue(t2?.data?.name || "");
1989
- setSlugValue(t2?.data?.slug || "");
1990
- const rows = m?.data || [];
1991
- setMembers(rows.map((row) => ({
1992
- userId: String(row.userId ?? row.user?.id ?? row.id ?? ""),
1993
- email: String(row.email ?? row.user?.email ?? ""),
1994
- name: String(row.name ?? row.user?.name ?? ""),
1995
- role: String(row.role ?? row.roles?.[0] ?? "tenant_member"),
1996
- joinedAt: row.joinedAt ?? row.createdAt
1997
- })));
1998
- } catch (err) {
1999
- if (!cancelled) setError(err instanceof Error ? err.message : "Failed to load organization");
2000
- } finally {
2001
- if (!cancelled) setLoading(false);
2002
- }
2003
- })();
2004
- return () => {
2005
- cancelled = true;
2006
- };
2007
- }, [baseUrl, tenantIdProp]);
2008
- const loadInvites = async (tid) => {
2009
- setInvitesLoading(true);
2010
- try {
2011
- const r = await fetch(`${baseUrl}/api/v1/invites?tenantId=${encodeURIComponent(tid)}&status=pending`, { credentials: "include" }).then((res) => res.json());
2012
- const rows = r?.data || [];
2013
- setPendingInvites(rows.map((inv) => ({
2014
- id: String(inv.id),
2015
- email: String(inv.email),
2016
- role: String(inv.role),
2017
- status: String(inv.status),
2018
- expiresAt: inv.expiresAt,
2019
- createdAt: inv.createdAt
2020
- })));
2021
- } catch (err) {
2022
- setError(err instanceof Error ? err.message : "Failed to load invitations");
2023
- } finally {
2024
- setInvitesLoading(false);
2025
- }
2026
- };
2027
- useEffect(() => {
2028
- if (activeTab === "invitations" && tenantId) loadInvites(tenantId);
2029
- }, [activeTab, tenantId]);
2030
- const reloadMembers = async () => {
2031
- if (!tenantId) return;
2032
- const m = await fetch(`${baseUrl}/api/v1/tenants/${tenantId}/users`, { credentials: "include" }).then((r) => r.json());
2033
- const rows = m?.data || [];
2034
- setMembers(rows.map((row) => ({
2035
- userId: String(row.userId ?? row.user?.id ?? row.id ?? ""),
2036
- email: String(row.email ?? row.user?.email ?? ""),
2037
- name: String(row.name ?? row.user?.name ?? ""),
2038
- role: String(row.role ?? row.roles?.[0] ?? "tenant_member"),
2039
- joinedAt: row.joinedAt ?? row.createdAt
2040
- })));
2041
- };
2042
- const submitRename = async (e) => {
2043
- e.preventDefault();
2044
- if (!tenantId) return;
2045
- setRenameSubmitting(true);
2046
- setError(null);
2047
- try {
2048
- const body = {};
2049
- if (renameValue.trim() && renameValue.trim() !== tenant?.name) body.name = renameValue.trim();
2050
- if (slugValue.trim() && slugValue.trim() !== tenant?.slug) body.slug = slugValue.trim();
2051
- if (Object.keys(body).length === 0) {
2052
- setRenameSubmitting(false);
2053
- return;
2054
- }
2055
- const res = await jsonFetch(`${baseUrl}/api/v1/tenants/${tenantId}`, {
2056
- method: "PATCH",
2057
- headers: { "Content-Type": "application/json" },
2058
- credentials: "include",
2059
- body: JSON.stringify(body)
2060
- });
2061
- const t2 = res?.data ?? res;
2062
- setTenant({ id: t2.id, name: t2.name, slug: t2.slug });
2063
- setActionMessage("Organization saved.");
2064
- } catch (err) {
2065
- setError(err instanceof Error ? err.message : "Failed to save");
2066
- } finally {
2067
- setRenameSubmitting(false);
2068
- }
2069
- };
2070
- const submitInvite = async (e) => {
2071
- e.preventDefault();
2072
- if (!tenantId) return;
2073
- setInviteSubmitting(true);
2074
- setError(null);
2075
- try {
2076
- await jsonFetch(`${baseUrl}/api/v1/tenants/${tenantId}/users/invite`, {
2077
- method: "POST",
2078
- headers: { "Content-Type": "application/json" },
2079
- credentials: "include",
2080
- body: JSON.stringify({ email: inviteEmail.trim(), role: inviteRole })
2081
- });
2082
- setActionMessage(`Invitation sent to ${inviteEmail.trim()}.`);
2083
- setInviteEmail("");
2084
- if (activeTab === "invitations") await loadInvites(tenantId);
2085
- } catch (err) {
2086
- setError(err instanceof Error ? err.message : "Failed to invite");
2087
- } finally {
2088
- setInviteSubmitting(false);
2089
- }
2090
- };
2091
- const changeRole = async (userId, role) => {
2092
- if (!tenantId) return;
2093
- try {
2094
- await jsonFetch(`${baseUrl}/api/v1/tenants/${tenantId}/users/${userId}/role`, {
2095
- method: "PATCH",
2096
- headers: { "Content-Type": "application/json" },
2097
- credentials: "include",
2098
- body: JSON.stringify({ role })
2099
- });
2100
- await reloadMembers();
2101
- setActionMessage("Role updated.");
2102
- } catch (err) {
2103
- setError(err instanceof Error ? err.message : "Failed to update role");
2104
- }
2105
- };
2106
- const removeMember = async (userId) => {
2107
- if (!tenantId) return;
2108
- try {
2109
- await jsonFetch(`${baseUrl}/api/v1/tenants/${tenantId}/users/${userId}`, { method: "DELETE", credentials: "include" });
2110
- await reloadMembers();
2111
- setActionMessage("Member removed.");
2112
- } catch (err) {
2113
- setError(err instanceof Error ? err.message : "Failed to remove member");
2114
- }
2115
- };
2116
- const resendInvite = async (id) => {
2117
- if (!tenantId) return;
2118
- try {
2119
- await jsonFetch(`${baseUrl}/api/v1/invites/${id}/resend`, { method: "POST", credentials: "include" });
2120
- setActionMessage("Invitation resent.");
2121
- await loadInvites(tenantId);
2122
- } catch (err) {
2123
- setError(err instanceof Error ? err.message : "Failed to resend invitation");
2124
- }
2125
- };
2126
- const revokeInvite = async (id) => {
2127
- if (!tenantId) return;
2128
- try {
2129
- await jsonFetch(`${baseUrl}/api/v1/invites/${id}/revoke`, { method: "POST", credentials: "include" });
2130
- setActionMessage("Invitation revoked.");
2131
- await loadInvites(tenantId);
2132
- } catch (err) {
2133
- setError(err instanceof Error ? err.message : "Failed to revoke invitation");
2134
- }
2135
- };
2136
- const submitDelete = async () => {
2137
- if (!tenantId || !tenant) return;
2138
- if (confirmDeleteText !== tenant.slug) {
2139
- setError("Type the organization slug to confirm deletion.");
2140
- return;
2141
- }
2142
- if (!confirmDeletePassword) {
2143
- setError("Re-enter your password to confirm deletion.");
2144
- return;
2145
- }
2146
- setDeleteSubmitting(true);
2147
- setError(null);
2148
- try {
2149
- await jsonFetch(`${baseUrl}/api/v1/tenants/${tenantId}`, {
2150
- method: "DELETE",
2151
- credentials: "include",
2152
- headers: { "Content-Type": "application/json" },
2153
- body: JSON.stringify({ confirmPassword: confirmDeletePassword })
2154
- });
2155
- setActionMessage("Organization deleted.");
2156
- setConfirmDeletePassword("");
2157
- onDeleted?.(tenantId);
2158
- } catch (err) {
2159
- setError(err instanceof Error ? err.message : "Failed to delete organization");
2160
- } finally {
2161
- setDeleteSubmitting(false);
2162
- }
2163
- };
2164
- if (loading) {
2165
- return /* @__PURE__ */ jsx(Shell, { appearance, branding, className, title: "Organization", children: /* @__PURE__ */ jsx("p", { role: "status", "aria-live": "polite", style: { fontSize: 13 }, children: "Loading\u2026" }) });
2166
- }
2167
- const tabBtnStyle = (key) => ({
2168
- background: activeTab === key ? `${branding?.accentColor || "#6366f1"}1a` : "transparent",
2169
- border: `1px solid ${activeTab === key ? branding?.accentColor || "#6366f1" : "rgba(15,23,42,0.12)"}`,
2170
- color: branding?.primaryColor || "#0f172a",
2171
- padding: "6px 12px",
2172
- borderRadius: 6,
2173
- cursor: "pointer",
2174
- fontSize: 12,
2175
- fontWeight: 500
2176
- });
2177
- return /* @__PURE__ */ jsx(Shell, { appearance, branding, className, title: tenant?.name || "Organization", subtitle: tenant?.slug ? `slug: ${tenant.slug}` : void 0, children: /* @__PURE__ */ jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 16 }, "data-iqauth-sdk-org-profile": "", children: [
2178
- error ? /* @__PURE__ */ jsx(ErrorBanner, { message: error }) : null,
2179
- actionMessage ? /* @__PURE__ */ jsx("p", { role: "status", "aria-live": "polite", style: { fontSize: 13, color: "#047857", margin: 0 }, children: actionMessage }) : null,
2180
- /* @__PURE__ */ jsx("div", { role: "tablist", "aria-label": "Organization sections", style: { display: "flex", gap: 6, flexWrap: "wrap" }, children: visibleTabsFiltered.map((t2) => /* @__PURE__ */ jsx(
2181
- "button",
2182
- {
2183
- role: "tab",
2184
- "aria-selected": activeTab === t2,
2185
- "aria-controls": `iqauth-org-tab-${t2}`,
2186
- "data-testid": `tab-org-${t2}`,
2187
- type: "button",
2188
- onClick: () => setActiveTab(t2),
2189
- style: tabBtnStyle(t2),
2190
- children: t2 === "general" ? "General" : t2 === "members" ? `Members (${members.length})` : t2 === "invitations" ? "Invitations" : "Danger zone"
2191
- },
2192
- t2
2193
- )) }),
2194
- activeTab === "general" ? /* @__PURE__ */ jsxs("section", { role: "tabpanel", id: "iqauth-org-tab-general", "aria-labelledby": "tab-org-general", style: { display: "flex", flexDirection: "column", gap: 8 }, children: [
2195
- /* @__PURE__ */ jsx("h3", { style: { fontSize: 14, fontWeight: 600, margin: 0 }, children: "Settings" }),
2196
- /* @__PURE__ */ jsxs("form", { onSubmit: submitRename, style: { display: "flex", flexDirection: "column", gap: 8 }, children: [
2197
- /* @__PURE__ */ jsx(Field, { label: "Organization name", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-org-rename", style: inputStyle(), value: renameValue, onChange: (e) => setRenameValue(e.target.value), required: true, minLength: 2 }) }),
2198
- /* @__PURE__ */ jsx(Field, { label: "Slug", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-org-slug", style: { ...inputStyle(), fontFamily: "monospace" }, value: slugValue, onChange: (e) => setSlugValue(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-")), required: true, pattern: "[a-z0-9-]+", minLength: 2 }) }),
2199
- /* @__PURE__ */ jsx(PrimaryButton, { "data-testid": "button-org-rename", type: "submit", disabled: renameSubmitting || renameValue.trim() === tenant?.name && slugValue.trim() === tenant?.slug, children: renameSubmitting ? "Saving\u2026" : "Save changes" })
2200
- ] })
2201
- ] }) : null,
2202
- activeTab === "members" ? /* @__PURE__ */ jsxs("section", { role: "tabpanel", id: "iqauth-org-tab-members", "aria-labelledby": "tab-org-members", style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
2203
- /* @__PURE__ */ jsxs("form", { onSubmit: submitInvite, style: { display: "flex", gap: 8, flexWrap: "wrap" }, "aria-label": "Invite a new member", children: [
2204
- /* @__PURE__ */ jsx("input", { "data-testid": "input-org-invite-email", type: "email", placeholder: "email@company.com", "aria-label": "Email", style: { ...inputStyle(), flex: 1, minWidth: 180 }, value: inviteEmail, onChange: (e) => setInviteEmail(e.target.value), required: true }),
2205
- /* @__PURE__ */ jsxs("select", { "data-testid": "select-org-invite-role", "aria-label": "Role", style: { ...inputStyle(), width: "auto" }, value: inviteRole, onChange: (e) => setInviteRole(e.target.value), children: [
2206
- /* @__PURE__ */ jsx("option", { value: "tenant_member", children: "tenant_member" }),
2207
- /* @__PURE__ */ jsx("option", { value: "tenant_admin", children: "tenant_admin" })
2208
- ] }),
2209
- /* @__PURE__ */ jsx(PrimaryButton, { "data-testid": "button-org-invite", type: "submit", disabled: inviteSubmitting || !inviteEmail.trim(), children: inviteSubmitting ? "Sending\u2026" : "Send invite" })
2210
- ] }),
2211
- members.length === 0 ? /* @__PURE__ */ jsx("p", { style: { fontSize: 13, opacity: 0.6 }, children: "No members yet." }) : /* @__PURE__ */ jsx("ul", { "aria-label": "Members", style: { listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }, children: members.map((m) => /* @__PURE__ */ jsxs("li", { "data-testid": `row-org-member-${m.userId}`, style: { display: "grid", gridTemplateColumns: "1fr auto auto", gap: 8, alignItems: "center", padding: "8px 10px", background: "rgba(15,23,42,0.04)", borderRadius: 6, fontSize: 13 }, children: [
2212
- /* @__PURE__ */ jsxs("div", { children: [
2213
- /* @__PURE__ */ jsx("div", { style: { fontWeight: 500 }, children: m.name || m.email }),
2214
- /* @__PURE__ */ jsx("div", { style: { fontSize: 11, opacity: 0.7 }, children: m.email })
2215
- ] }),
2216
- /* @__PURE__ */ jsxs("select", { "data-testid": `select-org-member-role-${m.userId}`, "aria-label": `Role for ${m.email}`, value: m.role, onChange: (e) => changeRole(m.userId, e.target.value), style: { ...inputStyle(), width: "auto", padding: "4px 8px", fontSize: 12 }, children: [
2217
- /* @__PURE__ */ jsx("option", { value: "tenant_member", children: "tenant_member" }),
2218
- /* @__PURE__ */ jsx("option", { value: "tenant_admin", children: "tenant_admin" })
2219
- ] }),
2220
- /* @__PURE__ */ jsx(
2221
- "button",
2222
- {
2223
- type: "button",
2224
- "data-testid": `button-org-member-remove-${m.userId}`,
2225
- "aria-label": `Remove ${m.email}`,
2226
- onClick: () => removeMember(m.userId),
2227
- style: { background: "transparent", border: "1px solid rgba(220,38,38,0.4)", color: "#b91c1c", borderRadius: 4, padding: "4px 10px", cursor: "pointer", fontSize: 12 },
2228
- children: "Remove"
2229
- }
2230
- )
2231
- ] }, m.userId)) })
2232
- ] }) : null,
2233
- activeTab === "invitations" ? /* @__PURE__ */ jsxs("section", { role: "tabpanel", id: "iqauth-org-tab-invitations", "aria-labelledby": "tab-org-invitations", style: { display: "flex", flexDirection: "column", gap: 8 }, children: [
2234
- /* @__PURE__ */ jsx("h3", { style: { fontSize: 14, fontWeight: 600, margin: 0 }, children: "Pending invitations" }),
2235
- invitesLoading ? /* @__PURE__ */ jsx("p", { role: "status", "aria-live": "polite", style: { fontSize: 13 }, children: "Loading\u2026" }) : pendingInvites.length === 0 ? /* @__PURE__ */ jsx("p", { style: { fontSize: 13, opacity: 0.6 }, children: "No pending invitations." }) : /* @__PURE__ */ jsx("ul", { "aria-label": "Pending invitations", style: { listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }, children: pendingInvites.map((inv) => /* @__PURE__ */ jsxs("li", { "data-testid": `row-org-invite-${inv.id}`, style: { display: "grid", gridTemplateColumns: "1fr auto auto", gap: 8, alignItems: "center", padding: "8px 10px", background: "rgba(15,23,42,0.04)", borderRadius: 6, fontSize: 13 }, children: [
2236
- /* @__PURE__ */ jsxs("div", { children: [
2237
- /* @__PURE__ */ jsx("div", { style: { fontWeight: 500 }, children: inv.email }),
2238
- /* @__PURE__ */ jsxs("div", { style: { fontSize: 11, opacity: 0.7 }, children: [
2239
- "role: ",
2240
- inv.role,
2241
- inv.expiresAt ? ` \u2022 expires ${new Date(inv.expiresAt).toLocaleDateString()}` : ""
2242
- ] })
2243
- ] }),
2244
- /* @__PURE__ */ jsx(
2245
- "button",
2246
- {
2247
- type: "button",
2248
- "data-testid": `button-org-invite-resend-${inv.id}`,
2249
- onClick: () => resendInvite(inv.id),
2250
- style: { background: "transparent", border: "1px solid rgba(15,23,42,0.18)", color: "#0f172a", borderRadius: 4, padding: "4px 10px", cursor: "pointer", fontSize: 12 },
2251
- children: "Resend"
2252
- }
2253
- ),
2254
- /* @__PURE__ */ jsx(
2255
- "button",
2256
- {
2257
- type: "button",
2258
- "data-testid": `button-org-invite-revoke-${inv.id}`,
2259
- onClick: () => revokeInvite(inv.id),
2260
- style: { background: "transparent", border: "1px solid rgba(220,38,38,0.4)", color: "#b91c1c", borderRadius: 4, padding: "4px 10px", cursor: "pointer", fontSize: 12 },
2261
- children: "Revoke"
2262
- }
2263
- )
2264
- ] }, inv.id)) })
2265
- ] }) : null,
2266
- activeTab === "danger" ? /* @__PURE__ */ jsxs("section", { role: "tabpanel", id: "iqauth-org-tab-danger", "aria-labelledby": "tab-org-danger", style: { display: "flex", flexDirection: "column", gap: 10, border: "1px solid rgba(220,38,38,0.3)", padding: 12, borderRadius: 8, background: "rgba(220,38,38,0.04)" }, children: [
2267
- /* @__PURE__ */ jsx("h3", { style: { fontSize: 14, fontWeight: 600, margin: 0, color: "#b91c1c" }, children: "Delete organization" }),
2268
- /* @__PURE__ */ jsxs("p", { style: { fontSize: 12, opacity: 0.85, margin: 0 }, children: [
2269
- "This permanently deletes ",
2270
- /* @__PURE__ */ jsx("strong", { children: tenant?.name }),
2271
- " and all of its members, roles, and audit history. To confirm, type the slug ",
2272
- /* @__PURE__ */ jsx("code", { children: tenant?.slug }),
2273
- " below."
2274
- ] }),
2275
- /* @__PURE__ */ jsx(Field, { label: "Type the organization slug to confirm", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-org-delete-confirm", autoComplete: "off", placeholder: tenant?.slug || "", "aria-label": "Type slug to confirm", style: { ...inputStyle(), fontFamily: "monospace" }, value: confirmDeleteText, onChange: (e) => setConfirmDeleteText(e.target.value) }) }),
2276
- /* @__PURE__ */ jsx(Field, { label: "Re-enter your password", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-org-delete-password", type: "password", autoComplete: "current-password", "aria-label": "Password to confirm deletion", style: inputStyle(), value: confirmDeletePassword, onChange: (e) => setConfirmDeletePassword(e.target.value) }) }),
2277
- /* @__PURE__ */ jsx(
2278
- "button",
2279
- {
2280
- type: "button",
2281
- "data-testid": "button-org-delete",
2282
- onClick: submitDelete,
2283
- disabled: deleteSubmitting || confirmDeleteText !== tenant?.slug || !confirmDeletePassword,
2284
- style: { background: "#b91c1c", color: "#fff", border: "none", padding: "8px 14px", borderRadius: 6, cursor: confirmDeleteText === tenant?.slug && confirmDeletePassword ? "pointer" : "not-allowed", fontSize: 13, opacity: confirmDeleteText === tenant?.slug && confirmDeletePassword ? 1 : 0.5 },
2285
- children: deleteSubmitting ? "Deleting\u2026" : "Permanently delete organization"
2286
- }
2287
- )
2288
- ] }) : null
2289
- ] }) });
2290
- }
2291
- function OrganizationList({ iqAuthBaseUrl, onSelect, showCreate = true, createRedirectUrl, appearance, className }) {
2292
- const [showCreateForm, setShowCreateForm] = useState(false);
2293
- const reloadList = () => {
2294
- setShowCreateForm(false);
2295
- if (typeof window !== "undefined") setTimeout(() => window.location.reload(), 50);
2296
- };
2297
- const branding = useResolvedSdkBranding(iqAuthBaseUrl);
2298
- const baseUrl = iqAuthBaseUrl.replace(/\/$/, "");
2299
- const accent = branding?.accentColor || "#6366f1";
2300
- const [memberships, setMemberships] = useState([]);
2301
- const [activeTenantId, setActiveTenantId] = useState(null);
2302
- const [loading, setLoading] = useState(true);
2303
- const [error, setError] = useState(null);
2304
- useEffect(() => {
2305
- let cancelled = false;
2306
- Promise.all([
2307
- fetch(`${baseUrl}/api/v1/auth/me`, { credentials: "include" }).then((r) => r.json()),
2308
- fetch(`${baseUrl}/api/v1/tenants/memberships`, { credentials: "include" }).then((r) => r.json())
2309
- ]).then(([me, mems]) => {
2310
- if (cancelled) return;
2311
- setActiveTenantId(me?.data?.tenantId || null);
2312
- setMemberships(mems?.data?.memberships || mems?.data || []);
2313
- }).catch((err) => {
2314
- if (!cancelled) setError(err instanceof Error ? err.message : "Failed to load organizations");
2315
- }).finally(() => {
2316
- if (!cancelled) setLoading(false);
2317
- });
2318
- return () => {
2319
- cancelled = true;
2320
- };
2321
- }, [baseUrl]);
2322
- const select = async (tenantId) => {
2323
- if (tenantId === activeTenantId) {
2324
- onSelect?.(tenantId);
2325
- return;
2326
- }
2327
- try {
2328
- await jsonFetch(`${baseUrl}/api/v1/auth/select-tenant`, {
2329
- method: "POST",
2330
- headers: { "Content-Type": "application/json" },
2331
- credentials: "include",
2332
- body: JSON.stringify({ tenantId })
2333
- });
2334
- setActiveTenantId(tenantId);
2335
- onSelect?.(tenantId);
2336
- } catch (err) {
2337
- setError(err instanceof Error ? err.message : "Failed to switch organization");
2338
- }
2339
- };
2340
- return /* @__PURE__ */ jsx(Shell, { appearance, branding, className, title: "Your organizations", subtitle: "Select an organization to make it active.", children: /* @__PURE__ */ jsxs("div", { "data-iqauth-sdk-org-list": "", style: { display: "flex", flexDirection: "column", gap: 8 }, children: [
2341
- error ? /* @__PURE__ */ jsx(ErrorBanner, { message: error }) : null,
2342
- loading ? /* @__PURE__ */ jsx("p", { style: { fontSize: 13 }, children: "Loading\u2026" }) : memberships.length === 0 ? /* @__PURE__ */ jsx("p", { style: { fontSize: 13, opacity: 0.6 }, children: "You don\u2019t belong to any organizations yet." }) : /* @__PURE__ */ jsx("ul", { style: { listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 6 }, children: memberships.map((m) => {
2343
- const active = m.tenantId === activeTenantId;
2344
- return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
2345
- "button",
2346
- {
2347
- type: "button",
2348
- "data-testid": `button-org-list-${m.tenantId}`,
2349
- onClick: () => select(m.tenantId),
2350
- style: {
2351
- display: "block",
2352
- width: "100%",
2353
- textAlign: "left",
2354
- padding: "10px 12px",
2355
- borderRadius: 6,
2356
- cursor: "pointer",
2357
- fontSize: 13,
2358
- background: active ? `${accent}1a` : "transparent",
2359
- border: `1px solid ${active ? accent : "rgba(15,23,42,0.12)"}`,
2360
- color: branding?.primaryColor || "#0f172a"
2361
- },
2362
- children: [
2363
- /* @__PURE__ */ jsx("div", { style: { fontWeight: 500 }, children: m.tenantName || m.tenantSlug || m.tenantId }),
2364
- /* @__PURE__ */ jsxs("div", { style: { fontSize: 11, opacity: 0.7 }, children: [
2365
- (m.roles || []).join(", ") || "\u2014",
2366
- active ? /* @__PURE__ */ jsx("span", { style: { marginLeft: 8, color: accent, fontWeight: 600 }, children: "active" }) : null
2367
- ] })
2368
- ]
2369
- }
2370
- ) }, m.tenantId);
2371
- }) }),
2372
- showCreate ? /* @__PURE__ */ jsx("div", { style: { marginTop: 12, paddingTop: 12, borderTop: "1px solid rgba(15,23,42,0.08)" }, children: showCreateForm ? /* @__PURE__ */ jsxs(Fragment2, { children: [
2373
- /* @__PURE__ */ jsx(
2374
- CreateOrganization,
2375
- {
2376
- iqAuthBaseUrl,
2377
- unstyled: true,
2378
- appearance,
2379
- onCreated: (t2) => {
2380
- onSelect?.(t2.id);
2381
- reloadList();
2382
- },
2383
- redirectUrl: createRedirectUrl
2384
- }
2385
- ),
2386
- /* @__PURE__ */ jsx(
2387
- "button",
2388
- {
2389
- type: "button",
2390
- "data-testid": "button-org-list-create-cancel",
2391
- onClick: () => setShowCreateForm(false),
2392
- style: { marginTop: 8, background: "transparent", border: "none", color: branding?.accentColor || "#6366f1", cursor: "pointer", fontSize: 12, padding: 0 },
2393
- children: "Cancel"
2394
- }
2395
- )
2396
- ] }) : /* @__PURE__ */ jsx(
2397
- "button",
2398
- {
2399
- type: "button",
2400
- "data-testid": "button-org-list-create",
2401
- onClick: () => setShowCreateForm(true),
2402
- style: { background: "transparent", border: `1px dashed ${accent}`, color: branding?.primaryColor || "#0f172a", padding: "10px 12px", borderRadius: 6, cursor: "pointer", fontSize: 13, width: "100%" },
2403
- children: "+ Create new organization"
2404
- }
2405
- ) }) : null
2406
- ] }) });
2407
- }
2408
- function Waitlist({ iqAuthBaseUrl, appKey, appId, title, subtitle, successMessage, appearance, className }) {
2409
- const branding = useResolvedSdkBranding(iqAuthBaseUrl, appId);
2410
- const [email, setEmail] = useState("");
2411
- const [name, setName] = useState("");
2412
- const [organizationName, setOrganizationName] = useState("");
2413
- const [submitting, setSubmitting] = useState(false);
2414
- const [error, setError] = useState(null);
2415
- const [submitted, setSubmitted] = useState(null);
2416
- const submit = async (e) => {
2417
- e.preventDefault();
2418
- setSubmitting(true);
2419
- setError(null);
2420
- try {
2421
- const res = await jsonFetch(`${iqAuthBaseUrl.replace(/\/$/, "")}/api/v1/waitlist`, {
2422
- method: "POST",
2423
- headers: { "Content-Type": "application/json" },
2424
- body: JSON.stringify({
2425
- email: email.trim().toLowerCase(),
2426
- name: name.trim() || void 0,
2427
- organizationName: organizationName.trim() || void 0,
2428
- appKey: appKey || void 0,
2429
- appId: appId || void 0
2430
- })
2431
- });
2432
- const data = res?.data ?? res;
2433
- setSubmitted({ duplicate: !!data?.duplicate });
2434
- } catch (err) {
2435
- setError(err instanceof Error ? err.message : "Failed to join the waitlist");
2436
- } finally {
2437
- setSubmitting(false);
2438
- }
2439
- };
2440
- if (submitted) {
2441
- return /* @__PURE__ */ jsx(Shell, { appearance, branding, className, title: title || "You\u2019re on the list", children: /* @__PURE__ */ jsx("p", { "data-testid": "text-waitlist-success", style: { fontSize: 14 }, children: successMessage || (submitted.duplicate ? "You were already on the waitlist \u2014 we\u2019ll be in touch." : "Thanks! We\u2019ll email you when access opens up.") }) });
2442
- }
2443
- return /* @__PURE__ */ jsx(Shell, { appearance, branding, className, title: title || "Join the waitlist", subtitle: subtitle || "Enter your email and we\u2019ll be in touch when access opens up.", children: /* @__PURE__ */ jsxs("form", { onSubmit: submit, style: { display: "flex", flexDirection: "column", gap: 12 }, "data-iqauth-sdk-waitlist": "", children: [
2444
- error ? /* @__PURE__ */ jsx(ErrorBanner, { message: error }) : null,
2445
- /* @__PURE__ */ jsx(Field, { label: "Work email", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-waitlist-email", type: "email", autoComplete: "email", required: true, style: inputStyle(), value: email, onChange: (e) => setEmail(e.target.value) }) }),
2446
- /* @__PURE__ */ jsx(Field, { label: "Name (optional)", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-waitlist-name", autoComplete: "name", style: inputStyle(), value: name, onChange: (e) => setName(e.target.value) }) }),
2447
- /* @__PURE__ */ jsx(Field, { label: "Organization (optional)", children: /* @__PURE__ */ jsx("input", { "data-testid": "input-waitlist-org", autoComplete: "organization", style: inputStyle(), value: organizationName, onChange: (e) => setOrganizationName(e.target.value) }) }),
2448
- /* @__PURE__ */ jsx(PrimaryButton, { "data-testid": "button-waitlist-submit", type: "submit", disabled: submitting || !email, children: submitting ? "Joining\u2026" : "Join the waitlist" })
2449
- ] }) });
2450
- }
2451
- function usePasswordlessOptions(override) {
2452
- const ctx = useContext(IQAuthContext);
2453
- const baseFromCtx = ctx?.manager?.issuerUrl;
2454
- const iqAuthBaseUrl = override?.iqAuthBaseUrl || baseFromCtx || (typeof window !== "undefined" ? window.location.origin : "");
2455
- return { iqAuthBaseUrl, cookieSession: override?.cookieSession ?? true };
2456
- }
2457
- function useMagicLink(override) {
2458
- const opts = usePasswordlessOptions(override);
2459
- const [sent, setSent] = useState(false);
2460
- const [busy, setBusy] = useState(false);
2461
- const [error, setError] = useState(null);
2462
- const request = useCallback(async (input) => {
2463
- setBusy(true);
2464
- setError(null);
2465
- setSent(false);
2466
- try {
2467
- await requestMagicLink(opts, input);
2468
- setSent(true);
2469
- } catch (e) {
2470
- setError(e instanceof Error ? e.message : "Magic link request failed");
2471
- } finally {
2472
- setBusy(false);
2473
- }
2474
- }, [opts.iqAuthBaseUrl, opts.cookieSession]);
2475
- return { request, sent, busy, error };
2476
- }
2477
- function usePasskey(override) {
2478
- const opts = usePasswordlessOptions(override);
2479
- const [busy, setBusy] = useState(false);
2480
- const [error, setError] = useState(null);
2481
- const signIn2 = useCallback(async (input = {}) => {
2482
- setBusy(true);
2483
- setError(null);
2484
- try {
2485
- return await signInWithPasskey(opts, input);
2486
- } catch (e) {
2487
- const msg = e instanceof Error ? e.message : "Passkey sign-in failed";
2488
- setError(msg);
2489
- throw e;
2490
- } finally {
2491
- setBusy(false);
2492
- }
2493
- }, [opts.iqAuthBaseUrl]);
2494
- const enroll = useCallback(async (name) => {
2495
- setBusy(true);
2496
- setError(null);
2497
- try {
2498
- return await enrollPasskey(opts, name);
2499
- } catch (e) {
2500
- const msg = e instanceof Error ? e.message : "Passkey enrollment failed";
2501
- setError(msg);
2502
- throw e;
2503
- } finally {
2504
- setBusy(false);
2505
- }
2506
- }, [opts.iqAuthBaseUrl]);
2507
- return { signIn: signIn2, enroll, busy, error };
2508
- }
2509
- function useLinkedIdentities(override) {
2510
- const opts = usePasswordlessOptions(override);
2511
- const [identities, setIdentities] = useState([]);
2512
- const [loading, setLoading] = useState(true);
2513
- const [error, setError] = useState(null);
2514
- const refresh = useCallback(async () => {
2515
- setLoading(true);
2516
- setError(null);
2517
- try {
2518
- setIdentities(await listLinkedIdentities(opts));
2519
- } catch (e) {
2520
- setError(e instanceof Error ? e.message : "Failed to load identities");
2521
- } finally {
2522
- setLoading(false);
2523
- }
2524
- }, [opts.iqAuthBaseUrl]);
2525
- const link = useCallback(async (input) => {
2526
- await linkProvider(opts, input);
2527
- await refresh();
2528
- }, [opts.iqAuthBaseUrl, refresh]);
2529
- const unlink = useCallback(async (provider, password) => {
2530
- await unlinkProvider(opts, { provider, reauth: { password } });
2531
- await refresh();
2532
- }, [opts.iqAuthBaseUrl, refresh]);
2533
- useEffect(() => {
2534
- refresh();
2535
- }, [refresh]);
2536
- return { identities, loading, error, refresh, link, unlink };
2537
- }
2538
- function MagicLinkSignInForm(props) {
2539
- const { request, sent, busy, error } = useMagicLink(props);
2540
- const [email, setEmail] = useState("");
2541
- return /* @__PURE__ */ jsxs(
2542
- "form",
2543
- {
2544
- "data-testid": "form-magic-link",
2545
- className: props.className,
2546
- onSubmit: (e) => {
2547
- e.preventDefault();
2548
- if (email) void request({ email, appId: props.appId, redirectUri: props.redirectUri });
2549
- },
2550
- style: { display: "flex", flexDirection: "column", gap: 8 },
2551
- children: [
2552
- /* @__PURE__ */ jsx(
2553
- "input",
2554
- {
2555
- "data-testid": "input-magic-link-email",
2556
- type: "email",
2557
- required: true,
2558
- value: email,
2559
- placeholder: props.placeholder ?? "you@example.com",
2560
- onChange: (e) => setEmail(e.target.value),
2561
- style: { padding: 8, border: "1px solid rgba(15,23,42,0.15)", borderRadius: 6 }
2562
- }
2563
- ),
2564
- /* @__PURE__ */ jsx("button", { "data-testid": "button-magic-link-submit", type: "submit", disabled: busy || !email, children: busy ? "Sending\u2026" : props.buttonLabel ?? "Email me a sign-in link" }),
2565
- sent ? /* @__PURE__ */ jsx("p", { "data-testid": "text-magic-link-sent", style: { fontSize: 12 }, children: "If the email is on file, a link is on the way." }) : null,
2566
- error ? /* @__PURE__ */ jsx("p", { "data-testid": "text-magic-link-error", style: { fontSize: 12, color: "#b91c1c" }, children: error }) : null
2567
- ]
2568
- }
2569
- );
2570
- }
2571
- function PasskeySignInButton({ email, className, children, ...rest }) {
2572
- const { signIn: signIn2, busy, error } = usePasskey(rest);
2573
- return /* @__PURE__ */ jsxs("div", { className, children: [
2574
- /* @__PURE__ */ jsx(
2575
- "button",
2576
- {
2577
- "data-testid": "button-passkey-signin",
2578
- disabled: busy,
2579
- onClick: () => void signIn2({ email }).catch(() => {
2580
- }),
2581
- style: { padding: "8px 12px", borderRadius: 6, border: "1px solid rgba(15,23,42,0.15)", background: "transparent", cursor: "pointer" },
2582
- children: busy ? "Verifying\u2026" : children ?? "Sign in with a passkey"
2583
- }
2584
- ),
2585
- error ? /* @__PURE__ */ jsx("p", { "data-testid": "text-passkey-error", style: { fontSize: 12, color: "#b91c1c", marginTop: 4 }, children: error }) : null
2586
- ] });
2587
- }
2588
- function LinkedAccounts({ className, onChange, ...rest }) {
2589
- const { identities, loading, error, unlink } = useLinkedIdentities(rest);
2590
- return /* @__PURE__ */ jsx("div", { "data-testid": "section-linked-accounts", className, children: loading ? /* @__PURE__ */ jsx("p", { children: "Loading\u2026" }) : error ? /* @__PURE__ */ jsx("p", { style: { color: "#b91c1c" }, children: error }) : /* @__PURE__ */ jsx("ul", { style: { listStyle: "none", padding: 0, margin: 0 }, children: identities.map((i) => /* @__PURE__ */ jsxs("li", { "data-testid": `row-identity-${i.provider}`, style: { display: "flex", justifyContent: "space-between", padding: "6px 0" }, children: [
2591
- /* @__PURE__ */ jsxs("span", { children: [
2592
- /* @__PURE__ */ jsx("strong", { style: { textTransform: "capitalize" }, children: i.provider }),
2593
- " ",
2594
- /* @__PURE__ */ jsx("span", { style: { opacity: 0.7 }, children: i.label || i.providerUserId || "" })
2595
- ] }),
2596
- i.canUnlink ? /* @__PURE__ */ jsx(
2597
- "button",
2598
- {
2599
- "data-testid": `button-unlink-${i.provider}`,
2600
- onClick: async () => {
2601
- const pw = window.prompt("Confirm your password to unlink this identity") || void 0;
2602
- try {
2603
- await unlink(i.provider, pw);
2604
- onChange?.();
2605
- } catch {
2606
- }
2607
- },
2608
- children: "Unlink"
2609
- }
2610
- ) : null
2611
- ] }, i.id)) }) });
2612
- }
2613
- var __version__ = "phase-bc-1.0.0";
2614
61
  export {
2615
62
  AuthCallback,
2616
63
  CreateOrganization,
@@ -2636,6 +83,7 @@ export {
2636
83
  UserButton,
2637
84
  UserProfile,
2638
85
  Waitlist,
86
+ __useIQAuthInternal,
2639
87
  __version__,
2640
88
  isReturnToAllowed,
2641
89
  isSilentSsoEligible,