Files
Homelab-manager/server/src/routes/publicApi.ts
T
bobbanandClaude Sonnet 5.5 0277126add What changed before this? on every incident, ranked
- A card on the incident page, and GET /api/incidents/:id/before and /api/v1/incidents/:id/before: what the app knows happened in the 30 min to 24 h before an alert began (audit log, maintenance windows, update runs and patch plans, other alerts, a step in the server's own figures), scored by how related, what kind and how close
- A host going down is shown once; Likely, Possible and Background; at most ten
- Docs and roles updated

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

176 lines
7.8 KiB
TypeScript

import { Router, type NextFunction, type Request, type Response } from "express";
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { endpointChecks, servers } from "../db/schema.js";
import { resolveApiToken, type ApiTokenRow, type ApiTokenUser } from "../services/apiTokens.js";
import { getEndpointHistory } from "../services/endpointChecks.js";
import { getIncident, listIncidents } from "../services/incidents.js";
import { whatChangedBefore } from "../services/incidentBefore.js";
import { buildNetworkOverview } from "../services/networkOverview.js";
import { alertsV1, endpointsV1, inventoryV1, maintenanceV1, oneServerV1, serversV1 } from "../services/publicApi.js";
import { getServerMetrics, MAX_RANGE_DAYS } from "../services/serverMetrics.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { rateLimit } from "../utils/rateLimit.js";
/**
* The read API: JSON about servers, alerts, incidents, inventory, network equipment, endpoint checks and maintenance, for scripts and things like Home Assistant.
* A personal token in the Authorization header (never the address, which ends up in logs); GET only; and nothing here writes anything.
*/
export const publicApiRouter = Router();
declare module "express-serve-static-core" {
interface Request {
apiToken?: { token: ApiTokenRow; user: ApiTokenUser };
}
}
const limiter = rateLimit({ windowMs: 60_000, max: 300, message: "Too many requests." });
publicApiRouter.use(limiter);
publicApiRouter.use((req: Request, res: Response, next: NextFunction) => {
res.setHeader("Cache-Control", "no-store");
if (req.method !== "GET" && req.method !== "HEAD") {
res.setHeader("Allow", "GET, HEAD");
return res.status(405).json({ error: "read_only", message: "This API only reads. It has no way to change anything." });
}
next();
});
publicApiRouter.use(
asyncHandler(async (req, res, next) => {
const match = /^Bearer\s+(\S+)$/i.exec(req.get("authorization") ?? "");
const found = match ? await resolveApiToken(match[1]) : null;
if (!found) {
// The same answer for no token, a wrong one, an expired one and a removed one.
res.setHeader("WWW-Authenticate", 'Bearer realm="homelab-manager"');
return res.status(401).json({ error: "unauthorized", message: "A token is needed: send it as 'Authorization: Bearer <token>'. Make one from the user menu → API tokens." });
}
req.apiToken = found;
next();
}),
);
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const daysOf = (v: unknown, fallback: number) => {
const n = Number(v);
return Number.isFinite(n) ? Math.min(MAX_RANGE_DAYS, Math.max(1, Math.round(n))) : fallback;
};
publicApiRouter.get("/", (_req, res) => {
res.json({
name: "Homelab Manager read API",
version: 1,
endpoints: [
"GET /api/v1/me",
"GET /api/v1/servers?tag=&status=",
"GET /api/v1/servers/:id",
"GET /api/v1/servers/:id/metrics?days=",
"GET /api/v1/alerts?severity=&category=&acknowledged=&silenced=",
"GET /api/v1/incidents?status=&limit=",
"GET /api/v1/incidents/:id",
"GET /api/v1/incidents/:id/before?minutes=",
"GET /api/v1/inventory",
"GET /api/v1/network",
"GET /api/v1/endpoints",
"GET /api/v1/endpoints/:id/history?days=",
"GET /api/v1/maintenance",
],
});
});
publicApiRouter.get("/me", (req, res) => {
const { token, user } = req.apiToken!;
res.json({ user: { id: user.id, name: user.name, email: user.email, role: user.role }, token: { id: token.id, label: token.label, expiresAt: token.expiresAt } });
});
publicApiRouter.get("/servers", asyncHandler(async (req, res) => {
let list = await serversV1();
if (typeof req.query.tag === "string" && req.query.tag) {
const tag = req.query.tag.toLowerCase();
list = list.filter((s) => s.tags.includes(tag));
}
if (req.query.status === "online" || req.query.status === "offline" || req.query.status === "unknown") list = list.filter((s) => s.status === req.query.status);
res.json({ servers: list });
}));
publicApiRouter.get("/servers/:id", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const server = await oneServerV1(id);
if (!server) return res.status(404).json({ error: "not_found" });
res.json({ server });
}));
publicApiRouter.get("/servers/:id/metrics", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [row] = await db.select({ id: servers.id }).from(servers).where(eq(servers.id, id)).limit(1);
if (!row) return res.status(404).json({ error: "not_found" });
const days = daysOf(req.query.days, 7);
res.json({ days, series: await getServerMetrics(id, days) });
}));
publicApiRouter.get("/alerts", asyncHandler(async (req, res) => {
const report = await alertsV1();
let alerts = report.alerts;
const q = req.query;
if (typeof q.severity === "string") alerts = alerts.filter((a) => a.severity === q.severity);
if (typeof q.category === "string") alerts = alerts.filter((a) => a.category === q.category);
if (q.acknowledged === "true" || q.acknowledged === "false") alerts = alerts.filter((a) => (a.acknowledgement !== null) === (q.acknowledged === "true"));
if (q.silenced === "true" || q.silenced === "false") alerts = alerts.filter((a) => a.silenced === (q.silenced === "true"));
res.json({ ...report, alerts });
}));
publicApiRouter.get("/incidents", asyncHandler(async (req, res) => {
const limit = Math.min(500, Math.max(1, Math.round(Number(req.query.limit)) || 100));
let list = await listIncidents({ limit });
if (req.query.status === "open") list = list.filter((i) => i.open);
else if (req.query.status === "resolved") list = list.filter((i) => !i.open);
res.json({ incidents: list });
}));
publicApiRouter.get("/incidents/:id", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const detail = await getIncident(id);
if (!detail) return res.status(404).json({ error: "not_found" });
res.json(detail);
}));
publicApiRouter.get("/incidents/:id/before", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const report = await whatChangedBefore(id, req.query.minutes === undefined ? undefined : Number(req.query.minutes));
if (!report) return res.status(404).json({ error: "not_found" });
res.json(report);
}));
publicApiRouter.get("/inventory", asyncHandler(async (_req, res) => {
res.json({ assets: await inventoryV1() });
}));
publicApiRouter.get("/network", asyncHandler(async (_req, res) => {
const overview = await buildNetworkOverview();
res.json({ devices: overview.devices, networks: overview.networks, ssids: overview.ssids, serverLinks: overview.serverLinks });
}));
publicApiRouter.get("/endpoints", asyncHandler(async (_req, res) => {
res.json({ endpoints: await endpointsV1() });
}));
publicApiRouter.get("/endpoints/:id/history", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [check] = await db.select({ id: endpointChecks.id, name: endpointChecks.name }).from(endpointChecks).where(eq(endpointChecks.id, id)).limit(1);
if (!check) return res.status(404).json({ error: "not_found" });
res.json({ check, ...(await getEndpointHistory(id, daysOf(req.query.days, 7))) });
}));
publicApiRouter.get("/maintenance", asyncHandler(async (_req, res) => {
res.json(await maintenanceV1());
}));
publicApiRouter.use((_req, res) => {
res.status(404).json({ error: "not_found", message: "No such address. GET /api/v1 lists them." });
});