acme-dns-01-dnsimple.js/lib/index.js

141 lines
3.1 KiB
JavaScript

'use strict';
var request;
var defaults = {
baseUrl: 'https://api.dnsimple.com/v2/'
};
module.exports.create = function(config) {
var baseUrl = (config.baseUrl || defaults.baseUrl).replace(/\/$/, '');
var token = config.token;
var account = config.account;
function api(method, path, form) {
var req = {
method: method,
url: baseUrl + path,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
json: true,
form: form
};
return request(req).then(function(resp) {
if (2 !== Math.floor(resp.statusCode / 100)) {
console.error(resp.statusCode, req.url);
console.error();
console.error('Request:');
console.error(req);
console.error();
console.error('Response:');
console.error(resp.body);
console.error();
throw new Error(
'Error response. Check token, baseUrl, domains, etc.'
);
}
return resp;
});
}
return {
init: function(opts) {
request = opts.request;
return null;
},
zones: function(data) {
// console.info('List Zones', data);
return api('GET', '/' + account + '/zones').then(function(resp) {
return resp['body']['data'].map(function(elem) {
//console.log('DEBUG >>> elem.name: ' + elem.name);
return elem.name;
});
});
},
set: function(data) {
// console.info('Add TXT', data);
var ch = data.challenge;
if (!ch.dnsZone) {
throw new Error('No matching zone for ' + ch.dnsHost);
}
var txt = ch.dnsAuthorization;
return api(
'POST',
'/' + account + '/zones/' + ch.dnsZone + '/records',
{
name: ch.dnsPrefix,
type: 'TXT',
content: txt
}
).then(function(resp) {
if (resp.statusCode === 201) {
return true;
}
throw new Error(
'record did not set. check subdomain, api key, etc'
);
});
},
get: function(data) {
// console.info('List TXT', data);
var ch = data.challenge;
// TODO use :name_like
// https://developer.dnsimple.com/v2/zones/records/
return api(
'GET',
'/' + account + '/zones/' + data.challenge.dnsZone + '/records'
).then(function(resp) {
var record = resp.body.data.filter(function(record) {
return (
ch.dnsPrefix === record.name &&
ch.dnsAuthorization === record.content
);
})[0];
if (record) {
return { dnsAuthorization: record.content };
}
return null;
});
},
remove: function(data) {
// console.info('Remove TXT', data);
var ch = data.challenge;
return api(
'GET',
'/' + account + '/zones/' + data.challenge.dnsZone + '/records'
).then(function(resp) {
var record = resp.body.data.filter(function(record) {
return (
ch.dnsPrefix === record.name &&
ch.dnsAuthorization === record.content
);
})[0];
if (!record) {
throw new Error('Txt Record not found for removal');
}
return api(
'DELETE',
'/' +
account +
'/zones/' +
ch.dnsZone +
'/records/' +
record.id
).then(function(resp) {
// console.info('DEBUG >>> resp: ', JSON.stringify(resp, null, 2));
return true;
});
});
}
};
};