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>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-18 15:38:08 +02:00
1 parent 2744a84719
commit 5cc51c57de
24 files changed
+4880 -35

No files matched your search

+9
View File
@@ -6,6 +6,7 @@ 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";
@@ -34,6 +35,14 @@ 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) });
+19
View File
@@ -0,0 +1,19 @@
import { Router } from "express";
import { NOT_FOUND, resolveShareLink } from "../services/shareLinks.js";
import { buildPublicStatus } from "../services/statusPage.js";
import { rateLimit } from "../utils/rateLimit.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const publicStatusRouter = Router();
// No sign-in: the secret in the address is the whole of the access, so this reads nothing but the page's own picture, and answers a link that
// doesn't work — never made, ended, taken back, or a wall's rather than a status page's — in the same words.
const limiter = rateLimit({ windowMs: 60_000, max: 60, message: "Too many requests. Wait a minute." });
publicStatusRouter.get("/:token", limiter, asyncHandler(async (req, res) => {
const link = await resolveShareLink(req.params.token);
if (!link || link.kind !== "status") return res.status(404).json(NOT_FOUND);
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Robots-Tag", "noindex, nofollow");
res.json(await buildPublicStatus(link));
}));
+2 -1
View File
@@ -12,7 +12,8 @@ const limiter = rateLimit({ windowMs: 60_000, max: 60, message: "Too many reques
publicWallRouter.get("/:token", limiter, asyncHandler(async (req, res) => {
const link = await resolveShareLink(req.params.token);
if (!link) return res.status(404).json(NOT_FOUND);
// A status page's address doesn't open the wall (and the other way round): each shows only what its link was made to show.
if (!link || link.kind !== "wall") return res.status(404).json(NOT_FOUND);
res.setHeader("Cache-Control", "no-store");
res.setHeader("X-Robots-Tag", "noindex, nofollow");
res.json(await buildPublicWall(link.detail));
+63 -7
View File
@@ -2,10 +2,11 @@ import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { shareLinkDetails, shareLinks } from "../db/schema.js";
import { shareLinkDetails, shareLinkKinds, shareLinks, statusItemKinds, statusItems } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { createShareLink, publicShareLink } from "../services/shareLinks.js";
import { getStatusItems, MAX_ITEMS, MAX_LABEL, MAX_MESSAGE, MAX_TITLE, setStatusItems, statusChoices, StatusPageError } from "../services/statusPage.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const shareLinksRouter = Router();
@@ -18,20 +19,31 @@ const MAX_LINKS = 20;
const createSchema = z.object({
label: z.string().trim().min(1).max(60),
detail: z.enum(shareLinkDetails),
kind: z.enum(shareLinkKinds).default("wall"),
// For a wall: how much it shows. A status page always shows only names and states, so this is ignored for it.
detail: z.enum(shareLinkDetails).default("summary"),
title: z.string().trim().max(MAX_TITLE).optional(),
message: z.string().trim().max(MAX_MESSAGE).optional(),
expiresInDays: z.number().int().min(1).max(365).nullable(),
});
shareLinksRouter.get("/", asyncHandler(async (_req, res) => {
const rows = await db.select().from(shareLinks).orderBy(shareLinks.createdAt);
res.json({ links: rows.map((r) => publicShareLink(r)) });
const counts = new Map<number, number>();
for (const i of await db.select({ linkId: statusItems.linkId }).from(statusItems)) counts.set(i.linkId, (counts.get(i.linkId) ?? 0) + 1);
res.json({ links: rows.map((r) => ({ ...publicShareLink(r), itemCount: counts.get(r.id) ?? 0 })) });
}));
// What a status page can be made of, for the editor: servers and integrations (Uptime Kuma's monitors are read from its own page of the app).
shareLinksRouter.get("/status-choices", asyncHandler(async (_req, res) => {
res.json(await statusChoices());
}));
// The secret part of the address is in this response and nowhere else, ever: only a hash of it is kept.
shareLinksRouter.post("/", asyncHandler(async (req, res) => {
const parsed = createSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "invalid_body", message: "Give the link a name, say how much it shows, and how long it lasts.", details: parsed.error.flatten() });
return res.status(400).json({ error: "invalid_body", message: "Give the link a name, say what it opens and how long it lasts.", details: parsed.error.flatten() });
}
const existing = await db.select({ id: shareLinks.id }).from(shareLinks);
if (existing.length >= MAX_LINKS) {
@@ -45,9 +57,53 @@ shareLinksRouter.post("/", asyncHandler(async (req, res) => {
action: "create",
targetType: "share_link",
targetId: link.id,
detail: { label: link.label, detail: link.detail, expiresAt: link.expiresAt },
detail: { label: link.label, kind: link.kind, detail: link.detail, expiresAt: link.expiresAt },
});
res.status(201).json({ link: publicShareLink(link), token, path: `/share/wall/${token}` });
res.status(201).json({ link: publicShareLink(link), token, path: `/share/${link.kind === "status" ? "status" : "wall"}/${token}` });
}));
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
// A status page's heading, message and the things on it.
shareLinksRouter.get("/:id/status", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.id, id)).limit(1);
if (!link || link.kind !== "status") return res.status(404).json({ error: "not_found" });
res.json({ title: link.title ?? "", message: link.message ?? "", items: await getStatusItems(id), maxItems: MAX_ITEMS });
}));
const statusSchema = z.object({
title: z.string().trim().max(MAX_TITLE),
message: z.string().trim().max(MAX_MESSAGE),
items: z
.array(
z.object({
label: z.string().trim().min(1).max(MAX_LABEL),
kind: z.enum(statusItemKinds),
targetId: z.number().int().positive(),
monitorId: z.string().max(100).nullable().optional(),
}),
)
.max(MAX_ITEMS),
});
shareLinksRouter.put("/:id/status", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.id, id)).limit(1);
if (!link || link.kind !== "status") return res.status(404).json({ error: "not_found" });
const parsed = statusSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.error.issues[0]?.message ?? "A title, a message and up to thirty named things.", details: parsed.error.flatten() });
try {
await setStatusItems(id, parsed.data.items);
} catch (err) {
if (err instanceof StatusPageError) return res.status(err.status).json({ error: err.code, message: err.message });
throw err;
}
await db.update(shareLinks).set({ title: parsed.data.title || null, message: parsed.data.message || null }).where(eq(shareLinks.id, id));
await recordAudit({ actor: req.currentUser!, category: "share_link", action: "update_status_page", targetType: "share_link", targetId: id, detail: { label: link.label, items: parsed.data.items.map((i) => i.label) } });
res.json({ title: parsed.data.title, message: parsed.data.message, items: await getStatusItems(id) });
}));
shareLinksRouter.delete("/:id", asyncHandler(async (req, res) => {
@@ -56,6 +112,6 @@ shareLinksRouter.delete("/:id", asyncHandler(async (req, res) => {
const [link] = await db.select().from(shareLinks).where(eq(shareLinks.id, id)).limit(1);
if (!link) return res.status(404).json({ error: "not_found" });
await db.delete(shareLinks).where(eq(shareLinks.id, id));
await recordAudit({ actor: req.currentUser!, category: "share_link", action: "delete", targetType: "share_link", targetId: id, detail: { label: link.label } });
await recordAudit({ actor: req.currentUser!, category: "share_link", action: "delete", targetType: "share_link", targetId: id, detail: { label: link.label, kind: link.kind } });
res.status(204).end();
}));