Sloth Manager tracked every API call made to DNS providers for connectivity troubleshooting. Port that here, generalized to cover every outbound integration this app makes, not just DNS -- Tailscale, Proxmox, Synology, Semaphore, Gitea, and Dockhand calls now show up too, since a broken API token or unreachable host on any of them is just as worth diagnosing. New services/diagLog.ts: a generic withDiagLogging(source, adapter) wraps every async method of any adapter object with timing + success/failure recording, without touching a single adapter's request/error-handling internals -- every DNS and integration adapter interface here is already just a flat set of async methods, so this one wrapper works for all twelve of them. Applied it at each adapter factory's own return statement (one line each) rather than at the route layer, so background jobs that construct adapters directly (the Tailscale key-expiry scheduler, IPAM sync, agent-driven Proxmox lookups) get logged too, not just requests through routes/integrations.ts. New diag_log table (ring-buffered to the last 500 rows, mirroring Sloth Manager's approach -- this is for live troubleshooting, not a durable record) and admin-only GET/DELETE /api/diag-log routes, source/ result filters, pagination. New admin-only Diagnostic Log page: filterable, paginated table with a Clear button. Also introduces the shared useSortable hook + SortableTh component used here for the first time -- a follow-up commit applies the same sorting (and CSV export) to the rest of the app's tables, per the same request. Verified end-to-end against a temp SQLite DB with real migrations: a fake wrapped adapter's successful and failing calls both land correctly in the log with the right source/operation/latency/error, and the source/ok filters and clear-log operation all behave correctly. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
185 lines
6.6 KiB
TypeScript
185 lines
6.6 KiB
TypeScript
/**
|
|
* 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";
|
|
import { withDiagLogging } from "../../services/diagLog.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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
}
|
|
|
|
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 withDiagLogging("loopia", { listZones, listRecords, addRecord, updateRecord, deleteRecord });
|
|
}
|