A UniFi controller (API key on Network 9+, or a read-only local login on any version) is read every five minutes. Its switches, access points and gateways are kept with state, IP, uptime, firmware and uplink; its networks and Wi-Fi names beside them (passphrases are never read). Nothing is written to the controller. Network > Network devices lists them. Devices are a new node type in the dependency map: uplinks become dependencies by themselves, others can be written by hand. A device offline past a limit is an offline alert, folds what depends on it, can be silenced with maintenance and have runbooks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
491 lines
30 KiB
TypeScript
491 lines
30 KiB
TypeScript
/**
|
|
* UniFi: reading a controller either way (API key, or a login), what is kept, when a device is called offline, and how network devices take part in the
|
|
* dependency map, the alerts and the pages that list them.
|
|
*
|
|
* 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-unifi-"));
|
|
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, networkDevices, networkSegments, dependencies, maintenanceWindows } = await import("../src/db/schema.js");
|
|
const { runMigrations } = await import("../src/db/migrate.js");
|
|
const { encryptSecret } = await import("../src/crypto.js");
|
|
const adapterModule = await import("../src/integrations/unifi/adapter.js");
|
|
const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy } = adapterModule;
|
|
const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses } = await import("../src/services/unifiSync.js");
|
|
const { evaluateHealth } = await import("../src/services/healthMonitor.js");
|
|
const { dependencyCover, uplinkEdges, loadGraph, alertIdOfNode } = await import("../src/services/dependencies.js");
|
|
const { subjectOfConditionKey, describeTarget } = await import("../src/services/maintenance.js");
|
|
const { networkRouter } = await import("../src/routes/network.js");
|
|
const { validateIntegrationConfig } = await import("../src/integrations/fieldSchemas.js");
|
|
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
|
|
const { setInternalFlag } = await import("../src/services/settingsStore.js");
|
|
const { eq } = await import("drizzle-orm");
|
|
|
|
await runMigrations();
|
|
|
|
// ─── A pretend controller ───────────────────────────────────────────────────
|
|
|
|
const MAC = { gw: "00:11:22:33:44:01", sw: "00:11:22:33:44:02", ap: "00:11:22:33:44:03" };
|
|
const SECRET_PASSPHRASE = "correct-horse-battery-staple";
|
|
|
|
const siteList = { offset: 0, limit: 200, count: 1, totalCount: 1, data: [{ id: "site-1", internalReference: "default", name: "Default" }] };
|
|
const deviceList = {
|
|
offset: 0,
|
|
limit: 200,
|
|
count: 3,
|
|
totalCount: 3,
|
|
data: [
|
|
{ id: "d-gw", macAddress: "00:11:22:33:44:01", ipAddress: "192.168.1.1", name: "Gateway", model: "UDM Pro", state: "ONLINE", firmwareVersion: "4.0.6", firmwareUpdatable: false, features: ["switching"] },
|
|
{ id: "d-sw", macAddress: "00:11:22:33:44:02", ipAddress: "192.168.1.2", name: "Rack switch", model: "USW-24-PoE", state: "ONLINE", firmwareVersion: "7.0.50", firmwareUpdatable: true, features: ["switching"] },
|
|
{ id: "d-ap", macAddress: "00:11:22:33:44:03", ipAddress: "192.168.1.3", name: "Hallway AP", model: "U6 Pro", state: "OFFLINE", firmwareVersion: "6.6.55", firmwareUpdatable: false, features: ["accessPoint"] },
|
|
],
|
|
};
|
|
const detail: Record<string, unknown> = { "d-sw": { uplink: { deviceId: "d-gw" } }, "d-ap": { uplink: { deviceId: "d-sw" } }, "d-gw": {} };
|
|
const stats: Record<string, unknown> = { "d-gw": { uptimeSec: 864000 }, "d-sw": { uptimeSec: 3600 }, "d-ap": {} };
|
|
const networkList = { offset: 0, limit: 200, count: 2, totalCount: 2, data: [{ id: "n-1", name: "Default", enabled: true, vlanId: 1, management: "GATEWAY" }, { id: "n-2", name: "IoT", enabled: true, vlanId: 20, management: "GATEWAY" }] };
|
|
const networkDetail: Record<string, unknown> = { "n-1": { ipv4Configuration: { hostIpAddress: "192.168.1.1", prefixLength: 24 } }, "n-2": { ipv4Configuration: { hostIpAddress: "192.168.20.1", prefixLength: 24 } } };
|
|
const wifiList = {
|
|
offset: 0,
|
|
limit: 200,
|
|
count: 2,
|
|
totalCount: 2,
|
|
data: [
|
|
{ id: "w-1", name: "Home", enabled: true, securityConfiguration: { type: "WPA2_PERSONAL" }, network: { type: "NATIVE" } },
|
|
{ id: "w-2", name: "IoT-net", enabled: true, securityConfiguration: { type: "WPA3_PERSONAL" }, network: { type: "SPECIFIC", networkId: "n-2" } },
|
|
],
|
|
};
|
|
|
|
const legacyDevices = [
|
|
{ _id: "x1", mac: "00:11:22:33:44:01", ip: "192.168.1.1", name: "Gateway", model: "UDMPRO", type: "udm", state: 1, uptime: 1000, version: "4.0.6", upgradable: false },
|
|
{ _id: "x2", mac: "00:11:22:33:44:02", ip: "192.168.1.2", name: "Rack switch", model: "US24PRO", type: "usw", state: 1, uptime: 500, version: "7.0.50", upgradable: true, uplink: { uplink_mac: "00:11:22:33:44:01", type: "wire" } },
|
|
{ _id: "x3", mac: "00:11:22:33:44:03", ip: "192.168.1.3", name: "Hallway AP", model: "U6PRO", type: "uap", state: 0, version: "6.6.55", uplink: { uplink_mac: "00:11:22:33:44:02", type: "wire" } },
|
|
];
|
|
const legacyNetworks = [{ _id: "ln-1", name: "Default", purpose: "corporate", vlan_enabled: false, ip_subnet: "192.168.1.1/24" }, { _id: "ln-2", name: "IoT", purpose: "corporate", vlan_enabled: true, vlan: "20", ip_subnet: "192.168.20.1/24" }];
|
|
const legacyWlans = [{ _id: "lw-1", name: "Home", enabled: true, security: "wpapsk", x_passphrase: SECRET_PASSPHRASE, networkconf_id: "ln-1" }, { _id: "lw-2", name: "Guests", enabled: false, security: "open", networkconf_id: "ln-2" }];
|
|
|
|
type Mode = "os-key" | "selfhosted-key" | "os-login" | "selfhosted-login";
|
|
let mode: Mode = "os-key";
|
|
let controller: Server;
|
|
let controllerUrl = "";
|
|
let loginsSeen = 0;
|
|
let logoutsSeen = 0;
|
|
|
|
function reply(res: ServerResponse, status: number, body?: unknown) {
|
|
res.writeHead(status, { "content-type": "application/json" });
|
|
res.end(body === undefined ? "" : JSON.stringify(body));
|
|
}
|
|
|
|
function handleApi(url: URL, res: ServerResponse, strip: string) {
|
|
const path = url.pathname.slice(strip.length);
|
|
const m = /^\/sites\/site-1\/(devices|networks|wifi\/broadcasts)(?:\/([^/]+?)(\/statistics\/latest)?)?$/.exec(path);
|
|
if (path === "/sites") return reply(res, 200, siteList);
|
|
if (!m) return reply(res, 404, { message: "no such endpoint" });
|
|
if (m[1] === "devices") return reply(res, 200, m[2] ? (m[3] ? (stats[m[2]] ?? {}) : (detail[m[2]] ?? {})) : deviceList);
|
|
if (m[1] === "networks") return reply(res, 200, m[2] ? (networkDetail[m[2]] ?? {}) : networkList);
|
|
return reply(res, 200, wifiList);
|
|
}
|
|
|
|
function handleLegacy(url: URL, res: ServerResponse, strip: string) {
|
|
const path = url.pathname.slice(strip.length);
|
|
if (path === "/api/self/sites") return reply(res, 200, { data: [{ name: "default", desc: "Default" }] });
|
|
if (path === "/api/s/default/stat/device") return reply(res, 200, { data: legacyDevices });
|
|
if (path === "/api/s/default/rest/networkconf") return reply(res, 200, { data: legacyNetworks });
|
|
if (path === "/api/s/default/rest/wlanconf") return reply(res, 200, { data: legacyWlans });
|
|
return reply(res, 404, {});
|
|
}
|
|
|
|
function route(req: IncomingMessage, res: ServerResponse) {
|
|
const url = new URL(req.url ?? "/", "http://x");
|
|
if (mode === "os-key" || mode === "selfhosted-key") {
|
|
if (req.headers["x-api-key"] !== "good-key") return reply(res, 401, { message: "bad key" });
|
|
const prefix = mode === "os-key" ? "/proxy/network/integration/v1" : "/integration/v1";
|
|
if (!url.pathname.startsWith(prefix)) return reply(res, 404, { message: "not here" });
|
|
return handleApi(url, res, prefix);
|
|
}
|
|
const os = mode === "os-login";
|
|
const loginPath = os ? "/api/auth/login" : "/api/login";
|
|
if (req.method === "POST" && url.pathname === loginPath) {
|
|
let body = "";
|
|
req.on("data", (c) => (body += c));
|
|
req.on("end", () => {
|
|
const { username, password } = JSON.parse(body || "{}");
|
|
if (username !== "reader" || password !== "pw") return reply(res, 401, { message: "nope" });
|
|
loginsSeen++;
|
|
res.setHeader("set-cookie", ["TOKEN=abc123; Path=/; HttpOnly", "other=1; Path=/"]);
|
|
if (os) res.setHeader("x-csrf-token", "csrf-1");
|
|
reply(res, 200, { ok: true });
|
|
});
|
|
return;
|
|
}
|
|
if (req.method === "POST" && url.pathname === (os ? "/api/auth/logout" : "/api/logout")) {
|
|
logoutsSeen++;
|
|
return reply(res, 200, {});
|
|
}
|
|
if (!String(req.headers.cookie ?? "").includes("TOKEN=abc123")) return reply(res, 401, {});
|
|
return handleLegacy(url, res, os ? "/proxy/network" : "");
|
|
}
|
|
|
|
// ─── The adapter ────────────────────────────────────────────────────────────
|
|
|
|
before(async () => {
|
|
controller = await new Promise<Server>((resolve) => {
|
|
const s = createServer(route).listen(0, "127.0.0.1", () => resolve(s));
|
|
});
|
|
controllerUrl = `http://127.0.0.1:${(controller.address() as AddressInfo).port}`;
|
|
});
|
|
after(() => {
|
|
controller.close();
|
|
try {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
} catch {
|
|
// Windows may still hold the database file
|
|
}
|
|
});
|
|
|
|
describe("normalising what a controller says", () => {
|
|
test("a MAC address is written one way, and anything else is not a MAC address", () => {
|
|
assert.equal(normaliseMac("AA-BB-CC-DD-EE-FF"), "aa:bb:cc:dd:ee:ff");
|
|
assert.equal(normaliseMac("aabbccddeeff"), "aa:bb:cc:dd:ee:ff");
|
|
assert.equal(normaliseMac("not a mac"), null);
|
|
assert.equal(normaliseMac(undefined), null);
|
|
});
|
|
|
|
test("the kind of device comes from its model, features or type — a gateway with a built-in switch is a gateway", () => {
|
|
assert.equal(deviceKind("UDM Pro", ["switching"], null), "gateway");
|
|
assert.equal(deviceKind("USW-24-PoE", ["switching"], null), "switch");
|
|
assert.equal(deviceKind("U6 Pro", ["accessPoint"], null), "access_point");
|
|
assert.equal(deviceKind(null, [], "uap"), "access_point");
|
|
assert.equal(deviceKind("UCG-Max", [], null), "gateway");
|
|
assert.equal(deviceKind("Mystery", [], null), "other");
|
|
});
|
|
|
|
test("only OFFLINE-like states are offline; adopting and updating devices are not a problem", () => {
|
|
assert.equal(stateFromApi("ONLINE"), "online");
|
|
assert.equal(stateFromApi("OFFLINE"), "offline");
|
|
assert.equal(stateFromApi("CONNECTION_INTERRUPTED"), "offline");
|
|
assert.equal(stateFromApi("UPDATING"), "updating");
|
|
assert.equal(stateFromApi("PENDING_ADOPTION"), "pending");
|
|
assert.equal(stateFromApi("something new"), "other");
|
|
assert.equal(stateFromLegacy(1), "online");
|
|
assert.equal(stateFromLegacy(0), "offline");
|
|
assert.equal(stateFromLegacy(6), "offline");
|
|
assert.equal(stateFromLegacy(4), "updating");
|
|
assert.equal(stateFromLegacy(7), "pending");
|
|
assert.equal(stateFromLegacy(99), "other");
|
|
});
|
|
|
|
test("a device from the Integration API gets its uplink as a MAC, and a missing detail only costs the uplink", () => {
|
|
const macById = new Map([["d-gw", MAC.gw], ["d-sw", MAC.sw]]);
|
|
const d = deviceFromApi(deviceList.data[1], detail["d-sw"], stats["d-sw"], "Default", macById)!;
|
|
assert.deepEqual([d.externalId, d.uplinkExternalId, d.uptimeSeconds, d.kind, d.firmwareUpdatable], [MAC.sw, MAC.gw, 3600, "switch", true]);
|
|
const bare = deviceFromApi(deviceList.data[1], null, null, "Default", macById)!;
|
|
assert.deepEqual([bare.uplinkExternalId, bare.uptimeSeconds, bare.name], [null, null, "Rack switch"]);
|
|
assert.equal(deviceFromApi({ name: "no mac" }, null, null, "Default", macById), null);
|
|
});
|
|
|
|
test("the classic API's device and Wi-Fi: the uplink MAC is read, and a passphrase is never carried over", () => {
|
|
const d = deviceFromLegacy(legacyDevices[2], "Default")!;
|
|
assert.deepEqual([d.uplinkExternalId, d.state, d.kind, d.model], [MAC.sw, "offline", "access_point", "U6PRO"]);
|
|
const s = ssidFromLegacy(legacyWlans[0], new Map([["ln-1", "Default"]]), "Default")!;
|
|
assert.deepEqual([s.name, s.security, s.networkName], ["Home", "WPA personal", "Default"]);
|
|
assert.ok(!JSON.stringify(s).includes(SECRET_PASSPHRASE));
|
|
});
|
|
});
|
|
|
|
describe("reading a controller", () => {
|
|
const cfg = (extra: Record<string, unknown>) => ({ url: controllerUrl, ...extra }) as never;
|
|
|
|
test("with an API key on a UniFi OS console: sites, devices with uplinks and uptime, networks with their ranges, Wi-Fi names", async () => {
|
|
mode = "os-key";
|
|
const inv = await createUnifiAdapter(cfg({ apiKey: "good-key" })).fetchInventory();
|
|
assert.equal(inv.mode, "api_key");
|
|
assert.deepEqual(inv.sites, ["Default"]);
|
|
const by = Object.fromEntries(inv.devices.map((d) => [d.name, d]));
|
|
assert.deepEqual([by["Gateway"].kind, by["Gateway"].uptimeSeconds, by["Gateway"].uplinkExternalId], ["gateway", 864000, null]);
|
|
assert.deepEqual([by["Rack switch"].uplinkExternalId, by["Hallway AP"].uplinkExternalId], [MAC.gw, MAC.sw]);
|
|
assert.deepEqual([by["Hallway AP"].state, by["Hallway AP"].uptimeSeconds], ["offline", null]);
|
|
assert.deepEqual(inv.networks.map((n) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]);
|
|
assert.deepEqual(inv.ssids.map((s) => [s.name, s.security, s.networkName]), [["Home", "WPA2", "Default"], ["IoT-net", "WPA3", "IoT"]]);
|
|
});
|
|
|
|
test("a self-hosted controller answers without /proxy/network: the other form of the address is found when the first is not there", async () => {
|
|
mode = "selfhosted-key";
|
|
const viaProbe = await createUnifiAdapter(cfg({ apiKey: "good-key" })).fetchInventory();
|
|
assert.equal(viaProbe.devices.length, 3);
|
|
const viaFlag = await createUnifiAdapter(cfg({ apiKey: "good-key", selfHosted: true })).fetchInventory();
|
|
assert.equal(viaFlag.devices.length, 3);
|
|
});
|
|
|
|
test("a key that is not accepted says so, and a site that does not exist says so", async () => {
|
|
mode = "os-key";
|
|
await assert.rejects(createUnifiAdapter(cfg({ apiKey: "wrong" })).fetchInventory(), /did not accept the API key/);
|
|
await assert.rejects(createUnifiAdapter(cfg({ apiKey: "good-key", site: "Garage" })).fetchInventory(), /no site called/);
|
|
const only = await createUnifiAdapter(cfg({ apiKey: "good-key", site: "default" })).fetchInventory();
|
|
assert.equal(only.devices.length, 3);
|
|
});
|
|
|
|
test("with a login on a UniFi OS console: the session cookie and CSRF token are used, the Wi-Fi passphrase is dropped, and the session is given back", async () => {
|
|
mode = "os-login";
|
|
loginsSeen = 0;
|
|
logoutsSeen = 0;
|
|
const inv = await createUnifiAdapter(cfg({ username: "reader", password: "pw" })).fetchInventory();
|
|
assert.equal(inv.mode, "login");
|
|
assert.equal(inv.devices.length, 3);
|
|
assert.equal(inv.devices.find((d) => d.name === "Hallway AP")!.uplinkExternalId, MAC.sw);
|
|
assert.deepEqual(inv.networks.map((n) => [n.name, n.vlanId, n.subnet]), [["Default", null, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]);
|
|
assert.deepEqual(inv.ssids.map((s) => [s.name, s.enabled, s.security, s.networkName]), [["Home", true, "WPA personal", "Default"], ["Guests", false, "Open", "IoT"]]);
|
|
assert.ok(!JSON.stringify(inv).includes(SECRET_PASSPHRASE));
|
|
assert.deepEqual([loginsSeen, logoutsSeen], [1, 1]);
|
|
});
|
|
|
|
test("with a login on a self-hosted controller, and the wrong password", async () => {
|
|
mode = "selfhosted-login";
|
|
const inv = await createUnifiAdapter(cfg({ username: "reader", password: "pw", selfHosted: true })).fetchInventory();
|
|
assert.equal(inv.devices.length, 3);
|
|
await assert.rejects(createUnifiAdapter(cfg({ username: "reader", password: "no" })).fetchInventory(), /did not accept the username and password/);
|
|
});
|
|
|
|
test("ping says whether it can get in", async () => {
|
|
mode = "os-key";
|
|
assert.equal((await createUnifiAdapter(cfg({ apiKey: "good-key" })).ping()).ok, true);
|
|
const bad = await createUnifiAdapter(cfg({ apiKey: "wrong" })).ping();
|
|
assert.equal(bad.ok, false);
|
|
assert.match(bad.error ?? "", /API key/);
|
|
});
|
|
|
|
test("the form needs a key, or a username with its password", () => {
|
|
assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x" }), ["apiKey"]);
|
|
assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x", username: "u" }), ["password"]);
|
|
assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x", apiKey: "k" }), []);
|
|
assert.deepEqual(validateIntegrationConfig("unifi", { url: "https://x", username: "u", password: "p" }), []);
|
|
});
|
|
});
|
|
|
|
// ─── What is kept ───────────────────────────────────────────────────────────
|
|
|
|
describe("keeping what was read", () => {
|
|
test("a device is offline from the first time it is seen not online, until it is online again", () => {
|
|
const t0 = "2026-01-01T10:00:00.000Z";
|
|
const t1 = "2026-01-01T10:05:00.000Z";
|
|
const t2 = "2026-01-01T10:10:00.000Z";
|
|
let s = trackOffline(undefined, "online", t0);
|
|
assert.deepEqual(s, { offlineSince: null, lastOnlineAt: t0 });
|
|
s = trackOffline(s, "offline", t1);
|
|
assert.deepEqual(s, { offlineSince: t1, lastOnlineAt: t0 });
|
|
s = trackOffline(s, "offline", t2);
|
|
assert.equal(s.offlineSince, t1, "still counted from the first time");
|
|
s = trackOffline(s, "updating", t2);
|
|
assert.equal(s.offlineSince, t1, "updating says nothing either way");
|
|
s = trackOffline(s, "online", t2);
|
|
assert.deepEqual(s, { offlineSince: null, lastOnlineAt: t2 });
|
|
});
|
|
|
|
test("freshness: only a good, recent read can be believed", () => {
|
|
const now = Date.parse("2026-01-01T12:00:00.000Z");
|
|
const status = (at: string, ok = true) => ({ at, ok, error: null, sites: [], mode: null, devices: 0, networks: 0, ssids: 0 });
|
|
assert.equal(isFresh(undefined, now), false);
|
|
assert.equal(isFresh(status("2026-01-01T11:55:00.000Z"), now), true);
|
|
assert.equal(isFresh(status("2026-01-01T11:00:00.000Z"), now), false);
|
|
assert.equal(isFresh(status("2026-01-01T11:55:00.000Z", false), now), false);
|
|
});
|
|
});
|
|
|
|
describe("a controller in the database", () => {
|
|
let integrationId = 0;
|
|
let gwId = 0;
|
|
let swId = 0;
|
|
let apId = 0;
|
|
let webId = 0;
|
|
|
|
before(async () => {
|
|
await db.insert(users).values([
|
|
{ oidcSub: "admin", name: "Ada", role: "admin" },
|
|
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
|
{ oidcSub: "operator", name: "Olga", role: "operator" },
|
|
]);
|
|
mode = "os-key";
|
|
const [cred] = await db.insert(integrationCredentials).values({ name: "unifi:Home", encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).returning();
|
|
const [row] = await db.insert(integrations).values({ type: "unifi", name: "Home UniFi", baseUrl: controllerUrl, credentialId: cred.id, config: JSON.stringify({ url: controllerUrl }) }).returning();
|
|
integrationId = row.id;
|
|
webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id;
|
|
});
|
|
|
|
test("the first read stores the devices, the networks and the Wi-Fi names, and says how it went", async () => {
|
|
const status = await syncUnifiIntegration(integrationId);
|
|
assert.equal(status.ok, true);
|
|
assert.deepEqual([status.devices, status.networks, status.ssids, status.mode], [3, 2, 2, "api_key"]);
|
|
const rows = await db.select().from(networkDevices);
|
|
assert.equal(rows.length, 3);
|
|
gwId = rows.find((r) => r.name === "Gateway")!.id;
|
|
swId = rows.find((r) => r.name === "Rack switch")!.id;
|
|
apId = rows.find((r) => r.name === "Hallway AP")!.id;
|
|
const ap = rows.find((r) => r.id === apId)!;
|
|
assert.deepEqual([ap.state, ap.kind, ap.ip, ap.uplinkExternalId], ["offline", "access_point", "192.168.1.3", MAC.sw]);
|
|
assert.ok(ap.offlineSince, "offline since the first look");
|
|
assert.equal((await db.select().from(networkSegments)).length, 4);
|
|
assert.equal((await syncStatuses())[integrationId].ok, true);
|
|
});
|
|
|
|
test("a second read keeps when the offline began, and a device that is gone from the controller is removed", async () => {
|
|
const before = (await db.select().from(networkDevices).where(eq(networkDevices.id, apId)))[0].offlineSince;
|
|
await new Promise((r) => setTimeout(r, 15));
|
|
await syncUnifiIntegration(integrationId, new Date());
|
|
assert.equal((await db.select().from(networkDevices).where(eq(networkDevices.id, apId)))[0].offlineSince, before);
|
|
assert.equal((await db.select().from(networkDevices)).length, 3, "updated in place, not added again");
|
|
});
|
|
|
|
test("a controller that cannot be read leaves what was stored, and says why", async () => {
|
|
mode = "selfhosted-key"; // the console form of the address now 404s... but the probe finds the other form, so break the key instead
|
|
const [cred] = await db.select().from(integrationCredentials);
|
|
await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "revoked" })) }).where(eq(integrationCredentials.id, cred.id));
|
|
const status = await syncUnifiIntegration(integrationId);
|
|
assert.equal(status.ok, false);
|
|
assert.match(status.error ?? "", /API key/);
|
|
assert.equal((await db.select().from(networkDevices)).length, 3);
|
|
await db.update(integrationCredentials).set({ encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).where(eq(integrationCredentials.id, cred.id));
|
|
mode = "os-key";
|
|
assert.equal((await syncUnifiIntegration(integrationId)).ok, true);
|
|
});
|
|
|
|
test("uplinks are dependencies nobody had to write: the access point needs the switch, which needs the gateway", async () => {
|
|
const graph = await loadGraph();
|
|
assert.deepEqual(graph.edges.get(`device:${apId}`), [`device:${swId}`]);
|
|
assert.deepEqual(graph.edges.get(`device:${swId}`), [`device:${gwId}`]);
|
|
assert.equal(graph.edges.get(`device:${gwId}`), undefined);
|
|
assert.equal(graph.rows.length, 0, "none of them is a written dependency");
|
|
assert.equal(alertIdOfNode(`device:${swId}`, graph), `offline:offline:device:${swId}`);
|
|
assert.deepEqual(uplinkEdges([{ id: 1, integrationId: 1, externalId: "a", uplinkExternalId: "zz" }]), [], "an uplink that is not known is none");
|
|
});
|
|
|
|
test("a server written as needing the access point is folded under whatever of them is the root cause", async () => {
|
|
await db.insert(dependencies).values({ fromType: "server", fromId: webId, toType: "device", toId: apId });
|
|
const cover = await dependencyCover([webId], [], [apId, swId]);
|
|
assert.equal(cover.cause.get(`device:${apId}`), `device:${swId}`, "the access point is down because the switch is");
|
|
assert.equal(cover.cause.get(`server:${webId}`), `device:${swId}`, "and so is the server that needs it");
|
|
assert.equal(cover.cause.get(`device:${swId}`), undefined, "the switch stands alone: nothing it needs is down");
|
|
assert.deepEqual([...(cover.taken.get(`device:${swId}`) ?? [])].sort(), ["Hallway AP", "web"]);
|
|
// with only the access point down, it is its own cause
|
|
const alone = await dependencyCover([], [], [apId]);
|
|
assert.equal(alone.cause.size, 0);
|
|
});
|
|
|
|
test("a device offline for longer than the limit is a critical offline alert about it", () => {
|
|
const device = (state: string, since: string | null) => ({ id: 7, name: "Hallway AP", kind: "access_point", model: "U6 Pro", state, offlineSince: since });
|
|
const snap = (devices: ReturnType<typeof device>[]) => ({ servers: [], proxmox: [], synology: [], unifi: [{ integrationId: 3, integrationName: "Home UniFi", devices }] });
|
|
const now = Date.parse("2026-01-01T12:00:00.000Z");
|
|
const limits = { serverOfflineMinutes: 60, diskUsagePercent: 90, deviceOfflineMinutes: 10 };
|
|
const five = evaluateHealth(snap([device("offline", "2026-01-01T11:55:00.000Z")]), limits, now);
|
|
assert.deepEqual(five, [], "five minutes is not yet");
|
|
const twenty = evaluateHealth(snap([device("offline", "2026-01-01T11:40:00.000Z")]), limits, now);
|
|
assert.equal(twenty.length, 1);
|
|
assert.deepEqual([twenty[0].key, twenty[0].source, twenty[0].severity], ["offline:device:7", "unifi:3", "critical"]);
|
|
assert.match(twenty[0].message, /Hallway AP \(access point, U6 Pro\) has been offline for 20 min/);
|
|
assert.deepEqual(evaluateHealth(snap([device("updating", "2026-01-01T11:00:00.000Z")]), limits, now), [], "updating is not offline");
|
|
assert.deepEqual(evaluateHealth(snap([device("online", null)]), limits, now), []);
|
|
assert.equal(subjectOfConditionKey("offline:device:7"), "device:7", "maintenance on a device holds its alert");
|
|
});
|
|
|
|
test("a maintenance window can be put on a device, and describes it", async () => {
|
|
const described = await describeTarget("device", apId);
|
|
assert.deepEqual(described, { name: "Hallway AP", kind: "Network device (access point)" });
|
|
assert.equal(await describeTarget("device", 99999), null);
|
|
await db.insert(maintenanceWindows).values({ targetType: "device", targetId: swId, startedAt: new Date(Date.now() - 1000).toISOString(), endsAt: new Date(Date.now() + 3600_000).toISOString(), reason: "rack work" });
|
|
});
|
|
|
|
test("on the Alerts page: the offline device, who it is about and where to go, silenced by maintenance, and held back when the controller has not been read for a while", async () => {
|
|
await db.update(networkDevices).set({ offlineSince: new Date(Date.now() - 30 * 60_000).toISOString() }).where(eq(networkDevices.id, apId));
|
|
invalidateAlertsCache();
|
|
const alertId = `offline:offline:device:${apId}`;
|
|
let report = await getAlerts(true);
|
|
const alert = report.alerts.find((a) => a.id === alertId)!;
|
|
assert.ok(alert, "the access point is raised");
|
|
assert.deepEqual([alert.severity, alert.category, alert.source, alert.link, alert.target?.type, alert.target?.name, alert.silenced], ["critical", "offline", "UniFi", "/network/devices", "device", "Hallway AP", false]);
|
|
assert.match(alert.message, /has been offline for 30 min/);
|
|
|
|
const [window] = await db.insert(maintenanceWindows).values({ targetType: "device", targetId: apId, startedAt: new Date(Date.now() - 1000).toISOString(), endsAt: new Date(Date.now() + 3600_000).toISOString() }).returning();
|
|
invalidateAlertsCache();
|
|
report = await getAlerts(true);
|
|
assert.equal(report.alerts.find((a) => a.id === alertId)!.silenced, true);
|
|
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.id, window.id));
|
|
|
|
// Not read for longer than anyone should trust it: neither raised nor cleared, and the page says it cannot tell.
|
|
const stale = { [integrationId]: { at: new Date(Date.now() - 3600_000).toISOString(), ok: true, error: null, sites: [], mode: "api_key", devices: 3, networks: 2, ssids: 2 } };
|
|
await setInternalFlag("unifiSync", JSON.stringify(stale));
|
|
invalidateAlertsCache();
|
|
report = await getAlerts(true);
|
|
assert.equal(report.alerts.some((a) => a.id === alertId), false);
|
|
assert.ok(report.couldntCheck.some((c) => /UniFi/.test(c.name)), "it says it could not check");
|
|
assert.equal((await syncUnifiIntegration(integrationId)).ok, true);
|
|
invalidateAlertsCache();
|
|
});
|
|
|
|
describe("the page's data", () => {
|
|
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/network", networkRouter);
|
|
app = await new Promise<Server>((resolve) => {
|
|
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
|
});
|
|
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/network`;
|
|
});
|
|
after(() => app.close());
|
|
|
|
test("everyone signed in sees the devices with their address, uptime, uplink and what depends on them", async () => {
|
|
const res = await fetch(base);
|
|
assert.equal(res.status, 200);
|
|
const body = (await res.json()) as any;
|
|
const by = Object.fromEntries(body.devices.map((d: any) => [d.name, d]));
|
|
assert.deepEqual([by["Rack switch"].ip, by["Rack switch"].uptimeSeconds, by["Rack switch"].uplink.name, by["Rack switch"].firmwareUpdatable], ["192.168.1.2", 3600, "Gateway", true]);
|
|
assert.equal(by["Hallway AP"].state, "offline");
|
|
assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind them");
|
|
assert.equal(by["Hallway AP"].needs, 2);
|
|
assert.equal(by["Rack switch"].inMaintenance, true);
|
|
assert.deepEqual(body.networks.map((n: any) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]);
|
|
assert.deepEqual(body.ssids.map((s: any) => [s.name, s.networkName]).sort(), [["Home", "Default"], ["IoT-net", "IoT"]]);
|
|
assert.equal(body.integrations[0].status.ok, true);
|
|
assert.ok(!JSON.stringify(body).includes(SECRET_PASSPHRASE));
|
|
});
|
|
|
|
test("reading again needs an operator", async () => {
|
|
who = "viewer";
|
|
assert.equal((await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status, 403);
|
|
who = "operator";
|
|
const res = await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ integrationId }) });
|
|
assert.equal(res.status, 200);
|
|
assert.equal(((await res.json()) as any).statuses[integrationId].ok, true);
|
|
const other = await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ integrationId: 424242 }) });
|
|
assert.equal(other.status, 404);
|
|
});
|
|
});
|
|
|
|
test("removing the integration removes what was read from it, and the dependencies written about its devices", async () => {
|
|
await removeIntegrationData(integrationId);
|
|
assert.equal((await db.select().from(networkDevices)).length, 0);
|
|
assert.equal((await db.select().from(networkSegments)).length, 0);
|
|
assert.equal((await db.select().from(dependencies)).length, 0);
|
|
assert.equal((await syncStatuses())[integrationId], undefined);
|
|
});
|
|
});
|