@alepha/ui 0.32.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/AccountConnections.js +1 -1
- package/dist/account/AccountConnections.js.map +1 -1
- package/dist/account/AccountDeleteDialog.d.ts.map +1 -1
- package/dist/account/AccountDeleteDialog.js +17 -17
- package/dist/account/AccountDeleteDialog.js.map +1 -1
- package/dist/account/AccountKeys.js +2 -2
- package/dist/account/AccountKeys.js.map +1 -1
- package/dist/account/AccountMfaDialog.d.ts.map +1 -1
- package/dist/account/AccountMfaDialog.js +19 -25
- package/dist/account/AccountMfaDialog.js.map +1 -1
- package/dist/account/AccountPasswordDialog.d.ts.map +1 -1
- package/dist/account/AccountPasswordDialog.js +25 -24
- package/dist/account/AccountPasswordDialog.js.map +1 -1
- package/dist/account/AccountProfile.d.ts.map +1 -1
- package/dist/account/AccountProfile.js +17 -24
- package/dist/account/AccountProfile.js.map +1 -1
- package/dist/account/AccountSecurity.d.ts.map +1 -1
- package/dist/account/AccountSecurity.js +21 -19
- package/dist/account/AccountSecurity.js.map +1 -1
- package/dist/account/AccountSessions.js +1 -1
- package/dist/account/AccountSessions.js.map +1 -1
- package/dist/account/ApiKeyCreateDialog.d.ts.map +1 -1
- package/dist/account/ApiKeyCreateDialog.js +8 -12
- package/dist/account/ApiKeyCreateDialog.js.map +1 -1
- package/dist/admin/AdminFiles.js +1 -1
- package/dist/admin/AdminFiles.js.map +1 -1
- package/dist/admin/AdminJobs.js +1 -1
- package/dist/admin/AdminJobs.js.map +1 -1
- package/dist/admin/AdminKeys.js +1 -1
- package/dist/admin/AdminKeys.js.map +1 -1
- package/dist/admin/AdminParameters.d.ts.map +1 -1
- package/dist/admin/AdminParameters.js +7 -5
- package/dist/admin/AdminParameters.js.map +1 -1
- package/dist/admin/AdminParametersTreeFooterActions.d.ts +2 -2
- package/dist/admin/AdminParametersTreeFooterActions.d.ts.map +1 -1
- package/dist/admin/AdminParametersTreeFooterActions.js.map +1 -1
- package/dist/admin/AdminParametersTreePane.d.ts +2 -2
- package/dist/admin/AdminParametersTreePane.d.ts.map +1 -1
- package/dist/admin/AdminParametersTreePane.js.map +1 -1
- package/dist/admin/AdminRouter.d.ts +1 -3
- package/dist/admin/AdminRouter.d.ts.map +1 -1
- package/dist/admin/AdminRouter.js +2 -4
- package/dist/admin/AdminRouter.js.map +1 -1
- package/dist/admin/AdminSessions.js +1 -1
- package/dist/admin/AdminSessions.js.map +1 -1
- package/dist/admin/AdminUserAvatarControl.d.ts.map +1 -1
- package/dist/admin/AdminUserAvatarControl.js +9 -16
- package/dist/admin/AdminUserAvatarControl.js.map +1 -1
- package/dist/admin/AdminUserDetail.js +4 -4
- package/dist/admin/AdminUserDetail.js.map +1 -1
- package/dist/admin/AdminUsers.d.ts.map +1 -1
- package/dist/admin/AdminUsers.js +10 -12
- package/dist/admin/AdminUsers.js.map +1 -1
- package/dist/admin/AdminUsersRolesPicker.d.ts +5 -1
- package/dist/admin/AdminUsersRolesPicker.d.ts.map +1 -1
- package/dist/admin/AdminUsersRolesPicker.js +2 -3
- package/dist/admin/AdminUsersRolesPicker.js.map +1 -1
- package/dist/admin/analytics/QueryPanel.js +1 -1
- package/dist/admin/analytics/QueryPanel.js.map +1 -1
- package/dist/admin/useConfirmedAction.d.ts +8 -2
- package/dist/admin/useConfirmedAction.d.ts.map +1 -1
- package/dist/admin/useConfirmedAction.js +15 -4
- package/dist/admin/useConfirmedAction.js.map +1 -1
- package/dist/auth/AuthLogin.d.ts.map +1 -1
- package/dist/auth/AuthLogin.js +4 -4
- package/dist/auth/AuthLogin.js.map +1 -1
- package/dist/auth/AuthRegister.js.map +1 -1
- package/dist/core/index.js +1 -1
- package/dist/form/AutoForm.js +1 -1
- package/dist/form/AutoForm.js.map +1 -1
- package/dist/form/Control.js +1 -1
- package/dist/form/Control.js.map +1 -1
- package/dist/form/ControlArray.js +5 -5
- package/dist/form/ControlArray.js.map +1 -1
- package/dist/form/ControlSelect.js +2 -2
- package/dist/form/ControlSelect.js.map +1 -1
- package/dist/form/ControlUpload.d.ts +1 -1
- package/dist/form/ControlUpload.js.map +1 -1
- package/dist/i18n/fr/uiFr.d.ts.map +1 -1
- package/dist/i18n/fr/uiFr.js +0 -9
- package/dist/i18n/fr/uiFr.js.map +1 -1
- package/dist/organizations/MyOrganizationInvitations.js +2 -2
- package/dist/organizations/MyOrganizationInvitations.js.map +1 -1
- package/dist/organizations/OrganizationInviteDialog.js +1 -1
- package/dist/organizations/OrganizationInviteDialog.js.map +1 -1
- package/dist/organizations/OrganizationMembers.js +1 -1
- package/dist/organizations/OrganizationMembers.js.map +1 -1
- package/dist/organizations/OrganizationPendingInvitations.js +1 -1
- package/dist/organizations/OrganizationPendingInvitations.js.map +1 -1
- package/dist/organizations/OrganizationRanks.js +3 -3
- package/dist/organizations/OrganizationRanks.js.map +1 -1
- package/dist/organizations/useInviteOrganizationMember.d.ts +6 -1
- package/dist/organizations/useInviteOrganizationMember.d.ts.map +1 -1
- package/dist/organizations/useInviteOrganizationMember.js +13 -13
- package/dist/organizations/useInviteOrganizationMember.js.map +1 -1
- package/dist/organizations/useRevokeOrganizationInvitation.d.ts +7 -1
- package/dist/organizations/useRevokeOrganizationInvitation.d.ts.map +1 -1
- package/dist/organizations/useRevokeOrganizationInvitation.js +13 -2
- package/dist/organizations/useRevokeOrganizationInvitation.js.map +1 -1
- package/dist/shell/ButtonUser.d.ts +1 -2
- package/dist/shell/ButtonUser.d.ts.map +1 -1
- package/dist/shell/ButtonUser.js +14 -42
- package/dist/shell/ButtonUser.js.map +1 -1
- package/dist/shell/ButtonUserContent.d.ts +13 -0
- package/dist/shell/ButtonUserContent.d.ts.map +1 -0
- package/dist/shell/ButtonUserContent.js +52 -0
- package/dist/shell/ButtonUserContent.js.map +1 -0
- package/dist/shell/ButtonUserPlaceholder.d.ts +14 -0
- package/dist/shell/ButtonUserPlaceholder.d.ts.map +1 -0
- package/dist/shell/ButtonUserPlaceholder.js +17 -0
- package/dist/shell/ButtonUserPlaceholder.js.map +1 -0
- package/dist/styles.css +31 -0
- package/dist/table/DataTable.js +1 -1
- package/dist/table/DataTable.js.map +1 -1
- package/dist/table/DataTableFilterBar.js +2 -2
- package/dist/table/DataTableFilterBar.js.map +1 -1
- package/dist/table/dataTableBaseProps.d.ts +1 -1
- package/dist/table/dataTableTypes.d.ts +3 -3
- package/dist/table/dataTableTypes.d.ts.map +1 -1
- package/dist/table/useDataTableData.d.ts.map +1 -1
- package/dist/table/useDataTableData.js +3 -1
- package/dist/table/useDataTableData.js.map +1 -1
- package/dist/table/useDataTableRefresh.js +2 -2
- package/dist/table/useDataTableRefresh.js.map +1 -1
- package/dist/table/useDataTableSummary.d.ts.map +1 -1
- package/dist/table/useDataTableSummary.js +2 -1
- package/dist/table/useDataTableSummary.js.map +1 -1
- package/package.json +6 -6
- package/src/account/AccountConnections.tsx +1 -1
- package/src/account/AccountDeleteDialog.tsx +25 -31
- package/src/account/AccountKeys.tsx +2 -2
- package/src/account/AccountMfaDialog.tsx +33 -27
- package/src/account/AccountPasswordDialog.tsx +36 -39
- package/src/account/AccountProfile.tsx +29 -43
- package/src/account/AccountSecurity.tsx +57 -64
- package/src/account/AccountSessions.tsx +1 -1
- package/src/account/ApiKeyCreateDialog.tsx +12 -20
- package/src/account/__tests__/AccountRouter.spec.ts +2 -1
- package/src/admin/AdminFiles.tsx +1 -1
- package/src/admin/AdminJobs.tsx +1 -1
- package/src/admin/AdminKeys.tsx +1 -1
- package/src/admin/AdminParameters.tsx +7 -5
- package/src/admin/AdminParametersTreeFooterActions.tsx +2 -2
- package/src/admin/AdminParametersTreePane.tsx +2 -2
- package/src/admin/AdminRouter.tsx +2 -4
- package/src/admin/AdminSessions.tsx +1 -1
- package/src/admin/AdminUserAvatarControl.tsx +17 -22
- package/src/admin/AdminUserDetail.tsx +4 -4
- package/src/admin/AdminUsers.tsx +10 -12
- package/src/admin/AdminUsersRolesPicker.tsx +11 -4
- package/src/admin/__tests__/AdminRouter.spec.ts +3 -2
- package/src/admin/analytics/QueryPanel.tsx +1 -1
- package/src/admin/useConfirmedAction.tsx +24 -10
- package/src/auth/AuthLogin.tsx +10 -9
- package/src/auth/AuthRegister.tsx +2 -2
- package/src/form/AutoForm.tsx +1 -1
- package/src/form/Control.tsx +1 -1
- package/src/form/ControlArray.tsx +5 -5
- package/src/form/ControlSelect.tsx +2 -2
- package/src/form/ControlUpload.tsx +1 -1
- package/src/form/__tests__/ControlArrayChildChange.browser.spec.tsx +1 -1
- package/src/i18n/fr/uiFr.ts +0 -9
- package/src/organizations/MyOrganizationInvitations.tsx +2 -2
- package/src/organizations/OrganizationInviteDialog.tsx +1 -1
- package/src/organizations/OrganizationMembers.tsx +1 -1
- package/src/organizations/OrganizationPendingInvitations.tsx +1 -1
- package/src/organizations/OrganizationRanks.tsx +3 -3
- package/src/organizations/useInviteOrganizationMember.ts +22 -15
- package/src/organizations/useRevokeOrganizationInvitation.ts +23 -4
- package/src/shell/ButtonUser.tsx +14 -79
- package/src/shell/ButtonUserContent.tsx +92 -0
- package/src/shell/ButtonUserPlaceholder.tsx +25 -0
- package/src/shell/__tests__/ActionErrorToaster.browser.spec.tsx +1 -1
- package/src/shell/__tests__/ActionErrorToasterHandled.browser.spec.tsx +1 -2
- package/src/shell/__tests__/AppShell.pageCache.spec.tsx +67 -0
- package/src/styles.css +31 -0
- package/src/table/DataTable.tsx +1 -1
- package/src/table/DataTableFilterBar.tsx +2 -2
- package/src/table/__tests__/DataTableFilterDateRange.browser.spec.tsx +1 -1
- package/src/table/__tests__/DataTableQuerySeed.browser.spec.tsx +1 -1
- package/src/table/__tests__/DataTableShareFilters.browser.spec.tsx +1 -1
- package/src/table/dataTableBaseProps.ts +1 -1
- package/src/table/dataTableTypes.ts +3 -3
- package/src/table/useDataTableData.ts +2 -0
- package/src/table/useDataTableRefresh.ts +3 -3
- package/src/table/useDataTableSummary.ts +2 -1
|
@@ -10,7 +10,7 @@ import { useI18n } from "alepha/react/i18n";
|
|
|
10
10
|
import { AtSign, Camera, Trash2, User } from "lucide-react";
|
|
11
11
|
import { useRef, useState } from "react";
|
|
12
12
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
13
|
-
import { useClient } from "alepha/react";
|
|
13
|
+
import { useAction, useClient } from "alepha/react";
|
|
14
14
|
import { useForm } from "alepha/react/form";
|
|
15
15
|
import { updateMyProfileBodySchema } from "alepha/api/users";
|
|
16
16
|
//#region src/account/AccountProfile.tsx
|
|
@@ -28,7 +28,18 @@ const AccountProfile = (props) => {
|
|
|
28
28
|
const { l, tr } = useI18n();
|
|
29
29
|
const fileInput = useRef(null);
|
|
30
30
|
const [profile, setProfile] = useState(props.profile);
|
|
31
|
-
const
|
|
31
|
+
const uploadAvatar = useAction({ handler: async (_ctx, file) => {
|
|
32
|
+
setProfile(await avatarApi.updateMyAvatar({ body: { file } }));
|
|
33
|
+
toaster.show(tr("account.profile.avatarUpdated", { default: "Avatar updated" }), "success");
|
|
34
|
+
} }, [
|
|
35
|
+
avatarApi,
|
|
36
|
+
toaster,
|
|
37
|
+
tr
|
|
38
|
+
]);
|
|
39
|
+
const removeAvatar = useAction({ handler: async () => {
|
|
40
|
+
setProfile(await avatarApi.deleteMyAvatar());
|
|
41
|
+
} }, [avatarApi]);
|
|
42
|
+
const uploading = uploadAvatar.loading || removeAvatar.loading;
|
|
32
43
|
const hasUsername = props.realmConfig?.settings?.username !== "none";
|
|
33
44
|
/**
|
|
34
45
|
* Validated against the server's own body schema, so "3 to 30 characters"
|
|
@@ -66,29 +77,11 @@ const AccountProfile = (props) => {
|
|
|
66
77
|
}
|
|
67
78
|
});
|
|
68
79
|
if (!profile) return null;
|
|
69
|
-
const onPickAvatar =
|
|
80
|
+
const onPickAvatar = (event) => {
|
|
70
81
|
const file = event.target.files?.[0];
|
|
82
|
+
event.target.value = "";
|
|
71
83
|
if (!file) return;
|
|
72
|
-
|
|
73
|
-
try {
|
|
74
|
-
setProfile(await avatarApi.updateMyAvatar({ body: { file } }));
|
|
75
|
-
toaster.show(tr("account.profile.avatarUpdated", { default: "Avatar updated" }), "success");
|
|
76
|
-
} catch (error) {
|
|
77
|
-
toaster.show(error?.message ?? tr("account.profile.avatarUploadError", { default: "Could not upload that image" }), "danger");
|
|
78
|
-
} finally {
|
|
79
|
-
setUploading(false);
|
|
80
|
-
if (fileInput.current) fileInput.current.value = "";
|
|
81
|
-
}
|
|
82
|
-
};
|
|
83
|
-
const removeAvatar = async () => {
|
|
84
|
-
setUploading(true);
|
|
85
|
-
try {
|
|
86
|
-
setProfile(await avatarApi.deleteMyAvatar());
|
|
87
|
-
} catch (error) {
|
|
88
|
-
toaster.show(error?.message ?? tr("account.profile.avatarRemoveError", { default: "Could not remove your avatar" }), "danger");
|
|
89
|
-
} finally {
|
|
90
|
-
setUploading(false);
|
|
91
|
-
}
|
|
84
|
+
uploadAvatar.run(file);
|
|
92
85
|
};
|
|
93
86
|
const canEditAvatar = avatarApi.updateMyAvatar.can();
|
|
94
87
|
return /* @__PURE__ */ jsxs(AccountPage, {
|
|
@@ -127,7 +120,7 @@ const AccountProfile = (props) => {
|
|
|
127
120
|
}), profile.picture ? /* @__PURE__ */ jsxs(Button, {
|
|
128
121
|
variant: "minimal",
|
|
129
122
|
size: "sm",
|
|
130
|
-
onClick: removeAvatar,
|
|
123
|
+
onClick: () => removeAvatar.run(),
|
|
131
124
|
disabled: uploading,
|
|
132
125
|
children: [/* @__PURE__ */ jsx(Trash2, { className: "size-4" }), tr("account.profile.avatarRemove", { default: "Remove" })]
|
|
133
126
|
}) : null]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountProfile.js","names":[],"sources":["../../src/account/AccountProfile.tsx"],"sourcesContent":["import type {\n MyAvatarController,\n MyProfile,\n MyProfileController,\n RealmConfig,\n} from \"alepha/api/users\";\nimport { updateMyProfileBodySchema } from \"alepha/api/users\";\nimport { useClient } from \"alepha/react\";\nimport { useForm } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { AtSign, Camera, Trash2, User } from \"lucide-react\";\nimport { type ChangeEvent, useRef, useState } from \"react\";\n\nimport { Badge } from \"../core/Badge.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { FileImage } from \"../core/FileImage.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { AutoForm } from \"../form/AutoForm.tsx\";\nimport { SettingsRow } from \"../settings/SettingsRow.tsx\";\nimport { SettingsSection } from \"../settings/SettingsSection.tsx\";\nimport { AccountPage } from \"./AccountPage.tsx\";\n\nexport interface AccountProfileProps {\n /**\n * Supplied by the route loader. Optional so the page can also be rendered\n * standalone in a story or a test.\n */\n profile?: MyProfile;\n\n /**\n * Supplied by the route loader, and read for one thing: whether this realm\n * collects usernames at all.\n *\n * Optional for the same reason `profile` is. Absent, the username field\n * renders — the historical behaviour, and the right guess for a realm nobody\n * described.\n */\n realmConfig?: RealmConfig;\n}\n\n/**\n * Who you are: avatar, name, and the read-only facts about the account.\n *\n * Email is shown but not editable — changing it is a verification flow, not a\n * profile edit, and `updateMyProfile` deliberately refuses it. Rather than\n * render a disabled input with no explanation, the row says so.\n */\nconst AccountProfile = (props: AccountProfileProps) => {\n const api = useClient<MyProfileController>();\n const avatarApi = useClient<MyAvatarController>();\n const toaster = useToast();\n const { l, tr } = useI18n();\n const fileInput = useRef<HTMLInputElement>(null);\n\n const [profile, setProfile] = useState<MyProfile | undefined>(props.profile);\n const [uploading, setUploading] = useState(false);\n\n /*\n * Does this realm have usernames at all?\n *\n * The avatar section above reads its switch through `can()`, because a realm\n * with `features.avatars` off registers no avatar action and the capability\n * is simply absent from `/api/_links`. That cannot work here:\n * `updateMyProfile` is the same call that saves first and last name, so it\n * exists in every realm and its presence says nothing about usernames.\n *\n * The realm's own `settings.username` is the switch, and `\"none\"` is the\n * only value that hides the row: it is the one that means this realm has no\n * such thing as a username, so there is nothing to show and nothing the user\n * could set.\n *\n * Without this, a `\"none\"` realm did not merely render a pointless field:\n * `?? \"\"` seeded an empty string into a column that is `.optional()` but\n * `minLength: 3`, `FormModel` decodes its initial values on construction,\n * and the whole page died at `useForm` with \"Too small: expected string to\n * have >=3 characters at /username\" — before anything rendered. `apps/examples/shop`\n * is such a realm, and `\"none\"` is also the framework default, so this is\n * what any new app hits first.\n *\n * ⚠️ `AuthRegister.tsx` excludes `\"email\"` here as well, and this\n * deliberately does not. In that mode `RegistrationService` derives the\n * handle from the address and drops whatever the client sent, so the\n * registration form is right to hide a field the user does not choose — but\n * the account page is where an existing, already-derived username is shown,\n * and Lore (github.com/alepha-dev/lore) runs exactly this mode. Whether\n * editing it there should be\n * possible at all is a real question (a rename desyncs it from the email\n * that produced it, and `updateMyProfile` does not re-run the slugger), but\n * it is a separate one from \"this realm has no usernames\", and answering it\n * by quietly deleting the field is not the place to start.\n */\n const hasUsername = props.realmConfig?.settings?.username !== \"none\";\n\n /**\n * Validated against the server's own body schema, so \"3 to 30 characters\"\n * is enforced before the request rather than only by the 400 that comes\n * back — and is stated in exactly one place.\n *\n * The schema stays whole and `username` is dropped from the *values*: the\n * column is `.optional()`, so an absent key decodes cleanly, while the empty\n * string does not. Omitting it from `groups` below is what hides the row —\n * `AutoForm` renders the fields its groups name and nothing else — and an\n * absent value is what keeps it out of the request.\n *\n * ⚠️ **`username` is never seeded as `\"\"`, even when the field is shown.**\n * The old `?? \"\"` was not only a `\"none\"`-realm problem: `\"optional\"` is a\n * realm that collects usernames and does not insist, so an account without\n * one is the normal case there — and it crashed the page for exactly those\n * users while working for everyone who had set one. `undefined` is what an\n * empty optional field means, and it is what the two name fields would use\n * too if they were not `.nullable()` with a real \"clear me\" state.\n */\n const form = useForm({\n initialValues: {\n ...(hasUsername ? { username: props.profile?.username } : {}),\n firstName: props.profile?.firstName ?? \"\",\n lastName: props.profile?.lastName ?? \"\",\n },\n schema: updateMyProfileBodySchema,\n handler: async (values) => {\n setProfile(\n await api.updateMyProfile({\n body: {\n // Empty is \"unset\", which the API spells `null` — NOT\n // `undefined`, which means \"leave this column alone\" and made\n // clearing a name a silent no-op that still toasted success.\n firstName: values.firstName || null,\n lastName: values.lastName || null,\n // Absent, not `null`, in a realm without usernames: `null` is the\n // \"clear this column\" signal the two name fields use, and\n // `username` has no such state — absent is \"leave it alone\".\n username: values.username,\n },\n }),\n );\n toaster.show(\n tr(\"account.profile.updated\", { default: \"Profile updated\" }),\n \"success\",\n );\n // No catch. A refusal (the username-taken 409, with its own message)\n // propagates: that keeps the form dirty and errored so Save stays\n // actionable, and `ActionErrorToaster` shows the message once. It used\n // to be toasted here too, which put it on screen twice wherever that\n // listener is mounted. Same division of labour as the auth forms and\n // `AdminUserDetail`: the handler throws, the toaster shows.\n },\n });\n\n if (!profile) {\n return null;\n }\n\n const onPickAvatar = async (event: ChangeEvent<HTMLInputElement>) => {\n const file = event.target.files?.[0];\n if (!file) {\n return;\n }\n setUploading(true);\n try {\n setProfile(await avatarApi.updateMyAvatar({ body: { file } }));\n toaster.show(\n tr(\"account.profile.avatarUpdated\", { default: \"Avatar updated\" }),\n \"success\",\n );\n } catch (error: any) {\n toaster.show(\n error?.message ??\n tr(\"account.profile.avatarUploadError\", {\n default: \"Could not upload that image\",\n }),\n \"danger\",\n );\n } finally {\n setUploading(false);\n // Reset so picking the same file again still fires a change event.\n if (fileInput.current) {\n fileInput.current.value = \"\";\n }\n }\n };\n\n const removeAvatar = async () => {\n setUploading(true);\n try {\n setProfile(await avatarApi.deleteMyAvatar());\n } catch (error: any) {\n toaster.show(\n error?.message ??\n tr(\"account.profile.avatarRemoveError\", {\n default: \"Could not remove your avatar\",\n }),\n \"danger\",\n );\n } finally {\n setUploading(false);\n }\n };\n\n // Realms opt into avatars (`features.avatars`, off by default), and an\n // unregistered action is absent from `/api/_links` — so this is the realm's\n // own switch read through the mechanism that cannot drift from it. Checking\n // a flag mirrored into the client instead would let the picker render\n // against endpoints that answer 404.\n const canEditAvatar = avatarApi.updateMyAvatar.can();\n\n return (\n <AccountPage variant=\"form\">\n {canEditAvatar && (\n <>\n <SettingsSection\n title={tr(\"account.profile.pictureTitle\", {\n default: \"Profile picture\",\n })}\n description={tr(\"account.profile.pictureDescription\", {\n default: \"Shown next to your name wherever you appear.\",\n })}\n >\n <SettingsRow\n label={tr(\"account.profile.avatar\", { default: \"Avatar\" })}\n description={tr(\"account.profile.avatarDescription\", {\n default: \"PNG, JPEG, GIF or WebP, up to 5 MB.\",\n })}\n >\n <div className=\"flex items-center gap-3\">\n <button\n type=\"button\"\n onClick={() => fileInput.current?.click()}\n disabled={uploading}\n aria-label={tr(\"account.profile.avatarChange\", {\n default: \"Change avatar\",\n })}\n className=\"relative size-14 shrink-0\"\n >\n {/* Only the image is clipped to a circle; the camera badge sits\n outside the wrapper so the round mask cannot crop it. */}\n <div className=\"bg-muted size-full overflow-hidden rounded-full border\">\n <FileImage\n id={profile.picture}\n public\n alt=\"\"\n className=\"size-full object-cover\"\n fallback={\n <div className=\"flex size-full items-center justify-center\">\n <User className=\"size-6\" />\n </div>\n }\n />\n </div>\n <div className=\"bg-card absolute right-0 bottom-0 flex size-5 items-center justify-center rounded-full border\">\n <Camera className=\"size-3\" />\n </div>\n </button>\n {profile.picture ? (\n <Button\n variant=\"minimal\"\n size=\"sm\"\n onClick={removeAvatar}\n disabled={uploading}\n >\n <Trash2 className=\"size-4\" />\n {tr(\"account.profile.avatarRemove\", { default: \"Remove\" })}\n </Button>\n ) : null}\n </div>\n </SettingsRow>\n </SettingsSection>\n\n <input\n type=\"file\"\n ref={fileInput}\n onChange={onPickAvatar}\n accept=\"image/jpeg,image/png,image/webp,image/gif\"\n className=\"hidden\"\n />\n </>\n )}\n\n {/* The one section here whose rows are all form fields, so it is an\n `AutoForm` in row layout rather than hand-wired `SettingsRow`s — same\n card, same rows, same heading, plus schema validation, the error\n popover, Reset, and a Save that knows whether anything changed. The\n sections above and below stay hand-wired because their rows are an\n avatar picker and read-only values, not fields. */}\n <AutoForm\n form={form}\n layout=\"row\"\n disabledIfPristine\n groups={[\n {\n title: tr(\"account.profile.nameTitle\", { default: \"Name\" }),\n description: tr(\"account.profile.nameDescription\", {\n default: \"How you are identified to other people.\",\n }),\n fields: hasUsername\n ? [\"username\", \"firstName\", \"lastName\"]\n : [\"firstName\", \"lastName\"],\n },\n ]}\n fields={{\n // Labels are explicit rather than derived: `prettyName` would title\n // -case them into \"First Name\", and this page's wording is settled.\n //\n // Icons are explicit because `Control`'s own fallback would resolve\n // the schema hint, and for a plain string that is the generic \"T\"\n // glyph — the same mark three times, saying \"this is text\" next to a\n // label that already said so. A field earns an icon by having one\n // that means something: `@` is what a handle looks like everywhere.\n username: {\n label: tr(\"account.profile.username\", { default: \"Username\" }),\n description: tr(\"account.profile.usernameDescription\", {\n default: \"Unique across this site.\",\n }),\n autoComplete: \"username\",\n icon: AtSign,\n // No clear button: `updateMyProfile` has no \"unset\" for a\n // username, so the × would offer a deletion the server cannot\n // perform. First and last name keep theirs — those genuinely\n // clear, via `null`.\n clearable: false,\n },\n firstName: {\n label: tr(\"account.profile.firstName\", { default: \"First name\" }),\n autoComplete: \"given-name\",\n icon: User,\n },\n lastName: {\n label: tr(\"account.profile.lastName\", { default: \"Last name\" }),\n autoComplete: \"family-name\",\n icon: User,\n },\n }}\n />\n\n <SettingsSection\n title={tr(\"account.profile.accountTitle\", { default: \"Account\" })}\n description={tr(\"account.profile.accountDescription\", {\n default: \"Details you cannot change from this page.\",\n })}\n >\n <SettingsRow\n label={tr(\"account.profile.email\", { default: \"Email\" })}\n description={tr(\"account.profile.emailDescription\", {\n default:\n \"Changing your email needs verification, so it is not a profile edit.\",\n })}\n >\n <span className=\"text-muted-foreground text-sm\">\n {profile.email ??\n tr(\"account.profile.emailUnset\", { default: \"Not set\" })}\n </span>\n </SettingsRow>\n <SettingsRow label={tr(\"account.profile.roles\", { default: \"Roles\" })}>\n <div className=\"flex flex-wrap gap-1\">\n {profile.roles.length > 0 ? (\n profile.roles.map((role) => (\n <Badge key={role} variant=\"outline\" className=\"text-xs\">\n {role}\n </Badge>\n ))\n ) : (\n <span className=\"text-muted-foreground text-sm\">—</span>\n )}\n </div>\n </SettingsRow>\n <SettingsRow\n label={tr(\"account.profile.memberSince\", { default: \"Member since\" })}\n >\n <span className=\"text-muted-foreground text-sm\">\n {l(profile.createdAt, { date: \"LL\" })}\n </span>\n </SettingsRow>\n </SettingsSection>\n </AccountPage>\n );\n};\n\nexport default AccountProfile;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,kBAAkB,UAA+B;CACrD,MAAM,MAAM,UAA+B;CAC3C,MAAM,YAAY,UAA8B;CAChD,MAAM,UAAU,SAAS;CACzB,MAAM,EAAE,GAAG,OAAO,QAAQ;CAC1B,MAAM,YAAY,OAAyB,IAAI;CAE/C,MAAM,CAAC,SAAS,cAAc,SAAgC,MAAM,OAAO;CAC3E,MAAM,CAAC,WAAW,gBAAgB,SAAS,KAAK;CAoChD,MAAM,cAAc,MAAM,aAAa,UAAU,aAAa;;;;;;;;;;;;;;;;;;;;CAqB9D,MAAM,OAAO,QAAQ;EACnB,eAAe;GACb,GAAI,cAAc,EAAE,UAAU,MAAM,SAAS,SAAS,IAAI,CAAC;GAC3D,WAAW,MAAM,SAAS,aAAa;GACvC,UAAU,MAAM,SAAS,YAAY;EACvC;EACA,QAAQ;EACR,SAAS,OAAO,WAAW;GACzB,WACE,MAAM,IAAI,gBAAgB,EACxB,MAAM;IAIJ,WAAW,OAAO,aAAa;IAC/B,UAAU,OAAO,YAAY;IAI7B,UAAU,OAAO;GACnB,EACF,CAAC,CACH;GACA,QAAQ,KACN,GAAG,2BAA2B,EAAE,SAAS,kBAAkB,CAAC,GAC5D,SACF;EAOF;CACF,CAAC;CAED,IAAI,CAAC,SACH,OAAO;CAGT,MAAM,eAAe,OAAO,UAAyC;EACnE,MAAM,OAAO,MAAM,OAAO,QAAQ;EAClC,IAAI,CAAC,MACH;EAEF,aAAa,IAAI;EACjB,IAAI;GACF,WAAW,MAAM,UAAU,eAAe,EAAE,MAAM,EAAE,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AAD;MACE,OAAO,GAAG,yBAAyB,EAAE,SAAS,QAAQ,CAAC;MACvD,aAAa,GAAG,oCAAoC,EAClD,SACE,uEACJ,CAAC;MAED,UAAA,oBAAC,QAAD;OAAM,WAAU;OACb,UAAA,QAAQ,SACP,GAAG,8BAA8B,EAAE,SAAS,UAAU,CAAC;MACrD,CAAA;KACK,CAAA;KACb,oBAAC,aAAD;MAAa,OAAO,GAAG,yBAAyB,EAAE,SAAS,QAAQ,CAAC;MAClE,UAAA,oBAAC,OAAD;OAAK,WAAU;OACZ,UAAA,QAAQ,MAAM,SAAS,IACtB,QAAQ,MAAM,KAAK,SACjB,oBAAC,OAAD;QAAkB,SAAQ;QAAU,WAAU;QAC3C,UAAA;OACI,GAFK,IAEL,CACR,IAED,oBAAC,QAAD;QAAM,WAAU;QAAgC,UAAA;OAAO,CAAA;MAEtD,CAAA;KACM,CAAA;KACb,oBAAC,aAAD;MACE,OAAO,GAAG,+BAA+B,EAAE,SAAS,eAAe,CAAC;MAEpE,UAAA,oBAAC,QAAD;OAAM,WAAU;OACb,UAAA,EAAE,QAAQ,WAAW,EAAE,MAAM,KAAK,CAAC;MAChC,CAAA;KACK,CAAA;IACE;;EACN;;AAEjB"}
|
|
1
|
+
{"version":3,"file":"AccountProfile.js","names":[],"sources":["../../src/account/AccountProfile.tsx"],"sourcesContent":["import type {\n MyAvatarController,\n MyProfile,\n MyProfileController,\n RealmConfig,\n} from \"alepha/api/users\";\nimport { updateMyProfileBodySchema } from \"alepha/api/users\";\nimport { useAction, useClient } from \"alepha/react\";\nimport { useForm } from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { AtSign, Camera, Trash2, User } from \"lucide-react\";\nimport { type ChangeEvent, useRef, useState } from \"react\";\n\nimport { Badge } from \"../core/Badge.tsx\";\nimport { Button } from \"../core/Button.tsx\";\nimport { FileImage } from \"../core/FileImage.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { AutoForm } from \"../form/AutoForm.tsx\";\nimport { SettingsRow } from \"../settings/SettingsRow.tsx\";\nimport { SettingsSection } from \"../settings/SettingsSection.tsx\";\nimport { AccountPage } from \"./AccountPage.tsx\";\n\nexport interface AccountProfileProps {\n /**\n * Supplied by the route loader. Optional so the page can also be rendered\n * standalone in a story or a test.\n */\n profile?: MyProfile;\n\n /**\n * Supplied by the route loader, and read for one thing: whether this realm\n * collects usernames at all.\n *\n * Optional for the same reason `profile` is. Absent, the username field\n * renders — the historical behaviour, and the right guess for a realm nobody\n * described.\n */\n realmConfig?: RealmConfig;\n}\n\n/**\n * Who you are: avatar, name, and the read-only facts about the account.\n *\n * Email is shown but not editable — changing it is a verification flow, not a\n * profile edit, and `updateMyProfile` deliberately refuses it. Rather than\n * render a disabled input with no explanation, the row says so.\n */\nconst AccountProfile = (props: AccountProfileProps) => {\n const api = useClient<MyProfileController>();\n const avatarApi = useClient<MyAvatarController>();\n const toaster = useToast();\n const { l, tr } = useI18n();\n const fileInput = useRef<HTMLInputElement>(null);\n\n const [profile, setProfile] = useState<MyProfile | undefined>(props.profile);\n // A refused image (too large, a type the realm does not take) is toasted\n // by the app's ActionErrorToaster with the server's message.\n const uploadAvatar = useAction<[file: File]>(\n {\n handler: async (_ctx, file) => {\n setProfile(await avatarApi.updateMyAvatar({ body: { file } }));\n toaster.show(\n tr(\"account.profile.avatarUpdated\", { default: \"Avatar updated\" }),\n \"success\",\n );\n },\n },\n [avatarApi, toaster, tr],\n );\n const removeAvatar = useAction<[]>(\n {\n handler: async () => {\n setProfile(await avatarApi.deleteMyAvatar());\n },\n },\n [avatarApi],\n );\n const uploading = uploadAvatar.loading || removeAvatar.loading;\n\n /*\n * Does this realm have usernames at all?\n *\n * The avatar section above reads its switch through `can()`, because a realm\n * with `features.avatars` off registers no avatar action and the capability\n * is simply absent from `/api/_links`. That cannot work here:\n * `updateMyProfile` is the same call that saves first and last name, so it\n * exists in every realm and its presence says nothing about usernames.\n *\n * The realm's own `settings.username` is the switch, and `\"none\"` is the\n * only value that hides the row: it is the one that means this realm has no\n * such thing as a username, so there is nothing to show and nothing the user\n * could set.\n *\n * Without this, a `\"none\"` realm did not merely render a pointless field:\n * `?? \"\"` seeded an empty string into a column that is `.optional()` but\n * `minLength: 3`, `FormModel` decodes its initial values on construction,\n * and the whole page died at `useForm` with \"Too small: expected string to\n * have >=3 characters at /username\" — before anything rendered. `apps/examples/shop`\n * is such a realm, and `\"none\"` is also the framework default, so this is\n * what any new app hits first.\n *\n * ⚠️ `AuthRegister.tsx` excludes `\"email\"` here as well, and this\n * deliberately does not. In that mode `RegistrationService` derives the\n * handle from the address and drops whatever the client sent, so the\n * registration form is right to hide a field the user does not choose — but\n * the account page is where an existing, already-derived username is shown,\n * and Lore (github.com/alepha-dev/lore) runs exactly this mode. Whether\n * editing it there should be\n * possible at all is a real question (a rename desyncs it from the email\n * that produced it, and `updateMyProfile` does not re-run the slugger), but\n * it is a separate one from \"this realm has no usernames\", and answering it\n * by quietly deleting the field is not the place to start.\n */\n const hasUsername = props.realmConfig?.settings?.username !== \"none\";\n\n /**\n * Validated against the server's own body schema, so \"3 to 30 characters\"\n * is enforced before the request rather than only by the 400 that comes\n * back — and is stated in exactly one place.\n *\n * The schema stays whole and `username` is dropped from the *values*: the\n * column is `.optional()`, so an absent key decodes cleanly, while the empty\n * string does not. Omitting it from `groups` below is what hides the row —\n * `AutoForm` renders the fields its groups name and nothing else — and an\n * absent value is what keeps it out of the request.\n *\n * ⚠️ **`username` is never seeded as `\"\"`, even when the field is shown.**\n * The old `?? \"\"` was not only a `\"none\"`-realm problem: `\"optional\"` is a\n * realm that collects usernames and does not insist, so an account without\n * one is the normal case there — and it crashed the page for exactly those\n * users while working for everyone who had set one. `undefined` is what an\n * empty optional field means, and it is what the two name fields would use\n * too if they were not `.nullable()` with a real \"clear me\" state.\n */\n const form = useForm({\n initialValues: {\n ...(hasUsername ? { username: props.profile?.username } : {}),\n firstName: props.profile?.firstName ?? \"\",\n lastName: props.profile?.lastName ?? \"\",\n },\n schema: updateMyProfileBodySchema,\n handler: async (values) => {\n setProfile(\n await api.updateMyProfile({\n body: {\n // Empty is \"unset\", which the API spells `null` — NOT\n // `undefined`, which means \"leave this column alone\" and made\n // clearing a name a silent no-op that still toasted success.\n firstName: values.firstName || null,\n lastName: values.lastName || null,\n // Absent, not `null`, in a realm without usernames: `null` is the\n // \"clear this column\" signal the two name fields use, and\n // `username` has no such state — absent is \"leave it alone\".\n username: values.username,\n },\n }),\n );\n toaster.show(\n tr(\"account.profile.updated\", { default: \"Profile updated\" }),\n \"success\",\n );\n // No catch. A refusal (the username-taken 409, with its own message)\n // propagates: that keeps the form dirty and errored so Save stays\n // actionable, and `ActionErrorToaster` shows the message once. It used\n // to be toasted here too, which put it on screen twice wherever that\n // listener is mounted. Same division of labour as the auth forms and\n // `AdminUserDetail`: the handler throws, the toaster shows.\n },\n });\n\n if (!profile) {\n return null;\n }\n\n const onPickAvatar = (event: ChangeEvent<HTMLInputElement>) => {\n const file = event.target.files?.[0];\n // Cleared at once, so picking the same file again still fires a change.\n event.target.value = \"\";\n if (!file) {\n return;\n }\n void uploadAvatar.run(file);\n };\n\n // Realms opt into avatars (`features.avatars`, off by default), and an\n // unregistered action is absent from `/api/_links` — so this is the realm's\n // own switch read through the mechanism that cannot drift from it. Checking\n // a flag mirrored into the client instead would let the picker render\n // against endpoints that answer 404.\n const canEditAvatar = avatarApi.updateMyAvatar.can();\n\n return (\n <AccountPage variant=\"form\">\n {canEditAvatar && (\n <>\n <SettingsSection\n title={tr(\"account.profile.pictureTitle\", {\n default: \"Profile picture\",\n })}\n description={tr(\"account.profile.pictureDescription\", {\n default: \"Shown next to your name wherever you appear.\",\n })}\n >\n <SettingsRow\n label={tr(\"account.profile.avatar\", { default: \"Avatar\" })}\n description={tr(\"account.profile.avatarDescription\", {\n default: \"PNG, JPEG, GIF or WebP, up to 5 MB.\",\n })}\n >\n <div className=\"flex items-center gap-3\">\n <button\n type=\"button\"\n onClick={() => fileInput.current?.click()}\n disabled={uploading}\n aria-label={tr(\"account.profile.avatarChange\", {\n default: \"Change avatar\",\n })}\n className=\"relative size-14 shrink-0\"\n >\n {/* Only the image is clipped to a circle; the camera badge sits\n outside the wrapper so the round mask cannot crop it. */}\n <div className=\"bg-muted size-full overflow-hidden rounded-full border\">\n <FileImage\n id={profile.picture}\n public\n alt=\"\"\n className=\"size-full object-cover\"\n fallback={\n <div className=\"flex size-full items-center justify-center\">\n <User className=\"size-6\" />\n </div>\n }\n />\n </div>\n <div className=\"bg-card absolute right-0 bottom-0 flex size-5 items-center justify-center rounded-full border\">\n <Camera className=\"size-3\" />\n </div>\n </button>\n {profile.picture ? (\n <Button\n variant=\"minimal\"\n size=\"sm\"\n onClick={() => removeAvatar.run()}\n disabled={uploading}\n >\n <Trash2 className=\"size-4\" />\n {tr(\"account.profile.avatarRemove\", { default: \"Remove\" })}\n </Button>\n ) : null}\n </div>\n </SettingsRow>\n </SettingsSection>\n\n <input\n type=\"file\"\n ref={fileInput}\n onChange={onPickAvatar}\n accept=\"image/jpeg,image/png,image/webp,image/gif\"\n className=\"hidden\"\n />\n </>\n )}\n\n {/* The one section here whose rows are all form fields, so it is an\n `AutoForm` in row layout rather than hand-wired `SettingsRow`s — same\n card, same rows, same heading, plus schema validation, the error\n popover, Reset, and a Save that knows whether anything changed. The\n sections above and below stay hand-wired because their rows are an\n avatar picker and read-only values, not fields. */}\n <AutoForm\n form={form}\n layout=\"row\"\n disabledIfPristine\n groups={[\n {\n title: tr(\"account.profile.nameTitle\", { default: \"Name\" }),\n description: tr(\"account.profile.nameDescription\", {\n default: \"How you are identified to other people.\",\n }),\n fields: hasUsername\n ? [\"username\", \"firstName\", \"lastName\"]\n : [\"firstName\", \"lastName\"],\n },\n ]}\n fields={{\n // Labels are explicit rather than derived: `prettyName` would title\n // -case them into \"First Name\", and this page's wording is settled.\n //\n // Icons are explicit because `Control`'s own fallback would resolve\n // the schema hint, and for a plain string that is the generic \"T\"\n // glyph — the same mark three times, saying \"this is text\" next to a\n // label that already said so. A field earns an icon by having one\n // that means something: `@` is what a handle looks like everywhere.\n username: {\n label: tr(\"account.profile.username\", { default: \"Username\" }),\n description: tr(\"account.profile.usernameDescription\", {\n default: \"Unique across this site.\",\n }),\n autoComplete: \"username\",\n icon: AtSign,\n // No clear button: `updateMyProfile` has no \"unset\" for a\n // username, so the × would offer a deletion the server cannot\n // perform. First and last name keep theirs — those genuinely\n // clear, via `null`.\n clearable: false,\n },\n firstName: {\n label: tr(\"account.profile.firstName\", { default: \"First name\" }),\n autoComplete: \"given-name\",\n icon: User,\n },\n lastName: {\n label: tr(\"account.profile.lastName\", { default: \"Last name\" }),\n autoComplete: \"family-name\",\n icon: User,\n },\n }}\n />\n\n <SettingsSection\n title={tr(\"account.profile.accountTitle\", { default: \"Account\" })}\n description={tr(\"account.profile.accountDescription\", {\n default: \"Details you cannot change from this page.\",\n })}\n >\n <SettingsRow\n label={tr(\"account.profile.email\", { default: \"Email\" })}\n description={tr(\"account.profile.emailDescription\", {\n default:\n \"Changing your email needs verification, so it is not a profile edit.\",\n })}\n >\n <span className=\"text-muted-foreground text-sm\">\n {profile.email ??\n tr(\"account.profile.emailUnset\", { default: \"Not set\" })}\n </span>\n </SettingsRow>\n <SettingsRow label={tr(\"account.profile.roles\", { default: \"Roles\" })}>\n <div className=\"flex flex-wrap gap-1\">\n {profile.roles.length > 0 ? (\n profile.roles.map((role) => (\n <Badge key={role} variant=\"outline\" className=\"text-xs\">\n {role}\n </Badge>\n ))\n ) : (\n <span className=\"text-muted-foreground text-sm\">—</span>\n )}\n </div>\n </SettingsRow>\n <SettingsRow\n label={tr(\"account.profile.memberSince\", { default: \"Member since\" })}\n >\n <span className=\"text-muted-foreground text-sm\">\n {l(profile.createdAt, { date: \"LL\" })}\n </span>\n </SettingsRow>\n </SettingsSection>\n </AccountPage>\n );\n};\n\nexport default AccountProfile;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,kBAAkB,UAA+B;CACrD,MAAM,MAAM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AD;QAAM,WAAU;QAAgC,UAAA;OAAO,CAAA;MAEtD,CAAA;KACM,CAAA;KACb,oBAAC,aAAD;MACE,OAAO,GAAG,+BAA+B,EAAE,SAAS,eAAe,CAAC;MAEpE,UAAA,oBAAC,QAAD;OAAM,WAAU;OACb,UAAA,EAAE,QAAQ,WAAW,EAAE,MAAM,KAAK,CAAC;MAChC,CAAA;KACK,CAAA;IACE;;EACN;;AAEjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountSecurity.d.ts","sourceRoot":"","sources":["../../src/account/AccountSecurity.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAIV,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EAAE,KAAK,SAAS,EAAY,MAAM,OAAO,CAAC;AAejD,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,UAAU,EAAE,CAAC;IAE1B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAE1B;;;;OAIG;IACH,aAAa,CAAC,EAAE,SAAS,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,QAAA,MAAM,eAAe,UAAW,oBAAoB,
|
|
1
|
+
{"version":3,"file":"AccountSecurity.d.ts","sourceRoot":"","sources":["../../src/account/AccountSecurity.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EAIV,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EAAE,KAAK,SAAS,EAAY,MAAM,OAAO,CAAC;AAejD,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,UAAU,EAAE,CAAC;IAE1B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAE1B;;;;OAIG;IACH,aAAa,CAAC,EAAE,SAAS,CAAC;CAC3B;AAED;;;;;;;GAOG;AACH,QAAA,MAAM,eAAe,UAAW,oBAAoB,gCAkVnD,CAAC;eAEa,eAAe"}
|
|
@@ -64,21 +64,23 @@ const AccountSecurity = (props) => {
|
|
|
64
64
|
* A session alone is not proof: someone at an unattended signed-in browser
|
|
65
65
|
* could otherwise strip the factor and come back later at leisure.
|
|
66
66
|
*/
|
|
67
|
-
const disableMfa = async () => {
|
|
67
|
+
const disableMfa = useAction({ handler: async () => {
|
|
68
68
|
const code = await dialog.prompt({
|
|
69
69
|
title: tr("account.security.mfaDisableTitle", { default: "Turn off two-factor authentication?" }),
|
|
70
70
|
description: tr("account.security.mfaDisableDescription", { default: "Enter a code from your authenticator app, or one of your recovery codes." }),
|
|
71
71
|
confirmLabel: tr("account.security.mfaTurnOff", { default: "Turn off" })
|
|
72
72
|
});
|
|
73
73
|
if (!code) return;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
74
|
+
await mfaApi.disableTotp({ body: { code: String(code) } });
|
|
75
|
+
await reloadMfa();
|
|
76
|
+
toaster.show(tr("account.security.mfaDisabled", { default: "Two-factor authentication is off" }), "success");
|
|
77
|
+
} }, [
|
|
78
|
+
dialog,
|
|
79
|
+
mfaApi,
|
|
80
|
+
reloadMfa,
|
|
81
|
+
toaster,
|
|
82
|
+
tr
|
|
83
|
+
]);
|
|
82
84
|
const [newCodes, setNewCodes] = useState();
|
|
83
85
|
/**
|
|
84
86
|
* A new set of recovery codes, for somebody who used some up or lost them
|
|
@@ -97,7 +99,7 @@ const AccountSecurity = (props) => {
|
|
|
97
99
|
setNewCodes(result.recoveryCodes);
|
|
98
100
|
await reloadMfa();
|
|
99
101
|
} }, [mfaApi, dialog]);
|
|
100
|
-
const unlink = async (identity) => {
|
|
102
|
+
const unlink = useAction({ handler: async (_ctx, identity) => {
|
|
101
103
|
const label = PROVIDER_LABELS[identity.provider] ?? identity.provider;
|
|
102
104
|
if (!await dialog.confirm({
|
|
103
105
|
title: tr("account.security.unlinkTitle", {
|
|
@@ -111,13 +113,13 @@ const AccountSecurity = (props) => {
|
|
|
111
113
|
confirmLabel: tr("account.security.unlink", { default: "Remove" }),
|
|
112
114
|
destructive: true
|
|
113
115
|
})) return;
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
116
|
+
await api.unlinkMyIdentity({ params: { id: identity.id } });
|
|
117
|
+
await reload();
|
|
118
|
+
} }, [
|
|
119
|
+
api,
|
|
120
|
+
dialog,
|
|
121
|
+
tr
|
|
122
|
+
]);
|
|
121
123
|
return /* @__PURE__ */ jsxs(AccountPage, {
|
|
122
124
|
variant: "form",
|
|
123
125
|
children: [
|
|
@@ -134,7 +136,7 @@ const AccountSecurity = (props) => {
|
|
|
134
136
|
children: signInMethods.length > 1 ? /* @__PURE__ */ jsx(Button, {
|
|
135
137
|
variant: "minimal",
|
|
136
138
|
size: "sm",
|
|
137
|
-
onClick: () => unlink(identity),
|
|
139
|
+
onClick: () => unlink.run(identity),
|
|
138
140
|
"aria-label": tr("account.security.unlinkAria", {
|
|
139
141
|
default: "Remove $1",
|
|
140
142
|
args: [identity.provider]
|
|
@@ -163,7 +165,7 @@ const AccountSecurity = (props) => {
|
|
|
163
165
|
variant: "solid",
|
|
164
166
|
intent: "none",
|
|
165
167
|
size: "sm",
|
|
166
|
-
onClick: disableMfa,
|
|
168
|
+
onClick: () => disableMfa.run(),
|
|
167
169
|
children: [/* @__PURE__ */ jsx(ShieldOff, { className: "size-4" }), tr("account.security.mfaTurnOff", { default: "Turn off" })]
|
|
168
170
|
})]
|
|
169
171
|
}) : /* @__PURE__ */ jsxs(Button, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountSecurity.js","names":[],"sources":["../../src/account/AccountSecurity.tsx"],"sourcesContent":["import type {\n MyIdentity,\n MyIdentityController,\n MyMfaController,\n MyMfaStatus,\n RealmConfig,\n} from \"alepha/api/users\";\nimport { useAction, useClient, useQuery } from \"alepha/react\";\nimport { useAuth } from \"alepha/react/auth\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport {\n KeyRound,\n RefreshCw,\n ShieldCheck,\n ShieldOff,\n Trash2,\n} from \"lucide-react\";\nimport { type ReactNode, useState } from \"react\";\n\nimport { PROVIDER_LABELS } from \"../auth/providerLabels.ts\";\nimport { Button } from \"../core/Button.tsx\";\nimport { useDialog } from \"../core/useDialog.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { SettingsDangerSection } from \"../settings/SettingsDangerSection.tsx\";\nimport { SettingsRow } from \"../settings/SettingsRow.tsx\";\nimport { SettingsSection } from \"../settings/SettingsSection.tsx\";\nimport { AccountDeleteDialog } from \"./AccountDeleteDialog.tsx\";\nimport { AccountMfaDialog } from \"./AccountMfaDialog.tsx\";\nimport { AccountPage } from \"./AccountPage.tsx\";\nimport { AccountPasswordDialog } from \"./AccountPasswordDialog.tsx\";\nimport { AccountRecoveryCodesDialog } from \"./AccountRecoveryCodesDialog.tsx\";\n\nexport interface AccountSecurityProps {\n identities?: MyIdentity[];\n\n /**\n * Carries `settings.mfa`, which decides whether the two-factor row is\n * offered at all.\n *\n * Optional for the same reason it is on Profile. Absent, the row renders:\n * the historical behaviour, and the safer guess, since hiding a factor a realm\n * does want is a worse failure than showing one it does not, because the\n * server refuses the enrollment either way.\n */\n realmConfig?: RealmConfig;\n\n /**\n * Rendered inside the delete-account dialog, above the confirmation field.\n * See {@link AccountDeleteDialogProps.warning} — this is how an application\n * states what deletion costs in *its* data.\n */\n deleteWarning?: ReactNode;\n}\n\n/**\n * How you get in, and how to stop existing.\n *\n * The delete-account row lives here rather than on Profile because the\n * re-authentication it demands is the same material as everything else on\n * this page — and because a destructive action on the page you land on by\n * default is a worse default than one behind a deliberate click.\n */\nconst AccountSecurity = (props: AccountSecurityProps) => {\n const api = useClient<MyIdentityController>();\n const mfaApi = useClient<MyMfaController>();\n const auth = useAuth();\n const dialog = useDialog();\n const toaster = useToast();\n const { l, tr } = useI18n();\n\n const [identities, setIdentities] = useState<MyIdentity[]>(\n props.identities ?? [],\n );\n const [passwordOpen, setPasswordOpen] = useState(false);\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [mfaOpen, setMfaOpen] = useState(false);\n\n const { data: mfa, refetch: reloadMfa } = useQuery<MyMfaStatus>(\n { handler: () => mfaApi.getMyMfa() as Promise<MyMfaStatus> },\n [],\n );\n\n const hasPassword = identities.some((it) => it.provider === \"credentials\");\n\n /**\n * A TOTP enrollment is stored as an identity row, but it is not a way to\n * sign in. Listing it here would both duplicate the two-factor row below\n * and offer a Remove button that strips the factor without asking for a\n * code, which is exactly what `disableTotp` refuses to do.\n */\n const signInMethods = identities.filter((it) => it.provider !== \"totp\");\n\n /**\n * A realm can turn the authenticator-app factor off. Offering a Set up\n * button then walks the user through a QR, ten recovery codes and an \"On\"\n * badge for a factor the login gate will never ask for, so the row is not\n * offered at all.\n *\n * An enrollment that predates the setting is the exception: it stays\n * visible, because hiding it would strand a factor the user can neither see\n * nor remove.\n */\n const totpDisabled = props.realmConfig?.settings?.mfa?.totp === \"disabled\";\n const totpStranded = totpDisabled && !!mfa?.totp.enabled;\n const showMfaRow = !totpDisabled || totpStranded;\n\n const reload = async () => setIdentities(await api.listMyIdentities());\n\n /**\n * Turning it off asks for a current code rather than just a confirmation.\n * A session alone is not proof: someone at an unattended signed-in browser\n * could otherwise strip the factor and come back later at leisure.\n */\n const disableMfa = async () => {\n const code = await dialog.prompt({\n title: tr(\"account.security.mfaDisableTitle\", {\n default: \"Turn off two-factor authentication?\",\n }),\n description: tr(\"account.security.mfaDisableDescription\", {\n default:\n \"Enter a code from your authenticator app, or one of your recovery codes.\",\n }),\n confirmLabel: tr(\"account.security.mfaTurnOff\", { default: \"Turn off\" }),\n });\n if (!code) {\n return;\n }\n try {\n await mfaApi.disableTotp({ body: { code: String(code) } });\n await reloadMfa();\n toaster.show(\n tr(\"account.security.mfaDisabled\", {\n default: \"Two-factor authentication is off\",\n }),\n \"success\",\n );\n } catch (error: any) {\n toaster.show(\n error?.message ??\n tr(\"account.security.invalidCode\", {\n default: \"That code is not valid\",\n }),\n \"danger\",\n );\n }\n };\n\n const [newCodes, setNewCodes] = useState<string[]>();\n\n /**\n * A new set of recovery codes, for somebody who used some up or lost them\n * (#Q2518). Asks for a code first, like turning the factor off: new codes\n * are a way in, so a live session alone must not be able to mint them. A\n * refusal (a wrong code) is toasted by the app's `ActionErrorToaster`.\n */\n const regenerateCodes = useAction<[], void>(\n {\n handler: async () => {\n const code = await dialog.prompt({\n title: tr(\"account.security.mfaRegenerateTitle\", {\n default: \"Get new recovery codes?\",\n }),\n description: tr(\"account.security.mfaRegenerateDescription\", {\n default:\n \"Your current recovery codes stop working. Enter a code from your authenticator app, or one of your recovery codes.\",\n }),\n confirmLabel: tr(\"account.security.mfaRegenerate\", {\n default: \"New recovery codes\",\n }),\n });\n if (!code) {\n return;\n }\n const result = await mfaApi.regenerateRecoveryCodes({\n body: { code: String(code) },\n });\n setNewCodes(result.recoveryCodes);\n await reloadMfa();\n },\n },\n [mfaApi, dialog],\n );\n\n const unlink = async (identity: MyIdentity) => {\n const label = PROVIDER_LABELS[identity.provider] ?? identity.provider;\n const ok = await dialog.confirm({\n title: tr(\"account.security.unlinkTitle\", {\n default: \"Remove $1?\",\n args: [label],\n }),\n description: tr(\"account.security.unlinkDescription\", {\n default: \"You will no longer be able to sign in with $1.\",\n args: [label],\n }),\n confirmLabel: tr(\"account.security.unlink\", { default: \"Remove\" }),\n destructive: true,\n });\n if (!ok) {\n return;\n }\n try {\n await api.unlinkMyIdentity({ params: { id: identity.id } });\n await reload();\n } catch (error: any) {\n // Includes the last-identity refusal, whose message is the whole point.\n toaster.show(\n error?.message ??\n tr(\"account.security.unlinkError\", {\n default: \"Could not remove that method\",\n }),\n \"danger\",\n );\n }\n };\n\n return (\n <AccountPage variant=\"form\">\n <SettingsSection\n title={tr(\"account.security.methodsTitle\", {\n default: \"Sign-in methods\",\n })}\n description={tr(\"account.security.methodsDescription\", {\n default:\n \"At least one must remain. Removing the last would lock you out permanently.\",\n })}\n >\n {signInMethods.map((identity) => (\n <SettingsRow\n key={identity.id}\n label={PROVIDER_LABELS[identity.provider] ?? identity.provider}\n description={tr(\"account.security.addedAt\", {\n default: \"Added $1\",\n args: [l(identity.createdAt, { date: \"ll\" })],\n })}\n >\n {signInMethods.length > 1 ? (\n <Button\n variant=\"minimal\"\n size=\"sm\"\n onClick={() => unlink(identity)}\n aria-label={tr(\"account.security.unlinkAria\", {\n default: \"Remove $1\",\n args: [identity.provider],\n })}\n >\n <Trash2 className=\"size-4\" />\n </Button>\n ) : null}\n </SettingsRow>\n ))}\n\n {showMfaRow ? (\n <SettingsRow\n label={tr(\"account.security.mfa\", {\n default: \"Two-factor authentication\",\n })}\n description={\n totpStranded\n ? tr(\"account.security.mfaNoLongerUsed\", {\n default:\n \"This site no longer asks for a code. You can remove it.\",\n })\n : mfa?.totp.enabled\n ? // Two calls, not one with a computed key: the FR coverage spec\n // finds keys by matching a literal right after `tr(`, so a key\n // chosen at runtime is invisible to it and would rot silently.\n mfa.totp.recoveryCodesLeft === 1\n ? tr(\"account.security.mfaOnOneCode\", {\n default: \"On. $1 recovery code left.\",\n args: [String(mfa.totp.recoveryCodesLeft)],\n })\n : tr(\"account.security.mfaOnCodes\", {\n default: \"On. $1 recovery codes left.\",\n args: [String(mfa.totp.recoveryCodesLeft)],\n })\n : tr(\"account.security.mfaOff\", {\n default:\n \"Ask for a code from an authenticator app as well as your password.\",\n })\n }\n >\n {mfa?.totp.enabled ? (\n <div className=\"flex gap-2\">\n {!totpStranded ? (\n <Button\n variant=\"minimal\"\n size=\"sm\"\n loading={regenerateCodes.loading}\n onClick={() => void regenerateCodes.run()}\n >\n <RefreshCw className=\"size-4\" />\n {tr(\"account.security.mfaRegenerate\", {\n default: \"New recovery codes\",\n })}\n </Button>\n ) : null}\n <Button\n variant=\"solid\"\n intent=\"none\"\n size=\"sm\"\n onClick={disableMfa}\n >\n <ShieldOff className=\"size-4\" />\n {tr(\"account.security.mfaTurnOff\", { default: \"Turn off\" })}\n </Button>\n </div>\n ) : (\n <Button\n variant=\"solid\"\n intent=\"none\"\n size=\"sm\"\n onClick={() => setMfaOpen(true)}\n >\n <ShieldCheck className=\"size-4\" />\n {tr(\"account.security.mfaSetUp\", { default: \"Set up\" })}\n </Button>\n )}\n </SettingsRow>\n ) : null}\n\n <SettingsRow\n label={tr(\"account.security.password\", { default: \"Password\" })}\n description={\n hasPassword\n ? tr(\"account.security.passwordChangeHint\", {\n default: \"Changing it signs out every other device.\",\n })\n : tr(\"account.security.passwordSetHint\", {\n default:\n \"This account signs in without a password. Add one as a fallback.\",\n })\n }\n >\n <Button\n variant=\"solid\"\n intent=\"none\"\n size=\"sm\"\n onClick={() => setPasswordOpen(true)}\n >\n <KeyRound className=\"size-4\" />\n {hasPassword\n ? tr(\"account.security.passwordChange\", {\n default: \"Change password\",\n })\n : tr(\"account.security.passwordSet\", {\n default: \"Set a password\",\n })}\n </Button>\n </SettingsRow>\n </SettingsSection>\n\n <SettingsDangerSection\n description={tr(\"account.security.dangerDescription\", {\n default: \"This cannot be undone.\",\n })}\n >\n <SettingsRow\n label={tr(\"account.security.delete\", {\n default: \"Delete this account\",\n })}\n description={tr(\"account.security.deleteDescription\", {\n default:\n \"Removes your account, its sign-in methods and every session.\",\n })}\n >\n <Button\n variant=\"outlined\"\n intent=\"danger\"\n size=\"sm\"\n onClick={() => setDeleteOpen(true)}\n >\n {tr(\"account.security.deleteButton\", {\n default: \"Delete account\",\n })}\n </Button>\n </SettingsRow>\n </SettingsDangerSection>\n\n <AccountPasswordDialog\n open={passwordOpen}\n hasPassword={hasPassword}\n onOpenChange={setPasswordOpen}\n onDone={reload}\n />\n\n <AccountRecoveryCodesDialog\n codes={newCodes}\n onClose={() => setNewCodes(undefined)}\n />\n\n <AccountMfaDialog\n open={mfaOpen}\n onOpenChange={setMfaOpen}\n onDone={async () => {\n await reloadMfa();\n }}\n />\n\n <AccountDeleteDialog\n open={deleteOpen}\n hasPassword={hasPassword}\n onOpenChange={setDeleteOpen}\n warning={props.deleteWarning}\n onDeleted={() => auth.logout()}\n />\n </AccountPage>\n );\n};\n\nexport default AccountSecurity;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,mBAAmB,UAAgC;CACvD,MAAM,MAAM,UAAgC;CAC5C,MAAM,SAAS,UAA2B;CAC1C,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,UAAU;CACzB,MAAM,UAAU,SAAS;CACzB,MAAM,EAAE,GAAG,OAAO,QAAQ;CAE1B,MAAM,CAAC,YAAY,iBAAiB,SAClC,MAAM,cAAc,CAAC,CACvB;CACA,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CACtD,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAE5C,MAAM,EAAE,MAAM,KAAK,SAAS,cAAc,SACxC,EAAE,eAAe,OAAO,SAAS,EAA0B,GAC3D,CAAC,CACH;CAEA,MAAM,cAAc,WAAW,MAAM,OAAO,GAAG,aAAa,aAAa;;;;;;;CAQzE,MAAM,gBAAgB,WAAW,QAAQ,OAAO,GAAG,aAAa,MAAM;;;;;;;;;;;CAYtE,MAAM,eAAe,MAAM,aAAa,UAAU,KAAK,SAAS;CAChE,MAAM,eAAe,gBAAgB,CAAC,CAAC,KAAK,KAAK;CACjD,MAAM,aAAa,CAAC,gBAAgB;CAEpC,MAAM,SAAS,YAAY,cAAc,MAAM,IAAI,iBAAiB,CAAC;;;;;;CAOrE,MAAM,aAAa,YAAY;EAC7B,MAAM,OAAO,MAAM,OAAO,OAAO;GAC/B,OAAO,GAAG,oCAAoC,EAC5C,SAAS,sCACX,CAAC;GACD,aAAa,GAAG,0CAA0C,EACxD,SACE,2EACJ,CAAC;GACD,cAAc,GAAG,+BAA+B,EAAE,SAAS,WAAW,CAAC;EACzE,CAAC;EACD,IAAI,CAAC,MACH;EAEF,IAAI;GAC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AAO;MACP,MAAK;MACL,eAAe,cAAc,IAAI;MAEhC,UAAA,GAAG,iCAAiC,EACnC,SAAS,iBACX,CAAC;KACK,CAAA;IACG,CAAA;GACQ,CAAA;GAEvB,oBAAC,uBAAD;IACE,MAAM;IACO;IACb,cAAc;IACd,QAAQ;GACT,CAAA;GAED,oBAAC,4BAAD;IACE,OAAO;IACP,eAAe,YAAY,KAAA,CAAS;GACrC,CAAA;GAED,oBAAC,kBAAD;IACE,MAAM;IACN,cAAc;IACd,QAAQ,YAAY;KAClB,MAAM,UAAU;IAClB;GACD,CAAA;GAED,oBAAC,qBAAD;IACE,MAAM;IACO;IACb,cAAc;IACd,SAAS,MAAM;IACf,iBAAiB,KAAK,OAAO;GAC9B,CAAA;EACU;;AAEjB"}
|
|
1
|
+
{"version":3,"file":"AccountSecurity.js","names":[],"sources":["../../src/account/AccountSecurity.tsx"],"sourcesContent":["import type {\n MyIdentity,\n MyIdentityController,\n MyMfaController,\n MyMfaStatus,\n RealmConfig,\n} from \"alepha/api/users\";\nimport { useAction, useClient, useQuery } from \"alepha/react\";\nimport { useAuth } from \"alepha/react/auth\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport {\n KeyRound,\n RefreshCw,\n ShieldCheck,\n ShieldOff,\n Trash2,\n} from \"lucide-react\";\nimport { type ReactNode, useState } from \"react\";\n\nimport { PROVIDER_LABELS } from \"../auth/providerLabels.ts\";\nimport { Button } from \"../core/Button.tsx\";\nimport { useDialog } from \"../core/useDialog.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { SettingsDangerSection } from \"../settings/SettingsDangerSection.tsx\";\nimport { SettingsRow } from \"../settings/SettingsRow.tsx\";\nimport { SettingsSection } from \"../settings/SettingsSection.tsx\";\nimport { AccountDeleteDialog } from \"./AccountDeleteDialog.tsx\";\nimport { AccountMfaDialog } from \"./AccountMfaDialog.tsx\";\nimport { AccountPage } from \"./AccountPage.tsx\";\nimport { AccountPasswordDialog } from \"./AccountPasswordDialog.tsx\";\nimport { AccountRecoveryCodesDialog } from \"./AccountRecoveryCodesDialog.tsx\";\n\nexport interface AccountSecurityProps {\n identities?: MyIdentity[];\n\n /**\n * Carries `settings.mfa`, which decides whether the two-factor row is\n * offered at all.\n *\n * Optional for the same reason it is on Profile. Absent, the row renders:\n * the historical behaviour, and the safer guess, since hiding a factor a realm\n * does want is a worse failure than showing one it does not, because the\n * server refuses the enrollment either way.\n */\n realmConfig?: RealmConfig;\n\n /**\n * Rendered inside the delete-account dialog, above the confirmation field.\n * See {@link AccountDeleteDialogProps.warning} — this is how an application\n * states what deletion costs in *its* data.\n */\n deleteWarning?: ReactNode;\n}\n\n/**\n * How you get in, and how to stop existing.\n *\n * The delete-account row lives here rather than on Profile because the\n * re-authentication it demands is the same material as everything else on\n * this page — and because a destructive action on the page you land on by\n * default is a worse default than one behind a deliberate click.\n */\nconst AccountSecurity = (props: AccountSecurityProps) => {\n const api = useClient<MyIdentityController>();\n const mfaApi = useClient<MyMfaController>();\n const auth = useAuth();\n const dialog = useDialog();\n const toaster = useToast();\n const { l, tr } = useI18n();\n\n const [identities, setIdentities] = useState<MyIdentity[]>(\n props.identities ?? [],\n );\n const [passwordOpen, setPasswordOpen] = useState(false);\n const [deleteOpen, setDeleteOpen] = useState(false);\n const [mfaOpen, setMfaOpen] = useState(false);\n\n const { data: mfa, refetch: reloadMfa } = useQuery<MyMfaStatus>(\n { handler: () => mfaApi.getMyMfa() as Promise<MyMfaStatus> },\n [],\n );\n\n const hasPassword = identities.some((it) => it.provider === \"credentials\");\n\n /**\n * A TOTP enrollment is stored as an identity row, but it is not a way to\n * sign in. Listing it here would both duplicate the two-factor row below\n * and offer a Remove button that strips the factor without asking for a\n * code, which is exactly what `disableTotp` refuses to do.\n */\n const signInMethods = identities.filter((it) => it.provider !== \"totp\");\n\n /**\n * A realm can turn the authenticator-app factor off. Offering a Set up\n * button then walks the user through a QR, ten recovery codes and an \"On\"\n * badge for a factor the login gate will never ask for, so the row is not\n * offered at all.\n *\n * An enrollment that predates the setting is the exception: it stays\n * visible, because hiding it would strand a factor the user can neither see\n * nor remove.\n */\n const totpDisabled = props.realmConfig?.settings?.mfa?.totp === \"disabled\";\n const totpStranded = totpDisabled && !!mfa?.totp.enabled;\n const showMfaRow = !totpDisabled || totpStranded;\n\n const reload = async () => setIdentities(await api.listMyIdentities());\n\n /**\n * Turning it off asks for a current code rather than just a confirmation.\n * A session alone is not proof: someone at an unattended signed-in browser\n * could otherwise strip the factor and come back later at leisure.\n */\n const disableMfa = useAction<[]>(\n {\n handler: async () => {\n const code = await dialog.prompt({\n title: tr(\"account.security.mfaDisableTitle\", {\n default: \"Turn off two-factor authentication?\",\n }),\n description: tr(\"account.security.mfaDisableDescription\", {\n default:\n \"Enter a code from your authenticator app, or one of your recovery codes.\",\n }),\n confirmLabel: tr(\"account.security.mfaTurnOff\", {\n default: \"Turn off\",\n }),\n });\n if (!code) {\n return;\n }\n await mfaApi.disableTotp({ body: { code: String(code) } });\n await reloadMfa();\n toaster.show(\n tr(\"account.security.mfaDisabled\", {\n default: \"Two-factor authentication is off\",\n }),\n \"success\",\n );\n },\n },\n [dialog, mfaApi, reloadMfa, toaster, tr],\n );\n\n const [newCodes, setNewCodes] = useState<string[]>();\n\n /**\n * A new set of recovery codes, for somebody who used some up or lost them\n * (#Q2518). Asks for a code first, like turning the factor off: new codes\n * are a way in, so a live session alone must not be able to mint them. A\n * refusal (a wrong code) is toasted by the app's `ActionErrorToaster`.\n */\n const regenerateCodes = useAction<[], void>(\n {\n handler: async () => {\n const code = await dialog.prompt({\n title: tr(\"account.security.mfaRegenerateTitle\", {\n default: \"Get new recovery codes?\",\n }),\n description: tr(\"account.security.mfaRegenerateDescription\", {\n default:\n \"Your current recovery codes stop working. Enter a code from your authenticator app, or one of your recovery codes.\",\n }),\n confirmLabel: tr(\"account.security.mfaRegenerate\", {\n default: \"New recovery codes\",\n }),\n });\n if (!code) {\n return;\n }\n const result = await mfaApi.regenerateRecoveryCodes({\n body: { code: String(code) },\n });\n setNewCodes(result.recoveryCodes);\n await reloadMfa();\n },\n },\n [mfaApi, dialog],\n );\n\n // The last-identity refusal arrives as an error whose message is the whole\n // point; the app's ActionErrorToaster shows it verbatim.\n const unlink = useAction<[identity: MyIdentity]>(\n {\n handler: async (_ctx, identity) => {\n const label = PROVIDER_LABELS[identity.provider] ?? identity.provider;\n const ok = await dialog.confirm({\n title: tr(\"account.security.unlinkTitle\", {\n default: \"Remove $1?\",\n args: [label],\n }),\n description: tr(\"account.security.unlinkDescription\", {\n default: \"You will no longer be able to sign in with $1.\",\n args: [label],\n }),\n confirmLabel: tr(\"account.security.unlink\", { default: \"Remove\" }),\n destructive: true,\n });\n if (!ok) {\n return;\n }\n await api.unlinkMyIdentity({ params: { id: identity.id } });\n await reload();\n },\n },\n [api, dialog, tr],\n );\n\n return (\n <AccountPage variant=\"form\">\n <SettingsSection\n title={tr(\"account.security.methodsTitle\", {\n default: \"Sign-in methods\",\n })}\n description={tr(\"account.security.methodsDescription\", {\n default:\n \"At least one must remain. Removing the last would lock you out permanently.\",\n })}\n >\n {signInMethods.map((identity) => (\n <SettingsRow\n key={identity.id}\n label={PROVIDER_LABELS[identity.provider] ?? identity.provider}\n description={tr(\"account.security.addedAt\", {\n default: \"Added $1\",\n args: [l(identity.createdAt, { date: \"ll\" })],\n })}\n >\n {signInMethods.length > 1 ? (\n <Button\n variant=\"minimal\"\n size=\"sm\"\n onClick={() => unlink.run(identity)}\n aria-label={tr(\"account.security.unlinkAria\", {\n default: \"Remove $1\",\n args: [identity.provider],\n })}\n >\n <Trash2 className=\"size-4\" />\n </Button>\n ) : null}\n </SettingsRow>\n ))}\n\n {showMfaRow ? (\n <SettingsRow\n label={tr(\"account.security.mfa\", {\n default: \"Two-factor authentication\",\n })}\n description={\n totpStranded\n ? tr(\"account.security.mfaNoLongerUsed\", {\n default:\n \"This site no longer asks for a code. You can remove it.\",\n })\n : mfa?.totp.enabled\n ? // Two calls, not one with a computed key: the FR coverage spec\n // finds keys by matching a literal right after `tr(`, so a key\n // chosen at runtime is invisible to it and would rot silently.\n mfa.totp.recoveryCodesLeft === 1\n ? tr(\"account.security.mfaOnOneCode\", {\n default: \"On. $1 recovery code left.\",\n args: [String(mfa.totp.recoveryCodesLeft)],\n })\n : tr(\"account.security.mfaOnCodes\", {\n default: \"On. $1 recovery codes left.\",\n args: [String(mfa.totp.recoveryCodesLeft)],\n })\n : tr(\"account.security.mfaOff\", {\n default:\n \"Ask for a code from an authenticator app as well as your password.\",\n })\n }\n >\n {mfa?.totp.enabled ? (\n <div className=\"flex gap-2\">\n {!totpStranded ? (\n <Button\n variant=\"minimal\"\n size=\"sm\"\n loading={regenerateCodes.loading}\n onClick={() => void regenerateCodes.run()}\n >\n <RefreshCw className=\"size-4\" />\n {tr(\"account.security.mfaRegenerate\", {\n default: \"New recovery codes\",\n })}\n </Button>\n ) : null}\n <Button\n variant=\"solid\"\n intent=\"none\"\n size=\"sm\"\n onClick={() => disableMfa.run()}\n >\n <ShieldOff className=\"size-4\" />\n {tr(\"account.security.mfaTurnOff\", { default: \"Turn off\" })}\n </Button>\n </div>\n ) : (\n <Button\n variant=\"solid\"\n intent=\"none\"\n size=\"sm\"\n onClick={() => setMfaOpen(true)}\n >\n <ShieldCheck className=\"size-4\" />\n {tr(\"account.security.mfaSetUp\", { default: \"Set up\" })}\n </Button>\n )}\n </SettingsRow>\n ) : null}\n\n <SettingsRow\n label={tr(\"account.security.password\", { default: \"Password\" })}\n description={\n hasPassword\n ? tr(\"account.security.passwordChangeHint\", {\n default: \"Changing it signs out every other device.\",\n })\n : tr(\"account.security.passwordSetHint\", {\n default:\n \"This account signs in without a password. Add one as a fallback.\",\n })\n }\n >\n <Button\n variant=\"solid\"\n intent=\"none\"\n size=\"sm\"\n onClick={() => setPasswordOpen(true)}\n >\n <KeyRound className=\"size-4\" />\n {hasPassword\n ? tr(\"account.security.passwordChange\", {\n default: \"Change password\",\n })\n : tr(\"account.security.passwordSet\", {\n default: \"Set a password\",\n })}\n </Button>\n </SettingsRow>\n </SettingsSection>\n\n <SettingsDangerSection\n description={tr(\"account.security.dangerDescription\", {\n default: \"This cannot be undone.\",\n })}\n >\n <SettingsRow\n label={tr(\"account.security.delete\", {\n default: \"Delete this account\",\n })}\n description={tr(\"account.security.deleteDescription\", {\n default:\n \"Removes your account, its sign-in methods and every session.\",\n })}\n >\n <Button\n variant=\"outlined\"\n intent=\"danger\"\n size=\"sm\"\n onClick={() => setDeleteOpen(true)}\n >\n {tr(\"account.security.deleteButton\", {\n default: \"Delete account\",\n })}\n </Button>\n </SettingsRow>\n </SettingsDangerSection>\n\n <AccountPasswordDialog\n open={passwordOpen}\n hasPassword={hasPassword}\n onOpenChange={setPasswordOpen}\n onDone={reload}\n />\n\n <AccountRecoveryCodesDialog\n codes={newCodes}\n onClose={() => setNewCodes(undefined)}\n />\n\n <AccountMfaDialog\n open={mfaOpen}\n onOpenChange={setMfaOpen}\n onDone={async () => {\n await reloadMfa();\n }}\n />\n\n <AccountDeleteDialog\n open={deleteOpen}\n hasPassword={hasPassword}\n onOpenChange={setDeleteOpen}\n warning={props.deleteWarning}\n onDeleted={() => auth.logout()}\n />\n </AccountPage>\n );\n};\n\nexport default AccountSecurity;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAM,mBAAmB,UAAgC;CACvD,MAAM,MAAM,UAAgC;CAC5C,MAAM,SAAS,UAA2B;CAC1C,MAAM,OAAO,QAAQ;CACrB,MAAM,SAAS,UAAU;CACzB,MAAM,UAAU,SAAS;CACzB,MAAM,EAAE,GAAG,OAAO,QAAQ;CAE1B,MAAM,CAAC,YAAY,iBAAiB,SAClC,MAAM,cAAc,CAAC,CACvB;CACA,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CACtD,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAE5C,MAAM,EAAE,MAAM,KAAK,SAAS,cAAc,SACxC,EAAE,e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EACxC,SAAS,4CACX,CAAC,IACD,GAAG,oCAAoC,EACrC,SACE,mEACJ,CAAC;MAGP,UAAA,qBAAC,QAAD;OACE,SAAQ;OACR,QAAO;OACP,MAAK;OACL,eAAe,gBAAgB,IAAI;OAJrC,UAAA,CAME,oBAAC,UAAD,EAAU,WAAU,SAAU,CAAA,GAC7B,cACG,GAAG,mCAAmC,EACpC,SAAS,kBACX,CAAC,IACD,GAAG,gCAAgC,EACjC,SAAS,iBACX,CAAC,CACC;;KACG,CAAA;IACE;;GAEjB,oBAAC,uBAAD;IACE,aAAa,GAAG,sCAAsC,EACpD,SAAS,yBACX,CAAC;IAED,UAAA,oBAAC,aAAD;KACE,OAAO,GAAG,2BAA2B,EACnC,SAAS,sBACX,CAAC;KACD,aAAa,GAAG,sCAAsC,EACpD,SACE,+DACJ,CAAC;KAED,UAAA,oBAAC,QAAD;MACE,SAAQ;MACR,QAAO;MACP,MAAK;MACL,eAAe,cAAc,IAAI;MAEhC,UAAA,GAAG,iCAAiC,EACnC,SAAS,iBACX,CAAC;KACK,CAAA;IACG,CAAA;GACQ,CAAA;GAEvB,oBAAC,uBAAD;IACE,MAAM;IACO;IACb,cAAc;IACd,QAAQ;GACT,CAAA;GAED,oBAAC,4BAAD;IACE,OAAO;IACP,eAAe,YAAY,KAAA,CAAS;GACrC,CAAA;GAED,oBAAC,kBAAD;IACE,MAAM;IACN,cAAc;IACd,QAAQ,YAAY;KAClB,MAAM,UAAU;IAClB;GACD,CAAA;GAED,oBAAC,qBAAD;IACE,MAAM;IACO;IACb,cAAc;IACd,SAAS,MAAM;IACf,iBAAiB,KAAK,OAAO;GAC9B,CAAA;EACU;;AAEjB"}
|
|
@@ -58,7 +58,7 @@ const AccountSessions = (props) => {
|
|
|
58
58
|
args: [agent.browser, agent.os]
|
|
59
59
|
});
|
|
60
60
|
};
|
|
61
|
-
const revoke = useAction({ handler: async (session) => {
|
|
61
|
+
const revoke = useAction({ handler: async (_ctx, session) => {
|
|
62
62
|
if (!await dialog.confirm({
|
|
63
63
|
title: tr("account.sessions.revokeTitle", { default: "Revoke this session?" }),
|
|
64
64
|
description: tr("account.sessions.revokeDescription", { default: "That browser or device is signed out. Signing in again there starts a new session." }),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AccountSessions.js","names":[],"sources":["../../src/account/AccountSessions.tsx"],"sourcesContent":["import type { MySession, MySessionController } from \"alepha/api/users\";\nimport { useAction, useClient } from \"alepha/react\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport {\n CircleHelp,\n LogOut,\n Monitor,\n RadioTower,\n Smartphone,\n Tablet,\n} from \"lucide-react\";\nimport { useState } from \"react\";\n\nimport { Badge } from \"../core/Badge.tsx\";\nimport TimeAgo from \"../core/TimeAgo.tsx\";\nimport { useDialog } from \"../core/useDialog.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { DataTable } from \"../table/DataTable.tsx\";\nimport { AccountPage } from \"./AccountPage.tsx\";\n\nexport interface AccountSessionsProps {\n sessions?: MySession[];\n}\n\n/**\n * Where you are signed in, and how to stop being: a `DataTable` over the\n * sessions the route loader fetched.\n *\n * `listMySessions` returns the whole list unpaginated, so the table is given\n * the array (`data`) and pages, sorts and filters it in memory\n * (`paginateLocal`). A revoke answers with nothing to re-read: the handler\n * drops the row from the array it owns, which is the table's refresh in this\n * mode.\n *\n * The current session carries a \"This device\" badge and no row action: the\n * way to end it is to sign out, and a row button that signs you out of the\n * page you are reading is a trap. \"Sign out everywhere else\" is the toolbar's\n * primary action, shown while there is anything else to end.\n *\n * Both writes are confirmed. They are `useAction` runs, so a failure is\n * toasted by the shell's `ActionErrorToaster`, and every row action and the\n * toolbar button are disabled while either is in flight.\n */\nconst AccountSessions = (props: AccountSessionsProps) => {\n const api = useClient<MySessionController>();\n const dialog = useDialog();\n const toast = useToast();\n const { tr } = useI18n();\n const [sessions, setSessions] = useState<MySession[]>(props.sessions ?? []);\n\n const deviceIcon = (session: MySession) => {\n if (session.userAgent?.device === \"MOBILE\") {\n return <Smartphone className=\"size-4 shrink-0\" />;\n }\n if (session.userAgent?.device === \"TABLET\") {\n return <Tablet className=\"size-4 shrink-0\" />;\n }\n // A monitor is a claim, not a neutral glyph: it says \"this was a computer\n // with a screen\". A client the parser could not place is drawn as such.\n if (!session.userAgent || session.userAgent.device === \"UNKNOWN\") {\n return <CircleHelp className=\"size-4 shrink-0\" />;\n }\n return <Monitor className=\"size-4 shrink-0\" />;\n };\n\n /**\n * The device's name, and the reason it is allowed to say nothing.\n *\n * A session minted for an API client or an OAuth/MCP agent carries a\n * user-agent the parser cannot place, and naming it after whichever\n * browser happens to be commonest would be inventing evidence about where\n * an account is signed in. Both halves unknown reads as one honest\n * \"Unknown device\" rather than \"Unknown on Unknown\".\n */\n const label = (session: MySession) => {\n const agent = session.userAgent;\n if (!agent || (agent.browser === \"Unknown\" && agent.os === \"Unknown\")) {\n return tr(\"account.sessions.unknownDevice\", {\n default: \"Unknown device\",\n });\n }\n return tr(\"account.sessions.deviceLabel\", {\n default: \"$1 on $2\",\n args: [agent.browser, agent.os],\n });\n };\n\n const revoke = useAction<[session: MySession], boolean>(\n {\n handler: async (session) => {\n const ok = await dialog.confirm({\n title: tr(\"account.sessions.revokeTitle\", {\n default: \"Revoke this session?\",\n }),\n description: tr(\"account.sessions.revokeDescription\", {\n default:\n \"That browser or device is signed out. Signing in again there starts a new session.\",\n }),\n confirmLabel: tr(\"account.sessions.revoke\", { default: \"Revoke\" }),\n destructive: true,\n });\n if (!ok) {\n return false;\n }\n await api.deleteMySession({ params: { id: session.id } });\n setSessions((prev) => prev.filter((it) => it.id !== session.id));\n return true;\n },\n },\n [api, dialog, tr],\n );\n\n const revokeOthers = useAction<[], boolean>(\n {\n handler: async () => {\n const ok = await dialog.confirm({\n title: tr(\"account.sessions.revokeOthersTitle\", {\n default: \"Sign out everywhere else?\",\n }),\n description: tr(\"account.sessions.revokeOthersDescription\", {\n default:\n \"Every other browser and device will be signed out. This one stays signed in.\",\n }),\n confirmLabel: tr(\"account.sessions.revokeOthers\", {\n default: \"Sign out everywhere else\",\n }),\n destructive: true,\n });\n if (!ok) {\n return false;\n }\n const { revoked } = await api.deleteMyOtherSessions();\n setSessions((prev) => prev.filter((it) => it.current));\n toast.success(\n revoked === 1\n ? tr(\"account.sessions.revokedOne\", {\n default: \"1 session signed out\",\n })\n : tr(\"account.sessions.revokedMany\", {\n default: \"$1 sessions signed out\",\n args: [String(revoked)],\n }),\n );\n return true;\n },\n },\n [api, dialog, toast, tr],\n );\n\n const busy = revoke.loading || revokeOthers.loading;\n const others = sessions.filter((it) => !it.current).length;\n\n return (\n <AccountPage variant=\"table\">\n <DataTable<MySession>\n className=\"min-h-0 flex-1\"\n data={sessions}\n rowKey={(session) => session.id}\n defaultSort={{ field: \"lastUsedAt\", direction: \"desc\" }}\n actions={\n others > 0\n ? [\n {\n icon: LogOut,\n primary: true,\n disabled: busy,\n label:\n others === 1\n ? tr(\"account.sessions.signOutOne\", {\n default: \"Sign out 1 other\",\n })\n : tr(\"account.sessions.signOutMany\", {\n default: \"Sign out $1 others\",\n args: [String(others)],\n }),\n onClick: () => void revokeOthers.run(),\n },\n ]\n : []\n }\n emptyState={{\n icon: RadioTower,\n title: tr(\"account.sessions.title\", { default: \"Active sessions\" }),\n description: tr(\"account.sessions.description\", {\n default: \"Revoke any session you do not recognise.\",\n }),\n }}\n columns={{\n device: {\n label: tr(\"account.sessions.colDevice\", { default: \"Device\" }),\n cell: (session) => (\n <span\n className=\"flex items-center gap-2\"\n data-testid=\"account-session-device\"\n >\n {deviceIcon(session)}\n <span className=\"truncate\">{label(session)}</span>\n {session.current ? (\n <Badge tone=\"success\" data-testid=\"account-session-current\">\n {tr(\"account.sessions.thisDevice\", {\n default: \"This device\",\n })}\n </Badge>\n ) : null}\n </span>\n ),\n },\n ip: {\n label: tr(\"account.sessions.colIp\", { default: \"IP\" }),\n cell: (session) => (\n <span className=\"flex items-center gap-1.5\">\n <code className=\"text-xs\">\n {session.ip ??\n tr(\"account.sessions.unknownIp\", {\n default: \"unknown IP\",\n })}\n </code>\n {session.country ? (\n <span className=\"text-muted-foreground text-xs uppercase\">\n {session.country}\n </span>\n ) : null}\n </span>\n ),\n },\n createdAt: {\n label: tr(\"account.sessions.colSignedIn\", {\n default: \"Signed in\",\n }),\n sortable: true,\n cell: (session) => (\n <TimeAgo\n value={session.createdAt}\n className=\"text-muted-foreground text-xs\"\n />\n ),\n },\n /*\n When the session was last used, not when it was born: a\n long-lived session that refreshed this morning looks identical to\n an abandoned one by its start date, and this is the column\n somebody hunting a stolen laptop reads.\n */\n lastUsedAt: {\n label: tr(\"account.sessions.colLastUsed\", {\n default: \"Last used\",\n }),\n sortable: true,\n cell: (session) =>\n session.lastUsedAt ? (\n <TimeAgo\n value={session.lastUsedAt}\n className=\"text-muted-foreground text-xs\"\n />\n ) : (\n <span className=\"text-muted-foreground text-xs\">-</span>\n ),\n },\n }}\n rowActions={(session) =>\n session.current\n ? []\n : [\n {\n label: tr(\"account.sessions.revoke\", { default: \"Revoke\" }),\n icon: LogOut,\n destructive: true,\n disabled: () => busy,\n onClick: () => void revoke.run(session),\n },\n ]\n }\n />\n </AccountPage>\n );\n};\n\nexport default AccountSessions;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,mBAAmB,UAAgC;CACvD,MAAM,MAAM,UAA+B;CAC3C,MAAM,SAAS,UAAU;CACzB,MAAM,QAAQ,SAAS;CACvB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,CAAC,UAAU,eAAe,SAAsB,MAAM,YAAY,CAAC,CAAC;CAE1E,MAAM,cAAc,YAAuB;EACzC,IAAI,QAAQ,WAAW,WAAW,UAChC,OAAO,oBAAC,YAAD,EAAY,WAAU,kBAAmB,CAAA;EAElD,IAAI,QAAQ,WAAW,WAAW,UAChC,OAAO,oBAAC,QAAD,EAAQ,WAAU,kBAAmB,CAAA;EAI9C,IAAI,CAAC,QAAQ,aAAa,QAAQ,UAAU,W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,SAAS,KAAK,CAAC;KACrD,OAAO,YACL,qBAAC,QAAD;MAAM,WAAU;MAAhB,UAAA,CACE,oBAAC,QAAD;OAAM,WAAU;OACb,UAAA,QAAQ,MACP,GAAG,8BAA8B,EAC/B,SAAS,aACX,CAAC;MACC,CAAA,GACL,QAAQ,UACP,oBAAC,QAAD;OAAM,WAAU;OACb,UAAA,QAAQ;MACL,CAAA,IACJ,IACA;;IAEV;IACA,WAAW;KACT,OAAO,GAAG,gCAAgC,EACxC,SAAS,YACX,CAAC;KACD,UAAU;KACV,OAAO,YACL,oBAAC,SAAD;MACE,OAAO,QAAQ;MACf,WAAU;KACX,CAAA;IAEL;IAOA,YAAY;KACV,OAAO,GAAG,gCAAgC,EACxC,SAAS,YACX,CAAC;KACD,UAAU;KACV,OAAO,YACL,QAAQ,aACN,oBAAC,SAAD;MACE,OAAO,QAAQ;MACf,WAAU;KACX,CAAA,IAED,oBAAC,QAAD;MAAM,WAAU;MAAgC,UAAA;KAAO,CAAA;IAE7D;GACF;GACA,aAAa,YACX,QAAQ,UACJ,CAAC,IACD,CACE;IACE,OAAO,GAAG,2BAA2B,EAAE,SAAS,SAAS,CAAC;IAC1D,MAAM;IACN,aAAa;IACb,gBAAgB;IAChB,eAAe,KAAK,OAAO,IAAI,OAAO;GACxC,CACF;EAEP,CAAA;CACU,CAAA;AAEjB"}
|
|
1
|
+
{"version":3,"file":"AccountSessions.js","names":[],"sources":["../../src/account/AccountSessions.tsx"],"sourcesContent":["import type { MySession, MySessionController } from \"alepha/api/users\";\nimport { useAction, useClient } from \"alepha/react\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport {\n CircleHelp,\n LogOut,\n Monitor,\n RadioTower,\n Smartphone,\n Tablet,\n} from \"lucide-react\";\nimport { useState } from \"react\";\n\nimport { Badge } from \"../core/Badge.tsx\";\nimport TimeAgo from \"../core/TimeAgo.tsx\";\nimport { useDialog } from \"../core/useDialog.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { DataTable } from \"../table/DataTable.tsx\";\nimport { AccountPage } from \"./AccountPage.tsx\";\n\nexport interface AccountSessionsProps {\n sessions?: MySession[];\n}\n\n/**\n * Where you are signed in, and how to stop being: a `DataTable` over the\n * sessions the route loader fetched.\n *\n * `listMySessions` returns the whole list unpaginated, so the table is given\n * the array (`data`) and pages, sorts and filters it in memory\n * (`paginateLocal`). A revoke answers with nothing to re-read: the handler\n * drops the row from the array it owns, which is the table's refresh in this\n * mode.\n *\n * The current session carries a \"This device\" badge and no row action: the\n * way to end it is to sign out, and a row button that signs you out of the\n * page you are reading is a trap. \"Sign out everywhere else\" is the toolbar's\n * primary action, shown while there is anything else to end.\n *\n * Both writes are confirmed. They are `useAction` runs, so a failure is\n * toasted by the shell's `ActionErrorToaster`, and every row action and the\n * toolbar button are disabled while either is in flight.\n */\nconst AccountSessions = (props: AccountSessionsProps) => {\n const api = useClient<MySessionController>();\n const dialog = useDialog();\n const toast = useToast();\n const { tr } = useI18n();\n const [sessions, setSessions] = useState<MySession[]>(props.sessions ?? []);\n\n const deviceIcon = (session: MySession) => {\n if (session.userAgent?.device === \"MOBILE\") {\n return <Smartphone className=\"size-4 shrink-0\" />;\n }\n if (session.userAgent?.device === \"TABLET\") {\n return <Tablet className=\"size-4 shrink-0\" />;\n }\n // A monitor is a claim, not a neutral glyph: it says \"this was a computer\n // with a screen\". A client the parser could not place is drawn as such.\n if (!session.userAgent || session.userAgent.device === \"UNKNOWN\") {\n return <CircleHelp className=\"size-4 shrink-0\" />;\n }\n return <Monitor className=\"size-4 shrink-0\" />;\n };\n\n /**\n * The device's name, and the reason it is allowed to say nothing.\n *\n * A session minted for an API client or an OAuth/MCP agent carries a\n * user-agent the parser cannot place, and naming it after whichever\n * browser happens to be commonest would be inventing evidence about where\n * an account is signed in. Both halves unknown reads as one honest\n * \"Unknown device\" rather than \"Unknown on Unknown\".\n */\n const label = (session: MySession) => {\n const agent = session.userAgent;\n if (!agent || (agent.browser === \"Unknown\" && agent.os === \"Unknown\")) {\n return tr(\"account.sessions.unknownDevice\", {\n default: \"Unknown device\",\n });\n }\n return tr(\"account.sessions.deviceLabel\", {\n default: \"$1 on $2\",\n args: [agent.browser, agent.os],\n });\n };\n\n const revoke = useAction<[session: MySession], boolean>(\n {\n handler: async (_ctx, session) => {\n const ok = await dialog.confirm({\n title: tr(\"account.sessions.revokeTitle\", {\n default: \"Revoke this session?\",\n }),\n description: tr(\"account.sessions.revokeDescription\", {\n default:\n \"That browser or device is signed out. Signing in again there starts a new session.\",\n }),\n confirmLabel: tr(\"account.sessions.revoke\", { default: \"Revoke\" }),\n destructive: true,\n });\n if (!ok) {\n return false;\n }\n await api.deleteMySession({ params: { id: session.id } });\n setSessions((prev) => prev.filter((it) => it.id !== session.id));\n return true;\n },\n },\n [api, dialog, tr],\n );\n\n const revokeOthers = useAction<[], boolean>(\n {\n handler: async () => {\n const ok = await dialog.confirm({\n title: tr(\"account.sessions.revokeOthersTitle\", {\n default: \"Sign out everywhere else?\",\n }),\n description: tr(\"account.sessions.revokeOthersDescription\", {\n default:\n \"Every other browser and device will be signed out. This one stays signed in.\",\n }),\n confirmLabel: tr(\"account.sessions.revokeOthers\", {\n default: \"Sign out everywhere else\",\n }),\n destructive: true,\n });\n if (!ok) {\n return false;\n }\n const { revoked } = await api.deleteMyOtherSessions();\n setSessions((prev) => prev.filter((it) => it.current));\n toast.success(\n revoked === 1\n ? tr(\"account.sessions.revokedOne\", {\n default: \"1 session signed out\",\n })\n : tr(\"account.sessions.revokedMany\", {\n default: \"$1 sessions signed out\",\n args: [String(revoked)],\n }),\n );\n return true;\n },\n },\n [api, dialog, toast, tr],\n );\n\n const busy = revoke.loading || revokeOthers.loading;\n const others = sessions.filter((it) => !it.current).length;\n\n return (\n <AccountPage variant=\"table\">\n <DataTable<MySession>\n className=\"min-h-0 flex-1\"\n data={sessions}\n rowKey={(session) => session.id}\n defaultSort={{ field: \"lastUsedAt\", direction: \"desc\" }}\n actions={\n others > 0\n ? [\n {\n icon: LogOut,\n primary: true,\n disabled: busy,\n label:\n others === 1\n ? tr(\"account.sessions.signOutOne\", {\n default: \"Sign out 1 other\",\n })\n : tr(\"account.sessions.signOutMany\", {\n default: \"Sign out $1 others\",\n args: [String(others)],\n }),\n onClick: () => void revokeOthers.run(),\n },\n ]\n : []\n }\n emptyState={{\n icon: RadioTower,\n title: tr(\"account.sessions.title\", { default: \"Active sessions\" }),\n description: tr(\"account.sessions.description\", {\n default: \"Revoke any session you do not recognise.\",\n }),\n }}\n columns={{\n device: {\n label: tr(\"account.sessions.colDevice\", { default: \"Device\" }),\n cell: (session) => (\n <span\n className=\"flex items-center gap-2\"\n data-testid=\"account-session-device\"\n >\n {deviceIcon(session)}\n <span className=\"truncate\">{label(session)}</span>\n {session.current ? (\n <Badge tone=\"success\" data-testid=\"account-session-current\">\n {tr(\"account.sessions.thisDevice\", {\n default: \"This device\",\n })}\n </Badge>\n ) : null}\n </span>\n ),\n },\n ip: {\n label: tr(\"account.sessions.colIp\", { default: \"IP\" }),\n cell: (session) => (\n <span className=\"flex items-center gap-1.5\">\n <code className=\"text-xs\">\n {session.ip ??\n tr(\"account.sessions.unknownIp\", {\n default: \"unknown IP\",\n })}\n </code>\n {session.country ? (\n <span className=\"text-muted-foreground text-xs uppercase\">\n {session.country}\n </span>\n ) : null}\n </span>\n ),\n },\n createdAt: {\n label: tr(\"account.sessions.colSignedIn\", {\n default: \"Signed in\",\n }),\n sortable: true,\n cell: (session) => (\n <TimeAgo\n value={session.createdAt}\n className=\"text-muted-foreground text-xs\"\n />\n ),\n },\n /*\n When the session was last used, not when it was born: a\n long-lived session that refreshed this morning looks identical to\n an abandoned one by its start date, and this is the column\n somebody hunting a stolen laptop reads.\n */\n lastUsedAt: {\n label: tr(\"account.sessions.colLastUsed\", {\n default: \"Last used\",\n }),\n sortable: true,\n cell: (session) =>\n session.lastUsedAt ? (\n <TimeAgo\n value={session.lastUsedAt}\n className=\"text-muted-foreground text-xs\"\n />\n ) : (\n <span className=\"text-muted-foreground text-xs\">-</span>\n ),\n },\n }}\n rowActions={(session) =>\n session.current\n ? []\n : [\n {\n label: tr(\"account.sessions.revoke\", { default: \"Revoke\" }),\n icon: LogOut,\n destructive: true,\n disabled: () => busy,\n onClick: () => void revoke.run(session),\n },\n ]\n }\n />\n </AccountPage>\n );\n};\n\nexport default AccountSessions;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,mBAAmB,UAAgC;CACvD,MAAM,MAAM,UAA+B;CAC3C,MAAM,SAAS,UAAU;CACzB,MAAM,QAAQ,SAAS;CACvB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,CAAC,UAAU,eAAe,SAAsB,MAAM,YAAY,CAAC,CAAC;CAE1E,MAAM,cAAc,YAAuB;EACzC,IAAI,QAAQ,WAAW,WAAW,UAChC,OAAO,oBAAC,YAAD,EAAY,WAAU,kBAAmB,CAAA;EAElD,IAAI,QAAQ,WAAW,WAAW,UAChC,OAAO,oBAAC,QAAD,EAAQ,WAAU,kBAAmB,CAAA;EAI9C,IAAI,CAAC,QAAQ,aAAa,QAAQ,UAAU,WAAW,WACrD,OAAO,oBAAC,YAAD,EAAY,WAAU,kBAAmB,CAAA;EAElD,OAAO,oBAAC,SAAD,EAAS,WAAU,kBAAmB,CAAA;CAC/C;;;;;;;;;;CAWA,MAAM,SAAS,YAAuB;EACpC,MAAM,QAAQ,QAAQ;EACtB,IAAI,CAAC,SAAU,MAAM,YAAY,aAAa,MAAM,OAAO,WACzD,OAAO,GAAG,kCAAkC,EAC1C,SAAS,iBACX,CAAC;EAEH,OAAO,GAAG,gCAAgC;GACxC,SAAS;GACT,MAAM,CAAC,MAAM,SAAS,MAAM,EAAE;EAChC,CAAC;CACH;CAEA,MAAM,SAAS,UACb,EACE,SAAS,OAAO,MAAM,YAAY;EAYhC,IAAI,CAAC,MAXY,OAAO,QAAQ;GAC9B,OAAO,GAAG,gCAAgC,EACxC,SAAS,uBACX,CAAC;GACD,aAAa,GAAG,s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AAQ;MACf,WAAU;KACX,CAAA,IAED,oBAAC,QAAD;MAAM,WAAU;MAAgC,UAAA;KAAO,CAAA;IAE7D;GACF;GACA,aAAa,YACX,QAAQ,UACJ,CAAC,IACD,CACE;IACE,OAAO,GAAG,2BAA2B,EAAE,SAAS,SAAS,CAAC;IAC1D,MAAM;IACN,aAAa;IACb,gBAAgB;IAChB,eAAe,KAAK,OAAO,IAAI,OAAO;GACxC,CACF;EAEP,CAAA;CACU,CAAA;AAEjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApiKeyCreateDialog.d.ts","sourceRoot":"","sources":["../../src/account/ApiKeyCreateDialog.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,qBAAqB,EACrB,YAAY,EACb,MAAM,iBAAiB,CAAC;AAwBzB,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,OAAO,CAAC;IAEd,YAAY,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;IAEtC;;;OAGG;IACH,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnD;;;;;OAKG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,YAAY,CAAA;KAAE,CAAC,CAAC;IAE7D;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;OAGG;IACH,OAAO,CAAC,EAAE,qBAAqB,CAAC;CACjC;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,kBAAkB,UAAW,uBAAuB,
|
|
1
|
+
{"version":3,"file":"ApiKeyCreateDialog.d.ts","sourceRoot":"","sources":["../../src/account/ApiKeyCreateDialog.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAEV,qBAAqB,EACrB,YAAY,EACb,MAAM,iBAAiB,CAAC;AAwBzB,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,OAAO,CAAC;IAEd,YAAY,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;IAEtC;;;OAGG;IACH,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnD;;;;;OAKG;IACH,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,YAAY,CAAA;KAAE,CAAC,CAAC;IAE7D;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;OAGG;IACH,OAAO,CAAC,EAAE,qBAAqB,CAAC;CACjC;AAED;;;;;;;;;;GAUG;AACH,eAAO,MAAM,kBAAkB,UAAW,uBAAuB,gCA0QhE,CAAC"}
|
|
@@ -77,18 +77,14 @@ const ApiKeyCreateDialog = (props) => {
|
|
|
77
77
|
message: tr("account.keys.scopeRequired", { default: "Select at least one permission, or give the key full access." }),
|
|
78
78
|
path: "/permissions"
|
|
79
79
|
});
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
props.onOpenChange(false);
|
|
89
|
-
} catch (error) {
|
|
90
|
-
toaster.show(error?.message ?? tr("account.keys.createError", { default: "Could not create that key" }), "danger");
|
|
91
|
-
}
|
|
80
|
+
const created = await api.createApiKey({ body: {
|
|
81
|
+
name,
|
|
82
|
+
description: values.description?.trim() || void 0,
|
|
83
|
+
expiresIn: values.expiresIn,
|
|
84
|
+
permissions
|
|
85
|
+
} });
|
|
86
|
+
await props.onCreated(created.token);
|
|
87
|
+
props.onOpenChange(false);
|
|
92
88
|
}
|
|
93
89
|
}, [props.open]);
|
|
94
90
|
const state = useFormState(form, ["loading"]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ApiKeyCreateDialog.js","names":[],"sources":["../../src/account/ApiKeyCreateDialog.tsx"],"sourcesContent":["import { z } from \"alepha\";\nimport type {\n ApiKeyController,\n ApiKeyOptionsResponse,\n ApiKeyStatus,\n} from \"alepha/api/keys\";\nimport { useClient } from \"alepha/react\";\nimport {\n FormValidationError,\n useFieldValue,\n useForm,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useEffect, useMemo, useState } from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"../core/Dialog.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { ApiKeyScopeMatrix } from \"./ApiKeyScopeMatrix.tsx\";\n\nexport interface ApiKeyCreateDialogProps {\n open: boolean;\n\n onOpenChange: (open: boolean) => void;\n\n /**\n * Called with the new key's plain token, the only time it exists in a\n * readable form. The caller shows it.\n */\n onCreated: (token: string) => void | Promise<void>;\n\n /**\n * The keys the owner already holds. A live or an expired key keeps its name\n * (revoking frees it), so a clashing name is explained before the request,\n * and an expired holder is pointed at its Rotate action rather than\n * refused with the database's words.\n */\n existingKeys?: Array<{ name: string; status: ApiKeyStatus }>;\n\n /**\n * One sentence on whose key this is, shown above the fields. The admin\n * surface says the key is minted for the admin's own account; the account\n * panel needs no such sentence.\n */\n ownershipNote?: string;\n\n /**\n * The answer of `GET /api-keys/options`, when the caller already holds it\n * (a story, a test). Omitted, the dialog asks for it each time it opens.\n */\n options?: ApiKeyOptionsResponse;\n}\n\n/**\n * Mint an API key: a name, an optional description, and how long it lives.\n *\n * The expiry durations and the one to preselect come from\n * `GET /api-keys/options`, never from a list in this file: the policy is\n * server-only configuration, and a capped deployment must not be offered a\n * duration it then refuses.\n *\n * One component for both surfaces that mint keys, the account panel and the\n * admin table, which differ only in {@link ApiKeyCreateDialogProps.ownershipNote}.\n */\nexport const ApiKeyCreateDialog = (props: ApiKeyCreateDialogProps) => {\n const api = useClient<ApiKeyController>();\n const toaster = useToast();\n const { tr } = useI18n();\n const [fetched, setFetched] = useState<ApiKeyOptionsResponse | undefined>();\n const options = props.options ?? fetched;\n\n useEffect(() => {\n if (!props.open || props.options) {\n return;\n }\n let cancelled = false;\n (api.getApiKeyOptions() as Promise<ApiKeyOptionsResponse>)\n .then((response) => {\n if (!cancelled) {\n setFetched(response);\n }\n })\n .catch((error: any) => {\n toaster.show(\n error?.message ??\n tr(\"account.keys.optionsError\", {\n default: \"Could not load the key options\",\n }),\n \"danger\",\n );\n });\n return () => {\n cancelled = true;\n };\n }, [props.open]);\n\n // Stable on purpose: `useForm` anchors its schema at mount. The presets\n // vary with the server's answer, so they reach the select as `items`, and\n // the refusal of anything else stays the server's.\n const schema = useMemo(\n () =>\n z.object({\n name: z.text({ maxLength: 100 }),\n description: z.text({ maxLength: 500 }).optional(),\n expiresIn: z.text().optional(),\n access: z.enum([\"full\", \"select\"]),\n permissions: z.array(z.text()).optional(),\n }),\n [],\n );\n\n const form = useForm(\n {\n schema,\n initialValues: {\n name: \"\",\n description: \"\",\n expiresIn: options?.expiry.default,\n // Full access needs no interaction: it is what every key was before\n // scopes existed, and the common case must not ask for a matrix.\n access: \"full\" as const,\n permissions: [],\n },\n handler: async (values) => {\n const name = values.name?.trim() ?? \"\";\n if (!name) {\n throw new FormValidationError({\n message: tr(\"account.keys.nameRequired\", {\n default: \"Give the key a name\",\n }),\n path: \"/name\",\n });\n }\n\n const holder = props.existingKeys?.find(\n (key) => key.name === name && key.status !== \"revoked\",\n );\n if (holder) {\n throw new FormValidationError({\n message:\n holder.status === \"expired\"\n ? tr(\"account.keys.nameHeldByExpired\", {\n default:\n \"An expired key is already called $1. Rotate it to renew it, or choose another name.\",\n args: [name],\n })\n : tr(\"account.keys.nameTaken\", {\n default: \"A key is already called $1.\",\n args: [name],\n }),\n path: \"/name\",\n });\n }\n\n // An empty scope means full access, so \"Select permissions\" with\n // nothing selected would quietly mint the widest key there is.\n const permissions =\n values.access === \"select\" ? (values.permissions ?? []) : [];\n if (values.access === \"select\" && permissions.length === 0) {\n throw new FormValidationError({\n message: tr(\"account.keys.scopeRequired\", {\n default:\n \"Select at least one permission, or give the key full access.\",\n }),\n path: \"/permissions\",\n });\n }\n\n try {\n const created: any = await api.createApiKey({\n body: {\n name,\n description: values.description?.trim() || undefined,\n expiresIn: values.expiresIn as never,\n permissions,\n },\n });\n await props.onCreated(created.token);\n props.onOpenChange(false);\n } catch (error: any) {\n toaster.show(\n error?.message ??\n tr(\"account.keys.createError\", {\n default: \"Could not create that key\",\n }),\n \"danger\",\n );\n }\n },\n },\n // Not keyed on the options: rebuilt when they arrive, the form dropped\n // whatever had been typed while `GET /api-keys/options` was in flight,\n // and a name typed quickly was gone by the time Create was clicked.\n [props.open],\n );\n const state = useFormState(form, [\"loading\"]);\n\n // The server's default reaches the select as a new baseline, keeping every\n // field the user has already touched.\n useEffect(() => {\n if (!props.open || !options) {\n return;\n }\n form.setInitialValues(\n {\n name: \"\",\n description: \"\",\n expiresIn: options.expiry.default,\n access: \"full\",\n permissions: [],\n },\n { keepDirty: true },\n );\n }, [props.open, options?.expiry.default]);\n const [access] = useFieldValue(form.input.access);\n\n const expiryLabel = (preset: string): string => {\n switch (preset) {\n case \"7d\":\n return tr(\"account.keys.expiry.7d\", { default: \"7 days\" });\n case \"30d\":\n return tr(\"account.keys.expiry.30d\", { default: \"30 days\" });\n case \"60d\":\n return tr(\"account.keys.expiry.60d\", { default: \"60 days\" });\n case \"90d\":\n return tr(\"account.keys.expiry.90d\", { default: \"90 days\" });\n case \"180d\":\n return tr(\"account.keys.expiry.180d\", { default: \"180 days\" });\n case \"1y\":\n return tr(\"account.keys.expiry.1y\", { default: \"1 year\" });\n case \"never\":\n return tr(\"account.keys.expiry.never\", { default: \"No expiration\" });\n default:\n return preset;\n }\n };\n\n return (\n <Dialog open={props.open} onOpenChange={props.onOpenChange}>\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {tr(\"account.keys.newTitle\", { default: \"New API key\" })}\n </DialogTitle>\n {props.ownershipNote ? (\n <DialogDescription>{props.ownershipNote}</DialogDescription>\n ) : null}\n </DialogHeader>\n <form {...form.props} className=\"flex flex-col gap-4\">\n <Control\n input={form.input.name}\n label={tr(\"account.keys.name\", { default: \"Name\" })}\n placeholder={tr(\"account.keys.namePlaceholder\", {\n default: \"CI pipeline\",\n })}\n />\n <Control\n input={form.input.description}\n label={tr(\"account.keys.descriptionLabel\", {\n default: \"Description\",\n })}\n placeholder={tr(\"account.keys.descriptionPlaceholder\", {\n default: \"What uses it, and where it is stored\",\n })}\n />\n <Control\n input={form.input.expiresIn}\n select\n label={tr(\"account.keys.expiresIn\", { default: \"Expires after\" })}\n description={\n options && options.expiry.maxDays > 0\n ? tr(\"account.keys.expiryCap\", {\n default: \"Keys on this server live at most $1 days.\",\n args: [String(options.expiry.maxDays)],\n })\n : undefined\n }\n items={(options?.expiry.presets ?? []).map((preset) => ({\n value: preset,\n label: expiryLabel(preset),\n }))}\n disabled={!options}\n />\n <Control\n input={form.input.access}\n segmented\n label={tr(\"account.keys.access\", { default: \"Access\" })}\n description={\n access === \"select\"\n ? tr(\"account.keys.accessSelectHint\", {\n default:\n \"The key may use only the permissions ticked below, and never more than its roles allow.\",\n })\n : tr(\"account.keys.accessFullHint\", {\n default: \"The key may do everything your roles allow.\",\n })\n }\n items={[\n {\n value: \"full\",\n label: tr(\"account.keys.accessFull\", {\n default: \"Full access\",\n }),\n },\n {\n value: \"select\",\n label: tr(\"account.keys.accessSelect\", {\n default: \"Select permissions\",\n }),\n },\n ]}\n />\n {access === \"select\" && options ? (\n <ApiKeyScopeMatrix\n input={form.input.permissions}\n groups={options.permissions.groups}\n />\n ) : null}\n {/* `DialogFooter`, not a hand-rolled row: the border-top, the\n tinted band and the rounded bottom live there, and they are\n what every imperative dialog (`useDialog`'s confirm and\n prompt) already looks like (feedback #P2143). */}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"minimal\"\n onClick={() => props.onOpenChange(false)}\n >\n {tr(\"account.keys.cancel\", { default: \"Cancel\" })}\n </Button>\n <Button type=\"submit\" disabled={!options || state.loading}>\n {tr(\"account.keys.submit\", { default: \"Create\" })}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyEA,MAAa,sBAAsB,UAAmC;CACpE,MAAM,MAAM,UAA4B;CACxC,MAAM,UAAU,SAAS;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,CAAC,SAAS,cAAc,SAA4C;CAC1E,MAAM,UAAU,MAAM,WAAW;CAEjC,gBAAgB;EACd,IAAI,CAAC,MAAM,QAAQ,MAAM,SACvB;EAEF,IAAI,YAAY;EAChB,IAAK,iBAAiB,CAAC,CACpB,MAAM,aAAa;GAClB,IAAI,CAAC,WACH,WAAW,QAAQ;EAEvB,CAAC,CAAC,CACD,OAAO,UAAe;GACrB,QAAQ,KACN,OAAO,WACL,GAAG,6BAA6B,EAC9B,SAAS,iCACX,CAAC,GACH,QACF;EACF,CAAC;EACH,aAAa;GACX,YAAY;EACd;CACF,GAAG,CAAC,MAAM,IAAI,CAAC;CAKf,MAAM,SAAS,cAEX,EAAE,OAAO;EACP,MAAM,EAAE,KAAK,EAAE,WAAW,IAAI,CAAC;EAC/B,aAAa,EAAE,KAAK,EAAE,WAAW,IAAI,CAAC,CAAC,CAAC,SAAS;EACjD,WAAW,EAAE,KAAK,CAAC,CAAC,SAAS;EAC7B,QAAQ,EAAE,KAAK,CAAC,QAAQ,QAAQ,CAAC;EACjC,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,SAAS;CAC1C,CAAC,GACH,CAAC,CACH;CAEA,MAAM,OAAO,QACX;EACE;EACA,eAAe;GACb,MAAM;GACN,aAAa;GACb,WAAW,SAAS,OAAO;GAG3B,QAAQ;GACR,aAAa,CAAC;EAChB;EACA,SAAS,OAAO,WAAW;GACzB,MAAM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A,CAAA,EAAA,CAAA;CACT,CAAA;AAEZ"}
|
|
1
|
+
{"version":3,"file":"ApiKeyCreateDialog.js","names":[],"sources":["../../src/account/ApiKeyCreateDialog.tsx"],"sourcesContent":["import { z } from \"alepha\";\nimport type {\n ApiKeyController,\n ApiKeyOptionsResponse,\n ApiKeyStatus,\n} from \"alepha/api/keys\";\nimport { useClient } from \"alepha/react\";\nimport {\n FormValidationError,\n useFieldValue,\n useForm,\n useFormState,\n} from \"alepha/react/form\";\nimport { useI18n } from \"alepha/react/i18n\";\nimport { useEffect, useMemo, useState } from \"react\";\n\nimport { Button } from \"../core/Button.tsx\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"../core/Dialog.tsx\";\nimport { useToast } from \"../core/useToast.tsx\";\nimport { Control } from \"../form/Control.tsx\";\nimport { ApiKeyScopeMatrix } from \"./ApiKeyScopeMatrix.tsx\";\n\nexport interface ApiKeyCreateDialogProps {\n open: boolean;\n\n onOpenChange: (open: boolean) => void;\n\n /**\n * Called with the new key's plain token, the only time it exists in a\n * readable form. The caller shows it.\n */\n onCreated: (token: string) => void | Promise<void>;\n\n /**\n * The keys the owner already holds. A live or an expired key keeps its name\n * (revoking frees it), so a clashing name is explained before the request,\n * and an expired holder is pointed at its Rotate action rather than\n * refused with the database's words.\n */\n existingKeys?: Array<{ name: string; status: ApiKeyStatus }>;\n\n /**\n * One sentence on whose key this is, shown above the fields. The admin\n * surface says the key is minted for the admin's own account; the account\n * panel needs no such sentence.\n */\n ownershipNote?: string;\n\n /**\n * The answer of `GET /api-keys/options`, when the caller already holds it\n * (a story, a test). Omitted, the dialog asks for it each time it opens.\n */\n options?: ApiKeyOptionsResponse;\n}\n\n/**\n * Mint an API key: a name, an optional description, and how long it lives.\n *\n * The expiry durations and the one to preselect come from\n * `GET /api-keys/options`, never from a list in this file: the policy is\n * server-only configuration, and a capped deployment must not be offered a\n * duration it then refuses.\n *\n * One component for both surfaces that mint keys, the account panel and the\n * admin table, which differ only in {@link ApiKeyCreateDialogProps.ownershipNote}.\n */\nexport const ApiKeyCreateDialog = (props: ApiKeyCreateDialogProps) => {\n const api = useClient<ApiKeyController>();\n const toaster = useToast();\n const { tr } = useI18n();\n const [fetched, setFetched] = useState<ApiKeyOptionsResponse | undefined>();\n const options = props.options ?? fetched;\n\n useEffect(() => {\n if (!props.open || props.options) {\n return;\n }\n let cancelled = false;\n (api.getApiKeyOptions() as Promise<ApiKeyOptionsResponse>)\n .then((response) => {\n if (!cancelled) {\n setFetched(response);\n }\n })\n .catch((error: any) => {\n toaster.show(\n error?.message ??\n tr(\"account.keys.optionsError\", {\n default: \"Could not load the key options\",\n }),\n \"danger\",\n );\n });\n return () => {\n cancelled = true;\n };\n }, [props.open]);\n\n // Stable on purpose: `useForm` anchors its schema at mount. The presets\n // vary with the server's answer, so they reach the select as `items`, and\n // the refusal of anything else stays the server's.\n const schema = useMemo(\n () =>\n z.object({\n name: z.text({ maxLength: 100 }),\n description: z.text({ maxLength: 500 }).optional(),\n expiresIn: z.text().optional(),\n access: z.enum([\"full\", \"select\"]),\n permissions: z.array(z.text()).optional(),\n }),\n [],\n );\n\n const form = useForm(\n {\n schema,\n initialValues: {\n name: \"\",\n description: \"\",\n expiresIn: options?.expiry.default,\n // Full access needs no interaction: it is what every key was before\n // scopes existed, and the common case must not ask for a matrix.\n access: \"full\" as const,\n permissions: [],\n },\n handler: async (values) => {\n const name = values.name?.trim() ?? \"\";\n if (!name) {\n throw new FormValidationError({\n message: tr(\"account.keys.nameRequired\", {\n default: \"Give the key a name\",\n }),\n path: \"/name\",\n });\n }\n\n const holder = props.existingKeys?.find(\n (key) => key.name === name && key.status !== \"revoked\",\n );\n if (holder) {\n throw new FormValidationError({\n message:\n holder.status === \"expired\"\n ? tr(\"account.keys.nameHeldByExpired\", {\n default:\n \"An expired key is already called $1. Rotate it to renew it, or choose another name.\",\n args: [name],\n })\n : tr(\"account.keys.nameTaken\", {\n default: \"A key is already called $1.\",\n args: [name],\n }),\n path: \"/name\",\n });\n }\n\n // An empty scope means full access, so \"Select permissions\" with\n // nothing selected would quietly mint the widest key there is.\n const permissions =\n values.access === \"select\" ? (values.permissions ?? []) : [];\n if (values.access === \"select\" && permissions.length === 0) {\n throw new FormValidationError({\n message: tr(\"account.keys.scopeRequired\", {\n default:\n \"Select at least one permission, or give the key full access.\",\n }),\n path: \"/permissions\",\n });\n }\n\n // A refusal is toasted by the app's ActionErrorToaster: the form\n // emits it, so a toast here put it on screen twice.\n const created = await api.createApiKey({\n body: {\n name,\n description: values.description?.trim() || undefined,\n expiresIn: values.expiresIn as never,\n permissions,\n },\n });\n await props.onCreated(created.token);\n props.onOpenChange(false);\n },\n },\n // Not keyed on the options: rebuilt when they arrive, the form dropped\n // whatever had been typed while `GET /api-keys/options` was in flight,\n // and a name typed quickly was gone by the time Create was clicked.\n [props.open],\n );\n const state = useFormState(form, [\"loading\"]);\n\n // The server's default reaches the select as a new baseline, keeping every\n // field the user has already touched.\n useEffect(() => {\n if (!props.open || !options) {\n return;\n }\n form.setInitialValues(\n {\n name: \"\",\n description: \"\",\n expiresIn: options.expiry.default,\n access: \"full\",\n permissions: [],\n },\n { keepDirty: true },\n );\n }, [props.open, options?.expiry.default]);\n const [access] = useFieldValue(form.input.access);\n\n const expiryLabel = (preset: string): string => {\n switch (preset) {\n case \"7d\":\n return tr(\"account.keys.expiry.7d\", { default: \"7 days\" });\n case \"30d\":\n return tr(\"account.keys.expiry.30d\", { default: \"30 days\" });\n case \"60d\":\n return tr(\"account.keys.expiry.60d\", { default: \"60 days\" });\n case \"90d\":\n return tr(\"account.keys.expiry.90d\", { default: \"90 days\" });\n case \"180d\":\n return tr(\"account.keys.expiry.180d\", { default: \"180 days\" });\n case \"1y\":\n return tr(\"account.keys.expiry.1y\", { default: \"1 year\" });\n case \"never\":\n return tr(\"account.keys.expiry.never\", { default: \"No expiration\" });\n default:\n return preset;\n }\n };\n\n return (\n <Dialog open={props.open} onOpenChange={props.onOpenChange}>\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {tr(\"account.keys.newTitle\", { default: \"New API key\" })}\n </DialogTitle>\n {props.ownershipNote ? (\n <DialogDescription>{props.ownershipNote}</DialogDescription>\n ) : null}\n </DialogHeader>\n <form {...form.props} className=\"flex flex-col gap-4\">\n <Control\n input={form.input.name}\n label={tr(\"account.keys.name\", { default: \"Name\" })}\n placeholder={tr(\"account.keys.namePlaceholder\", {\n default: \"CI pipeline\",\n })}\n />\n <Control\n input={form.input.description}\n label={tr(\"account.keys.descriptionLabel\", {\n default: \"Description\",\n })}\n placeholder={tr(\"account.keys.descriptionPlaceholder\", {\n default: \"What uses it, and where it is stored\",\n })}\n />\n <Control\n input={form.input.expiresIn}\n select\n label={tr(\"account.keys.expiresIn\", { default: \"Expires after\" })}\n description={\n options && options.expiry.maxDays > 0\n ? tr(\"account.keys.expiryCap\", {\n default: \"Keys on this server live at most $1 days.\",\n args: [String(options.expiry.maxDays)],\n })\n : undefined\n }\n items={(options?.expiry.presets ?? []).map((preset) => ({\n value: preset,\n label: expiryLabel(preset),\n }))}\n disabled={!options}\n />\n <Control\n input={form.input.access}\n segmented\n label={tr(\"account.keys.access\", { default: \"Access\" })}\n description={\n access === \"select\"\n ? tr(\"account.keys.accessSelectHint\", {\n default:\n \"The key may use only the permissions ticked below, and never more than its roles allow.\",\n })\n : tr(\"account.keys.accessFullHint\", {\n default: \"The key may do everything your roles allow.\",\n })\n }\n items={[\n {\n value: \"full\",\n label: tr(\"account.keys.accessFull\", {\n default: \"Full access\",\n }),\n },\n {\n value: \"select\",\n label: tr(\"account.keys.accessSelect\", {\n default: \"Select permissions\",\n }),\n },\n ]}\n />\n {access === \"select\" && options ? (\n <ApiKeyScopeMatrix\n input={form.input.permissions}\n groups={options.permissions.groups}\n />\n ) : null}\n {/* `DialogFooter`, not a hand-rolled row: the border-top, the\n tinted band and the rounded bottom live there, and they are\n what every imperative dialog (`useDialog`'s confirm and\n prompt) already looks like (feedback #P2143). */}\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"minimal\"\n onClick={() => props.onOpenChange(false)}\n >\n {tr(\"account.keys.cancel\", { default: \"Cancel\" })}\n </Button>\n <Button type=\"submit\" disabled={!options || state.loading}>\n {tr(\"account.keys.submit\", { default: \"Create\" })}\n </Button>\n </DialogFooter>\n </form>\n </DialogContent>\n </Dialog>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyEA,MAAa,sBAAsB,UAAmC;CACpE,MAAM,MAAM,UAA4B;CACxC,MAAM,UAAU,SAAS;CACzB,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,CAAC,SAAS,cAAc,SAA4C;CAC1E,MAAM,UAAU,MAAM,WAAW;CAEjC,gBAAgB;EACd,IAAI,CAAC,MAAM,QAAQ,MAAM,SACvB;EAEF,IAAI,YAAY;EAChB,IAAK,iBAAiB,CAAC,CACpB,MAAM,aAAa;GAClB,IAAI,CAAC,WACH,WAAW,QAAQ;EAEvB,CAAC,CAAC,CACD,OAAO,UAAe;GACrB,QAAQ,KACN,OAAO,WACL,GAAG,6BAA6B,EAC9B,SAAS,iCACX,CAAC,GACH,QACF;EACF,CAAC;EACH,aAAa;GACX,YAAY;EACd;CACF,GAAG,CAAC,MAAM,IAAI,CAAC;CAKf,MAAM,SAAS,cAEX,EAAE,OAAO;EACP,MAAM,EAAE,KAAK,EAAE,WAAW,IAAI,CAAC;EAC/B,aAAa,EAAE,KAAK,EAAE,WAAW,IAAI,CAAC,CAAC,CAAC,SAAS;EACjD,WAAW,EAAE,KAAK,CAAC,CAAC,SAAS;EAC7B,QAAQ,EAAE,KAAK,CAAC,QAAQ,QAAQ,CAAC;EACjC,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,SAAS;CAC1C,CAAC,GACH,CAAC,CACH;CAEA,MAAM,OAAO,QACX;EACE;EACA,eAAe;GACb,MAAM;GACN,aAAa;GACb,WAAW,SAAS,OAAO;GAG3B,QA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in/AdminFiles.js
CHANGED
|
@@ -34,7 +34,7 @@ const AdminFiles = () => {
|
|
|
34
34
|
const downloadFile = useCallback((f) => {
|
|
35
35
|
window.open(`/api/files/${f.id}`, "_blank");
|
|
36
36
|
}, []);
|
|
37
|
-
const upload = useAction({ handler: async (e) => {
|
|
37
|
+
const upload = useAction({ handler: async (_ctx, e) => {
|
|
38
38
|
const file = e.target.files?.[0];
|
|
39
39
|
if (fileInputRef.current) fileInputRef.current.value = "";
|
|
40
40
|
if (!file) return;
|