Add a Technitium DNS Server integration for its statistics and health

A new integration type (Network, next to AdGuard Home) reads Technitium's API
every two minutes with a non-expiring API token in the Authorization header:
version and uptime, whether blocking is on, block lists and their next update,
the last day's queries and how they ended, cache and zone counts, the top
clients and names, zone health (expired or unsynced secondary zones), DHCP
leases — and puts one real DNS question to it over UDP. A Technitium page
shows it; alerts: DNS not answering (critical), blocking left off, block lists
overdue, zones expired or not syncing; /metrics gets homelab_technitium_*.
Nothing is changed on the server. Technitium's API has no CPU, memory or disk
figures; the page says a server agent covers that. New table technitium_state
(migration 0081).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 21:48:46 +01:00
1 parent e4cd01e9ba
commit 312093d3f7
24 files changed
+10189 -7

No files matched your search

+531
View File
@@ -0,0 +1,531 @@
/**
* 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;
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: [{}, {}] });
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 }];
};
test("a read puts the token in the Authorization header, asks the five 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/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("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 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)), []);
});
});