import { useEffect, useMemo, useState } from "react"; import { useSearchParams } from "react-router-dom"; import { api, type CurrentUser, type SecretInput, type SecretRecord, type SecretStatus } from "../api/client"; import { downloadCsv } from "../utils/csv"; import { formatDateTime } from "../utils/date"; import { readableError } from "../utils/errors"; import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; import { usePagination } from "../hooks/usePagination"; import Pagination from "../components/Pagination"; import { useSelection } from "../hooks/useSelection"; import { confirmDialog } from "../utils/dialogs"; import { ErrorNotice } from "../components/Notice"; import { toast } from "../utils/toast"; import TableToolbar from "../components/TableToolbar"; import { EmptyRow, LoadingRow } from "../components/EmptyState"; const TYPE_LABELS: Record = { api_token: "API Token", ssl_certificate: "SSL Certificate", password: "Password", generic: "Generic", }; const STATUS_BADGE: Record = { ok: "bg-green-lt text-green", expiring: "bg-yellow-lt text-yellow", expired: "bg-red-lt text-red", never: "bg-secondary-lt text-secondary", }; const STATUS_LABEL: Record = { ok: "ok", expiring: "expiring", expired: "expired", never: "no expiry", }; const emptyForm: SecretInput = { name: "", type: "generic", description: "", expiryDate: "", warnDays: 30, notes: "", checkHost: "", checkPort: 443, }; export default function Secrets({ user }: { user: CurrentUser }) { const canEdit = user.role === "admin" || user.role === "operator"; const [secrets, setSecrets] = useState(null); const [error, setError] = useState(null); const [searchParams] = useSearchParams(); const [search, setSearch] = useState(() => searchParams.get("q") ?? ""); const [statusFilter, setStatusFilter] = useState<"all" | SecretStatus>("all"); const [editingId, setEditingId] = useState(null); const [form, setForm] = useState(emptyForm); const [saving, setSaving] = useState(false); const [neverExpires, setNeverExpires] = useState(false); const selection = useSelection(); const [bulkDeleting, setBulkDeleting] = useState(false); const [checkingId, setCheckingId] = useState(null); function load() { api.secrets .list() .then((res) => { setSecrets(res.secrets); // Deep-link from global search (?editId=) — jump straight to that secret's edit form. const editId = Number(searchParams.get("editId")); const target = res.secrets.find((s) => s.id === editId); if (target && canEdit) startEdit(target); }) .catch((err) => setError(String(err))); } useEffect(load, []); const filtered = useMemo(() => { if (!secrets) return []; return secrets.filter((s) => { if (statusFilter !== "all" && s.status !== statusFilter) return false; const q = search.trim().toLowerCase(); if (!q) return true; return s.name.toLowerCase().includes(q) || (s.description ?? "").toLowerCase().includes(q); }); }, [secrets, search, statusFilter]); function startEdit(s: SecretRecord) { setEditingId(s.id); setNeverExpires(s.expiryDate === null); setForm({ name: s.name, type: s.type, description: s.description ?? "", expiryDate: s.expiryDate ?? "", warnDays: s.warnDays, notes: s.notes ?? "", checkHost: s.checkHost ?? "", checkPort: s.checkPort ?? 443, }); } function cancelEdit() { setEditingId(null); setNeverExpires(false); setForm(emptyForm); } async function submit(e: React.FormEvent) { e.preventDefault(); setError(null); setSaving(true); try { // A host only means something for a certificate; when one is set the date comes from the live cert, so it isn't sent. const host = form.type === "ssl_certificate" ? (form.checkHost ?? "").trim() : ""; const payload: SecretInput = { ...form, expiryDate: host ? undefined : neverExpires ? null : form.expiryDate, checkHost: host || null, checkPort: host ? form.checkPort || 443 : null, }; if (editingId) { await api.secrets.update(editingId, payload); toast.success(`Saved ${form.name}.`); } else { await api.secrets.create(payload); toast.success(`Added ${form.name}.`); } cancelEdit(); load(); } catch (err) { setError(readableError(err)); } finally { setSaving(false); } } async function checkNow(s: SecretRecord) { setError(null); setCheckingId(s.id); try { const res = await api.secrets.checkTls(s.id); if (!res.result.ok) setError(`Couldn't read the certificate for "${s.name}": ${res.result.error}`); load(); } catch (err) { setError(readableError(err)); } finally { setCheckingId(null); } } async function remove(s: SecretRecord) { if (!(await confirmDialog({ title: "Delete secret", message: `Delete secret "${s.name}"?`, confirmLabel: "Delete", danger: true }))) return; setError(null); try { await api.secrets.remove(s.id); toast.success(`Deleted ${s.name}.`); load(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } async function bulkDelete() { const ids = Array.from(selection.selected); if (ids.length === 0) return; if (!(await confirmDialog({ title: "Delete secrets", message: `Delete ${ids.length} secret${ids.length !== 1 ? "s" : ""}?`, confirmLabel: "Delete", danger: true }))) return; setError(null); setBulkDeleting(true); try { const results = await Promise.allSettled(ids.map((id) => api.secrets.remove(id))); const failed = results.filter((r) => r.status === "rejected").length; if (failed > 0) setError(`${failed} of ${ids.length} deletions failed.`); selection.clear(); load(); } finally { setBulkDeleting(false); } } const { sorted, sortKey, sortDir, requestSort } = useSortable(filtered); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { downloadCsv( "secrets.csv", ["Name", "Type", "Description", "Expiry Date", "Warn Days", "Status", "Days Left", "Notes", "Monitored Host"], (sorted ?? []).map((s) => [ s.name, TYPE_LABELS[s.type], s.description ?? "", s.expiryDate ?? "never expires", s.warnDays, STATUS_LABEL[s.status], s.daysLeft ?? "", s.notes ?? "", s.checkHost ? `${s.checkHost}:${s.checkPort ?? 443}` : "", ]), ); } const monitoredInForm = form.type === "ssl_certificate" && !!(form.checkHost ?? "").trim(); return ( <>

Secrets

{canEdit && (

{editingId ? "Edit secret" : "Add a secret"}

setForm({ ...form, name: e.target.value })} />
setForm({ ...form, expiryDate: e.target.value })} /> {monitoredInForm ? (
Read from the live certificate.
) : ( )}
{form.type === "ssl_certificate" && ( <>
setForm({ ...form, checkHost: e.target.value })} />
Connects over TLS and reads the certificate's real expiry, checked daily.
setForm({ ...form, checkPort: Number(e.target.value) })} />
)}
setForm({ ...form, warnDays: Number(e.target.value) })} />
setForm({ ...form, description: e.target.value })} />
setForm({ ...form, notes: e.target.value })} />
{editingId && ( )}
)}
setStatusFilter(e.target.value as typeof statusFilter)} > } shown={filtered.length} total={secrets?.length} onExport={exportCsv} /> {canEdit && selection.count > 0 && (
{selection.count} selected
)}
{canEdit && ( )} label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Type" sortKeyName="type" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Expiry" sortKeyName="expiryDate" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Days left" sortKeyName="daysLeft" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Status" sortKeyName="status" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Description" sortKeyName="description" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {canEdit && } {(pageItems ?? []).map((s) => ( {canEdit && ( )} {canEdit && ( )} ))} {secrets === null && } {secrets !== null && (sorted ?? []).length === 0 && ( 0 ? () => { setSearch(""); setStatusFilter("all"); } : undefined} /> )}
0 && (pageItems ?? []).every((s) => selection.isSelected(s.id))} onChange={() => selection.toggleAll((pageItems ?? []).map((s) => s.id))} /> Actions
selection.toggle(s.id)} /> {s.name} {TYPE_LABELS[s.type]} {s.expiryDate ?? Never} {s.checkHost && ( Auto )} {s.lastCheckError && ( Check failed )} {s.daysLeft === null ? "—" : s.daysLeft < 0 ? `${Math.abs(s.daysLeft)}d ago` : `${s.daysLeft}d`} {STATUS_LABEL[s.status]} {s.description ?? "—"}
{s.checkHost && ( )}
); }