Files
cloudron-box/src/dns/namecheap.js

323 lines
13 KiB
JavaScript
Raw Normal View History

2019-01-16 18:05:42 +02:00
'use strict';
exports = module.exports = {
removePrivateFields: removePrivateFields,
injectPrivateFields: injectPrivateFields,
2019-01-16 18:05:42 +02:00
upsert: upsert,
get: get,
del: del,
verifyDnsConfig: verifyDnsConfig,
wait: wait
2019-01-16 18:05:42 +02:00
};
var assert = require('assert'),
2019-10-23 10:02:04 -07:00
BoxError = require('../boxerror.js'),
constants = require('../constants.js'),
2019-01-16 18:05:42 +02:00
debug = require('debug')('box:dns/namecheap'),
dns = require('../native-dns.js'),
domains = require('../domains.js'),
2021-04-13 21:36:05 -07:00
querystring = require('querystring'),
2019-05-16 17:00:17 +02:00
safe = require('safetydance'),
superagent = require('superagent'),
2019-05-16 17:00:17 +02:00
sysinfo = require('../sysinfo.js'),
waitForDns = require('./waitfordns.js'),
xml2js = require('xml2js');
2019-01-16 18:05:42 +02:00
const ENDPOINT = 'https://api.namecheap.com/xml.response';
2019-01-16 18:05:42 +02:00
function removePrivateFields(domainObject) {
domainObject.config.token = constants.SECRET_PLACEHOLDER;
return domainObject;
}
function injectPrivateFields(newConfig, currentConfig) {
if (newConfig.token === constants.SECRET_PLACEHOLDER) newConfig.token = currentConfig.token;
}
function getQuery(dnsConfig, callback) {
assert.strictEqual(typeof dnsConfig, 'object');
assert.strictEqual(typeof callback, 'function');
2019-10-29 15:46:33 -07:00
sysinfo.getServerIp(function (error, ip) {
2019-10-23 10:02:04 -07:00
if (error) return callback(error);
callback(null, {
ApiUser: dnsConfig.username,
ApiKey: dnsConfig.token,
UserName: dnsConfig.username,
ClientIp: ip
});
});
}
2021-04-13 15:10:24 -07:00
function getZone(dnsConfig, zoneName, callback) {
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof dnsConfig, 'object');
assert.strictEqual(typeof zoneName, 'string');
assert.strictEqual(typeof callback, 'function');
getQuery(dnsConfig, function (error, query) {
if (error) return callback(error);
2019-01-16 18:05:42 +02:00
query.Command = 'namecheap.domains.dns.getHosts';
query.SLD = zoneName.split('.')[0];
query.TLD = zoneName.split('.')[1];
2019-01-16 18:05:42 +02:00
superagent.get(ENDPOINT).query(query).end(function (error, result) {
2019-10-23 10:02:04 -07:00
if (error) return callback(new BoxError(BoxError.EXTERNAL_ERROR, error));
2019-01-16 18:05:42 +02:00
var parser = new xml2js.Parser();
parser.parseString(result.text, function (error, result) {
2019-10-23 10:02:04 -07:00
if (error) return callback(new BoxError(BoxError.EXTERNAL_ERROR, error));
var tmp = result.ApiResponse;
2019-09-23 20:00:49 +02:00
if (tmp['$'].Status !== 'OK') {
var errorMessage = safe.query(tmp, 'Errors[0].Error[0]._', 'Invalid response');
2019-10-23 10:02:04 -07:00
if (errorMessage === 'API Key is invalid or API access has not been enabled') return callback(new BoxError(BoxError.ACCESS_DENIED, errorMessage));
2019-09-23 20:00:49 +02:00
2019-10-23 10:02:04 -07:00
return callback(new BoxError(BoxError.EXTERNAL_ERROR, errorMessage));
2019-09-23 20:00:49 +02:00
}
const host = safe.query(tmp, 'CommandResponse[0].DomainDNSGetHostsResult[0].host');
if (!host) return callback(new BoxError(BoxError.EXTERNAL_ERROR, `Invalid response: ${JSON.stringify(tmp)}`));
if (!Array.isArray(host)) return callback(new BoxError(BoxError.EXTERNAL_ERROR, `host is not an array: ${JSON.stringify(tmp)}`));
const hosts = host.map(h => h['$']);
callback(null, hosts);
});
});
2019-01-16 18:05:42 +02:00
});
}
2021-04-13 15:10:24 -07:00
function setZone(dnsConfig, zoneName, hosts, callback) {
assert.strictEqual(typeof dnsConfig, 'object');
assert.strictEqual(typeof zoneName, 'string');
assert(Array.isArray(hosts));
assert.strictEqual(typeof callback, 'function');
getQuery(dnsConfig, function (error, query) {
if (error) return callback(error);
query.Command = 'namecheap.domains.dns.setHosts';
query.SLD = zoneName.split('.')[0];
query.TLD = zoneName.split('.')[1];
// Map to query params https://www.namecheap.com/support/api/methods/domains-dns/set-hosts.aspx
hosts.forEach(function (host, i) {
var n = i+1; // api starts with 1 not 0
query['TTL' + n] = '300'; // keep it low
query['HostName' + n] = host.HostName || host.Name;
query['RecordType' + n] = host.RecordType || host.Type;
query['Address' + n] = host.Address;
if (host.Type === 'MX') {
query['EmailType' + n] = 'MX';
if (host.MXPref) query['MXPref' + n] = host.MXPref;
}
});
2021-04-13 21:36:05 -07:00
// namecheap recommends sending as POSTDATA with > 10 records
const qs = querystring.stringify(query);
superagent.post(ENDPOINT).set('Content-Type', 'application/x-www-form-urlencoded').send(qs).end(function (error, result) {
2019-10-23 10:02:04 -07:00
if (error) return callback(new BoxError(BoxError.EXTERNAL_ERROR, error));
var parser = new xml2js.Parser();
parser.parseString(result.text, function (error, result) {
2019-10-23 10:02:04 -07:00
if (error) return callback(new BoxError(BoxError.EXTERNAL_ERROR, error));
var tmp = result.ApiResponse;
2019-09-23 20:00:49 +02:00
if (tmp['$'].Status !== 'OK') {
var errorMessage = safe.query(tmp, 'Errors[0].Error[0]._', 'Invalid response');
2019-10-23 10:02:04 -07:00
if (errorMessage === 'API Key is invalid or API access has not been enabled') return callback(new BoxError(BoxError.ACCESS_DENIED, errorMessage));
2019-09-23 20:00:49 +02:00
2019-10-23 10:02:04 -07:00
return callback(new BoxError(BoxError.EXTERNAL_ERROR, errorMessage));
2019-09-23 20:00:49 +02:00
}
2019-10-23 10:02:04 -07:00
if (!tmp.CommandResponse[0]) return callback(new BoxError(BoxError.EXTERNAL_ERROR, 'Invalid response'));
if (!tmp.CommandResponse[0].DomainDNSSetHostsResult[0]) return callback(new BoxError(BoxError.EXTERNAL_ERROR, 'Invalid response'));
if (tmp.CommandResponse[0].DomainDNSSetHostsResult[0]['$'].IsSuccess !== 'true') return callback(new BoxError(BoxError.EXTERNAL_ERROR, 'Invalid response'));
callback(null);
});
});
2019-01-16 18:05:42 +02:00
});
}
function upsert(domainObject, subdomain, type, values, callback) {
assert.strictEqual(typeof domainObject, 'object');
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof type, 'string');
2021-04-13 15:10:24 -07:00
assert(Array.isArray(values));
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof callback, 'function');
const dnsConfig = domainObject.config;
const zoneName = domainObject.zoneName;
subdomain = domains.getName(domainObject, subdomain, type) || '@';
2019-01-16 18:05:42 +02:00
debug('upsert: %s for zone %s of type %s with values %j', subdomain, zoneName, type, values);
2021-04-13 15:10:24 -07:00
getZone(dnsConfig, zoneName, function (error, result) {
if (error) return callback(error);
2019-01-16 18:05:42 +02:00
// Array to keep track of records that need to be inserted
let toInsert = [];
2021-04-13 15:10:24 -07:00
for (let i = 0; i < values.length; i++) {
2019-01-16 18:05:42 +02:00
let curValue = values[i];
let wasUpdate = false;
2021-04-13 15:10:24 -07:00
for (let j = 0; j < result.length; j++) {
2019-01-16 18:05:42 +02:00
let curHost = result[j];
if (curHost.Type === type && curHost.Name === subdomain) {
// Updating an already existing host
wasUpdate = true;
if (type === 'MX') {
2019-01-16 18:05:42 +02:00
curHost.MXPref = curValue.split(' ')[0];
curHost.Address = curValue.split(' ')[1];
} else {
curHost.Address = curValue;
}
}
}
// We don't have this host at all yet, let's push to toInsert array
if (!wasUpdate) {
let newRecord = {
RecordType: type,
HostName: subdomain,
Address: curValue
};
// Special case for MX records
if (type === 'MX') {
2019-01-16 18:05:42 +02:00
newRecord.MXPref = curValue.split(' ')[0];
newRecord.Address = curValue.split(' ')[1];
}
toInsert.push(newRecord);
}
}
2021-04-13 15:10:24 -07:00
const hosts = result.concat(toInsert);
2019-01-16 18:05:42 +02:00
2021-04-13 15:10:24 -07:00
setZone(dnsConfig, zoneName, hosts, callback);
2019-01-16 18:05:42 +02:00
});
}
function get(domainObject, subdomain, type, callback) {
assert.strictEqual(typeof domainObject, 'object');
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof type, 'string');
assert.strictEqual(typeof callback, 'function');
const dnsConfig = domainObject.config;
const zoneName = domainObject.zoneName;
subdomain = domains.getName(domainObject, subdomain, type) || '@';
2019-01-16 18:05:42 +02:00
2021-04-13 15:10:24 -07:00
getZone(dnsConfig, zoneName, function (error, result) {
2019-01-16 18:05:42 +02:00
if (error) return callback(error);
// We need to filter hosts to ones with this subdomain and type
2021-04-13 15:10:24 -07:00
const actualHosts = result.filter((host) => host.Type === type && host.Name === subdomain);
2019-01-16 18:05:42 +02:00
// We only return the value string
2021-04-13 15:10:24 -07:00
const tmp = actualHosts.map(function (record) { return record.Address; });
2019-01-16 18:05:42 +02:00
2021-04-13 15:10:24 -07:00
debug(`get: subdomain: ${subdomain} type:${type} value:${JSON.stringify(tmp)}`);
2019-01-16 18:05:42 +02:00
return callback(null, tmp);
});
}
function del(domainObject, subdomain, type, values, callback) {
assert.strictEqual(typeof domainObject, 'object');
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof type, 'string');
2021-04-13 15:10:24 -07:00
assert(Array.isArray(values));
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof callback, 'function');
const dnsConfig = domainObject.config;
const zoneName = domainObject.zoneName;
subdomain = domains.getName(domainObject, subdomain, type) || '@';
2019-01-16 18:05:42 +02:00
debug('del: %s for zone %s of type %s with values %j', subdomain, zoneName, type, values);
2021-04-13 15:10:24 -07:00
getZone(dnsConfig, zoneName, function (error, result) {
2019-01-16 18:05:42 +02:00
if (error) return callback(error);
if (result.length === 0) return callback();
2021-04-13 22:27:38 -07:00
const originalLength = result.length;
2019-01-16 18:05:42 +02:00
2021-04-13 22:27:38 -07:00
for (let i = 0; i < values.length; i++) {
2019-01-16 18:05:42 +02:00
let curValue = values[i];
2021-04-13 22:27:38 -07:00
result = result.filter(curHost => curHost.Type !== type || curHost.Name !== subdomain || curHost.Address !== curValue);
2019-01-16 18:05:42 +02:00
}
2021-04-13 22:27:38 -07:00
if (result.length !== originalLength) return setZone(dnsConfig, zoneName, result, callback);
callback();
2019-01-16 18:05:42 +02:00
});
}
function verifyDnsConfig(domainObject, callback) {
assert.strictEqual(typeof domainObject, 'object');
2019-01-16 18:05:42 +02:00
assert.strictEqual(typeof callback, 'function');
const dnsConfig = domainObject.config;
const zoneName = domainObject.zoneName;
const ip = '127.0.0.1';
2019-10-23 10:02:04 -07:00
if (!dnsConfig.username || typeof dnsConfig.username !== 'string') return callback(new BoxError(BoxError.BAD_FIELD, 'username must be a non-empty string', { field: 'username' }));
if (!dnsConfig.token || typeof dnsConfig.token !== 'string') return callback(new BoxError(BoxError.BAD_FIELD, 'token must be a non-empty string', { field: 'token' }));
2019-01-16 18:05:42 +02:00
2019-02-08 19:09:28 -08:00
let credentials = {
2019-01-16 18:05:42 +02:00
username: dnsConfig.username,
token: dnsConfig.token
2019-01-16 18:05:42 +02:00
};
2019-05-20 22:21:07 +02:00
if (process.env.BOX_ENV === 'test') return callback(null, credentials); // this shouldn't be here
2019-01-16 18:05:42 +02:00
dns.resolve(zoneName, 'NS', { timeout: 5000 }, function (error, nameservers) {
2019-10-23 10:02:04 -07:00
if (error && error.code === 'ENOTFOUND') return callback(new BoxError(BoxError.BAD_FIELD, 'Unable to resolve nameservers for this domain', { field: 'nameservers' }));
if (error || !nameservers) return callback(new BoxError(BoxError.BAD_FIELD, error ? error.message : 'Unable to get nameservers', { field: 'nameservers' }));
2019-01-16 18:05:42 +02:00
2019-01-22 11:56:56 +01:00
if (nameservers.some(function (n) { return n.toLowerCase().indexOf('.registrar-servers.com') === -1; })) {
2019-01-16 18:05:42 +02:00
debug('verifyDnsConfig: %j does not contains NC NS', nameservers);
2019-10-23 10:02:04 -07:00
return callback(new BoxError(BoxError.BAD_FIELD, 'Domain nameservers are not set to NameCheap', { field: 'nameservers' }));
2019-01-16 18:05:42 +02:00
}
const testSubdomain = 'cloudrontestdns';
upsert(domainObject, testSubdomain, 'A', [ip], function (error, changeId) {
2019-01-16 18:05:42 +02:00
if (error) return callback(error);
debug('verifyDnsConfig: Test A record added with change id %s', changeId);
del(domainObject, testSubdomain, 'A', [ip], function (error) {
2019-01-16 18:05:42 +02:00
if (error) return callback(error);
debug('verifyDnsConfig: Test A record removed again');
2019-02-08 19:09:28 -08:00
callback(null, credentials);
2019-01-16 18:05:42 +02:00
});
});
});
}
function wait(domainObject, subdomain, type, value, options, callback) {
assert.strictEqual(typeof domainObject, 'object');
assert.strictEqual(typeof subdomain, 'string');
assert.strictEqual(typeof type, 'string');
assert.strictEqual(typeof value, 'string');
assert(options && typeof options === 'object'); // { interval: 5000, times: 50000 }
assert.strictEqual(typeof callback, 'function');
const fqdn = domains.fqdn(subdomain, domainObject);
waitForDns(fqdn, domainObject.zoneName, type, value, options, callback);
}