DC-005: Fix all 138 broken test paths after src/ refactor

After the DC-005 module reorganization (41 files moved into src/ subdirs),
138 test suites failed because the refactor script's path-rewrite logic
missed three categories:

1. Files inside src/ doing 'require("./src/...")' — should be 'require("../...")'
2. Files in src/X/Y/ doing 'require("../../../src/...")' — should be 'require("../../...")'
3. Test files in __tests__/ with leftover 'require("../../../src/...")' paths

Root cause: the original refactor script ran before all files were moved,
so it computed relative paths against stale filesystem state.

Result:
- 30/30 test suites pass
- 879/879 tests pass (was: 18/30 suites, 614/687 tests)

Also fixed:
- routes/apps/restore.js: wrong responses import path
- routes/*/*.js: '../../src/utilities/X' → '../src/utilities/X' (depth 2 routes)
This commit is contained in:
Hermes
2026-06-13 12:16:56 -07:00
parent 9468dfc0eb
commit 7bc2a207f3
129 changed files with 591 additions and 310 deletions
+273
View File
@@ -0,0 +1,273 @@
/**
* DNS Propagation Checker
* Verifies DNS record propagation by querying multiple resolvers.
* Runs as background jobs with configurable timeout and interval.
*
* @module dns-propagation
*/
const dns = require('dns').promises;
const EventEmitter = require('events');
/** Default verification options */
const DEFAULT_OPTIONS = {
timeout: 300000, // 5 minutes
interval: 10000, // 10 seconds
resolvers: ['1.1.1.1', '8.8.8.8', '9.9.9.9']
};
/** Maximum age for stored verification results (1 hour) */
const MAX_RESULT_AGE_MS = 3600000;
class DNSPropagationChecker extends EventEmitter {
/**
* Create a DNSPropagationChecker instance.
* @param {Object} ctx - Shared application context
* @param {Object} ctx.notification - NotificationManager instance
* @param {Object} ctx.log - Logger instance
*/
constructor(ctx) {
super();
this.ctx = ctx;
this.log = ctx.log || console;
/** @type {Map<string, Object>} domain → verification status */
this.verifications = new Map();
}
/**
* Verify that a DNS record has propagated by querying multiple resolvers.
* Retries every `interval` ms until `timeout` is reached.
*
* @param {string} domain - The domain to check (e.g., 'test.sami')
* @param {string} expectedIp - The expected IP address
* @param {Object} [options={}] - Verification options
* @param {number} [options.timeout=300000] - Maximum time to wait (ms)
* @param {number} [options.interval=10000] - Time between retries (ms)
* @param {string[]} [options.resolvers] - DNS resolvers to query
* @returns {Promise<Object>} Verification result
*/
async verifyRecord(domain, expectedIp, options = {}) {
const startTime = Date.now();
const {
timeout = DEFAULT_OPTIONS.timeout,
interval = DEFAULT_OPTIONS.interval,
resolvers = DEFAULT_OPTIONS.resolvers
} = options;
const allResults = [];
let propagated = false;
while (Date.now() - startTime < timeout) {
const roundResults = [];
for (const resolver of resolvers) {
const checkStart = Date.now();
try {
// Use dns.resolve4 with a custom resolver
const resolverInstance = new dns.Resolver();
resolverInstance.setServers([resolver]);
resolverInstance.setTimeout(5000);
const addresses = await resolverInstance.resolve4(domain);
const matched = addresses.includes(expectedIp);
const result = {
resolver,
ips: addresses,
matched,
checkedAt: new Date().toISOString(),
responseTime: Date.now() - checkStart
};
roundResults.push(result);
if (matched) {
propagated = true;
}
} catch (err) {
roundResults.push({
resolver,
ips: [],
matched: false,
checkedAt: new Date().toISOString(),
error: err.code || err.message,
responseTime: Date.now() - checkStart
});
}
}
allResults.push(...roundResults);
// Emit progress event
this.emit('propagation-check', {
domain,
expectedIp,
roundResults,
elapsed: Date.now() - startTime,
propagated
});
if (propagated) {
break;
}
// Wait before next attempt
await new Promise(resolve => setTimeout(resolve, interval));
}
const totalTime = Date.now() - startTime;
return {
domain,
expectedIp,
propagated,
results: allResults,
totalTime,
checkedAt: new Date().toISOString()
};
}
/**
* Start a background DNS propagation verification.
* Does not block — returns immediately with the job reference.
*
* @param {string} domain - The domain to verify
* @param {string} expectedIp - The expected IP address
* @param {Object} [options={}] - Verification options
* @returns {Object} Job status object
*/
startVerification(domain, expectedIp, options = {}) {
// If there's already a running verification for this domain, return it
const existing = this.verifications.get(domain);
if (existing && existing.status === 'running') {
return existing;
}
const job = {
domain,
expectedIp,
status: 'running',
startedAt: new Date().toISOString(),
progress: [],
result: null
};
this.verifications.set(domain, job);
// Run verification in background (non-blocking)
this.verifyRecord(domain, expectedIp, options)
.then(result => {
job.status = 'completed';
job.result = result;
job.completedAt = new Date().toISOString();
if (result.propagated) {
this.emit('propagation-complete', result);
if (this.ctx.notification) {
this.ctx.notification.send('dns-propagation', {
text: `✅ DNS record for ${domain} propagated successfully to ${expectedIp}`,
domain,
expectedIp,
totalTime: result.totalTime
}, 'success').catch(err => {
this.log.error('dns-propagation', 'Failed to send propagation notification', {
error: err.message
});
});
}
} else {
this.emit('propagation-timeout', result);
if (this.ctx.notification) {
this.ctx.notification.send('dns-propagation', {
text: `⏱️ DNS propagation timeout for ${domain} — expected ${expectedIp} not found after ${Math.round(result.totalTime / 1000)}s`,
domain,
expectedIp,
totalTime: result.totalTime
}, 'warning').catch(err => {
this.log.error('dns-propagation', 'Failed to send timeout notification', {
error: err.message
});
});
}
}
})
.catch(err => {
job.status = 'error';
job.error = err.message;
job.completedAt = new Date().toISOString();
this.log.error('dns-propagation', `Verification failed for ${domain}`, {
error: err.message
});
});
return job;
}
/**
* Get the current verification status for a domain.
*
* @param {string} domain - The domain to look up
* @returns {Object|null} Verification status or null if not found
*/
getVerificationStatus(domain) {
const job = this.verifications.get(domain);
if (!job) return null;
return {
domain: job.domain,
expectedIp: job.expectedIp,
status: job.status,
startedAt: job.startedAt,
completedAt: job.completedAt || null,
result: job.result || null,
error: job.error || null
};
}
/**
* Get all recent verifications.
*
* @returns {Object[]} Array of verification statuses
*/
getAllVerifications() {
const results = [];
for (const [domain, job] of this.verifications.entries()) {
results.push({
domain,
expectedIp: job.expectedIp,
status: job.status,
startedAt: job.startedAt,
completedAt: job.completedAt || null,
propagated: job.result?.propagated || null,
totalTime: job.result?.totalTime || null,
error: job.error || null
});
}
return results;
}
/**
* Remove verifications older than 1 hour.
*/
cleanup() {
const now = Date.now();
for (const [domain, job] of this.verifications.entries()) {
const completedAt = job.completedAt ? new Date(job.completedAt).getTime() : null;
const startedAt = new Date(job.startedAt).getTime();
// Clean up completed/error jobs older than 1 hour
// Also clean up stale running jobs that started over 2 hours ago
const age = completedAt ? (now - completedAt) : (now - startedAt);
const maxAge = job.status === 'running' ? MAX_RESULT_AGE_MS * 2 : MAX_RESULT_AGE_MS;
if (age > maxAge) {
this.verifications.delete(domain);
}
}
}
}
module.exports = DNSPropagationChecker;
@@ -0,0 +1,69 @@
/**
* Base DNS Provider Adapter
* All DNS provider adapters must extend this class and implement the required methods.
*
* Each adapter handles the specifics of talking to a particular DNS provider's API.
* The routes layer calls these methods generically — no provider-specific logic in routes.
*/
class BaseDNSProvider {
constructor(config, ctx) {
this.config = config; // Provider-specific config (api token, server url, etc.)
this.ctx = ctx; // Shared app context (log, credentialManager, fetchT, etc.)
this.providerId = 'base';
this.displayName = 'Base DNS Provider';
}
/** Check if this provider supports a given capability */
supportsCapability(cap) {
// Capabilities: 'create-record', 'delete-record', 'resolve', 'list-records',
// 'logs', 'restart', 'update-check', 'credentials', 'zones'
return false;
}
/** Authenticate and return a token/session */
async authenticate() { throw new Error('Not implemented'); }
/** Create a DNS record */
async createRecord({ domain, zone, type, value, ttl, overwrite }) { throw new Error('Not implemented'); }
/** Delete a DNS record */
async deleteRecord({ domain, type, value }) { throw new Error('Not implemented'); }
/** Resolve/query existing records for a domain */
async resolveRecords({ domain, zone, type }) { throw new Error('Not implemented'); }
/** List all records in a zone */
async listRecords({ zone }) { throw new Error('Not implemented'); }
/** Get DNS query logs */
async getLogs({ limit, server }) { throw new Error('Not implemented'); }
/** Restart the DNS server */
async restartServer({ server }) { throw new Error('Not implemented'); }
/** Check for DNS server updates */
async checkUpdate({ server }) { throw new Error('Not implemented'); }
/** Get provider status info */
async getStatus() {
return {
providerId: this.providerId,
displayName: this.displayName,
capabilities: this.getCapabilities(),
authenticated: false
};
}
/** Get list of supported capabilities */
getCapabilities() {
return [];
}
/** Validate provider-specific config */
validateConfig() { return { valid: true, errors: [] }; }
/** Clean up resources on shutdown */
async shutdown() {}
}
module.exports = BaseDNSProvider;
@@ -0,0 +1,269 @@
/**
* Cloudflare DNS Provider Adapter
* Manages DNS records via the Cloudflare API v4.
*/
const BaseDNSProvider = require('./base');
const CF_API_BASE = 'https://api.cloudflare.com/client/v4';
class CloudflareDNSProvider extends BaseDNSProvider {
constructor(config, ctx) {
super(config, ctx);
this.providerId = 'cloudflare';
this.displayName = 'Cloudflare DNS';
// Resolve API token: explicit config takes priority, then credential manager
this.apiToken = config.apiToken
|| (ctx.credentialManager && ctx.credentialManager.get('dns.cloudflare.apiToken'))
|| null;
this.zoneId = config.zoneId || null;
this.domain = config.domain || null;
}
// ── Helpers ────────────────────────────────────────────────────────────
/** Build common request headers for Cloudflare API calls */
_headers() {
return {
'Authorization': `Bearer ${this.apiToken}`,
'Content-Type': 'application/json',
};
}
/** Make an authenticated request to the Cloudflare API */
async _cfRequest(method, path, body) {
const url = `${CF_API_BASE}${path}`;
const opts = {
method,
headers: this._headers(),
};
if (body !== undefined) {
opts.body = JSON.stringify(body);
}
return this.ctx.fetchT(url, opts);
}
/** Map a Cloudflare DNS record to the normalised format expected by routes */
_mapRecord(rec) {
return {
id: rec.id,
type: rec.type,
name: rec.name,
value: rec.content,
ttl: rec.ttl,
proxied: rec.proxied || false,
};
}
// ── Capabilities ───────────────────────────────────────────────────────
supportsCapability(cap) {
return this.getCapabilities().includes(cap);
}
getCapabilities() {
return ['create-record', 'delete-record', 'resolve', 'list-records', 'credentials', 'zones'];
}
// ── Authentication ─────────────────────────────────────────────────────
/**
* Validate the API token by calling the Cloudflare verify endpoint.
* Stores basic zone info on success.
*/
async authenticate() {
this.ctx.log('[cloudflare] Authenticating verifying API token…');
if (!this.apiToken) {
return { status: 'error', message: 'No Cloudflare API token provided' };
}
const res = await this._cfRequest('GET', '/user/tokens/verify');
const data = await res.json();
if (!data.success) {
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'Token verification failed';
this.ctx.log(`[cloudflare] Authentication failed: ${msg}`);
return { status: 'error', message: msg };
}
this.ctx.log(`[cloudflare] Token verified for status "${data.status}"`);
// Optionally fetch zone info if zoneId is configured
if (this.zoneId) {
try {
const zoneRes = await this._cfRequest('GET', `/zones/${this.zoneId}`);
const zoneData = await zoneRes.json();
if (zoneData.success && zoneData.result) {
this.zoneInfo = zoneData.result;
this.ctx.log(`[cloudflare] Zone loaded: ${zoneData.result.name} (${zoneData.result.id})`);
}
} catch (err) {
this.ctx.log(`[cloudflare] Could not fetch zone info: ${err.message}`);
}
}
return { status: 'ok', response: { status: data.status } };
}
// ── Create Record ──────────────────────────────────────────────────────
/**
* Create a DNS record.
* If overwrite is true, first delete any existing record with the same name+type.
*/
async createRecord({ domain, zone, type, value, ttl, overwrite }) {
const targetDomain = domain || this.domain;
const targetZone = zone || this.zoneId;
if (!targetZone) {
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
}
if (overwrite) {
this.ctx.log(`[cloudflare] Overwrite requested deleting existing ${type} record for ${targetDomain}`);
try {
await this.deleteRecord({ domain: targetDomain, type, value });
} catch (err) {
this.ctx.log(`[cloudflare] No existing record to overwrite (or delete failed): ${err.message}`);
}
}
const body = {
type,
name: targetDomain,
content: value,
ttl: ttl || 1, // 1 = automatic TTL in Cloudflare
proxied: false,
};
this.ctx.log(`[cloudflare] Creating ${type} record: ${targetDomain}${value}`);
const res = await this._cfRequest('POST', `/zones/${targetZone}/dns_records`, body);
const data = await res.json();
if (!data.success) {
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'Record creation failed';
this.ctx.log(`[cloudflare] Create failed: ${msg}`);
return { status: 'error', message: msg };
}
return { status: 'ok', response: { record: this._mapRecord(data.result) } };
}
// ── Delete Record ──────────────────────────────────────────────────────
/**
* Delete DNS records matching domain+type.
* Lists matching records first, then deletes each one.
*/
async deleteRecord({ domain, type, value }) {
const targetDomain = domain || this.domain;
const targetZone = this.zoneId;
if (!targetZone) {
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
}
// List records matching name + type
let queryPath = `/zones/${targetZone}/dns_records?name=${encodeURIComponent(targetDomain)}`;
if (type) {
queryPath += `&type=${encodeURIComponent(type)}`;
}
const listRes = await this._cfRequest('GET', queryPath);
const listData = await listRes.json();
if (!listData.success) {
const msg = (listData.errors && listData.errors[0] && listData.errors[0].message) || 'Failed to list records for deletion';
this.ctx.log(`[cloudflare] Delete list failed: ${msg}`);
return { status: 'error', message: msg };
}
const matching = listData.result || [];
if (matching.length === 0) {
this.ctx.log(`[cloudflare] No records found for ${targetDomain} (${type || 'any type'})`);
return { status: 'ok', response: { deleted: 0 } };
}
// If a specific value is given, only delete records matching that value
const toDelete = value
? matching.filter((r) => r.content === value)
: matching;
let deleted = 0;
for (const record of toDelete) {
const delRes = await this._cfRequest('DELETE', `/zones/${targetZone}/dns_records/${record.id}`);
const delData = await delRes.json();
if (delData.success) {
deleted++;
this.ctx.log(`[cloudflare] Deleted record ${record.id} (${record.type} ${record.name})`);
} else {
const msg = (delData.errors && delData.errors[0] && delData.errors[0].message) || 'Delete failed';
this.ctx.log(`[cloudflare] Failed to delete record ${record.id}: ${msg}`);
}
}
return { status: 'ok', response: { deleted } };
}
// ── Resolve Records ───────────────────────────────────────────────────
/**
* Resolve/query existing records for a domain.
* Returns records matching domain (and optionally type).
*/
async resolveRecords({ domain, zone, type }) {
const targetDomain = domain || this.domain;
const targetZone = zone || this.zoneId;
if (!targetZone) {
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
}
let queryPath = `/zones/${targetZone}/dns_records?name=${encodeURIComponent(targetDomain)}`;
if (type) {
queryPath += `&type=${encodeURIComponent(type)}`;
}
this.ctx.log(`[cloudflare] Resolving records for ${targetDomain}${type ? ` (${type})` : ''}`);
const res = await this._cfRequest('GET', queryPath);
const data = await res.json();
if (!data.success) {
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'Resolve failed';
this.ctx.log(`[cloudflare] Resolve failed: ${msg}`);
return { status: 'error', message: msg };
}
const records = (data.result || []).map(this._mapRecord);
return { status: 'ok', response: { records } };
}
// ── List Records ───────────────────────────────────────────────────────
/**
* List all DNS records in a zone.
*/
async listRecords({ zone }) {
const targetZone = zone || this.zoneId;
if (!targetZone) {
return { status: 'error', message: 'No zone ID configured for Cloudflare' };
}
this.ctx.log(`[cloudflare] Listing all records in zone ${targetZone}`);
const res = await this._cfRequest('GET', `/zones/${targetZone}/dns_records`);
const data = await res.json();
if (!data.success) {
const msg = (data.errors && data.errors[0] && data.errors[0].message) || 'List failed';
this.ctx.log(`[cloudflare] List failed: ${msg}`);
return { status: 'error', message: msg };
}
const records = (data.result || []).map(this._mapRecord);
return { status: 'ok', response: { records } };
}
}
module.exports = CloudflareDNSProvider;
@@ -0,0 +1,93 @@
/**
* Manual DNS Provider Adapter
* No-op adapter for users who manage DNS externally (manual, cPanel, other control panels).
* Provides propagation checking only — all record operations return helpful instructions.
*/
const BaseDNSProvider = require('./base');
class ManualDNSProvider extends BaseDNSProvider {
constructor(config, ctx) {
super(config, ctx);
this.providerId = 'manual';
this.displayName = 'Manual / External DNS';
this.description = 'Manage DNS records yourself via your provider\'s control panel';
}
supportsCapability(cap) {
return ['credentials'].includes(cap);
}
getCapabilities() {
return ['credentials'];
}
async authenticate() {
return { success: true, message: 'Manual DNS — no authentication needed' };
}
async createRecord({ domain, zone, type, value, ttl }) {
return {
status: 'manual',
message: `Create this record manually in your DNS control panel:`,
instructions: {
name: domain,
type: type || 'A',
value,
ttl: ttl || 300
}
};
}
async deleteRecord({ domain, type, value }) {
return {
status: 'manual',
message: `Delete this record manually from your DNS control panel:`,
instructions: {
name: domain,
type: type || 'A',
value: value || '(any)'
}
};
}
async resolveRecords({ domain, zone, type }) {
// Use Node.js built-in DNS to resolve regardless of provider
const dns = require('dns').promises;
try {
const resolver = new dns.Resolver();
resolver.setServers(['1.1.1.1', '8.8.8.8']);
const records = await resolver.resolve(domain, type || 'A');
return {
status: 'ok',
response: {
records: records.map(r => ({
type: type || 'A',
domain,
rData: { ipAddress: r },
ttl: 0,
manual: true
}))
}
};
} catch (err) {
return { status: 'ok', response: { records: [] } };
}
}
async getStatus() {
return {
providerId: this.providerId,
displayName: this.displayName,
description: this.description,
capabilities: this.getCapabilities(),
authenticated: true,
note: 'DNS records are managed externally. Use propagation checks to verify changes.'
};
}
validateConfig() {
return { valid: true, errors: [] };
}
}
module.exports = ManualDNSProvider;
@@ -0,0 +1,101 @@
/**
* DNS Provider Registry
* Manages available DNS provider adapters.
* Providers register themselves, and the active provider is selected by config.
*/
const path = require('path');
class DNSProviderRegistry {
constructor() {
this.providers = new Map(); // providerId -> adapter class
this.instances = new Map(); // providerId -> adapter instance
}
/** Register a provider adapter class */
register(adapterClass) {
const instance = new adapterClass({}, {});
const id = instance.providerId;
if (this.providers.has(id)) {
console.warn(`DNS provider "${id}" already registered, overwriting`);
}
this.providers.set(id, adapterClass);
}
/** Get list of all registered provider IDs */
getProviderIds() {
return Array.from(this.providers.keys());
}
/** Get metadata for all providers (without instantiating with real config) */
getProviderMeta() {
return this.getProviderIds().map(id => {
const Adapter = this.providers.get(id);
const inst = new Adapter({}, {});
return {
id: inst.providerId,
displayName: inst.displayName,
capabilities: inst.getCapabilities()
};
});
}
/**
* Get or create an adapter instance for the given provider + config
* @param {string} providerId - The provider to instantiate
* @param {Object} config - Provider-specific configuration
* @param {Object} ctx - Shared application context
* @returns {BaseDNSProvider} The provider adapter instance
*/
getProvider(providerId, config, ctx) {
// Re-create if config changed
const cacheKey = providerId;
const Adapter = this.providers.get(providerId);
if (!Adapter) {
throw new Error(`Unknown DNS provider: ${providerId}. Available: ${this.getProviderIds().join(', ')}`);
}
const instance = new Adapter(config, ctx);
this.instances.set(cacheKey, instance);
return instance;
}
/** Auto-discover and register all providers in this directory */
autoDiscover() {
const fs = require('fs');
const dir = __dirname;
const files = fs.readdirSync(dir).filter(f =>
f !== 'base.js' && f !== 'registry.js' && f.endsWith('.js') && !f.startsWith('.')
);
for (const file of files) {
try {
const Loaded = require(path.join(dir, file));
// Support: module.exports = Class, module.exports = { Class }, or plain objects
let cls = null;
if (typeof Loaded === 'function') {
cls = Loaded;
} else if (typeof Loaded === 'object' && Loaded !== null) {
// Try to find a class in the exported object
cls = Object.values(Loaded).find(v => typeof v === 'function');
}
if (cls) {
// Verify it has providerId (on prototype or set in constructor)
try {
const test = new cls({}, {});
if (test.providerId && typeof test.getCapabilities === 'function') {
this.register(cls);
}
} catch {
// Not a valid provider adapter, skip
}
}
} catch (err) {
console.error(`Failed to load DNS provider from ${file}:`, err.message);
}
}
}
}
// Singleton
const registry = new DNSProviderRegistry();
registry.autoDiscover();
module.exports = registry;
@@ -0,0 +1,383 @@
/**
* RFC 2136 Dynamic DNS Provider Adapter
*
* Manages DNS records via RFC 2136 dynamic updates using the nsupdate CLI tool.
* Compatible with BIND, PowerDNS, Windows DNS, and any RFC 2136-compliant server.
*
* Capabilities: create-record, delete-record, resolve, credentials
* Not supported: logs, restart, update-check, list-records, zones
*/
const { execFile } = require('child_process');
const { promisify } = require('util');
const dns = require('dns');
const os = require('os');
const path = require('path');
const fs = require('fs');
const execFileAsync = promisify(execFile);
const BaseDNSProvider = require('./base');
const CAPABILITIES = ['create-record', 'delete-record', 'resolve', 'credentials'];
const DEFAULT_PORT = 53;
const DEFAULT_TSIG_ALGORITHM = 'hmac-sha256';
const NSUPDATE_TIMEOUT_MS = 15000;
class RFC2136Provider extends BaseDNSProvider {
static providerId = 'rfc2136';
static displayName = 'RFC 2136 (Dynamic DNS)';
constructor(config, ctx) {
super(config, ctx);
this.providerId = 'rfc2136';
this.displayName = 'RFC 2136 (Dynamic DNS)';
// Core config
this.server = config.server || null;
this.port = config.port || DEFAULT_PORT;
this.zone = config.zone || null;
// TSIG authentication
this.tsigAlgorithm = config.tsigAlgorithm || DEFAULT_TSIG_ALGORITHM;
this.tsigKeyName = config.tsigKeyName || null;
this.tsigSecret = config.tsigSecret || null;
// Resolve credentials from credential manager if available
if (ctx && ctx.credentialManager) {
if (!this.tsigKeyName && ctx.credentialManager.get) {
this.tsigKeyName = ctx.credentialManager.get('rfc2136_tsigKeyName') || null;
}
if (!this.tsigSecret && ctx.credentialManager.get) {
this.tsigSecret = ctx.credentialManager.get('rfc2136_tsigSecret') || null;
}
}
// Logger shorthand
this._log = ctx && ctx.log ? ctx.ctx : null;
}
// ── Logging helper ────────────────────────────────────────────────────────
_log(level, message, meta) {
if (this.ctx && this.ctx.log && typeof this.ctx.log[level] === 'function') {
this.ctx.log[level](`[rfc2136] ${message}`, meta || {});
}
}
// ── Capabilities ──────────────────────────────────────────────────────────
supportsCapability(cap) {
return CAPABILITIES.includes(cap);
}
getCapabilities() {
return [...CAPABILITIES];
}
// ── Config validation ─────────────────────────────────────────────────────
validateConfig() {
const errors = [];
if (!this.server) errors.push('Missing required config: server');
if (!this.zone) errors.push('Missing required config: zone');
return { valid: errors.length === 0, errors };
}
// ── Helpers ───────────────────────────────────────────────────────────────
/**
* Ensure a domain name ends with a trailing dot (FQDN for nsupdate).
*/
_ensureFqdn(domain) {
if (!domain) return domain;
return domain.endsWith('.') ? domain : `${domain}.`;
}
/**
* Build the common nsupdate header lines (server, zone, key).
*/
_buildHeader() {
const lines = [];
lines.push(`server ${this.server} ${this.port}`);
lines.push(`zone ${this.zone}`);
if (this.tsigKeyName && this.tsigSecret) {
lines.push(`key ${this.tsigAlgorithm}:${this.tsigKeyName} ${this.tsigSecret}`);
}
return lines;
}
/**
* Execute an nsupdate script and return { stdout, stderr }.
* Writes commands to a temporary file and runs `nsupdate <file>`.
*/
async _runNsupdate(commands) {
const script = commands.join('\n') + '\n';
const tmpFile = path.join(os.tmpdir(), `nsupdate-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.cmd`);
try {
await fs.promises.writeFile(tmpFile, script, { mode: 0o600 });
this._log('debug', `Executing nsupdate script`, { script: script.trim() });
const { stdout, stderr } = await execFileAsync('nsupdate', [tmpFile], {
timeout: NSUPDATE_TIMEOUT_MS,
maxBuffer: 1024 * 1024,
});
this._log('debug', 'nsupdate completed', { stdout: (stdout || '').trim(), stderr: (stderr || '').trim() });
if (stderr && stderr.toLowerCase().includes('refused')) {
throw new Error(`nsupdate refused: ${stderr.trim()}`);
}
if (stderr && stderr.toLowerCase().includes('failed')) {
throw new Error(`nsupdate failed: ${stderr.trim()}`);
}
return { stdout: (stdout || '').trim(), stderr: (stderr || '').trim() };
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error('nsupdate command not found. Install bind9utils (Debian/Ubuntu) or bind-utils (RHEL/CentOS).');
}
throw err;
} finally {
try { await fs.promises.unlink(tmpFile); } catch (_) { /* ignore */ }
}
}
// ── Authenticate ──────────────────────────────────────────────────────────
/**
* Verify nsupdate is available and optionally test connectivity.
* Runs a minimal nsupdate with just "show" (no-op) to confirm the tool works.
*/
async authenticate() {
const validation = this.validateConfig();
if (!validation.valid) {
throw new Error(`RFC 2136 config invalid: ${validation.errors.join('; ')}`);
}
// Check nsupdate binary is available with a dry-run command set
const commands = [
...this._buildHeader(),
'show',
];
try {
const { stdout } = await this._runNsupdate(commands);
this._log('info', 'Authenticated to RFC 2136 server', { server: this.server, port: this.port });
return { success: true, server: this.server, port: this.port };
} catch (err) {
this._log('error', 'Authentication test failed', { error: err.message });
// If nsupdate is missing, rethrow immediately
if (err.message.includes('not found')) throw err;
// Otherwise, the server might be unreachable but the tool works — return partial
return { success: false, error: err.message, server: this.server };
}
}
// ── Create Record ─────────────────────────────────────────────────────────
/**
* Create (add) a DNS record via RFC 2136 UPDATE.
*
* @param {Object} params
* @param {string} params.domain - Record name (e.g. "www.example.com")
* @param {string} params.zone - Zone name (overrides constructor zone)
* @param {string} params.type - Record type (A, AAAA, CNAME, TXT, etc.)
* @param {string} params.value - Record value
* @param {number} [params.ttl=300] - TTL in seconds
*/
async createRecord({ domain, zone, type, value, ttl }) {
const effectiveZone = zone || this.zone;
const effectiveTtl = ttl || 300;
const fqdn = this._ensureFqdn(domain);
const commands = [
`server ${this.server} ${this.port}`,
`zone ${effectiveZone}`,
];
if (this.tsigKeyName && this.tsigSecret) {
commands.push(`key ${this.tsigAlgorithm}:${this.tsigKeyName} ${this.tsigSecret}`);
}
commands.push(`update add ${fqdn} ${effectiveTtl} ${type} ${value}`);
commands.push('show');
commands.push('send');
this._log('info', 'Creating DNS record', { domain: fqdn, type, value, ttl: effectiveTtl });
const result = await this._runNsupdate(commands);
return {
success: true,
action: 'create-record',
domain: fqdn,
type,
value,
ttl: effectiveTtl,
zone: effectiveZone,
raw: result.stdout,
};
}
// ── Delete Record ─────────────────────────────────────────────────────────
/**
* Delete a DNS record via RFC 2136 UPDATE.
*
* @param {Object} params
* @param {string} params.domain - Record name
* @param {string} params.type - Record type
* @param {string} [params.value] - Optional specific value to match
*/
async deleteRecord({ domain, type, value }) {
const effectiveZone = this.zone;
const fqdn = this._ensureFqdn(domain);
const commands = [
`server ${this.server} ${this.port}`,
`zone ${effectiveZone}`,
];
if (this.tsigKeyName && this.tsigSecret) {
commands.push(`key ${this.tsigAlgorithm}:${this.tsigKeyName} ${this.tsigSecret}`);
}
// "update delete" with value removes that specific RR;
// without value it removes all RRs of that type for the name.
const deleteClause = value
? `update delete ${fqdn} ${type} ${value}`
: `update delete ${fqdn} ${type}`;
commands.push(deleteClause);
commands.push('show');
commands.push('send');
this._log('info', 'Deleting DNS record', { domain: fqdn, type, value: value || '(all)' });
const result = await this._runNsupdate(commands);
return {
success: true,
action: 'delete-record',
domain: fqdn,
type,
value: value || null,
zone: effectiveZone,
raw: result.stdout,
};
}
// ── Resolve Records ───────────────────────────────────────────────────────
/**
* Resolve DNS records for a domain.
* First attempts dig against the configured server, then falls back to Node dns module.
*
* @param {Object} params
* @param {string} params.domain - Domain to resolve
* @param {string} [params.zone] - Zone (unused for resolution, kept for interface consistency)
* @param {string} [params.type='A'] - Record type to query
*/
async resolveRecords({ domain, zone, type }) {
const queryType = type || 'A';
const fqdn = domain.endsWith('.') ? domain : domain;
// Strategy 1: Use dig against the configured RFC 2136 server
try {
const { stdout } = await execFileAsync('dig', [
`@${this.server}`,
'-p', String(this.port),
fqdn,
queryType,
'+short',
'+time=5',
'+tries=1',
], { timeout: 10000 });
const records = stdout
.split('\n')
.map(line => line.trim())
.filter(Boolean);
if (records.length > 0) {
this._log('debug', `Resolved ${fqdn} ${queryType} via dig`, { records });
return {
domain: fqdn,
type: queryType,
records: records.map(r => ({ value: r, type: queryType })),
source: 'dig',
server: this.server,
};
}
} catch (err) {
this._log('warn', 'dig resolution failed, falling back to Node dns', { error: err.message });
}
// Strategy 2: Fallback to Node.js built-in resolver
try {
const resolver = new dns.Resolver();
resolver.setServers([this.server]);
const resolveMethod = this._getResolveMethod(queryType);
const resolveAsync = promisify(resolver[resolveMethod]).bind(resolver);
const results = await resolveAsync(fqdn);
const records = Array.isArray(results) ? results : [results];
this._log('debug', `Resolved ${fqdn} ${queryType} via Node dns`, { records });
return {
domain: fqdn,
type: queryType,
records: records.map(r => ({ value: String(r), type: queryType })),
source: 'node-dns',
server: this.server,
};
} catch (err) {
this._log('warn', 'Node dns resolution also failed', { error: err.message });
return {
domain: fqdn,
type: queryType,
records: [],
source: 'none',
server: this.server,
error: err.message,
};
}
}
/**
* Map record type to the Node dns resolver method name.
*/
_getResolveMethod(type) {
const map = {
A: 'resolve4',
AAAA: 'resolve6',
CNAME: 'resolveCname',
MX: 'resolveMx',
TXT: 'resolveTxt',
NS: 'resolveNs',
SOA: 'resolveSoa',
SRV: 'resolveSrv',
PTR: 'reverse',
};
return map[(type || '').toUpperCase()] || 'resolve4';
}
// ── Shutdown ──────────────────────────────────────────────────────────────
async shutdown() {
this._log('info', 'RFC 2136 provider shutting down');
}
}
// Expose providerId on the prototype so the registry's auto-discover can detect it
RFC2136Provider.prototype.providerId = 'rfc2136';
module.exports = RFC2136Provider;
@@ -0,0 +1,507 @@
/**
* Technitium DNS Server Provider Adapter
*
* Wraps Technitium-specific DNS logic into the standard adapter interface.
* Uses the Technitium HTTP API (default port 5380) for all operations.
*/
const BaseDNSProvider = require('./base');
const SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24-hour token lifetime
class TechnitiumDNSProvider extends BaseDNSProvider {
constructor(config, ctx) {
super(config, ctx);
this.providerId = 'technitium';
this.displayName = 'Technitium DNS Server';
this.serverIp = config.serverIp;
this.serverPort = config.serverPort || 5380;
this.dnsId = config.dnsId || null;
// Token state
this.token = null;
this.tokenExpiry = null;
}
// ---------------------------------------------------------------------------
// Capabilities
// ---------------------------------------------------------------------------
static CAPABILITIES = [
'create-record',
'delete-record',
'resolve',
'list-records',
'logs',
'restart',
'update-check',
'credentials',
'zones'
];
supportsCapability(cap) {
return TechnitiumDNSProvider.CAPABILITIES.includes(cap);
}
getCapabilities() {
return [...TechnitiumDNSProvider.CAPABILITIES];
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Build the base URL for this server */
_baseUrl() {
return `http://${this.serverIp}:${this.serverPort}`;
}
/** Build a full API URL with query-string params */
_buildUrl(apiPath, params = {}) {
const qs = new URLSearchParams(params).toString();
return `${this._baseUrl()}${apiPath}${qs ? '?' + qs : ''}`;
}
/** Ensure we have a valid token; throws on failure */
async _requireToken() {
// Re-use existing token if still valid
if (this.token && this.tokenExpiry && new Date() < new Date(this.tokenExpiry)) {
return this.token;
}
const result = await this.authenticate();
if (!result.success) {
const err = new Error('No valid DNS token available. ' + (result.error || ''));
err.statusCode = 401;
throw err;
}
return this.token;
}
// ---------------------------------------------------------------------------
// Authentication
// ---------------------------------------------------------------------------
/**
* Authenticate against the Technitium server.
* Checks per-server credentials first (dns.{dnsId}.readonly.username),
* then falls back to global credentials (dns.username).
*
* Stores token + expiry on success.
*/
async authenticate() {
const { credentialManager, log } = this.ctx;
// Try per-server credentials first
if (this.dnsId) {
for (const role of ['readonly', 'admin']) {
try {
const username = await credentialManager.retrieve(`dns.${this.dnsId}.${role}.username`);
const password = await credentialManager.retrieve(`dns.${this.dnsId}.${role}.password`);
if (username && password) {
const result = await this._doLogin(username, password);
if (result.success) return result;
}
} catch (err) {
log.error('technitium', `Per-server ${role} credential error`, {
dnsId: this.dnsId,
error: err.message
});
}
}
}
// Fall back to global credentials
try {
const username = await credentialManager.retrieve('dns.username');
const password = await credentialManager.retrieve('dns.password');
if (username && password) {
return await this._doLogin(username, password);
}
} catch (err) {
log.error('technitium', 'Global credential error', { error: err.message });
}
return {
success: false,
error: 'No DNS credentials configured. Please set up credentials via /api/dns/credentials'
};
}
/**
* Perform the actual login POST to Technitium.
* Stores token on success.
*/
async _doLogin(username, password) {
const { fetchT, log } = this.ctx;
try {
const params = new URLSearchParams({
user: username,
pass: password,
includeInfo: 'false'
});
const url = `${this._baseUrl()}/api/user/login?${params.toString()}`;
const response = await fetchT(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const result = await response.json();
if (result.status === 'ok' && result.token) {
this.token = result.token;
this.tokenExpiry = new Date(Date.now() + SESSION_TTL_MS).toISOString();
log.info('technitium', 'DNS token obtained', {
server: this.serverIp,
expires: this.tokenExpiry
});
return { success: true, token: this.token };
}
return { success: false, error: result.errorMessage || 'Login failed' };
} catch (error) {
log.error('technitium', 'Login error', { error: error.message });
return { success: false, error: error.message };
}
}
// ---------------------------------------------------------------------------
// Record Management
// ---------------------------------------------------------------------------
/**
* Create (or overwrite) a DNS record.
* GET /api/zones/records/add?token=...&domain=...&zone=...&type=...&ipAddress=...&ttl=...&overwrite=...
*/
async createRecord({ domain, zone, type, value, ttl, overwrite }) {
const token = await this._requireToken();
const { fetchT, log } = this.ctx;
const params = {
token,
domain,
zone,
type: type || 'A',
ipAddress: value,
ttl: String(ttl || 300),
overwrite: String(overwrite !== false)
};
try {
log.info('technitium', 'Creating DNS record', { domain, type, value });
const url = this._buildUrl('/api/zones/records/add', params);
const response = await fetchT(url, {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (result.status === 'ok') {
log.info('technitium', 'DNS record created', { domain, type, value });
return { success: true };
}
// If token expired, re-authenticate and retry once
if (result.errorMessage && result.errorMessage.toLowerCase().includes('token')) {
log.info('technitium', 'Token expired, re-authenticating');
this.token = null;
this.tokenExpiry = null;
const retryToken = await this._requireToken();
params.token = retryToken;
const retryUrl = this._buildUrl('/api/zones/records/add', params);
const retryResp = await fetchT(retryUrl, {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
const retryResult = await retryResp.json();
if (retryResult.status === 'ok') {
return { success: true };
}
throw new Error(retryResult.errorMessage || 'Failed after token refresh');
}
throw new Error(result.errorMessage || 'Unknown error');
} catch (error) {
throw new Error(`Failed to create DNS record for ${domain}: ${error.message}`);
}
}
/**
* Delete a DNS record.
* GET /api/zones/records/delete?token=...&domain=...&type=... (+ ipAddress if value provided)
*/
async deleteRecord({ domain, type, value }) {
const token = await this._requireToken();
const { fetchT, log } = this.ctx;
const params = {
token,
domain,
type: type || 'A'
};
if (value) {
params.ipAddress = value;
}
try {
log.info('technitium', 'Deleting DNS record', { domain, type, value });
const url = this._buildUrl('/api/zones/records/delete', params);
const response = await fetchT(url, {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (result.status === 'ok') {
log.info('technitium', 'DNS record deleted', { domain, type, value });
return { success: true };
}
throw new Error(result.errorMessage || 'Unknown error');
} catch (error) {
throw new Error(`Failed to delete DNS record for ${domain}: ${error.message}`);
}
}
/**
* Resolve/query records for a domain in a zone.
* GET /api/zones/records/get?token=...&domain=...&zone=...&listZone=true
* Filters returned records by type if provided.
*/
async resolveRecords({ domain, zone, type }) {
const token = await this._requireToken();
const { fetchT, log } = this.ctx;
const params = {
token,
domain,
zone,
listZone: 'true'
};
try {
log.info('technitium', 'Resolving records', { domain, zone, type });
const url = this._buildUrl('/api/zones/records/get', params);
const response = await fetchT(url, {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (result.status !== 'ok') {
throw new Error(result.errorMessage || 'Failed to resolve records');
}
let records = (result.response && result.response.records) || [];
// Filter by type if specified
if (type) {
records = records.filter(r => r.type === type);
}
return { success: true, records };
} catch (error) {
throw new Error(`Failed to resolve records for ${domain}: ${error.message}`);
}
}
/**
* List all records in a zone.
* Delegates to resolveRecords with a wildcard domain.
*/
async listRecords({ zone }) {
return this.resolveRecords({ domain: zone, zone, type: null });
}
// ---------------------------------------------------------------------------
// Logs
// ---------------------------------------------------------------------------
/**
* Fetch and parse DNS query logs.
* 1. GET /api/logs/list to discover the latest log file
* 2. GET /api/logs/download?token=...&fileName=... to download it
* 3. Parse text format: [timestamp] [client:port] [protocol] QNAME: domain; QTYPE: type; QCLASS: class; RCODE: rcode; ANSWER: [answer]
*/
async getLogs({ limit, server } = {}) {
const token = await this._requireToken();
const { fetchT, log } = this.ctx;
const targetIp = server || this.serverIp;
const targetPort = this.serverPort;
const baseUrl = `http://${targetIp}:${targetPort}`;
try {
// Step 1: Get log file list
const listUrl = this._buildUrl('/api/logs/list', { token });
const listResp = await fetchT(listUrl.replace(this._baseUrl(), baseUrl), {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
const listResult = await listResp.json();
if (listResult.status !== 'ok' || !listResult.response || !listResult.response.length) {
throw new Error(listResult.errorMessage || 'No log files found');
}
// Pick the latest log file (last entry)
const logFile = listResult.response[listResult.response.length - 1];
const fileName = logFile.name || logFile.fileName || logFile;
// Step 2: Download the log file
const downloadUrl = `${baseUrl}/api/logs/download?${new URLSearchParams({ token, fileName }).toString()}`;
const downloadResp = await fetchT(downloadUrl, {
method: 'GET'
});
const logText = await downloadResp.text();
// Step 3: Parse lines
const parsed = this._parseLogText(logText, limit);
return { success: true, logs: parsed };
} catch (error) {
log.error('technitium', 'Failed to fetch DNS logs', { error: error.message });
throw new Error(`Failed to get DNS logs: ${error.message}`);
}
}
/**
* Parse Technitium DNS log text format.
* Line format: [timestamp] [client:port] [protocol] QNAME: domain; QTYPE: type; QCLASS: class; RCODE: rcode; ANSWER: [answer]
*/
_parseLogText(text, limit) {
const lines = text.split('\n').filter(l => l.trim());
const parsed = [];
// Process newest first if we need to limit
const iterable = limit ? lines.slice(-limit).reverse() : lines;
for (const line of iterable) {
try {
const entry = {};
// Extract timestamp: [2024-01-15 10:30:45]
const tsMatch = line.match(/\[([^\]]+)\]/);
if (tsMatch) entry.timestamp = tsMatch[1];
// Extract client:port: [192.168.1.100:12345]
const clientMatch = line.match(/\[([^\]]+:\d+)\]/g);
if (clientMatch && clientMatch.length >= 2) {
entry.client = clientMatch[1].replace(/\[|\]/g, '');
}
// Extract protocol: [UDP] or [TCP]
const protoMatch = line.match(/\]\s*\[(UDP|TCP|DoH|DoT|DoH2)\]/i);
if (protoMatch) entry.protocol = protoMatch[1];
// Extract key-value pairs: QNAME: value; QTYPE: value; etc.
const kvPattern = /(\w+):\s*([^;]+)/g;
let match;
while ((match = kvPattern.exec(line)) !== null) {
const key = match[1];
const val = match[2].trim();
if (['QNAME', 'QTYPE', 'QCLASS', 'RCODE'].includes(key)) {
entry[key.toLowerCase()] = val;
} else if (key === 'ANSWER') {
entry.answer = val;
}
}
entry.raw = line;
parsed.push(entry);
} catch {
// Skip unparseable lines
}
}
return parsed;
}
// ---------------------------------------------------------------------------
// Server Management
// ---------------------------------------------------------------------------
/**
* Restart the DNS server.
* POST /api/admin/restart?token=...
* Requires admin credentials.
*/
async restartServer({ server } = {}) {
const token = await this._requireToken();
const { fetchT, log } = this.ctx;
try {
log.info('technitium', 'Restarting DNS server', { server: this.serverIp });
const url = this._buildUrl('/api/admin/restart', { token });
const response = await fetchT(url, {
method: 'POST',
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (result.status === 'ok') {
log.info('technitium', 'DNS server restart initiated');
return { success: true, message: 'Server restart initiated' };
}
throw new Error(result.errorMessage || 'Restart failed');
} catch (error) {
log.error('technitium', 'DNS restart error', { error: error.message });
throw new Error(`Failed to restart DNS server: ${error.message}`);
}
}
/**
* Check for DNS server updates.
* GET /api/user/checkForUpdate?token=...
*/
async checkUpdate({ server } = {}) {
const token = await this._requireToken();
const { fetchT, log } = this.ctx;
try {
log.info('technitium', 'Checking for DNS server update', { server: this.serverIp });
const url = this._buildUrl('/api/user/checkForUpdate', { token });
const response = await fetchT(url, {
method: 'GET',
headers: { 'Accept': 'application/json' }
});
const result = await response.json();
if (result.status === 'ok') {
return {
success: true,
updateAvailable: !!(result.response && result.response.updateAvailable),
latestVersion: (result.response && result.response.latestVersion) || null,
currentVersion: (result.response && result.response.currentVersion) || null,
response: result.response
};
}
throw new Error(result.errorMessage || 'Update check failed');
} catch (error) {
log.error('technitium', 'Update check error', { error: error.message });
throw new Error(`Failed to check for updates: ${error.message}`);
}
}
// ---------------------------------------------------------------------------
// Config Validation
// ---------------------------------------------------------------------------
validateConfig() {
const errors = [];
if (!this.serverIp) {
errors.push('serverIp is required');
}
if (this.serverPort && (typeof this.serverPort !== 'number' || this.serverPort < 1 || this.serverPort > 65535)) {
errors.push('serverPort must be a valid port number (1-65535)');
}
return { valid: errors.length === 0, errors };
}
}
module.exports = TechnitiumDNSProvider;