@krak-stack/auth 0.1.51 → 0.1.53

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.
@@ -1,15 +1,16 @@
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
+ import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
3
4
  import {} from "@tanstack/react-table";
4
5
  import { useNavigate, useRouterState, } from "@tanstack/react-router";
5
6
  import { Effect, Schema } from "effect";
6
7
  import { AsyncResult, Atom } from "effect/unstable/reactivity";
7
- import { Check, Copy, Building2, KeyRound, LogOutIcon, ShieldCheck, StopCircle, Trash2, UserCircleIcon, Users, UserIcon, } from "lucide-react";
8
+ import { Check, Copy, Building2, KeyRound, Loader2, LogOutIcon, ShieldCheck, StopCircle, Trash2, UserCircleIcon, Users, UserIcon, } from "lucide-react";
8
9
  import { QRCode } from "react-qr-code";
9
- import { createContext, useContext, useState, } from "react";
10
+ import { createContext, useContext, useRef, useState, } from "react";
10
11
  import { DataTable } from "@/components/ui/data-table";
11
12
  import { AppBrand } from "@/components/ui/app-brand";
12
- import { useAppForm } from "@/components/ui/form";
13
+ import { effectFormMessages, ImageField, SubmitButton, SubmitError, TextField, } from "@/components/ui/effect-form";
13
14
  import { Badge } from "@/components/ui/badge";
14
15
  import { Button } from "@/components/ui/button";
15
16
  import { Checkbox } from "@/components/ui/checkbox";
@@ -228,6 +229,15 @@ const hasAdminRole = (user) => typeof user === "object" &&
228
229
  user !== null &&
229
230
  "role" in user &&
230
231
  hasRole(user.role, ["admin"]);
232
+ const changePasswordFormBuilder = FormBuilder.empty
233
+ .addField("currentPassword", Schema.NonEmptyString)
234
+ .addField("newPassword", Schema.NonEmptyString);
235
+ const passwordFormBuilder = (required) => FormBuilder.empty.addField("password", required ? Schema.NonEmptyString : Schema.String);
236
+ const userFormBuilder = FormBuilder.empty
237
+ .addField("name", Schema.NonEmptyString)
238
+ .addField("image", Schema.UndefinedOr(Schema.NullOr(Schema.Union([Schema.String, Schema.instanceOf(File)]))));
239
+ const totpCodeFormBuilder = FormBuilder.empty.addField("code", Schema.NonEmptyString);
240
+ const apiKeyFormBuilder = FormBuilder.empty.addField("name", Schema.NonEmptyString);
231
241
  const isFile = (value) => value instanceof File;
232
242
  const decodeUploadedAsset = Schema.decodeUnknownPromise(ExtraUploadedAsset);
233
243
  const uploadUserImageAsset = async (file, m, uploadUserImage) => {
@@ -472,96 +482,96 @@ function PasswordSettings({ authClient, baseUrl, accountCache, }) {
472
482
  function ChangePasswordForm({ authClient }) {
473
483
  const m = useUserButtonMessages();
474
484
  const [saved, setSaved] = useState(false);
475
- const form = useAppForm({
476
- defaultValues: { currentPassword: "", newPassword: "" },
477
- onSubmit: async ({ value, formApi }) => {
478
- setSaved(false);
479
- formApi.setErrorMap({ onSubmit: undefined });
480
- const result = await authClient.changePassword({
481
- currentPassword: value.currentPassword,
482
- newPassword: value.newPassword,
483
- });
484
- if (result.error) {
485
- formApi.setErrorMap({
486
- onSubmit: {
487
- form: result.error.message ?? m.user_account_password_change_error(),
488
- fields: {},
489
- },
485
+ const [form] = useState(() => FormReact.make(changePasswordFormBuilder, {
486
+ fields: { currentPassword: TextField, newPassword: TextField },
487
+ mode: { validation: "onSubmit" },
488
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
489
+ try: async () => {
490
+ setSaved(false);
491
+ const result = await authClient.changePassword({
492
+ currentPassword: decoded.currentPassword,
493
+ newPassword: decoded.newPassword,
490
494
  });
491
- return;
492
- }
493
- form.reset();
494
- setSaved(true);
495
- },
496
- });
497
- return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-md", onSubmit: (event) => {
495
+ if (result.error) {
496
+ throw new Error(result.error.message ?? m.user_account_password_change_error());
497
+ }
498
+ reset();
499
+ setSaved(true);
500
+ },
501
+ catch: (cause) => cause instanceof Error
502
+ ? cause
503
+ : new Error(m.user_account_password_change_error()),
504
+ }),
505
+ }));
506
+ const reset = useAtomSet(form.reset);
507
+ const submit = useAtomSet(form.submit);
508
+ const submitResult = useAtomValue(form.submit);
509
+ return (_jsx(form.Initialize, { defaultValues: { currentPassword: "", newPassword: "" }, children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-md", onSubmit: (event) => {
498
510
  event.preventDefault();
499
511
  event.stopPropagation();
500
- form.handleSubmit();
501
- }, 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.AppField, { name: "currentPassword", children: (field) => (_jsx(field.TextField, { label: m.user_account_current_password(), type: "password", autoComplete: "current-password", required: true })) }), _jsx(form.AppField, { name: "newPassword", children: (field) => (_jsx(field.TextField, { label: m.user_account_new_password(), type: "password", autoComplete: "new-password", required: true })) }), _jsx(form.FormError, {}), saved ? (_jsx("p", { className: "text-sm text-green-600", children: m.user_account_password_change_success() })) : null, _jsx(Button, { type: "submit", className: "self-start", children: m.user_account_password_change_submit() })] }) }));
512
+ submit();
513
+ }, 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() })] }) }));
502
514
  }
503
515
  function SetPasswordForm({ authClient, onSaved, }) {
504
516
  const m = useUserButtonMessages();
505
- const form = useAppForm({
506
- defaultValues: { password: "" },
507
- onSubmit: async ({ value, formApi }) => {
508
- formApi.setErrorMap({ onSubmit: undefined });
509
- const result = await authClient.$fetch("/set-password", {
510
- method: "POST",
511
- body: { newPassword: value.password },
512
- });
513
- if (result.error) {
514
- formApi.setErrorMap({
515
- onSubmit: {
516
- form: result.error.message ?? m.user_account_password_set_error(),
517
- fields: {},
518
- },
517
+ const [form] = useState(() => FormReact.make(passwordFormBuilder(true), {
518
+ fields: { password: TextField },
519
+ mode: { validation: "onSubmit" },
520
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
521
+ try: async () => {
522
+ const result = await authClient.$fetch("/set-password", {
523
+ method: "POST",
524
+ body: { newPassword: decoded.password },
519
525
  });
520
- return;
521
- }
522
- form.reset();
523
- await onSaved();
524
- },
525
- });
526
- return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-sm", onSubmit: (event) => {
526
+ if (result.error) {
527
+ throw new Error(result.error.message ?? m.user_account_password_set_error());
528
+ }
529
+ reset();
530
+ await onSaved();
531
+ },
532
+ catch: (cause) => cause instanceof Error
533
+ ? cause
534
+ : new Error(m.user_account_password_set_error()),
535
+ }),
536
+ }));
537
+ const reset = useAtomSet(form.reset);
538
+ const submit = useAtomSet(form.submit);
539
+ const submitResult = useAtomValue(form.submit);
540
+ return (_jsx(form.Initialize, { defaultValues: { password: "" }, children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-sm", onSubmit: (event) => {
527
541
  event.preventDefault();
528
542
  event.stopPropagation();
529
- form.handleSubmit();
530
- }, children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_account_new_password(), type: "password", autoComplete: "new-password", required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, { children: m.user_account_password_set() })] }) }));
543
+ submit();
544
+ }, children: [_jsx(form.password, { label: m.user_account_new_password(), type: "password", autoComplete: "new-password", required: true }), _jsx(SubmitError, { result: submitResult }), _jsx(SubmitButton, { form: form, children: m.user_account_password_set() })] }) }));
531
545
  }
532
546
  function RevokeAccountForm({ baseUrl, account, requirePassword, onCancel, onRevoke, }) {
533
547
  const m = useUserButtonMessages();
534
548
  const verifyPassword = useAtomSet(authClientApi(baseUrl).mutation("authExtra", "verifyPassword"), { mode: "promise" });
535
- const form = useAppForm({
536
- defaultValues: { password: "" },
537
- onSubmit: async ({ value, formApi }) => {
538
- formApi.setErrorMap({ onSubmit: undefined });
539
- if (requirePassword) {
540
- try {
541
- await verifyPassword({ payload: { password: value.password } });
542
- }
543
- catch (error) {
544
- formApi.setErrorMap({
545
- onSubmit: {
546
- form: error instanceof Error
547
- ? error.message
548
- : m.user_account_password_verify_error(),
549
- fields: {},
550
- },
549
+ const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
550
+ fields: { password: TextField },
551
+ mode: { validation: "onSubmit" },
552
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
553
+ try: async () => {
554
+ if (requirePassword) {
555
+ await verifyPassword({
556
+ payload: { password: decoded.password },
551
557
  });
552
- return;
553
558
  }
554
- }
555
- await onRevoke(account);
556
- },
557
- });
558
- return (_jsx(form.AppForm, { children: _jsxs("form", { className: "bg-muted/40 flex flex-col gap-3 rounded-lg border p-4", onSubmit: (event) => {
559
+ await onRevoke(account);
560
+ },
561
+ catch: (cause) => cause instanceof Error
562
+ ? cause
563
+ : new Error(m.user_account_password_verify_error()),
564
+ }),
565
+ }));
566
+ const submit = useAtomSet(form.submit);
567
+ const submitResult = useAtomValue(form.submit);
568
+ return (_jsx(form.Initialize, { defaultValues: { password: "" }, children: _jsxs("form", { className: "bg-muted/40 flex flex-col gap-3 rounded-lg border p-4", onSubmit: (event) => {
559
569
  event.preventDefault();
560
570
  event.stopPropagation();
561
- form.handleSubmit();
571
+ submit();
562
572
  }, children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("h3", { className: "text-sm font-medium", children: m.user_account_revoke() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_revoke_description({
563
573
  provider: providerName(account.providerId, m),
564
- }) })] }), requirePassword ? (_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) })) : null, _jsx(form.FormError, {}), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx(Button, { type: "button", variant: "outline", onClick: onCancel, children: m.user_account_cancel() }), _jsx(Button, { type: "submit", children: m.user_account_confirm_revoke() })] })] }) }));
574
+ }) })] }), requirePassword ? (_jsx(form.password, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) : null, _jsx(SubmitError, { result: submitResult }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx(Button, { type: "button", variant: "outline", onClick: onCancel, children: m.user_account_cancel() }), requirePassword ? (_jsx(SubmitButton, { form: form, children: m.user_account_confirm_revoke() })) : (_jsxs(Button, { type: "button", disabled: submitResult.waiting, onClick: () => submit(), children: [submitResult.waiting ? (_jsx(Loader2, { "data-icon": "inline-start", className: "animate-spin" })) : null, m.user_account_confirm_revoke()] }))] })] }) }));
565
575
  }
566
576
  const providerName = (providerId, m) => {
567
577
  if (providerId === "google")
@@ -572,20 +582,27 @@ const providerName = (providerId, m) => {
572
582
  };
573
583
  const UserForm = ({ defaultValues, error, onSubmit, }) => {
574
584
  const m = useUserButtonMessages();
575
- const form = useAppForm({
576
- defaultValues,
577
- onSubmit: ({ value }) => onSubmit(value),
578
- });
579
- 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", { className: "flex flex-col gap-4", onSubmit: (event) => {
580
- event.preventDefault();
581
- event.stopPropagation();
582
- form.handleSubmit();
583
- }, children: _jsxs(form.AppForm, { children: [_jsx(form.AppField, { name: "image", children: (field) => (_jsx(field.ImageField, { label: m.user_profile_photo_upload_label(), size: {
584
- width: 96,
585
- height: 96,
586
- suggestedWidth: 512,
587
- suggestedHeight: 512,
588
- } })) }), _jsx(form.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.user_form_name_label(), autoComplete: "name", required: true })) }), error && (_jsx("p", { role: "alert", className: "text-destructive text-sm", children: error })), _jsx(form.SubmitButton, {})] }) })] }));
585
+ const [form] = useState(() => FormReact.make(userFormBuilder, {
586
+ fields: { name: TextField, image: ImageField },
587
+ mode: { validation: "onSubmit" },
588
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
589
+ try: () => onSubmit({ ...decoded, image: decoded.image ?? null }),
590
+ catch: (cause) => cause instanceof Error
591
+ ? cause
592
+ : new Error(m.user_form_update_error()),
593
+ }),
594
+ }));
595
+ const submit = useAtomSet(form.submit);
596
+ 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) => {
597
+ event.preventDefault();
598
+ event.stopPropagation();
599
+ submit();
600
+ }, children: [_jsx(form.image, { label: m.user_profile_photo_upload_label(), size: {
601
+ width: 96,
602
+ height: 96,
603
+ suggestedWidth: 512,
604
+ suggestedHeight: 512,
605
+ } }), _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 })] }) })] }));
589
606
  };
590
607
  function AccountSecuritySettings({ authClient, accountCache, }) {
591
608
  const m = useUserButtonMessages();
@@ -611,83 +628,86 @@ function AccountSecuritySettings({ authClient, accountCache, }) {
611
628
  }
612
629
  function EnableTotpForm({ authClient, requirePassword, onEnabled, }) {
613
630
  const m = useUserButtonMessages();
614
- const form = useAppForm({
615
- defaultValues: { password: "" },
616
- onSubmit: async ({ value, formApi }) => {
617
- formApi.setErrorMap({ onSubmit: undefined });
618
- const result = await authClient.twoFactor.enable(requirePassword ? { password: value.password } : {});
619
- if (result.error || !result.data) {
620
- formApi.setErrorMap({
621
- onSubmit: {
622
- form: result.error?.message ?? m.user_two_factor_enable_error(),
623
- fields: {},
624
- },
631
+ const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
632
+ fields: { password: TextField },
633
+ mode: { validation: "onSubmit" },
634
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
635
+ try: async () => {
636
+ const result = await authClient.twoFactor.enable(requirePassword ? { password: decoded.password } : {});
637
+ if (result.error || !result.data) {
638
+ throw new Error(result.error?.message ?? m.user_two_factor_enable_error());
639
+ }
640
+ onEnabled({
641
+ totpURI: result.data.totpURI,
642
+ backupCodes: result.data.backupCodes,
625
643
  });
626
- return;
627
- }
628
- onEnabled({
629
- totpURI: result.data.totpURI,
630
- backupCodes: result.data.backupCodes,
631
- });
632
- },
633
- });
634
- return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-md flex-col gap-4", onSubmit: (event) => {
644
+ },
645
+ catch: (cause) => cause instanceof Error
646
+ ? cause
647
+ : new Error(m.user_two_factor_enable_error()),
648
+ }),
649
+ }));
650
+ const submit = useAtomSet(form.submit);
651
+ const submitResult = useAtomValue(form.submit);
652
+ return (_jsx(form.Initialize, { defaultValues: { password: "" }, children: _jsxs("form", { className: "flex max-w-md flex-col gap-4", onSubmit: (event) => {
635
653
  event.preventDefault();
636
654
  event.stopPropagation();
637
- form.handleSubmit();
638
- }, children: [requirePassword ? (_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) })) : null, _jsx(form.FormError, {}), _jsx(form.SubmitButton, { children: m.user_two_factor_enable_submit() })] }) }));
655
+ submit();
656
+ }, 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()] }))] }) }));
639
657
  }
640
658
  function VerifyTotpSetup({ authClient, setup, onVerified, }) {
641
659
  const m = useUserButtonMessages();
642
- const form = useAppForm({
643
- defaultValues: { code: "" },
644
- onSubmit: async ({ value, formApi }) => {
645
- formApi.setErrorMap({ onSubmit: undefined });
646
- const result = await authClient.twoFactor.verifyTotp({
647
- code: value.code.trim(),
648
- });
649
- if (result.error) {
650
- formApi.setErrorMap({
651
- onSubmit: {
652
- form: result.error.message ?? m.user_two_factor_verify_error(),
653
- fields: {},
654
- },
660
+ const [form] = useState(() => FormReact.make(totpCodeFormBuilder, {
661
+ fields: { code: TextField },
662
+ mode: { validation: "onSubmit" },
663
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
664
+ try: async () => {
665
+ const result = await authClient.twoFactor.verifyTotp({
666
+ code: decoded.code.trim(),
655
667
  });
656
- return;
657
- }
658
- await onVerified();
659
- },
660
- });
661
- return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsxs("div", { className: "flex flex-col items-center gap-4 rounded-lg border p-4 text-center sm:p-6", children: [_jsx("div", { className: "rounded-xl border bg-white p-3", children: _jsx(QRCode, { value: setup.totpURI, title: m.user_two_factor_scan_title(), className: "size-44 max-w-full" }) }), _jsx("p", { className: "text-muted-foreground max-w-md text-sm", children: m.user_two_factor_scan_description() })] }), _jsxs("div", { className: "flex flex-col gap-3 rounded-lg border p-4", children: [_jsx("div", { className: "bg-muted/40 grid gap-2 rounded-md p-3 font-mono text-sm sm:grid-cols-2", children: setup.backupCodes.map((code) => (_jsx("span", { children: code }, code))) }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_two_factor_backup_codes_warning() })] }), _jsx(form.AppForm, { children: _jsxs("form", { className: "flex w-full max-w-sm flex-col gap-4", onSubmit: (event) => {
668
+ if (result.error) {
669
+ throw new Error(result.error.message ?? m.user_two_factor_verify_error());
670
+ }
671
+ await onVerified();
672
+ },
673
+ catch: (cause) => cause instanceof Error
674
+ ? cause
675
+ : new Error(m.user_two_factor_verify_error()),
676
+ }),
677
+ }));
678
+ const submit = useAtomSet(form.submit);
679
+ const submitResult = useAtomValue(form.submit);
680
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsxs("div", { className: "flex flex-col items-center gap-4 rounded-lg border p-4 text-center sm:p-6", children: [_jsx("div", { className: "rounded-xl border bg-white p-3", children: _jsx(QRCode, { value: setup.totpURI, title: m.user_two_factor_scan_title(), className: "size-44 max-w-full" }) }), _jsx("p", { className: "text-muted-foreground max-w-md text-sm", children: m.user_two_factor_scan_description() })] }), _jsxs("div", { className: "flex flex-col gap-3 rounded-lg border p-4", children: [_jsx("div", { className: "bg-muted/40 grid gap-2 rounded-md p-3 font-mono text-sm sm:grid-cols-2", children: setup.backupCodes.map((code) => (_jsx("span", { children: code }, code))) }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_two_factor_backup_codes_warning() })] }), _jsx(form.Initialize, { defaultValues: { code: "" }, children: _jsxs("form", { className: "flex w-full max-w-sm flex-col gap-4", onSubmit: (event) => {
662
681
  event.preventDefault();
663
682
  event.stopPropagation();
664
- form.handleSubmit();
665
- }, children: [_jsx(form.AppField, { name: "code", children: (field) => (_jsx(field.TextField, { label: m.user_two_factor_code(), autoComplete: "one-time-code", inputMode: "numeric", required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) })] }));
683
+ submit();
684
+ }, 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 })] }) })] }));
666
685
  }
667
686
  function DisableTotpForm({ authClient, requirePassword, onDisabled, }) {
668
687
  const m = useUserButtonMessages();
669
- const form = useAppForm({
670
- defaultValues: { password: "" },
671
- onSubmit: async ({ value, formApi }) => {
672
- formApi.setErrorMap({ onSubmit: undefined });
673
- const result = await authClient.twoFactor.disable(requirePassword ? { password: value.password } : {});
674
- if (result.error) {
675
- formApi.setErrorMap({
676
- onSubmit: {
677
- form: result.error.message ?? m.user_two_factor_disable_error(),
678
- fields: {},
679
- },
680
- });
681
- return;
682
- }
683
- await onDisabled();
684
- },
685
- });
686
- return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-md flex-col gap-4", onSubmit: (event) => {
688
+ const [form] = useState(() => FormReact.make(passwordFormBuilder(requirePassword), {
689
+ fields: { password: TextField },
690
+ mode: { validation: "onSubmit" },
691
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
692
+ try: async () => {
693
+ const result = await authClient.twoFactor.disable(requirePassword ? { password: decoded.password } : {});
694
+ if (result.error) {
695
+ throw new Error(result.error.message ?? m.user_two_factor_disable_error());
696
+ }
697
+ await onDisabled();
698
+ },
699
+ catch: (cause) => cause instanceof Error
700
+ ? cause
701
+ : new Error(m.user_two_factor_disable_error()),
702
+ }),
703
+ }));
704
+ const submit = useAtomSet(form.submit);
705
+ const submitResult = useAtomValue(form.submit);
706
+ return (_jsx(form.Initialize, { defaultValues: { password: "" }, children: _jsxs("form", { className: "flex max-w-md flex-col gap-4", onSubmit: (event) => {
687
707
  event.preventDefault();
688
708
  event.stopPropagation();
689
- form.handleSubmit();
690
- }, children: [requirePassword ? (_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) })) : null, _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }));
709
+ submit();
710
+ }, 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] }))] }) }));
691
711
  }
692
712
  function ApiKeyManager({ authClient, active, permissions = {}, }) {
693
713
  const m = useUserButtonMessages();
@@ -711,36 +731,35 @@ function ApiKeyManager({ authClient, active, permissions = {}, }) {
711
731
  onSuccess: () => null,
712
732
  });
713
733
  const loading = keysResult._tag === "Initial";
714
- const createForm = useAppForm({
715
- defaultValues: { name: "" },
716
- onSubmit: async ({ value, formApi }) => {
717
- formApi.setErrorMap({ onSubmit: undefined });
718
- setCreatedKey(null);
719
- setCopiedKey(false);
720
- const selectedPermissionObject = getSelectedPermissionObject(permissionOptions, selectedPermissions);
721
- try {
734
+ const permissionOptionsRef = useRef(permissionOptions);
735
+ const selectedPermissionsRef = useRef(selectedPermissions);
736
+ permissionOptionsRef.current = permissionOptions;
737
+ selectedPermissionsRef.current = selectedPermissions;
738
+ const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
739
+ fields: { name: TextField },
740
+ mode: { validation: "onSubmit" },
741
+ onSubmit: (_, { decoded }) => Effect.tryPromise({
742
+ try: async () => {
743
+ setCreatedKey(null);
744
+ setCopiedKey(false);
722
745
  const created = await createApiKey({
723
746
  configId: "user",
724
- name: value.name.trim(),
725
- permissions: selectedPermissionObject,
747
+ name: decoded.name.trim(),
748
+ permissions: getSelectedPermissionObject(permissionOptionsRef.current, selectedPermissionsRef.current),
726
749
  }, m.user_api_key_create_error());
727
750
  setCreatedKey(created.key);
728
- createForm.reset();
751
+ resetCreateForm();
729
752
  setSelectedPermissions({});
730
753
  refreshKeys();
731
- }
732
- catch (cause) {
733
- formApi.setErrorMap({
734
- onSubmit: {
735
- form: cause instanceof Error
736
- ? cause.message
737
- : m.user_api_key_create_error(),
738
- fields: {},
739
- },
740
- });
741
- }
742
- },
743
- });
754
+ },
755
+ catch: (cause) => cause instanceof Error
756
+ ? cause
757
+ : new Error(m.user_api_key_create_error()),
758
+ }),
759
+ }));
760
+ const resetCreateForm = useAtomSet(createForm.reset);
761
+ const submitCreateForm = useAtomSet(createForm.submit);
762
+ const createSubmitResult = useAtomValue(createForm.submit);
744
763
  const togglePermission = (id, checked) => {
745
764
  setSelectedPermissions((current) => ({ ...current, [id]: checked }));
746
765
  };
@@ -762,11 +781,11 @@ function ApiKeyManager({ authClient, active, permissions = {}, }) {
762
781
  }
763
782
  refreshKeys();
764
783
  };
765
- return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(createForm.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
784
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(createForm.Initialize, { defaultValues: { name: "" }, children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
766
785
  event.preventDefault();
767
786
  event.stopPropagation();
768
- createForm.handleSubmit();
769
- }, children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.api_key_rate_limit_notice() }), _jsx(createForm.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.user_api_key_name(), required: true })) }), permissionOptions.length > 0 ? (_jsxs(FieldSet, { children: [_jsx(FieldLegend, { children: m.user_api_key_permissions() }), _jsx(FieldDescription, { children: m.user_api_key_permissions_description() }), _jsx(FieldGroup, { "data-slot": "checkbox-group", className: "gap-3", children: permissionOptions.map((permission) => (_jsxs(Field, { orientation: "horizontal", children: [_jsx(Checkbox, { id: permission.id, checked: selectedPermissions[permission.id] ?? false, onCheckedChange: (checked) => togglePermission(permission.id, checked) }), _jsx(FieldContent, { children: _jsx(FieldLabel, { htmlFor: permission.id, children: permission.id }) })] }, permission.id))) })] })) : null, _jsx(createForm.FormError, {}), _jsx(createForm.SubmitButton, {})] }) }), createdKey ? (_jsxs("div", { className: "flex flex-col gap-2 rounded-lg border p-4", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(KeyRound, {}), m.user_api_key_created_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_api_key_created_description() }), _jsxs("div", { className: "grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center", children: [_jsx("code", { className: "bg-muted block max-w-full overflow-x-auto rounded-md p-3 text-sm whitespace-nowrap", children: createdKey }), _jsxs(Button, { type: "button", variant: "outline", onClick: copyCreatedKey, className: "self-start sm:self-auto", children: [copiedKey ? _jsx(Check, {}) : _jsx(Copy, {}), copiedKey ? m.user_api_key_copied() : m.user_api_key_copy()] })] })] })) : null, keysError ? (_jsx("p", { className: "text-destructive text-sm", children: keysError })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsx(Separator, {}), _jsx(DataTable, { columns: apiKeyColumns({ m }), data: keys, features: {
787
+ submitCreateForm();
788
+ }, children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.api_key_rate_limit_notice() }), _jsx(createForm.name, { label: m.user_api_key_name(), required: true }), permissionOptions.length > 0 ? (_jsxs(FieldSet, { children: [_jsx(FieldLegend, { children: m.user_api_key_permissions() }), _jsx(FieldDescription, { children: m.user_api_key_permissions_description() }), _jsx(FieldGroup, { "data-slot": "checkbox-group", className: "gap-3", children: permissionOptions.map((permission) => (_jsxs(Field, { orientation: "horizontal", children: [_jsx(Checkbox, { id: permission.id, checked: selectedPermissions[permission.id] ?? false, onCheckedChange: (checked) => togglePermission(permission.id, checked) }), _jsx(FieldContent, { children: _jsx(FieldLabel, { htmlFor: permission.id, children: permission.id }) })] }, permission.id))) })] })) : null, _jsx(SubmitError, { result: createSubmitResult }), _jsx(SubmitButton, { form: createForm })] }) }), createdKey ? (_jsxs("div", { className: "flex flex-col gap-2 rounded-lg border p-4", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(KeyRound, {}), m.user_api_key_created_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_api_key_created_description() }), _jsxs("div", { className: "grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center", children: [_jsx("code", { className: "bg-muted block max-w-full overflow-x-auto rounded-md p-3 text-sm whitespace-nowrap", children: createdKey }), _jsxs(Button, { type: "button", variant: "outline", onClick: copyCreatedKey, className: "self-start sm:self-auto", children: [copiedKey ? _jsx(Check, {}) : _jsx(Copy, {}), copiedKey ? m.user_api_key_copied() : m.user_api_key_copy()] })] })] })) : null, keysError ? (_jsx("p", { className: "text-destructive text-sm", children: keysError })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsx(Separator, {}), _jsx(DataTable, { columns: apiKeyColumns({ m }), data: keys, features: {
770
789
  export: { baseName: m.user_api_keys_export_file_name() },
771
790
  gallery: false,
772
791
  rowActions: {
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { AuthClientApi, AuthServiceApi } from "./api";
5
5
  export { AuthService, type AuthServiceLayerOptions } from "./service";
6
6
  export { AuthClientConfig } from "./config";
7
7
  export { proxyAuthRequest } from "./server/proxy";
8
- export { OrganizationSwitcher, MemberRequired, KrakstackAuthProvider, ResetPassword, Signin, Signup, TwoFactor, AdminOrganizationForm, AdminOrganizationsTable, AdminUsersTable, UserButton, assetUrl, createAuthUiClient, type AuthUiClient, type MemberRequiredMessages, type MemberRequiredProps, type KrakstackAuthContextValue, type KrakstackAuthLocale, type KrakstackAuthProviderProps, type OrganizationSwitcherDialog, type OrganizationSwitcherProps, type UserButtonDialog, useAuthClient, useAdminUsersTotal, } from "./components";
8
+ export { OrganizationSwitcher, MemberRequired, KrakstackAuthProvider, ResetPassword, Signin, Signup, TwoFactor, VerifyEmail, AdminOrganizationForm, AdminOrganizationsTable, AdminUsersTable, UserButton, assetUrl, createAuthUiClient, type AuthUiClient, type MemberRequiredMessages, type MemberRequiredProps, type KrakstackAuthContextValue, type KrakstackAuthLocale, type KrakstackAuthProviderProps, type OrganizationSwitcherDialog, type OrganizationSwitcherProps, type UserButtonDialog, useAuthClient, useAdminUsersTotal, } from "./components";
9
9
  export * as BetterAuth from "./better-auth/api.group";
10
10
  export * as Extra from "./extra/api.group";
11
11
  export * as Server from "./server";
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ export { AuthClientApi, AuthServiceApi } from "./api";
5
5
  export { AuthService } from "./service";
6
6
  export { AuthClientConfig } from "./config";
7
7
  export { proxyAuthRequest } from "./server/proxy";
8
- export { OrganizationSwitcher, MemberRequired, KrakstackAuthProvider, ResetPassword, Signin, Signup, TwoFactor, AdminOrganizationForm, AdminOrganizationsTable, AdminUsersTable, UserButton, assetUrl, createAuthUiClient, useAuthClient, useAdminUsersTotal, } from "./components";
8
+ export { OrganizationSwitcher, MemberRequired, KrakstackAuthProvider, ResetPassword, Signin, Signup, TwoFactor, VerifyEmail, AdminOrganizationForm, AdminOrganizationsTable, AdminUsersTable, UserButton, assetUrl, createAuthUiClient, useAuthClient, useAdminUsersTotal, } from "./components";
9
9
  export * as BetterAuth from "./better-auth/api.group";
10
10
  export * as Extra from "./extra/api.group";
11
11
  export * as Server from "./server";
package/dist/schema.d.ts CHANGED
@@ -58,6 +58,7 @@ export declare const Organization: Schema.Struct<{
58
58
  readonly location: Schema.optional<Schema.NullOr<Schema.String>>;
59
59
  }>>;
60
60
  }>>;
61
+ readonly parentId: Schema.NullOr<Schema.String>;
61
62
  readonly createdAt: Schema.Date;
62
63
  }>;
63
64
  export declare const Member: Schema.Struct<{
package/dist/schema.js CHANGED
@@ -119,6 +119,7 @@ export const Organization = Schema.Struct({
119
119
  slug: Schema.String,
120
120
  logo: Schema.NullOr(Schema.String),
121
121
  metadata: Schema.NullOr(OrganizationMetadata),
122
+ parentId: Schema.NullOr(Schema.String),
122
123
  createdAt: Schema.Date,
123
124
  }).annotate({
124
125
  identifier: "Organization",
@@ -130,6 +131,7 @@ export const Organization = Schema.Struct({
130
131
  name: "KrakStack",
131
132
  slug: "krakstack",
132
133
  logo: null,
134
+ parentId: null,
133
135
  metadata: {
134
136
  translations: [
135
137
  {
@@ -71,8 +71,28 @@ export declare const ServerOrganizationsApiGroup: HttpApiGroup.HttpApiGroup<"org
71
71
  readonly location: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
72
72
  }>>;
73
73
  }>>;
74
+ readonly parentId: import("effect/Schema").NullOr<import("effect/Schema").String>;
74
75
  readonly createdAt: import("effect/Schema").Date;
75
- }>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.NotFound | typeof HttpApiError.InternalServerError>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"listOrganizationMembers", "GET", "/organizations/:organizationId/members", HttpApiEndpoint.StringTree<import("effect/Schema").Struct<{
76
+ }>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.NotFound | typeof HttpApiError.InternalServerError>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"getOrganizationChildren", "GET", "/organizations/:organizationId/children", HttpApiEndpoint.StringTree<import("effect/Schema").Struct<{
77
+ readonly organizationId: import("effect/Schema").NonEmptyString;
78
+ }>>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<import("effect/Schema").$Array<import("effect/Schema").Struct<{
79
+ readonly id: import("effect/Schema").String;
80
+ readonly name: import("effect/Schema").String;
81
+ readonly slug: import("effect/Schema").String;
82
+ readonly logo: import("effect/Schema").NullOr<import("effect/Schema").String>;
83
+ readonly metadata: import("effect/Schema").NullOr<import("effect/Schema").Struct<{
84
+ readonly translations: import("effect/Schema").$Array<import("effect/Schema").Struct<{
85
+ readonly locale: import("effect/Schema").Union<readonly [import("effect/Schema").Literal<"en">, import("effect/Schema").Literal<"fr">]>;
86
+ readonly name: import("effect/Schema").String;
87
+ readonly logo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
88
+ readonly icon: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
89
+ readonly contactEmail: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
90
+ readonly location: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
91
+ }>>;
92
+ }>>;
93
+ readonly parentId: import("effect/Schema").NullOr<import("effect/Schema").String>;
94
+ readonly createdAt: import("effect/Schema").Date;
95
+ }>>>, HttpApiEndpoint.Json<typeof HttpApiError.Unauthorized | typeof HttpApiError.InternalServerError>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"listOrganizationMembers", "GET", "/organizations/:organizationId/members", HttpApiEndpoint.StringTree<import("effect/Schema").Struct<{
76
96
  readonly organizationId: import("effect/Schema").NonEmptyString;
77
97
  }>>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.StringTree<never>, HttpApiEndpoint.Json<import("effect/Schema").$Array<import("effect/Schema").Struct<{
78
98
  readonly id: import("effect/Schema").String;
@@ -111,6 +131,7 @@ export declare const ServerOrganizationsApiGroup: HttpApiGroup.HttpApiGroup<"org
111
131
  readonly location: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
112
132
  }>>;
113
133
  }>>;
134
+ readonly parentId: import("effect/Schema").NullOr<import("effect/Schema").String>;
114
135
  readonly createdAt: import("effect/Schema").Date;
115
136
  }>>;
116
137
  readonly missingIds: import("effect/Schema").$Array<import("effect/Schema").String>;
@@ -1,7 +1,7 @@
1
1
  import { OpenApi } from "effect/unstable/httpapi";
2
2
  import { HttpApiEndpoint, HttpApiError, HttpApiGroup, } from "effect/unstable/httpapi";
3
3
  import { Member, Organization, User } from "../schema";
4
- import { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerIdParams, ServerIdsQuery, ServerMemberParams, ServerMembersResponse, ServerOrganizationIdParams, ServerOrganizationsQuery, ServerOrganizationsResponse, ServerUserIdParams, ServerUsersResponse, } from "./schema";
4
+ import { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerIdParams, ServerIdsQuery, ServerMemberParams, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationIdParams, ServerOrganizationsQuery, ServerOrganizationsResponse, ServerUserIdParams, ServerUsersResponse, } from "./schema";
5
5
  export const ServerUsersApiGroup = HttpApiGroup.make("users")
6
6
  .add(HttpApiEndpoint.get("listUsersByIds", "/users", {
7
7
  query: ServerIdsQuery,
@@ -64,6 +64,15 @@ export const ServerOrganizationsApiGroup = HttpApiGroup.make("organizations")
64
64
  title: "Get organization",
65
65
  summary: "Get an organization by ID",
66
66
  description: "Returns a trusted organization record by ID. Requires a service API key.",
67
+ })))
68
+ .add(HttpApiEndpoint.get("getOrganizationChildren", "/organizations/:organizationId/children", {
69
+ params: ServerOrganizationIdParams,
70
+ success: ServerOrganizationChildrenResponse,
71
+ error: [HttpApiError.Unauthorized, HttpApiError.InternalServerError],
72
+ }).annotateMerge(OpenApi.annotations({
73
+ title: "Get organization children",
74
+ summary: "Get direct child organizations",
75
+ description: "Returns direct child organizations for a parent organization. Requires a service API key.",
67
76
  })))
68
77
  .add(HttpApiEndpoint.get("getActiveMember", "/organizations/:organizationId/members/:userId", {
69
78
  params: ServerMemberParams,
@@ -5,5 +5,5 @@ export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup
5
5
  export { proxyAuthRequest } from "./proxy";
6
6
  export { ApiKeySecurity, AuthMiddleware, makeAuthenticationLive, } from "./middleware";
7
7
  export type { AuthenticationLiveOptions } from "./middleware";
8
- export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema";
8
+ export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema";
9
9
  export type { Member, Organization, OrganizationMetadata, User, } from "../schema";