@krak-stack/auth 0.2.31 → 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.
- package/CHANGELOG.md +19 -0
- package/README.md +175 -1
- package/dist/access.d.ts +3 -1
- package/dist/admin/api.group.d.ts +41 -41
- package/dist/admin/schema.d.ts +23 -23
- package/dist/admin/schema.js +21 -19
- package/dist/api.d.ts +141 -81
- package/dist/auth/api.group.d.ts +37 -19
- package/dist/auth/api.group.js +17 -1
- package/dist/auth/schema.d.ts +61 -33
- package/dist/auth/schema.js +30 -18
- package/dist/components/account-deletion-request.d.ts +5 -0
- package/dist/components/account-deletion-request.js +7 -0
- package/dist/components/account-deletion.d.ts +8 -0
- package/dist/components/account-deletion.js +59 -0
- package/dist/components/admin-organization-form.js +2 -2
- package/dist/components/admin-organizations.js +9 -7
- package/dist/components/admin-users.js +6 -6
- package/dist/components/api-key-edit-form.js +19 -11
- package/dist/components/associated-projects-notice.d.ts +2 -1
- package/dist/components/associated-projects-notice.js +7 -3
- package/dist/components/auth-atoms.js +1 -2
- package/dist/components/auth-client-api.d.ts +94 -61
- package/dist/components/auth-forms.d.ts +1 -0
- package/dist/components/auth-forms.js +41 -56
- package/dist/components/auth-provider.d.ts +3 -1
- package/dist/components/deletion-visibility.d.ts +1 -0
- package/dist/components/deletion-visibility.js +3 -0
- package/dist/components/hooks.d.ts +2 -0
- package/dist/components/hooks.js +13 -6
- package/dist/components/index.d.ts +3 -0
- package/dist/components/index.js +2 -0
- package/dist/components/member-required.js +3 -5
- package/dist/components/oauth-consent.d.ts +22 -0
- package/dist/components/oauth-consent.js +79 -0
- package/dist/components/organization-deletion-request.d.ts +17 -0
- package/dist/components/organization-deletion-request.js +9 -0
- package/dist/components/organization-switcher.d.ts +1 -1
- package/dist/components/organization-switcher.js +113 -55
- package/dist/components/project-card-list.d.ts +6 -0
- package/dist/components/project-card-list.js +4 -0
- package/dist/components/user-button.d.ts +29 -1
- package/dist/components/user-button.js +145 -47
- package/dist/extra/api.group.d.ts +13 -1
- package/dist/extra/api.group.js +5 -1
- package/dist/extra/schema.d.ts +16 -1
- package/dist/extra/schema.js +13 -0
- package/dist/oauth/authorization.d.ts +3 -0
- package/dist/oauth/authorization.js +39 -0
- package/dist/oauth/schema.d.ts +24 -0
- package/dist/oauth/schema.js +12 -0
- package/dist/oauth/verify.d.ts +13 -0
- package/dist/oauth/verify.js +67 -0
- package/dist/schema.d.ts +35 -0
- package/dist/schema.js +26 -1
- package/dist/server/actor.js +2 -4
- package/dist/server/index.d.ts +4 -1
- package/dist/server/index.js +2 -0
- package/dist/server/mcp.d.ts +20 -0
- package/dist/server/mcp.js +66 -0
- package/dist/server/middleware.d.ts +15 -7
- package/dist/server/middleware.js +19 -6
- package/dist/server/webhook-layer.d.ts +6 -0
- package/dist/server/webhook-layer.js +41 -0
- package/dist/server/webhooks.d.ts +44 -0
- package/dist/server/webhooks.js +39 -0
- package/dist/service.d.ts +118 -46
- package/dist/service.js +56 -9
- package/package.json +8 -3
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import
|
|
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,24 +23,42 @@ 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";
|
|
36
37
|
import { AdminUsersTable } from "./admin-users.js";
|
|
37
38
|
import { ScrollableDialogBody, ScrollableDialogContent, ScrollableDialogHeader, } from "./scrollable-dialog.js";
|
|
38
39
|
import { AssociatedProjectsNotice } from "./associated-projects-notice.js";
|
|
40
|
+
import { AccountDeletionDialog } from "./account-deletion.js";
|
|
41
|
+
import { deletionControlsEnabled } from "./deletion-visibility.js";
|
|
39
42
|
import { ContactEmailsField, ContactPhonesField, ContactSocialsField, ContactWebsitesField, } from "./contact-fields.js";
|
|
40
43
|
import { decodeUserMetadata, ContactLocale, SocialPlatform, USER_CONTACT_LIMIT, UserMetadata, } from "../schema.js";
|
|
44
|
+
class UserAccountActionError extends Data.TaggedError("UserAccountActionError") {
|
|
45
|
+
}
|
|
41
46
|
const messages = {
|
|
42
47
|
en: {
|
|
48
|
+
user_delete_title: "Delete account",
|
|
49
|
+
user_delete_description: "Permanently delete your account and unshared personal organizations. This cannot be undone.",
|
|
50
|
+
user_delete_projects: "Connected projects",
|
|
51
|
+
user_delete_organizations: "Organizations to resolve",
|
|
52
|
+
user_delete_retention: "Project cleanup is requested separately. Legal retention may apply.",
|
|
53
|
+
user_delete_missing: "Some projects need support to complete cleanup.",
|
|
54
|
+
user_delete_owner: "Transfer ownership or delete these in the organization switcher. Shared personal organizations need support.",
|
|
55
|
+
user_delete_admin: "Remove your platform admin role before continuing.",
|
|
56
|
+
user_delete_confirm: "Type DELETE to confirm",
|
|
57
|
+
user_delete_password: "Current password (if required)",
|
|
58
|
+
user_delete_error: "Unable to delete your account. Check your password, or sign in again and retry.",
|
|
59
|
+
user_delete_load_error: "Loading requirements… Close and retry if this takes too long.",
|
|
60
|
+
user_delete_complete: "Your account is deleted. Project cleanup may still be pending; retained records are not necessarily erased.",
|
|
61
|
+
user_delete_done: "Done",
|
|
43
62
|
table_empty: "No results.",
|
|
44
63
|
user_account_cancel: "Cancel",
|
|
45
64
|
user_account_back: "Back",
|
|
@@ -185,6 +204,20 @@ const messages = {
|
|
|
185
204
|
user_two_factor_verify_error: "Could not verify the code.",
|
|
186
205
|
},
|
|
187
206
|
fr: {
|
|
207
|
+
user_delete_title: "Supprimer le compte",
|
|
208
|
+
user_delete_description: "Supprimez définitivement votre compte et vos organisations personnelles non partagées. Cette action est irréversible.",
|
|
209
|
+
user_delete_projects: "Projets liés",
|
|
210
|
+
user_delete_organizations: "Organisations à régler",
|
|
211
|
+
user_delete_retention: "Le nettoyage des projets est demandé séparément. Une conservation légale peut s’appliquer.",
|
|
212
|
+
user_delete_missing: "Certains projets nécessitent l’assistance pour terminer le nettoyage.",
|
|
213
|
+
user_delete_owner: "Transférez la propriété ou supprimez ces organisations dans le sélecteur. Les organisations personnelles partagées nécessitent l’assistance.",
|
|
214
|
+
user_delete_admin: "Retirez votre rôle administrateur de plateforme avant de continuer.",
|
|
215
|
+
user_delete_confirm: "Saisissez DELETE pour confirmer",
|
|
216
|
+
user_delete_password: "Mot de passe actuel (si nécessaire)",
|
|
217
|
+
user_delete_error: "Impossible de supprimer le compte. Vérifiez votre mot de passe ou reconnectez-vous, puis réessayez.",
|
|
218
|
+
user_delete_load_error: "Chargement des conditions… Fermez et réessayez si l’attente se prolonge.",
|
|
219
|
+
user_delete_complete: "Votre compte est supprimé. Le nettoyage des projets peut être en attente ; les données conservées ne sont pas nécessairement effacées.",
|
|
220
|
+
user_delete_done: "Terminé",
|
|
188
221
|
table_empty: "Aucun résultat.",
|
|
189
222
|
user_account_cancel: "Annuler",
|
|
190
223
|
user_account_back: "Retour",
|
|
@@ -481,7 +514,9 @@ const isFile = (value) => value instanceof File;
|
|
|
481
514
|
const uploadUserImageAsset = (file, m, baseUrl) => {
|
|
482
515
|
const payload = new FormData();
|
|
483
516
|
payload.append("file", file);
|
|
484
|
-
return authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.authExtra.uploadUserImage({ payload })), Effect.flatMap(Schema.decodeUnknownEffect(ExtraUploadedAsset)), Effect.mapError(() => new
|
|
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
|
+
})));
|
|
485
520
|
};
|
|
486
521
|
const requiresPasswordForAccountRevoke = (accounts) => accounts.some((account) => account.providerId === "credential");
|
|
487
522
|
const userAccountsAtom = Atom.family((baseUrl) => Atom.optimistic(Atom.keepAlive(Atom.map(authClientApi(baseUrl).query("auth", "listAccounts", {
|
|
@@ -603,11 +638,36 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
|
|
|
603
638
|
: `${import.meta.env.VITE_SITE_URL}${signOutRedirect.startsWith("/") ? signOutRedirect : `/${signOutRedirect}`}`;
|
|
604
639
|
signOut({ baseUrl: resolvedBaseUrl, redirectUrl });
|
|
605
640
|
};
|
|
606
|
-
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(
|
|
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({
|
|
607
644
|
baseUrl: resolvedBaseUrl,
|
|
608
645
|
currentSiteHref,
|
|
609
646
|
refreshSession,
|
|
610
|
-
}), 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] }) })] })),
|
|
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) => {
|
|
611
671
|
setSettingsDialog((current) => open ? "account" : current === "account" ? null : current);
|
|
612
672
|
}, children: _jsx(UserForm, { primaryEmail: displayEmail, defaultValues: {
|
|
613
673
|
name: displayName ?? "",
|
|
@@ -626,7 +686,9 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
|
|
|
626
686
|
...values.emails,
|
|
627
687
|
],
|
|
628
688
|
}),
|
|
629
|
-
catch: () => new
|
|
689
|
+
catch: () => new UserAccountActionError({
|
|
690
|
+
message: m.user_contact_validation_error(),
|
|
691
|
+
}),
|
|
630
692
|
});
|
|
631
693
|
const imageFile = isFile(values.image) ? values.image : null;
|
|
632
694
|
const image = imageFile
|
|
@@ -703,7 +765,7 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
|
|
|
703
765
|
await accountCache.reload();
|
|
704
766
|
setRevokingAccount(null);
|
|
705
767
|
} })) : totpSetup ? (_jsx(VerifyTotpSetup, { baseUrl: resolvedBaseUrl, setup: totpSetup, onVerified: async () => {
|
|
706
|
-
await
|
|
768
|
+
await Effect.runPromise(refreshAuthSession(registry, resolvedBaseUrl));
|
|
707
769
|
setTotpSetup(null);
|
|
708
770
|
setManagingTwoFactor(false);
|
|
709
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)
|
|
@@ -779,7 +841,6 @@ function PasswordSettings({ onSetupPassword, onRevokeAccount, onChangePassword,
|
|
|
779
841
|
function ChangePasswordForm({ baseUrl, onResetPassword, }) {
|
|
780
842
|
const m = useUserButtonMessages();
|
|
781
843
|
const [saved, setSaved] = useState(false);
|
|
782
|
-
let reset = () => { };
|
|
783
844
|
const [form] = useState(() => FormReact.make(changePasswordFormBuilder, {
|
|
784
845
|
runtime: authClientApi(baseUrl).runtime,
|
|
785
846
|
fields: { currentPassword: PasswordField, newPassword: PasswordField },
|
|
@@ -789,11 +850,18 @@ function ChangePasswordForm({ baseUrl, onResetPassword, }) {
|
|
|
789
850
|
currentPassword: decoded.currentPassword,
|
|
790
851
|
newPassword: decoded.newPassword,
|
|
791
852
|
},
|
|
792
|
-
})), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.tap(() => Effect.sync(() =>
|
|
793
|
-
|
|
794
|
-
|
|
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
|
+
}))),
|
|
795
859
|
}));
|
|
796
|
-
reset = useAtomSet(form.reset);
|
|
860
|
+
const reset = useAtomSet(form.reset);
|
|
861
|
+
useAtomSubscribe(form.submit, (result) => {
|
|
862
|
+
if (AsyncResult.isSuccess(result))
|
|
863
|
+
reset();
|
|
864
|
+
});
|
|
797
865
|
const submit = useAtomSet(form.submit);
|
|
798
866
|
const submitResult = useAtomValue(form.submit);
|
|
799
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) => {
|
|
@@ -813,9 +881,12 @@ function SetPasswordForm({ baseUrl, onSaved, }) {
|
|
|
813
881
|
mode: { validation: "onSubmit" },
|
|
814
882
|
onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.authExtra.setPassword({
|
|
815
883
|
payload: { newPassword: decoded.password },
|
|
816
|
-
})), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onSaved())), Effect.mapError((cause) =>
|
|
817
|
-
|
|
818
|
-
|
|
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
|
+
}))),
|
|
819
890
|
}));
|
|
820
891
|
const submit = useAtomSet(form.submit);
|
|
821
892
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -845,14 +916,20 @@ function RevokeAccountForm({ baseUrl, onResetPassword, account, requirePassword,
|
|
|
845
916
|
accountId: account.accountId,
|
|
846
917
|
},
|
|
847
918
|
})
|
|
848
|
-
.pipe(Effect.mapError((cause) =>
|
|
849
|
-
|
|
850
|
-
|
|
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
|
+
})));
|
|
851
925
|
yield* Effect.sync(notifyAuthChange);
|
|
852
926
|
yield* Effect.tryPromise(onRevoked);
|
|
853
|
-
}).pipe(Effect.mapError((cause) =>
|
|
854
|
-
|
|
855
|
-
|
|
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
|
+
}))),
|
|
856
933
|
}));
|
|
857
934
|
const submit = useAtomSet(form.submit);
|
|
858
935
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -886,9 +963,12 @@ const UserForm = ({ defaultValues, primaryEmail, error, onSubmit, }) => {
|
|
|
886
963
|
socials: ContactSocialsField,
|
|
887
964
|
},
|
|
888
965
|
mode: { validation: "onSubmit" },
|
|
889
|
-
onSubmit: (_, { decoded }) => onSubmit({ ...decoded, image: decoded.image ?? null }).pipe(Effect.mapError((cause) =>
|
|
890
|
-
|
|
891
|
-
|
|
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
|
+
}))),
|
|
892
972
|
}));
|
|
893
973
|
const submit = useAtomSet(form.submit);
|
|
894
974
|
return (_jsx(form.Initialize, { defaultValues: defaultValues, children: _jsx("form", { onSubmit: (event) => {
|
|
@@ -907,7 +987,7 @@ function AccountSecuritySettings({ baseUrl, onResetPassword, accountCache, onSet
|
|
|
907
987
|
const m = useUserButtonMessages();
|
|
908
988
|
const sessionAtom = authSessionAtom(baseUrl);
|
|
909
989
|
const sessionResult = useAtomValue(sessionAtom);
|
|
910
|
-
const
|
|
990
|
+
const registry = useContext(RegistryContext);
|
|
911
991
|
const session = AsyncResult.match(sessionResult, {
|
|
912
992
|
onInitial: () => null,
|
|
913
993
|
onFailure: () => null,
|
|
@@ -922,7 +1002,7 @@ function AccountSecuritySettings({ baseUrl, onResetPassword, accountCache, onSet
|
|
|
922
1002
|
? "text-destructive text-sm"
|
|
923
1003
|
: "text-muted-foreground text-sm", children: accountCache.error ?? m.user_loading() })) : twoFactorEnabled ? (_jsx(DisableTotpForm, { onResetPassword: onResetPassword, baseUrl: baseUrl, requirePassword: requirePassword, onDisabled: async () => {
|
|
924
1004
|
setMessage(m.user_two_factor_disabled_message());
|
|
925
|
-
await
|
|
1005
|
+
await Effect.runPromise(refreshAuthSession(registry, baseUrl));
|
|
926
1006
|
} })) : (_jsx(EnableTotpForm, { onResetPassword: onResetPassword, baseUrl: baseUrl, requirePassword: requirePassword, onEnabled: onSetup })), message ? (_jsx("p", { className: "text-muted-foreground text-sm", children: message })) : null] }));
|
|
927
1007
|
}
|
|
928
1008
|
function EnableTotpForm({ baseUrl, onResetPassword, requirePassword, onEnabled, }) {
|
|
@@ -936,9 +1016,12 @@ function EnableTotpForm({ baseUrl, onResetPassword, requirePassword, onEnabled,
|
|
|
936
1016
|
})), Effect.tap((result) => Effect.sync(() => onEnabled({
|
|
937
1017
|
totpURI: result.totpURI,
|
|
938
1018
|
backupCodes: Array.from(result.backupCodes),
|
|
939
|
-
}))), Effect.mapError((cause) =>
|
|
940
|
-
|
|
941
|
-
|
|
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
|
+
}))),
|
|
942
1025
|
}));
|
|
943
1026
|
const submit = useAtomSet(form.submit);
|
|
944
1027
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -966,9 +1049,12 @@ function VerifyTotpSetup({ baseUrl, setup, onVerified, }) {
|
|
|
966
1049
|
mode: { validation: "onSubmit" },
|
|
967
1050
|
onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorVerifyTotp({
|
|
968
1051
|
payload: { code: decoded.code.trim() },
|
|
969
|
-
})), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onVerified())), Effect.mapError((cause) =>
|
|
970
|
-
|
|
971
|
-
|
|
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
|
+
}))),
|
|
972
1058
|
}));
|
|
973
1059
|
const submit = useAtomSet(form.submit);
|
|
974
1060
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -986,9 +1072,12 @@ function DisableTotpForm({ baseUrl, onResetPassword, requirePassword, onDisabled
|
|
|
986
1072
|
mode: { validation: "onSubmit" },
|
|
987
1073
|
onSubmit: (_, { decoded }) => authHttpClient(baseUrl).pipe(Effect.flatMap((client) => client.auth.twoFactorDisable({
|
|
988
1074
|
payload: requirePassword ? { password: decoded.password } : {},
|
|
989
|
-
})), Effect.tap(() => Effect.sync(notifyAuthChange)), Effect.flatMap(() => Effect.tryPromise(() => onDisabled())), Effect.mapError((cause) =>
|
|
990
|
-
|
|
991
|
-
|
|
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
|
+
}))),
|
|
992
1081
|
}));
|
|
993
1082
|
const submit = useAtomSet(form.submit);
|
|
994
1083
|
const submitResult = useAtomValue(form.submit);
|
|
@@ -1027,39 +1116,48 @@ function ApiKeyManager({ baseUrl, active, locale, permissionLabels, permissions
|
|
|
1027
1116
|
onSuccess: () => null,
|
|
1028
1117
|
});
|
|
1029
1118
|
const loading = keysResult._tag === "Initial";
|
|
1030
|
-
const
|
|
1031
|
-
const
|
|
1032
|
-
permissionOptionsRef.current = permissionOptions;
|
|
1033
|
-
selectedPermissionsRef.current = selectedPermissions;
|
|
1119
|
+
const permissionOptionsAtom = useLatestAtom(permissionOptions);
|
|
1120
|
+
const selectedPermissionsAtom = useLatestAtom(selectedPermissions);
|
|
1034
1121
|
const [createForm] = useState(() => FormReact.make(apiKeyFormBuilder, {
|
|
1035
1122
|
runtime: authClientApi(baseUrl).runtime,
|
|
1036
1123
|
fields: { name: TextField, referrers: TextAreaField },
|
|
1037
1124
|
mode: { validation: "onSubmit" },
|
|
1038
|
-
onSubmit: (_, { decoded }) => Effect.gen(function* () {
|
|
1125
|
+
onSubmit: (_, { decoded, get }) => Effect.gen(function* () {
|
|
1039
1126
|
setCreatedKey(null);
|
|
1040
1127
|
const referrers = yield* Effect.try({
|
|
1041
1128
|
try: () => parseApiKeyReferrers(decoded.referrers, m.user_api_key_referrers_error()),
|
|
1042
|
-
catch: (cause) =>
|
|
1129
|
+
catch: (cause) => new UserAccountActionError({
|
|
1130
|
+
message: cause instanceof Error
|
|
1131
|
+
? cause.message
|
|
1132
|
+
: m.user_api_key_create_error(),
|
|
1133
|
+
cause,
|
|
1134
|
+
}),
|
|
1043
1135
|
});
|
|
1044
1136
|
const client = yield* authHttpClient(baseUrl);
|
|
1045
1137
|
return yield* client.authExtra.createApiKey({
|
|
1046
1138
|
payload: {
|
|
1047
1139
|
configId: "user",
|
|
1048
1140
|
name: decoded.name.trim(),
|
|
1049
|
-
permissions: getSelectedPermissionObject(
|
|
1141
|
+
permissions: getSelectedPermissionObject(get(permissionOptionsAtom), get(selectedPermissionsAtom)),
|
|
1050
1142
|
referrers,
|
|
1051
1143
|
},
|
|
1052
1144
|
});
|
|
1053
1145
|
}).pipe(Effect.tap((created) => Effect.sync(() => {
|
|
1054
1146
|
setCreatedKey(created.key);
|
|
1055
|
-
resetCreateForm();
|
|
1056
1147
|
setSelectedPermissions({});
|
|
1057
1148
|
refreshKeys();
|
|
1058
|
-
})), Effect.mapError((cause) =>
|
|
1059
|
-
|
|
1060
|
-
|
|
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
|
+
}))),
|
|
1061
1155
|
}));
|
|
1062
1156
|
const resetCreateForm = useAtomSet(createForm.reset);
|
|
1157
|
+
useAtomSubscribe(createForm.submit, (result) => {
|
|
1158
|
+
if (AsyncResult.isSuccess(result))
|
|
1159
|
+
resetCreateForm();
|
|
1160
|
+
});
|
|
1063
1161
|
const submitCreateForm = useAtomSet(createForm.submit);
|
|
1064
1162
|
const createSubmitResult = useAtomValue(createForm.submit);
|
|
1065
1163
|
const togglePermission = (id, checked) => {
|
|
@@ -12,7 +12,19 @@ export declare const ExtraApiGroup: HttpApiGroup.HttpApiGroup<"authExtra", HttpA
|
|
|
12
12
|
}>>, never, Schema.toCodecJson<Schema.Struct<{
|
|
13
13
|
readonly id: Schema.String;
|
|
14
14
|
readonly key: Schema.String;
|
|
15
|
-
}>>, Schema.toCodecJson<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError | typeof ExtraBadRequest>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"
|
|
15
|
+
}>>, Schema.toCodecJson<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError | typeof ExtraBadRequest>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"getAccountDeletionPlan", "GET", "/auth/account-deletion", never, never, never, never, Schema.toCodecJson<Schema.Struct<{
|
|
16
|
+
readonly projects: Schema.$Array<Schema.Struct<{
|
|
17
|
+
readonly id: Schema.String;
|
|
18
|
+
readonly name: Schema.String;
|
|
19
|
+
readonly ready: Schema.Boolean;
|
|
20
|
+
}>>;
|
|
21
|
+
readonly organizations: Schema.$Array<Schema.Struct<{
|
|
22
|
+
readonly id: Schema.String;
|
|
23
|
+
readonly name: Schema.String;
|
|
24
|
+
readonly personal: Schema.Boolean;
|
|
25
|
+
}>>;
|
|
26
|
+
readonly adminAccount: Schema.Boolean;
|
|
27
|
+
}>>, Schema.toCodecJson<typeof HttpApiError.Unauthorized | typeof HttpApiError.Forbidden | typeof HttpApiError.InternalServerError>, never, never> | HttpApiEndpoint.HttpApiEndpoint<"getOrganizationPublicProfile", "GET", "/auth/organization-profile", never, Schema.toCodecStringTree<Schema.Struct<{
|
|
16
28
|
readonly organizationId: Schema.String;
|
|
17
29
|
readonly locale: Schema.optional<Schema.Union<readonly [Schema.Literal<"en">, Schema.Literal<"fr">]>>;
|
|
18
30
|
}>>, never, never, Schema.toCodecJson<Schema.Struct<{
|
package/dist/extra/api.group.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
2
|
import { OpenApi } from "effect/http-api";
|
|
3
3
|
import { HttpApiEndpoint, HttpApiError, HttpApiGroup } from "effect/http-api";
|
|
4
|
-
import { ExtraBadRequest, ExtraAssociatedProjects, ExtraAssociatedProjectsQuery, ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraImageUploadMultipartPayload, ExtraOkResponse, ExtraOrganizationPublicProfile, ExtraOrganizationPublicProfileQuery, ExtraProjectPublicConfig, ExtraProjectPublicConfigQuery, ExtraSetPasswordPayload, ExtraUpdateApiKeyPayload, ExtraUploadedAsset, ExtraVerifyApiKeyPayload, ExtraVerifyApiKeyResponse, ExtraVerifyPasswordPayload, } from "./schema.js";
|
|
4
|
+
import { ExtraAccountDeletionPlan, ExtraBadRequest, ExtraAssociatedProjects, ExtraAssociatedProjectsQuery, ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraImageUploadMultipartPayload, ExtraOkResponse, ExtraOrganizationPublicProfile, ExtraOrganizationPublicProfileQuery, ExtraProjectPublicConfig, ExtraProjectPublicConfigQuery, ExtraSetPasswordPayload, ExtraUpdateApiKeyPayload, ExtraUploadedAsset, ExtraVerifyApiKeyPayload, ExtraVerifyApiKeyResponse, ExtraVerifyPasswordPayload, } from "./schema.js";
|
|
5
5
|
export * from "./schema.js";
|
|
6
6
|
export const ExtraApiGroup = HttpApiGroup.make("authExtra")
|
|
7
|
+
.add(HttpApiEndpoint.get("getAccountDeletionPlan", "/auth/account-deletion", {
|
|
8
|
+
success: ExtraAccountDeletionPlan,
|
|
9
|
+
error: [HttpApiError.Unauthorized, HttpApiError.Forbidden, HttpApiError.InternalServerError],
|
|
10
|
+
}))
|
|
7
11
|
.add(HttpApiEndpoint.get("getProjectPublicConfig", "/auth/project-config", {
|
|
8
12
|
query: ExtraProjectPublicConfigQuery.fields,
|
|
9
13
|
success: ExtraProjectPublicConfig,
|
package/dist/extra/schema.d.ts
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
2
|
import { Multipart } from "effect/http";
|
|
3
3
|
import { HttpApiSchema } from "effect/http-api";
|
|
4
|
+
export declare const ExtraAccountDeletionPlan: Schema.Struct<{
|
|
5
|
+
readonly projects: Schema.$Array<Schema.Struct<{
|
|
6
|
+
readonly id: Schema.String;
|
|
7
|
+
readonly name: Schema.String;
|
|
8
|
+
readonly ready: Schema.Boolean;
|
|
9
|
+
}>>;
|
|
10
|
+
readonly organizations: Schema.$Array<Schema.Struct<{
|
|
11
|
+
readonly id: Schema.String;
|
|
12
|
+
readonly name: Schema.String;
|
|
13
|
+
readonly personal: Schema.Boolean;
|
|
14
|
+
}>>;
|
|
15
|
+
readonly adminAccount: Schema.Boolean;
|
|
16
|
+
}>;
|
|
4
17
|
export declare const ExtraImageUploadPayload: Schema.Struct<{
|
|
5
18
|
readonly file: Schema.decodeTo<Multipart.PersistedFileSchema, Schema.$Array<Multipart.PersistedFileSchema>, never, never>;
|
|
6
19
|
}>;
|
|
@@ -175,7 +188,9 @@ export declare const ExtraUploadedAsset: Schema.Struct<{
|
|
|
175
188
|
}>;
|
|
176
189
|
declare const ExtraBadRequest_base: Schema.Class<ExtraBadRequest, Schema.TaggedStruct<"ExtraBadRequest", {
|
|
177
190
|
readonly message: Schema.String;
|
|
178
|
-
}>, import("effect/Cause").YieldableError
|
|
191
|
+
}>, import("effect/Cause").YieldableError & {
|
|
192
|
+
readonly brand: unique symbol;
|
|
193
|
+
}>;
|
|
179
194
|
export declare class ExtraBadRequest extends ExtraBadRequest_base {
|
|
180
195
|
}
|
|
181
196
|
export type ExtraImageUploadPayload = typeof ExtraImageUploadPayload.Type;
|
package/dist/extra/schema.js
CHANGED
|
@@ -2,6 +2,19 @@ import { Schema } from "effect";
|
|
|
2
2
|
import { Multipart } from "effect/http";
|
|
3
3
|
import { HttpApiSchema } from "effect/http-api";
|
|
4
4
|
import { OrganizationEmail, OrganizationLocale, OrganizationPhone, OrganizationSocial, OrganizationWebsite, FormattedOrganizationAddress, } from "../schema.js";
|
|
5
|
+
export const ExtraAccountDeletionPlan = Schema.Struct({
|
|
6
|
+
projects: Schema.Array(Schema.Struct({
|
|
7
|
+
id: Schema.String,
|
|
8
|
+
name: Schema.String,
|
|
9
|
+
ready: Schema.Boolean,
|
|
10
|
+
})),
|
|
11
|
+
organizations: Schema.Array(Schema.Struct({
|
|
12
|
+
id: Schema.String,
|
|
13
|
+
name: Schema.String,
|
|
14
|
+
personal: Schema.Boolean,
|
|
15
|
+
})),
|
|
16
|
+
adminAccount: Schema.Boolean,
|
|
17
|
+
}).annotate({ identifier: "ExtraAccountDeletionPlan" });
|
|
5
18
|
export const ExtraImageUploadPayload = Schema.Struct({
|
|
6
19
|
file: Multipart.SingleFileSchema,
|
|
7
20
|
}).annotate({
|
|
@@ -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
|
+
});
|