Add runbooks, backup coverage, inventory, roles from groups, Prometheus metrics and event webhooks
- Runbooks: notes per server/integration, shown next to matching alerts - Backup coverage page across Proxmox and PBS, with a digest section - Hardware inventory with warranty, power and running cost - Authentik group to role mapping with preview and safeguards - /metrics (bearer token) and signed outgoing event webhooks - Docs: README, DATABASE, NOTIFICATIONS, ROLES and new API.md Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c36e2092c5
commit
c17e9aa140
55 files changed
+7177
-27
No files matched your search
@@ -13,6 +13,7 @@ import { ErrorNotice } from "../components/Notice";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import SilenceButton from "../components/SilenceButton";
|
||||
import RunPlaybookButton from "../components/RunPlaybookButton";
|
||||
import RunbookEntry from "../components/RunbookEntry";
|
||||
|
||||
const SEVERITY: Record<AlertSeverity, { label: string; badge: string; rank: number }> = {
|
||||
critical: { label: "Critical", badge: "bg-red-lt text-red", rank: 0 },
|
||||
@@ -243,6 +244,11 @@ export default function Alerts({ user }: { user: CurrentUser }) {
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
{a.target && (
|
||||
<div>
|
||||
<RunbookEntry targetType={a.target.type} targetId={a.target.id} targetName={a.target.name} canEdit={canSilence} forCategory={a.category} />
|
||||
</div>
|
||||
)}
|
||||
{a.affects && a.affects.length > 0 && (
|
||||
<div className="text-secondary small">
|
||||
Also takes down {a.affects.length} {a.affects.length === 1 ? "server" : "servers"}: {a.affects.join(", ")}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus } from "../api/client";
|
||||
import Pagination from "../components/Pagination";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { usePagination } from "../hooks/usePagination";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
import { useTableSearch } from "../hooks/useTableSearch";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { readableError } from "../utils/errors";
|
||||
|
||||
interface Row extends CoverageGuest {
|
||||
/** Worst first, so a default sort puts what needs attention at the top. */
|
||||
rank: number;
|
||||
}
|
||||
|
||||
const RANK: Record<CoverageStatus, number> = { failed: 0, none: 1, stale: 2, unknown: 3, ok: 4 };
|
||||
|
||||
const STATUS: Record<CoverageStatus, { label: string; badge: string; hint: string }> = {
|
||||
ok: { label: "Recent backup", badge: "bg-green-lt text-green", hint: "Backed up within the limit, and nothing failed." },
|
||||
stale: { label: "Stale", badge: "bg-yellow-lt text-yellow", hint: "Its newest backup is older than the limit." },
|
||||
failed: { label: "Failed", badge: "bg-red-lt text-red", hint: "The latest backup didn't succeed, or the newest snapshot failed verification." },
|
||||
none: { label: "No backup", badge: "bg-red-lt text-red", hint: "No backup found, and no backup job covers it." },
|
||||
unknown: { label: "Unknown", badge: "bg-secondary-lt text-secondary", hint: "A backup job covers it, but nothing here says when it last ran — typical when backups go somewhere other than a Backup Server." },
|
||||
};
|
||||
|
||||
const STALE_CHOICES = [1, 2, 3, 7, 14];
|
||||
|
||||
/**
|
||||
* What is and isn't backed up: every Proxmox guest, whether a backup job covers it, when it was last backed up (from Proxmox Backup Server
|
||||
* snapshots and Proxmox's own backup tasks), and whether that went well — one page instead of an alert per gap.
|
||||
*/
|
||||
export default function Backups() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const staleParam = Number(params.get("stale"));
|
||||
const staleDays = STALE_CHOICES.includes(staleParam) ? staleParam : 2;
|
||||
const statusParam = params.get("status");
|
||||
const status: CoverageStatus | "attention" | "" = statusParam === "attention" || (statusParam && statusParam in RANK) ? (statusParam as CoverageStatus | "attention") : "";
|
||||
|
||||
const [report, setReport] = useState<BackupCoverage | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
|
||||
function load(refresh = false) {
|
||||
setChecking(true);
|
||||
api.backups
|
||||
.coverage(staleDays, refresh)
|
||||
.then((r) => {
|
||||
setReport(r);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)))
|
||||
.finally(() => setChecking(false));
|
||||
}
|
||||
useEffect(() => load(), [staleDays]);
|
||||
|
||||
function setParam(key: string, value: string | null) {
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
if (value) next.set(key, value);
|
||||
else next.delete(key);
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
);
|
||||
}
|
||||
|
||||
const rows: Row[] = (report?.guests ?? []).map((g) => ({ ...g, rank: RANK[g.status] }));
|
||||
const shown = rows.filter((r) => (status === "" ? true : status === "attention" ? r.status === "failed" || r.status === "none" || r.status === "stale" : r.status === status));
|
||||
const tableSearch = useTableSearch(shown);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "rank", "asc", { url: true });
|
||||
const page = usePagination(sorted);
|
||||
const c = report?.counts;
|
||||
const trouble = (c?.failed ?? 0) + (c?.none ?? 0) + (c?.stale ?? 0);
|
||||
const badSources = (report?.sources ?? []).filter((s) => !s.ok);
|
||||
|
||||
function exportCsv() {
|
||||
if (!sorted) return;
|
||||
downloadCsv(
|
||||
"backup-coverage.csv",
|
||||
["Guest", "Type", "ID", "Node", "Cluster", "In a backup job", "Last backup", "Source", "Status", "Problem"],
|
||||
sorted.map((r) => [r.name, r.type === "qemu" ? "VM" : "Container", r.vmid, r.node, r.integrationName, r.inJob ? "yes" : "no", r.lastBackupAt ?? "", r.lastSource === "pbs" ? "Backup Server" : r.lastSource === "task" ? "Proxmox task" : "", STATUS[r.status].label, r.failure ?? ""]),
|
||||
);
|
||||
}
|
||||
|
||||
const cards: { label: string; value: string | number; color: string; note?: string }[] = [
|
||||
{ label: "Guests", value: report ? (c?.total ?? 0) : "…", color: "" },
|
||||
{ label: "Recent backup", value: report ? (c?.ok ?? 0) : "…", color: "text-green" },
|
||||
{ label: "Failed", value: report ? (c?.failed ?? 0) : "…", color: (c?.failed ?? 0) > 0 ? "text-red" : "" },
|
||||
{ label: "No backup", value: report ? (c?.none ?? 0) : "…", color: (c?.none ?? 0) > 0 ? "text-red" : "" },
|
||||
{ label: "Stale", value: report ? (c?.stale ?? 0) : "…", color: (c?.stale ?? 0) > 0 ? "text-yellow" : "", note: `older than ${staleDays} ${staleDays === 1 ? "day" : "days"}` },
|
||||
{ label: "Unknown", value: report ? (c?.unknown ?? 0) : "…", color: "text-secondary", note: (c?.unknown ?? 0) > 0 ? "in a job, last run not visible" : undefined },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<h2 className="page-title mb-0">Backup coverage</h2>
|
||||
<button className="btn btn-outline-secondary ms-auto" onClick={() => load(true)} disabled={checking}>
|
||||
{checking ? "Checking…" : "Check now"}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-secondary">
|
||||
Every Proxmox guest: is a backup job covering it, when was it last backed up, and did that go well. {report && trouble > 0 ? `${trouble} need a look.` : ""}
|
||||
</p>
|
||||
<ErrorNotice error={error} />
|
||||
{badSources.length > 0 && (
|
||||
<div className="alert alert-warning">
|
||||
Couldn't read everything — what is missing below isn't necessarily wrong:{" "}
|
||||
{badSources.map((s) => `${s.kind === "pbs" ? "Backup Server" : "Proxmox"} “${s.name}” (${s.error})`).join("; ")}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="row row-cards mb-3">
|
||||
{cards.map((card) => (
|
||||
<div className="col-6 col-lg-2" key={card.label}>
|
||||
<div className="card card-sm">
|
||||
<div className="card-body">
|
||||
<div className={`h2 mb-0 ${card.color}`}>{card.value}</div>
|
||||
<div className="text-secondary">{card.label}</div>
|
||||
{card.note && <div className="text-secondary small">{card.note}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<TableToolbar
|
||||
search={tableSearch.query}
|
||||
onSearch={tableSearch.setQuery}
|
||||
placeholder="Search guests…"
|
||||
filters={
|
||||
<>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="Show guests that are" value={status} onChange={(e) => setParam("status", e.target.value)}>
|
||||
<option value="">All guests</option>
|
||||
<option value="attention">Needing attention</option>
|
||||
{(Object.keys(RANK) as CoverageStatus[]).map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{STATUS[s].label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="Stale after" value={staleDays} onChange={(e) => setParam("stale", e.target.value === "2" ? null : e.target.value)}>
|
||||
{STALE_CHOICES.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
Stale after {d} {d === 1 ? "day" : "days"}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</>
|
||||
}
|
||||
shown={sorted?.length}
|
||||
total={rows.length}
|
||||
onExport={exportCsv}
|
||||
exportDisabled={!sorted || sorted.length === 0}
|
||||
/>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<SortableTh<Row> label="Guest" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="In a job" sortKeyName="inJob" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Last backup" sortKeyName="lastBackupAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Row> label="Status" sortKeyName="rank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{report === null && !error && (
|
||||
<tr>
|
||||
<td colSpan={4}>
|
||||
<BlockSkeleton lines={4} />
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{page.pageItems?.map((r) => (
|
||||
<tr key={`${r.integrationId}:${r.type}:${r.vmid}`}>
|
||||
<td>
|
||||
{r.name}
|
||||
<div className="text-secondary small">
|
||||
{r.type === "qemu" ? "VM" : "Container"} {r.vmid} · {r.node}
|
||||
{report && report.sources.filter((s) => s.kind === "proxmox").length > 1 ? ` · ${r.integrationName}` : ""}
|
||||
</div>
|
||||
{r.server && (
|
||||
<div className="small">
|
||||
is <Link to={`/servers/${r.server.id}`}>{r.server.name}</Link>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td>{r.inJob ? <span className="text-green">yes</span> : <span className="text-red">no</span>}</td>
|
||||
<td>
|
||||
{r.lastBackupAt ? (
|
||||
<>
|
||||
<TimeAgo value={r.lastBackupAt} />
|
||||
<div className="text-secondary small">{r.lastSource === "pbs" ? "Backup Server" : "Proxmox task"}</div>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-secondary">—</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<span className={`badge ${STATUS[r.status].badge}`} title={STATUS[r.status].hint}>
|
||||
{STATUS[r.status].label}
|
||||
</span>
|
||||
{r.failure && <div className="text-secondary small">{r.failure}</div>}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{report !== null && sorted?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
{rows.length === 0 ? (
|
||||
<>
|
||||
No Proxmox guests to show. Connect a Proxmox integration under <Link to="/integrations">Integrations</Link>.
|
||||
</>
|
||||
) : (
|
||||
"Nothing matches that."
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
|
||||
<div className="card-footer text-secondary small">
|
||||
“Last backup” is the newest snapshot of the guest on a Proxmox Backup Server, or the last successful Proxmox backup task that names it. A task from an “all guests” job doesn't
|
||||
name its guests, so a guest backed up to something other than a Backup Server reads “Unknown” rather than being guessed at. The result is kept for a minute; “Check now” asks again.
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { confirmDialog } from "../utils/dialogs";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { toast } from "../utils/toast";
|
||||
import UptimeRibbon from "../components/UptimeRibbon";
|
||||
import RunbookEntry from "../components/RunbookEntry";
|
||||
|
||||
const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
tailscale: "Tailscale",
|
||||
@@ -74,6 +75,7 @@ function typeBadgeStyle(colors: Record<string, string>, type: IntegrationType):
|
||||
|
||||
export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
const isAdmin = user.role === "admin";
|
||||
const isOperator = user.role === "admin" || user.role === "operator";
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
|
||||
@@ -257,6 +259,9 @@ export default function Integrations({ user }: { user: CurrentUser }) {
|
||||
<UptimeRibbon kind="integrations" id={i.id} name={i.name} />
|
||||
</div>
|
||||
)}
|
||||
<div className="mb-3">
|
||||
<RunbookEntry targetType="integration" targetId={i.id} targetName={i.name} canEdit={isOperator} offerAdd />
|
||||
</div>
|
||||
{result && !result.ok && testingId !== i.id && <div className="text-red small mb-3">{result.error}</div>}
|
||||
<div className="btn-list mt-auto">
|
||||
{i.enabled && (
|
||||
|
||||
@@ -0,0 +1,473 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type Asset, type AssetInput, type AssetKind, type CurrentUser, type InventoryConfig } from "../api/client";
|
||||
import SortableTh from "../components/SortableTh";
|
||||
import TableToolbar from "../components/TableToolbar";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { usePagination } from "../hooks/usePagination";
|
||||
import Pagination from "../components/Pagination";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
import { useTableSearch } from "../hooks/useTableSearch";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { downloadCsv } from "../utils/csv";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { KIND_HINTS, KIND_LABELS, money, warrantyDays, warrantyState, yearlyCost, yearlyKwh } from "../utils/inventory";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
const KINDS = Object.keys(KIND_LABELS) as AssetKind[];
|
||||
|
||||
interface Draft {
|
||||
id: number | null;
|
||||
name: string;
|
||||
kind: AssetKind;
|
||||
manufacturer: string;
|
||||
model: string;
|
||||
serial: string;
|
||||
purchaseDate: string;
|
||||
purchasePrice: string;
|
||||
warrantyUntil: string;
|
||||
location: string;
|
||||
rackUnit: string;
|
||||
powerWatts: string;
|
||||
serverId: string;
|
||||
notes: string;
|
||||
}
|
||||
|
||||
const EMPTY: Draft = { id: null, name: "", kind: "server", manufacturer: "", model: "", serial: "", purchaseDate: "", purchasePrice: "", warrantyUntil: "", location: "", rackUnit: "", powerWatts: "", serverId: "", notes: "" };
|
||||
|
||||
function toDraft(a: Asset): Draft {
|
||||
return {
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
kind: a.kind,
|
||||
manufacturer: a.manufacturer ?? "",
|
||||
model: a.model ?? "",
|
||||
serial: a.serial ?? "",
|
||||
purchaseDate: a.purchaseDate ?? "",
|
||||
purchasePrice: a.purchasePrice === null ? "" : String(a.purchasePrice),
|
||||
warrantyUntil: a.warrantyUntil ?? "",
|
||||
location: a.location ?? "",
|
||||
rackUnit: a.rackUnit ?? "",
|
||||
powerWatts: a.powerWatts === null ? "" : String(a.powerWatts),
|
||||
serverId: a.serverId === null ? "" : String(a.serverId),
|
||||
notes: a.notes ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function toInput(d: Draft): AssetInput {
|
||||
const num = (s: string) => (s.trim() === "" ? null : Number(s));
|
||||
return {
|
||||
name: d.name.trim(),
|
||||
kind: d.kind,
|
||||
manufacturer: d.manufacturer,
|
||||
model: d.model,
|
||||
serial: d.serial,
|
||||
purchaseDate: d.purchaseDate || null,
|
||||
purchasePrice: num(d.purchasePrice),
|
||||
warrantyUntil: d.warrantyUntil || null,
|
||||
location: d.location,
|
||||
rackUnit: d.rackUnit,
|
||||
powerWatts: num(d.powerWatts),
|
||||
serverId: d.serverId === "" ? null : Number(d.serverId),
|
||||
notes: d.notes,
|
||||
};
|
||||
}
|
||||
|
||||
function WarrantyBadge({ until }: { until: string | null }) {
|
||||
const state = warrantyState(until);
|
||||
const days = warrantyDays(until);
|
||||
if (state === "none" || days === null) return <span className="text-secondary">—</span>;
|
||||
if (state === "expired") return <span className="badge bg-red-lt text-red" title={until ?? undefined}>ended {Math.abs(days)} d ago</span>;
|
||||
if (state === "expiring") return <span className="badge bg-yellow-lt text-yellow" title={until ?? undefined}>ends in {days} d</span>;
|
||||
return <span className="text-secondary">until {until}</span>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hardware behind it all: what each machine is, when it was bought, how long it is covered, where it sits and what it draws —
|
||||
* and, with a price of power, roughly what the lot costs to run. Everyone signed in can look; operators keep it up to date.
|
||||
*/
|
||||
export default function Inventory({ user }: { user: CurrentUser }) {
|
||||
const canEdit = user.role === "admin" || user.role === "operator";
|
||||
const isAdmin = user.role === "admin";
|
||||
const [assets, setAssets] = useState<Asset[] | null>(null);
|
||||
const [config, setConfig] = useState<InventoryConfig>({ currency: "", pricePerKwh: null });
|
||||
const [servers, setServers] = useState<{ id: number; name: string }[]>([]);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [priceText, setPriceText] = useState("");
|
||||
const [currencyText, setCurrencyText] = useState("");
|
||||
|
||||
const [params, setParams] = useSearchParams();
|
||||
const kind = (KINDS as string[]).includes(params.get("kind") ?? "") ? (params.get("kind") as AssetKind) : "";
|
||||
|
||||
function load() {
|
||||
api.inventory
|
||||
.list()
|
||||
.then((res) => {
|
||||
setAssets(res.assets);
|
||||
setConfig(res.config);
|
||||
setServers(res.servers);
|
||||
setPriceText(res.config.pricePerKwh === null ? "" : String(res.config.pricePerKwh));
|
||||
setCurrencyText(res.config.currency);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}
|
||||
useEffect(load, []);
|
||||
|
||||
const ofKind = (assets ?? []).filter((a) => kind === "" || a.kind === kind);
|
||||
const tableSearch = useTableSearch(ofKind);
|
||||
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "name", "asc", { url: true });
|
||||
const page = usePagination(sorted);
|
||||
|
||||
const all = assets ?? [];
|
||||
const covered = all.filter((a) => warrantyState(a.warrantyUntil) === "ok").length;
|
||||
const expiring = all.filter((a) => warrantyState(a.warrantyUntil) === "expiring").length;
|
||||
const expired = all.filter((a) => warrantyState(a.warrantyUntil) === "expired").length;
|
||||
const watts = all.reduce((n, a) => n + (a.powerWatts ?? 0), 0);
|
||||
const cost = yearlyCost(watts, config.pricePerKwh);
|
||||
const spent = all.reduce((n, a) => n + (a.purchasePrice ?? 0), 0);
|
||||
|
||||
async function save(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!draft) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
if (draft.id === null) await api.inventory.create(toInput(draft));
|
||||
else await api.inventory.update(draft.id, toInput(draft));
|
||||
toast.success(draft.id === null ? `Added ${draft.name}.` : "Saved.");
|
||||
setDraft(null);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(a: Asset) {
|
||||
if (!(await confirmDialog({ title: "Remove from the inventory", message: `Remove "${a.name}"?`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.inventory.remove(a.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function saveConfig(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
try {
|
||||
const price = priceText.trim() === "" ? null : Number(priceText.replace(",", "."));
|
||||
const res = await api.inventory.setConfig({ currency: currencyText.trim(), pricePerKwh: price });
|
||||
setConfig(res.config);
|
||||
toast.success("Saved.");
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
function exportCsv() {
|
||||
if (!sorted) return;
|
||||
downloadCsv(
|
||||
"inventory.csv",
|
||||
["Name", "Kind", "Manufacturer", "Model", "Serial", "Location", "Rack unit", "Purchased", "Price", "Warranty until", "Power (W)", "Server", "Notes"],
|
||||
sorted.map((a) => [a.name, KIND_LABELS[a.kind], a.manufacturer ?? "", a.model ?? "", a.serial ?? "", a.location ?? "", a.rackUnit ?? "", a.purchaseDate ?? "", a.purchasePrice ?? "", a.warrantyUntil ?? "", a.powerWatts ?? "", a.server?.name ?? "", a.notes ?? ""]),
|
||||
);
|
||||
}
|
||||
|
||||
const set = <K extends keyof Draft>(key: K, value: Draft[K]) => setDraft((d) => (d ? { ...d, [key]: value } : d));
|
||||
|
||||
const cards: { label: string; value: string; note?: string; color: string }[] = [
|
||||
{ label: "Hardware", value: assets ? String(all.length) : "…", note: spent > 0 ? `${money(spent, config.currency)} paid` : undefined, color: "" },
|
||||
{ label: "Under warranty", value: assets ? String(covered + expiring) : "…", note: expiring > 0 ? `${expiring} ending within 90 days` : expired > 0 ? `${expired} ended` : undefined, color: expiring > 0 ? "text-yellow" : "text-green" },
|
||||
{ label: "Power draw", value: assets ? `${watts} W` : "…", note: watts > 0 ? `${yearlyKwh(watts).toLocaleString("sv-SE")} kWh a year` : undefined, color: "" },
|
||||
{
|
||||
label: "Running cost",
|
||||
value: cost !== null ? `${money(cost, config.currency)} / year` : "—",
|
||||
note: cost === null ? (config.pricePerKwh === null ? "set a price of power below" : "add power draws to see it") : undefined,
|
||||
color: "",
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex align-items-center mb-3">
|
||||
<h2 className="page-title mb-0">Inventory</h2>
|
||||
{canEdit && !draft && (
|
||||
<button className="btn btn-primary ms-auto" onClick={() => setDraft({ ...EMPTY })}>
|
||||
Add hardware
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
<div className="row row-cards mb-3">
|
||||
{cards.map((c) => (
|
||||
<div className="col-6 col-lg-3" key={c.label}>
|
||||
<div className="card card-sm">
|
||||
<div className="card-body">
|
||||
<div className={`h2 mb-0 ${c.color}`}>{c.value}</div>
|
||||
<div className="text-secondary">{c.label}</div>
|
||||
{c.note && <div className="text-secondary small">{c.note}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{draft && (
|
||||
<form className="card mb-3" onSubmit={save}>
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{draft.id === null ? "Add hardware" : `Edit ${draft.name || "hardware"}`}</h3>
|
||||
</div>
|
||||
<div className="card-body row g-3">
|
||||
<div className="col-md-5">
|
||||
<label className="form-label" htmlFor="inv-name">
|
||||
Name
|
||||
</label>
|
||||
<input id="inv-name" className="form-control" required maxLength={120} value={draft.name} onChange={(e) => set("name", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="inv-kind">
|
||||
Kind
|
||||
</label>
|
||||
<select id="inv-kind" className="form-select" value={draft.kind} onChange={(e) => set("kind", e.target.value as AssetKind)}>
|
||||
{KINDS.map((k) => (
|
||||
<option key={k} value={k}>
|
||||
{KIND_LABELS[k]} — {KIND_HINTS[k]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="inv-server">
|
||||
Is the server
|
||||
</label>
|
||||
<select id="inv-server" className="form-select" value={draft.serverId} onChange={(e) => set("serverId", e.target.value)}>
|
||||
<option value="">— not a server here —</option>
|
||||
{servers.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="inv-maker">
|
||||
Manufacturer
|
||||
</label>
|
||||
<input id="inv-maker" className="form-control" maxLength={100} value={draft.manufacturer} onChange={(e) => set("manufacturer", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="inv-model">
|
||||
Model
|
||||
</label>
|
||||
<input id="inv-model" className="form-control" maxLength={100} value={draft.model} onChange={(e) => set("model", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="inv-serial">
|
||||
Serial number
|
||||
</label>
|
||||
<input id="inv-serial" className="form-control" maxLength={100} value={draft.serial} onChange={(e) => set("serial", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="inv-bought">
|
||||
Bought
|
||||
</label>
|
||||
<input id="inv-bought" type="date" className="form-control" value={draft.purchaseDate} onChange={(e) => set("purchaseDate", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="inv-price">
|
||||
Price {config.currency && <span className="text-secondary">({config.currency})</span>}
|
||||
</label>
|
||||
<input id="inv-price" type="number" min={0} step="any" className="form-control" value={draft.purchasePrice} onChange={(e) => set("purchasePrice", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="inv-warranty">
|
||||
Warranty until
|
||||
</label>
|
||||
<input id="inv-warranty" type="date" className="form-control" value={draft.warrantyUntil} onChange={(e) => set("warrantyUntil", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="inv-power">
|
||||
Typical power draw
|
||||
</label>
|
||||
<div className="input-group">
|
||||
<input id="inv-power" type="number" min={0} max={100000} step={1} className="form-control" value={draft.powerWatts} onChange={(e) => set("powerWatts", e.target.value)} />
|
||||
<span className="input-group-text">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-md-5">
|
||||
<label className="form-label" htmlFor="inv-location">
|
||||
Where it is
|
||||
</label>
|
||||
<input id="inv-location" className="form-control" maxLength={120} placeholder="e.g. Rack in the cellar" value={draft.location} onChange={(e) => set("location", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-2">
|
||||
<label className="form-label" htmlFor="inv-unit">
|
||||
Rack unit
|
||||
</label>
|
||||
<input id="inv-unit" className="form-control" maxLength={30} placeholder="U12" value={draft.rackUnit} onChange={(e) => set("rackUnit", e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-5">
|
||||
<label className="form-label" htmlFor="inv-notes">
|
||||
Notes
|
||||
</label>
|
||||
<input id="inv-notes" className="form-control" maxLength={2000} value={draft.notes} onChange={(e) => set("notes", e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer d-flex gap-2">
|
||||
<button type="submit" className="btn btn-primary" disabled={busy || draft.name.trim() === ""}>
|
||||
{busy ? "Saving…" : "Save"}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="card mb-3">
|
||||
<TableToolbar
|
||||
search={tableSearch.query}
|
||||
onSearch={tableSearch.setQuery}
|
||||
placeholder="Search hardware…"
|
||||
filters={
|
||||
<select
|
||||
className="form-select form-select-sm w-auto"
|
||||
aria-label="Show hardware of kind"
|
||||
value={kind}
|
||||
onChange={(e) =>
|
||||
setParams(
|
||||
(prev) => {
|
||||
const next = new URLSearchParams(prev);
|
||||
if (e.target.value) next.set("kind", e.target.value);
|
||||
else next.delete("kind");
|
||||
return next;
|
||||
},
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
>
|
||||
<option value="">Every kind</option>
|
||||
{KINDS.map((k) => (
|
||||
<option key={k} value={k}>
|
||||
{KIND_LABELS[k]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
}
|
||||
shown={sorted?.length}
|
||||
total={all.length}
|
||||
onExport={exportCsv}
|
||||
exportDisabled={!sorted || sorted.length === 0}
|
||||
/>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<SortableTh<Asset> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Asset> label="Kind" sortKeyName="kind" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Asset> label="Where" sortKeyName="location" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Asset> label="Bought" sortKeyName="purchaseDate" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Asset> label="Warranty" sortKeyName="warrantyUntil" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<Asset> label="Power" sortKeyName="powerWatts" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
{canEdit && <th className="w-1">Actions</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{assets === null && !error && (
|
||||
<tr>
|
||||
<td colSpan={canEdit ? 7 : 6}>
|
||||
<BlockSkeleton lines={3} />
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{page.pageItems?.map((a) => (
|
||||
<tr key={a.id}>
|
||||
<td>
|
||||
{a.name}
|
||||
{(a.manufacturer || a.model) && <div className="text-secondary small">{[a.manufacturer, a.model].filter(Boolean).join(" ")}</div>}
|
||||
{a.server && (
|
||||
<div className="small">
|
||||
is <Link to={`/servers/${a.server.id}`}>{a.server.name}</Link>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td>{KIND_LABELS[a.kind]}</td>
|
||||
<td>
|
||||
{a.location ?? "—"}
|
||||
{a.rackUnit && <span className="text-secondary"> · {a.rackUnit}</span>}
|
||||
</td>
|
||||
<td className="text-secondary">
|
||||
{a.purchaseDate ?? "—"}
|
||||
{a.purchasePrice !== null && <div className="small">{money(a.purchasePrice, config.currency)}</div>}
|
||||
</td>
|
||||
<td>
|
||||
<WarrantyBadge until={a.warrantyUntil} />
|
||||
</td>
|
||||
<td>{a.powerWatts === null ? <span className="text-secondary">—</span> : `${a.powerWatts} W`}</td>
|
||||
{canEdit && (
|
||||
<td>
|
||||
<div className="btn-list flex-nowrap">
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => setDraft(toDraft(a))}>
|
||||
Edit
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(a)}>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
{assets !== null && sorted?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={canEdit ? 7 : 6} className="text-secondary text-center">
|
||||
{tableSearch.active || kind ? "Nothing matches that." : `Nothing in the inventory yet.${canEdit ? " Add the first piece of hardware." : ""}`}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
|
||||
</div>
|
||||
|
||||
{isAdmin && (
|
||||
<form className="card" onSubmit={saveConfig}>
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Price of power</h3>
|
||||
</div>
|
||||
<div className="card-body row g-3 align-items-end">
|
||||
<div className="col-md-3">
|
||||
<label className="form-label" htmlFor="inv-kwh">
|
||||
Price per kWh
|
||||
</label>
|
||||
<input id="inv-kwh" type="number" min={0} step="any" className="form-control" value={priceText} onChange={(e) => setPriceText(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-2">
|
||||
<label className="form-label" htmlFor="inv-cur">
|
||||
Currency
|
||||
</label>
|
||||
<input id="inv-cur" className="form-control" maxLength={8} placeholder="SEK" value={currencyText} onChange={(e) => setCurrencyText(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-7 text-secondary small">
|
||||
Used for the running cost above: each machine's typical draw, all day, all year, at this price. It is a rough guide — a machine rarely draws its typical figure all the time.
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer">
|
||||
<button type="submit" className="btn btn-primary">
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import TimeAgo from "../components/TimeAgo";
|
||||
import UptimeRibbon from "../components/UptimeRibbon";
|
||||
import RunsOn from "../components/RunsOn";
|
||||
import RunPlaybook from "../components/RunPlaybook";
|
||||
import RunbookPanel from "../components/RunbookPanel";
|
||||
import UpdatesBadge from "../components/UpdatesBadge";
|
||||
import { agentState, agentVersionWords } from "../utils/agent";
|
||||
import ServerTags from "../components/ServerTags";
|
||||
@@ -808,6 +809,14 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
|
||||
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
|
||||
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Runbooks</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
|
||||
</div>
|
||||
</div>
|
||||
{canEditTasks && (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
|
||||
@@ -4,11 +4,13 @@ import { NavLink, Outlet } from "react-router-dom";
|
||||
const SUB_NAV = [
|
||||
{ to: "/settings/notifications", label: "Notifications" },
|
||||
{ to: "/settings/badges", label: "Badges" },
|
||||
{ to: "/settings/sign-in", label: "Sign-in" },
|
||||
{ to: "/settings/display", label: "Display" },
|
||||
{ to: "/settings/tags", label: "Tags" },
|
||||
{ to: "/settings/alert-tickets", label: "Alert tickets" },
|
||||
{ to: "/settings/names", label: "Names" },
|
||||
{ to: "/settings/share", label: "Share links" },
|
||||
{ to: "/settings/api", label: "API and webhooks" },
|
||||
{ to: "/settings/cache", label: "Cache" },
|
||||
{ to: "/settings/logs", label: "Logs" },
|
||||
{ to: "/settings/backup", label: "Backup" },
|
||||
|
||||
+20
-3
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type UserRecord, type UserRole } from "../api/client";
|
||||
import { formatDateTime } from "../utils/date";
|
||||
import { useSortable } from "../hooks/useSortable";
|
||||
@@ -14,11 +15,16 @@ export default function Users() {
|
||||
const [users, setUsers] = useState<UserRecord[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [savingId, setSavingId] = useState<number | null>(null);
|
||||
// Roles follow sign-in groups (Settings → Sign-in): they are shown, not set here.
|
||||
const [followGroups, setFollowGroups] = useState(false);
|
||||
|
||||
function load() {
|
||||
api.users
|
||||
.list()
|
||||
.then((res) => setUsers(res.users))
|
||||
.then((res) => {
|
||||
setUsers(res.users);
|
||||
setFollowGroups(res.rolesFollowGroups);
|
||||
})
|
||||
.catch((err) => setError(String(err)));
|
||||
}
|
||||
|
||||
@@ -58,6 +64,12 @@ export default function Users() {
|
||||
</button>
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
{followGroups && (
|
||||
<div className="alert alert-info">
|
||||
Roles are set from sign-in groups, so they can't be changed here: change a person's group in the identity provider, and their role follows at their next sign-in.{" "}
|
||||
<Link to="/settings/sign-in">Sign-in settings</Link>
|
||||
</div>
|
||||
)}
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<SearchBox value={tableSearch.query} onChange={tableSearch.setQuery} />
|
||||
@@ -69,6 +81,7 @@ export default function Users() {
|
||||
<SortableTh<UserRecord> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<UserRecord> label="Email" sortKeyName="email" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<SortableTh<UserRecord> label="Role" sortKeyName="role" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
|
||||
<th>Groups at last sign-in</th>
|
||||
<SortableTh<UserRecord>
|
||||
label="Last login"
|
||||
sortKeyName="lastLoginAt"
|
||||
@@ -87,7 +100,8 @@ export default function Users() {
|
||||
<select
|
||||
className="form-select form-select-sm"
|
||||
value={u.role}
|
||||
disabled={savingId === u.id}
|
||||
disabled={savingId === u.id || followGroups}
|
||||
title={followGroups ? "Set from sign-in groups" : undefined}
|
||||
onChange={(e) => changeRole(u.id, e.target.value as UserRole)}
|
||||
>
|
||||
{ROLES.map((r) => (
|
||||
@@ -97,12 +111,15 @@ export default function Users() {
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
<td className="text-secondary small">
|
||||
{u.groups === null ? "—" : u.groups.length === 0 ? "none" : u.groups.length <= 3 ? u.groups.join(", ") : `${u.groups.slice(0, 3).join(", ")} and ${u.groups.length - 3} more`}
|
||||
</td>
|
||||
<td>{u.lastLoginAt ? formatDateTime(new Date(u.lastLoginAt)) : "never"}</td>
|
||||
</tr>
|
||||
))}
|
||||
{sorted?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
<td colSpan={5} className="text-secondary text-center">
|
||||
No users yet.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type EventWebhook, type MetricsToken, type WebhookEventName } from "../../api/client";
|
||||
import CopyButton from "../../components/CopyButton";
|
||||
import TimeAgo from "../../components/TimeAgo";
|
||||
import { ErrorNotice } from "../../components/Notice";
|
||||
import { confirmDialog } from "../../utils/dialogs";
|
||||
import { readableError } from "../../utils/errors";
|
||||
import { toast } from "../../utils/toast";
|
||||
|
||||
const EVENT_WORDS: Record<WebhookEventName, string> = {
|
||||
"alert.opened": "A problem begins",
|
||||
"alert.resolved": "A problem ends",
|
||||
"maintenance.started": "Maintenance begins",
|
||||
"maintenance.ended": "Maintenance ends",
|
||||
};
|
||||
|
||||
const hostOf = (address: string) => {
|
||||
try {
|
||||
return new URL(address).host;
|
||||
} catch {
|
||||
return address;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Two ways for other systems to work with this one: a read-only /metrics address for Prometheus (and so Grafana), opened with a token of
|
||||
* its own, and webhooks that are sent a signed JSON message when an alert begins or ends or maintenance starts or finishes.
|
||||
*/
|
||||
export default function ApiSettings() {
|
||||
const [tokens, setTokens] = useState<MetricsToken[] | null>(null);
|
||||
const [hooks, setHooks] = useState<EventWebhook[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [tokenLabel, setTokenLabel] = useState("");
|
||||
const [newSecret, setNewSecret] = useState<{ label: string; secret: string } | null>(null);
|
||||
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [hookLabel, setHookLabel] = useState("");
|
||||
const [hookUrl, setHookUrl] = useState("");
|
||||
const [hookSecret, setHookSecret] = useState("");
|
||||
const [hookEvents, setHookEvents] = useState<Set<WebhookEventName>>(new Set(["alert.opened", "alert.resolved"]));
|
||||
const [testResults, setTestResults] = useState<Record<number, string>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
function load() {
|
||||
api.metricsTokens
|
||||
.list()
|
||||
.then((r) => setTokens(r.tokens))
|
||||
.catch((err) => setError(readableError(err)));
|
||||
api.eventWebhooks
|
||||
.list()
|
||||
.then((r) => setHooks(r.webhooks))
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}
|
||||
useEffect(load, []);
|
||||
|
||||
async function makeToken(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await api.metricsTokens.create(tokenLabel.trim());
|
||||
setNewSecret({ label: res.token.label, secret: res.secret });
|
||||
setTokenLabel("");
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeToken(t: MetricsToken) {
|
||||
if (!(await confirmDialog({ title: "Remove metrics token", message: `Remove "${t.label}"? Whatever scrapes with it stops working at once.`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.metricsTokens.remove(t.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function makeHook(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.eventWebhooks.create({ label: hookLabel.trim(), url: hookUrl.trim(), secret: hookSecret || undefined, events: [...hookEvents] });
|
||||
toast.success(`Added ${hookLabel.trim()}.`);
|
||||
setHookLabel("");
|
||||
setHookUrl("");
|
||||
setHookSecret("");
|
||||
setAdding(false);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleHook(h: EventWebhook) {
|
||||
try {
|
||||
await api.eventWebhooks.setEnabled(h.id, !h.enabled);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function testHook(h: EventWebhook) {
|
||||
setTestResults((r) => ({ ...r, [h.id]: "Sending…" }));
|
||||
try {
|
||||
const res = await api.eventWebhooks.test(h.id);
|
||||
setTestResults((r) => ({ ...r, [h.id]: res.ok ? `✓ delivered (${res.result})` : `✕ ${res.result}` }));
|
||||
load();
|
||||
} catch (err) {
|
||||
setTestResults((r) => ({ ...r, [h.id]: `✕ ${readableError(err)}` }));
|
||||
}
|
||||
}
|
||||
|
||||
async function removeHook(h: EventWebhook) {
|
||||
if (!(await confirmDialog({ title: "Remove webhook", message: `Remove "${h.label}"? It stops being sent anything.`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.eventWebhooks.remove(h.id);
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
const origin = window.location.origin;
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3 className="mb-3">API and webhooks</h3>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Metrics for Prometheus</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
<code>{origin}/metrics</code> answers in Prometheus's text format — whether each server is up, its load, memory, disks and waiting updates, the alert counts, which integrations work, maintenance, and things about to expire — so a
|
||||
Grafana dashboard or Prometheus alert can use it. It is read-only and opens with a token sent as <code>Authorization: Bearer …</code>; a token in the address isn't accepted. It reads what the app already knows, so a scrape every 15 seconds is cheap.
|
||||
</p>
|
||||
{newSecret && (
|
||||
<div className="border border-success rounded p-3 mb-3">
|
||||
<div className="fw-bold mb-1">Token for {newSecret.label}</div>
|
||||
<div className="text-secondary mb-2">Copy it now — it can't be shown again. If it's lost, remove the token and make a new one.</div>
|
||||
<div className="input-group mb-2">
|
||||
<input className="form-control" readOnly value={newSecret.secret} aria-label="The metrics token" onFocus={(e) => e.currentTarget.select()} />
|
||||
<CopyButton text={newSecret.secret} />
|
||||
</div>
|
||||
<div className="text-secondary small mb-1">In prometheus.yml:</div>
|
||||
<pre className="border rounded p-2 mb-2" style={{ fontSize: "0.8125rem" }}>
|
||||
{`scrape_configs:
|
||||
- job_name: homelab-manager
|
||||
scheme: ${window.location.protocol === "https:" ? "https" : "http"}
|
||||
metrics_path: /metrics
|
||||
authorization:
|
||||
credentials: ${newSecret.secret}
|
||||
static_configs:
|
||||
- targets: ["${window.location.host}"]`}
|
||||
</pre>
|
||||
<button className="btn btn-sm" onClick={() => setNewSecret(null)}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<form className="d-flex flex-wrap gap-2 mb-3" onSubmit={makeToken}>
|
||||
<input className="form-control w-auto" style={{ minWidth: 220 }} required maxLength={60} placeholder="Name, e.g. Prometheus" aria-label="Name for the new token" value={tokenLabel} onChange={(e) => setTokenLabel(e.target.value)} />
|
||||
<button className="btn btn-primary" disabled={busy || tokenLabel.trim() === ""}>
|
||||
Make a token
|
||||
</button>
|
||||
</form>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Made</th>
|
||||
<th>Last used</th>
|
||||
<th className="w-1">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{tokens?.map((t) => (
|
||||
<tr key={t.id}>
|
||||
<td>
|
||||
{t.label} <span className="text-secondary small">{t.tokenPrefix}…</span>
|
||||
</td>
|
||||
<td className="text-secondary">
|
||||
{t.createdBy ?? "—"}, <TimeAgo value={t.createdAt} fromDb />
|
||||
</td>
|
||||
<td className="text-secondary">{t.lastUsedAt ? <TimeAgo value={t.lastUsedAt} /> : "Never"}</td>
|
||||
<td>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void removeToken(t)}>
|
||||
Remove
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{tokens?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
No tokens yet, so /metrics refuses everyone.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Event webhooks</h3>
|
||||
{!adding && (
|
||||
<div className="card-actions">
|
||||
<button className="btn btn-sm btn-primary" onClick={() => setAdding(true)}>
|
||||
Add a webhook
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
A webhook is sent a JSON message when something happens, for Home Assistant, n8n or a status board. This is separate from the chat-style webhook under Notifications, which carries the sentence a person would read. A problem is announced on the same terms as a
|
||||
notification — one under maintenance isn't until it ends. If you give a secret, each message carries <code>X-HLM-Signature: sha256=…</code>, an HMAC of the body, so the receiver can tell it came from here. A failed delivery is tried once more.
|
||||
</p>
|
||||
{adding && (
|
||||
<form className="border rounded p-3 mb-3" onSubmit={makeHook}>
|
||||
<div className="row g-3">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="wh-label">
|
||||
Name
|
||||
</label>
|
||||
<input id="wh-label" className="form-control" required maxLength={60} placeholder="Home Assistant" value={hookLabel} onChange={(e) => setHookLabel(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-8">
|
||||
<label className="form-label" htmlFor="wh-url">
|
||||
Address
|
||||
</label>
|
||||
<input id="wh-url" type="url" className="form-control" required maxLength={500} placeholder="https://ha.example.lan/api/webhook/…" value={hookUrl} onChange={(e) => setHookUrl(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label" htmlFor="wh-secret">
|
||||
Secret (optional, signs each message)
|
||||
</label>
|
||||
<input id="wh-secret" type="password" className="form-control" maxLength={200} autoComplete="off" value={hookSecret} onChange={(e) => setHookSecret(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<div className="form-label">Send when</div>
|
||||
{(Object.keys(EVENT_WORDS) as WebhookEventName[]).map((ev) => (
|
||||
<label key={ev} className="form-check mb-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
checked={hookEvents.has(ev)}
|
||||
onChange={(e) =>
|
||||
setHookEvents((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (e.target.checked) next.add(ev);
|
||||
else next.delete(ev);
|
||||
return next;
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="form-check-label">
|
||||
{EVENT_WORDS[ev]} <code className="small">{ev}</code>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="btn-list mt-3">
|
||||
<button className="btn btn-primary" disabled={busy || hookLabel.trim() === "" || hookUrl.trim() === "" || hookEvents.size === 0}>
|
||||
{busy ? "Adding…" : "Add"}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setAdding(false)}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Sends</th>
|
||||
<th>Last</th>
|
||||
<th className="w-1">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{hooks?.map((h) => (
|
||||
<tr key={h.id} className={h.enabled ? undefined : "text-secondary"}>
|
||||
<td>
|
||||
{h.label} {!h.enabled && <span className="badge bg-secondary-lt text-secondary">off</span>} {h.hasSecret && <span className="badge bg-green-lt text-green">signed</span>}
|
||||
<div className="text-secondary small">{hostOf(h.url)}</div>
|
||||
</td>
|
||||
<td>
|
||||
<div className="d-flex flex-wrap gap-1">
|
||||
{h.events.map((ev) => (
|
||||
<span key={ev} className="badge bg-blue-lt text-blue">
|
||||
{ev}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td className="small">
|
||||
{testResults[h.id] ?? (h.lastAttemptAt ? (
|
||||
<>
|
||||
<span className={h.lastResult?.startsWith("2") ? "text-green" : "text-red"}>{h.lastResult}</span> <span className="text-secondary"><TimeAgo value={h.lastAttemptAt} /></span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-secondary">not sent yet</span>
|
||||
))}
|
||||
</td>
|
||||
<td>
|
||||
<div className="btn-list flex-nowrap">
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => void testHook(h)}>
|
||||
Test
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => void toggleHook(h)}>
|
||||
{h.enabled ? "Turn off" : "Turn on"}
|
||||
</button>
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void removeHook(h)}>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{hooks?.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className="text-secondary text-center">
|
||||
No webhooks yet.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type GroupRolePreview, type SignInSettings as SignInSettingsData } from "../../api/client";
|
||||
import { ErrorNotice } from "../../components/Notice";
|
||||
import { PageSkeleton } from "../../components/Skeleton";
|
||||
import { readableError } from "../../utils/errors";
|
||||
import { toast } from "../../utils/toast";
|
||||
|
||||
const DEFAULTS: SignInSettingsData = { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" };
|
||||
|
||||
/** One name per line or separated by commas — whichever is easier to paste in. */
|
||||
const parseNames = (text: string): string[] => [...new Set(text.split(/[\n,]/).map((s) => s.trim()).filter(Boolean))];
|
||||
|
||||
/**
|
||||
* Who is an administrator, an operator or a viewer, decided from the groups the identity provider (Authentik) says a person is in, each
|
||||
* time they sign in — instead of by hand on the Users page. Off by default. "Check" shows what each person would become, from the
|
||||
* groups they had at their last sign-in, before it is switched on.
|
||||
*/
|
||||
export default function SignInSettings() {
|
||||
const [loaded, setLoaded] = useState<SignInSettingsData | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [claim, setClaim] = useState("groups");
|
||||
const [adminText, setAdminText] = useState("");
|
||||
const [operatorText, setOperatorText] = useState("");
|
||||
const [otherwise, setOtherwise] = useState<"viewer" | "keep">("viewer");
|
||||
const [preview, setPreview] = useState<GroupRolePreview | null>(null);
|
||||
const [busy, setBusy] = useState<"check" | "save" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
api.settings
|
||||
.get()
|
||||
.then((res) => {
|
||||
const s = res.settings.signIn ?? DEFAULTS;
|
||||
setLoaded(s);
|
||||
setEnabled(s.roleFromGroups);
|
||||
setClaim(s.groupsClaim);
|
||||
setAdminText(s.adminGroups.join("\n"));
|
||||
setOperatorText(s.operatorGroups.join("\n"));
|
||||
setOtherwise(s.otherwise);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}, []);
|
||||
|
||||
if (!loaded) return error ? <ErrorNotice error={error} /> : <PageSkeleton />;
|
||||
|
||||
const draft = (): SignInSettingsData => ({ roleFromGroups: enabled, groupsClaim: claim.trim() || "groups", adminGroups: parseNames(adminText), operatorGroups: parseNames(operatorText), otherwise });
|
||||
const dirty = JSON.stringify(draft()) !== JSON.stringify(loaded);
|
||||
|
||||
async function check() {
|
||||
setBusy("check");
|
||||
setError(null);
|
||||
try {
|
||||
const d = draft();
|
||||
setPreview(await api.users.previewGroupRoles({ groupsClaim: d.groupsClaim, adminGroups: d.adminGroups, operatorGroups: d.operatorGroups, otherwise: d.otherwise }));
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
setBusy("save");
|
||||
setError(null);
|
||||
try {
|
||||
const d = draft();
|
||||
await api.settings.update({ signIn: d });
|
||||
setLoaded(d);
|
||||
toast.success(d.roleFromGroups ? "Saved. Roles now follow groups at each sign-in." : "Saved. Roles are set by hand on the Users page.");
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}
|
||||
|
||||
const noAdmin = enabled && preview !== null && preview.adminsAfter === 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex align-items-center justify-content-between mb-3">
|
||||
<h3 className="mb-0">Sign-in</h3>
|
||||
<button className="btn btn-primary" onClick={save} disabled={busy !== null || !dirty || noAdmin}>
|
||||
{busy === "save" ? "Saving…" : "Save"}
|
||||
</button>
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Roles from groups</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
By default a new person is a viewer until an administrator changes their role on the Users page. Here you can let the groups the identity provider reports decide it instead:
|
||||
at every sign-in a person is an administrator if they are in an admin group, an operator if they are in an operator group, and otherwise what you choose below.
|
||||
In Authentik the <code>groups</code> claim comes with the <em>profile</em> scope this app already asks for.
|
||||
</p>
|
||||
<label className="form-check mb-3">
|
||||
<input type="checkbox" className="form-check-input" checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />
|
||||
<span className="form-check-label">Set roles from groups at each sign-in</span>
|
||||
</label>
|
||||
<div className="row g-3">
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="si-claim">
|
||||
Claim that holds the groups
|
||||
</label>
|
||||
<input id="si-claim" className="form-control" value={claim} onChange={(e) => setClaim(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="si-admin">
|
||||
Admin groups
|
||||
</label>
|
||||
<textarea id="si-admin" className="form-control" rows={3} placeholder={"homelab-admins"} value={adminText} onChange={(e) => setAdminText(e.target.value)} />
|
||||
<div className="form-hint">One per line, or separated by commas. Case doesn't matter.</div>
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="si-operator">
|
||||
Operator groups
|
||||
</label>
|
||||
<textarea id="si-operator" className="form-control" rows={3} placeholder={"homelab-ops"} value={operatorText} onChange={(e) => setOperatorText(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<label className="form-label" htmlFor="si-otherwise">
|
||||
Someone in none of those groups
|
||||
</label>
|
||||
<select id="si-otherwise" className="form-select" value={otherwise} onChange={(e) => setOtherwise(e.target.value as "viewer" | "keep")}>
|
||||
<option value="viewer">becomes a viewer</option>
|
||||
<option value="keep">keeps the role they already have</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="alert alert-info mt-3 mb-0">
|
||||
Safeguards: if a sign-in carries no groups at all (a wrong claim name, say) roles are left exactly as they are; the only administrator is never demoted by a group rule;
|
||||
and the very first person to sign in is still the administrator. While this is on, roles can't be set by hand — a role set on the Users page would be undone at the next sign-in.
|
||||
</div>
|
||||
</div>
|
||||
<div className="card-footer d-flex flex-wrap align-items-center gap-2">
|
||||
<button className="btn btn-outline-secondary" onClick={check} disabled={busy !== null}>
|
||||
{busy === "check" ? "Checking…" : "Check against the groups people had last time"}
|
||||
</button>
|
||||
<span className="text-secondary small">Changes nothing — it shows what each person would be.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{preview && (
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">What these rules would do</h3>
|
||||
</div>
|
||||
{preview.adminsAfter === 0 && (
|
||||
<div className="alert alert-danger m-3 mb-0" role="alert">
|
||||
With these rules nobody would be an administrator. Add an admin group that someone is in before switching this on.
|
||||
</div>
|
||||
)}
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Person</th>
|
||||
<th>Groups at last sign-in</th>
|
||||
<th>Now</th>
|
||||
<th>Would be</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{preview.people.map((p) => (
|
||||
<tr key={p.id}>
|
||||
<td>{p.name}</td>
|
||||
<td className="text-secondary">{p.groups === null ? "not known yet — they haven't signed in with groups" : p.groups.length === 0 ? "none" : p.groups.join(", ")}</td>
|
||||
<td>{p.role}</td>
|
||||
<td>
|
||||
{p.wouldBe === null ? (
|
||||
<span className="text-secondary">unchanged until they sign in</span>
|
||||
) : p.wouldBe === p.role ? (
|
||||
<span className="text-secondary">{p.wouldBe}</span>
|
||||
) : (
|
||||
<span className="fw-bold">{p.wouldBe}</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="card-footer text-secondary small">
|
||||
Groups are recorded at every sign-in, whether or not this is on, so people need to have signed in once since this was installed to show up here.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user