/** * Nginx Proxy Manager and Home Assistant: reading each (against pretend ones), what is kept, what makes an alert, and the suggestions NPM feeds. * * Run with: npm test --workspace server */ import { test, describe, before, after } from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import type { AddressInfo } from "node:net"; const dir = mkdtempSync(join(tmpdir(), "hm-npmha-")); process.env.DATABASE_PATH = join(dir, "test.sqlite"); process.env.SESSION_DIR = join(dir, "sessions"); process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); process.env.HEALTH_STARTUP_GRACE_MS = "0"; const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { users, servers, integrations, integrationCredentials, haEntities, haReadings, haWatched } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { encryptSecret } = await import("../src/crypto.js"); const { createNpmAdapter, isoOf, hostFrom } = await import("../src/integrations/npm/adapter.js"); const { createHomeAssistantAdapter, entityFrom } = await import("../src/integrations/homeassistant/adapter.js"); const { npmProblems, readNpm, clearNpmCacheForTests } = await import("../src/services/npmReader.js"); const { haProblems, trackUnavailable, syncHomeAssistant, removeHomeAssistantData, isHaFresh, haSyncStatuses } = await import("../src/services/homeAssistantSync.js"); const { suggestChecks, loadSuggestions } = await import("../src/services/endpointSuggestions.js"); const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); const { npmRouter } = await import("../src/routes/npm.js"); const { homeAssistantRouter } = await import("../src/routes/homeAssistant.js"); const { validateIntegrationConfig } = await import("../src/integrations/fieldSchemas.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); const DAY = 86_400_000; const inDays = (n: number) => new Date(Date.now() + n * DAY).toISOString(); const npmTime = (n: number) => inDays(n).replace("T", " ").slice(0, 19); // ─── A pretend Nginx Proxy Manager ────────────────────────────────────────── let npmPassword = "pw"; const npmCertificates = [ { id: 1, nice_name: "wiki.example.com", provider: "letsencrypt", domain_names: ["wiki.example.com"], expires_on: npmTime(40) }, { id: 2, nice_name: "git.example.com", provider: "letsencrypt", domain_names: ["git.example.com"], expires_on: npmTime(2) }, { id: 3, nice_name: "old.example.com", provider: "letsencrypt", domain_names: ["old.example.com"], expires_on: npmTime(-5) }, ]; const npmHosts = [ { id: 10, domain_names: ["wiki.example.com"], forward_scheme: "http", forward_host: "10.0.0.5", forward_port: 8080, enabled: 1, ssl_forced: 1, certificate: npmCertificates[0], meta: { nginx_online: true } }, { id: 11, domain_names: ["git.example.com"], forward_scheme: "http", forward_host: "10.0.0.6", forward_port: 3000, enabled: 1, ssl_forced: 1, certificate: npmCertificates[1], meta: { nginx_online: true } }, // A certificate that ran out, but on a host that is switched off: nobody is served it, so it is not a problem. { id: 12, domain_names: ["old.example.com"], forward_scheme: "http", forward_host: "10.0.0.7", forward_port: 80, enabled: 0, ssl_forced: 0, certificate: npmCertificates[2], meta: {} }, { id: 13, domain_names: ["broken.example.com"], forward_scheme: "http", forward_host: "10.0.0.8", forward_port: 80, enabled: 1, ssl_forced: 0, certificate: null, meta: { nginx_online: false, nginx_err: "host not found in upstream" } }, ]; let npmRequests: string[] = []; function reply(res: ServerResponse, status: number, body: unknown) { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); } function npmRoute(req: IncomingMessage, res: ServerResponse) { const url = req.url ?? ""; npmRequests.push(`${req.method} ${url.split("?")[0]}`); if (url === "/api/tokens" && req.method === "POST") { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", () => { const b = JSON.parse(raw || "{}"); if (b.identity === "viewer@example.com" && b.secret === npmPassword) return reply(res, 200, { token: "npm-token", expires: inDays(1) }); return reply(res, 400, { error: { message: "Invalid email or password" } }); }); return; } if (req.headers.authorization !== "Bearer npm-token") return reply(res, 401, {}); if (url.startsWith("/api/nginx/proxy-hosts")) return reply(res, 200, npmHosts); if (url.startsWith("/api/nginx/certificates")) return reply(res, 200, npmCertificates); if (url === "/api/") return reply(res, 200, { status: "OK", version: { major: 2, minor: 11, revision: 3 } }); return reply(res, 404, {}); } // ─── A pretend Home Assistant ─────────────────────────────────────────────── let haToken = "good-token"; let haStates: Record[] = []; const state = (entity_id: string, s: string, attributes: Record = {}) => ({ entity_id, state: s, attributes, last_changed: "2026-10-20T08:00:00+00:00" }); function haRoute(req: IncomingMessage, res: ServerResponse) { if (req.headers.authorization !== `Bearer ${haToken}`) return reply(res, 401, { message: "401: Unauthorized" }); if (req.url === "/api/") return reply(res, 200, { message: "API running." }); if (req.url === "/api/states") return reply(res, 200, haStates); return reply(res, 404, {}); } let npmServer: Server; let haServer: Server; let npmUrl = ""; let haUrl = ""; let npmId = 0; let haId = 0; before(async () => { npmServer = await new Promise((resolve) => { const s = createServer(npmRoute).listen(0, "127.0.0.1", () => resolve(s)); }); haServer = await new Promise((resolve) => { const s = createServer(haRoute).listen(0, "127.0.0.1", () => resolve(s)); }); npmUrl = `http://127.0.0.1:${(npmServer.address() as AddressInfo).port}`; haUrl = `http://127.0.0.1:${(haServer.address() as AddressInfo).port}`; }); after(() => { npmServer.close(); haServer.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows may still hold the database file } }); describe("normalising what they say", () => { test("NPM writes its times without a zone, and they are UTC", () => { assert.equal(isoOf("2026-12-31 23:59:59"), "2026-12-31T23:59:59.000Z"); assert.equal(isoOf("2026-12-31T23:59:59+01:00"), "2026-12-31T22:59:59.000Z"); assert.equal(isoOf("nonsense"), null); assert.equal(isoOf(null), null); }); test("a proxy host: where it goes, whether it is on, and that NPM's own error makes it not working; a host with no id is nothing", () => { const h = hostFrom(npmHosts[3])!; assert.deepEqual([h.domains, h.forwardHost, h.forwardPort, h.enabled, h.online, h.error], [["broken.example.com"], "10.0.0.8", 80, true, false, "host not found in upstream"]); const ok = hostFrom(npmHosts[0])!; assert.deepEqual([ok.sslForced, ok.online, ok.certificate?.id], [true, true, 1]); assert.equal(hostFrom({ domain_names: ["x"] }), null); assert.equal(hostFrom(npmHosts[2])!.enabled, false); }); test("a Home Assistant entity: a number when its state is one, unavailable when it says nothing, its friendly name or else its id", () => { const e = entityFrom(state("sensor.ups_battery", "87.5", { friendly_name: "UPS battery", unit_of_measurement: "%", device_class: "battery" }))!; assert.deepEqual([e.name, e.value, e.unit, e.deviceClass, e.unavailable], ["UPS battery", 87.5, "%", "battery", false]); const off = entityFrom(state("switch.pump", "unavailable"))!; assert.deepEqual([off.name, off.value, off.unavailable], ["switch.pump", null, true]); assert.equal(entityFrom(state("light.x", "on"))!.value, null, "on/off is not a number"); assert.equal(entityFrom(state("sensor.blank", ""))!.value, null); assert.equal(entityFrom({ state: "1" }), null); }); }); describe("Nginx Proxy Manager", () => { const cfg = (extra: Record = {}) => ({ url: npmUrl, email: "viewer@example.com", password: npmPassword, ...extra }) as never; test("signs in, then only reads: hosts with their certificate, the certificates, the version", async () => { npmRequests = []; const snap = await createNpmAdapter(cfg()).fetchSnapshot(); assert.equal(snap.version, "2.11.3"); assert.equal(snap.hosts.length, 4); assert.equal(snap.certificates.length, 3); assert.ok(npmRequests.every((r) => r.startsWith("GET") || r === "POST /api/tokens"), "nothing but the sign-in and reads"); }); test("a wrong password is said plainly, and the login check works as a ping", async () => { await assert.rejects(createNpmAdapter(cfg({ password: "wrong" })).fetchSnapshot(), /did not accept the email and password/); assert.equal((await createNpmAdapter(cfg()).ping()).ok, true); assert.equal((await createNpmAdapter(cfg({ password: "wrong" })).ping()).ok, false); }); test("certificates in use that run out soon are a problem — critical in the last days, and an expired one too — but not on a host that is off", async () => { const snap = await createNpmAdapter(cfg()).fetchSnapshot(); const problems = npmProblems(1, "Edge NPM", snap, new Date()); const by = Object.fromEntries(problems.map((p) => [p.key, p])); assert.deepEqual(Object.keys(by).sort(), ["npm-cert:1:2", "npm-host:1:13"], "wiki is fine (40 days), old is on a host that is off"); assert.equal(by["npm-cert:1:2"].severity, "critical"); assert.match(by["npm-cert:1:2"].message, /git\.example\.com.*expires in [12] days?/); assert.match(by["npm-host:1:13"].message, /broken\.example\.com is not working.*host not found in upstream/); const later = npmProblems(1, "Edge NPM", snap, new Date(Date.now() + 30 * DAY)); assert.ok(later.some((p) => p.key === "npm-cert:1:1"), "and the wiki one in time"); assert.match(later.find((p) => p.key === "npm-cert:1:2")!.message, /expired 2[89] days ago/); }); }); describe("Home Assistant", () => { const cfg = (extra: Record = {}) => ({ url: haUrl, token: haToken, ...extra }) as never; test("lists every entity with the token; a refused token and a wrong address are said plainly", async () => { haStates = [state("sensor.ups_battery", "87", { friendly_name: "UPS battery", unit_of_measurement: "%" }), state("light.hall", "on")]; assert.equal((await createHomeAssistantAdapter(cfg()).listEntities()).length, 2); await assert.rejects(createHomeAssistantAdapter(cfg({ token: "nope" })).listEntities(), /did not accept the token/); const ping = await createHomeAssistantAdapter(cfg()).ping(); assert.equal(ping.ok, true); }); test("an entity that says nothing is only a problem after a while, and a number only past a limit that was set", () => { const now = new Date("2026-10-20T12:00:00Z"); const watched = [ { entityId: "sensor.ups", name: "UPS", above: null, below: 30 }, { entityId: "sensor.freezer", name: null, above: -10, below: null }, { entityId: "switch.pump", name: "Pump", above: null, below: null }, { entityId: "sensor.fine", name: null, above: 50, below: 10 }, ]; const rows = new Map([ ["sensor.ups", { friendlyName: "UPS battery", state: "22", value: 22, unit: "%", unavailableSince: null }], ["sensor.freezer", { friendlyName: "Freezer", state: "-18", value: -18, unit: "°C", unavailableSince: null }], ["switch.pump", { friendlyName: null, state: "unavailable", value: null, unit: null, unavailableSince: "2026-10-20T11:30:00Z" }], ["sensor.fine", { friendlyName: null, state: "20", value: 20, unit: null, unavailableSince: null }], ]); const problems = haProblems(3, "Home", watched, rows, now); assert.deepEqual(problems.map((p) => p.key), ["ha-limit:3:sensor.ups", "ha-unavailable:3:switch.pump"]); assert.match(problems[0].message, /UPS is 22 %, below its limit of 30 %/); assert.match(problems[1].message, /Pump has been unavailable in Home Assistant for 30 min/); rows.get("switch.pump")!.unavailableSince = "2026-10-20T11:55:00Z"; assert.equal(haProblems(3, "Home", watched, rows, now).length, 1, "five minutes of silence is nothing"); }); test("when an entity first went quiet is kept until it speaks again", () => { assert.equal(trackUnavailable(null, true, "T1"), "T1"); assert.equal(trackUnavailable("T0", true, "T1"), "T0"); assert.equal(trackUnavailable("T0", false, "T1"), null); }); }); describe("kept in the app", () => { before(async () => { await db.insert(users).values([ { oidcSub: "viewer", name: "Vic", role: "viewer" }, { oidcSub: "operator", name: "Olga", role: "operator" }, ]); const [npmCred] = await db.insert(integrationCredentials).values({ name: "npm:Edge", encryptedSecret: encryptSecret(JSON.stringify({ password: "pw" })) }).returning(); const [npmRow] = await db.insert(integrations).values({ type: "npm", name: "Edge NPM", baseUrl: npmUrl, credentialId: npmCred.id, config: JSON.stringify({ url: npmUrl, email: "viewer@example.com" }) }).returning(); npmId = npmRow.id; const [haCred] = await db.insert(integrationCredentials).values({ name: "ha:Home", encryptedSecret: encryptSecret(JSON.stringify({ token: "good-token" })) }).returning(); const [haRow] = await db.insert(integrations).values({ type: "homeassistant", name: "Home", baseUrl: haUrl, credentialId: haCred.id, config: JSON.stringify({ url: haUrl }) }).returning(); haId = haRow.id; await db.insert(servers).values({ name: "wiki-host", hostname: "wiki-host.example.lan", ipAddresses: JSON.stringify(["10.0.0.5"]), osType: "linux", apiTokenHash: "x", apiTokenPrefix: "x" } as never); }); test("the field forms need what each one needs", () => { assert.deepEqual(validateIntegrationConfig("npm", { url: "https://npm", email: "a@b" }), ["password"]); assert.deepEqual(validateIntegrationConfig("homeassistant", { url: "https://ha" }), ["token"]); assert.deepEqual(validateIntegrationConfig("homeassistant", { url: "https://ha", token: "t" }), []); }); test("NPM is read once a minute at most, and a failed read is kept just as briefly", async () => { clearNpmCacheForTests(); npmRequests = []; const a = await readNpm(npmId); const b = await readNpm(npmId); assert.ok(a.snapshot && b.snapshot); assert.equal(npmRequests.filter((r) => r === "POST /api/tokens").length, 1); await readNpm(npmId, true); assert.equal(npmRequests.filter((r) => r === "POST /api/tokens").length, 2, "asking again is possible"); }); test("on the Alerts page: the certificate in its last days and the host NPM can't set up, from the right place", async () => { clearNpmCacheForTests(); invalidateAlertsCache(); const report = await getAlerts(true); const cert = report.alerts.find((a) => a.id === `expiry:npm-cert:${npmId}:2`)!; assert.ok(cert, "the certificate that runs out"); assert.deepEqual([cert.severity, cert.source, cert.link, cert.target?.type], ["critical", "Nginx Proxy Manager", "/proxy-hosts", "integration"]); const host = report.alerts.find((a) => a.id === `monitoring:npm-host:${npmId}:13`)!; assert.ok(host); assert.equal(report.alerts.some((a) => a.id === `expiry:npm-cert:${npmId}:3`), false, "the one on the host that is off is left alone"); }); test("an NPM that can't be read says so rather than being quiet", async () => { npmPassword = "changed"; clearNpmCacheForTests(); invalidateAlertsCache(); const report = await getAlerts(true); assert.ok(report.couldntCheck.some((c) => /Nginx Proxy Manager/.test(c.name))); assert.equal(report.alerts.some((a) => a.id.startsWith("expiry:npm-cert")), false, "and raises nothing from what it could not read"); npmPassword = "pw"; clearNpmCacheForTests(); }); test("hosts NPM serves are offered as checks on the name people use, linked to the server it forwards to — and not when a check already covers it", async () => { invalidateAlertsCache(); const { suggestions } = await loadSuggestions(); const wiki = suggestions.find((s) => s.target === "https://wiki.example.com/")!; assert.ok(wiki); assert.deepEqual([wiki.kind, wiki.serverName], ["http", "wiki-host"]); assert.match(wiki.reason, /Edge NPM serves wiki\.example\.com, forwarding to wiki-host/); assert.ok(suggestions.some((s) => s.target === "http://broken.example.com/"), "a host with no certificate is a plain web check"); assert.ok(!suggestions.some((s) => /old\.example\.com/.test(s.target)), "a host that is off is not offered"); const none = suggestChecks({ servers: [], dns: [], secrets: [], dismissed: new Set(), existing: [{ kind: "http", target: "https://wiki.example.com/", port: null }], proxied: [{ domain: "wiki.example.com", secure: true, serverId: null, serverName: null, integrationName: "x" }, { domain: "*.example.com", secure: true, serverId: null, serverName: null, integrationName: "x" }, { domain: "10.0.0.1", secure: false, serverId: null, serverName: null, integrationName: "x" }] }); assert.deepEqual(none.suggestions, []); }); test("the NPM page: each host with the server it forwards to, its certificate, and the problems; anyone signed in may see it", async () => { const a = express(); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: "viewer" } }; next(); }); a.use("/api/npm", npmRouter); const s = await new Promise((resolve) => { const x = a.listen(0, "127.0.0.1", () => resolve(x)); }); const res = await fetch(`http://127.0.0.1:${(s.address() as AddressInfo).port}/api/npm?refresh=1`); assert.equal(res.status, 200); const body = (await res.json()) as any; const npm = body.integrations[0]; assert.equal(npm.version, "2.11.3"); const wiki = npm.hosts.find((h: any) => h.id === 10); assert.deepEqual([wiki.server?.name, wiki.certificate.name], ["wiki-host", "wiki.example.com"]); assert.equal(npm.hosts.find((h: any) => h.id === 11).server, null, "an address no server has is left unmatched"); assert.equal(npm.problems.length, 2); s.close(); }); describe("Home Assistant stored", () => { let app: Server; let base = ""; let who = "viewer"; before(async () => { const a = express(); a.use(express.json()); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: who } }; next(); }); a.use("/api/home-assistant", homeAssistantRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/home-assistant`; }); after(() => app.close()); const put = (body: unknown) => fetch(`${base}/${haId}/watched`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); test("choosing what to watch needs an operator; only entities that exist and sensible limits are accepted", async () => { haStates = [state("sensor.ups_battery", "87", { friendly_name: "UPS battery", unit_of_measurement: "%" }), state("switch.pump", "on", { friendly_name: "Pump" }), state("light.hall", "on")]; who = "viewer"; assert.equal((await put({ entityId: "sensor.ups_battery" })).status, 403); assert.equal((await fetch(`${base}/${haId}/entities`)).status, 403); who = "operator"; assert.equal((await put({ entityId: "not an entity" })).status, 400); assert.equal((await put({ entityId: "sensor.ups_battery", above: 10, below: 20 })).status, 400, "the lower limit has to be lower"); assert.equal((await fetch(`${base}/999/entities`)).status, 404); const list = (await (await fetch(`${base}/${haId}/entities?q=ups`)).json()) as any; assert.deepEqual(list.entities.map((e: any) => e.entityId), ["sensor.ups_battery"]); const ok = await put({ entityId: "sensor.ups_battery", name: "UPS", below: 30 }); assert.equal(ok.status, 200); assert.equal(((await ok.json()) as any).status.ok, true); assert.equal((await put({ entityId: "switch.pump" })).status, 200); const [row] = await db.select().from(haEntities).where(eq(haEntities.entityId, "sensor.ups_battery")); assert.deepEqual([row.state, row.value, row.unit], ["87", 87, "%"]); }); test("the page lists what is watched with its state; a number keeps a point of history, but two passes close together keep one", async () => { who = "viewer"; const body = (await (await fetch(base)).json()) as any; const ha = body.integrations[0]; assert.deepEqual(ha.watched.map((w) => [w.entityId, w.entity?.state]), [["switch.pump", "on"], ["sensor.ups_battery", "87"]], "by the name it is shown under: Pump, then UPS"); assert.equal(ha.fresh, true); await syncHomeAssistant(haId); const readings = await db.select().from(haReadings).where(eq(haReadings.entityId, "sensor.ups_battery")); assert.equal(readings.length, 1, "the pump is not a number, the second pass is too soon"); const hist = (await (await fetch(`${base}/${haId}/history?entity=sensor.ups_battery&days=7`)).json()) as any; assert.equal(hist.days, 7); assert.ok(hist.points.length >= 1); }); test("a number past its limit is an alert, an entity that goes quiet becomes one after a while, and a Home Assistant that is down holds them rather than clearing", async () => { haStates = [state("sensor.ups_battery", "22", { friendly_name: "UPS battery", unit_of_measurement: "%" }), state("switch.pump", "unavailable", { friendly_name: "Pump" })]; await syncHomeAssistant(haId, new Date()); invalidateAlertsCache(); let report = await getAlerts(true); const limit = report.alerts.find((a) => a.id === `monitoring:ha-limit:${haId}:sensor.ups_battery`)!; assert.ok(limit); assert.deepEqual([limit.source, limit.link], ["Home Assistant", "/home-assistant"]); assert.equal(report.alerts.some((a) => a.id.includes("ha-unavailable")), false, "the pump just went quiet"); await db.update(haEntities).set({ unavailableSince: new Date(Date.now() - 40 * 60_000).toISOString() }).where(eq(haEntities.entityId, "switch.pump")); invalidateAlertsCache(); report = await getAlerts(true); assert.ok(report.alerts.some((a) => a.id === `monitoring:ha-unavailable:${haId}:switch.pump`)); haToken = "revoked"; const down = await syncHomeAssistant(haId); assert.equal(down.ok, false); assert.match(down.error ?? "", /did not accept the token/); invalidateAlertsCache(); report = await getAlerts(true); assert.ok(report.couldntCheck.some((c) => /Home Assistant/.test(c.name))); assert.equal(report.alerts.some((a) => a.id.includes("ha-limit")), false, "neither raised nor cleared while it can't be read"); assert.equal(isHaFresh((await haSyncStatuses())[haId], Date.now()), false); haToken = "good-token"; assert.equal((await syncHomeAssistant(haId)).ok, true); }); test("an entity that disappears from Home Assistant counts as quiet; stopping watching forgets it and its history", async () => { haStates = [state("sensor.ups_battery", "50", { unit_of_measurement: "%" })]; await syncHomeAssistant(haId); const [pump] = await db.select().from(haEntities).where(eq(haEntities.entityId, "switch.pump")); assert.equal(pump.state, "missing"); who = "operator"; assert.equal((await fetch(`${base}/${haId}/watched/sensor.ups_battery`, { method: "DELETE" })).status, 204); assert.equal((await db.select().from(haReadings).where(eq(haReadings.entityId, "sensor.ups_battery"))).length, 0); assert.equal((await fetch(`${base}/${haId}/watched/sensor.ups_battery`, { method: "DELETE" })).status, 404); }); test("removing the integration removes everything read from it", async () => { await removeHomeAssistantData(haId); assert.equal((await db.select().from(haWatched)).length, 0); assert.equal((await db.select().from(haEntities)).length, 0); assert.equal((await haSyncStatuses())[haId], undefined); assert.equal((await db.select({ id: integrationCredentials.id }).from(integrationCredentials)).length >= 1, true); }); }); });