A year of history, one chart, and a read API with personal tokens
History: server load, memory and disks are also kept as hourly (four months) and daily (over two years) averages with lowest and highest; endpoint answers as hourly (four months) beside the daily figures. Charts ask for 24 hours to a year and are drawn from whichever is fine enough. A disk that two weeks call flat is looked at again over ninety days for the forecast. Built once from what is kept. One chart: TimeChart replaces the sparkline and the multi-line chart: hover and arrow-key readout, a lowest/highest band, gaps shown as gaps, the same ranges everywhere and the choice remembered. Used for server trends, comparing servers, a check's availability and answer times (Endpoints > History) and a server's availability. Read API: /api/v1 (servers, metrics, alerts, incidents, inventory, network, endpoints and their history, maintenance) with personal read-only tokens made under the user menu: shown once, hashed, 30/90/365 days or none, ten at most, removed with their owner. GET only. Documented in API.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5e26e77340
commit
68b41b5586
47 files changed
+12360
-247
No files matched your search
@@ -0,0 +1,221 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { api, type ApiToken } from "../api/client";
|
||||
import CopyButton from "../components/CopyButton";
|
||||
import { EmptyRow } from "../components/EmptyState";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { confirmDialog } from "../utils/dialogs";
|
||||
import { formatDate } from "../utils/date";
|
||||
import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
|
||||
const EXPIRY = [
|
||||
{ value: "90", label: "90 days" },
|
||||
{ value: "30", label: "30 days" },
|
||||
{ value: "365", label: "1 year" },
|
||||
{ value: "", label: "No end — until I remove it" },
|
||||
];
|
||||
|
||||
const READS = [
|
||||
["/api/v1/servers", "every server: whether it is online, its addresses, load, memory, disks and waiting updates"],
|
||||
["/api/v1/servers/:id/metrics?days=365", "a server's load, memory and disks, up to a year back"],
|
||||
["/api/v1/alerts", "what is wrong now, and whether somebody is on it"],
|
||||
["/api/v1/incidents?status=open", "the record of alerts that began and ended"],
|
||||
["/api/v1/inventory", "the hardware"],
|
||||
["/api/v1/network", "switches, access points and gateways, networks and Wi-Fi names"],
|
||||
["/api/v1/endpoints", "the checks, and /endpoints/:id/history for how one has done"],
|
||||
["/api/v1/maintenance", "what is under maintenance now, and what is coming"],
|
||||
];
|
||||
|
||||
/**
|
||||
* A person's own read-only tokens for the API (/api/v1): a script, Home Assistant or a dashboard sends one in a header and gets JSON back. A token can only read, sees
|
||||
* what its owner sees, and is gone when its owner is. The secret is shown once, here, when it is made.
|
||||
*/
|
||||
export default function ApiTokens() {
|
||||
const [tokens, setTokens] = useState<ApiToken[] | null>(null);
|
||||
const [max, setMax] = useState(10);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [label, setLabel] = useState("");
|
||||
const [expiry, setExpiry] = useState("90");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [fresh, setFresh] = useState<{ label: string; secret: string } | null>(null);
|
||||
|
||||
function load() {
|
||||
api.apiTokens
|
||||
.list()
|
||||
.then((res) => {
|
||||
setTokens(res.tokens);
|
||||
setMax(res.max);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
}
|
||||
useEffect(load, []);
|
||||
|
||||
async function make(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await api.apiTokens.create({ label: label.trim(), expiresInDays: expiry === "" ? null : Number(expiry) });
|
||||
setFresh({ label: res.token.label, secret: res.secret });
|
||||
setLabel("");
|
||||
load();
|
||||
} catch (err) {
|
||||
setError(readableError(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(t: ApiToken) {
|
||||
// Not undoable: the secret is not kept, so a token cannot be made again the same.
|
||||
if (!(await confirmDialog({ title: "Remove a token", message: `Remove "${t.label}"? Whatever uses it stops working at once, and it cannot be put back.`, confirmLabel: "Remove", danger: true }))) return;
|
||||
try {
|
||||
await api.apiTokens.remove(t.id);
|
||||
toast.success(`Removed "${t.label}".`);
|
||||
load();
|
||||
} catch (err) {
|
||||
toast.error(readableError(err));
|
||||
}
|
||||
}
|
||||
|
||||
const origin = window.location.origin;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="d-flex align-items-center mb-1">
|
||||
<h2 className="page-title mb-0">API tokens</h2>
|
||||
</div>
|
||||
<div className="text-secondary mb-3">
|
||||
Read-only access to your installation’s data for scripts, Home Assistant and dashboards. A token can only read, sees what you see, and stops working when you are removed. Make one for each thing that reads, so each can be removed on its own.
|
||||
</div>
|
||||
<ErrorNotice error={error} />
|
||||
|
||||
{fresh && (
|
||||
<div className="alert alert-success" role="status">
|
||||
<div className="w-100">
|
||||
<div className="fw-bold mb-1">Your token “{fresh.label}” — copy it now, it is not shown again</div>
|
||||
<div className="d-flex flex-wrap align-items-center gap-2 mb-2">
|
||||
<code className="text-break">{fresh.secret}</code>
|
||||
<CopyButton text={fresh.secret} />
|
||||
</div>
|
||||
<div className="small">Send it in a header, never in the address:</div>
|
||||
<pre className="mb-2 mt-1 small">{`curl -H "Authorization: Bearer ${fresh.secret}" ${origin}/api/v1/alerts`}</pre>
|
||||
<button type="button" className="btn btn-sm" onClick={() => setFresh(null)}>
|
||||
I have copied it
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form className="card mb-3" onSubmit={make}>
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Make a token</h3>
|
||||
</div>
|
||||
<div className="card-body row g-3 align-items-end">
|
||||
<div className="col-md-5">
|
||||
<label className="form-label" htmlFor="tok-label">
|
||||
What it is for
|
||||
</label>
|
||||
<input id="tok-label" className="form-control" maxLength={60} required placeholder="e.g. Home Assistant" value={label} onChange={(e) => setLabel(e.target.value)} />
|
||||
</div>
|
||||
<div className="col-md-4">
|
||||
<label className="form-label" htmlFor="tok-exp">
|
||||
Works for
|
||||
</label>
|
||||
<select id="tok-exp" className="form-select" value={expiry} onChange={(e) => setExpiry(e.target.value)}>
|
||||
{EXPIRY.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<button type="submit" className="btn btn-primary w-100" disabled={busy || label.trim() === "" || (tokens?.length ?? 0) >= max}>
|
||||
{busy ? "Making…" : "Make the token"}
|
||||
</button>
|
||||
</div>
|
||||
{(tokens?.length ?? 0) >= max && <div className="col-12 text-secondary small">You have {max} tokens, the most there can be. Remove one you do not use.</div>}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">Your tokens</h3>
|
||||
</div>
|
||||
<div className="table-responsive">
|
||||
<table className="table table-vcenter card-table table-stack">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Starts with</th>
|
||||
<th>Made</th>
|
||||
<th>Last used</th>
|
||||
<th>Ends</th>
|
||||
<th className="w-1">
|
||||
<span className="visually-hidden">Actions</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{tokens === null && !error && (
|
||||
<tr>
|
||||
<td colSpan={6}>
|
||||
<BlockSkeleton lines={2} />
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{tokens?.map((t) => (
|
||||
<tr key={t.id}>
|
||||
<td className="stack-wide">
|
||||
<strong>{t.label}</strong>
|
||||
{t.expired && <span className="badge bg-red-lt text-red ms-2">expired</span>}
|
||||
</td>
|
||||
<td className="stack-label font-monospace" data-label="Starts with">
|
||||
{t.tokenPrefix}…
|
||||
</td>
|
||||
<td className="stack-label" data-label="Made">
|
||||
<TimeAgo value={t.createdAt} fromDb />
|
||||
</td>
|
||||
<td className="stack-label" data-label="Last used">
|
||||
{t.lastUsedAt ? <TimeAgo value={t.lastUsedAt} /> : <span className="text-secondary">never</span>}
|
||||
</td>
|
||||
<td className="stack-label" data-label="Ends">
|
||||
{t.expiresAt ? formatDate(new Date(t.expiresAt)) : <span className="text-secondary">no end</span>}
|
||||
</td>
|
||||
<td className="stack-wide">
|
||||
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(t)}>
|
||||
Remove
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{tokens !== null && tokens.length === 0 && <EmptyRow colSpan={6} title="No tokens yet" hint="Make one above, and copy it when it is shown: that is the only time it is." />}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">What it can read</h3>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<p className="text-secondary">
|
||||
Everything is a <code>GET</code> that answers JSON, under <code>{origin}/api/v1</code>, with the token as <code>Authorization: Bearer …</code>. Nothing can be changed through it. Dates are ISO 8601 in UTC and sizes are in bytes.
|
||||
</p>
|
||||
<ul className="mb-2">
|
||||
{READS.map(([path, what]) => (
|
||||
<li key={path}>
|
||||
<code>{path}</code> — {what}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="text-secondary small">The full list, with an example of each answer, is in API.md.</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { readableError } from "../utils/errors";
|
||||
import { toast } from "../utils/toast";
|
||||
import { EmptyRow } from "../components/EmptyState";
|
||||
import EndpointSuggestions from "../components/EndpointSuggestions";
|
||||
import EndpointHistory from "../components/EndpointHistory";
|
||||
|
||||
const KIND_LABELS: Record<EndpointKind, string> = { http: "Web address", tcp: "Port", tls: "Certificate" };
|
||||
const KIND_HINTS: Record<EndpointKind, string> = {
|
||||
@@ -128,6 +129,7 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
|
||||
const [draft, setDraft] = useState<Draft | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [asking, setAsking] = useState<number | null>(null);
|
||||
const [historyFor, setHistoryFor] = useState<{ id: number; name: string } | null>(null);
|
||||
|
||||
function load() {
|
||||
api.endpoints
|
||||
@@ -438,6 +440,9 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
|
||||
<div>
|
||||
<Ticks recent={c.stats?.recent ?? []} />
|
||||
</div>
|
||||
<button type="button" className="btn btn-link btn-sm p-0" onClick={() => setHistoryFor({ id: c.id, name: c.name })}>
|
||||
History…
|
||||
</button>
|
||||
</td>
|
||||
<td className="stack-label" data-label="Certificate">
|
||||
{c.certDays === null ? (
|
||||
@@ -488,6 +493,7 @@ export default function Endpoints({ user }: { user: CurrentUser }) {
|
||||
</div>
|
||||
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
|
||||
</div>
|
||||
{historyFor && <EndpointHistory checkId={historyFor.id} name={historyFor.name} onClose={() => setHistoryFor(null)} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { api, type ServerMetricSeries, type ServerRecord } from "../api/client";
|
||||
import MultiLineChart, { type ChartSeries } from "../components/MultiLineChart";
|
||||
import TimeChart, { type ChartSeries } from "../components/TimeChart";
|
||||
import RangeSelect from "../components/RangeSelect";
|
||||
import { CHART_RANGES, useChartRange } from "../utils/chartRanges";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import ExportTableButton from "../components/ExportTableButton";
|
||||
|
||||
const MAX_SERVERS = 4;
|
||||
const RANGES = [
|
||||
{ days: 1, label: "24 hours" },
|
||||
{ days: 7, label: "7 days" },
|
||||
{ days: 30, label: "30 days" },
|
||||
];
|
||||
// A colour and a dash pattern for each line, so they can be told apart by either.
|
||||
const LOOKS = [
|
||||
{ color: "#4299e1", dash: "" },
|
||||
@@ -43,7 +40,7 @@ export default function ServerCompare() {
|
||||
return [...seen].slice(0, MAX_SERVERS);
|
||||
}, [params]);
|
||||
|
||||
const [days, setDays] = useState(7);
|
||||
const [days, setDays] = useChartRange(7);
|
||||
const [metric, setMetric] = useState("cpu");
|
||||
const [loaded, setLoaded] = useState<Loaded[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
@@ -98,7 +95,7 @@ export default function ServerCompare() {
|
||||
};
|
||||
});
|
||||
const chart: ChartSeries[] = rows.filter((r) => r.series).map((r) => ({ name: r.server.name, color: r.look.color, dash: r.look.dash, points: r.series!.points }));
|
||||
const summary = `${metricName} over the last ${RANGES.find((r) => r.days === days)?.label}: ${rows.map((r) => `${r.server.name} ${percent(r.now)} now`).join(", ")}`;
|
||||
const summary = `${metricName} over the last ${CHART_RANGES.find((r) => r.days === days)?.label}: ${rows.map((r) => `${r.server.name} ${percent(r.now)} now`).join(", ")}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -126,13 +123,7 @@ export default function ServerCompare() {
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select className="form-select form-select-sm w-auto" aria-label="Time range" value={days} onChange={(e) => setDays(Number(e.target.value))}>
|
||||
{RANGES.map((r) => (
|
||||
<option key={r.days} value={r.days}>
|
||||
Last {r.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<RangeSelect value={days} onChange={setDays} />
|
||||
<ExportTableButton filename={`compare-${metric}`} />
|
||||
</div>
|
||||
<div className="card-body">
|
||||
@@ -145,7 +136,7 @@ export default function ServerCompare() {
|
||||
{chart.length === 0 ? (
|
||||
<div className="text-secondary mb-3">None of these servers has a history for this yet. A sample is kept about every ten minutes once an agent has reported.</div>
|
||||
) : (
|
||||
<MultiLineChart series={chart} from={to - days * 86_400_000} to={to} label={summary} />
|
||||
<TimeChart series={chart} from={to - days * 86_400_000} to={to} label={summary} />
|
||||
)}
|
||||
<div className="table-responsive mt-3">
|
||||
<table className="table table-vcenter">
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "../api/client";
|
||||
import ServerPorts from "../components/ServerPorts";
|
||||
import ServerTrends from "../components/ServerTrends";
|
||||
import UptimeHistory from "../components/UptimeHistory";
|
||||
import ServerActivity from "../components/ServerActivity";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import UptimeRibbon from "../components/UptimeRibbon";
|
||||
@@ -800,6 +801,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
||||
|
||||
{view === "history" && (
|
||||
<>
|
||||
<UptimeHistory kind="servers" id={server.id} name={server.name} />
|
||||
{hardware.source === "agent" && <ServerTrends serverId={serverId} />}
|
||||
{(user.role === "admin" || user.role === "operator") && <ServerActivity serverId={serverId} />}
|
||||
</>
|
||||
|
||||
Reference in new issue
Block a user