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:
1 parent
e4cd01e9ba
commit
312093d3f7
24 files changed
+10189
-7
No files matched your search
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE `technitium_state` (
|
||||
`integration_id` integer PRIMARY KEY NOT NULL,
|
||||
`version` text,
|
||||
`started_at` text,
|
||||
`dns_port` integer DEFAULT 53 NOT NULL,
|
||||
`blocking_enabled` integer DEFAULT true NOT NULL,
|
||||
`blocking_off_since` text,
|
||||
`settings` text NOT NULL,
|
||||
`stats` text,
|
||||
`zones` text,
|
||||
`dhcp` text,
|
||||
`probe` text,
|
||||
`probe_fail_since` text,
|
||||
`updated_at` text NOT NULL,
|
||||
FOREIGN KEY (`integration_id`) REFERENCES `integrations`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -568,6 +568,13 @@
|
||||
"when": 1793482370383,
|
||||
"tag": "0080_lazy_iron_fist",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 81,
|
||||
"version": "6",
|
||||
"when": 1793564076431,
|
||||
"tag": "0081_powerful_thing",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -72,6 +72,7 @@ import { fragnetRouter } from "./routes/fragnet.js";
|
||||
import { arrRouter } from "./routes/arr.js";
|
||||
import { wallRouter } from "./routes/wall.js";
|
||||
import { adguardRouter } from "./routes/adguard.js";
|
||||
import { technitiumRouter } from "./routes/technitium.js";
|
||||
import { grafanaRouter } from "./routes/grafana.js";
|
||||
import { versionsRouter } from "./routes/versions.js";
|
||||
import { portPresetsRouter } from "./routes/portPresets.js";
|
||||
@@ -225,6 +226,7 @@ export function createApp() {
|
||||
app.use("/api/arr", arrRouter);
|
||||
app.use("/api/wall", wallRouter);
|
||||
app.use("/api/adguard", adguardRouter);
|
||||
app.use("/api/technitium", technitiumRouter);
|
||||
app.use("/api/grafana", grafanaRouter);
|
||||
app.use("/api/versions", versionsRouter);
|
||||
app.use("/api/port-presets", portPresetsRouter);
|
||||
|
||||
@@ -571,6 +571,7 @@ export const integrationTypes = [
|
||||
"radarr",
|
||||
"prowlarr",
|
||||
"adguard",
|
||||
"technitium",
|
||||
"grafana",
|
||||
"lidarr",
|
||||
"readarr",
|
||||
@@ -1382,6 +1383,29 @@ export const adguardState = sqliteTable("adguard_state", {
|
||||
updatedAt: text("updated_at").notNull(), // ISO
|
||||
});
|
||||
|
||||
// ─── Technitium DNS Server ──────────────────────────────────────────────────
|
||||
|
||||
// How a Technitium DNS Server (an integration of type "technitium") is right now, one row each, replaced at every read: its version and when it started, whether blocking is on, its settings that
|
||||
// matter (block lists and when they are next updated, the cache size, recursion), the statistics of the last day, the health of its zones, its DHCP leases and the result of a real DNS question
|
||||
// put to it — plus since when blocking has been off and the question unanswered, which only this app can know. A column that is null could not be read. Read by services/technitiumSync.ts.
|
||||
export const technitiumState = sqliteTable("technitium_state", {
|
||||
integrationId: integer("integration_id")
|
||||
.primaryKey()
|
||||
.references(() => integrations.id, { onDelete: "cascade" }),
|
||||
version: text("version"),
|
||||
startedAt: text("started_at"), // ISO: when the DNS server last started; null when it did not say
|
||||
dnsPort: integer("dns_port").notNull().default(53),
|
||||
blockingEnabled: integer("blocking_enabled", { mode: "boolean" }).notNull().default(true),
|
||||
blockingOffSince: text("blocking_off_since"), // ISO: the first read that showed blocking off; null while it is on
|
||||
settings: text("settings").notNull(), // JSON: { blockLists: { count, intervalHours, nextUpdate }, cacheMaximumEntries, recursion, dnssecValidation }
|
||||
stats: text("stats"), // JSON: the last day's queries and how they ended, cache and zone counts, top clients and names; null: could not be read
|
||||
zones: text("zones"), // JSON: { total, disabled, issues: [{ name, problem }] }; null: could not be read
|
||||
dhcp: text("dhcp"), // JSON: { scopes, enabledScopes, leases }; null: no DHCP server, or could not be read
|
||||
probe: text("probe"), // JSON: the DNS question — { ok, ms, error, name, host }
|
||||
probeFailSince: text("probe_fail_since"), // ISO: the first read in which the question went unanswered; null while it is answered
|
||||
updatedAt: text("updated_at").notNull(), // ISO
|
||||
});
|
||||
|
||||
// ─── Grafana ────────────────────────────────────────────────────────────────
|
||||
|
||||
// How a Grafana (an integration of type "grafana") is right now, one row each, replaced at every read: the alert rules that are firing, pending or cannot be evaluated (and how many there are), and
|
||||
|
||||
@@ -43,6 +43,7 @@ import { initSpeedtestSync } from "./services/speedtestSync.js";
|
||||
import { initFragnetSync } from "./services/fragnetSync.js";
|
||||
import { initArrSync } from "./services/arrSync.js";
|
||||
import { initAdguardSync } from "./services/adguardSync.js";
|
||||
import { initTechnitiumSync } from "./services/technitiumSync.js";
|
||||
import { initGrafanaSync } from "./services/grafanaSync.js";
|
||||
import { initVersionCheck } from "./services/appVersions.js";
|
||||
import { backfillMetricRollups } from "./services/serverMetrics.js";
|
||||
@@ -109,6 +110,7 @@ initSpeedtestSync();
|
||||
initFragnetSync();
|
||||
initArrSync();
|
||||
initAdguardSync();
|
||||
initTechnitiumSync();
|
||||
initGrafanaSync();
|
||||
initVersionCheck();
|
||||
// The hourly and daily figures are built from what is already kept, once, the first time after they were added (in the background: nothing waits for it).
|
||||
|
||||
@@ -147,6 +147,13 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
|
||||
{ key: "probeDomain", label: "Name to test DNS with (optional)", secret: false, optional: true, placeholder: "example.com" },
|
||||
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
||||
],
|
||||
technitium: [
|
||||
{ key: "url", label: "Technitium web console URL", secret: false, placeholder: "http://dns.example.lan:5380" },
|
||||
{ key: "token", label: "API token", secret: true, type: "password", placeholder: "Administration → Sessions → Create Token (a user who may view the dashboard, settings and zones)" },
|
||||
{ key: "dnsHost", label: "DNS server address (optional)", secret: false, optional: true, placeholder: "the host of the URL — only if its DNS server is somewhere else" },
|
||||
{ key: "probeDomain", label: "Name to test DNS with (optional)", secret: false, optional: true, placeholder: "example.com" },
|
||||
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
|
||||
],
|
||||
grafana: [
|
||||
{ key: "url", label: "Grafana URL", secret: false, placeholder: "http://grafana.example.lan:3000" },
|
||||
{ key: "token", label: "Service account token", secret: true, type: "password", placeholder: "Administration → Service accounts → add a token (role Viewer)" },
|
||||
|
||||
@@ -26,6 +26,7 @@ import { createSpeedtestAdapter } from "./speedtest/adapter.js";
|
||||
import { createFragnetAdapter } from "./fragnet/adapter.js";
|
||||
import { createArrAdapter } from "./arr/adapter.js";
|
||||
import { createAdguardAdapter } from "./adguard/adapter.js";
|
||||
import { createTechnitiumAdapter } from "./technitium/adapter.js";
|
||||
import { createGrafanaAdapter } from "./grafana/adapter.js";
|
||||
import { createNextcloudAdapter } from "./nextcloud/adapter.js";
|
||||
|
||||
@@ -96,6 +97,8 @@ export function createIntegrationAdapter(type: IntegrationType, config: Integrat
|
||||
return createArrAdapter(type, config as any);
|
||||
case "adguard":
|
||||
return createAdguardAdapter(config as any);
|
||||
case "technitium":
|
||||
return createTechnitiumAdapter(config as any);
|
||||
case "grafana":
|
||||
return createGrafanaAdapter(config as any);
|
||||
case "netbox":
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
/**
|
||||
* Technitium DNS Server adapter — its health and statistics. (The adapter in dns/adapters/technitium.ts is the one for zones and records; this one only reads.) Config: url (its web console,
|
||||
* port 5380 by default), token (a non-expiring API token: Administration → Sessions → Create Token, for a user who may view the dashboard, the settings and the zones), optionally dnsHost
|
||||
* (where its DNS server is, when that is not the host of the web address), probeDomain (the name a test question is asked about; example.com unless told) and insecure.
|
||||
*
|
||||
* Reading only: what the server is and since when it has run, whether blocking is on and when its block lists are next updated (`/api/settings/get`), what it has done in the last day — queries and
|
||||
* how each ended, cache and zone counts, the clients and names asked about most (`/api/dashboard/stats/get`), the health of its zones — a secondary zone that has expired or cannot sync
|
||||
* (`/api/zones/list`), its DHCP scopes and leases (`/api/dhcp/…`) — and one real DNS question put to its DNS server over UDP (see ../adguard/dnsProbe.ts), because the console can be up while DNS is
|
||||
* not. Technitium's API says nothing about the CPU, memory or disk of the machine it runs on: that is what a server agent on that machine reports. Nothing is changed.
|
||||
*
|
||||
* Endpoints and fields are from Technitium's published API documentation (APIDOCS.md) and have not been checked against a live install here; every field is read defensively. The token goes in an
|
||||
* `Authorization: Bearer` header, which is what version 15.0 and later require.
|
||||
*/
|
||||
import { requestJson } from "../httpJson.js";
|
||||
import { withDiagLogging } from "../../services/diagLog.js";
|
||||
import { probeDns, type ProbeResult } from "../adguard/dnsProbe.js";
|
||||
|
||||
export interface TechnitiumConfig {
|
||||
url: string;
|
||||
token: string;
|
||||
insecure?: boolean;
|
||||
dnsHost?: string;
|
||||
probeDomain?: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_PROBE_DOMAIN = "example.com";
|
||||
|
||||
export interface TechnitiumCounted {
|
||||
name: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface TechnitiumStats {
|
||||
/** What Technitium's statistics cover: "LastDay". */
|
||||
period: string;
|
||||
queries: number;
|
||||
noError: number;
|
||||
serverFailure: number;
|
||||
nxDomain: number;
|
||||
refused: number;
|
||||
authoritative: number;
|
||||
recursive: number;
|
||||
cached: number;
|
||||
blocked: number;
|
||||
dropped: number;
|
||||
clients: number;
|
||||
/** Counts as the server has them now (not over the period). */
|
||||
zones: number | null;
|
||||
cachedEntries: number | null;
|
||||
allowedZones: number | null;
|
||||
blockedZones: number | null;
|
||||
allowListZones: number | null;
|
||||
blockListZones: number | null;
|
||||
/** Shares of the queries, in percent; null with no queries. */
|
||||
blockedPercent: number | null;
|
||||
cachedPercent: number | null;
|
||||
failurePercent: number | null;
|
||||
topClients: TechnitiumCounted[];
|
||||
topDomains: TechnitiumCounted[];
|
||||
topBlocked: TechnitiumCounted[];
|
||||
}
|
||||
|
||||
export interface TechnitiumSettings {
|
||||
version: string | null;
|
||||
/** ISO; null when it did not say. */
|
||||
startedAt: string | null;
|
||||
dnsPort: number;
|
||||
blockingEnabled: boolean;
|
||||
blockLists: { count: number; intervalHours: number | null; nextUpdate: string | null };
|
||||
cacheMaximumEntries: number | null;
|
||||
recursion: string | null;
|
||||
dnssecValidation: boolean | null;
|
||||
}
|
||||
|
||||
export interface TechnitiumZoneIssue {
|
||||
name: string;
|
||||
problem: "expired" | "sync failed";
|
||||
}
|
||||
|
||||
export interface TechnitiumZones {
|
||||
total: number;
|
||||
disabled: number;
|
||||
issues: TechnitiumZoneIssue[];
|
||||
}
|
||||
|
||||
export interface TechnitiumDhcp {
|
||||
scopes: number;
|
||||
enabledScopes: number;
|
||||
leases: number;
|
||||
}
|
||||
|
||||
export interface TechnitiumRead {
|
||||
version: string | null;
|
||||
startedAt: string | null;
|
||||
dnsPort: number;
|
||||
blockingEnabled: boolean;
|
||||
settings: Pick<TechnitiumSettings, "blockLists" | "cacheMaximumEntries" | "recursion" | "dnssecValidation">;
|
||||
/** Null when the statistics could not be read. */
|
||||
stats: TechnitiumStats | null;
|
||||
/** Null when the zones could not be listed. */
|
||||
zones: TechnitiumZones | null;
|
||||
/** Null when there is no DHCP server to ask, or it could not be read. */
|
||||
dhcp: TechnitiumDhcp | null;
|
||||
/** The real DNS question: whether it was answered, how fast, and about what. */
|
||||
probe: ProbeResult & { name: string; host: string };
|
||||
}
|
||||
|
||||
export interface TechnitiumAdapter {
|
||||
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
|
||||
read(): Promise<TechnitiumRead>;
|
||||
}
|
||||
|
||||
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
|
||||
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
|
||||
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
|
||||
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
||||
/** A moment as Technitium writes it (up to seven fractional digits, which Date.parse does not always take) as ISO; null for none, or for the year 1 it writes for "never". */
|
||||
const isoOf = (v: unknown): string | null => {
|
||||
const s = str(v);
|
||||
if (!s) return null;
|
||||
const t = Date.parse(s.replace(/(\.\d{3})\d+/, "$1"));
|
||||
return Number.isFinite(t) && t > Date.UTC(2000, 0, 1) ? new Date(t).toISOString() : null;
|
||||
};
|
||||
const percent = (part: number, whole: number): number | null => (whole > 0 ? Math.round((part / whole) * 1000) / 10 : null);
|
||||
|
||||
/** Pure: `/api/settings/get`'s answer. */
|
||||
export function parseSettings(raw: unknown): TechnitiumSettings {
|
||||
const s = obj(raw);
|
||||
const port = arr(s.dnsServerLocalEndPoints)
|
||||
.map((e) => (typeof e === "string" ? /:(\d{1,5})$/.exec(e.trim()) : null))
|
||||
.find((m) => m !== null);
|
||||
const interval = num(s.blockListUpdateIntervalHours);
|
||||
return {
|
||||
version: str(s.version),
|
||||
startedAt: isoOf(s.uptimestamp),
|
||||
dnsPort: port ? Number(port[1]) : 53,
|
||||
blockingEnabled: s.enableBlocking !== false,
|
||||
blockLists: { count: arr(s.blockListUrls).filter((u) => str(u) !== null).length, intervalHours: interval !== null && interval > 0 ? interval : null, nextUpdate: isoOf(s.blockListNextUpdatedOn) },
|
||||
cacheMaximumEntries: num(s.cacheMaximumEntries),
|
||||
recursion: str(s.recursion),
|
||||
dnssecValidation: typeof s.dnssecValidation === "boolean" ? s.dnssecValidation : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Pure: the clients or names asked about most — `[{ name, hits }]`; a client may carry the name its address resolves to (`domain`). */
|
||||
export function parseTop(raw: unknown, limit = 10): TechnitiumCounted[] {
|
||||
const out: TechnitiumCounted[] = [];
|
||||
for (const item of arr(raw)) {
|
||||
const i = obj(item);
|
||||
const name = str(i.name);
|
||||
const hits = num(i.hits);
|
||||
if (name === null || hits === null) continue;
|
||||
const domain = str(i.domain);
|
||||
out.push({ name: domain && domain !== name ? `${name} (${domain})` : name, count: hits });
|
||||
}
|
||||
return out.sort((a, b) => b.count - a.count).slice(0, limit);
|
||||
}
|
||||
|
||||
/** Pure: `/api/dashboard/stats/get`'s `response`. No query count is not zero queries: it is "could not be read". */
|
||||
export function parseStats(raw: unknown, period = "LastDay"): TechnitiumStats | null {
|
||||
const r = obj(raw);
|
||||
const s = obj(r.stats);
|
||||
const queries = num(s.totalQueries);
|
||||
if (queries === null) return null;
|
||||
const n = (k: string) => num(s[k]) ?? 0;
|
||||
return {
|
||||
period,
|
||||
queries,
|
||||
noError: n("totalNoError"),
|
||||
serverFailure: n("totalServerFailure"),
|
||||
nxDomain: n("totalNxDomain"),
|
||||
refused: n("totalRefused"),
|
||||
authoritative: n("totalAuthoritative"),
|
||||
recursive: n("totalRecursive"),
|
||||
cached: n("totalCached"),
|
||||
blocked: n("totalBlocked"),
|
||||
dropped: n("totalDropped"),
|
||||
clients: n("totalClients"),
|
||||
zones: num(s.zones),
|
||||
cachedEntries: num(s.cachedEntries),
|
||||
allowedZones: num(s.allowedZones),
|
||||
blockedZones: num(s.blockedZones),
|
||||
allowListZones: num(s.allowListZones),
|
||||
blockListZones: num(s.blockListZones),
|
||||
blockedPercent: percent(n("totalBlocked"), queries),
|
||||
cachedPercent: percent(n("totalCached"), queries),
|
||||
failurePercent: percent(n("totalServerFailure"), queries),
|
||||
topClients: parseTop(r.topClients),
|
||||
topDomains: parseTop(r.topDomains),
|
||||
topBlocked: parseTop(r.topBlockedDomains),
|
||||
};
|
||||
}
|
||||
|
||||
/** Pure: `/api/zones/list`'s `response`. Internal zones are the server's own; a disabled zone is not judged. A secondary zone that has expired no longer answers; one that cannot sync is going stale. */
|
||||
export function parseZones(raw: unknown): TechnitiumZones | null {
|
||||
const r = obj(raw);
|
||||
if (!Array.isArray(r.zones)) return null;
|
||||
const zones = r.zones.map(obj).filter((z) => str(z.name) !== null && z.internal !== true);
|
||||
const issues: TechnitiumZoneIssue[] = [];
|
||||
for (const z of zones) {
|
||||
if (z.disabled === true) continue;
|
||||
if (z.isExpired === true) issues.push({ name: str(z.name)!, problem: "expired" });
|
||||
else if (z.syncFailed === true) issues.push({ name: str(z.name)!, problem: "sync failed" });
|
||||
}
|
||||
return { total: zones.length, disabled: zones.filter((z) => z.disabled === true).length, issues };
|
||||
}
|
||||
|
||||
/** Pure: the DHCP scopes (`/api/dhcp/scopes/list`) and how many leases there are (`/api/dhcp/leases/list`, null when not asked). Null when the scopes are not a list. */
|
||||
export function parseDhcp(scopesRaw: unknown, leasesRaw: unknown | null): TechnitiumDhcp | null {
|
||||
const s = obj(scopesRaw);
|
||||
if (!Array.isArray(s.scopes)) return null;
|
||||
return { scopes: s.scopes.length, enabledScopes: s.scopes.filter((x) => obj(x).enabled === true).length, leases: leasesRaw === null ? 0 : arr(obj(leasesRaw).leases).length };
|
||||
}
|
||||
|
||||
export function createTechnitiumAdapter(config: TechnitiumConfig): TechnitiumAdapter {
|
||||
const raw = String(config.url ?? "").trim().replace(/\/+$/, "");
|
||||
const insecure = config.insecure === true;
|
||||
const headers = { Authorization: `Bearer ${config.token}`, Accept: "application/json" };
|
||||
|
||||
/** One call; what is returned is its `response` (the answer is `{ status, response }`, and a session or token that is not accepted is a `status`, not an HTTP error). */
|
||||
async function get(path: string, params: Record<string, string> = {}): Promise<Record<string, unknown>> {
|
||||
const qs = new URLSearchParams(params).toString();
|
||||
const res = await requestJson(`${raw}${path}${qs ? `?${qs}` : ""}`, { headers, insecure });
|
||||
if (res.status === 401 || res.status === 403) throw new Error(`Technitium did not accept the token (HTTP ${res.status})`);
|
||||
if (res.status === 404) throw new Error("Technitium has no API at this address (HTTP 404) — check the address of its web console (port 5380 unless changed)");
|
||||
if (res.status < 200 || res.status >= 300) throw new Error(`Technitium error: HTTP ${res.status}`);
|
||||
if (res.json === null) throw new Error("Technitium answered with something that isn't JSON — is the address its own?");
|
||||
const body = obj(res.json);
|
||||
const status = str(body.status);
|
||||
if (status === "invalid-token") throw new Error("Technitium did not accept the token — make a non-expiring API token (Administration → Sessions → Create Token); a server older than 15.0 does not take it in the header");
|
||||
if (status === "error") throw new Error(`Technitium: ${str(body.errorMessage) ?? "an error"}`);
|
||||
if (status !== "ok") throw new Error(`Technitium answered with status "${status ?? "none"}"`);
|
||||
return obj(body.response);
|
||||
}
|
||||
|
||||
const soft = async <T>(run: () => Promise<T>): Promise<T | null> => {
|
||||
try {
|
||||
return await run();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
function dnsHostOf(): string {
|
||||
const given = str(config.dnsHost);
|
||||
if (given) return given.replace(/^\[|\]$/g, "");
|
||||
try {
|
||||
return new URL(raw).hostname.replace(/^\[|\]$/g, "");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
async function readDhcp(): Promise<TechnitiumDhcp | null> {
|
||||
const scopes = await get("/api/dhcp/scopes/list");
|
||||
const withoutLeases = parseDhcp(scopes, null);
|
||||
if (withoutLeases === null || withoutLeases.scopes === 0) return withoutLeases;
|
||||
return parseDhcp(scopes, await get("/api/dhcp/leases/list"));
|
||||
}
|
||||
|
||||
async function read(): Promise<TechnitiumRead> {
|
||||
// The settings must work: they say it is there and the token is accepted.
|
||||
const settings = parseSettings(await get("/api/settings/get"));
|
||||
const name = str(config.probeDomain) ?? DEFAULT_PROBE_DOMAIN;
|
||||
const host = dnsHostOf();
|
||||
const [stats, zones, dhcp, probe] = await Promise.all([
|
||||
soft(async () => parseStats(await get("/api/dashboard/stats/get", { type: "LastDay" }))),
|
||||
soft(async () => parseZones(await get("/api/zones/list", { pageNumber: "1", zonesPerPage: "1000" }))),
|
||||
soft(readDhcp),
|
||||
host ? probeDns(host, settings.dnsPort, name) : Promise.resolve({ ok: false, ms: null, error: "no address to ask" } as ProbeResult),
|
||||
]);
|
||||
return {
|
||||
version: settings.version,
|
||||
startedAt: settings.startedAt,
|
||||
dnsPort: settings.dnsPort,
|
||||
blockingEnabled: settings.blockingEnabled,
|
||||
settings: { blockLists: settings.blockLists, cacheMaximumEntries: settings.cacheMaximumEntries, recursion: settings.recursion, dnssecValidation: settings.dnssecValidation },
|
||||
stats,
|
||||
zones,
|
||||
dhcp,
|
||||
probe: { ...probe, name, host },
|
||||
};
|
||||
}
|
||||
|
||||
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
|
||||
const start = Date.now();
|
||||
try {
|
||||
await get("/api/settings/get");
|
||||
return { ok: true, latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
return withDiagLogging("technitium", { ping, read });
|
||||
}
|
||||
@@ -43,6 +43,7 @@ import { forgetFragnet, syncFragnet } from "../services/fragnetSync.js";
|
||||
import { forgetArr, syncArr } from "../services/arrSync.js";
|
||||
import { ARR_KINDS } from "../integrations/arr/adapter.js";
|
||||
import { forgetAdguard, syncAdguard } from "../services/adguardSync.js";
|
||||
import { forgetTechnitium, syncTechnitium } from "../services/technitiumSync.js";
|
||||
import { forgetGrafana, syncGrafana } from "../services/grafanaSync.js";
|
||||
import { forgetNextcloud, syncNextcloud } from "../services/nextcloudSync.js";
|
||||
import { dockerVulnSyncStatuses, findingsOf, forgetDockerVulns, imageAgeDays, imagesOf, isDockerVulnFresh, syncDockerVulns } from "../services/dockerVulnSync.js";
|
||||
@@ -160,6 +161,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res)
|
||||
if (type === "fragnet") void syncFragnet(created.id).then(() => invalidateAlertsCache());
|
||||
if ((ARR_KINDS as string[]).includes(type)) void syncArr(created.id).then(() => invalidateAlertsCache());
|
||||
if (type === "adguard") void syncAdguard(created.id).then(() => invalidateAlertsCache());
|
||||
if (type === "technitium") void syncTechnitium(created.id).then(() => invalidateAlertsCache());
|
||||
if (type === "grafana") void syncGrafana(created.id).then(() => invalidateAlertsCache());
|
||||
if (type === "nextcloud") void syncNextcloud(created.id).then(() => invalidateAlertsCache());
|
||||
if (type === "dockhand") void syncDockerVulns(created.id).then(() => invalidateAlertsCache());
|
||||
@@ -278,6 +280,7 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req,
|
||||
if (updated.type === "fragnet" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncFragnet(updated.id).then(() => invalidateAlertsCache());
|
||||
if ((ARR_KINDS as string[]).includes(updated.type) && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncArr(updated.id).then(() => invalidateAlertsCache());
|
||||
if (updated.type === "adguard" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncAdguard(updated.id).then(() => invalidateAlertsCache());
|
||||
if (updated.type === "technitium" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncTechnitium(updated.id).then(() => invalidateAlertsCache());
|
||||
if (updated.type === "grafana" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncGrafana(updated.id).then(() => invalidateAlertsCache());
|
||||
if (updated.type === "nextcloud" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncNextcloud(updated.id).then(() => invalidateAlertsCache());
|
||||
if (updated.type === "dockhand" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncDockerVulns(updated.id).then(() => invalidateAlertsCache());
|
||||
@@ -403,6 +406,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req,
|
||||
if (existing.type === "fragnet") await forgetFragnet(id);
|
||||
if ((ARR_KINDS as string[]).includes(existing.type)) await forgetArr(id);
|
||||
if (existing.type === "adguard") await forgetAdguard(id);
|
||||
if (existing.type === "technitium") await forgetTechnitium(id);
|
||||
if (existing.type === "grafana") await forgetGrafana(id);
|
||||
if (existing.type === "nextcloud") await forgetNextcloud(id);
|
||||
if (existing.type === "dockhand") await forgetDockerVulns(id);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { integrations, technitiumState } from "../db/schema.js";
|
||||
import { requireAuth } from "../auth/middleware.js";
|
||||
import { blockListsOverdueMs, isTechnitiumFresh, storedOf, technitiumProblems, technitiumSyncStatuses } from "../services/technitiumSync.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const technitiumRouter = Router();
|
||||
technitiumRouter.use(requireAuth);
|
||||
|
||||
/** Every Technitium DNS Server, how it is, from what the last reads stored: whether DNS answers, whether blocking is on, the last day's statistics, its zones and what is wrong. Everyone signed in can see it. */
|
||||
technitiumRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const [rows, states, statuses] = await Promise.all([
|
||||
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled, baseUrl: integrations.baseUrl }).from(integrations).where(eq(integrations.type, "technitium")).orderBy(integrations.name),
|
||||
db.select().from(technitiumState),
|
||||
technitiumSyncStatuses(),
|
||||
]);
|
||||
const byId = new Map(states.map((s) => [s.integrationId, s]));
|
||||
const now = Date.now();
|
||||
res.json({
|
||||
instances: rows.map((r) => {
|
||||
const row = byId.get(r.id);
|
||||
const state = row ? storedOf(row) : null;
|
||||
const status = statuses[r.id] ?? null;
|
||||
const fresh = isTechnitiumFresh(status ?? undefined, now);
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
enabled: r.enabled,
|
||||
url: r.baseUrl,
|
||||
status,
|
||||
fresh,
|
||||
state: state && { ...state, blockListsOverdueMs: blockListsOverdueMs(state, now) },
|
||||
problems: state && fresh ? technitiumProblems(r.id, r.name, state, now) : [],
|
||||
};
|
||||
}),
|
||||
});
|
||||
}));
|
||||
@@ -92,6 +92,7 @@ const SOURCES: Record<string, { label: string; link: string }> = {
|
||||
readarr: { label: "Readarr", link: "/media" },
|
||||
prowlarr: { label: "Prowlarr", link: "/media" },
|
||||
adguard: { label: "AdGuard Home", link: "/adguard" },
|
||||
technitium: { label: "Technitium DNS", link: "/technitium" },
|
||||
versions: { label: "Versions", link: "/versions" },
|
||||
grafana: { label: "Grafana", link: "/grafana" },
|
||||
secrets: { label: "Secrets", link: "/secrets" },
|
||||
@@ -140,6 +141,8 @@ function originOfConditionKey(key: string): { type: string; id: number | null; c
|
||||
if (m) return { type: "versions", id: Number(m[1]), category: "updates" };
|
||||
m = /^adguard-(stopped|dns|protection|filters):(\d+)/.exec(key);
|
||||
if (m) return { type: "adguard", id: Number(m[2]), category: m[1] === "stopped" || m[1] === "dns" ? "services" : "monitoring" };
|
||||
m = /^technitium-(dns|blocking|lists|zones):(\d+)/.exec(key);
|
||||
if (m) return { type: "technitium", id: Number(m[2]), category: m[1] === "dns" || m[1] === "zones" ? "services" : "monitoring" };
|
||||
m = /^grafana-(firing|rule-error|ds):(\d+):/.exec(key);
|
||||
if (m) return { type: "grafana", id: Number(m[2]), category: m[1] === "ds" ? "integration" : "monitoring" };
|
||||
m = /^(sonarr|radarr|prowlarr|lidarr|readarr)-(health|queue|disk):(\d+)/.exec(key);
|
||||
@@ -298,7 +301,7 @@ export async function collectAlerts(): Promise<AlertsReport> {
|
||||
if (held.has("slo")) cannotCheck("Service-level targets", "couldn't be judged — see the server log", "Server and storage health");
|
||||
if (held.has("server:baseline")) cannotCheck("What is usual for the time", "couldn't be judged — see the server log", "Server and storage health");
|
||||
for (const h of held) {
|
||||
const m = /^(proxmox|synology|unifi|ups|dockhand|jellyfin|authentik|prometheus|immich|paperless|nextcloud|netbox|n8n|hetzner|speedtest|fragnet|sonarr|radarr|prowlarr|lidarr|readarr|adguard|grafana):(\d+)(?::(.+))?$/.exec(h);
|
||||
const m = /^(proxmox|synology|unifi|ups|dockhand|jellyfin|authentik|prometheus|immich|paperless|nextcloud|netbox|n8n|hetzner|speedtest|fragnet|sonarr|radarr|prowlarr|lidarr|readarr|adguard|technitium|grafana):(\d+)(?::(.+))?$/.exec(h);
|
||||
if (!m || (m[3] && held.has(`${m[1]}:${m[2]}`))) continue;
|
||||
const row = intById.get(Number(m[2]));
|
||||
cannotCheck(`${SOURCES[m[1]].label} “${row?.name ?? `#${m[2]}`}”${m[3] === "vuln" ? " (vulnerability scans)" : m[3] === "images" ? " (age of the images)" : m[3] ? ` (node ${m[3]})` : ""}`, "couldn't be read — see the Diagnostic Log", "Server and storage health");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { authentikState, n8nState, netboxState, nextcloudState, paperlessState, immichState, prometheusState, integrations, jellyfinState, networkDevices, serverPorts, servers, upsState , dockhandVulnerabilities , hetznerState , fragnetState , arrState , adguardState , grafanaState } from "../db/schema.js";
|
||||
import { technitiumState, authentikState, n8nState, netboxState, nextcloudState, paperlessState, immichState, prometheusState, integrations, jellyfinState, networkDevices, serverPorts, servers, upsState , dockhandVulnerabilities , hetznerState , fragnetState , arrState , adguardState , grafanaState } from "../db/schema.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { createProxmoxAdapter, type ProxmoxNodeStats } from "../integrations/proxmox/adapter.js";
|
||||
import { createSynologyAdapter, type SynologyStorageInfo } from "../integrations/synology/adapter.js";
|
||||
@@ -36,6 +36,7 @@ import { hetznerProblems, hetznerSyncStatuses, imagesOf as hetznerImagesOf, load
|
||||
import { ARR_KINDS, type ArrKind } from "../integrations/arr/adapter.js";
|
||||
import { versionProblems, versionRows, type VersionProblem } from "./appVersions.js";
|
||||
import { adguardProblems, adguardSyncStatuses, isAdguardFresh, storedOf as adguardStoredOf, type AdguardProblem } from "./adguardSync.js";
|
||||
import { isTechnitiumFresh, storedOf as technitiumStoredOf, technitiumProblems, technitiumSyncStatuses, type TechnitiumProblem } from "./technitiumSync.js";
|
||||
import { grafanaProblems, grafanaSyncStatuses, isGrafanaFresh, storedOf as grafanaStoredOf, type GrafanaProblem } from "./grafanaSync.js";
|
||||
import { arrProblems, arrSyncStatuses, isArrFresh, storedOf as arrStoredOf, type ArrProblem } from "./arrSync.js";
|
||||
import { fragnetProblems, fragnetSyncStatuses, isFragnetFresh, optionsOf as fragnetOptions, serversOf as fragnetServersOf, type FragnetProblem } from "./fragnetSync.js";
|
||||
@@ -141,6 +142,8 @@ export interface HealthSnapshot {
|
||||
arr?: { integrationId: number; kind: ArrKind; problems: ArrProblem[] }[];
|
||||
/** What is wrong with each AdGuard Home (DNS not running or not answering, protection left off, filter lists not updating), only while that reading is recent (services/adguardSync.ts). */
|
||||
adguard?: { integrationId: number; problems: AdguardProblem[] }[];
|
||||
/** What is wrong with each Technitium DNS Server (DNS not answering, blocking left off, block lists not updating, zones expired or not syncing), only while that reading is recent (services/technitiumSync.ts). */
|
||||
technitium?: { integrationId: number; problems: TechnitiumProblem[] }[];
|
||||
/** Applications a newer release of which has been out for the number of days set (services/appVersions.ts), only while the lookup of releases is on. */
|
||||
versions?: VersionProblem[];
|
||||
/** What is wrong with each Grafana (rules firing or failing, data sources failing their check), only while that reading is recent (services/grafanaSync.ts). */
|
||||
@@ -291,6 +294,7 @@ export function evaluateHealth(snapshot: HealthSnapshot, thresholds: Thresholds,
|
||||
|
||||
// AdGuard Home and Grafana.
|
||||
for (const a of snapshot.adguard ?? []) for (const p of a.problems) out.push({ key: p.key, source: `adguard:${a.integrationId}`, message: p.message, severity: p.severity });
|
||||
for (const t of snapshot.technitium ?? []) for (const p of t.problems) out.push({ key: p.key, source: `technitium:${t.integrationId}`, message: p.message, severity: p.severity });
|
||||
for (const g of snapshot.grafana ?? []) for (const p of g.problems) out.push({ key: p.key, source: `grafana:${g.integrationId}`, message: p.message, severity: p.severity });
|
||||
|
||||
// Sonarr, Radarr and Prowlarr: what they say is wrong, downloads that are stuck, disks nearly full.
|
||||
@@ -628,6 +632,24 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
|
||||
console.error("[health] couldn't judge AdGuard Home:", err instanceof Error ? err.message : err);
|
||||
}
|
||||
|
||||
// Technitium DNS Server: read by its own pass every two minutes; what is judged is what that pass stored, and only while it is recent.
|
||||
try {
|
||||
const rowsT = await db.select({ id: integrations.id, name: integrations.name }).from(integrations).where(and(eq(integrations.type, "technitium"), eq(integrations.enabled, true)));
|
||||
if (rowsT.length > 0) {
|
||||
const statuses = await technitiumSyncStatuses();
|
||||
for (const r of rowsT) {
|
||||
const [state] = await db.select().from(technitiumState).where(eq(technitiumState.integrationId, r.id)).limit(1);
|
||||
if (!state || !isTechnitiumFresh(statuses[r.id], Date.now())) {
|
||||
held.add(`technitium:${r.id}`);
|
||||
continue;
|
||||
}
|
||||
(snapshot.technitium ??= []).push({ integrationId: r.id, problems: technitiumProblems(r.id, r.name, technitiumStoredOf(state), Date.now()) });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[health] couldn't judge Technitium DNS Server:", err instanceof Error ? err.message : err);
|
||||
}
|
||||
|
||||
// Grafana: read by its own pass every five minutes; what is judged is what that pass stored, and only while it is recent.
|
||||
try {
|
||||
const rowsR = await db.select({ id: integrations.id, name: integrations.name }).from(integrations).where(and(eq(integrations.type, "grafana"), eq(integrations.enabled, true)));
|
||||
|
||||
@@ -6,7 +6,7 @@ export const INTEGRATION_GROUPS: { id: string; label: string; types: string[] }[
|
||||
{ id: "infrastructure", label: "Infrastructure", types: ["proxmox", "synology", "dockhand", "hetzner", "fragnet", "tailscale"] },
|
||||
{ id: "apps", label: "Apps", types: ["homeassistant", "jellyfin", "sonarr", "radarr", "lidarr", "readarr", "prowlarr", "immich", "paperless", "nextcloud", "authentik"] },
|
||||
{ id: "backups", label: "Backups", types: ["pbs"] },
|
||||
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard"] },
|
||||
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard", "technitium"] },
|
||||
{ id: "monitoring", label: "Monitoring", types: ["uptimekuma", "prometheus", "grafana", "ups", "speedtest"] },
|
||||
{ id: "automation", label: "Automation", types: ["semaphore", "gitea", "osticket", "n8n"] },
|
||||
];
|
||||
@@ -49,6 +49,8 @@ export function subjectOfConditionKey(key: string): string | null {
|
||||
if (m) return `integration:${m[1]}`;
|
||||
m = /^adguard-(?:stopped|dns|protection|filters):(\d+)/.exec(key);
|
||||
if (m) return `integration:${m[1]}`;
|
||||
m = /^technitium-(?:dns|blocking|lists|zones):(\d+)/.exec(key);
|
||||
if (m) return `integration:${m[1]}`;
|
||||
m = /^grafana-(?:firing|rule-error|ds):(\d+):/.exec(key);
|
||||
if (m) return `integration:${m[1]}`;
|
||||
m = /^netbox-(?:workers):(\d+)/.exec(key);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers, upsState, jellyfinState, authentikState, immichState, paperlessState, nextcloudState, netboxState, n8nState, dockhandVulnerabilities, hetznerState, fragnetState, arrState, adguardState, grafanaState } from "../db/schema.js";
|
||||
import { technitiumState, assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers, upsState, jellyfinState, authentikState, immichState, paperlessState, nextcloudState, netboxState, n8nState, dockhandVulnerabilities, hetznerState, fragnetState, arrState, adguardState, grafanaState } from "../db/schema.js";
|
||||
import { isUpsFresh, upsSyncStatuses } from "./upsSync.js";
|
||||
import { levelStatuses } from "./serviceLevels.js";
|
||||
import { backupState, listAll as listDuplicati } from "./duplicati.js";
|
||||
@@ -17,6 +17,7 @@ import { costOf as hetznerCostOf, hetznerSyncStatuses, isHetznerFresh, serversOf
|
||||
import { ARR_KINDS } from "../integrations/arr/adapter.js";
|
||||
import { versionRows as appVersionRows } from "./appVersions.js";
|
||||
import { adguardSyncStatuses, isAdguardFresh, storedOf as adguardStoredOf } from "./adguardSync.js";
|
||||
import { blockListsOverdueMs, isTechnitiumFresh, storedOf as technitiumStoredOf, technitiumSyncStatuses } from "./technitiumSync.js";
|
||||
import { grafanaSyncStatuses, isGrafanaFresh, storedOf as grafanaStoredOf } from "./grafanaSync.js";
|
||||
import { arrSyncStatuses, distinctDisks as arrDisks, isArrFresh, stuckItems as arrStuck, storedOf as arrStoredOf } from "./arrSync.js";
|
||||
import { fragnetSyncStatuses, isFragnetFresh, newestBackup as fragnetNewestBackup, serversOf as fragnetServersOf } from "./fragnetSync.js";
|
||||
@@ -115,6 +116,40 @@ async function addVersionMetrics(out: Exposition) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Each Technitium DNS Server, for /metrics: whether the test question was answered and how fast, whether blocking is on, how long it has run, the last day's queries and how they ended, the cache, the zones with a problem and the DHCP leases. Only while the reading is recent. */
|
||||
async function addTechnitiumMetrics(out: Exposition, now: Date) {
|
||||
const statuses = await technitiumSyncStatuses();
|
||||
const rows = new Map((await db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "technitium"))).map((r) => [r.id, r]));
|
||||
for (const s of await db.select().from(technitiumState)) {
|
||||
const row = rows.get(s.integrationId);
|
||||
if (!row || !row.enabled || !isTechnitiumFresh(statuses[s.integrationId], now.getTime())) continue;
|
||||
const state = technitiumStoredOf(s);
|
||||
const labels = { name: row.name };
|
||||
out.add("homelab_technitium_blocking_enabled", "gauge", "1 if Technitium's blocking is switched on, else 0.", state.blockingEnabled ? 1 : 0, labels);
|
||||
if (state.startedAt !== null) out.add("homelab_technitium_uptime_seconds", "gauge", "How long the Technitium DNS server has been running, in seconds.", Math.max(0, (now.getTime() - Date.parse(state.startedAt)) / 1000), labels);
|
||||
if (state.probe) {
|
||||
out.add("homelab_technitium_dns_up", "gauge", "1 if Technitium's DNS server answered a test question, else 0.", state.probe.ok ? 1 : 0, labels);
|
||||
if (state.probe.ok && state.probe.ms !== null) out.add("homelab_technitium_dns_probe_seconds", "gauge", "How long Technitium's DNS server took to answer a test question, in seconds.", state.probe.ms / 1000, labels);
|
||||
}
|
||||
const overdue = blockListsOverdueMs(state, now.getTime());
|
||||
if (state.settings.blockLists.count > 0) out.add("homelab_technitium_block_lists_overdue", "gauge", "1 if the block lists were due for an update more than six hours ago, else 0.", overdue !== null ? 1 : 0, labels);
|
||||
if (state.stats) {
|
||||
out.add("homelab_technitium_queries", "gauge", "DNS queries Technitium answered in the last day.", state.stats.queries, labels);
|
||||
out.add("homelab_technitium_blocked", "gauge", "Of them, the ones it blocked.", state.stats.blocked, labels);
|
||||
out.add("homelab_technitium_cached", "gauge", "Of them, the ones answered from its cache.", state.stats.cached, labels);
|
||||
out.add("homelab_technitium_recursive", "gauge", "Of them, the ones it had to resolve itself.", state.stats.recursive, labels);
|
||||
out.add("homelab_technitium_server_failures", "gauge", "Of them, the ones that ended in a server failure.", state.stats.serverFailure, labels);
|
||||
out.add("homelab_technitium_clients", "gauge", "Different clients that asked in the last day.", state.stats.clients, labels);
|
||||
if (state.stats.cachedEntries !== null) out.add("homelab_technitium_cache_entries", "gauge", "Entries in Technitium's DNS cache now.", state.stats.cachedEntries, labels);
|
||||
}
|
||||
if (state.zones) {
|
||||
out.add("homelab_technitium_zones", "gauge", "Zones Technitium holds (its own internal ones not counted).", state.zones.total, labels);
|
||||
out.add("homelab_technitium_zone_problems", "gauge", "Zones that have expired or cannot sync.", state.zones.issues.length, labels);
|
||||
}
|
||||
if (state.dhcp) out.add("homelab_technitium_dhcp_leases", "gauge", "DHCP leases Technitium holds.", state.dhcp.leases, labels);
|
||||
}
|
||||
}
|
||||
|
||||
/** Each AdGuard Home, for /metrics: whether its DNS server runs and protects, whether the test question was answered and how fast, and what it has done over its statistics period. Only while the reading is recent. */
|
||||
async function addAdguardMetrics(out: Exposition, now: Date) {
|
||||
const statuses = await adguardSyncStatuses();
|
||||
@@ -552,6 +587,7 @@ export async function buildMetrics(now: Date = new Date()): Promise<string> {
|
||||
await addFragnetMetrics(out, now);
|
||||
await addArrMetrics(out, now);
|
||||
await addAdguardMetrics(out, now);
|
||||
await addTechnitiumMetrics(out, now);
|
||||
await addVersionMetrics(out);
|
||||
await addGrafanaMetrics(out, now);
|
||||
await addHeartbeatMetrics(out, now);
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* Keeps what Technitium DNS Server says up to date: every two minutes each Technitium integration is read — its version and when it started, whether blocking is on, its block lists, the
|
||||
* statistics of the last day, the health of its zones, its DHCP leases — and one real DNS question is put to its DNS server; the state is stored. Pages and alerts are built from what is
|
||||
* stored. (Two minutes, not five: DNS is what everything else leans on.)
|
||||
*
|
||||
* What is raised: **DNS is not answering** — the test question went unanswered, or was answered with an error, in every read for ten minutes (critical; one lost packet is not an outage);
|
||||
* **blocking is switched off** for an hour or more while block lists are set up (someone paused it and forgot: warning); **the block lists are overdue** — their next update was due more than
|
||||
* six hours ago (warning); **a zone has a problem** — a secondary zone that has expired no longer answers (critical), one that cannot sync is going stale (warning). "Since when" is what this
|
||||
* app saw: the time of the first read that showed it.
|
||||
*/
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db } from "../db/client.js";
|
||||
import { integrations, technitiumState } from "../db/schema.js";
|
||||
import { createTechnitiumAdapter, type TechnitiumDhcp, type TechnitiumRead, type TechnitiumStats, type TechnitiumZones } from "../integrations/technitium/adapter.js";
|
||||
import type { ProbeResult } from "../integrations/adguard/dnsProbe.js";
|
||||
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
||||
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
|
||||
|
||||
export const SYNC_INTERVAL_MS = 2 * 60_000;
|
||||
/** After this long without a good read, what is stored is no longer believed. */
|
||||
export const STALE_AFTER_MS = 10 * 60_000;
|
||||
const STATUS_FLAG = "technitiumSync";
|
||||
|
||||
const MIN = 60_000;
|
||||
const HOUR = 60 * MIN;
|
||||
/** DNS that has not answered in any read for this long is down. */
|
||||
export const DNS_FAIL_AFTER_MS = 10 * MIN;
|
||||
/** Blocking off for this long is forgotten, not paused. */
|
||||
export const BLOCKING_OFF_AFTER_MS = HOUR;
|
||||
/** Block lists whose next update was due this long ago have stopped updating (Technitium tries again soon after a failed one). */
|
||||
export const LISTS_OVERDUE_MS = 6 * HOUR;
|
||||
|
||||
export interface TechnitiumSyncStatus {
|
||||
/** The last read that worked (kept when a later one failed). */
|
||||
at: string;
|
||||
ok: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
async function readStatuses(): Promise<Record<string, TechnitiumSyncStatus>> {
|
||||
try {
|
||||
const raw = await getInternalFlag(STATUS_FLAG);
|
||||
return raw ? (JSON.parse(raw) as Record<string, TechnitiumSyncStatus>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export async function technitiumSyncStatuses(): Promise<Record<number, TechnitiumSyncStatus>> {
|
||||
return Object.fromEntries(Object.entries(await readStatuses()).map(([k, v]) => [Number(k), v]));
|
||||
}
|
||||
|
||||
export const isTechnitiumFresh = (status: TechnitiumSyncStatus | undefined, nowMs: number) => !!status && status.ok && nowMs - Date.parse(status.at) <= STALE_AFTER_MS;
|
||||
|
||||
export type StateRow = typeof technitiumState.$inferSelect;
|
||||
|
||||
/** What is stored of one Technitium, as the read gave it, plus what the app has seen between reads. */
|
||||
export interface StoredTechnitium {
|
||||
version: string | null;
|
||||
startedAt: string | null;
|
||||
dnsPort: number;
|
||||
blockingEnabled: boolean;
|
||||
/** When the first read that showed blocking off was made; null while it is on. */
|
||||
blockingOffSince: string | null;
|
||||
settings: TechnitiumRead["settings"];
|
||||
stats: TechnitiumStats | null;
|
||||
zones: TechnitiumZones | null;
|
||||
dhcp: TechnitiumDhcp | null;
|
||||
probe: (ProbeResult & { name: string; host: string }) | null;
|
||||
/** When the first read that showed the DNS test failing was made; null while it works. */
|
||||
probeFailSince: string | null;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
function parse<T>(stored: string | null): T | null {
|
||||
if (stored === null) return null;
|
||||
try {
|
||||
return JSON.parse(stored) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const NO_SETTINGS: TechnitiumRead["settings"] = { blockLists: { count: 0, intervalHours: null, nextUpdate: null }, cacheMaximumEntries: null, recursion: null, dnssecValidation: null };
|
||||
|
||||
export const storedOf = (row: StateRow): StoredTechnitium => ({
|
||||
version: row.version,
|
||||
startedAt: row.startedAt,
|
||||
dnsPort: row.dnsPort,
|
||||
blockingEnabled: row.blockingEnabled,
|
||||
blockingOffSince: row.blockingOffSince,
|
||||
settings: parse<TechnitiumRead["settings"]>(row.settings) ?? NO_SETTINGS,
|
||||
stats: parse<TechnitiumStats>(row.stats),
|
||||
zones: parse<TechnitiumZones>(row.zones),
|
||||
dhcp: parse<TechnitiumDhcp>(row.dhcp),
|
||||
probe: parse<StoredTechnitium["probe"]>(row.probe),
|
||||
probeFailSince: row.probeFailSince,
|
||||
updatedAt: row.updatedAt,
|
||||
});
|
||||
|
||||
/** Pure: what the app has seen between reads, carried from the last read. A thing first seen wrong starts its clock now. */
|
||||
export function carrySince(read: Pick<TechnitiumRead, "blockingEnabled" | "probe">, previous: Pick<StoredTechnitium, "blockingOffSince" | "probeFailSince"> | null, now: Date): { blockingOffSince: string | null; probeFailSince: string | null } {
|
||||
const at = now.toISOString();
|
||||
return {
|
||||
blockingOffSince: read.blockingEnabled ? null : (previous?.blockingOffSince ?? at),
|
||||
probeFailSince: read.probe.ok ? null : (previous?.probeFailSince ?? at),
|
||||
};
|
||||
}
|
||||
|
||||
/** Writes down one read, replacing the last (and carrying what was seen between reads). */
|
||||
export async function storeRead(integrationId: number, r: TechnitiumRead, now: Date = new Date()): Promise<void> {
|
||||
const [previous] = await db.select().from(technitiumState).where(eq(technitiumState.integrationId, integrationId)).limit(1);
|
||||
const since = carrySince(r, previous ? storedOf(previous) : null, now);
|
||||
const values = {
|
||||
version: r.version,
|
||||
startedAt: r.startedAt,
|
||||
dnsPort: r.dnsPort,
|
||||
blockingEnabled: r.blockingEnabled,
|
||||
blockingOffSince: since.blockingOffSince,
|
||||
settings: JSON.stringify(r.settings),
|
||||
stats: r.stats && JSON.stringify(r.stats),
|
||||
zones: r.zones && JSON.stringify(r.zones),
|
||||
dhcp: r.dhcp && JSON.stringify(r.dhcp),
|
||||
probe: JSON.stringify(r.probe),
|
||||
probeFailSince: since.probeFailSince,
|
||||
updatedAt: now.toISOString(),
|
||||
};
|
||||
await db.insert(technitiumState).values({ integrationId, ...values }).onConflictDoUpdate({ target: technitiumState.integrationId, set: values });
|
||||
}
|
||||
|
||||
/** Reads one Technitium and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
|
||||
export async function syncTechnitium(integrationId: number, now: Date = new Date(), read?: (config: Record<string, unknown>) => Promise<TechnitiumRead>): Promise<TechnitiumSyncStatus> {
|
||||
let status: TechnitiumSyncStatus;
|
||||
try {
|
||||
const loaded = await loadIntegrationConfig(integrationId);
|
||||
if (!loaded || loaded.integration.type !== "technitium") throw new Error("not a Technitium integration");
|
||||
const result = await (read ? read(loaded.config) : createTechnitiumAdapter(loaded.config as never).read());
|
||||
await storeRead(integrationId, result, now);
|
||||
status = { at: now.toISOString(), ok: true, error: null };
|
||||
} catch (err) {
|
||||
const previous = (await readStatuses())[String(integrationId)];
|
||||
status = { at: previous?.at ?? now.toISOString(), ok: false, error: err instanceof Error ? err.message : String(err) };
|
||||
console.error(`[technitium] couldn't read integration ${integrationId}:`, status.error);
|
||||
}
|
||||
try {
|
||||
const all = await readStatuses();
|
||||
all[String(integrationId)] = status;
|
||||
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
|
||||
} catch (err) {
|
||||
console.error("[technitium] couldn't record the result:", err);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
export async function syncAllTechnitium(now: Date = new Date()): Promise<Record<number, TechnitiumSyncStatus>> {
|
||||
const rows = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "technitium"), eq(integrations.enabled, true)));
|
||||
const out: Record<number, TechnitiumSyncStatus> = {};
|
||||
for (const r of rows) out[r.id] = await syncTechnitium(r.id, now);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function forgetTechnitium(integrationId: number): Promise<void> {
|
||||
const all = await readStatuses();
|
||||
if (String(integrationId) in all) {
|
||||
delete all[String(integrationId)];
|
||||
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── What is wrong ──────────────────────────────────────────────────────────
|
||||
|
||||
export interface TechnitiumProblem {
|
||||
key: string;
|
||||
message: string;
|
||||
severity: "warning" | "critical";
|
||||
}
|
||||
|
||||
const plural = (n: number, unit: string) => `${n} ${unit}${n === 1 ? "" : "s"}`;
|
||||
const ago = (ms: number): string => (ms >= 48 * HOUR ? plural(Math.round(ms / (24 * HOUR)), "day") : ms >= HOUR ? plural(Math.round(ms / HOUR), "hour") : plural(Math.max(1, Math.round(ms / MIN)), "minute"));
|
||||
|
||||
/** Pure: how long ago the block lists were due for an update, when that is more than the grace; null when they are not overdue, or none are set up, or no time was said. */
|
||||
export function blockListsOverdueMs(s: Pick<StoredTechnitium, "settings">, nowMs: number): number | null {
|
||||
const l = s.settings.blockLists;
|
||||
if (l.count === 0 || l.nextUpdate === null) return null;
|
||||
const over = nowMs - Date.parse(l.nextUpdate);
|
||||
return over > LISTS_OVERDUE_MS ? over : null;
|
||||
}
|
||||
|
||||
/** Pure: what is wrong with one Technitium, from what is stored for it. */
|
||||
export function technitiumProblems(id: number, name: string, s: StoredTechnitium, nowMs: number): TechnitiumProblem[] {
|
||||
const out: TechnitiumProblem[] = [];
|
||||
if (s.probe && !s.probe.ok && s.probeFailSince !== null && nowMs - Date.parse(s.probeFailSince) >= DNS_FAIL_AFTER_MS) {
|
||||
out.push({ key: `technitium-dns:${id}`, severity: "critical", message: `${name}: DNS has not answered a question about ${s.probe.name} for ${ago(nowMs - Date.parse(s.probeFailSince))} (asked ${s.probe.host}:${s.dnsPort}) — ${s.probe.error ?? "no answer"}` });
|
||||
}
|
||||
if (!s.blockingEnabled && s.settings.blockLists.count > 0 && s.blockingOffSince !== null && nowMs - Date.parse(s.blockingOffSince) >= BLOCKING_OFF_AFTER_MS) {
|
||||
out.push({ key: `technitium-blocking:${id}`, severity: "warning", message: `${name}: Technitium's blocking has been switched off for ${ago(nowMs - Date.parse(s.blockingOffSince))} — nothing is being blocked` });
|
||||
}
|
||||
const overdue = blockListsOverdueMs(s, nowMs);
|
||||
if (overdue !== null) {
|
||||
out.push({ key: `technitium-lists:${id}`, severity: "warning", message: `${name}: the block lists were due for an update ${ago(overdue)} ago and have not been updated` });
|
||||
}
|
||||
const issues = s.zones?.issues ?? [];
|
||||
if (issues.length > 0) {
|
||||
const expired = issues.some((i) => i.problem === "expired");
|
||||
const names = issues.slice(0, 3).map((i) => `${i.name} (${i.problem})`);
|
||||
out.push({
|
||||
key: `technitium-zones:${id}`,
|
||||
severity: expired ? "critical" : "warning",
|
||||
message: `${name}: ${plural(issues.length, "zone")} ${issues.length === 1 ? "has" : "have"} a problem — ${names.join(", ")}${issues.length > 3 ? ` and ${issues.length - 3} more` : ""}${expired ? " (an expired secondary zone no longer answers)" : ""}`,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let timer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
export function initTechnitiumSync(): void {
|
||||
if (timer) return;
|
||||
const pass = () => void syncAllTechnitium().catch((err) => console.error("[technitium] pass failed:", err));
|
||||
timer = setInterval(pass, SYNC_INTERVAL_MS);
|
||||
setTimeout(pass, 40_000);
|
||||
console.log(`[technitium] reading Technitium DNS Server every ${SYNC_INTERVAL_MS / 60000} minutes`);
|
||||
}
|
||||
@@ -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)), []);
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,7 @@ import Hetzner from "./pages/Hetzner";
|
||||
import GameServers from "./pages/GameServers";
|
||||
import Media from "./pages/Media";
|
||||
import AdguardHome from "./pages/AdguardHome";
|
||||
import TechnitiumDns from "./pages/TechnitiumDns";
|
||||
import Grafana from "./pages/Grafana";
|
||||
import Speedtest from "./pages/Speedtest";
|
||||
import Costs from "./pages/Costs";
|
||||
@@ -187,6 +188,7 @@ function Shelled({ user }: { user: CurrentUser }) {
|
||||
<Route path="/media" element={<Media />} />
|
||||
<Route path="/versions" element={<Versions user={user} />} />
|
||||
<Route path="/adguard" element={<AdguardHome />} />
|
||||
<Route path="/technitium" element={<TechnitiumDns />} />
|
||||
<Route path="/grafana" element={<Grafana />} />
|
||||
<Route path="/speedtest" element={<Speedtest />} />
|
||||
<Route path="/costs" element={<Costs user={user} />} />
|
||||
|
||||
+59
-1
@@ -1519,6 +1519,61 @@ export interface AdguardInstance {
|
||||
problems: { key: string; message: string; severity: "warning" | "critical" }[];
|
||||
}
|
||||
|
||||
/** One Technitium DNS Server (an integration of type technitium), as its page shows it. */
|
||||
export interface TechnitiumInstance {
|
||||
id: number;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
url: string;
|
||||
status: { at: string; ok: boolean; error: string | null } | null;
|
||||
fresh: boolean;
|
||||
state: {
|
||||
version: string | null;
|
||||
/** When the DNS server last started. */
|
||||
startedAt: string | null;
|
||||
dnsPort: number;
|
||||
blockingEnabled: boolean;
|
||||
blockingOffSince: string | null;
|
||||
settings: { blockLists: { count: number; intervalHours: number | null; nextUpdate: string | null }; cacheMaximumEntries: number | null; recursion: string | null; dnssecValidation: boolean | null };
|
||||
/** The last day. */
|
||||
stats: {
|
||||
period: string;
|
||||
queries: number;
|
||||
noError: number;
|
||||
serverFailure: number;
|
||||
nxDomain: number;
|
||||
refused: number;
|
||||
authoritative: number;
|
||||
recursive: number;
|
||||
cached: number;
|
||||
blocked: number;
|
||||
dropped: number;
|
||||
clients: number;
|
||||
zones: number | null;
|
||||
cachedEntries: number | null;
|
||||
allowedZones: number | null;
|
||||
blockedZones: number | null;
|
||||
allowListZones: number | null;
|
||||
blockListZones: number | null;
|
||||
blockedPercent: number | null;
|
||||
cachedPercent: number | null;
|
||||
failurePercent: number | null;
|
||||
topClients: { name: string; count: number }[];
|
||||
topDomains: { name: string; count: number }[];
|
||||
topBlocked: { name: string; count: number }[];
|
||||
} | null;
|
||||
zones: { total: number; disabled: number; issues: { name: string; problem: "expired" | "sync failed" }[] } | null;
|
||||
dhcp: { scopes: number; enabledScopes: number; leases: number } | null;
|
||||
/** The real DNS question put to it. */
|
||||
probe: { ok: boolean; ms: number | null; error: string | null; name: string; host: string } | null;
|
||||
probeFailSince: string | null;
|
||||
updatedAt: string;
|
||||
/** How long ago the block lists were due for an update, when that is overdue; null otherwise. */
|
||||
blockListsOverdueMs: number | null;
|
||||
} | null;
|
||||
problems: { key: string; message: string; severity: "warning" | "critical" }[];
|
||||
}
|
||||
|
||||
/** One Grafana (an integration of type grafana), as its page shows it. */
|
||||
export interface GrafanaInstance {
|
||||
id: number;
|
||||
@@ -2800,7 +2855,7 @@ export interface ManualTaskInput {
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant" | "ups" | "jellyfin" | "authentik" | "prometheus" | "immich" | "paperless" | "nextcloud" | "netbox" | "n8n" | "hetzner" | "speedtest" | "fragnet" | "sonarr" | "radarr" | "prowlarr" | "adguard" | "grafana" | "lidarr" | "readarr";
|
||||
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant" | "ups" | "jellyfin" | "authentik" | "prometheus" | "immich" | "paperless" | "nextcloud" | "netbox" | "n8n" | "hetzner" | "speedtest" | "fragnet" | "sonarr" | "radarr" | "prowlarr" | "adguard" | "technitium" | "grafana" | "lidarr" | "readarr";
|
||||
|
||||
export interface IntegrationField {
|
||||
key: string;
|
||||
@@ -3407,6 +3462,9 @@ export const api = {
|
||||
save: (data: { enabled: boolean; alertAfterDays: number }) => request<AppVersions>("/api/versions/settings", { method: "PUT", body: JSON.stringify(data) }),
|
||||
refresh: () => request<AppVersions & { result: { checked: number; failed: number } }>("/api/versions/refresh", { method: "POST" }),
|
||||
},
|
||||
technitium: {
|
||||
list: () => request<{ instances: TechnitiumInstance[] }>("/api/technitium"),
|
||||
},
|
||||
adguard: {
|
||||
list: () => request<{ instances: AdguardInstance[] }>("/api/adguard"),
|
||||
},
|
||||
|
||||
@@ -35,6 +35,7 @@ const TYPE_LABELS: Record<string, string> = {
|
||||
radarr: "Radarr",
|
||||
prowlarr: "Prowlarr",
|
||||
adguard: "AdGuard Home",
|
||||
technitium: "Technitium DNS",
|
||||
grafana: "Grafana",
|
||||
lidarr: "Lidarr",
|
||||
readarr: "Readarr",
|
||||
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
IconGitCommit,
|
||||
IconShieldCheck,
|
||||
IconShieldLock,
|
||||
IconWorldWww,
|
||||
IconVersions,
|
||||
IconChartAreaLine,
|
||||
IconActivityHeartbeat,
|
||||
@@ -137,6 +138,7 @@ export const NAV: NavEntry[] = [
|
||||
items: [
|
||||
{ to: "/dns", label: "DNS", icon: <IconWorld size={20} /> },
|
||||
{ to: "/adguard", label: "AdGuard Home", icon: <IconShieldLock size={20} /> },
|
||||
{ to: "/technitium", label: "Technitium DNS", icon: <IconWorldWww size={20} /> },
|
||||
{ to: "/network/devices", label: "Network devices", icon: <IconRouter size={20} /> },
|
||||
{ to: "/proxy-hosts", label: "Proxy hosts", icon: <IconArrowsSplit2 size={20} /> },
|
||||
{ to: "/ipam", label: "IP Addresses", icon: <IconNetwork size={20} /> },
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { api, type TechnitiumInstance } from "../api/client";
|
||||
import EmptyState from "../components/EmptyState";
|
||||
import TimeAgo from "../components/TimeAgo";
|
||||
import { BlockSkeleton } from "../components/Skeleton";
|
||||
import { ErrorNotice } from "../components/Notice";
|
||||
import { formatAgo } from "../utils/duration";
|
||||
import { readableError } from "../utils/errors";
|
||||
|
||||
function Badge({ a }: { a: TechnitiumInstance }) {
|
||||
if (!a.enabled) return <span className="badge bg-secondary-lt text-secondary">Off</span>;
|
||||
if (!a.state) return <span className="badge bg-secondary-lt text-secondary">Not read yet</span>;
|
||||
if (!a.fresh) return <span className="badge bg-yellow-lt text-yellow">Can’t be read</span>;
|
||||
if (a.problems.some((x) => x.severity === "critical")) return <span className="badge bg-red-lt text-red">Needs a look</span>;
|
||||
if (a.problems.length > 0) return <span className="badge bg-yellow-lt text-yellow">Needs a look</span>;
|
||||
return <span className="badge bg-green-lt text-green">In order</span>;
|
||||
}
|
||||
|
||||
function Tile({ label, value, sub, tone }: { label: string; value: string; sub?: string | null; tone?: "bad" | "warn" }) {
|
||||
return (
|
||||
<div className="col-6 col-lg-3">
|
||||
<div className="card card-sm h-100">
|
||||
<div className="card-body">
|
||||
<div className="text-secondary small">{label}</div>
|
||||
<div className={`h2 mb-0 ${tone === "bad" ? "text-red" : tone === "warn" ? "text-yellow" : ""}`}>{value}</div>
|
||||
{sub && <div className="text-secondary small">{sub}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Counted({ title, items, empty }: { title: string; items: { name: string; count: number }[]; empty: string }) {
|
||||
const top = items[0]?.count ?? 0;
|
||||
return (
|
||||
<div className="col-lg-4">
|
||||
<h4>{title}</h4>
|
||||
{items.length === 0 && <div className="text-secondary small">{empty}</div>}
|
||||
{items.slice(0, 7).map((i) => (
|
||||
<div key={i.name} className="mb-1">
|
||||
<div className="d-flex small">
|
||||
<span className="text-break">{i.name}</span>
|
||||
<span className="ms-auto text-secondary ps-2">{i.count.toLocaleString()}</span>
|
||||
</div>
|
||||
<div className="progress progress-sm">
|
||||
<div className="progress-bar" style={{ width: `${top > 0 ? Math.max(2, (i.count / top) * 100) : 0}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** "12 d 3 h", "5 h 20 min", "40 min": how long since a moment. */
|
||||
function upFor(startedAt: string, now: number = Date.now()): string {
|
||||
const minutes = Math.max(0, Math.floor((now - Date.parse(startedAt)) / 60_000));
|
||||
if (minutes < 60) return `${minutes} min`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return minutes % 60 ? `${hours} h ${minutes % 60} min` : `${hours} h`;
|
||||
const days = Math.floor(hours / 24);
|
||||
return hours % 24 ? `${days} d ${hours % 24} h` : `${days} d`;
|
||||
}
|
||||
|
||||
/** How the last day's queries were answered, as one bar: from the cache, resolved by the server, from its own zones, blocked, dropped. */
|
||||
const HOW: { key: "cached" | "recursive" | "authoritative" | "blocked" | "dropped"; label: string; className: string }[] = [
|
||||
{ key: "cached", label: "from the cache", className: "bg-blue" },
|
||||
{ key: "recursive", label: "resolved", className: "bg-azure" },
|
||||
{ key: "authoritative", label: "from its own zones", className: "bg-green" },
|
||||
{ key: "blocked", label: "blocked", className: "bg-orange" },
|
||||
{ key: "dropped", label: "dropped", className: "bg-red" },
|
||||
];
|
||||
|
||||
function Card({ a }: { a: TechnitiumInstance }) {
|
||||
const s = a.state;
|
||||
const st = s?.stats ?? null;
|
||||
const cacheMax = s?.settings.cacheMaximumEntries ?? null;
|
||||
const cacheFill = st && st.cachedEntries !== null && cacheMax !== null && cacheMax > 0 ? Math.min(100, Math.round((st.cachedEntries / cacheMax) * 100)) : null;
|
||||
return (
|
||||
<div className="card mb-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">
|
||||
{a.name} <span className="text-secondary fw-normal">{s?.version ? `v${s.version}` : ""}</span> <Badge a={a} />
|
||||
</h3>
|
||||
<div className="card-actions text-secondary small">{a.status ? <>read <TimeAgo value={a.status.at} /></> : "not read yet"}</div>
|
||||
</div>
|
||||
<div className="card-body">
|
||||
{a.status && !a.status.ok && <div className="text-yellow mb-2">The last attempt to read it failed: {a.status.error ?? "no answer"}.</div>}
|
||||
{a.problems.length > 0 && (
|
||||
<ul className="mb-3">
|
||||
{a.problems.map((x) => (
|
||||
<li key={x.key} className={x.severity === "critical" ? "text-red" : ""}>
|
||||
{x.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{s && (
|
||||
<>
|
||||
<div className="row g-3 mb-3">
|
||||
<Tile
|
||||
label="DNS answers"
|
||||
value={s.probe === null ? "—" : s.probe.ok ? `${s.probe.ms ?? "?"} ms` : "No"}
|
||||
sub={s.probe ? (s.probe.ok ? `a question about ${s.probe.name}, asked ${s.probe.host}:${s.dnsPort}` : `${s.probe.error ?? "no answer"} (${s.probe.host}:${s.dnsPort})`) : "no test yet"}
|
||||
tone={s.probe && !s.probe.ok ? "bad" : undefined}
|
||||
/>
|
||||
<Tile
|
||||
label="Blocking"
|
||||
value={s.blockingEnabled ? "On" : "Off"}
|
||||
sub={s.blockingEnabled ? (s.settings.blockLists.count === 0 ? "no block lists are set up" : null) : s.blockingOffSince ? `since ${formatAgo(s.blockingOffSince)}` : null}
|
||||
tone={!s.blockingEnabled && s.settings.blockLists.count > 0 ? "warn" : undefined}
|
||||
/>
|
||||
<Tile label="Queries, last day" value={st ? st.queries.toLocaleString() : "—"} sub={st ? `from ${st.clients.toLocaleString()} client${st.clients === 1 ? "" : "s"}` : "could not be read"} />
|
||||
<Tile label="Blocked" value={st ? st.blocked.toLocaleString() : "—"} sub={st ? (st.blockedPercent === null ? null : `${st.blockedPercent}% of the queries`) : "could not be read"} />
|
||||
<Tile label="From the cache" value={st ? (st.cachedPercent === null ? "—" : `${st.cachedPercent}%`) : "—"} sub={st ? `${st.cached.toLocaleString()} queries` : "could not be read"} />
|
||||
<Tile
|
||||
label="Failed"
|
||||
value={st ? (st.failurePercent === null ? "—" : `${st.failurePercent}%`) : "—"}
|
||||
sub={st ? `${st.serverFailure.toLocaleString()} server failures, ${st.refused.toLocaleString()} refused` : "could not be read"}
|
||||
tone={st && st.failurePercent !== null && st.queries >= 200 && st.failurePercent >= 20 ? "warn" : undefined}
|
||||
/>
|
||||
<Tile label="Running for" value={s.startedAt ? upFor(s.startedAt) : "—"} sub={s.startedAt ? `since ${new Date(s.startedAt).toLocaleString()}` : "it did not say"} />
|
||||
<Tile
|
||||
label="DNS cache"
|
||||
value={st && st.cachedEntries !== null ? st.cachedEntries.toLocaleString() : "—"}
|
||||
sub={cacheFill !== null ? `${cacheFill}% of ${cacheMax!.toLocaleString()} entries` : cacheMax !== null ? `up to ${cacheMax.toLocaleString()} entries` : null}
|
||||
tone={cacheFill !== null && cacheFill >= 95 ? "warn" : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{st && st.queries > 0 && (
|
||||
<div className="mb-3">
|
||||
<h4>How the queries were answered</h4>
|
||||
<div className="progress mb-1">
|
||||
{HOW.map((h) => (
|
||||
<div key={h.key} className={`progress-bar ${h.className}`} style={{ width: `${(st[h.key] / st.queries) * 100}%` }} title={`${h.label}: ${st[h.key].toLocaleString()}`} />
|
||||
))}
|
||||
</div>
|
||||
<div className="d-flex flex-wrap gap-3 small text-secondary">
|
||||
{HOW.map((h) => (
|
||||
<span key={h.key}>
|
||||
<span className={`badge ${h.className} me-1`}> </span>
|
||||
{h.label} {st[h.key].toLocaleString()}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{st && (st.topBlocked.length > 0 || st.topClients.length > 0 || st.topDomains.length > 0) && (
|
||||
<div className="row g-3 mb-3">
|
||||
<Counted title="Blocked most" items={st.topBlocked} empty="Nothing blocked." />
|
||||
<Counted title="Asked about most" items={st.topDomains} empty="No queries." />
|
||||
<Counted title="Asking most" items={st.topClients} empty="No clients." />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h4>Zones</h4>
|
||||
{s.zones === null ? (
|
||||
<div className="text-secondary small mb-3">They could not be read.</div>
|
||||
) : (
|
||||
<div className="small mb-3">
|
||||
<div className="text-secondary">
|
||||
{s.zones.total} zone{s.zones.total === 1 ? "" : "s"}
|
||||
{s.zones.disabled > 0 ? `, ${s.zones.disabled} switched off` : ""}
|
||||
{s.zones.issues.length === 0 ? " — none with a problem." : "."}
|
||||
</div>
|
||||
{s.zones.issues.length > 0 && (
|
||||
<ul className="mb-0">
|
||||
{s.zones.issues.map((z) => (
|
||||
<li key={z.name} className={z.problem === "expired" ? "text-red" : "text-yellow"}>
|
||||
{z.name} — {z.problem === "expired" ? "expired: it no longer answers" : "cannot sync with its primary"}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h4>Block lists and the rest</h4>
|
||||
<ul className="small mb-0">
|
||||
<li>
|
||||
{s.settings.blockLists.count === 0 ? (
|
||||
"No block lists are set up."
|
||||
) : (
|
||||
<>
|
||||
{s.settings.blockLists.count} block list{s.settings.blockLists.count === 1 ? "" : "s"}
|
||||
{st && st.blockListZones !== null ? `, ${st.blockListZones.toLocaleString()} names on them` : ""}
|
||||
{s.settings.blockLists.nextUpdate ? (
|
||||
s.blockListsOverdueMs !== null ? (
|
||||
<span className="text-yellow">
|
||||
{" "}
|
||||
— update was due <TimeAgo value={s.settings.blockLists.nextUpdate} />
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-secondary"> — next update {new Date(s.settings.blockLists.nextUpdate).toLocaleString()}</span>
|
||||
)
|
||||
) : (
|
||||
""
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
{st && (st.allowedZones !== null || st.blockedZones !== null) && (
|
||||
<li className="text-secondary">
|
||||
Allowed by hand: {(st.allowedZones ?? 0).toLocaleString()} · blocked by hand: {(st.blockedZones ?? 0).toLocaleString()}
|
||||
</li>
|
||||
)}
|
||||
<li className="text-secondary">
|
||||
Recursion: {s.settings.recursion ?? "—"} · DNSSEC validation: {s.settings.dnssecValidation === null ? "—" : s.settings.dnssecValidation ? "on" : "off"}
|
||||
</li>
|
||||
{s.dhcp && (
|
||||
<li className="text-secondary">
|
||||
DHCP: {s.dhcp.scopes} scope{s.dhcp.scopes === 1 ? "" : "s"} ({s.dhcp.enabledScopes} on), {s.dhcp.leases.toLocaleString()} lease{s.dhcp.leases === 1 ? "" : "s"}
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Technitium DNS Server: whether DNS really answers, whether it blocks, what it has done in the last day, how its zones and block lists are, and how it is doing. */
|
||||
export default function TechnitiumDns() {
|
||||
const [data, setData] = useState<TechnitiumInstance[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
const load = () =>
|
||||
api.technitium
|
||||
.list()
|
||||
.then((r) => {
|
||||
setData(r.instances);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(readableError(err)));
|
||||
void load();
|
||||
const t = setInterval(load, 60_000);
|
||||
return () => clearInterval(t);
|
||||
}, []);
|
||||
return (
|
||||
<>
|
||||
<h2 className="page-title">Technitium DNS</h2>
|
||||
<p className="text-secondary">
|
||||
Read every two minutes (see <Link to="/integrations">Integrations</Link>), with a real DNS question put to it each time — its web console can be up while DNS is not. Nothing is changed. <strong>DNS that stops answering</strong>, <strong>blocking left off for an hour</strong>,{" "}
|
||||
<strong>block lists that stopped updating</strong> and <strong>an expired or unsynced zone</strong> are alerts — see <Link to="/alerts">Alerts</Link>. Technitium does not report the CPU, memory or disk of the machine it runs on: put a <Link to="/servers">server agent</Link> there for that.
|
||||
</p>
|
||||
<ErrorNotice error={error} />
|
||||
{!data && !error && <BlockSkeleton lines={4} />}
|
||||
{data && data.length === 0 && (
|
||||
<div className="card">
|
||||
<div className="card-body">
|
||||
<EmptyState title="No Technitium DNS Server connected" hint="Add one under Integrations with the address of its web console and an API token (Administration → Sessions → Create Token). Zones and records are connected separately, under DNS." />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{data?.map((a) => <Card key={a.id} a={a} />)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -31,6 +31,7 @@ export const TYPE_LABELS: Record<IntegrationType, string> = {
|
||||
radarr: "Radarr",
|
||||
prowlarr: "Prowlarr",
|
||||
adguard: "AdGuard Home",
|
||||
technitium: "Technitium DNS",
|
||||
grafana: "Grafana",
|
||||
lidarr: "Lidarr",
|
||||
readarr: "Readarr",
|
||||
@@ -67,6 +68,7 @@ export const TYPE_PAGES: Record<IntegrationType, string> = {
|
||||
radarr: "/media",
|
||||
prowlarr: "/media",
|
||||
adguard: "/adguard",
|
||||
technitium: "/technitium",
|
||||
grafana: "/grafana",
|
||||
lidarr: "/media",
|
||||
readarr: "/media",
|
||||
@@ -77,13 +79,13 @@ export const TYPE_GROUPS: { id: string; label: string; types: IntegrationType[]
|
||||
{ id: "infrastructure", label: "Infrastructure", types: ["proxmox", "synology", "dockhand", "hetzner", "fragnet", "tailscale"] },
|
||||
{ id: "apps", label: "Apps", types: ["homeassistant", "jellyfin", "sonarr", "radarr", "lidarr", "readarr", "prowlarr", "immich", "paperless", "nextcloud", "authentik"] },
|
||||
{ id: "backups", label: "Backups", types: ["pbs"] },
|
||||
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard"] },
|
||||
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard", "technitium"] },
|
||||
{ id: "monitoring", label: "Monitoring", types: ["uptimekuma", "prometheus", "grafana", "ups", "speedtest"] },
|
||||
{ id: "automation", label: "Automation", types: ["semaphore", "gitea", "osticket", "n8n"] },
|
||||
];
|
||||
|
||||
/** The kinds whose reader can be inspected (Settings → Integrations → Check what can be read): the ones that read through the shared HTTP helper and have a reader to run. */
|
||||
export const INSPECTABLE: IntegrationType[] = ["authentik", "immich", "jellyfin", "netbox", "nextcloud", "paperless", "prometheus", "hetzner", "speedtest", "fragnet", "sonarr", "radarr", "prowlarr", "lidarr", "readarr", "adguard", "grafana"];
|
||||
export const INSPECTABLE: IntegrationType[] = ["authentik", "immich", "jellyfin", "netbox", "nextcloud", "paperless", "prometheus", "hetzner", "speedtest", "fragnet", "sonarr", "radarr", "prowlarr", "lidarr", "readarr", "adguard", "technitium", "grafana"];
|
||||
|
||||
/** The group a kind belongs to; a kind nobody has placed yet falls in "Other" rather than vanishing. */
|
||||
export function groupOfType(type: IntegrationType): { id: string; label: string } {
|
||||
|
||||
Reference in new issue
Block a user