Files
Gerhard Scheikl d317e8c758 feat(admin): live redis kill-switch on tunnel actions, sortable columns + CSV export + bulk actions, Node 24 LTS
WS1: pin all Docker stages to node:24.16.0-alpine; add engines node>=20.
WS2: lib/redis.ts gains TTL-backed redisSet, redisDel, setTunnelActive (writes tunnel:active:<sub>=1/0 EX 30, TUNNEL_ACTIVE_TTL override, no-op without REDIS_URL); wired into tunnel active/delete/reassign routes.
WS3: sortable columns, CSV export routes (token excluded), and bulk actions (self-account guard) across users/tunnels/audit admin tables.
2026-05-31 14:46:22 +02:00

217 lines
6.2 KiB
TypeScript

'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { formatDate } from '@/lib/format';
import type { AuditItem } from '@/lib/admin/list';
import { SortHeader, downloadUrl, type SortOrder } from '../table-ui';
const PER_PAGE = 50;
export function AuditTable({
initialEntries,
initialTotal,
}: {
initialEntries: AuditItem[];
initialTotal: number;
}) {
const [entries, setEntries] = useState<AuditItem[]>(initialEntries);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [action, setAction] = useState('');
const [targetType, setTargetType] = useState('');
const [sort, setSort] = useState('created_at');
const [order, setOrder] = useState<SortOrder>('desc');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const queryParams = useCallback(() => {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
sort,
order,
});
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
return params;
}, [page, action, targetType, sort, order]);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/admin/audit?${queryParams().toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
entries: AuditItem[];
total: number;
};
setEntries(data.entries);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [queryParams]);
// First page is server-rendered; skip the on-mount fetch to avoid racing the
// SSR session-cookie refresh (which intermittently 401'd).
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
function onSort(col: string) {
setPage(1);
if (col === sort) {
setOrder((o) => (o === 'asc' ? 'desc' : 'asc'));
} else {
setSort(col);
setOrder('asc');
}
}
function exportCsv() {
const params = new URLSearchParams({ sort, order });
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
downloadUrl(`/api/admin/audit/export?${params.toString()}`);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Audit log</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Filter action (e.g. tunnel.delete)"
value={action}
onChange={(e) => {
setPage(1);
setAction(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<input
type="text"
placeholder="Filter target_type (user/tunnel…)"
value={targetType}
onChange={(e) => {
setPage(1);
setTargetType(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
<div className="toolbar-actions">
<button
className="secondary btn-sm"
type="button"
onClick={exportCsv}
>
Export CSV
</button>
</div>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : entries.length === 0 ? (
<p className="muted">No audit entries.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<SortHeader
label="When"
col="created_at"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Actor"
col="actor_email"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Action"
col="action"
sort={sort}
order={order}
onSort={onSort}
/>
<th>Target</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{entries.map((e) => (
<tr key={e.id}>
<td>{formatDate(e.created_at)}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.actor_email ?? e.actor_id ?? '—'}
</td>
<td>{e.action}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.target_type ? `${e.target_type}:` : ''}
{e.target_id ?? ''}
</td>
<td>
<code className="muted">
{JSON.stringify(e.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}