Heartbeats: a cron job or script calls /api/heartbeat/<token> (and /start, /fail); the app alerts when the call is late or the job says it failed. Coming up: one agenda of everything dated (expiries, warranties, end of support, planned and recurring maintenance, restore tests, waiting updates), with a dashboard card and an iCalendar feed behind a share link. Suggested checks: web ports and certificates the app already knows about, added with a click. Menu: Incidents become Alerts -> History (old /incidents links redirect); new Monitoring group (Endpoints, Heartbeats, Uptime Kuma); osTicket under Automation, Admin Links under Infrastructure, Generator under Administration. Also makes the restore-test metrics test follow the real clock. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
118 lines
6.3 KiB
TypeScript
118 lines
6.3 KiB
TypeScript
import { Router } from "express";
|
|
import { eq } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import { db } from "../db/client.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();
|
|
|
|
// Making a link that anyone can open without signing in is an administrator's decision.
|
|
shareLinksRouter.use(requireAuth, requireRole("admin"));
|
|
|
|
/** More links than anyone needs; each is something to keep track of and take back. */
|
|
const MAX_LINKS = 20;
|
|
|
|
const createSchema = z.object({
|
|
label: z.string().trim().min(1).max(60),
|
|
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. For a calendar: summary leaves the names out of the events.
|
|
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);
|
|
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 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) {
|
|
return res.status(400).json({ error: "too_many", message: `There are already ${MAX_LINKS} share links. Remove one you no longer use first.` });
|
|
}
|
|
const actor = req.currentUser!;
|
|
const { link, token } = await createShareLink({ ...parsed.data, createdBy: actor.name ?? actor.email ?? actor.oidcSub });
|
|
await recordAudit({
|
|
actor,
|
|
category: "share_link",
|
|
action: "create",
|
|
targetType: "share_link",
|
|
targetId: link.id,
|
|
detail: { label: link.label, kind: link.kind, detail: link.detail, expiresAt: link.expiresAt },
|
|
});
|
|
res.status(201).json({ link: publicShareLink(link), token, path: link.kind === "calendar" ? `/api/public/calendar/${token}.ics` : `/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) => {
|
|
const id = Number(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) 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, kind: link.kind } });
|
|
res.status(204).end();
|
|
}));
|