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); }));