@krak-stack/auth 0.2.32 → 0.3.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 (53) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +101 -5
  3. package/dist/access.d.ts +3 -1
  4. package/dist/admin/api.group.d.ts +41 -41
  5. package/dist/admin/schema.d.ts +23 -23
  6. package/dist/admin/schema.js +21 -19
  7. package/dist/api.d.ts +1313 -1313
  8. package/dist/auth/api.group.d.ts +18 -18
  9. package/dist/auth/schema.d.ts +49 -33
  10. package/dist/auth/schema.js +18 -18
  11. package/dist/components/admin-organization-form.js +2 -2
  12. package/dist/components/admin-organizations.js +6 -5
  13. package/dist/components/admin-users.js +6 -6
  14. package/dist/components/api-key-edit-form.js +19 -11
  15. package/dist/components/associated-projects-notice.d.ts +2 -1
  16. package/dist/components/associated-projects-notice.js +6 -2
  17. package/dist/components/auth-atoms.js +1 -2
  18. package/dist/components/auth-client-api.d.ts +61 -61
  19. package/dist/components/auth-forms.d.ts +1 -0
  20. package/dist/components/auth-forms.js +41 -56
  21. package/dist/components/auth-provider.d.ts +3 -1
  22. package/dist/components/hooks.d.ts +2 -0
  23. package/dist/components/hooks.js +13 -6
  24. package/dist/components/index.d.ts +3 -0
  25. package/dist/components/index.js +2 -0
  26. package/dist/components/member-required.js +3 -5
  27. package/dist/components/oauth-consent.d.ts +22 -0
  28. package/dist/components/oauth-consent.js +79 -0
  29. package/dist/components/organization-switcher.d.ts +1 -1
  30. package/dist/components/organization-switcher.js +83 -54
  31. package/dist/components/project-card-list.d.ts +6 -0
  32. package/dist/components/project-card-list.js +4 -0
  33. package/dist/components/user-button.js +115 -54
  34. package/dist/extra/schema.d.ts +3 -1
  35. package/dist/oauth/authorization.d.ts +3 -0
  36. package/dist/oauth/authorization.js +39 -0
  37. package/dist/oauth/schema.d.ts +24 -0
  38. package/dist/oauth/schema.js +12 -0
  39. package/dist/oauth/verify.d.ts +13 -0
  40. package/dist/oauth/verify.js +67 -0
  41. package/dist/schema.js +1 -1
  42. package/dist/server/actor.js +2 -4
  43. package/dist/server/index.d.ts +2 -0
  44. package/dist/server/index.js +1 -0
  45. package/dist/server/mcp.d.ts +20 -0
  46. package/dist/server/mcp.js +66 -0
  47. package/dist/server/middleware.d.ts +5 -5
  48. package/dist/server/middleware.js +15 -5
  49. package/dist/server/webhook-layer.js +8 -4
  50. package/dist/server/webhooks.d.ts +9 -3
  51. package/dist/service.d.ts +52 -46
  52. package/dist/service.js +56 -9
  53. package/package.json +2 -1
@@ -1,5 +1,6 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { RegistryContext, useAtomRefresh, useAtomSet, useAtomValue, } from "@effect/atom-react";
2
+ import * as Data from "effect/Data";
3
+ import { RegistryContext, useAtomRefresh, useAtomSet, useAtomSubscribe, useAtomValue, } from "@effect/atom-react";
3
4
  import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
5
  import { useNavigate, useRouterState, } from "@tanstack/react-router";
5
6
  import { Effect, Option, Predicate, Schema } from "effect";
@@ -22,14 +23,14 @@ import { Input } from "@/components/ui/input";
22
23
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
23
24
  import { PasswordField } from "./password-field.js";
24
25
  import { PasswordResetActions, PasswordResetFeedback, usePasswordResetRequest, } from "./password-reset-flow.js";
25
- import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
26
+ import { authSessionAtom, notifyAuthChange, refreshAuthSession, } from "./auth-atoms.js";
26
27
  import { useKrakstackAuth } from "./auth-provider.js";
27
28
  import { parseApiKeyReferrers } from "./api-key.js";
28
29
  import { ApiKeyEditForm } from "./api-key-edit-form.js";
29
30
  import { ApiKeyPermissions } from "./api-key-permissions.js";
30
31
  import { ApiKeyRateLimit, apiKeyUsagePercent } from "./api-key-rate-limit.js";
31
32
  import { ApiKeyReferrers } from "./api-key-referrers.js";
32
- import { useOpenedOnce } from "./hooks.js";
33
+ import { useLatestAtom, useOpenedOnce } from "./hooks.js";
33
34
  import { ExtraUploadedAsset } from "../extra/schema.js";
34
35
  import { assetPath, assetUrl } from "./utils.js";
35
36
  import { AdminOrganizationsTable } from "./admin-organizations.js";
@@ -40,6 +41,8 @@ import { AccountDeletionDialog } from "./account-deletion.js";
40
41
  import { deletionControlsEnabled } from "./deletion-visibility.js";
41
42
  import { ContactEmailsField, ContactPhonesField, ContactSocialsField, ContactWebsitesField, } from "./contact-fields.js";
42
43
  import { decodeUserMetadata, ContactLocale, SocialPlatform, USER_CONTACT_LIMIT, UserMetadata, } from "../schema.js";
44
+ class UserAccountActionError extends Data.TaggedError("UserAccountActionError") {
45
+ }
43
46
  const messages = {
44
47
  en: {
45
48
  user_delete_title: "Delete account",
@@ -511,7 +514,9 @@ const isFile = (value) => value instanceof File;
511
514
  const uploadUserImageAsset = (file, m, baseUrl) => {
512
515
  const payload = new FormData();
513
516
  payload.append("file", file);
514
- 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())));
517
+ return authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.authExtra.uploadUserImage({ payload })), Effect.flatMap(Schema.decodeUnknownEffect(ExtraUploadedAsset)), Effect.mapError(() => new UserAccountActionError({
518
+ message: m.user_profile_image_upload_error(),
519
+ })));
515
520
  };
516
521
  const requiresPasswordForAccountRevoke = (accounts) => accounts.some((account) => account.providerId === "credential");
517
522
  const userAccountsAtom = Atom.family((baseUrl) => Atom.optimistic(Atom.keepAlive(Atom.map(authClientApi(baseUrl).query("auth", "listAccounts", {
@@ -633,18 +638,36 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
633
638
  : `${import.meta.env.VITE_SITE_URL}${signOutRedirect.startsWith("/") ? signOutRedirect : `/${signOutRedirect}`}`;
634
639
  signOut({ baseUrl: resolvedBaseUrl, redirectUrl });
635
640
  };
636
- return (_jsxs(UserButtonMessagesContext.Provider, { value: m, children: [hideTrigger ? null : (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsxs(Button, { variant: "outline", size: "icon", className: "overflow-hidden", children: [displayImage ? (_jsx("img", { src: displayImage, alt: displayName || displayEmail, className: "size-full 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 } : {}) }) }), _jsx(AssociatedProjectsNotice, { baseUrl: resolvedBaseUrl, getSummary: (count) => m.user_form_projects_summary({ count }), viewLabel: m.user_form_projects_view() }), 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, deletionControlsEnabled && !isImpersonating && !isOrganizationImpersonating ? _jsxs(DropdownMenuItem, { variant: "destructive", onClick: () => setSettingsDialog("deleteAccount"), children: [_jsx(Trash2, {}), m.user_delete_title()] }) : 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({
641
+ return (_jsxs(UserButtonMessagesContext.Provider, { value: m, children: [hideTrigger ? null : (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsxs(Button, { variant: "outline", size: "icon", className: "overflow-hidden", children: [displayImage ? (_jsx("img", { src: displayImage, alt: displayName || displayEmail, className: "size-full 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 } : {}) }) }), _jsx(AssociatedProjectsNotice, { baseUrl: resolvedBaseUrl, getSummary: (count) => m.user_form_projects_summary({ count }), viewLabel: m.user_form_projects_view() }), 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, deletionControlsEnabled &&
642
+ !isImpersonating &&
643
+ !isOrganizationImpersonating ? (_jsxs(DropdownMenuItem, { variant: "destructive", onClick: () => setSettingsDialog("deleteAccount"), children: [_jsx(Trash2, {}), m.user_delete_title()] })) : 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({
637
644
  baseUrl: resolvedBaseUrl,
638
645
  currentSiteHref,
639
646
  refreshSession,
640
- }), 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] }) })] })), deletionControlsEnabled && settingsDialog === "deleteAccount" && !isImpersonating && !isOrganizationImpersonating ? _jsx(AccountDeletionDialog, { baseUrl: resolvedBaseUrl, userId: session.user.id, onClose: () => setSettingsDialog(null), onDeleted: () => { notifyAuthChange(); void navigate({ href: signOutRedirect }); }, labels: {
641
- title: m.user_delete_title(), description: m.user_delete_description(), projects: m.user_delete_projects(),
642
- organizations: m.user_delete_organizations(), retention: m.user_delete_retention(),
643
- missing: m.user_delete_missing(), owner: m.user_delete_owner(), admin: m.user_delete_admin(),
644
- confirm: m.user_delete_confirm(), password: m.user_delete_password(), error: m.user_delete_error(),
645
- loadError: m.user_delete_load_error(), cancel: m.user_account_cancel(), submit: m.user_delete_title(),
646
- done: m.user_delete_done(), complete: m.user_delete_complete(),
647
- } }) : null, _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "account", onOpenChange: (open) => {
647
+ }), 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] }) })] })), deletionControlsEnabled &&
648
+ settingsDialog === "deleteAccount" &&
649
+ !isImpersonating &&
650
+ !isOrganizationImpersonating ? (_jsx(AccountDeletionDialog, { baseUrl: resolvedBaseUrl, userId: session.user.id, onClose: () => setSettingsDialog(null), onDeleted: () => {
651
+ notifyAuthChange();
652
+ void navigate({ href: signOutRedirect });
653
+ }, labels: {
654
+ title: m.user_delete_title(),
655
+ description: m.user_delete_description(),
656
+ projects: m.user_delete_projects(),
657
+ organizations: m.user_delete_organizations(),
658
+ retention: m.user_delete_retention(),
659
+ missing: m.user_delete_missing(),
660
+ owner: m.user_delete_owner(),
661
+ admin: m.user_delete_admin(),
662
+ confirm: m.user_delete_confirm(),
663
+ password: m.user_delete_password(),
664
+ error: m.user_delete_error(),
665
+ loadError: m.user_delete_load_error(),
666
+ cancel: m.user_account_cancel(),
667
+ submit: m.user_delete_title(),
668
+ done: m.user_delete_done(),
669
+ complete: m.user_delete_complete(),
670
+ } })) : null, _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "account", onOpenChange: (open) => {
648
671
  setSettingsDialog((current) => open ? "account" : current === "account" ? null : current);
649
672
  }, children: _jsx(UserForm, { primaryEmail: displayEmail, defaultValues: {
650
673
  name: displayName ?? "",
@@ -663,7 +686,9 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
663
686
  ...values.emails,
664
687
  ],
665
688
  }),
666
- catch: () => new Error(m.user_contact_validation_error()),
689
+ catch: () => new UserAccountActionError({
690
+ message: m.user_contact_validation_error(),
691
+ }),
667
692
  });
668
693
  const imageFile = isFile(values.image) ? values.image : null;
669
694
  const image = imageFile
@@ -740,7 +765,7 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
740
765
  await accountCache.reload();
741
766
  setRevokingAccount(null);
742
767
  } })) : totpSetup ? (_jsx(VerifyTotpSetup, { baseUrl: resolvedBaseUrl, setup: totpSetup, onVerified: async () => {
743
- await refreshSession();
768
+ await Effect.runPromise(refreshAuthSession(registry, resolvedBaseUrl));
744
769
  setTotpSetup(null);
745
770
  setManagingTwoFactor(false);
746
771
  } })) : managingTwoFactor ? (_jsx(AccountSecuritySettings, { onResetPassword: startPasswordReset, baseUrl: resolvedBaseUrl, accountCache: accountCache, onSetup: setTotpSetup })) : (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(ConnectedAccounts, { onChangePassword: () => setChangingPassword(true), onSetupPassword: () => setSettingPassword(true), onRevokeAccount: setRevokingAccount, baseUrl: resolvedBaseUrl, accountCache: accountCache, googleEnabled: projectConfig?.authOptions.google ?? true, currentSiteHref: currentSiteHref, navigate: navigate }), _jsx(Separator, {}), _jsxs("section", { className: "flex flex-col gap-6", children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_two_factor_title() }), _jsx("p", { className: "text-muted-foreground text-xs", children: m.user_two_factor_description() })] }), _jsx(Badge, { variant: hasTwoFactorEnabled(session?.user)
@@ -816,7 +841,6 @@ function PasswordSettings({ onSetupPassword, onRevokeAccount, onChangePassword,
816
841
  function ChangePasswordForm({ baseUrl, onResetPassword, }) {
817
842
  const m = useUserButtonMessages();
818
843
  const [saved, setSaved] = useState(false);
819
- let reset = () => { };
820
844
  const [form] = useState(() => FormReact.make(changePasswordFormBuilder, {
821
845
  runtime: authClientApi(baseUrl).runtime,
822
846
  fields: { currentPassword: PasswordField, newPassword: PasswordField },
@@ -826,11 +850,18 @@ function ChangePasswordForm({ baseUrl, onResetPassword, }) {
826
850
  currentPassword: decoded.currentPassword,
827
851
  newPassword: decoded.newPassword,
828
852
  },
829
- })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap(() => Effect.sync(() => reset())), Effect.tap(() => Effect.sync(() => setSaved(true))), Effect.mapError((cause) => cause instanceof Error
830
- ? cause
831
- : new Error(m.user_account_password_change_error()))),
853
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap(() => Effect.sync(() => setSaved(true))), Effect.mapError((cause) => new UserAccountActionError({
854
+ message: cause instanceof Error
855
+ ? cause.message
856
+ : m.user_account_password_change_error(),
857
+ cause: cause,
858
+ }))),
832
859
  }));
833
- reset = useAtomSet(form.reset);
860
+ const reset = useAtomSet(form.reset);
861
+ useAtomSubscribe(form.submit, (result) => {
862
+ if (AsyncResult.isSuccess(result))
863
+ reset();
864
+ });
834
865
  const submit = useAtomSet(form.submit);
835
866
  const submitResult = useAtomValue(form.submit);
836
867
  return (_jsx(form.Initialize, { defaultValues: { currentPassword: "", newPassword: "" }, children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-md", onSubmit: (event) => {
@@ -850,9 +881,12 @@ function SetPasswordForm({ baseUrl, onSaved, }) {
850
881
  mode: { validation: "onSubmit" },
851
882
  onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.authExtra.setPassword({
852
883
  payload: { newPassword: decoded.password },
853
- })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onSaved())), Effect.mapError((cause) => cause instanceof Error
854
- ? cause
855
- : new Error(m.user_account_password_set_error()))),
884
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onSaved())), Effect.mapError((cause) => new UserAccountActionError({
885
+ message: cause instanceof Error
886
+ ? cause.message
887
+ : m.user_account_password_set_error(),
888
+ cause: cause,
889
+ }))),
856
890
  }));
857
891
  const submit = useAtomSet(form.submit);
858
892
  const submitResult = useAtomValue(form.submit);
@@ -882,14 +916,20 @@ function RevokeAccountForm({ baseUrl, onResetPassword, account, requirePassword,
882
916
  accountId: account.accountId,
883
917
  },
884
918
  })
885
- .pipe(Effect.mapError((cause) => cause instanceof Error
886
- ? cause
887
- : new Error(m.user_account_revoke_error())));
919
+ .pipe(Effect.mapError((cause) => new UserAccountActionError({
920
+ message: cause instanceof Error
921
+ ? cause.message
922
+ : m.user_account_revoke_error(),
923
+ cause: cause,
924
+ })));
888
925
  yield* Effect.sync(notifyAuthChange);
889
926
  yield* Effect.tryPromise(onRevoked);
890
- }).pipe(Effect.mapError((cause) => cause instanceof Error
891
- ? cause
892
- : new Error(m.user_account_password_verify_error()))),
927
+ }).pipe(Effect.mapError((cause) => new UserAccountActionError({
928
+ message: cause instanceof Error
929
+ ? cause.message
930
+ : m.user_account_password_verify_error(),
931
+ cause: cause,
932
+ }))),
893
933
  }));
894
934
  const submit = useAtomSet(form.submit);
895
935
  const submitResult = useAtomValue(form.submit);
@@ -923,9 +963,12 @@ const UserForm = ({ defaultValues, primaryEmail, error, onSubmit, }) => {
923
963
  socials: ContactSocialsField,
924
964
  },
925
965
  mode: { validation: "onSubmit" },
926
- onSubmit: (_, { decoded }) => onSubmit({ ...decoded, image: decoded.image ?? null }).pipe(Effect.mapError((cause) => cause instanceof Error
927
- ? cause
928
- : new Error(m.user_form_update_error()))),
966
+ onSubmit: (_, { decoded }) => onSubmit({ ...decoded, image: decoded.image ?? null }).pipe(Effect.mapError((cause) => new UserAccountActionError({
967
+ message: cause instanceof Error
968
+ ? cause.message
969
+ : m.user_form_update_error(),
970
+ cause: cause,
971
+ }))),
929
972
  }));
930
973
  const submit = useAtomSet(form.submit);
931
974
  return (_jsx(form.Initialize, { defaultValues: defaultValues, children: _jsx("form", { onSubmit: (event) => {
@@ -944,7 +987,7 @@ function AccountSecuritySettings({ baseUrl, onResetPassword, accountCache, onSet
944
987
  const m = useUserButtonMessages();
945
988
  const sessionAtom = authSessionAtom(baseUrl);
946
989
  const sessionResult = useAtomValue(sessionAtom);
947
- const refreshSession = useAtomRefresh(sessionAtom);
990
+ const registry = useContext(RegistryContext);
948
991
  const session = AsyncResult.match(sessionResult, {
949
992
  onInitial: () => null,
950
993
  onFailure: () => null,
@@ -959,7 +1002,7 @@ function AccountSecuritySettings({ baseUrl, onResetPassword, accountCache, onSet
959
1002
  ? "text-destructive text-sm"
960
1003
  : "text-muted-foreground text-sm", children: accountCache.error ?? m.user_loading() })) : twoFactorEnabled ? (_jsx(DisableTotpForm, { onResetPassword: onResetPassword, baseUrl: baseUrl, requirePassword: requirePassword, onDisabled: async () => {
961
1004
  setMessage(m.user_two_factor_disabled_message());
962
- await refreshSession();
1005
+ await Effect.runPromise(refreshAuthSession(registry, baseUrl));
963
1006
  } })) : (_jsx(EnableTotpForm, { onResetPassword: onResetPassword, baseUrl: baseUrl, requirePassword: requirePassword, onEnabled: onSetup })), message ? (_jsx("p", { className: "text-muted-foreground text-sm", children: message })) : null] }));
964
1007
  }
965
1008
  function EnableTotpForm({ baseUrl, onResetPassword, requirePassword, onEnabled, }) {
@@ -973,9 +1016,12 @@ function EnableTotpForm({ baseUrl, onResetPassword, requirePassword, onEnabled,
973
1016
  })), Effect.tap((result) => Effect.sync(() => onEnabled({
974
1017
  totpURI: result.totpURI,
975
1018
  backupCodes: Array.from(result.backupCodes),
976
- }))), Effect.mapError((cause) => cause instanceof Error
977
- ? cause
978
- : new Error(m.user_two_factor_enable_error()))),
1019
+ }))), Effect.mapError((cause) => new UserAccountActionError({
1020
+ message: cause instanceof Error
1021
+ ? cause.message
1022
+ : m.user_two_factor_enable_error(),
1023
+ cause: cause,
1024
+ }))),
979
1025
  }));
980
1026
  const submit = useAtomSet(form.submit);
981
1027
  const submitResult = useAtomValue(form.submit);
@@ -1003,9 +1049,12 @@ function VerifyTotpSetup({ baseUrl, setup, onVerified, }) {
1003
1049
  mode: { validation: "onSubmit" },
1004
1050
  onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorVerifyTotp({
1005
1051
  payload: { code: decoded.code.trim() },
1006
- })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onVerified())), Effect.mapError((cause) => cause instanceof Error
1007
- ? cause
1008
- : new Error(m.user_two_factor_verify_error()))),
1052
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onVerified())), Effect.mapError((cause) => new UserAccountActionError({
1053
+ message: cause instanceof Error
1054
+ ? cause.message
1055
+ : m.user_two_factor_verify_error(),
1056
+ cause: cause,
1057
+ }))),
1009
1058
  }));
1010
1059
  const submit = useAtomSet(form.submit);
1011
1060
  const submitResult = useAtomValue(form.submit);
@@ -1023,9 +1072,12 @@ function DisableTotpForm({ baseUrl, onResetPassword, requirePassword, onDisabled
1023
1072
  mode: { validation: "onSubmit" },
1024
1073
  onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorDisable({
1025
1074
  payload: requirePassword ? { password: decoded.password } : {},
1026
- })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onDisabled())), Effect.mapError((cause) => cause instanceof Error
1027
- ? cause
1028
- : new Error(m.user_two_factor_disable_error()))),
1075
+ })), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onDisabled())), Effect.mapError((cause) => new UserAccountActionError({
1076
+ message: cause instanceof Error
1077
+ ? cause.message
1078
+ : m.user_two_factor_disable_error(),
1079
+ cause: cause,
1080
+ }))),
1029
1081
  }));
1030
1082
  const submit = useAtomSet(form.submit);
1031
1083
  const submitResult = useAtomValue(form.submit);
@@ -1064,39 +1116,48 @@ function ApiKeyManager({ baseUrl, active, locale, permissionLabels, permissions
1064
1116
  onSuccess: () => null,
1065
1117
  });
1066
1118
  const loading = keysResult._tag === "Initial";
1067
- const permissionOptionsRef = useRef(permissionOptions);
1068
- const selectedPermissionsRef = useRef(selectedPermissions);
1069
- permissionOptionsRef.current = permissionOptions;
1070
- selectedPermissionsRef.current = selectedPermissions;
1119
+ const permissionOptionsAtom = useLatestAtom(permissionOptions);
1120
+ const selectedPermissionsAtom = useLatestAtom(selectedPermissions);
1071
1121
  const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
1072
1122
  runtime: authClientApi(baseUrl).runtime,
1073
1123
  fields: { name: TextField, referrers: TextAreaField },
1074
1124
  mode: { validation: "onSubmit" },
1075
- onSubmit: (_, { decoded }) => Effect.gen(function* () {
1125
+ onSubmit: (_, { decoded, get }) => Effect.gen(function* () {
1076
1126
  setCreatedKey(null);
1077
1127
  const referrers = yield* Effect.try({
1078
1128
  try: () => parseApiKeyReferrers(decoded.referrers, m.user_api_key_referrers_error()),
1079
- catch: (cause) => cause,
1129
+ catch: (cause) => new UserAccountActionError({
1130
+ message: cause instanceof Error
1131
+ ? cause.message
1132
+ : m.user_api_key_create_error(),
1133
+ cause,
1134
+ }),
1080
1135
  });
1081
1136
  const client = yield* authHttpClient(baseUrl);
1082
1137
  return yield* client.authExtra.createApiKey({
1083
1138
  payload: {
1084
1139
  configId: "user",
1085
1140
  name: decoded.name.trim(),
1086
- permissions: getSelectedPermissionObject(permissionOptionsRef.current, selectedPermissionsRef.current),
1141
+ permissions: getSelectedPermissionObject(get(permissionOptionsAtom), get(selectedPermissionsAtom)),
1087
1142
  referrers,
1088
1143
  },
1089
1144
  });
1090
1145
  }).pipe(Effect.tap((created) => Effect.sync(() => {
1091
1146
  setCreatedKey(created.key);
1092
- resetCreateForm();
1093
1147
  setSelectedPermissions({});
1094
1148
  refreshKeys();
1095
- })), Effect.mapError((cause) => cause instanceof Error
1096
- ? cause
1097
- : new Error(m.user_api_key_create_error()))),
1149
+ })), Effect.mapError((cause) => new UserAccountActionError({
1150
+ message: cause instanceof Error
1151
+ ? cause.message
1152
+ : m.user_api_key_create_error(),
1153
+ cause: cause,
1154
+ }))),
1098
1155
  }));
1099
1156
  const resetCreateForm = useAtomSet(createForm.reset);
1157
+ useAtomSubscribe(createForm.submit, (result) => {
1158
+ if (AsyncResult.isSuccess(result))
1159
+ resetCreateForm();
1160
+ });
1100
1161
  const submitCreateForm = useAtomSet(createForm.submit);
1101
1162
  const createSubmitResult = useAtomValue(createForm.submit);
1102
1163
  const togglePermission = (id, checked) => {
@@ -188,7 +188,9 @@ export declare const ExtraUploadedAsset: Schema.Struct<{
188
188
  }>;
189
189
  declare const ExtraBadRequest_base: Schema.Class<ExtraBadRequest, Schema.TaggedStruct<"ExtraBadRequest", {
190
190
  readonly message: Schema.String;
191
- }>, import("effect/Cause").YieldableError>;
191
+ }>, import("effect/Cause").YieldableError & {
192
+ readonly brand: unique symbol;
193
+ }>;
192
194
  export declare class ExtraBadRequest extends ExtraBadRequest_base {
193
195
  }
194
196
  export type ExtraImageUploadPayload = typeof ExtraImageUploadPayload.Type;
@@ -0,0 +1,3 @@
1
+ /** Extract only the provider-signed parameters. Modern Better Auth queries
2
+ * declare them with repeated ba_param entries, independent of URL ordering. */
3
+ export declare const getOAuthAuthorizationQuery: (searchString: string) => string | null;
@@ -0,0 +1,39 @@
1
+ import { Option, Schema } from "effect";
2
+ const RepeatedOAuthValues = Schema.fromJsonString(Schema.NonEmptyArray(Schema.String)).annotate({ identifier: "RepeatedOAuthQueryValues" });
3
+ /** Extract only the provider-signed parameters. Modern Better Auth queries
4
+ * declare them with repeated ba_param entries, independent of URL ordering. */
5
+ export const getOAuthAuthorizationQuery = (searchString) => {
6
+ const search = new URLSearchParams(searchString);
7
+ if (!search.has("sig") || !search.has("client_id"))
8
+ return null;
9
+ // Recover links normalized by a JSON-first router. This only restores
10
+ // known repeatable protocol fields; the provider still verifies the signature.
11
+ for (const key of ["ba_param", "resource"]) {
12
+ const values = search.getAll(key);
13
+ if (values.length !== 1 || values[0] === undefined)
14
+ continue;
15
+ const parsed = Schema.decodeOption(RepeatedOAuthValues)(values[0]);
16
+ if (Option.isSome(parsed)) {
17
+ search.delete(key);
18
+ for (const value of parsed.value)
19
+ search.append(key, value);
20
+ }
21
+ }
22
+ const parameterNames = search.getAll("ba_param");
23
+ if (parameterNames.length) {
24
+ const names = new Set([...parameterNames, "sig", "ba_param"]);
25
+ const signed = new URLSearchParams();
26
+ for (const [key, value] of search)
27
+ if (names.has(key))
28
+ signed.append(key, value);
29
+ return signed.toString();
30
+ }
31
+ // Compatibility with providers that do not publish a signed-field manifest.
32
+ const signed = new URLSearchParams();
33
+ for (const [key, value] of search) {
34
+ signed.append(key, value);
35
+ if (key === "sig")
36
+ break;
37
+ }
38
+ return signed.toString();
39
+ };
@@ -0,0 +1,24 @@
1
+ import { Schema } from "effect";
2
+ export declare const OAuthAccessTokenClaims: Schema.Struct<{
3
+ readonly sub: Schema.NonEmptyString;
4
+ readonly azp: Schema.NonEmptyString;
5
+ readonly exp: Schema.Finite;
6
+ readonly iat: Schema.Finite;
7
+ readonly scope: Schema.String;
8
+ readonly organization_id: Schema.NonEmptyString;
9
+ readonly cnf: Schema.optional<Schema.Never>;
10
+ }>;
11
+ export type OAuthResourceOptions = {
12
+ readonly issuer: string;
13
+ readonly resource: string;
14
+ readonly jwksUrl: string;
15
+ readonly requiredScopes: readonly string[];
16
+ /** Capabilities clients may request; not every request must hold all of them. */
17
+ readonly scopesSupported?: readonly string[];
18
+ /** Scope hint sent to clients starting or upgrading authorization. */
19
+ readonly challengeScopes?: readonly string[];
20
+ /** Defaults to read-only API access. MCP transport POSTs are handled separately. */
21
+ readonly allowedMethods?: readonly string[];
22
+ /** Required in addition to requiredScopes for non-GET/HEAD API requests. */
23
+ readonly writeScope?: string;
24
+ };
@@ -0,0 +1,12 @@
1
+ import { Schema } from "effect";
2
+ export const OAuthAccessTokenClaims = Schema.Struct({
3
+ sub: Schema.NonEmptyString,
4
+ azp: Schema.NonEmptyString,
5
+ exp: Schema.Finite,
6
+ iat: Schema.Finite,
7
+ scope: Schema.String,
8
+ organization_id: Schema.NonEmptyString,
9
+ // Sender-constrained tokens need request-bound proof verification. This
10
+ // integration intentionally supports bearer tokens only, never strips cnf.
11
+ cnf: Schema.optional(Schema.Never),
12
+ }).annotate({ identifier: "OAuthAccessTokenClaims" });
@@ -0,0 +1,13 @@
1
+ import { Effect } from "effect";
2
+ import { HttpClient } from "effect/http";
3
+ import { HttpApiError } from "effect/http-api";
4
+ import { type OAuthResourceOptions } from "./schema.js";
5
+ export declare const verifyOAuthAccessToken: (token: string, options: OAuthResourceOptions) => Effect.Effect<{
6
+ readonly sub: string;
7
+ readonly azp: string;
8
+ readonly exp: number;
9
+ readonly iat: number;
10
+ readonly scope: string;
11
+ readonly organization_id: string;
12
+ readonly cnf?: undefined;
13
+ }, HttpApiError.Forbidden | HttpApiError.ServiceUnavailable | HttpApiError.Unauthorized, HttpClient.HttpClient>;
@@ -0,0 +1,67 @@
1
+ import { verifyJwsAccessToken } from "@better-auth/core/oauth2";
2
+ import { Effect, Schema } from "effect";
3
+ import { HttpClient, HttpClientResponse } from "effect/http";
4
+ import { HttpApiError } from "effect/http-api";
5
+ import { OAuthAccessTokenClaims } from "./schema.js";
6
+ const PublicJwkSet = Schema.Struct({
7
+ keys: Schema.Array(Schema.Struct({
8
+ kty: Schema.String,
9
+ kid: Schema.optional(Schema.String),
10
+ alg: Schema.optional(Schema.String),
11
+ use: Schema.optional(Schema.String),
12
+ crv: Schema.optional(Schema.String),
13
+ x: Schema.optional(Schema.String),
14
+ y: Schema.optional(Schema.String),
15
+ n: Schema.optional(Schema.String),
16
+ e: Schema.optional(Schema.String),
17
+ })),
18
+ }).annotate({ identifier: "OAuthPublicJwkSet" });
19
+ // Stable per-URL identity enables Better Auth's bounded JWKS cache and kid-miss
20
+ // refresh. The URL is trusted application configuration, never token input.
21
+ const jwksCacheKeys = new Map();
22
+ class OAuthJwksUnavailable extends Schema.TaggedError()("OAuthJwksUnavailable", {}) {
23
+ }
24
+ export const verifyOAuthAccessToken = Effect.fn("Auth.verifyOAuthAccessToken")(function* (token, options) {
25
+ const http = yield* HttpClient.HttpClient;
26
+ const runPromise = Effect.runPromiseWith(yield* Effect.context());
27
+ let cacheKey = jwksCacheKeys.get(options.jwksUrl);
28
+ if (!cacheKey) {
29
+ cacheKey = {};
30
+ jwksCacheKeys.set(options.jwksUrl, cacheKey);
31
+ }
32
+ const payload = yield* Effect.tryPromise({
33
+ try: () => verifyJwsAccessToken(token, {
34
+ jwksCacheKey: cacheKey,
35
+ jwksFetch: async () => {
36
+ const result = await runPromise(HttpClient.filterStatusOk(http)
37
+ .get(options.jwksUrl)
38
+ .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(PublicJwkSet)), Effect.map((jwks) => ({ keys: Array.from(jwks.keys) })), Effect.result));
39
+ if (result._tag === "Failure")
40
+ throw new OAuthJwksUnavailable({});
41
+ return result.success;
42
+ },
43
+ verifyOptions: {
44
+ issuer: options.issuer,
45
+ audience: options.resource,
46
+ typ: "at+jwt",
47
+ requiredClaims: [
48
+ "sub",
49
+ "azp",
50
+ "exp",
51
+ "iat",
52
+ "scope",
53
+ "organization_id",
54
+ ],
55
+ },
56
+ }),
57
+ catch: (error) => error instanceof OAuthJwksUnavailable
58
+ ? new HttpApiError.ServiceUnavailable({})
59
+ : new HttpApiError.Unauthorized({}),
60
+ });
61
+ const claims = yield* Schema.decodeUnknownEffect(OAuthAccessTokenClaims)(payload).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
62
+ const scopes = new Set(claims.scope.split(/\s+/).filter(Boolean));
63
+ if (!options.requiredScopes.every((scope) => scopes.has(scope))) {
64
+ return yield* new HttpApiError.Forbidden({});
65
+ }
66
+ return claims;
67
+ });
package/dist/schema.js CHANGED
@@ -227,7 +227,7 @@ export const decodeUserMetadata = (metadata) => {
227
227
  metadataValue = { ...metadataValue, websites: websites.value };
228
228
  if (Option.isSome(socials))
229
229
  metadataValue = { ...metadataValue, socials: socials.value };
230
- return Option.getOrElse(Schema.decodeUnknownOption(UserMetadata)(metadataValue), () => ({}));
230
+ return Option.getOrElse(Schema.decodeOption(UserMetadata)(metadataValue), () => ({}));
231
231
  };
232
232
  export const UserMetadataStandard = Schema.toStandardSchemaV1(UserMetadata);
233
233
  const CompatibleUserMetadata = Schema.Unknown.pipe(Schema.decodeTo(UserMetadata, {
@@ -15,7 +15,7 @@ const resolveCurrentActor = (access) => Effect.gen(function* () {
15
15
  const session = yield* auth.requireSession();
16
16
  if (session.authMethod.type === "apiKey") {
17
17
  const apiKey = session.authMethod.apiKey;
18
- const grant = yield* Schema.decodeUnknownEffect(ApiKeyPermissionGrant)(apiKey.permissions ?? {}).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
18
+ const grant = yield* Schema.decodeEffect(ApiKeyPermissionGrant)(apiKey.permissions ?? {}).pipe(Effect.mapError(() => new HttpApiError.Unauthorized({})));
19
19
  const organizationId = session.session.activeOrganizationId;
20
20
  if (!organizationId)
21
21
  return yield* new HttpApiError.Unauthorized({});
@@ -107,9 +107,7 @@ const matchesConstraint = (actor, constraint) => {
107
107
  return (actor.actor.type === "apiKey" &&
108
108
  (!constraint.ownerType || actor.actor.owner.type === constraint.ownerType));
109
109
  };
110
- const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.flatMap((actor) => matchesConstraint(actor, constraint)
111
- ? Effect.succeed(actor)
112
- : Effect.fail(new HttpApiError.Forbidden({}))));
110
+ const requiredActor = (access, constraint) => resolveCurrentActor(access).pipe(Effect.filterOrFail((actor) => matchesConstraint(actor, constraint), () => new HttpApiError.Forbidden({})));
113
111
  const withCurrentActor = (httpEffect, actor) => {
114
112
  const roles = actor.actor.type === "user"
115
113
  ? actor.actor.roles
@@ -1,4 +1,6 @@
1
1
  export { AuthService } from "../service.js";
2
+ export type { OAuthResourceOptions } from "../oauth/schema.js";
3
+ export { McpAuth } from "./mcp.js";
2
4
  export { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, OrganizationDeletionWebhook, AuthWebhook, AuthWebhookData, } from "../schema.js";
3
5
  export type { AuthSession, AuthSessionWithOrganization, AuthSessionWithUser, AuthSessionWithUserAndOrganization, } from "../service.js";
4
6
  export { AuthClientConfig } from "../config.js";
@@ -1,4 +1,5 @@
1
1
  export { AuthService } from "../service.js";
2
+ export { McpAuth } from "./mcp.js";
2
3
  export { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, OrganizationDeletionWebhook, AuthWebhook, AuthWebhookData, } from "../schema.js";
3
4
  export { AuthClientConfig } from "../config.js";
4
5
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group.js";
@@ -0,0 +1,20 @@
1
+ import { Layer } from "effect";
2
+ import { HttpRouter } from "effect/http";
3
+ import type { OAuthResourceOptions } from "../oauth/schema.js";
4
+ declare const metadataPath: (resource: string) => `/${string}`;
5
+ /** OAuth discovery and authentication for an existing MCP transport. */
6
+ export declare const McpAuth: {
7
+ metadataPath: typeof metadataPath;
8
+ /** Forward public discovery through the consumer's existing auth proxy. */
9
+ discoveryRequest: (request: Request, options: OAuthResourceOptions) => Request | undefined;
10
+ metadataLayer: (options: OAuthResourceOptions) => Layer.Layer<never, never, HttpRouter.HttpRouter>;
11
+ middleware: (options: OAuthResourceOptions) => HttpRouter.Middleware<{
12
+ provides: never;
13
+ handles: never;
14
+ error: never;
15
+ requires: never;
16
+ layerError: never;
17
+ layerRequires: never;
18
+ }>;
19
+ };
20
+ export {};