@krak-stack/auth 0.1.70 → 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 -46
  17. package/dist/components/admin-users.js +115 -138
  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 -324
  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 +265 -316
  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 +30 -32
  58. package/dist/server/actor.js +39 -22
  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 +3 -3
  63. package/dist/server/middleware.js +10 -5
  64. package/dist/server/schema.js +1 -1
  65. package/dist/service.d.ts +2053 -201
  66. package/dist/service.js +32 -21
  67. package/package.json +10 -9
  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,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomSet, useAtomValue } from "@effect/atom-react";
3
- import {} from "@tanstack/react-table";
2
+ import { useAtomSet, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
3
+ import { Cause, Effect, Schema } from "effect";
4
4
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
5
5
  import { Building2, Pencil, Trash2 } from "lucide-react";
6
6
  import { useState } from "react";
@@ -9,10 +9,10 @@ import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-tabl
9
9
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
10
10
  import { AppBrand } from "@krak-stack/registry/app-brand";
11
11
  import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
12
- import { AdminOrganizationForm } from "./admin-organization-form";
13
- import { authClientApi } from "./auth-client-api";
14
- import { useKrakstackAuth } from "./auth-provider";
15
- 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";
16
16
  const defaultMessages = {
17
17
  en: {
18
18
  admin_column_created: "Created",
@@ -57,31 +57,45 @@ const organizationDisplay = (organization, locale, baseUrl) => {
57
57
  image: assetUrl(branding?.logo, baseUrl),
58
58
  };
59
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" });
60
70
  const organizationsQuery = (search, projectId) => {
61
- const query = {
71
+ let query = {
62
72
  page: search.page ?? 0,
63
73
  pageSize: search.pageSize ?? 10,
64
- ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
65
- ...(search.sort ? { sort: search.sort } : {}),
66
- ...(projectId ? { projectId } : {}),
67
- };
68
- return {
69
- query,
70
- key: JSON.stringify(query),
71
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;
72
82
  };
73
- const organizationsAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
74
- 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);
75
89
  return authClientApi(baseUrl).query("admin", "listOrganizations", {
76
- query: request.query,
90
+ query,
77
91
  timeToLive: "1 minute",
78
92
  reactivityKeys: [
79
93
  "organizations",
80
- ...(projectId ? [`project:${projectId}`] : []),
94
+ ...(query.projectId ? [`project:${query.projectId}`] : []),
81
95
  ],
82
- serializationKey: `organizations:${reloadKey}:${request.key}`,
96
+ serializationKey: `organizations:${reloadKey}:${JSON.stringify(query)}`,
83
97
  });
84
- });
98
+ }));
85
99
  export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
86
100
  const auth = useKrakstackAuth();
87
101
  const locale = auth?.locale ?? "en";
@@ -95,13 +109,7 @@ export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
95
109
  globalFilter: "",
96
110
  });
97
111
  const tableSearch = search ?? localSearch;
98
- const result = useAtomValue(organizationsAtom({
99
- baseUrl,
100
- projectId,
101
- reloadKey: reloadKey + refreshKey,
102
- search: tableSearch,
103
- }));
104
- const deleteOrganization = useAtomSet(authClientApi(baseUrl).mutation("admin", "deleteOrganization"), { mode: "promise" });
112
+ const result = useAtomValue(organizationsAtom(baseUrl)(adminOrganizationsFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
105
113
  const organizations = AsyncResult.match(result, {
106
114
  onInitial: () => [],
107
115
  onFailure: () => [],
@@ -149,10 +157,7 @@ export function AdminOrganizationsTable({ from, reloadKey = 0, search, }) {
149
157
  onSearchChange: setLocalSearch,
150
158
  searchState: "local",
151
159
  }
152
- : {}), 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 () => {
153
- await deleteOrganization({
154
- params: { id: deletingOrganization.id },
155
- });
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: () => {
156
161
  toast.success(m.organization_deleted_toast);
157
162
  setDeletingOrganization(null);
158
163
  setRefreshKey((current) => current + 1);
@@ -211,21 +216,22 @@ function OrganizationMembers({ baseUrl, members, total, }) {
211
216
  };
212
217
  }), totalCount: total, variant: "icon" }));
213
218
  }
214
- function DeleteOrganizationDialog({ labels: m, organization, onClose, onDelete, }) {
215
- const [error, setError] = useState("");
216
- const [isPending, setIsPending] = useState(false);
217
- 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) => {
218
234
  event.preventDefault();
219
- setError("");
220
- setIsPending(true);
221
- try {
222
- await onDelete();
223
- }
224
- catch (cause) {
225
- setError(cause instanceof Error
226
- ? cause.message
227
- : m.organization_delete_error);
228
- setIsPending(false);
229
- }
235
+ deleteOrganization(organization.id);
230
236
  }, children: m.organization_delete_confirm })] })] }) }));
231
237
  }
@@ -1,8 +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
- import {} from "@tanstack/react-table";
5
4
  import { Atom, AsyncResult } from "effect/unstable/reactivity";
5
+ import { Effect, Option, Schema } from "effect";
6
6
  import { Ban, Building2, Loader2, ShieldOff, UserCog, UserIcon, } from "lucide-react";
7
7
  import { useState } from "react";
8
8
  import { DataTable, DataTableListSummary, } from "@krak-stack/registry/data-table";
@@ -10,9 +10,10 @@ import { ErrorMessage } from "@krak-stack/registry/effect-form";
10
10
  import { AppBrand } from "@krak-stack/registry/app-brand";
11
11
  import { Badge } from "@/components/ui/badge";
12
12
  import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
13
- import { authClientApi } from "./auth-client-api";
14
- import { useKrakstackAuth } from "./auth-provider";
15
- 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";
16
17
  const defaultMessages = {
17
18
  en: {
18
19
  admin_action_ban: "Ban",
@@ -85,78 +86,113 @@ const initials = (name) => name
85
86
  .join("")
86
87
  .toUpperCase();
87
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" });
88
99
  const adminUsersQuery = (search, projectId) => {
89
- const query = {
100
+ let query = {
90
101
  page: search.page ?? 0,
91
102
  pageSize: search.pageSize ?? 10,
92
- ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
93
- ...(search.sort ? { sort: search.sort } : {}),
94
- ...(projectId ? { projectId } : {}),
95
- };
96
- return {
97
- query,
98
- key: JSON.stringify(query),
99
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;
100
111
  };
101
- const usersAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
102
- 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);
103
115
  return authClientApi(baseUrl).query("admin", "listUsers", {
104
- query: request.query,
116
+ query,
105
117
  timeToLive: "1 minute",
106
118
  reactivityKeys: [
107
119
  "admin-users",
108
- ...(projectId ? [`project:${projectId}`] : []),
120
+ ...(query.projectId ? [`project:${query.projectId}`] : []),
109
121
  ],
110
- serializationKey: `admin-users:${reloadKey}:${request.key}`,
122
+ serializationKey: `admin-users:${reloadKey}:${JSON.stringify(query)}`,
111
123
  });
112
- });
113
- const banUser = async (authClient, userId, m) => {
114
- const result = await authClient.admin.banUser({ userId });
115
- if (result.error)
116
- throw new Error(result.error.message ?? m.admin_error_ban);
117
- };
118
- const unbanUser = async (authClient, userId, m) => {
119
- const result = await authClient.admin.unbanUser({ userId });
120
- if (result.error)
121
- throw new Error(result.error.message ?? m.admin_error_unban);
122
- };
123
- const impersonateUser = async (authClient, userId, m) => {
124
- const result = await authClient.admin.impersonateUser({ userId });
125
- if (result.error)
126
- throw new Error(result.error.message ?? m.admin_error_impersonate);
127
- };
124
+ }));
128
125
  const activeOrganizationId = (session) => {
129
126
  const value = session?.session?.activeOrganizationId;
130
- return typeof value === "string" && value ? value : null;
127
+ return Option.getOrNull(Schema.decodeUnknownOption(Schema.NonEmptyString)(value));
131
128
  };
132
129
  export function AdminUsersTable({ from, reloadKey = 0, search, }) {
133
130
  const navigate = useNavigate();
134
131
  const router = useRouter();
135
132
  const auth = useKrakstackAuth();
136
133
  const m = labels(auth?.locale ?? "en");
137
- const authClient = auth?.authClient;
138
134
  const baseUrl = auth?.baseUrl;
139
- const { data: session, refetch: refetchSession } = authClient?.useSession() ?? {
140
- data: null,
141
- refetch: async () => undefined,
142
- };
143
- 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
+ });
144
143
  const projectId = auth?.projectId;
145
- const [impersonatingUserId, setImpersonatingUserId] = useState(null);
146
144
  const [impersonateError, setImpersonateError] = useState("");
147
145
  const [refreshKey, setRefreshKey] = useState(0);
148
146
  const [localSearch, setLocalSearch] = useState({
149
147
  globalFilter: "",
150
148
  });
151
149
  const tableSearch = search ?? localSearch;
152
- const result = useAtomValue(usersAtom({
153
- baseUrl,
154
- projectId,
155
- search: tableSearch,
156
- reloadKey: reloadKey + refreshKey,
157
- }));
150
+ const result = useAtomValue(usersAtom(baseUrl)(adminUsersFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
158
151
  const [banningUser, setBanningUser] = useState(null);
159
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;
160
196
  const users = AsyncResult.match(result, {
161
197
  onInitial: () => [],
162
198
  onFailure: () => [],
@@ -177,12 +213,6 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
177
213
  onFailure: () => false,
178
214
  onSuccess: () => false,
179
215
  });
180
- const refreshSessionAndNavigate = async () => {
181
- auth?.refreshAuth();
182
- await refetchSession();
183
- await navigate({ to: "/" });
184
- await router.invalidate();
185
- };
186
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: {
187
217
  columnVisibility: { default: { id: false } },
188
218
  export: { baseName: "users" },
@@ -192,58 +222,32 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
192
222
  items: [
193
223
  {
194
224
  name: m.admin_action_impersonate,
195
- icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
196
- onClick: async (user) => {
225
+ icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
226
+ onClick: (user) => {
197
227
  setImpersonateError("");
198
- setImpersonatingUserId(user.id);
199
- try {
200
- if (!authClient)
201
- throw new Error(m.admin_error_access_required);
202
- await impersonateUser(authClient, user.id, m);
203
- await refreshSessionAndNavigate();
204
- }
205
- catch (cause) {
206
- setImpersonateError(cause instanceof Error
207
- ? cause.message
208
- : m.admin_error_impersonate);
209
- }
210
- finally {
211
- setImpersonatingUserId(null);
212
- }
228
+ impersonateUser(user.id);
213
229
  },
214
230
  visible: (user) => !user.banned,
215
231
  },
216
232
  {
217
233
  name: m.admin_action_impersonate_organization,
218
- icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(Building2, { className: "size-4" })),
219
- onClick: async (user) => {
234
+ icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(Building2, { className: "size-4" })),
235
+ onClick: (user) => {
220
236
  setImpersonateError("");
221
- setImpersonatingUserId(user.id);
222
- try {
223
- if (!session?.user?.id) {
224
- throw new Error(m.admin_error_access_required);
225
- }
226
- const organizationId = activeOrganizationId(session);
227
- if (!organizationId) {
228
- throw new Error(m.admin_error_organization_required);
229
- }
230
- await impersonateOrganizationUser({
231
- payload: {
232
- organizationId,
233
- actorUserId: session.user.id,
234
- targetUserId: user.id,
235
- },
236
- });
237
- await refreshSessionAndNavigate();
238
- }
239
- catch (cause) {
240
- setImpersonateError(cause instanceof Error
241
- ? cause.message
242
- : m.admin_error_impersonate_organization);
237
+ if (!session?.user?.id) {
238
+ setImpersonateError(m.admin_error_access_required);
239
+ return;
243
240
  }
244
- finally {
245
- setImpersonatingUserId(null);
241
+ const organizationId = activeOrganizationId(session);
242
+ if (!organizationId) {
243
+ setImpersonateError(m.admin_error_organization_required);
244
+ return;
246
245
  }
246
+ impersonateOrganizationUser({
247
+ organizationId,
248
+ actorUserId: session.user.id,
249
+ targetUserId: user.id,
250
+ });
247
251
  },
248
252
  visible: (user) => !user.banned,
249
253
  },
@@ -268,16 +272,11 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
268
272
  onSearchChange: setLocalSearch,
269
273
  searchState: "local",
270
274
  }
271
- : {}), 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] }));
272
276
  }
273
277
  export function useAdminUsersTotal(search) {
274
278
  const auth = useKrakstackAuth();
275
- const result = useAtomValue(usersAtom({
276
- baseUrl: auth?.baseUrl,
277
- projectId: auth?.projectId,
278
- search,
279
- reloadKey: 0,
280
- }));
279
+ const result = useAtomValue(usersAtom(auth?.baseUrl)(adminUsersFamilyKey(search, auth?.projectId, 0)));
281
280
  return AsyncResult.match(result, {
282
281
  onInitial: () => 0,
283
282
  onFailure: () => 0,
@@ -355,51 +354,29 @@ const userColumns = (m, baseUrl) => [
355
354
  cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(row.original.createdAt).toLocaleDateString() })),
356
355
  },
357
356
  ];
358
- function BanUserDialog({ labels: m, authClient, user, onBanned, onClose, }) {
359
- 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))))));
360
359
  const [error, setError] = useState("");
360
+ const banUser = useAtomSet(banUserAtom);
361
+ const isPending = useAtomValue(banUserAtom).waiting;
361
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, {
362
363
  name: user.name,
363
364
  email: user.email,
364
- }) })] }), 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: () => {
365
366
  setError("");
366
- setIsPending(true);
367
- try {
368
- if (!authClient)
369
- throw new Error(m.admin_error_access_required);
370
- await banUser(authClient, user.id, m);
371
- onBanned();
372
- onClose();
373
- }
374
- catch (cause) {
375
- setError(cause instanceof Error ? cause.message : m.admin_error_ban);
376
- }
377
- finally {
378
- setIsPending(false);
379
- }
367
+ banUser(user.id);
380
368
  }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_ban] })] })] }) }));
381
369
  }
382
- function UnbanUserDialog({ labels: m, authClient, user, onUnbanned, onClose, }) {
383
- 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))))));
384
372
  const [error, setError] = useState("");
373
+ const unbanUser = useAtomSet(unbanUserAtom);
374
+ const isPending = useAtomValue(unbanUserAtom).waiting;
385
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, {
386
376
  name: user.name,
387
377
  email: user.email,
388
- }) })] }), 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: () => {
389
379
  setError("");
390
- setIsPending(true);
391
- try {
392
- if (!authClient)
393
- throw new Error(m.admin_error_access_required);
394
- await unbanUser(authClient, user.id, m);
395
- onUnbanned();
396
- onClose();
397
- }
398
- catch (cause) {
399
- setError(cause instanceof Error ? cause.message : m.admin_error_unban);
400
- }
401
- finally {
402
- setIsPending(false);
403
- }
380
+ unbanUser(user.id);
404
381
  }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_unban] })] })] }) }));
405
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;