Files
Homelab-manager/server/src/routes/runbooks.ts
T
bobbanandClaude Sonnet 5.5 396e074108 UniFi integration: network devices, Wi-Fi and networks, as part of the dependency map
A UniFi controller (API key on Network 9+, or a read-only local login on any
version) is read every five minutes. Its switches, access points and gateways
are kept with state, IP, uptime, firmware and uplink; its networks and Wi-Fi
names beside them (passphrases are never read). Nothing is written to the
controller.

Network > Network devices lists them. Devices are a new node type in the
dependency map: uplinks become dependencies by themselves, others can be
written by hand. A device offline past a limit is an offline alert, folds what
depends on it, can be silenced with maintenance and have runbooks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 00:35:48 +02:00

101 lines
6.0 KiB
TypeScript

import { Router } from "express";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { dnsProviders, integrations, maintenanceTargetTypes, networkDevices, runbooks, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { describeTarget } from "../services/maintenance.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const runbooksRouter = Router();
// Anyone signed in can read what to do when something is wrong — that is the point of having it written down. Changing it is for operators.
runbooksRouter.use(requireAuth);
/** More than anyone needs for one thing; each is another note to keep true. */
const MAX_PER_TARGET = 20;
export const ALERT_CATEGORIES = ["offline", "disk", "services", "backup", "updates", "expiry", "automation", "integration", "monitoring", "tickets"] as const;
const bodySchema = z.object({
title: z.string().trim().min(1).max(120),
body: z.string().max(20_000),
/** An alert category this is for, or null for any alert about the target. */
category: z.enum(ALERT_CATEGORIES).nullable().optional(),
});
const createSchema = bodySchema.extend({ targetType: z.enum(maintenanceTargetTypes), targetId: z.number().int().positive() });
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
// What there is for one thing: the full text.
runbooksRouter.get("/", asyncHandler(async (req, res) => {
const targetType = z.enum(maintenanceTargetTypes).safeParse(req.query.targetType);
const targetId = idOf(String(req.query.targetId ?? ""));
if (!targetType.success || !Number.isInteger(targetId)) return res.status(400).json({ error: "invalid_target" });
const rows = await db.select().from(runbooks).where(and(eq(runbooks.targetType, targetType.data), eq(runbooks.targetId, targetId))).orderBy(runbooks.title);
res.json({ runbooks: rows });
}));
// What there is, everywhere, by title only — so a page can show a "runbook" button exactly where one exists, without fetching the texts.
// Notes for something that has since been removed are left out.
runbooksRouter.get("/summary", asyncHandler(async (_req, res) => {
const [rows, serverIds, integrationIds, providerIds, deviceIds] = await Promise.all([
db.select({ id: runbooks.id, targetType: runbooks.targetType, targetId: runbooks.targetId, category: runbooks.category, title: runbooks.title }).from(runbooks),
db.select({ id: servers.id }).from(servers),
db.select({ id: integrations.id }).from(integrations),
db.select({ id: dnsProviders.id }).from(dnsProviders),
db.select({ id: networkDevices.id }).from(networkDevices),
]);
const exists = {
server: new Set(serverIds.map((r) => r.id)),
integration: new Set(integrationIds.map((r) => r.id)),
dns_provider: new Set(providerIds.map((r) => r.id)),
device: new Set(deviceIds.map((r) => r.id)),
};
res.json({ runbooks: rows.filter((r) => exists[r.targetType].has(r.targetId)) });
}));
runbooksRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => {
const parsed = createSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give it a title and some text, and say what it is for.", details: parsed.error.flatten() });
const d = parsed.data;
if (!(await describeTarget(d.targetType, d.targetId))) return res.status(400).json({ error: "unknown_target", message: "That server, integration or DNS provider doesn't exist." });
const existing = await db.select({ id: runbooks.id }).from(runbooks).where(and(eq(runbooks.targetType, d.targetType), eq(runbooks.targetId, d.targetId)));
if (existing.length >= MAX_PER_TARGET) return res.status(400).json({ error: "too_many", message: `There are already ${MAX_PER_TARGET} notes for this. Tidy those first.` });
const actor = req.currentUser!;
const now = new Date().toISOString();
const [row] = await db
.insert(runbooks)
.values({ targetType: d.targetType, targetId: d.targetId, title: d.title, body: d.body, category: d.category ?? null, updatedBy: actor.name ?? actor.email ?? actor.oidcSub, createdAt: now, updatedAt: now })
.returning();
await recordAudit({ actor, category: "runbook", action: "create", targetType: d.targetType, targetId: d.targetId, detail: { title: d.title, category: d.category ?? null } });
res.status(201).json({ runbook: row });
}));
runbooksRouter.put("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const parsed = bodySchema.safeParse(req.body);
if (!Number.isInteger(id) || !parsed.success) return res.status(400).json({ error: "invalid_body", details: parsed.success ? undefined : parsed.error.flatten() });
const [before] = await db.select().from(runbooks).where(eq(runbooks.id, id)).limit(1);
if (!before) return res.status(404).json({ error: "not_found" });
const actor = req.currentUser!;
const [row] = await db
.update(runbooks)
.set({ title: parsed.data.title, body: parsed.data.body, category: parsed.data.category ?? null, updatedBy: actor.name ?? actor.email ?? actor.oidcSub, updatedAt: new Date().toISOString() })
.where(eq(runbooks.id, id))
.returning();
await recordAudit({ actor, category: "runbook", action: "update", targetType: before.targetType, targetId: before.targetId, detail: { title: parsed.data.title } });
res.json({ runbook: row });
}));
runbooksRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [before] = await db.select().from(runbooks).where(eq(runbooks.id, id)).limit(1);
if (!before) return res.status(404).json({ error: "not_found" });
await db.delete(runbooks).where(eq(runbooks.id, id));
await recordAudit({ actor: req.currentUser!, category: "runbook", action: "delete", targetType: before.targetType, targetId: before.targetId, detail: { title: before.title } });
res.status(204).end();
}));