@krak-stack/auth 0.1.71 → 0.2.1

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 (78) hide show
  1. package/README.md +4 -3
  2. package/dist/access.d.ts +5 -7
  3. package/dist/access.js +11 -7
  4. package/dist/admin/api.group.d.ts +53 -53
  5. package/dist/admin/api.group.js +15 -15
  6. package/dist/admin/schema.d.ts +18 -18
  7. package/dist/admin/schema.js +3 -3
  8. package/dist/api.d.ts +1995 -533
  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 +808 -0
  13. package/dist/auth/schema.js +628 -0
  14. package/dist/components/admin-organization-form.d.ts +1 -1
  15. package/dist/components/admin-organization-form.js +17 -18
  16. package/dist/components/admin-organizations.d.ts +4 -5
  17. package/dist/components/admin-organizations.js +83 -73
  18. package/dist/components/admin-users.d.ts +5 -6
  19. package/dist/components/admin-users.js +160 -181
  20. package/dist/components/api-key-edit-form.d.ts +4 -3
  21. package/dist/components/api-key-edit-form.js +33 -27
  22. package/dist/components/api-key-permissions.d.ts +1 -1
  23. package/dist/components/api-key-rate-limit.d.ts +1 -1
  24. package/dist/components/api-key-referrers.d.ts +3 -2
  25. package/dist/components/api-key-referrers.js +2 -3
  26. package/dist/components/api-key.d.ts +0 -9
  27. package/dist/components/api-key.js +0 -39
  28. package/dist/components/auth-atoms.d.ts +178 -0
  29. package/dist/components/auth-atoms.js +46 -0
  30. package/dist/components/auth-client-api.d.ts +1371 -556
  31. package/dist/components/auth-client-api.js +22 -14
  32. package/dist/components/auth-forms.d.ts +1 -3
  33. package/dist/components/auth-forms.js +173 -195
  34. package/dist/components/auth-provider.d.ts +16 -20
  35. package/dist/components/auth-provider.js +56 -30
  36. package/dist/components/has-permission.js +1 -1
  37. package/dist/components/index.d.ts +19 -20
  38. package/dist/components/index.js +13 -13
  39. package/dist/components/member-required.d.ts +1 -3
  40. package/dist/components/member-required.js +102 -78
  41. package/dist/components/organization-switcher.d.ts +4 -6
  42. package/dist/components/organization-switcher.js +539 -390
  43. package/dist/components/project-access-matrix.d.ts +1 -1
  44. package/dist/components/project-access-matrix.js +9 -13
  45. package/dist/components/user-button.d.ts +5 -3
  46. package/dist/components/user-button.js +291 -336
  47. package/dist/components/utils.d.ts +3 -1
  48. package/dist/components/utils.js +4 -11
  49. package/dist/extra/api.group.d.ts +22 -22
  50. package/dist/extra/api.group.js +9 -9
  51. package/dist/extra/schema.d.ts +1 -2
  52. package/dist/extra/schema.js +2 -3
  53. package/dist/index.d.ts +11 -12
  54. package/dist/index.js +11 -12
  55. package/dist/query.d.ts +2 -2
  56. package/dist/query.js +5 -5
  57. package/dist/roles.d.ts +5 -4
  58. package/dist/roles.js +11 -7
  59. package/dist/schema.d.ts +1 -1
  60. package/dist/schema.js +26 -19
  61. package/dist/server/actor.d.ts +20 -22
  62. package/dist/server/actor.js +14 -17
  63. package/dist/server/api.group.d.ts +29 -29
  64. package/dist/server/api.group.js +14 -14
  65. package/dist/server/index.d.ts +14 -14
  66. package/dist/server/index.js +8 -8
  67. package/dist/server/middleware.d.ts +1 -1
  68. package/dist/server/middleware.js +1 -1
  69. package/dist/server/schema.js +1 -1
  70. package/dist/service.d.ts +1997 -583
  71. package/dist/service.js +23 -16
  72. package/package.json +10 -9
  73. package/dist/better-auth/api.group.d.ts +0 -62
  74. package/dist/better-auth/api.group.js +0 -39
  75. package/dist/better-auth/schema.d.ts +0 -72
  76. package/dist/better-auth/schema.js +0 -110
  77. package/dist/components/auth-client.d.ts +0 -50
  78. package/dist/components/auth-client.js +0 -46
@@ -1,17 +1,20 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useAtomSet, useAtomValue } from "@effect/atom-react";
3
- import { useNavigate, useRouter, } from "@tanstack/react-router";
2
+ import { useAtomRefresh, useAtomSet, useAtomValue } from "@effect/atom-react";
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
+ import { SortParamsFromString, } from "@krak-stack/registry/query";
8
10
  import { ErrorMessage } from "@krak-stack/registry/effect-form";
9
11
  import { AppBrand } from "@krak-stack/registry/app-brand";
10
12
  import { Badge } from "@/components/ui/badge";
11
13
  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";
14
+ import { authSessionAtom, notifyAuthChange } from "./auth-atoms.js";
15
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
16
+ import { useKrakstackAuth } from "./auth-provider.js";
17
+ import { assetUrl } from "./utils.js";
15
18
  const defaultMessages = {
16
19
  en: {
17
20
  admin_action_ban: "Ban",
@@ -84,78 +87,117 @@ const initials = (name) => name
84
87
  .join("")
85
88
  .toUpperCase();
86
89
  const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
90
+ const AdminUsersFamilyKey = Schema.fromJsonString(Schema.Struct({
91
+ query: Schema.Struct({
92
+ page: Schema.Number,
93
+ pageSize: Schema.Number,
94
+ globalFilter: Schema.optional(Schema.String),
95
+ sort: Schema.optional(Schema.String),
96
+ projectId: Schema.optional(Schema.String),
97
+ }),
98
+ reloadKey: Schema.Number,
99
+ })).annotate({ identifier: "AdminUsersFamilyKey" });
87
100
  const adminUsersQuery = (search, projectId) => {
88
- const query = {
101
+ let query = {
89
102
  page: search.page ?? 0,
90
103
  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
104
  };
105
+ if (search.globalFilter)
106
+ query = { ...query, globalFilter: search.globalFilter };
107
+ if (search.sort)
108
+ query = {
109
+ ...query,
110
+ sort: Schema.encodeSync(SortParamsFromString)(search.sort),
111
+ };
112
+ if (projectId)
113
+ query = { ...query, projectId };
114
+ return query;
99
115
  };
100
- const usersAtom = Atom.family(({ baseUrl, projectId, reloadKey, search, }) => {
101
- const request = adminUsersQuery(search, projectId);
116
+ const adminUsersFamilyKey = (search, projectId, reloadKey) => JSON.stringify({ query: adminUsersQuery(search, projectId), reloadKey });
117
+ const usersAtom = Atom.family((baseUrl) => Atom.family((key) => {
118
+ const { query, reloadKey } = Schema.decodeUnknownSync(AdminUsersFamilyKey)(key);
102
119
  return authClientApi(baseUrl).query("admin", "listUsers", {
103
- query: request.query,
120
+ query,
104
121
  timeToLive: "1 minute",
105
122
  reactivityKeys: [
106
123
  "admin-users",
107
- ...(projectId ? [`project:${projectId}`] : []),
124
+ ...(query.projectId ? [`project:${query.projectId}`] : []),
108
125
  ],
109
- serializationKey: `admin-users:${reloadKey}:${request.key}`,
126
+ serializationKey: `admin-users:${reloadKey}:${JSON.stringify(query)}`,
110
127
  });
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
- };
128
+ }));
127
129
  const activeOrganizationId = (session) => {
128
130
  const value = session?.session?.activeOrganizationId;
129
- return typeof value === "string" && value ? value : null;
131
+ return Option.getOrNull(Schema.decodeUnknownOption(Schema.NonEmptyString)(value));
130
132
  };
131
- export function AdminUsersTable({ from, reloadKey = 0, search, }) {
133
+ export function AdminUsersTable({ onSearchChange, reloadKey = 0, search, }) {
132
134
  const navigate = useNavigate();
133
135
  const router = useRouter();
134
136
  const auth = useKrakstackAuth();
135
137
  const m = labels(auth?.locale ?? "en");
136
- const authClient = auth?.authClient;
137
138
  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" });
139
+ const sessionAtom = authSessionAtom(baseUrl);
140
+ const sessionResult = useAtomValue(sessionAtom);
141
+ const refetchSession = useAtomRefresh(sessionAtom);
142
+ const session = AsyncResult.match(sessionResult, {
143
+ onInitial: () => null,
144
+ onFailure: () => null,
145
+ onSuccess: ({ value }) => value,
146
+ });
143
147
  const projectId = auth?.projectId;
144
- const [impersonatingUserId, setImpersonatingUserId] = useState(null);
145
148
  const [impersonateError, setImpersonateError] = useState("");
146
149
  const [refreshKey, setRefreshKey] = useState(0);
147
150
  const [localSearch, setLocalSearch] = useState({
148
- globalFilter: "",
151
+ page: 0,
152
+ pageSize: 10,
149
153
  });
150
154
  const tableSearch = search ?? localSearch;
151
- const result = useAtomValue(usersAtom({
152
- baseUrl,
153
- projectId,
154
- search: tableSearch,
155
- reloadKey: reloadKey + refreshKey,
156
- }));
155
+ const result = useAtomValue(usersAtom(baseUrl)(adminUsersFamilyKey(tableSearch, projectId, reloadKey + refreshKey)));
157
156
  const [banningUser, setBanningUser] = useState(null);
158
157
  const [unbanningUser, setUnbanningUser] = useState(null);
158
+ const [impersonateUserAtom] = useState(() => authClientApi(baseUrl).runtime.fn((userId) => Effect.gen(function* () {
159
+ const client = yield* authHttpClient(baseUrl);
160
+ yield* client.auth.adminImpersonateUser({ payload: { userId } });
161
+ notifyAuthChange();
162
+ auth?.refreshAuth();
163
+ refetchSession();
164
+ yield* Effect.tryPromise({
165
+ try: async () => {
166
+ await navigate({ to: "/" });
167
+ await router.invalidate();
168
+ },
169
+ catch: (cause) => cause instanceof Error
170
+ ? cause
171
+ : new Error(m.admin_error_impersonate),
172
+ });
173
+ }).pipe(Effect.catch((cause) => Effect.sync(() => setImpersonateError(cause instanceof Error
174
+ ? cause.message
175
+ : m.admin_error_impersonate))))));
176
+ const [impersonateOrganizationUserAtom] = useState(() => authClientApi(baseUrl).runtime.fn(({ actorUserId, organizationId, targetUserId, }) => Effect.gen(function* () {
177
+ const client = yield* authHttpClient(baseUrl);
178
+ yield* client.auth.organizationImpersonateUser({
179
+ payload: { organizationId, actorUserId, targetUserId },
180
+ });
181
+ notifyAuthChange();
182
+ auth?.refreshAuth();
183
+ refetchSession();
184
+ yield* Effect.tryPromise({
185
+ try: async () => {
186
+ await navigate({ to: "/" });
187
+ await router.invalidate();
188
+ },
189
+ catch: (cause) => cause instanceof Error
190
+ ? cause
191
+ : new Error(m.admin_error_impersonate_organization),
192
+ });
193
+ }).pipe(Effect.catch((cause) => Effect.sync(() => setImpersonateError(cause instanceof Error
194
+ ? cause.message
195
+ : m.admin_error_impersonate_organization))))));
196
+ const impersonateUser = useAtomSet(impersonateUserAtom);
197
+ const impersonateUserResult = useAtomValue(impersonateUserAtom);
198
+ const impersonateOrganizationUser = useAtomSet(impersonateOrganizationUserAtom);
199
+ const impersonateOrganizationUserResult = useAtomValue(impersonateOrganizationUserAtom);
200
+ const isImpersonating = impersonateUserResult.waiting || impersonateOrganizationUserResult.waiting;
159
201
  const users = AsyncResult.match(result, {
160
202
  onInitial: () => [],
161
203
  onFailure: () => [],
@@ -176,73 +218,42 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
176
218
  onFailure: () => false,
177
219
  onSuccess: () => false,
178
220
  });
179
- const refreshSessionAndNavigate = async () => {
180
- auth?.refreshAuth();
181
- await refetchSession();
182
- await navigate({ to: "/" });
183
- await router.invalidate();
184
- };
185
- 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
- columnVisibility: { default: { id: false } },
221
+ return (_jsxs(_Fragment, { children: [error ? _jsx(ErrorMessage, { text: error }) : null, impersonateError ? _jsx(ErrorMessage, { text: impersonateError }) : null, _jsx(DataTable, { columnDefs: userColumns(m, baseUrl), rowData: users, features: {
222
+ columnVisibility: true,
187
223
  export: { baseName: "users" },
188
224
  gallery: false,
189
225
  pagination: { mode: "server", rowCount: total },
226
+ refresh: () => setRefreshKey((current) => current + 1),
190
227
  rowActions: {
191
228
  items: [
192
229
  {
193
230
  name: m.admin_action_impersonate,
194
- icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
195
- onClick: async (user) => {
231
+ icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
232
+ onClick: (user) => {
196
233
  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
- }
234
+ impersonateUser(user.id);
212
235
  },
213
236
  visible: (user) => !user.banned,
214
237
  },
215
238
  {
216
239
  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) => {
240
+ icon: isImpersonating ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(Building2, { className: "size-4" })),
241
+ onClick: (user) => {
219
242
  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);
243
+ if (!session?.user?.id) {
244
+ setImpersonateError(m.admin_error_access_required);
245
+ return;
242
246
  }
243
- finally {
244
- setImpersonatingUserId(null);
247
+ const organizationId = activeOrganizationId(session);
248
+ if (!organizationId) {
249
+ setImpersonateError(m.admin_error_organization_required);
250
+ return;
245
251
  }
252
+ impersonateOrganizationUser({
253
+ organizationId,
254
+ actorUserId: session.user.id,
255
+ targetUserId: user.id,
256
+ });
246
257
  },
247
258
  visible: (user) => !user.banned,
248
259
  },
@@ -261,22 +272,19 @@ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
261
272
  },
262
273
  ],
263
274
  },
264
- }, ...(from ? { routeFrom: from } : {}), ...(!search
265
- ? {
266
- search: tableSearch,
267
- onSearchChange: setLocalSearch,
268
- searchState: "local",
275
+ }, initialState: tableSearch, onStateChange: ({ page, pageSize, globalFilter, sort }) => {
276
+ const nextSearch = { page, pageSize, globalFilter, sort };
277
+ if (onSearchChange) {
278
+ onSearchChange(nextSearch);
279
+ }
280
+ else {
281
+ setLocalSearch(nextSearch);
269
282
  }
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] }));
283
+ }, status: { 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
284
  }
272
285
  export function useAdminUsersTotal(search) {
273
286
  const auth = useKrakstackAuth();
274
- const result = useAtomValue(usersAtom({
275
- baseUrl: auth?.baseUrl,
276
- projectId: auth?.projectId,
277
- search,
278
- reloadKey: 0,
279
- }));
287
+ const result = useAtomValue(usersAtom(auth?.baseUrl)(adminUsersFamilyKey(search, auth?.projectId, 0)));
280
288
  return AsyncResult.match(result, {
281
289
  onInitial: () => 0,
282
290
  onFailure: () => 0,
@@ -285,22 +293,17 @@ export function useAdminUsersTotal(search) {
285
293
  }
286
294
  const userColumns = (m, baseUrl) => [
287
295
  {
288
- accessorKey: "id",
289
- header: m.admin_column_id,
290
- cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground font-mono text-xs", children: row.original.id })),
291
- },
292
- {
293
- accessorKey: "email",
294
- header: m.admin_column_user,
295
- cell: ({ row }) => {
296
- const image = assetUrl(row.original.image);
297
- return (_jsx(AppBrand, { to: null, label: row.original.email, subtitle: row.original.name, icon: UserIcon, className: "min-w-48", ...(image ? { imageSrc: image } : {}) }));
296
+ field: "email",
297
+ headerName: m.admin_column_user,
298
+ cellRenderer: ({ data }) => {
299
+ const image = assetUrl(data.image);
300
+ return (_jsx(AppBrand, { to: null, label: data.email, subtitle: data.name, icon: UserIcon, className: "min-w-48", ...(image ? { imageSrc: image } : {}) }));
298
301
  },
299
302
  },
300
303
  {
301
- accessorKey: "organizations",
302
- header: m.admin_column_organizations,
303
- cell: ({ row }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: row.original.organizations.map((organization) => {
304
+ field: "organizations",
305
+ headerName: m.admin_column_organizations,
306
+ cellRenderer: ({ data }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: data.organizations.map((organization) => {
304
307
  const logo = assetUrl(organization.logo, baseUrl);
305
308
  return {
306
309
  label: organization.name,
@@ -310,9 +313,9 @@ const userColumns = (m, baseUrl) => [
310
313
  }), variant: "icon" })),
311
314
  },
312
315
  {
313
- accessorKey: "projects",
314
- header: m.admin_column_projects,
315
- cell: ({ row }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: row.original.projects.map((project) => {
316
+ field: "projects",
317
+ headerName: m.admin_column_projects,
318
+ cellRenderer: ({ data }) => (_jsx(DataTableListSummary, { emptyLabel: "-", items: data.projects.map((project) => {
316
319
  const logo = assetUrl(project.logo, baseUrl);
317
320
  return {
318
321
  label: project.name,
@@ -322,83 +325,59 @@ const userColumns = (m, baseUrl) => [
322
325
  }), variant: "icon" })),
323
326
  },
324
327
  {
325
- accessorKey: "emailVerified",
326
- header: m.admin_column_verified,
327
- cell: ({ row }) => row.original.emailVerified ? (_jsx(Badge, { variant: "outline", children: m.admin_column_verified })) : (_jsx(Badge, { variant: "secondary", children: m.admin_column_unverified })),
328
+ field: "emailVerified",
329
+ headerName: m.admin_column_verified,
330
+ cellRenderer: ({ data }) => data.emailVerified ? (_jsx(Badge, { variant: "outline", children: m.admin_column_verified })) : (_jsx(Badge, { variant: "secondary", children: m.admin_column_unverified })),
328
331
  },
329
332
  {
330
- accessorKey: "role",
331
- header: m.admin_column_role,
332
- cell: ({ row }) => {
333
- const role = row.original.role;
333
+ field: "role",
334
+ headerName: m.admin_column_role,
335
+ cellRenderer: ({ data }) => {
336
+ const role = data.role;
334
337
  if (!role)
335
338
  return _jsx(Badge, { variant: "outline", children: m.user_role_default });
336
339
  return (_jsx("div", { className: "flex flex-wrap gap-1.5", children: role.split(",").map((r) => (_jsx(Badge, { variant: r.trim() === "admin" ? "default" : "outline", children: r.trim() }, r.trim()))) }));
337
340
  },
338
341
  },
339
342
  {
340
- accessorKey: "banned",
341
- header: m.admin_column_status,
342
- cell: ({ row }) => row.original.banned ? (_jsx(Badge, { variant: "destructive", children: m.admin_status_banned })) : (_jsx(Badge, { variant: "outline", children: m.admin_status_active })),
343
+ field: "banned",
344
+ headerName: m.admin_column_status,
345
+ cellRenderer: ({ data }) => data.banned ? (_jsx(Badge, { variant: "destructive", children: m.admin_status_banned })) : (_jsx(Badge, { variant: "outline", children: m.admin_status_active })),
343
346
  },
344
347
  {
345
- accessorKey: "lastSignedIn",
346
- header: m.admin_column_last_signed_in,
347
- cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: row.original.lastSignedIn
348
- ? new Date(row.original.lastSignedIn).toLocaleString()
349
- : "-" })),
348
+ field: "lastSignedIn",
349
+ headerName: m.admin_column_last_signed_in,
350
+ cellRenderer: ({ data }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: data.lastSignedIn ? new Date(data.lastSignedIn).toLocaleString() : "-" })),
350
351
  },
351
352
  {
352
- accessorKey: "createdAt",
353
- header: m.admin_column_created,
354
- cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(row.original.createdAt).toLocaleDateString() })),
353
+ field: "createdAt",
354
+ headerName: m.admin_column_created,
355
+ cellRenderer: ({ data }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(data.createdAt).toLocaleDateString() })),
355
356
  },
356
357
  ];
357
- function BanUserDialog({ labels: m, authClient, user, onBanned, onClose, }) {
358
- const [isPending, setIsPending] = useState(false);
358
+ function BanUserDialog({ labels: m, baseUrl, user, onBanned, onClose, }) {
359
+ const [banUserAtom] = useState(() => authClientApi(baseUrl).runtime.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
360
  const [error, setError] = useState("");
361
+ const banUser = useAtomSet(banUserAtom);
362
+ const isPending = useAtomValue(banUserAtom).waiting;
360
363
  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
364
  name: user.name,
362
365
  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 () => {
366
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: () => {
364
367
  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
- }
368
+ banUser(user.id);
379
369
  }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_ban] })] })] }) }));
380
370
  }
381
- function UnbanUserDialog({ labels: m, authClient, user, onUnbanned, onClose, }) {
382
- const [isPending, setIsPending] = useState(false);
371
+ function UnbanUserDialog({ labels: m, baseUrl, user, onUnbanned, onClose, }) {
372
+ const [unbanUserAtom] = useState(() => authClientApi(baseUrl).runtime.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
373
  const [error, setError] = useState("");
374
+ const unbanUser = useAtomSet(unbanUserAtom);
375
+ const isPending = useAtomValue(unbanUserAtom).waiting;
384
376
  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
377
  name: user.name,
386
378
  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 () => {
379
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: () => {
388
380
  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
- }
381
+ unbanUser(user.id);
403
382
  }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_unban] })] })] }) }));
404
383
  }
@@ -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;
@@ -4,17 +4,18 @@ import { FormBuilder, FormReact } from "@lucas-barake/effect-form-react";
4
4
  import { Effect, Schema } from "effect";
5
5
  import { useRef, useState } from "react";
6
6
  import { CheckboxField, SubmitButton, SubmitError, TextAreaField, TextField, } from "@krak-stack/registry/effect-form";
7
- import { parseApiKeyReferrers, updateApiKey } from "./api-key";
8
- import { ApiKeyPermissions } from "./api-key-permissions";
9
- import { apiKeyReferrers } from "./api-key-referrers";
10
- import { ExtraApiKeyPermissions } from "../extra/schema";
7
+ import { parseApiKeyReferrers } from "./api-key.js";
8
+ import { authClientApi, authHttpClient } from "./auth-client-api.js";
9
+ import { ApiKeyPermissions } from "./api-key-permissions.js";
10
+ import { apiKeyReferrers } from "./api-key-referrers.js";
11
+ import { ExtraApiKeyPermissions } from "../extra/schema.js";
11
12
  const editApiKeyFormBuilder = FormBuilder.empty
12
13
  .addField("name", Schema.NonEmptyString)
13
14
  .addField("enabled", Schema.Boolean)
14
15
  .addField("referrers", Schema.String)
15
16
  .addField("permissions", Schema.Record(Schema.String, Schema.Boolean));
16
17
  const ApiKeyPermissionsField = ({ field, props }) => (_jsx(ApiKeyPermissions, { description: props.description, idPrefix: props.idPrefix, permissions: props.permissions, labels: props.labels, selected: field.value, title: props.title, onChange: (id, checked) => field.onChange({ ...field.value, [id]: checked }) }));
17
- export const ApiKeyEditForm = ({ configId, keyData, messages, permissions, permissionLabels, onSaved, }) => {
18
+ export const ApiKeyEditForm = ({ baseUrl, configId, keyData, messages, permissions, permissionLabels, onSaved, }) => {
18
19
  const permissionOptions = Object.entries(permissions).flatMap(([project, actions]) => actions.map((action) => ({
19
20
  id: `${project}:${action}`,
20
21
  project,
@@ -31,6 +32,7 @@ export const ApiKeyEditForm = ({ configId, keyData, messages, permissions, permi
31
32
  permissionOptionsRef.current = permissionOptions;
32
33
  permissionsRef.current = permissions;
33
34
  const [form] = useState(() => FormReact.make(editApiKeyFormBuilder, {
35
+ runtime: authClientApi(baseUrl).runtime,
34
36
  fields: {
35
37
  name: TextField,
36
38
  enabled: CheckboxField,
@@ -38,33 +40,37 @@ export const ApiKeyEditForm = ({ configId, keyData, messages, permissions, permi
38
40
  permissions: ApiKeyPermissionsField,
39
41
  },
40
42
  mode: { validation: "onSubmit" },
41
- onSubmit: (_, { decoded }) => Effect.tryPromise({
42
- try: async () => {
43
- const referrers = parseApiKeyReferrers(decoded.referrers, messages.referrersError);
44
- const selectedGrant = {};
45
- for (const project of Object.keys(permissionsRef.current)) {
46
- selectedGrant[project] = [];
47
- }
48
- for (const option of permissionOptionsRef.current) {
49
- if (!decoded.permissions[option.id])
50
- continue;
51
- selectedGrant[option.project] = [
52
- ...(selectedGrant[option.project] ?? []),
53
- option.action,
54
- ];
55
- }
56
- await updateApiKey({
43
+ onSubmit: (_, { decoded }) => Effect.gen(function* () {
44
+ const referrers = yield* Effect.try({
45
+ try: () => parseApiKeyReferrers(decoded.referrers, messages.referrersError),
46
+ catch: (cause) => cause instanceof Error ? cause : new Error(messages.updateError),
47
+ });
48
+ const selectedGrant = {};
49
+ for (const project of Object.keys(permissionsRef.current)) {
50
+ selectedGrant[project] = [];
51
+ }
52
+ for (const option of permissionOptionsRef.current) {
53
+ if (!decoded.permissions[option.id])
54
+ continue;
55
+ selectedGrant[option.project] = [
56
+ ...(selectedGrant[option.project] ?? []),
57
+ option.action,
58
+ ];
59
+ }
60
+ const client = yield* authHttpClient(baseUrl);
61
+ const updated = yield* client.authExtra.updateApiKey({
62
+ params: { keyId: keyData.id },
63
+ payload: {
57
64
  configId,
58
- keyId: keyData.id,
59
65
  name: decoded.name.trim(),
60
66
  enabled: decoded.enabled,
61
67
  permissions: selectedGrant,
62
68
  referrers,
63
- }, messages.updateError);
64
- onSaved();
65
- },
66
- catch: (cause) => cause instanceof Error ? cause : new Error(messages.updateError),
67
- }),
69
+ },
70
+ });
71
+ yield* Effect.sync(onSaved);
72
+ return updated;
73
+ }).pipe(Effect.mapError((cause) => cause instanceof Error ? cause : new Error(messages.updateError))),
68
74
  }));
69
75
  const submit = useAtomSet(form.submit);
70
76
  const submitResult = useAtomValue(form.submit);
@@ -1,4 +1,4 @@
1
- import type { ProjectAccessLabelCatalog } from "../access";
1
+ import type { ProjectAccessLabelCatalog } from "../access.js";
2
2
  export declare const ApiKeyPermissions: ({ description, idPrefix, permissions, labels, selected, title, onChange, }: {
3
3
  description: string;
4
4
  idPrefix: string;
@@ -1,4 +1,4 @@
1
- import type { ApiKey } from "@better-auth/api-key/client";
1
+ import type { AuthApiKey as ApiKey } from "../auth/schema.js";
2
2
  type ApiKeyRateLimitMessages = {
3
3
  disabled: string;
4
4
  none: string;
@@ -1,5 +1,6 @@
1
- export declare const apiKeyReferrers: (metadata: unknown) => never[] | readonly string[];
2
- export declare const withApiKeyReferrers: (metadata: unknown, referrers: ReadonlyArray<string>) => {
1
+ import { Schema } from "effect";
2
+ export declare const apiKeyReferrers: (metadata: typeof Schema.Unknown.Type) => never[] | readonly string[];
3
+ export declare const withApiKeyReferrers: (metadata: typeof Schema.Unknown.Type, referrers: ReadonlyArray<string>) => {
3
4
  allowedOrigins: string[];
4
5
  };
5
6
  export declare const ApiKeyReferrers: ({ metadata, unrestrictedLabel, }: {
@@ -3,11 +3,10 @@ import { Option, Schema } from "effect";
3
3
  import { Badge } from "@/components/ui/badge";
4
4
  const Metadata = Schema.Record(Schema.String, Schema.Unknown);
5
5
  const MetadataJson = Schema.fromJsonString(Metadata);
6
+ const MetadataInput = Schema.Union([Metadata, MetadataJson]);
6
7
  const Referrers = Schema.Array(Schema.String);
7
8
  const apiKeyMetadata = (metadata) => {
8
- const decodedMetadata = typeof metadata === "string"
9
- ? Schema.decodeUnknownOption(MetadataJson)(metadata)
10
- : Schema.decodeUnknownOption(Metadata)(metadata);
9
+ const decodedMetadata = Schema.decodeUnknownOption(MetadataInput)(metadata);
11
10
  return Option.getOrElse(decodedMetadata, () => ({}));
12
11
  };
13
12
  export const apiKeyReferrers = (metadata) => Option.getOrElse(Schema.decodeUnknownOption(Referrers)(apiKeyMetadata(metadata).allowedOrigins), () => []);
@@ -1,10 +1 @@
1
- import { Schema } from "effect";
2
- import { ExtraCreateApiKeyPayload, ExtraCreateApiKeyResponse, ExtraUpdateApiKeyPayload } from "../extra/schema";
3
- export type CreateApiKeyPayload = typeof ExtraCreateApiKeyPayload.Type;
4
- export type CreatedApiKey = typeof ExtraCreateApiKeyResponse.Type;
5
- export type UpdateApiKeyPayload = typeof ExtraUpdateApiKeyPayload.Type;
6
1
  export declare const parseApiKeyReferrers: (value: string, errorMessage: string) => string[];
7
- export declare const createApiKey: (payload: CreateApiKeyPayload, fallbackError: string) => Promise<CreatedApiKey>;
8
- export declare const updateApiKey: (payload: UpdateApiKeyPayload, fallbackError: string) => Promise<Schema.Struct.ReadonlySide<{
9
- readonly ok: Schema.Boolean;
10
- }, "Type">>;