Add runbooks, backup coverage, inventory, roles from groups, Prometheus metrics and event webhooks
- Runbooks: notes per server/integration, shown next to matching alerts - Backup coverage page across Proxmox and PBS, with a digest section - Hardware inventory with warranty, power and running cost - Authentik group to role mapping with preview and safeguards - /metrics (bearer token) and signed outgoing event webhooks - Docs: README, DATABASE, NOTIFICATIONS, ROLES and new API.md Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c36e2092c5
commit
c17e9aa140
55 files changed
+7177
-27
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import { Router } from "express";
|
||||
import { requireAuth } from "../auth/middleware.js";
|
||||
import { DEFAULT_STALE_HOURS, getBackupCoverage } from "../services/backupCoverage.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const backupsRouter = Router();
|
||||
|
||||
// Everyone signed in can see what is and isn't backed up, like the Proxmox and Backup Server pages it is drawn from.
|
||||
backupsRouter.use(requireAuth);
|
||||
|
||||
// `staleDays`: how old the newest backup may be before a guest counts as stale (default 2). `refresh=1` asks Proxmox again now.
|
||||
backupsRouter.get("/coverage", asyncHandler(async (req, res) => {
|
||||
const days = Number(req.query.staleDays);
|
||||
const staleHours = Number.isFinite(days) && days >= 1 && days <= 60 ? Math.round(days * 24) : DEFAULT_STALE_HOURS;
|
||||
res.json(await getBackupCoverage({ staleHours, refresh: req.query.refresh === "1" }));
|
||||
}));
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { eventWebhooks, webhookEvents } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { deliver, parseEvents, sealSecret, type EventWebhookRow } from "../services/eventWebhooks.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const eventWebhooksRouter = Router();
|
||||
|
||||
// A URL that is sent a message whenever something happens: an administrator's to set up.
|
||||
eventWebhooksRouter.use(requireAuth, requireRole("admin"));
|
||||
|
||||
const MAX_WEBHOOKS = 20;
|
||||
|
||||
const url = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(500)
|
||||
.refine((v) => {
|
||||
try {
|
||||
const u = new URL(v);
|
||||
return (u.protocol === "http:" || u.protocol === "https:") && !u.username && !u.password;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, "Use an http:// or https:// address, without a user name or password in it");
|
||||
|
||||
const createSchema = z.object({
|
||||
label: z.string().trim().min(1).max(60),
|
||||
url,
|
||||
secret: z.string().max(200).optional(),
|
||||
events: z.array(z.enum(webhookEvents)).min(1).max(webhookEvents.length),
|
||||
});
|
||||
const patchSchema = z.object({ enabled: z.boolean() });
|
||||
|
||||
/** A webhook as the list shows it: never the secret, only whether there is one. */
|
||||
function present(row: EventWebhookRow) {
|
||||
return { id: row.id, label: row.label, url: row.url, hasSecret: !!row.secret, events: parseEvents(row.events), enabled: row.enabled, createdBy: row.createdBy, createdAt: row.createdAt, lastAttemptAt: row.lastAttemptAt, lastResult: row.lastResult };
|
||||
}
|
||||
|
||||
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
|
||||
|
||||
eventWebhooksRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const rows = await db.select().from(eventWebhooks).orderBy(eventWebhooks.label);
|
||||
res.json({ webhooks: rows.map(present), events: webhookEvents });
|
||||
}));
|
||||
|
||||
eventWebhooksRouter.post("/", 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 name, an http(s) address and at least one event.", details: parsed.error.flatten() });
|
||||
}
|
||||
if ((await db.select({ id: eventWebhooks.id }).from(eventWebhooks)).length >= MAX_WEBHOOKS) {
|
||||
return res.status(400).json({ error: "too_many", message: `There are already ${MAX_WEBHOOKS} webhooks. Remove one you don't use first.` });
|
||||
}
|
||||
const actor = req.currentUser!;
|
||||
const [row] = await db
|
||||
.insert(eventWebhooks)
|
||||
.values({ label: parsed.data.label, url: parsed.data.url, secret: parsed.data.secret ? sealSecret(parsed.data.secret) : null, events: JSON.stringify([...new Set(parsed.data.events)]), createdBy: actor.name ?? actor.email ?? actor.oidcSub })
|
||||
.returning();
|
||||
// The address can carry a token of its own, so the audit log gets the name and the events, not the address.
|
||||
await recordAudit({ actor, category: "webhook", action: "create", targetType: "event_webhook", targetId: row.id, detail: { label: row.label, events: parseEvents(row.events), signed: !!row.secret } });
|
||||
res.status(201).json({ webhook: present(row) });
|
||||
}));
|
||||
|
||||
eventWebhooksRouter.patch("/:id", asyncHandler(async (req, res) => {
|
||||
const id = idOf(req.params.id);
|
||||
const parsed = patchSchema.safeParse(req.body);
|
||||
if (!Number.isInteger(id) || !parsed.success) return res.status(400).json({ error: "invalid_body" });
|
||||
const [row] = await db.update(eventWebhooks).set({ enabled: parsed.data.enabled }).where(eq(eventWebhooks.id, id)).returning();
|
||||
if (!row) return res.status(404).json({ error: "not_found" });
|
||||
await recordAudit({ actor: req.currentUser!, category: "webhook", action: parsed.data.enabled ? "enable" : "disable", targetType: "event_webhook", targetId: id, detail: { label: row.label } });
|
||||
res.json({ webhook: present(row) });
|
||||
}));
|
||||
|
||||
eventWebhooksRouter.delete("/:id", 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().from(eventWebhooks).where(eq(eventWebhooks.id, id)).limit(1);
|
||||
if (!row) return res.status(404).json({ error: "not_found" });
|
||||
await db.delete(eventWebhooks).where(eq(eventWebhooks.id, id));
|
||||
await recordAudit({ actor: req.currentUser!, category: "webhook", action: "delete", targetType: "event_webhook", targetId: id, detail: { label: row.label } });
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
// Sends one test message, signed like the real ones, and says how it went — whether or not the webhook is switched on or wants the event.
|
||||
eventWebhooksRouter.post("/:id/test", 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().from(eventWebhooks).where(eq(eventWebhooks.id, id)).limit(1);
|
||||
if (!row) return res.status(404).json({ error: "not_found" });
|
||||
const outcome = await deliver(row, "test", { message: "This is a test from Homelab Manager." });
|
||||
res.json(outcome);
|
||||
}));
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { assetKinds, assets, servers } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { isRealDate } from "../services/inventory.js";
|
||||
import { getSettings, updateSettings } from "../services/settingsStore.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const inventoryRouter = Router();
|
||||
|
||||
inventoryRouter.use(requireAuth);
|
||||
|
||||
const text = (max: number) => z.string().trim().max(max).nullable().optional();
|
||||
const date = z.string().refine(isRealDate, "Use a date like 2026-10-17").nullable().optional();
|
||||
|
||||
const assetSchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
kind: z.enum(assetKinds),
|
||||
manufacturer: text(100),
|
||||
model: text(100),
|
||||
serial: text(100),
|
||||
purchaseDate: date,
|
||||
purchasePrice: z.number().min(0).max(1_000_000_000).nullable().optional(),
|
||||
warrantyUntil: date,
|
||||
location: text(120),
|
||||
rackUnit: text(30),
|
||||
powerWatts: z.number().int().min(0).max(100_000).nullable().optional(),
|
||||
serverId: z.number().int().positive().nullable().optional(),
|
||||
notes: text(2000),
|
||||
});
|
||||
|
||||
/** A blank field is no value, not an empty string. */
|
||||
const clean = (v: string | null | undefined) => (v === undefined || v === null || v.trim() === "" ? null : v.trim());
|
||||
|
||||
function values(d: z.infer<typeof assetSchema>) {
|
||||
return {
|
||||
name: d.name,
|
||||
kind: d.kind,
|
||||
manufacturer: clean(d.manufacturer),
|
||||
model: clean(d.model),
|
||||
serial: clean(d.serial),
|
||||
purchaseDate: clean(d.purchaseDate),
|
||||
purchasePrice: d.purchasePrice ?? null,
|
||||
warrantyUntil: clean(d.warrantyUntil),
|
||||
location: clean(d.location),
|
||||
rackUnit: clean(d.rackUnit),
|
||||
powerWatts: d.powerWatts ?? null,
|
||||
serverId: d.serverId ?? null,
|
||||
notes: clean(d.notes),
|
||||
};
|
||||
}
|
||||
|
||||
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
|
||||
|
||||
// Everything signed-in people may see: the hardware, and the price of power the running cost is worked out with.
|
||||
inventoryRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const [rows, serverRows, settings] = await Promise.all([db.select().from(assets).orderBy(assets.name), db.select({ id: servers.id, name: servers.name }).from(servers), getSettings()]);
|
||||
const serverName = new Map(serverRows.map((s) => [s.id, s.name]));
|
||||
res.json({
|
||||
assets: rows.map((a) => ({ ...a, server: a.serverId !== null && serverName.has(a.serverId) ? { id: a.serverId, name: serverName.get(a.serverId)! } : null })),
|
||||
config: settings.inventory,
|
||||
servers: serverRows.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
});
|
||||
}));
|
||||
|
||||
const configSchema = z.object({
|
||||
currency: z.string().trim().max(8),
|
||||
pricePerKwh: z.number().min(0).max(1000).nullable(),
|
||||
});
|
||||
|
||||
// The price of power, for the running cost. An administrator's to set.
|
||||
inventoryRouter.put("/config", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = configSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "A price per kWh (or none) and a short currency name.", details: parsed.error.flatten() });
|
||||
const before = (await getSettings()).inventory;
|
||||
const updated = await updateSettings({ inventory: parsed.data });
|
||||
await recordAudit({ actor: req.currentUser!, category: "inventory", action: "update_config", targetType: "settings", detail: { from: before, to: parsed.data } });
|
||||
res.json({ config: updated.inventory });
|
||||
}));
|
||||
|
||||
inventoryRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const parsed = assetSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give it a name and a kind; dates look like 2026-10-17.", details: parsed.error.flatten() });
|
||||
const v = values(parsed.data);
|
||||
if (v.serverId !== null && (await db.select({ id: servers.id }).from(servers).where(eq(servers.id, v.serverId))).length === 0) {
|
||||
return res.status(400).json({ error: "unknown_server", message: "That server doesn't exist." });
|
||||
}
|
||||
const now = new Date().toISOString();
|
||||
const [row] = await db.insert(assets).values({ ...v, createdAt: now, updatedAt: now }).returning();
|
||||
await recordAudit({ actor: req.currentUser!, category: "inventory", action: "create", targetType: "asset", targetId: row.id, detail: { name: row.name, kind: row.kind } });
|
||||
res.status(201).json({ asset: row });
|
||||
}));
|
||||
|
||||
inventoryRouter.put("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = idOf(req.params.id);
|
||||
const parsed = assetSchema.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(assets).where(eq(assets.id, id)).limit(1);
|
||||
if (!before) return res.status(404).json({ error: "not_found" });
|
||||
const v = values(parsed.data);
|
||||
if (v.serverId !== null && (await db.select({ id: servers.id }).from(servers).where(eq(servers.id, v.serverId))).length === 0) {
|
||||
return res.status(400).json({ error: "unknown_server", message: "That server doesn't exist." });
|
||||
}
|
||||
const [row] = await db.update(assets).set({ ...v, updatedAt: new Date().toISOString() }).where(eq(assets.id, id)).returning();
|
||||
await recordAudit({ actor: req.currentUser!, category: "inventory", action: "update", targetType: "asset", targetId: id, detail: { name: row.name } });
|
||||
res.json({ asset: row });
|
||||
}));
|
||||
|
||||
inventoryRouter.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(assets).where(eq(assets.id, id)).limit(1);
|
||||
if (!before) return res.status(404).json({ error: "not_found" });
|
||||
await db.delete(assets).where(eq(assets.id, id));
|
||||
await recordAudit({ actor: req.currentUser!, category: "inventory", action: "delete", targetType: "asset", targetId: id, detail: { name: before.name } });
|
||||
res.status(204).end();
|
||||
}));
|
||||
@@ -0,0 +1,63 @@
|
||||
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 { 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;
|
||||
|
||||
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();
|
||||
}));
|
||||
@@ -0,0 +1,98 @@
|
||||
import { Router } from "express";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { dnsProviders, integrations, maintenanceTargetTypes, 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", "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] = 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),
|
||||
]);
|
||||
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)),
|
||||
};
|
||||
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();
|
||||
}));
|
||||
@@ -102,6 +102,16 @@ const updateSchema = z.object({
|
||||
.object({ enabled: z.boolean(), start: z.string().regex(/^\d{2}:\d{2}$/), end: z.string().regex(/^\d{2}:\d{2}$/) })
|
||||
.partial()
|
||||
.optional(),
|
||||
signIn: z
|
||||
.object({
|
||||
roleFromGroups: z.boolean(),
|
||||
groupsClaim: z.string().regex(/^[A-Za-z0-9_:.\-/]{1,60}$/, "Use the claim's name, like groups"),
|
||||
adminGroups: z.array(z.string().trim().min(1).max(100)).max(20),
|
||||
operatorGroups: z.array(z.string().trim().min(1).max(100)).max(20),
|
||||
otherwise: z.enum(["viewer", "keep"]),
|
||||
})
|
||||
.partial()
|
||||
.optional(),
|
||||
digest: z
|
||||
.object({ enabled: z.boolean(), day: z.number().int().min(0).max(6), time: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/) })
|
||||
.partial()
|
||||
|
||||
@@ -6,14 +6,32 @@ import { users, userRoles } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
import { getSettings } from "../services/settingsStore.js";
|
||||
import { roleFromGroups } from "../auth/groups.js";
|
||||
|
||||
export const usersRouter = Router();
|
||||
|
||||
usersRouter.use(requireAuth, requireRole("admin"));
|
||||
|
||||
/** What is stored for a person's groups, as a list. Anything that isn't one is none rather than an error. */
|
||||
export function parseGroups(stored: string | null): string[] | null {
|
||||
if (!stored) return null;
|
||||
try {
|
||||
const v = JSON.parse(stored);
|
||||
return Array.isArray(v) ? v.filter((g): g is string => typeof g === "string") : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
usersRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const rows = await db.select().from(users).orderBy(users.createdAt);
|
||||
res.json({ users: rows });
|
||||
const { signIn } = await getSettings();
|
||||
res.json({
|
||||
users: rows.map((u) => ({ id: u.id, oidcSub: u.oidcSub, email: u.email, name: u.name, role: u.role, createdAt: u.createdAt, lastLoginAt: u.lastLoginAt, groups: parseGroups(u.groups) })),
|
||||
// When roles follow groups, a role set by hand would be undone at the next sign-in, so the page says so instead of offering it.
|
||||
rolesFollowGroups: signIn.roleFromGroups,
|
||||
});
|
||||
}));
|
||||
|
||||
const updateRoleSchema = z.object({
|
||||
@@ -21,6 +39,10 @@ const updateRoleSchema = z.object({
|
||||
});
|
||||
|
||||
usersRouter.patch("/:id/role", asyncHandler(async (req, res) => {
|
||||
const { signIn } = await getSettings();
|
||||
if (signIn.roleFromGroups) {
|
||||
return res.status(409).json({ error: "managed_by_groups", message: "Roles are set from sign-in groups (Settings → Sign-in), so a role set here would be undone at the next sign-in. Change the person's group in the identity provider, or switch the group rules off." });
|
||||
}
|
||||
const id = Number(req.params.id);
|
||||
const parsed = updateRoleSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
@@ -60,3 +82,26 @@ usersRouter.patch("/:id/role", asyncHandler(async (req, res) => {
|
||||
|
||||
res.json({ user: updated });
|
||||
}));
|
||||
|
||||
const previewSchema = z.object({
|
||||
groupsClaim: z.string().optional(),
|
||||
adminGroups: z.array(z.string().trim().min(1).max(100)).max(20).default([]),
|
||||
operatorGroups: z.array(z.string().trim().min(1).max(100)).max(20).default([]),
|
||||
otherwise: z.enum(["viewer", "keep"]).default("viewer"),
|
||||
});
|
||||
|
||||
// What each person would be, if these group rules were switched on now and they signed in again with the groups they had last time.
|
||||
// Nothing is saved or changed: it is for checking the names before relying on them.
|
||||
usersRouter.post("/preview-group-roles", asyncHandler(async (req, res) => {
|
||||
const parsed = previewSchema.safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
||||
const rows = await db.select().from(users).orderBy(users.name);
|
||||
const rules = { roleFromGroups: true, groupsClaim: parsed.data.groupsClaim ?? "groups", adminGroups: parsed.data.adminGroups, operatorGroups: parsed.data.operatorGroups, otherwise: parsed.data.otherwise };
|
||||
const people = rows.map((u) => {
|
||||
const groups = parseGroups(u.groups);
|
||||
return { id: u.id, name: u.name ?? u.email ?? u.oidcSub, role: u.role, groups, wouldBe: groups === null ? null : roleFromGroups(rules, groups, u.role) };
|
||||
});
|
||||
// Said plainly, because it is the one way to lock yourself out: nobody left with admin.
|
||||
const adminsAfter = people.filter((p) => (p.wouldBe ?? p.role) === "admin").length;
|
||||
res.json({ people, adminsAfter });
|
||||
}));
|
||||
Reference in new issue
Block a user