/** * How long a server has been up, as its agent says it: taken from a report (and dropped if it makes no sense), kept when an older agent * reports without it, given back on the server's page, and not claimed on the strip once the server has stopped reporting. * * Run with: npm test --workspace server */ import { test, describe, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AddressInfo } from "node:net"; import type { Server } from "node:http"; const dir = mkdtempSync(join(tmpdir(), "hm-uptime-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users, servers } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { serversRouter } = await import("../src/routes/servers.js"); const { agentReportRouter } = await import("../src/routes/agentReport.js"); const { hashToken } = await import("../src/services/tokens.js"); const { parseAgentVersion, latestAgentVersions, AGENT_DIR } = await import("../src/services/agentVersions.js"); const { serverStrip } = await import("../../web/src/utils/serverStrip.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); describe("a report's uptime", () => { let app: Server; let base = ""; let id = 0; before(async () => { await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "viewer" }); id = (await db.insert(servers).values({ name: "web-1", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id; const a = express(); a.use("/api/agent/report", agentReportRouter); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: "tester" } }; next(); }); a.use("/api/servers", serversRouter); app = await new Promise((resolve) => { const x = a.listen(0, "127.0.0.1", () => resolve(x)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); const system = (extra: Record) => ({ cpu: { model: "x", cores: 4, load_percent: 5 }, memory: { total_bytes: 1000, used_bytes: 100 }, disks: [], ...extra }); const report = (sys: unknown) => fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ os_type: "linux", system: sys, tasks: [] }) }); const stored = async () => (await db.select().from(servers).where(eq(servers.id, id)))[0].uptimeSeconds; const detail = async () => (await (await fetch(`${base}/servers/${id}/detail`)).json()) as { hardware: { uptime?: number | null }; server: Record }; test("a report with uptime stores it, whole seconds, and the server's page gives it back", async () => { assert.equal((await report(system({ uptime_seconds: 1_234_567.8 }))).status, 202); assert.equal(await stored(), 1_234_567); const d = await detail(); assert.equal(d.hardware.uptime, 1_234_567); assert.ok(!("uptimeSeconds" in d.server), "it is not handed out twice"); }); test("a newer report replaces it, and an older agent's report (with none) leaves it as it was", async () => { await report(system({ uptime_seconds: 2_000_000 })); assert.equal(await stored(), 2_000_000); assert.equal((await report(system({}))).status, 202); assert.equal(await stored(), 2_000_000); }); test("a figure that makes no sense is dropped, never costing the report", async () => { for (const bad of [-5, 0, "12", null, Number.MAX_SAFE_INTEGER, { a: 1 }]) { assert.equal((await report(system({ uptime_seconds: bad }))).status, 202, JSON.stringify(bad)); assert.equal(await stored(), 2_000_000, `kept after ${JSON.stringify(bad)}`); } }); }); describe("the strip", () => { const NOW = Date.parse("2026-06-10T12:00:00Z"); const base = { defaults: { serverOfflineMinutes: 15, diskUsagePercent: 90 }, alerts: [], windows: [], now: NOW } as never; const make = (lastSeenAt: string) => serverStrip({ ...(base as object), server: { id: 1, name: "web-1", lastSeenAt, pendingUpdates: null, thresholds: null }, hardware: { source: "agent", uptime: 90_000 } } as never); test("shows how long it has been up while it reports", () => { const t = make(new Date(NOW - 60_000).toISOString()).find((x) => x.id === "uptime"); assert.equal(t?.value, "1d 1h"); }); test("says nothing of it once the server has stopped reporting — that is no longer how long it has been up", () => { const tiles = make(new Date(NOW - 3 * 3600_000).toISOString()); assert.equal(tiles[0].value, "Offline"); assert.equal(tiles.find((x) => x.id === "uptime"), undefined); }); }); describe("the agents", () => { test("both say the new version, and the Linux one reads /proc/uptime and sends it as uptime_seconds", () => { const latest = latestAgentVersions(); assert.equal(latest.linux, 8); assert.equal(latest.windows, 7); const sh = readFileSync(join(AGENT_DIR, "linux", "report-tasks.sh"), "utf8"); assert.equal(parseAgentVersion(sh, "linux"), 8); assert.match(sh, /\/proc\/uptime/); assert.match(sh, /uptime_seconds: \$uptime_seconds/); }); test("the Windows one works it out from when Windows started, and the file stays plain ASCII", () => { const ps = readFileSync(join(AGENT_DIR, "windows", "report-tasks.ps1"), "utf8"); assert.match(ps, /LastBootUpTime/); assert.match(ps, /uptime_seconds\s*=\s*\$uptime/); assert.ok(!/[^\x00-\x7f]/.test(ps), "downloaded as text, so no characters beyond ASCII"); }); });