-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
258 lines (236 loc) · 7.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
'use strict';
const dns = require('node:dns');
const { promisify } = require('node:util');
const resolveTxtPromise = promisify(dns.resolveTxt);
const cloudflare = require('cloudflare');
function formatCloudflareError(err) {
if (!err.response || !err.response.body) {
return err;
}
// maintain Cloudflare API errors, not just a generic HTTPError from `got`
const newErr = err;
newErr.cloudflare_errors = err.response.body.errors;
return newErr;
}
/* Thanks to https://github.com/buschtoens/le-challenge-cloudflare for this great pagination implementation */
async function *consumePages(loader, pageSize = 10) {
for (let page = 1, didReadAll = false; !didReadAll; page++) {
let response;
try {
response = await loader({
per_page: pageSize,
page,
});
} catch (err) {
// try to pass-through human-friendly Cloudflare API errors
throw formatCloudflareError(err);
}
if (response.success) {
yield* response.result;
} else {
const error = new Error('Cloudflare API error.');
error.response = response;
throw formatCloudflareError(error);
}
didReadAll = page >= response.result_info.total_pages;
}
}
async function resolveTxt(fqdn) {
const records = await resolveTxtPromise(fqdn);
return records.map(record => record.join(' '));
}
function delay(ms) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});
}
class Challenge {
constructor(options = {}) {
this.module = 'acme-dns-01-cloudflare';
this.options = options;
this.cfClient = new cloudflare({
email: options.client && options.client.email || options.email,
key: options.client && options.client.key || options.key,
token: options.client && options.client.token || options.token,
});
this.client = {
email: options.client && options.client.email || options.email,
key: options.client && options.client.key || options.key,
token: options.client && options.client.token || options.token,
};
this.propagationDelay = options.propagationDelay || 15000; // set propagationDelay for ACME.js
if (this.options.verifyPropagation) {
// if our own propagation is set, like is required for greenlock.js at time of writing, disable use native ACME.js propagation delay to prevent double verification
this.propagationDelay = 0;
}
}
static create(config) {
return new Challenge(Object.assign(config, this.options));
}
async init() {
return null;
}
async set(args) {
if (!args.challenge) {
throw new Error('You must be using Greenlock v2.7+ to use acme-dns-01-cloudflare');
}
try {
const fullRecordName = args.challenge.dnsPrefix + '.' + args.challenge.dnsZone;
const zone = await this.getZoneForDomain(args.challenge.dnsZone);
if (!zone) {
throw new Error(`Could not find a zone for '${fullRecordName}'.`);
}
// add record
await this.cfClient.dnsRecords.add(zone.id, {
type: 'TXT',
name: fullRecordName,
content: args.challenge.dnsAuthorization,
ttl: 120,
});
// verify propagation
if (this.options.verifyPropagation) {
// wait for one "tick" before attempting to query. This can help prevent the DNS cache from getting polluted with a bad value
await delay(this.options.waitFor || 10000);
await Challenge.verifyPropagation(args.challenge, this.options.verbose, this.options.waitFor, this.options.retries);
}
return null;
} catch (err) {
if (err instanceof Error) {
throw formatCloudflareError(err);
}
throw new Error(err);
}
}
async remove(args) {
if (!args.challenge) {
throw new Error('You must be using Greenlock v2.7+ to use acme-dns-01-cloudflare');
}
try {
const fullRecordName = args.challenge.dnsPrefix + '.' + args.challenge.dnsZone;
const zone = await this.getZoneForDomain(args.challenge.dnsZone);
if (!zone) {
throw new Error(`Could not find a zone for '${fullRecordName}'.`);
}
const records = await this.getTxtRecords(zone, fullRecordName);
if (records.length === 0) {
throw new Error(`No TXT records found for ${fullRecordName}`);
}
for (const record of records) {
if (record.name === fullRecordName && record.content === args.challenge.dnsAuthorization) {
await this.cfClient.dnsRecords.del(zone.id, record.id);
}
}
if (this.options.verifyPropagation) {
// wait for one "tick" before attempting to query. This can help prevent the DNS cache from getting polluted with a bad value
await delay(this.options.waitFor || 10000);
// allow time for deletion to propagate
await Challenge.verifyPropagation(Object.assign({}, args.challenge, { removed: true }), this.options.verbose);
}
return null;
} catch (err) {
if (err instanceof Error) {
throw formatCloudflareError(err);
}
throw new Error(err);
}
}
/* implemented for testing purposes */
async get(args) {
if (!args.challenge) {
throw new Error('You must be using Greenlock v2.7+ to use acme-dns-01-cloudflare');
}
try {
const fullRecordName = args.challenge.dnsPrefix + '.' + args.challenge.dnsZone;
const zone = await this.getZoneForDomain(fullRecordName);
if (!zone) {
throw new Error(`Could not find a zone for '${fullRecordName}'.`);
}
const records = await this.getTxtRecords(zone, fullRecordName);
if (records.length === 0) {
return null;
}
// find the applicable record if multiple
let foundRecord = null;
for (const record of records) {
if (record.name === fullRecordName && record.content === args.challenge.dnsAuthorization) {
foundRecord = record;
}
}
if (!foundRecord) {
return null;
}
return {
dnsAuthorization: foundRecord.content,
};
} catch {
// could not get record
return null;
}
}
async zones(args) { // eslint-disable-line no-unused-vars
try {
const zones = [];
for await (const zone of consumePages(pagination => this.cfClient.zones.browse(pagination))) {
zones.push(zone.name);
}
return zones;
} catch (err) {
if (err instanceof Error) {
throw formatCloudflareError(err);
}
throw new Error(err);
}
}
static async verifyPropagation(challenge, verbose = false, waitFor = 10000, retries = 30) {
const fullRecordName = challenge.dnsPrefix + '.' + challenge.dnsZone;
for (let i = 0; i < retries; i++) {
try {
const records = await resolveTxt(fullRecordName);
const verifyCheck = challenge.dnsAuthorization;
if (challenge.removed === true && records.includes(verifyCheck)) {
throw new Error(`DNS record deletion not yet propagated for ${fullRecordName}`);
}
if (!records.includes(verifyCheck)) {
if (challenge.removed === true) {
return;
}
throw new Error(`Could not verify DNS for ${fullRecordName}`);
}
return;
} catch (err) {
if (err.code === 'ENODATA' && challenge.removed === true) {
return;
}
if (verbose) {
console.log(`DNS not propagated yet for ${fullRecordName}. Checking again in ${waitFor}ms. (Attempt ${i + 1} / ${retries})`);
}
await delay(waitFor);
}
}
throw new Error(`Could not verify challenge for '${fullRecordName}'.`);
}
async getZoneForDomain(domain) {
for await (const zone of consumePages(pagination => this.cfClient.zones.browse(pagination))) {
if (domain === zone.name || domain.endsWith(`.${zone.name}`)) {
return zone;
}
}
return null;
}
async getTxtRecords(zone, name) {
const records = [];
for await (const txtRecord of consumePages(pagination => this.cfClient.dnsRecords.browse(zone.id, {
...pagination,
type: 'TXT',
name,
}))) {
if (txtRecord.name === name) {
records.push(txtRecord);
}
}
return records;
}
}
module.exports = Challenge;