Add an Uptime Kuma integration: monitor status and which server each one watches
New integration, following the existing pattern: config in-app (URL + API key, credentials encrypted at rest), its own Uptime Kuma page, an Integrations list entry, a Dashboard widget, and diagnostic-log/ integration-down-alert coverage for free via the shared withDiagLogging wrapper. Read-only -- no start/stop equivalent exists for a monitor. Uptime Kuma has no conventional REST API (the dashboard talks to it over Socket.IO); researched before writing any code, since guessing wrong here would have cost real time. The one machine-readable, authenticated endpoint that lists every monitor is its Prometheus exporter at GET /metrics, gated by HTTP Basic auth -- an API key as the password with the username left blank on current installs, or the real dashboard login on installs from before the API-key feature existed. This adapter authenticates the same way and parses that endpoint's text-exposition format itself (metrics: monitor_status, monitor_response_time, monitor_cert_days_remaining, monitor_uptime_ratio; labels: monitor_id, monitor_name, monitor_type, monitor_url, monitor_hostname, monitor_port), verified against the documented metric/label set and the actual upstream source (server/prometheus.js). A malformed line is skipped rather than failing the whole scrape. "What server is being monitored for what": each monitor's target (an IP for TCP checks, or the hostname out of the URL for HTTP/keyword checks) is matched against your servers' own IPs and hostnames -- reusing the same kind of match already used in the consistency report -- and linked to that server's page. Monitors with no single network target (groups, push monitors, DNS/keyword checks with a complex URL) are left unmatched rather than guessed at. Uptime Kuma's tags aren't read, since the Prometheus endpoint doesn't reliably distinguish a tag label from any other label it might add later. The username field is the first genuinely optional integration config field this app has had; IntegrationField gained an `optional` flag (server validation and both the add/edit web forms honor it) rather than special-casing Uptime Kuma. Verified with 48 backend checks (Prometheus text parsing including escaped quotes, decimals, negative numbers, and malformed lines; TCP vs. HTTP target/port extraction; every documented status code; server matching by IP, hostname, and short name, including no-match cases; the route's real HTTP round trip against a fake Uptime Kuma server, wrong credentials, upstream failures, roles, wrong/disabled/missing integration, diagnostic-log entries; the optional-field validation rule) and by driving the real page and the real Dashboard widget in a browser against the real routers, including CSV export and column sorting. Real dev database mtime untouched. Not verified: a real Uptime Kuma instance. Everything here was checked against Uptime Kuma's documented metric format, its actual upstream source, and a fake server built to match both -- not against a live installation. If your instance's /metrics output differs from what's documented (older version, unusual monitor types), the parser should degrade to an empty or partial monitor list rather than error, but that degradation itself hasn't been observed against the real thing. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ada2e648e9
commit
1a2dd19736
19 files changed
+706
-15
No files matched your search
@@ -286,6 +286,7 @@ export const integrationTypes = [
|
||||
"tailscale",
|
||||
"gitea",
|
||||
"dockhand",
|
||||
"uptimekuma",
|
||||
] as const;
|
||||
export type IntegrationType = (typeof integrationTypes)[number];
|
||||
|
||||
|
||||
@@ -39,6 +39,17 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
|
||||
{ key: "password", label: "Password", secret: true, type: "password" },
|
||||
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
||||
],
|
||||
uptimekuma: [
|
||||
{ key: "url", label: "Uptime Kuma URL", secret: false, placeholder: "https://kuma.example.lan" },
|
||||
{
|
||||
key: "username",
|
||||
label: "Username (leave blank when using an API key)",
|
||||
secret: false,
|
||||
optional: true,
|
||||
placeholder: "only needed on very old installs without API keys",
|
||||
},
|
||||
{ key: "password", label: "API key (or password, on old installs)", secret: true, type: "password" },
|
||||
],
|
||||
};
|
||||
|
||||
/** Fixed base URL per integration type, stored on the row for display/reference. */
|
||||
@@ -81,7 +92,7 @@ export function validateIntegrationConfig(
|
||||
): string[] {
|
||||
const fields = INTEGRATION_FIELDS[type] ?? [];
|
||||
return fields
|
||||
.filter((f) => f.type !== "checkbox")
|
||||
.filter((f) => f.type !== "checkbox" && !f.optional)
|
||||
.filter((f) => merged[f.key] === undefined || merged[f.key] === "")
|
||||
.map((f) => f.key);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { createDockhandAdapter } from "./dockhand/adapter.js";
|
||||
import { createSemaphoreAdapter } from "./semaphore/adapter.js";
|
||||
import { createProxmoxAdapter } from "./proxmox/adapter.js";
|
||||
import { createSynologyAdapter } from "./synology/adapter.js";
|
||||
import { createUptimeKumaAdapter } from "./uptimekuma/adapter.js";
|
||||
|
||||
export interface PingableAdapter {
|
||||
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
|
||||
@@ -32,6 +33,8 @@ export function createIntegrationAdapter(type: IntegrationType, config: Integrat
|
||||
return createProxmoxAdapter(config as any);
|
||||
case "synology":
|
||||
return createSynologyAdapter(config as any);
|
||||
case "uptimekuma":
|
||||
return createUptimeKumaAdapter(config as any);
|
||||
default:
|
||||
throw new Error(`Integration type "${type}" is not implemented yet`);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ export interface IntegrationField {
|
||||
secret: boolean;
|
||||
type?: "text" | "password" | "checkbox";
|
||||
placeholder?: string;
|
||||
/** Not required to save the integration (e.g. a username that's normally left blank in favor of an API key). */
|
||||
optional?: boolean;
|
||||
}
|
||||
|
||||
export type IntegrationConfig = Record<string, string | boolean | undefined>;
|
||||
@@ -0,0 +1,221 @@
|
||||
/**
|
||||
* Uptime Kuma adapter.
|
||||
* Requires config: url, password (an API key, or — on installs older than the API-key
|
||||
* feature — the account password); username is optional and normally left blank.
|
||||
*
|
||||
* Uptime Kuma has no conventional REST API (the dashboard talks to it over Socket.IO).
|
||||
* The one machine-readable endpoint that lists every monitor is its Prometheus exporter
|
||||
* at GET /metrics, gated by HTTP Basic auth — empty username + an API key as the
|
||||
* password once one exists, or the real login username/password on older installs
|
||||
* (https://github.com/louislam/uptime-kuma/wiki/Prometheus-API-Keys). This adapter reads
|
||||
* that endpoint and parses the Prometheus text-exposition format itself; there is no
|
||||
* JSON alternative.
|
||||
*
|
||||
* Verified against the documented metric/label set (server/prometheus.js upstream):
|
||||
* gauges monitor_status (1=up, 0=down, 2=pending, 3=maintenance), monitor_response_time
|
||||
* (ms), monitor_cert_days_remaining, monitor_uptime_ratio{window="1d"|"30d"|"365d"}, each
|
||||
* carrying labels monitor_id, monitor_name, monitor_type, monitor_url, monitor_hostname,
|
||||
* monitor_port (plus the monitor's own tags, which this adapter doesn't try to separate
|
||||
* out from the fixed labels, since tag label *names* are user-defined and not reliably
|
||||
* distinguishable from any other label Uptime Kuma might add later).
|
||||
*/
|
||||
import { withDiagLogging } from "../../services/diagLog.js";
|
||||
|
||||
export interface UptimeKumaConfig {
|
||||
url: string;
|
||||
username?: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export type MonitorStatus = "up" | "down" | "pending" | "maintenance" | "unknown";
|
||||
|
||||
const STATUS_BY_CODE: Record<number, MonitorStatus> = { 0: "down", 1: "up", 2: "pending", 3: "maintenance" };
|
||||
|
||||
export interface UptimeKumaMonitor {
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
/** The host Uptime Kuma actually checks — a bare hostname/IP for TCP-style monitors, or the host part of the URL for HTTP/keyword ones. Null for types with no single network target (group, push, docker, ...). */
|
||||
target: string | null;
|
||||
port: number | null;
|
||||
status: MonitorStatus;
|
||||
responseTimeMs: number | null;
|
||||
certDaysRemaining: number | null;
|
||||
/** Percent, 0–100. */
|
||||
uptime24h: number | null;
|
||||
uptime30d: number | null;
|
||||
uptime1y: number | null;
|
||||
}
|
||||
|
||||
export interface UptimeKumaAdapter {
|
||||
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
|
||||
listMonitors(): Promise<UptimeKumaMonitor[]>;
|
||||
}
|
||||
|
||||
// ─── Prometheus text-exposition parsing (pure) ─────────────────────────────
|
||||
|
||||
export interface PromSample {
|
||||
metric: string;
|
||||
labels: Record<string, string>;
|
||||
value: number;
|
||||
}
|
||||
|
||||
const SAMPLE_LINE = /^([a-zA-Z_:][a-zA-Z0-9_:]*)(\{(.*)\})?\s+(\S+)\s*$/;
|
||||
// key="value" pairs; the value may contain an escaped quote (\") or backslash (\\), per the exposition format.
|
||||
const LABEL_PAIR = /([a-zA-Z_][a-zA-Z0-9_]*)="((?:[^"\\]|\\.)*)"/g;
|
||||
|
||||
function unescapeLabelValue(raw: string): string {
|
||||
return raw.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
|
||||
}
|
||||
|
||||
/** Parses Prometheus's plain-text exposition format into flat samples. Comment (#) and blank lines are skipped; a line that doesn't parse as a sample is skipped rather than failing the whole scrape — one odd line from a future Uptime Kuma version shouldn't blank the page. */
|
||||
export function parsePrometheusText(text: string): PromSample[] {
|
||||
const samples: PromSample[] = [];
|
||||
for (const line of text.split("\n")) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith("#")) continue;
|
||||
const m = SAMPLE_LINE.exec(trimmed);
|
||||
if (!m) continue;
|
||||
const value = Number(m[4]);
|
||||
if (!Number.isFinite(value)) continue;
|
||||
const labels: Record<string, string> = {};
|
||||
if (m[3]) {
|
||||
LABEL_PAIR.lastIndex = 0;
|
||||
let lm: RegExpExecArray | null;
|
||||
while ((lm = LABEL_PAIR.exec(m[3]))) labels[lm[1]] = unescapeLabelValue(lm[2]);
|
||||
}
|
||||
samples.push({ metric: m[1], labels, value });
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
|
||||
/** Groups flat samples into one row per monitor_id, reading whichever of the known metrics are present for it. */
|
||||
export function monitorsFromSamples(samples: PromSample[]): UptimeKumaMonitor[] {
|
||||
interface Acc {
|
||||
name: string;
|
||||
type: string;
|
||||
url: string;
|
||||
hostname: string;
|
||||
port: string;
|
||||
status: MonitorStatus;
|
||||
responseTimeMs: number | null;
|
||||
certDaysRemaining: number | null;
|
||||
uptime: Partial<Record<"1d" | "30d" | "365d", number>>;
|
||||
}
|
||||
const byId = new Map<string, Acc>();
|
||||
const get = (id: string, labels: Record<string, string>) => {
|
||||
let acc = byId.get(id);
|
||||
if (!acc) {
|
||||
acc = {
|
||||
name: labels.monitor_name ?? id,
|
||||
type: labels.monitor_type ?? "unknown",
|
||||
url: labels.monitor_url ?? "",
|
||||
hostname: labels.monitor_hostname ?? "",
|
||||
port: labels.monitor_port ?? "",
|
||||
status: "unknown",
|
||||
responseTimeMs: null,
|
||||
certDaysRemaining: null,
|
||||
uptime: {},
|
||||
};
|
||||
byId.set(id, acc);
|
||||
}
|
||||
return acc;
|
||||
};
|
||||
|
||||
for (const s of samples) {
|
||||
const id = s.labels.monitor_id;
|
||||
if (!id) continue;
|
||||
const acc = get(id, s.labels);
|
||||
switch (s.metric) {
|
||||
case "monitor_status":
|
||||
acc.status = STATUS_BY_CODE[s.value] ?? "unknown";
|
||||
break;
|
||||
case "monitor_response_time":
|
||||
acc.responseTimeMs = s.value;
|
||||
break;
|
||||
case "monitor_cert_days_remaining":
|
||||
acc.certDaysRemaining = s.value;
|
||||
break;
|
||||
case "monitor_uptime_ratio": {
|
||||
const window = s.labels.window;
|
||||
if (window === "1d" || window === "30d" || window === "365d") acc.uptime[window] = s.value;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const target = (acc: Acc): { target: string | null; port: number | null } => {
|
||||
if (acc.hostname) {
|
||||
const port = Number(acc.port);
|
||||
return { target: acc.hostname, port: Number.isFinite(port) && port > 0 ? port : null };
|
||||
}
|
||||
if (acc.url) {
|
||||
try {
|
||||
const u = new URL(acc.url);
|
||||
const port = u.port ? Number(u.port) : null;
|
||||
return { target: u.hostname, port };
|
||||
} catch {
|
||||
return { target: null, port: null };
|
||||
}
|
||||
}
|
||||
return { target: null, port: null };
|
||||
};
|
||||
const pct = (v: number | undefined): number | null => (v === undefined ? null : Math.round(v * 1000) / 10);
|
||||
|
||||
return [...byId.entries()]
|
||||
.map(([id, acc]) => {
|
||||
const { target: t, port } = target(acc);
|
||||
return {
|
||||
id,
|
||||
name: acc.name,
|
||||
type: acc.type,
|
||||
target: t,
|
||||
port,
|
||||
status: acc.status,
|
||||
responseTimeMs: acc.responseTimeMs,
|
||||
certDaysRemaining: acc.certDaysRemaining,
|
||||
uptime24h: pct(acc.uptime["1d"]),
|
||||
uptime30d: pct(acc.uptime["30d"]),
|
||||
uptime1y: pct(acc.uptime["365d"]),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
// ─── HTTP ───────────────────────────────────────────────────────────────────
|
||||
|
||||
export function createUptimeKumaAdapter(config: UptimeKumaConfig): UptimeKumaAdapter {
|
||||
function base() {
|
||||
return config.url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
async function fetchMetrics(): Promise<string> {
|
||||
const auth = Buffer.from(`${config.username ?? ""}:${config.password}`).toString("base64");
|
||||
const res = await fetch(`${base()}/metrics`, { headers: { Authorization: `Basic ${auth}` } });
|
||||
if (res.status === 401) {
|
||||
throw new Error("Uptime Kuma rejected the credentials — check the API key (or username/password) and try again.");
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(`Uptime Kuma API error: HTTP ${res.status}`);
|
||||
}
|
||||
return res.text();
|
||||
}
|
||||
|
||||
async function listMonitors(): Promise<UptimeKumaMonitor[]> {
|
||||
return monitorsFromSamples(parsePrometheusText(await fetchMetrics()));
|
||||
}
|
||||
|
||||
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
|
||||
const start = Date.now();
|
||||
try {
|
||||
await fetchMetrics();
|
||||
return { ok: true, latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
return withDiagLogging("uptimekuma", { ping, listMonitors });
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { Router, type Request, type Response } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { integrations, integrationCredentials, integrationTypes } from "../db/schema.js";
|
||||
import { integrations, integrationCredentials, integrationTypes, servers } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { encryptSecret } from "../crypto.js";
|
||||
@@ -20,6 +20,8 @@ import { createDockhandAdapter } from "../integrations/dockhand/adapter.js";
|
||||
import { createSemaphoreAdapter } from "../integrations/semaphore/adapter.js";
|
||||
import { createProxmoxAdapter, guestsWithoutBackupCoverage } from "../integrations/proxmox/adapter.js";
|
||||
import { createSynologyAdapter } from "../integrations/synology/adapter.js";
|
||||
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
|
||||
import { attachMatchedServers, summarizeMonitors, type MatchableServer } from "../services/uptimeKumaMatch.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const integrationsRouter = Router();
|
||||
@@ -769,3 +771,48 @@ integrationsRouter.get("/:id/synology/system", asyncHandler(async (req, res) =>
|
||||
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}));
|
||||
|
||||
// ─── Uptime Kuma ─────────────────────────────────────────────────────────────
|
||||
|
||||
async function requireUptimeKumaAdapter(req: Request, res: Response) {
|
||||
const id = Number(req.params.id);
|
||||
const loaded = await loadIntegrationConfig(id);
|
||||
if (!loaded) {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return null;
|
||||
}
|
||||
if (loaded.integration.type !== "uptimekuma") {
|
||||
res.status(400).json({ error: "wrong_type" });
|
||||
return null;
|
||||
}
|
||||
if (!loaded.integration.enabled) {
|
||||
res.status(400).json({ error: "integration_disabled" });
|
||||
return null;
|
||||
}
|
||||
return { integration: loaded.integration, adapter: createUptimeKumaAdapter(loaded.config as any) };
|
||||
}
|
||||
|
||||
function parseServerIps(stored: string | null): string[] {
|
||||
if (!stored) return [];
|
||||
try {
|
||||
const value = JSON.parse(stored);
|
||||
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
integrationsRouter.get("/:id/uptimekuma/monitors", asyncHandler(async (req, res) => {
|
||||
const found = await requireUptimeKumaAdapter(req, res);
|
||||
if (!found) return;
|
||||
|
||||
try {
|
||||
const monitors = await found.adapter.listMonitors();
|
||||
const serverRows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers);
|
||||
const matchable: MatchableServer[] = serverRows.map((s) => ({ id: s.id, name: s.name, hostname: s.hostname, ips: parseServerIps(s.ips) }));
|
||||
const withServers = attachMatchedServers(monitors, matchable);
|
||||
res.json({ monitors: withServers, summary: summarizeMonitors(monitors) });
|
||||
} catch (err) {
|
||||
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}));
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as net from "node:net";
|
||||
import type { UptimeKumaMonitor } from "../integrations/uptimekuma/adapter.js";
|
||||
|
||||
/** The columns of a server row this needs, so it can be tested without a live database. */
|
||||
export interface MatchableServer {
|
||||
id: number;
|
||||
name: string;
|
||||
hostname: string | null;
|
||||
ips: string[];
|
||||
}
|
||||
|
||||
const clean = (s: string) => s.trim().toLowerCase().replace(/\.$/, "");
|
||||
const firstLabel = (s: string) => clean(s).split(".")[0];
|
||||
|
||||
/**
|
||||
* Which of these servers a monitor's target host belongs to — an IP is matched against
|
||||
* each server's reported addresses; anything else is matched as a hostname, against the
|
||||
* server's own hostname or its short name (so "elsa" and "elsa.lab.example" both work).
|
||||
* Returns null rather than guessing when nothing lines up.
|
||||
*/
|
||||
export function matchServerForTarget(target: string | null, servers: MatchableServer[]): MatchableServer | null {
|
||||
if (!target) return null;
|
||||
const t = target.trim();
|
||||
if (!t) return null;
|
||||
|
||||
if (net.isIP(t) !== 0) {
|
||||
const ip = t.toLowerCase();
|
||||
return servers.find((s) => s.ips.some((a) => a.toLowerCase() === ip)) ?? null;
|
||||
}
|
||||
const name = clean(t);
|
||||
const short = firstLabel(t);
|
||||
return (
|
||||
servers.find((s) => s.hostname && clean(s.hostname) === name) ??
|
||||
servers.find((s) => clean(s.name) === short) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export interface MonitorWithServer extends UptimeKumaMonitor {
|
||||
matchedServer: { id: number; name: string } | null;
|
||||
}
|
||||
|
||||
export function attachMatchedServers(monitors: UptimeKumaMonitor[], servers: MatchableServer[]): MonitorWithServer[] {
|
||||
return monitors.map((m) => {
|
||||
const match = matchServerForTarget(m.target, servers);
|
||||
return { ...m, matchedServer: match ? { id: match.id, name: match.name } : null };
|
||||
});
|
||||
}
|
||||
|
||||
export interface MonitorSummary {
|
||||
total: number;
|
||||
up: number;
|
||||
down: number;
|
||||
pending: number;
|
||||
maintenance: number;
|
||||
unknown: number;
|
||||
}
|
||||
|
||||
export function summarizeMonitors(monitors: UptimeKumaMonitor[]): MonitorSummary {
|
||||
const summary: MonitorSummary = { total: monitors.length, up: 0, down: 0, pending: 0, maintenance: 0, unknown: 0 };
|
||||
for (const m of monitors) summary[m.status]++;
|
||||
return summary;
|
||||
}
|
||||
Reference in new issue
Block a user