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