Add dynamic DNS: keep A records pointed at the current public IP

For deployments on WAN DHCP, operators can declare A records in the DNS section
that the app updates to this box's current public IP every 4 hours (and
immediately on create).

- utils/public_ip.js: getPublicIp() queries external echo services (ipify +
  fallbacks, configurable) with pure isIPv4/extractIp helpers.
- utils/dns_records.js: pure planARecordUpdate() reconciliation decision.
- models/dns_provider.js: Domain.upsertARecord(name, ip) — provider-agnostic
  upsert via getRecords + deleteRecordById + createRecord (createRecord alone is
  not a reliable cross-provider upsert). Apex ('@') handling added to each
  provider (CloudFlare uses the domain name, Porkbun an empty name, DigitalOcean
  '@') via a new DnsApi.apexName().
- models/dynamic_record.js: DynamicRecord model (deterministic id per host,
  apply()/refreshAll()), registered + ModelPs-wrapped for live UI updates.
- services/dynamic_dns.js + conf: 4h scheduler mirroring host_scheduler.
- routes/dns.js: /dynamic CRUD + /dynamic/ip, gated to domain managers/admins.
- views/dns.ejs: "Dynamic A Records (WAN IP)" card with add form + list.
- test/unit/dynamic_record.test.js: public-IP parsing + reconciliation logic.

Verified end-to-end against a live Porkbun domain (create, idempotent, IP-change,
cleanup) plus unit suite (111 pass).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-10 23:55:56 -04:00
parent 1f7a9e5ded
commit a2d194f855
17 changed files with 542 additions and 7 deletions
+21
View File
@@ -0,0 +1,21 @@
'use strict';
// Pure DNS-record reconciliation logic, kept out of models/dns_provider.js so it
// can be unit-tested without a redis connection. Used by Domain.upsertARecord.
/**
* Decide how to reconcile an A record to `ip`, given the domain's current A
* records (as returned by a provider's getRecords: {id, name, data}) and the
* target sub-name (`''` for apex).
*
* Returns {deleteIds: [...], create: bool}: delete every same-name A record whose
* value differs, and create a new one unless a correct one already exists.
*/
function planARecordUpdate(aRecords, sub, ip){
let matches = (aRecords || []).filter(r => (r.name || '') === sub);
let correct = matches.some(r => r.data === ip);
let deleteIds = matches.filter(r => r.data !== ip).map(r => r.id);
return {deleteIds, create: !correct};
}
module.exports = {planARecordUpdate};
+69
View File
@@ -0,0 +1,69 @@
'use strict';
// Discover this deployment's current public (WAN) IP by asking an external echo
// service. Used by the dynamic-DNS feature to keep A records pointed at the box
// even on WAN DHCP. Pure helpers (isIPv4/extractIp) are unit-tested; getPublicIp
// does the network calls.
const axios = require('axios');
const conf = require('@simpleworkjs/conf');
const DEFAULT_SERVICES = [
'https://api.ipify.org',
'https://icanhazip.com',
'https://ifconfig.me/ip',
];
// Strict dotted-quad IPv4 check (0-255 per octet).
function isIPv4(str){
if(typeof str !== 'string') return false;
let m = str.trim().match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
if(!m) return false;
for(let i = 1; i <= 4; i++){
if(Number(m[i]) > 255) return false;
}
return true;
}
// Pull an IPv4 out of a service response, which may be bare text ("1.2.3.4\n")
// or JSON ({"ip":"1.2.3.4"}). Returns the IP string or null.
function extractIp(body){
if(body === undefined || body === null) return null;
if(typeof body === 'object'){
let candidate = body.ip || body.address || body.origin;
return isIPv4(candidate) ? candidate.trim() : null;
}
let text = String(body).trim();
if(isIPv4(text)) return text;
// Some endpoints wrap the value; try to find the first IPv4 token.
let m = text.match(/\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/);
return m && isIPv4(m[1]) ? m[1] : null;
}
// Try each configured service in order; return the first valid IPv4. Throws if
// they all fail so the caller can log and skip this cycle.
async function getPublicIp(){
let services = (conf.dynamicDns && conf.dynamicDns.ipServices) || DEFAULT_SERVICES;
let lastError;
for(let url of services){
try{
let res = await axios.get(url, {timeout: 5000, responseType: 'text'});
let ip = extractIp(res.data);
if(ip) return ip;
lastError = new Error(`No IPv4 in response from ${url}`);
}catch(error){
lastError = error;
}
}
let error = new Error('PublicIpUnavailable');
error.name = 'PublicIpUnavailable';
error.message = `Could not determine public IP: ${lastError && lastError.message}`;
throw error;
}
module.exports = {isIPv4, extractIp, getPublicIp, DEFAULT_SERVICES};