Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
37a3282f98 | ||
|
|
1fbe65f524 | ||
|
|
320f21c113 | ||
|
|
5c76c3df97 | ||
|
|
260575c6bd | ||
|
|
e361d9a328 | ||
|
|
aa25bcc053 | ||
|
|
bda08b592e | ||
|
|
0e408974a0 | ||
|
|
f4b35dcc30 | ||
|
|
1c0d765182 | ||
|
|
2cd62208ac | ||
|
|
7557a6364a | ||
|
|
54c4b049a8 | ||
|
|
2de72ed506 | ||
|
|
0aa1c3d077 |
@@ -11,6 +11,7 @@ RUN npm install --production
|
|||||||
COPY *.js ./
|
COPY *.js ./
|
||||||
COPY src/ ./src/
|
COPY src/ ./src/
|
||||||
COPY routes/ ./routes/
|
COPY routes/ ./routes/
|
||||||
|
COPY dns-providers/ ./dns-providers/
|
||||||
COPY openapi.yaml ./
|
COPY openapi.yaml ./
|
||||||
|
|
||||||
# VERSION file holds the short git SHA the image was built from. Committed as
|
# VERSION file holds the short git SHA the image was built from. Committed as
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
1.9.0
|
1.10.0
|
||||||
|
|||||||
@@ -342,7 +342,8 @@ const APP_TEMPLATES = {
|
|||||||
volumes: [
|
volumes: [
|
||||||
"/var/run/docker.sock:/var/run/docker.sock",
|
"/var/run/docker.sock:/var/run/docker.sock",
|
||||||
"/opt/portainer/data:/data"
|
"/opt/portainer/data:/data"
|
||||||
]
|
],
|
||||||
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "portainer",
|
subdomain: "portainer",
|
||||||
defaultPort: 9000,
|
defaultPort: 9000,
|
||||||
@@ -393,7 +394,8 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "louislam/uptime-kuma:latest",
|
image: "louislam/uptime-kuma:latest",
|
||||||
ports: ["{{PORT}}:3001"],
|
ports: ["{{PORT}}:3001"],
|
||||||
volumes: ["/opt/uptime-kuma:/app/data"]
|
volumes: ["/opt/uptime-kuma:/app/data"],
|
||||||
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "uptime",
|
subdomain: "uptime",
|
||||||
defaultPort: 3002,
|
defaultPort: 3002,
|
||||||
@@ -549,7 +551,7 @@ const APP_TEMPLATES = {
|
|||||||
},
|
},
|
||||||
subdomain: "dns2",
|
subdomain: "dns2",
|
||||||
defaultPort: 953,
|
defaultPort: 953,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:53",
|
||||||
subpathSupport: 'strip',
|
subpathSupport: 'strip',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Configure zone files in /opt/bind9/config/",
|
"Configure zone files in /opt/bind9/config/",
|
||||||
@@ -640,14 +642,14 @@ const APP_TEMPLATES = {
|
|||||||
],
|
],
|
||||||
docker: {
|
docker: {
|
||||||
image: "coredns/coredns:latest",
|
image: "coredns/coredns:latest",
|
||||||
ports: ["53:53", "53:53/udp"],
|
ports: ["{{PORT}}:53", "53:53", "53:53/udp"],
|
||||||
volumes: ["/opt/coredns/config:/etc/coredns"],
|
volumes: ["/opt/coredns/config:/etc/coredns"],
|
||||||
environment: {},
|
environment: {},
|
||||||
command: ["-conf", "/etc/coredns/Corefile"]
|
command: ["-conf", "/etc/coredns/Corefile"]
|
||||||
},
|
},
|
||||||
subdomain: "dns4",
|
subdomain: "dns4",
|
||||||
defaultPort: 53,
|
defaultPort: 53,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:53",
|
||||||
subpathSupport: 'strip',
|
subpathSupport: 'strip',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Create Corefile in /opt/coredns/config/",
|
"Create Corefile in /opt/coredns/config/",
|
||||||
@@ -1007,7 +1009,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "adminer:latest",
|
image: "adminer:latest",
|
||||||
ports: ["{{PORT}}:8080"],
|
ports: ["{{PORT}}:8080"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/adminer:/var/www/html"
|
||||||
|
],
|
||||||
environment: {
|
environment: {
|
||||||
"ADMINER_DEFAULT_SERVER": "postgres"
|
"ADMINER_DEFAULT_SERVER": "postgres"
|
||||||
}
|
}
|
||||||
@@ -1099,6 +1103,7 @@ const APP_TEMPLATES = {
|
|||||||
popularity: 85,
|
popularity: 85,
|
||||||
difficulty: "Easy",
|
difficulty: "Easy",
|
||||||
isDashboardWidget: true,
|
isDashboardWidget: true,
|
||||||
|
isStaticSite: true,
|
||||||
widgetSelector: ".weather-widget-container",
|
widgetSelector: ".weather-widget-container",
|
||||||
subdomain: null,
|
subdomain: null,
|
||||||
defaultPort: null,
|
defaultPort: null,
|
||||||
@@ -1126,6 +1131,7 @@ const APP_TEMPLATES = {
|
|||||||
popularity: 80,
|
popularity: 80,
|
||||||
difficulty: "Easy",
|
difficulty: "Easy",
|
||||||
isDashboardWidget: true,
|
isDashboardWidget: true,
|
||||||
|
isStaticSite: true,
|
||||||
widgetSelector: ".clock-widget-container",
|
widgetSelector: ".clock-widget-container",
|
||||||
subdomain: null,
|
subdomain: null,
|
||||||
defaultPort: null,
|
defaultPort: null,
|
||||||
@@ -1908,7 +1914,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "traefik/whoami:latest",
|
image: "traefik/whoami:latest",
|
||||||
ports: ["{{PORT}}:80"],
|
ports: ["{{PORT}}:80"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/whoami/config:/config"
|
||||||
|
],
|
||||||
environment: {}
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "whoami",
|
subdomain: "whoami",
|
||||||
@@ -2233,7 +2241,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "excalidraw/excalidraw:latest",
|
image: "excalidraw/excalidraw:latest",
|
||||||
ports: ["{{PORT}}:80"],
|
ports: ["{{PORT}}:80"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/excalidraw/data:/var/lib/excalidraw"
|
||||||
|
],
|
||||||
environment: {}
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "draw",
|
subdomain: "draw",
|
||||||
@@ -2258,7 +2268,9 @@ const APP_TEMPLATES = {
|
|||||||
docker: {
|
docker: {
|
||||||
image: "corentinth/it-tools:latest",
|
image: "corentinth/it-tools:latest",
|
||||||
ports: ["{{PORT}}:80"],
|
ports: ["{{PORT}}:80"],
|
||||||
volumes: [],
|
volumes: [
|
||||||
|
"/opt/it-tools/config:/config"
|
||||||
|
],
|
||||||
environment: {}
|
environment: {}
|
||||||
},
|
},
|
||||||
subdomain: "tools",
|
subdomain: "tools",
|
||||||
@@ -2417,7 +2429,7 @@ const APP_TEMPLATES = {
|
|||||||
},
|
},
|
||||||
subdomain: "mc",
|
subdomain: "mc",
|
||||||
defaultPort: 25565,
|
defaultPort: 25565,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:25565",
|
||||||
subpathSupport: 'none',
|
subpathSupport: 'none',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Server accepts the Minecraft EULA automatically",
|
"Server accepts the Minecraft EULA automatically",
|
||||||
@@ -2451,7 +2463,7 @@ const APP_TEMPLATES = {
|
|||||||
},
|
},
|
||||||
subdomain: "valheim",
|
subdomain: "valheim",
|
||||||
defaultPort: 2456,
|
defaultPort: 2456,
|
||||||
healthCheck: null,
|
healthCheck: "tcp://localhost:2456",
|
||||||
subpathSupport: 'none',
|
subpathSupport: 'none',
|
||||||
setupInstructions: [
|
setupInstructions: [
|
||||||
"Connect via Steam: Add Server > IP:2456",
|
"Connect via Steam: Add Server > IP:2456",
|
||||||
|
|||||||
@@ -59,6 +59,15 @@ function validateConfig(config) {
|
|||||||
errors.push('dns.servers must be an object');
|
errors.push('dns.servers must be an object');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// DNS provider validation
|
||||||
|
if (config.dns.provider !== undefined) {
|
||||||
|
const validProviders = ['technitium', 'cloudflare', 'rfc2136', 'manual'];
|
||||||
|
if (typeof config.dns.provider !== 'string') {
|
||||||
|
errors.push('dns.provider must be a string');
|
||||||
|
} else if (!validProviders.includes(config.dns.provider)) {
|
||||||
|
warnings.push(`dns.provider "${config.dns.provider}" is not one of: ${validProviders.join(', ')}. It may still work if a custom adapter is installed.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ const DNS_RECORD_TYPES = ['A', 'AAAA', 'CNAME', 'MX', 'TXT', 'NS', 'SRV', 'PTR',
|
|||||||
// ── Docker ──────────────────────────────────────────────────────
|
// ── Docker ──────────────────────────────────────────────────────
|
||||||
const DOCKER = {
|
const DOCKER = {
|
||||||
CONTAINER_PREFIX: 'sami-',
|
CONTAINER_PREFIX: 'sami-',
|
||||||
TIMEOUT: 30000, // 30s — timeout for docker pull/create operations
|
TIMEOUT: 300000, // 300s — timeout for docker pull/create operations
|
||||||
LOG_CONFIG: {
|
LOG_CONFIG: {
|
||||||
Type: 'json-file',
|
Type: 'json-file',
|
||||||
Config: { 'max-size': '10m', 'max-file': '3' } // 30MB max per container
|
Config: { 'max-size': '10m', 'max-file': '3' } // 30MB max per container
|
||||||
|
|||||||
@@ -10,7 +10,26 @@ const lockfile = require('proper-lockfile');
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
|
||||||
const CREDENTIALS_FILE = process.env.CREDENTIALS_FILE || path.join(__dirname, 'credentials.json');
|
// Resolve credentials file path — supports both standard install (/app/credentials.json)
|
||||||
|
// and custom deployments with consolidated data directory (/app/data/credentials.json)
|
||||||
|
function resolveCredentialsFile() {
|
||||||
|
if (process.env.CREDENTIALS_FILE) {
|
||||||
|
return process.env.CREDENTIALS_FILE;
|
||||||
|
}
|
||||||
|
const candidates = [
|
||||||
|
path.join(__dirname, 'credentials.json'),
|
||||||
|
path.join(__dirname, 'data', 'credentials.json'),
|
||||||
|
];
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (fs.existsSync(candidate)) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No existing file — return standard path so first store() creates it there
|
||||||
|
return candidates[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const CREDENTIALS_FILE = resolveCredentialsFile();
|
||||||
|
|
||||||
class CredentialManager {
|
class CredentialManager {
|
||||||
constructor() {
|
constructor() {
|
||||||
|
|||||||
@@ -15,8 +15,26 @@ const IV_LENGTH = 16; // 128 bits for GCM
|
|||||||
const AUTH_TAG_LENGTH = 16;
|
const AUTH_TAG_LENGTH = 16;
|
||||||
const SALT_LENGTH = 32;
|
const SALT_LENGTH = 32;
|
||||||
|
|
||||||
// Key file location (should be outside of mounted volumes for security)
|
// Resolve encryption key file path — supports both standard install (/app/.encryption-key)
|
||||||
const KEY_FILE = process.env.ENCRYPTION_KEY_FILE || path.join(__dirname, '.encryption-key');
|
// and custom deployments with consolidated data directory (/app/data/.encryption-key)
|
||||||
|
function resolveKeyFile() {
|
||||||
|
if (process.env.ENCRYPTION_KEY_FILE) {
|
||||||
|
return process.env.ENCRYPTION_KEY_FILE;
|
||||||
|
}
|
||||||
|
const candidates = [
|
||||||
|
path.join(__dirname, '.encryption-key'),
|
||||||
|
path.join(__dirname, 'data', '.encryption-key'),
|
||||||
|
];
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
if (fs.existsSync(candidate)) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// No existing file — return standard path so first load creates it there
|
||||||
|
return candidates[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEY_FILE = resolveKeyFile();
|
||||||
|
|
||||||
let encryptionKey = null;
|
let encryptionKey = null;
|
||||||
|
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -317,6 +317,9 @@ class LicenseManager {
|
|||||||
*/
|
*/
|
||||||
isExpired() {
|
isExpired() {
|
||||||
if (!this.activation) return true;
|
if (!this.activation) return true;
|
||||||
|
// Lifetime licenses never expire
|
||||||
|
if (this.activation.lifetime || this.activation.durationDays === 0) return false;
|
||||||
|
if (!this.activation.expiresAt) return false; // No expiry set = lifetime
|
||||||
return Date.now() > new Date(this.activation.expiresAt).getTime();
|
return Date.now() > new Date(this.activation.expiresAt).getTime();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -305,6 +305,8 @@ module.exports = function configureMiddleware(app, {
|
|||||||
{ path: '/api/v1/config', exact: true, method: 'GET' },
|
{ path: '/api/v1/config', exact: true, method: 'GET' },
|
||||||
{ path: '/api/v1/services/status', exact: true, method: 'GET' },
|
{ path: '/api/v1/services/status', exact: true, method: 'GET' },
|
||||||
{ path: '/api/v1/system/update-notify', exact: true, method: 'POST' },
|
{ path: '/api/v1/system/update-notify', exact: true, method: 'POST' },
|
||||||
|
{ path: '/api/v1/monitoring/stats', exact: true, method: 'GET' },
|
||||||
|
{ path: '/api/v1/health-checks/status', exact: true, method: 'GET' },
|
||||||
];
|
];
|
||||||
|
|
||||||
function isPublicRoute(req) {
|
function isPublicRoute(req) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "dashcaddy-api",
|
"name": "dashcaddy-api",
|
||||||
"version": "1.9.0",
|
"version": "1.12.0",
|
||||||
"description": "DashCaddy API server - Dashboard backend for Docker, Caddy & DNS management",
|
"description": "DashCaddy API server - Dashboard backend for Docker, Caddy & DNS management",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
// All paths can be overridden via environment variables.
|
// All paths can be overridden via environment variables.
|
||||||
|
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const fs = require('fs');
|
||||||
const isWindows = process.platform === 'win32';
|
const isWindows = process.platform === 'win32';
|
||||||
|
|
||||||
// Base directories
|
// Base directories
|
||||||
@@ -34,6 +35,8 @@ const paths = {
|
|||||||
caCertDir: path.join(CADDY_SITES, 'ca'),
|
caCertDir: path.join(CADDY_SITES, 'ca'),
|
||||||
pkiRootCert: path.join(CADDY_PKI, 'root.crt'),
|
pkiRootCert: path.join(CADDY_PKI, 'root.crt'),
|
||||||
pkiIntermediateCert: path.join(CADDY_PKI, 'intermediate.crt'),
|
pkiIntermediateCert: path.join(CADDY_PKI, 'intermediate.crt'),
|
||||||
|
generatedCertsDir: path.join(CADDY_SITES, 'generated-certs'),
|
||||||
|
pkiDir: CADDY_PKI,
|
||||||
|
|
||||||
// Static site base path
|
// Static site base path
|
||||||
sitePath: (subdomain) => path.join(CADDY_SITES, subdomain),
|
sitePath: (subdomain) => path.join(CADDY_SITES, subdomain),
|
||||||
@@ -41,6 +44,24 @@ const paths = {
|
|||||||
// Docker data path for app volumes
|
// Docker data path for app volumes
|
||||||
appData: (appName) => path.join(DOCKER_DATA, appName),
|
appData: (appName) => path.join(DOCKER_DATA, appName),
|
||||||
|
|
||||||
|
// In-container paths (used by self-updater and Docker deployments)
|
||||||
|
// Override via env vars for custom Docker layouts
|
||||||
|
containerUpdatesDir: process.env.DASHCADDY_UPDATES_DIR || '/app/updates',
|
||||||
|
containerFrontendDir: process.env.DASHCADDY_FRONTEND_DIR || '/app/dashboard',
|
||||||
|
containerAssetsDir: process.env.ASSETS_DIR || '/app/assets',
|
||||||
|
|
||||||
|
// Asset path resolution — supports both Docker (single file mount) and
|
||||||
|
// consolidated data directory layouts
|
||||||
|
resolveAssetsPath: (envPath) => {
|
||||||
|
if (envPath) return envPath;
|
||||||
|
// Standard Docker mount: /app/assets (volume-mounted)
|
||||||
|
if (fs.existsSync('/app/assets')) return '/app/assets';
|
||||||
|
// Consolidated data directory: /app/data/assets
|
||||||
|
if (fs.existsSync(path.join(CADDY_BASE, 'assets'))) return path.join(CADDY_BASE, 'assets');
|
||||||
|
// Fall back to /app/assets even if it doesn't exist (will create on write)
|
||||||
|
return '/app/assets';
|
||||||
|
},
|
||||||
|
|
||||||
// Log digest directory
|
// Log digest directory
|
||||||
digestDir: process.env.DIGEST_DIR || path.join(CADDY_BASE, 'digests'),
|
digestDir: process.env.DIGEST_DIR || path.join(CADDY_BASE, 'digests'),
|
||||||
|
|
||||||
|
|||||||
@@ -226,7 +226,23 @@ const server = http.createServer(async (req, res) => {
|
|||||||
json(res, 404, { error: 'Not found' });
|
json(res, 404, { error: 'Not found' });
|
||||||
});
|
});
|
||||||
|
|
||||||
server.listen(PORT, '0.0.0.0', () => {
|
const PYLON_PORT = parseInt(process.env.PYLON_PORT, 10) || 7842;
|
||||||
console.log(`[Pylon] ${PYLON_NAME} listening on port ${PORT}`);
|
const PYLON_HOST = process.env.PYLON_HOST || '0.0.0.0';
|
||||||
|
|
||||||
|
server.listen(PYLON_PORT, PYLON_HOST, () => {
|
||||||
|
console.log(`[Pylon] ${PYLON_NAME} listening on ${PYLON_HOST}:${PYLON_PORT}`);
|
||||||
if (API_KEY) console.log('[Pylon] API key authentication enabled');
|
if (API_KEY) console.log('[Pylon] API key authentication enabled');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Graceful shutdown — drain connections, then exit
|
||||||
|
const shutdown = (signal) => {
|
||||||
|
console.log(`[Pylon] ${signal} received, draining...`);
|
||||||
|
server.close(() => {
|
||||||
|
console.log('[Pylon] HTTP server closed');
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
// Force exit after 5s if connections don't drain
|
||||||
|
setTimeout(() => process.exit(0), 5000).unref();
|
||||||
|
};
|
||||||
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||||
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||||
|
|||||||
@@ -197,8 +197,18 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const container = await docker.client.createContainer(containerConfig);
|
let container;
|
||||||
|
try {
|
||||||
|
container = await docker.client.createContainer(containerConfig);
|
||||||
await container.start();
|
await container.start();
|
||||||
|
} catch (createErr) {
|
||||||
|
// If create fails with "no such image", wrap with user-friendly message
|
||||||
|
const errMsg = createErr?.message || String(createErr);
|
||||||
|
if (errMsg.includes('No such image') || errMsg.includes('no such image')) {
|
||||||
|
throw new Error(`[DC-201] Image pull succeeded but container creation failed — image may be corrupted: ${processedTemplate.docker.image}. ${errMsg}`);
|
||||||
|
}
|
||||||
|
throw createErr;
|
||||||
|
}
|
||||||
|
|
||||||
// Prune dangling images to prevent disk bloat
|
// Prune dangling images to prevent disk bloat
|
||||||
try {
|
try {
|
||||||
@@ -306,7 +316,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
} else {
|
} else {
|
||||||
containerId = await deployContainer(appId, config, template);
|
containerId = await deployContainer(appId, config, template);
|
||||||
log.info('deploy', 'Container deployed', { containerId });
|
log.info('deploy', 'Container deployed', { containerId });
|
||||||
await helpers.waitForHealthCheck(containerId, template.healthCheck, config.port || template.defaultPort);
|
await helpers.waitForHealthCheck(containerId, template.healthCheck, config.port || template.defaultPort, 30);
|
||||||
log.info('deploy', 'Container is healthy', { containerId });
|
log.info('deploy', 'Container is healthy', { containerId });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,7 +326,7 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
let dnsWarning = null;
|
let dnsWarning = null;
|
||||||
if (config.createDns && !isSubdirectoryMode) {
|
if (config.createDns && !isSubdirectoryMode) {
|
||||||
try {
|
try {
|
||||||
await ctx.dns.createRecord(config.subdomain, config.ip);
|
await ctx.dns.universalCreateRecord(config.subdomain, config.ip);
|
||||||
log.info('deploy', 'DNS record created', { domain: ctx.buildDomain(config.subdomain), ip: config.ip });
|
log.info('deploy', 'DNS record created', { domain: ctx.buildDomain(config.subdomain), ip: config.ip });
|
||||||
} catch (dnsError) {
|
} catch (dnsError) {
|
||||||
await logError('app-deploy-dns', dnsError, { appId, subdomain: config.subdomain, ip: config.ip });
|
await logError('app-deploy-dns', dnsError, { appId, subdomain: config.subdomain, ip: config.ip });
|
||||||
@@ -420,10 +430,11 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
|
|
||||||
res.json(response);
|
res.json(response);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await logError('app-deploy', error, { appId, config });
|
try { await logError('app-deploy', error, { appId, config }); } catch (_) { /* logError failure should not mask original error */ }
|
||||||
log.error('deploy', 'Deployment failed', { appId, error: error.message });
|
const msg = error?.message || String(error || 'Unknown error');
|
||||||
|
log.error('deploy', 'Deployment failed', { appId, error: msg });
|
||||||
const template = ctx.APP_TEMPLATES[appId];
|
const template = ctx.APP_TEMPLATES[appId];
|
||||||
ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${error.message}`, 'error');
|
try { ctx.notification.send('deploymentFailed', 'Deployment Failed', `Failed to deploy **${template?.name || appId}**.\nError: ${msg}`, 'error'); } catch (_) {}
|
||||||
errorResponse(res, 500, ctx.safeErrorMessage(error));
|
errorResponse(res, 500, ctx.safeErrorMessage(error));
|
||||||
}
|
}
|
||||||
}, 'apps-deploy'));
|
}, 'apps-deploy'));
|
||||||
|
|||||||
@@ -379,9 +379,12 @@ module.exports = function({ docker, caddy, credentialManager, servicesStateManag
|
|||||||
return content.slice(0, endIdx) + injection + content.slice(endIdx);
|
return content.slice(0, endIdx) + injection + content.slice(endIdx);
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success && result.error !== 'No changes to apply') {
|
||||||
throw new Error(`[DC-303] Failed to add subpath config for ${subdomain}: ${result.error}`);
|
throw new Error(`[DC-303] Failed to add subpath config for ${subdomain}: ${result.error}`);
|
||||||
}
|
}
|
||||||
|
if (result.error === 'No changes to apply') {
|
||||||
|
log.info('caddy', 'Subpath config already exists, reusing', { subdomain });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remove a subpath config block from between its markers in the Caddyfile. */
|
/** Remove a subpath config block from between its markers in the Caddyfile. */
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ module.exports = function(ctx) {
|
|||||||
asyncHandler: ctx.asyncHandler,
|
asyncHandler: ctx.asyncHandler,
|
||||||
errorResponse: ctx.errorResponse,
|
errorResponse: ctx.errorResponse,
|
||||||
log: ctx.log,
|
log: ctx.log,
|
||||||
// Additional context properties needed by routes
|
|
||||||
APP_TEMPLATES: ctx.APP_TEMPLATES,
|
APP_TEMPLATES: ctx.APP_TEMPLATES,
|
||||||
TEMPLATE_CATEGORIES: ctx.TEMPLATE_CATEGORIES,
|
TEMPLATE_CATEGORIES: ctx.TEMPLATE_CATEGORIES,
|
||||||
DIFFICULTY_LEVELS: ctx.DIFFICULTY_LEVELS,
|
DIFFICULTY_LEVELS: ctx.DIFFICULTY_LEVELS,
|
||||||
@@ -40,26 +39,27 @@ module.exports = function(ctx) {
|
|||||||
ctx: ctx
|
ctx: ctx
|
||||||
};
|
};
|
||||||
|
|
||||||
// Initialize helpers with dependencies (ctx is the Koa context)
|
|
||||||
const helpers = initHelpers({ ...deps, ctx });
|
const helpers = initHelpers({ ...deps, ctx });
|
||||||
|
|
||||||
// Mount sub-routes — pass full ctx so sub-routes can reference ctx.* properties
|
|
||||||
const subCtx = Object.assign({}, ctx, { helpers });
|
const subCtx = Object.assign({}, ctx, { helpers });
|
||||||
|
|
||||||
try { router.use('/deploy', initDeploy(subCtx)); }
|
// Mount sub-routers at their prefix paths.
|
||||||
catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message); }
|
// Sub-modules define routes at '/' (root of their sub-router).
|
||||||
|
// Final paths: /api/v1/apps/deploy, /api/v1/apps/remove, /api/v1/apps/templates, etc.
|
||||||
|
|
||||||
try { router.use('/remove', initRemoval(subCtx)); }
|
try { router.use('/apps', initDeploy(subCtx)); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] deploy routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
|
try { router.use('/apps', initRemoval(subCtx)); }
|
||||||
|
catch(e) { (ctx.log || console).error('[apps] removal routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
try { router.use('/apps', initTemplates(subCtx)); }
|
try { router.use('/apps', initTemplates(subCtx)); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] templates routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
try { router.use('/restore', initRestore(Object.assign({}, subCtx, { backupManager: ctx.backupManager }))); }
|
try { router.use('/apps', initRestore(Object.assign({}, subCtx, { backupManager: ctx.backupManager }))); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] restore routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
try { router.use('/compose', initCompose(subCtx)); }
|
try { router.use('/apps', initCompose(subCtx)); }
|
||||||
catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message); }
|
catch(e) { (ctx.log || console).error('[apps] compose routes init failed:', e.message, e.stack); }
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -71,18 +71,13 @@ module.exports = function({
|
|||||||
if (shouldDeleteContainer && subdomain && ctx.dns.getToken()) {
|
if (shouldDeleteContainer && subdomain && ctx.dns.getToken()) {
|
||||||
try {
|
try {
|
||||||
const domain = ctx.buildDomain(subdomain);
|
const domain = ctx.buildDomain(subdomain);
|
||||||
const getResult = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/get', {
|
const resolveResult = await ctx.dns.universalResolveRecord(domain, 'A');
|
||||||
token: ctx.dns.getToken(), domain, zone: ctx.siteConfig.tld.replace(/^\./, ''), listZone: 'true'
|
|
||||||
});
|
|
||||||
let recordIp = ip || 'localhost';
|
let recordIp = ip || 'localhost';
|
||||||
if (getResult.status === 'ok' && getResult.response?.records) {
|
if (resolveResult) {
|
||||||
const aRecord = getResult.response.records.find(r => r.type === 'A');
|
recordIp = resolveResult;
|
||||||
if (aRecord && aRecord.rData?.ipAddress) recordIp = aRecord.rData.ipAddress;
|
|
||||||
}
|
}
|
||||||
const dnsResult = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/delete', {
|
await ctx.dns.universalDeleteRecord(domain, recordIp);
|
||||||
token: ctx.dns.getToken(), domain, type: 'A', ipAddress: recordIp
|
results.dns = 'deleted';
|
||||||
});
|
|
||||||
results.dns = dnsResult.status === 'ok' ? 'deleted' : (dnsResult.errorMessage || 'failed');
|
|
||||||
log.info('dns', 'DNS record removal', { result: results.dns });
|
log.info('dns', 'DNS record removal', { result: results.dns });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.dns = error.message;
|
results.dns = error.message;
|
||||||
|
|||||||
@@ -458,7 +458,7 @@ module.exports = function({ docker, caddy, servicesStateManager, asyncHandler, e
|
|||||||
// DNS record
|
// DNS record
|
||||||
if (manifest.config.createDns && manifest.caddy.routingMode !== 'subdirectory') {
|
if (manifest.config.createDns && manifest.caddy.routingMode !== 'subdirectory') {
|
||||||
try {
|
try {
|
||||||
await ctx.dns.createRecord(manifest.config.subdomain, manifest.config.ip);
|
await ctx.dns.universalCreateRecord(manifest.config.subdomain, manifest.config.ip);
|
||||||
log.info('restore', 'DNS record recreated', { subdomain: manifest.config.subdomain });
|
log.info('restore', 'DNS record recreated', { subdomain: manifest.config.subdomain });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.warn('restore', `DNS recreation failed: ${e.message}`);
|
log.warn('restore', `DNS recreation failed: ${e.message}`);
|
||||||
|
|||||||
@@ -107,10 +107,8 @@ module.exports = function({
|
|||||||
if (oldSubdomain && ctx.dns.getToken()) {
|
if (oldSubdomain && ctx.dns.getToken()) {
|
||||||
try {
|
try {
|
||||||
const oldDomain = oldSubdomain.includes('.') ? oldSubdomain : ctx.buildDomain(oldSubdomain);
|
const oldDomain = oldSubdomain.includes('.') ? oldSubdomain : ctx.buildDomain(oldSubdomain);
|
||||||
const result = await ctx.dns.call(ctx.siteConfig.dnsServerIp, '/api/zones/records/delete', {
|
await ctx.dns.universalDeleteRecord(oldDomain, ip || 'localhost');
|
||||||
token: ctx.dns.getToken(), domain: oldDomain, type: 'A', ipAddress: ip || 'localhost'
|
results.oldDns = 'deleted';
|
||||||
});
|
|
||||||
results.oldDns = result.status === 'ok' ? 'deleted' : result.errorMessage;
|
|
||||||
log.info('dns', 'Old DNS record deleted', { domain: oldDomain });
|
log.info('dns', 'Old DNS record deleted', { domain: oldDomain });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
results.oldDns = `failed: ${error.message}`;
|
results.oldDns = `failed: ${error.message}`;
|
||||||
@@ -120,7 +118,7 @@ module.exports = function({
|
|||||||
|
|
||||||
if (newSubdomain && ctx.dns.getToken()) {
|
if (newSubdomain && ctx.dns.getToken()) {
|
||||||
try {
|
try {
|
||||||
await ctx.dns.createRecord(newSubdomain, ip || 'localhost');
|
await ctx.dns.universalCreateRecord(newSubdomain, ip || 'localhost');
|
||||||
results.newDns = 'created';
|
results.newDns = 'created';
|
||||||
log.info('dns', 'New DNS record created', { domain: ctx.buildDomain(newSubdomain) });
|
log.info('dns', 'New DNS record created', { domain: ctx.buildDomain(newSubdomain) });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
+10
-16
@@ -12,14 +12,11 @@ module.exports = function(ctx) {
|
|||||||
|
|
||||||
// Get CA certificate information
|
// Get CA certificate information
|
||||||
router.get('/info', ctx.asyncHandler(async (req, res) => {
|
router.get('/info', ctx.asyncHandler(async (req, res) => {
|
||||||
const certInfoPath = '/app/ca/cert-info.json';
|
const certInfoPath = path.join(platformPaths.caCertDir, 'cert-info.json');
|
||||||
const fallbackCertInfoPath = path.join(platformPaths.caCertDir, 'cert-info.json');
|
|
||||||
|
|
||||||
let certInfoFile;
|
let certInfoFile;
|
||||||
if (await exists(certInfoPath)) {
|
if (await exists(certInfoPath)) {
|
||||||
certInfoFile = certInfoPath;
|
certInfoFile = certInfoPath;
|
||||||
} else if (await exists(fallbackCertInfoPath)) {
|
|
||||||
certInfoFile = fallbackCertInfoPath;
|
|
||||||
} else {
|
} else {
|
||||||
const { NotFoundError } = require('../errors');
|
const { NotFoundError } = require('../errors');
|
||||||
throw new NotFoundError('CA certificate information');
|
throw new NotFoundError('CA certificate information');
|
||||||
@@ -46,13 +43,11 @@ module.exports = function(ctx) {
|
|||||||
|
|
||||||
// Serve root CA certificate directly (works even without DashCA deployed)
|
// Serve root CA certificate directly (works even without DashCA deployed)
|
||||||
router.get('/root.crt', ctx.asyncHandler(async (req, res) => {
|
router.get('/root.crt', ctx.asyncHandler(async (req, res) => {
|
||||||
const pkiCertPath = '/app/pki/root.crt';
|
|
||||||
const hostCertPath = platformPaths.pkiRootCert;
|
const hostCertPath = platformPaths.pkiRootCert;
|
||||||
const dashcaCertPath = path.join(platformPaths.caCertDir, 'root.crt');
|
const dashcaCertPath = path.join(platformPaths.caCertDir, 'root.crt');
|
||||||
|
|
||||||
let certPath;
|
let certPath;
|
||||||
if (await exists(pkiCertPath)) certPath = pkiCertPath;
|
if (await exists(dashcaCertPath)) certPath = dashcaCertPath;
|
||||||
else if (await exists(dashcaCertPath)) certPath = dashcaCertPath;
|
|
||||||
else if (await exists(hostCertPath)) certPath = hostCertPath;
|
else if (await exists(hostCertPath)) certPath = hostCertPath;
|
||||||
else {
|
else {
|
||||||
const { NotFoundError } = require('../errors');
|
const { NotFoundError } = require('../errors');
|
||||||
@@ -72,13 +67,12 @@ module.exports = function(ctx) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Load cert info to get the fingerprint
|
// Load cert info to get the fingerprint
|
||||||
const certInfoPath = '/app/ca/cert-info.json';
|
const certInfoPath = path.join(platformPaths.caCertDir, 'cert-info.json');
|
||||||
const fallbackCertInfoPath2 = path.join(platformPaths.caCertDir, 'cert-info.json');
|
|
||||||
|
|
||||||
let certInfoFile;
|
let certInfoFile;
|
||||||
if (await exists(certInfoPath)) certInfoFile = certInfoPath;
|
if (await exists(certInfoPath)) {
|
||||||
else if (await exists(fallbackCertInfoPath2)) certInfoFile = fallbackCertInfoPath2;
|
certInfoFile = certInfoPath;
|
||||||
else {
|
} else {
|
||||||
const { NotFoundError } = require('../errors');
|
const { NotFoundError } = require('../errors');
|
||||||
throw new NotFoundError('CA certificate information. Deploy DashCA first or ensure cert-info.json exists.');
|
throw new NotFoundError('CA certificate information. Deploy DashCA first or ensure cert-info.json exists.');
|
||||||
}
|
}
|
||||||
@@ -100,7 +94,7 @@ module.exports = function(ctx) {
|
|||||||
// Look for template in multiple locations (packaged app vs dev)
|
// Look for template in multiple locations (packaged app vs dev)
|
||||||
const templatePaths = [
|
const templatePaths = [
|
||||||
path.join(__dirname, '..', 'scripts', templateName),
|
path.join(__dirname, '..', 'scripts', templateName),
|
||||||
path.join('/app', 'scripts', templateName)
|
path.join(platformPaths.caddyBase, 'scripts', templateName)
|
||||||
];
|
];
|
||||||
|
|
||||||
let templateContent;
|
let templateContent;
|
||||||
@@ -142,8 +136,8 @@ module.exports = function(ctx) {
|
|||||||
return ctx.errorResponse(res, 400, `Invalid domain name. Must be a valid hostname (e.g., dns1${ctx.siteConfig.tld})`);
|
return ctx.errorResponse(res, 400, `Invalid domain name. Must be a valid hostname (e.g., dns1${ctx.siteConfig.tld})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const pkiPath = '/app/pki';
|
const pkiPath = platformPaths.pkiDir;
|
||||||
const certsDir = '/app/generated-certs';
|
const certsDir = platformPaths.generatedCertsDir;
|
||||||
const domainDir = path.join(certsDir, domain);
|
const domainDir = path.join(certsDir, domain);
|
||||||
|
|
||||||
const intermediateCert = path.join(pkiPath, 'intermediate.crt');
|
const intermediateCert = path.join(pkiPath, 'intermediate.crt');
|
||||||
@@ -246,7 +240,7 @@ ${safeDomain.includes('.') ? `DNS.2 = *.${safeDomain}` : ''}`;
|
|||||||
|
|
||||||
// List generated certificates
|
// List generated certificates
|
||||||
router.get('/certs', ctx.asyncHandler(async (req, res) => {
|
router.get('/certs', ctx.asyncHandler(async (req, res) => {
|
||||||
const certsDir = '/app/generated-certs';
|
const certsDir = platformPaths.generatedCertsDir;
|
||||||
|
|
||||||
if (!await exists(certsDir)) {
|
if (!await exists(certsDir)) {
|
||||||
return res.json({ success: true, certificates: [] });
|
return res.json({ success: true, certificates: [] });
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const path = require('path');
|
|||||||
const { LIMITS } = require('../../constants');
|
const { LIMITS } = require('../../constants');
|
||||||
const { exists } = require('../../fs-helpers');
|
const { exists } = require('../../fs-helpers');
|
||||||
const { ValidationError } = require('../../errors');
|
const { ValidationError } = require('../../errors');
|
||||||
|
const platformPaths = require('../../platform-paths');
|
||||||
/**
|
/**
|
||||||
* Config assets routes factory
|
* Config assets routes factory
|
||||||
* @param {Object} deps - Explicit dependencies
|
* @param {Object} deps - Explicit dependencies
|
||||||
@@ -51,7 +52,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
const buffer = Buffer.from(base64Data, 'base64');
|
const buffer = Buffer.from(base64Data, 'base64');
|
||||||
|
|
||||||
// Determine assets path (mounted volume)
|
// Determine assets path (mounted volume)
|
||||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||||
|
|
||||||
// Ensure directory exists
|
// Ensure directory exists
|
||||||
if (!await exists(assetsPath)) {
|
if (!await exists(assetsPath)) {
|
||||||
@@ -96,7 +97,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
const extension = matches[1] === 'svg+xml' ? 'svg' : matches[1];
|
const extension = matches[1] === 'svg+xml' ? 'svg' : matches[1];
|
||||||
const buffer = Buffer.from(matches[2], 'base64');
|
const buffer = Buffer.from(matches[2], 'base64');
|
||||||
|
|
||||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||||
if (!await exists(assetsPath)) {
|
if (!await exists(assetsPath)) {
|
||||||
await fsp.mkdir(assetsPath, { recursive: true });
|
await fsp.mkdir(assetsPath, { recursive: true });
|
||||||
}
|
}
|
||||||
@@ -170,7 +171,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
// Reset all branding to defaults
|
// Reset all branding to defaults
|
||||||
router.delete('/logo', asyncHandler(async (req, res) => {
|
router.delete('/logo', asyncHandler(async (req, res) => {
|
||||||
const config = await ctx.readConfig();
|
const config = await ctx.readConfig();
|
||||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||||
|
|
||||||
// Delete all custom logo files
|
// Delete all custom logo files
|
||||||
const logoPaths = [config.customLogo, config.customLogoDark, config.customLogoLight].filter(Boolean);
|
const logoPaths = [config.customLogo, config.customLogoDark, config.customLogoLight].filter(Boolean);
|
||||||
@@ -234,7 +235,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
const base64Data = matches[2];
|
const base64Data = matches[2];
|
||||||
const buffer = Buffer.from(base64Data, 'base64');
|
const buffer = Buffer.from(base64Data, 'base64');
|
||||||
|
|
||||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||||
if (!await exists(assetsPath)) {
|
if (!await exists(assetsPath)) {
|
||||||
await fsp.mkdir(assetsPath, { recursive: true });
|
await fsp.mkdir(assetsPath, { recursive: true });
|
||||||
}
|
}
|
||||||
@@ -279,7 +280,7 @@ module.exports = function({ servicesStateManager: _servicesStateManager, asyncHa
|
|||||||
const config = await ctx.readConfig();
|
const config = await ctx.readConfig();
|
||||||
|
|
||||||
// Delete custom favicon files
|
// Delete custom favicon files
|
||||||
const assetsPath = process.env.ASSETS_PATH || '/app/assets';
|
const assetsPath = platformPaths.resolveAssetsPath(process.env.ASSETS_PATH);
|
||||||
const filesToDelete = ['favicon.ico', 'favicon.png'];
|
const filesToDelete = ['favicon.ico', 'favicon.png'];
|
||||||
for (const file of filesToDelete) {
|
for (const file of filesToDelete) {
|
||||||
const filePath = `${assetsPath}/${file}`;
|
const filePath = `${assetsPath}/${file}`;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const path = require('path');
|
|||||||
const { CADDY } = require('../../constants');
|
const { CADDY } = require('../../constants');
|
||||||
const { exists } = require('../../fs-helpers');
|
const { exists } = require('../../fs-helpers');
|
||||||
const { ValidationError, AuthenticationError } = require('../../errors');
|
const { ValidationError, AuthenticationError } = require('../../errors');
|
||||||
|
const platformPaths = require('../../platform-paths');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Config backup routes factory
|
* Config backup routes factory
|
||||||
@@ -115,7 +116,7 @@ module.exports = function(deps) {
|
|||||||
|
|
||||||
// Include custom assets (logo, favicon) as base64
|
// Include custom assets (logo, favicon) as base64
|
||||||
try {
|
try {
|
||||||
const assetsDir = process.env.ASSETS_DIR || '/app/assets';
|
const assetsDir = platformPaths.resolveAssetsPath(process.env.ASSETS_DIR);
|
||||||
const configData = backup.files.config?.data || {};
|
const configData = backup.files.config?.data || {};
|
||||||
const assetFiles = [configData.customLogo, configData.customFavicon]
|
const assetFiles = [configData.customLogo, configData.customFavicon]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
@@ -346,7 +347,7 @@ module.exports = function(deps) {
|
|||||||
|
|
||||||
// Restore custom assets from base64
|
// Restore custom assets from base64
|
||||||
if (backup.assets && typeof backup.assets === 'object') {
|
if (backup.assets && typeof backup.assets === 'object') {
|
||||||
const assetsDir = process.env.ASSETS_DIR || '/app/assets';
|
const assetsDir = platformPaths.resolveAssetsPath(process.env.ASSETS_DIR);
|
||||||
for (const [name, b64] of Object.entries(backup.assets)) {
|
for (const [name, b64] of Object.entries(backup.assets)) {
|
||||||
try {
|
try {
|
||||||
const safeName = path.basename(name); // prevent path traversal
|
const safeName = path.basename(name); // prevent path traversal
|
||||||
|
|||||||
+155
-7
@@ -42,7 +42,137 @@ module.exports = function({
|
|||||||
return serverIp;
|
return serverIp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// DELETE /record — Delete a DNS record from Technitium
|
// ===== DNS PROVIDER ENDPOINTS =====
|
||||||
|
|
||||||
|
// GET /providers — List all available DNS providers
|
||||||
|
router.get('/providers', asyncHandler(async (req, res) => {
|
||||||
|
const providers = dns.getAvailableProviders ? dns.getAvailableProviders() : [];
|
||||||
|
const activeProvider = dns.getProviderId ? dns.getProviderId() : 'technitium';
|
||||||
|
success(res, { providers, activeProvider });
|
||||||
|
}, 'dns-providers-list'));
|
||||||
|
|
||||||
|
// GET /provider/status — Get active provider status
|
||||||
|
router.get('/provider/status', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
return success(res, { providerId: 'technitium', capabilities: ['create-record', 'delete-record', 'resolve', 'list-records', 'logs', 'restart', 'update-check', 'credentials', 'zones'] });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
const status = await provider.getStatus();
|
||||||
|
success(res, status);
|
||||||
|
} catch (err) {
|
||||||
|
errorResponse(res, safeErrorMessage(err), 500);
|
||||||
|
}
|
||||||
|
}, 'dns-provider-status'));
|
||||||
|
|
||||||
|
// ===== UNIVERSAL RECORD ENDPOINTS (work with any provider) =====
|
||||||
|
|
||||||
|
// POST /universal/record — Create a DNS record via any provider
|
||||||
|
router.post('/universal/record', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
// Fallback to legacy Technitium route
|
||||||
|
return res.redirect(307, '/api/dns/record');
|
||||||
|
}
|
||||||
|
const { domain, ip, ttl, type, server } = req.body;
|
||||||
|
if (!domain || !ip) throw new ValidationError('domain and ip are required');
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
if (!validatorLib.isIP(ip)) throw new ValidationError('[DC-210] Invalid IP address');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
if (!provider.supportsCapability('create-record')) {
|
||||||
|
const result = await provider.createRecord({
|
||||||
|
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A', value: ip, ttl: ttl || 300, overwrite: true
|
||||||
|
});
|
||||||
|
return success(res, {
|
||||||
|
message: result.message || `DNS record instructions provided`,
|
||||||
|
manual: true,
|
||||||
|
instructions: result.instructions
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await provider.createRecord({
|
||||||
|
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A', value: ip, ttl: ttl || 300, overwrite: true
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start propagation check in background
|
||||||
|
if (dnsPropagationChecker && ip) {
|
||||||
|
dnsPropagationChecker.startVerification(domain, ip).catch(err => {
|
||||||
|
log('DNS propagation check start failed:', err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: result.status === 'manual' ? result.message : `DNS record ${domain} -> ${ip} created`,
|
||||||
|
provider: dns.getProviderId(),
|
||||||
|
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'Universal DNS record creation error', { error: error.message });
|
||||||
|
errorResponse(res, safeErrorMessage(error), 500);
|
||||||
|
}
|
||||||
|
}, 'dns-universal-create'));
|
||||||
|
|
||||||
|
// DELETE /universal/record — Delete a DNS record via any provider
|
||||||
|
router.delete('/universal/record', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
return res.redirect(307, '/api/dns/record');
|
||||||
|
}
|
||||||
|
const { domain, type, value } = req.query;
|
||||||
|
if (!domain) throw new ValidationError('domain is required');
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
const result = await provider.deleteRecord({
|
||||||
|
domain, type: type || 'A', value
|
||||||
|
});
|
||||||
|
|
||||||
|
success(res, {
|
||||||
|
message: result.status === 'manual' ? result.message : `DNS record ${domain} deleted`,
|
||||||
|
provider: dns.getProviderId(),
|
||||||
|
...(result.instructions ? { manual: true, instructions: result.instructions } : {})
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'Universal DNS record deletion error', { error: error.message });
|
||||||
|
errorResponse(res, safeErrorMessage(error), 500);
|
||||||
|
}
|
||||||
|
}, 'dns-universal-delete'));
|
||||||
|
|
||||||
|
// GET /universal/resolve — Resolve a domain via any provider
|
||||||
|
router.get('/universal/resolve', asyncHandler(async (req, res) => {
|
||||||
|
if (!dns.getActiveProvider) {
|
||||||
|
return res.redirect(307, '/api/dns/resolve');
|
||||||
|
}
|
||||||
|
const { domain, type } = req.query;
|
||||||
|
if (!domain) throw new ValidationError('domain is required');
|
||||||
|
if (!REGEX.DOMAIN.test(domain)) throw new ValidationError('[DC-301] Invalid domain format');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const provider = dns.getActiveProvider();
|
||||||
|
const result = await provider.resolveRecords({
|
||||||
|
domain, zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A'
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.response?.records?.length > 0) {
|
||||||
|
const ipAddresses = result.response.records
|
||||||
|
.filter(r => r.type === (type || 'A'))
|
||||||
|
.map(r => r.rData?.ipAddress || r.content || r.rData?.address)
|
||||||
|
.filter(Boolean);
|
||||||
|
success(res, { answer: ipAddresses });
|
||||||
|
} else {
|
||||||
|
throw new NotFoundError('No records found for domain');
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'Universal DNS resolve error', { error: error.message });
|
||||||
|
errorResponse(res, safeErrorMessage(error), error.statusCode || 500);
|
||||||
|
}
|
||||||
|
}, 'dns-universal-resolve'));
|
||||||
|
|
||||||
|
// ===== LEGACY TECHNITIUM-SPECIFIC ROUTES (unchanged) =====
|
||||||
router.delete('/record', asyncHandler(async (req, res) => {
|
router.delete('/record', asyncHandler(async (req, res) => {
|
||||||
const { domain, type, token, server, ipAddress } = req.query;
|
const { domain, type, token, server, ipAddress } = req.query;
|
||||||
|
|
||||||
@@ -203,8 +333,13 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-resolve'));
|
}, 'dns-resolve'));
|
||||||
|
|
||||||
// GET /logs — Fetch DNS query logs from Technitium
|
// GET /logs — Fetch DNS query logs (Technitium only)
|
||||||
router.get('/logs', asyncHandler(async (req, res) => {
|
router.get('/logs', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate: logs are provider-specific
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('logs')) {
|
||||||
|
return success(res, { server: 'N/A', count: 0, logs: [], message: 'DNS logs not supported by current provider' });
|
||||||
|
}
|
||||||
|
|
||||||
const { server, limit } = req.query;
|
const { server, limit } = req.query;
|
||||||
|
|
||||||
if (!server) {
|
if (!server) {
|
||||||
@@ -484,8 +619,13 @@ module.exports = function({
|
|||||||
success(res, { message: 'DNS credentials removed' });
|
success(res, { message: 'DNS credentials removed' });
|
||||||
}, 'dns-credentials-delete'));
|
}, 'dns-credentials-delete'));
|
||||||
|
|
||||||
// POST /restart/:dnsId — Restart a DNS server (proxied through backend for auth)
|
// POST /restart/:dnsId — Restart a DNS server (Technitium only)
|
||||||
router.post('/restart/:dnsId', asyncHandler(async (req, res) => {
|
router.post('/restart/:dnsId', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('restart')) {
|
||||||
|
return errorResponse(res, 'Server restart not supported by current DNS provider', 501);
|
||||||
|
}
|
||||||
|
|
||||||
const { dnsId } = req.params;
|
const { dnsId } = req.params;
|
||||||
const serverInfo = siteConfig.dnsServers?.[dnsId];
|
const serverInfo = siteConfig.dnsServers?.[dnsId];
|
||||||
if (!serverInfo?.ip) {
|
if (!serverInfo?.ip) {
|
||||||
@@ -527,8 +667,13 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-refresh-token'));
|
}, 'dns-refresh-token'));
|
||||||
|
|
||||||
// GET /check-update — Check for Technitium DNS server updates
|
// GET /check-update — Check for DNS server updates (Technitium only)
|
||||||
router.get('/check-update', asyncHandler(async (req, res) => {
|
router.get('/check-update', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('update-check')) {
|
||||||
|
return success(res, { updateAvailable: false, message: 'Update check not supported by current DNS provider' });
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { server } = req.query;
|
const { server } = req.query;
|
||||||
if (!server) {
|
if (!server) {
|
||||||
@@ -585,10 +730,13 @@ module.exports = function({
|
|||||||
}
|
}
|
||||||
}, 'dns-check-update'));
|
}, 'dns-check-update'));
|
||||||
|
|
||||||
// POST /update — Update Technitium DNS server
|
// POST /update — Update DNS server (Technitium only)
|
||||||
// Note: Technitium v14+ has no installUpdate API. This endpoint checks for updates
|
|
||||||
// and returns download info. The frontend handles showing update instructions.
|
|
||||||
router.post('/update', asyncHandler(async (req, res) => {
|
router.post('/update', asyncHandler(async (req, res) => {
|
||||||
|
// Capability gate
|
||||||
|
if (dns.supportsCapability && !dns.supportsCapability('update-check')) {
|
||||||
|
return errorResponse(res, 'Server update not supported by current DNS provider', 501);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { server } = req.query;
|
const { server } = req.query;
|
||||||
if (!server) {
|
if (!server) {
|
||||||
|
|||||||
@@ -322,9 +322,16 @@ module.exports = function({
|
|||||||
// ===== HEALTH CHECK (health-checker module) =====
|
// ===== HEALTH CHECK (health-checker module) =====
|
||||||
|
|
||||||
// Get current status for all services
|
// Get current status for all services
|
||||||
|
// Returns per-service status plus a summary for the System Overview widget:
|
||||||
|
// { status: { ... }, summary: { healthy, unhealthy, total } }
|
||||||
router.get('/health-checks/status', asyncHandler(async (req, res) => {
|
router.get('/health-checks/status', asyncHandler(async (req, res) => {
|
||||||
const status = healthChecker.getCurrentStatus();
|
const status = healthChecker.getCurrentStatus();
|
||||||
success(res, { status });
|
// Build summary for the overview widget
|
||||||
|
const entries = Object.values(status);
|
||||||
|
const healthy = entries.filter(s => s.status === 'up' || s.status === 'healthy').length;
|
||||||
|
const unhealthy = entries.filter(s => s.status === 'down' || s.status === 'unhealthy').length;
|
||||||
|
const total = entries.length;
|
||||||
|
success(res, { status, summary: { healthy, unhealthy, total } });
|
||||||
}, 'health-check-status'));
|
}, 'health-check-status'));
|
||||||
|
|
||||||
// Get service statistics
|
// Get service statistics
|
||||||
|
|||||||
@@ -16,8 +16,22 @@ module.exports = function({ resourceMonitor, docker, asyncHandler, log, notifica
|
|||||||
// ===== RESOURCE MONITORING ENDPOINTS =====
|
// ===== RESOURCE MONITORING ENDPOINTS =====
|
||||||
|
|
||||||
// Get all container stats (from resource monitor module)
|
// Get all container stats (from resource monitor module)
|
||||||
|
// Returns a flat summary format for the System Overview widget:
|
||||||
|
// { containerId: { cpu: <percent>, memory: <percent>, memoryUsage: <bytes>, name } }
|
||||||
router.get('/monitoring/stats', asyncHandler(async (req, res) => {
|
router.get('/monitoring/stats', asyncHandler(async (req, res) => {
|
||||||
const stats = resourceMonitor.getAllStats();
|
const raw = resourceMonitor.getAllStats();
|
||||||
|
// Transform nested { current: { cpu: { percent }, memory: { percent, usage } } }
|
||||||
|
// into flat { cpu: number, memory: number, memoryUsage: number } for the frontend widget
|
||||||
|
const stats = {};
|
||||||
|
for (const [id, data] of Object.entries(raw)) {
|
||||||
|
const cur = data.current || {};
|
||||||
|
stats[id] = {
|
||||||
|
name: data.name,
|
||||||
|
cpu: typeof cur.cpu === 'object' ? (cur.cpu.percent ?? 0) : (Number(cur.cpu) || 0),
|
||||||
|
memory: typeof cur.memory === 'object' ? (cur.memory.percent ?? 0) : (Number(cur.memory) || 0),
|
||||||
|
memoryUsage: typeof cur.memory === 'object' ? (cur.memory.usage ?? 0) : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
success(res, { stats });
|
success(res, { stats });
|
||||||
}, 'monitoring-stats'));
|
}, 'monitoring-stats'));
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ module.exports = function({
|
|||||||
dns
|
dns
|
||||||
}) {
|
}) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const CA_CERT_PATH = process.env.CA_CERT_PATH || '/app/pki/root.crt';
|
const CA_CERT_PATH = process.env.CA_CERT_PATH || platformPaths.pkiRootCert;
|
||||||
const PROBE_CONCURRENCY = 6;
|
const PROBE_CONCURRENCY = 6;
|
||||||
let probeHttpsAgent;
|
let probeHttpsAgent;
|
||||||
|
|
||||||
@@ -520,9 +520,8 @@ module.exports = function({
|
|||||||
|
|
||||||
if (oldSubdomain !== newSubdomain) {
|
if (oldSubdomain !== newSubdomain) {
|
||||||
try {
|
try {
|
||||||
const dnsToken = dns.getToken();
|
await dns.universalDeleteRecord(oldDomain);
|
||||||
await dns.call(siteConfig.dnsServerIp, '/api/zones/records/delete', { token: dnsToken, domain: oldDomain, type: 'A' });
|
await dns.universalCreateRecord(newSubdomain, ip || 'localhost');
|
||||||
await dns.createRecord(newSubdomain, ip || 'localhost');
|
|
||||||
results.dns = 'updated';
|
results.dns = 'updated';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
results.dns = `failed: ${e.message}`;
|
results.dns = `failed: ${e.message}`;
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ module.exports = function({ asyncHandler, caddy, dns, fetchT, buildDomain, addSe
|
|||||||
|
|
||||||
if (createDns) {
|
if (createDns) {
|
||||||
try {
|
try {
|
||||||
await dns.createRecord(subdomain, siteConfig.dnsServerIp);
|
await dns.universalCreateRecord(subdomain, siteConfig.dnsServerIp);
|
||||||
log.info('dns', 'DNS record created for external proxy', { domain, ip: siteConfig.dnsServerIp });
|
log.info('dns', 'DNS record created for external proxy', { domain, ip: siteConfig.dnsServerIp });
|
||||||
} catch (dnsError) {
|
} catch (dnsError) {
|
||||||
dnsWarning = `DNS creation failed: ${dnsError.message}. You may need to create the DNS record manually.`;
|
dnsWarning = `DNS creation failed: ${dnsError.message}. You may need to create the DNS record manually.`;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ const fs = require('fs');
|
|||||||
const path = require('path');
|
const path = require('path');
|
||||||
const { success } = require('../response-helpers');
|
const { success } = require('../response-helpers');
|
||||||
const { ValidationError, NotFoundError } = require('../errors');
|
const { ValidationError, NotFoundError } = require('../errors');
|
||||||
|
const platformPaths = require('../platform-paths');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Themes routes factory
|
* Themes routes factory
|
||||||
@@ -13,7 +14,7 @@ const { ValidationError, NotFoundError } = require('../errors');
|
|||||||
*/
|
*/
|
||||||
module.exports = function({ asyncHandler, log }) {
|
module.exports = function({ asyncHandler, log }) {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const THEMES_DIR = process.env.THEMES_DIR || path.join(path.dirname(process.env.SERVICES_FILE || '/app/services.json'), 'themes');
|
const THEMES_DIR = process.env.THEMES_DIR || path.join(path.dirname(platformPaths.servicesFile), 'themes');
|
||||||
|
|
||||||
// Ensure themes directory exists
|
// Ensure themes directory exists
|
||||||
if (!fs.existsSync(THEMES_DIR)) {
|
if (!fs.existsSync(THEMES_DIR)) {
|
||||||
|
|||||||
@@ -21,17 +21,17 @@ const isWindows = platformPaths.isWindows;
|
|||||||
|
|
||||||
const DEFAULTS = {
|
const DEFAULTS = {
|
||||||
CHECK_INTERVAL: 30 * 60 * 1000, // 30 minutes
|
CHECK_INTERVAL: 30 * 60 * 1000, // 30 minutes
|
||||||
UPDATE_URL: 'https://get.dashcaddy.net/release',
|
UPDATE_URL: process.env.DASHCADDY_UPDATE_URL || 'https://get.dashcaddy.net/release',
|
||||||
MIRROR_URL: 'https://get2.dashcaddy.net/release',
|
MIRROR_URL: process.env.DASHCADDY_MIRROR_URL || 'https://get2.dashcaddy.net/release',
|
||||||
UPDATES_DIR: platformPaths.isWindows ? path.join(platformPaths.caddyBase, 'updates') : '/app/updates',
|
UPDATES_DIR: platformPaths.containerUpdatesDir,
|
||||||
// API_SOURCE_DIR is the HOST path — written to trigger.json for the host-side updater
|
// API_SOURCE_DIR is the HOST path — written to trigger.json for the host-side updater
|
||||||
API_SOURCE_DIR: path.join(platformPaths.caddySites, 'dashcaddy-api'),
|
API_SOURCE_DIR: path.join(platformPaths.caddySites, 'dashcaddy-api'),
|
||||||
// FRONTEND_DIR is the container path — dashboard is volume-mounted at /app/dashboard
|
// FRONTEND_DIR is the container path — dashboard is volume-mounted at /app/dashboard
|
||||||
FRONTEND_DIR: platformPaths.isWindows ? path.join(platformPaths.caddySites, 'status') : '/app/dashboard',
|
FRONTEND_DIR: platformPaths.containerFrontendDir,
|
||||||
MAX_BACKUPS: 3,
|
MAX_BACKUPS: 3,
|
||||||
HEALTH_TIMEOUT: 60000,
|
HEALTH_TIMEOUT: 60000,
|
||||||
DOWNLOAD_TIMEOUT: 120000,
|
DOWNLOAD_TIMEOUT: 120000,
|
||||||
CHANNEL: 'stable',
|
CHANNEL: process.env.DASHCADDY_UPDATE_CHANNEL || 'stable',
|
||||||
INSTANCE_ID_FILE: platformPaths.isWindows
|
INSTANCE_ID_FILE: platformPaths.isWindows
|
||||||
? path.join(platformPaths.caddyBase, 'instance-id')
|
? path.join(platformPaths.caddyBase, 'instance-id')
|
||||||
: '/etc/dashcaddy/instance-id',
|
: '/etc/dashcaddy/instance-id',
|
||||||
|
|||||||
@@ -25,7 +25,8 @@ process.on('uncaughtException', (error) => {
|
|||||||
// Load license
|
// Load license
|
||||||
await licenseManager.load();
|
await licenseManager.load();
|
||||||
|
|
||||||
const PORT = process.env.PORT || 3001;
|
const PORT = parseInt(process.env.PORT, 10) || 3001;
|
||||||
|
const HOST = process.env.HOST || '0.0.0.0';
|
||||||
const CADDYFILE_PATH = process.env.CADDYFILE_PATH || platformPaths.caddyfile;
|
const CADDYFILE_PATH = process.env.CADDYFILE_PATH || platformPaths.caddyfile;
|
||||||
const CADDY_ADMIN_URL = process.env.CADDY_ADMIN_URL || platformPaths.caddyAdminUrl;
|
const CADDY_ADMIN_URL = process.env.CADDY_ADMIN_URL || platformPaths.caddyAdminUrl;
|
||||||
const SERVICES_FILE = process.env.SERVICES_FILE || platformPaths.servicesFile;
|
const SERVICES_FILE = process.env.SERVICES_FILE || platformPaths.servicesFile;
|
||||||
@@ -43,9 +44,10 @@ process.on('uncaughtException', (error) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Start HTTP server
|
// Start HTTP server
|
||||||
const server = app.listen(PORT, '0.0.0.0', () => {
|
const server = app.listen(PORT, HOST, () => {
|
||||||
log.info('server', 'DashCaddy API server started', {
|
log.info('server', 'DashCaddy API server started', {
|
||||||
port: PORT,
|
port: PORT,
|
||||||
|
host: HOST,
|
||||||
caddyfile: CADDYFILE_PATH,
|
caddyfile: CADDYFILE_PATH,
|
||||||
caddyAdmin: CADDY_ADMIN_URL,
|
caddyAdmin: CADDY_ADMIN_URL,
|
||||||
services: SERVICES_FILE,
|
services: SERVICES_FILE,
|
||||||
@@ -73,9 +75,12 @@ process.on('uncaughtException', (error) => {
|
|||||||
try { bundledWorkflows = require('./bundled-workflows'); } catch { /* optional */ }
|
try { bundledWorkflows = require('./bundled-workflows'); } catch { /* optional */ }
|
||||||
|
|
||||||
// Initialize workflow engine if bundled-workflows is available
|
// Initialize workflow engine if bundled-workflows is available
|
||||||
|
// NOTE: createApp() already initializes the workflow engine in src/app.js
|
||||||
|
// This block is kept for backward compat with entry points that don't use createApp()
|
||||||
let workflowEngine = null;
|
let workflowEngine = null;
|
||||||
if (bundledWorkflows) {
|
if (bundledWorkflows) {
|
||||||
try {
|
try {
|
||||||
|
const { fetchT } = require('./src/utils/http');
|
||||||
const { WorkflowEngine } = bundledWorkflows;
|
const { WorkflowEngine } = bundledWorkflows;
|
||||||
// Create a context with needed services
|
// Create a context with needed services
|
||||||
const workflowCtx = {
|
const workflowCtx = {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ const { asyncHandler } = require('./utils/async-handler');
|
|||||||
|
|
||||||
// Managers and utilities
|
// Managers and utilities
|
||||||
const StateManager = require('../state-manager');
|
const StateManager = require('../state-manager');
|
||||||
|
const platformPaths = require('../platform-paths');
|
||||||
const { LicenseManager } = require('../license-manager');
|
const { LicenseManager } = require('../license-manager');
|
||||||
const credentialManager = require('../credential-manager');
|
const credentialManager = require('../credential-manager');
|
||||||
const authManager = require('../auth-manager');
|
const authManager = require('../auth-manager');
|
||||||
@@ -84,8 +85,8 @@ const configDriftRoutes = require('../routes/config-drift');
|
|||||||
const sslMonitorRoutes = require('../routes/ssl-monitor');
|
const sslMonitorRoutes = require('../routes/ssl-monitor');
|
||||||
const { AutoRestartManager } = require('../auto-restart-manager');
|
const { AutoRestartManager } = require('../auto-restart-manager');
|
||||||
const { ConfigDriftDetector } = require('../config-drift-detector');
|
const { ConfigDriftDetector } = require('../config-drift-detector');
|
||||||
const { SSLMonitor } = require('../ssl-monitor');
|
const SSLMonitor = require('../ssl-monitor');
|
||||||
const { DNSPropagationChecker } = require('../dns-propagation');
|
const DNSPropagationChecker = require('../dns-propagation');
|
||||||
|
|
||||||
// Constants
|
// Constants
|
||||||
const { APP } = require('../constants');
|
const { APP } = require('../constants');
|
||||||
@@ -96,6 +97,19 @@ const { APP } = require('../constants');
|
|||||||
async function createApp() {
|
async function createApp() {
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
|
// Global request timeout (default 5 minutes — covers slow Docker pulls)
|
||||||
|
// Routes that need longer can override per-request with req.setTimeout()
|
||||||
|
const REQUEST_TIMEOUT_MS = parseInt(process.env.REQUEST_TIMEOUT_MS, 10) || 5 * 60 * 1000;
|
||||||
|
app.use((req, res, next) => {
|
||||||
|
req.setTimeout(REQUEST_TIMEOUT_MS);
|
||||||
|
res.setTimeout(REQUEST_TIMEOUT_MS);
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
// Disable x-powered-by header for security (don't advertise framework)
|
||||||
|
app.disable('x-powered-by');
|
||||||
|
// Trust first proxy (Caddy/nginx in front of us) so req.ip works correctly
|
||||||
|
app.set('trust proxy', 1);
|
||||||
|
|
||||||
// Initialize logging
|
// Initialize logging
|
||||||
const log = createLogger(config.LOG_LEVEL);
|
const log = createLogger(config.LOG_LEVEL);
|
||||||
|
|
||||||
@@ -111,7 +125,7 @@ async function createApp() {
|
|||||||
licenseManager.loadSecret(config.LICENSE_SECRET_FILE);
|
licenseManager.loadSecret(config.LICENSE_SECRET_FILE);
|
||||||
|
|
||||||
// HTTPS agent for internal CA
|
// HTTPS agent for internal CA
|
||||||
const CA_CERT_PATH = process.env.CA_CERT_PATH || '/app/pki/root.crt';
|
const CA_CERT_PATH = process.env.CA_CERT_PATH || platformPaths.pkiRootCert;
|
||||||
let httpsAgent;
|
let httpsAgent;
|
||||||
try {
|
try {
|
||||||
const caCert = fs.readFileSync(CA_CERT_PATH);
|
const caCert = fs.readFileSync(CA_CERT_PATH);
|
||||||
@@ -380,6 +394,29 @@ async function createApp() {
|
|||||||
// Build versioned API router
|
// Build versioned API router
|
||||||
const apiRouter = express.Router();
|
const apiRouter = express.Router();
|
||||||
|
|
||||||
|
// Version endpoint — public, no auth required
|
||||||
|
// Reads version from package.json at startup so the response always matches the running code
|
||||||
|
let appVersion = '0.0.0';
|
||||||
|
let appName = 'dashcaddy-api';
|
||||||
|
try {
|
||||||
|
const pkg = require('../package.json');
|
||||||
|
appVersion = pkg.version || appVersion;
|
||||||
|
appName = pkg.name || appName;
|
||||||
|
} catch { /* package.json unreadable — keep fallback */ }
|
||||||
|
apiRouter.get('/version', (req, res) => {
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
name: appName,
|
||||||
|
version: appVersion,
|
||||||
|
node: process.version,
|
||||||
|
platform: process.platform,
|
||||||
|
arch: process.arch,
|
||||||
|
uptime: process.uptime(),
|
||||||
|
instanceId: process.env.DASHCADDY_INSTANCE_ID || null
|
||||||
|
});
|
||||||
|
});
|
||||||
|
log.info('app', `Version endpoint available at /api/v1/version (v${appVersion})`);
|
||||||
|
|
||||||
// Wire up notification listeners for resourceMonitor and backupManager
|
// Wire up notification listeners for resourceMonitor and backupManager
|
||||||
if (ctx.notification && ctx.resourceMonitor) {
|
if (ctx.notification && ctx.resourceMonitor) {
|
||||||
ctx.resourceMonitor.on('alert', (alertData) => {
|
ctx.resourceMonitor.on('alert', (alertData) => {
|
||||||
@@ -539,7 +576,7 @@ async function createApp() {
|
|||||||
sslMonitor: ctx.sslMonitor,
|
sslMonitor: ctx.sslMonitor,
|
||||||
dnsPropagationChecker: ctx.dnsPropagationChecker
|
dnsPropagationChecker: ctx.dnsPropagationChecker
|
||||||
}));
|
}));
|
||||||
apiRouter.use(workflowsRoutes({
|
apiRouter.use('/workflows', workflowsRoutes({
|
||||||
workflowEngine: ctx.workflowEngine,
|
workflowEngine: ctx.workflowEngine,
|
||||||
licenseManager: ctx.licenseManager,
|
licenseManager: ctx.licenseManager,
|
||||||
asyncHandler: ctx.asyncHandler
|
asyncHandler: ctx.asyncHandler
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* DNS context - Technitium DNS operations and token management
|
* DNS context - Technitium DNS operations and token management
|
||||||
|
*
|
||||||
|
* DEPRECATED: This module is kept for backward compatibility.
|
||||||
|
* New code should use src/context/provider-dns.js which supports multiple providers.
|
||||||
|
*
|
||||||
|
* This module now delegates to the provider system internally.
|
||||||
*/
|
*/
|
||||||
const { TIMEOUTS, SESSION_TTL, CADDY } = require('../../constants');
|
const { TIMEOUTS, SESSION_TTL, CADDY } = require('../../constants');
|
||||||
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
||||||
|
const { createProviderDnsContext } = require('./provider-dns');
|
||||||
|
|
||||||
// DNS token management
|
// DNS token management
|
||||||
let dnsToken = process.env.DNS_ADMIN_TOKEN || '';
|
let dnsToken = process.env.DNS_ADMIN_TOKEN || '';
|
||||||
@@ -281,6 +287,10 @@ function invalidateTokenForServer(serverIp) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE) {
|
function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE) {
|
||||||
|
// Create the new provider-aware context
|
||||||
|
const providerCtx = createProviderDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE);
|
||||||
|
|
||||||
|
// Legacy Technitium-specific wrappers (kept for backward compat)
|
||||||
const ensureToken = () => ensureValidDnsToken(siteConfig, credentialManager, fetchT, log);
|
const ensureToken = () => ensureValidDnsToken(siteConfig, credentialManager, fetchT, log);
|
||||||
const require = (providedToken) => requireDnsToken(providedToken, siteConfig, credentialManager, fetchT, log);
|
const require = (providedToken) => requireDnsToken(providedToken, siteConfig, credentialManager, fetchT, log);
|
||||||
const getForServer = (server, role) => getTokenForServer(server, siteConfig, credentialManager, fetchT, log, role);
|
const getForServer = (server, role) => getTokenForServer(server, siteConfig, credentialManager, fetchT, log, role);
|
||||||
@@ -289,6 +299,7 @@ function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, ht
|
|||||||
const call = (server, apiPath, params) => callDns(server, apiPath, params, fetchT, httpsAgent);
|
const call = (server, apiPath, params) => callDns(server, apiPath, params, fetchT, httpsAgent);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
// Legacy Technitium-specific interface (unchanged)
|
||||||
call,
|
call,
|
||||||
buildUrl: buildDnsUrl,
|
buildUrl: buildDnsUrl,
|
||||||
requireToken: require,
|
requireToken: require,
|
||||||
@@ -302,6 +313,17 @@ function createDnsContext(siteConfig, buildDomain, credentialManager, fetchT, ht
|
|||||||
invalidateTokenForServer,
|
invalidateTokenForServer,
|
||||||
refresh,
|
refresh,
|
||||||
credentialsFile: DNS_CREDENTIALS_FILE,
|
credentialsFile: DNS_CREDENTIALS_FILE,
|
||||||
|
|
||||||
|
// Provider-aware methods (new)
|
||||||
|
getProviderId: providerCtx.getProviderId,
|
||||||
|
getActiveProvider: providerCtx.getActiveProvider,
|
||||||
|
getAvailableProviders: providerCtx.getAvailableProviders,
|
||||||
|
supportsCapability: providerCtx.supportsCapability,
|
||||||
|
|
||||||
|
// Universal DNS helpers (delegated to provider context)
|
||||||
|
universalCreateRecord: providerCtx.universalCreateRecord,
|
||||||
|
universalDeleteRecord: providerCtx.universalDeleteRecord,
|
||||||
|
universalResolveRecord: providerCtx.universalResolveRecord,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,302 @@
|
|||||||
|
/**
|
||||||
|
* Provider-aware DNS Context
|
||||||
|
* Replaces the Technitium-only context with a provider-agnostic layer.
|
||||||
|
* Delegates to the active DNS provider adapter based on config.
|
||||||
|
*
|
||||||
|
* Falls back to legacy Technitium context for backward compatibility
|
||||||
|
* when no provider is explicitly configured.
|
||||||
|
*/
|
||||||
|
const { createCache, CACHE_CONFIGS } = require('../../cache-config');
|
||||||
|
const { TIMEOUTS, SESSION_TTL, CADDY } = require('../../constants');
|
||||||
|
const registry = require('../../dns-providers/registry');
|
||||||
|
|
||||||
|
// Per-server token cache (legacy Technitium)
|
||||||
|
const dnsServerTokens = createCache(CACHE_CONFIGS.dnsTokens);
|
||||||
|
let dnsToken = '';
|
||||||
|
let dnsTokenExpiry = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a provider-aware DNS context.
|
||||||
|
* This wraps both the new provider system and the legacy Technitium context
|
||||||
|
* for seamless migration.
|
||||||
|
*/
|
||||||
|
function createProviderDnsContext(siteConfig, buildDomain, credentialManager, fetchT, httpsAgent, log, DNS_CREDENTIALS_FILE) {
|
||||||
|
/** Resolve the active provider from config */
|
||||||
|
function getProviderId() {
|
||||||
|
// New explicit provider field
|
||||||
|
if (siteConfig.dns?.provider) return siteConfig.dns.provider;
|
||||||
|
// Legacy: if dns.ip is set, default to technitium
|
||||||
|
if (siteConfig.dnsServerIp || siteConfig.dns?.ip) return 'technitium';
|
||||||
|
// No DNS configured
|
||||||
|
return 'manual';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get provider-specific config from site config */
|
||||||
|
function getProviderConfig(providerId) {
|
||||||
|
const dnsConfig = siteConfig.dns || {};
|
||||||
|
|
||||||
|
switch (providerId) {
|
||||||
|
case 'technitium':
|
||||||
|
return {
|
||||||
|
serverIp: siteConfig.dnsServerIp || dnsConfig.ip || '',
|
||||||
|
serverPort: siteConfig.dnsServerPort || dnsConfig.port || '5380',
|
||||||
|
dnsServers: siteConfig.dnsServers || {},
|
||||||
|
dnsId: Object.keys(siteConfig.dnsServers || {})[0] || 'dns1'
|
||||||
|
};
|
||||||
|
case 'cloudflare':
|
||||||
|
return {
|
||||||
|
apiToken: dnsConfig.apiToken || '',
|
||||||
|
zoneId: dnsConfig.zoneId || '',
|
||||||
|
domain: siteConfig.domain || ''
|
||||||
|
};
|
||||||
|
case 'rfc2136':
|
||||||
|
return {
|
||||||
|
server: dnsConfig.server || siteConfig.dnsServerIp || '',
|
||||||
|
port: dnsConfig.port || 53,
|
||||||
|
zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
tsigAlgorithm: dnsConfig.tsigAlgorithm || 'hmac-sha256',
|
||||||
|
tsigKeyName: dnsConfig.tsigKeyName || '',
|
||||||
|
tsigSecret: dnsConfig.tsigSecret || ''
|
||||||
|
};
|
||||||
|
case 'manual':
|
||||||
|
return {};
|
||||||
|
default:
|
||||||
|
return dnsConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get or create the active provider adapter */
|
||||||
|
function getActiveProvider() {
|
||||||
|
const providerId = getProviderId();
|
||||||
|
const config = getProviderConfig(providerId);
|
||||||
|
const ctx = { log, credentialManager, fetchT, httpsAgent };
|
||||||
|
return registry.getProvider(providerId, config, ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Legacy Technitium helpers (kept for backward compat) =====
|
||||||
|
function buildDnsUrl(server, apiPath, params) {
|
||||||
|
const protocol = server.match(/^\d+\.\d+\.\d+\.\d+$/) ? 'http' : 'https';
|
||||||
|
const port = protocol === 'http' ? `:${CADDY.DEFAULT_DNS_PORT}` : '';
|
||||||
|
const qs = params instanceof URLSearchParams ? params.toString() : new URLSearchParams(params).toString();
|
||||||
|
return `${protocol}://${server}${port}${apiPath}?${qs}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function callDns(server, apiPath, params) {
|
||||||
|
const url = buildDnsUrl(server, apiPath, params);
|
||||||
|
const response = await fetchT(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: { 'Accept': 'application/json' },
|
||||||
|
agent: httpsAgent
|
||||||
|
}, TIMEOUTS.HTTP_LONG);
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshDnsToken(username, password, server) {
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({ user: username, pass: password, includeInfo: 'false' });
|
||||||
|
const response = await fetchT(
|
||||||
|
`http://${server}:5380/api/user/login?${params.toString()}`,
|
||||||
|
{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' }, timeout: 10000 }
|
||||||
|
);
|
||||||
|
const result = await response.json();
|
||||||
|
if (result.status === 'ok' && result.token) {
|
||||||
|
dnsToken = result.token;
|
||||||
|
dnsTokenExpiry = new Date(Date.now() + SESSION_TTL.DNS_TOKEN).toISOString();
|
||||||
|
log.info('dns', 'DNS token refreshed', { expires: dnsTokenExpiry });
|
||||||
|
return { success: true, token: dnsToken };
|
||||||
|
}
|
||||||
|
return { success: false, error: result.errorMessage || 'Login failed' };
|
||||||
|
} catch (error) {
|
||||||
|
log.error('dns', 'DNS token refresh error', { error: error.message });
|
||||||
|
return { success: false, error: error.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function dnsIpToDnsId(serverIp) {
|
||||||
|
for (const [dnsId, info] of Object.entries(siteConfig.dnsServers || {})) {
|
||||||
|
if (info.ip === serverIp) return dnsId;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureValidDnsToken() {
|
||||||
|
if (dnsToken && dnsTokenExpiry && new Date() < new Date(dnsTokenExpiry)) {
|
||||||
|
return { success: true, token: dnsToken };
|
||||||
|
}
|
||||||
|
const primaryIp = siteConfig.dnsServerIp;
|
||||||
|
if (primaryIp) {
|
||||||
|
const dnsId = dnsIpToDnsId(primaryIp);
|
||||||
|
if (dnsId) {
|
||||||
|
for (const role of ['admin', 'readonly']) {
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve(`dns.${dnsId}.${role}.username`);
|
||||||
|
const password = await credentialManager.retrieve(`dns.${dnsId}.${role}.password`);
|
||||||
|
if (username && password) return await refreshDnsToken(username, password, primaryIp);
|
||||||
|
} catch (err) { /* try next */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve('dns.username');
|
||||||
|
const password = await credentialManager.retrieve('dns.password');
|
||||||
|
const server = await credentialManager.retrieve('dns.server');
|
||||||
|
if (username && password) return await refreshDnsToken(username, password, server || primaryIp);
|
||||||
|
} catch (err) { /* no global creds */ }
|
||||||
|
return { success: false, error: 'No DNS credentials configured' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getTokenForServer(targetServer, role = 'readonly') {
|
||||||
|
const cacheKey = `${targetServer}:${role}`;
|
||||||
|
const cached = dnsServerTokens.get(cacheKey);
|
||||||
|
if (cached?.token && cached?.expiry && new Date() < new Date(cached.expiry)) {
|
||||||
|
return { success: true, token: cached.token };
|
||||||
|
}
|
||||||
|
const serverPort = siteConfig.dnsServerPort || '5380';
|
||||||
|
async function authToServer(username, password) {
|
||||||
|
const params = new URLSearchParams({ user: username, pass: password, includeInfo: 'false' });
|
||||||
|
const response = await fetchT(
|
||||||
|
`http://${targetServer}:${serverPort}/api/user/login?${params.toString()}`,
|
||||||
|
{ method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } }
|
||||||
|
);
|
||||||
|
const result = await response.json();
|
||||||
|
if (result.status === 'ok' && result.token) {
|
||||||
|
dnsServerTokens.set(cacheKey, { token: result.token, expiry: new Date(Date.now() + SESSION_TTL.DNS_TOKEN).toISOString() });
|
||||||
|
log.info('dns', 'DNS token obtained for server', { server: targetServer, role });
|
||||||
|
return { success: true, token: result.token };
|
||||||
|
}
|
||||||
|
return { success: false, error: result.errorMessage || 'Login failed' };
|
||||||
|
}
|
||||||
|
const dnsId = dnsIpToDnsId(targetServer);
|
||||||
|
if (dnsId) {
|
||||||
|
for (const r of [role, role === 'readonly' ? 'admin' : 'readonly']) {
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve(`dns.${dnsId}.${r}.username`);
|
||||||
|
const password = await credentialManager.retrieve(`dns.${dnsId}.${r}.password`);
|
||||||
|
if (username && password) return await authToServer(username, password);
|
||||||
|
} catch { /* try next */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const username = await credentialManager.retrieve('dns.username');
|
||||||
|
const password = await credentialManager.retrieve('dns.password');
|
||||||
|
if (username && password) return await authToServer(username, password);
|
||||||
|
} catch { /* no global creds */ }
|
||||||
|
return { success: false, error: 'No DNS credentials configured' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireDnsToken(providedToken) {
|
||||||
|
if (providedToken) return providedToken;
|
||||||
|
const result = await ensureValidDnsToken();
|
||||||
|
if (result.success) return result.token;
|
||||||
|
const err = new Error('No valid DNS token available. ' + result.error);
|
||||||
|
err.statusCode = 401;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidateTokenForServer(serverIp) {
|
||||||
|
dnsServerTokens.delete(`${serverIp}:readonly`);
|
||||||
|
dnsServerTokens.delete(`${serverIp}:admin`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Public context API =====
|
||||||
|
// This maintains the same interface as the old createDnsContext()
|
||||||
|
// but adds provider-aware methods on top.
|
||||||
|
|
||||||
|
return {
|
||||||
|
// --- Provider-aware methods ---
|
||||||
|
/** Get the active provider ID */
|
||||||
|
getProviderId,
|
||||||
|
|
||||||
|
/** Get the active provider adapter instance */
|
||||||
|
getActiveProvider,
|
||||||
|
|
||||||
|
/** Get metadata for all available providers */
|
||||||
|
getAvailableProviders: () => registry.getProviderMeta(),
|
||||||
|
|
||||||
|
/** Check if the active provider supports a capability */
|
||||||
|
supportsCapability: (cap) => {
|
||||||
|
try { return getActiveProvider().supportsCapability(cap); }
|
||||||
|
catch { return false; }
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Legacy Technitium context (backward compat) ---
|
||||||
|
call: callDns,
|
||||||
|
buildUrl: buildDnsUrl,
|
||||||
|
requireToken: requireDnsToken,
|
||||||
|
ensureToken: ensureValidDnsToken,
|
||||||
|
getToken: () => dnsToken,
|
||||||
|
setToken: (t) => { dnsToken = t; },
|
||||||
|
getTokenExpiry: () => dnsTokenExpiry,
|
||||||
|
setTokenExpiry: (e) => { dnsTokenExpiry = e; },
|
||||||
|
getTokenForServer,
|
||||||
|
invalidateTokenForServer,
|
||||||
|
refresh: refreshDnsToken,
|
||||||
|
credentialsFile: DNS_CREDENTIALS_FILE,
|
||||||
|
|
||||||
|
// --- Universal DNS helpers (provider-agnostic) ---
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a DNS A record using the active provider.
|
||||||
|
* Gracefully handles manual adapters that return instructions instead of performing the action.
|
||||||
|
*/
|
||||||
|
async universalCreateRecord(subdomain, ip) {
|
||||||
|
const provider = getActiveProvider();
|
||||||
|
const result = await provider.createRecord({
|
||||||
|
domain: buildDomain(subdomain),
|
||||||
|
zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: 'A',
|
||||||
|
value: ip,
|
||||||
|
ttl: 300,
|
||||||
|
overwrite: true,
|
||||||
|
});
|
||||||
|
// Manual adapter returns instructions instead of performing the action
|
||||||
|
if (result?.manual || result?.instructions) {
|
||||||
|
return { success: true, manual: true, instructions: result.instructions || result };
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a DNS A record using the active provider.
|
||||||
|
* Gracefully handles manual adapters that return instructions instead of performing the action.
|
||||||
|
*/
|
||||||
|
async universalDeleteRecord(domain, ip) {
|
||||||
|
const provider = getActiveProvider();
|
||||||
|
const result = await provider.deleteRecord({
|
||||||
|
domain,
|
||||||
|
type: 'A',
|
||||||
|
value: ip,
|
||||||
|
});
|
||||||
|
if (result?.manual || result?.instructions) {
|
||||||
|
return { success: true, manual: true, instructions: result.instructions || result };
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve DNS records using the active provider.
|
||||||
|
* Returns parsed IP addresses from the result.
|
||||||
|
*/
|
||||||
|
async universalResolveRecord(domain, type) {
|
||||||
|
const provider = getActiveProvider();
|
||||||
|
const result = await provider.resolveRecords({
|
||||||
|
domain,
|
||||||
|
zone: siteConfig.tld?.replace(/^\./, '') || '',
|
||||||
|
type: type || 'A',
|
||||||
|
});
|
||||||
|
// Parse IP addresses from the result
|
||||||
|
if (Array.isArray(result)) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
if (result?.records) {
|
||||||
|
return result.records.map(r => r.ipAddress || r.value || r.address || r).filter(Boolean);
|
||||||
|
}
|
||||||
|
if (result?.ips) {
|
||||||
|
return result.ips;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createProviderDnsContext };
|
||||||
@@ -94,8 +94,12 @@ async function logError(ERROR_LOG_FILE, MAX_ERROR_LOG_SIZE, context, error, addi
|
|||||||
* Return a safe error message without leaking internals
|
* Return a safe error message without leaking internals
|
||||||
*/
|
*/
|
||||||
function safeErrorMessage(error) {
|
function safeErrorMessage(error) {
|
||||||
|
if (!error) return 'An internal error occurred';
|
||||||
const msg = error.message || String(error);
|
const msg = error.message || String(error);
|
||||||
|
|
||||||
|
// Always expose DC-prefixed user-facing errors
|
||||||
|
if (/\[DC-\d+\]/.test(msg)) return msg;
|
||||||
|
|
||||||
// Detect port conflict errors
|
// Detect port conflict errors
|
||||||
const portMatch = msg.match(/exposing port TCP [^:]*:(\d+)/);
|
const portMatch = msg.match(/exposing port TCP [^:]*:(\d+)/);
|
||||||
if (portMatch || msg.includes('port is already allocated') || msg.includes('ports are not available')) {
|
if (portMatch || msg.includes('port is already allocated') || msg.includes('ports are not available')) {
|
||||||
@@ -103,7 +107,7 @@ function safeErrorMessage(error) {
|
|||||||
return `[DC-200] Port ${port} is already in use. Try a different port or stop the service using that port first.`;
|
return `[DC-200] Port ${port} is already in use. Try a different port or stop the service using that port first.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only expose short, user-facing messages
|
// Only expose short, user-facing messages (no paths, stack traces, or internal details)
|
||||||
if (msg.length < 200 && !msg.includes('/') && !msg.includes('\\') && !msg.includes(' at ')) {
|
if (msg.length < 200 && !msg.includes('/') && !msg.includes('\\') && !msg.includes(' at ')) {
|
||||||
return msg;
|
return msg;
|
||||||
}
|
}
|
||||||
|
|||||||
Executable
+379
@@ -0,0 +1,379 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# DashCaddy Host-Side Updater
|
||||||
|
# Triggered by systemd path unit when the container writes trigger.json.
|
||||||
|
# Reads the trigger, backs up current API + data/, copies new files, rebuilds container.
|
||||||
|
# Writes result.json so the new container knows the outcome.
|
||||||
|
#
|
||||||
|
# This runs on the HOST, outside the container.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
readonly UPDATES_DIR="/opt/dashcaddy/updates"
|
||||||
|
readonly TRIGGER_FILE="${UPDATES_DIR}/trigger.json"
|
||||||
|
readonly RESULT_FILE="${UPDATES_DIR}/result.json"
|
||||||
|
readonly BACKUPS_DIR="${UPDATES_DIR}/backups"
|
||||||
|
readonly CONTAINER_NAME="dashcaddy-api"
|
||||||
|
readonly IMAGE_TAG="dashcaddy-dashcaddy-api:latest"
|
||||||
|
readonly MAX_BACKUPS=3
|
||||||
|
readonly HEALTH_TIMEOUT=60
|
||||||
|
|
||||||
|
# Data directory backup — stored alongside code backups so everything rolls back together
|
||||||
|
readonly DATA_SOURCE_DIR="/opt/dashcaddy/dashcaddy-api/data"
|
||||||
|
readonly DATA_BACKUP_PREFIX="data-backup"
|
||||||
|
|
||||||
|
log() { echo "[dashcaddy-update] $(date '+%Y-%m-%d %H:%M:%S') $*"; }
|
||||||
|
|
||||||
|
write_result() {
|
||||||
|
local success="$1" version="$2" duration="$3"
|
||||||
|
shift 3
|
||||||
|
local error="${1:-}"
|
||||||
|
|
||||||
|
if [[ "$success" == "true" ]]; then
|
||||||
|
cat > "$RESULT_FILE" <<EOF
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"version": "${version}",
|
||||||
|
"duration": ${duration},
|
||||||
|
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
else
|
||||||
|
cat > "$RESULT_FILE" <<EOF
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"version": "${version}",
|
||||||
|
"duration": ${duration},
|
||||||
|
"error": "${error}",
|
||||||
|
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup_old_backups() {
|
||||||
|
local count
|
||||||
|
count=$(find "$BACKUPS_DIR" -maxdepth 1 -mindepth 1 -type d 2>/dev/null | wc -l)
|
||||||
|
if (( count > MAX_BACKUPS )); then
|
||||||
|
log "Cleaning old backups (${count} > ${MAX_BACKUPS})"
|
||||||
|
find "$BACKUPS_DIR" -maxdepth 1 -mindepth 1 -type d -printf '%T+ %p\n' \
|
||||||
|
| sort | head -n $(( count - MAX_BACKUPS )) | cut -d' ' -f2- \
|
||||||
|
| xargs rm -rf
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Data backup (rsync for efficiency + permissions) ──────────────────────────
|
||||||
|
backup_data_dir() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
if [[ -d "$DATA_SOURCE_DIR" ]]; then
|
||||||
|
log "Backing up data/ to ${backup_dir}/${DATA_BACKUP_PREFIX}/"
|
||||||
|
mkdir -p "${backup_dir}/${DATA_BACKUP_PREFIX}"
|
||||||
|
rsync -a --delete "$DATA_SOURCE_DIR/" "${backup_dir}/${DATA_BACKUP_PREFIX}/" 2>/dev/null \
|
||||||
|
|| cp -a "$DATA_SOURCE_DIR" "${backup_dir}/${DATA_BACKUP_PREFIX}"
|
||||||
|
log "Data backup complete ($(du -sh "${backup_dir}/${DATA_BACKUP_PREFIX}" 2>/dev/null | cut -f1))"
|
||||||
|
else
|
||||||
|
log "WARNING: Data source dir $DATA_SOURCE_DIR not found — skipping data backup"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Data restore ──────────────────────────────────────────────────────────────
|
||||||
|
restore_data_dir() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
local data_backup="${backup_dir}/${DATA_BACKUP_PREFIX}"
|
||||||
|
if [[ -d "$data_backup" ]]; then
|
||||||
|
log "Restoring data/ from backup..."
|
||||||
|
rsync -a --delete "$data_backup/" "$DATA_SOURCE_DIR/" 2>/dev/null \
|
||||||
|
|| cp -a "$data_backup" "$DATA_SOURCE_DIR"
|
||||||
|
log "Data restored successfully"
|
||||||
|
else
|
||||||
|
log "WARNING: No data backup found at ${data_backup} — data/ not restored"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_health() {
|
||||||
|
local port="${1:-3001}"
|
||||||
|
local timeout="$HEALTH_TIMEOUT"
|
||||||
|
local elapsed=0
|
||||||
|
|
||||||
|
log "Waiting for health check (timeout: ${timeout}s)..."
|
||||||
|
while (( elapsed < timeout )); do
|
||||||
|
if curl -fsSL --max-time 3 "http://localhost:${port}/health" &>/dev/null; then
|
||||||
|
log "Health check passed after ${elapsed}s"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
sleep 2
|
||||||
|
elapsed=$(( elapsed + 2 ))
|
||||||
|
done
|
||||||
|
|
||||||
|
log "Health check FAILED after ${timeout}s"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Shared rollback: restore code + data ────────────────────────────────────
|
||||||
|
rollback_restore() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
log "Rolling back: restoring code files..."
|
||||||
|
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
if [[ -d "$backup_dir/routes" ]]; then
|
||||||
|
rm -rf "$api_source_dir/routes"
|
||||||
|
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
||||||
|
fi
|
||||||
|
if [[ -d "$backup_dir/src" ]]; then
|
||||||
|
rm -rf "$api_source_dir/src"
|
||||||
|
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
||||||
|
fi
|
||||||
|
if [[ -d "$backup_dir/dns-providers" ]]; then
|
||||||
|
rm -rf "$api_source_dir/dns-providers"
|
||||||
|
cp -rf "$backup_dir/dns-providers" "$api_source_dir/dns-providers"
|
||||||
|
fi
|
||||||
|
restore_data_dir "$backup_dir"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Deployment mode ───────────────────────────────────────────────────────────
|
||||||
|
# Reproduce the SAME container the install created so an auto-update keeps every
|
||||||
|
# volume + env var (docker socket, Caddyfile, config/credentials, updates mount),
|
||||||
|
# not a minimal subset. Standard installs use docker-compose (compose file in the
|
||||||
|
# api source dir); the publish/dev host uses /opt/dashcaddy/start.sh; otherwise a
|
||||||
|
# bare docker run is the last resort. build_image() and restart_container() both
|
||||||
|
# honor the detected mode so build and run stay consistent.
|
||||||
|
deploy_mode() {
|
||||||
|
if [[ -f "$api_source_dir/docker-compose.yml" || -f "$api_source_dir/compose.yml" || -f "$api_source_dir/compose.yaml" ]]; then
|
||||||
|
echo compose
|
||||||
|
elif [[ -x /opt/dashcaddy/start.sh ]]; then
|
||||||
|
echo startsh
|
||||||
|
else
|
||||||
|
echo run
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Build the API image using whatever the install is wired for. Returns the build
|
||||||
|
# command's exit status so callers can detect failure.
|
||||||
|
build_image() {
|
||||||
|
cd "$api_source_dir" || return 1
|
||||||
|
case "$(deploy_mode)" in
|
||||||
|
compose) docker compose build 2>&1 || docker-compose build 2>&1 ;;
|
||||||
|
*) docker build -t "$IMAGE_TAG" . 2>&1 ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Shared container restart — recreate with the full, install-defined spec ───
|
||||||
|
# Recreates (rm + run / compose up) so new code AND new env vars take effect.
|
||||||
|
restart_container() {
|
||||||
|
cd "$api_source_dir" 2>/dev/null || true
|
||||||
|
case "$(deploy_mode)" in
|
||||||
|
compose)
|
||||||
|
log "Recreating container via docker compose (full compose spec)..."
|
||||||
|
docker compose up -d 2>&1 || docker-compose up -d 2>&1
|
||||||
|
;;
|
||||||
|
startsh)
|
||||||
|
log "Recreating container via /opt/dashcaddy/start.sh (full container spec)..."
|
||||||
|
bash /opt/dashcaddy/start.sh
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
log "Recreating container via minimal docker run (fallback)..."
|
||||||
|
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
||||||
|
docker run -d --restart unless-stopped --name "$CONTAINER_NAME" \
|
||||||
|
-p 127.0.0.1:3001:3001 \
|
||||||
|
-v /opt/dashcaddy/dashcaddy-api/data:/app/data \
|
||||||
|
-e SERVICES_FILE=/app/data/services.json \
|
||||||
|
"$IMAGE_TAG"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
log "Container recreated"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── Code-only restore (used after failed build when data hasn't changed yet) ──
|
||||||
|
code_restore() {
|
||||||
|
local backup_dir="$1"
|
||||||
|
log "Restoring code files..."
|
||||||
|
for item in "$backup_dir"/*.js "$backup_dir"/package.json "$backup_dir"/package-lock.json "$backup_dir"/Dockerfile "$backup_dir"/openapi.yaml "$backup_dir"/VERSION; do
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
if [[ -d "$backup_dir/routes" ]]; then
|
||||||
|
rm -rf "$api_source_dir/routes"
|
||||||
|
cp -rf "$backup_dir/routes" "$api_source_dir/routes"
|
||||||
|
fi
|
||||||
|
if [[ -d "$backup_dir/src" ]]; then
|
||||||
|
rm -rf "$api_source_dir/src"
|
||||||
|
cp -rf "$backup_dir/src" "$api_source_dir/src"
|
||||||
|
fi
|
||||||
|
if [[ -d "$backup_dir/dns-providers" ]]; then
|
||||||
|
rm -rf "$api_source_dir/dns-providers"
|
||||||
|
cp -rf "$backup_dir/dns-providers" "$api_source_dir/dns-providers"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local start_time
|
||||||
|
start_time=$(date +%s)
|
||||||
|
|
||||||
|
# 1. Read trigger
|
||||||
|
if [[ ! -f "$TRIGGER_FILE" ]]; then
|
||||||
|
log "No trigger file found — nothing to do"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Parse trigger.json (uses python3 which is available on all supported distros)
|
||||||
|
local action version from_version staging_dir api_source_dir commit
|
||||||
|
local frontend_staging_dir frontend_target_dir
|
||||||
|
action=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['action'])")
|
||||||
|
version=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['version'])")
|
||||||
|
from_version=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['fromVersion'])")
|
||||||
|
staging_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['stagingDir'])")
|
||||||
|
api_source_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}'))['apiSourceDir'])")
|
||||||
|
commit=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('commit') or '')")
|
||||||
|
frontend_staging_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('frontendStagingDir') or '')")
|
||||||
|
frontend_target_dir=$(python3 -c "import json; print(json.load(open('${TRIGGER_FILE}')).get('frontendTargetDir') or '')")
|
||||||
|
# Handle action=rollback (no new version to deploy)
|
||||||
|
local to_version="${version}"
|
||||||
|
|
||||||
|
log "=== ${action^^}: v${from_version} -> v${to_version} ==="
|
||||||
|
log "Staging: ${staging_dir}"
|
||||||
|
log "API source: ${api_source_dir}"
|
||||||
|
|
||||||
|
# Consume the trigger immediately so we don't re-process on failure
|
||||||
|
mv "$TRIGGER_FILE" "${TRIGGER_FILE}.processing"
|
||||||
|
|
||||||
|
# ── Handle rollback ────────────────────────────────────────────────────────
|
||||||
|
if [[ "$action" == "rollback" ]]; then
|
||||||
|
local backup_dir="${BACKUPS_DIR}/${version}"
|
||||||
|
if [[ ! -d "$backup_dir" ]]; then
|
||||||
|
log "ERROR: No backup found for version ${version}"
|
||||||
|
write_result "false" "$version" "$(( $(date +%s) - start_time ))" "No backup found for version ${version}"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "Performing rollback to v${version}..."
|
||||||
|
rollback_restore "$backup_dir"
|
||||||
|
|
||||||
|
# Rebuild old code
|
||||||
|
log "Rebuilding container..."
|
||||||
|
build_image 2>&1 | tail -3 || true
|
||||||
|
|
||||||
|
restart_container
|
||||||
|
wait_for_health || log "WARNING: Health check failed after rollback"
|
||||||
|
|
||||||
|
write_result "true" "$version" "$(( $(date +%s) - start_time ))"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
log "=== Rollback complete ==="
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# ── Handle update ───────────────────────────────────────────────────────────
|
||||||
|
if [[ ! -d "$staging_dir" ]]; then
|
||||||
|
log "ERROR: Staging directory not found: ${staging_dir}"
|
||||||
|
write_result "false" "$to_version" "$(( $(date +%s) - start_time ))" "Staging directory not found"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. Backup current API code + data/
|
||||||
|
local backup_dir="${BACKUPS_DIR}/${from_version}"
|
||||||
|
mkdir -p "$backup_dir"
|
||||||
|
log "Backing up current API files to ${backup_dir}"
|
||||||
|
for item in "$api_source_dir"/*.js "$api_source_dir"/package.json "$api_source_dir"/package-lock.json "$api_source_dir"/Dockerfile "$api_source_dir"/openapi.yaml "$api_source_dir"/VERSION; do
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$backup_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
[[ -d "$api_source_dir/routes" ]] && cp -rf "$api_source_dir/routes" "$backup_dir/"
|
||||||
|
[[ -d "$api_source_dir/src" ]] && cp -rf "$api_source_dir/src" "$backup_dir/"
|
||||||
|
[[ -d "$api_source_dir/dns-providers" ]] && cp -rf "$api_source_dir/dns-providers" "$backup_dir/"
|
||||||
|
|
||||||
|
# Backup data/ directory (services.json, config.json, credentials, etc.)
|
||||||
|
backup_data_dir "$backup_dir"
|
||||||
|
|
||||||
|
cleanup_old_backups
|
||||||
|
|
||||||
|
# 3. Copy new files from staging to API source
|
||||||
|
log "Deploying new API files..."
|
||||||
|
for item in "$staging_dir"/*.js "$staging_dir"/package.json "$staging_dir"/package-lock.json "$staging_dir"/Dockerfile "$staging_dir"/openapi.yaml "$staging_dir"/VERSION; do
|
||||||
|
[[ -f "$item" ]] && cp -f "$item" "$api_source_dir/" 2>/dev/null || true
|
||||||
|
done
|
||||||
|
if [[ -d "$staging_dir/routes" ]]; then
|
||||||
|
rm -rf "$api_source_dir/routes"
|
||||||
|
cp -rf "$staging_dir/routes" "$api_source_dir/routes"
|
||||||
|
fi
|
||||||
|
if [[ -d "$staging_dir/src" ]]; then
|
||||||
|
rm -rf "$api_source_dir/src"
|
||||||
|
cp -rf "$staging_dir/src" "$api_source_dir/src"
|
||||||
|
fi
|
||||||
|
if [[ -d "$staging_dir/dns-providers" ]]; then
|
||||||
|
rm -rf "$api_source_dir/dns-providers"
|
||||||
|
cp -rf "$staging_dir/dns-providers" "$api_source_dir/dns-providers"
|
||||||
|
fi
|
||||||
|
if [[ -n "$commit" ]]; then
|
||||||
|
echo "$commit" > "$api_source_dir/VERSION"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3b. Sync frontend
|
||||||
|
if [[ -z "$frontend_staging_dir" ]]; then
|
||||||
|
parent_staging=$(dirname "$staging_dir")
|
||||||
|
[[ -d "$parent_staging/status" ]] && frontend_staging_dir="$parent_staging/status"
|
||||||
|
fi
|
||||||
|
if [[ -z "$frontend_target_dir" ]]; then
|
||||||
|
for candidate in /var/www/dashcaddy-status /etc/dashcaddy/sites/status; do
|
||||||
|
[[ -d "$candidate" ]] && frontend_target_dir="$candidate" && break
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
if [[ -n "$frontend_staging_dir" && -n "$frontend_target_dir" && -d "$frontend_staging_dir" ]]; then
|
||||||
|
log "Syncing frontend: $frontend_staging_dir -> $frontend_target_dir"
|
||||||
|
mkdir -p "$frontend_target_dir"
|
||||||
|
[[ -f "$frontend_staging_dir/index.html" ]] && cp -f "$frontend_staging_dir/index.html" "$frontend_target_dir/index.html"
|
||||||
|
[[ -f "$frontend_staging_dir/sw.js" ]] && cp -f "$frontend_staging_dir/sw.js" "$frontend_target_dir/sw.js"
|
||||||
|
for sub in dist css vendor js; do
|
||||||
|
if [[ -d "$frontend_staging_dir/$sub" ]]; then
|
||||||
|
mkdir -p "$frontend_target_dir/$sub"
|
||||||
|
cp -rf "$frontend_staging_dir/$sub/"* "$frontend_target_dir/$sub/" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [[ -d "$frontend_staging_dir/assets" ]]; then
|
||||||
|
mkdir -p "$frontend_target_dir/assets"
|
||||||
|
cp -rf "$frontend_staging_dir/assets/"* "$frontend_target_dir/assets/" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4. Rebuild container
|
||||||
|
log "Rebuilding container..."
|
||||||
|
local build_ok=false
|
||||||
|
if build_image; then
|
||||||
|
build_ok=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ "$build_ok" != "true" ]]; then
|
||||||
|
log "ERROR: Docker build failed — rolling back code + data"
|
||||||
|
code_restore "$backup_dir"
|
||||||
|
build_image 2>&1 | tail -3 || true
|
||||||
|
restart_container
|
||||||
|
wait_for_health || true
|
||||||
|
write_result "false" "$to_version" "$(( $(date +%s) - start_time ))" "Docker build failed"
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. Restart container (recreate so new code + env vars take effect)
|
||||||
|
restart_container
|
||||||
|
|
||||||
|
# 6. Health check
|
||||||
|
if wait_for_health; then
|
||||||
|
local duration=$(( $(date +%s) - start_time ))
|
||||||
|
log "=== Update successful: v${to_version} in ${duration}s ==="
|
||||||
|
write_result "true" "$to_version" "$duration"
|
||||||
|
else
|
||||||
|
local duration=$(( $(date +%s) - start_time ))
|
||||||
|
log "ERROR: Health check failed after update — rolling back code + data"
|
||||||
|
rollback_restore "$backup_dir"
|
||||||
|
build_image 2>&1 | tail -3 || true
|
||||||
|
restart_container
|
||||||
|
wait_for_health || log "WARNING: Rollback health check also failed"
|
||||||
|
write_result "false" "$to_version" "$duration" "Health check failed after update"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 7. Cleanup
|
||||||
|
rm -f "${TRIGGER_FILE}.processing"
|
||||||
|
rm -rf "${UPDATES_DIR}/staging" 2>/dev/null || true
|
||||||
|
|
||||||
|
log "=== Update process complete ==="
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
+8
-2
@@ -393,8 +393,14 @@
|
|||||||
<!-- DNS Server Configuration -->
|
<!-- DNS Server Configuration -->
|
||||||
<div>
|
<div>
|
||||||
<label class="form-label-accent">
|
<label class="form-label-accent">
|
||||||
🗂️ DNS Server (Technitium)
|
🗂️ DNS Provider
|
||||||
</label>
|
</label>
|
||||||
|
<select id="setup-dns-provider" class="form-input-lg" style="margin-bottom: 12px;">
|
||||||
|
<option value="technitium">Technitium DNS (recommended)</option>
|
||||||
|
<option value="cloudflare">Cloudflare DNS</option>
|
||||||
|
<option value="rfc2136">RFC 2136 (BIND / PowerDNS / other)</option>
|
||||||
|
<option value="manual">Manual / External DNS</option>
|
||||||
|
</select>
|
||||||
<div style="display: grid; grid-template-columns: 1fr auto; gap: 8px;">
|
<div style="display: grid; grid-template-columns: 1fr auto; gap: 8px;">
|
||||||
<input type="text" id="setup-dns-ip" value="" placeholder="DNS server IP"
|
<input type="text" id="setup-dns-ip" value="" placeholder="DNS server IP"
|
||||||
style="padding: 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem;" />
|
style="padding: 12px; background: var(--card-bg); color: var(--fg); border: 1px solid var(--border); border-radius: 6px; font-size: 1rem;" />
|
||||||
@@ -409,7 +415,7 @@
|
|||||||
<!-- DNS Admin Token -->
|
<!-- DNS Admin Token -->
|
||||||
<div>
|
<div>
|
||||||
<label class="form-label-accent">
|
<label class="form-label-accent">
|
||||||
🔑 Technitium Admin Token
|
🔑 DNS Admin Token / API Key
|
||||||
</label>
|
</label>
|
||||||
<input type="password" id="setup-dns-token" placeholder="Paste your admin token here"
|
<input type="password" id="setup-dns-token" placeholder="Paste your admin token here"
|
||||||
class="form-input-lg" />
|
class="form-input-lg" />
|
||||||
|
|||||||
@@ -95,6 +95,36 @@
|
|||||||
'Prometheus metrics'
|
'Prometheus metrics'
|
||||||
],
|
],
|
||||||
recommended: false
|
recommended: false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cloudflare',
|
||||||
|
name: 'Cloudflare DNS',
|
||||||
|
description: 'Managed DNS with API access — no self-hosting needed',
|
||||||
|
icon: '🔶',
|
||||||
|
difficulty: 'Easy',
|
||||||
|
features: [
|
||||||
|
'Fully managed, no server needed',
|
||||||
|
'API for automated record management',
|
||||||
|
'Global anycast network',
|
||||||
|
'Free tier available'
|
||||||
|
],
|
||||||
|
recommended: false,
|
||||||
|
providerId: 'cloudflare'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'external',
|
||||||
|
name: 'External / Manual DNS',
|
||||||
|
description: 'Use your own DNS provider (cPanel, Route53, etc.)',
|
||||||
|
icon: '🔗',
|
||||||
|
difficulty: 'Easy',
|
||||||
|
features: [
|
||||||
|
'Works with any DNS provider',
|
||||||
|
'DashCaddy shows you what records to create',
|
||||||
|
'Propagation checking still works',
|
||||||
|
'No API credentials needed'
|
||||||
|
],
|
||||||
|
recommended: false,
|
||||||
|
providerId: 'manual'
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -174,8 +174,9 @@ window.populateTimezoneSelect = function(selectEl, selectedTz) {
|
|||||||
if (currentConfigType === 'homelab') {
|
if (currentConfigType === 'homelab') {
|
||||||
config.tld = document.getElementById('setup-tld')?.value?.trim() || '.home';
|
config.tld = document.getElementById('setup-tld')?.value?.trim() || '.home';
|
||||||
config.caName = document.getElementById('setup-ca-name')?.value?.trim() || '';
|
config.caName = document.getElementById('setup-ca-name')?.value?.trim() || '';
|
||||||
|
const selectedProvider = document.getElementById('setup-dns-provider')?.value || 'technitium';
|
||||||
config.dns = {
|
config.dns = {
|
||||||
provider: 'technitium',
|
provider: selectedProvider,
|
||||||
ip: document.getElementById('setup-dns-ip')?.value?.trim() || '',
|
ip: document.getElementById('setup-dns-ip')?.value?.trim() || '',
|
||||||
port: document.getElementById('setup-dns-port')?.value?.trim() || DC.DEFAULTS.DNS_PORT,
|
port: document.getElementById('setup-dns-port')?.value?.trim() || DC.DEFAULTS.DNS_PORT,
|
||||||
token: document.getElementById('setup-dns-token')?.value?.trim() || ''
|
token: document.getElementById('setup-dns-token')?.value?.trim() || ''
|
||||||
|
|||||||
Reference in New Issue
Block a user