@krak-stack/auth 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +26 -7
  2. package/dist/backend/api.d.ts +80 -6
  3. package/dist/backend/api.d.ts.map +1 -1
  4. package/dist/backend/api.js +31 -4
  5. package/dist/backend/api.js.map +1 -1
  6. package/dist/backend/index.d.ts +100 -41
  7. package/dist/backend/index.d.ts.map +1 -1
  8. package/dist/backend/index.js +5 -12
  9. package/dist/backend/index.js.map +1 -1
  10. package/dist/backend/schema.d.ts +12 -1
  11. package/dist/backend/schema.d.ts.map +1 -1
  12. package/dist/backend/schema.js +11 -3
  13. package/dist/backend/schema.js.map +1 -1
  14. package/dist/components/index.d.ts +3 -0
  15. package/dist/components/index.d.ts.map +1 -0
  16. package/dist/components/index.js +3 -0
  17. package/dist/components/index.js.map +1 -0
  18. package/dist/components/organization-switcher.d.ts +11 -0
  19. package/dist/components/organization-switcher.d.ts.map +1 -0
  20. package/dist/components/organization-switcher.js +569 -0
  21. package/dist/components/organization-switcher.js.map +1 -0
  22. package/dist/components/user-button.d.ts +11 -0
  23. package/dist/components/user-button.d.ts.map +1 -0
  24. package/dist/components/user-button.js +613 -0
  25. package/dist/components/user-button.js.map +1 -0
  26. package/dist/frontend/api.d.ts +18 -2
  27. package/dist/frontend/api.d.ts.map +1 -1
  28. package/dist/frontend/index.d.ts +35 -11
  29. package/dist/frontend/index.d.ts.map +1 -1
  30. package/dist/frontend/index.js +4 -4
  31. package/dist/frontend/index.js.map +1 -1
  32. package/dist/frontend/schema.d.ts +9 -1
  33. package/dist/frontend/schema.d.ts.map +1 -1
  34. package/dist/index.d.ts +2 -2
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +2 -2
  37. package/dist/index.js.map +1 -1
  38. package/dist/schema.d.ts +29 -1
  39. package/dist/schema.d.ts.map +1 -1
  40. package/dist/schema.js +61 -2
  41. package/dist/schema.js.map +1 -1
  42. package/package.json +13 -2
@@ -0,0 +1,613 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import {} from "@tanstack/react-table";
3
+ import { useNavigate, useRouterState, } from "@tanstack/react-router";
4
+ import { Check, Copy, KeyRound, LogOutIcon, ShieldCheck, Trash2, UserCircleIcon, UserIcon, } from "lucide-react";
5
+ import { QRCode } from "react-qr-code";
6
+ import { useEffect, useState, } from "react";
7
+ import { createDataTableActionsColumn, DataTable, } from "@/components/ui/data-table";
8
+ import { AppBrand } from "@/components/ui/app-brand";
9
+ import { useAppForm } from "@/components/ui/form";
10
+ import { Badge } from "@/components/ui/badge";
11
+ import { Button } from "@/components/ui/button";
12
+ import { Checkbox } from "@/components/ui/checkbox";
13
+ import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog";
14
+ import { Field, FieldContent, FieldDescription, FieldGroup, FieldLabel, FieldLegend, FieldSet, } from "@/components/ui/field";
15
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu";
16
+ import { Separator } from "@/components/ui/separator";
17
+ import { m } from "@/paraglide/messages";
18
+ import { authClient } from "@/services/auth/client";
19
+ import { centralAuthClient } from "@/services/auth/client/central";
20
+ const isFile = (value) => value instanceof File;
21
+ const authUrl = (path) => new URL(path, import.meta.env.VITE_KRAKSTACK_AUTH_URL ??
22
+ globalThis.location?.origin ??
23
+ "http://localhost:3000").toString();
24
+ const presignUserImageUpload = async (file) => {
25
+ const response = await fetch(authUrl("/api/auth/image/presign"), {
26
+ method: "POST",
27
+ credentials: "include",
28
+ headers: { "Content-Type": "application/json" },
29
+ body: JSON.stringify({ fileName: file.name, contentType: file.type }),
30
+ });
31
+ if (!response.ok) {
32
+ throw new Error(m.user_profile_image_upload_error());
33
+ }
34
+ const body = await response.json();
35
+ if (typeof body !== "object" || body === null) {
36
+ throw new Error(m.user_profile_image_upload_error());
37
+ }
38
+ const uploadUrl = Reflect.get(body, "uploadUrl");
39
+ const url = Reflect.get(body, "url");
40
+ if (typeof uploadUrl !== "string" || typeof url !== "string") {
41
+ throw new Error(m.user_profile_image_upload_error());
42
+ }
43
+ return { uploadUrl, url };
44
+ };
45
+ export const UserButton = ({ signOutRedirect = "/", side = "bottom", renderUnauthenticated, apiKeyPermissions, }) => {
46
+ const navigate = useNavigate();
47
+ const currentSiteHref = useRouterState({
48
+ select: (state) => `${import.meta.env.VITE_SITE_URL}${state.location.href}`,
49
+ });
50
+ const { data: session, isPending, refetch } = authClient.useSession();
51
+ const centralSession = centralAuthClient.useSession();
52
+ const [settingsDialog, setSettingsDialog] = useState(null);
53
+ const [formError, setFormError] = useState(null);
54
+ const [centralAuthError, setCentralAuthError] = useState(null);
55
+ if (!session) {
56
+ return _jsx(_Fragment, { children: renderUnauthenticated?.() });
57
+ }
58
+ const displayName = session.user.name.trim();
59
+ const displayEmail = session.user.email.trim();
60
+ const displayImage = session.user.image?.trim()
61
+ ? authUrl(session.user.image.trim())
62
+ : "";
63
+ const signOut = async () => {
64
+ const redirectUrl = signOutRedirect.startsWith("http")
65
+ ? signOutRedirect
66
+ : `${import.meta.env.VITE_SITE_URL}${signOutRedirect.startsWith("/") ? signOutRedirect : `/${signOutRedirect}`}`;
67
+ await Promise.allSettled([
68
+ authClient.signOut(),
69
+ centralAuthClient.signOut(),
70
+ ]);
71
+ await navigate({ href: redirectUrl });
72
+ };
73
+ const updateUser = async (values) => {
74
+ setFormError(null);
75
+ const imageFile = isFile(values.image) ? values.image : null;
76
+ const image = imageFile
77
+ ? await (async () => {
78
+ const presigned = await presignUserImageUpload(imageFile);
79
+ const uploadResponse = await fetch(presigned.uploadUrl, {
80
+ method: "PUT",
81
+ headers: { "Content-Type": imageFile.type },
82
+ body: imageFile,
83
+ });
84
+ if (!uploadResponse.ok) {
85
+ throw new Error(m.user_profile_image_upload_error());
86
+ }
87
+ return presigned.url;
88
+ })()
89
+ : typeof values.image === "string"
90
+ ? values.image
91
+ : null;
92
+ const result = await centralAuthClient.updateUser({
93
+ name: values.name.trim(),
94
+ image: image?.trim() ?? "",
95
+ });
96
+ if (isAuthErrorResult(result)) {
97
+ throw new Error(result.error.message || m.user_form_update_error());
98
+ }
99
+ await centralSession.refetch();
100
+ await refetch();
101
+ setSettingsDialog(null);
102
+ };
103
+ const reconnectCentralAuth = async () => {
104
+ setCentralAuthError(null);
105
+ const result = await authClient.signIn.oauth2({
106
+ providerId: "krakstack-auth",
107
+ callbackURL: currentSiteHref,
108
+ });
109
+ if (result.error) {
110
+ setCentralAuthError(result.error.message ?? m.user_central_auth_reconnect_error());
111
+ return;
112
+ }
113
+ if (result.data?.url)
114
+ await navigate({ href: result.data.url });
115
+ };
116
+ return (_jsxs(_Fragment, { children: [_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsxs(Button, { variant: "outline", size: "icon", children: [_jsx(UserIcon, { className: "size-4.5" }), _jsx("span", { className: "sr-only", children: m.user_button_aria_label() })] }) }), _jsx(DropdownMenuContent, { className: "min-w-56 rounded-lg", side: side, align: "end", sideOffset: 4, children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { className: "p-0 font-normal", children: _jsx(AppBrand, { to: null, label: displayName || displayEmail, subtitle: displayName ? displayEmail : m.user_button_account(), icon: UserIcon, className: "px-1 py-1.5 text-left text-sm", ...(displayImage ? { imageSrc: displayImage } : {}) }) }), _jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuItem, { disabled: isPending, onClick: () => setSettingsDialog("account"), children: [_jsx(UserCircleIcon, {}), m.user_button_account()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("security"), children: [_jsx(ShieldCheck, {}), m.user_button_security()] }), _jsxs(DropdownMenuItem, { onClick: () => setSettingsDialog("apiKeys"), children: [_jsx(KeyRound, {}), m.user_button_api_keys()] }), _jsx(DropdownMenuSeparator, {}), _jsxs(DropdownMenuItem, { onClick: signOut, children: [_jsx(LogOutIcon, {}), m.user_button_logout()] })] }) })] }), _jsx(Dialog, { open: settingsDialog === "account", onOpenChange: (open) => {
117
+ setSettingsDialog((current) => open ? "account" : current === "account" ? null : current);
118
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_form_title() }), _jsx(DialogDescription, { children: m.user_form_description() })] }), _jsx(Separator, {}), centralSession.isPending ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : !centralSession.data ? (_jsxs("div", { className: "flex flex-col gap-3", children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_central_auth_required() }), centralAuthError ? (_jsx("p", { className: "text-destructive text-sm", children: centralAuthError })) : null, _jsx(Button, { type: "button", className: "self-start", onClick: reconnectCentralAuth, children: m.user_central_auth_reconnect() })] })) : (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsx(UserForm, { defaultValues: {
119
+ name: displayName ?? "",
120
+ image: displayImage || null,
121
+ }, error: formError, onSubmit: async (data) => {
122
+ try {
123
+ await updateUser(data);
124
+ }
125
+ catch (error) {
126
+ setFormError(error instanceof Error
127
+ ? error.message
128
+ : m.user_form_update_error());
129
+ }
130
+ } }), _jsx(Separator, {}), _jsx(ConnectedAccounts, { currentSiteHref: currentSiteHref, navigate: navigate }), _jsx(Separator, {}), _jsx(PasswordSettings, {})] }))] }) }), _jsx(Dialog, { open: settingsDialog === "security", onOpenChange: (open) => {
131
+ setSettingsDialog((current) => open ? "security" : current === "security" ? null : current);
132
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_security_title() }), _jsx(DialogDescription, { children: m.user_security_description() })] }), _jsx(Separator, {}), _jsx(AccountSecuritySettings, {})] }) }), _jsx(Dialog, { open: settingsDialog === "apiKeys", onOpenChange: (open) => {
133
+ setSettingsDialog((current) => open ? "apiKeys" : current === "apiKeys" ? null : current);
134
+ }, children: _jsxs(DialogContent, { className: "max-h-[85vh] overflow-y-auto sm:max-w-3xl", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-2xl", children: m.user_api_keys_title() }), _jsx(DialogDescription, { children: m.user_api_keys_description() })] }), _jsx(Separator, {}), _jsx(ApiKeyManager, { permissions: apiKeyPermissions ?? {} })] }) })] }));
135
+ };
136
+ function ConnectedAccounts({ currentSiteHref, navigate, }) {
137
+ const [accounts, setAccounts] = useState([]);
138
+ const [error, setError] = useState(null);
139
+ const [loading, setLoading] = useState(true);
140
+ const [isLinking, setIsLinking] = useState(false);
141
+ const [revokingAccount, setRevokingAccount] = useState(null);
142
+ const loadAccounts = async () => {
143
+ setLoading(true);
144
+ setError(null);
145
+ const result = await centralAuthClient.listAccounts();
146
+ if (result.error) {
147
+ setError(result.error.message ?? m.user_accounts_load_error());
148
+ setLoading(false);
149
+ return;
150
+ }
151
+ setAccounts(result.data ?? []);
152
+ setLoading(false);
153
+ };
154
+ useEffect(() => {
155
+ void loadAccounts();
156
+ }, []);
157
+ const googleAccount = accounts.find((account) => account.providerId === "google");
158
+ const hasPassword = accounts.some((account) => account.providerId === "credential");
159
+ const canRevokeAccount = accounts.length > 1;
160
+ const linkGoogle = async () => {
161
+ setError(null);
162
+ setIsLinking(true);
163
+ const result = await centralAuthClient.linkSocial({
164
+ provider: "google",
165
+ callbackURL: currentSiteHref,
166
+ });
167
+ if (result.error) {
168
+ setError(result.error.message ?? m.user_account_google_link_error());
169
+ setIsLinking(false);
170
+ return;
171
+ }
172
+ if (result.data?.url) {
173
+ await navigate({ href: result.data.url });
174
+ return;
175
+ }
176
+ setIsLinking(false);
177
+ };
178
+ const revokeAccount = async (account) => {
179
+ setError(null);
180
+ const result = await centralAuthClient.unlinkAccount({
181
+ providerId: account.providerId,
182
+ accountId: account.accountId,
183
+ });
184
+ if (result.error) {
185
+ setError(result.error.message ?? m.user_account_revoke_error());
186
+ return;
187
+ }
188
+ setRevokingAccount(null);
189
+ await loadAccounts();
190
+ };
191
+ return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_accounts_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_accounts_description() })] }), loading ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : null, _jsx(AccountProviderRow, { initial: "G", title: m.user_account_google_title(), description: m.user_account_google_description(), account: googleAccount, connected: Boolean(googleAccount), canRevoke: canRevokeAccount, connectLabel: m.user_account_google_connect(), revokeLabel: m.user_account_revoke(), onlyMethodLabel: m.user_account_only_method(), isConnecting: isLinking, renderDisconnected: undefined, onConnect: linkGoogle, onRevoke: (account) => setRevokingAccount(account) }), revokingAccount ? (_jsx(RevokeAccountForm, { account: revokingAccount, requirePassword: hasPassword, onCancel: () => setRevokingAccount(null), onRevoke: revokeAccount })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }));
192
+ }
193
+ function AccountProviderRow({ initial, title, description, account, connected, canRevoke, connectLabel, revokeLabel, onlyMethodLabel, isConnecting, renderDisconnected, onConnect, onRevoke, }) {
194
+ return (_jsx("div", { className: "flex flex-col gap-3 rounded-lg border p-4", children: _jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-3", children: [_jsx("span", { className: "bg-background flex size-9 shrink-0 items-center justify-center rounded-full border text-sm font-semibold", children: initial }), _jsxs("div", { className: "min-w-0", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("p", { className: "font-medium", children: title }), _jsx(Badge, { variant: connected ? "default" : "secondary", children: connected
195
+ ? m.user_account_connected()
196
+ : m.user_account_not_connected() })] }), _jsx("p", { className: "text-muted-foreground text-sm", children: description })] })] }), connected && account ? (_jsx(Button, { type: "button", variant: "outline", disabled: !canRevoke, onClick: () => onRevoke(account), children: canRevoke ? revokeLabel : onlyMethodLabel })) : renderDisconnected ? (renderDisconnected) : (_jsx(Button, { type: "button", variant: "outline", disabled: isConnecting, onClick: onConnect, children: connectLabel }))] }) }));
197
+ }
198
+ function PasswordSettings() {
199
+ const [accounts, setAccounts] = useState([]);
200
+ const [error, setError] = useState(null);
201
+ const [loading, setLoading] = useState(true);
202
+ const [revokingAccount, setRevokingAccount] = useState(null);
203
+ const loadAccounts = async () => {
204
+ setLoading(true);
205
+ setError(null);
206
+ const result = await centralAuthClient.listAccounts();
207
+ if (result.error) {
208
+ setError(result.error.message ?? m.user_accounts_load_error());
209
+ setLoading(false);
210
+ return;
211
+ }
212
+ setAccounts(result.data ?? []);
213
+ setLoading(false);
214
+ };
215
+ useEffect(() => {
216
+ void loadAccounts();
217
+ }, []);
218
+ const passwordAccount = accounts.find((account) => account.providerId === "credential");
219
+ const hasPassword = Boolean(passwordAccount);
220
+ const canRevokeAccount = accounts.length > 1;
221
+ const revokePassword = async (account) => {
222
+ setError(null);
223
+ const result = await centralAuthClient.unlinkAccount({
224
+ providerId: account.providerId,
225
+ accountId: account.accountId,
226
+ });
227
+ if (result.error) {
228
+ setError(result.error.message ?? m.user_account_revoke_error());
229
+ return;
230
+ }
231
+ setRevokingAccount(null);
232
+ await loadAccounts();
233
+ };
234
+ return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_account_password_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_description() })] }), loading ? (_jsx("p", { className: "text-muted-foreground text-sm", children: m.user_loading() })) : null, hasPassword && passwordAccount ? (_jsxs("div", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-3 rounded-lg border p-4", children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [_jsx("p", { className: "font-medium", children: m.user_account_password_title() }), _jsx(Badge, { children: m.user_account_connected() })] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_connected_description() })] }), _jsx(Button, { type: "button", variant: "outline", disabled: !canRevokeAccount, onClick: () => setRevokingAccount(passwordAccount), children: canRevokeAccount
235
+ ? m.user_account_revoke()
236
+ : m.user_account_only_method() })] }), revokingAccount ? (_jsx(RevokeAccountForm, { account: revokingAccount, requirePassword: true, onCancel: () => setRevokingAccount(null), onRevoke: revokePassword })) : null, _jsx(Separator, {}), _jsx(ChangePasswordForm, {})] })) : (_jsx(SetPasswordForm, { onSaved: loadAccounts })), error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null] }));
237
+ }
238
+ function ChangePasswordForm() {
239
+ const [saved, setSaved] = useState(false);
240
+ const form = useAppForm({
241
+ defaultValues: { currentPassword: "", newPassword: "" },
242
+ onSubmit: async ({ value, formApi }) => {
243
+ setSaved(false);
244
+ formApi.setErrorMap({ onSubmit: undefined });
245
+ const result = await centralAuthClient.changePassword({
246
+ currentPassword: value.currentPassword,
247
+ newPassword: value.newPassword,
248
+ });
249
+ if (result.error) {
250
+ formApi.setErrorMap({
251
+ onSubmit: {
252
+ form: result.error.message ?? m.user_account_password_change_error(),
253
+ fields: {},
254
+ },
255
+ });
256
+ return;
257
+ }
258
+ form.reset();
259
+ setSaved(true);
260
+ },
261
+ });
262
+ return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-md", onSubmit: (event) => {
263
+ event.preventDefault();
264
+ event.stopPropagation();
265
+ form.handleSubmit();
266
+ }, children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("h3", { className: "text-sm font-medium", children: m.user_account_password_change_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_password_change_description() })] }), _jsx(form.AppField, { name: "currentPassword", children: (field) => (_jsx(field.TextField, { label: m.user_account_current_password(), type: "password", autoComplete: "current-password", required: true })) }), _jsx(form.AppField, { name: "newPassword", children: (field) => (_jsx(field.TextField, { label: m.user_account_new_password(), type: "password", autoComplete: "new-password", required: true })) }), _jsx(form.FormError, {}), saved ? (_jsx("p", { className: "text-sm text-green-600", children: m.user_account_password_change_success() })) : null, _jsx(Button, { type: "submit", className: "self-start", children: m.user_account_password_change_submit() })] }) }));
267
+ }
268
+ function SetPasswordForm({ onSaved }) {
269
+ const form = useAppForm({
270
+ defaultValues: { password: "" },
271
+ onSubmit: async ({ value, formApi }) => {
272
+ formApi.setErrorMap({ onSubmit: undefined });
273
+ const result = await centralAuthClient.$fetch("/set-password", {
274
+ method: "POST",
275
+ body: { newPassword: value.password },
276
+ });
277
+ if (result.error) {
278
+ formApi.setErrorMap({
279
+ onSubmit: {
280
+ form: result.error.message ?? m.user_account_password_set_error(),
281
+ fields: {},
282
+ },
283
+ });
284
+ return;
285
+ }
286
+ form.reset();
287
+ await onSaved();
288
+ },
289
+ });
290
+ return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex w-full flex-col gap-3 sm:max-w-sm", onSubmit: (event) => {
291
+ event.preventDefault();
292
+ event.stopPropagation();
293
+ form.handleSubmit();
294
+ }, children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_account_new_password(), type: "password", autoComplete: "new-password", required: true })) }), _jsx(form.FormError, {}), _jsx(Button, { type: "submit", className: "self-start", children: m.user_account_password_set() })] }) }));
295
+ }
296
+ function RevokeAccountForm({ account, requirePassword, onCancel, onRevoke, }) {
297
+ const form = useAppForm({
298
+ defaultValues: { password: "" },
299
+ onSubmit: async ({ value, formApi }) => {
300
+ formApi.setErrorMap({ onSubmit: undefined });
301
+ if (requirePassword) {
302
+ const verified = await centralAuthClient.$fetch("/verify-password", {
303
+ method: "POST",
304
+ body: { password: value.password },
305
+ });
306
+ if (verified.error) {
307
+ formApi.setErrorMap({
308
+ onSubmit: {
309
+ form: m.user_account_password_verify_error(),
310
+ fields: {},
311
+ },
312
+ });
313
+ return;
314
+ }
315
+ }
316
+ await onRevoke(account);
317
+ },
318
+ });
319
+ return (_jsx(form.AppForm, { children: _jsxs("form", { className: "bg-muted/40 flex flex-col gap-3 rounded-lg border p-4", onSubmit: (event) => {
320
+ event.preventDefault();
321
+ event.stopPropagation();
322
+ form.handleSubmit();
323
+ }, children: [_jsxs("div", { className: "flex flex-col gap-1", children: [_jsx("h3", { className: "text-sm font-medium", children: m.user_account_revoke() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_account_revoke_description({
324
+ provider: providerName(account.providerId),
325
+ }) })] }), requirePassword ? (_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) })) : null, _jsx(form.FormError, {}), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx(Button, { type: "button", variant: "outline", onClick: onCancel, children: m.user_account_cancel() }), _jsx(Button, { type: "submit", children: m.user_account_confirm_revoke() })] })] }) }));
326
+ }
327
+ const providerName = (providerId) => {
328
+ if (providerId === "google")
329
+ return m.user_account_google_title();
330
+ if (providerId === "credential")
331
+ return m.user_account_password_title();
332
+ return providerId;
333
+ };
334
+ const UserForm = ({ defaultValues, error, onSubmit, }) => {
335
+ const form = useAppForm({
336
+ defaultValues,
337
+ onSubmit: ({ value }) => onSubmit(value),
338
+ });
339
+ return (_jsxs("section", { className: "flex flex-col gap-4", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_profile_title() }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_profile_description() })] }), _jsx("form", { className: "flex flex-col gap-4", onSubmit: (event) => {
340
+ event.preventDefault();
341
+ event.stopPropagation();
342
+ form.handleSubmit();
343
+ }, children: _jsxs(form.AppForm, { children: [_jsx(form.AppField, { name: "image", children: (field) => (_jsx(field.ImageField, { label: m.user_profile_photo_upload_label(), size: {
344
+ width: 96,
345
+ height: 96,
346
+ suggestedWidth: 512,
347
+ suggestedHeight: 512,
348
+ } })) }), _jsx(form.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.user_form_name_label(), autoComplete: "name", required: true })) }), error && (_jsx("p", { role: "alert", className: "text-destructive text-sm", children: error })), _jsx(form.SubmitButton, {})] }) })] }));
349
+ };
350
+ function AccountSecuritySettings() {
351
+ const session = centralAuthClient.useSession();
352
+ const [setup, setSetup] = useState(null);
353
+ const [message, setMessage] = useState(null);
354
+ const twoFactorEnabled = hasTwoFactorEnabled(session.data?.user);
355
+ return (_jsxs("div", { className: "flex flex-col gap-6", children: [_jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [_jsxs("div", { className: "flex flex-col gap-1.5", children: [_jsx("h2", { className: "text-sm leading-none font-medium", children: m.user_two_factor_title() }), _jsx("p", { className: "text-muted-foreground text-xs", children: m.user_two_factor_description() })] }), _jsx(Badge, { variant: twoFactorEnabled ? "default" : "secondary", children: twoFactorEnabled
356
+ ? m.user_two_factor_enabled()
357
+ : m.user_two_factor_disabled() })] }), twoFactorEnabled ? (_jsx(DisableTotpForm, { onDisabled: async () => {
358
+ setMessage(m.user_two_factor_disabled_message());
359
+ await session.refetch();
360
+ } })) : setup ? (_jsx(VerifyTotpSetup, { setup: setup, onVerified: async () => {
361
+ setSetup(null);
362
+ setMessage(m.user_two_factor_enabled_message());
363
+ await session.refetch();
364
+ } })) : (_jsx(EnableTotpForm, { onEnabled: setSetup })), message ? (_jsx("p", { className: "text-muted-foreground text-sm", children: message })) : null] }));
365
+ }
366
+ function EnableTotpForm({ onEnabled, }) {
367
+ const form = useAppForm({
368
+ defaultValues: { password: "" },
369
+ onSubmit: async ({ value, formApi }) => {
370
+ formApi.setErrorMap({ onSubmit: undefined });
371
+ const result = await centralAuthClient.twoFactor.enable({
372
+ password: value.password,
373
+ });
374
+ if (result.error || !result.data) {
375
+ formApi.setErrorMap({
376
+ onSubmit: {
377
+ form: result.error?.message ?? m.user_two_factor_enable_error(),
378
+ fields: {},
379
+ },
380
+ });
381
+ return;
382
+ }
383
+ onEnabled({
384
+ totpURI: result.data.totpURI,
385
+ backupCodes: result.data.backupCodes,
386
+ });
387
+ },
388
+ });
389
+ return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-md flex-col gap-4", onSubmit: (event) => {
390
+ event.preventDefault();
391
+ event.stopPropagation();
392
+ form.handleSubmit();
393
+ }, children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }));
394
+ }
395
+ function VerifyTotpSetup({ setup, onVerified, }) {
396
+ const form = useAppForm({
397
+ defaultValues: { code: "" },
398
+ onSubmit: async ({ value, formApi }) => {
399
+ formApi.setErrorMap({ onSubmit: undefined });
400
+ const result = await centralAuthClient.twoFactor.verifyTotp({
401
+ code: value.code.trim(),
402
+ });
403
+ if (result.error) {
404
+ formApi.setErrorMap({
405
+ onSubmit: {
406
+ form: result.error.message ?? m.user_two_factor_verify_error(),
407
+ fields: {},
408
+ },
409
+ });
410
+ return;
411
+ }
412
+ await onVerified();
413
+ },
414
+ });
415
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsxs("div", { className: "flex flex-col items-center gap-4 rounded-lg border p-4 text-center sm:p-6", children: [_jsx("div", { className: "rounded-xl border bg-white p-3", children: _jsx(QRCode, { value: setup.totpURI, title: m.user_two_factor_scan_title(), className: "size-44 max-w-full" }) }), _jsx("p", { className: "text-muted-foreground max-w-md text-sm", children: m.user_two_factor_scan_description() })] }), _jsxs("div", { className: "flex flex-col gap-3 rounded-lg border p-4", children: [_jsx("div", { className: "bg-muted/40 grid gap-2 rounded-md p-3 font-mono text-sm sm:grid-cols-2", children: setup.backupCodes.map((code) => (_jsx("span", { children: code }, code))) }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_two_factor_backup_codes_warning() })] }), _jsx(form.AppForm, { children: _jsxs("form", { className: "flex w-full max-w-sm flex-col gap-4", onSubmit: (event) => {
416
+ event.preventDefault();
417
+ event.stopPropagation();
418
+ form.handleSubmit();
419
+ }, children: [_jsx(form.AppField, { name: "code", children: (field) => (_jsx(field.TextField, { label: m.user_two_factor_code(), autoComplete: "one-time-code", inputMode: "numeric", required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) })] }));
420
+ }
421
+ function DisableTotpForm({ onDisabled }) {
422
+ const form = useAppForm({
423
+ defaultValues: { password: "" },
424
+ onSubmit: async ({ value, formApi }) => {
425
+ formApi.setErrorMap({ onSubmit: undefined });
426
+ const result = await centralAuthClient.twoFactor.disable({
427
+ password: value.password,
428
+ });
429
+ if (result.error) {
430
+ formApi.setErrorMap({
431
+ onSubmit: {
432
+ form: result.error.message ?? m.user_two_factor_disable_error(),
433
+ fields: {},
434
+ },
435
+ });
436
+ return;
437
+ }
438
+ await onDisabled();
439
+ },
440
+ });
441
+ return (_jsx(form.AppForm, { children: _jsxs("form", { className: "flex max-w-md flex-col gap-4", onSubmit: (event) => {
442
+ event.preventDefault();
443
+ event.stopPropagation();
444
+ form.handleSubmit();
445
+ }, children: [_jsx(form.AppField, { name: "password", children: (field) => (_jsx(field.TextField, { label: m.user_field_password(), type: "password", autoComplete: "current-password", required: true })) }), _jsx(form.FormError, {}), _jsx(form.SubmitButton, {})] }) }));
446
+ }
447
+ function ApiKeyManager({ permissions = {}, }) {
448
+ const [keys, setKeys] = useState([]);
449
+ const [createdKey, setCreatedKey] = useState(null);
450
+ const [copiedKey, setCopiedKey] = useState(false);
451
+ const [error, setError] = useState(null);
452
+ const [loading, setLoading] = useState(true);
453
+ const permissionOptions = getPermissionOptions(permissions);
454
+ const [selectedPermissions, setSelectedPermissions] = useState({});
455
+ const loadKeys = async () => {
456
+ setLoading(true);
457
+ setError(null);
458
+ const result = await centralAuthClient.apiKey.list({
459
+ query: { configId: "user" },
460
+ });
461
+ if (result.error) {
462
+ setError(result.error.message ?? m.user_api_keys_load_error());
463
+ setLoading(false);
464
+ return;
465
+ }
466
+ setKeys(result.data?.apiKeys ?? []);
467
+ setLoading(false);
468
+ };
469
+ useEffect(() => {
470
+ void loadKeys();
471
+ }, []);
472
+ const createForm = useAppForm({
473
+ defaultValues: { name: "" },
474
+ onSubmit: async ({ value, formApi }) => {
475
+ formApi.setErrorMap({ onSubmit: undefined });
476
+ setCreatedKey(null);
477
+ setCopiedKey(false);
478
+ const selectedPermissionObject = getSelectedPermissionObject(permissionOptions, selectedPermissions);
479
+ const result = await centralAuthClient.$fetch("/create-api-key", {
480
+ method: "POST",
481
+ body: {
482
+ configId: "user",
483
+ name: value.name.trim(),
484
+ permissions: selectedPermissionObject,
485
+ },
486
+ });
487
+ const created = getCreatedApiKey(result.data);
488
+ if (result.error || !created) {
489
+ formApi.setErrorMap({
490
+ onSubmit: {
491
+ form: result.error?.message ?? m.user_api_key_create_error(),
492
+ fields: {},
493
+ },
494
+ });
495
+ return;
496
+ }
497
+ setCreatedKey(created.key);
498
+ createForm.reset();
499
+ setSelectedPermissions({});
500
+ await loadKeys();
501
+ },
502
+ });
503
+ const togglePermission = (id, checked) => {
504
+ setSelectedPermissions((current) => ({ ...current, [id]: checked }));
505
+ };
506
+ const copyCreatedKey = async () => {
507
+ if (!createdKey)
508
+ return;
509
+ await navigator.clipboard.writeText(createdKey);
510
+ setCopiedKey(true);
511
+ window.setTimeout(() => setCopiedKey(false), 2000);
512
+ };
513
+ const deleteKey = async (key) => {
514
+ const result = await centralAuthClient.apiKey.delete({
515
+ configId: "user",
516
+ keyId: key.id,
517
+ });
518
+ if (result.error) {
519
+ setError(result.error.message ?? m.user_api_key_delete_error());
520
+ return;
521
+ }
522
+ await loadKeys();
523
+ };
524
+ return (_jsxs("div", { className: "flex flex-col gap-5", children: [_jsx(createForm.AppForm, { children: _jsxs("form", { className: "flex max-w-xl flex-col gap-4", onSubmit: (event) => {
525
+ event.preventDefault();
526
+ event.stopPropagation();
527
+ createForm.handleSubmit();
528
+ }, children: [_jsx("p", { className: "text-muted-foreground text-sm", children: m.api_key_rate_limit_notice() }), _jsx(createForm.AppField, { name: "name", children: (field) => (_jsx(field.TextField, { label: m.user_api_key_name(), required: true })) }), permissionOptions.length > 0 ? (_jsxs(FieldSet, { children: [_jsx(FieldLegend, { children: m.user_api_key_permissions() }), _jsx(FieldDescription, { children: m.user_api_key_permissions_description() }), _jsx(FieldGroup, { "data-slot": "checkbox-group", className: "gap-3", children: permissionOptions.map((permission) => (_jsxs(Field, { orientation: "horizontal", children: [_jsx(Checkbox, { id: permission.id, checked: selectedPermissions[permission.id] ?? false, onCheckedChange: (checked) => togglePermission(permission.id, checked) }), _jsx(FieldContent, { children: _jsx(FieldLabel, { htmlFor: permission.id, children: permission.id }) })] }, permission.id))) })] })) : null, _jsx(createForm.FormError, {}), _jsx(createForm.SubmitButton, {})] }) }), createdKey ? (_jsxs("div", { className: "flex flex-col gap-2 rounded-lg border p-4", children: [_jsxs("div", { className: "flex items-center gap-2 font-medium", children: [_jsx(KeyRound, {}), m.user_api_key_created_title()] }), _jsx("p", { className: "text-muted-foreground text-sm", children: m.user_api_key_created_description() }), _jsxs("div", { className: "grid min-w-0 gap-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center", children: [_jsx("code", { className: "bg-muted block max-w-full overflow-x-auto rounded-md p-3 text-sm whitespace-nowrap", children: createdKey }), _jsxs(Button, { type: "button", variant: "outline", onClick: copyCreatedKey, className: "self-start sm:self-auto", children: [copiedKey ? _jsx(Check, {}) : _jsx(Copy, {}), copiedKey ? m.user_api_key_copied() : m.user_api_key_copy()] })] })] })) : null, error ? _jsx("p", { className: "text-destructive text-sm", children: error }) : null, _jsx(Separator, {}), _jsx(DataTable, { columns: apiKeyColumns({ onDelete: deleteKey }), data: keys, emptyLabel: loading ? m.user_loading() : m.table_empty(), exportFileName: m.user_api_keys_export_file_name(), features: { gallery: false } })] }));
529
+ }
530
+ const apiKeyColumns = ({ onDelete, }) => [
531
+ {
532
+ accessorKey: "name",
533
+ header: m.user_api_key_name(),
534
+ cell: ({ row }) => (_jsx("div", { className: "min-w-0", children: _jsx("p", { className: "truncate font-medium", children: row.original.name ?? m.user_api_key_hidden() }) })),
535
+ },
536
+ {
537
+ accessorKey: "enabled",
538
+ header: m.user_api_key_status(),
539
+ cell: ({ row }) => (_jsx(Badge, { variant: row.original.enabled ? "default" : "secondary", children: row.original.enabled
540
+ ? m.user_api_key_enabled()
541
+ : m.user_api_key_disabled() })),
542
+ },
543
+ {
544
+ accessorKey: "permissions",
545
+ header: m.user_api_key_permissions(),
546
+ cell: ({ row }) => {
547
+ const permissions = formatPermissions(row.original.permissions);
548
+ if (permissions.length === 0) {
549
+ return (_jsx("span", { className: "text-muted-foreground text-sm", children: m.user_api_key_no_permissions() }));
550
+ }
551
+ return (_jsx("div", { className: "flex max-w-sm flex-wrap gap-1.5", children: permissions.map((permission) => (_jsx(Badge, { variant: "secondary", children: permission }, permission))) }));
552
+ },
553
+ },
554
+ createDataTableActionsColumn([
555
+ {
556
+ name: m.user_delete(),
557
+ icon: _jsx(Trash2, {}),
558
+ variant: "destructive",
559
+ onClick: onDelete,
560
+ },
561
+ ]),
562
+ ];
563
+ const getPermissionId = (resource, action) => `${resource}:${action}`;
564
+ const isPermissionRecord = (permissions) => typeof permissions === "object" &&
565
+ permissions !== null &&
566
+ Object.values(permissions).every((actions) => Array.isArray(actions) &&
567
+ actions.every((action) => typeof action === "string"));
568
+ const formatPermissions = (permissions) => {
569
+ if (!isPermissionRecord(permissions))
570
+ return [];
571
+ return Object.entries(permissions).flatMap(([resource, actions]) => actions.map((action) => `${resource}:${action}`));
572
+ };
573
+ const getPermissionOptions = (permissions) => Object.entries(permissions).flatMap(([resource, actions]) => actions.map((action) => ({
574
+ id: getPermissionId(resource, action),
575
+ resource,
576
+ action,
577
+ })));
578
+ const getSelectedPermissionObject = (options, selected) => {
579
+ const permissions = {};
580
+ for (const option of options) {
581
+ if (!selected[option.id])
582
+ continue;
583
+ permissions[option.resource] = [
584
+ ...(permissions[option.resource] ?? []),
585
+ option.action,
586
+ ];
587
+ }
588
+ return permissions;
589
+ };
590
+ const hasTwoFactorEnabled = (user) => {
591
+ if (typeof user !== "object" ||
592
+ user === null ||
593
+ !("twoFactorEnabled" in user))
594
+ return false;
595
+ return user.twoFactorEnabled === true;
596
+ };
597
+ const isAuthErrorResult = (result) => {
598
+ return (typeof result === "object" &&
599
+ result !== null &&
600
+ "error" in result &&
601
+ typeof result.error === "object" &&
602
+ result.error !== null);
603
+ };
604
+ const getCreatedApiKey = (data) => {
605
+ if (typeof data === "object" &&
606
+ data !== null &&
607
+ "key" in data &&
608
+ typeof data.key === "string") {
609
+ return { key: data.key };
610
+ }
611
+ return null;
612
+ };
613
+ //# sourceMappingURL=user-button.js.map