@midsummer-ai/sdk 0.1.0-staging.3653 → 0.1.0-staging.3656

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/THIRD-PARTY-NOTICES +1279 -0
  2. package/auth/client.d.mts +222 -18
  3. package/auth/client.mjs +321 -40
  4. package/auth/contract.d.mts +10 -1
  5. package/auth/contract.mjs +347 -30
  6. package/auth/files.d.mts +2 -28
  7. package/auth/files.mjs +2 -231
  8. package/auth/impersonate.d.mts +33 -0
  9. package/auth/impersonate.mjs +42 -0
  10. package/auth/import.d.mts +71 -0
  11. package/auth/import.mjs +195 -0
  12. package/auth/index.d.mts +5 -198
  13. package/auth/index.mjs +3 -2
  14. package/auth/mail.d.mts +23 -5
  15. package/auth/mail.mjs +93 -39
  16. package/auth/password.d.mts +10 -2
  17. package/auth/password.mjs +14 -2
  18. package/auth/react.d.mts +86 -0
  19. package/auth/react.mjs +865 -0
  20. package/auth/stand-in.d.mts +14 -3
  21. package/auth/stand-in.mjs +162 -29
  22. package/auth-CND9RW17.mjs +1819 -0
  23. package/authorize-BzDrbYtI-0gOzDrp2.mjs +18783 -0
  24. package/{client-BX56cXDt.mjs → connection-C_JSWUrt.mjs} +3 -668
  25. package/database/client.mjs +665 -1
  26. package/dist-DXtY-DJA.mjs +343 -0
  27. package/engine-BhA0XgI7.mjs +48423 -0
  28. package/esm-E3EvzsGX.mjs +1518 -0
  29. package/factory-9jfDGyc1.mjs +1138 -0
  30. package/files-C-FvBxT4.d.mts +75 -0
  31. package/files-DAFOuID_.mjs +692 -0
  32. package/get-id-field-vhOArqXN.mjs +1455 -0
  33. package/index-CsgQ_ouh.d.mts +246 -0
  34. package/package.json +24 -7
  35. package/qr-C1mfuCT9.mjs +1163 -0
  36. package/request-state-BaLB2Hrt.mjs +85 -0
  37. package/rolldown-runtime-CL6CfywC.mjs +36 -0
  38. package/schemas-DTJTcCdK.mjs +6046 -0
  39. package/settings-si8iBtwc.d.mts +47 -0
  40. package/store-CeIGY-xT.d.mts +16 -0
  41. package/{store-B-1coCxW.mjs → store-CsBhnabU.mjs} +1 -1
  42. package/{tabs-CDplCS02.mjs → tabs-gHJHkhm2.mjs} +1 -1
  43. package/auth-Bf7IuulG.mjs +0 -754
  44. package/store-gCz6XVaG.d.mts +0 -15
package/auth/react.mjs ADDED
@@ -0,0 +1,865 @@
1
+ import { a as WORDS, c as setupKeyOf, i as CAPTCHA_WIDGETS, o as ago, r as AUTH_CSS, s as deviceOf, t as qrPath } from "../qr-C1mfuCT9.mjs";
2
+ import { AuthClientError, authClient } from "./client.mjs";
3
+ import { Fragment, createContext, createElement, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
4
+ //#region src/auth/react.ts
5
+ /**
6
+ * Sign-in's drop-in screens for React apps: React is the only thing they need.
7
+ *
8
+ * import { AuthProvider, SignIn, UserButton } from "@midsummer-ai/sdk/auth/react"
9
+ *
10
+ * <AuthProvider>
11
+ * <UserButton />
12
+ * <SignIn redirectTo="/dashboard" />
13
+ * </AuthProvider>
14
+ *
15
+ * `<SignIn/>`, `<SignUp/>`, `<UserButton/>`, `<UserProfile/>` (profile, password, two-step sign-in, passkeys,
16
+ * sessions, API keys and the apps a person let in), `<OrganizationSwitcher/>` and `<OrganizationProfile/>` (members,
17
+ * roles and invitations). They show only the ways in the app's settings turn on, in the app's name, logo and colour,
18
+ * with the app's own font; set `--msa-accent`, `--msa-radius` and the other variables in `./look.ts` on any parent to
19
+ * match the app's look. `useAuth()` gives any component who is signed in. The hosted pages under `/api/auth/ui` are
20
+ * the same screens for apps that don't use React.
21
+ */
22
+ const Context = createContext(null);
23
+ /** Gives the screens inside it the client and who is signed in; `baseURL` when the app's server is on another address. */
24
+ function AuthProvider(props) {
25
+ const client = useMemo(() => props.client ?? authClient(props.baseURL ? { baseURL: props.baseURL } : {}), [props.client, props.baseURL]);
26
+ const [signedIn, setSignedIn] = useState(void 0);
27
+ const [settings, setSettings] = useState(void 0);
28
+ const refresh = useCallback(async () => {
29
+ setSignedIn(await client.session().catch(() => null));
30
+ }, [client]);
31
+ useEffect(() => {
32
+ refresh();
33
+ client.settings().then(setSettings, () => {});
34
+ return client.onChange(() => void refresh());
35
+ }, [client, refresh]);
36
+ const state = useMemo(() => ({
37
+ client,
38
+ signedIn,
39
+ settings,
40
+ refresh
41
+ }), [
42
+ client,
43
+ signedIn,
44
+ settings,
45
+ refresh
46
+ ]);
47
+ return createElement(Context.Provider, { value: state }, createElement("style", { "data-msa": "" }, AUTH_CSS), props.children);
48
+ }
49
+ /** Who is signed in, the client and the app's settings: inside an `AuthProvider`. */
50
+ function useAuth() {
51
+ const state = useContext(Context);
52
+ if (!state) throw new Error("useAuth and the sign-in screens go inside <AuthProvider>.");
53
+ return state;
54
+ }
55
+ /** Runs one call at a time, keeping whether it is running and the words of its refusal. */
56
+ function useCall() {
57
+ const [busy, setBusy] = useState(false);
58
+ const [error, setError] = useState(null);
59
+ return {
60
+ busy,
61
+ error,
62
+ setError,
63
+ run: useCallback(async (work) => {
64
+ setBusy(true);
65
+ setError(null);
66
+ try {
67
+ await work();
68
+ return true;
69
+ } catch (caught) {
70
+ setError(caught instanceof AuthClientError ? caught.message : caught instanceof DOMException ? WORDS.errors.passkeyCancelled : WORDS.errors.generic);
71
+ return false;
72
+ } finally {
73
+ setBusy(false);
74
+ }
75
+ }, [])
76
+ };
77
+ }
78
+ /** The card every screen sits in, with the app's logo and colour. */
79
+ function Card(props) {
80
+ const { settings } = useAuth();
81
+ const color = settings?.branding.color;
82
+ return createElement("div", {
83
+ className: "msa",
84
+ style: color ? { "--msa-brand": color } : void 0
85
+ }, createElement("div", { className: props.wide ? "msa-card msa-wide" : "msa-card" }, settings?.branding.logo ? createElement("img", {
86
+ className: "msa-logo",
87
+ src: settings.branding.logo,
88
+ alt: settings.branding.name
89
+ }) : null, createElement("h1", null, props.title), props.lead ? createElement("p", { className: "msa-lead" }, props.lead) : null, props.children));
90
+ }
91
+ function Field(props) {
92
+ return createElement("label", null, props.label, createElement("input", {
93
+ type: props.type ?? "text",
94
+ value: props.value,
95
+ required: props.required ?? true,
96
+ autoComplete: props.autoComplete,
97
+ inputMode: props.inputMode,
98
+ onChange: (event) => props.onChange(event.target.value)
99
+ }));
100
+ }
101
+ const Problem = (props) => createElement("p", {
102
+ className: "msa-error",
103
+ role: "alert",
104
+ "aria-live": "assertive"
105
+ }, props.message ?? "");
106
+ const Note = (props) => createElement("p", {
107
+ className: "msa-note",
108
+ role: "status"
109
+ }, props.children);
110
+ function Submit(props) {
111
+ return createElement("button", {
112
+ type: "submit",
113
+ className: "msa-primary",
114
+ disabled: props.busy,
115
+ "aria-busy": props.busy
116
+ }, props.label);
117
+ }
118
+ const onSubmit = (work) => (event) => {
119
+ event.preventDefault();
120
+ work();
121
+ };
122
+ /** The bot check's widget, once the app sets one; `onToken` gets its token. */
123
+ function Captcha(props) {
124
+ const { settings } = useAuth();
125
+ const captcha = settings?.captcha;
126
+ const id = useId().replace(/[^a-zA-Z0-9]/g, "");
127
+ useEffect(() => {
128
+ if (!captcha) return;
129
+ const widget = CAPTCHA_WIDGETS[captcha.provider];
130
+ globalThis[`msaCaptcha${id}`] = props.onToken;
131
+ if (!document.querySelector(`script[src="${widget.script}"]`)) {
132
+ const script = document.createElement("script");
133
+ script.src = widget.script;
134
+ script.async = true;
135
+ document.head.append(script);
136
+ }
137
+ }, [
138
+ captcha,
139
+ id,
140
+ props.onToken
141
+ ]);
142
+ if (!captcha) return null;
143
+ return createElement("div", {
144
+ className: CAPTCHA_WIDGETS[captcha.provider].className,
145
+ "data-sitekey": captcha.siteKey,
146
+ "data-callback": `msaCaptcha${id}`
147
+ });
148
+ }
149
+ /** A secret shown once, on one line, with a Copy button that says when it copied. */
150
+ function Secret(props) {
151
+ const [copied, setCopied] = useState(false);
152
+ return createElement("div", { className: "msa-secret" }, createElement("code", { "aria-label": props.label }, props.value), createElement("button", {
153
+ type: "button",
154
+ onClick: () => void navigator.clipboard?.writeText(props.value).then(() => setCopied(true), () => {})
155
+ }, copied ? WORDS.account.copied : WORDS.account.copy));
156
+ }
157
+ /** The code an authenticator app scans as two-step sign-in starts. */
158
+ function QrCode(props) {
159
+ const { d, size } = qrPath(props.value);
160
+ return createElement("svg", {
161
+ className: "msa-qr",
162
+ role: "img",
163
+ "aria-label": WORDS.account.qr,
164
+ viewBox: `0 0 ${size} ${size}`,
165
+ width: 176,
166
+ height: 176,
167
+ shapeRendering: "crispEdges"
168
+ }, createElement("rect", {
169
+ width: size,
170
+ height: size,
171
+ fill: "#ffffff"
172
+ }), createElement("path", {
173
+ d,
174
+ fill: "#111111"
175
+ }));
176
+ }
177
+ /** A Copy button for a value that isn't on one line, such as backup codes. */
178
+ function CopyButton(props) {
179
+ const [copied, setCopied] = useState(false);
180
+ return createElement("div", null, createElement("button", {
181
+ type: "button",
182
+ onClick: () => void navigator.clipboard?.writeText(props.value).then(() => setCopied(true), () => {})
183
+ }, copied ? WORDS.account.copied : props.label));
184
+ }
185
+ /** A destructive action that asks first: its button, then the same words for good, beside Cancel. */
186
+ function Confirm(props) {
187
+ const [asking, setAsking] = useState(false);
188
+ if (!asking) return createElement("button", {
189
+ type: "button",
190
+ className: "msa-quiet msa-danger",
191
+ onClick: () => setAsking(true)
192
+ }, props.label);
193
+ return createElement("div", { style: {
194
+ display: "flex",
195
+ gap: 8
196
+ } }, createElement("button", {
197
+ type: "button",
198
+ className: "msa-quiet",
199
+ onClick: () => setAsking(false)
200
+ }, WORDS.account.cancel), createElement("button", {
201
+ type: "button",
202
+ className: "msa-danger",
203
+ disabled: props.busy,
204
+ onClick: () => {
205
+ setAsking(false);
206
+ props.onConfirm();
207
+ }
208
+ }, props.confirm));
209
+ }
210
+ /** Where a screen sends the browser once someone is signed in. */
211
+ const go = (to) => {
212
+ globalThis.location.href = to;
213
+ };
214
+ /** Sign-in: a password, a code or a link by mail, a passkey, Google or GitHub, as the app's settings turn them on. */
215
+ function SignIn(props) {
216
+ const { client, settings } = useAuth();
217
+ const [mode, setMode] = useState("start");
218
+ const [email, setEmail] = useState(""), [password, setPassword] = useState(""), [code, setCode] = useState(""), [captcha, setCaptcha] = useState("");
219
+ const call = useCall();
220
+ const done = () => go(props.redirectTo ?? "/");
221
+ if (!settings) return null;
222
+ const methods = settings.methods, app = settings.branding.name;
223
+ const withCaptcha = captcha ? { captcha } : {};
224
+ if (mode === "two-factor" || mode === "mail-code" || mode === "backup") return createElement(Card, {
225
+ title: WORDS.twoFactor.title,
226
+ lead: mode === "mail-code" ? WORDS.twoFactor.mailed : WORDS.twoFactor.lead
227
+ }, createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
228
+ await (mode === "backup" ? client.twoFactor.verifyBackupCode(code) : mode === "mail-code" ? client.twoFactor.verifyCode(code) : client.twoFactor.verifyTotp(code));
229
+ done();
230
+ })) }, createElement(Field, {
231
+ label: mode === "backup" ? WORDS.twoFactor.backupField : WORDS.fields.code,
232
+ value: code,
233
+ onChange: setCode,
234
+ autoComplete: "one-time-code",
235
+ inputMode: mode === "backup" ? void 0 : "numeric"
236
+ }), createElement(Problem, { message: call.error }), createElement(Submit, {
237
+ busy: call.busy,
238
+ label: WORDS.twoFactor.submit
239
+ })), createElement("div", {
240
+ className: "msa-stack",
241
+ style: { marginTop: 12 }
242
+ }, createElement("button", {
243
+ type: "button",
244
+ className: "msa-quiet",
245
+ onClick: () => void call.run(async () => {
246
+ await client.twoFactor.sendCode();
247
+ setCode("");
248
+ setMode("mail-code");
249
+ })
250
+ }, WORDS.twoFactor.byMail), createElement("button", {
251
+ type: "button",
252
+ className: "msa-quiet",
253
+ onClick: () => {
254
+ setCode("");
255
+ setMode("backup");
256
+ }
257
+ }, WORDS.twoFactor.backup)));
258
+ if (mode === "code") return createElement(Card, {
259
+ title: WORDS.signIn.title(app),
260
+ lead: WORDS.code.sent(email)
261
+ }, createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
262
+ await client.signIn.code.verify(email, code.trim());
263
+ done();
264
+ })) }, createElement(Field, {
265
+ label: WORDS.fields.code,
266
+ value: code,
267
+ onChange: setCode,
268
+ autoComplete: "one-time-code",
269
+ inputMode: "numeric"
270
+ }), createElement(Problem, { message: call.error }), createElement(Submit, {
271
+ busy: call.busy,
272
+ label: WORDS.code.submit
273
+ })), createElement("p", { className: "msa-foot" }, createElement("button", {
274
+ type: "button",
275
+ className: "msa-quiet",
276
+ onClick: () => void call.run(() => client.signIn.code.send(email, withCaptcha))
277
+ }, WORDS.code.again)));
278
+ if (mode === "link") return createElement(Card, { title: WORDS.signIn.title(app) }, createElement(Note, null, WORDS.link.sent(email)));
279
+ const social = ["google", "github"].filter((one) => methods[one]);
280
+ const byMail = methods.code ? "code" : methods.link ? "link" : null;
281
+ return createElement(Card, { title: WORDS.signIn.title(app) }, social.length || methods.passkey ? createElement("div", { className: "msa-stack" }, ...social.map((provider) => createElement("button", {
282
+ key: provider,
283
+ type: "button",
284
+ onClick: () => void call.run(() => client.signIn.social(provider, { callbackURL: props.redirectTo ?? "/" }))
285
+ }, WORDS.ways[provider])), methods.passkey ? createElement("button", {
286
+ type: "button",
287
+ onClick: () => void call.run(async () => {
288
+ await client.signIn.passkey();
289
+ done();
290
+ })
291
+ }, WORDS.ways.passkey) : null) : null, social.length || methods.passkey ? createElement("div", { className: "msa-or" }, WORDS.ways.or) : null, createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
292
+ if (!methods.password) {
293
+ if (byMail === "link") {
294
+ await client.signIn.link(email, {
295
+ callbackURL: props.redirectTo ?? "/",
296
+ ...withCaptcha
297
+ });
298
+ setMode("link");
299
+ return;
300
+ }
301
+ await client.signIn.code.send(email, withCaptcha);
302
+ setMode("code");
303
+ return;
304
+ }
305
+ if ("twoFactor" in await client.signIn.password({
306
+ email,
307
+ password,
308
+ ...withCaptcha
309
+ })) {
310
+ setMode("two-factor");
311
+ return;
312
+ }
313
+ done();
314
+ })) }, createElement(Field, {
315
+ label: WORDS.fields.email,
316
+ type: "email",
317
+ value: email,
318
+ onChange: setEmail,
319
+ autoComplete: "email"
320
+ }), methods.password ? createElement(Field, {
321
+ label: WORDS.fields.password,
322
+ type: "password",
323
+ value: password,
324
+ onChange: setPassword,
325
+ autoComplete: "current-password"
326
+ }) : null, createElement(Captcha, { onToken: setCaptcha }), createElement(Problem, { message: call.error }), createElement(Submit, {
327
+ busy: call.busy,
328
+ label: methods.password ? WORDS.signIn.submit : byMail === "link" ? WORDS.ways.link : WORDS.ways.code
329
+ })), methods.password && (methods.code || methods.link) ? createElement("div", {
330
+ className: "msa-stack",
331
+ style: { marginTop: 12 }
332
+ }, methods.code ? createElement("button", {
333
+ type: "button",
334
+ className: "msa-quiet",
335
+ onClick: () => void call.run(async () => {
336
+ await client.signIn.code.send(email, withCaptcha);
337
+ setMode("code");
338
+ })
339
+ }, WORDS.ways.code) : null, methods.link ? createElement("button", {
340
+ type: "button",
341
+ className: "msa-quiet",
342
+ onClick: () => void call.run(async () => {
343
+ await client.signIn.link(email, {
344
+ callbackURL: props.redirectTo ?? "/",
345
+ ...withCaptcha
346
+ });
347
+ setMode("link");
348
+ })
349
+ }, WORDS.ways.link) : null) : null, createElement("p", { className: "msa-foot" }, methods.password ? createElement(Fragment, null, createElement("a", { href: props.resetUrl ?? "/api/auth/ui/reset-password" }, WORDS.signIn.forgot), " · ") : null, settings.signUp.policy === "invite" ? null : createElement(Fragment, null, `${WORDS.signIn.noAccount} `, createElement("a", { href: props.signUpUrl ?? "/api/auth/ui/sign-up" }, WORDS.signIn.signUp))));
350
+ }
351
+ /** Sign-up with a name, an email and a password; under a waitlist, joining it. */
352
+ function SignUp(props) {
353
+ const { client, settings } = useAuth();
354
+ const [name, setName] = useState(""), [email, setEmail] = useState(""), [password, setPassword] = useState(""), [captcha, setCaptcha] = useState("");
355
+ const [waiting, setWaiting] = useState(null);
356
+ const call = useCall();
357
+ if (!settings) return null;
358
+ const policy = settings.signUp.policy;
359
+ if (waiting) return createElement(Card, { title: WORDS.signUp.title(settings.branding.name) }, createElement(Note, null, waiting));
360
+ return createElement(Card, {
361
+ title: WORDS.signUp.title(settings.branding.name),
362
+ ...policy === "invite" ? { lead: WORDS.signUp.invite } : {}
363
+ }, createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
364
+ try {
365
+ await client.signUp({
366
+ name,
367
+ email,
368
+ password,
369
+ ...captcha ? { captcha } : {}
370
+ });
371
+ go(props.redirectTo ?? "/");
372
+ } catch (error) {
373
+ if (error instanceof AuthClientError && error.code === "SIGN_UP_WAITLIST") {
374
+ setWaiting(error.message);
375
+ return;
376
+ }
377
+ throw error;
378
+ }
379
+ })) }, createElement(Field, {
380
+ label: WORDS.fields.name,
381
+ value: name,
382
+ onChange: setName,
383
+ autoComplete: "name"
384
+ }), createElement(Field, {
385
+ label: WORDS.fields.email,
386
+ type: "email",
387
+ value: email,
388
+ onChange: setEmail,
389
+ autoComplete: "email"
390
+ }), createElement(Field, {
391
+ label: WORDS.fields.password,
392
+ type: "password",
393
+ value: password,
394
+ onChange: setPassword,
395
+ autoComplete: "new-password"
396
+ }), createElement(Captcha, { onToken: setCaptcha }), createElement(Problem, { message: call.error }), createElement(Submit, {
397
+ busy: call.busy,
398
+ label: policy === "waitlist" ? WORDS.signUp.waitlist : WORDS.signUp.submit
399
+ })), createElement("p", { className: "msa-foot" }, `${WORDS.signUp.haveAccount} `, createElement("a", { href: props.signInUrl ?? "/api/auth/ui/sign-in" }, WORDS.signUp.signIn)));
400
+ }
401
+ /** The signed-in person's picture or initial, opening a menu: their account, and signing out. */
402
+ function UserButton(props) {
403
+ const { client, signedIn } = useAuth();
404
+ const [open, setOpen] = useState(false);
405
+ const menu = useRef(null);
406
+ const id = useId();
407
+ useEffect(() => {
408
+ if (!open) return;
409
+ menu.current?.querySelector("[role=menuitem]")?.focus();
410
+ const away = (event) => {
411
+ if (!menu.current?.parentElement?.contains(event.target)) setOpen(false);
412
+ };
413
+ document.addEventListener("mousedown", away);
414
+ return () => document.removeEventListener("mousedown", away);
415
+ }, [open]);
416
+ if (!signedIn) return null;
417
+ const { user } = signedIn;
418
+ const keys = (event) => {
419
+ const items = [...menu.current?.querySelectorAll("[role=menuitem]") ?? []];
420
+ const at = items.indexOf(document.activeElement);
421
+ if (event.key === "Escape") {
422
+ setOpen(false);
423
+ (menu.current?.parentElement?.querySelector("button"))?.focus();
424
+ }
425
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
426
+ event.preventDefault();
427
+ items[(at + (event.key === "ArrowDown" ? 1 : items.length - 1)) % items.length]?.focus();
428
+ }
429
+ };
430
+ const left = (event) => {
431
+ if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);
432
+ };
433
+ return createElement("div", {
434
+ className: "msa msa-menu",
435
+ onKeyDown: keys,
436
+ onBlur: left
437
+ }, createElement("button", {
438
+ type: "button",
439
+ className: "msa-avatar",
440
+ "aria-label": WORDS.user.menu,
441
+ "aria-haspopup": "menu",
442
+ "aria-expanded": open,
443
+ "aria-controls": id,
444
+ onClick: () => setOpen(!open),
445
+ onKeyDown: (event) => {
446
+ if (event.key === "ArrowDown" && !open) {
447
+ event.preventDefault();
448
+ setOpen(true);
449
+ }
450
+ }
451
+ }, user.image ? createElement("img", {
452
+ src: user.image,
453
+ alt: ""
454
+ }) : (user.name || user.email).slice(0, 1).toUpperCase()), open ? createElement("div", {
455
+ id,
456
+ role: "menu",
457
+ ref: menu,
458
+ "aria-label": WORDS.user.menu
459
+ }, createElement("div", { style: { padding: "8px 10px" } }, createElement("strong", null, user.name || user.email), user.name ? createElement("span", { style: {
460
+ display: "block",
461
+ fontSize: 13
462
+ } }, user.email) : null), createElement("a", {
463
+ role: "menuitem",
464
+ href: props.accountUrl ?? "/api/auth/ui/account",
465
+ style: { textDecoration: "none" }
466
+ }, WORDS.user.manage), createElement("button", {
467
+ type: "button",
468
+ role: "menuitem",
469
+ onClick: async () => {
470
+ await client.signOut();
471
+ go(props.afterSignOut ?? "/");
472
+ }
473
+ }, WORDS.user.signOut)) : null);
474
+ }
475
+ /** The signed-in person's account: profile, password, two-step sign-in, passkeys, sessions, keys and apps. */
476
+ function UserProfile() {
477
+ const { client, signedIn, settings, refresh } = useAuth();
478
+ const [sessions, setSessions] = useState([]);
479
+ const [passkeys, setPasskeys] = useState([]);
480
+ const [keys, setKeys] = useState([]);
481
+ const [grants, setGrants] = useState([]);
482
+ const [name, setName] = useState(""), [current, setCurrent] = useState(""), [next, setNext] = useState(""), [twoFactorPassword, setTwoFactorPassword] = useState(""), [totpCode, setTotpCode] = useState("");
483
+ const [keyName, setKeyName] = useState(""), [keyScopes, setKeyScopes] = useState([]);
484
+ const [made, setMade] = useState(null), [setup, setSetup] = useState(null), [notice, setNotice] = useState(null);
485
+ const call = useCall();
486
+ const [at, setAt] = useState("");
487
+ /** Runs one action of `section`, clearing what the last one said. */
488
+ const run = (section, work) => {
489
+ setNotice(null);
490
+ setAt(section);
491
+ return call.run(work);
492
+ };
493
+ const problemIn = (section) => at === section ? createElement(Problem, { message: call.error }) : null;
494
+ const load = useCallback(async () => {
495
+ const scoped = Object.keys(settings?.scopes ?? {}).length > 0;
496
+ const [s, p, k, g] = await Promise.all([
497
+ client.sessions.list(),
498
+ settings?.methods.passkey ? client.passkeys.list() : [],
499
+ scoped ? client.keys.list() : [],
500
+ client.grants.list()
501
+ ]);
502
+ setSessions(s);
503
+ setPasskeys(p);
504
+ setKeys(k);
505
+ setGrants(g);
506
+ }, [client, settings]);
507
+ useEffect(() => {
508
+ if (signedIn) {
509
+ setName(signedIn.user.name);
510
+ load().catch(() => {});
511
+ }
512
+ }, [signedIn, load]);
513
+ if (!signedIn || !settings) return null;
514
+ const { user, session } = signedIn;
515
+ const scopes = Object.entries(settings.scopes);
516
+ return createElement(Card, {
517
+ title: WORDS.account.title,
518
+ lead: user.email,
519
+ wide: true
520
+ }, notice ? createElement(Note, null, notice) : null, createElement("section", { "aria-labelledby": "msa-profile" }, createElement("h2", { id: "msa-profile" }, WORDS.account.profile), problemIn("profile"), createElement("form", { onSubmit: onSubmit(() => void run("profile", async () => {
521
+ await client.profile.update({ name });
522
+ await refresh();
523
+ setNotice(WORDS.account.saved);
524
+ })) }, createElement(Field, {
525
+ label: WORDS.fields.name,
526
+ value: name,
527
+ onChange: setName,
528
+ autoComplete: "name"
529
+ }), createElement("div", null, createElement("button", {
530
+ type: "submit",
531
+ disabled: call.busy
532
+ }, WORDS.account.save)))), createElement("section", { "aria-labelledby": "msa-security" }, createElement("h2", { id: "msa-security" }, WORDS.account.security), problemIn("security"), settings.methods.password ? createElement("form", { onSubmit: onSubmit(() => void run("security", async () => {
533
+ await client.password.change({
534
+ current,
535
+ next,
536
+ signOutOthers: true
537
+ });
538
+ setCurrent("");
539
+ setNext("");
540
+ setNotice(WORDS.account.passwordChanged);
541
+ })) }, createElement(Field, {
542
+ label: WORDS.fields.currentPassword,
543
+ type: "password",
544
+ value: current,
545
+ onChange: setCurrent,
546
+ autoComplete: "current-password"
547
+ }), createElement(Field, {
548
+ label: WORDS.fields.newPassword,
549
+ type: "password",
550
+ value: next,
551
+ onChange: setNext,
552
+ autoComplete: "new-password"
553
+ }), createElement("div", null, createElement("button", {
554
+ type: "submit",
555
+ disabled: call.busy
556
+ }, WORDS.account.changePassword))) : null, createElement("div", {
557
+ className: "msa-row",
558
+ style: { marginTop: 12 }
559
+ }, createElement("div", null, createElement("strong", null, user.twoFactorEnabled ? WORDS.account.twoFactorOn : WORDS.account.twoFactorOff)), createElement("form", {
560
+ style: {
561
+ display: "flex",
562
+ gap: 8,
563
+ alignItems: "end"
564
+ },
565
+ onSubmit: onSubmit(() => void run("security", async () => {
566
+ if (user.twoFactorEnabled) {
567
+ await client.twoFactor.disable(twoFactorPassword);
568
+ await refresh();
569
+ } else setSetup(await client.twoFactor.enable(twoFactorPassword));
570
+ setTwoFactorPassword("");
571
+ }))
572
+ }, createElement(Field, {
573
+ label: WORDS.account.yourPassword,
574
+ type: "password",
575
+ value: twoFactorPassword,
576
+ onChange: setTwoFactorPassword,
577
+ autoComplete: "current-password"
578
+ }), createElement("button", {
579
+ type: "submit",
580
+ disabled: call.busy
581
+ }, user.twoFactorEnabled ? WORDS.account.turnOff : WORDS.account.turnOn))), setup ? createElement("div", { className: "msa-stack" }, createElement("p", { className: "msa-note" }, WORDS.account.twoFactorSetup), createElement(QrCode, { value: setup.totpURI }), createElement(Secret, {
582
+ label: WORDS.account.setupKey,
583
+ value: setupKeyOf(setup.totpURI)
584
+ }), createElement("a", { href: setup.totpURI }, WORDS.account.openInApp), createElement("p", { className: "msa-note" }, WORDS.account.backupCodes), createElement("ul", { className: "msa-codes" }, ...setup.backupCodes.map((one) => createElement("li", { key: one }, createElement("code", null, one)))), createElement(CopyButton, {
585
+ label: WORDS.account.copyCodes,
586
+ value: setup.backupCodes.join("\n")
587
+ }), createElement("form", { onSubmit: onSubmit(() => void run("security", async () => {
588
+ await client.twoFactor.verifyTotp(totpCode);
589
+ setSetup(null);
590
+ setTotpCode("");
591
+ await refresh();
592
+ })) }, createElement(Field, {
593
+ label: WORDS.fields.code,
594
+ value: totpCode,
595
+ onChange: setTotpCode,
596
+ autoComplete: "one-time-code",
597
+ inputMode: "numeric"
598
+ }), createElement("div", null, createElement("button", {
599
+ type: "submit",
600
+ disabled: call.busy
601
+ }, WORDS.twoFactor.submit)))) : null), settings.methods.passkey ? createElement("section", { "aria-labelledby": "msa-passkeys" }, createElement("h2", { id: "msa-passkeys" }, WORDS.account.passkeys), problemIn("passkeys"), passkeys.length ? passkeys.map((one) => createElement("div", {
602
+ key: one.id,
603
+ className: "msa-row"
604
+ }, createElement("div", null, createElement("strong", null, one.name || WORDS.account.passkey), createElement("span", null, ago(one.createdAt))), createElement(Confirm, {
605
+ label: WORDS.account.remove,
606
+ confirm: WORDS.account.removeForGood,
607
+ busy: call.busy,
608
+ onConfirm: () => void run("passkeys", async () => {
609
+ await client.passkeys.remove(one.id);
610
+ await load();
611
+ })
612
+ }))) : createElement("p", { className: "msa-note" }, WORDS.account.noPasskeys), createElement("div", { style: { marginTop: 12 } }, createElement("button", {
613
+ type: "button",
614
+ onClick: () => void run("passkeys", async () => {
615
+ await client.passkeys.add();
616
+ await load();
617
+ })
618
+ }, WORDS.account.addPasskey))) : null, createElement("section", { "aria-labelledby": "msa-sessions" }, createElement("h2", { id: "msa-sessions" }, WORDS.account.sessions), problemIn("sessions"), sessions.map((one) => createElement("div", {
619
+ key: one.id,
620
+ className: "msa-row"
621
+ }, createElement("div", null, createElement("strong", null, one.id === session.id ? WORDS.account.thisDevice : deviceOf(one.userAgent) ?? WORDS.account.unknownDevice), createElement("span", null, [
622
+ one.impersonatedBy ? WORDS.account.signedInBy(one.impersonatedBy) : null,
623
+ ago(one.createdAt),
624
+ one.ipAddress
625
+ ].filter(Boolean).join(" · "))), one.id === session.id ? null : createElement("button", {
626
+ type: "button",
627
+ className: "msa-quiet",
628
+ onClick: () => void run("sessions", async () => {
629
+ await client.sessions.revoke(one.token);
630
+ await load();
631
+ })
632
+ }, WORDS.account.signOut)))), scopes.length || grants.length ? createElement("section", { "aria-labelledby": "msa-agents" }, createElement("h2", { id: "msa-agents" }, WORDS.account.agents), problemIn("agents"), scopes.length ? createElement(Fragment, null, keys.length ? keys.map((one) => createElement("div", {
633
+ key: one.id,
634
+ className: "msa-row"
635
+ }, createElement("div", null, createElement("strong", null, one.name ?? one.start ?? one.id), createElement("span", null, [one.scopes.map((scope) => settings.scopes[scope] ?? scope).join(", "), one.lastUsedAt ? WORDS.account.lastUsed(ago(one.lastUsedAt)) : WORDS.account.neverUsed].join(" · "))), createElement(Confirm, {
636
+ label: WORDS.account.revoke,
637
+ confirm: WORDS.account.revokeForGood,
638
+ busy: call.busy,
639
+ onConfirm: () => void run("agents", async () => {
640
+ await client.keys.revoke(one.id);
641
+ await load();
642
+ })
643
+ }))) : createElement("p", { className: "msa-note" }, WORDS.account.noKeys), made ? createElement("div", { className: "msa-stack" }, createElement("p", {
644
+ className: "msa-note",
645
+ role: "status"
646
+ }, WORDS.account.keyShown), createElement(Secret, {
647
+ label: WORDS.account.keys,
648
+ value: made
649
+ })) : null, createElement("form", {
650
+ style: { marginTop: 12 },
651
+ onSubmit: onSubmit(() => void run("agents", async () => {
652
+ setMade(null);
653
+ const key = await client.keys.create({
654
+ name: keyName,
655
+ scopes: keyScopes
656
+ });
657
+ setMade(key.key);
658
+ setKeyName("");
659
+ setKeyScopes([]);
660
+ await load();
661
+ }))
662
+ }, createElement(Field, {
663
+ label: WORDS.fields.keyName,
664
+ value: keyName,
665
+ onChange: setKeyName
666
+ }), createElement("fieldset", { style: {
667
+ border: 0,
668
+ padding: 0,
669
+ margin: 0,
670
+ display: "grid",
671
+ gap: 6
672
+ } }, createElement("legend", { style: {
673
+ fontWeight: 500,
674
+ fontSize: 14,
675
+ marginBottom: 6
676
+ } }, WORDS.account.scopes), ...scopes.map(([scope, what]) => createElement("label", {
677
+ key: scope,
678
+ style: {
679
+ display: "flex",
680
+ gap: 8,
681
+ alignItems: "center",
682
+ fontWeight: 400
683
+ }
684
+ }, createElement("input", {
685
+ type: "checkbox",
686
+ style: {
687
+ width: "auto",
688
+ minHeight: 0
689
+ },
690
+ checked: keyScopes.includes(scope),
691
+ onChange: () => setKeyScopes(keyScopes.includes(scope) ? keyScopes.filter((one) => one !== scope) : [...keyScopes, scope])
692
+ }), what))), createElement("div", null, createElement("button", {
693
+ type: "submit",
694
+ disabled: call.busy || !keyScopes.length
695
+ }, WORDS.account.createKey)))) : null, createElement("h2", { style: { marginTop: 20 } }, WORDS.account.apps), grants.length ? grants.map((one) => createElement("div", {
696
+ key: one.id,
697
+ className: "msa-row"
698
+ }, createElement("div", null, createElement("strong", null, one.client ?? one.clientId), createElement("span", null, one.scopes.map((scope) => settings.scopes[scope] ?? scope).join(", "))), createElement(Confirm, {
699
+ label: WORDS.account.removeAccess,
700
+ confirm: WORDS.account.removeAccessForGood,
701
+ busy: call.busy,
702
+ onConfirm: () => void run("agents", async () => {
703
+ await client.grants.revoke(one.id);
704
+ await load();
705
+ })
706
+ }))) : createElement("p", { className: "msa-note" }, WORDS.account.noApps)) : null);
707
+ }
708
+ /** Which organization the person works in, or their personal account; and making a new one. */
709
+ function OrganizationSwitcher() {
710
+ const { client, signedIn, refresh } = useAuth();
711
+ const [organizations, setOrganizations] = useState([]);
712
+ const [creating, setCreating] = useState(false), [name, setName] = useState("");
713
+ const call = useCall();
714
+ useEffect(() => {
715
+ if (signedIn) client.organizations.list().then(setOrganizations, () => {});
716
+ }, [client, signedIn]);
717
+ if (!signedIn) return null;
718
+ const active = signedIn.session.activeOrganizationId ?? "";
719
+ const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
720
+ return createElement("div", {
721
+ className: "msa",
722
+ style: {
723
+ display: "grid",
724
+ gap: 8
725
+ }
726
+ }, createElement("label", null, WORDS.organizations.switch, createElement("select", {
727
+ value: active,
728
+ onChange: (event) => void call.run(async () => {
729
+ await client.organizations.setActive(event.target.value || null);
730
+ await refresh();
731
+ })
732
+ }, createElement("option", { value: "" }, WORDS.organizations.personal), ...organizations.map((one) => createElement("option", {
733
+ key: one.id,
734
+ value: one.id
735
+ }, one.name)))), creating ? createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
736
+ const made = await client.organizations.create({
737
+ name: name.trim(),
738
+ slug
739
+ });
740
+ await client.organizations.setActive(made.id);
741
+ setOrganizations([...organizations, made]);
742
+ setCreating(false);
743
+ setName("");
744
+ await refresh();
745
+ })) }, createElement(Field, {
746
+ label: WORDS.fields.organization,
747
+ value: name,
748
+ onChange: setName
749
+ }), createElement("div", null, createElement("button", {
750
+ type: "submit",
751
+ disabled: call.busy || !slug
752
+ }, WORDS.organizations.create))) : createElement("div", null, createElement("button", {
753
+ type: "button",
754
+ className: "msa-quiet",
755
+ onClick: () => setCreating(true)
756
+ }, WORDS.organizations.create)), createElement(Problem, { message: call.error }));
757
+ }
758
+ /** One organization: its name, its members and their roles, and its invitations. The active one unless `organizationId` names another. */
759
+ function OrganizationProfile(props) {
760
+ const { client, signedIn, refresh } = useAuth();
761
+ const [organization, setOrganization] = useState(null);
762
+ const [email, setEmail] = useState(""), [role, setRole] = useState("member"), [name, setName] = useState("");
763
+ const call = useCall();
764
+ const id = props.organizationId ?? signedIn?.session.activeOrganizationId ?? void 0;
765
+ const load = useCallback(async () => {
766
+ const found = await client.organizations.get(id);
767
+ setOrganization(found);
768
+ setName(found?.name ?? "");
769
+ }, [client, id]);
770
+ useEffect(() => {
771
+ if (signedIn && id) load().catch(() => {});
772
+ }, [
773
+ signedIn,
774
+ id,
775
+ load
776
+ ]);
777
+ if (!signedIn || !organization) return null;
778
+ const me = organization.members.find((member) => member.userId === signedIn.user.id);
779
+ const manages = me?.role === "owner" || me?.role === "admin";
780
+ const roles = WORDS.organizations.roles;
781
+ return createElement(Card, {
782
+ title: organization.name,
783
+ wide: true
784
+ }, createElement(Problem, { message: call.error }), manages ? createElement("section", { "aria-labelledby": "msa-org" }, createElement("h2", { id: "msa-org" }, WORDS.organizations.settings), createElement("form", { onSubmit: onSubmit(() => void call.run(async () => {
785
+ await client.organizations.update(organization.id, { name: name.trim() });
786
+ await load();
787
+ })) }, createElement(Field, {
788
+ label: WORDS.fields.organization,
789
+ value: name,
790
+ onChange: setName
791
+ }), createElement("div", null, createElement("button", {
792
+ type: "submit",
793
+ disabled: call.busy
794
+ }, WORDS.organizations.save)))) : null, createElement("section", { "aria-labelledby": "msa-members" }, createElement("h2", { id: "msa-members" }, WORDS.organizations.members), organization.members.map((member) => createElement("div", {
795
+ key: member.id,
796
+ className: "msa-row"
797
+ }, createElement("div", null, createElement("strong", null, member.user.name || member.user.email), createElement("span", null, member.user.email)), manages && member.userId !== signedIn.user.id ? createElement("div", { style: {
798
+ display: "flex",
799
+ gap: 8
800
+ } }, createElement("select", {
801
+ "aria-label": `${WORDS.fields.role}, ${member.user.email}`,
802
+ value: member.role,
803
+ style: { width: "auto" },
804
+ onChange: (event) => void call.run(async () => {
805
+ await client.organizations.setRole(organization.id, member.id, event.target.value);
806
+ await load();
807
+ })
808
+ }, ...Object.keys(roles).map((one) => createElement("option", {
809
+ key: one,
810
+ value: one
811
+ }, roles[one]))), createElement(Confirm, {
812
+ label: WORDS.organizations.remove,
813
+ confirm: WORDS.organizations.removeForGood,
814
+ busy: call.busy,
815
+ onConfirm: () => void call.run(async () => {
816
+ await client.organizations.removeMember(organization.id, member.id);
817
+ await load();
818
+ })
819
+ })) : createElement("span", null, roles[member.role] ?? member.role)))), manages ? createElement("section", { "aria-labelledby": "msa-invitations" }, createElement("h2", { id: "msa-invitations" }, WORDS.organizations.invitations), organization.invitations.filter((one) => one.status === "pending").map((one) => createElement("div", {
820
+ key: one.id,
821
+ className: "msa-row"
822
+ }, createElement("div", null, createElement("strong", null, one.email), createElement("span", null, roles[one.role ?? "member"])), createElement("button", {
823
+ type: "button",
824
+ className: "msa-quiet msa-danger",
825
+ onClick: () => void call.run(async () => {
826
+ await client.organizations.cancelInvitation(one.id);
827
+ await load();
828
+ })
829
+ }, WORDS.organizations.cancel))), createElement("form", {
830
+ style: { marginTop: 12 },
831
+ onSubmit: onSubmit(() => void call.run(async () => {
832
+ await client.organizations.invite(organization.id, {
833
+ email,
834
+ role
835
+ });
836
+ setEmail("");
837
+ await load();
838
+ }))
839
+ }, createElement(Field, {
840
+ label: WORDS.fields.inviteEmail,
841
+ type: "email",
842
+ value: email,
843
+ onChange: setEmail,
844
+ autoComplete: "off"
845
+ }), createElement("label", null, WORDS.fields.role, createElement("select", {
846
+ value: role,
847
+ onChange: (event) => setRole(event.target.value)
848
+ }, ...Object.keys(roles).map((one) => createElement("option", {
849
+ key: one,
850
+ value: one
851
+ }, roles[one])))), createElement("div", null, createElement("button", {
852
+ type: "submit",
853
+ disabled: call.busy
854
+ }, WORDS.organizations.invite)))) : null, me && me.role !== "owner" ? createElement("section", null, createElement(Confirm, {
855
+ label: WORDS.organizations.leave,
856
+ confirm: WORDS.organizations.leaveForGood,
857
+ busy: call.busy,
858
+ onConfirm: () => void call.run(async () => {
859
+ await client.organizations.leave(organization.id);
860
+ await refresh();
861
+ })
862
+ })) : null);
863
+ }
864
+ //#endregion
865
+ export { AuthProvider, OrganizationProfile, OrganizationSwitcher, SignIn, SignUp, UserButton, UserProfile, useAuth };