@krak-stack/auth 0.1.70 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +4 -3
  2. package/dist/access.d.ts +4 -4
  3. package/dist/access.js +10 -4
  4. package/dist/admin/api.group.d.ts +17 -17
  5. package/dist/admin/api.group.js +2 -2
  6. package/dist/admin/schema.d.ts +18 -18
  7. package/dist/admin/schema.js +3 -3
  8. package/dist/api.d.ts +2093 -631
  9. package/dist/api.js +7 -7
  10. package/dist/auth/api.group.d.ts +793 -0
  11. package/dist/auth/api.group.js +241 -0
  12. package/dist/auth/schema.d.ts +800 -0
  13. package/dist/auth/schema.js +625 -0
  14. package/dist/components/admin-organization-form.d.ts +1 -1
  15. package/dist/components/admin-organization-form.js +16 -18
  16. package/dist/components/admin-organizations.js +52 -46
  17. package/dist/components/admin-users.js +115 -138
  18. package/dist/components/api-key-edit-form.d.ts +4 -3
  19. package/dist/components/api-key-edit-form.js +32 -27
  20. package/dist/components/api-key-permissions.d.ts +1 -1
  21. package/dist/components/api-key-rate-limit.d.ts +1 -1
  22. package/dist/components/api-key-referrers.d.ts +3 -2
  23. package/dist/components/api-key-referrers.js +2 -3
  24. package/dist/components/api-key.d.ts +0 -9
  25. package/dist/components/api-key.js +0 -39
  26. package/dist/components/auth-atoms.d.ts +178 -0
  27. package/dist/components/auth-atoms.js +46 -0
  28. package/dist/components/auth-client-api.d.ts +2474 -142
  29. package/dist/components/auth-client-api.js +14 -10
  30. package/dist/components/auth-forms.d.ts +1 -3
  31. package/dist/components/auth-forms.js +168 -195
  32. package/dist/components/auth-provider.d.ts +3 -7
  33. package/dist/components/auth-provider.js +56 -30
  34. package/dist/components/has-permission.js +1 -1
  35. package/dist/components/index.d.ts +19 -20
  36. package/dist/components/index.js +13 -13
  37. package/dist/components/member-required.d.ts +1 -3
  38. package/dist/components/member-required.js +102 -78
  39. package/dist/components/organization-switcher.d.ts +4 -6
  40. package/dist/components/organization-switcher.js +469 -324
  41. package/dist/components/project-access-matrix.d.ts +1 -1
  42. package/dist/components/project-access-matrix.js +9 -13
  43. package/dist/components/user-button.d.ts +5 -3
  44. package/dist/components/user-button.js +265 -316
  45. package/dist/components/utils.d.ts +3 -1
  46. package/dist/components/utils.js +4 -11
  47. package/dist/extra/api.group.d.ts +3 -3
  48. package/dist/extra/api.group.js +6 -6
  49. package/dist/extra/schema.js +1 -1
  50. package/dist/index.d.ts +11 -12
  51. package/dist/index.js +11 -12
  52. package/dist/query.d.ts +2 -2
  53. package/dist/roles.d.ts +5 -4
  54. package/dist/roles.js +11 -7
  55. package/dist/schema.d.ts +1 -1
  56. package/dist/schema.js +26 -19
  57. package/dist/server/actor.d.ts +30 -32
  58. package/dist/server/actor.js +39 -22
  59. package/dist/server/api.group.js +2 -2
  60. package/dist/server/index.d.ts +14 -14
  61. package/dist/server/index.js +8 -8
  62. package/dist/server/middleware.d.ts +3 -3
  63. package/dist/server/middleware.js +10 -5
  64. package/dist/server/schema.js +1 -1
  65. package/dist/service.d.ts +2053 -201
  66. package/dist/service.js +32 -21
  67. package/package.json +10 -9
  68. package/dist/better-auth/api.group.d.ts +0 -62
  69. package/dist/better-auth/api.group.js +0 -39
  70. package/dist/better-auth/schema.d.ts +0 -72
  71. package/dist/better-auth/schema.js +0 -110
  72. package/dist/components/auth-client.d.ts +0 -50
  73. package/dist/components/auth-client.js +0 -46
@@ -1,14 +1,13 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
3
3
  import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
- import {} from "@tanstack/react-table";
5
4
  import { useNavigate, useRouterState, } from "@tanstack/react-router";
6
- import { Effect, Schema } from "effect";
5
+ import { Effect, Option, Predicate, Schema } from "effect";
7
6
  import { AsyncResult, Atom } from "effect/unstable/reactivity";
8
7
  import { ArrowLeft, Building2, KeyRound, Loader2, LogOutIcon, Pencil, Plus, ShieldCheck, StopCircle, Trash2, UserCircleIcon, Users, UserIcon, } from "lucide-react";
9
8
  import { QRCode } from "react-qr-code";
10
9
  import { createContext, useContext, useRef, useState, } from "react";
11
- import { DataTable } from "@krak-stack/registry/data-table";
10
+ import { DataTable, } from "@krak-stack/registry/data-table";
12
11
  import { AppBrand } from "@krak-stack/registry/app-brand";
13
12
  import { effectFormMessages, ImageField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@krak-stack/registry/effect-form";
14
13
  import { Badge } from "@/components/ui/badge";
@@ -17,18 +16,19 @@ import { CopyButton } from "@krak-stack/registry/copy-button";
17
16
  import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
18
17
  import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu";
19
18
  import { Separator } from "@/components/ui/separator";
20
- import { authClientApi } from "./auth-client-api";
21
- import { useKrakstackAuth } from "./auth-provider";
22
- import { createApiKey, parseApiKeyReferrers } from "./api-key";
23
- import { ApiKeyEditForm } from "./api-key-edit-form";
24
- import { ApiKeyPermissions } from "./api-key-permissions";
25
- import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit";
26
- import { ApiKeyReferrers } from "./api-key-referrers";
27
- import { useOpenedOnce } from "./hooks";
28
- import { ExtraUploadedAsset } from "../extra/schema";
29
- import { assetPath, assetUrl } from "./utils";
30
- import { AdminOrganizationsTable } from "./admin-organizations";
31
- import { AdminUsersTable } from "./admin-users";
19
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
20
+ import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
21
+ import { useKrakstackAuth } from "./auth-provider.js";
22
+ import { parseApiKeyReferrers } from "./api-key.js";
23
+ import { ApiKeyEditForm } from "./api-key-edit-form.js";
24
+ import { ApiKeyPermissions } from "./api-key-permissions.js";
25
+ import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit.js";
26
+ import { ApiKeyReferrers } from "./api-key-referrers.js";
27
+ import { useOpenedOnce } from "./hooks.js";
28
+ import { ExtraUploadedAsset } from "../extra/schema.js";
29
+ import { assetPath, assetUrl } from "./utils.js";
30
+ import { AdminOrganizationsTable } from "./admin-organizations.js";
31
+ import { AdminUsersTable } from "./admin-users.js";
32
32
  const messages = {
33
33
  en: {
34
34
  table_empty: "No results.",
@@ -107,8 +107,10 @@ const messages = {
107
107
  user_button_aria_label: "Open user menu",
108
108
  user_button_impersonating: "Impersonating",
109
109
  user_button_logout: "Log out",
110
+ user_button_logout_error: "Could not log out. Try again.",
110
111
  user_button_security: "Security",
111
112
  user_button_stop_impersonating: "Stop impersonating",
113
+ user_button_stop_impersonating_error: "Could not stop impersonating. Try again.",
112
114
  user_delete: "Delete",
113
115
  user_field_password: "Password",
114
116
  user_form_description: "Update the profile details associated with your account.",
@@ -214,8 +216,10 @@ const messages = {
214
216
  user_button_aria_label: "Ouvrir le menu utilisateur",
215
217
  user_button_impersonating: "Imitation",
216
218
  user_button_logout: "Se déconnecter",
219
+ user_button_logout_error: "Impossible de se déconnecter. Réessayez.",
217
220
  user_button_security: "Sécurité",
218
221
  user_button_stop_impersonating: "Arrêter l'imitation",
222
+ user_button_stop_impersonating_error: "Impossible d'arrêter l'imitation. Réessayez.",
219
223
  user_delete: "Supprimer",
220
224
  user_field_password: "Mot de passe",
221
225
  user_form_description: "Mettez à jour les informations de profil associées à votre compte.",
@@ -259,17 +263,29 @@ const userButtonMessages = (overrides) => ({
259
263
  const interpolate = (value, params) => params
260
264
  ? value.replace(/\{([^}]+)\}/g, (_, key) => String(params[key] ?? `{${key}}`))
261
265
  : value;
262
- const userButtonMessageFns = (labels) => new Proxy({}, {
263
- get: (_target, key) => (params) => interpolate(labels[key], params),
264
- });
266
+ const interpolateMessage = (labels, key, params) => {
267
+ const entry = Object.entries(labels).find(([labelKey]) => labelKey === key);
268
+ return interpolate(entry?.[1] ?? key, params);
269
+ };
270
+ const userButtonMessageFns = (labels) => {
271
+ return new Proxy({}, {
272
+ get: (_target, key) => (params) => interpolateMessage(labels, key, params),
273
+ });
274
+ };
265
275
  const UserButtonMessagesContext = createContext(userButtonMessageFns(userButtonMessages()));
266
276
  const useUserButtonMessages = () => useContext(UserButtonMessagesContext);
267
- const hasRole = (role, roles) => typeof role === "string" &&
268
- role.split(",").some((item) => roles.includes(item.trim().toLowerCase()));
269
- const hasAdminRole = (user) => typeof user === "object" &&
270
- user !== null &&
271
- "role" in user &&
272
- hasRole(user.role, ["admin"]);
277
+ const UserRole = Schema.Struct({ role: Schema.String });
278
+ const hasRole = (role, roles) => {
279
+ const decoded = Schema.decodeUnknownOption(Schema.String)(role);
280
+ return (Option.isSome(decoded) &&
281
+ decoded.value
282
+ .split(",")
283
+ .some((item) => roles.includes(item.trim().toLowerCase())));
284
+ };
285
+ const hasAdminRole = (user) => {
286
+ const decoded = Schema.decodeUnknownOption(UserRole)(user);
287
+ return Option.isSome(decoded) && hasRole(decoded.value.role, ["admin"]);
288
+ };
273
289
  const changePasswordFormBuilder = FormBuilder.empty
274
290
  .addField("currentPassword", Schema.NonEmptyString)
275
291
  .addField("newPassword", Schema.NonEmptyString);
@@ -282,48 +298,24 @@ const apiKeyFormBuilder = FormBuilder.empty
282
298
  .addField("name", Schema.NonEmptyString)
283
299
  .addField("referrers", Schema.String);
284
300
  const isFile = (value) => value instanceof File;
285
- const decodeUploadedAsset = Schema.decodeUnknownPromise(ExtraUploadedAsset);
286
- const uploadUserImageAsset = async (file, m, uploadUserImage) => {
301
+ const uploadUserImageAsset = (file, m, baseUrl) => {
287
302
  const payload = new FormData();
288
303
  payload.append("file", file);
289
- try {
290
- return await decodeUploadedAsset(await uploadUserImage({ payload }));
291
- }
292
- catch {
293
- throw new Error(m.user_profile_image_upload_error());
294
- }
304
+ return authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.authExtra.uploadUserImage({ payload })), Effect.flatMap(Schema.decodeUnknownEffect(ExtraUploadedAsset)), Effect.mapError(() => new Error(m.user_profile_image_upload_error())));
295
305
  };
296
306
  const requiresPasswordForAccountRevoke = (accounts) => accounts.some((account) => account.providerId === "credential");
297
- const userAccountsAtom = Atom.family((authClient) => Atom.keepAlive(Atom.make(Effect.tryPromise({
298
- try: async () => {
299
- const result = await authClient.listAccounts();
300
- if (result.error) {
301
- throw new Error(result.error.message ?? "Could not load accounts.");
302
- }
303
- return result.data ?? [];
304
- },
305
- catch: (error) => error,
306
- }))));
307
- const emptyAccountsAtom = Atom.make(Effect.succeed([]));
308
- const userApiKeysAtom = Atom.family((authClient) => Atom.keepAlive(Atom.make(Effect.tryPromise({
309
- try: async () => {
310
- const result = await authClient.apiKey.list({
311
- query: { configId: "user" },
312
- });
313
- if (result.error) {
314
- throw new Error(result.error.message ?? "Could not load API keys.");
315
- }
316
- return result.data?.apiKeys ?? [];
317
- },
318
- catch: (error) => error,
319
- }))));
320
- const emptyApiKeysAtom = Atom.make(Effect.succeed([]));
321
- export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRedirect = "/", side = "bottom", defaultDialog = null, hideTrigger = false, renderUnauthenticated, menuActions, apiKeyPermissions, messages, dialog: controlledDialog, onDialogChange, }) => {
307
+ const userAccountsAtom = Atom.family((baseUrl) => Atom.keepAlive(Atom.map(authClientApi(baseUrl).query("auth", "listAccounts", {
308
+ reactivityKeys: ["user-accounts", baseUrl],
309
+ }), AsyncResult.map((accounts) => Array.from(accounts)))));
310
+ const emptyAccountsAtom = Atom.make(Effect.succeed(Array()));
311
+ const userApiKeysAtom = Atom.family((baseUrl) => Atom.keepAlive(Atom.map(authClientApi(baseUrl).query("auth", "apiKeyList", {
312
+ query: { configId: "user" },
313
+ reactivityKeys: ["user-api-keys", baseUrl],
314
+ }), AsyncResult.map(({ apiKeys }) => Array.from(apiKeys)))));
315
+ const emptyApiKeysAtom = Atom.make(Effect.succeed(Array()));
316
+ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", defaultDialog = null, hideTrigger = false, renderUnauthenticated, menuActions, apiKeyPermissions, messages, dialog: controlledDialog, onDialogChange, }) => {
322
317
  const auth = useKrakstackAuth();
323
- const authClient = providedAuthClient ?? auth?.authClient;
324
- if (!authClient) {
325
- throw new Error("KrakstackAuthProvider is required to use authClient.");
326
- }
318
+ const resolvedBaseUrl = baseUrl ?? auth?.baseUrl;
327
319
  const labels = userButtonMessages(messages);
328
320
  const m = userButtonMessageFns(labels);
329
321
  const projectConfig = auth?.projectConfig ?? null;
@@ -331,19 +323,45 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
331
323
  const currentSiteHref = useRouterState({
332
324
  select: (state) => `${import.meta.env.VITE_SITE_URL}${state.location.href}`,
333
325
  });
334
- const { data: session, isPending, refetch } = authClient.useSession();
326
+ const sessionAtom = authSessionAtom(resolvedBaseUrl);
327
+ const sessionResult = useAtomValue(sessionAtom);
328
+ const refreshSession = useAtomRefresh(sessionAtom);
329
+ const session = AsyncResult.match(sessionResult, {
330
+ onInitial: () => null,
331
+ onFailure: () => null,
332
+ onSuccess: ({ value }) => value,
333
+ });
334
+ const isPending = sessionResult.waiting;
335
335
  const [uncontrolledDialog, setUncontrolledDialog] = useState(defaultDialog);
336
336
  const [isStoppingImpersonation, setIsStoppingImpersonation] = useState(false);
337
337
  const settingsDialog = controlledDialog !== undefined ? controlledDialog : uncontrolledDialog;
338
338
  const [formError, setFormError] = useState(null);
339
339
  const shouldLoadAccounts = Boolean(session) &&
340
340
  (settingsDialog === "account" || settingsDialog === "security");
341
+ const loadedAccountsAtom = userAccountsAtom(resolvedBaseUrl);
341
342
  const accountsAtom = shouldLoadAccounts
342
- ? userAccountsAtom(authClient)
343
+ ? loadedAccountsAtom
343
344
  : emptyAccountsAtom;
344
345
  const accountsResult = useAtomValue(accountsAtom);
345
- const refreshAccounts = useAtomRefresh(accountsAtom);
346
- const uploadUserImage = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"), { mode: "promise" });
346
+ const refreshLoadedAccounts = useAtomRefresh(loadedAccountsAtom);
347
+ const refreshEmptyAccounts = useAtomRefresh(emptyAccountsAtom);
348
+ const refreshAccounts = shouldLoadAccounts
349
+ ? refreshLoadedAccounts
350
+ : refreshEmptyAccounts;
351
+ const [signOutAction] = useState(() => Atom.fn(({ baseUrl, redirectUrl, }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.signOut()), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => navigate({ href: redirectUrl }))))));
352
+ const signOut = useAtomSet(signOutAction);
353
+ const signOutResult = useAtomValue(signOutAction);
354
+ const [stopImpersonatingAction] = useState(() => Atom.fn((input) => Effect.gen(function* () {
355
+ setIsStoppingImpersonation(true);
356
+ yield* authHttpClient(input.baseUrl).pipe(Effect.flatMap((client) => client.auth.adminStopImpersonating()), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap(() => Effect.sync(input.refreshSession)), Effect.flatMap(() => Effect.tryPromise(() => navigate({ href: input.currentSiteHref }))), Effect.ensuring(Effect.sync(() => setIsStoppingImpersonation(false))));
357
+ })));
358
+ const stopImpersonating = useAtomSet(stopImpersonatingAction);
359
+ const stopImpersonatingResult = useAtomValue(stopImpersonatingAction);
360
+ const authActionError = AsyncResult.isFailure(signOutResult)
361
+ ? m.user_button_logout_error()
362
+ : AsyncResult.isFailure(stopImpersonatingResult)
363
+ ? m.user_button_stop_impersonating_error()
364
+ : null;
347
365
  const accountCache = {
348
366
  accounts: AsyncResult.match(accountsResult, {
349
367
  onInitial: () => null,
@@ -358,7 +376,7 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
358
376
  reload: async () => refreshAccounts(),
359
377
  };
360
378
  const setSettingsDialog = (next) => {
361
- const nextDialog = typeof next === "function" ? next(settingsDialog) : next;
379
+ const nextDialog = Predicate.isFunction(next) ? next(settingsDialog) : next;
362
380
  if (nextDialog === settingsDialog)
363
381
  return;
364
382
  if (controlledDialog === undefined)
@@ -370,70 +388,54 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
370
388
  }
371
389
  const displayName = session.user.name.trim();
372
390
  const displayEmail = session.user.email.trim();
373
- const displayImage = assetUrl(session.user.image, baseUrl);
391
+ const displayImage = assetUrl(session.user.image, resolvedBaseUrl);
374
392
  const isImpersonating = Boolean(session.session.impersonatedBy);
375
393
  const isOrganizationImpersonating = Boolean(session.session.impersonatedByOrganizationId);
376
394
  const canManageUserSettings = !isOrganizationImpersonating;
377
395
  const canUseAdminSettings = !isOrganizationImpersonating;
378
396
  const isAdmin = hasAdminRole(session.user);
379
- const signOut = async () => {
397
+ const startSignOut = () => {
380
398
  const redirectUrl = signOutRedirect.startsWith("http")
381
399
  ? signOutRedirect
382
400
  : `${import.meta.env.VITE_SITE_URL}${signOutRedirect.startsWith("/") ? signOutRedirect : `/${signOutRedirect}`}`;
383
- await authClient.signOut();
384
- await navigate({ href: redirectUrl });
385
- };
386
- const stopImpersonating = async () => {
387
- setIsStoppingImpersonation(true);
388
- try {
389
- await authClient.admin.stopImpersonating();
390
- await refetch();
391
- await navigate({ href: currentSiteHref });
392
- }
393
- finally {
394
- setIsStoppingImpersonation(false);
395
- }
401
+ signOut({ baseUrl: resolvedBaseUrl, redirectUrl });
396
402
  };
397
- const updateUser = async (values) => {
398
- setFormError(null);
399
- const imageFile = isFile(values.image) ? values.image : null;
400
- const image = imageFile
401
- ? await (async () => {
402
- const uploaded = await uploadUserImageAsset(imageFile, m, uploadUserImage);
403
- return assetPath(uploaded.url);
404
- })()
405
- : typeof values.image === "string"
406
- ? assetPath(values.image)
407
- : null;
408
- const result = await authClient.updateUser({
409
- name: values.name.trim(),
410
- image: image?.trim() ?? "",
411
- });
412
- if (isAuthErrorResult(result)) {
413
- throw new Error(result.error.message || m.user_form_update_error());
414
- }
415
- await refetch();
416
- setSettingsDialog(null);
417
- };
418
- return (_jsxs(UserButtonMessagesContext.Provider, { value: m, children: [hideTrigger ? null : (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsxs(Button, { variant: "outline", size: "icon", children: [displayImage ? (_jsx("img", { src: displayImage, alt: displayName || displayEmail, className: "size-full rounded-md object-cover" })) : (_jsx(UserIcon, { className: "size-4.5" })), _jsx("span", { className: "sr-only", children: m.user_button_aria_label() })] }) }), _jsx(DropdownMenuContent, { className: "w-56 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [isImpersonating ? (_jsx("div", { className: "px-1 py-0.5", children: _jsx(Badge, { variant: "secondary", className: "text-xs font-normal", children: m.user_button_impersonating() }) })) : null, _jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: displayName || displayEmail, subtitle: displayName ? displayEmail : m.user_button_account(), icon: UserIcon, className: "px-1 py-1.5 text-left text-sm", ...(displayImage ? { imageSrc: displayImage } : {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, _jsx(DropdownMenuSeparator, {}), canManageUserSettings ? (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuItem, { disabled: isPending, onClick: () => setSettingsDialog("account"), children: [_jsx(UserCircleIcon, {}), m.user_button_account()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("security"), children: [_jsx(ShieldCheck, {}), m.user_button_security()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] }), _jsx(DropdownMenuSeparator, {})] })) : null, (isAdmin && canUseAdminSettings) || isImpersonating ? (_jsxs(_Fragment, { children: [isAdmin && canUseAdminSettings ? (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("adminUsers"), children: [_jsx(Users, {}), m.user_button_admin_users()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("adminOrganizations"), children: [_jsx(Building2, {}), m.user_button_admin_organizations()] })] })) : null, isImpersonating ? (_jsxs(DropdownMenuItem, { disabled: isStoppingImpersonation, onClick: stopImpersonating, children: [_jsx(StopCircle, {}), m.user_button_stop_impersonating()] })) : null, _jsx(DropdownMenuSeparator, {})] })) : null, _jsxs(DropdownMenuItem, { onClick: signOut, children: [_jsx(LogOutIcon, {}), m.user_button_logout()] })] }) })] })), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "account", onOpenChange: (open) => {
403
+ return (_jsxs(UserButtonMessagesContext.Provider, { value: m, children: [hideTrigger ? null : (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsxs(Button, { variant: "outline", size: "icon", children: [displayImage ? (_jsx("img", { src: displayImage, alt: displayName || displayEmail, className: "size-full rounded-md object-cover" })) : (_jsx(UserIcon, { className: "size-4.5" })), _jsx("span", { className: "sr-only", children: m.user_button_aria_label() })] }) }), _jsx(DropdownMenuContent, { className: "w-56 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [isImpersonating ? (_jsx("div", { className: "px-1 py-0.5", children: _jsx(Badge, { variant: "secondary", className: "text-xs font-normal", children: m.user_button_impersonating() }) })) : null, _jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: displayName || displayEmail, subtitle: displayName ? displayEmail : m.user_button_account(), icon: UserIcon, className: "px-1 py-1.5 text-left text-sm", ...(displayImage ? { imageSrc: displayImage } : {}) }) }), menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, _jsx(DropdownMenuSeparator, {}), canManageUserSettings ? (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuItem, { disabled: isPending, onClick: () => setSettingsDialog("account"), children: [_jsx(UserCircleIcon, {}), m.user_button_account()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("security"), children: [_jsx(ShieldCheck, {}), m.user_button_security()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] }), _jsx(DropdownMenuSeparator, {})] })) : null, (isAdmin && canUseAdminSettings) || isImpersonating ? (_jsxs(_Fragment, { children: [isAdmin && canUseAdminSettings ? (_jsxs(_Fragment, { children: [_jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("adminUsers"), children: [_jsx(Users, {}), m.user_button_admin_users()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("adminOrganizations"), children: [_jsx(Building2, {}), m.user_button_admin_organizations()] })] })) : null, isImpersonating ? (_jsxs(DropdownMenuItem, { disabled: isStoppingImpersonation, onClick: () => stopImpersonating({
404
+ baseUrl: resolvedBaseUrl,
405
+ currentSiteHref,
406
+ refreshSession,
407
+ }), children: [_jsx(StopCircle, {}), m.user_button_stop_impersonating()] })) : null, _jsx(DropdownMenuSeparator, {})] })) : null, _jsxs(DropdownMenuItem, { disabled: signOutResult.waiting, onClick: startSignOut, children: [_jsx(LogOutIcon, {}), m.user_button_logout()] }), authActionError ? (_jsx(DropdownMenuLabel, { className: "text-destructive text-xs font-normal", children: authActionError })) : null] }) })] })), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "account", onOpenChange: (open) => {
419
408
  setSettingsDialog((current) => open ? "account" : current === "account" ? null : current);
420
409
  }, children: _jsxs(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_form_title() }), _jsx(DialogDescription, { children: m.user_form_description() })] }), _jsx(Separator, {}), isPending ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(UserForm, { defaultValues: {
421
410
  name: displayName ?? "",
422
411
  image: displayImage || null,
423
- }, error: formError, onSubmit: async (data) => {
424
- try {
425
- await updateUser(data);
426
- }
427
- catch (error) {
428
- setFormError(error instanceof Error
429
- ? error.message
430
- : m.user_form_update_error());
431
- }
432
- } }), _jsx(Separator, {}), _jsx(ConnectedAccounts, { authClient: authClient, baseUrl: baseUrl, accountCache: accountCache, googleEnabled: projectConfig?.authOptions.google ?? true, currentSiteHref: currentSiteHref, navigate: navigate })] }))] }) }), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "security", onOpenChange: (open) => {
412
+ }, error: formError, onSubmit: (values) => Effect.gen(function* () {
413
+ setFormError(null);
414
+ const imageFile = isFile(values.image)
415
+ ? values.image
416
+ : null;
417
+ const image = imageFile
418
+ ? assetPath((yield* uploadUserImageAsset(imageFile, m, resolvedBaseUrl)).url)
419
+ : Schema.is(Schema.String)(values.image)
420
+ ? assetPath(values.image)
421
+ : null;
422
+ const client = yield* authHttpClient(resolvedBaseUrl);
423
+ yield* client.auth.updateUser({
424
+ payload: {
425
+ name: values.name.trim(),
426
+ image: image?.trim() ?? "",
427
+ },
428
+ });
429
+ notifyAuthChange();
430
+ yield* Effect.sync(refreshSession);
431
+ setSettingsDialog(null);
432
+ }).pipe(Effect.tapError((error) => Effect.sync(() => setFormError(error instanceof Error
433
+ ? error.message
434
+ : m.user_form_update_error())))) }), _jsx(Separator, {}), _jsx(ConnectedAccounts, { baseUrl: resolvedBaseUrl, accountCache: accountCache, googleEnabled: projectConfig?.authOptions.google ?? true, currentSiteHref: currentSiteHref, navigate: navigate })] }))] }) }), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "security", onOpenChange: (open) => {
433
435
  setSettingsDialog((current) => open ? "security" : current === "security" ? null : current);
434
- }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_security_title() }), _jsx(DialogDescription, { children: m.user_security_description() })] }), _jsx(Separator, {}), _jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(PasswordSettings, { authClient: authClient, baseUrl: baseUrl, accountCache: accountCache }), _jsx(Separator, {}), _jsx(AccountSecuritySettings, { authClient: authClient, accountCache: accountCache })] })] }) }), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "apiKeys", onOpenChange: (open) => {
436
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_security_title() }), _jsx(DialogDescription, { children: m.user_security_description() })] }), _jsx(Separator, {}), _jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(PasswordSettings, { baseUrl: resolvedBaseUrl, accountCache: accountCache }), _jsx(Separator, {}), _jsx(AccountSecuritySettings, { baseUrl: resolvedBaseUrl, accountCache: accountCache })] })] }) }), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "apiKeys", onOpenChange: (open) => {
435
437
  setSettingsDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
436
- }, children: _jsx(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-3xl", children: _jsx(ApiKeyManager, { authClient: authClient, active: settingsDialog === "apiKeys", permissionLabels: auth?.accessLabels ?? undefined, permissions: apiKeyPermissions ?? auth?.access?.apiKeyPermissions.user ?? {} }) }) }), isAdmin ? (_jsxs(_Fragment, { children: [_jsx(Dialog, { open: settingsDialog === "adminUsers", onOpenChange: (open) => {
438
+ }, children: _jsx(DialogContent, { className: "max-h-[85vh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-3xl", children: _jsx(ApiKeyManager, { baseUrl: resolvedBaseUrl, active: settingsDialog === "apiKeys", permissionLabels: auth?.accessLabels ?? undefined, permissions: apiKeyPermissions ?? auth?.access?.apiKeyPermissions.user ?? {} }) }) }), isAdmin ? (_jsxs(_Fragment, { children: [_jsx(Dialog, { open: settingsDialog === "adminUsers", onOpenChange: (open) => {
437
439
  setSettingsDialog((current) => open ? "adminUsers" : current === "adminUsers" ? null : current);
438
440
  }, children: _jsxs(DialogContent, { className: "flex h-[85vh] flex-col overflow-y-auto sm:max-w-6xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_button_admin_users() }), _jsx(DialogDescription, { children: m.user_button_admin_users_description() })] }), _jsx(Separator, {}), _jsx("div", { className: "min-h-0 flex-1", children: _jsx(AdminUsersTable, {}) })] }) }), _jsx(Dialog, { open: settingsDialog === "adminOrganizations", onOpenChange: (open) => {
439
441
  setSettingsDialog((current) => open
@@ -443,52 +445,55 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
443
445
  : current);
444
446
  }, children: _jsxs(DialogContent, { className: "flex h-[85vh] flex-col overflow-y-auto sm:max-w-6xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_button_admin_organizations() }), _jsx(DialogDescription, { children: m.user_button_admin_organizations_description() })] }), _jsx(Separator, {}), _jsx("div", { className: "min-h-0 flex-1", children: _jsx(AdminOrganizationsTable, {}) })] }) })] })) : null] }));
445
447
  };
446
- function ConnectedAccounts({ authClient, baseUrl, accountCache, googleEnabled, currentSiteHref, navigate, }) {
448
+ function ConnectedAccounts({ baseUrl, accountCache, googleEnabled, currentSiteHref, navigate, }) {
447
449
  const m = useUserButtonMessages();
448
450
  const [error, setError] = useState(null);
449
451
  const [isLinking, setIsLinking] = useState(false);
450
452
  const [revokingAccount, setRevokingAccount] = useState(null);
451
- const accounts = accountCache.accounts ?? [];
452
- const googleAccount = accounts.find((account) => account.providerId === "google");
453
- const requirePassword = requiresPasswordForAccountRevoke(accounts);
454
- const showGoogleAccount = googleEnabled || Boolean(googleAccount);
455
- if (accountCache.accounts && (accounts.length === 0 || !showGoogleAccount)) {
456
- return null;
457
- }
458
- const linkGoogle = async () => {
459
- if (!googleEnabled)
460
- return;
453
+ const [linkGoogleAction] = useState(() => Atom.fn((input) => Effect.gen(function* () {
461
454
  setError(null);
462
455
  setIsLinking(true);
463
- const result = await authClient.linkSocial({
464
- provider: "google",
465
- callbackURL: currentSiteHref,
456
+ const client = yield* authHttpClient(input.baseUrl);
457
+ const result = yield* client.auth.linkSocial({
458
+ payload: { provider: "google", callbackURL: input.callbackURL },
466
459
  });
467
- if (result.error) {
468
- setError(result.error.message ?? m.user_account_google_link_error());
469
- setIsLinking(false);
470
- return;
460
+ notifyAuthChange();
461
+ yield* Effect.tryPromise(() => accountCache.reload());
462
+ const redirectUrl = result.url;
463
+ if (redirectUrl) {
464
+ yield* Effect.tryPromise(() => navigate({ href: redirectUrl }));
471
465
  }
472
- if (result.data?.url) {
473
- await navigate({ href: result.data.url });
474
- return;
466
+ else {
467
+ setIsLinking(false);
475
468
  }
469
+ }).pipe(Effect.catch((cause) => Effect.sync(() => {
470
+ setError(cause instanceof Error && cause.message
471
+ ? cause.message
472
+ : m.user_account_google_link_error());
476
473
  setIsLinking(false);
477
- };
478
- const revokeAccount = async (account) => {
479
- setError(null);
480
- const result = await authClient.unlinkAccount({
474
+ })))));
475
+ const linkGoogle = useAtomSet(linkGoogleAction);
476
+ const revokeAccount = (account) => authHttpClient(baseUrl).pipe(Effect.tap(() => Effect.sync(() => setError(null))), Effect.flatMap((client) => client.auth.unlinkAccount({
477
+ payload: {
481
478
  providerId: account.providerId,
482
479
  accountId: account.accountId,
483
- });
484
- if (result.error) {
485
- setError(result.error.message ?? m.user_account_revoke_error());
480
+ },
481
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => accountCache.reload())), Effect.tap(() => Effect.sync(() => setRevokingAccount(null))), Effect.catch((cause) => Effect.sync(() => setError(cause instanceof Error && cause.message
482
+ ? cause.message
483
+ : m.user_account_revoke_error()))));
484
+ const accounts = accountCache.accounts ?? [];
485
+ const googleAccount = accounts.find((account) => account.providerId === "google");
486
+ const requirePassword = requiresPasswordForAccountRevoke(accounts);
487
+ const showGoogleAccount = googleEnabled || Boolean(googleAccount);
488
+ if (accountCache.accounts && (accounts.length === 0 || !showGoogleAccount)) {
489
+ return null;
490
+ }
491
+ const startLinkGoogle = () => {
492
+ if (!googleEnabled)
486
493
  return;
487
- }
488
- setRevokingAccount(null);
489
- await accountCache.reload();
494
+ linkGoogle({ baseUrl, callbackURL: currentSiteHref });
490
495
  };
491
- return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_accounts_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_accounts_description() })] }), accountCache.accounts ? (_jsxs(_Fragment, { children: [showGoogleAccount ? (_jsx(AccountProviderRow, { icon: _jsx(GoogleLogo, {}), title: m.user_account_google_title(), description: m.user_account_google_description(), account: googleAccount, connected: Boolean(googleAccount), connectLabel: m.user_account_google_connect(), revokeLabel: m.user_account_revoke(), isConnecting: isLinking, renderDisconnected: undefined, onConnect: linkGoogle, onRevoke: (account) => setRevokingAccount(account) })) : null, revokingAccount ? (_jsx(RevokeAccountForm, { baseUrl: baseUrl, account: revokingAccount, requirePassword: requirePassword, onCancel: () => setRevokingAccount(null), onRevoke: revokeAccount })) : null] })) : !accountCache.error ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : null, accountCache.error ? (_jsx("p", { className: "text-destructive text-sm", children: accountCache.error })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }));
496
+ return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_accounts_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_accounts_description() })] }), accountCache.accounts ? (_jsxs(_Fragment, { children: [showGoogleAccount ? (_jsx(AccountProviderRow, { icon: _jsx(GoogleLogo, {}), title: m.user_account_google_title(), description: m.user_account_google_description(), account: googleAccount, connected: Boolean(googleAccount), connectLabel: m.user_account_google_connect(), revokeLabel: m.user_account_revoke(), isConnecting: isLinking, renderDisconnected: undefined, onConnect: startLinkGoogle, onRevoke: (account) => setRevokingAccount(account) })) : null, revokingAccount ? (_jsx(RevokeAccountForm, { baseUrl: baseUrl, account: revokingAccount, requirePassword: requirePassword, onCancel: () => setRevokingAccount(null), onRevoke: revokeAccount })) : null] })) : !accountCache.error ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : null, accountCache.error ? (_jsx("p", { className: "text-destructive text-sm", children: accountCache.error })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }));
492
497
  }
493
498
  function AccountProviderRow({ icon, title, description, account, connected, connectLabel, revokeLabel, isConnecting, renderDisconnected, onConnect, onRevoke, }) {
494
499
  const m = useUserButtonMessages();
@@ -499,7 +504,7 @@ function AccountProviderRow({ icon, title, description, account, connected, conn
499
504
  function GoogleLogo() {
500
505
  return (_jsxs("svg", { viewBox: "0 0 24 24", "aria-hidden": "true", className: "size-5", children: [_jsx("path", { fill: "#4285F4", d: "M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" }), _jsx("path", { fill: "#34A853", d: "M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" }), _jsx("path", { fill: "#FBBC05", d: "M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" }), _jsx("path", { fill: "#EA4335", d: "M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z" })] }));
501
506
  }
502
- function PasswordSettings({ authClient, baseUrl, accountCache, }) {
507
+ function PasswordSettings({ baseUrl, accountCache, }) {
503
508
  const [error, setError] = useState(null);
504
509
  const [revokingAccount, setRevokingAccount] = useState(null);
505
510
  const m = useUserButtonMessages();
@@ -507,46 +512,33 @@ function PasswordSettings({ authClient, baseUrl, accountCache, }) {
507
512
  const passwordAccount = accounts.find((account) => account.providerId === "credential");
508
513
  const hasPassword = Boolean(passwordAccount);
509
514
  const requirePassword = requiresPasswordForAccountRevoke(accounts);
510
- const revokePassword = async (account) => {
511
- setError(null);
512
- const result = await authClient.unlinkAccount({
515
+ const revokePassword = (account) => authHttpClient(baseUrl).pipe(Effect.tap(() => Effect.sync(() => setError(null))), Effect.flatMap((client) => client.auth.unlinkAccount({
516
+ payload: {
513
517
  providerId: account.providerId,
514
518
  accountId: account.accountId,
515
- });
516
- if (result.error) {
517
- setError(result.error.message ?? m.user_account_revoke_error());
518
- return;
519
- }
520
- setRevokingAccount(null);
521
- await accountCache.reload();
522
- };
523
- return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_account_password_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_description() })] }), accountCache.accounts && hasPassword && passwordAccount ? (_jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3 rounded-lg border p-4", children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("p", { className: "font-medium", children: m.user_account_password_title() }), _jsx(Badge, { children: m.user_account_connected() })] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_connected_description() })] }), _jsx(Button, { type: "button", variant: "outline", onClick: () => setRevokingAccount(passwordAccount), children: m.user_account_revoke() })] }), revokingAccount ? (_jsx(RevokeAccountForm, { baseUrl: baseUrl, account: revokingAccount, requirePassword: requirePassword, onCancel: () => setRevokingAccount(null), onRevoke: revokePassword })) : null, _jsx(Separator, {}), _jsx(ChangePasswordForm, { authClient: authClient })] })) : accountCache.accounts ? (_jsx(SetPasswordForm, { authClient: authClient, onSaved: accountCache.reload })) : !accountCache.error ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : null, accountCache.error ? (_jsx("p", { className: "text-destructive text-sm", children: accountCache.error })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }));
519
+ },
520
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => accountCache.reload())), Effect.tap(() => Effect.sync(() => setRevokingAccount(null))), Effect.catch((cause) => Effect.sync(() => setError(cause instanceof Error && cause.message
521
+ ? cause.message
522
+ : m.user_account_revoke_error()))));
523
+ return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_account_password_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_description() })] }), accountCache.accounts && hasPassword && passwordAccount ? (_jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3 rounded-lg border p-4", children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("p", { className: "font-medium", children: m.user_account_password_title() }), _jsx(Badge, { children: m.user_account_connected() })] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_connected_description() })] }), _jsx(Button, { type: "button", variant: "outline", onClick: () => setRevokingAccount(passwordAccount), children: m.user_account_revoke() })] }), revokingAccount ? (_jsx(RevokeAccountForm, { baseUrl: baseUrl, account: revokingAccount, requirePassword: requirePassword, onCancel: () => setRevokingAccount(null), onRevoke: revokePassword })) : null, _jsx(Separator, {}), _jsx(ChangePasswordForm, { baseUrl: baseUrl })] })) : accountCache.accounts ? (_jsx(SetPasswordForm, { baseUrl: baseUrl, onSaved: accountCache.reload })) : !accountCache.error ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : null, accountCache.error ? (_jsx("p", { className: "text-destructive text-sm", children: accountCache.error })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }));
524
524
  }
525
- function ChangePasswordForm({ authClient }) {
525
+ function ChangePasswordForm({ baseUrl }) {
526
526
  const m = useUserButtonMessages();
527
527
  const [saved, setSaved] = useState(false);
528
+ let reset = () => { };
528
529
  const [form] = useState(() => FormReact.make(changePasswordFormBuilder, {
529
530
  fields: { currentPassword: TextField, newPassword: TextField },
530
531
  mode: { validation: "onSubmit" },
531
- onSubmit: (_, { decoded }) => Effect.tryPromise({
532
- try: async () => {
533
- setSaved(false);
534
- const result = await authClient.changePassword({
535
- currentPassword: decoded.currentPassword,
536
- newPassword: decoded.newPassword,
537
- });
538
- if (result.error) {
539
- throw new Error(result.error.message ?? m.user_account_password_change_error());
540
- }
541
- reset();
542
- setSaved(true);
532
+ onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.tap(() => Effect.sync(() => setSaved(false))), Effect.flatMap((client) => client.auth.changePassword({
533
+ payload: {
534
+ currentPassword: decoded.currentPassword,
535
+ newPassword: decoded.newPassword,
543
536
  },
544
- catch: (cause) => cause instanceof Error
545
- ? cause
546
- : new Error(m.user_account_password_change_error()),
547
- }),
537
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap(() => Effect.sync(() => reset())), Effect.tap(() => Effect.sync(() => setSaved(true))), Effect.mapError((cause) => cause instanceof Error
538
+ ? cause
539
+ : new Error(m.user_account_password_change_error()))),
548
540
  }));
549
- const reset = useAtomSet(form.reset);
541
+ reset = useAtomSet(form.reset);
550
542
  const submit = useAtomSet(form.submit);
551
543
  const submitResult = useAtomValue(form.submit);
552
544
  return (_jsx(form.Initialize, { defaultValues: { currentPassword: "", newPassword: "" }, children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-md", onSubmit: (event) => {
@@ -555,29 +547,19 @@ function ChangePasswordForm({ authClient }) {
555
547
  submit();
556
548
  }, children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("h3", { className: "text-sm font-medium", children: m.user_account_password_change_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_change_description() })] }), _jsx(form.currentPassword, { label: m.user_account_current_password(), type: "password", autoComplete: "current-password", required: true }), _jsx(form.newPassword, { label: m.user_account_new_password(), type: "password", autoComplete: "new-password", required: true }), _jsx(SubmitError, { result: submitResult }), saved ? (_jsx("p", { className: "text-sm text-green-600", children: m.user_account_password_change_success() })) : null, _jsx(SubmitButton, { form: form, children: m.user_account_password_change_submit() })] }) }));
557
549
  }
558
- function SetPasswordForm({ authClient, onSaved, }) {
550
+ function SetPasswordForm({ baseUrl, onSaved, }) {
559
551
  const m = useUserButtonMessages();
552
+ let reset = () => { };
560
553
  const [form] = useState(() => FormReact.make(passwordFormBuilder(true), {
561
554
  fields: { password: TextField },
562
555
  mode: { validation: "onSubmit" },
563
- onSubmit: (_, { decoded }) => Effect.tryPromise({
564
- try: async () => {
565
- const result = await authClient.$fetch("/set-password", {
566
- method: "POST",
567
- body: { newPassword: decoded.password },
568
- });
569
- if (result.error) {
570
- throw new Error(result.error.message ?? m.user_account_password_set_error());
571
- }
572
- reset();
573
- await onSaved();
574
- },
575
- catch: (cause) => cause instanceof Error
576
- ? cause
577
- : new Error(m.user_account_password_set_error()),
578
- }),
556
+ onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.authExtra.setPassword({
557
+ payload: { newPassword: decoded.password },
558
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap(() => Effect.sync(() => reset())), Effect.flatMap(() => Effect.tryPromise(() => onSaved())), Effect.mapError((cause) => cause instanceof Error
559
+ ? cause
560
+ : new Error(m.user_account_password_set_error()))),
579
561
  }));
580
- const reset = useAtomSet(form.reset);
562
+ reset = useAtomSet(form.reset);
581
563
  const submit = useAtomSet(form.submit);
582
564
  const submitResult = useAtomValue(form.submit);
583
565
  return (_jsx(form.Initialize, { defaultValues: { password: "" }, children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-sm", onSubmit: (event) => {
@@ -588,23 +570,20 @@ function SetPasswordForm({ authClient, onSaved, }) {
588
570
  }
589
571
  function RevokeAccountForm({ baseUrl, account, requirePassword, onCancel, onRevoke, }) {
590
572
  const m = useUserButtonMessages();
591
- const verifyPassword = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "verifyPassword"), { mode: "promise" });
592
573
  const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
593
574
  fields: { password: TextField },
594
575
  mode: { validation: "onSubmit" },
595
- onSubmit: (_, { decoded }) => Effect.tryPromise({
596
- try: async () => {
597
- if (requirePassword) {
598
- await verifyPassword({
599
- payload: { password: decoded.password },
600
- });
601
- }
602
- await onRevoke(account);
603
- },
604
- catch: (cause) => cause instanceof Error
605
- ? cause
606
- : new Error(m.user_account_password_verify_error()),
607
- }),
576
+ onSubmit: (_, { decoded }) => Effect.gen(function* () {
577
+ if (requirePassword) {
578
+ const client = yield* authHttpClient(baseUrl);
579
+ yield* client.authExtra.verifyPassword({
580
+ payload: { password: decoded.password },
581
+ });
582
+ }
583
+ yield* onRevoke(account);
584
+ }).pipe(Effect.mapError((cause) => cause instanceof Error
585
+ ? cause
586
+ : new Error(m.user_account_password_verify_error()))),
608
587
  }));
609
588
  const submit = useAtomSet(form.submit);
610
589
  const submitResult = useAtomValue(form.submit);
@@ -628,12 +607,9 @@ const UserForm = ({ defaultValues, error, onSubmit, }) => {
628
607
  const [form] = useState(() => FormReact.make(userFormBuilder, {
629
608
  fields: { name: TextField, image: ImageField },
630
609
  mode: { validation: "onSubmit" },
631
- onSubmit: (_, { decoded }) => Effect.tryPromise({
632
- try: () => onSubmit({ ...decoded, image: decoded.image ?? null }),
633
- catch: (cause) => cause instanceof Error
634
- ? cause
635
- : new Error(m.user_form_update_error()),
636
- }),
610
+ onSubmit: (_, { decoded }) => onSubmit({ ...decoded, image: decoded.image ?? null }).pipe(Effect.mapError((cause) => cause instanceof Error
611
+ ? cause
612
+ : new Error(m.user_form_update_error()))),
637
613
  }));
638
614
  const submit = useAtomSet(form.submit);
639
615
  return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_profile_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_profile_description() })] }), _jsx(form.Initialize, { defaultValues: defaultValues, children: _jsxs("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
@@ -647,12 +623,19 @@ const UserForm = ({ defaultValues, error, onSubmit, }) => {
647
623
  suggestedHeight: 512,
648
624
  } }), _jsx(form.name, { label: m.user_form_name_label(), autoComplete: "name", required: true }), error && (_jsx("p", { role: "alert", className: "text-destructive text-sm", children: error })), _jsx(SubmitButton, { form: form })] }) })] }));
649
625
  };
650
- function AccountSecuritySettings({ authClient, accountCache, }) {
626
+ function AccountSecuritySettings({ baseUrl, accountCache, }) {
651
627
  const m = useUserButtonMessages();
652
- const session = authClient.useSession();
628
+ const sessionAtom = authSessionAtom(baseUrl);
629
+ const sessionResult = useAtomValue(sessionAtom);
630
+ const refreshSession = useAtomRefresh(sessionAtom);
631
+ const session = AsyncResult.match(sessionResult, {
632
+ onInitial: () => null,
633
+ onFailure: () => null,
634
+ onSuccess: ({ value }) => value,
635
+ });
653
636
  const [setup, setSetup] = useState(null);
654
637
  const [message, setMessage] = useState(null);
655
- const twoFactorEnabled = hasTwoFactorEnabled(session.data?.user);
638
+ const twoFactorEnabled = hasTwoFactorEnabled(session?.user);
656
639
  const requirePassword = accountCache.accounts
657
640
  ? accountCache.accounts.some((account) => account.providerId === "credential")
658
641
  : null;
@@ -660,35 +643,28 @@ function AccountSecuritySettings({ authClient, accountCache, }) {
660
643
  ? m.user_two_factor_enabled()
661
644
  : m.user_two_factor_disabled() })] }), requirePassword === null ? (_jsx("p", { className: accountCache.error
662
645
  ? "text-destructive text-sm"
663
- : "text-muted-foreground text-sm", children: accountCache.error ?? m.user_loading() })) : twoFactorEnabled ? (_jsx(DisableTotpForm, { authClient: authClient, requirePassword: requirePassword, onDisabled: async () => {
646
+ : "text-muted-foreground text-sm", children: accountCache.error ?? m.user_loading() })) : twoFactorEnabled ? (_jsx(DisableTotpForm, { baseUrl: baseUrl, requirePassword: requirePassword, onDisabled: async () => {
664
647
  setMessage(m.user_two_factor_disabled_message());
665
- await session.refetch();
666
- } })) : setup ? (_jsx(VerifyTotpSetup, { authClient: authClient, setup: setup, onVerified: async () => {
648
+ await refreshSession();
649
+ } })) : setup ? (_jsx(VerifyTotpSetup, { baseUrl: baseUrl, setup: setup, onVerified: async () => {
667
650
  setSetup(null);
668
651
  setMessage(m.user_two_factor_enabled_message());
669
- await session.refetch();
670
- } })) : (_jsx(EnableTotpForm, { authClient: authClient, requirePassword: requirePassword, onEnabled: setSetup })), message ? (_jsx("p", { className: "text-muted-foreground text-sm", children: message })) : null] }));
652
+ await refreshSession();
653
+ } })) : (_jsx(EnableTotpForm, { baseUrl: baseUrl, requirePassword: requirePassword, onEnabled: setSetup })), message ? (_jsx("p", { className: "text-muted-foreground text-sm", children: message })) : null] }));
671
654
  }
672
- function EnableTotpForm({ authClient, requirePassword, onEnabled, }) {
655
+ function EnableTotpForm({ baseUrl, requirePassword, onEnabled, }) {
673
656
  const m = useUserButtonMessages();
674
657
  const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
675
658
  fields: { password: TextField },
676
659
  mode: { validation: "onSubmit" },
677
- onSubmit: (_, { decoded }) => Effect.tryPromise({
678
- try: async () => {
679
- const result = await authClient.twoFactor.enable(requirePassword ? { password: decoded.password } : {});
680
- if (result.error || !result.data) {
681
- throw new Error(result.error?.message ?? m.user_two_factor_enable_error());
682
- }
683
- onEnabled({
684
- totpURI: result.data.totpURI,
685
- backupCodes: result.data.backupCodes,
686
- });
687
- },
688
- catch: (cause) => cause instanceof Error
689
- ? cause
690
- : new Error(m.user_two_factor_enable_error()),
691
- }),
660
+ onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorEnable({
661
+ payload: requirePassword ? { password: decoded.password } : {},
662
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap((result) => Effect.sync(() => onEnabled({
663
+ totpURI: result.totpURI,
664
+ backupCodes: Array.from(result.backupCodes),
665
+ }))), Effect.mapError((cause) => cause instanceof Error
666
+ ? cause
667
+ : new Error(m.user_two_factor_enable_error()))),
692
668
  }));
693
669
  const submit = useAtomSet(form.submit);
694
670
  const submitResult = useAtomValue(form.submit);
@@ -698,25 +674,16 @@ function EnableTotpForm({ authClient, requirePassword, onEnabled, }) {
698
674
  submit();
699
675
  }, children: [requirePassword ? (_jsx(form.password, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) : null, _jsx(SubmitError, { result: submitResult }), requirePassword ? (_jsx(SubmitButton, { form: form, children: m.user_two_factor_enable_submit() })) : (_jsxs(Button, { type: "button", disabled: submitResult.waiting, onClick: () => submit(), children: [submitResult.waiting ? (_jsx(Loader2, { "data-icon": "inline-start", className: "animate-spin" })) : null, m.user_two_factor_enable_submit()] }))] }) }));
700
676
  }
701
- function VerifyTotpSetup({ authClient, setup, onVerified, }) {
677
+ function VerifyTotpSetup({ baseUrl, setup, onVerified, }) {
702
678
  const m = useUserButtonMessages();
703
679
  const [form] = useState(() => FormReact.make(totpCodeFormBuilder, {
704
680
  fields: { code: TextField },
705
681
  mode: { validation: "onSubmit" },
706
- onSubmit: (_, { decoded }) => Effect.tryPromise({
707
- try: async () => {
708
- const result = await authClient.twoFactor.verifyTotp({
709
- code: decoded.code.trim(),
710
- });
711
- if (result.error) {
712
- throw new Error(result.error.message ?? m.user_two_factor_verify_error());
713
- }
714
- await onVerified();
715
- },
716
- catch: (cause) => cause instanceof Error
717
- ? cause
718
- : new Error(m.user_two_factor_verify_error()),
719
- }),
682
+ onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorVerifyTotp({
683
+ payload: { code: decoded.code.trim() },
684
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onVerified())), Effect.mapError((cause) => cause instanceof Error
685
+ ? cause
686
+ : new Error(m.user_two_factor_verify_error()))),
720
687
  }));
721
688
  const submit = useAtomSet(form.submit);
722
689
  const submitResult = useAtomValue(form.submit);
@@ -726,23 +693,16 @@ function VerifyTotpSetup({ authClient, setup, onVerified, }) {
726
693
  submit();
727
694
  }, children: [_jsx(form.code, { label: m.user_two_factor_code(), autoComplete: "one-time-code", inputMode: "numeric", required: true }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form })] }) })] }));
728
695
  }
729
- function DisableTotpForm({ authClient, requirePassword, onDisabled, }) {
696
+ function DisableTotpForm({ baseUrl, requirePassword, onDisabled, }) {
730
697
  const m = useUserButtonMessages();
731
698
  const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
732
699
  fields: { password: TextField },
733
700
  mode: { validation: "onSubmit" },
734
- onSubmit: (_, { decoded }) => Effect.tryPromise({
735
- try: async () => {
736
- const result = await authClient.twoFactor.disable(requirePassword ? { password: decoded.password } : {});
737
- if (result.error) {
738
- throw new Error(result.error.message ?? m.user_two_factor_disable_error());
739
- }
740
- await onDisabled();
741
- },
742
- catch: (cause) => cause instanceof Error
743
- ? cause
744
- : new Error(m.user_two_factor_disable_error()),
745
- }),
701
+ onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorDisable({
702
+ payload: requirePassword ? { password: decoded.password } : {},
703
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onDisabled())), Effect.mapError((cause) => cause instanceof Error
704
+ ? cause
705
+ : new Error(m.user_two_factor_disable_error()))),
746
706
  }));
747
707
  const submit = useAtomSet(form.submit);
748
708
  const submitResult = useAtomValue(form.submit);
@@ -752,12 +712,15 @@ function DisableTotpForm({ authClient, requirePassword, onDisabled, }) {
752
712
  submit();
753
713
  }, children: [requirePassword ? (_jsx(form.password, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) : null, _jsx(SubmitError, { result: submitResult }), requirePassword ? (_jsx(SubmitButton, { form: form })) : (_jsxs(Button, { type: "button", disabled: submitResult.waiting, onClick: () => submit(), children: [submitResult.waiting ? (_jsx(Loader2, { "data-icon": "inline-start", className: "animate-spin" })) : null, effectFormMessages().submit] }))] }) }));
754
714
  }
755
- function ApiKeyManager({ authClient, active, permissionLabels, permissions = {}, }) {
715
+ function ApiKeyManager({ baseUrl, active, permissionLabels, permissions = {}, }) {
756
716
  const m = useUserButtonMessages();
757
717
  const hasOpened = useOpenedOnce(active);
758
- const keysAtom = hasOpened ? userApiKeysAtom(authClient) : emptyApiKeysAtom;
718
+ const loadedKeysAtom = userApiKeysAtom(baseUrl);
719
+ const keysAtom = hasOpened ? loadedKeysAtom : emptyApiKeysAtom;
759
720
  const keysResult = useAtomValue(keysAtom);
760
- const refreshKeys = useAtomRefresh(keysAtom);
721
+ const refreshLoadedKeys = useAtomRefresh(loadedKeysAtom);
722
+ const refreshEmptyKeys = useAtomRefresh(emptyApiKeysAtom);
723
+ const refreshKeys = hasOpened ? refreshLoadedKeys : refreshEmptyKeys;
761
724
  const [createdKey, setCreatedKey] = useState(null);
762
725
  const [creating, setCreating] = useState(false);
763
726
  const [editingKey, setEditingKey] = useState(null);
@@ -782,24 +745,29 @@ function ApiKeyManager({ authClient, active, permissionLabels, permissions = {},
782
745
  const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
783
746
  fields: { name: TextField, referrers: TextAreaField },
784
747
  mode: { validation: "onSubmit" },
785
- onSubmit: (_, { decoded }) => Effect.tryPromise({
786
- try: async () => {
787
- setCreatedKey(null);
788
- const created = await createApiKey({
748
+ onSubmit: (_, { decoded }) => Effect.gen(function* () {
749
+ setCreatedKey(null);
750
+ const referrers = yield* Effect.try({
751
+ try: () => parseApiKeyReferrers(decoded.referrers, m.user_api_key_referrers_error()),
752
+ catch: (cause) => cause,
753
+ });
754
+ const client = yield* authHttpClient(baseUrl);
755
+ return yield* client.authExtra.createApiKey({
756
+ payload: {
789
757
  configId: "user",
790
758
  name: decoded.name.trim(),
791
759
  permissions: getSelectedPermissionObject(permissionOptionsRef.current, selectedPermissionsRef.current),
792
- referrers: parseApiKeyReferrers(decoded.referrers, m.user_api_key_referrers_error()),
793
- }, m.user_api_key_create_error());
794
- setCreatedKey(created.key);
795
- resetCreateForm();
796
- setSelectedPermissions({});
797
- refreshKeys();
798
- },
799
- catch: (cause) => cause instanceof Error
800
- ? cause
801
- : new Error(m.user_api_key_create_error()),
802
- }),
760
+ referrers,
761
+ },
762
+ });
763
+ }).pipe(Effect.tap((created) => Effect.sync(() => {
764
+ setCreatedKey(created.key);
765
+ resetCreateForm();
766
+ setSelectedPermissions({});
767
+ refreshKeys();
768
+ })), Effect.mapError((cause) => cause instanceof Error
769
+ ? cause
770
+ : new Error(m.user_api_key_create_error()))),
803
771
  }));
804
772
  const resetCreateForm = useAtomSet(createForm.reset);
805
773
  const submitCreateForm = useAtomSet(createForm.submit);
@@ -807,17 +775,12 @@ function ApiKeyManager({ authClient, active, permissionLabels, permissions = {},
807
775
  const togglePermission = (id, checked) => {
808
776
  setSelectedPermissions((current) => ({ ...current, [id]: checked }));
809
777
  };
810
- const deleteKey = async (key) => {
811
- const result = await authClient.apiKey.delete({
812
- configId: "user",
813
- keyId: key.id,
814
- });
815
- if (result.error) {
816
- setError(result.error.message ?? m.user_api_key_delete_error());
817
- return;
818
- }
819
- refreshKeys();
820
- };
778
+ const [deleteKeyAction] = useState(() => Atom.fn((key) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.apiKeyDelete({
779
+ payload: { configId: "user", keyId: key.id },
780
+ })), Effect.tap(() => Effect.sync(refreshKeys)), Effect.catch((cause) => Effect.sync(() => setError(cause instanceof Error && cause.message
781
+ ? cause.message
782
+ : m.user_api_key_delete_error()))))));
783
+ const deleteKey = useAtomSet(deleteKeyAction);
821
784
  return (_jsxs(_Fragment, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: editingKey
822
785
  ? m.user_api_key_edit_title()
823
786
  : createdKey
@@ -857,7 +820,7 @@ function ApiKeyManager({ authClient, active, permissionLabels, permissions = {},
857
820
  }, searchState: "local", state: {
858
821
  empty: loading ? m.user_loading() : m.table_empty(),
859
822
  loading,
860
- } }) })) : null, editingKey ? (_jsx(ApiKeyEditForm, { configId: "user", keyData: editingKey, permissions: permissions, permissionLabels: permissionLabels, messages: {
823
+ } }) })) : null, editingKey ? (_jsx(ApiKeyEditForm, { baseUrl: baseUrl, configId: "user", keyData: editingKey, permissions: permissions, permissionLabels: permissionLabels, messages: {
861
824
  enabled: m.user_api_key_enabled(),
862
825
  name: m.user_api_key_name(),
863
826
  referrers: m.user_api_key_referrers(),
@@ -932,10 +895,8 @@ const apiKeyRowActions = ({ m, onDelete, onEdit, }) => [
932
895
  },
933
896
  ];
934
897
  const getPermissionId = (resource, action) => `${resource}:${action}`;
935
- const isPermissionRecord = (permissions) => typeof permissions === "object" &&
936
- permissions !== null &&
937
- Object.values(permissions).every((actions) => Array.isArray(actions) &&
938
- actions.every((action) => typeof action === "string"));
898
+ const PermissionRecord = Schema.Record(Schema.String, Schema.Array(Schema.String));
899
+ const isPermissionRecord = Schema.is(PermissionRecord);
939
900
  const formatPermissions = (permissions) => {
940
901
  if (!isPermissionRecord(permissions))
941
902
  return [];
@@ -958,17 +919,5 @@ const getSelectedPermissionObject = (options, selected) => {
958
919
  }
959
920
  return permissions;
960
921
  };
961
- const hasTwoFactorEnabled = (user) => {
962
- if (typeof user !== "object" ||
963
- user === null ||
964
- !("twoFactorEnabled" in user))
965
- return false;
966
- return user.twoFactorEnabled === true;
967
- };
968
- const isAuthErrorResult = (result) => {
969
- return (typeof result === "object" &&
970
- result !== null &&
971
- "error" in result &&
972
- typeof result.error === "object" &&
973
- result.error !== null);
974
- };
922
+ const TwoFactorUser = Schema.Struct({ twoFactorEnabled: Schema.Boolean });
923
+ const hasTwoFactorEnabled = (user) => Option.exists(Schema.decodeUnknownOption(TwoFactorUser)(user), (decoded) => decoded.twoFactorEnabled);