import express, { Router, type NextFunction, type Request, type Response } from "express"; import { z } from "zod"; import { db } from "../db/client.js"; import { hashToken } from "../services/tokens.js"; import { syncServerTasks } from "../services/taskSync.js"; import { asyncHandler } from "../utils/asyncHandler.js"; import { getSettings } from "../services/settingsStore.js"; import { latestAgentSha256, latestAgentVersions } from "../services/agentVersions.js"; export const agentReportRouter = Router(); // A host with a lot of listening sockets and cron entries sends a big report, so this endpoint takes far more than the // 100 KB the rest of the API does. It's only safe to read that much from someone who has proved they're an agent, so the // token is checked before the body is — and this route is mounted ahead of the app-wide JSON parser (see index.ts). const AGENT_BODY_LIMIT = "4mb"; /** Text from an agent is trimmed to a sane length rather than rejected: a report that's refused over one long line costs the host its whole report. */ const text = (max: number) => z.string().transform((s) => (s.length > max ? s.slice(0, max) : s)); const cap = (max: number) => (items: T[]) => (items.length > max ? items.slice(0, max) : items); const listeningPortSchema = z.object({ protocol: z.enum(["tcp", "udp"]), port: z.number().int().min(1).max(65535), address: text(100), process: text(100).optional(), }); // What is waiting to be installed. As lenient as the ports: a malformed answer is dropped, never allowed to cost the agent its report. const updatesSchema = z.object({ manager: text(30).optional(), count: z.number().int().min(0).max(100_000), security: z.number().int().min(0).max(100_000).nullable().optional(), reboot_required: z.boolean().optional(), }); // Failed services, disk health, ZFS pools. Each part is checked on its own and a bad one dropped, like the rest: it must never cost the report. const healthSchema = z.object({ failed_units: z .array(z.object({ unit: text(200), description: text(300).optional() })) .transform(cap(100)) .optional() .catch(undefined), smart: z .array(z.object({ device: text(100), model: text(200).optional(), healthy: z.boolean().nullable().optional(), temperature_c: z.number().nullable().optional(), wear_percent: z.number().nullable().optional() })) .transform(cap(100)) .optional() .catch(undefined), zfs: z .array(z.object({ name: text(200), health: text(40), capacity_percent: z.number().nullable().optional() })) .transform(cap(100)) .optional() .catch(undefined), }); // What the machine is. Each part is optional and a malformed one is dropped, like the rest. const hardwareSchema = z.object({ manufacturer: text(100).optional().catch(undefined), model: text(150).optional().catch(undefined), serial: text(100).optional().catch(undefined), }); const systemSchema = z.object({ hardware: z .unknown() .optional() .transform((h) => { const parsed = hardwareSchema.safeParse(h); return parsed.success && Object.values(parsed.data).some((v) => typeof v === "string" && v.trim()) ? parsed.data : undefined; }), health: z .unknown() .optional() .transform((h) => { const parsed = healthSchema.safeParse(h); return parsed.success && Object.values(parsed.data).some((v) => v !== undefined) ? parsed.data : undefined; }), updates: z .unknown() .optional() .transform((u) => { const parsed = updatesSchema.safeParse(u); return parsed.success ? parsed.data : undefined; }), ip_addresses: z.array(text(100)).transform(cap(200)).optional(), cpu: z.object({ model: text(200).optional(), cores: z.number().optional(), load_percent: z.number().nullable().optional() }).optional(), memory: z.object({ total_bytes: z.number().optional(), used_bytes: z.number().optional() }).optional(), disks: z .array(z.object({ mount: text(500), size_bytes: z.number(), used_bytes: z.number() })) .transform(cap(500)) .optional(), // Deliberately lenient: one odd line from `ss` must never cost the agent its whole report (tasks included), // so entries are validated one by one and bad ones dropped rather than failing the request. listening_ports: z .array(z.unknown()) .max(5000) .optional() .transform((entries) => entries?.flatMap((e) => { const parsed = listeningPortSchema.safeParse(e); return parsed.success ? [parsed.data] : []; })), }); // What a task's free-form metadata may weigh once written out; more than this is dropped, the task itself kept. const MAX_METADATA_JSON = 50_000; const reportSchema = z.object({ hostname: text(255).optional(), os_type: text(50).optional(), reported_at: text(50).optional(), // Lenient like the rest: a number that makes no sense is dropped, never allowed to cost the agent its report. agent_version: z .unknown() .optional() .transform((v) => (typeof v === "number" && Number.isInteger(v) && v >= 1 && v <= 100_000 ? v : undefined)), system: systemSchema.nullable().optional(), tasks: z .array( z.object({ schedule_type: z.enum(["cron", "systemd_timer", "windows_task"]), name: z.string().min(1).transform((s) => (s.length > 500 ? s.slice(0, 500) : s)), command: text(8000).optional(), schedule_expression: text(500).optional(), source: text(500).optional(), enabled: z.boolean().optional(), next_run_at: text(100).optional(), metadata: z .unknown() .optional() .transform((m) => (m !== undefined && (JSON.stringify(m) ?? "").length > MAX_METADATA_JSON ? undefined : m)), }), ) .transform(cap(5000)), }); /** Who's calling: the server a bearer token belongs to. Runs before the body is read. */ async function authenticateAgent(req: Request, res: Response, next: NextFunction) { const match = (req.header("authorization") ?? "").match(/^Bearer\s+(.+)$/i); if (!match) return res.status(401).json({ error: "missing_token" }); const tokenHash = hashToken(match[1]); const server = await db.query.servers.findFirst({ where: (s, { eq }) => eq(s.apiTokenHash, tokenHash), }); if (!server) return res.status(401).json({ error: "invalid_token" }); res.locals.agentServer = server; next(); } /** * "Should I replace myself?" — asked by an agent that has been told to keep itself up to date, before it reports. Says yes only when an * administrator has switched automatic updates on and this agent is behind the script this app serves, and gives the script's SHA-256 so * the agent can check what it downloads. The agent says which version it is; failing that, the last one it reported counts. */ agentReportRouter.get("/update", asyncHandler(authenticateAgent), asyncHandler(async (req, res) => { const server = res.locals.agentServer as { osType: string; agentVersion: number | null }; const os = server.osType === "windows" ? "windows" : "linux"; const claimed = Number(req.query.version); const running = Number.isInteger(claimed) && claimed >= 1 && claimed <= 100_000 ? claimed : (server.agentVersion ?? 1); const latest = latestAgentVersions()[os]; const sha256 = latestAgentSha256(os); const { agents } = await getSettings(); const update = agents.autoUpdate && latest !== null && sha256 !== null && running < latest; res.json({ update, version: update ? latest : null, sha256: update ? sha256 : null }); })); agentReportRouter.post("/", asyncHandler(authenticateAgent), express.json({ limit: AGENT_BODY_LIMIT }), asyncHandler(async (req, res) => { const server = res.locals.agentServer as { id: number }; const parsed = reportSchema.safeParse(req.body); if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); } await syncServerTasks(server.id, { hostname: parsed.data.hostname, osType: parsed.data.os_type, agentVersion: parsed.data.agent_version, system: parsed.data.system, tasks: parsed.data.tasks.map((t) => ({ scheduleType: t.schedule_type, name: t.name, command: t.command, scheduleExpression: t.schedule_expression, source: t.source, enabled: t.enabled, nextRunAt: t.next_run_at, metadata: t.metadata, })), }); res.status(202).json({ ok: true, taskCount: parsed.data.tasks.length }); }));