@krak-stack/auth 0.1.38 → 0.1.40

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 (38) hide show
  1. package/dist/api.d.ts +22 -0
  2. package/dist/better-auth/api.d.ts +2 -0
  3. package/dist/better-auth/index.d.ts +1 -0
  4. package/dist/better-auth/schema.d.ts +1 -0
  5. package/dist/better-auth/schema.js +1 -0
  6. package/dist/components/admin-organization-form.d.ts +6 -0
  7. package/dist/components/admin-organization-form.js +136 -0
  8. package/dist/components/admin-organizations.d.ts +7 -0
  9. package/dist/components/admin-organizations.js +118 -0
  10. package/dist/components/admin-users.d.ts +8 -0
  11. package/dist/components/admin-users.js +265 -0
  12. package/dist/components/auth-api-client.d.ts +22 -0
  13. package/dist/components/auth-client.d.ts +3 -1
  14. package/dist/components/auth-forms.js +10 -24
  15. package/dist/components/auth-provider.d.ts +16 -15
  16. package/dist/components/auth-provider.js +51 -4
  17. package/dist/components/index.d.ts +3 -0
  18. package/dist/components/index.js +3 -0
  19. package/dist/components/user-button.d.ts +11 -1
  20. package/dist/components/user-button.js +73 -15
  21. package/dist/extra/api.d.ts +2 -0
  22. package/dist/extra/index.d.ts +1 -0
  23. package/dist/extra/schema.d.ts +1 -0
  24. package/dist/extra/schema.js +2 -0
  25. package/dist/index.d.ts +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/schema.d.ts +2 -0
  28. package/dist/schema.js +3 -0
  29. package/dist/server/api.d.ts +40 -0
  30. package/dist/server/index.d.ts +3 -0
  31. package/dist/server/index.js +1 -0
  32. package/dist/server/middleware.d.ts +23 -0
  33. package/dist/server/middleware.js +40 -0
  34. package/dist/server/schema.d.ts +6 -0
  35. package/dist/server/schema.js +8 -0
  36. package/dist/service.d.ts +516 -437
  37. package/dist/service.js +96 -12
  38. package/package.json +1 -1
@@ -0,0 +1,265 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // @ts-nocheck
3
+ import { useAtomValue } from "@effect/atom-react";
4
+ import { useNavigate } from "@tanstack/react-router";
5
+ import {} from "@tanstack/react-table";
6
+ import { Atom, AsyncResult } from "effect/unstable/reactivity";
7
+ import { Ban, Loader2, ShieldOff, UserCog, UserIcon } from "lucide-react";
8
+ import { useState } from "react";
9
+ import { DataTable } from "@/components/ui/data-table";
10
+ import { ErrorMessage } from "@/components/ui/form";
11
+ import { AppBrand } from "@/components/ui/app-brand";
12
+ import { Badge } from "@/components/ui/badge";
13
+ import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog";
14
+ import { authBaseUrl, authClient } from "@/services/auth/client";
15
+ import { assetUrl } from "@/lib/assets";
16
+ import { AdminApiClient } from "@/lib/admin-api-client";
17
+ import { useKrakstackAuth } from "./auth-provider";
18
+ const defaultMessages = {
19
+ en: {
20
+ admin_action_ban: "Ban",
21
+ admin_action_impersonate: "Impersonate",
22
+ admin_action_unban: "Unban",
23
+ admin_ban_description: "Are you sure you want to ban {name} ({email})? They will not be able to sign in.",
24
+ admin_ban_title: "Ban user",
25
+ admin_column_created: "Created",
26
+ admin_column_role: "Role",
27
+ admin_column_status: "Status",
28
+ admin_column_unverified: "Unverified",
29
+ admin_column_user: "User",
30
+ admin_column_verified: "Verified",
31
+ admin_error_access_required: "Admin access is required.",
32
+ admin_error_ban: "Unable to ban user.",
33
+ admin_error_impersonate: "Unable to impersonate user.",
34
+ admin_error_unban: "Unable to unban user.",
35
+ admin_status_active: "Active",
36
+ admin_status_banned: "Banned",
37
+ admin_unban_description: "Are you sure you want to unban {name} ({email})? They will be able to sign in again.",
38
+ admin_unban_title: "Unban user",
39
+ form_cancel: "Cancel",
40
+ user_role_default: "user",
41
+ },
42
+ fr: {
43
+ admin_action_ban: "Bannir",
44
+ admin_action_impersonate: "Emprunter l'identité",
45
+ admin_action_unban: "Débannir",
46
+ admin_ban_description: "Êtes-vous sûr de vouloir bannir {name} ({email}) ? Il ne pourra plus se connecter.",
47
+ admin_ban_title: "Bannir l'utilisateur",
48
+ admin_column_created: "Créé",
49
+ admin_column_role: "Rôle",
50
+ admin_column_status: "Statut",
51
+ admin_column_unverified: "Non vérifié",
52
+ admin_column_user: "Utilisateur",
53
+ admin_column_verified: "Vérifié",
54
+ admin_error_access_required: "Accès administrateur requis.",
55
+ admin_error_ban: "Impossible de bannir l'utilisateur.",
56
+ admin_error_impersonate: "Impossible d'emprunter l'identité de l'utilisateur.",
57
+ admin_error_unban: "Impossible de débannir l'utilisateur.",
58
+ admin_status_active: "Actif",
59
+ admin_status_banned: "Banni",
60
+ admin_unban_description: "Êtes-vous sûr de vouloir débannir {name} ({email}) ? Il pourra se reconnecter.",
61
+ admin_unban_title: "Débannir l'utilisateur",
62
+ form_cancel: "Annuler",
63
+ user_role_default: "utilisateur",
64
+ },
65
+ };
66
+ const labels = (locale) => ({
67
+ ...defaultMessages[locale],
68
+ });
69
+ const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
70
+ const adminUsersQuery = (search, projectId) => {
71
+ const query = {
72
+ page: search.page ?? 0,
73
+ pageSize: search.pageSize ?? 10,
74
+ ...(search.globalFilter ? { globalFilter: search.globalFilter } : {}),
75
+ ...(search.sort ? { sort: search.sort } : {}),
76
+ ...(projectId ? { projectId } : {}),
77
+ };
78
+ return {
79
+ query,
80
+ key: JSON.stringify(query),
81
+ };
82
+ };
83
+ const usersAtom = Atom.family(({ projectId, reloadKey, search, }) => {
84
+ const request = adminUsersQuery(search, projectId);
85
+ return AdminApiClient.query("admin", "listUsers", {
86
+ query: request.query,
87
+ timeToLive: "1 minute",
88
+ reactivityKeys: [
89
+ "admin-users",
90
+ ...(projectId ? [`project:${projectId}`] : []),
91
+ ],
92
+ serializationKey: `admin-users:${reloadKey}:${request.key}`,
93
+ });
94
+ });
95
+ const banUser = async (userId, m) => {
96
+ const result = await authClient.admin.banUser({ userId });
97
+ if (result.error)
98
+ throw new Error(result.error.message ?? m.admin_error_ban);
99
+ };
100
+ const unbanUser = async (userId, m) => {
101
+ const result = await authClient.admin.unbanUser({ userId });
102
+ if (result.error)
103
+ throw new Error(result.error.message ?? m.admin_error_unban);
104
+ };
105
+ const impersonateUser = async (userId, m) => {
106
+ const result = await authClient.admin.impersonateUser({ userId });
107
+ if (result.error)
108
+ throw new Error(result.error.message ?? m.admin_error_impersonate);
109
+ };
110
+ export function AdminUsersTable({ from, reloadKey = 0, search, }) {
111
+ const navigate = useNavigate();
112
+ const auth = useKrakstackAuth();
113
+ const m = labels(auth?.locale ?? "en");
114
+ const projectId = auth?.projectId;
115
+ const [impersonatingUserId, setImpersonatingUserId] = useState(null);
116
+ const [impersonateError, setImpersonateError] = useState("");
117
+ const [refreshKey, setRefreshKey] = useState(0);
118
+ const result = useAtomValue(usersAtom({ projectId, search, reloadKey: reloadKey + refreshKey }));
119
+ const [banningUser, setBanningUser] = useState(null);
120
+ const [unbanningUser, setUnbanningUser] = useState(null);
121
+ const users = AsyncResult.match(result, {
122
+ onInitial: () => [],
123
+ onFailure: () => [],
124
+ onSuccess: ({ value }) => Array.from(value.data),
125
+ });
126
+ const total = AsyncResult.match(result, {
127
+ onInitial: () => 0,
128
+ onFailure: () => 0,
129
+ onSuccess: ({ value }) => value.meta.total,
130
+ });
131
+ const error = AsyncResult.match(result, {
132
+ onInitial: () => "",
133
+ onFailure: () => m.admin_error_access_required,
134
+ onSuccess: () => "",
135
+ });
136
+ const isLoading = AsyncResult.match(result, {
137
+ onInitial: () => true,
138
+ onFailure: () => false,
139
+ onSuccess: () => false,
140
+ });
141
+ return (_jsxs(_Fragment, { children: [error ? _jsx(ErrorMessage, { text: error }) : null, impersonateError ? _jsx(ErrorMessage, { text: impersonateError }) : null, _jsx(DataTable, { columns: userColumns(m), data: users, exportFileName: "users.csv", features: { gallery: false }, ...(from ? { from } : {}), isLoading: isLoading, onRefresh: () => setRefreshKey((current) => current + 1), serverPagination: { rowCount: total }, rowActions: [
142
+ {
143
+ name: m.admin_action_impersonate,
144
+ icon: impersonatingUserId ? (_jsx(Loader2, { className: "size-4 animate-spin" })) : (_jsx(UserCog, { className: "size-4" })),
145
+ onClick: async (user) => {
146
+ setImpersonateError("");
147
+ setImpersonatingUserId(user.id);
148
+ try {
149
+ await impersonateUser(user.id, m);
150
+ await navigate({ to: "/" });
151
+ }
152
+ catch (cause) {
153
+ setImpersonateError(cause instanceof Error
154
+ ? cause.message
155
+ : m.admin_error_impersonate);
156
+ }
157
+ finally {
158
+ setImpersonatingUserId(null);
159
+ }
160
+ },
161
+ visible: (user) => !user.banned,
162
+ },
163
+ {
164
+ name: m.admin_action_ban,
165
+ icon: _jsx(Ban, { className: "size-4" }),
166
+ variant: "destructive",
167
+ onClick: (user) => setBanningUser(user),
168
+ visible: (user) => !user.banned,
169
+ },
170
+ {
171
+ name: m.admin_action_unban,
172
+ icon: _jsx(ShieldOff, { className: "size-4" }),
173
+ onClick: (user) => setUnbanningUser(user),
174
+ visible: (user) => !!user.banned,
175
+ },
176
+ ] }), banningUser ? (_jsx(BanUserDialog, { labels: m, user: banningUser, onBanned: () => setRefreshKey((current) => current + 1), onClose: () => setBanningUser(null) })) : null, unbanningUser ? (_jsx(UnbanUserDialog, { labels: m, user: unbanningUser, onUnbanned: () => setRefreshKey((current) => current + 1), onClose: () => setUnbanningUser(null) })) : null] }));
177
+ }
178
+ export function useAdminUsersTotal(search) {
179
+ const projectId = useKrakstackAuth()?.projectId;
180
+ const result = useAtomValue(usersAtom({ projectId, search, reloadKey: 0 }));
181
+ return AsyncResult.match(result, {
182
+ onInitial: () => 0,
183
+ onFailure: () => 0,
184
+ onSuccess: ({ value }) => value.meta.total,
185
+ });
186
+ }
187
+ const userColumns = (m) => [
188
+ {
189
+ accessorKey: "email",
190
+ header: m.admin_column_user,
191
+ cell: ({ row }) => {
192
+ const image = assetUrl(row.original.image, authBaseUrl);
193
+ return (_jsx(AppBrand, { to: null, label: row.original.email, subtitle: row.original.name, icon: UserIcon, className: "min-w-48", ...(image ? { imageSrc: image } : {}) }));
194
+ },
195
+ },
196
+ {
197
+ accessorKey: "emailVerified",
198
+ header: m.admin_column_verified,
199
+ cell: ({ row }) => row.original.emailVerified ? (_jsx(Badge, { variant: "outline", children: m.admin_column_verified })) : (_jsx(Badge, { variant: "secondary", children: m.admin_column_unverified })),
200
+ },
201
+ {
202
+ accessorKey: "role",
203
+ header: m.admin_column_role,
204
+ cell: ({ row }) => {
205
+ const role = row.original.role;
206
+ if (!role)
207
+ return _jsx(Badge, { variant: "outline", children: m.user_role_default });
208
+ 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()))) }));
209
+ },
210
+ },
211
+ {
212
+ accessorKey: "banned",
213
+ header: m.admin_column_status,
214
+ cell: ({ row }) => row.original.banned ? (_jsx(Badge, { variant: "destructive", children: m.admin_status_banned })) : (_jsx(Badge, { variant: "outline", children: m.admin_status_active })),
215
+ },
216
+ {
217
+ accessorKey: "createdAt",
218
+ header: m.admin_column_created,
219
+ cell: ({ row }) => (_jsx("span", { className: "text-muted-foreground text-sm", children: new Date(row.original.createdAt).toLocaleDateString() })),
220
+ },
221
+ ];
222
+ function BanUserDialog({ labels: m, user, onBanned, onClose, }) {
223
+ const [isPending, setIsPending] = useState(false);
224
+ const [error, setError] = useState("");
225
+ 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, {
226
+ name: user.name,
227
+ email: user.email,
228
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: async () => {
229
+ setError("");
230
+ setIsPending(true);
231
+ try {
232
+ await banUser(user.id, m);
233
+ onBanned();
234
+ onClose();
235
+ }
236
+ catch (cause) {
237
+ setError(cause instanceof Error ? cause.message : m.admin_error_ban);
238
+ }
239
+ finally {
240
+ setIsPending(false);
241
+ }
242
+ }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_ban] })] })] }) }));
243
+ }
244
+ function UnbanUserDialog({ labels: m, user, onUnbanned, onClose, }) {
245
+ const [isPending, setIsPending] = useState(false);
246
+ const [error, setError] = useState("");
247
+ 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, {
248
+ name: user.name,
249
+ email: user.email,
250
+ }) })] }), error ? _jsx(ErrorMessage, { text: error }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { disabled: isPending, children: m.form_cancel }), _jsxs(AlertDialogAction, { onClick: async () => {
251
+ setError("");
252
+ setIsPending(true);
253
+ try {
254
+ await unbanUser(user.id, m);
255
+ onUnbanned();
256
+ onClose();
257
+ }
258
+ catch (cause) {
259
+ setError(cause instanceof Error ? cause.message : m.admin_error_unban);
260
+ }
261
+ finally {
262
+ setIsPending(false);
263
+ }
264
+ }, disabled: isPending, children: [isPending ? (_jsx(Loader2, { className: "animate-spin", "data-icon": "inline-start" })) : null, m.admin_action_unban] })] })] }) }));
265
+ }
@@ -20,6 +20,7 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
20
20
  readonly image: import("effect/Schema").NullOr<import("effect/Schema").String>;
21
21
  readonly role: import("effect/Schema").NullOr<import("effect/Schema").String>;
22
22
  readonly banned: import("effect/Schema").NullOr<import("effect/Schema").Boolean>;
23
+ readonly lastLoginMethod: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
23
24
  readonly createdAt: import("effect/Schema").Date;
24
25
  readonly updatedAt: import("effect/Schema").Date;
25
26
  }>;
@@ -35,6 +36,7 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
35
36
  readonly projectId: import("effect/Schema").optional<import("effect/Schema").String>;
36
37
  readonly clientId: import("effect/Schema").optional<import("effect/Schema").String>;
37
38
  readonly host: import("effect/Schema").optional<import("effect/Schema").String>;
39
+ readonly rootHost: import("effect/Schema").optional<import("effect/Schema").String>;
38
40
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<never>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<import("effect/Schema").Struct<{
39
41
  readonly projectKey: import("effect/Schema").String;
40
42
  readonly name: import("effect/Schema").NullOr<import("effect/Schema").String>;
@@ -100,7 +102,11 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
100
102
  readonly hostname: import("effect/Schema").String;
101
103
  readonly rootHostname: import("effect/Schema").String;
102
104
  readonly projectId: import("effect/Schema").NullOr<import("effect/Schema").String>;
105
+ readonly projectName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
106
+ readonly projectLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
103
107
  readonly organizationId: import("effect/Schema").NullOr<import("effect/Schema").String>;
108
+ readonly organizationName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
109
+ readonly organizationLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
104
110
  readonly hostnameId: import("effect/Schema").String;
105
111
  readonly managed: import("effect/Schema").Boolean;
106
112
  readonly active: import("effect/Schema").Boolean;
@@ -113,7 +119,11 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
113
119
  readonly hostname: import("effect/Schema").String;
114
120
  readonly rootHostname: import("effect/Schema").String;
115
121
  readonly projectId: import("effect/Schema").NullOr<import("effect/Schema").String>;
122
+ readonly projectName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
123
+ readonly projectLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
116
124
  readonly organizationId: import("effect/Schema").NullOr<import("effect/Schema").String>;
125
+ readonly organizationName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
126
+ readonly organizationLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
117
127
  readonly hostnameId: import("effect/Schema").String;
118
128
  readonly managed: import("effect/Schema").Boolean;
119
129
  readonly active: import("effect/Schema").Boolean;
@@ -126,7 +136,11 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
126
136
  readonly hostname: import("effect/Schema").String;
127
137
  readonly rootHostname: import("effect/Schema").String;
128
138
  readonly projectId: import("effect/Schema").NullOr<import("effect/Schema").String>;
139
+ readonly projectName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
140
+ readonly projectLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
129
141
  readonly organizationId: import("effect/Schema").NullOr<import("effect/Schema").String>;
142
+ readonly organizationName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
143
+ readonly organizationLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
130
144
  readonly hostnameId: import("effect/Schema").String;
131
145
  readonly managed: import("effect/Schema").Boolean;
132
146
  readonly active: import("effect/Schema").Boolean;
@@ -139,7 +153,11 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
139
153
  readonly hostname: import("effect/Schema").String;
140
154
  readonly rootHostname: import("effect/Schema").String;
141
155
  readonly projectId: import("effect/Schema").NullOr<import("effect/Schema").String>;
156
+ readonly projectName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
157
+ readonly projectLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
142
158
  readonly organizationId: import("effect/Schema").NullOr<import("effect/Schema").String>;
159
+ readonly organizationName: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
160
+ readonly organizationLogo: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
143
161
  readonly hostnameId: import("effect/Schema").String;
144
162
  readonly managed: import("effect/Schema").Boolean;
145
163
  readonly active: import("effect/Schema").Boolean;
@@ -170,6 +188,7 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
170
188
  readonly image: import("effect/Schema").NullOr<import("effect/Schema").String>;
171
189
  readonly role: import("effect/Schema").NullOr<import("effect/Schema").String>;
172
190
  readonly banned: import("effect/Schema").NullOr<import("effect/Schema").Boolean>;
191
+ readonly lastLoginMethod: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
173
192
  readonly createdAt: import("effect/Schema").Date;
174
193
  readonly updatedAt: import("effect/Schema").Date;
175
194
  }>;
@@ -207,6 +226,7 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
207
226
  readonly image: import("effect/Schema").NullOr<import("effect/Schema").String>;
208
227
  readonly role: import("effect/Schema").NullOr<import("effect/Schema").String>;
209
228
  readonly banned: import("effect/Schema").NullOr<import("effect/Schema").Boolean>;
229
+ readonly lastLoginMethod: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
210
230
  readonly createdAt: import("effect/Schema").Date;
211
231
  readonly updatedAt: import("effect/Schema").Date;
212
232
  }>;
@@ -242,6 +262,7 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
242
262
  readonly image: import("effect/Schema").NullOr<import("effect/Schema").String>;
243
263
  readonly role: import("effect/Schema").NullOr<import("effect/Schema").String>;
244
264
  readonly banned: import("effect/Schema").NullOr<import("effect/Schema").Boolean>;
265
+ readonly lastLoginMethod: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
245
266
  readonly createdAt: import("effect/Schema").Date;
246
267
  readonly updatedAt: import("effect/Schema").Date;
247
268
  }>>, import("effect/unstable/httpapi/HttpApiEndpoint").Json<typeof import("effect/unstable/httpapi/HttpApiError").Unauthorized | typeof import("effect/unstable/httpapi/HttpApiError").NotFound | typeof import("effect/unstable/httpapi/HttpApiError").InternalServerError>, never, never> | import("effect/unstable/httpapi/HttpApiEndpoint").HttpApiEndpoint<"getUserActiveOrganization", "GET", "/api/organizations/user/:userId/active", import("effect/unstable/httpapi/HttpApiEndpoint").StringTree<import("effect/Schema").Struct<{
@@ -259,6 +280,7 @@ export declare const authApiClient: (baseUrl?: string | undefined) => AtomHttpAp
259
280
  readonly image: import("effect/Schema").NullOr<import("effect/Schema").String>;
260
281
  readonly role: import("effect/Schema").NullOr<import("effect/Schema").String>;
261
282
  readonly banned: import("effect/Schema").NullOr<import("effect/Schema").Boolean>;
283
+ readonly lastLoginMethod: import("effect/Schema").optional<import("effect/Schema").NullOr<import("effect/Schema").String>>;
262
284
  readonly createdAt: import("effect/Schema").Date;
263
285
  readonly updatedAt: import("effect/Schema").Date;
264
286
  }>>;
@@ -1,9 +1,11 @@
1
1
  import type { apiKeyClient } from "@better-auth/api-key/client";
2
- import type { emailOTPClient, genericOAuthClient, organizationClient, twoFactorClient } from "better-auth/client/plugins";
2
+ import type { adminClient, emailOTPClient, genericOAuthClient, lastLoginMethodClient, organizationClient, twoFactorClient } from "better-auth/client/plugins";
3
3
  import type { createAuthClient } from "better-auth/react";
4
4
  export type AuthUiClient = ReturnType<typeof createAuthClient<{
5
5
  plugins: [
6
+ ReturnType<typeof adminClient>,
6
7
  ReturnType<typeof emailOTPClient>,
8
+ ReturnType<typeof lastLoginMethodClient>,
7
9
  ReturnType<typeof organizationClient>,
8
10
  ReturnType<typeof twoFactorClient>,
9
11
  ReturnType<typeof apiKeyClient>,
@@ -161,6 +161,7 @@ const useAuthProjectConfig = (baseUrl, searchString, projectConfig) => {
161
161
  };
162
162
  const text = (value, params) => Object.entries(params ?? {}).reduce((current, [key, replacement]) => current.replace(`{${key}}`, replacement), value);
163
163
  const authLinkClassName = cn(buttonVariants({ variant: "link" }), "h-auto px-0 align-baseline");
164
+ const lastLoginMethodToAuthMethod = (method) => method === "email" ? "password" : "emailOtp";
164
165
  const searchObject = (searchString) => Object.fromEntries(new URLSearchParams(searchString));
165
166
  export function Signin(props) {
166
167
  const { authClient, baseUrl, labels: m, projectConfig: providedProjectConfig, } = useAuthFormOptions(props);
@@ -182,7 +183,7 @@ export function Signin(props) {
182
183
  signUp: authOptions.signUp ?? true,
183
184
  };
184
185
  const [emailSubmitted, setEmailSubmitted] = useState(false);
185
- const [authMethod, setAuthMethod] = useState("password");
186
+ const [authMethod, setAuthMethod] = useState(() => lastLoginMethodToAuthMethod(authClient.getLastUsedLoginMethod?.()));
186
187
  const [otpSentTo, setOtpSentTo] = useState("");
187
188
  const [emailOtpResendAvailableAt, setEmailOtpResendAvailableAt] = useState(0);
188
189
  const [emailOtpResendSeconds, setEmailOtpResendSeconds] = useState(0);
@@ -349,7 +350,12 @@ export function Signin(props) {
349
350
  event.preventDefault();
350
351
  event.stopPropagation();
351
352
  form.handleSubmit();
352
- }, children: [!emailSubmitted ? (_jsx(form.AppField, { name: "email", children: (field) => (_jsx(field.TextField, { label: m.field_email, type: "email", autoComplete: "email", required: true })) })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.field_password, type: "password", autoComplete: "current-password", required: true })) }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [_jsx(Link, { className: authLinkClassName, to: "/forgot-password", search: searchObject(searchString), children: m.sign_in_forgot_password }), canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(Mail, {}), m.sign_in_use_email_otp] })) : null] })] })) : null, emailSubmitted && selectedAuthMethod === "emailOtp" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.AppField, { name: "otp", children: (field) => (_jsx(OtpInput, { field: field, label: m.sign_in_email_otp_code })) }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [otpSentTo ? (_jsx(Button, { type: "button", variant: "link", className: "h-auto px-0", disabled: emailOtpResendSeconds > 0, onClick: resendEmailOtp, children: emailOtpResendSeconds > 0
353
+ }, children: [!emailSubmitted ? (_jsx(form.AppField, { name: "email", children: (field) => (_jsx(field.TextField, { label: m.field_email, type: "email", autoComplete: "email", onKeyDown: (event) => {
354
+ if (event.key !== "Enter")
355
+ return;
356
+ event.preventDefault();
357
+ form.handleSubmit();
358
+ }, required: true })) })) : null, emailSubmitted && selectedAuthMethod === "password" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.field_password, type: "password", autoComplete: "current-password", required: true })) }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [_jsx(Link, { className: authLinkClassName, to: "/forgot-password", search: searchObject(searchString), children: m.sign_in_forgot_password }), canChangeAuthMethod ? (_jsxs(Button, { type: "button", variant: "link", className: "h-auto px-0", onClick: switchAuthMethod, children: [_jsx(Mail, {}), m.sign_in_use_email_otp] })) : null] })] })) : null, emailSubmitted && selectedAuthMethod === "emailOtp" ? (_jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(form.AppField, { name: "otp", children: (field) => (_jsx(OtpInput, { field: field, label: m.sign_in_email_otp_code })) }), _jsxs("div", { className: "flex flex-wrap gap-x-4 gap-y-2 text-sm", children: [otpSentTo ? (_jsx(Button, { type: "button", variant: "link", className: "h-auto px-0", disabled: emailOtpResendSeconds > 0, onClick: resendEmailOtp, children: emailOtpResendSeconds > 0
353
359
  ? text(m.sign_in_email_otp_resend_countdown, {
354
360
  seconds: String(emailOtpResendSeconds),
355
361
  })
@@ -635,28 +641,8 @@ const getAuthRedirectParam = (searchString) => {
635
641
  search.get("redirectTo") ??
636
642
  search.get("returnTo"));
637
643
  };
638
- const getDefaultAuthRedirectTarget = (projectAuthDomain, projectRootDomain) => {
639
- if (typeof window === "undefined")
640
- return "/admin";
641
- const currentHost = normalizeAuthHost(window.location.host);
642
- const isProjectDomain = normalizeAuthHost(projectAuthDomain) === currentHost;
643
- if (!isProjectDomain)
644
- return "/admin";
645
- const rootDomain = normalizeAuthHost(projectRootDomain);
646
- if (!rootDomain)
647
- return "/admin";
648
- return `${window.location.protocol}//${rootDomain}`;
649
- };
650
- const normalizeAuthHost = (value) => {
651
- const raw = value?.trim().toLowerCase();
652
- if (!raw)
653
- return null;
654
- try {
655
- return new URL(raw.includes("://") ? raw : `https://${raw}`).host;
656
- }
657
- catch {
658
- return raw.split("/")[0]?.trim() || null;
659
- }
644
+ const getDefaultAuthRedirectTarget = (_projectAuthDomain, _projectRootDomain) => {
645
+ return "/admin";
660
646
  };
661
647
  const getSearchParam = (searchString, key) => new URLSearchParams(searchString).get(key);
662
648
  const getBrowserAuthHost = () => typeof window === "undefined" ? null : window.location.host;
@@ -12,23 +12,24 @@ export type KrakstackAuthProviderProps = {
12
12
  export type KrakstackAuthContextValue = {
13
13
  locale: KrakstackAuthLocale;
14
14
  baseUrl?: string | undefined;
15
+ projectId?: string | null | undefined;
15
16
  authClient: AuthUiClient;
16
17
  projectConfig: ExtraProjectPublicConfig | null;
17
18
  };
18
19
  export declare function KrakstackAuthProvider({ children, locale, baseUrl, projectId, authClient, }: KrakstackAuthProviderProps): import("react").JSX.Element;
19
20
  export declare const useKrakstackAuth: () => KrakstackAuthContextValue | null;
20
- export declare const useKrakstackAuthProjectConfig: () => {
21
- readonly projectKey: string;
22
- readonly name: string | null;
23
- readonly logoUrl: string | null;
24
- readonly authDomain: string | null;
25
- readonly rootDomain: string | null;
26
- readonly themeCss: string | null;
27
- readonly authOptions: {
28
- readonly emailPassword: boolean;
29
- readonly emailOtp: boolean;
30
- readonly google: boolean;
31
- readonly signUp: boolean;
32
- readonly signUpName: boolean;
33
- };
34
- } | null;
21
+ export declare const useKrakstackAuthProjectConfig: () => import("effect/Schema").Struct.ReadonlySide<{
22
+ readonly projectKey: import("effect/Schema").String;
23
+ readonly name: import("effect/Schema").NullOr<import("effect/Schema").String>;
24
+ readonly logoUrl: import("effect/Schema").NullOr<import("effect/Schema").String>;
25
+ readonly authDomain: import("effect/Schema").NullOr<import("effect/Schema").String>;
26
+ readonly rootDomain: import("effect/Schema").NullOr<import("effect/Schema").String>;
27
+ readonly themeCss: import("effect/Schema").NullOr<import("effect/Schema").String>;
28
+ readonly authOptions: import("effect/Schema").Struct<{
29
+ readonly emailPassword: import("effect/Schema").Boolean;
30
+ readonly emailOtp: import("effect/Schema").Boolean;
31
+ readonly google: import("effect/Schema").Boolean;
32
+ readonly signUp: import("effect/Schema").Boolean;
33
+ readonly signUpName: import("effect/Schema").Boolean;
34
+ }>;
35
+ }, "Type"> | null;
@@ -2,15 +2,28 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { apiKeyClient } from "@better-auth/api-key/client";
3
3
  import { useAtomSuspense } from "@effect/atom-react";
4
4
  import { useRouterState } from "@tanstack/react-router";
5
- import { emailOTPClient, genericOAuthClient, organizationClient, twoFactorClient, } from "better-auth/client/plugins";
5
+ import { adminClient, emailOTPClient, genericOAuthClient, lastLoginMethodClient, organizationClient, twoFactorClient, } from "better-auth/client/plugins";
6
6
  import { createAuthClient } from "better-auth/react";
7
- import { createContext, useContext, useMemo } from "react";
7
+ import { createContext, useContext, useEffect, useMemo, } from "react";
8
8
  import { authApiClient } from "./auth-api-client";
9
9
  const KrakstackAuthContext = createContext(null);
10
+ const PROJECT_CONTEXT_COOKIE = "krakstack-auth.project_context";
11
+ const setProjectContextCookie = (projectId) => {
12
+ if (typeof document === "undefined")
13
+ return;
14
+ const secure = window.location.protocol === "https:" ? "; Secure" : "";
15
+ if (!projectId) {
16
+ document.cookie = `${PROJECT_CONTEXT_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
17
+ return;
18
+ }
19
+ document.cookie = `${PROJECT_CONTEXT_COOKIE}=${encodeURIComponent(projectId)}; Path=/; Max-Age=600; SameSite=Lax${secure}`;
20
+ };
10
21
  const createAuthUiClient = (baseUrl) => createAuthClient({
11
22
  ...(baseUrl ? { baseURL: baseUrl } : {}),
12
23
  plugins: [
24
+ adminClient(),
13
25
  emailOTPClient(),
26
+ lastLoginMethodClient(),
14
27
  organizationClient(),
15
28
  twoFactorClient(),
16
29
  apiKeyClient(),
@@ -23,6 +36,24 @@ const getSearchParam = (searchString, key) => {
23
36
  return new URLSearchParams(searchString).get(key);
24
37
  };
25
38
  const getBrowserAuthHost = () => typeof window === "undefined" ? null : window.location.host;
39
+ const getRedirectHost = (searchString) => {
40
+ if (!searchString)
41
+ return null;
42
+ const search = new URLSearchParams(searchString);
43
+ const target = search.get("callbackURL") ??
44
+ search.get("redirect") ??
45
+ search.get("redirectTo") ??
46
+ search.get("returnTo") ??
47
+ search.get("redirect_uri");
48
+ if (!target)
49
+ return null;
50
+ try {
51
+ return new URL(target).host;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ };
26
57
  const useProjectConfig = (baseUrl, providedProjectId) => {
27
58
  const searchString = useRouterState({
28
59
  select: (state) => state.location.searchStr,
@@ -30,11 +61,13 @@ const useProjectConfig = (baseUrl, providedProjectId) => {
30
61
  const projectId = providedProjectId ?? getSearchParam(searchString, "projectId");
31
62
  const clientId = getSearchParam(searchString, "client_id");
32
63
  const host = getBrowserAuthHost();
64
+ const rootHost = getRedirectHost(searchString);
33
65
  const result = useAtomSuspense(authApiClient(baseUrl).query("authExtra", "getProjectPublicConfig", {
34
66
  query: {
35
67
  ...(projectId ? { projectId } : {}),
36
68
  ...(clientId ? { clientId } : {}),
37
69
  ...(host ? { host } : {}),
70
+ ...(rootHost ? { rootHost } : {}),
38
71
  },
39
72
  timeToLive: "5 minutes",
40
73
  reactivityKeys: [
@@ -42,15 +75,29 @@ const useProjectConfig = (baseUrl, providedProjectId) => {
42
75
  ...(projectId ? [`project:${projectId}`] : []),
43
76
  ...(clientId ? [`client:${clientId}`] : []),
44
77
  ...(host ? [`host:${host}`] : []),
78
+ ...(rootHost ? [`root-host:${rootHost}`] : []),
45
79
  ],
46
- serializationKey: `project-public-config:${projectId ?? ""}:${clientId ?? ""}:${host ?? ""}`,
80
+ serializationKey: `project-public-config:${projectId ?? ""}:${clientId ?? ""}:${host ?? ""}:${rootHost ?? ""}`,
47
81
  }), { suspendOnWaiting: true });
48
82
  return result.value;
49
83
  };
50
84
  export function KrakstackAuthProvider({ children, locale = "en", baseUrl, projectId, authClient, }) {
85
+ const searchString = useRouterState({
86
+ select: (state) => state.location.searchStr,
87
+ });
88
+ const resolvedProjectId = projectId ?? getSearchParam(searchString, "projectId");
51
89
  const resolvedAuthClient = useMemo(() => authClient ?? createAuthUiClient(baseUrl), [authClient, baseUrl]);
52
90
  const projectConfig = useProjectConfig(baseUrl, projectId);
53
- const value = useMemo(() => ({ authClient: resolvedAuthClient, baseUrl, locale, projectConfig }), [resolvedAuthClient, baseUrl, locale, projectConfig]);
91
+ useEffect(() => {
92
+ setProjectContextCookie(resolvedProjectId);
93
+ }, [resolvedProjectId]);
94
+ const value = useMemo(() => ({
95
+ authClient: resolvedAuthClient,
96
+ baseUrl,
97
+ locale,
98
+ projectId: resolvedProjectId,
99
+ projectConfig,
100
+ }), [resolvedAuthClient, baseUrl, locale, resolvedProjectId, projectConfig]);
54
101
  return (_jsx(KrakstackAuthContext.Provider, { value: value, children: children }));
55
102
  }
56
103
  export const useKrakstackAuth = () => useContext(KrakstackAuthContext);
@@ -2,6 +2,9 @@ export { KrakstackAuthProvider, useKrakstackAuth, useKrakstackAuthProjectConfig,
2
2
  export { OrganizationSwitcher } from "./organization-switcher";
3
3
  export { ResetPassword, Signin, Signup, TwoFactor } from "./auth-forms";
4
4
  export { UserButton } from "./user-button";
5
+ export { AdminOrganizationsTable } from "./admin-organizations";
6
+ export { AdminOrganizationForm } from "./admin-organization-form";
7
+ export { AdminUsersTable, useAdminUsersTotal } from "./admin-users";
5
8
  export type { KrakstackAuthContextValue, KrakstackAuthLocale, KrakstackAuthProviderProps, } from "./auth-provider";
6
9
  export type { OrganizationSwitcherDialog } from "./organization-switcher";
7
10
  export type { UserButtonDialog } from "./user-button";
@@ -2,3 +2,6 @@ export { KrakstackAuthProvider, useKrakstackAuth, useKrakstackAuthProjectConfig,
2
2
  export { OrganizationSwitcher } from "./organization-switcher";
3
3
  export { ResetPassword, Signin, Signup, TwoFactor } from "./auth-forms";
4
4
  export { UserButton } from "./user-button";
5
+ export { AdminOrganizationsTable } from "./admin-organizations";
6
+ export { AdminOrganizationForm } from "./admin-organization-form";
7
+ export { AdminUsersTable, useAdminUsersTotal } from "./admin-users";