@mano8/astro-auth-m8 1.5.0 → 2.1.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/CHANGELOG.md +151 -0
- package/README.md +81 -3
- package/dist/src/runtime/api/apiKeys.d.ts +3 -1
- package/dist/src/runtime/api/apiKeys.d.ts.map +1 -1
- package/dist/src/runtime/api/apiKeys.js +9 -1
- package/dist/src/runtime/api/apiKeys.js.map +1 -1
- package/dist/src/runtime/api/index.d.ts +1 -0
- package/dist/src/runtime/api/index.d.ts.map +1 -1
- package/dist/src/runtime/api/index.js +1 -0
- package/dist/src/runtime/api/index.js.map +1 -1
- package/dist/src/runtime/api/ops.d.ts +2 -1
- package/dist/src/runtime/api/ops.d.ts.map +1 -1
- package/dist/src/runtime/api/ops.js +6 -1
- package/dist/src/runtime/api/ops.js.map +1 -1
- package/dist/src/runtime/api/security.d.ts +8 -0
- package/dist/src/runtime/api/security.d.ts.map +1 -0
- package/dist/src/runtime/api/security.js +23 -0
- package/dist/src/runtime/api/security.js.map +1 -0
- package/dist/src/runtime/api/users.d.ts +2 -2
- package/dist/src/runtime/api/users.d.ts.map +1 -1
- package/dist/src/runtime/api/users.js +2 -2
- package/dist/src/runtime/api/users.js.map +1 -1
- package/dist/src/runtime/authEvents.d.ts +25 -0
- package/dist/src/runtime/authEvents.d.ts.map +1 -0
- package/dist/src/runtime/authEvents.js +26 -0
- package/dist/src/runtime/authEvents.js.map +1 -0
- package/dist/src/runtime/authorization.d.ts +80 -0
- package/dist/src/runtime/authorization.d.ts.map +1 -0
- package/dist/src/runtime/authorization.js +109 -0
- package/dist/src/runtime/authorization.js.map +1 -0
- package/dist/src/runtime/browserAdapter.d.ts.map +1 -1
- package/dist/src/runtime/browserAdapter.js +23 -0
- package/dist/src/runtime/browserAdapter.js.map +1 -1
- package/dist/src/runtime/compatibility.d.ts +6 -6
- package/dist/src/runtime/compatibility.d.ts.map +1 -1
- package/dist/src/runtime/compatibility.js +35 -5
- package/dist/src/runtime/compatibility.js.map +1 -1
- package/dist/src/runtime/errors.d.ts +39 -0
- package/dist/src/runtime/errors.d.ts.map +1 -1
- package/dist/src/runtime/errors.js +79 -0
- package/dist/src/runtime/errors.js.map +1 -1
- package/dist/src/runtime/hooks/index.d.ts +1 -0
- package/dist/src/runtime/hooks/index.d.ts.map +1 -1
- package/dist/src/runtime/hooks/index.js +1 -0
- package/dist/src/runtime/hooks/index.js.map +1 -1
- package/dist/src/runtime/hooks/useApiKeys.d.ts +69 -0
- package/dist/src/runtime/hooks/useApiKeys.d.ts.map +1 -1
- package/dist/src/runtime/hooks/useApiKeys.js +38 -1
- package/dist/src/runtime/hooks/useApiKeys.js.map +1 -1
- package/dist/src/runtime/hooks/useSecurity.d.ts +70 -0
- package/dist/src/runtime/hooks/useSecurity.d.ts.map +1 -0
- package/dist/src/runtime/hooks/useSecurity.js +60 -0
- package/dist/src/runtime/hooks/useSecurity.js.map +1 -0
- package/dist/src/runtime/hooks/useUsers.d.ts +4 -15
- package/dist/src/runtime/hooks/useUsers.d.ts.map +1 -1
- package/dist/src/runtime/hooks/useUsers.js +18 -4
- package/dist/src/runtime/hooks/useUsers.js.map +1 -1
- package/dist/src/runtime/queryKeys.d.ts +2 -0
- package/dist/src/runtime/queryKeys.d.ts.map +1 -1
- package/dist/src/runtime/queryKeys.js +3 -1
- package/dist/src/runtime/queryKeys.js.map +1 -1
- package/dist/src/runtime/react/AuthProvider.d.ts.map +1 -1
- package/dist/src/runtime/react/AuthProvider.js +24 -0
- package/dist/src/runtime/react/AuthProvider.js.map +1 -1
- package/dist/src/runtime/react/RequireRole.d.ts +39 -2
- package/dist/src/runtime/react/RequireRole.d.ts.map +1 -1
- package/dist/src/runtime/react/RequireRole.js +19 -3
- package/dist/src/runtime/react/RequireRole.js.map +1 -1
- package/dist/src/runtime/react/index.d.ts +2 -0
- package/dist/src/runtime/react/index.d.ts.map +1 -1
- package/dist/src/runtime/react/index.js +11 -0
- package/dist/src/runtime/react/index.js.map +1 -1
- package/dist/src/runtime/schemas.d.ts +186 -1
- package/dist/src/runtime/schemas.d.ts.map +1 -1
- package/dist/src/runtime/schemas.js +74 -3
- package/dist/src/runtime/schemas.js.map +1 -1
- package/package.json +8 -5
- package/registry/r/account-crud.json +1 -1
- package/registry/r/account-dashboard.json +1 -1
- package/registry/r/admin-users-panel.json +1 -1
- package/registry/r/api-keys-panel.json +1 -1
- package/registry/r/registry.json +6 -0
- package/registry/r/security-panel.json +27 -0
- package/registry/r/sessions-panel.json +1 -1
- package/registry.json +22 -0
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"files": [
|
|
22
22
|
{
|
|
23
23
|
"path": "registry/blocks/account/admin-users-panel.tsx",
|
|
24
|
-
"content": "\"use client\";\n\n// fa-auth admin users panel: superuser-only user management (create / update /\n// delete). Headless logic stays a live dependency - `useUsers`\n// (@mano8/astro-auth-m8/hooks) owns the API calls, the package Zod schemas\n// validate the forms, and the package's `RequireRole superuser` gates the whole\n// panel. This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry - edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport type { ColumnDef, RowSelectionState } from \"@tanstack/react-table\";\nimport { UserPlus } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useUsers } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n RoleTypeSchema,\n UserCreateSchema,\n UserUpdateSchema,\n type UserPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport { DialogFooter } from \"@/components/ui/dialog\";\nimport {\n DataTable,\n createDataTableSelectionColumn,\n} from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n EntityFormDialog,\n RowActions,\n errorMessage,\n useClientTable,\n} from \"./account-crud\";\n\nexport interface AdminUsersPanelLabels {\n title: string;\n description: string;\n updateScope: string;\n invalidCreate: string;\n invalidUpdate: string;\n created: string;\n updated: string;\n createFailed: string;\n updateFailed: string;\n deleteFailed: string;\n deleted: string;\n email: string;\n fullName: string;\n avatar: string;\n avatarPlaceholder: string;\n password: string;\n passwordPlaceholder: string;\n passwordUnsupported: string;\n create: string;\n createTitle: string;\n editTitle: string;\n role: string;\n emailVerified: string;\n superuser: string;\n users: string;\n loading: string;\n provider: string;\n providerPassword: string;\n providerGoogle: string;\n actions: string;\n status: string;\n active: string;\n inactive: string;\n save: string;\n cancel: string;\n edit: string;\n delete: string;\n deleteSelected: string;\n confirmDeleteTitle: string;\n confirmDeleteBody: string;\n empty: string;\n search: string;\n}\n\nconst DEFAULT_LABELS: AdminUsersPanelLabels = {\n title: \"Admin users\",\n description: \"Superuser-only user management.\",\n updateScope:\n \"User updates support email, full name, avatar, password, and role. Provider, account status, and verification flags are managed by the auth service.\",\n invalidCreate: \"Invalid user payload.\",\n invalidUpdate: \"Invalid update payload.\",\n created: \"User created.\",\n updated: \"User updated.\",\n createFailed: \"Failed to create user.\",\n updateFailed: \"Failed to update user.\",\n deleteFailed: \"Failed to delete user.\",\n deleted: \"User deleted.\",\n email: \"Email\",\n fullName: \"Full name\",\n avatar: \"Avatar URL\",\n avatarPlaceholder: \"https://example.com/avatar.png\",\n password: \"Password\",\n passwordPlaceholder: \"Leave blank to keep current password\",\n passwordUnsupported: \"Password disabled for Google users\",\n create: \"Create user\",\n createTitle: \"Create user\",\n editTitle: \"Edit user\",\n role: \"Role\",\n emailVerified: \"Email verified\",\n superuser: \"Superuser\",\n users: \"users\",\n loading: \"Loading users...\",\n provider: \"Provider\",\n providerPassword: \"Password\",\n providerGoogle: \"Google\",\n actions: \"Actions\",\n status: \"Status\",\n active: \"Active\",\n inactive: \"Inactive\",\n save: \"Save\",\n cancel: \"Cancel\",\n edit: \"Edit\",\n delete: \"Delete\",\n deleteSelected: \"Delete selected\",\n confirmDeleteTitle: \"Delete user?\",\n confirmDeleteBody:\n \"This permanently removes the user account and revokes its access.\",\n empty: \"No users found.\",\n search: \"Search users\",\n};\n\ninterface CreateFormState {\n email: string;\n full_name: string;\n avatar: string;\n password: string;\n role: string;\n is_active: boolean;\n is_superuser: boolean;\n}\n\ninterface EditFormState {\n email: string;\n full_name: string;\n avatar: string;\n password: string;\n role: string;\n}\n\nconst EMPTY_CREATE: CreateFormState = {\n email: \"\",\n full_name: \"\",\n avatar: \"\",\n password: \"\",\n role: \"user\",\n is_active: true,\n is_superuser: false,\n};\n\nconst selectClassName =\n \"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\";\n\nfunction RoleSelect({\n id,\n value,\n onChange,\n}: {\n id: string;\n value: string;\n onChange: (value: string) => void;\n}) {\n return (\n <select\n id={id}\n aria-label=\"Role\"\n className={selectClassName}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n >\n {RoleTypeSchema.options.map((role) => (\n <option key={role} value={role}>\n {role}\n </option>\n ))}\n </select>\n );\n}\n\nfunction AdminUsersPanelInner({ t }: { t: AdminUsersPanelLabels }) {\n const { users: usersData, loading, reload, create, update, remove } =\n useUsers(false);\n const users = usersData?.data ?? [];\n\n const [creating, setCreating] = React.useState(false);\n const [createForm, setCreateForm] =\n React.useState<CreateFormState>(EMPTY_CREATE);\n const [editing, setEditing] = React.useState<UserPublic | null>(null);\n const [editForm, setEditForm] = React.useState<EditFormState | null>(null);\n const [deleting, setDeleting] = React.useState<UserPublic | null>(null);\n const [bulkDelete, setBulkDelete] = React.useState(false);\n const [submitting, setSubmitting] = React.useState(false);\n const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const openCreate = () => {\n setCreateForm(EMPTY_CREATE);\n setCreating(true);\n };\n\n const openEdit = (user: UserPublic) => {\n setEditForm({\n email: user.email,\n full_name: user.full_name ?? \"\",\n avatar: user.avatar ?? \"\",\n password: \"\",\n role: user.role,\n });\n setEditing(user);\n };\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const parsed = UserCreateSchema.safeParse({\n email: createForm.email || undefined,\n password: createForm.password || undefined,\n full_name: createForm.full_name || undefined,\n avatar: createForm.avatar || undefined,\n provider: \"password\",\n role: createForm.role ? RoleTypeSchema.parse(createForm.role) : \"user\",\n is_active: createForm.is_active,\n is_superuser: createForm.is_superuser,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.invalidCreate,\n });\n return;\n }\n setSubmitting(true);\n try {\n await create(parsed.data);\n // The hook query is disabled (useUsers(false)), so invalidation alone\n // won't repopulate the table — refetch explicitly.\n await reload();\n setCreating(false);\n accountToast.success({ title: t.created });\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.createFailed) });\n } finally {\n setSubmitting(false);\n }\n };\n\n const handleUpdate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!editing || !editForm) return;\n const parsed = UserUpdateSchema.safeParse({\n email: editForm.email || undefined,\n full_name: editForm.full_name || undefined,\n avatar: editForm.avatar || undefined,\n password: editForm.password || undefined,\n role: editForm.role || undefined,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.invalidUpdate,\n });\n return;\n }\n setSubmitting(true);\n try {\n await update(editing.id, parsed.data);\n await reload();\n setEditing(null);\n setEditForm(null);\n accountToast.success({ title: t.updated });\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.updateFailed) });\n } finally {\n setSubmitting(false);\n }\n };\n\n const confirmDelete = async (ids: string[]) => {\n setSubmitting(true);\n try {\n for (const id of ids) {\n await remove(id);\n }\n await reload();\n accountToast.success({ title: t.deleted });\n setDeleting(null);\n setBulkDelete(false);\n setRowSelection({});\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.deleteFailed) });\n } finally {\n setSubmitting(false);\n }\n };\n\n const controller = useClientTable(users, {\n search: (user) => `${user.email} ${user.full_name ?? \"\"}`,\n sorters: {\n email: (user) => user.email,\n role: (user) => user.role,\n provider: (user) => user.provider,\n status: (user) => (user.is_active ? t.active : t.inactive),\n },\n initialSortBy: \"email\",\n });\n\n const columns = React.useMemo<ColumnDef<UserPublic>[]>(\n () => [\n createDataTableSelectionColumn<UserPublic>({\n selectAllVisible: t.actions,\n selectRow: (user) => `${t.edit} ${user.email}`,\n }),\n {\n id: \"actions\",\n header: t.actions,\n enableHiding: false,\n enableSorting: false,\n cell: ({ row }) => (\n <RowActions\n editLabel={t.edit}\n deleteLabel={t.delete}\n onEdit={() => openEdit(row.original)}\n onDelete={() => setDeleting(row.original)}\n />\n ),\n },\n {\n accessorKey: \"email\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.email} />\n ),\n cell: ({ row }) => (\n <div className=\"min-w-0\">\n <div className=\"font-medium\">{row.original.email}</div>\n {row.original.full_name ? (\n <div className=\"text-xs text-muted-foreground\">\n {row.original.full_name}\n </div>\n ) : null}\n </div>\n ),\n },\n {\n accessorKey: \"role\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.role} />\n ),\n cell: ({ row }) => (\n <span className=\"capitalize\">{row.original.role}</span>\n ),\n },\n {\n accessorKey: \"provider\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.provider} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\" className=\"capitalize\">\n {row.original.provider === \"google\"\n ? t.providerGoogle\n : t.providerPassword}\n </Badge>\n ),\n },\n {\n accessorKey: \"status\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.status} />\n ),\n cell: ({ row }) => {\n const user = row.original;\n return (\n <div className=\"flex flex-wrap gap-1\">\n <Badge variant={user.is_active ? \"default\" : \"outline\"}>\n {user.is_active ? t.active : t.inactive}\n </Badge>\n {user.email_verified ? (\n <Badge variant=\"secondary\">{t.emailVerified}</Badge>\n ) : null}\n {user.is_superuser ? (\n <Badge variant=\"secondary\">{t.superuser}</Badge>\n ) : null}\n </div>\n );\n },\n },\n ],\n [t],\n );\n\n const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);\n const editingGoogle = editing?.provider === \"google\";\n\n return (\n <Card className=\"not-content w-full\">\n <AccountToastHost />\n <CardHeader>\n <CardTitle>{t.title}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.updateScope}</p>\n <DataTable<UserPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && users.length === 0}\n getRowId={(user) => user.id}\n rowSelection={rowSelection}\n onRowSelectionChange={setRowSelection}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={\n <Button type=\"button\" size=\"sm\" onClick={openCreate}>\n <UserPlus className=\"size-4\" />\n {t.create}\n </Button>\n }\n selectionActions={\n selectedIds.length > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => setBulkDelete(true)}\n >\n {t.deleteSelected} ({selectedIds.length})\n </Button>\n ) : null\n }\n />\n </CardContent>\n\n {/* Create popup */}\n <EntityFormDialog\n open={creating}\n onOpenChange={setCreating}\n title={t.createTitle}\n description={t.updateScope}\n >\n <form onSubmit={handleCreate} className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-email\">{t.email}</Label>\n <Input\n id=\"admin-create-email\"\n type=\"email\"\n required\n value={createForm.email}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n email: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-name\">{t.fullName}</Label>\n <Input\n id=\"admin-create-name\"\n value={createForm.full_name}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n full_name: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-avatar\">{t.avatar}</Label>\n <Input\n id=\"admin-create-avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n value={createForm.avatar}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n avatar: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-password\">{t.password}</Label>\n <Input\n id=\"admin-create-password\"\n type=\"password\"\n minLength={8}\n required\n value={createForm.password}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n password: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-role\">{t.role}</Label>\n <RoleSelect\n id=\"admin-create-role\"\n value={createForm.role}\n onChange={(role) => setCreateForm((prev) => ({ ...prev, role }))}\n />\n </div>\n <div className=\"flex items-end gap-4\">\n <label className=\"flex items-center gap-2 text-sm\">\n <input\n type=\"checkbox\"\n className=\"size-4\"\n checked={createForm.is_active}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n is_active: event.target.checked,\n }))\n }\n />\n {t.active}\n </label>\n <label className=\"flex items-center gap-2 text-sm\">\n <input\n type=\"checkbox\"\n className=\"size-4\"\n checked={createForm.is_superuser}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n is_superuser: event.target.checked,\n }))\n }\n />\n {t.superuser}\n </label>\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setCreating(false)}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={submitting}>\n {t.save}\n </Button>\n </DialogFooter>\n </form>\n </EntityFormDialog>\n\n {/* Edit popup */}\n <EntityFormDialog\n open={Boolean(editing) && Boolean(editForm)}\n onOpenChange={(open) => {\n if (!open) {\n setEditing(null);\n setEditForm(null);\n }\n }}\n title={t.editTitle}\n description={editing?.email}\n >\n {editForm ? (\n <form onSubmit={handleUpdate} className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-email\">{t.email}</Label>\n <Input\n id=\"admin-edit-email\"\n type=\"email\"\n required\n value={editForm.email}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, email: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-name\">{t.fullName}</Label>\n <Input\n id=\"admin-edit-name\"\n value={editForm.full_name}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, full_name: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-avatar\">{t.avatar}</Label>\n <Input\n id=\"admin-edit-avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n value={editForm.avatar}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, avatar: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-password\">{t.password}</Label>\n <Input\n id=\"admin-edit-password\"\n type=\"password\"\n disabled={editingGoogle}\n placeholder={\n editingGoogle\n ? t.passwordUnsupported\n : t.passwordPlaceholder\n }\n value={editForm.password}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, password: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-role\">{t.role}</Label>\n <RoleSelect\n id=\"admin-edit-role\"\n value={editForm.role}\n onChange={(role) =>\n setEditForm((prev) => (prev ? { ...prev, role } : prev))\n }\n />\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setEditing(null);\n setEditForm(null);\n }}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={submitting}>\n {t.save}\n </Button>\n </DialogFooter>\n </form>\n ) : null}\n </EntityFormDialog>\n\n {/* Delete confirmations */}\n <ConfirmDeleteDialog\n open={Boolean(deleting)}\n onOpenChange={(open) => {\n if (!open) setDeleting(null);\n }}\n title={t.confirmDeleteTitle}\n description={t.confirmDeleteBody}\n confirmLabel={t.delete}\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={() => deleting && confirmDelete([deleting.id])}\n />\n <ConfirmDeleteDialog\n open={bulkDelete}\n onOpenChange={setBulkDelete}\n title={t.confirmDeleteTitle}\n description={t.confirmDeleteBody}\n confirmLabel={t.deleteSelected}\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={() => confirmDelete(selectedIds)}\n />\n </Card>\n );\n}\n\nexport function AdminUsersPanel({\n labels,\n}: {\n labels?: Partial<AdminUsersPanelLabels>;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n // Superuser-only: gate the whole panel via the package's RequireRole so the\n // privileged API calls never mount for non-superusers, even if a consumer\n // renders it unconditionally.\n return (\n <RequireRole superuser>\n <AdminUsersPanelInner t={t} />\n </RequireRole>\n );\n}\n",
|
|
24
|
+
"content": "\"use client\";\n\n// fa-auth admin users panel: superuser-only user management (create / update /\n// delete). Headless logic stays a live dependency - `useUsers`\n// (@mano8/astro-auth-m8/hooks) owns the API calls, the package Zod schemas\n// validate the forms, and the package's `RequireRole superuser` gates the whole\n// panel. This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry - edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport type { ColumnDef, RowSelectionState } from \"@tanstack/react-table\";\nimport { UserPlus } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useUsers } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n RoleTypeSchema,\n UserCreateSchema,\n UserUpdateSchema,\n type UserPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport { DialogFooter } from \"@/components/ui/dialog\";\nimport {\n DataTable,\n createDataTableSelectionColumn,\n} from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n EntityFormDialog,\n RowActions,\n errorMessage,\n useClientTable,\n} from \"./account-crud\";\n\nexport interface AdminUsersPanelLabels {\n title: string;\n description: string;\n updateScope: string;\n invalidCreate: string;\n invalidUpdate: string;\n created: string;\n updated: string;\n createFailed: string;\n updateFailed: string;\n deleteFailed: string;\n deleted: string;\n email: string;\n fullName: string;\n avatar: string;\n avatarPlaceholder: string;\n password: string;\n passwordPlaceholder: string;\n passwordUnsupported: string;\n create: string;\n createTitle: string;\n editTitle: string;\n role: string;\n emailVerified: string;\n superuser: string;\n users: string;\n loading: string;\n provider: string;\n providerPassword: string;\n providerGoogle: string;\n actions: string;\n status: string;\n active: string;\n inactive: string;\n save: string;\n cancel: string;\n edit: string;\n delete: string;\n deleteSelected: string;\n confirmDeleteTitle: string;\n confirmDeleteBody: string;\n empty: string;\n search: string;\n activate: string;\n deactivate: string;\n activated: string;\n deactivated: string;\n activationFailed: string;\n confirmActivateTitle: string;\n confirmDeactivateTitle: string;\n confirmActivateBody: string;\n confirmDeactivateBody: string;\n}\n\nconst DEFAULT_LABELS: AdminUsersPanelLabels = {\n title: \"Admin users\",\n description: \"Superuser-only user management.\",\n updateScope:\n \"User updates support email, full name, avatar, password, and role. Provider, account status, and verification flags are managed by the auth service.\",\n invalidCreate: \"Invalid user payload.\",\n invalidUpdate: \"Invalid update payload.\",\n created: \"User created.\",\n updated: \"User updated.\",\n createFailed: \"Failed to create user.\",\n updateFailed: \"Failed to update user.\",\n deleteFailed: \"Failed to delete user.\",\n deleted: \"User deleted.\",\n email: \"Email\",\n fullName: \"Full name\",\n avatar: \"Avatar URL\",\n avatarPlaceholder: \"https://example.com/avatar.png\",\n password: \"Password\",\n passwordPlaceholder: \"Leave blank to keep current password\",\n passwordUnsupported: \"Password disabled for Google users\",\n create: \"Create user\",\n createTitle: \"Create user\",\n editTitle: \"Edit user\",\n role: \"Role\",\n emailVerified: \"Email verified\",\n superuser: \"Superuser\",\n users: \"users\",\n loading: \"Loading users...\",\n provider: \"Provider\",\n providerPassword: \"Password\",\n providerGoogle: \"Google\",\n actions: \"Actions\",\n status: \"Status\",\n active: \"Active\",\n inactive: \"Inactive\",\n save: \"Save\",\n cancel: \"Cancel\",\n edit: \"Edit\",\n delete: \"Delete\",\n deleteSelected: \"Delete selected\",\n confirmDeleteTitle: \"Delete user?\",\n confirmDeleteBody:\n \"This permanently removes the user account and revokes its access.\",\n empty: \"No users found.\",\n search: \"Search users\",\n activate: \"Activate account\",\n deactivate: \"Deactivate account\",\n activated: \"Account activated.\",\n deactivated: \"Account deactivated.\",\n activationFailed: \"Failed to change account status.\",\n confirmActivateTitle: \"Activate this account?\",\n confirmDeactivateTitle: \"Deactivate this account?\",\n confirmActivateBody:\n \"This bumps the account's authorization generation and revokes its active sessions, so any browser signed in as this user must sign in again.\",\n confirmDeactivateBody:\n \"This bumps the account's authorization generation, revokes its active sessions, and revokes its API keys. Reactivating the account afterward does not restore the revoked keys — new keys must be issued.\",\n};\n\ninterface CreateFormState {\n email: string;\n full_name: string;\n avatar: string;\n password: string;\n role: string;\n is_active: boolean;\n}\n\ninterface EditFormState {\n email: string;\n full_name: string;\n avatar: string;\n password: string;\n role: string;\n}\n\nconst EMPTY_CREATE: CreateFormState = {\n email: \"\",\n full_name: \"\",\n avatar: \"\",\n password: \"\",\n role: \"user\",\n is_active: true,\n};\n\nconst selectClassName =\n \"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\";\n\nfunction RoleSelect({\n id,\n value,\n onChange,\n}: {\n id: string;\n value: string;\n onChange: (value: string) => void;\n}) {\n return (\n <select\n id={id}\n aria-label=\"Role\"\n className={selectClassName}\n value={value}\n onChange={(event) => onChange(event.target.value)}\n >\n {RoleTypeSchema.options.map((role) => (\n <option key={role} value={role}>\n {role}\n </option>\n ))}\n </select>\n );\n}\n\nfunction AdminUsersPanelInner({ t }: { t: AdminUsersPanelLabels }) {\n const { users: usersData, loading, reload, create, update, remove } =\n useUsers(false);\n const users = usersData?.data ?? [];\n\n const [creating, setCreating] = React.useState(false);\n const [createForm, setCreateForm] =\n React.useState<CreateFormState>(EMPTY_CREATE);\n const [editing, setEditing] = React.useState<UserPublic | null>(null);\n const [editForm, setEditForm] = React.useState<EditFormState | null>(null);\n const [deleting, setDeleting] = React.useState<UserPublic | null>(null);\n const [bulkDelete, setBulkDelete] = React.useState(false);\n const [activationTarget, setActivationTarget] =\n React.useState<UserPublic | null>(null);\n const [submitting, setSubmitting] = React.useState(false);\n const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const openCreate = () => {\n setCreateForm(EMPTY_CREATE);\n setCreating(true);\n };\n\n const openEdit = (user: UserPublic) => {\n setEditForm({\n email: user.email,\n full_name: user.full_name ?? \"\",\n avatar: user.avatar ?? \"\",\n password: \"\",\n role: user.role,\n });\n setEditing(user);\n };\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const parsed = UserCreateSchema.safeParse({\n email: createForm.email || undefined,\n password: createForm.password || undefined,\n full_name: createForm.full_name || undefined,\n avatar: createForm.avatar || undefined,\n provider: \"password\",\n role: createForm.role ? RoleTypeSchema.parse(createForm.role) : \"user\",\n is_active: createForm.is_active,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.invalidCreate,\n });\n return;\n }\n setSubmitting(true);\n try {\n await create(parsed.data);\n // The hook query is disabled (useUsers(false)), so invalidation alone\n // won't repopulate the table — refetch explicitly.\n await reload();\n setCreating(false);\n accountToast.success({ title: t.created });\n } catch (error) {\n accountToast.error(errorMessage(error, t.createFailed));\n } finally {\n setSubmitting(false);\n }\n };\n\n const handleUpdate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n if (!editing || !editForm) return;\n const parsed = UserUpdateSchema.safeParse({\n email: editForm.email || undefined,\n full_name: editForm.full_name || undefined,\n avatar: editForm.avatar || undefined,\n password: editForm.password || undefined,\n role: editForm.role || undefined,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.invalidUpdate,\n });\n return;\n }\n setSubmitting(true);\n try {\n await update(editing.id, parsed.data);\n await reload();\n setEditing(null);\n setEditForm(null);\n accountToast.success({ title: t.updated });\n } catch (error) {\n accountToast.error(errorMessage(error, t.updateFailed));\n } finally {\n setSubmitting(false);\n }\n };\n\n const confirmActivation = async () => {\n if (!activationTarget) return;\n setSubmitting(true);\n try {\n await update(activationTarget.id, { is_active: !activationTarget.is_active });\n await reload();\n accountToast.success({\n title: activationTarget.is_active ? t.deactivated : t.activated,\n });\n setActivationTarget(null);\n setEditing(null);\n setEditForm(null);\n } catch (error) {\n accountToast.error(errorMessage(error, t.activationFailed));\n } finally {\n setSubmitting(false);\n }\n };\n\n const confirmDelete = async (ids: string[]) => {\n setSubmitting(true);\n try {\n for (const id of ids) {\n await remove(id);\n }\n await reload();\n accountToast.success({ title: t.deleted });\n setDeleting(null);\n setBulkDelete(false);\n setRowSelection({});\n } catch (error) {\n accountToast.error(errorMessage(error, t.deleteFailed));\n } finally {\n setSubmitting(false);\n }\n };\n\n const controller = useClientTable(users, {\n search: (user) => `${user.email} ${user.full_name ?? \"\"}`,\n sorters: {\n email: (user) => user.email,\n role: (user) => user.role,\n provider: (user) => user.provider,\n status: (user) => (user.is_active ? t.active : t.inactive),\n },\n initialSortBy: \"email\",\n });\n\n const columns = React.useMemo<ColumnDef<UserPublic>[]>(\n () => [\n createDataTableSelectionColumn<UserPublic>({\n selectAllVisible: t.actions,\n selectRow: (user) => `${t.edit} ${user.email}`,\n }),\n {\n id: \"actions\",\n header: t.actions,\n enableHiding: false,\n enableSorting: false,\n cell: ({ row }) => (\n <RowActions\n editLabel={t.edit}\n deleteLabel={t.delete}\n onEdit={() => openEdit(row.original)}\n onDelete={() => setDeleting(row.original)}\n />\n ),\n },\n {\n accessorKey: \"email\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.email} />\n ),\n cell: ({ row }) => (\n <div className=\"min-w-0\">\n <div className=\"font-medium\">{row.original.email}</div>\n {row.original.full_name ? (\n <div className=\"text-xs text-muted-foreground\">\n {row.original.full_name}\n </div>\n ) : null}\n </div>\n ),\n },\n {\n accessorKey: \"role\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.role} />\n ),\n cell: ({ row }) => (\n <span className=\"capitalize\">{row.original.role}</span>\n ),\n },\n {\n accessorKey: \"provider\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.provider} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\" className=\"capitalize\">\n {row.original.provider === \"google\"\n ? t.providerGoogle\n : t.providerPassword}\n </Badge>\n ),\n },\n {\n accessorKey: \"status\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.status} />\n ),\n cell: ({ row }) => {\n const user = row.original;\n return (\n <div className=\"flex flex-wrap gap-1\">\n <Badge variant={user.is_active ? \"default\" : \"outline\"}>\n {user.is_active ? t.active : t.inactive}\n </Badge>\n {user.email_verified ? (\n <Badge variant=\"secondary\">{t.emailVerified}</Badge>\n ) : null}\n {user.is_superuser ? (\n <Badge variant=\"secondary\">{t.superuser}</Badge>\n ) : null}\n </div>\n );\n },\n },\n ],\n [t],\n );\n\n const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);\n const editingGoogle = editing?.provider === \"google\";\n\n return (\n <Card className=\"not-content w-full\">\n <AccountToastHost />\n <CardHeader>\n <CardTitle>{t.title}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.updateScope}</p>\n <DataTable<UserPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && users.length === 0}\n getRowId={(user) => user.id}\n rowSelection={rowSelection}\n onRowSelectionChange={setRowSelection}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={\n <Button type=\"button\" size=\"sm\" onClick={openCreate}>\n <UserPlus className=\"size-4\" />\n {t.create}\n </Button>\n }\n selectionActions={\n selectedIds.length > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => setBulkDelete(true)}\n >\n {t.deleteSelected} ({selectedIds.length})\n </Button>\n ) : null\n }\n />\n </CardContent>\n\n {/* Create popup */}\n <EntityFormDialog\n open={creating}\n onOpenChange={setCreating}\n title={t.createTitle}\n description={t.updateScope}\n >\n <form onSubmit={handleCreate} className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-email\">{t.email}</Label>\n <Input\n id=\"admin-create-email\"\n type=\"email\"\n required\n value={createForm.email}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n email: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-name\">{t.fullName}</Label>\n <Input\n id=\"admin-create-name\"\n value={createForm.full_name}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n full_name: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-avatar\">{t.avatar}</Label>\n <Input\n id=\"admin-create-avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n value={createForm.avatar}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n avatar: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-password\">{t.password}</Label>\n <Input\n id=\"admin-create-password\"\n type=\"password\"\n minLength={8}\n required\n value={createForm.password}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n password: event.target.value,\n }))\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-create-role\">{t.role}</Label>\n <RoleSelect\n id=\"admin-create-role\"\n value={createForm.role}\n onChange={(role) => setCreateForm((prev) => ({ ...prev, role }))}\n />\n </div>\n <div className=\"flex items-end gap-4\">\n <label className=\"flex items-center gap-2 text-sm\">\n <input\n type=\"checkbox\"\n className=\"size-4\"\n checked={createForm.is_active}\n onChange={(event) =>\n setCreateForm((prev) => ({\n ...prev,\n is_active: event.target.checked,\n }))\n }\n />\n {t.active}\n </label>\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setCreating(false)}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={submitting}>\n {t.save}\n </Button>\n </DialogFooter>\n </form>\n </EntityFormDialog>\n\n {/* Edit popup */}\n <EntityFormDialog\n open={Boolean(editing) && Boolean(editForm)}\n onOpenChange={(open) => {\n if (!open) {\n setEditing(null);\n setEditForm(null);\n }\n }}\n title={t.editTitle}\n description={editing?.email}\n >\n {editForm ? (\n <form onSubmit={handleUpdate} className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-2\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-email\">{t.email}</Label>\n <Input\n id=\"admin-edit-email\"\n type=\"email\"\n required\n value={editForm.email}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, email: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-name\">{t.fullName}</Label>\n <Input\n id=\"admin-edit-name\"\n value={editForm.full_name}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, full_name: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-avatar\">{t.avatar}</Label>\n <Input\n id=\"admin-edit-avatar\"\n type=\"url\"\n placeholder={t.avatarPlaceholder}\n value={editForm.avatar}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, avatar: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-password\">{t.password}</Label>\n <Input\n id=\"admin-edit-password\"\n type=\"password\"\n disabled={editingGoogle}\n placeholder={\n editingGoogle\n ? t.passwordUnsupported\n : t.passwordPlaceholder\n }\n value={editForm.password}\n onChange={(event) =>\n setEditForm((prev) =>\n prev ? { ...prev, password: event.target.value } : prev,\n )\n }\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"admin-edit-role\">{t.role}</Label>\n <RoleSelect\n id=\"admin-edit-role\"\n value={editForm.role}\n onChange={(role) =>\n setEditForm((prev) => (prev ? { ...prev, role } : prev))\n }\n />\n </div>\n </div>\n\n {/* Account status is never a bare checkbox on this form: it is an\n authorization-state transition (generation bump, session\n revocation, and on deactivation API-key revocation), so it goes\n through its own focused confirmation panel below instead of\n being bundled into the silent field save above. */}\n <div className=\"flex items-center justify-between gap-4 rounded-md border p-3\">\n <div className=\"space-y-1\">\n <p className=\"text-sm font-medium\">{t.status}</p>\n <Badge variant={editing?.is_active ? \"default\" : \"outline\"}>\n {editing?.is_active ? t.active : t.inactive}\n </Badge>\n </div>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => editing && setActivationTarget(editing)}\n >\n {editing?.is_active ? t.deactivate : t.activate}\n </Button>\n </div>\n\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setEditing(null);\n setEditForm(null);\n }}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={submitting}>\n {t.save}\n </Button>\n </DialogFooter>\n </form>\n ) : null}\n </EntityFormDialog>\n\n {/* Delete confirmations */}\n <ConfirmDeleteDialog\n open={Boolean(deleting)}\n onOpenChange={(open) => {\n if (!open) setDeleting(null);\n }}\n title={t.confirmDeleteTitle}\n description={t.confirmDeleteBody}\n confirmLabel={t.delete}\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={() => deleting && confirmDelete([deleting.id])}\n />\n <ConfirmDeleteDialog\n open={bulkDelete}\n onOpenChange={setBulkDelete}\n title={t.confirmDeleteTitle}\n description={t.confirmDeleteBody}\n confirmLabel={t.deleteSelected}\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={() => confirmDelete(selectedIds)}\n />\n\n {/* Activation/deactivation confirmation - the sole path that can change\n is_active; see the status control above for why this is never a bare\n checkbox. */}\n <ConfirmDeleteDialog\n open={Boolean(activationTarget)}\n onOpenChange={(open) => {\n if (!open) setActivationTarget(null);\n }}\n title={\n activationTarget?.is_active\n ? t.confirmDeactivateTitle\n : t.confirmActivateTitle\n }\n description={\n activationTarget?.is_active\n ? t.confirmDeactivateBody\n : t.confirmActivateBody\n }\n confirmLabel={\n activationTarget?.is_active ? t.deactivate : t.activate\n }\n cancelLabel={t.cancel}\n pending={submitting}\n onConfirm={confirmActivation}\n />\n </Card>\n );\n}\n\nexport function AdminUsersPanel({\n labels,\n}: {\n labels?: Partial<AdminUsersPanelLabels>;\n}) {\n const t = { ...DEFAULT_LABELS, ...labels };\n // Superuser-only: gate the whole panel via the package's RequireRole so the\n // privileged API calls never mount for non-superusers, even if a consumer\n // renders it unconditionally.\n return (\n <RequireRole superuser>\n <AdminUsersPanelInner t={t} />\n </RequireRole>\n );\n}\n",
|
|
25
25
|
"type": "registry:component",
|
|
26
26
|
"target": "components/fa-auth/admin-users-panel.tsx"
|
|
27
27
|
}
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"files": [
|
|
22
22
|
{
|
|
23
23
|
"path": "registry/blocks/account/api-keys-panel.tsx",
|
|
24
|
-
"content": "\"use client\";\n\n// fa-auth API keys panel: mint and revoke programmatic API tokens. Headless\n// logic stays a live dependency — `useApiKeys` (@mano8/astro-auth-m8/hooks) owns\n// the list/create/revoke calls and the package Zod schema validates the form.\n// This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry — edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport type { ColumnDef, RowSelectionState } from \"@tanstack/react-table\";\nimport { KeyRound, Trash2 } from \"lucide-react\";\nimport { useApiKeys } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n ApiKeyCreateSchema,\n type ApiKeyPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n DataTable,\n createDataTableSelectionColumn,\n} from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n EntityFormDialog,\n errorMessage,\n useClientTable,\n} from \"./account-crud\";\n\nexport interface ApiKeysPanelLabels {\n title: string;\n description: string;\n createTitle: string;\n createDescription: string;\n name: string;\n namePlaceholder: string;\n ttl: string;\n ttlUnit: string;\n unitHours: string;\n unitDays: string;\n unitWeeks: string;\n defaultName: string;\n generating: string;\n mint: string;\n cancel: string;\n securityNotice: string;\n revealTitle: string;\n copied: string;\n copy: string;\n done: string;\n activeTitle: string;\n loading: string;\n empty: string;\n active: string;\n revoked: string;\n status: string;\n expires: string;\n lastUsed: string;\n notUsed: string;\n notAvailable: string;\n revoke: string;\n revokeSelected: string;\n confirmRevokeTitle: string;\n confirmRevokeBody: string;\n actions: string;\n search: string;\n created: string;\n createFailed: string;\n revokedOk: string;\n revokeFailed: string;\n}\n\nconst DEFAULT_LABELS: ApiKeysPanelLabels = {\n title: \"API keys\",\n description: \"Provision and revoke programmatic client identifiers.\",\n createTitle: \"Create API token\",\n createDescription:\n \"Provision programmatic client identifiers for remote integrations.\",\n name: \"Token name\",\n namePlaceholder: \"e.g. CI/CD deployment server\",\n ttl: \"Validity\",\n ttlUnit: \"Unit\",\n unitHours: \"Hours\",\n unitDays: \"Days\",\n unitWeeks: \"Weeks\",\n defaultName: \"Default key\",\n generating: \"Generating...\",\n mint: \"Mint new key\",\n cancel: \"Cancel\",\n securityNotice:\n \"Security notice: copy this API key now. It will not be shown again.\",\n revealTitle: \"API token created\",\n copied: \"Copied\",\n copy: \"Copy\",\n done: \"Done\",\n activeTitle: \"Active credentials\",\n loading: \"Loading API tokens...\",\n empty: \"No active API tokens found.\",\n active: \"Active\",\n revoked: \"Revoked\",\n status: \"Status\",\n expires: \"Expires\",\n lastUsed: \"Last used\",\n notUsed: \"Never used\",\n notAvailable: \"n/a\",\n revoke: \"Revoke\",\n revokeSelected: \"Revoke selected\",\n confirmRevokeTitle: \"Revoke API token?\",\n confirmRevokeBody:\n \"This immediately invalidates the token. Integrations using it will stop working.\",\n actions: \"Actions\",\n search: \"Search tokens\",\n created: \"API token created.\",\n createFailed: \"Failed to create API token.\",\n revokedOk: \"API token revoked.\",\n revokeFailed: \"Failed to revoke API token.\",\n};\n\n// Backend currently accepts whole-hour TTLs only; sub-hour units need an auth-API change.\nconst TTL_UNIT_HOURS = { hours: 1, days: 24, weeks: 168 } as const;\ntype TtlUnit = keyof typeof TTL_UNIT_HOURS;\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n return value ? new Date(value).toLocaleString() : fallback;\n}\n\nexport function ApiKeysPanel({ labels }: { labels?: Partial<ApiKeysPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const {\n apiKeys: keys,\n loading,\n reload,\n create,\n createdKey: lastCreated,\n revoke,\n } = useApiKeys(false);\n\n const [creating, setCreating] = React.useState(false);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const [name, setName] = React.useState(\"\");\n const [ttlAmount, setTtlAmount] = React.useState(\"30\");\n const [ttlUnit, setTtlUnit] = React.useState<TtlUnit>(\"days\");\n\n const [revealOpen, setRevealOpen] = React.useState(false);\n const [copied, setCopied] = React.useState(false);\n\n const [revoking, setRevoking] = React.useState<ApiKeyPublic | null>(null);\n const [bulkRevoke, setBulkRevoke] = React.useState(false);\n const [isRevoking, setIsRevoking] = React.useState(false);\n const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const openCreate = () => {\n setName(\"\");\n setTtlAmount(\"30\");\n setTtlUnit(\"days\");\n setCreating(true);\n };\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const ttlHours = Math.max(\n 1,\n Math.round((Number(ttlAmount) || 1) * TTL_UNIT_HOURS[ttlUnit]),\n );\n const parsed = ApiKeyCreateSchema.safeParse({\n name: name.trim() || t.defaultName,\n ttl_hours: ttlHours,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.createFailed,\n });\n return;\n }\n setIsSubmitting(true);\n try {\n await create(parsed.data);\n // The hook query is disabled (useApiKeys(false)), so invalidation alone\n // won't repopulate the table — refetch explicitly.\n await reload();\n setCreating(false);\n setCopied(false);\n setRevealOpen(true);\n accountToast.success({ title: t.created });\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.createFailed) });\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const handleCopy = (text: string) => {\n navigator.clipboard?.writeText(text);\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n };\n\n const confirmRevoke = async (ids: string[]) => {\n setIsRevoking(true);\n try {\n for (const id of ids) {\n await revoke(id);\n }\n await reload();\n accountToast.success({ title: t.revokedOk });\n setRevoking(null);\n setBulkRevoke(false);\n setRowSelection({});\n } catch (error) {\n accountToast.error({ title: errorMessage(error, t.revokeFailed) });\n } finally {\n setIsRevoking(false);\n }\n };\n\n const controller = useClientTable(keys, {\n search: (key) => key.name,\n sorters: {\n name: (key) => key.name,\n status: (key) => (key.revoked ? t.revoked : t.active),\n expires: (key) => key.expires_at ?? \"\",\n lastUsed: (key) => key.last_used_at ?? \"\",\n },\n initialSortBy: \"name\",\n });\n\n const columns = React.useMemo<ColumnDef<ApiKeyPublic>[]>(\n () => [\n createDataTableSelectionColumn<ApiKeyPublic>({\n selectAllVisible: t.actions,\n selectRow: (key) => `${t.revoke} ${key.name}`,\n }),\n {\n id: \"actions\",\n header: t.actions,\n enableHiding: false,\n enableSorting: false,\n cell: ({ row }) => (\n <div className=\"flex items-center gap-2\" data-account-row-actions=\"\">\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={row.original.revoked}\n onClick={() => setRevoking(row.original)}\n data-account-action=\"revoke\"\n >\n <Trash2 className=\"size-3.5\" />\n <span className=\"sr-only lg:not-sr-only\">{t.revoke}</span>\n </Button>\n </div>\n ),\n },\n {\n accessorKey: \"name\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.name} />\n ),\n },\n {\n accessorKey: \"status\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.status} />\n ),\n cell: ({ row }) =>\n row.original.revoked ? (\n <Badge variant=\"outline\">{t.revoked}</Badge>\n ) : (\n <Badge>{t.active}</Badge>\n ),\n },\n {\n accessorKey: \"expires\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.expires} />\n ),\n cell: ({ row }) => formatDate(row.original.expires_at, t.notAvailable),\n },\n {\n accessorKey: \"lastUsed\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.lastUsed} />\n ),\n cell: ({ row }) => formatDate(row.original.last_used_at, t.notUsed),\n },\n ],\n [t],\n );\n\n // A token has no editable fields — both row actions revoke, and a single\n // confirm dialog covers the individual revoke path.\n const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);\n\n return (\n <div className=\"not-content flex w-full flex-col gap-6\">\n <AccountToastHost />\n <Card>\n <CardHeader>\n <CardTitle>{t.activeTitle}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent>\n <DataTable<ApiKeyPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && keys.length === 0}\n getRowId={(key) => key.id}\n rowSelection={rowSelection}\n onRowSelectionChange={setRowSelection}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={\n <Button type=\"button\" size=\"sm\" onClick={openCreate}>\n <KeyRound className=\"size-4\" />\n {t.mint}\n </Button>\n }\n selectionActions={\n selectedIds.length > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => setBulkRevoke(true)}\n >\n {t.revokeSelected} ({selectedIds.length})\n </Button>\n ) : null\n }\n />\n </CardContent>\n </Card>\n\n {/* Create token popup */}\n <EntityFormDialog\n open={creating}\n onOpenChange={setCreating}\n title={t.createTitle}\n description={t.createDescription}\n >\n <form onSubmit={handleCreate} className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-name\">{t.name}</Label>\n <Input\n id=\"api-key-name\"\n aria-label={t.name}\n value={name}\n onChange={(event) => setName(event.target.value)}\n placeholder={t.namePlaceholder}\n />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-ttl\">{t.ttl}</Label>\n <Input\n id=\"api-key-ttl\"\n type=\"number\"\n min={1}\n value={ttlAmount}\n onChange={(event) => setTtlAmount(event.target.value)}\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-unit\">{t.ttlUnit}</Label>\n <select\n id=\"api-key-unit\"\n aria-label={t.ttlUnit}\n value={ttlUnit}\n onChange={(event) => setTtlUnit(event.target.value as TtlUnit)}\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n >\n <option value=\"hours\">{t.unitHours}</option>\n <option value=\"days\">{t.unitDays}</option>\n <option value=\"weeks\">{t.unitWeeks}</option>\n </select>\n </div>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setCreating(false)}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={isSubmitting}>\n {isSubmitting ? t.generating : t.mint}\n </Button>\n </DialogFooter>\n </form>\n </EntityFormDialog>\n\n {/* One-time plaintext reveal */}\n <Dialog\n open={revealOpen && Boolean(lastCreated)}\n onOpenChange={setRevealOpen}\n >\n <DialogContent className=\"sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>{t.revealTitle}</DialogTitle>\n <DialogDescription>{t.securityNotice}</DialogDescription>\n </DialogHeader>\n <div className=\"flex items-center gap-2 overflow-x-auto rounded-md border bg-muted/40 p-2 font-mono text-xs\">\n <span className=\"flex-1 select-all break-all\">\n {lastCreated?.plaintext}\n </span>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => lastCreated && handleCopy(lastCreated.plaintext)}\n >\n {copied ? t.copied : t.copy}\n </Button>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => setRevealOpen(false)}>\n {t.done}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n\n {/* Revoke confirmations */}\n <ConfirmDeleteDialog\n open={Boolean(revoking)}\n onOpenChange={(open) => {\n if (!open) setRevoking(null);\n }}\n title={t.confirmRevokeTitle}\n description={t.confirmRevokeBody}\n confirmLabel={t.revoke}\n cancelLabel={t.cancel}\n pending={isRevoking}\n onConfirm={() => revoking && confirmRevoke([revoking.id])}\n />\n <ConfirmDeleteDialog\n open={bulkRevoke}\n onOpenChange={setBulkRevoke}\n title={t.confirmRevokeTitle}\n description={t.confirmRevokeBody}\n confirmLabel={t.revokeSelected}\n cancelLabel={t.cancel}\n pending={isRevoking}\n onConfirm={() => confirmRevoke(selectedIds)}\n />\n </div>\n );\n}\n",
|
|
24
|
+
"content": "\"use client\";\n\n// fa-auth API keys panel: mint and revoke programmatic API tokens. Headless\n// logic stays a live dependency — `useApiKeys` (@mano8/astro-auth-m8/hooks) owns\n// the list/create/revoke calls and the package Zod schema validates the form.\n// This file is only the shadcn skin, copied into the consumer via the\n// @fa-m8-auth registry — edit (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport type { ColumnDef, RowSelectionState } from \"@tanstack/react-table\";\nimport { KeyRound, Trash2 } from \"lucide-react\";\nimport { useApiKeys } from \"@mano8/astro-auth-m8/hooks\";\nimport {\n ApiKeyCreateSchema,\n type ApiKeyAccessMode,\n type ApiKeyPublic,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from \"@/components/ui/dialog\";\nimport {\n DataTable,\n createDataTableSelectionColumn,\n} from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n EntityFormDialog,\n errorMessage,\n useClientTable,\n} from \"./account-crud\";\n\nexport interface ApiKeysPanelLabels {\n title: string;\n description: string;\n createTitle: string;\n createDescription: string;\n name: string;\n namePlaceholder: string;\n ttl: string;\n ttlUnit: string;\n unitHours: string;\n unitDays: string;\n unitWeeks: string;\n defaultName: string;\n accessMode: string;\n accessModeReadOnly: string;\n accessModeReadWrite: string;\n audiences: string;\n audiencesPlaceholder: string;\n audiencesHelp: string;\n generating: string;\n mint: string;\n cancel: string;\n securityNotice: string;\n revealTitle: string;\n copied: string;\n copy: string;\n done: string;\n activeTitle: string;\n loading: string;\n empty: string;\n active: string;\n revoked: string;\n status: string;\n expires: string;\n lastUsed: string;\n audiencesNone: string;\n notUsed: string;\n notAvailable: string;\n revoke: string;\n revokeSelected: string;\n confirmRevokeTitle: string;\n confirmRevokeBody: string;\n actions: string;\n search: string;\n created: string;\n createFailed: string;\n revokedOk: string;\n revokeFailed: string;\n}\n\nconst DEFAULT_LABELS: ApiKeysPanelLabels = {\n title: \"API keys\",\n description: \"Provision and revoke programmatic client identifiers.\",\n createTitle: \"Create API token\",\n createDescription:\n \"Provision programmatic client identifiers for remote integrations.\",\n name: \"Token name\",\n namePlaceholder: \"e.g. CI/CD deployment server\",\n ttl: \"Validity\",\n ttlUnit: \"Unit\",\n unitHours: \"Hours\",\n unitDays: \"Days\",\n unitWeeks: \"Weeks\",\n defaultName: \"Default key\",\n accessMode: \"Access mode\",\n accessModeReadOnly: \"Read-only\",\n accessModeReadWrite: \"Read-write\",\n audiences: \"Audiences\",\n audiencesPlaceholder: \"e.g. media-service-m8, prompt-engine-m8\",\n audiencesHelp:\n \"Comma-separated consumer ids permitted to introspect this key remotely. Leave empty for issuer-local use only. Immutable after issuance.\",\n generating: \"Generating...\",\n mint: \"Mint new key\",\n cancel: \"Cancel\",\n securityNotice:\n \"Security notice: copy this API key now. It will not be shown again.\",\n revealTitle: \"API token created\",\n copied: \"Copied\",\n copy: \"Copy\",\n done: \"Done\",\n activeTitle: \"Active credentials\",\n loading: \"Loading API tokens...\",\n empty: \"No active API tokens found.\",\n active: \"Active\",\n revoked: \"Revoked\",\n status: \"Status\",\n expires: \"Expires\",\n lastUsed: \"Last used\",\n audiencesNone: \"Issuer-local only\",\n notUsed: \"Never used\",\n notAvailable: \"n/a\",\n revoke: \"Revoke\",\n revokeSelected: \"Revoke selected\",\n confirmRevokeTitle: \"Revoke API token?\",\n confirmRevokeBody:\n \"This immediately invalidates the token. Integrations using it will stop working.\",\n actions: \"Actions\",\n search: \"Search tokens\",\n created: \"API token created.\",\n createFailed: \"Failed to create API token.\",\n revokedOk: \"API token revoked.\",\n revokeFailed: \"Failed to revoke API token.\",\n};\n\n// Backend currently accepts whole-hour TTLs only; sub-hour units need an auth-API change.\nconst TTL_UNIT_HOURS = { hours: 1, days: 24, weeks: 168 } as const;\ntype TtlUnit = keyof typeof TTL_UNIT_HOURS;\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n return value ? new Date(value).toLocaleString() : fallback;\n}\n\nexport function ApiKeysPanel({ labels }: { labels?: Partial<ApiKeysPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const {\n apiKeys: keys,\n loading,\n reload,\n create,\n createdKey: lastCreated,\n revoke,\n } = useApiKeys(false);\n\n const [creating, setCreating] = React.useState(false);\n const [isSubmitting, setIsSubmitting] = React.useState(false);\n const [name, setName] = React.useState(\"\");\n const [ttlAmount, setTtlAmount] = React.useState(\"30\");\n const [ttlUnit, setTtlUnit] = React.useState<TtlUnit>(\"days\");\n const [accessMode, setAccessMode] = React.useState<ApiKeyAccessMode>(\"read_only\");\n const [audiences, setAudiences] = React.useState(\"\");\n\n const [revealOpen, setRevealOpen] = React.useState(false);\n const [copied, setCopied] = React.useState(false);\n\n const [revoking, setRevoking] = React.useState<ApiKeyPublic | null>(null);\n const [bulkRevoke, setBulkRevoke] = React.useState(false);\n const [isRevoking, setIsRevoking] = React.useState(false);\n const [rowSelection, setRowSelection] = React.useState<RowSelectionState>({});\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const openCreate = () => {\n setName(\"\");\n setTtlAmount(\"30\");\n setTtlUnit(\"days\");\n setAccessMode(\"read_only\");\n setAudiences(\"\");\n setCreating(true);\n };\n\n const handleCreate = async (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n const ttlHours = Math.max(\n 1,\n Math.round((Number(ttlAmount) || 1) * TTL_UNIT_HOURS[ttlUnit]),\n );\n const parsedAudiences = audiences\n .split(\",\")\n .map((audience) => audience.trim())\n .filter((audience) => audience.length > 0);\n const parsed = ApiKeyCreateSchema.safeParse({\n name: name.trim() || t.defaultName,\n ttl_hours: ttlHours,\n access_mode: accessMode,\n audiences: parsedAudiences.length > 0 ? parsedAudiences : undefined,\n });\n if (!parsed.success) {\n accountToast.error({\n title: parsed.error.issues[0]?.message ?? t.createFailed,\n });\n return;\n }\n setIsSubmitting(true);\n try {\n await create(parsed.data);\n // The hook query is disabled (useApiKeys(false)), so invalidation alone\n // won't repopulate the table — refetch explicitly.\n await reload();\n setCreating(false);\n setCopied(false);\n setRevealOpen(true);\n accountToast.success({ title: t.created });\n } catch (error) {\n accountToast.error(errorMessage(error, t.createFailed));\n } finally {\n setIsSubmitting(false);\n }\n };\n\n const handleCopy = (text: string) => {\n navigator.clipboard?.writeText(text);\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n };\n\n const confirmRevoke = async (ids: string[]) => {\n setIsRevoking(true);\n try {\n for (const id of ids) {\n await revoke(id);\n }\n await reload();\n accountToast.success({ title: t.revokedOk });\n setRevoking(null);\n setBulkRevoke(false);\n setRowSelection({});\n } catch (error) {\n accountToast.error(errorMessage(error, t.revokeFailed));\n } finally {\n setIsRevoking(false);\n }\n };\n\n const controller = useClientTable(keys, {\n search: (key) => key.name,\n sorters: {\n name: (key) => key.name,\n status: (key) => (key.revoked ? t.revoked : t.active),\n expires: (key) => key.expires_at ?? \"\",\n lastUsed: (key) => key.last_used_at ?? \"\",\n },\n initialSortBy: \"name\",\n });\n\n const columns = React.useMemo<ColumnDef<ApiKeyPublic>[]>(\n () => [\n createDataTableSelectionColumn<ApiKeyPublic>({\n selectAllVisible: t.actions,\n selectRow: (key) => `${t.revoke} ${key.name}`,\n }),\n {\n id: \"actions\",\n header: t.actions,\n enableHiding: false,\n enableSorting: false,\n cell: ({ row }) => (\n <div className=\"flex items-center gap-2\" data-account-row-actions=\"\">\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={row.original.revoked}\n onClick={() => setRevoking(row.original)}\n data-account-action=\"revoke\"\n >\n <Trash2 className=\"size-3.5\" />\n <span className=\"sr-only lg:not-sr-only\">{t.revoke}</span>\n </Button>\n </div>\n ),\n },\n {\n accessorKey: \"name\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.name} />\n ),\n },\n {\n accessorKey: \"status\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.status} />\n ),\n cell: ({ row }) =>\n row.original.revoked ? (\n <Badge variant=\"outline\">{t.revoked}</Badge>\n ) : (\n <Badge>{t.active}</Badge>\n ),\n },\n {\n accessorKey: \"accessMode\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.accessMode} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\">\n {row.original.access_mode === \"read_write\"\n ? t.accessModeReadWrite\n : t.accessModeReadOnly}\n </Badge>\n ),\n },\n {\n accessorKey: \"audiences\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.audiences} />\n ),\n cell: ({ row }) =>\n row.original.audiences.length > 0\n ? row.original.audiences.join(\", \")\n : t.audiencesNone,\n },\n {\n accessorKey: \"expires\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.expires} />\n ),\n cell: ({ row }) => formatDate(row.original.expires_at, t.notAvailable),\n },\n {\n accessorKey: \"lastUsed\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.lastUsed} />\n ),\n cell: ({ row }) => formatDate(row.original.last_used_at, t.notUsed),\n },\n ],\n [t],\n );\n\n // A token has no editable fields — both row actions revoke, and a single\n // confirm dialog covers the individual revoke path.\n const selectedIds = Object.keys(rowSelection).filter((id) => rowSelection[id]);\n\n return (\n <div className=\"not-content flex w-full flex-col gap-6\">\n <AccountToastHost />\n <Card>\n <CardHeader>\n <CardTitle>{t.activeTitle}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent>\n <DataTable<ApiKeyPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && keys.length === 0}\n getRowId={(key) => key.id}\n rowSelection={rowSelection}\n onRowSelectionChange={setRowSelection}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={\n <Button type=\"button\" size=\"sm\" onClick={openCreate}>\n <KeyRound className=\"size-4\" />\n {t.mint}\n </Button>\n }\n selectionActions={\n selectedIds.length > 0 ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={() => setBulkRevoke(true)}\n >\n {t.revokeSelected} ({selectedIds.length})\n </Button>\n ) : null\n }\n />\n </CardContent>\n </Card>\n\n {/* Create token popup */}\n <EntityFormDialog\n open={creating}\n onOpenChange={setCreating}\n title={t.createTitle}\n description={t.createDescription}\n >\n <form onSubmit={handleCreate} className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-name\">{t.name}</Label>\n <Input\n id=\"api-key-name\"\n aria-label={t.name}\n value={name}\n onChange={(event) => setName(event.target.value)}\n placeholder={t.namePlaceholder}\n />\n </div>\n <div className=\"grid grid-cols-2 gap-3\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-ttl\">{t.ttl}</Label>\n <Input\n id=\"api-key-ttl\"\n type=\"number\"\n min={1}\n value={ttlAmount}\n onChange={(event) => setTtlAmount(event.target.value)}\n />\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-unit\">{t.ttlUnit}</Label>\n <select\n id=\"api-key-unit\"\n aria-label={t.ttlUnit}\n value={ttlUnit}\n onChange={(event) => setTtlUnit(event.target.value as TtlUnit)}\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n >\n <option value=\"hours\">{t.unitHours}</option>\n <option value=\"days\">{t.unitDays}</option>\n <option value=\"weeks\">{t.unitWeeks}</option>\n </select>\n </div>\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-access-mode\">{t.accessMode}</Label>\n <select\n id=\"api-key-access-mode\"\n aria-label={t.accessMode}\n value={accessMode}\n onChange={(event) =>\n setAccessMode(event.target.value as ApiKeyAccessMode)\n }\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n >\n <option value=\"read_only\">{t.accessModeReadOnly}</option>\n <option value=\"read_write\">{t.accessModeReadWrite}</option>\n </select>\n </div>\n <div className=\"space-y-1\">\n <Label htmlFor=\"api-key-audiences\">{t.audiences}</Label>\n <Input\n id=\"api-key-audiences\"\n aria-label={t.audiences}\n value={audiences}\n onChange={(event) => setAudiences(event.target.value)}\n placeholder={t.audiencesPlaceholder}\n />\n <p className=\"text-xs text-muted-foreground\">{t.audiencesHelp}</p>\n </div>\n <DialogFooter>\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => setCreating(false)}\n >\n {t.cancel}\n </Button>\n <Button type=\"submit\" disabled={isSubmitting}>\n {isSubmitting ? t.generating : t.mint}\n </Button>\n </DialogFooter>\n </form>\n </EntityFormDialog>\n\n {/* One-time plaintext reveal */}\n <Dialog\n open={revealOpen && Boolean(lastCreated)}\n onOpenChange={setRevealOpen}\n >\n <DialogContent className=\"sm:max-w-lg\">\n <DialogHeader>\n <DialogTitle>{t.revealTitle}</DialogTitle>\n <DialogDescription>{t.securityNotice}</DialogDescription>\n </DialogHeader>\n <div className=\"flex items-center gap-2 overflow-x-auto rounded-md border bg-muted/40 p-2 font-mono text-xs\">\n <span className=\"flex-1 select-all break-all\">\n {lastCreated?.plaintext}\n </span>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n onClick={() => lastCreated && handleCopy(lastCreated.plaintext)}\n >\n {copied ? t.copied : t.copy}\n </Button>\n </div>\n <DialogFooter>\n <Button type=\"button\" onClick={() => setRevealOpen(false)}>\n {t.done}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n\n {/* Revoke confirmations */}\n <ConfirmDeleteDialog\n open={Boolean(revoking)}\n onOpenChange={(open) => {\n if (!open) setRevoking(null);\n }}\n title={t.confirmRevokeTitle}\n description={t.confirmRevokeBody}\n confirmLabel={t.revoke}\n cancelLabel={t.cancel}\n pending={isRevoking}\n onConfirm={() => revoking && confirmRevoke([revoking.id])}\n />\n <ConfirmDeleteDialog\n open={bulkRevoke}\n onOpenChange={setBulkRevoke}\n title={t.confirmRevokeTitle}\n description={t.confirmRevokeBody}\n confirmLabel={t.revokeSelected}\n cancelLabel={t.cancel}\n pending={isRevoking}\n onConfirm={() => confirmRevoke(selectedIds)}\n />\n </div>\n );\n}\n",
|
|
25
25
|
"type": "registry:component",
|
|
26
26
|
"target": "components/fa-auth/api-keys-panel.tsx"
|
|
27
27
|
}
|
package/registry/r/registry.json
CHANGED
|
@@ -50,6 +50,12 @@
|
|
|
50
50
|
"type": "registry:component",
|
|
51
51
|
"title": "Admin Users Panel",
|
|
52
52
|
"description": "fa-auth superuser-only user management on the canonical data-table (page selector, orderable columns, column visibility), with popup create/edit forms, alert-dialog delete confirm, and bottom-right toasts. Gated by the package's RequireRole and driven by useUsers. Requires @mano8/astro-auth-m8 installed."
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"name": "security-panel",
|
|
56
|
+
"type": "registry:component",
|
|
57
|
+
"title": "Account Security Panel",
|
|
58
|
+
"description": "fa-auth admin-tier privileged-action audit log on the canonical data-table plus the two superuser-only retention purges, each behind a confirmation naming the retention floor. Gated by the package's RequireRole (role hierarchy for the log, dual evidence for the purges) and driven by useAuditLog + useSecurityPurges. Requires @mano8/astro-auth-m8 installed."
|
|
53
59
|
}
|
|
54
60
|
]
|
|
55
61
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
|
3
|
+
"name": "security-panel",
|
|
4
|
+
"type": "registry:component",
|
|
5
|
+
"title": "Account Security Panel",
|
|
6
|
+
"description": "fa-auth admin-tier privileged-action audit log on the canonical data-table plus the two superuser-only retention purges, each behind a confirmation naming the retention floor. Gated by the package's RequireRole (role hierarchy for the log, dual evidence for the purges) and driven by useAuditLog + useSecurityPurges. Requires @mano8/astro-auth-m8 installed.",
|
|
7
|
+
"dependencies": [
|
|
8
|
+
"lucide-react",
|
|
9
|
+
"@tanstack/react-table"
|
|
10
|
+
],
|
|
11
|
+
"registryDependencies": [
|
|
12
|
+
"card",
|
|
13
|
+
"button",
|
|
14
|
+
"label",
|
|
15
|
+
"badge",
|
|
16
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
17
|
+
"./account-crud.json"
|
|
18
|
+
],
|
|
19
|
+
"files": [
|
|
20
|
+
{
|
|
21
|
+
"path": "registry/blocks/account/security-panel.tsx",
|
|
22
|
+
"content": "\"use client\";\n\n// fa-auth security panel: the admin-tier privileged-action audit log plus the\n// two superadmin-only retention purges. Headless logic stays a live dependency\n// — `useAuditLog` / `useSecurityPurges` (@mano8/astro-auth-m8/hooks) own the\n// calls and the package Zod schemas own the closed retention-window enum. This\n// file is only the shadcn skin, copied into the consumer via the @fa-m8-auth\n// registry — edit (and translate via `labels`) freely per app.\n//\n// Two tiers, two deliberately different gates, mirroring fa-auth-m8 2.0.0:\n// * the audit-log READ is authorized by the role hierarchy alone\n// (`get_current_active_admin`), so it is gated with `RequireRole\n// minimumRole=\"admin\"` — gating it on superuser would hide an admin's own\n// surface from them;\n// * both PURGES are superuser actions (`get_current_active_superuser`), so\n// they are gated with `RequireRole superuser` (dual evidence).\n// Which rows the log returns — an admin's own, or every row for a superadmin —\n// is decided server-side from the authenticated principal. This panel renders\n// what it receives and never sends an actor id to widen or narrow that.\nimport * as React from \"react\";\nimport type { ColumnDef } from \"@tanstack/react-table\";\nimport { RotateCcw, Trash2 } from \"lucide-react\";\nimport { RequireRole } from \"@mano8/astro-auth-m8/react\";\nimport { useAuditLog, useSecurityPurges } from \"@mano8/astro-auth-m8/hooks\";\nimport { ApiError } from \"@mano8/astro-auth-m8/errors\";\nimport {\n RetentionWindowSchema,\n type PrivilegedActionAuditPublic,\n type PurgeResponse,\n type RetentionWindow,\n} from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Label } from \"@/components/ui/label\";\nimport { Badge } from \"@/components/ui/badge\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\nimport { DataTable } from \"@/components/m8-ui/data-table\";\nimport { DataTableColumnHeader } from \"@/components/m8-ui/data-table-column-header\";\nimport {\n AccountToastHost,\n accountToast,\n ConfirmDeleteDialog,\n errorMessage,\n useClientTable,\n type UseClientTableOptions,\n} from \"./account-crud\";\n\nexport interface SecurityPanelLabels {\n auditTitle: string;\n auditDescription: string;\n auditScopeNotice: string;\n adminRequired: string;\n refresh: string;\n loading: string;\n empty: string;\n search: string;\n when: string;\n action: string;\n actor: string;\n actorRole: string;\n table: string;\n row: string;\n targetOwner: string;\n notAvailable: string;\n auditLoadFailed: string;\n purgeTitle: string;\n purgeDescription: string;\n retentionFloorNotice: string;\n window: string;\n windowLabels: Record<RetentionWindow, string>;\n purgeAuditTitle: string;\n purgeAuditDescription: string;\n purgeAuditConfirmTitle: string;\n purgeAuditConfirmBody: string;\n purgeKeysTitle: string;\n purgeKeysDescription: string;\n purgeKeysConfirmTitle: string;\n purgeKeysConfirmBody: string;\n purge: string;\n purging: string;\n cancel: string;\n purged: string;\n purgedRemoved: string;\n purgeFailed: string;\n unknownOutcomeTitle: string;\n unknownOutcomeBody: string;\n unknownOutcomeAcknowledge: string;\n}\n\nconst DEFAULT_LABELS: SecurityPanelLabels = {\n auditTitle: \"Privileged action audit log\",\n auditDescription:\n \"Every privileged write recorded by the auth service, newest first.\",\n auditScopeNotice:\n \"Scope is decided by the auth service from your own credentials: an admin sees the entries it authored, a superadmin sees every entry. This view never requests another user's entries.\",\n adminRequired: \"The audit log is available to admin accounts and above.\",\n refresh: \"Refresh\",\n loading: \"Loading audit entries...\",\n empty: \"No audit entries found.\",\n search: \"Search entries\",\n when: \"When\",\n action: \"Action\",\n actor: \"Actor\",\n actorRole: \"Actor role\",\n table: \"Table\",\n row: \"Row\",\n targetOwner: \"Target owner\",\n notAvailable: \"n/a\",\n auditLoadFailed: \"Failed to load the audit log.\",\n purgeTitle: \"Retention purges\",\n purgeDescription:\n \"Superuser-only maintenance: permanently delete records older than the selected retention window.\",\n retentionFloorNotice:\n \"The auth service enforces a minimum retention floor. It is server-side configuration and is not published by any endpoint, so a window shorter than the floor cannot be caught here - the service rejects it and its reason is shown verbatim.\",\n window: \"Retention window\",\n windowLabels: {\n \"1w\": \"Older than 1 week\",\n \"1m\": \"Older than 1 month\",\n \"3m\": \"Older than 3 months\",\n \"6m\": \"Older than 6 months\",\n \"1y\": \"Older than 1 year\",\n },\n purgeAuditTitle: \"Purge audit entries\",\n purgeAuditDescription:\n \"Deletes privileged-action audit entries older than the selected window.\",\n purgeAuditConfirmTitle: \"Purge audit entries?\",\n purgeAuditConfirmBody:\n \"This permanently deletes every audit entry older than the selected retention window. Audit history cannot be restored, and entries below the service's retention floor are refused.\",\n purgeKeysTitle: \"Purge revoked API keys\",\n purgeKeysDescription:\n \"Deletes revoked or expired API key records older than the selected window.\",\n purgeKeysConfirmTitle: \"Purge API key records?\",\n purgeKeysConfirmBody:\n \"This permanently deletes revoked and expired API key records older than the selected retention window. The records cannot be restored, and windows below the service's retention floor are refused.\",\n purge: \"Purge\",\n purging: \"Purging...\",\n cancel: \"Cancel\",\n purged: \"Purge complete.\",\n purgedRemoved: \"Records removed\",\n purgeFailed: \"Purge failed.\",\n unknownOutcomeTitle: \"Outcome unknown\",\n unknownOutcomeBody:\n \"The auth service could not confirm whether this purge ran. Check the current record counts before doing anything else - re-running it now could delete more than you intend, and the reported count would be wrong either way.\",\n unknownOutcomeAcknowledge: \"I have checked - re-enable\",\n};\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n return value ? new Date(value).toLocaleString() : fallback;\n}\n\n// Raw identifiers are shown verbatim in a mono face: they are what an operator\n// correlates against the service's own logs, so they are never truncated.\nfunction monoCell(value: string | null | undefined, fallback: string) {\n return <span className=\"font-mono text-xs\">{value ?? fallback}</span>;\n}\n\n// Human-readable, sortable columns.\nfunction auditDetailColumns(\n t: SecurityPanelLabels,\n): ColumnDef<PrivilegedActionAuditPublic>[] {\n return [\n {\n accessorKey: \"created_at\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.when} />\n ),\n cell: ({ row }) => formatDate(row.original.created_at, t.notAvailable),\n },\n {\n accessorKey: \"action\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.action} />\n ),\n cell: ({ row }) => (\n <Badge variant=\"outline\" className=\"capitalize\">\n {row.original.action}\n </Badge>\n ),\n },\n {\n accessorKey: \"table_name\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.table} />\n ),\n },\n {\n accessorKey: \"actor_role\",\n header: ({ column }) => (\n <DataTableColumnHeader column={column} title={t.actorRole} />\n ),\n cell: ({ row }) => (\n <span className=\"capitalize\">{row.original.actor_role}</span>\n ),\n },\n ];\n}\n\n// The three id columns differ only by which field they read, so they share one\n// builder rather than repeating the same cell three times.\nfunction auditIdentifierColumns(\n t: SecurityPanelLabels,\n): ColumnDef<PrivilegedActionAuditPublic>[] {\n const identifier = (\n accessorKey: \"row_pk\" | \"actor_user_id\" | \"target_owner_id\",\n header: string,\n ): ColumnDef<PrivilegedActionAuditPublic> => ({\n accessorKey,\n header,\n enableSorting: false,\n cell: ({ row }) => monoCell(row.original[accessorKey], t.notAvailable),\n });\n\n return [\n identifier(\"row_pk\", t.row),\n identifier(\"actor_user_id\", t.actor),\n identifier(\"target_owner_id\", t.targetOwner),\n ];\n}\n\n// Client-side search/sort behaviour for the audit rows. Static, so it is built\n// once here rather than on every render of the section.\nconst AUDIT_TABLE_OPTIONS: UseClientTableOptions<PrivilegedActionAuditPublic> = {\n search: (entry) => `${entry.action} ${entry.table_name} ${entry.actor_user_id}`,\n sorters: {\n created_at: (entry) => entry.created_at,\n action: (entry) => entry.action,\n actor_role: (entry) => entry.actor_role,\n table_name: (entry) => entry.table_name,\n },\n initialSortBy: \"created_at\",\n initialSortDir: \"desc\",\n};\n\nfunction AuditRefreshButton({\n t,\n reload,\n}: {\n t: SecurityPanelLabels;\n reload: () => Promise<unknown>;\n}) {\n return (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => {\n reload().catch((error) => {\n accountToast.error(errorMessage(error, t.auditLoadFailed));\n });\n }}\n >\n <RotateCcw className=\"size-4\" />\n {t.refresh}\n </Button>\n );\n}\n\nfunction AuditLogSection({ t }: { t: SecurityPanelLabels }) {\n // No actor filter is sent: the service scopes the rows from the caller's own\n // credentials, and passing one here could only ever ask for someone else's.\n const { rows, count, loading, reload } = useAuditLog({}, false);\n\n React.useEffect(() => {\n reload().catch(() => {});\n }, [reload]);\n\n const controller = useClientTable(rows, AUDIT_TABLE_OPTIONS);\n const columns = React.useMemo(\n () => [...auditDetailColumns(t), ...auditIdentifierColumns(t)],\n [t],\n );\n\n return (\n <Card>\n <CardHeader>\n <CardTitle>{t.auditTitle}</CardTitle>\n <CardDescription>{t.auditDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.auditScopeNotice}</p>\n <DataTable<PrivilegedActionAuditPublic, unknown>\n columns={columns}\n data={controller.data}\n rowCount={controller.rowCount}\n page={controller.page}\n pageSize={controller.pageSize}\n onPageChange={controller.onPageChange}\n onPageSizeChange={controller.onPageSizeChange}\n sortBy={controller.sortBy}\n sortDir={controller.sortDir}\n onSortChange={controller.onSortChange}\n q={controller.q}\n onSearchChange={controller.onSearchChange}\n loading={loading && count === 0}\n getRowId={(entry) => entry.id}\n labels={{\n loading: t.loading,\n empty: t.empty,\n toolbar: { search: t.search },\n }}\n addButton={<AuditRefreshButton t={t} reload={reload} />}\n />\n </CardContent>\n </Card>\n );\n}\n\nfunction PurgeCard({\n t,\n title,\n description,\n confirmTitle,\n confirmBody,\n action,\n testId,\n}: {\n t: SecurityPanelLabels;\n title: string;\n description: string;\n confirmTitle: string;\n confirmBody: string;\n action: (retention: RetentionWindow) => Promise<PurgeResponse>;\n testId: string;\n}) {\n const [retention, setRetention] = React.useState<RetentionWindow>(\"1y\");\n const [confirming, setConfirming] = React.useState(false);\n const [pending, setPending] = React.useState(false);\n // Set on a 503 only. The purge may or may not have run, so the control is\n // locked until the operator explicitly acknowledges having checked: a purge\n // is not idempotent in its reporting, and a blind re-run would both delete\n // more than intended and report a count the operator would misread.\n const [outcomeUnknown, setOutcomeUnknown] = React.useState(false);\n\n const confirm = async () => {\n setPending(true);\n try {\n const result = await action(retention);\n setConfirming(false);\n accountToast.success({\n title: t.purged,\n description: `${t.purgedRemoved}: ${result.removed}`,\n });\n } catch (error) {\n if (error instanceof ApiError && error.status === 503) {\n setOutcomeUnknown(true);\n setConfirming(false);\n }\n // 429 (rate limited, not attempted), 503 (unknown) and the free-text 400\n // retention-floor rejection are all mapped by the package's\n // describeApiError; nothing is retried automatically here.\n accountToast.error(errorMessage(error, t.purgeFailed));\n } finally {\n setPending(false);\n }\n };\n\n const selectId = `${testId}-window`;\n\n return (\n <Card className=\"h-full\" data-account-purge={testId}>\n <CardHeader>\n <CardTitle className=\"text-base\">{title}</CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor={selectId}>{t.window}</Label>\n {/* Closed enum, never free text or a date: the service accepts only\n these five windows, and the list is derived from the package\n schema so it cannot drift from the contract. */}\n <select\n id={selectId}\n aria-label={t.window}\n className=\"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\"\n value={retention}\n onChange={(event) =>\n setRetention(event.target.value as RetentionWindow)\n }\n >\n {RetentionWindowSchema.options.map((option) => (\n <option key={option} value={option}>\n {t.windowLabels[option]}\n </option>\n ))}\n </select>\n </div>\n\n {outcomeUnknown ? (\n <div\n role=\"alert\"\n className=\"space-y-2 rounded-md border border-destructive/50 p-3 text-sm\"\n >\n <p className=\"font-medium\">{t.unknownOutcomeTitle}</p>\n <p className=\"text-muted-foreground\">{t.unknownOutcomeBody}</p>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n onClick={() => setOutcomeUnknown(false)}\n data-account-action=\"acknowledge-unknown\"\n >\n {t.unknownOutcomeAcknowledge}\n </Button>\n </div>\n ) : null}\n\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n disabled={pending || outcomeUnknown}\n onClick={() => setConfirming(true)}\n data-account-action=\"purge\"\n >\n <Trash2 className=\"size-3.5\" />\n {pending ? t.purging : t.purge}\n </Button>\n </CardContent>\n\n {/* Purges are never a one-click action: each goes through its own\n confirmation naming what is deleted and that a window below the\n service's retention floor is refused. */}\n <ConfirmDeleteDialog\n open={confirming}\n onOpenChange={(open) => {\n if (!open) setConfirming(false);\n }}\n title={confirmTitle}\n description={`${confirmBody} ${t.retentionFloorNotice}`}\n confirmLabel={t.purge}\n cancelLabel={t.cancel}\n pending={pending}\n onConfirm={() => {\n void confirm();\n }}\n />\n </Card>\n );\n}\n\nfunction PurgeSection({ t }: { t: SecurityPanelLabels }) {\n const { purgeAudit, purgeKeys } = useSecurityPurges();\n\n return (\n <Card>\n <CardHeader>\n <CardTitle>{t.purgeTitle}</CardTitle>\n <CardDescription>{t.purgeDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{t.retentionFloorNotice}</p>\n <div className=\"grid auto-rows-fr gap-4 lg:grid-cols-2\">\n <PurgeCard\n t={t}\n testId=\"audit-log\"\n title={t.purgeAuditTitle}\n description={t.purgeAuditDescription}\n confirmTitle={t.purgeAuditConfirmTitle}\n confirmBody={t.purgeAuditConfirmBody}\n action={purgeAudit}\n />\n <PurgeCard\n t={t}\n testId=\"api-keys\"\n title={t.purgeKeysTitle}\n description={t.purgeKeysDescription}\n confirmTitle={t.purgeKeysConfirmTitle}\n confirmBody={t.purgeKeysConfirmBody}\n action={purgeKeys}\n />\n </div>\n </CardContent>\n </Card>\n );\n}\n\nexport function SecurityPanel({\n labels,\n}: {\n labels?: Partial<SecurityPanelLabels>;\n}) {\n const t = {\n ...DEFAULT_LABELS,\n ...labels,\n windowLabels: { ...DEFAULT_LABELS.windowLabels, ...labels?.windowLabels },\n };\n\n return (\n <div className=\"not-content flex w-full flex-col gap-6\">\n <AccountToastHost />\n {/* Admin tier: role hierarchy only, so a superadmin is admitted too. */}\n <RequireRole\n minimumRole=\"admin\"\n fallback={\n <p className=\"text-sm text-muted-foreground\">{t.adminRequired}</p>\n }\n >\n <AuditLogSection t={t} />\n </RequireRole>\n {/* Superadmin tier: dual evidence. Rendering nothing (not a message) for\n everyone else keeps the maintenance surface out of an admin's view. */}\n <RequireRole superuser>\n <PurgeSection t={t} />\n </RequireRole>\n </div>\n );\n}\n",
|
|
23
|
+
"type": "registry:component",
|
|
24
|
+
"target": "components/fa-auth/security-panel.tsx"
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"files": [
|
|
15
15
|
{
|
|
16
16
|
"path": "registry/blocks/account/sessions-panel.tsx",
|
|
17
|
-
"content": "\"use client\";\n\n// fa-auth sessions panel: current session details + your/all activity summaries,\n// with superuser-only session revocation. Headless logic stays a live dependency\n// — `useAuth` (@mano8/astro-auth-m8/react) supplies the user, `useSessions` and\n// `useDashboard` (@mano8/astro-auth-m8/hooks) supply the data. This file is only\n// the shadcn skin, copied into the consumer via the @fa-m8-auth registry — edit\n// (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport { RefreshCw, Trash2 } from \"lucide-react\";\nimport { useAuth } from \"@mano8/astro-auth-m8/react\";\nimport { useSessions, useDashboard } from \"@mano8/astro-auth-m8/hooks\";\nimport type { UsersActivity } from \"@mano8/astro-auth-m8/schemas\";\n\nimport { Button } from \"@/components/ui/button\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\n\nexport interface SessionsPanelLabels {\n notAvailable: string;\n logins: string;\n registrations: string;\n users: string;\n title: string;\n description: string;\n provider: string;\n jwtExpires: string;\n refreshExpires: string;\n notLoaded: string;\n yourActivity: string;\n refresh: string;\n adminTitle: string;\n adminDescription: string;\n allActivity: string;\n loading: string;\n empty: string;\n expires: string;\n revoke: string;\n}\n\nconst DEFAULT_LABELS: SessionsPanelLabels = {\n notAvailable: \"n/a\",\n logins: \"Logins\",\n registrations: \"Registrations\",\n users: \"Users\",\n title: \"Session\",\n description: \"Current authentication session and account activity.\",\n provider: \"Provider\",\n jwtExpires: \"JWT expires\",\n refreshExpires: \"Refresh expires\",\n notLoaded: \"Session details are not loaded.\",\n yourActivity: \"Your activity\",\n refresh: \"Refresh\",\n adminTitle: \"Admin sessions\",\n adminDescription: \"Superuser-only session overview.\",\n allActivity: \"All activity\",\n loading: \"Loading sessions...\",\n empty: \"No sessions returned.\",\n expires: \"Expires\",\n revoke: \"Revoke\",\n};\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n if (!value) return fallback;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? value : date.toLocaleString();\n}\n\nfunction ActivitySummary({\n title,\n totalLogins,\n totalRegistrations,\n totalUsers,\n t,\n}: {\n title: string;\n totalLogins?: number;\n totalRegistrations?: number;\n totalUsers?: number;\n t: SessionsPanelLabels;\n}) {\n return (\n <div className=\"rounded-md border p-3\">\n <h4 className=\"text-sm font-semibold\">{title}</h4>\n <dl className=\"mt-3 grid grid-cols-3 gap-3 text-sm\">\n <div>\n <dt className=\"text-muted-foreground\">{t.logins}</dt>\n <dd className=\"font-medium\">{totalLogins ?? \"-\"}</dd>\n </div>\n <div>\n <dt className=\"text-muted-foreground\">{t.registrations}</dt>\n <dd className=\"font-medium\">{totalRegistrations ?? \"-\"}</dd>\n </div>\n <div>\n <dt className=\"text-muted-foreground\">{t.users}</dt>\n <dd className=\"font-medium\">{totalUsers ?? \"-\"}</dd>\n </div>\n </dl>\n </div>\n );\n}\n\nfunction activityAdded(stats: UsersActivity | null, model: string): number | undefined {\n return stats?.activity.activity.find((entry) => entry.model === model)?.added;\n}\n\nexport function SessionsPanel({ labels }: { labels?: Partial<SessionsPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const { user } = useAuth();\n const isSuperuser = user
|
|
17
|
+
"content": "\"use client\";\n\n// fa-auth sessions panel: current session details + your/all activity summaries,\n// with superuser-only session revocation. Headless logic stays a live dependency\n// — `useAuth` (@mano8/astro-auth-m8/react) supplies the user, `useSessions` and\n// `useDashboard` (@mano8/astro-auth-m8/hooks) supply the data. This file is only\n// the shadcn skin, copied into the consumer via the @fa-m8-auth registry — edit\n// (and translate via `labels`) freely per app.\nimport * as React from \"react\";\nimport { RefreshCw, Trash2 } from \"lucide-react\";\nimport { useAuth } from \"@mano8/astro-auth-m8/react\";\nimport { useSessions, useDashboard } from \"@mano8/astro-auth-m8/hooks\";\nimport type { UsersActivity } from \"@mano8/astro-auth-m8/schemas\";\nimport { hasSuperuserPrivileges } from \"@mano8/astro-auth-m8/authorization\";\n\nimport { Button } from \"@/components/ui/button\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"@/components/ui/card\";\n\nexport interface SessionsPanelLabels {\n notAvailable: string;\n logins: string;\n registrations: string;\n users: string;\n title: string;\n description: string;\n provider: string;\n jwtExpires: string;\n refreshExpires: string;\n notLoaded: string;\n yourActivity: string;\n refresh: string;\n adminTitle: string;\n adminDescription: string;\n allActivity: string;\n loading: string;\n empty: string;\n expires: string;\n revoke: string;\n}\n\nconst DEFAULT_LABELS: SessionsPanelLabels = {\n notAvailable: \"n/a\",\n logins: \"Logins\",\n registrations: \"Registrations\",\n users: \"Users\",\n title: \"Session\",\n description: \"Current authentication session and account activity.\",\n provider: \"Provider\",\n jwtExpires: \"JWT expires\",\n refreshExpires: \"Refresh expires\",\n notLoaded: \"Session details are not loaded.\",\n yourActivity: \"Your activity\",\n refresh: \"Refresh\",\n adminTitle: \"Admin sessions\",\n adminDescription: \"Superuser-only session overview.\",\n allActivity: \"All activity\",\n loading: \"Loading sessions...\",\n empty: \"No sessions returned.\",\n expires: \"Expires\",\n revoke: \"Revoke\",\n};\n\nfunction formatDate(value: string | null | undefined, fallback: string): string {\n if (!value) return fallback;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? value : date.toLocaleString();\n}\n\nfunction ActivitySummary({\n title,\n totalLogins,\n totalRegistrations,\n totalUsers,\n t,\n}: {\n title: string;\n totalLogins?: number;\n totalRegistrations?: number;\n totalUsers?: number;\n t: SessionsPanelLabels;\n}) {\n return (\n <div className=\"rounded-md border p-3\">\n <h4 className=\"text-sm font-semibold\">{title}</h4>\n <dl className=\"mt-3 grid grid-cols-3 gap-3 text-sm\">\n <div>\n <dt className=\"text-muted-foreground\">{t.logins}</dt>\n <dd className=\"font-medium\">{totalLogins ?? \"-\"}</dd>\n </div>\n <div>\n <dt className=\"text-muted-foreground\">{t.registrations}</dt>\n <dd className=\"font-medium\">{totalRegistrations ?? \"-\"}</dd>\n </div>\n <div>\n <dt className=\"text-muted-foreground\">{t.users}</dt>\n <dd className=\"font-medium\">{totalUsers ?? \"-\"}</dd>\n </div>\n </dl>\n </div>\n );\n}\n\nfunction activityAdded(stats: UsersActivity | null, model: string): number | undefined {\n return stats?.activity.activity.find((entry) => entry.model === model)?.added;\n}\n\nexport function SessionsPanel({ labels }: { labels?: Partial<SessionsPanelLabels> }) {\n const t = { ...DEFAULT_LABELS, ...labels };\n const { user } = useAuth();\n const isSuperuser = user ? hasSuperuserPrivileges(user.role, user.is_superuser) : false;\n\n const { current, reloadCurrent, sessions, reload: list, revoke, loading } = useSessions(false);\n const { activity: mine, reload: reloadMine } = useDashboard(\"me\", false);\n const { activity: all, reload: reloadAll } = useDashboard(\"global\", false);\n\n const rows = sessions?.data ?? [];\n\n React.useEffect(() => {\n reloadCurrent().catch(() => {});\n reloadMine().catch(() => {});\n }, [reloadCurrent, reloadMine]);\n\n React.useEffect(() => {\n if (!isSuperuser) return;\n list().catch(() => {});\n reloadAll().catch(() => {});\n }, [isSuperuser, list, reloadAll]);\n\n return (\n <div className=\"not-content grid auto-rows-fr gap-6 lg:grid-cols-2\">\n <Card className=\"h-full\">\n <CardHeader>\n <CardTitle>{t.title}</CardTitle>\n <CardDescription>{t.description}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n {current ? (\n <dl className=\"grid gap-2 text-sm\">\n <div className=\"flex justify-between gap-3\">\n <dt className=\"text-muted-foreground\">{t.provider}</dt>\n <dd className=\"font-medium\">{current.provider}</dd>\n </div>\n <div className=\"flex justify-between gap-3\">\n <dt className=\"text-muted-foreground\">{t.jwtExpires}</dt>\n <dd className=\"font-medium text-right\">{formatDate(current.jwt_expires_at, t.notAvailable)}</dd>\n </div>\n <div className=\"flex justify-between gap-3\">\n <dt className=\"text-muted-foreground\">{t.refreshExpires}</dt>\n <dd className=\"font-medium text-right\">{formatDate(current.refresh_expires_at, t.notAvailable)}</dd>\n </div>\n </dl>\n ) : (\n <p className=\"text-sm text-muted-foreground\">{t.notLoaded}</p>\n )}\n\n <ActivitySummary\n title={t.yourActivity}\n totalLogins={activityAdded(mine, \"login\")}\n totalRegistrations={activityAdded(mine, \"registration\")}\n totalUsers={mine?.nb_users}\n t={t}\n />\n\n <Button type=\"button\" variant=\"outline\" onClick={() => { reloadCurrent(); reloadMine(); }}>\n <RefreshCw />\n {t.refresh}\n </Button>\n </CardContent>\n </Card>\n\n {isSuperuser && (\n <Card className=\"h-full\">\n <CardHeader>\n <CardTitle>{t.adminTitle}</CardTitle>\n <CardDescription>{t.adminDescription}</CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <ActivitySummary\n title={t.allActivity}\n totalLogins={activityAdded(all, \"login\")}\n totalRegistrations={activityAdded(all, \"registration\")}\n totalUsers={all?.nb_users}\n t={t}\n />\n\n {rows.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">\n {loading ? t.loading : t.empty}\n </p>\n ) : (\n <div className=\"divide-y rounded-md border\">\n {rows.map((session) => (\n <div key={session.id} className=\"flex items-center justify-between gap-3 p-3\">\n <div className=\"min-w-0 text-sm\">\n <p className=\"truncate font-medium\">{session.id}</p>\n <p className=\"text-muted-foreground\">{t.expires} {formatDate(session.refresh_expires_at, t.notAvailable)}</p>\n </div>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"destructive\"\n onClick={async () => {\n await revoke(session.id);\n await list();\n }}\n >\n <Trash2 />\n {t.revoke}\n </Button>\n </div>\n ))}\n </div>\n )}\n </CardContent>\n </Card>\n )}\n </div>\n );\n}\n",
|
|
18
18
|
"type": "registry:component",
|
|
19
19
|
"target": "components/fa-auth/sessions-panel.tsx"
|
|
20
20
|
}
|
package/registry.json
CHANGED
|
@@ -152,6 +152,28 @@
|
|
|
152
152
|
"target": "components/fa-auth/admin-users-panel.tsx"
|
|
153
153
|
}
|
|
154
154
|
]
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
"name": "security-panel",
|
|
158
|
+
"type": "registry:component",
|
|
159
|
+
"title": "Account Security Panel",
|
|
160
|
+
"description": "fa-auth admin-tier privileged-action audit log on the canonical data-table plus the two superuser-only retention purges, each behind a confirmation naming the retention floor. Gated by the package's RequireRole (role hierarchy for the log, dual evidence for the purges) and driven by useAuditLog + useSecurityPurges. Requires @mano8/astro-auth-m8 installed.",
|
|
161
|
+
"dependencies": ["lucide-react", "@tanstack/react-table"],
|
|
162
|
+
"registryDependencies": [
|
|
163
|
+
"card",
|
|
164
|
+
"button",
|
|
165
|
+
"label",
|
|
166
|
+
"badge",
|
|
167
|
+
"./node_modules/@mano8/astro-ui-m8/registry/r/data-table.json",
|
|
168
|
+
"./account-crud.json"
|
|
169
|
+
],
|
|
170
|
+
"files": [
|
|
171
|
+
{
|
|
172
|
+
"path": "registry/blocks/account/security-panel.tsx",
|
|
173
|
+
"type": "registry:component",
|
|
174
|
+
"target": "components/fa-auth/security-panel.tsx"
|
|
175
|
+
}
|
|
176
|
+
]
|
|
155
177
|
}
|
|
156
178
|
]
|
|
157
179
|
}
|