Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(views): per-tab saved views on Security and Settings

Juan Denisaa0c51a09997
diff --git a/frontend/src/components/security/Fail2banTab.jsx b/frontend/src/components/security/Fail2banTab.jsx
index 3ed2b389..3118a031 100644
--- a/frontend/src/components/security/Fail2banTab.jsx
+++ b/frontend/src/components/security/Fail2banTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useMemo } from 'react';
import { Ban, Shield } from 'lucide-react';
import api from '../../services/api';
import { useToast } from '../../contexts/ToastContext';
@@ -8,11 +8,52 @@ import Modal from '../Modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
-import { DataTable, DataTableFooter, Pill } from '@/components/ds';
+import { DataTable, DataTableFooter, ListToolbar, Pill } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import { Select, SelectTrigger, SelectContent, SelectItem, SelectValue } from '@/components/ui/select';
+// Fail2ban's own default jail name since 0.9, and the one this tab's Ban modal
+// pre-selects — so it is the value a preset can actually count on being there.
+const SSH_JAIL = 'sshd';
+
+// Built-in saved views. A ban row is only { ip, jail }, so the jail is the one
+// axis worth slicing: SSH is where the internet-wide noise lands, and everything
+// else is a jail someone configured on purpose and should be reading.
+const FAIL2BAN_VIEWS = [
+ {
+ // The drive-by traffic. Usually the longest list on the page and the
+ // one you scan for a source you recognise rather than act on row by row.
+ name: 'SSH bans',
+ state: {
+ sorts: [{ key: 'ip', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'f2b1', field: 'jail', op: 'any', value: [SSH_JAIL] }],
+ },
+ },
+ },
+ {
+ // Everything the SSH view buries: web-auth, WordPress and per-app jails.
+ // A ban here means something reached an application, so it is the half
+ // worth reading first. Jail before IP, so each jail stays together.
+ name: 'App & web jail bans',
+ state: {
+ sorts: [{ key: 'jail', direction: 'asc' }, { key: 'ip', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'f2b2', field: 'jail', op: 'none', value: [SSH_JAIL] }],
+ },
+ },
+ },
+];
+
const Fail2banTab = () => {
const [status, setStatus] = useState(null);
const [bans, setBans] = useState([]);
@@ -110,11 +151,9 @@ const Fail2banTab = () => {
}
};
- if (loading) {
- return <div className="loading-sm">Loading Fail2ban status...</div>;
- }
-
// Cell markup/classNames identical to the hand-rolled table they replace.
+ // Declared above the loading guard now: the chrome below is a hook, so it
+ // cannot sit behind an early return.
const banColumns = [
{
key: 'ip',
@@ -129,6 +168,12 @@ const Fail2banTab = () => {
key: 'jail',
header: 'Jail',
sortable: true,
+ // Declared, not inferred: a host with two jails and two bans fails
+ // the enum cardinality test and would fall back to text, which
+ // turns the jail pick-list into a typed fragment and both views
+ // above into no-ops. `value` is what the rules read.
+ type: 'enum',
+ value: (ban) => ban.jail || '',
sortValue: (ban) => ban.jail || '',
render: (ban) => <span className="sk-tag">{ban.jail}</span>,
},
@@ -145,6 +190,33 @@ const Fail2banTab = () => {
},
];
+ // Scoped to this table, not to Security as a page: one tab is mounted at a
+ // time, so a picker at the page heading would sit above whichever tab
+ // happened to be open. No `urlScope` — the bans table is the only one on
+ // this tab, so its links keep the plain ?view= names.
+ const chrome = useTableChrome({
+ columns: banColumns,
+ rows: bans,
+ viewPageKey: 'security-fail2ban',
+ builtinViews: FAIL2BAN_VIEWS,
+ noun: 'bans',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
+ // DataTable applies the column rules itself, so the count has to be
+ // re-derived here or a view that narrows to two rows still claims the total.
+ const shownBans = useMemo(
+ () => applyFilters(bans, chrome.cfg.filters, chrome.columns),
+ [bans, chrome.cfg.filters, chrome.columns],
+ );
+
+ if (loading) {
+ return <div className="loading-sm">Loading Fail2ban status...</div>;
+ }
+
return (
<div className="fail2ban-tab">
{!status?.installed ? (
@@ -231,36 +303,57 @@ const Fail2banTab = () => {
</div>
)}
- <div className="card sec-flush">
- <div className="card-header">
- <h3>Banned IPs {bans.length > 0 && <span className="sec-count">· {bans.length}</span>}</h3>
+ {/* The view name replaces the old "Banned IPs" <h3>: it is
+ the same heading slot, and it now says WHICH bans you
+ are looking at rather than just that they are bans. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="bans"
+ total={`${shownBans.length} of ${bans.length} bans`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadData} />
+ </>
+ )}
+ />
+
+ <GridChips {...chrome.chipProps} />
+
+ {bans.length === 0 ? (
+ <div className="card">
+ <p className="text-muted">No IPs are currently banned.</p>
</div>
- {bans.length === 0 ? (
- <div className="card-body">
- <p className="text-muted">No IPs are currently banned.</p>
- </div>
- ) : (
+ ) : (
+ <div className="card sec-flush">
<DataTable
- columns={banColumns}
+ columns={chrome.columns}
data={bans}
keyField={(ban) => `${ban.ip}-${ban.jail}`}
sorts={sorts}
onSortsChange={setSorts}
- hiddenKeys={hiddenKeys}
- onHiddenKeysChange={setHiddenKeys}
+ {...chrome.tableProps}
footer={(
<DataTableFooter
- shown={bans.length}
+ shown={shownBans.length}
total={bans.length}
noun="banned IP"
/>
)}
/>
- )}
- </div>
+ </div>
+ )}
</>
)}
+ <GridFilterDrawer {...chrome.drawerProps} />
+
<Modal open={showBanModal} onClose={() => setShowBanModal(false)} title="Ban IP Address">
<div className="form-group">
<Label>IP Address</Label>
diff --git a/frontend/src/components/security/FirewallTab.jsx b/frontend/src/components/security/FirewallTab.jsx
index f557b16a..ddb13be7 100644
--- a/frontend/src/components/security/FirewallTab.jsx
+++ b/frontend/src/components/security/FirewallTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useMemo } from 'react';
import api from '../../services/api';
import { useToast } from '../../contexts/ToastContext';
import { useConfirm } from '@/hooks/useConfirm';
@@ -8,7 +8,11 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
-import { DataTable, DataTableFooter, Pill, SegControl } from '@/components/ds';
+import { DataTable, DataTableFooter, ListToolbar, Pill, SegControl } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import { Ban, Shield } from 'lucide-react';
@@ -20,6 +24,65 @@ const RULE_TYPE_TONES = {
rich: 'violet',
};
+// UFW and firewalld describe the same rule differently: firewalld splits a port
+// rule into `port` + `protocol`, while UFW hands back one printed target
+// ('8080/tcp') and no protocol field at all. Reading both here is what lets a
+// saved view mean the same thing whichever firewall the host runs — and stops
+// the Protocol column reading '-' on every UFW box.
+const ruleTarget = (rule) => rule.service || rule.port || rule.rule || '';
+const ruleProtocol = (rule) => (
+ rule.protocol || /\/(tcp|udp)\b/i.exec(String(ruleTarget(rule)))?.[1] || ''
+).toLowerCase();
+
+// Built-in saved views. Every rule matches a column's `value` accessor, so the
+// strings below are what the Protocol cell actually shows: 'tcp' / 'udp' for a
+// port opening on either firewall, and '' for a rule that opens no port at all.
+// The three partition the table on that one axis, because "what is reachable"
+// and "what is blocked or named" are the two questions this list answers.
+const FIREWALL_VIEWS = [
+ {
+ // The port surface, in target order: what this host answers on. A
+ // firewalld *service* rule (ssh, http) carries no protocol of its own,
+ // so it is deliberately absent here — it lands under the third view.
+ name: 'Port openings',
+ state: {
+ sorts: [{ key: 'target', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fw1', field: 'protocol', op: 'any', value: ['tcp', 'udp'] }],
+ },
+ },
+ },
+ {
+ // Short by design. UDP gets opened for DNS, WireGuard or QUIC and
+ // almost never by accident, so any row appearing here is worth reading.
+ name: 'UDP openings',
+ state: {
+ sorts: [{ key: 'target', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fw2', field: 'protocol', op: 'any', value: ['udp'] }],
+ },
+ },
+ },
+ {
+ // The half the two port views hide: firewalld services and rich
+ // drop/reject rules, UFW app profiles and address-scoped rules. An IP
+ // block lives here, so this is the list to read after an incident.
+ name: 'Service & rich rules',
+ state: {
+ sorts: [{ key: 'type', direction: 'asc' }, { key: 'target', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fw3', field: 'protocol', op: 'none', value: ['tcp', 'udp'] }],
+ },
+ },
+ },
+];
+
const FirewallTab = () => {
const [status, setStatus] = useState(null);
const [rules, setRules] = useState([]);
@@ -268,7 +331,7 @@ const FirewallTab = () => {
key: 'target',
header: 'Target',
sortable: true,
- sortValue: (rule) => rule.service || rule.port || rule.rule || '',
+ sortValue: ruleTarget,
cellClassName: 'sk-cell-mono',
render: (rule) => (
<>
@@ -282,9 +345,16 @@ const FirewallTab = () => {
key: 'protocol',
header: 'Protocol',
sortable: true,
- sortValue: (rule) => rule.protocol || '',
+ // Declared, not inferred: with only tcp/udp in play a short rule
+ // list fails the enum cardinality test and falls back to text,
+ // which turns the pick-list into a typed fragment and every view
+ // above into a no-op. `value` is what the rules read; `sortValue`
+ // is what the sorter reads, and they must agree.
+ type: 'enum',
+ value: ruleProtocol,
+ sortValue: ruleProtocol,
cellClassName: 'sk-cell-mono sec-proto',
- render: (rule) => rule.protocol || '-',
+ render: (rule) => ruleProtocol(rule) || '-',
},
{
key: 'actions',
@@ -301,6 +371,34 @@ const FirewallTab = () => {
},
];
+ // Saved views are scoped to THIS table, not to Security as a page: only one
+ // of the 13 tabs is mounted at a time, so a picker at the page heading would
+ // sit above whichever tab happened to be open. No `urlScope` either — the
+ // rules table is the only one on this tab, so its shareable links keep the
+ // plain ?view= names every single-table page produces.
+ //
+ // No `pageState`: the sub-tab strip below is navigation, not a filter, and a
+ // view that switched you to another sub-tab would hide the table it names.
+ const chrome = useTableChrome({
+ columns: ruleColumns,
+ rows: rules,
+ viewPageKey: 'security-firewall',
+ builtinViews: FIREWALL_VIEWS,
+ noun: 'rules',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
+ // The count has to be the count you can SEE. DataTable applies the column
+ // rules itself, so without re-applying them here a view that narrows to two
+ // rows would still claim the full total.
+ const shownRules = useMemo(
+ () => applyFilters(rules, chrome.cfg.filters, chrome.columns),
+ [rules, chrome.cfg.filters, chrome.columns],
+ );
+
if (loading) {
return <div className="loading-sm">Loading firewall status...</div>;
}
@@ -406,36 +504,56 @@ const FirewallTab = () => {
)}
{activeSubTab === 'rules' && (
- <div className="card sec-flush">
- <div className="card-header">
- <h3>Firewall Rules</h3>
- <div className="sec-tableactions">
- <Button variant="default" size="sm" onClick={() => setShowPortModal(true)}>Add Rule</Button>
- </div>
- </div>
+ <>
+ {/* The view name IS this section's heading — the old
+ "Firewall Rules" <h3> would title the same table
+ twice, and the segment above already says Rules. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="rules"
+ total={`${shownRules.length} of ${rules.length} rules`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadData} />
+ </>
+ )}
+ >
+ <Button variant="default" size="sm" onClick={() => setShowPortModal(true)}>Add Rule</Button>
+ </ListToolbar>
+
+ <GridChips {...chrome.chipProps} />
+
{rules.length === 0 ? (
- <div className="card-body">
+ <div className="card">
<p className="text-muted">No rules configured</p>
</div>
) : (
- <DataTable
- columns={ruleColumns}
- data={rules}
- keyField={(rule) => `${rule.type}-${rule.service || rule.port || rule.rule}-${rule.protocol || ''}`}
- sorts={sorts}
- onSortsChange={setSorts}
- hiddenKeys={hiddenKeys}
- onHiddenKeysChange={setHiddenKeys}
- footer={(
- <DataTableFooter
- shown={rules.length}
- total={rules.length}
- noun="rule"
- />
- )}
- />
+ <div className="card sec-flush">
+ <DataTable
+ columns={chrome.columns}
+ data={rules}
+ keyField={(rule) => `${rule.type}-${rule.service || rule.port || rule.rule}-${rule.protocol || ''}`}
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
+ footer={(
+ <DataTableFooter
+ shown={shownRules.length}
+ total={rules.length}
+ noun="rule"
+ />
+ )}
+ />
+ </div>
)}
- </div>
+ </>
)}
{activeSubTab === 'blocked' && (
@@ -540,6 +658,8 @@ const FirewallTab = () => {
</div>
)}
+ <GridFilterDrawer {...chrome.drawerProps} />
+
{/* Block IP Modal */}
<Modal open={showBlockIPModal} onClose={() => setShowBlockIPModal(false)} title="Block IP Address">
<div className="form-group">
diff --git a/frontend/src/components/security/IPListsTab.jsx b/frontend/src/components/security/IPListsTab.jsx
index 75166824..feaf3afd 100644
--- a/frontend/src/components/security/IPListsTab.jsx
+++ b/frontend/src/components/security/IPListsTab.jsx
@@ -7,9 +7,123 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { DataTable, DataTableFooter } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
+// Both lists have the same columns; only the accent tone and the remove
+// target differ, so one factory builds both. Two accessors per column on
+// purpose: `value` is what the column menu, the filter rules and the export
+// read (ds/grid/fields.js), `sortValue` is what DataTable orders by.
+const ipListColumns = (listType, tone, onRemove) => [
+ {
+ key: 'ip',
+ header: 'IP / CIDR',
+ sortable: true,
+ hideable: false,
+ type: 'text',
+ value: (item) => item.ip || '',
+ sortValue: (item) => item.ip || '',
+ cellClassName: `sk-cell-mono sec-ip--${tone}`,
+ render: (item) => item.ip,
+ },
+ {
+ key: 'comment',
+ header: 'Comment',
+ sortable: true,
+ type: 'text',
+ // Filters read the em dash the empty cell actually shows. That is what
+ // makes "needs a comment" expressible at all: a rule with an empty
+ // value is never armed (fields.js `ruleIsArmed`), so the obvious
+ // `comment is ""` would quietly match every row instead of none.
+ value: (item) => item.comment || '—',
+ // Ordering stays on the raw comment so undocumented entries sink to the
+ // bottom instead of clustering wherever an em dash happens to collate.
+ sortValue: (item) => item.comment || '',
+ render: (item) => item.comment || <span className="sec-dash">—</span>,
+ },
+ {
+ key: 'added',
+ header: 'Added',
+ sortable: true,
+ // Declared, not inferred: the sorter wants epoch ms, and letting that
+ // number type the column would offer "is under 1754…" instead of a date
+ // picker — and make any date rule match nothing.
+ type: 'date',
+ value: (item) => item.added_at || null,
+ sortValue: (item) => {
+ const t = new Date(item.added_at).getTime();
+ return Number.isNaN(t) ? null : t;
+ },
+ cellClassName: 'sk-cell-mono sec-faint',
+ render: (item) => new Date(item.added_at).toLocaleDateString(),
+ },
+ {
+ key: 'actions',
+ header: '',
+ sortable: false,
+ hideable: false,
+ cellClassName: 'sec-rowend',
+ render: (item) => (
+ <Button variant="destructive" size="sm" onClick={() => onRemove(item, listType)}>
+ Remove
+ </Button>
+ ),
+ },
+];
+
+// Built-in views. The two lists ask the same questions of the same columns, so
+// they share these definitions — but each list keeps its OWN saved-view bucket
+// (`viewPageKey`) and its own URL namespace (`urlScope`), so a view saved on
+// the allowlist never turns up on the blocklist.
+const NO_RULES = { match: 'all', rules: [] };
+
+const IP_LIST_VIEWS = [
+ {
+ // The hygiene worklist. An entry nobody explained is also one nobody
+ // dares remove; newest first, because those are the ones whose reason
+ // someone can still remember.
+ name: 'Needs a comment',
+ state: {
+ sorts: [{ key: 'added', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'ipc1', field: 'comment', op: 'is', value: '—' }],
+ },
+ },
+ },
+ {
+ // Sort only — what changed lately. The empty rule set is spelled out so
+ // switching here CLEARS whatever the previous view was filtering.
+ name: 'Newest first',
+ state: {
+ sorts: [{ key: 'added', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: NO_RULES,
+ },
+ },
+ {
+ // Ranges, not hosts: one /24 is 256 addresses, so a CIDR entry carries
+ // 256x the consequence of the line above it in either list.
+ name: 'Ranges (CIDR)',
+ state: {
+ sorts: [{ key: 'ip', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'ipr1', field: 'ip', op: 'contains', value: '/' }],
+ },
+ },
+ },
+];
+
const IPListsTab = () => {
const [lists, setLists] = useState({ allowlist: [], blocklist: [] });
const [loading, setLoading] = useState(true);
@@ -92,83 +206,91 @@ const IPListsTab = () => {
}
};
+ // Two tables on one route, so two chrome instances — called here at the top
+ // level in a fixed order, because renderList below is a plain function and
+ // a hook cannot live inside it. Each gets its own view bucket AND its own
+ // `urlScope`: the link params (`view`, `sort`, `hide`, `f`…) are global
+ // names, so unscoped the allowlist's sort would arrive as the blocklist's.
+ const allowChrome = useTableChrome({
+ columns: ipListColumns('allowlist', 'green', handleRemove),
+ rows: lists.allowlist,
+ viewPageKey: 'security-ip-allowlist',
+ urlScope: 'allowlist',
+ builtinViews: IP_LIST_VIEWS,
+ noun: 'entries',
+ sorts: allowSorts.sorts,
+ setSorts: allowSorts.setSorts,
+ hiddenKeys: allowCols.hiddenKeys,
+ setHiddenKeys: allowCols.setHiddenKeys,
+ });
+ const blockChrome = useTableChrome({
+ columns: ipListColumns('blocklist', 'red', handleRemove),
+ rows: lists.blocklist,
+ viewPageKey: 'security-ip-blocklist',
+ urlScope: 'blocklist',
+ builtinViews: IP_LIST_VIEWS,
+ noun: 'entries',
+ sorts: blockSorts.sorts,
+ setSorts: blockSorts.setSorts,
+ hiddenKeys: blockCols.hiddenKeys,
+ setHiddenKeys: blockCols.setHiddenKeys,
+ });
+
// Cell markup/classNames identical to the hand-rolled table they replace.
- const renderList = (title, listType, items, tone, sortState, colState) => {
- const columns = [
- {
- key: 'ip',
- header: 'IP / CIDR',
- sortable: true,
- hideable: false,
- sortValue: (item) => item.ip || '',
- cellClassName: `sk-cell-mono sec-ip--${tone}`,
- render: (item) => item.ip,
- },
- {
- key: 'comment',
- header: 'Comment',
- sortable: true,
- sortValue: (item) => item.comment || '',
- render: (item) => item.comment || <span className="sec-dash">—</span>,
- },
- {
- key: 'added',
- header: 'Added',
- sortable: true,
- sortValue: (item) => {
- const t = new Date(item.added_at).getTime();
- return Number.isNaN(t) ? null : t;
- },
- cellClassName: 'sk-cell-mono sec-faint',
- render: (item) => new Date(item.added_at).toLocaleDateString(),
- },
- {
- key: 'actions',
- header: '',
- sortable: false,
- hideable: false,
- cellClassName: 'sec-rowend',
- render: (item) => (
- <Button variant="destructive" size="sm" onClick={() => handleRemove(item, listType)}>
- Remove
- </Button>
- ),
- },
- ];
+ const renderList = (listType, items, sortState, chrome) => {
+ // DataTable applies the column rules itself, so mirror them here for
+ // the counts — a header that says "12 entries" above 3 filtered rows is
+ // the table lying about what you are looking at.
+ const shown = applyFilters(items, chrome.cfg.filters, chrome.columns);
return (
<div className="card sec-flush">
<div className="card-header">
- <h3 className={`sec-listtitle sec-listtitle--${tone}`}>
- {title} <span className="sec-count">· {items.length}</span>
- </h3>
+ {/* The view name IS the heading — there is no room for two
+ titles in a card this narrow. `label` keeps which list this
+ is inside that name, since the pair sits side by side and
+ used to be told apart by this line alone. */}
+ <GridViewPicker
+ views={chrome.views}
+ label={`${listType} entries`}
+ total={shown.length === items.length
+ ? `${items.length} entries`
+ : `${shown.length} of ${items.length} entries`}
+ onCreate={chrome.createView}
+ />
<div className="sec-tableactions">
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadLists} />
<Button variant="default" size="sm" onClick={() => setShowAddModal(listType)}>
- Add IP
+ Add to {listType}
</Button>
</div>
</div>
+ <GridChips {...chrome.chipProps} />
{items.length === 0 ? (
<div className="card-body">
<p className="text-muted">No IPs in {listType}.</p>
</div>
) : (
<DataTable
- columns={columns}
+ columns={chrome.columns}
data={items}
keyField={(item) => item.ip}
sorts={sortState.sorts}
onSortsChange={sortState.setSorts}
- hiddenKeys={colState.hiddenKeys}
- onHiddenKeysChange={colState.setHiddenKeys}
+ {...chrome.tableProps}
footer={(
<DataTableFooter
- shown={items.length}
+ shown={shown.length}
total={items.length}
noun="entry"
/>
)}
/>
)}
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};
@@ -180,8 +302,8 @@ const IPListsTab = () => {
return (
<div className="ip-lists-tab">
<div className="ip-lists-grid">
- {renderList('Allowlist', 'allowlist', lists.allowlist, 'green', allowSorts, allowCols)}
- {renderList('Blocklist', 'blocklist', lists.blocklist, 'red', blockSorts, blockCols)}
+ {renderList('allowlist', lists.allowlist, allowSorts, allowChrome)}
+ {renderList('blocklist', lists.blocklist, blockSorts, blockChrome)}
</div>
<Modal open={!!showAddModal} onClose={() => setShowAddModal(null)} title={`Add to ${showAddModal || ''}`}>
diff --git a/frontend/src/components/security/IntegrityTab.jsx b/frontend/src/components/security/IntegrityTab.jsx
index 34f50dc3..9446564c 100644
--- a/frontend/src/components/security/IntegrityTab.jsx
+++ b/frontend/src/components/security/IntegrityTab.jsx
@@ -1,8 +1,14 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import api from '../../services/api';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, DataTableFooter, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
+import { useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
// Scoped file-integrity monitoring: baseline-and-diff over the paths
// ServerKit manages (nginx configs, serverkit-owned systemd units, and
@@ -19,6 +25,10 @@ const SCOPE_META = {
},
};
+// Matches the service's own listing cap — a check that touched thousands of
+// files reports counts, not a scrollback.
+const MAX_LISTED_CHANGES = 200;
+
function formatAge(iso) {
if (!iso) return null;
const ms = Date.now() - new Date(iso).getTime();
@@ -36,6 +46,119 @@ function scopeLabel(scope) {
return scope.app_name ? `App: ${scope.app_name}` : `App #${scope.app_id}`;
}
+// A check result is three separate lists; the table is one. `tone` rides along
+// so each cell keeps the colour the hand-rolled table gave it.
+function toChangeRows(check) {
+ if (!check || !check.total_changes) return [];
+ return [
+ ...(check.added || []).map((p) => ({ kind: 'added', tone: 'green', path: p, what: null })),
+ ...(check.removed || []).map((p) => ({ kind: 'removed', tone: 'red', path: p, what: null })),
+ ...(check.modified || []).map((m) => ({
+ kind: 'modified', tone: 'amber', path: m.path, what: m.what,
+ })),
+ ];
+}
+
+// Cell markup/classNames identical to the hand-rolled table they replace. Two
+// accessors per column on purpose: `value` is what the column menu, the filter
+// rules and the export read, `sortValue` is what DataTable's sorter reads — it
+// has no fallback to `value`, so a sortable column needs both.
+const CHANGE_COLUMNS = [
+ {
+ key: 'change',
+ header: 'Change',
+ sortable: true,
+ // Declared, not inferred: a check that turned up a single change gives
+ // the inferrer one sample, which fails its "values repeat" test and
+ // types the column `text` — and then every preset that picks a kind
+ // matches zero rows on exactly the tables that are easiest to read.
+ type: 'enum',
+ enumOrder: ['added', 'removed', 'modified'],
+ value: (row) => row.kind,
+ sortValue: (row) => row.kind,
+ render: (row) => <span className={`sec-state sec-state--${row.tone}`}>{row.kind}</span>,
+ },
+ {
+ key: 'path',
+ header: 'Path',
+ sortable: true,
+ type: 'text',
+ value: (row) => row.path,
+ sortValue: (row) => row.path,
+ cellClassName: 'sk-cell-mono sec-path',
+ render: (row) => row.path,
+ },
+ {
+ key: 'what',
+ header: 'What changed',
+ // The service reports exactly hash | size | mode, in that order, and
+ // only for modified rows. Joined into one string so a rule can ask for
+ // "the bytes moved" (contains hash) or "only the bits moved"
+ // (is mode); added/removed rows carry nothing and read ''.
+ type: 'text',
+ value: (row) => (row.what || []).join(', '),
+ render: (row) => (
+ row.what ? (
+ <span className="sec-what">
+ {row.what.map((w) => (
+ <span key={w} className="sec-state sec-state--gray">{w}</span>
+ ))}
+ </span>
+ ) : (
+ <span className="sec-dash">—</span>
+ )
+ ),
+ },
+];
+
+// Built-in saved views. A check result is a pile of diffs of three very
+// different kinds, and the whole job of reading one is separating "something
+// touched the box" from "a deploy chmod'd a file".
+const INTEGRITY_VIEWS = [
+ {
+ // Nothing ServerKit does adds a file to sites-enabled or drops a unit
+ // in /etc/systemd/system without going through the panel, so a file
+ // appearing or vanishing is the loudest signal on this table.
+ name: 'Added or removed',
+ state: {
+ sorts: [{ key: 'path', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fi1', field: 'change', op: 'any', value: ['added', 'removed'] }],
+ },
+ },
+ },
+ {
+ // The bytes moved. A size- or mode-only diff is not tampering; a
+ // changed sha256 on a managed config is the thing you came here for.
+ name: 'Content changed',
+ state: {
+ sorts: [{ key: 'path', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fi2', field: 'what', op: 'contains', value: 'hash' }],
+ },
+ },
+ },
+ {
+ // Permission bits moved and the content did not — nearly always a
+ // chmod from a deploy or a hand-run command, so it triages apart from
+ // the content diffs. `is` rather than `contains`: a row whose hash
+ // moved as well belongs in the view above, not here.
+ name: 'Permissions only',
+ state: {
+ sorts: [{ key: 'path', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fi3', field: 'what', op: 'is', value: 'mode' }],
+ },
+ },
+ },
+];
+
const IntegrityTab = () => {
const [status, setStatus] = useState(null);
const [apps, setApps] = useState([]);
@@ -44,6 +167,16 @@ const IntegrityTab = () => {
const [message, setMessage] = useState(null);
const [expanded, setExpanded] = useState(null); // scope whose changes table is open
+ // Lifted out of <DataTable storageKey> so the chrome can capture and
+ // restore them. The keys keep DataTable's own `-sort` / `-cols` suffixes so
+ // a sort or a hidden column persisted by an earlier build still loads.
+ const { sorts, setSorts } = useTableSort({
+ storageKey: 'serverkit-table-integrity-changes-sort',
+ });
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
+ storageKey: 'serverkit-table-integrity-changes-cols',
+ });
+
const load = useCallback(async () => {
try {
const data = await api.request('/security/fim');
@@ -106,74 +239,50 @@ const IntegrityTab = () => {
const scopes = status?.scopes || [];
const optins = status?.app_optins || [];
- function renderChanges(scope) {
- const check = scope.last_check;
- if (!check || check.total_changes === 0 || expanded !== scope.scope) return null;
- const rows = [
- ...(check.added || []).map((p) => ({ kind: 'added', tone: 'green', path: p, what: null })),
- ...(check.removed || []).map((p) => ({ kind: 'removed', tone: 'red', path: p, what: null })),
- ...(check.modified || []).map((m) => ({
- kind: 'modified', tone: 'amber', path: m.path, what: m.what,
- })),
- ];
- const shown = rows.slice(0, 200);
- // Cell markup/classNames identical to the hand-rolled table they
- // replace. The old "… and N more" truncation row is now the standard
- // DataTableFooter count ("Shown 200 of N changes").
- const columns = [
- {
- key: 'change',
- header: 'Change',
- sortable: true,
- sortValue: (row) => row.kind,
- render: (row) => <span className={`sec-state sec-state--${row.tone}`}>{row.kind}</span>,
- },
- {
- key: 'path',
- header: 'Path',
- sortable: true,
- sortValue: (row) => row.path,
- cellClassName: 'sk-cell-mono sec-path',
- render: (row) => row.path,
- },
- {
- key: 'what',
- header: 'What changed',
- render: (row) => (
- row.what ? (
- <span className="sec-what">
- {row.what.map((w) => (
- <span key={w} className="sec-state sec-state--gray">{w}</span>
- ))}
- </span>
- ) : (
- <span className="sec-dash">—</span>
- )
- ),
- },
- ];
- return (
- <DataTable
- columns={columns}
- data={shown}
- keyField={(row) => `${row.kind}:${row.path}`}
- storageKey="serverkit-table-integrity-changes"
- footer={(
- <DataTableFooter
- shown={shown.length}
- total={rows.length}
- noun="change"
- />
- )}
- />
- );
- }
+ // `expanded` holds ONE scope key, so at most one changes table is mounted —
+ // which is why this tab has a single chrome instance and passes no
+ // urlScope: there is no second table to fight it over ?view= / ?sort=.
+ const openScope = scopes.find((s) => s.scope === expanded) || null;
+ const changeRows = useMemo(() => toChangeRows(openScope?.last_check), [openScope]);
+ const shownRows = useMemo(
+ () => changeRows.slice(0, MAX_LISTED_CHANGES),
+ [changeRows],
+ );
+
+ // No `pageState`: a check result is whatever the last run produced, and the
+ // tab owns no search or filter of its own, so there is nothing
+ // page-private for a saved view to carry.
+ const chrome = useTableChrome({
+ columns: CHANGE_COLUMNS,
+ rows: shownRows,
+ viewPageKey: 'security-integrity',
+ builtinViews: INTEGRITY_VIEWS,
+ noun: 'changes',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
+ // DataTable applies the column rules itself, so the tab re-runs them to say
+ // how many rows survived them.
+ const shownCount = useMemo(
+ () => applyFilters(shownRows, chrome.cfg.filters, chrome.columns).length,
+ [shownRows, chrome.cfg.filters, chrome.columns],
+ );
+
+ const countLabel = shownCount === changeRows.length
+ ? `${changeRows.length} change${changeRows.length === 1 ? '' : 's'}`
+ : `${shownCount} of ${changeRows.length} changes`;
function renderScopeCard(scope) {
const key = scope.scope;
const baseline = scope.baseline;
const check = scope.last_check;
const changed = check && check.total_changes > 0;
+ // Same guard the old renderChanges() applied: a scope with nothing to
+ // show never opens, even if it is the expanded one.
+ const isOpen = expanded === key && changeRows.length > 0;
return (
<div className="card sec-flush" key={key}>
<div className="card-header">
@@ -197,7 +306,20 @@ const IntegrityTab = () => {
: 'No baseline yet — create one to start tracking changes.'}
{check && ` · Last check ${formatAge(check.checked_at) || ''}`}
</p>
- <div className="card-actions">
+ {/* The scope's own actions share the toolbar with the
+ table's controls, so opening the changes list does not
+ grow a second row of buttons. */}
+ <ListToolbar
+ tools={isOpen ? (
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
+ </>
+ ) : null}
+ >
<Button
variant="outline"
size="sm"
@@ -233,9 +355,38 @@ const IntegrityTab = () => {
</Button>
</>
)}
- </div>
+ </ListToolbar>
+ {/* The view name is the changes table's heading — the card's
+ own h3 names the SCOPE, which is a different thing. */}
+ {isOpen && (
+ <>
+ <GridViewPicker
+ views={chrome.views}
+ label="changes"
+ total={countLabel}
+ onCreate={chrome.createView}
+ />
+ <GridChips {...chrome.chipProps} />
+ </>
+ )}
</div>
- {renderChanges(scope)}
+ {isOpen && (
+ <DataTable
+ columns={chrome.columns}
+ data={shownRows}
+ keyField={(row) => `${row.kind}:${row.path}`}
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
+ footer={(
+ <DataTableFooter
+ shown={shownCount}
+ total={changeRows.length}
+ noun="change"
+ />
+ )}
+ />
+ )}
</div>
);
}
@@ -291,6 +442,8 @@ const IntegrityTab = () => {
)}
</div>
</div>
+
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};
diff --git a/frontend/src/components/security/QuarantineTab.jsx b/frontend/src/components/security/QuarantineTab.jsx
index 07454e63..5ebeebe8 100644
--- a/frontend/src/components/security/QuarantineTab.jsx
+++ b/frontend/src/components/security/QuarantineTab.jsx
@@ -1,13 +1,64 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useMemo } from 'react';
import { ShieldCheck } from 'lucide-react';
import api from '../../services/api';
import EmptyState from '@/components/EmptyState';
import { Button } from '@/components/ui/button';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, DataTableFooter, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import { formatBytes } from '@/utils/formatBytes';
+// Built-in saved views. Three, because the quarantine list only ever answers
+// three questions: what did the last scan catch, what is filling the
+// quarantine directory, and which of these can still be put back.
+//
+// Every rule matches a column's `value` accessor (ds/grid/fields.js), never
+// `sortValue` — see the `quarantined` column for why that distinction bites.
+const NO_RULES = { match: 'all', rules: [] };
+
+const QUARANTINE_VIEWS = [
+ {
+ // The landing view: quarantine is an event log, so the newest catch is
+ // the one nobody has looked at yet.
+ name: 'Newest first',
+ state: {
+ sorts: [{ key: 'quarantined', direction: 'desc' }],
+ hiddenKeys: [],
+ columnFilters: NO_RULES,
+ },
+ },
+ {
+ // Nothing ages out of quarantine on its own, so this is the view you
+ // open when the partition holding it starts to fill.
+ name: 'Largest first',
+ state: {
+ sorts: [{ key: 'size', direction: 'desc' }],
+ hiddenKeys: [],
+ columnFilters: NO_RULES,
+ },
+ },
+ {
+ // Restore needs the sidecar that recorded where the file came from —
+ // without it the Restore button is dead and delete is the only move.
+ // The rule is "an absolute path was recorded": the quarantine service
+ // writes os.path.abspath(), and a row with no sidecar reads '', which
+ // starts with nothing.
+ name: 'Restorable',
+ state: {
+ sorts: [{ key: 'quarantined', direction: 'desc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'qr1', field: 'original', op: 'starts', value: '/' }],
+ },
+ },
+ },
+];
+
const QuarantineTab = () => {
const [files, setFiles] = useState([]);
const [loading, setLoading] = useState(true);
@@ -58,12 +109,17 @@ const QuarantineTab = () => {
}
// Cell markup/classNames identical to the hand-rolled table they replace.
+ // Two accessors per column on purpose: `value` is what the column menu, the
+ // filter rules and the export read, `sortValue` is what DataTable's sorter
+ // reads — it has no fallback to `value`, so a column needs both.
const columns = [
{
key: 'filename',
header: 'Filename',
sortable: true,
hideable: false,
+ type: 'text',
+ value: (file) => file.name || '',
sortValue: (file) => file.name || '',
cellClassName: 'sk-cell-mono sec-path sec-path--red',
render: (file) => file.name,
@@ -72,6 +128,11 @@ const QuarantineTab = () => {
key: 'original',
header: 'Original Location',
sortable: true,
+ type: 'text',
+ // '' rather than null when the sidecar is missing: the Restorable
+ // view asks whether the recorded path is absolute, and a null would
+ // make that rule compare against the string "null".
+ value: (file) => file.original_path || '',
sortValue: (file) => file.original_path || '',
cellClassName: 'sk-cell-mono sec-path sec-faint',
render: (file) => (
@@ -84,6 +145,8 @@ const QuarantineTab = () => {
key: 'size',
header: 'Size',
sortable: true,
+ type: 'num',
+ value: (file) => (file.size == null ? null : Number(file.size)),
sortValue: (file) => (file.size == null ? null : Number(file.size)),
cellClassName: 'sk-cell-mono',
render: (file) => formatBytes(file.size, { defaultValue: '0 B' }),
@@ -92,6 +155,11 @@ const QuarantineTab = () => {
key: 'quarantined',
header: 'Quarantined',
sortable: true,
+ // Declared, not inferred: the sorter wants epoch ms, and letting
+ // that number type the column would offer "is under 1754…" instead
+ // of a date picker — and make any date rule match nothing.
+ type: 'date',
+ value: (file) => file.quarantined_at || null,
sortValue: (file) => {
const t = new Date(file.quarantined_at).getTime();
return Number.isNaN(t) ? null : t;
@@ -127,6 +195,35 @@ const QuarantineTab = () => {
},
];
+ // No `pageState`: the endpoint returns the whole quarantine directory
+ // unpaginated, and the tab owns no search or server-side filter of its own,
+ // so there is nothing page-private for a saved view to carry.
+ const chrome = useTableChrome({
+ columns,
+ rows: files,
+ viewPageKey: 'security-quarantine',
+ builtinViews: QUARANTINE_VIEWS,
+ noun: 'files',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
+ // DataTable applies the column rules itself, so the tab has to re-run them
+ // to say how many rows survived. Cheap — the list is a directory listing.
+ const shownCount = useMemo(
+ () => applyFilters(files, chrome.cfg.filters, chrome.columns).length,
+ [files, chrome.cfg.filters, chrome.columns],
+ );
+
+ // Null while the fetch is in flight: an empty `files` is "not known yet",
+ // and "0 files" is a claim.
+ const countLabel = loading ? null
+ : shownCount === files.length
+ ? `${files.length} file${files.length === 1 ? '' : 's'}`
+ : `${shownCount} of ${files.length} files`;
+
return (
<div className="quarantine-tab">
{message && (
@@ -135,44 +232,56 @@ const QuarantineTab = () => {
</div>
)}
- <div className="card sec-flush">
- <div className="card-header">
- <h3>Quarantined Files {!loading && files.length > 0 && <span className="sec-count">· {files.length}</span>}</h3>
- <div className="sec-tableactions">
- <Button variant="outline" size="sm" onClick={loadFiles}>Refresh</Button>
- </div>
- </div>
- {loading ? (
- <div className="card-body">
- <div className="loading-sm">Loading...</div>
- </div>
- ) : files.length === 0 ? (
- <div className="card-body">
- <EmptyState
- icon={ShieldCheck}
- title="No files in quarantine"
- description="Infected files will appear here when detected"
+ {/* The view name replaces the old "Quarantined Files · N" eyebrow:
+ the view IS what you are looking at, and two titles stacked read
+ as two sections. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="files"
+ total={countLabel}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
/>
- </div>
- ) : (
- <DataTable
- columns={columns}
- data={files}
- keyField="name"
- sorts={sorts}
- onSortsChange={setSorts}
- hiddenKeys={hiddenKeys}
- onHiddenKeysChange={setHiddenKeys}
- footer={(
- <DataTableFooter
- shown={files.length}
- total={files.length}
- noun="file"
- />
- )}
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadFiles} />
+ </>
+ )}
+ >
+ <Button variant="outline" size="sm" onClick={loadFiles}>Refresh</Button>
+ </ListToolbar>
+
+ <GridChips {...chrome.chipProps} />
+
+ <DataTable
+ loading={loading}
+ columns={chrome.columns}
+ data={files}
+ keyField="name"
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
+ emptyState={(
+ <EmptyState
+ icon={ShieldCheck}
+ title="No files in quarantine"
+ description="Infected files will appear here when detected"
+ />
+ )}
+ footer={(
+ <DataTableFooter
+ shown={shownCount}
+ total={files.length}
+ noun="file"
/>
)}
- </div>
+ />
+
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};
diff --git a/frontend/src/components/security/SSHKeysTab.jsx b/frontend/src/components/security/SSHKeysTab.jsx
index b8a19663..a9ec9402 100644
--- a/frontend/src/components/security/SSHKeysTab.jsx
+++ b/frontend/src/components/security/SSHKeysTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useMemo } from 'react';
import { KeyRound } from 'lucide-react';
import api from '../../services/api';
import { useToast } from '../../contexts/ToastContext';
@@ -8,10 +8,56 @@ import Modal from '../Modal';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, DataTableFooter, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
+// What the Comment cell renders when a key carries none. It has to be a real
+// value, not '': `ruleIsArmed` drops any rule whose value is empty, so
+// "comment is ''" would silently filter nothing at all. Filtering on the same
+// dash the cell shows keeps the rule and the row telling the same story.
+const NO_COMMENT = '—';
+
+// The modern default. Everything else in authorized_keys — ssh-rsa, ssh-dss,
+// the ecdsa-sha2-* family — is a key someone generated years ago.
+const MODERN_KEY_TYPE = 'ssh-ed25519';
+
+// Built-in saved views. Both are hygiene worklists rather than slices: an
+// authorized_keys file you can fully account for shows nothing under either,
+// which is exactly the answer they exist to give.
+const SSH_KEY_VIEWS = [
+ {
+ // A key you cannot attribute to a person is a key you cannot safely
+ // remove — and the one most likely to outlive whoever added it.
+ name: 'Unlabelled keys',
+ state: {
+ sorts: [{ key: 'type', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'sk1', field: 'comment', op: 'is', value: NO_COMMENT }],
+ },
+ },
+ },
+ {
+ // The rotation list, stated as "not ed25519" rather than as a list of
+ // legacy names, so a type we have never seen still shows up here.
+ name: 'Legacy key types',
+ state: {
+ sorts: [{ key: 'type', direction: 'asc' }, { key: 'comment', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'sk2', field: 'type', op: 'none', value: [MODERN_KEY_TYPE] }],
+ },
+ },
+ },
+];
+
const SSHKeysTab = () => {
const [keys, setKeys] = useState([]);
const [loading, setLoading] = useState(true);
@@ -80,6 +126,12 @@ const SSHKeysTab = () => {
key: 'type',
header: 'Type',
sortable: true,
+ // Declared, not inferred: two keys of two types fail the enum
+ // cardinality test and would fall back to text, which turns the
+ // pick-list into a typed fragment and "Legacy key types" into a
+ // no-op. `value` is what the rules read.
+ type: 'enum',
+ value: (key) => key.type || '',
sortValue: (key) => key.type || '',
render: (key) => <span className="sk-tag">{key.type}</span>,
},
@@ -96,8 +148,15 @@ const SSHKeysTab = () => {
key: 'comment',
header: 'Comment',
sortable: true,
+ // Text, never enum: on a box with three unlabelled keys the
+ // inference would see one repeated value and offer a checklist.
+ // `value` substitutes the dash the cell shows so the unlabelled
+ // rows are addressable; `sortValue` keeps returning '' so the
+ // ordering users already have persisted does not shift.
+ type: 'text',
+ value: (key) => key.comment || NO_COMMENT,
sortValue: (key) => key.comment || '',
- render: (key) => key.comment || <span className="sec-dash">—</span>,
+ render: (key) => key.comment || <span className="sec-dash">{NO_COMMENT}</span>,
},
{
key: 'actions',
@@ -112,55 +171,100 @@ const SSHKeysTab = () => {
},
];
+ // Scoped to this table, not to Security as a page: one tab is mounted at a
+ // time, so a picker at the page heading would sit above whichever tab
+ // happened to be open. No `urlScope` — the keys table is the only one on
+ // this tab, so its links keep the plain ?view= names.
+ const chrome = useTableChrome({
+ columns,
+ rows: keys,
+ viewPageKey: 'security-ssh-keys',
+ builtinViews: SSH_KEY_VIEWS,
+ noun: 'keys',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
+ // DataTable applies the column rules itself, so the count has to be
+ // re-derived here or a view that narrows to one key still claims the total.
+ const shownKeys = useMemo(
+ () => applyFilters(keys, chrome.cfg.filters, chrome.columns),
+ [keys, chrome.cfg.filters, chrome.columns],
+ );
+
return (
<div className="ssh-keys-tab">
- <div className="card sec-flush">
- <div className="card-header">
- <h3>SSH Authorized Keys {!loading && keys.length > 0 && <span className="sec-count">· {keys.length}</span>}</h3>
- <div className="card-actions">
- <Button variant="default" size="sm" onClick={() => setShowAddModal(true)}>
- Add Key
- </Button>
- <Button variant="outline" size="sm" onClick={loadKeys}>
- Refresh
- </Button>
- </div>
- </div>
- {loading ? (
- <div className="card-body">
- <div className="loading-sm">Loading...</div>
- </div>
- ) : keys.length === 0 ? (
- <div className="card-body">
- <EmptyState
- icon={KeyRound}
- title="No SSH keys configured for root user."
- action={(
- <Button variant="default" onClick={() => setShowAddModal(true)}>
- Add SSH Key
- </Button>
- )}
+ {/* The view name replaces the old "SSH Authorized Keys" <h3>: one
+ heading, and it now names the slice you are looking at. Add Key
+ and Refresh stay put — they are actions, not filters. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="keys"
+ // Null while the read is in flight: an empty `keys` means "not
+ // known yet", and "0 of 0 keys" would be a claim.
+ total={loading ? null : `${shownKeys.length} of ${keys.length} keys`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
/>
- </div>
- ) : (
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadKeys} />
+ </>
+ )}
+ >
+ <Button variant="default" size="sm" onClick={() => setShowAddModal(true)}>
+ Add Key
+ </Button>
+ <Button variant="outline" size="sm" onClick={loadKeys}>
+ Refresh
+ </Button>
+ </ListToolbar>
+
+ <GridChips {...chrome.chipProps} />
+
+ {loading ? (
+ <div className="card">
+ <div className="loading-sm">Loading...</div>
+ </div>
+ ) : keys.length === 0 ? (
+ <div className="card">
+ <EmptyState
+ icon={KeyRound}
+ title="No SSH keys configured for root user."
+ action={(
+ <Button variant="default" onClick={() => setShowAddModal(true)}>
+ Add SSH Key
+ </Button>
+ )}
+ />
+ </div>
+ ) : (
+ <div className="card sec-flush">
<DataTable
- columns={columns}
+ columns={chrome.columns}
data={keys}
keyField="id"
sorts={sorts}
onSortsChange={setSorts}
- hiddenKeys={hiddenKeys}
- onHiddenKeysChange={setHiddenKeys}
+ {...chrome.tableProps}
footer={(
<DataTableFooter
- shown={keys.length}
+ shown={shownKeys.length}
total={keys.length}
noun="key"
/>
)}
/>
- )}
- </div>
+ </div>
+ )}
+
+ <GridFilterDrawer {...chrome.drawerProps} />
<Modal open={showAddModal} onClose={() => setShowAddModal(false)} title="Add SSH Public Key" size="lg">
<div className="form-group">
diff --git a/frontend/src/components/security/ScannerTab.jsx b/frontend/src/components/security/ScannerTab.jsx
index 75a14833..8be899ea 100644
--- a/frontend/src/components/security/ScannerTab.jsx
+++ b/frontend/src/components/security/ScannerTab.jsx
@@ -3,9 +3,13 @@ import api from '../../services/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DataTable, DataTableFooter, Pill } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer, applyFilters,
+} from '@/components/ds/grid';
import { useTableSort } from '@/hooks/useTableSort';
import { useColumnVisibility } from '@/hooks/useColumnVisibility';
-import { Zap, Radar, FolderSearch, Download, Box, ShieldAlert, FileCode2, Trash2, Search } from 'lucide-react';
+import { Zap, Radar, FolderSearch, Download, Box, FileCode2, Trash2, Search } from 'lucide-react';
import EmptyState from '@/components/EmptyState';
const SEVERITY_TONE = {
@@ -15,6 +19,108 @@ const SEVERITY_TONE = {
low: 'gray',
};
+// Urgency order for the Severity column. The severity strings sort
+// alphabetically — critical, high, low, medium — which files "low" above
+// "medium" and puts the wrong finding on top of a triage list.
+const SEVERITY_RANK = { critical: 0, high: 1, medium: 2, low: 3 };
+
+const NO_RULES = { match: 'all', rules: [] };
+
+// Built-in views for the findings table. Every rule matches a column's `value`
+// accessor, which for Severity and Source is the raw scanner word the cell
+// renders — never the rank the table sorts by.
+const FINDING_VIEWS = [
+ {
+ // The triage default: worst first. Sort only, and the empty rule set is
+ // spelled out so switching here clears the previous view's filters.
+ name: 'Worst first',
+ state: {
+ sorts: [{ key: 'severity', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: NO_RULES,
+ },
+ },
+ {
+ // What you act on before closing the tab. 'medium' is deliberately out:
+ // the curated rules emit it as their default, so it is the bucket an
+ // unclassified match lands in rather than a judgement about the file.
+ name: 'Critical & high',
+ state: {
+ sorts: [{ key: 'severity', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fs1', field: 'severity', op: 'any', value: ['critical', 'high'] }],
+ },
+ },
+ },
+ {
+ // The curated web-shell pass on its own — a backdoor in a docroot, not
+ // a known-malware signature. Grouped by file through the sort, because
+ // one shell usually trips several rules and you quarantine the FILE.
+ name: 'Web-shell hits',
+ state: {
+ sorts: [{ key: 'file', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'fw1', field: 'source', op: 'any', value: ['yara'] }],
+ },
+ },
+ },
+];
+
+// Built-in views for the scan-history table.
+const HISTORY_VIEWS = [
+ {
+ name: 'Newest first',
+ state: {
+ sorts: [{ key: 'date', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: NO_RULES,
+ },
+ },
+ {
+ // Scans that actually found something — the audit trail you re-read
+ // after an incident. A scan with no infected list reads 0 threats, so
+ // `over 0` can only ever be a real hit.
+ name: 'Threats found',
+ state: {
+ sorts: [{ key: 'date', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'hs1', field: 'threats', op: 'gt', value: 0 }],
+ },
+ },
+ },
+ {
+ // A scan that never finished proves nothing about the directory it was
+ // pointed at — 'completed with 0 threats' and 'timed out' look equally
+ // green from a distance, and only one of them is an answer.
+ name: 'Did not finish',
+ state: {
+ sorts: [{ key: 'date', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{
+ id: 'hf1',
+ field: 'status',
+ op: 'any',
+ value: ['error', 'timeout', 'cancelled'],
+ }],
+ },
+ },
+ },
+];
+
const ScannerTab = () => {
const [scanStatus, setScanStatus] = useState({ status: 'idle' });
const [scanPath, setScanPath] = useState('/var/www');
@@ -243,6 +349,8 @@ const ScannerTab = () => {
header: 'Rule',
sortable: true,
hideable: false,
+ type: 'text',
+ value: (f) => f.rule || '',
sortValue: (f) => f.rule || '',
cellClassName: 'sk-cell-mono',
render: (f) => <span title={f.description}>{f.rule}</span>,
@@ -251,7 +359,14 @@ const ScannerTab = () => {
key: 'severity',
header: 'Severity',
sortable: true,
- sortValue: (f) => f.severity || '',
+ type: 'enum',
+ // Both accessors spelled out: `value` is the word a rule matches,
+ // `sortValue` is the urgency rank the table orders by. A numeric
+ // sortValue on its own would type the column `num`, and every
+ // severity preset would then match exactly zero rows.
+ value: (f) => f.severity || 'unknown',
+ sortValue: (f) => SEVERITY_RANK[f.severity] ?? 9,
+ enumOrder: ['critical', 'high', 'medium', 'low'],
render: (f) => (
<span className={`sec-state sec-state--${SEVERITY_TONE[f.severity] || 'gray'}`}>
{f.severity}
@@ -262,6 +377,8 @@ const ScannerTab = () => {
key: 'file',
header: 'File',
sortable: true,
+ type: 'text',
+ value: (f) => f.file || '',
sortValue: (f) => f.file || '',
cellClassName: 'sk-cell-mono sec-path sec-path--red',
render: (f) => <span title={f.file}>{f.file}</span>,
@@ -269,6 +386,11 @@ const ScannerTab = () => {
{
key: 'match',
header: 'Match',
+ // The row field is `matched`, not `match`, so without an accessor
+ // the column has nothing behind it: no filter, and an export column
+ // of empty strings.
+ type: 'text',
+ value: (f) => f.matched || '',
cellClassName: 'sk-cell-mono scan-snippet',
render: (f) => f.matched || '—',
},
@@ -276,7 +398,10 @@ const ScannerTab = () => {
key: 'source',
header: 'Source',
sortable: true,
+ type: 'enum',
+ value: (f) => f.source || 'unknown',
sortValue: (f) => f.source || '',
+ enumOrder: ['yara', 'clamav'],
render: (f) => <span className="sec-state sec-state--gray">{f.source}</span>,
},
{
@@ -304,6 +429,11 @@ const ScannerTab = () => {
header: 'Date',
sortable: true,
hideable: false,
+ // Declared, not inferred: the sorter wants epoch ms, and letting
+ // that number type the column would offer "is under 1754…" instead
+ // of a date picker — and make any date rule match nothing.
+ type: 'date',
+ value: (scan) => scan.started_at || null,
sortValue: (scan) => {
const t = new Date(scan.started_at).getTime();
return Number.isNaN(t) ? null : t;
@@ -323,7 +453,10 @@ const ScannerTab = () => {
key: 'status',
header: 'Status',
sortable: true,
+ type: 'enum',
+ value: (scan) => scan.status || 'unknown',
sortValue: (scan) => scan.status || '',
+ enumOrder: ['completed', 'running', 'error', 'timeout', 'cancelled'],
render: (scan) => (
<Pill kind={scan.status === 'completed' ? 'green' : scan.status === 'error' ? 'red' : 'amber'}>
{scan.status}
@@ -334,6 +467,11 @@ const ScannerTab = () => {
key: 'threats',
header: 'Threats',
sortable: true,
+ type: 'num',
+ // A scan with no infected list reads 0 rather than blank, so the
+ // "over 0" preset can only ever be a real hit — a scan that failed
+ // before it wrote a list can never look like a clean one.
+ value: (scan) => scan.infected_files?.length ?? 0,
sortValue: (scan) => scan.infected_files?.length ?? 0,
render: (scan) => (
scan.infected_files?.length > 0 ? (
@@ -345,6 +483,41 @@ const ScannerTab = () => {
},
];
+ // Two tables on one route, so two chrome instances — each with its own view
+ // bucket AND its own `urlScope`. The link params (`view`, `sort`, `hide`,
+ // `f`…) are global names: unscoped, the findings table's sort would arrive
+ // as the history table's and each would overwrite the other's ?view=.
+ const findingsChrome = useTableChrome({
+ columns: findingColumns,
+ rows: findings,
+ viewPageKey: 'security-scanner-findings',
+ urlScope: 'findings',
+ builtinViews: FINDING_VIEWS,
+ noun: 'findings',
+ sorts: findingsSorts.sorts,
+ setSorts: findingsSorts.setSorts,
+ hiddenKeys: findingsCols.hiddenKeys,
+ setHiddenKeys: findingsCols.setHiddenKeys,
+ });
+ const historyChrome = useTableChrome({
+ columns: historyColumns,
+ rows: history,
+ viewPageKey: 'security-scan-history',
+ urlScope: 'history',
+ builtinViews: HISTORY_VIEWS,
+ noun: 'scans',
+ sorts: historySorts.sorts,
+ setSorts: historySorts.setSorts,
+ hiddenKeys: historyCols.hiddenKeys,
+ setHiddenKeys: historyCols.setHiddenKeys,
+ });
+
+ // The tables filter internally, so mirror the rules here for the counts —
+ // a header claiming "12 findings" above 3 filtered rows is the table lying
+ // about what you are looking at.
+ const shownFindings = applyFilters(findings, findingsChrome.cfg.filters, findingsChrome.columns);
+ const shownHistory = applyFilters(history, historyChrome.cfg.filters, historyChrome.columns);
+
return (
<div className="scanner-tab">
{message && (
@@ -539,40 +712,67 @@ const ScannerTab = () => {
{findings.length > 0 && (
<div className="card sec-flush scan-findings">
<div className="card-header">
- <h3 className="sec-listtitle--red">
- <ShieldAlert size={13} />
- Findings <span className="sec-count">· {findings.length}</span>
- </h3>
+ {/* The view name replaces the section heading — two
+ titles stacked would compete, and the view IS what
+ you are looking at. The card keeps its red border,
+ so the alarm does not depend on the words. */}
+ <GridViewPicker
+ views={findingsChrome.views}
+ label="findings"
+ total={shownFindings.length === findings.length
+ ? `${findings.length} findings`
+ : `${shownFindings.length} of ${findings.length} findings`}
+ onCreate={findingsChrome.createView}
+ />
<div className="sec-tableactions">
+ <GridFilterButton
+ count={findingsChrome.filterCount}
+ onClick={() => findingsChrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...findingsChrome.toolsProps} onRefresh={loadScanStatus} />
<Button variant="outline" size="sm" onClick={() => setFindings([])}>Dismiss</Button>
</div>
</div>
+ <GridChips {...findingsChrome.chipProps} />
<DataTable
- columns={findingColumns}
+ columns={findingsChrome.columns}
data={findings}
keyField={(f) => `${f.file}-${f.rule}-${f.source}`}
sorts={findingsSorts.sorts}
onSortsChange={findingsSorts.setSorts}
- hiddenKeys={findingsCols.hiddenKeys}
- onHiddenKeysChange={findingsCols.setHiddenKeys}
+ {...findingsChrome.tableProps}
footer={(
<DataTableFooter
- shown={findings.length}
+ shown={shownFindings.length}
total={findings.length}
noun="finding"
/>
)}
/>
+ <GridFilterDrawer {...findingsChrome.drawerProps} />
</div>
)}
<div className="card sec-flush">
<div className="card-header">
- <h3>Scan History</h3>
+ <GridViewPicker
+ views={historyChrome.views}
+ label="scans"
+ total={shownHistory.length === history.length
+ ? `${history.length} scans`
+ : `${shownHistory.length} of ${history.length} scans`}
+ onCreate={historyChrome.createView}
+ />
<div className="sec-tableactions">
+ <GridFilterButton
+ count={historyChrome.filterCount}
+ onClick={() => historyChrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...historyChrome.toolsProps} onRefresh={loadHistory} />
<Button variant="outline" size="sm" onClick={loadHistory}>Refresh</Button>
</div>
</div>
+ <GridChips {...historyChrome.chipProps} />
{history.length === 0 ? (
<div className="card-body">
<EmptyState
@@ -583,22 +783,22 @@ const ScannerTab = () => {
</div>
) : (
<DataTable
- columns={historyColumns}
+ columns={historyChrome.columns}
data={history}
keyField={(scan) => `${scan.started_at}-${scan.directory}`}
sorts={historySorts.sorts}
onSortsChange={historySorts.setSorts}
- hiddenKeys={historyCols.hiddenKeys}
- onHiddenKeysChange={historyCols.setHiddenKeys}
+ {...historyChrome.tableProps}
footer={(
<DataTableFooter
- shown={history.length}
+ shown={shownHistory.length}
total={history.length}
noun="scan"
/>
)}
/>
)}
+ <GridFilterDrawer {...historyChrome.drawerProps} />
</div>
</div>
);
diff --git a/frontend/src/components/settings/ApiSettingsTab.jsx b/frontend/src/components/settings/ApiSettingsTab.jsx
index 5ef930d3..148a5c18 100644
--- a/frontend/src/components/settings/ApiSettingsTab.jsx
+++ b/frontend/src/components/settings/ApiSettingsTab.jsx
@@ -13,7 +13,13 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Pill } from '@/components/ds/Pill';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, DataTableFooter, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer,
+} from '@/components/ds/grid';
+import { useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import EmptyState from '../EmptyState';
const ApiSettingsTab = () => {
@@ -30,6 +36,60 @@ const ApiSettingsTab = () => {
};
// ─── API Keys Section ──────────────────────────────────
+
+// The label the Status cell shows. A key is live only while it is active AND
+// un-revoked, so the view's rule has to read the same pair the badge does.
+const keyStatus = (key) => (key.is_active && !key.revoked_at ? 'Active' : 'Revoked');
+
+// Built-in saved views for the API keys table. Only this table gets them: the
+// webhook deliveries list and the top-endpoints summary further down are a
+// drill-down and a readout, not surfaces you come back to and narrow.
+const API_KEY_VIEWS = [
+ {
+ // What is actually live. Revoked keys are never deleted, so on an
+ // instance that has been running a while they are most of the table.
+ // Least recently used first — a live key nobody calls is one to ask
+ // about.
+ name: 'Active keys',
+ state: {
+ sorts: [{ key: 'lastUsed', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'kv1', field: 'status', op: 'any', value: ['Active'] }],
+ },
+ },
+ },
+ {
+ // The security review: which keys can call everything. `is` rather
+ // than `contains` because the value is the joined scope list, and
+ // `contains '*'` would also catch a key scoped to `domains:*`.
+ name: 'Full access',
+ state: {
+ sorts: [{ key: 'name', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'kv2', field: 'scopes', op: 'is', value: '*' }],
+ },
+ },
+ },
+ {
+ // The audit trail. Rotations and revocations pile up here; most
+ // recently used first, because that is the one whose blast radius you
+ // are trying to remember.
+ name: 'Revoked',
+ state: {
+ sorts: [{ key: 'lastUsed', direction: 'desc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'kv3', field: 'status', op: 'any', value: ['Revoked'] }],
+ },
+ },
+ },
+];
+
const ApiKeysSection = () => {
const register = useSettingFocus();
const [keys, setKeys] = useState([]);
@@ -37,6 +97,16 @@ const ApiKeysSection = () => {
const [showModal, setShowModal] = useState(false);
const [createdKey, setCreatedKey] = useState(null);
+ // Lifted out of <DataTable> so a saved view can capture them. The storage
+ // keys are the ones DataTable derived from storageKey="serverkit-table-
+ // settings-api-keys", so a persisted sort or hidden column survives.
+ const { sorts, setSorts } = useTableSort({
+ storageKey: 'serverkit-table-settings-api-keys-sort',
+ });
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
+ storageKey: 'serverkit-table-settings-api-keys-cols',
+ });
+
const loadKeys = () => {
setLoading(true);
api.getApiKeys().then(data => {
@@ -75,12 +145,20 @@ const ApiKeysSection = () => {
// identical to the hand-rolled table they replace, so _api-settings.scss
// keeps applying (.api-settings__key-name, __key-prefix, __scopes,
// __muted, __actions).
+ //
+ // `type` + `value` are declared on every column a built-in view reads.
+ // Two of them would otherwise be typed from the wrong thing: Last Used has
+ // a `sortValue` of epoch ms, which inference would call numeric, and
+ // Scopes and Status render from fields no accessor exposed at all, so they
+ // were not filterable in any way.
const keyColumns = [
{
key: 'name',
header: 'Name',
sortable: true,
hideable: false,
+ type: 'text',
+ value: (key) => key.name || '',
sortValue: (key) => key.name || '',
cellClassName: 'api-settings__key-name',
render: (key) => key.name,
@@ -88,11 +166,20 @@ const ApiKeysSection = () => {
{
key: 'key',
header: 'Key',
+ // Searchable by prefix: that is the only part of a key that ever
+ // appears again after creation, so it is how a log line gets
+ // matched back to a row here.
+ type: 'text',
+ value: (key) => key.key_prefix || '',
render: (key) => <code className="api-settings__key-prefix">{key.key_prefix}...</code>,
},
{
key: 'scopes',
header: 'Scopes',
+ // The joined list, so "contains domains" finds every key that can
+ // touch domains and "is *" finds exactly the full-access ones.
+ type: 'text',
+ value: (key) => (key.scopes || []).join(', '),
render: (key) => (
<div className="api-settings__scopes">
{(!key.scopes || key.scopes.length === 0) ? (
@@ -115,12 +202,16 @@ const ApiKeysSection = () => {
{
key: 'tier',
header: 'Tier',
+ type: 'enum',
+ value: (key) => key.tier || '',
render: (key) => <Badge variant="outline">{key.tier}</Badge>,
},
{
key: 'lastUsed',
header: 'Last Used',
sortable: true,
+ type: 'date',
+ value: (key) => key.last_used_at || null,
sortValue: (key) => (key.last_used_at ? new Date(key.last_used_at).getTime() : null),
cellClassName: 'api-settings__muted',
render: (key) => (
@@ -132,8 +223,12 @@ const ApiKeysSection = () => {
{
key: 'status',
header: 'Status',
+ sortable: true,
+ type: 'enum',
+ value: keyStatus,
+ sortValue: keyStatus,
render: (key) => (
- key.is_active && !key.revoked_at ? (
+ keyStatus(key) === 'Active' ? (
<Badge variant="success">Active</Badge>
) : (
<Badge variant="destructive">Revoked</Badge>
@@ -172,20 +267,52 @@ const ApiKeysSection = () => {
},
];
+ // This tab renders three tables, so the link params are namespaced — the
+ // deliveries and top-endpoints tables below have no chrome today, but an
+ // unscoped `?view=` here would be theirs to collide with the moment one
+ // did. No `pageState`: the section has no search or filter of its own.
+ const chrome = useTableChrome({
+ columns: keyColumns,
+ rows: keys,
+ viewPageKey: 'settings-api-keys',
+ urlScope: 'keys',
+ builtinViews: API_KEY_VIEWS,
+ noun: 'keys',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
return (
<div {...register('api-keys', 'settings-card')}>
- <div className="settings-card__header">
- <div className="settings-card__header-left">
- <Key size={20} />
- <div>
- <h3>API Keys</h3>
- <p>Manage programmatic access to the ServerKit API</p>
- </div>
- </div>
+ {/* The view name replaces this card's "API Keys" header: it is the
+ one card in the stack whose body is a table, and stacking a
+ title above the picker would be two names for one list. Create
+ Key moves into the toolbar and stays reachable while empty. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="keys"
+ total={loading ? null : `${keys.length} key${keys.length === 1 ? '' : 's'}`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadKeys} />
+ </>
+ )}
+ >
<Button variant="default" size="sm" onClick={() => setShowModal(true)}>
<Plus size={14} /> Create Key
</Button>
- </div>
+ </ListToolbar>
+
+ <GridChips {...chrome.chipProps} />
{loading ? (
<div className="settings-card__loading">Loading...</div>
@@ -198,18 +325,13 @@ const ApiKeysSection = () => {
) : (
<div className="api-settings__table-wrap">
<DataTable
- columns={keyColumns}
+ columns={chrome.columns}
data={keys}
keyField="id"
- storageKey="serverkit-table-settings-api-keys"
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
tableClassName="api-settings__table"
- footer={(
- <DataTableFooter
- shown={keys.length}
- total={keys.length}
- noun="key"
- />
- )}
/>
</div>
)}
@@ -221,6 +343,8 @@ const ApiKeysSection = () => {
createdKey={createdKey}
/>
)}
+
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};
diff --git a/frontend/src/components/settings/InvitationsTab.jsx b/frontend/src/components/settings/InvitationsTab.jsx
index 63312f7b..d75514e6 100644
--- a/frontend/src/components/settings/InvitationsTab.jsx
+++ b/frontend/src/components/settings/InvitationsTab.jsx
@@ -3,15 +3,82 @@ import api from '../../services/api';
import InviteModal from './InviteModal';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer,
+} from '@/components/ds/grid';
+import { useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import EmptyState from '../EmptyState';
+// A pending invite whose window has closed still carries status 'pending' in
+// the database — the row only becomes 'expired' on screen. One accessor for
+// the cell, the sort and the filter rules, so all three agree.
+const effectiveStatus = (inv) => (
+ inv.is_expired && inv.status === 'pending' ? 'expired' : inv.status || ''
+);
+
+// Built-in saved views. The three that matter are the three lifecycle states:
+// what is still live, what lapsed, and what was taken up.
+const INVITATION_VIEWS = [
+ {
+ // The live links — the ones that can still be used to create an
+ // account. Soonest to lapse first, so a resend beats the deadline.
+ name: 'Pending',
+ state: {
+ sorts: [{ key: 'expires', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'iv1', field: 'status', op: 'any', value: ['pending'] }],
+ },
+ },
+ },
+ {
+ // The worklist: each of these is a person who was invited and never
+ // got in. Resend or revoke, newest first.
+ name: 'Expired',
+ state: {
+ sorts: [{ key: 'created', direction: 'desc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'iv2', field: 'status', op: 'any', value: ['expired'] }],
+ },
+ },
+ },
+ {
+ // Who actually joined, and when. Expires is hidden — it stopped
+ // meaning anything the moment the invite was accepted.
+ name: 'Accepted',
+ state: {
+ sorts: [{ key: 'created', direction: 'desc' }],
+ hiddenKeys: ['expires'],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'iv3', field: 'status', op: 'any', value: ['accepted'] }],
+ },
+ },
+ },
+];
+
const InvitationsTab = () => {
const [invitations, setInvitations] = useState([]);
const [loading, setLoading] = useState(true);
const [showInviteModal, setShowInviteModal] = useState(false);
const [copied, setCopied] = useState(null);
+ // Lifted out of <DataTable> so a saved view can capture them. The storage
+ // keys are the ones DataTable derived from storageKey="serverkit-table-
+ // settings-invitations", so a persisted sort or hidden column survives.
+ const { sorts, setSorts } = useTableSort({
+ storageKey: 'serverkit-table-settings-invitations-sort',
+ });
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
+ storageKey: 'serverkit-table-settings-invitations-cols',
+ });
+
useEffect(() => {
loadInvitations();
}, []);
@@ -81,18 +148,27 @@ const InvitationsTab = () => {
// Columns for the shared DataTable. Cell markup and classNames are
// identical to the hand-rolled table they replace, so _users.scss keeps
// applying (.users-table, .date-cell, .actions-cell).
+ //
+ // `type` + `value` are declared wherever a built-in view reads a column:
+ // inference falls back to `sortValue`, which on the date columns is an
+ // epoch number and would have typed them numeric — a date rule against a
+ // numeric column matches nothing.
const columns = [
{
key: 'recipient',
header: 'Recipient',
sortable: true,
hideable: false,
+ type: 'text',
+ value: (inv) => inv.email || '',
sortValue: (inv) => inv.email || '',
render: (inv) => inv.email || <span className="text-muted">Link only</span>,
},
{
key: 'role',
header: 'Role',
+ type: 'enum',
+ value: (inv) => inv.role || '',
render: (inv) => (
<Badge variant={getRoleBadgeVariant(inv.role)}>
{inv.role}
@@ -103,10 +179,12 @@ const InvitationsTab = () => {
key: 'status',
header: 'Status',
sortable: true,
- sortValue: (inv) => (inv.is_expired && inv.status === 'pending' ? 'expired' : inv.status || ''),
+ type: 'enum',
+ value: effectiveStatus,
+ sortValue: effectiveStatus,
render: (inv) => (
<Badge variant={getStatusBadgeVariant(inv.status, inv.is_expired)}>
- {inv.is_expired && inv.status === 'pending' ? 'expired' : inv.status}
+ {effectiveStatus(inv)}
</Badge>
),
},
@@ -114,13 +192,21 @@ const InvitationsTab = () => {
key: 'created',
header: 'Created',
sortable: true,
+ type: 'date',
+ value: (inv) => inv.created_at || null,
sortValue: (inv) => (inv.created_at ? new Date(inv.created_at).getTime() : null),
cellClassName: 'date-cell',
render: (inv) => formatDate(inv.created_at),
},
{
+ // Sortable now: "Pending" leads with whatever lapses first, which
+ // needs a real accessor behind the column rather than a render.
key: 'expires',
header: 'Expires',
+ sortable: true,
+ type: 'date',
+ value: (inv) => inv.expires_at || null,
+ sortValue: (inv) => (inv.expires_at ? new Date(inv.expires_at).getTime() : null),
cellClassName: 'date-cell',
render: (inv) => formatDate(inv.expires_at),
},
@@ -166,13 +252,45 @@ const InvitationsTab = () => {
},
];
+ // This component is rendered INSIDE <UsersTab />, so the Users tab shows
+ // two tables and both chrome instances would otherwise fight over the same
+ // `?view=`/`?sort=` keys. The scope namespaces this one's link params.
+ //
+ // No `pageState`: the section has no search or filter of its own.
+ const chrome = useTableChrome({
+ columns,
+ rows: invitations,
+ viewPageKey: 'settings-invitations',
+ urlScope: 'invites',
+ builtinViews: INVITATION_VIEWS,
+ noun: 'invitations',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
return (
<div className="invitations-section">
- <div className="tab-header">
- <div className="tab-header-content">
- <h4>Invitations</h4>
- <p>Manage team invitations</p>
- </div>
+ {/* The view name replaces the old "Invitations" h4: it names the
+ section AND says which slice of it you are looking at. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="invitations"
+ total={loading ? null : `${invitations.length} invitation${invitations.length === 1 ? '' : 's'}`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadInvitations} />
+ </>
+ )}
+ >
<Button variant="default" size="sm" onClick={() => setShowInviteModal(true)}>
<svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">
<path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
@@ -182,7 +300,9 @@ const InvitationsTab = () => {
</svg>
Invite User
</Button>
- </div>
+ </ListToolbar>
+
+ <GridChips {...chrome.chipProps} />
{loading ? (
<div className="loading-state">Loading invitations...</div>
@@ -191,18 +311,13 @@ const InvitationsTab = () => {
) : (
<div className="users-table-container">
<DataTable
- columns={columns}
+ columns={chrome.columns}
data={invitations}
keyField="id"
- storageKey="serverkit-table-settings-invitations"
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
tableClassName="users-table"
- footer={(
- <DataTableFooter
- shown={invitations.length}
- total={invitations.length}
- noun="invitation"
- />
- )}
/>
</div>
)}
@@ -213,6 +328,8 @@ const InvitationsTab = () => {
onCreated={loadInvitations}
/>
)}
+
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};
diff --git a/frontend/src/components/settings/MigrationHistoryTab.jsx b/frontend/src/components/settings/MigrationHistoryTab.jsx
index df241229..ef87441f 100644
--- a/frontend/src/components/settings/MigrationHistoryTab.jsx
+++ b/frontend/src/components/settings/MigrationHistoryTab.jsx
@@ -2,7 +2,13 @@ import { useState, useEffect, useCallback } from 'react';
import api from '../../services/api';
import { Database, Loader, CheckCircle, ArrowUpCircle, ShieldCheck } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer,
+} from '@/components/ds/grid';
+import { useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import EmptyState from '../EmptyState';
import { useToast } from '../../contexts/ToastContext';
import { useConfirm } from '../../hooks/useConfirm';
@@ -12,6 +18,36 @@ import useSettingFocus from '../../hooks/useSettingFocus';
// so show them in full rather than truncating mid-word.
const short = (rev) => rev || '';
+// Built-in saved views. Revisions are numbered slugs, so sorting the Revision
+// column IS chronological order — there is no timestamp on a revision row.
+const MIGRATION_VIEWS = [
+ {
+ // What is about to run, in the order it will run. This is the list you
+ // read before pressing Apply, and on a long history it is three rows
+ // buried at the bottom of eighty.
+ name: 'Pending',
+ state: {
+ sorts: [{ key: 'revision', direction: 'asc' }],
+ hiddenKeys: [],
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'mv1', field: 'status', op: 'any', value: ['Pending'] }],
+ },
+ },
+ },
+ {
+ // No rules — the whole chain, newest first. "What did the last upgrade
+ // bring in" is the other question this table gets asked, and the
+ // natural order (oldest first) is the wrong end for it.
+ name: 'Newest first',
+ state: {
+ sorts: [{ key: 'revision', direction: 'desc' }],
+ hiddenKeys: [],
+ columnFilters: { match: 'all', rules: [] },
+ },
+ },
+];
+
const MigrationHistoryTab = () => {
const toast = useToast();
const { confirm } = useConfirm();
@@ -24,6 +60,16 @@ const MigrationHistoryTab = () => {
const [applying, setApplying] = useState(false);
const [backupFirst, setBackupFirst] = useState(true);
+ // Lifted out of <DataTable> so a saved view can capture them. The storage
+ // keys are the ones DataTable derived from storageKey="serverkit-table-
+ // settings-migrations", so a persisted sort or hidden column survives.
+ const { sorts, setSorts } = useTableSort({
+ storageKey: 'serverkit-table-settings-migrations-sort',
+ });
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
+ storageKey: 'serverkit-table-settings-migrations-cols',
+ });
+
const load = useCallback(async () => {
try {
setLoading(true);
@@ -61,6 +107,13 @@ const MigrationHistoryTab = () => {
// re-stamps the version pointer rather than running DDL.
const orphaned = Boolean(currentRev) && currentIdx === -1 && revisions.length > 0;
+ // The label the Status cell shows. Derived, not stored: a revision is
+ // "pending" because of where it sits relative to the current one, so the
+ // view's rule has to read the same computation the badge does.
+ const statusLabel = (rev) => (
+ rev.is_current ? 'Current' : pendingIds.has(rev.revision) ? 'Pending' : 'Applied'
+ );
+
// Columns for the shared DataTable. Cell markup is identical to the
// hand-rolled table it replaces, so the .data-table rules keep applying.
const columns = [
@@ -69,6 +122,8 @@ const MigrationHistoryTab = () => {
header: 'Revision',
sortable: true,
hideable: false,
+ type: 'text',
+ value: (rev) => rev.revision || '',
sortValue: (rev) => rev.revision || '',
render: (rev) => <code>{short(rev.revision)}</code>,
},
@@ -76,6 +131,8 @@ const MigrationHistoryTab = () => {
key: 'description',
header: 'Description',
sortable: true,
+ type: 'text',
+ value: (rev) => rev.description || 'Schema update',
sortValue: (rev) => rev.description || 'Schema update',
render: (rev) => rev.description || 'Schema update',
},
@@ -83,6 +140,11 @@ const MigrationHistoryTab = () => {
key: 'status',
header: 'Status',
sortable: true,
+ // Typed explicitly: `sortValue` is a rank, and letting that number
+ // infer the type would make Status numeric — "Pending" would then
+ // be a string rule against a numeric column, matching zero rows.
+ type: 'enum',
+ value: statusLabel,
// current -> applied -> pending keeps the lifecycle order sensible.
sortValue: (rev) => (rev.is_current ? 0 : pendingIds.has(rev.revision) ? 2 : 1),
render: (rev) => (
@@ -101,6 +163,21 @@ const MigrationHistoryTab = () => {
},
];
+ // Single table on this tab, so no `urlScope` — the shareable link keeps the
+ // plain `?view=` every other single-table page produces. No `pageState`
+ // either: the history endpoint returns the whole chain, unfiltered.
+ const chrome = useTableChrome({
+ columns,
+ rows: revisions,
+ viewPageKey: 'settings-migrations',
+ builtinViews: MIGRATION_VIEWS,
+ noun: 'migrations',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ });
+
async function runMigrations() {
const ok = await confirm({
title: orphaned ? 'Re-sync database version?' : `Apply ${count} migration${plural}?`,
@@ -225,23 +302,45 @@ const MigrationHistoryTab = () => {
{revisions.length === 0 ? (
<EmptyState icon={Database} title="No migration history found." />
) : (
- <div {...register('migrations-history', 'table-container')}>
- <DataTable
- columns={columns}
- data={revisions}
- keyField="revision"
- storageKey="serverkit-table-settings-migrations"
- tableClassName="data-table"
- footer={(
- <DataTableFooter
- shown={revisions.length}
- total={revisions.length}
- noun="migration"
- />
+ <>
+ {/* The section's h2 above stays put — it heads the apply
+ banner as well as the table, so the picker sits with
+ the table it actually belongs to. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="migrations"
+ total={`${revisions.length} revision${revisions.length === 1 ? '' : 's'}`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
+ </>
)}
/>
- </div>
+
+ <GridChips {...chrome.chipProps} />
+
+ <div {...register('migrations-history', 'table-container')}>
+ <DataTable
+ columns={chrome.columns}
+ data={revisions}
+ keyField="revision"
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
+ tableClassName="data-table"
+ />
+ </div>
+ </>
)}
+
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};
diff --git a/frontend/src/components/settings/RecycleBinTab.jsx b/frontend/src/components/settings/RecycleBinTab.jsx
index 7482e38b..76503c91 100644
--- a/frontend/src/components/settings/RecycleBinTab.jsx
+++ b/frontend/src/components/settings/RecycleBinTab.jsx
@@ -5,9 +5,52 @@ import { useToast } from '@/contexts/ToastContext';
import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import EmptyState from '@/components/EmptyState';
-import { SegControl, Pill, DataTable, DataTableFooter } from '@/components/ds';
+import { SegControl, Pill, DataTable, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer,
+} from '@/components/ds/grid';
+import { useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import ConfirmDialog from '@/components/ConfirmDialog';
+// Built-in saved views. Neither one names a `kind`: the registry decides what
+// lands here, so a preset that spelled out 'domain' would be a list this file
+// otherwise never hard-codes — and it would duplicate the type SegControl
+// anyway. Both views work on whatever the server registered.
+//
+// `page.kind` is spelled out on both. The SegControl is part of the captured
+// state, so a preset that left it out would compare unequal to the live state
+// the instant it was applied and the picker would read "Unsaved" every time.
+const RECYCLEBIN_VIEWS = [
+ {
+ // Oldest deletion first — the rows closest to being reaped by the
+ // retention window, which is the only deadline this page has. The
+ // default order (newest first) puts them at the very bottom.
+ name: 'Closest to purge',
+ state: {
+ sorts: [{ key: 'deleted_at', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: { match: 'all', rules: [] },
+ page: { kind: 'all' },
+ },
+ },
+ {
+ // No rules either: everything, bucketed by what it is. The group
+ // headers carry the per-type counts, so this answers "what kind of
+ // thing have we been deleting" without touching the SegControl.
+ name: 'By type',
+ state: {
+ sorts: [{ key: 'deleted_at', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: 'kind',
+ columnFilters: { match: 'all', rules: [] },
+ page: { kind: 'all' },
+ },
+ },
+];
+
// Everything the panel has soft-deleted, in one place. Type-agnostic on
// purpose: `kind` comes from the server's registry, so a newly restorable model
// shows up here with no change to this file.
@@ -22,6 +65,19 @@ export default function RecycleBinTab() {
const [busyId, setBusyId] = useState(null);
const [purgeTarget, setPurgeTarget] = useState(null);
+ // Lifted out of <DataTable> so a saved view can capture them. The storage
+ // keys are the ones DataTable derived from storageKey="serverkit-table-
+ // recyclebin", so a persisted sort or hidden column survives.
+ const { sorts, setSorts } = useTableSort({
+ defaultSorts: [{ key: 'deleted_at', direction: 'desc' }],
+ storageKey: 'serverkit-table-recyclebin-sort',
+ });
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
+ storageKey: 'serverkit-table-recyclebin-cols',
+ });
+ // Not persisted on its own: a grouping worth keeping is a saved view.
+ const [groupBy, setGroupBy] = useState(null);
+
const load = useCallback(async () => {
try {
setLoading(true);
@@ -109,7 +165,11 @@ export default function RecycleBinTab() {
sortable: true,
type: 'enum',
groupable: true,
+ // `groupValue` spelled out because grouping otherwise falls back to
+ // row[key] — the raw registry slug ('saved_view'), where every
+ // other surface here reads the noun ('saved view').
value: (r) => r.noun,
+ groupValue: (r) => r.noun,
render: (r) => <Pill kind="gray">{r.noun}</Pill>,
},
{
@@ -167,6 +227,29 @@ export default function RecycleBinTab() {
},
], [busyId, isAdmin, retentionDays]); // eslint-disable-line react-hooks/exhaustive-deps
+ // Single table on this tab, so no `urlScope` — the shareable link keeps
+ // the plain `?view=` every other single-table page produces.
+ //
+ // The type SegControl goes in `pageState`, so saving a view remembers
+ // which type you had picked. A preset that omits `kind` must land back on
+ // 'all': the envelope's page bag is `{}` there, and `undefined` would
+ // leave the SegControl with no selected option.
+ const chrome = useTableChrome({
+ columns,
+ rows: shown,
+ viewPageKey: 'settings-recyclebin',
+ builtinViews: RECYCLEBIN_VIEWS,
+ noun: 'items',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ groupBy,
+ setGroupBy,
+ pageState: { kind },
+ applyPage: (p) => setKind(p.kind || 'all'),
+ });
+
return (
<div className="settings-section recyclebin">
<div className="settings-section__head">
@@ -193,28 +276,56 @@ export default function RecycleBinTab() {
/>
) : (
<>
- <div className="recyclebin__toolbar">
- <SegControl value={kind} onChange={setKind} options={filters} />
- <span className="recyclebin__retention">
- <Clock size={13} /> kept {retentionDays} days
- </span>
- </div>
+ {/* The section's h2 above stays put — it heads the
+ retention explanation as much as the table, so the
+ picker sits with the table it actually belongs to. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="items"
+ total={`${shown.length} of ${items.length} item${items.length === 1 ? '' : 's'}`}
+ onCreate={chrome.createView}
+ />
+ {/* The retention note goes in the count slot: it is meta,
+ not a tool, and that also spares
+ `.recyclebin__retention`'s margin-left:auto from a flex
+ row it was never written for. */}
+ <ListToolbar
+ filters={<SegControl value={kind} onChange={setKind} options={filters} />}
+ count={(
+ <span className="recyclebin__retention">
+ <Clock size={13} /> kept {retentionDays} days
+ </span>
+ )}
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={load} />
+ </>
+ )}
+ />
+
+ <GridChips {...chrome.chipProps} />
<DataTable
- columns={columns}
+ columns={chrome.columns}
data={shown}
keyField={rowKey}
- defaultSorts={[{ key: 'deleted_at', direction: 'desc' }]}
- storageKey="serverkit-table-recyclebin"
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
emptyTitle="Nothing of this type"
emptyMessage="Try another type."
- footer={(
- <DataTableFooter shown={shown.length} total={items.length} noun="record" />
- )}
/>
</>
)}
+ <GridFilterDrawer {...chrome.drawerProps} />
+
<ConfirmDialog
isOpen={!!purgeTarget}
variant="danger"
diff --git a/frontend/src/components/settings/UsersTab.jsx b/frontend/src/components/settings/UsersTab.jsx
index 8e3f93a1..532e2373 100644
--- a/frontend/src/components/settings/UsersTab.jsx
+++ b/frontend/src/components/settings/UsersTab.jsx
@@ -7,9 +7,67 @@ import LoginLinksSection from './LoginLinksSection';
import Modal from '../Modal';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
-import { DataTable, DataTableFooter } from '@/components/ds';
+import { DataTable, ListToolbar } from '@/components/ds';
+import {
+ useTableChrome, GridViewPicker, GridChips, GridFilterButton,
+ GridToolsMenu, GridFilterDrawer,
+} from '@/components/ds/grid';
+import { useTableSort } from '@/hooks/useTableSort';
+import { useColumnVisibility } from '@/hooks/useColumnVisibility';
import useSettingFocus from '../../hooks/useSettingFocus';
+// The label the Status cell shows, in one place: the built-in view below
+// filters on it, and a rule matches a column's `value`, not the row's
+// `is_active` boolean.
+const statusLabel = (user) => (user.is_active ? 'Active' : 'Disabled');
+
+// Built-in saved views. Every rule matches a column's `value` accessor, so the
+// strings here are the LABELS the cells render ('Disabled', 'admin') rather
+// than whatever the API happens to call the field.
+const USER_VIEWS = [
+ {
+ // Who can do anything on this panel. It is the first question of an
+ // access review and the one a flat alphabetical list buries as soon as
+ // the team is bigger than a screen.
+ name: 'Admins',
+ state: {
+ sorts: [{ key: 'user', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'uv1', field: 'role', op: 'any', value: ['admin'] }],
+ },
+ },
+ },
+ {
+ // Offboarding check: a disabled account keeps its role and its history,
+ // so it is still worth looking at. Most recently created first, because
+ // the one you just switched off is the one you are verifying.
+ name: 'Disabled accounts',
+ state: {
+ sorts: [{ key: 'created', direction: 'desc' }],
+ hiddenKeys: [],
+ groupBy: null,
+ columnFilters: {
+ match: 'all',
+ rules: [{ id: 'uv2', field: 'status', op: 'any', value: ['Disabled'] }],
+ },
+ },
+ },
+ {
+ // No rules: the whole team, bucketed by privilege. The group headers
+ // carry the per-role counts, which is what "who has what" is asking.
+ name: 'By role',
+ state: {
+ sorts: [{ key: 'user', direction: 'asc' }],
+ hiddenKeys: [],
+ groupBy: 'role',
+ columnFilters: { match: 'all', rules: [] },
+ },
+ },
+];
+
const UsersTab = () => {
const register = useSettingFocus();
const [users, setUsers] = useState([]);
@@ -20,6 +78,18 @@ const UsersTab = () => {
const [deleteConfirm, setDeleteConfirm] = useState(null);
const { user: currentUser } = useAuth();
+ // Lifted out of <DataTable> so a saved view can capture them. The storage
+ // keys are the ones DataTable derived from storageKey="serverkit-table-
+ // settings-users", so everyone's persisted sort and hidden columns survive.
+ const { sorts, setSorts } = useTableSort({
+ storageKey: 'serverkit-table-settings-users-sort',
+ });
+ const { hiddenKeys, setHiddenKeys } = useColumnVisibility({
+ storageKey: 'serverkit-table-settings-users-cols',
+ });
+ // Not persisted on its own: a grouping worth keeping is a saved view.
+ const [groupBy, setGroupBy] = useState(null);
+
useEffect(() => {
loadUsers();
}, []);
@@ -100,24 +170,25 @@ const UsersTab = () => {
});
}
- if (loading) {
- return (
- <div className="users-tab">
- <div className="loading-state">Loading users...</div>
- </div>
- );
- }
-
// Columns for the shared DataTable. Cell markup and classNames are
// identical to the hand-rolled table they replace, so _users.scss keeps
// applying (.user-info, .user-avatar, .status-badge, .date-cell,
// .actions-cell, tr.inactive).
+ //
+ // `type` + `value` are declared on every column a built-in view touches.
+ // Inference reads `sortValue` when a column has no `value`, and both ways
+ // it lands on the wrong type here: Created's epoch number would type that
+ // column numeric, and three distinct roles across three users is over the
+ // enum cardinality ratio, so Role would degrade to free text. Either way
+ // the preset's rule would match zero rows.
const columns = [
{
key: 'user',
header: 'User',
sortable: true,
hideable: false,
+ type: 'text',
+ value: (user) => user.username || '',
sortValue: (user) => user.username || '',
cellClassName: 'user-info',
render: (user) => (
@@ -141,6 +212,13 @@ const UsersTab = () => {
key: 'role',
header: 'Role',
sortable: true,
+ type: 'enum',
+ groupable: true,
+ // All three accessors spelled out so the "By role" view groups,
+ // filters and sorts on the same string. Grouping otherwise falls
+ // back to row[key], which only works here by luck of naming.
+ value: (user) => user.role || '',
+ groupValue: (user) => user.role || '',
sortValue: (user) => user.role || '',
render: (user) => (
<Badge variant={getRoleBadgeVariant(user.role)}>
@@ -151,15 +229,24 @@ const UsersTab = () => {
{
key: 'status',
header: 'Status',
+ type: 'enum',
+ value: statusLabel,
render: (user) => (
<span className={`status-badge ${user.is_active ? 'active' : 'inactive'}`}>
- {user.is_active ? 'Active' : 'Disabled'}
+ {statusLabel(user)}
</span>
),
},
{
+ // Sortable and typed rather than render-only: "when did this person
+ // last sign in" is the access-review question, and without an
+ // accessor the column had nothing behind it to sort or filter on.
key: 'lastLogin',
header: 'Last Login',
+ sortable: true,
+ type: 'date',
+ value: (user) => user.last_login_at || null,
+ sortValue: (user) => (user.last_login_at ? new Date(user.last_login_at).getTime() : null),
cellClassName: 'date-cell',
render: (user) => formatDate(user.last_login_at),
},
@@ -167,6 +254,11 @@ const UsersTab = () => {
key: 'created',
header: 'Created',
sortable: true,
+ // Declared, not inferred: the sorter wants epoch ms, and letting
+ // that number type the column would offer "is under 1754…" instead
+ // of a date picker.
+ type: 'date',
+ value: (user) => user.created_at || null,
sortValue: (user) => (user.created_at ? new Date(user.created_at).getTime() : null),
cellClassName: 'date-cell',
render: (user) => formatDate(user.created_at),
@@ -230,13 +322,58 @@ const UsersTab = () => {
},
];
+ // This tab renders TWO tables — the users list and, below it, the whole of
+ // <InvitationsTab /> — so both chrome instances need their own URL
+ // namespace. Unscoped they would read and write the same `?view=`/`?sort=`
+ // and each would arrive as the other's.
+ //
+ // No `pageState`: the list is /users' whole response, with no search or
+ // server-side filter of its own, so there is nothing page-private to carry.
+ const chrome = useTableChrome({
+ columns,
+ rows: users,
+ viewPageKey: 'settings-users',
+ urlScope: 'users',
+ builtinViews: USER_VIEWS,
+ noun: 'users',
+ sorts,
+ setSorts,
+ hiddenKeys,
+ setHiddenKeys,
+ groupBy,
+ setGroupBy,
+ });
+
+ if (loading) {
+ return (
+ <div className="users-tab">
+ <div className="loading-state">Loading users...</div>
+ </div>
+ );
+ }
+
return (
<div className="users-tab">
- <div className="tab-header">
- <div className="tab-header-content">
- <h3>User Management</h3>
- <p>Manage user accounts and permissions</p>
- </div>
+ {/* The view name IS the heading — the old "User Management" h3 said
+ what the tab strip already said, and stacking it above the
+ picker would have been two titles for one table. */}
+ <GridViewPicker
+ views={chrome.views}
+ label="users"
+ total={`${users.length} user${users.length === 1 ? '' : 's'}`}
+ onCreate={chrome.createView}
+ />
+ <ListToolbar
+ tools={(
+ <>
+ <GridFilterButton
+ count={chrome.filterCount}
+ onClick={() => chrome.setDrawerOpen(true)}
+ />
+ <GridToolsMenu {...chrome.toolsProps} onRefresh={loadUsers} />
+ </>
+ )}
+ >
<Button variant="default" onClick={handleAddUser}>
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">
<line x1="12" y1="5" x2="12" y2="19"/>
@@ -244,25 +381,24 @@ const UsersTab = () => {
</svg>
Add User
</Button>
- </div>
+ </ListToolbar>
+
+ <GridChips {...chrome.chipProps} />
{error && <div className="error-message">{error}</div>}
<div {...register('users-management', 'users-table-container')}>
<DataTable
- columns={columns}
+ columns={chrome.columns}
data={users}
keyField="id"
- storageKey="serverkit-table-settings-users"
+ sorts={sorts}
+ onSortsChange={setSorts}
+ {...chrome.tableProps}
+ groupBy={groupBy}
+ onGroupByChange={setGroupBy}
rowClassName={(user) => (!user.is_active ? 'inactive' : '')}
tableClassName="users-table"
- footer={(
- <DataTableFooter
- shown={users.length}
- total={users.length}
- noun="user"
- />
- )}
/>
</div>
@@ -292,6 +428,8 @@ const UsersTab = () => {
<LoginLinksSection users={users} currentUserId={currentUser?.id} />
<InvitationsTab />
+
+ <GridFilterDrawer {...chrome.drawerProps} />
</div>
);
};