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 = { "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(null); const [hooks, setHooks] = useState(null); const [error, setError] = useState(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>(new Set(["alert.opened", "alert.resolved"])); const [testResults, setTestResults] = useState>({}); const [busy, setBusy] = useState(false); const [logOf, setLogOf] = useState(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 ( <>

API and webhooks

Metrics for Prometheus

{origin}/metrics 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 Authorization: Bearer …; a token in the address isn't accepted. It reads what the app already knows, so a scrape every 15 seconds is cheap.

For Grafana there is a ready-made dashboard — what needs attention, servers, disks, backups and the quieter things — that asks only for these series.{" "} Download the dashboard , then in Grafana choose Dashboards → New → Import and pick your Prometheus when asked.

{newSecret && (
Token for {newSecret.label}
Copy it now — it can't be shown again. If it's lost, remove the token and make a new one.
e.currentTarget.select()} />
In prometheus.yml:
                {`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}"]`}
              
)}
setTokenLabel(e.target.value)} />
{tokens?.map((item_) => ( ))} {tokens === null && } {tokens?.length === 0 && ( )}
{t("Name")} Made Last used {t("Actions")}
{item_.label} {item_.tokenPrefix}… {item_.createdBy ?? "—"}, {item_.lastUsedAt ? : "Never"}

Event webhooks

{!adding && ( )}

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 X-HLM-Signature: sha256=…, 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 Sent — where a message can be sent again exactly as it was.

{adding && (
setHookLabel(e.target.value)} />
setHookUrl(e.target.value)} />
setHookSecret(e.target.value)} />
Send when
{(Object.keys(EVENT_WORDS) as WebhookEventName[]).map((ev) => ( ))}
)}
{hooks?.map((h) => ( ))} {hooks === null && } {hooks?.length === 0 && ( setAdding(true) }} /> )}
{t("Name")} Sends Last {t("Actions")}
{h.label} {!h.enabled && off} {h.hasSecret && signed}
{hostOf(h.url)}
{h.events.map((ev) => ( {ev} ))}
{testResults[h.id] ?? (h.lastAttemptAt ? ( <> {h.lastResult} ) : ( not sent yet ))}
{logOf && setLogOf(null)} onChanged={load} />} ); }