@krak-stack/auth 0.2.30 → 0.2.32

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 (42) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +79 -1
  3. package/dist/admin/api.group.d.ts +94 -0
  4. package/dist/admin/api.group.js +3 -3
  5. package/dist/admin/schema.d.ts +215 -0
  6. package/dist/admin/schema.js +39 -1
  7. package/dist/api.d.ts +1531 -1377
  8. package/dist/auth/api.group.d.ts +19 -1
  9. package/dist/auth/api.group.js +17 -1
  10. package/dist/auth/schema.d.ts +12 -0
  11. package/dist/auth/schema.js +12 -0
  12. package/dist/components/account-deletion-request.d.ts +5 -0
  13. package/dist/components/account-deletion-request.js +7 -0
  14. package/dist/components/account-deletion.d.ts +8 -0
  15. package/dist/components/account-deletion.js +59 -0
  16. package/dist/components/admin-organizations.js +13 -3
  17. package/dist/components/admin-users.js +18 -1
  18. package/dist/components/associated-projects-notice.js +1 -1
  19. package/dist/components/auth-client-api.d.ts +127 -0
  20. package/dist/components/deletion-visibility.d.ts +1 -0
  21. package/dist/components/deletion-visibility.js +3 -0
  22. package/dist/components/organization-deletion-request.d.ts +17 -0
  23. package/dist/components/organization-deletion-request.js +9 -0
  24. package/dist/components/organization-switcher.js +31 -2
  25. package/dist/components/user-button.d.ts +29 -1
  26. package/dist/components/user-button.js +39 -2
  27. package/dist/extra/api.group.d.ts +13 -1
  28. package/dist/extra/api.group.js +5 -1
  29. package/dist/extra/schema.d.ts +13 -0
  30. package/dist/extra/schema.js +13 -0
  31. package/dist/schema.d.ts +35 -0
  32. package/dist/schema.js +25 -0
  33. package/dist/server/index.d.ts +2 -1
  34. package/dist/server/index.js +1 -0
  35. package/dist/server/middleware.d.ts +10 -2
  36. package/dist/server/middleware.js +4 -1
  37. package/dist/server/webhook-layer.d.ts +6 -0
  38. package/dist/server/webhook-layer.js +37 -0
  39. package/dist/server/webhooks.d.ts +38 -0
  40. package/dist/server/webhooks.js +39 -0
  41. package/dist/service.d.ts +66 -0
  42. package/package.json +7 -3
@@ -12,6 +12,7 @@ import { AppBrand } from "@krak-stack/registry/app-brand";
12
12
  import { FieldSet } from "@/components/ui/field";
13
13
  import { Badge } from "@/components/ui/badge";
14
14
  import { Button } from "@/components/ui/button";
15
+ import { AlertDialog, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
15
16
  import { CopyButton } from "@krak-stack/registry/copy-button";
16
17
  import { Dialog, DialogFooter, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
17
18
  import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu";
@@ -19,6 +20,9 @@ import { Separator } from "@/components/ui/separator";
19
20
  import { OrganizationEmail, OrganizationAddress, OrganizationMetadata, OrganizationPhone, OrganizationSocial, OrganizationTranslation, OrganizationWebsite, decodeOrganizationMetadata, } from "@krak-stack/auth/schema";
20
21
  import { isOrganizationRole, normalizeOrganizationRole, normalizeOrganizationRoles, organizationRoles, parseRoleList, } from "../roles.js";
21
22
  import { authClientApi, authHttpClient } from "./auth-client-api.js";
23
+ import { adminOrganizationsMessages } from "./admin-organizations.js";
24
+ import { deletionControlsEnabled } from "./deletion-visibility.js";
25
+ import { canDeleteOrganization, requestOrganizationDeletion, } from "./organization-deletion-request.js";
22
26
  import { activeAuthOrganizationAtom, authOrganizationsAtom, authSessionAtom, notifyAuthChange, refreshOnAuthChange, } from "./auth-atoms.js";
23
27
  import { useKrakstackAuth } from "./auth-provider.js";
24
28
  import { parseApiKeyReferrers } from "./api-key.js";
@@ -749,6 +753,8 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
749
753
  payload: { organizationId },
750
754
  })));
751
755
  const [uncontrolledDialog, setUncontrolledDialog] = useState(defaultDialog);
756
+ const [deletingOrganization, setDeletingOrganization] = useState(null);
757
+ const deletionLabels = adminOrganizationsMessages(auth?.locale ?? "en");
752
758
  const [editingOrganizationLocale, setEditingOrganizationLocale] = useState(currentOrganizationLocale);
753
759
  const dialog = controlledDialog !== undefined ? controlledDialog : uncontrolledDialog;
754
760
  const invitationsAtom = userInvitationsAtom(baseUrl);
@@ -818,7 +824,7 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
818
824
  ? { imageSrc: activeDisplay.image }
819
825
  : {}) }), _jsx(ChevronsUpDown, { className: "text-muted-foreground size-4 shrink-0 group-data-[collapsible=icon]:hidden" })] }) }), _jsx(DropdownMenuContent, { className: "max-w-[calc(100vw-1rem)] min-w-64 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: activeDisplay.name, subtitle: activeSubtitle, icon: Building2, variant: "sidebar", className: "px-1 py-1.5 text-left text-sm", ...(activeDisplay.image
820
826
  ? { imageSrc: activeDisplay.image }
821
- : {}) }) }), active ? (_jsx("div", { className: "px-1 py-2", children: _jsx(AssociatedProjectsNotice, { baseUrl: baseUrl, getSummary: (count) => m.organization_projects_summary({ count }), organizationId: active.id, viewLabel: m.organization_projects_view() }) })) : null, menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizationsResult._tag === "Initial" ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizationsError ? (_jsx(DropdownMenuItem, { disabled: true, children: organizationsError })) : null, canSwitchOrganizations && selectableOrganizations.length ? (_jsx("div", { className: cn(scrollOrganizationList &&
827
+ : {}) }) }), active ? (_jsx(AssociatedProjectsNotice, { baseUrl: baseUrl, getSummary: (count) => m.organization_projects_summary({ count }), organizationId: active.id, viewLabel: m.organization_projects_view() })) : null, menuActions ? (_jsxs(_Fragment, { children: [_jsx(DropdownMenuSeparator, {}), menuActions] })) : null, hasOrganizationListItems ? _jsx(DropdownMenuSeparator, {}) : null, organizationsResult._tag === "Initial" ? (_jsx(DropdownMenuItem, { disabled: true, children: m.organization_loading() })) : null, organizationsError ? (_jsx(DropdownMenuItem, { disabled: true, children: organizationsError })) : null, canSwitchOrganizations && selectableOrganizations.length ? (_jsx("div", { className: cn(scrollOrganizationList &&
822
828
  "max-h-64 overflow-y-auto overscroll-contain"), children: selectableOrganizations.map((organization) => {
823
829
  const display = organizationDisplay(organization, m, baseUrl);
824
830
  return (_jsx(DropdownMenuItem, { onClick: async () => {
@@ -845,7 +851,15 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
845
851
  return (_jsxs(DropdownMenuItem, { onClick: () => {
846
852
  void navigator.clipboard.writeText(organizationId);
847
853
  }, children: [_jsx(Copy, {}), m.organization_copy_id()] }));
848
- })(), canUpdateOrganization ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("manage"), children: [_jsx(PencilIcon, {}), m.organization_switcher_manage()] })) : null, _jsxs(DropdownMenuItem, { onClick: () => setDialog("members"), children: [_jsx(Users, {}), m.organization_members_title()] }), canManageApiKeys ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] })) : null] })) : null] }) })] })), _jsx(Dialog, { open: dialog === "create" && canCreateOrganization, onOpenChange: (open) => {
854
+ })(), canUpdateOrganization ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("manage"), children: [_jsx(PencilIcon, {}), m.organization_switcher_manage()] })) : null, _jsxs(DropdownMenuItem, { onClick: () => setDialog("members"), children: [_jsx(Users, {}), m.organization_members_title()] }), canManageApiKeys ? (_jsxs(DropdownMenuItem, { onClick: () => setDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] })) : null, deletionControlsEnabled &&
855
+ canDeleteOrganization(activeOrganization, session.user.id) ? (_jsxs(DropdownMenuItem, { variant: "destructive", onClick: () => setDeletingOrganization({
856
+ id: activeOrganization.id,
857
+ name: activeOrganization.name,
858
+ }), children: [_jsx(Trash2, {}), deletionLabels.organization_action_delete] })) : null] })) : null] }) })] })), deletionControlsEnabled && deletingOrganization ? (_jsx(OrganizationDeletionDialog, { baseUrl: baseUrl, organization: deletingOrganization, onClose: () => setDeletingOrganization(null), onDeleted: () => {
859
+ setDeletingOrganization(null);
860
+ setDialog(null);
861
+ onChange?.(null);
862
+ } }, deletingOrganization.id)) : null, _jsx(Dialog, { open: dialog === "create" && canCreateOrganization, onOpenChange: (open) => {
849
863
  setDialog((current) => open ? "create" : current === "create" ? null : current);
850
864
  }, children: _jsx(CreateOrganizationSection, { header: _jsxs(DialogHeader, { className: "sm:flex-row sm:items-end sm:justify-between sm:gap-4", children: [_jsxs("div", { className: "flex min-w-0 flex-col gap-2", children: [_jsx(DialogTitle, { className: "text-2xl", children: m.organization_create_title() }), _jsx(DialogDescription, { children: m.organization_create_description() })] }), _jsx("div", { className: "mt-2 w-fit sm:mt-0", children: _jsx(EditingLocaleSwitcher, { locale: auth?.locale, value: editingOrganizationLocale, onValueChange: (value) => setEditingOrganizationLocale(value === "fr" ? "fr" : "en") }) })] }), baseUrl: baseUrl, editingLocale: editingOrganizationLocale, onCreated: async (organization) => {
851
865
  setDialog(null);
@@ -879,6 +893,21 @@ export function OrganizationSwitcher({ baseUrl: providedBaseUrl, side = "bottom"
879
893
  ? { activeOrganizationId: activeOrganization.id }
880
894
  : {}), onActionComplete: refreshAfterInvitationAction }) })] }) })] }));
881
895
  }
896
+ const OrganizationDeletionDialog = ({ baseUrl, organization, onClose, onDeleted, }) => {
897
+ const auth = useKrakstackAuth();
898
+ const labels = adminOrganizationsMessages(auth?.locale ?? "en");
899
+ // Cross-project deletion cannot be predicted or rolled back on the client.
900
+ const [mutation] = useState(() => authClientApi(baseUrl).runtime.fn(() => requestOrganizationDeletion(organization.id, baseUrl).pipe(Effect.tap(() => Effect.sync(() => {
901
+ notifyAuthChange();
902
+ onDeleted();
903
+ })))));
904
+ const remove = useAtomSet(mutation);
905
+ const result = useAtomValue(mutation);
906
+ return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => {
907
+ if (!open && !result.waiting)
908
+ onClose();
909
+ }, children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: labels.organization_delete_title }), _jsx(AlertDialogDescription, { children: labels.organization_delete_description.replace("{name}", organization.name) })] }), AsyncResult.isFailure(result) ? (_jsx("p", { role: "alert", children: labels.organization_delete_error })) : null, _jsxs(AlertDialogFooter, { children: [_jsx(Button, { type: "button", variant: "outline", disabled: result.waiting, onClick: onClose, children: labels.organization_delete_cancel }), _jsx(Button, { type: "button", variant: "destructive", disabled: result.waiting, onClick: () => remove(), children: labels.organization_delete_confirm })] })] }) }));
910
+ };
882
911
  function UserInvitationsManager({ baseUrl, invitations, loading, error, activeOrganizationId, onActionComplete, }) {
883
912
  const m = useOrganizationMessages();
884
913
  const [actingInvitationId, setActingInvitationId] = useState(null);
@@ -4,6 +4,20 @@ import { DropdownMenuContent } from "@/components/ui/dropdown-menu";
4
4
  import { type ContactEmail as ContactEmailValue, type ContactPhone as ContactPhoneValue, type ContactSocial as ContactSocialValue, type ContactWebsite as ContactWebsiteValue, UserMetadata } from "../schema.js";
5
5
  declare const messages: {
6
6
  readonly en: {
7
+ readonly user_delete_title: "Delete account";
8
+ readonly user_delete_description: "Permanently delete your account and unshared personal organizations. This cannot be undone.";
9
+ readonly user_delete_projects: "Connected projects";
10
+ readonly user_delete_organizations: "Organizations to resolve";
11
+ readonly user_delete_retention: "Project cleanup is requested separately. Legal retention may apply.";
12
+ readonly user_delete_missing: "Some projects need support to complete cleanup.";
13
+ readonly user_delete_owner: "Transfer ownership or delete these in the organization switcher. Shared personal organizations need support.";
14
+ readonly user_delete_admin: "Remove your platform admin role before continuing.";
15
+ readonly user_delete_confirm: "Type DELETE to confirm";
16
+ readonly user_delete_password: "Current password (if required)";
17
+ readonly user_delete_error: "Unable to delete your account. Check your password, or sign in again and retry.";
18
+ readonly user_delete_load_error: "Loading requirements… Close and retry if this takes too long.";
19
+ readonly user_delete_complete: "Your account is deleted. Project cleanup may still be pending; retained records are not necessarily erased.";
20
+ readonly user_delete_done: "Done";
7
21
  readonly table_empty: "No results.";
8
22
  readonly user_account_cancel: "Cancel";
9
23
  readonly user_account_back: "Back";
@@ -149,6 +163,20 @@ declare const messages: {
149
163
  readonly user_two_factor_verify_error: "Could not verify the code.";
150
164
  };
151
165
  readonly fr: {
166
+ readonly user_delete_title: "Supprimer le compte";
167
+ readonly user_delete_description: "Supprimez définitivement votre compte et vos organisations personnelles non partagées. Cette action est irréversible.";
168
+ readonly user_delete_projects: "Projets liés";
169
+ readonly user_delete_organizations: "Organisations à régler";
170
+ readonly user_delete_retention: "Le nettoyage des projets est demandé séparément. Une conservation légale peut s’appliquer.";
171
+ readonly user_delete_missing: "Certains projets nécessitent l’assistance pour terminer le nettoyage.";
172
+ readonly 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.";
173
+ readonly user_delete_admin: "Retirez votre rôle administrateur de plateforme avant de continuer.";
174
+ readonly user_delete_confirm: "Saisissez DELETE pour confirmer";
175
+ readonly user_delete_password: "Mot de passe actuel (si nécessaire)";
176
+ readonly user_delete_error: "Impossible de supprimer le compte. Vérifiez votre mot de passe ou reconnectez-vous, puis réessayez.";
177
+ readonly user_delete_load_error: "Chargement des conditions… Fermez et réessayez si l’attente se prolonge.";
178
+ readonly 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.";
179
+ readonly user_delete_done: "Terminé";
152
180
  readonly table_empty: "Aucun résultat.";
153
181
  readonly user_account_cancel: "Annuler";
154
182
  readonly user_account_back: "Retour";
@@ -350,6 +378,6 @@ export type UserButtonProps = {
350
378
  dialog?: UserButtonDialog | null;
351
379
  onDialogChange?: (dialog: UserButtonDialog | null) => void;
352
380
  };
353
- export type UserButtonDialog = "account" | "security" | "apiKeys" | "adminUsers" | "adminOrganizations";
381
+ export type UserButtonDialog = "deleteAccount" | "account" | "security" | "apiKeys" | "adminUsers" | "adminOrganizations";
354
382
  export declare const UserButton: ({ baseUrl, signOutRedirect, side, defaultDialog, hideTrigger, renderUnauthenticated, menuActions, apiKeyPermissions, messages, dialog: controlledDialog, onDialogChange, }: UserButtonProps) => import("react").JSX.Element;
355
383
  export {};
@@ -36,10 +36,26 @@ import { AdminOrganizationsTable } from "./admin-organizations.js";
36
36
  import { AdminUsersTable } from "./admin-users.js";
37
37
  import { ScrollableDialogBody, ScrollableDialogContent, ScrollableDialogHeader, } from "./scrollable-dialog.js";
38
38
  import { AssociatedProjectsNotice } from "./associated-projects-notice.js";
39
+ import { AccountDeletionDialog } from "./account-deletion.js";
40
+ import { deletionControlsEnabled } from "./deletion-visibility.js";
39
41
  import { ContactEmailsField, ContactPhonesField, ContactSocialsField, ContactWebsitesField, } from "./contact-fields.js";
40
42
  import { decodeUserMetadata, ContactLocale, SocialPlatform, USER_CONTACT_LIMIT, UserMetadata, } from "../schema.js";
41
43
  const messages = {
42
44
  en: {
45
+ user_delete_title: "Delete account",
46
+ user_delete_description: "Permanently delete your account and unshared personal organizations. This cannot be undone.",
47
+ user_delete_projects: "Connected projects",
48
+ user_delete_organizations: "Organizations to resolve",
49
+ user_delete_retention: "Project cleanup is requested separately. Legal retention may apply.",
50
+ user_delete_missing: "Some projects need support to complete cleanup.",
51
+ user_delete_owner: "Transfer ownership or delete these in the organization switcher. Shared personal organizations need support.",
52
+ user_delete_admin: "Remove your platform admin role before continuing.",
53
+ user_delete_confirm: "Type DELETE to confirm",
54
+ user_delete_password: "Current password (if required)",
55
+ user_delete_error: "Unable to delete your account. Check your password, or sign in again and retry.",
56
+ user_delete_load_error: "Loading requirements… Close and retry if this takes too long.",
57
+ user_delete_complete: "Your account is deleted. Project cleanup may still be pending; retained records are not necessarily erased.",
58
+ user_delete_done: "Done",
43
59
  table_empty: "No results.",
44
60
  user_account_cancel: "Cancel",
45
61
  user_account_back: "Back",
@@ -185,6 +201,20 @@ const messages = {
185
201
  user_two_factor_verify_error: "Could not verify the code.",
186
202
  },
187
203
  fr: {
204
+ user_delete_title: "Supprimer le compte",
205
+ user_delete_description: "Supprimez définitivement votre compte et vos organisations personnelles non partagées. Cette action est irréversible.",
206
+ user_delete_projects: "Projets liés",
207
+ user_delete_organizations: "Organisations à régler",
208
+ user_delete_retention: "Le nettoyage des projets est demandé séparément. Une conservation légale peut s’appliquer.",
209
+ user_delete_missing: "Certains projets nécessitent l’assistance pour terminer le nettoyage.",
210
+ 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.",
211
+ user_delete_admin: "Retirez votre rôle administrateur de plateforme avant de continuer.",
212
+ user_delete_confirm: "Saisissez DELETE pour confirmer",
213
+ user_delete_password: "Mot de passe actuel (si nécessaire)",
214
+ user_delete_error: "Impossible de supprimer le compte. Vérifiez votre mot de passe ou reconnectez-vous, puis réessayez.",
215
+ user_delete_load_error: "Chargement des conditions… Fermez et réessayez si l’attente se prolonge.",
216
+ 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.",
217
+ user_delete_done: "Terminé",
188
218
  table_empty: "Aucun résultat.",
189
219
  user_account_cancel: "Annuler",
190
220
  user_account_back: "Retour",
@@ -603,11 +633,18 @@ export const UserButton = ({ baseUrl, signOutRedirect = "/", side = "bottom", de
603
633
  : `${import.meta.env.VITE_SITE_URL}${signOutRedirect.startsWith("/") ? signOutRedirect : `/${signOutRedirect}`}`;
604
634
  signOut({ baseUrl: resolvedBaseUrl, redirectUrl });
605
635
  };
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("div", { className: "px-1 py-2", children: _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, (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({
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({
607
637
  baseUrl: resolvedBaseUrl,
608
638
  currentSiteHref,
609
639
  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] }) })] })), _jsx(Dialog, { open: canManageUserSettings && settingsDialog === "account", onOpenChange: (open) => {
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) => {
611
648
  setSettingsDialog((current) => open ? "account" : current === "account" ? null : current);
612
649
  }, children: _jsx(UserForm, { primaryEmail: displayEmail, defaultValues: {
613
650
  name: displayName ?? "",
@@ -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<"getOrganizationPublicProfile", "GET", "/auth/organization-profile", never, Schema.toCodecStringTree<Schema.Struct<{
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<{
@@ -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,
@@ -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
  }>;
@@ -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({
package/dist/schema.d.ts CHANGED
@@ -1,4 +1,39 @@
1
1
  import { Schema } from "effect";
2
+ export declare const AuthWebhookData: Schema.StructWithRest<Schema.Struct<{
3
+ readonly projectId: Schema.NonEmptyString;
4
+ }>, readonly [Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
5
+ export declare const AuthWebhook: Schema.Struct<{
6
+ readonly event: Schema.NonEmptyString;
7
+ readonly data: Schema.StructWithRest<Schema.Struct<{
8
+ readonly projectId: Schema.NonEmptyString;
9
+ }>, readonly [Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>;
10
+ }>;
11
+ export declare const AccountDeletionData: Schema.Struct<{
12
+ readonly projectId: Schema.NonEmptyString;
13
+ readonly userId: Schema.NonEmptyString;
14
+ readonly scope: Schema.Literal<"account">;
15
+ }>;
16
+ export declare const AccountDeletionWebhook: Schema.Struct<{
17
+ readonly event: Schema.Literal<"user.deletion_requested">;
18
+ readonly data: Schema.Struct<{
19
+ readonly projectId: Schema.NonEmptyString;
20
+ readonly userId: Schema.NonEmptyString;
21
+ readonly scope: Schema.Literal<"account">;
22
+ }>;
23
+ }>;
24
+ export declare const OrganizationDeletionData: Schema.Struct<{
25
+ readonly projectId: Schema.NonEmptyString;
26
+ readonly organizationId: Schema.NonEmptyString;
27
+ readonly scope: Schema.Literal<"organization">;
28
+ }>;
29
+ export declare const OrganizationDeletionWebhook: Schema.Struct<{
30
+ readonly event: Schema.Literal<"organization.deletion_requested">;
31
+ readonly data: Schema.Struct<{
32
+ readonly projectId: Schema.NonEmptyString;
33
+ readonly organizationId: Schema.NonEmptyString;
34
+ readonly scope: Schema.Literal<"organization">;
35
+ }>;
36
+ }>;
2
37
  export declare const Session: Schema.Struct<{
3
38
  readonly id: Schema.String;
4
39
  readonly expiresAt: Schema.Date;
package/dist/schema.js CHANGED
@@ -1,4 +1,29 @@
1
1
  import { Option, Schema, SchemaGetter } from "effect";
2
+ export const AuthWebhookData = Schema.StructWithRest(Schema.Struct({
3
+ projectId: Schema.NonEmptyString,
4
+ }), [Schema.Record(Schema.String, Schema.Json)]).annotate({ identifier: "AuthWebhookData" });
5
+ export const AuthWebhook = Schema.Struct({
6
+ event: Schema.NonEmptyString,
7
+ data: AuthWebhookData,
8
+ }).annotate({ identifier: "AuthWebhook" });
9
+ export const AccountDeletionData = Schema.Struct({
10
+ projectId: Schema.NonEmptyString,
11
+ userId: Schema.NonEmptyString,
12
+ scope: Schema.Literal("account"),
13
+ }).annotate({ identifier: "AccountDeletionData" });
14
+ export const AccountDeletionWebhook = Schema.Struct({
15
+ event: Schema.Literal("user.deletion_requested"),
16
+ data: AccountDeletionData,
17
+ }).annotate({ identifier: "AccountDeletionWebhook" });
18
+ export const OrganizationDeletionData = Schema.Struct({
19
+ projectId: Schema.NonEmptyString,
20
+ organizationId: Schema.NonEmptyString,
21
+ scope: Schema.Literal("organization"),
22
+ }).annotate({ identifier: "OrganizationDeletionData" });
23
+ export const OrganizationDeletionWebhook = Schema.Struct({
24
+ event: Schema.Literal("organization.deletion_requested"),
25
+ data: OrganizationDeletionData,
26
+ }).annotate({ identifier: "OrganizationDeletionWebhook" });
2
27
  export const Session = Schema.Struct({
3
28
  id: Schema.String,
4
29
  expiresAt: Schema.Date,
@@ -1,4 +1,5 @@
1
1
  export { AuthService } from "../service.js";
2
+ export { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, OrganizationDeletionWebhook, AuthWebhook, AuthWebhookData, } from "../schema.js";
2
3
  export type { AuthSession, AuthSessionWithOrganization, AuthSessionWithUser, AuthSessionWithUserAndOrganization, } from "../service.js";
3
4
  export { AuthClientConfig } from "../config.js";
4
5
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group.js";
@@ -8,7 +9,7 @@ export { AuthProxyError, authProxyKeyHeader, proxyOriginHeaders, readProxyOrigin
8
9
  export { ActorRequired } from "./actor.js";
9
10
  export type { ActorConstraint } from "./actor.js";
10
11
  export { ApiKeySecurity, AuthMiddleware, makeAuthenticationLive, } from "./middleware.js";
11
- export type { AuthenticationLiveOptions, AuthRouterOptions, } from "./middleware.js";
12
+ export type { AuthMiddlewareOptions, AuthenticationLiveOptions, AuthRouterOptions, } from "./middleware.js";
12
13
  export { ServerActiveOrganization, ServerCreateDomainPayload, ServerDomain, ServerDomainHostParams, ServerDomainIdParams, ServerDomainRecordsResponse, ServerMembersResponse, ServerOrganizationChildrenResponse, ServerOrganizationsResponse, ServerUpdateDomainPayload, ServerUsersResponse, } from "./schema.js";
13
14
  export type { Member, Organization, OrganizationMetadata, User, } from "../schema.js";
14
15
  export { ApiKeyPermissionGrant, CurrentActor, Forbidden, all, actorUserId, any, defineProjectAccess, permission, policy, withPolicy, } from "../access.js";
@@ -1,4 +1,5 @@
1
1
  export { AuthService } from "../service.js";
2
+ export { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, OrganizationDeletionWebhook, AuthWebhook, AuthWebhookData, } from "../schema.js";
2
3
  export { AuthClientConfig } from "../config.js";
3
4
  export { ServerDomainsApiGroup, ServerOrganizationsApiGroup, ServerUsersApiGroup, } from "./api.group.js";
4
5
  export { proxyAuthHttpEffect, proxyAuthRequest, proxyAuthRequestEffect, } from "./proxy.js";
@@ -1,7 +1,8 @@
1
- import { Layer } from "effect";
1
+ import { Effect, Layer, Redacted } from "effect";
2
2
  import { HttpRouter, HttpServerRequest } from "effect/http";
3
3
  import { HttpApiError, HttpApiMiddleware, HttpApiSecurity } from "effect/http-api";
4
4
  import { AuthService, type AuthServiceLayerOptions } from "../service.js";
5
+ import type { AccountDeletionData, OrganizationDeletionData, AuthWebhook } from "../schema.js";
5
6
  export declare const ApiKeySecurity: HttpApiSecurity.ApiKey;
6
7
  declare const AuthMiddleware_base: HttpApiMiddleware.ServiceClass<AuthMiddleware, "@krak-stack/auth/AuthMiddleware", {
7
8
  requires: never;
@@ -16,7 +17,7 @@ declare const AuthMiddleware_base: HttpApiMiddleware.ServiceClass<AuthMiddleware
16
17
  readonly apiKey: HttpApiSecurity.ApiKey;
17
18
  }, AuthService, readonly [typeof HttpApiError.Unauthorized, typeof HttpApiError.Forbidden, typeof HttpApiError.ServiceUnavailable], never>>;
18
19
  export declare class AuthMiddleware extends AuthMiddleware_base {
19
- static readonly layer: (options?: AuthenticationLiveOptions | Layer.Layer<AuthService, unknown>) => Layer.Layer<AuthMiddleware, never, never>;
20
+ static readonly layer: <E, R>(options: AuthMiddlewareOptions<E, R>) => Layer.Layer<AuthMiddleware, import("./webhooks.js").AuthWebhookConfigurationError | import("effect/Config").ConfigError | import("effect/sql/Migrator").MigrationError | import("effect/Schema").SchemaError | import("effect/sql/SqlError").SqlError, HttpRouter.HttpRouter | import("effect/sql/SqlClient").SqlClient | Exclude<Exclude<R, import("effect/Scope").Scope>, import("@krak-stack/registry/webhooks").WebhooksReceiver>>;
20
21
  /** The same optional authentication and attribution for plain HttpRouter routes. */
21
22
  static readonly routerLayer: (options?: AuthRouterOptions) => Layer.Layer<never, import("effect/Config").ConfigError, HttpRouter.Request<"Error", HttpApiError.Forbidden> | HttpRouter.Request<"Error", HttpApiError.ServiceUnavailable>>;
22
23
  }
@@ -27,6 +28,13 @@ export type AuthenticationLiveOptions = AuthServiceLayerOptions & {
27
28
  }[];
28
29
  readonly authLayer?: Layer.Layer<AuthService, unknown, HttpServerRequest.HttpServerRequest>;
29
30
  };
31
+ export type AuthMiddlewareOptions<E, R> = AuthenticationLiveOptions & {
32
+ readonly projectId?: string;
33
+ readonly webhookSecret?: Redacted.Redacted<string>;
34
+ readonly onDeleteUser: (data: typeof AccountDeletionData.Type) => Effect.Effect<void, E, R>;
35
+ readonly onDeleteOrganization: (data: typeof OrganizationDeletionData.Type) => Effect.Effect<void, E, R>;
36
+ readonly onWebhook?: (webhook: typeof AuthWebhook.Type) => Effect.Effect<void, E, R>;
37
+ };
30
38
  export type AuthRouterOptions = AuthenticationLiveOptions & {
31
39
  /** Resolve auth only for these exact URL pathnames. Defaults to every route in scope. */
32
40
  readonly paths?: readonly string[];
@@ -18,7 +18,10 @@ export class AuthMiddleware extends HttpApiMiddleware.Service()("@krak-stack/aut
18
18
  apiKey: ApiKeySecurity,
19
19
  },
20
20
  }) {
21
- static layer = (options = {}) => makeAuthenticationLive(options);
21
+ static layer = (options) => Layer.merge(makeAuthenticationLive(options), Layer.unwrap(
22
+ // API contracts also import this class in the browser. Load persistence
23
+ // only when the server acquires its implementation layer.
24
+ Effect.promise(() => import("./webhook-layer.js")).pipe(Effect.map(({ makeAuthWebhookLayer }) => makeAuthWebhookLayer(options)))));
22
25
  /** The same optional authentication and attribution for plain HttpRouter routes. */
23
26
  static routerLayer = (options = {}) => HttpRouter.middleware(Effect.gen(function* () {
24
27
  const config = options.authLayer
@@ -0,0 +1,6 @@
1
+ import { Config, Layer, Schema } from "effect";
2
+ import { HttpRouter } from "effect/http";
3
+ import { WebhooksReceiver } from "@krak-stack/registry/webhooks";
4
+ import type { AuthMiddlewareOptions } from "./middleware.js";
5
+ import { AuthWebhookConfigurationError } from "./webhooks.js";
6
+ export declare const makeAuthWebhookLayer: <E, R>(options: AuthMiddlewareOptions<E, R>) => Layer.Layer<never, AuthWebhookConfigurationError | Config.ConfigError | import("effect/sql/Migrator").MigrationError | Schema.SchemaError | import("effect/sql/SqlError").SqlError, HttpRouter.HttpRouter | import("effect/sql/SqlClient").SqlClient | Exclude<Exclude<R, import("effect/Scope").Scope>, WebhooksReceiver>>;
@@ -0,0 +1,37 @@
1
+ import { ByteSize, Config, Effect, Layer, Redacted, Schema } from "effect";
2
+ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
3
+ import { WebhooksReceiver } from "@krak-stack/registry/webhooks";
4
+ import { AuthWebhookCleanupError, AuthWebhookConfigurationError, receiveAuthWebhook, } from "./webhooks.js";
5
+ export const makeAuthWebhookLayer = (options) => Layer.unwrap(Effect.gen(function* () {
6
+ const receiver = yield* WebhooksReceiver;
7
+ const services = yield* Effect.context();
8
+ const projectId = yield* Schema.decodeUnknownEffect(Schema.NonEmptyString)(options.projectId ??
9
+ (yield* Config.NonEmptyString("VITE_KRAKSTACK_AUTH_PROJECT_ID")));
10
+ const secret = options.webhookSecret ??
11
+ (yield* Config.Redacted("KRAKSTACK_AUTH_WEBHOOK_SECRET"));
12
+ if (!Schema.is(Schema.String.check(Schema.isMinLength(32)))(Redacted.value(secret))) {
13
+ return yield* new AuthWebhookConfigurationError({
14
+ message: "The auth webhook signing secret must contain at least 32 characters",
15
+ });
16
+ }
17
+ const onWebhook = options.onWebhook;
18
+ const handle = Effect.gen(function* () {
19
+ const request = yield* HttpServerRequest.HttpServerRequest;
20
+ const body = yield* request.text;
21
+ yield* receiveAuthWebhook({
22
+ projectId,
23
+ secret,
24
+ body,
25
+ headers: request.headers,
26
+ onDeleteUser: (data) => options.onDeleteUser(data).pipe(Effect.provideContext(services), Effect.mapError(() => new AuthWebhookCleanupError({}))),
27
+ onDeleteOrganization: (data) => options.onDeleteOrganization(data).pipe(Effect.provideContext(services), Effect.mapError(() => new AuthWebhookCleanupError({}))),
28
+ onWebhook: onWebhook
29
+ ? (webhook) => onWebhook(webhook).pipe(Effect.provideContext(services), Effect.mapError(() => new AuthWebhookCleanupError({})))
30
+ : undefined,
31
+ }).pipe(Effect.provideService(WebhooksReceiver, receiver));
32
+ return HttpServerResponse.empty({ status: 204 });
33
+ }).pipe(Effect.provideService(HttpServerRequest.MaxBodySize, ByteSize.kibibytes(16)), Effect.catchTag("WebhookVerificationError", (error) => Effect.succeed(HttpServerResponse.empty({
34
+ status: error.reason === "payload" ? 400 : 401,
35
+ }))), Effect.catchTag("WebhookReceiptConflict", () => Effect.succeed(HttpServerResponse.empty({ status: 409 }))), Effect.catchTag("UnsupportedAuthWebhook", () => Effect.succeed(HttpServerResponse.empty({ status: 400 }))), Effect.catch(() => Effect.succeed(HttpServerResponse.empty({ status: 500 }))));
36
+ return HttpRouter.add("POST", "/api/webhooks/auth", handle);
37
+ })).pipe(Layer.provide(WebhooksReceiver.layer));
@@ -0,0 +1,38 @@
1
+ import { Effect, Redacted, Schema } from "effect";
2
+ import { WebhooksReceiver, WebhookVerificationError } from "@krak-stack/registry/webhooks";
3
+ import { AccountDeletionData, OrganizationDeletionData, AuthWebhook } from "../schema.js";
4
+ export { AccountDeletionData, AccountDeletionWebhook } from "../schema.js";
5
+ export { OrganizationDeletionData, OrganizationDeletionWebhook, } from "../schema.js";
6
+ export { AuthWebhook, AuthWebhookData } from "../schema.js";
7
+ declare const AuthWebhookConfigurationError_base: Schema.Class<AuthWebhookConfigurationError, Schema.TaggedStruct<"AuthWebhookConfigurationError", {
8
+ readonly message: Schema.String;
9
+ }>, import("effect/Cause").YieldableError>;
10
+ export declare class AuthWebhookConfigurationError extends AuthWebhookConfigurationError_base {
11
+ }
12
+ declare const AuthWebhookCleanupError_base: Schema.Class<AuthWebhookCleanupError, Schema.TaggedStruct<"AuthWebhookCleanupError", {}>, import("effect/Cause").YieldableError>;
13
+ export declare class AuthWebhookCleanupError extends AuthWebhookCleanupError_base {
14
+ }
15
+ declare const UnsupportedAuthWebhook_base: Schema.Class<UnsupportedAuthWebhook, Schema.TaggedStruct<"UnsupportedAuthWebhook", {}>, import("effect/Cause").YieldableError>;
16
+ export declare class UnsupportedAuthWebhook extends UnsupportedAuthWebhook_base {
17
+ }
18
+ /** Acknowledge only after the app's same-database cleanup has committed. */
19
+ export declare const receiveAuthWebhook: <E, R>(input: {
20
+ readonly projectId: string;
21
+ readonly secret: Redacted.Redacted<string>;
22
+ readonly headers: Readonly<Record<string, string | undefined>>;
23
+ readonly body: string;
24
+ readonly onDeleteUser: (data: typeof AccountDeletionData.Type) => Effect.Effect<void, E, R>;
25
+ readonly onDeleteOrganization: (data: typeof OrganizationDeletionData.Type) => Effect.Effect<void, E, R>;
26
+ readonly onWebhook?: ((webhook: typeof AuthWebhook.Type) => Effect.Effect<void, E, R>) | undefined;
27
+ }) => Effect.Effect<{
28
+ duplicate: boolean;
29
+ }, E | import("effect/crypto/CryptoError").CryptoError | import("effect/Cause").NoSuchElementError | Schema.SchemaError | import("effect/sql/SqlError").SqlError | UnsupportedAuthWebhook | import("@krak-stack/registry/webhooks").WebhookReceiptConflict | WebhookVerificationError, R | WebhooksReceiver>;
30
+ export declare const receiveAccountDeletion: <E, R>(input: {
31
+ readonly projectId: string;
32
+ readonly secret: Redacted.Redacted<string>;
33
+ readonly headers: Readonly<Record<string, string | undefined>>;
34
+ readonly body: string;
35
+ readonly handle: (data: typeof AccountDeletionData.Type) => Effect.Effect<void, E, R>;
36
+ }) => Effect.Effect<{
37
+ duplicate: boolean;
38
+ }, E | import("effect/crypto/CryptoError").CryptoError | import("effect/Cause").NoSuchElementError | Schema.SchemaError | import("effect/sql/SqlError").SqlError | UnsupportedAuthWebhook | import("@krak-stack/registry/webhooks").WebhookReceiptConflict | WebhookVerificationError, R | WebhooksReceiver>;
@@ -0,0 +1,39 @@
1
+ import { Effect, Redacted, Schema } from "effect";
2
+ import { WebhooksReceiver, WebhookVerificationError, } from "@krak-stack/registry/webhooks";
3
+ import { AccountDeletionData, AccountDeletionWebhook, OrganizationDeletionData, AuthWebhook, OrganizationDeletionWebhook, } from "../schema.js";
4
+ export { AccountDeletionData, AccountDeletionWebhook } from "../schema.js";
5
+ export { OrganizationDeletionData, OrganizationDeletionWebhook, } from "../schema.js";
6
+ export { AuthWebhook, AuthWebhookData } from "../schema.js";
7
+ export class AuthWebhookConfigurationError extends Schema.TaggedError()("AuthWebhookConfigurationError", {
8
+ message: Schema.String,
9
+ }) {
10
+ }
11
+ export class AuthWebhookCleanupError extends Schema.TaggedError()("AuthWebhookCleanupError", {}) {
12
+ }
13
+ export class UnsupportedAuthWebhook extends Schema.TaggedError()("UnsupportedAuthWebhook", {}) {
14
+ }
15
+ /** Acknowledge only after the app's same-database cleanup has committed. */
16
+ export const receiveAuthWebhook = Effect.fn("Auth.receiveAuthWebhook")(function* (input) {
17
+ const receiver = yield* WebhooksReceiver;
18
+ return yield* receiver.receive({
19
+ receiver: `krakstack-auth:${input.projectId}`,
20
+ secret: input.secret,
21
+ headers: input.headers,
22
+ body: input.body,
23
+ schema: AuthWebhook.check(Schema.makeFilter((payload) => payload.data.projectId === input.projectId, { expected: "the configured auth project" })),
24
+ handle: (webhook) => {
25
+ if (webhook.event === "user.deletion_requested")
26
+ return Schema.decodeUnknownEffect(AccountDeletionWebhook)(webhook).pipe(Effect.mapError(() => new WebhookVerificationError({ reason: "payload" })), Effect.flatMap(({ data }) => input.onDeleteUser(data)));
27
+ if (webhook.event === "organization.deletion_requested")
28
+ return Schema.decodeUnknownEffect(OrganizationDeletionWebhook)(webhook).pipe(Effect.mapError(() => new WebhookVerificationError({ reason: "payload" })), Effect.flatMap(({ data }) => input.onDeleteOrganization(data)));
29
+ return input.onWebhook
30
+ ? input.onWebhook(webhook)
31
+ : Effect.fail(new UnsupportedAuthWebhook({}));
32
+ },
33
+ });
34
+ });
35
+ export const receiveAccountDeletion = (input) => receiveAuthWebhook({
36
+ ...input,
37
+ onDeleteUser: input.handle,
38
+ onDeleteOrganization: () => Effect.fail(new UnsupportedAuthWebhook({})),
39
+ });