Sent for every Fragnet game server seen turned on or off, whatever the notification switch says, with the server, game, account and, when a power signal sent from here caused it, which signal and who sent it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
370 lines
17 KiB
TypeScript
370 lines
17 KiB
TypeScript
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";
|
|
import ExportTableButton from "../../components/ExportTableButton";
|
|
import { EmptyRow, LoadingRow } from "../../components/EmptyState";
|
|
import WebhookDeliveries from "./WebhookDeliveries";
|
|
import { t } from "../../i18n";
|
|
|
|
const EVENT_WORDS: Record<WebhookEventName, string> = {
|
|
"alert.opened": "A problem begins",
|
|
"alert.resolved": "A problem ends",
|
|
"maintenance.started": "Maintenance begins",
|
|
"maintenance.ended": "Maintenance ends",
|
|
"game_server.started": "A game server turns on",
|
|
"game_server.stopped": "A game server turns off",
|
|
};
|
|
|
|
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);
|
|
const [logOf, setLogOf] = useState<EventWebhook | null>(null);
|
|
|
|
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(item_: MetricsToken) {
|
|
if (!(await confirmDialog({ title: "Remove metrics token", message: `Remove "${item_.label}"? Whatever scrapes with it stops working at once.`, confirmLabel: "Remove", danger: true }))) return;
|
|
try {
|
|
await api.metricsTokens.remove(item_.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 className="card-actions">
|
|
<ExportTableButton filename="metrics-tokens" />
|
|
</div>
|
|
</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>
|
|
<p className="text-secondary">
|
|
For Grafana there is a ready-made dashboard — what needs attention, servers, disks, backups and the quieter things — that asks only for these series.{" "}
|
|
<a href="/api/metrics-tokens/grafana-dashboard.json" download>
|
|
Download the dashboard
|
|
</a>
|
|
, then in Grafana choose Dashboards → New → Import and pick your Prometheus when asked.
|
|
</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)}>
|
|
{t("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>{t("Name")}</th>
|
|
<th>Made</th>
|
|
<th>Last used</th>
|
|
<th className="w-1">{t("Actions")}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{tokens?.map((item_) => (
|
|
<tr key={item_.id}>
|
|
<td>
|
|
{item_.label} <span className="text-secondary small">{item_.tokenPrefix}…</span>
|
|
</td>
|
|
<td className="text-secondary">
|
|
{item_.createdBy ?? "—"}, <TimeAgo value={item_.createdAt} fromDb />
|
|
</td>
|
|
<td className="text-secondary">{item_.lastUsedAt ? <TimeAgo value={item_.lastUsedAt} /> : "Never"}</td>
|
|
<td>
|
|
<button className="btn btn-sm btn-outline-danger" onClick={() => void removeToken(item_)}>
|
|
{t("Remove")}
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
{tokens === null && <LoadingRow colSpan={4} />}
|
|
{tokens?.length === 0 && (
|
|
<EmptyRow colSpan={4} title="No metrics tokens yet" hint="/metrics refuses everyone until a token is made. Make one for Prometheus and give it the secret, which is shown once." />
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="card">
|
|
<div className="card-header">
|
|
<h3 className="card-title">Event webhooks</h3>
|
|
<div className="card-actions">
|
|
<ExportTableButton filename="event-webhooks" />
|
|
{!adding && (
|
|
<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, and what was sent and how it went is kept under <em>Sent</em> — where a message can be sent again exactly as it was.
|
|
</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">
|
|
{t("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)}>
|
|
{t("Cancel")}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
)}
|
|
<div className="table-responsive">
|
|
<table className="table table-vcenter">
|
|
<thead>
|
|
<tr>
|
|
<th>{t("Name")}</th>
|
|
<th>Sends</th>
|
|
<th>Last</th>
|
|
<th className="w-1">{t("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)}>
|
|
{t("Test")}
|
|
</button>
|
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => setLogOf(h)}>
|
|
Sent
|
|
</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)}>
|
|
{t("Remove")}
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
{hooks === null && <LoadingRow colSpan={4} />}
|
|
{hooks?.length === 0 && (
|
|
<EmptyRow colSpan={4} title="No webhooks yet" hint="A webhook tells another system when an alert opens or resolves, when maintenance starts or ends, or when a game server is turned on or off." action={{ label: "Add a webhook", onClick: () => setAdding(true) }} />
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
{logOf && <WebhookDeliveries hook={logOf} onClose={() => setLogOf(null)} onChanged={load} />}
|
|
</>
|
|
);
|
|
}
|