Add DNS module ported from Sloth Manager

Ports zone/record management across Cloudflare, Loopia, Pi-hole, Azure DNS,
cPanel, and Technitium onto the new stack. Unlike the original (one instance
per provider configured via env vars), providers are now configured through
the UI and support multiple named instances per type, with API
credentials encrypted at rest via the integration_credentials table.

- server/src/dns/adapters/*: each provider ported to a config-based factory
  (no more process.env reads), preserving each provider's original quirks
  (Pi-hole session auth, Azure record-set merging, Loopia XML-RPC, cPanel
  UAPI/API2 fallbacks, Technitium composite record IDs).
- server/src/routes/dns.ts: provider CRUD (admin), a "test connection"
  endpoint, and zone/record browsing+sync+CRUD (operator+), all audit-logged.
- dns_zones_cache/dns_records_cache tables replace Sloth Manager's
  dns-cache.json file, keeping the same "cache is the source of truth for
  display, sync fetches fresh from the provider" behavior.
- web: a DNS page with provider management, zone browsing, and a record
  editor, plus a reusable dynamic provider-config form.

Verified: full build (tsc + vite) passes; a scripted HTTP-layer test against
a running server exercises auth, role gating (403 for viewer), validation
(400 on missing config fields), provider CRUD, credential non-leakage in
list responses, and adapter error propagation (502 against an unreachable
host) — all passing. Real provider connectivity still needs to be checked
against the user's actual DNS accounts.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5 committed 2026-09-14 23:00:30 +02:00
1 parent 89919fdbff
commit 39b1d1fe2e
24 files changed
+2726 -33

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
/**
* Loopia adapter — uses the Loopia XML-RPC API.
* Requires config: username, password
*
* API docs: https://www.loopia.se/api/
*/
import { parseStringPromise } from "xml2js";
import type { DnsAdapter, DnsRecord, DnsRecordInput, DnsZone } from "../types.js";
const ENDPOINT = "https://api.loopia.se/RPCSERV";
export interface LoopiaConfig {
username: string;
password: string;
}
function xmlEscape(s: string): string {
return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function valueXml(v: unknown): string {
if (v === null || v === undefined) return "<value><string></string></value>";
if (typeof v === "boolean") return `<value><boolean>${v ? 1 : 0}</boolean></value>`;
if (typeof v === "number") {
return Number.isInteger(v) ? `<value><int>${v}</int></value>` : `<value><double>${v}</double></value>`;
}
if (typeof v === "string") return `<value><string>${xmlEscape(v)}</string></value>`;
if (Array.isArray(v)) {
return `<value><array><data>${v.map(valueXml).join("")}</data></array></value>`;
}
if (typeof v === "object") {
const members = Object.entries(v as Record<string, unknown>)
.map(([k, val]) => `<member><name>${xmlEscape(k)}</name>${valueXml(val)}</member>`)
.join("");
return `<value><struct>${members}</struct></value>`;
}
return `<value><string>${xmlEscape(String(v))}</string></value>`;
}
function buildRequest(method: string, args: unknown[]): string {
const params = args.map((a) => `<param>${valueXml(a)}</param>`).join("");
return `<?xml version="1.0" encoding="UTF-8"?><methodCall><methodName>${method}</methodName><params>${params}</params></methodCall>`;
}
function parseValue(node: any): any {
if (node.string !== undefined) return Array.isArray(node.string) ? node.string[0] : node.string;
if (node.int !== undefined) return parseInt(Array.isArray(node.int) ? node.int[0] : node.int);
if (node.i4 !== undefined) return parseInt(Array.isArray(node.i4) ? node.i4[0] : node.i4);
if (node.boolean !== undefined) {
const b = Array.isArray(node.boolean) ? node.boolean[0] : node.boolean;
return b === "1" || b === 1 || b === true;
}
if (node.double !== undefined) return parseFloat(Array.isArray(node.double) ? node.double[0] : node.double);
if (node.array) {
const data = node.array[0]?.data?.[0]?.value ?? [];
return data.map(parseValue);
}
if (node.struct) {
const obj: Record<string, any> = {};
for (const member of node.struct[0].member ?? []) {
obj[member.name[0]] = parseValue(member.value[0]);
}
return obj;
}
const keys = Object.keys(node).filter((k) => k !== "_");
if (keys.length > 0) {
const v = node[keys[0]];
return Array.isArray(v) ? v[0] : v;
}
return node._ ?? null;
}
async function xmlRpc(method: string, args: unknown[]): Promise<any> {
const body = buildRequest(method, args);
const res = await fetch(ENDPOINT, {
method: "POST",
headers: { "Content-Type": "text/xml; charset=utf-8" },
body,
});
const text = await res.text();
let parsed;
try {
parsed = await parseStringPromise(text, { explicitArray: true });
} catch {
throw new Error(`Loopia returned invalid XML: ${text.slice(0, 300)}`);
}
const fault = parsed?.methodResponse?.fault;
if (fault) {
const fv = parseValue(fault[0].value[0]);
throw new Error(`Loopia fault ${fv.faultCode}: ${fv.faultString}`);
}
const param = parsed?.methodResponse?.params?.[0]?.param?.[0]?.value?.[0];
const result = param ? parseValue(param) : null;
if (typeof result === "string" && result !== "OK" && !/^\d+$/.test(result)) {
throw new Error(`Loopia returned status: ${result}`);
}
return result;
}
export function createLoopiaAdapter(config: LoopiaConfig): DnsAdapter {
function creds(): [string, string] {
return [config.username, config.password];
}
async function listZones(): Promise<DnsZone[]> {
const domains = await xmlRpc("getDomains", creds());
if (!Array.isArray(domains)) throw new Error(`getDomains returned unexpected value: ${JSON.stringify(domains)}`);
return domains.map((d: any) => ({ id: d.domain, name: d.domain }));
}
async function listRecords(domain: string): Promise<DnsRecord[]> {
const subdomains = await xmlRpc("getSubdomains", [...creds(), domain]);
if (!Array.isArray(subdomains)) {
throw new Error(`getSubdomains returned unexpected value: ${JSON.stringify(subdomains)}`);
}
const allRecords: DnsRecord[] = [];
for (const sub of subdomains) {
const records = await xmlRpc("getZoneRecords", [...creds(), domain, sub]);
if (!Array.isArray(records)) continue;
for (const r of records) {
allRecords.push({
id: `${sub}::${r.record_id}`,
type: r.type,
name: sub === "@" ? domain : `${sub}.${domain}`,
content: r.rdata,
ttl: r.ttl,
priority: r.priority ?? null,
});
}
}
return allRecords;
}
async function addRecord(domain: string, record: DnsRecordInput): Promise<DnsRecord> {
let subdomain = record.name;
if (subdomain.endsWith(`.${domain}`)) subdomain = subdomain.slice(0, -(domain.length + 1));
if (subdomain === domain || subdomain === "") subdomain = "@";
const entry = {
type: record.type,
ttl: Number(record.ttl) || 3600,
priority: Number(record.priority) || 0,
rdata: record.content,
};
await xmlRpc("addZoneRecord", [...creds(), domain, subdomain, entry]);
const displayName = subdomain === "@" ? domain : `${subdomain}.${domain}`;
return {
id: `${subdomain}::new`,
type: record.type,
name: displayName,
content: record.content,
ttl: entry.ttl,
priority: entry.priority ?? null,
};
}
async function updateRecord(domain: string, recordId: string, record: DnsRecordInput): Promise<DnsRecord> {
await deleteRecord(domain, recordId);
return addRecord(domain, record);
}
async function deleteRecord(domain: string, recordId: string): Promise<void> {
const [subdomain, loopiaId] = recordId.split("::");
await xmlRpc("removeZoneRecord", [...creds(), domain, subdomain, parseInt(loopiaId)]);
if (subdomain !== "@") {
const remaining = await xmlRpc("getZoneRecords", [...creds(), domain, subdomain]);
if (!Array.isArray(remaining) || remaining.length === 0) {
await xmlRpc("removeSubdomain", [...creds(), domain, subdomain]);
}
}
}
return { listZones, listRecords, addRecord, updateRecord, deleteRecord };
}