Files
Homelab-manager/server/src/routes/metrics.ts
T
bobbanandClaude Sonnet 5.5 5cc51c57de Add status pages (a share link kind) and a downloadable Grafana dashboard
- Share links can open a status page: an admin picks servers, integrations and Uptime Kuma
  monitors and names them; the public sees only those names, Working / Not working /
  Being worked on / Can't tell, an optional message and the 30-day figure (share_links.kind/
  title/message and status_items, migration 0033). A status address doesn't open the wall and
  the other way round; Uptime Kuma is asked at most every 30 seconds
- Grafana dashboard built from code (download in Settings -> API and webhooks); a test checks
  it only uses series /metrics serves
- Tests and docs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 15:38:08 +02:00

73 lines
4.0 KiB
TypeScript

import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { metricsTokens } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { buildMetrics } from "../services/metrics.js";
import { buildGrafanaDashboard } from "../services/grafanaDashboard.js";
import { createMetricsToken, publicMetricsToken, resolveMetricsToken } from "../services/metricsTokens.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { rateLimit } from "../utils/rateLimit.js";
/** Prometheus's scrape: no sign-in, a bearer token instead. The token goes in a header only — never the address, which ends up in logs. */
export const metricsRouter = Router();
const limiter = rateLimit({ windowMs: 60_000, max: 120, message: "Too many requests." });
metricsRouter.get("/", limiter, asyncHandler(async (req, res) => {
const match = /^Bearer\s+(\S+)$/i.exec(req.get("authorization") ?? "");
const token = match ? await resolveMetricsToken(match[1]) : null;
if (!token) {
// The same answer for no token, a wrong one and a removed one.
res.setHeader("WWW-Authenticate", 'Bearer realm="metrics"');
return res.status(401).type("text/plain").send("A metrics token is needed: send it as 'Authorization: Bearer <token>'.\n");
}
res.setHeader("Cache-Control", "no-store");
// Written out as Prometheus documents it (Express would put the parameters in another order).
res.setHeader("Content-Type", "text/plain; version=0.0.4; charset=utf-8");
res.end(await buildMetrics());
}));
/** Managing the tokens: an administrator's. */
export const metricsTokensRouter = Router();
metricsTokensRouter.use(requireAuth, requireRole("admin"));
const MAX_TOKENS = 10;
// A Grafana dashboard for these series, to import (Dashboards → New → Import). Nothing in it is specific to this installation: Grafana asks which
// Prometheus to use.
metricsTokensRouter.get("/grafana-dashboard.json", asyncHandler(async (_req, res) => {
res.setHeader("Content-Disposition", "attachment; filename=\"homelab-manager-dashboard.json\"");
res.setHeader("Cache-Control", "no-store");
res.json(buildGrafanaDashboard());
}));
metricsTokensRouter.get("/", asyncHandler(async (_req, res) => {
const rows = await db.select().from(metricsTokens).orderBy(metricsTokens.createdAt);
res.json({ tokens: rows.map(publicMetricsToken) });
}));
// The secret is in this answer and nowhere else, ever.
metricsTokensRouter.post("/", asyncHandler(async (req, res) => {
const parsed = z.object({ label: z.string().trim().min(1).max(60) }).safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give the token a name, like Prometheus." });
if ((await db.select({ id: metricsTokens.id }).from(metricsTokens)).length >= MAX_TOKENS) {
return res.status(400).json({ error: "too_many", message: `There are already ${MAX_TOKENS} tokens. Remove one you don't use first.` });
}
const actor = req.currentUser!;
const { row, token } = await createMetricsToken({ label: parsed.data.label, createdBy: actor.name ?? actor.email ?? actor.oidcSub });
await recordAudit({ actor, category: "metrics_token", action: "create", targetType: "metrics_token", targetId: row.id, detail: { label: row.label } });
res.status(201).json({ token: publicMetricsToken(row), secret: token });
}));
metricsTokensRouter.delete("/:id", asyncHandler(async (req, res) => {
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [row] = await db.select().from(metricsTokens).where(eq(metricsTokens.id, id)).limit(1);
if (!row) return res.status(404).json({ error: "not_found" });
await db.delete(metricsTokens).where(eq(metricsTokens.id, id));
await recordAudit({ actor: req.currentUser!, category: "metrics_token", action: "delete", targetType: "metrics_token", targetId: id, detail: { label: row.label } });
res.status(204).end();
}));