@krak-stack/auth 0.1.71 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +4 -3
  2. package/dist/access.d.ts +4 -4
  3. package/dist/access.js +10 -4
  4. package/dist/admin/api.group.d.ts +17 -17
  5. package/dist/admin/api.group.js +2 -2
  6. package/dist/admin/schema.d.ts +18 -18
  7. package/dist/admin/schema.js +3 -3
  8. package/dist/api.d.ts +2093 -631
  9. package/dist/api.js +7 -7
  10. package/dist/auth/api.group.d.ts +793 -0
  11. package/dist/auth/api.group.js +241 -0
  12. package/dist/auth/schema.d.ts +800 -0
  13. package/dist/auth/schema.js +625 -0
  14. package/dist/components/admin-organization-form.d.ts +1 -1
  15. package/dist/components/admin-organization-form.js +16 -18
  16. package/dist/components/admin-organizations.js +52 -45
  17. package/dist/components/admin-users.js +115 -137
  18. package/dist/components/api-key-edit-form.d.ts +4 -3
  19. package/dist/components/api-key-edit-form.js +32 -27
  20. package/dist/components/api-key-permissions.d.ts +1 -1
  21. package/dist/components/api-key-rate-limit.d.ts +1 -1
  22. package/dist/components/api-key-referrers.d.ts +3 -2
  23. package/dist/components/api-key-referrers.js +2 -3
  24. package/dist/components/api-key.d.ts +0 -9
  25. package/dist/components/api-key.js +0 -39
  26. package/dist/components/auth-atoms.d.ts +178 -0
  27. package/dist/components/auth-atoms.js +46 -0
  28. package/dist/components/auth-client-api.d.ts +2474 -142
  29. package/dist/components/auth-client-api.js +14 -10
  30. package/dist/components/auth-forms.d.ts +1 -3
  31. package/dist/components/auth-forms.js +168 -195
  32. package/dist/components/auth-provider.d.ts +3 -7
  33. package/dist/components/auth-provider.js +56 -30
  34. package/dist/components/has-permission.js +1 -1
  35. package/dist/components/index.d.ts +19 -20
  36. package/dist/components/index.js +13 -13
  37. package/dist/components/member-required.d.ts +1 -3
  38. package/dist/components/member-required.js +102 -78
  39. package/dist/components/organization-switcher.d.ts +4 -6
  40. package/dist/components/organization-switcher.js +469 -323
  41. package/dist/components/project-access-matrix.d.ts +1 -1
  42. package/dist/components/project-access-matrix.js +9 -13
  43. package/dist/components/user-button.d.ts +5 -3
  44. package/dist/components/user-button.js +264 -314
  45. package/dist/components/utils.d.ts +3 -1
  46. package/dist/components/utils.js +4 -11
  47. package/dist/extra/api.group.d.ts +3 -3
  48. package/dist/extra/api.group.js +6 -6
  49. package/dist/extra/schema.js +1 -1
  50. package/dist/index.d.ts +11 -12
  51. package/dist/index.js +11 -12
  52. package/dist/query.d.ts +2 -2
  53. package/dist/roles.d.ts +5 -4
  54. package/dist/roles.js +11 -7
  55. package/dist/schema.d.ts +1 -1
  56. package/dist/schema.js +26 -19
  57. package/dist/server/actor.d.ts +20 -22
  58. package/dist/server/actor.js +14 -17
  59. package/dist/server/api.group.js +2 -2
  60. package/dist/server/index.d.ts +14 -14
  61. package/dist/server/index.js +8 -8
  62. package/dist/server/middleware.d.ts +1 -1
  63. package/dist/server/middleware.js +1 -1
  64. package/dist/server/schema.js +1 -1
  65. package/dist/service.d.ts +2043 -191
  66. package/dist/service.js +23 -16
  67. package/package.json +8 -7
  68. package/dist/better-auth/api.group.d.ts +0 -62
  69. package/dist/better-auth/api.group.js +0 -39
  70. package/dist/better-auth/schema.d.ts +0 -72
  71. package/dist/better-auth/schema.js +0 -110
  72. package/dist/components/auth-client.d.ts +0 -50
  73. package/dist/components/auth-client.js +0 -46
@@ -7,16 +7,16 @@ import { useState } from "react";
7
7
  import { toast } from "sonner";
8
8
  import { ImageField, SingleSearchableSelectField, SubmitButton, SubmitError, TextField, } from "@krak-stack/registry/effect-form";
9
9
  import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
10
- import { AdminCreateOrganizationPayload, } from "../admin/schema";
11
- import { authClientApi } from "./auth-client-api";
12
- import { useKrakstackAuth } from "./auth-provider";
13
- import { assetPath, assetUrl } from "./utils";
10
+ import { AdminCreateOrganizationPayload, } from "../admin/schema.js";
11
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
12
+ import { useKrakstackAuth } from "./auth-provider.js";
13
+ import { assetPath, assetUrl } from "./utils.js";
14
14
  const defaultMessages = {
15
15
  en: {
16
16
  admin_organization_edit_description: "Update {name}'s canonical organization details.",
17
17
  field_name: "Name",
18
18
  form_submit: "Save",
19
- organization_create_description: "Create an organization that can be used for Better Auth membership.",
19
+ organization_create_description: "Create an organization that can be used for authentication membership.",
20
20
  organization_create_error: "Unable to create organization.",
21
21
  organization_create_title: "Create organization",
22
22
  organization_created_toast: "Organization created.",
@@ -36,7 +36,7 @@ const defaultMessages = {
36
36
  admin_organization_edit_description: "Mettez à jour les détails canoniques de l'organisation {name}.",
37
37
  field_name: "Nom",
38
38
  form_submit: "Enregistrer",
39
- organization_create_description: "Créez une organisation utilisable pour les adhésions Better Auth.",
39
+ organization_create_description: "Créez une organisation utilisable pour les adhésions d'authentification.",
40
40
  organization_create_error: "Impossible de créer l'organisation.",
41
41
  organization_create_title: "Créer une organisation",
42
42
  organization_created_toast: "Organisation créée.",
@@ -61,9 +61,6 @@ const organizationOptionsAtom = Atom.family((baseUrl) => authClientApi(baseUrl).
61
61
  timeToLive: "1 minute",
62
62
  reactivityKeys: ["organizations"],
63
63
  }));
64
- const createOrganizationAtom = Atom.family((baseUrl) => authClientApi(baseUrl).mutation("admin", "createOrganization"));
65
- const updateOrganizationAtom = Atom.family((baseUrl) => authClientApi(baseUrl).mutation("admin", "updateOrganization"));
66
- const uploadOrganizationLogoAtom = Atom.family((baseUrl) => authClientApi(baseUrl).mutation("authExtra", "uploadUserImage"));
67
64
  const slugify = (value) => value
68
65
  .trim()
69
66
  .toLowerCase()
@@ -82,25 +79,26 @@ const makeOrganizationForm = ({ baseUrl, organization, }) => FormReact.make(orga
82
79
  parentId: SingleSearchableSelectField,
83
80
  },
84
81
  mode: { validation: "onSubmit" },
85
- onSubmit: (_, { decoded, get }) => Effect.gen(function* () {
82
+ onSubmit: (_, { decoded }) => Effect.gen(function* () {
83
+ const http = yield* authHttpClient(baseUrl);
86
84
  const logoValue = decoded.logo;
87
85
  let logo = assetPath(logoValue instanceof File ? null : logoValue);
88
86
  if (logoValue instanceof File) {
89
87
  const payload = new FormData();
90
88
  payload.append("file", logoValue);
91
- const uploaded = yield* get.setResult(uploadOrganizationLogoAtom(baseUrl), { payload });
89
+ const uploaded = yield* http.authExtra.uploadUserImage({ payload });
92
90
  logo = assetPath(uploaded.url);
93
91
  }
94
- const payload = Schema.decodeUnknownSync(AdminCreateOrganizationPayload)({
92
+ const input = {
95
93
  name: decoded.name.trim(),
96
94
  slug: slugify(decoded.slug || decoded.name),
97
95
  logo: logo ?? undefined,
98
- ...(decoded.parentId === noParentOrganization
99
- ? {}
100
- : { parentId: decoded.parentId }),
101
- });
96
+ };
97
+ const payload = Schema.decodeUnknownSync(AdminCreateOrganizationPayload)(decoded.parentId === noParentOrganization
98
+ ? input
99
+ : { ...input, parentId: decoded.parentId });
102
100
  const saved = organization
103
- ? yield* get.setResult(updateOrganizationAtom(baseUrl), {
101
+ ? yield* http.admin.updateOrganization({
104
102
  params: { id: organization.id },
105
103
  payload: {
106
104
  ...payload,
@@ -109,7 +107,7 @@ const makeOrganizationForm = ({ baseUrl, organization, }) => FormReact.make(orga
109
107
  : decoded.parentId,
110
108
  },
111
109
  })
112
- : yield* get.setResult(createOrganizationAtom(baseUrl), { payload });
110
+ : yield* http.admin.createOrganization({ payload });
113
111
  return saved;
114
112
  }),
115
113
  });
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomSet, useAtomValue } from "@effect/atom-react";
2
+ import { useAtomSet, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
3
+ import { Cause, Effect, Schema } from "effect";
3
4
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
4
5
  import { Building2, Pencil, Trash2 } from "lucide-react";
5
6
  import { useState } from "react";
@@ -8,10 +9,10 @@ import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-tabl
8
9
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
9
10
  import { AppBrand } from "@krak-stack/registry/app-brand";
10
11
  import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
11
- import { AdminOrganizationForm } from "./admin-organization-form";
12
- import { authClientApi } from "./auth-client-api";
13
- import { useKrakstackAuth } from "./auth-provider";
14
- import { assetUrl, organizationBranding } from "./utils";
12
+ import { AdminOrganizationForm } from "./admin-organization-form.js";
13
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
14
+ import { useKrakstackAuth } from "./auth-provider.js";
15
+ import { assetUrl, organizationBranding } from "./utils.js";
15
16
  const defaultMessages = {
16
17
  en: {
17
18
  admin_column_created: "Created",
@@ -56,31 +57,45 @@ const organizationDisplay = (organization, locale, baseUrl) => {
56
57
  image: assetUrl(branding?.logo, baseUrl),
57
58
  };
58
59
  };
60
+ const AdminOrganizationsFamilyKey = Schema.fromJsonString(Schema.Struct({
61
+ query: Schema.Struct({
62
+ page: Schema.Number,
63
+ pageSize: Schema.Number,
64
+ globalFilter: Schema.optional(Schema.String),
65
+ sort: Schema.optional(Schema.String),
66
+ projectId: Schema.optional(Schema.String),
67
+ }),
68
+ reloadKey: Schema.Number,
69
+ })).annotate({ identifier: "AdminOrganizationsFamilyKey" });
59
70
  const organizationsQuery = (search, projectId) => {
60
- const query = {
71
+ let query = {
61
72
  page: search.page ?? 0,
62
73
  pageSize: search.pageSize ?? 10,
63
- ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
64
- ...(search.sort ? { sort: search.sort } : {}),
65
- ...(projectId ? { projectId } : {}),
66
- };
67
- return {
68
- query,
69
- key: JSON.stringify(query),
70
74
  };
75
+ if (search.globalFilter)
76
+ query = { ...query, globalFilter: search.globalFilter };
77
+ if (search.sort)
78
+ query = { ...query, sort: search.sort };
79
+ if (projectId)
80
+ query = { ...query, projectId };
81
+ return query;
71
82
  };
72
- const organizationsAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
73
- const request = organizationsQuery(search, projectId);
83
+ const adminOrganizationsFamilyKey = (search, projectId, reloadKey) => JSON.stringify({
84
+ query: organizationsQuery(search, projectId),
85
+ reloadKey,
86
+ });
87
+ const organizationsAtom = Atom.family((baseUrl) => Atom.family((key) => {
88
+ const { query, reloadKey } = Schema.decodeUnknownSync(AdminOrganizationsFamilyKey)(key);
74
89
  return authClientApi(baseUrl).query("admin", "listOrganizations", {
75
- query: request.query,
90
+ query,
76
91
  timeToLive: "1 minute",
77
92
  reactivityKeys: [
78
93
  "organizations",
79
- ...(projectId ? [`project:${projectId}`] : []),
94
+ ...(query.projectId ? [`project:${query.projectId}`] : []),
80
95
  ],
81
- serializationKey: `organizations:${reloadKey}:${request.key}`,
96
+ serializationKey: `organizations:${reloadKey}:${JSON.stringify(query)}`,
82
97
  });
83
- });
98
+ }));
84
99
  export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
85
100
  const auth = useKrakstackAuth();
86
101
  const locale = auth?.locale ?? "en";
@@ -94,13 +109,7 @@ export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
94
109
  globalFilter: "",
95
110
  });
96
111
  const tableSearch = search ?? localSearch;
97
- const result = useAtomValue(organizationsAtom({
98
- baseUrl,
99
- projectId,
100
- reloadKey: reloadKey + refreshKey,
101
- search: tableSearch,
102
- }));
103
- const deleteOrganization = useAtomSet(authClientApi(baseUrl).mutation("admin", "deleteOrganization"), { mode: "promise" });
112
+ const result = useAtomValue(organizationsAtom(baseUrl)(adminOrganizationsFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
104
113
  const organizations = AsyncResult.match(result, {
105
114
  onInitial: () => [],
106
115
  onFailure: () => [],
@@ -148,10 +157,7 @@ export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
148
157
  onSearchChange: setLocalSearch,
149
158
  searchState: "local",
150
159
  }
151
- : {}), onRefresh: () => setRefreshKey((current) => current + 1), state: { loading: isLoading } }), editingOrganization ? (_jsx(AdminOrganizationForm, { organization: editingOrganization, onClose: () => setEditingOrganization(null), onSaved: () => setRefreshKey((current) => current + 1) })) : null, deletingOrganization ? (_jsx(DeleteOrganizationDialog, { labels: m, organization: deletingOrganization, onClose: () => setDeletingOrganization(null), onDelete: async () => {
152
- await deleteOrganization({
153
- params: { id: deletingOrganization.id },
154
- });
160
+ : {}), onRefresh: () => setRefreshKey((current) => current + 1), state: { loading: isLoading } }), editingOrganization ? (_jsx(AdminOrganizationForm, { organization: editingOrganization, onClose: () => setEditingOrganization(null), onSaved: () => setRefreshKey((current) => current + 1) })) : null, deletingOrganization ? (_jsx(DeleteOrganizationDialog, { labels: m, organization: deletingOrganization, baseUrl: baseUrl, onClose: () => setDeletingOrganization(null), onDeleted: () => {
155
161
  toast.success(m.organization_deleted_toast);
156
162
  setDeletingOrganization(null);
157
163
  setRefreshKey((current) => current + 1);
@@ -210,21 +216,22 @@ function OrganizationMembers({ baseUrl, members, total, }) {
210
216
  };
211
217
  }), totalCount: total, variant: "icon" }));
212
218
  }
213
- function DeleteOrganizationDialog({ labels: m, organization, onClose, onDelete, }) {
214
- const [error, setError] = useState("");
215
- const [isPending, setIsPending] = useState(false);
216
- return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: m.organization_delete_title }), _jsx(AlertDialogDescription, { children: m.organization_delete_description.replace("{name}", organization.name) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.organization_delete_cancel }), _jsx(AlertDialogAction, { disabled: isPending, onClick: async (event) => {
219
+ function DeleteOrganizationDialog({ baseUrl, labels: m, organization, onClose, onDeleted, }) {
220
+ const [deleteOrganizationAtom] = useState(() => Atom.fn((id) => Effect.flatMap(authHttpClient(baseUrl), (http) => http.admin.deleteOrganization({ params: { id } }))));
221
+ const deleteOrganization = useAtomSet(deleteOrganizationAtom);
222
+ const result = useAtomValue(deleteOrganizationAtom);
223
+ useAtomSubscribe(deleteOrganizationAtom, (current) => {
224
+ if (AsyncResult.isSuccess(current))
225
+ onDeleted();
226
+ });
227
+ const error = AsyncResult.isFailure(result)
228
+ ? Cause.squash(result.cause)
229
+ : undefined;
230
+ const isPending = !AsyncResult.isInitial(result) && result.waiting;
231
+ return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: m.organization_delete_title }), _jsx(AlertDialogDescription, { children: m.organization_delete_description.replace("{name}", organization.name) })] }), error ? (_jsx(ErrorMessage, { text: error instanceof Error
232
+ ? error.message
233
+ : m.organization_delete_error })) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.organization_delete_cancel }), _jsx(AlertDialogAction, { disabled: isPending, onClick: (event) => {
217
234
  event.preventDefault();
218
- setError("");
219
- setIsPending(true);
220
- try {
221
- await onDelete();
222
- }
223
- catch (cause) {
224
- setError(cause instanceof Error
225
- ? cause.message
226
- : m.organization_delete_error);
227
- setIsPending(false);
228
- }
235
+ deleteOrganization(organization.id);
229
236
  }, children: m.organization_delete_confirm })] })] }) }));
230
237
  }
@@ -1,7 +1,8 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomSet, useAtomValue } from "@effect/atom-react";
2
+ import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
3
3
  import { useNavigate, useRouter, } from "@tanstack/react-router";
4
4
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
5
+ import { Effect, Option, Schema } from "effect";
5
6
  import { Ban, Building2, Loader2, ShieldOff, UserCog, UserIcon, } from "lucide-react";
6
7
  import { useState } from "react";
7
8
  import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-table";
@@ -9,9 +10,10 @@ import { ErrorMessage } from "@krak-stack/registry/effect-form";
9
10
  import { AppBrand } from "@krak-stack/registry/app-brand";
10
11
  import { Badge } from "@/components/ui/badge";
11
12
  import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
12
- import { authClientApi } from "./auth-client-api";
13
- import { useKrakstackAuth } from "./auth-provider";
14
- import { assetUrl } from "./utils";
13
+ import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
14
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
15
+ import { useKrakstackAuth } from "./auth-provider.js";
16
+ import { assetUrl } from "./utils.js";
15
17
  const defaultMessages = {
16
18
  en: {
17
19
  admin_action_ban: "Ban",
@@ -84,78 +86,113 @@ const initials = (name) => name
84
86
  .join("")
85
87
  .toUpperCase();
86
88
  const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
89
+ const AdminUsersFamilyKey = Schema.fromJsonString(Schema.Struct({
90
+ query: Schema.Struct({
91
+ page: Schema.Number,
92
+ pageSize: Schema.Number,
93
+ globalFilter: Schema.optional(Schema.String),
94
+ sort: Schema.optional(Schema.String),
95
+ projectId: Schema.optional(Schema.String),
96
+ }),
97
+ reloadKey: Schema.Number,
98
+ })).annotate({ identifier: "AdminUsersFamilyKey" });
87
99
  const adminUsersQuery = (search, projectId) => {
88
- const query = {
100
+ let query = {
89
101
  page: search.page ?? 0,
90
102
  pageSize: search.pageSize ?? 10,
91
- ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
92
- ...(search.sort ? { sort: search.sort } : {}),
93
- ...(projectId ? { projectId } : {}),
94
- };
95
- return {
96
- query,
97
- key: JSON.stringify(query),
98
103
  };
104
+ if (search.globalFilter)
105
+ query = { ...query, globalFilter: search.globalFilter };
106
+ if (search.sort)
107
+ query = { ...query, sort: search.sort };
108
+ if (projectId)
109
+ query = { ...query, projectId };
110
+ return query;
99
111
  };
100
- const usersAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
101
- const request = adminUsersQuery(search, projectId);
112
+ const adminUsersFamilyKey = (search, projectId, reloadKey) => JSON.stringify({ query: adminUsersQuery(search, projectId), reloadKey });
113
+ const usersAtom = Atom.family((baseUrl) => Atom.family((key) => {
114
+ const { query, reloadKey } = Schema.decodeUnknownSync(AdminUsersFamilyKey)(key);
102
115
  return authClientApi(baseUrl).query("admin", "listUsers", {
103
- query: request.query,
116
+ query,
104
117
  timeToLive: "1 minute",
105
118
  reactivityKeys: [
106
119
  "admin-users",
107
- ...(projectId ? [`project:${projectId}`] : []),
120
+ ...(query.projectId ? [`project:${query.projectId}`] : []),
108
121
  ],
109
- serializationKey: `admin-users:${reloadKey}:${request.key}`,
122
+ serializationKey: `admin-users:${reloadKey}:${JSON.stringify(query)}`,
110
123
  });
111
- });
112
- const banUser = async (authClient, userId, m) => {
113
- const result = await authClient.admin.banUser({ userId });
114
- if (result.error)
115
- throw new Error(result.error.message ?? m.admin_error_ban);
116
- };
117
- const unbanUser = async (authClient, userId, m) => {
118
- const result = await authClient.admin.unbanUser({ userId });
119
- if (result.error)
120
- throw new Error(result.error.message ?? m.admin_error_unban);
121
- };
122
- const impersonateUser = async (authClient, userId, m) => {
123
- const result = await authClient.admin.impersonateUser({ userId });
124
- if (result.error)
125
- throw new Error(result.error.message ?? m.admin_error_impersonate);
126
- };
124
+ }));
127
125
  const activeOrganizationId = (session) => {
128
126
  const value = session?.session?.activeOrganizationId;
129
- return typeof value === "string" && value ? value : null;
127
+ return Option.getOrNull(Schema.decodeUnknownOption(Schema.NonEmptyString)(value));
130
128
  };
131
129
  export function AdminUsersTable({ from, reloadKey = 0, search, }) {
132
130
  const navigate = useNavigate();
133
131
  const router = useRouter();
134
132
  const auth = useKrakstackAuth();
135
133
  const m = labels(auth?.locale ?? "en");
136
- const authClient = auth?.authClient;
137
134
  const baseUrl = auth?.baseUrl;
138
- const { data: session, refetch: refetchSession } = authClient?.useSession() ?? {
139
- data: null,
140
- refetch: async () => undefined,
141
- };
142
- const impersonateOrganizationUser = useAtomSet(authClientApi(baseUrl).mutation("auth", "organizationImpersonateUser"), { mode: "promise" });
135
+ const sessionAtom = authSessionAtom(baseUrl);
136
+ const sessionResult = useAtomValue(sessionAtom);
137
+ const refetchSession = useAtomRefresh(sessionAtom);
138
+ const session = AsyncResult.match(sessionResult, {
139
+ onInitial: () => null,
140
+ onFailure: () => null,
141
+ onSuccess: ({ value }) => value,
142
+ });
143
143
  const projectId = auth?.projectId;
144
- const [impersonatingUserId, setImpersonatingUserId] = useState(null);
145
144
  const [impersonateError, setImpersonateError] = useState("");
146
145
  const [refreshKey, setRefreshKey] = useState(0);
147
146
  const [localSearch, setLocalSearch] = useState({
148
147
  globalFilter: "",
149
148
  });
150
149
  const tableSearch = search ?? localSearch;
151
- const result = useAtomValue(usersAtom({
152
- baseUrl,
153
- projectId,
154
- search: tableSearch,
155
- reloadKey: reloadKey + refreshKey,
156
- }));
150
+ const result = useAtomValue(usersAtom(baseUrl)(adminUsersFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
157
151
  const [banningUser, setBanningUser] = useState(null);
158
152
  const [unbanningUser, setUnbanningUser] = useState(null);
153
+ const [impersonateUserAtom] = useState(() => Atom.fn((userId) => Effect.gen(function* () {
154
+ const client = yield* authHttpClient(baseUrl);
155
+ yield* client.auth.adminImpersonateUser({ payload: { userId } });
156
+ notifyAuthChange();
157
+ auth?.refreshAuth();
158
+ refetchSession();
159
+ yield* Effect.tryPromise({
160
+ try: async () => {
161
+ await navigate({ to: "/" });
162
+ await router.invalidate();
163
+ },
164
+ catch: (cause) => cause instanceof Error
165
+ ? cause
166
+ : new Error(m.admin_error_impersonate),
167
+ });
168
+ }).pipe(Effect.catch((cause) => Effect.sync(() => setImpersonateError(cause instanceof Error
169
+ ? cause.message
170
+ : m.admin_error_impersonate))))));
171
+ const [impersonateOrganizationUserAtom] = useState(() => Atom.fn(({ actorUserId, organizationId, targetUserId, }) => Effect.gen(function* () {
172
+ const client = yield* authHttpClient(baseUrl);
173
+ yield* client.auth.organizationImpersonateUser({
174
+ payload: { organizationId, actorUserId, targetUserId },
175
+ });
176
+ notifyAuthChange();
177
+ auth?.refreshAuth();
178
+ refetchSession();
179
+ yield* Effect.tryPromise({
180
+ try: async () => {
181
+ await navigate({ to: "/" });
182
+ await router.invalidate();
183
+ },
184
+ catch: (cause) => cause instanceof Error
185
+ ? cause
186
+ : new Error(m.admin_error_impersonate_organization),
187
+ });
188
+ }).pipe(Effect.catch((cause) => Effect.sync(() => setImpersonateError(cause instanceof Error
189
+ ? cause.message
190
+ : m.admin_error_impersonate_organization))))));
191
+ const impersonateUser = useAtomSet(impersonateUserAtom);
192
+ const impersonateUserResult = useAtomValue(impersonateUserAtom);
193
+ const impersonateOrganizationUser = useAtomSet(impersonateOrganizationUserAtom);
194
+ const impersonateOrganizationUserResult = useAtomValue(impersonateOrganizationUserAtom);
195
+ const isImpersonating = impersonateUserResult.waiting || impersonateOrganizationUserResult.waiting;
159
196
  const users = AsyncResult.match(result, {
160
197
  onInitial: () => [],
161
198
  onFailure: () => [],
@@ -176,12 +213,6 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
176
213
  onFailure: () => false,
177
214
  onSuccess: () => false,
178
215
  });
179
- const refreshSessionAndNavigate = async () => {
180
- auth?.refreshAuth();
181
- await refetchSession();
182
- await navigate({ to: "/" });
183
- await router.invalidate();
184
- };
185
216
  return (_jsxs(_Fragment, { children: [error ? _jsx(ErrorMessage, { text: error }) : null, impersonateError ? _jsx(ErrorMessage, { text: impersonateError }) : null, _jsx(DataTable, { columns: userColumns(m, baseUrl), data: users, features: {
186
217
  columnVisibility: { default: { id: false } },
187
218
  export: { baseName: "users" },
@@ -191,58 +222,32 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
191
222
  items: [
192
223
  {
193
224
  name: m.admin_action_impersonate,
194
- icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
195
- onClick: async (user) => {
225
+ icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
226
+ onClick: (user) => {
196
227
  setImpersonateError("");
197
- setImpersonatingUserId(user.id);
198
- try {
199
- if (!authClient)
200
- throw new Error(m.admin_error_access_required);
201
- await impersonateUser(authClient, user.id, m);
202
- await refreshSessionAndNavigate();
203
- }
204
- catch (cause) {
205
- setImpersonateError(cause instanceof Error
206
- ? cause.message
207
- : m.admin_error_impersonate);
208
- }
209
- finally {
210
- setImpersonatingUserId(null);
211
- }
228
+ impersonateUser(user.id);
212
229
  },
213
230
  visible: (user) => !user.banned,
214
231
  },
215
232
  {
216
233
  name: m.admin_action_impersonate_organization,
217
- icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(Building2, { className: "size-4" })),
218
- onClick: async (user) => {
234
+ icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(Building2, { className: "size-4" })),
235
+ onClick: (user) => {
219
236
  setImpersonateError("");
220
- setImpersonatingUserId(user.id);
221
- try {
222
- if (!session?.user?.id) {
223
- throw new Error(m.admin_error_access_required);
224
- }
225
- const organizationId = activeOrganizationId(session);
226
- if (!organizationId) {
227
- throw new Error(m.admin_error_organization_required);
228
- }
229
- await impersonateOrganizationUser({
230
- payload: {
231
- organizationId,
232
- actorUserId: session.user.id,
233
- targetUserId: user.id,
234
- },
235
- });
236
- await refreshSessionAndNavigate();
237
- }
238
- catch (cause) {
239
- setImpersonateError(cause instanceof Error
240
- ? cause.message
241
- : m.admin_error_impersonate_organization);
237
+ if (!session?.user?.id) {
238
+ setImpersonateError(m.admin_error_access_required);
239
+ return;
242
240
  }
243
- finally {
244
- setImpersonatingUserId(null);
241
+ const organizationId = activeOrganizationId(session);
242
+ if (!organizationId) {
243
+ setImpersonateError(m.admin_error_organization_required);
244
+ return;
245
245
  }
246
+ impersonateOrganizationUser({
247
+ organizationId,
248
+ actorUserId: session.user.id,
249
+ targetUserId: user.id,
250
+ });
246
251
  },
247
252
  visible: (user) => !user.banned,
248
253
  },
@@ -267,16 +272,11 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
267
272
  onSearchChange: setLocalSearch,
268
273
  searchState: "local",
269
274
  }
270
- : {}), onRefresh: () => setRefreshKey((current) => current + 1), state: { loading: isLoading } }), banningUser ? (_jsx(BanUserDialog, { labels: m, authClient: authClient, user: banningUser, onBanned: () => setRefreshKey((current) => current + 1), onClose: () => setBanningUser(null) })) : null, unbanningUser ? (_jsx(UnbanUserDialog, { labels: m, authClient: authClient, user: unbanningUser, onUnbanned: () => setRefreshKey((current) => current + 1), onClose: () => setUnbanningUser(null) })) : null] }));
275
+ : {}), onRefresh: () => setRefreshKey((current) => current + 1), state: { loading: isLoading } }), banningUser ? (_jsx(BanUserDialog, { labels: m, baseUrl: baseUrl, user: banningUser, onBanned: () => setRefreshKey((current) => current + 1), onClose: () => setBanningUser(null) })) : null, unbanningUser ? (_jsx(UnbanUserDialog, { labels: m, baseUrl: baseUrl, user: unbanningUser, onUnbanned: () => setRefreshKey((current) => current + 1), onClose: () => setUnbanningUser(null) })) : null] }));
271
276
  }
272
277
  export function useAdminUsersTotal(search) {
273
278
  const auth = useKrakstackAuth();
274
- const result = useAtomValue(usersAtom({
275
- baseUrl: auth?.baseUrl,
276
- projectId: auth?.projectId,
277
- search,
278
- reloadKey: 0,
279
- }));
279
+ const result = useAtomValue(usersAtom(auth?.baseUrl)(adminUsersFamilyKey(search, auth?.projectId, 0)));
280
280
  return AsyncResult.match(result, {
281
281
  onInitial: () => 0,
282
282
  onFailure: () => 0,
@@ -354,51 +354,29 @@ const userColumns = (m, baseUrl) => [
354
354
  cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(row.original.createdAt).toLocaleDateString() })),
355
355
  },
356
356
  ];
357
- function BanUserDialog({ labels: m, authClient, user, onBanned, onClose, }) {
358
- const [isPending, setIsPending] = useState(false);
357
+ function BanUserDialog({ labels: m, baseUrl, user, onBanned, onClose, }) {
358
+ const [banUserAtom] = useState(() => Atom.fn((userId) => Effect.flatMap(authHttpClient(baseUrl), (client) => client.auth.adminBanUser({ payload: { userId } })).pipe(Effect.tap(() => Effect.sync(onBanned)), Effect.tap(() => Effect.sync(onClose)), Effect.catch((cause) => Effect.sync(() => setError(cause instanceof Error ? cause.message : m.admin_error_ban))))));
359
359
  const [error, setError] = useState("");
360
+ const banUser = useAtomSet(banUserAtom);
361
+ const isPending = useAtomValue(banUserAtom).waiting;
360
362
  return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: m.admin_ban_title }), _jsx(AlertDialogDescription, { children: text(m.admin_ban_description, {
361
363
  name: user.name,
362
364
  email: user.email,
363
- }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: async () => {
365
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: () => {
364
366
  setError("");
365
- setIsPending(true);
366
- try {
367
- if (!authClient)
368
- throw new Error(m.admin_error_access_required);
369
- await banUser(authClient, user.id, m);
370
- onBanned();
371
- onClose();
372
- }
373
- catch (cause) {
374
- setError(cause instanceof Error ? cause.message : m.admin_error_ban);
375
- }
376
- finally {
377
- setIsPending(false);
378
- }
367
+ banUser(user.id);
379
368
  }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_ban] })] })] }) }));
380
369
  }
381
- function UnbanUserDialog({ labels: m, authClient, user, onUnbanned, onClose, }) {
382
- const [isPending, setIsPending] = useState(false);
370
+ function UnbanUserDialog({ labels: m, baseUrl, user, onUnbanned, onClose, }) {
371
+ const [unbanUserAtom] = useState(() => Atom.fn((userId) => Effect.flatMap(authHttpClient(baseUrl), (client) => client.auth.adminUnbanUser({ payload: { userId } })).pipe(Effect.tap(() => Effect.sync(onUnbanned)), Effect.tap(() => Effect.sync(onClose)), Effect.catch((cause) => Effect.sync(() => setError(cause instanceof Error ? cause.message : m.admin_error_unban))))));
383
372
  const [error, setError] = useState("");
373
+ const unbanUser = useAtomSet(unbanUserAtom);
374
+ const isPending = useAtomValue(unbanUserAtom).waiting;
384
375
  return (_jsx(AlertDialog, { open: true, onOpenChange: (open) => !open && onClose(), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: m.admin_unban_title }), _jsx(AlertDialogDescription, { children: text(m.admin_unban_description, {
385
376
  name: user.name,
386
377
  email: user.email,
387
- }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: async () => {
378
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: () => {
388
379
  setError("");
389
- setIsPending(true);
390
- try {
391
- if (!authClient)
392
- throw new Error(m.admin_error_access_required);
393
- await unbanUser(authClient, user.id, m);
394
- onUnbanned();
395
- onClose();
396
- }
397
- catch (cause) {
398
- setError(cause instanceof Error ? cause.message : m.admin_error_unban);
399
- }
400
- finally {
401
- setIsPending(false);
402
- }
380
+ unbanUser(user.id);
403
381
  }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_unban] })] })] }) }));
404
382
  }
@@ -1,5 +1,5 @@
1
- import type { ApiKey } from "@better-auth/api-key/client";
2
- import type { ProjectAccessLabelCatalog } from "../access";
1
+ import type { AuthApiKey as ApiKey } from "../auth/schema.js";
2
+ import type { ProjectAccessLabelCatalog } from "../access.js";
3
3
  type ApiKeySummary = Omit<ApiKey, "key">;
4
4
  export type ApiKeyEditMessages = {
5
5
  enabled: string;
@@ -12,7 +12,8 @@ export type ApiKeyEditMessages = {
12
12
  permissionsDescription: string;
13
13
  updateError: string;
14
14
  };
15
- export declare const ApiKeyEditForm: ({ configId, keyData, messages, permissions, permissionLabels, onSaved, }: {
15
+ export declare const ApiKeyEditForm: ({ baseUrl, configId, keyData, messages, permissions, permissionLabels, onSaved, }: {
16
+ baseUrl?: string | undefined;
16
17
  configId: "organization" | "user";
17
18
  keyData: ApiKeySummary;
18
19
  messages: ApiKeyEditMessages;