Files
cloudron-box/src/dyndns.js
Girish Ramakrishnan f48690ee11 dyndns: fix typo
2022-03-15 09:53:54 -07:00

58 lines
2.3 KiB
JavaScript

'use strict';
exports = module.exports = {
sync
};
const apps = require('./apps.js'),
assert = require('assert'),
constants = require('./constants.js'),
debug = require('debug')('box:dyndns'),
dns = require('./dns.js'),
eventlog = require('./eventlog.js'),
paths = require('./paths.js'),
safe = require('safetydance'),
settings = require('./settings.js'),
sysinfo = require('./sysinfo.js');
// called for dynamic dns setups where we have to update the IP
async function sync(auditSource) {
assert.strictEqual(typeof auditSource, 'object');
const ipv4 = await sysinfo.getServerIPv4();
const ipv6 = await sysinfo.getServerIPv6();
const info = safe.JSON.parse(safe.fs.readFileSync(paths.DYNDNS_INFO_FILE, 'utf8')) || { ipv4: null, ipv6: null };
if (info.ip) { // legacy cache file
info.ipv4 = info.ip;
delete info.ip;
}
const ipv4Changed = info.ipv4 !== ipv4;
const ipv6Changed = ipv6 && info.ipv6 !== ipv6; // both should be RFC 5952 format
if (!ipv4Changed && !ipv6Changed) {
debug(`refreshDNS: no change in IP ipv4: ${ipv4} ipv6: ${ipv6}`);
return;
}
debug(`refreshDNS: updating IP from ${info.ipv4} to ipv4: ${ipv4} (changed: ${ipv4Changed}) ipv6: ${ipv6} (changed: ${ipv6Changed})`);
if (ipv4Changed) await dns.upsertDnsRecords(constants.DASHBOARD_LOCATION, settings.dashboardDomain(), 'A', [ ipv4 ]);
if (ipv6Changed) await dns.upsertDnsRecords(constants.DASHBOARD_LOCATION, settings.dashboardDomain(), 'AAAA', [ ipv6 ]);
const result = await apps.list();
for (const app of result) {
// do not change state of installing apps since apptask will error if dns record already exists
if (app.installationState !== apps.ISTATE_INSTALLED) continue;
if (ipv4Changed) await dns.upsertDnsRecords(app.subdomain, app.domain, 'A', [ ipv4 ]);
if (ipv6Changed) await dns.upsertDnsRecords(app.subdomain, app.domain, 'AAAA', [ ipv6 ]);
}
debug('refreshDNS: updated apps');
await eventlog.add(eventlog.ACTION_DYNDNS_UPDATE, auditSource, { fromIpv4: info.ipv4, fromIpv6: info.ipv6, toIpv4: ipv4, toIpv6: ipv6 });
info.ipv4 = ipv4;
info.ipv6 = ipv6;
safe.fs.writeFileSync(paths.DYNDNS_INFO_FILE, JSON.stringify(info), 'utf8');
}