Add address aliases for the Uptime Kuma maintenance sync, and ignore Kuma's "null"

Uptime Kuma often watches a host by another address than the one it was added
with here (a Proxmox host monitored over Tailscale, say). Address aliases on
the Maintenance page say that an address belongs to a server, integration or
DNS provider, so the sync puts the window there; matching stays exact.
Migration 0018 adds maintenance_aliases.

Also fixes monitors whose empty hostname/URL/port arrive from Kuma's metrics as
the text "null": they were taken as an address, hiding the real URL.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-13 20:25:57 +02:00
1 parent 3e6404371b
commit 44cc9d1cf2
12 files changed
+2239 -14

No files matched your search

@@ -0,0 +1,9 @@
CREATE TABLE `maintenance_aliases` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`address` text NOT NULL,
`target_type` text NOT NULL,
`target_id` integer NOT NULL,
`created_at` text DEFAULT (current_timestamp) NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `maintenance_aliases_unique_idx` ON `maintenance_aliases` (`address`,`target_type`,`target_id`);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -127,6 +127,13 @@
"when": 1791754643361,
"tag": "0017_yummy_lady_ursula",
"breakpoints": true
},
{
"idx": 18,
"version": "6",
"when": 1791757001527,
"tag": "0018_even_marvel_zombies",
"breakpoints": true
}
]
}
+17
View File
@@ -76,6 +76,23 @@ export const maintenanceWindows = sqliteTable("maintenance_windows", {
source: text("source"),
});
// An address that Uptime Kuma's monitors use for a thing this app knows by another address (a Tailscale IP for a host added by its LAN
// address, say), so a maintenance window in Uptime Kuma lands on the right server, integration or DNS provider. The address is stored as a
// bare lowercase host.
export const maintenanceAliases = sqliteTable(
"maintenance_aliases",
{
id: integer("id").primaryKey({ autoIncrement: true }),
address: text("address").notNull(),
targetType: text("target_type").$type<MaintenanceTargetType>().notNull(),
targetId: integer("target_id").notNull(), // polymorphic, like maintenance_windows — no FK; an alias whose target was deleted is ignored
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
},
(table) => [uniqueIndex("maintenance_aliases_unique_idx").on(table.address, table.targetType, table.targetId)],
);
// ─── Settings (key/value) ───────────────────────────────────────────────────
export const settings = sqliteTable("settings", {
@@ -111,15 +111,17 @@ export function monitorsFromSamples(samples: PromSample[]): UptimeKumaMonitor[]
uptime: Partial<Record<"1d" | "30d" | "365d", number>>;
}
const byId = new Map<string, Acc>();
// Uptime Kuma writes the text "null" for a field a monitor doesn't have; that is no address.
const present = (v: string | undefined): string => (v === undefined || v === "null" || v === "undefined" ? "" : v);
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 ?? "",
url: present(labels.monitor_url),
hostname: present(labels.monitor_hostname),
port: present(labels.monitor_port),
status: "unknown",
responseTimeMs: null,
certDaysRemaining: null,
+63 -3
View File
@@ -1,8 +1,9 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { dnsProviders, integrations, maintenanceTargetTypes, maintenanceWindows, servers } from "../db/schema.js";
import { dnsProviders, integrations, maintenanceAliases, maintenanceTargetTypes, maintenanceWindows, servers } from "../db/schema.js";
import { hostOfAddress } from "../services/kumaTargets.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { describeTarget, listActiveWindows, listUpcomingWindows, startOrExtendWindow } from "../services/maintenance.js";
@@ -38,7 +39,13 @@ maintenanceRouter.get("/", asyncHandler(async (_req, res) => {
db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).orderBy(integrations.name),
db.select({ id: dnsProviders.id, name: dnsProviders.name, providerType: dnsProviders.providerType }).from(dnsProviders).orderBy(dnsProviders.name),
]);
res.json({ windows, upcoming, targets: { servers: serverRows, integrations: integrationRows, dnsProviders: providerRows } });
const aliases = [];
for (const a of await db.select().from(maintenanceAliases).orderBy(maintenanceAliases.address)) {
const target = await describeTarget(a.targetType, a.targetId);
if (!target) continue; // target was deleted — the alias has nothing left to point at
aliases.push({ id: a.id, address: a.address, targetType: a.targetType, targetId: a.targetId, targetName: target.name, targetKind: target.kind });
}
res.json({ windows, upcoming, aliases, targets: { servers: serverRows, integrations: integrationRows, dnsProviders: providerRows } });
}));
const startSchema = z.object({
@@ -145,6 +152,59 @@ maintenanceRouter.post("/import/uptimekuma", requireRole("operator"), asyncHandl
res.json({ imported, unmatched, monitorsInMaintenance: inMaintenance.length, monitorsChecked: monitors.length });
}));
const aliasSchema = z.object({
address: z.string().min(1).max(253),
targetType: z.enum(maintenanceTargetTypes),
targetId: z.number().int().positive(),
});
maintenanceRouter.post("/aliases", requireRole("operator"), asyncHandler(async (req, res) => {
const parsed = aliasSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", message: "Give an address and say what it belongs to.", details: parsed.error.flatten() });
}
const host = hostOfAddress(parsed.data.address);
if (!host) {
return res.status(400).json({ error: "invalid_address", message: "That isn't an address — use a host name or IP, like 100.64.0.7 or pve.example.lan." });
}
const target = await describeTarget(parsed.data.targetType, parsed.data.targetId);
if (!target) return res.status(404).json({ error: "not_found", message: "That target doesn't exist." });
const [existing] = await db
.select()
.from(maintenanceAliases)
.where(and(eq(maintenanceAliases.address, host), eq(maintenanceAliases.targetType, parsed.data.targetType), eq(maintenanceAliases.targetId, parsed.data.targetId)))
.limit(1);
if (existing) return res.status(409).json({ error: "exists", message: `${host} is already an alias of ${target.name}.` });
const [created] = await db.insert(maintenanceAliases).values({ address: host, targetType: parsed.data.targetType, targetId: parsed.data.targetId }).returning();
await recordAudit({
actor: req.currentUser!,
category: "maintenance",
action: "alias_add",
targetType: parsed.data.targetType,
targetId: parsed.data.targetId,
detail: { name: target.name, address: host },
});
res.status(201).json({ alias: { ...created, targetName: target.name, targetKind: target.kind } });
}));
maintenanceRouter.delete("/aliases/:id", requireRole("operator"), asyncHandler(async (req, res) => {
const id = Number(req.params.id);
const [existing] = await db.select().from(maintenanceAliases).where(eq(maintenanceAliases.id, id)).limit(1);
if (!existing) return res.status(404).json({ error: "not_found" });
await db.delete(maintenanceAliases).where(eq(maintenanceAliases.id, id));
await recordAudit({
actor: req.currentUser!,
category: "maintenance",
action: "alias_remove",
targetType: existing.targetType,
targetId: existing.targetId,
detail: { address: existing.address },
});
res.status(204).end();
}));
const syncUptimeKumaSchema = z.object({ integrationId: z.number().int().positive() });
/** Reads Uptime Kuma's maintenance schedule now and brings the mirrored windows in line with it (the same pass that runs every 15 minutes when switched on). */
+12 -2
View File
@@ -13,7 +13,7 @@
*/
import { eq, like, lt } from "drizzle-orm";
import { db } from "../db/client.js";
import { dnsProviders, integrations, maintenanceWindows, servers, type MaintenanceTargetType } from "../db/schema.js";
import { dnsProviders, integrations, maintenanceAliases, maintenanceWindows, servers, type MaintenanceTargetType } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
import type { KumaMaintenance } from "../integrations/uptimekuma/maintenanceFeed.js";
@@ -232,6 +232,16 @@ export async function syncKumaMaintenance(integrationId: number, now: Date = new
const host = typeof url === "string" ? hostOfAddress(url) : null;
if (host) addressed.push({ type: "dns_provider", id: p.id, name: p.name, host });
}
// Addresses someone has said belong to a server, integration or DNS provider (the Tailscale IP of a host that was added by its LAN address).
const names = new Map<string, string>();
for (const r of serverRows) names.set(`server:${r.id}`, r.name);
for (const t of addressed) names.set(`${t.type}:${t.id}`, t.name);
for (const i of await db.select({ id: integrations.id, name: integrations.name }).from(integrations)) names.set(`integration:${i.id}`, i.name);
for (const p of await db.select({ id: dnsProviders.id, name: dnsProviders.name }).from(dnsProviders)) names.set(`dns_provider:${p.id}`, p.name);
for (const a of await db.select().from(maintenanceAliases)) {
const name = names.get(`${a.targetType}:${a.targetId}`);
if (name) addressed.push({ type: a.targetType, id: a.targetId, name, host: a.address });
}
const byMonitor = new Map(monitors.map((m) => [m.id, m]));
const { desired, summary } = desiredWindows(
@@ -241,7 +251,7 @@ export async function syncKumaMaintenance(integrationId: number, now: Date = new
(id) => targetsForHost(byMonitor.get(id)?.target ?? null, matchableServers, addressed),
(id) => {
const m = byMonitor.get(id);
if (!m) return `monitor #${id}`;
if (!m) return `monitor #${id} (not in Uptime Kuma's metrics — paused?)`;
return m.target ? `${m.name} (${m.target}${m.port ? `:${m.port}` : ""})` : `${m.name} (no address)`;
},
now,
+66 -1
View File
@@ -23,7 +23,9 @@ process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default;
const { Server: IOServer } = await import("socket.io");
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, dnsProviders, maintenanceWindows } = await import("../src/db/schema.js");
const { users, servers, integrations, dnsProviders, maintenanceAliases, maintenanceWindows } = await import("../src/db/schema.js");
const { eq } = await import("drizzle-orm");
const { parsePrometheusText, monitorsFromSamples } = await import("../src/integrations/uptimekuma/adapter.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { maintenanceRouter } = await import("../src/routes/maintenance.js");
const { kumaInstant, normalizeMaintenanceList, monitorIdsFromReply } = await import("../src/integrations/uptimekuma/maintenanceFeed.js");
@@ -78,6 +80,21 @@ describe("reading Kuma's lists", () => {
});
});
describe("Uptime Kuma's text \"null\"", () => {
test("a monitor field that is the text null is no address, and the URL is used instead", () => {
const text = [
'monitor_status{monitor_id="1",monitor_name="Site",monitor_type="keyword",monitor_url="https://www.example.com/x",monitor_hostname="null",monitor_port="null"} 1',
'monitor_status{monitor_id="2",monitor_name="Empty",monitor_type="group",monitor_url="null",monitor_hostname="null",monitor_port="null"} 1',
].join("\n");
const monitors = monitorsFromSamples(parsePrometheusText(text));
const site = monitors.find((m) => m.name === "Site")!;
const empty = monitors.find((m) => m.name === "Empty")!;
assert.equal(site.target, "www.example.com");
assert.equal(site.port, null);
assert.equal(empty.target, null);
});
});
describe("which things a monitor's address belongs to", () => {
const serverList = [{ id: 1, name: "elsa", hostname: "elsa.lab.example", ips: ["10.0.0.5", "fd00::5"] }];
const addressed = [
@@ -371,6 +388,54 @@ describe("syncing from a stand-in Uptime Kuma", () => {
await sync();
});
test("an alias sends a monitor on some other address to the thing it belongs to, and removing it takes the window away again", async () => {
await db.delete(maintenanceWindows);
const [felicia] = await db.select().from(integrations).where(eq(integrations.name, "Proxmox Felicia"));
const start = Date.now() + 4 * HOUR;
kuma.list = { "7": daily(start, start + HOUR, { id: 7, title: "Over Tailscale" }) };
kuma.monitorsOf = { "7": [3] }; // watches 10.9.9.9, which nothing here is called
assert.equal((await sync()).body.started, 0, "before the alias there is nothing to attach to");
const added = await fetch(`${base}/aliases`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ address: "https://10.9.9.9:8006/", targetType: "integration", targetId: felicia.id }),
});
assert.equal(added.status, 201, await added.clone().text());
const alias = (await added.json()).alias;
assert.equal(alias.address, "10.9.9.9", "stored as a bare host");
const { body } = await sync();
assert.equal(body.started, 1);
assert.deepEqual(body.maintenances[0].targets, [{ type: "integration", name: "Proxmox Felicia" }]);
const listed = await (await fetch(base)).json();
assert.equal(listed.aliases.length, 1);
assert.equal(listed.aliases[0].targetName, "Proxmox Felicia");
assert.equal((await fetch(`${base}/aliases/${alias.id}`, { method: "DELETE" })).status, 204);
const after = await sync();
assert.equal(after.body.removed, 1, "with the alias gone, the window that depended on it goes too");
assert.equal((await listUpcomingWindows()).length, 0);
kuma.list = { "5": daily(start, start + HOUR) };
kuma.monitorsOf = { "5": [1, 2, 3] };
await sync();
});
test("an alias must be a real address, can't be added twice, and must point at something that exists", async () => {
const [felicia] = await db.select().from(integrations).where(eq(integrations.name, "Proxmox Felicia"));
const post = (body: unknown) =>
fetch(`${base}/aliases`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
assert.equal((await post({ address: " ", targetType: "integration", targetId: felicia.id })).status, 400);
assert.equal((await post({ address: "10.1.1.1", targetType: "integration", targetId: 99999 })).status, 404);
assert.equal((await post({ address: "10.1.1.1", targetType: "integration", targetId: felicia.id })).status, 201);
assert.equal((await post({ address: "10.1.1.1", targetType: "integration", targetId: felicia.id })).status, 409);
const [row] = await db.select().from(maintenanceAliases);
await fetch(`${base}/aliases/${row.id}`, { method: "DELETE" });
});
test("syncing again adds nothing", async () => {
const { body } = await sync();
assert.deepEqual([body.started, body.updated, body.removed], [0, 0, 0]);