Files
bobbanandClaude Sonnet 5.5 d78aba8bf9 Show cluster health in the Technitium DNS integration
Reads /api/admin/cluster/state (Technitium 14+): a Cluster table on the page,
alerts for a node unreachable for ten minutes (primary critical) and for a
secondary that has stopped taking the primary's configuration, and three
/metrics series. A server in no cluster shows nothing; a token that may not
view administration is told so and the rest of the read is unaffected.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 23:37:11 +01:00

710 lines
45 KiB
TypeScript

/**
* Technitium DNS Server (statistics, zones, block lists, DHCP and a real DNS question over UDP): reading what its API says, what is stored and carried between reads, what is wrong, the
* health pass, the alerts, the page's route and /metrics.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import * as dgram from "node:dgram";
import { createServer as createHttpServer, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-technitium-"));
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, integrations, technitiumState } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { INTEGRATION_FIELDS } = await import("../src/integrations/fieldSchemas.js");
const tn = await import("../src/integrations/technitium/adapter.js");
const ts = await import("../src/services/technitiumSync.js");
const { evaluateHealth, collectSnapshot } = await import("../src/services/healthMonitor.js");
const { subjectOfConditionKey } = await import("../src/services/maintenance.js");
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
const { technitiumRouter } = await import("../src/routes/technitium.js");
const { buildMetrics } = await import("../src/services/metrics.js");
const { setInternalFlag } = await import("../src/services/settingsStore.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
const MIN = 60_000;
const HOUR = 60 * MIN;
const DAY = 24 * HOUR;
const iso = (ms: number) => new Date(ms).toISOString();
/** A DNS server that answers with the rcode it is told to (or not at all), once per question. */
async function fakeDns(behaviour: () => { rcode?: number; silent?: boolean }) {
const socket = dgram.createSocket("udp4");
const questions: string[] = [];
socket.on("message", (msg, rinfo) => {
const b = behaviour();
let i = 12;
const labels: string[] = [];
while (msg[i] !== 0 && i < msg.length) {
labels.push(msg.subarray(i + 1, i + 1 + msg[i]).toString("ascii"));
i += msg[i] + 1;
}
questions.push(labels.join("."));
if (b.silent) return;
const reply = Buffer.from(msg);
reply.writeUInt16BE(0x8180 | (b.rcode ?? 0), 2);
reply.writeUInt16BE(b.rcode ? 0 : 1, 6);
socket.send(reply, rinfo.port, rinfo.address);
});
await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", resolve));
return { port: socket.address().port, questions, close: () => socket.close() };
}
describe("what Technitium's API says", () => {
test("the settings: version, when it started (seven fractional digits are fine), the DNS port from its endpoints, blocking, the block lists and when they are next updated", () => {
const s = tn.parseSettings({
version: "15.5",
uptimestamp: "2026-10-20T08:00:00.1234567Z",
dnsServerLocalEndPoints: ["[::]:5353", "0.0.0.0:5353"],
enableBlocking: false,
blockListUrls: ["https://a.example/list", " ", "https://b.example/list"],
blockListUpdateIntervalHours: 24,
blockListNextUpdatedOn: "2026-10-21T08:00:00.0000000Z",
cacheMaximumEntries: 10000,
recursion: "AllowOnlyForPrivateNetworks",
dnssecValidation: true,
});
assert.deepEqual(s, {
version: "15.5",
startedAt: "2026-10-20T08:00:00.123Z",
dnsPort: 5353,
blockingEnabled: false,
blockLists: { count: 2, intervalHours: 24, nextUpdate: "2026-10-21T08:00:00.000Z" },
cacheMaximumEntries: 10000,
recursion: "AllowOnlyForPrivateNetworks",
dnssecValidation: true,
});
});
test("a setting that is missing is what it should be: port 53, blocking on, nothing set up, nothing known", () => {
assert.deepEqual(tn.parseSettings({}), { version: null, startedAt: null, dnsPort: 53, blockingEnabled: true, blockLists: { count: 0, intervalHours: null, nextUpdate: null }, cacheMaximumEntries: null, recursion: null, dnssecValidation: null });
assert.equal(tn.parseSettings({ uptimestamp: "0001-01-01T00:00:00Z", blockListNextUpdatedOn: "0001-01-01T00:00:00Z" }).startedAt, null, "the year 1 is never a time");
assert.equal(tn.parseSettings({ blockListUpdateIntervalHours: 0 }).blockLists.intervalHours, null);
});
test("the clients and names asked about most: biggest first, a client with the name its address resolves to is both", () => {
const top = tn.parseTop([{ name: "ads.example", hits: 5 }, { name: "192.168.1.5", domain: "laptop.lan", hits: 40 }, { name: "x", hits: "many" }, { hits: 3 }, { name: "same", domain: "same", hits: 9 }]);
assert.deepEqual(top, [{ name: "192.168.1.5 (laptop.lan)", count: 40 }, { name: "same", count: 9 }, { name: "ads.example", count: 5 }]);
assert.equal(tn.parseTop(Array.from({ length: 30 }, (_, i) => ({ name: `n${i}`, hits: i }))).length, 10);
});
test("the statistics: how the queries ended and what share was blocked, cached or failed; no query count is not zero queries", () => {
const s = tn.parseStats({
stats: { totalQueries: 2000, totalNoError: 1700, totalServerFailure: 100, totalNxDomain: 150, totalRefused: 50, totalAuthoritative: 200, totalRecursive: 500, totalCached: 1000, totalBlocked: 250, totalDropped: 50, totalClients: 12, zones: 7, cachedEntries: 4321, allowedZones: 2, blockedZones: 3, allowListZones: 0, blockListZones: 90210 },
topClients: [{ name: "10.0.0.2", hits: 700 }],
topDomains: [{ name: "example.com", hits: 90 }],
topBlockedDomains: [{ name: "ads.example", hits: 60 }],
})!;
assert.deepEqual([s.queries, s.blocked, s.blockedPercent, s.cachedPercent, s.failurePercent, s.clients, s.cachedEntries, s.blockListZones], [2000, 250, 12.5, 50, 5, 12, 4321, 90210]);
assert.deepEqual([s.topClients[0], s.topDomains[0], s.topBlocked[0]], [{ name: "10.0.0.2", count: 700 }, { name: "example.com", count: 90 }, { name: "ads.example", count: 60 }]);
assert.equal(tn.parseStats({ stats: {} }), null);
assert.equal(tn.parseStats("nonsense"), null);
assert.equal(tn.parseStats({ stats: { totalQueries: 0 } })!.blockedPercent, null, "no queries, no share");
});
test("the zones: an expired secondary zone and one that cannot sync are problems; the server's own, and switched-off ones, are not", () => {
const z = tn.parseZones({
totalZones: 6,
zones: [
{ name: "home.lan", type: "Primary" },
{ name: "lab.lan", type: "Secondary", isExpired: true, syncFailed: true },
{ name: "other.lan", type: "Secondary", syncFailed: true },
{ name: "old.lan", type: "Secondary", isExpired: true, disabled: true },
{ name: "localhost", type: "Primary", internal: true },
{ type: "Primary" },
],
})!;
assert.deepEqual(z, { total: 4, disabled: 1, issues: [{ name: "lab.lan", problem: "expired" }, { name: "other.lan", problem: "sync failed" }] });
assert.equal(tn.parseZones({}), null);
});
test("DHCP: the scopes, which are on, and the leases; not a list of scopes is not a DHCP server", () => {
const scopes = { scopes: [{ name: "lan", enabled: true }, { name: "guest", enabled: false }] };
assert.deepEqual(tn.parseDhcp(scopes, { leases: [{}, {}, {}] }), { scopes: 2, enabledScopes: 1, leases: 3 });
assert.deepEqual(tn.parseDhcp(scopes, null), { scopes: 2, enabledScopes: 1, leases: 0 });
assert.equal(tn.parseDhcp({}, null), null);
});
test("the token is a required secret of the integration, and the DNS test address and name are optional", () => {
const fields = INTEGRATION_FIELDS.technitium!;
const token = fields.find((f) => f.key === "token")!;
assert.deepEqual([token.secret, token.type, token.optional ?? false], [true, "password", false]);
assert.equal(fields.find((f) => f.key === "dnsHost")?.optional, true);
assert.equal(fields.find((f) => f.key === "probeDomain")?.optional, true);
});
});
describe("the adapter against a Technitium that answers", () => {
let web: Server;
let url = "";
let dns: Awaited<ReturnType<typeof fakeDns>>;
const seen: { path: string; auth: string }[] = [];
let envelope: { status: string; errorMessage?: string } = { status: "ok" };
let failing = new Set<string>();
let httpStatus = 200;
let rawBody: string | null = null;
let dhcpScopes: unknown[] = [{ name: "lan", enabled: true }];
/** The port the fake settings say the DNS server is on; the one of the answering fake DNS server unless a test points it elsewhere. */
let endpointPort: number | null = null;
/** What the fake cluster call answers: nothing (a server with no such call), a refusal of the token's user, a failure, or a cluster. */
let clusterMode: "none" | "denied" | "boom" | "cluster" = "none";
const clusterBody = { clusterInitialized: true, dnsServerDomain: "dns2.example.com", version: "15.6", clusterDomain: "example.com", heartbeatRefreshIntervalSeconds: 30, configRefreshIntervalSeconds: 900, configLastSynced: "2026-09-26T12:30:16.1234567Z", clusterNodes: [{ id: 2, name: "dns2.example.com", url: "https://dns2.example.com:53443/", ipAddress: "10.0.0.3", type: "Secondary", state: "Self", version: "15.6" }, { id: 3, name: "dns3.example.com", type: "Secondary", state: "Unreachable", lastSeen: "0001-01-01T00:00:00" }, { id: 1, name: "dns1.example.com", url: "https://dns1.example.com:53443/", ipAddresses: ["10.0.0.2"], type: "Primary", state: "Connected", version: "15.6", lastSeen: "2026-09-26T12:30:16Z" }] };
before(async () => {
dns = await fakeDns(() => ({}));
web = createHttpServer((req, res) => {
const u = new URL(req.url ?? "", "http://x");
seen.push({ path: u.pathname + u.search, auth: String(req.headers.authorization ?? "") });
const send = (status: number, body: string) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(body);
};
if (httpStatus !== 200) return send(httpStatus, "");
if (rawBody !== null) return send(200, rawBody);
if (failing.has(u.pathname)) return send(500, "{}");
if (envelope.status !== "ok") return send(200, JSON.stringify(envelope));
const ok = (response: unknown) => send(200, JSON.stringify({ status: "ok", response }));
switch (u.pathname) {
case "/api/settings/get":
return ok({ version: "15.5", uptimestamp: iso(Date.now() - 3 * DAY), dnsServerLocalEndPoints: [`127.0.0.1:${endpointPort ?? dns.port}`], enableBlocking: true, blockListUrls: ["https://a.example/list"], blockListUpdateIntervalHours: 24, blockListNextUpdatedOn: iso(Date.now() + 5 * HOUR), cacheMaximumEntries: 10000, recursion: "AllowOnlyForPrivateNetworks", dnssecValidation: true });
case "/api/dashboard/stats/get":
return ok({ stats: { totalQueries: 1000, totalBlocked: 200, totalCached: 500, totalServerFailure: 10, totalClients: 4, cachedEntries: 300, zones: 2 }, topClients: [{ name: "10.0.0.2", hits: 600 }], topDomains: [], topBlockedDomains: [] });
case "/api/zones/list":
return ok({ totalZones: 2, zones: [{ name: "home.lan", type: "Primary" }, { name: "lab.lan", type: "Secondary", isExpired: true }] });
case "/api/dhcp/scopes/list":
return ok({ scopes: dhcpScopes });
case "/api/dhcp/leases/list":
return ok({ leases: [{}, {}] });
case "/api/admin/cluster/state":
if (clusterMode === "denied") return send(200, JSON.stringify({ status: "error", errorMessage: "Access was denied." }));
if (clusterMode === "boom") return send(500, "{}");
if (clusterMode === "cluster") return ok(clusterBody);
return send(404, "{}");
default:
return send(404, "{}");
}
});
await new Promise<void>((resolve) => web.listen(0, "127.0.0.1", resolve));
url = `http://127.0.0.1:${(web.address() as AddressInfo).port}`;
});
after(() => {
web.close();
dns.close();
});
const adapter = (extra: Record<string, unknown> = {}) => tn.createTechnitiumAdapter({ url: `${url}/`, token: "tok-1", ...extra } as never);
const reset = () => {
seen.length = 0;
envelope = { status: "ok" };
failing = new Set();
httpStatus = 200;
rawBody = null;
dhcpScopes = [{ name: "lan", enabled: true }];
clusterMode = "none";
};
test("a read puts the token in the Authorization header, asks the six things and one DNS question, and says what each answered", async () => {
reset();
const r = await adapter().read();
assert.deepEqual([...new Set(seen.map((s) => s.auth))], ["Bearer tok-1"]);
assert.deepEqual(seen.map((s) => s.path).sort(), ["/api/admin/cluster/state", "/api/dashboard/stats/get?type=LastDay", "/api/dhcp/leases/list", "/api/dhcp/scopes/list", "/api/settings/get", "/api/zones/list?pageNumber=1&zonesPerPage=1000"]);
assert.deepEqual([r.version, r.dnsPort, r.blockingEnabled, r.settings.blockLists.count, r.settings.cacheMaximumEntries], ["15.5", dns.port, true, 1, 10000]);
assert.deepEqual([r.stats?.queries, r.stats?.blockedPercent, r.zones?.issues, r.dhcp], [1000, 20, [{ name: "lab.lan", problem: "expired" }], { scopes: 1, enabledScopes: 1, leases: 2 }]);
assert.deepEqual([r.probe.ok, r.probe.name, r.probe.host], [true, "example.com", "127.0.0.1"]);
assert.deepEqual(dns.questions.at(-1), "example.com");
assert.ok(Date.now() - Date.parse(r.startedAt!) > 2.9 * DAY);
});
test("the name asked about and the DNS address can be set; no DHCP scopes means the leases are not asked for", async () => {
reset();
dhcpScopes = [];
const r = await adapter({ probeDomain: "internal.test", dnsHost: "127.0.0.1" }).read();
assert.equal(dns.questions.at(-1), "internal.test");
assert.deepEqual(r.dhcp, { scopes: 0, enabledScopes: 0, leases: 0 });
assert.equal(seen.some((s) => s.path === "/api/dhcp/leases/list"), false);
});
test("the cluster: a server with no such call is in none, one in a cluster says its nodes, and neither costs the rest of the read", async () => {
reset();
const none = await adapter().read();
assert.deepEqual(none.cluster, { info: null, note: null, denied: false });
clusterMode = "cluster";
const r = await adapter().read();
assert.equal(r.cluster?.note, null);
assert.deepEqual([r.cluster?.info?.domain, r.cluster?.info?.thisNode, r.cluster?.info?.nodes.map((n) => `${n.name}=${n.type}/${n.state}`)], ["example.com", "dns2.example.com", ["dns1.example.com=Primary/Connected", "dns2.example.com=Secondary/Self", "dns3.example.com=Secondary/Unreachable"]]);
assert.equal(r.stats?.queries, 1000, "the rest of the read is as before");
});
test("the cluster: a token that may not view it is told so, a read that failed this time is said, and the rest of the read still works", async () => {
reset();
clusterMode = "denied";
const denied = await adapter().read();
assert.equal(denied.cluster?.denied, true);
assert.match(denied.cluster?.note ?? "", /not allowed to view the cluster/);
clusterMode = "boom";
const boom = await adapter().read();
assert.equal(boom.cluster?.denied, false);
assert.match(boom.cluster?.note ?? "", /could not be read this time: Technitium error: HTTP 500/);
assert.equal(boom.version, "15.5");
});
test("what cannot be read is left out and the rest is kept: statistics, zones and DHCP are each soft; the settings are not", async () => {
reset();
failing = new Set(["/api/dashboard/stats/get", "/api/zones/list", "/api/dhcp/scopes/list"]);
const r = await adapter().read();
assert.deepEqual([r.stats, r.zones, r.dhcp, r.version], [null, null, null, "15.5"]);
reset();
failing = new Set(["/api/settings/get"]);
await assert.rejects(() => adapter().read(), /HTTP 500/);
});
test("a token that is not accepted, an error Technitium words, an address that is not Technitium's and an answer that is not JSON are each said", async () => {
reset();
envelope = { status: "invalid-token" };
await assert.rejects(() => adapter().read(), /did not accept the token — make a non-expiring API token/);
envelope = { status: "error", errorMessage: "Access was denied." };
await assert.rejects(() => adapter().read(), /Technitium: Access was denied\./);
envelope = { status: "2fa-required" };
await assert.rejects(() => adapter().read(), /status "2fa-required"/);
reset();
httpStatus = 404;
await assert.rejects(() => adapter().read(), /no API at this address/);
httpStatus = 403;
await assert.rejects(() => adapter().read(), /did not accept the token \(HTTP 403\)/);
reset();
rawBody = "<html>hello</html>";
await assert.rejects(() => adapter().read(), /isn't JSON/);
});
test("a DNS server that does not answer, or answers with a failure, is said in the read — and the read still works; \"no such name\" is an answer", async () => {
reset();
const quiet = await fakeDns(() => ({ silent: true }));
endpointPort = quiet.port;
try {
const r = await adapter().read();
assert.deepEqual([r.probe.ok, /no answer/.test(r.probe.error ?? ""), r.stats?.queries], [false, true, 1000]);
} finally {
quiet.close();
}
const failing = await fakeDns(() => ({ rcode: 2 }));
endpointPort = failing.port;
try {
const r = await adapter().read();
assert.deepEqual([r.probe.ok, /server failure/.test(r.probe.error ?? "")], [false, true]);
} finally {
failing.close();
}
const nx = await fakeDns(() => ({ rcode: 3 }));
endpointPort = nx.port;
try {
assert.equal((await adapter().read()).probe.ok, true);
} finally {
nx.close();
endpointPort = null;
}
});
test("ping asks the settings and says how long it took, or why not", async () => {
reset();
const ok = await adapter().ping();
assert.equal(ok.ok, true);
assert.equal(typeof ok.latencyMs, "number");
envelope = { status: "invalid-token" };
const bad = await adapter().ping();
assert.deepEqual([bad.ok, /did not accept the token/.test(bad.error ?? "")], [false, true]);
});
});
/** A read as the adapter gives it, for the parts that need only what it says. */
function read(over: Partial<import("../src/integrations/technitium/adapter.js").TechnitiumRead> = {}): import("../src/integrations/technitium/adapter.js").TechnitiumRead {
return {
version: "15.5",
startedAt: iso(Date.now() - 5 * DAY),
dnsPort: 53,
blockingEnabled: true,
settings: { blockLists: { count: 2, intervalHours: 24, nextUpdate: iso(Date.now() + 6 * HOUR) }, cacheMaximumEntries: 10000, recursion: "AllowOnlyForPrivateNetworks", dnssecValidation: true },
stats: { period: "LastDay", queries: 1000, noError: 900, serverFailure: 20, nxDomain: 60, refused: 20, authoritative: 100, recursive: 300, cached: 500, blocked: 100, dropped: 0, clients: 5, zones: 3, cachedEntries: 4000, allowedZones: 0, blockedZones: 0, allowListZones: 0, blockListZones: 80000, blockedPercent: 10, cachedPercent: 50, failurePercent: 2, topClients: [{ name: "10.0.0.2", count: 500 }], topDomains: [{ name: "example.com", count: 90 }], topBlocked: [{ name: "ads.example", count: 60 }] },
zones: { total: 3, disabled: 0, issues: [] },
dhcp: { scopes: 1, enabledScopes: 1, leases: 12 },
probe: { ok: true, ms: 7, error: null, name: "example.com", host: "dns.lan" },
...over,
};
}
describe("what Technitium is carried and judged by", () => {
const now = new Date("2026-11-01T12:00:00Z");
const stored = (over: Partial<import("../src/services/technitiumSync.js").StoredTechnitium> = {}): import("../src/services/technitiumSync.js").StoredTechnitium => ({
version: "15.5",
startedAt: null,
dnsPort: 53,
blockingEnabled: true,
blockingOffSince: null,
settings: read().settings,
stats: null,
zones: { total: 2, disabled: 0, issues: [] },
dhcp: null,
probe: { ok: true, ms: 5, error: null, name: "example.com", host: "dns.lan" },
probeFailSince: null,
updatedAt: now.toISOString(),
...over,
});
test("since when: a thing first seen wrong starts its clock now, keeps it while it stays wrong, and loses it when it is right", () => {
const bad = read({ blockingEnabled: false, probe: { ok: false, ms: null, error: "no answer in 3 s", name: "example.com", host: "dns.lan" } });
const first = ts.carrySince(bad, null, now);
assert.deepEqual(first, { blockingOffSince: now.toISOString(), probeFailSince: now.toISOString() });
const later = ts.carrySince(bad, { blockingOffSince: iso(now.getTime() - HOUR), probeFailSince: iso(now.getTime() - 30 * MIN) }, now);
assert.deepEqual(later, { blockingOffSince: iso(now.getTime() - HOUR), probeFailSince: iso(now.getTime() - 30 * MIN) });
assert.deepEqual(ts.carrySince(read(), { blockingOffSince: iso(now.getTime() - HOUR), probeFailSince: iso(now.getTime() - HOUR) }, now), { blockingOffSince: null, probeFailSince: null });
});
const failing = (min: number) => ({ probe: { ok: false, ms: null, error: "no answer in 3 s", name: "example.com", host: "dns.lan" }, probeFailSince: iso(now.getTime() - min * MIN) });
test("a DNS question unanswered for ten minutes is critical; for less it is one lost packet", () => {
assert.deepEqual(ts.technitiumProblems(1, "Home DNS", stored(failing(9)), now.getTime()), []);
const [p] = ts.technitiumProblems(1, "Home DNS", stored(failing(12)), now.getTime());
assert.deepEqual([p.key, p.severity], ["technitium-dns:1", "critical"]);
assert.match(p.message, /Home DNS: DNS has not answered a question about example\.com for 12 minutes \(asked dns\.lan:53\) — no answer in 3 s/);
});
test("blocking off for an hour is a warning, but only where block lists are set up; for less it is a pause", () => {
const off = (min: number, count = 2) => stored({ blockingEnabled: false, blockingOffSince: iso(now.getTime() - min * MIN), settings: { ...read().settings, blockLists: { count, intervalHours: 24, nextUpdate: null } } });
assert.deepEqual(ts.technitiumProblems(1, "D", off(59), now.getTime()), []);
assert.deepEqual(ts.technitiumProblems(1, "D", off(61), now.getTime()).map((p) => [p.key, p.severity]), [["technitium-blocking:1", "warning"]]);
assert.deepEqual(ts.technitiumProblems(1, "D", off(600, 0), now.getTime()), [], "no block lists: off is how it is");
});
test("block lists whose update was due more than six hours ago are a warning; one not yet due, one with no time said and none set up are not", () => {
const lists = (nextUpdate: string | null, count = 2) => stored({ settings: { ...read().settings, blockLists: { count, intervalHours: 24, nextUpdate } } });
assert.equal(ts.blockListsOverdueMs(lists(iso(now.getTime() - 5 * HOUR)), now.getTime()), null);
assert.equal(ts.blockListsOverdueMs(lists(iso(now.getTime() - 10 * HOUR)), now.getTime()), 10 * HOUR);
assert.equal(ts.blockListsOverdueMs(lists(null), now.getTime()), null);
assert.equal(ts.blockListsOverdueMs(lists(iso(now.getTime() - 10 * HOUR), 0), now.getTime()), null);
const [p] = ts.technitiumProblems(1, "D", lists(iso(now.getTime() - 30 * HOUR)), now.getTime());
assert.deepEqual([p.key, p.severity], ["technitium-lists:1", "warning"]);
assert.match(p.message, /due for an update 30 hours ago/);
});
test("an expired secondary zone is critical and says it no longer answers; zones that only cannot sync are a warning; each is one alert that names the first few", () => {
const sync = ts.technitiumProblems(1, "D", stored({ zones: { total: 5, disabled: 0, issues: [{ name: "a.lan", problem: "sync failed" }] } }), now.getTime());
assert.deepEqual(sync.map((p) => [p.key, p.severity]), [["technitium-zones:1", "warning"]]);
assert.match(sync[0].message, /1 zone has a problem — a\.lan \(sync failed\)$/);
const many = ts.technitiumProblems(
1,
"D",
stored({ zones: { total: 9, disabled: 0, issues: [{ name: "a.lan", problem: "expired" }, { name: "b.lan", problem: "sync failed" }, { name: "c.lan", problem: "sync failed" }, { name: "d.lan", problem: "sync failed" }] } }),
now.getTime(),
);
assert.deepEqual(many.map((p) => [p.key, p.severity]), [["technitium-zones:1", "critical"]]);
assert.match(many[0].message, /4 zones have a problem — a\.lan \(expired\), b\.lan \(sync failed\), c\.lan \(sync failed\) and 1 more \(an expired secondary zone no longer answers\)/);
});
test("a Technitium with nothing wrong says nothing; a zones list that could not be read says nothing either", () => {
assert.deepEqual(ts.technitiumProblems(1, "D", stored(), now.getTime()), []);
assert.deepEqual(ts.technitiumProblems(1, "D", stored({ zones: null }), now.getTime()), []);
});
});
describe("what Technitium has stored", () => {
let id = 0;
before(async () => {
id = (await db.insert(integrations).values({ type: "technitium", name: "Stored DNS", baseUrl: "http://stored", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
});
const row = async () => (await db.select().from(technitiumState).where(eq(technitiumState.integrationId, id)))[0];
after(async () => {
await ts.forgetTechnitium(id);
await db.delete(integrations).where(eq(integrations.id, id));
});
test("the state is replaced at each read, carrying the clocks between them; what could not be read is stored as not read", async () => {
const t0 = new Date();
const down = read({ blockingEnabled: false, probe: { ok: false, ms: null, error: "no answer", name: "example.com", host: "dns.lan" }, stats: null, zones: null, dhcp: null });
await ts.storeRead(id, down, t0);
await ts.storeRead(id, down, new Date(t0.getTime() + 5 * MIN));
const r1 = await row();
assert.deepEqual([r1.blockingOffSince, r1.probeFailSince], [t0.toISOString(), t0.toISOString()]);
assert.deepEqual([r1.stats, r1.zones, r1.dhcp], [null, null, null]);
await ts.storeRead(id, read(), new Date(t0.getTime() + 10 * MIN));
const r2 = await row();
assert.deepEqual([r2.blockingOffSince, r2.probeFailSince, ts.storedOf(r2).stats?.queries], [null, null, 1000]);
});
test("a read that failed is said, and what was stored is left alone", async () => {
const ok = await ts.syncTechnitium(id, new Date(), async () => read({ version: "kept" }));
assert.equal(ok.ok, true);
const failed = await ts.syncTechnitium(id, new Date(), async () => {
throw new Error("connection refused");
});
assert.deepEqual([failed.ok, failed.error], [false, "connection refused"]);
assert.equal(failed.at, ok.at);
assert.equal((await row()).version, "kept");
assert.equal(ts.isTechnitiumFresh((await ts.technitiumSyncStatuses())[id], Date.now()), false);
});
test("an integration of another kind is not read", async () => {
const other = (await db.insert(integrations).values({ type: "adguard", name: "Not Technitium", baseUrl: "http://x", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
const status = await ts.syncTechnitium(other, new Date(), async () => read());
assert.deepEqual([status.ok, status.error], [false, "not a Technitium integration"]);
await db.delete(integrations).where(eq(integrations.id, other));
});
});
describe("the cluster: reading it, carrying it, judging it", () => {
const MINUTE = MIN;
const t = iso;
const NOW = Date.parse("2026-11-01T12:00:00Z");
const node = (over: Partial<import("../src/integrations/technitium/adapter.js").TechnitiumClusterNode> = {}): import("../src/integrations/technitium/adapter.js").TechnitiumClusterNode => ({ id: 1, name: "dns1", type: "Primary", state: "Connected", url: null, version: "15.6", lastSeen: null, ipAddresses: [], ...over });
const info = (nodes: ReturnType<typeof node>[], over: Partial<import("../src/integrations/technitium/adapter.js").TechnitiumCluster> = {}): import("../src/integrations/technitium/adapter.js").TechnitiumCluster => ({ domain: "example.com", thisNode: "dns2", heartbeatSeconds: 30, configRefreshSeconds: 900, configLastSynced: null, nodes, ...over });
const cluster = (i: ReturnType<typeof info> | null, over: Partial<import("../src/services/technitiumSync.js").StoredCluster> = {}): import("../src/services/technitiumSync.js").StoredCluster => ({ info: i, note: null, unreachableSince: {}, ...over });
describe("parsing what Technitium says", () => {
test("a server that is not in a cluster, or says nonsense, has none", () => {
assert.equal(tn.parseCluster({ clusterInitialized: false, dnsServerDomain: "x", version: "15.6" }), null);
for (const junk of [null, undefined, "x", [], {}, { clusterInitialized: "yes" }]) assert.equal(tn.parseCluster(junk), null, JSON.stringify(junk));
});
test("the nodes come primary first and then by name; a node with no name is left out; an address may be one or many, and never twice", () => {
const c = tn.parseCluster({ clusterInitialized: true, clusterNodes: [{ name: "b", type: "Secondary", state: "Connected", ipAddress: "10.0.0.2", ipAddresses: ["10.0.0.2", "10.0.0.9"] }, { type: "Secondary" }, { name: "a", type: "Secondary", state: "Self" }, { name: "z", type: "Primary", state: "Connected" }] })!;
assert.deepEqual(c.nodes.map((n) => n.name), ["z", "a", "b"]);
assert.deepEqual(c.nodes[2].ipAddresses, ["10.0.0.2", "10.0.0.9"]);
});
test("a moment is read as Technitium writes it, and the year 1 it writes for never is none", () => {
const c = tn.parseCluster({ clusterInitialized: true, configLastSynced: "2026-09-26T12:30:16.1234567Z", clusterNodes: [{ name: "a", lastSeen: "0001-01-01T00:00:00" }, { name: "b", lastSeen: "2026-09-26T12:30:16Z" }] })!;
assert.equal(c.configLastSynced, "2026-09-26T12:30:16.123Z");
assert.deepEqual(c.nodes.map((n) => [n.name, n.lastSeen]), [["a", null], ["b", "2026-09-26T12:30:16.000Z"]]);
});
test("what a node leaves out is unknown, not an error", () => {
const c = tn.parseCluster({ clusterInitialized: true, clusterNodes: [{ name: "a" }] })!;
assert.deepEqual([c.nodes[0].type, c.nodes[0].state, c.nodes[0].id, c.nodes[0].version, c.domain, c.configLastSynced], ["Unknown", "Unknown", null, null, null, null]);
});
});
describe("carrying it between reads", () => {
const read = (i: ReturnType<typeof info> | null, note: string | null = null, denied = false) => ({ info: i, note, denied });
const down = info([node({ id: 3, name: "dns3", type: "Secondary", state: "Unreachable" })]);
test("a node first seen unreachable starts its clock now, keeps it while it stays so, and loses it when it comes back", () => {
const first = ts.carryCluster(read(down), null, new Date(NOW))!;
assert.deepEqual(first.unreachableSince, { "3": t(NOW) });
const later = ts.carryCluster(read(down), first, new Date(NOW + 5 * MINUTE))!;
assert.deepEqual(later.unreachableSince, { "3": t(NOW) });
const back = ts.carryCluster(read(info([node({ id: 3, name: "dns3", type: "Secondary" })])), later, new Date(NOW + 6 * MINUTE))!;
assert.deepEqual(back.unreachableSince, {});
});
test("a node with no id is known by its name", () => {
const c = ts.carryCluster(read(info([node({ id: null, name: "dnsX", state: "Unreachable" })])), null, new Date(NOW))!;
assert.deepEqual(Object.keys(c.unreachableSince), ["dnsX"]);
});
test("a read that failed this time keeps what was known and the clocks, and says why; a refusal does not keep it", () => {
const before = ts.carryCluster(read(down), null, new Date(NOW))!;
const failed = ts.carryCluster(read(null, "boom"), before, new Date(NOW + 4 * MINUTE))!;
assert.deepEqual([failed.info?.nodes.length, failed.note, failed.unreachableSince], [1, "boom", { "3": t(NOW) }]);
const refused = ts.carryCluster(read(null, "not allowed", true), before, new Date(NOW + 4 * MINUTE))!;
assert.deepEqual([refused.info, refused.note], [null, "not allowed"]);
});
test("a read made before the cluster was asked about leaves what is stored as it is", () => {
const before = cluster(down);
assert.equal(ts.carryCluster(undefined, before, new Date(NOW)), before);
assert.equal(ts.carryCluster(undefined, null, new Date(NOW)), null);
});
});
describe("what is wrong", () => {
const primaryDown = (extra: Partial<ReturnType<typeof node>> = {}) => node({ id: 1, name: "dns1", type: "Primary", state: "Unreachable", ...extra });
const secondaryDown = (extra: Partial<ReturnType<typeof node>> = {}) => node({ id: 3, name: "dns3", type: "Secondary", state: "Unreachable", ...extra });
const self = (extra: Partial<ReturnType<typeof node>> = {}) => node({ id: 2, name: "dns2", type: "Secondary", state: "Self", ...extra });
const problems = (c: ReturnType<typeof cluster> | null, now = NOW) => ts.clusterProblems(7, "Home DNS", c, now);
test("nothing in a cluster that is well, in none, never asked about, or that could not be read", () => {
assert.deepEqual(problems(cluster(info([node(), self()]))), []);
assert.deepEqual(problems(null), []);
assert.deepEqual(problems(cluster(null)), []);
assert.deepEqual(problems(cluster(info([secondaryDown()]), { note: "boom", unreachableSince: { "3": t(NOW - HOUR) } })), []);
});
test("a node unreachable for ten minutes by this app's clock is an alert; a blip is not", () => {
assert.deepEqual(problems(cluster(info([secondaryDown()]), { unreachableSince: { "3": t(NOW - 9 * MINUTE) } })), []);
const p = problems(cluster(info([secondaryDown()]), { unreachableSince: { "3": t(NOW - 12 * MINUTE) } }));
assert.deepEqual(p.map((x) => [x.key, x.severity]), [["technitium-node:7:3", "warning"]]);
assert.match(p[0].message, /Home DNS: the cluster's secondary node dns3 has been unreachable for 12 minutes — one node fewer to answer/);
});
test("the primary being down is critical, and says what it costs", () => {
const p = problems(cluster(info([primaryDown()]), { unreachableSince: { "1": t(NOW - 30 * MINUTE) } }));
assert.deepEqual(p.map((x) => [x.key, x.severity]), [["technitium-node:7:1", "critical"]]);
assert.match(p[0].message, /primary node dns1 has been unreachable for 30 minutes — the other nodes can take no configuration changes/);
});
test("when the node says when it was last seen, that is what counts; no clock at all says nothing yet", () => {
assert.equal(problems(cluster(info([secondaryDown({ lastSeen: t(NOW - 3 * 60 * MINUTE) })]), { unreachableSince: { "3": t(NOW - MINUTE) } })).length, 1);
assert.equal(problems(cluster(info([secondaryDown()]))).length, 0);
});
test("each node that is down is its own alert", () => {
const c = cluster(info([primaryDown(), secondaryDown()]), { unreachableSince: { "1": t(NOW - HOUR), "3": t(NOW - HOUR) } });
assert.deepEqual(problems(c).map((x) => x.key).sort(), ["technitium-node:7:1", "technitium-node:7:3"]);
});
test("a secondary that has not taken the configuration for three of its periods (and half an hour) is no longer a copy", () => {
const synced = (ago: number, refresh = 900) => cluster(info([self(), node()], { configLastSynced: t(NOW - ago), configRefreshSeconds: refresh }));
assert.deepEqual(problems(synced(40 * MINUTE)), [], "three periods of 15 minutes is 45");
const p = problems(synced(50 * MINUTE));
assert.deepEqual(p.map((x) => [x.key, x.severity]), [["technitium-config:7", "warning"]]);
assert.match(p[0].message, /has not taken the configuration from the primary for 50 minutes/);
assert.deepEqual(problems(synced(25 * MINUTE, 60)), [], "a short period still allows half an hour");
assert.equal(problems(synced(40 * MINUTE, 60)).length, 1, "past half an hour and three periods of a minute");
assert.equal(problems(synced(3 * HOUR, 3600)).length, 0, "three periods of an hour is three hours");
});
test("the primary takes no configuration, so it has nothing to be late with; and a cluster that does not say when says nothing", () => {
assert.deepEqual(problems(cluster(info([node({ id: 1, name: "dns1", type: "Primary", state: "Self" })], { configLastSynced: t(NOW - 5 * HOUR) }))), []);
assert.deepEqual(problems(cluster(info([self()]))), []);
});
});
describe("through the stored state, the alerts, maintenance and /metrics", () => {
let id = 0;
before(async () => {
id = (await db.insert(integrations).values({ type: "technitium", name: "Cluster DNS", baseUrl: "http://technitium-c", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
});
const readWith = (i: ReturnType<typeof info>) => ({ ...read(), cluster: { info: i, note: null, denied: false } });
const stored = async () => ts.storedOf((await db.select().from(technitiumState).where(eq(technitiumState.integrationId, id)))[0]);
test("a read stores the cluster, the clock of a node that is down carries from read to read, and it is judged from what is stored", async () => {
const t0 = new Date(Date.now() - 20 * MINUTE);
const c = info([node({ id: 1, name: "dns1", type: "Primary", state: "Unreachable" }), node({ id: 2, name: "dns2", type: "Secondary", state: "Self" })], { configLastSynced: t(Date.now() - 2 * 60 * MINUTE) });
await ts.storeRead(id, readWith(c), t0);
await ts.storeRead(id, readWith(c), new Date());
const s = await stored();
assert.deepEqual([s.cluster?.info?.nodes.length, s.cluster?.unreachableSince], [2, { "1": t0.toISOString() }]);
assert.deepEqual(ts.technitiumProblems(id, "Cluster DNS", s, Date.now()).map((x) => x.key).sort(), [`technitium-config:${id}`, `technitium-node:${id}:1`]);
});
test("the Alerts page files them under Services and Monitoring, and maintenance on the integration holds them", async () => {
await setInternalFlag("technitiumSync", JSON.stringify({ [id]: { at: new Date().toISOString(), ok: true, error: null } }));
invalidateAlertsCache();
const report = await getAlerts(true);
const find = (key: string) => report.alerts.find((x) => x.id.endsWith(key));
const node1 = find(`technitium-node:${id}:1`);
assert.ok(node1, "the node alert is raised");
assert.deepEqual([node1!.category, node1!.severity, node1!.source, node1!.link, node1!.target?.type], ["services", "critical", "Technitium DNS", "/technitium", "integration"]);
assert.equal(find(`technitium-config:${id}`)?.category, "monitoring");
assert.equal(subjectOfConditionKey(`technitium-node:${id}:1`), `integration:${id}`);
assert.equal(subjectOfConditionKey(`technitium-config:${id}`), `integration:${id}`);
});
test("/metrics has how many nodes there are, how many cannot be reached, and when this one last synced", async () => {
const text = await buildMetrics(new Date());
assert.match(text, /homelab_technitium_cluster_nodes\{name="Cluster DNS"\} 2/);
assert.match(text, /homelab_technitium_cluster_nodes_unreachable\{name="Cluster DNS"\} 1/);
assert.match(text, /homelab_technitium_cluster_config_synced_timestamp_seconds\{name="Cluster DNS"\} 1\d{9}/);
});
});
});
describe("the health pass, the Alerts page, the page's route and /metrics", () => {
let tId = 0;
let app: Server;
let base = "";
const statusAt = (ms: number) => setInternalFlag("technitiumSync", JSON.stringify({ [tId]: { at: new Date(ms).toISOString(), ok: true, error: null } }));
const fresh = () => statusAt(Date.now());
const stale = () => statusAt(Date.now() - 30 * MIN);
before(async () => {
await db.insert(users).values([{ oidcSub: "viewer", name: "Vic", role: "viewer" }]);
tId = (await db.insert(integrations).values({ type: "technitium", name: "Home DNS 2", baseUrl: "http://technitium", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
const t0 = new Date(Date.now() - 3 * HOUR);
const bad = read({
blockingEnabled: false,
settings: { blockLists: { count: 2, intervalHours: 24, nextUpdate: iso(Date.now() - 10 * HOUR) }, cacheMaximumEntries: 10000, recursion: null, dnssecValidation: null },
zones: { total: 3, disabled: 0, issues: [{ name: "lab.lan", problem: "expired" }] },
probe: { ok: false, ms: null, error: "no answer in 3 s", name: "example.com", host: "dns.lan" },
});
await ts.storeRead(tId, bad, t0);
await ts.storeRead(tId, bad, new Date());
await fresh();
const a = express();
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "viewer" } };
next();
});
a.use("/api/technitium", technitiumRouter);
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/technitium`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("the health pass judges it from what is stored, and holds it when the last read is old; maintenance on the integration silences each", async () => {
let { snapshot, held } = await collectSnapshot();
assert.deepEqual(snapshot.technitium?.map((x) => x.integrationId), [tId]);
const list = evaluateHealth(snapshot, { serverOfflineMinutes: 60, diskUsagePercent: 90 }, Date.now(), { skipServers: true });
const mine = list.filter((x) => x.key.startsWith("technitium-")).map((x) => `${x.key}=${x.severity}`).sort();
assert.deepEqual(mine, [`technitium-blocking:${tId}=warning`, `technitium-dns:${tId}=critical`, `technitium-lists:${tId}=warning`, `technitium-zones:${tId}=critical`].sort());
assert.equal(list.find((x) => x.key === `technitium-dns:${tId}`)!.source, `technitium:${tId}`);
for (const k of ["dns", "blocking", "lists", "zones"]) assert.equal(subjectOfConditionKey(`technitium-${k}:${tId}`), `integration:${tId}`, k);
await stale();
({ snapshot, held } = await collectSnapshot());
assert.deepEqual([snapshot.technitium ?? [], held.has(`technitium:${tId}`)], [[], true]);
await fresh();
});
test("the Alerts page says where to look: DNS and zones under Services, blocking and block lists under Monitoring", async () => {
invalidateAlertsCache();
const report = await getAlerts(true);
const find = (key: string) => report.alerts.find((x) => x.id.endsWith(key))!;
assert.deepEqual([find(`technitium-dns:${tId}`).category, find(`technitium-dns:${tId}`).source, find(`technitium-dns:${tId}`).link, find(`technitium-dns:${tId}`).target?.type], ["services", "Technitium DNS", "/technitium", "integration"]);
assert.equal(find(`technitium-zones:${tId}`).category, "services");
assert.deepEqual([find(`technitium-blocking:${tId}`).category, find(`technitium-lists:${tId}`).category], ["monitoring", "monitoring"]);
});
test("the page: the DNS question, blocking, the statistics, the zones and what is wrong; an old reading says nothing is wrong", async () => {
const body = (await (await fetch(base)).json()) as { instances: { id: number; fresh: boolean; problems: unknown[]; state: { probe: { ok: boolean }; blockingEnabled: boolean; blockingOffSince: string | null; stats: { queries: number }; zones: { issues: unknown[] }; blockListsOverdueMs: number | null; settings: { blockLists: { count: number } } } }[] };
const t = body.instances.find((x) => x.id === tId)!;
assert.deepEqual([t.fresh, t.problems.length, t.state.probe.ok, t.state.blockingEnabled, t.state.blockingOffSince !== null, t.state.stats.queries, t.state.zones.issues.length, t.state.settings.blockLists.count], [true, 4, false, false, true, 1000, 1, 2]);
assert.ok((t.state.blockListsOverdueMs ?? 0) >= 9 * HOUR);
await stale();
const old = (await (await fetch(base)).json()) as typeof body;
assert.deepEqual(old.instances.find((x) => x.id === tId)!.problems, []);
await fresh();
});
test("/metrics has DNS up, blocking, how long it has run, the queries, the zones with a problem — only while the reading is recent", async () => {
let text = await buildMetrics(new Date());
assert.match(text, /homelab_technitium_dns_up\{name="Home DNS 2"\} 0/);
assert.doesNotMatch(text, /homelab_technitium_dns_probe_seconds/, "no answer, no time");
assert.match(text, /homelab_technitium_blocking_enabled\{name="Home DNS 2"\} 0/);
assert.match(text, /homelab_technitium_block_lists_overdue\{name="Home DNS 2"\} 1/);
assert.match(text, /homelab_technitium_queries\{name="Home DNS 2"\} 1000/);
assert.match(text, /homelab_technitium_blocked\{name="Home DNS 2"\} 100/);
assert.match(text, /homelab_technitium_cache_entries\{name="Home DNS 2"\} 4000/);
assert.match(text, /homelab_technitium_zone_problems\{name="Home DNS 2"\} 1/);
assert.match(text, /homelab_technitium_dhcp_leases\{name="Home DNS 2"\} 12/);
assert.match(text, /homelab_technitium_uptime_seconds\{name="Home DNS 2"\} 4\d{5}/);
await stale();
text = await buildMetrics(new Date());
assert.doesNotMatch(text, /homelab_technitium_/);
await fresh();
});
test("taking the integration away takes what was read with it", async () => {
await ts.forgetTechnitium(tId);
assert.equal((await ts.technitiumSyncStatuses())[tId], undefined);
await db.delete(integrations).where(eq(integrations.id, tId));
assert.deepEqual(await db.select().from(technitiumState).where(eq(technitiumState.integrationId, tId)), []);
});
});