@krak-stack/auth 0.1.71 → 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 -45
  17. package/dist/components/admin-users.js +115 -137
  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 -323
  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 +264 -314
  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 +20 -22
  58. package/dist/server/actor.js +14 -17
  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 +1 -1
  63. package/dist/server/middleware.js +1 -1
  64. package/dist/server/schema.js +1 -1
  65. package/dist/service.d.ts +2043 -191
  66. package/dist/service.js +23 -16
  67. package/package.json +8 -7
  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
@@ -2,7 +2,7 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
3
3
  import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
4
  import { useNavigate, useRouterState, } from "@tanstack/react-router";
5
- import { Effect, Schema } from "effect";
5
+ import { Effect, Option, Predicate, Schema } from "effect";
6
6
  import { AsyncResult, Atom } from "effect/unstable/reactivity";
7
7
  import { ArrowLeft, Building2, KeyRound, Loader2, LogOutIcon, Pencil, Plus, ShieldCheck, StopCircle, Trash2, UserCircleIcon, Users, UserIcon, } from "lucide-react";
8
8
  import { QRCode } from "react-qr-code";
@@ -16,18 +16,19 @@ import { CopyButton } from "@krak-stack/registry/copy-button";
16
16
  import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
17
17
  import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu";
18
18
  import { Separator } from "@/components/ui/separator";
19
- import { authClientApi } from "./auth-client-api";
20
- import { useKrakstackAuth } from "./auth-provider";
21
- import { createApiKey, parseApiKeyReferrers } from "./api-key";
22
- import { ApiKeyEditForm } from "./api-key-edit-form";
23
- import { ApiKeyPermissions } from "./api-key-permissions";
24
- import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit";
25
- import { ApiKeyReferrers } from "./api-key-referrers";
26
- import { useOpenedOnce } from "./hooks";
27
- import { ExtraUploadedAsset } from "../extra/schema";
28
- import { assetPath, assetUrl } from "./utils";
29
- import { AdminOrganizationsTable } from "./admin-organizations";
30
- 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";
31
32
  const messages = {
32
33
  en: {
33
34
  table_empty: "No results.",
@@ -106,8 +107,10 @@ const messages = {
106
107
  user_button_aria_label: "Open user menu",
107
108
  user_button_impersonating: "Impersonating",
108
109
  user_button_logout: "Log out",
110
+ user_button_logout_error: "Could not log out. Try again.",
109
111
  user_button_security: "Security",
110
112
  user_button_stop_impersonating: "Stop impersonating",
113
+ user_button_stop_impersonating_error: "Could not stop impersonating. Try again.",
111
114
  user_delete: "Delete",
112
115
  user_field_password: "Password",
113
116
  user_form_description: "Update the profile details associated with your account.",
@@ -213,8 +216,10 @@ const messages = {
213
216
  user_button_aria_label: "Ouvrir le menu utilisateur",
214
217
  user_button_impersonating: "Imitation",
215
218
  user_button_logout: "Se déconnecter",
219
+ user_button_logout_error: "Impossible de se déconnecter. Réessayez.",
216
220
  user_button_security: "Sécurité",
217
221
  user_button_stop_impersonating: "Arrêter l'imitation",
222
+ user_button_stop_impersonating_error: "Impossible d'arrêter l'imitation. Réessayez.",
218
223
  user_delete: "Supprimer",
219
224
  user_field_password: "Mot de passe",
220
225
  user_form_description: "Mettez à jour les informations de profil associées à votre compte.",
@@ -258,17 +263,29 @@ const userButtonMessages = (overrides) => ({
258
263
  const interpolate = (value, params) => params
259
264
  ? value.replace(/\{([^}]+)\}/g, (_, key) => String(params[key] ?? `{${key}}`))
260
265
  : value;
261
- const userButtonMessageFns = (labels) => new Proxy({}, {
262
- get: (_target, key) => (params) => interpolate(labels[key], params),
263
- });
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
+ };
264
275
  const UserButtonMessagesContext = createContext(userButtonMessageFns(userButtonMessages()));
265
276
  const useUserButtonMessages = () => useContext(UserButtonMessagesContext);
266
- const hasRole = (role, roles) => typeof role === "string" &&
267
- role.split(",").some((item) => roles.includes(item.trim().toLowerCase()));
268
- const hasAdminRole = (user) => typeof user === "object" &&
269
- user !== null &&
270
- "role" in user &&
271
- 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
+ };
272
289
  const changePasswordFormBuilder = FormBuilder.empty
273
290
  .addField("currentPassword", Schema.NonEmptyString)
274
291
  .addField("newPassword", Schema.NonEmptyString);
@@ -281,48 +298,24 @@ const apiKeyFormBuilder = FormBuilder.empty
281
298
  .addField("name", Schema.NonEmptyString)
282
299
  .addField("referrers", Schema.String);
283
300
  const isFile = (value) => value instanceof File;
284
- const decodeUploadedAsset = Schema.decodeUnknownPromise(ExtraUploadedAsset);
285
- const uploadUserImageAsset = async (file, m, uploadUserImage) => {
301
+ const uploadUserImageAsset = (file, m, baseUrl) => {
286
302
  const payload = new FormData();
287
303
  payload.append("file", file);
288
- try {
289
- return await decodeUploadedAsset(await uploadUserImage({ payload }));
290
- }
291
- catch {
292
- throw new Error(m.user_profile_image_upload_error());
293
- }
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())));
294
305
  };
295
306
  const requiresPasswordForAccountRevoke = (accounts) => accounts.some((account) => account.providerId === "credential");
296
- const userAccountsAtom = Atom.family((authClient) => Atom.keepAlive(Atom.make(Effect.tryPromise({
297
- try: async () => {
298
- const result = await authClient.listAccounts();
299
- if (result.error) {
300
- throw new Error(result.error.message ?? "Could not load accounts.");
301
- }
302
- return result.data ?? [];
303
- },
304
- catch: (error) => error,
305
- }))));
306
- const emptyAccountsAtom = Atom.make(Effect.succeed([]));
307
- const userApiKeysAtom = Atom.family((authClient) => Atom.keepAlive(Atom.make(Effect.tryPromise({
308
- try: async () => {
309
- const result = await authClient.apiKey.list({
310
- query: { configId: "user" },
311
- });
312
- if (result.error) {
313
- throw new Error(result.error.message ?? "Could not load API keys.");
314
- }
315
- return result.data?.apiKeys ?? [];
316
- },
317
- catch: (error) => error,
318
- }))));
319
- const emptyApiKeysAtom = Atom.make(Effect.succeed([]));
320
- 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, }) => {
321
317
  const auth = useKrakstackAuth();
322
- const authClient = providedAuthClient ?? auth?.authClient;
323
- if (!authClient) {
324
- throw new Error("KrakstackAuthProvider is required to use authClient.");
325
- }
318
+ const resolvedBaseUrl = baseUrl ?? auth?.baseUrl;
326
319
  const labels = userButtonMessages(messages);
327
320
  const m = userButtonMessageFns(labels);
328
321
  const projectConfig = auth?.projectConfig ?? null;
@@ -330,19 +323,45 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
330
323
  const currentSiteHref = useRouterState({
331
324
  select: (state) => `${import.meta.env.VITE_SITE_URL}${state.location.href}`,
332
325
  });
333
- 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;
334
335
  const [uncontrolledDialog, setUncontrolledDialog] = useState(defaultDialog);
335
336
  const [isStoppingImpersonation, setIsStoppingImpersonation] = useState(false);
336
337
  const settingsDialog = controlledDialog !== undefined ? controlledDialog : uncontrolledDialog;
337
338
  const [formError, setFormError] = useState(null);
338
339
  const shouldLoadAccounts = Boolean(session) &&
339
340
  (settingsDialog === "account" || settingsDialog === "security");
341
+ const loadedAccountsAtom = userAccountsAtom(resolvedBaseUrl);
340
342
  const accountsAtom = shouldLoadAccounts
341
- ? userAccountsAtom(authClient)
343
+ ? loadedAccountsAtom
342
344
  : emptyAccountsAtom;
343
345
  const accountsResult = useAtomValue(accountsAtom);
344
- const refreshAccounts = useAtomRefresh(accountsAtom);
345
- 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;
346
365
  const accountCache = {
347
366
  accounts: AsyncResult.match(accountsResult, {
348
367
  onInitial: () => null,
@@ -357,7 +376,7 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
357
376
  reload: async () => refreshAccounts(),
358
377
  };
359
378
  const setSettingsDialog = (next) => {
360
- const nextDialog = typeof next === "function" ? next(settingsDialog) : next;
379
+ const nextDialog = Predicate.isFunction(next) ? next(settingsDialog) : next;
361
380
  if (nextDialog === settingsDialog)
362
381
  return;
363
382
  if (controlledDialog === undefined)
@@ -369,70 +388,54 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
369
388
  }
370
389
  const displayName = session.user.name.trim();
371
390
  const displayEmail = session.user.email.trim();
372
- const displayImage = assetUrl(session.user.image, baseUrl);
391
+ const displayImage = assetUrl(session.user.image, resolvedBaseUrl);
373
392
  const isImpersonating = Boolean(session.session.impersonatedBy);
374
393
  const isOrganizationImpersonating = Boolean(session.session.impersonatedByOrganizationId);
375
394
  const canManageUserSettings = !isOrganizationImpersonating;
376
395
  const canUseAdminSettings = !isOrganizationImpersonating;
377
396
  const isAdmin = hasAdminRole(session.user);
378
- const signOut = async () => {
397
+ const startSignOut = () => {
379
398
  const redirectUrl = signOutRedirect.startsWith("http")
380
399
  ? signOutRedirect
381
400
  : `${import.meta.env.VITE_SITE_URL}${signOutRedirect.startsWith("/") ? signOutRedirect : `/${signOutRedirect}`}`;
382
- await authClient.signOut();
383
- await navigate({ href: redirectUrl });
384
- };
385
- const stopImpersonating = async () => {
386
- setIsStoppingImpersonation(true);
387
- try {
388
- await authClient.admin.stopImpersonating();
389
- await refetch();
390
- await navigate({ href: currentSiteHref });
391
- }
392
- finally {
393
- setIsStoppingImpersonation(false);
394
- }
401
+ signOut({ baseUrl: resolvedBaseUrl, redirectUrl });
395
402
  };
396
- const updateUser = async (values) => {
397
- setFormError(null);
398
- const imageFile = isFile(values.image) ? values.image : null;
399
- const image = imageFile
400
- ? await (async () => {
401
- const uploaded = await uploadUserImageAsset(imageFile, m, uploadUserImage);
402
- return assetPath(uploaded.url);
403
- })()
404
- : typeof values.image === "string"
405
- ? assetPath(values.image)
406
- : null;
407
- const result = await authClient.updateUser({
408
- name: values.name.trim(),
409
- image: image?.trim() ?? "",
410
- });
411
- if (isAuthErrorResult(result)) {
412
- throw new Error(result.error.message || m.user_form_update_error());
413
- }
414
- await refetch();
415
- setSettingsDialog(null);
416
- };
417
- 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) => {
418
408
  setSettingsDialog((current) => open ? "account" : current === "account" ? null : current);
419
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: {
420
410
  name: displayName ?? "",
421
411
  image: displayImage || null,
422
- }, error: formError, onSubmit: async (data) => {
423
- try {
424
- await updateUser(data);
425
- }
426
- catch (error) {
427
- setFormError(error instanceof Error
428
- ? error.message
429
- : m.user_form_update_error());
430
- }
431
- } }), _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) => {
432
435
  setSettingsDialog((current) => open ? "security" : current === "security" ? null : current);
433
- }, 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) => {
434
437
  setSettingsDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
435
- }, 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) => {
436
439
  setSettingsDialog((current) => open ? "adminUsers" : current === "adminUsers" ? null : current);
437
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) => {
438
441
  setSettingsDialog((current) => open
@@ -442,52 +445,55 @@ export const UserButton = ({ authClient: providedAuthClient, baseUrl, signOutRed
442
445
  : current);
443
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] }));
444
447
  };
445
- function ConnectedAccounts({ authClient, baseUrl, accountCache, googleEnabled, currentSiteHref, navigate, }) {
448
+ function ConnectedAccounts({ baseUrl, accountCache, googleEnabled, currentSiteHref, navigate, }) {
446
449
  const m = useUserButtonMessages();
447
450
  const [error, setError] = useState(null);
448
451
  const [isLinking, setIsLinking] = useState(false);
449
452
  const [revokingAccount, setRevokingAccount] = useState(null);
450
- const accounts = accountCache.accounts ?? [];
451
- const googleAccount = accounts.find((account) => account.providerId === "google");
452
- const requirePassword = requiresPasswordForAccountRevoke(accounts);
453
- const showGoogleAccount = googleEnabled || Boolean(googleAccount);
454
- if (accountCache.accounts && (accounts.length === 0 || !showGoogleAccount)) {
455
- return null;
456
- }
457
- const linkGoogle = async () => {
458
- if (!googleEnabled)
459
- return;
453
+ const [linkGoogleAction] = useState(() => Atom.fn((input) => Effect.gen(function* () {
460
454
  setError(null);
461
455
  setIsLinking(true);
462
- const result = await authClient.linkSocial({
463
- provider: "google",
464
- callbackURL: currentSiteHref,
456
+ const client = yield* authHttpClient(input.baseUrl);
457
+ const result = yield* client.auth.linkSocial({
458
+ payload: { provider: "google", callbackURL: input.callbackURL },
465
459
  });
466
- if (result.error) {
467
- setError(result.error.message ?? m.user_account_google_link_error());
468
- setIsLinking(false);
469
- return;
460
+ notifyAuthChange();
461
+ yield* Effect.tryPromise(() => accountCache.reload());
462
+ const redirectUrl = result.url;
463
+ if (redirectUrl) {
464
+ yield* Effect.tryPromise(() => navigate({ href: redirectUrl }));
470
465
  }
471
- if (result.data?.url) {
472
- await navigate({ href: result.data.url });
473
- return;
466
+ else {
467
+ setIsLinking(false);
474
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());
475
473
  setIsLinking(false);
476
- };
477
- const revokeAccount = async (account) => {
478
- setError(null);
479
- 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: {
480
478
  providerId: account.providerId,
481
479
  accountId: account.accountId,
482
- });
483
- if (result.error) {
484
- 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)
485
493
  return;
486
- }
487
- setRevokingAccount(null);
488
- await accountCache.reload();
494
+ linkGoogle({ baseUrl, callbackURL: currentSiteHref });
489
495
  };
490
- 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] }));
491
497
  }
492
498
  function AccountProviderRow({ icon, title, description, account, connected, connectLabel, revokeLabel, isConnecting, renderDisconnected, onConnect, onRevoke, }) {
493
499
  const m = useUserButtonMessages();
@@ -498,7 +504,7 @@ function AccountProviderRow({ icon, title, description, account, connected, conn
498
504
  function GoogleLogo() {
499
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" })] }));
500
506
  }
501
- function PasswordSettings({ authClient, baseUrl, accountCache, }) {
507
+ function PasswordSettings({ baseUrl, accountCache, }) {
502
508
  const [error, setError] = useState(null);
503
509
  const [revokingAccount, setRevokingAccount] = useState(null);
504
510
  const m = useUserButtonMessages();
@@ -506,46 +512,33 @@ function PasswordSettings({ authClient, baseUrl, accountCache, }) {
506
512
  const passwordAccount = accounts.find((account) => account.providerId === "credential");
507
513
  const hasPassword = Boolean(passwordAccount);
508
514
  const requirePassword = requiresPasswordForAccountRevoke(accounts);
509
- const revokePassword = async (account) => {
510
- setError(null);
511
- 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: {
512
517
  providerId: account.providerId,
513
518
  accountId: account.accountId,
514
- });
515
- if (result.error) {
516
- setError(result.error.message ?? m.user_account_revoke_error());
517
- return;
518
- }
519
- setRevokingAccount(null);
520
- await accountCache.reload();
521
- };
522
- 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] }));
523
524
  }
524
- function ChangePasswordForm({ authClient }) {
525
+ function ChangePasswordForm({ baseUrl }) {
525
526
  const m = useUserButtonMessages();
526
527
  const [saved, setSaved] = useState(false);
528
+ let reset = () => { };
527
529
  const [form] = useState(() => FormReact.make(changePasswordFormBuilder, {
528
530
  fields: { currentPassword: TextField, newPassword: TextField },
529
531
  mode: { validation: "onSubmit" },
530
- onSubmit: (_, { decoded }) => Effect.tryPromise({
531
- try: async () => {
532
- setSaved(false);
533
- const result = await authClient.changePassword({
534
- currentPassword: decoded.currentPassword,
535
- newPassword: decoded.newPassword,
536
- });
537
- if (result.error) {
538
- throw new Error(result.error.message ?? m.user_account_password_change_error());
539
- }
540
- reset();
541
- 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,
542
536
  },
543
- catch: (cause) => cause instanceof Error
544
- ? cause
545
- : new Error(m.user_account_password_change_error()),
546
- }),
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()))),
547
540
  }));
548
- const reset = useAtomSet(form.reset);
541
+ reset = useAtomSet(form.reset);
549
542
  const submit = useAtomSet(form.submit);
550
543
  const submitResult = useAtomValue(form.submit);
551
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) => {
@@ -554,29 +547,19 @@ function ChangePasswordForm({ authClient }) {
554
547
  submit();
555
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() })] }) }));
556
549
  }
557
- function SetPasswordForm({ authClient, onSaved, }) {
550
+ function SetPasswordForm({ baseUrl, onSaved, }) {
558
551
  const m = useUserButtonMessages();
552
+ let reset = () => { };
559
553
  const [form] = useState(() => FormReact.make(passwordFormBuilder(true), {
560
554
  fields: { password: TextField },
561
555
  mode: { validation: "onSubmit" },
562
- onSubmit: (_, { decoded }) => Effect.tryPromise({
563
- try: async () => {
564
- const result = await authClient.$fetch("/set-password", {
565
- method: "POST",
566
- body: { newPassword: decoded.password },
567
- });
568
- if (result.error) {
569
- throw new Error(result.error.message ?? m.user_account_password_set_error());
570
- }
571
- reset();
572
- await onSaved();
573
- },
574
- catch: (cause) => cause instanceof Error
575
- ? cause
576
- : new Error(m.user_account_password_set_error()),
577
- }),
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()))),
578
561
  }));
579
- const reset = useAtomSet(form.reset);
562
+ reset = useAtomSet(form.reset);
580
563
  const submit = useAtomSet(form.submit);
581
564
  const submitResult = useAtomValue(form.submit);
582
565
  return (_jsx(form.Initialize, { defaultValues: { password: "" }, children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-sm", onSubmit: (event) => {
@@ -587,23 +570,20 @@ function SetPasswordForm({ authClient, onSaved, }) {
587
570
  }
588
571
  function RevokeAccountForm({ baseUrl, account, requirePassword, onCancel, onRevoke, }) {
589
572
  const m = useUserButtonMessages();
590
- const verifyPassword = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "verifyPassword"), { mode: "promise" });
591
573
  const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
592
574
  fields: { password: TextField },
593
575
  mode: { validation: "onSubmit" },
594
- onSubmit: (_, { decoded }) => Effect.tryPromise({
595
- try: async () => {
596
- if (requirePassword) {
597
- await verifyPassword({
598
- payload: { password: decoded.password },
599
- });
600
- }
601
- await onRevoke(account);
602
- },
603
- catch: (cause) => cause instanceof Error
604
- ? cause
605
- : new Error(m.user_account_password_verify_error()),
606
- }),
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()))),
607
587
  }));
608
588
  const submit = useAtomSet(form.submit);
609
589
  const submitResult = useAtomValue(form.submit);
@@ -627,12 +607,9 @@ const UserForm = ({ defaultValues, error, onSubmit, }) => {
627
607
  const [form] = useState(() => FormReact.make(userFormBuilder, {
628
608
  fields: { name: TextField, image: ImageField },
629
609
  mode: { validation: "onSubmit" },
630
- onSubmit: (_, { decoded }) => Effect.tryPromise({
631
- try: () => onSubmit({ ...decoded, image: decoded.image ?? null }),
632
- catch: (cause) => cause instanceof Error
633
- ? cause
634
- : new Error(m.user_form_update_error()),
635
- }),
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()))),
636
613
  }));
637
614
  const submit = useAtomSet(form.submit);
638
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) => {
@@ -646,12 +623,19 @@ const UserForm = ({ defaultValues, error, onSubmit, }) => {
646
623
  suggestedHeight: 512,
647
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 })] }) })] }));
648
625
  };
649
- function AccountSecuritySettings({ authClient, accountCache, }) {
626
+ function AccountSecuritySettings({ baseUrl, accountCache, }) {
650
627
  const m = useUserButtonMessages();
651
- 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
+ });
652
636
  const [setup, setSetup] = useState(null);
653
637
  const [message, setMessage] = useState(null);
654
- const twoFactorEnabled = hasTwoFactorEnabled(session.data?.user);
638
+ const twoFactorEnabled = hasTwoFactorEnabled(session?.user);
655
639
  const requirePassword = accountCache.accounts
656
640
  ? accountCache.accounts.some((account) => account.providerId === "credential")
657
641
  : null;
@@ -659,35 +643,28 @@ function AccountSecuritySettings({ authClient, accountCache, }) {
659
643
  ? m.user_two_factor_enabled()
660
644
  : m.user_two_factor_disabled() })] }), requirePassword === null ? (_jsx("p", { className: accountCache.error
661
645
  ? "text-destructive text-sm"
662
- : "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 () => {
663
647
  setMessage(m.user_two_factor_disabled_message());
664
- await session.refetch();
665
- } })) : setup ? (_jsx(VerifyTotpSetup, { authClient: authClient, setup: setup, onVerified: async () => {
648
+ await refreshSession();
649
+ } })) : setup ? (_jsx(VerifyTotpSetup, { baseUrl: baseUrl, setup: setup, onVerified: async () => {
666
650
  setSetup(null);
667
651
  setMessage(m.user_two_factor_enabled_message());
668
- await session.refetch();
669
- } })) : (_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] }));
670
654
  }
671
- function EnableTotpForm({ authClient, requirePassword, onEnabled, }) {
655
+ function EnableTotpForm({ baseUrl, requirePassword, onEnabled, }) {
672
656
  const m = useUserButtonMessages();
673
657
  const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
674
658
  fields: { password: TextField },
675
659
  mode: { validation: "onSubmit" },
676
- onSubmit: (_, { decoded }) => Effect.tryPromise({
677
- try: async () => {
678
- const result = await authClient.twoFactor.enable(requirePassword ? { password: decoded.password } : {});
679
- if (result.error || !result.data) {
680
- throw new Error(result.error?.message ?? m.user_two_factor_enable_error());
681
- }
682
- onEnabled({
683
- totpURI: result.data.totpURI,
684
- backupCodes: result.data.backupCodes,
685
- });
686
- },
687
- catch: (cause) => cause instanceof Error
688
- ? cause
689
- : new Error(m.user_two_factor_enable_error()),
690
- }),
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()))),
691
668
  }));
692
669
  const submit = useAtomSet(form.submit);
693
670
  const submitResult = useAtomValue(form.submit);
@@ -697,25 +674,16 @@ function EnableTotpForm({ authClient, requirePassword, onEnabled, }) {
697
674
  submit();
698
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()] }))] }) }));
699
676
  }
700
- function VerifyTotpSetup({ authClient, setup, onVerified, }) {
677
+ function VerifyTotpSetup({ baseUrl, setup, onVerified, }) {
701
678
  const m = useUserButtonMessages();
702
679
  const [form] = useState(() => FormReact.make(totpCodeFormBuilder, {
703
680
  fields: { code: TextField },
704
681
  mode: { validation: "onSubmit" },
705
- onSubmit: (_, { decoded }) => Effect.tryPromise({
706
- try: async () => {
707
- const result = await authClient.twoFactor.verifyTotp({
708
- code: decoded.code.trim(),
709
- });
710
- if (result.error) {
711
- throw new Error(result.error.message ?? m.user_two_factor_verify_error());
712
- }
713
- await onVerified();
714
- },
715
- catch: (cause) => cause instanceof Error
716
- ? cause
717
- : new Error(m.user_two_factor_verify_error()),
718
- }),
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()))),
719
687
  }));
720
688
  const submit = useAtomSet(form.submit);
721
689
  const submitResult = useAtomValue(form.submit);
@@ -725,23 +693,16 @@ function VerifyTotpSetup({ authClient, setup, onVerified, }) {
725
693
  submit();
726
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 })] }) })] }));
727
695
  }
728
- function DisableTotpForm({ authClient, requirePassword, onDisabled, }) {
696
+ function DisableTotpForm({ baseUrl, requirePassword, onDisabled, }) {
729
697
  const m = useUserButtonMessages();
730
698
  const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
731
699
  fields: { password: TextField },
732
700
  mode: { validation: "onSubmit" },
733
- onSubmit: (_, { decoded }) => Effect.tryPromise({
734
- try: async () => {
735
- const result = await authClient.twoFactor.disable(requirePassword ? { password: decoded.password } : {});
736
- if (result.error) {
737
- throw new Error(result.error.message ?? m.user_two_factor_disable_error());
738
- }
739
- await onDisabled();
740
- },
741
- catch: (cause) => cause instanceof Error
742
- ? cause
743
- : new Error(m.user_two_factor_disable_error()),
744
- }),
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()))),
745
706
  }));
746
707
  const submit = useAtomSet(form.submit);
747
708
  const submitResult = useAtomValue(form.submit);
@@ -751,12 +712,15 @@ function DisableTotpForm({ authClient, requirePassword, onDisabled, }) {
751
712
  submit();
752
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] }))] }) }));
753
714
  }
754
- function ApiKeyManager({ authClient, active, permissionLabels, permissions = {}, }) {
715
+ function ApiKeyManager({ baseUrl, active, permissionLabels, permissions = {}, }) {
755
716
  const m = useUserButtonMessages();
756
717
  const hasOpened = useOpenedOnce(active);
757
- const keysAtom = hasOpened ? userApiKeysAtom(authClient) : emptyApiKeysAtom;
718
+ const loadedKeysAtom = userApiKeysAtom(baseUrl);
719
+ const keysAtom = hasOpened ? loadedKeysAtom : emptyApiKeysAtom;
758
720
  const keysResult = useAtomValue(keysAtom);
759
- const refreshKeys = useAtomRefresh(keysAtom);
721
+ const refreshLoadedKeys = useAtomRefresh(loadedKeysAtom);
722
+ const refreshEmptyKeys = useAtomRefresh(emptyApiKeysAtom);
723
+ const refreshKeys = hasOpened ? refreshLoadedKeys : refreshEmptyKeys;
760
724
  const [createdKey, setCreatedKey] = useState(null);
761
725
  const [creating, setCreating] = useState(false);
762
726
  const [editingKey, setEditingKey] = useState(null);
@@ -781,24 +745,29 @@ function ApiKeyManager({ authClient, active, permissionLabels, permissions = {},
781
745
  const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
782
746
  fields: { name: TextField, referrers: TextAreaField },
783
747
  mode: { validation: "onSubmit" },
784
- onSubmit: (_, { decoded }) => Effect.tryPromise({
785
- try: async () => {
786
- setCreatedKey(null);
787
- 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: {
788
757
  configId: "user",
789
758
  name: decoded.name.trim(),
790
759
  permissions: getSelectedPermissionObject(permissionOptionsRef.current, selectedPermissionsRef.current),
791
- referrers: parseApiKeyReferrers(decoded.referrers, m.user_api_key_referrers_error()),
792
- }, m.user_api_key_create_error());
793
- setCreatedKey(created.key);
794
- resetCreateForm();
795
- setSelectedPermissions({});
796
- refreshKeys();
797
- },
798
- catch: (cause) => cause instanceof Error
799
- ? cause
800
- : new Error(m.user_api_key_create_error()),
801
- }),
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()))),
802
771
  }));
803
772
  const resetCreateForm = useAtomSet(createForm.reset);
804
773
  const submitCreateForm = useAtomSet(createForm.submit);
@@ -806,17 +775,12 @@ function ApiKeyManager({ authClient, active, permissionLabels, permissions = {},
806
775
  const togglePermission = (id, checked) => {
807
776
  setSelectedPermissions((current) => ({ ...current, [id]: checked }));
808
777
  };
809
- const deleteKey = async (key) => {
810
- const result = await authClient.apiKey.delete({
811
- configId: "user",
812
- keyId: key.id,
813
- });
814
- if (result.error) {
815
- setError(result.error.message ?? m.user_api_key_delete_error());
816
- return;
817
- }
818
- refreshKeys();
819
- };
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);
820
784
  return (_jsxs(_Fragment, { children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: editingKey
821
785
  ? m.user_api_key_edit_title()
822
786
  : createdKey
@@ -856,7 +820,7 @@ function ApiKeyManager({ authClient, active, permissionLabels, permissions = {},
856
820
  }, searchState: "local", state: {
857
821
  empty: loading ? m.user_loading() : m.table_empty(),
858
822
  loading,
859
- } }) })) : 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: {
860
824
  enabled: m.user_api_key_enabled(),
861
825
  name: m.user_api_key_name(),
862
826
  referrers: m.user_api_key_referrers(),
@@ -931,10 +895,8 @@ const apiKeyRowActions = ({ m, onDelete, onEdit, }) => [
931
895
  },
932
896
  ];
933
897
  const getPermissionId = (resource, action) => `${resource}:${action}`;
934
- const isPermissionRecord = (permissions) => typeof permissions === "object" &&
935
- permissions !== null &&
936
- Object.values(permissions).every((actions) => Array.isArray(actions) &&
937
- actions.every((action) => typeof action === "string"));
898
+ const PermissionRecord = Schema.Record(Schema.String, Schema.Array(Schema.String));
899
+ const isPermissionRecord = Schema.is(PermissionRecord);
938
900
  const formatPermissions = (permissions) => {
939
901
  if (!isPermissionRecord(permissions))
940
902
  return [];
@@ -957,17 +919,5 @@ const getSelectedPermissionObject = (options, selected) => {
957
919
  }
958
920
  return permissions;
959
921
  };
960
- const hasTwoFactorEnabled = (user) => {
961
- if (typeof user !== "object" ||
962
- user === null ||
963
- !("twoFactorEnabled" in user))
964
- return false;
965
- return user.twoFactorEnabled === true;
966
- };
967
- const isAuthErrorResult = (result) => {
968
- return (typeof result === "object" &&
969
- result !== null &&
970
- "error" in result &&
971
- typeof result.error === "object" &&
972
- result.error !== null);
973
- };
922
+ const TwoFactorUser = Schema.Struct({ twoFactorEnabled: Schema.Boolean });
923
+ const hasTwoFactorEnabled = (user) => Option.exists(Schema.decodeUnknownOption(TwoFactorUser)(user), (decoded) => decoded.twoFactorEnabled);