/**
* 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, """);
}
function valueXml(v: unknown): string {
if (v === null || v === undefined) return "";
if (typeof v === "boolean") return `${v ? 1 : 0}`;
if (typeof v === "number") {
return Number.isInteger(v) ? `${v}` : `${v}`;
}
if (typeof v === "string") return `${xmlEscape(v)}`;
if (Array.isArray(v)) {
return `${v.map(valueXml).join("")}`;
}
if (typeof v === "object") {
const members = Object.entries(v as Record)
.map(([k, val]) => `${xmlEscape(k)}${valueXml(val)}`)
.join("");
return `${members}`;
}
return `${xmlEscape(String(v))}`;
}
function buildRequest(method: string, args: unknown[]): string {
const params = args.map((a) => `${valueXml(a)}`).join("");
return `${method}${params}`;
}
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 = {};
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 {
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 {
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 {
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 {
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 {
await deleteRecord(domain, recordId);
return addRecord(domain, record);
}
async function deleteRecord(domain: string, recordId: string): Promise {
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 });
}