-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
740 lines (664 loc) · 18.9 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/** @format */
"use strict";
const _ = require("lodash");
const CACHE = require("./Cache").default;
const DEFAULT_SERVERS = require("./DefaultServers").default;
const fetch = require("cross-fetch");
const makeDebug = require("debug");
const lookupRrtype = require("./Rrtypes").default;
const {
name: packageName,
version: packageVersion,
} = require("./package.json");
module.exports = {};
_.merge(module.exports, require("./Constants"));
/* eslint-disable no-magic-numbers */
const DEFAULT_TTL_SECONDS = 3600;
const IP_FAMILY_4 = 4;
const IP_FAMILY_6 = 6;
const IP_FAMILY_ANY = 0;
/* eslint-enable no-magic-numbers */
// DEBUG configuration
const log = makeDebug("fetch-dns");
const debug = log.extend("debug");
const error = log.extend("error");
if (debug.enabled) log.enabled = true;
if (log.enabled) error.enabled = true;
// Retrieve the methods for an object
function getMethods(obj) {
const properties = new Set();
let currentObj = obj;
do {
Object.getOwnPropertyNames(currentObj).forEach((item) =>
properties.add(item),
);
} while ((currentObj = Object.getPrototypeOf(currentObj)));
return [...properties.keys()].filter((item) => _.isFunction(obj[item]));
}
// Promote the methods of an object onto a target.
function promoteMethods(object, target) {
getMethods(object).forEach((funcName) => {
target[funcName] = _.bind(object[funcName], object);
});
}
function forceMatch(input, regex) {
return _.trim(input).match(regex) || [];
}
function isFamily(it) {
return (
_.isFinite(it) &&
(it === IP_FAMILY_4 || it === IP_FAMILY_6 || it === IP_FAMILY_ANY)
);
}
function isLookupOptions(it) {
if (_.isNil(it)) return false;
return (
(!("family" in it) || isFamily(it.family)) &&
(!("hints" in it) || _.isNumber(it.hints) || _.isNil(it.hints)) &&
(!("all" in it) || _.isBoolean(it.all) || _.isNil(it.all)) &&
(!("verbatim" in it) || _.isBoolean(it.verbatim) || _.isNil(it.verbatim))
);
}
function splitNaptr(str) {
// TODO Add validation
const [, order = 0, preference = 0, afterNumbers = ""] = forceMatch(
str,
/^(\d+)\s*(\d+)\s*(.*)$/,
);
const maybeQuotedStrRE = /("(?:\\\\"|[^"])*"|'(?:\\\\'|[^'])*'|[^\s]+)\s*(.*)$/;
const [, flags = "", afterFlags = ""] = forceMatch(
afterNumbers,
maybeQuotedStrRE,
);
const [, service = "", afterService = ""] = forceMatch(
afterFlags,
maybeQuotedStrRE,
);
const [, regexp = "", afterRegexp = ""] = forceMatch(
afterService,
maybeQuotedStrRE,
);
const [, replacement = ""] = forceMatch(afterRegexp, maybeQuotedStrRE);
const record = {
order: _.toFinite(order),
preference: _.toFinite(preference),
flags,
service,
regexp,
replacement,
};
debug("Parsed a NAPTR record's data", { data: str, record });
return record;
}
function isLookupAllOptions(it) {
return isLookupOptions(it) && it.all === true; // Yes, the "=== true" matters here for typing
}
function isLookupOneOptions(it) {
return isLookupOptions(it) && !it.all;
}
function toLookupAddress(family, hostname) {
return (address) => {
if (_.isEmpty(address)) {
throw new Error(`No IPv${family} address found for ${hostname}`);
}
return { address, family };
};
}
function isResolveOptions(it) {
if (_.isEmpty(it)) return false;
return "ttl" in it && _.isBoolean(it.ttl);
}
function isResolveWithTtlOptions(it) {
return isResolveOptions(it) && it.ttl === true;
}
class NotImplementedError extends Error {
constructor(methodName) {
super(
`'${methodName}' is not implemented in ${packageName} ${packageVersion}`,
);
this.methodName = methodName;
this.name = "NotImplementedError";
}
}
/* eslint-disable promise/no-callback-in-promise */
function callbackPromise1(promise, callback) {
const cb = _.once(callback);
Promise.resolve(promise)
.tap((result) => {
cb(null, result);
})
.catch((e) => {
cb(e);
});
}
function callbackPromise2(promise, callback) {
const cb = _.once(callback);
Promise.resolve(promise)
.tap(([t, u]) => {
cb(null, t, u);
})
.catch((e) => {
cb(e);
});
}
function lookupCallback(promise, callback) {
callbackPromise2(
promise.then(({ address, family }) => [address, family]),
callback,
);
}
/* eslint-enable promise/no-callback-in-promise */
module.exports.getDefaultServers = () => {
return _.cloneDeep(DEFAULT_SERVERS);
};
const promises = (module.exports.promises = {});
promises.Resolver = class PromiseResolver {
constructor(servers = DEFAULT_SERVERS) {
this.setServers(servers); // Ensures we don't accept empty servers
}
// The actual fetch-based DNS lookup implementations: everything is derived from here!
_doResolve(hostname, rrtype, mapper) {
const cachedResult = CACHE.check(hostname, rrtype);
if (!_.isEmpty(cachedResult)) {
debug("Retrieved cached result", { hostname, rrtype, cachedResult });
return Promise.resolve(cachedResult);
}
const server = this._pickServer();
const url = `${server}?name=${hostname}&type=${
rrtype === "ANY" ? "*" : _.toUpper(rrtype)
}`;
return Promise.resolve(
fetch(url, {
method: "GET",
headers: { Accept: "application/dns-json" },
mode: "no-cors",
keepalive: true,
}),
)
.then(async (res) => {
if (!res.ok) {
log("Result of fetching DNS record over HTTPS was not 'OK'", {
status: `${res.status} ${res.statusText}`,
hostname,
rrtype,
server,
requestUrl: url,
resultUrl: res.url,
});
return [];
}
const body = await res.json();
debug("Retrieved result", body);
const results = await Promise.map(
_.get(body, "Answer", []),
async (ans) => {
const ttl = _.isFinite(ans.TTL) ? ans.TTL : DEFAULT_TTL_SECONDS;
const result = await mapper({ ...ans, rrtype, ttl });
return { result, ttl };
},
);
CACHE.put(hostname, rrtype, results);
const toReturn = _.reject(_.map(results, "result"), _.isEmpty);
debug("Result of fetching DNS", hostname, rrtype, toReturn);
return toReturn;
})
.then(_.compact)
.tap((result) => {
if (_.isEmpty(result)) {
debug("Returning an empty result for a resolve", {
hostname,
rrtype,
result,
});
}
});
}
// A common, simple case.
_doResolveSimple(hostname, rrtype) {
const toReturn = this._doResolve(hostname, rrtype, ({ data }) => data);
if (_.isEmpty(toReturn)) {
debug("Returning an empty result for a simple resolve", {
hostname,
rrtype,
result: toReturn,
});
}
return toReturn;
}
getServers() {
const servers = this._servers;
debug("Retrieving servers", servers);
if (!servers || _.isEmpty(servers)) {
throw new Error("No servers found");
} else {
return _.cloneDeep(servers);
}
}
setServers(servers) {
if (_.isEmpty(servers)) {
throw new Error("Refusing to set empty servers for DNS");
}
log("Setting servers", servers);
this._servers = _.cloneDeep(servers);
}
_pickServer() {
const toReturn = _.sample(this.getServers());
if (_.isNil(toReturn)) {
throw new Error(`No server picked: ${JSON.stringify(this.servers)}`);
} else {
return toReturn;
}
}
lookup(hostname, familyOrOptions) {
if (_.isNil(familyOrOptions)) {
return this._lookupHostname(hostname);
} else if (isFamily(familyOrOptions)) {
return this._lookupHostnameFamily(hostname, familyOrOptions);
} else {
return this._lookupHostnameOptions(hostname, familyOrOptions);
}
}
_lookupHostname(hostname) {
return this._lookupHostnameFamily(hostname, 0);
}
_lookupHostnameFamily(hostname, family) {
if (family === IP_FAMILY_4) {
return this._lookup4(hostname);
} else if (family === IP_FAMILY_6) {
return this._lookup6(hostname);
} else {
return Promise.any([this._lookup4(hostname), this._lookup6(hostname)]);
}
}
_lookup4(hostname) {
return this.resolve4(hostname)
.then((result) => {
debug("Retrieved hostname via lookup4", hostname, result);
if (_.isArray(result)) {
return _.head(result);
} else {
return result;
}
})
.then((result) => {
if (_.isNil(result)) {
throw new Error(
`No result found when querying for 'A' record of '${hostname}'`,
);
} else {
return result;
}
})
.then(toLookupAddress(IP_FAMILY_4, hostname));
}
_lookup6(hostname) {
const mkLA = toLookupAddress(IP_FAMILY_6, hostname);
return this.resolve6(hostname)
.then((result) => {
if (_.isArray(result)) {
return _.sample(result);
} else {
return result;
}
})
.then((result) => {
if (_.isNil(result)) {
throw new Error(
`No result found when querying for 'AAAA' record of '${hostname}'`,
);
} else {
return result;
}
})
.then(mkLA);
}
_lookupHostnameOptions(hostname, options) {
// The 'verbatim' flag doesn't actually do anything because of the implementation.
// The 'hint' flag isn't supported by DoH.
const optionsFamily = _.get(options, "family", IP_FAMILY_4);
if (!isFamily(optionsFamily)) {
throw new Error(
`Could not determine desired address family (4, 6, or 0) from options: ${JSON.stringify(
options,
)}`,
);
}
if (_.isNil(options.all) || !options.all) {
return this._lookupHostnameFamily(hostname, optionsFamily);
} else {
const toLookupAddress4 = toLookupAddress(IP_FAMILY_4, hostname);
const toLookupAddress6 = toLookupAddress(IP_FAMILY_6, hostname);
if (optionsFamily === IP_FAMILY_4) {
return this.resolve4(hostname).map(toLookupAddress4);
} else if (optionsFamily === IP_FAMILY_6) {
return this.resolve6(hostname).map(toLookupAddress6);
} else if (optionsFamily === IP_FAMILY_ANY) {
return Promise.join(
this.resolve4(hostname).map(toLookupAddress4),
this.resolve6(hostname).map(toLookupAddress6),
)
.then(_.concat)
.then(_.flatten);
}
}
throw new Error(
`Unreachable code reached in '_lookupHostnameOptions(${JSON.stringify(
hostname,
)},${JSON.stringify(options)})'`,
);
}
lookupService(/*address, port*/) {
// TODO Find/create a web service exposing `getnameinfo` over HTTP
return new NotImplementedError("lookupService");
}
async resolve(hostname, rrtype) {
if (_.isEmpty(rrtype)) {
return this.resolve4(hostname);
} else {
const methodRrType = _.upperFirst(_.toLower(rrtype));
if (methodRrType === "A") {
return this.resolve4(hostname);
} else if (methodRrType === "Aaaa") {
return this.resolve6(hostname);
} else {
const f = this[`resolve${methodRrType}`];
if (_.isFunction(f)) {
return f.call(this, hostname);
} else {
throw new NotImplementedError(
`resolve(...,${JSON.stringify(rrtype)})`,
);
}
}
}
}
resolve4(hostname, options) {
const ttl = !!_.get(options, "ttl", false);
if (ttl) {
return this._doResolve(hostname, "A", (res) => ({
address: res.data,
ttl: res.ttl,
}));
} else {
return this._doResolveSimple(hostname, "A");
}
}
resolve6(hostname, options) {
const ttl = !!_.get(options, "ttl", false);
if (ttl) {
return this._doResolve(hostname, "AAAA", (res) => ({
address: res.data,
ttl: res.ttl,
}));
} else {
return this._doResolveSimple(hostname, "AAAA");
}
}
resolveAny(hostname) {
const results = this._doResolve(hostname, "*", (initialResponse) => {
if(!_.isFunction(lookupRrtype)) {
error(`lookupRrtype is not a function, but '${typeof lookupRrtype}': ${JSON.stringify(lookupRrtype)}`);
return [];
}
const rrtype = lookupRrtype(initialResponse.type);
return Promise.resolve(this.resolve(hostname, rrtype))
.catch(NotImplementedError, () => {
debug("Skipping lookup for unsupported rrtype", { rrtype, hostname });
return [];
})
.map((res) => {
if (_.isEmpty(res)) {
log("Saw an empty response", { hostname, rrtype, res });
return null;
} else if (_.isString(res)) {
return { value: res, type: rrtype };
} else {
return { ...res, type: rrtype };
}
});
});
return _.compact(_.flatten(results));
}
resolveCname(hostname) {
return this._doResolveSimple(hostname, "CNAME");
}
resolveMx(hostname) {
return this._doResolve(hostname, "MX", ({ data }) => {
const [priority, exchange] = _.split(_.trim(data), /\s+/, 2);
if (_.isEmpty(priority) || _.isEmpty(exchange)) {
log(
"Discovered an MX record with empty priority or exchange",
{ hostname },
data,
);
return [];
} else {
return { priority: _.toFinite(priority), exchange };
}
}).then(_.flatten);
}
resolveNaptr(hostname) {
return this._doResolve(hostname, "NAPTR", ({ data }) => splitNaptr(data));
}
resolveNs(hostname) {
return this._doResolveSimple(hostname, "NS");
}
resolvePtr(hostname) {
return this._doResolveSimple(hostname, "PTR");
}
resolveSoa(hostname) {
return this._doResolve(hostname, "SOA", (ans) => {
const { data } = ans;
const [
nsname,
hostmaster,
serial,
refresh,
retry,
expire,
minttl,
] = _.split(_.trim(data), /\s+/);
return {
...ans,
nsname,
hostmaster,
serial: _.toFinite(serial),
refresh: _.toFinite(refresh),
retry: _.toFinite(retry),
expire: _.toFinite(expire),
minttl: _.toFinite(minttl),
};
})
.then(_.head)
.then((result) => {
if (_.isNil(result)) {
throw new Error(
`No SOA record was able to be found for '${hostname}'`,
);
} else {
return result;
}
});
}
resolveTxt(hostname) {
return this._doResolve(hostname, "TXT", ({ data }) => [data]);
}
resolveSrv(hostname) {
return this._doResolve(hostname, "SRV", (ans) => {
const { data } = ans;
const [, , , , , priority, weight, port, name] = _.split(
_.trim(data),
/s+/,
);
return {
...ans,
priority: _.toFinite(priority),
weight: _.toFinite(weight),
port: _.toFinite(port),
name: name,
};
});
}
async reverse(ip) {
// TODO Find/create a web service that exposes reverse DNS lookups
throw new NotImplementedError("reverse");
}
};
const PROMISE_RESOLVER = new promises.Resolver(DEFAULT_SERVERS);
promoteMethods(PROMISE_RESOLVER, promises);
const Resolver = (module.exports.Resolver = class Resolver {
constructor(resolver = new promises.Resolver(DEFAULT_SERVERS)) {
this.resolver = resolver;
}
getServers() {
return this.resolver.getServers();
}
setServers(newServers) {
this.resolver.setServers(newServers);
}
lookup(hostname, familyOptionsOrCallback, callback) {
if (_.isFunction(familyOptionsOrCallback)) {
this._lookupHostname(hostname, familyOptionsOrCallback);
} else if (isFamily(familyOptionsOrCallback)) {
this._lookupFamily(hostname, familyOptionsOrCallback, callback);
} else if (isLookupAllOptions(familyOptionsOrCallback)) {
this._lookupAll(hostname, familyOptionsOrCallback, callback);
} else if (isLookupOneOptions(familyOptionsOrCallback)) {
this._lookupOne(hostname, familyOptionsOrCallback, callback);
} else {
throw new Error(
`Unknown lookup type based on args: ${JSON.stringify({
hostname,
familyOptionsOrCallback,
callback,
})}`,
);
}
}
_lookupHostname(hostname, callback) {
lookupCallback(this.resolver.lookup(hostname), callback);
}
_lookupFamily(hostname, family, callback) {
lookupCallback(this.resolver.lookup(hostname, family), callback);
}
_lookupAll(hostname, options, callback) {
callbackPromise1(this.resolver.lookup(hostname, options), callback);
}
_lookupOne(hostname, options, callback) {
lookupCallback(this.resolver.lookup(hostname, options), callback);
}
lookupService(address, port, callback) {
callbackPromise1(
this.resolver.lookupService(address, port),
(e, params) => {
if (_.isNil(e)) {
if (_.isNil(params)) {
throw new Error(`No parameters nor error provided to the callback`);
} else {
const { hostname, service } = params;
callback(null, hostname, service);
}
} else if (_.isError(e)) {
callback(e);
} else {
throw new Error(
`First argument is neither nil nor an error: ${e} (${typeof e})`,
);
}
},
);
}
resolve(hostname, rrtypeOrCallback, callback) {
if (_.isFunction(rrtypeOrCallback)) {
callbackPromise1(this.resolver.resolve(hostname), rrtypeOrCallback);
} else {
const rrtype = _.upperFirst(_.toLower(rrtypeOrCallback));
if (rrtype === "A") {
this.resolve4(hostname, callback);
} else if (rrtype === "Aaaa") {
this.resolve6(hostname, callback);
} else {
const f = this[`resolve${rrtype}`];
if (_.isFunction(f)) {
f.call(this, hostname, callback);
} else {
callback(
new NotImplementedError(
`resolve(...,${JSON.stringify(rrtypeOrCallback)})`,
),
);
}
}
}
}
resolve4(hostname, optionsOrCallback, callback) {
if (_.isFunction(optionsOrCallback)) {
this._resolve4Hostname(hostname, optionsOrCallback);
} else if (isResolveWithTtlOptions(optionsOrCallback)) {
this._resolve4Ttl(hostname, callback);
} else {
const cb = (err, recordsWithTtl) =>
callback(err, recordsWithTtl && _.map(recordsWithTtl, "address"));
this._resolve4Ttl(hostname, cb);
}
}
_resolve4Hostname(hostname, callback) {
callbackPromise1(this.resolver.resolve4(hostname), callback);
}
_resolve4Ttl(hostname, callback) {
callbackPromise1(this.resolver.resolve4(hostname, { ttl: true }), callback);
}
resolve6(hostname, optionsOrCallback, callback) {
if (_.isFunction(optionsOrCallback)) {
this._resolve6Hostname(hostname, optionsOrCallback);
} else if (isResolveWithTtlOptions(optionsOrCallback)) {
this._resolve6Ttl(hostname, callback);
} else {
const cb = (err, recordsWithTtl) =>
callback(err, recordsWithTtl && _.map(recordsWithTtl, "address"));
this._resolve6Ttl(hostname, cb);
}
}
_resolve6Hostname(hostname, callback) {
callbackPromise1(this.resolver.resolve6(hostname), callback);
}
_resolve6Ttl(hostname, callback) {
callbackPromise1(this.resolver.resolve6(hostname, { ttl: true }), callback);
}
resolveAny(hostname, callback) {
callbackPromise1(this.resolver.resolveAny(hostname), callback);
}
resolveCname(hostname, callback) {
callbackPromise1(this.resolver.resolveCname(hostname), callback);
}
resolveMx(hostname, callback) {
callbackPromise1(this.resolver.resolveMx(hostname), callback);
}
resolveNaptr(hostname, callback) {
callbackPromise1(this.resolver.resolveNaptr(hostname), callback);
}
resolveNs(hostname, callback) {
callbackPromise1(this.resolver.resolveNs(hostname), callback);
}
resolvePtr(hostname, callback) {
callbackPromise1(this.resolver.resolvePtr(hostname), callback);
}
resolveSoa(hostname, callback) {
callbackPromise1(this.resolver.resolveSoa(hostname), callback);
}
resolveSrv(hostname, callback) {
callbackPromise1(this.resolver.resolveSrv(hostname), callback);
}
resolveTxt(hostname, callback) {
callbackPromise1(this.resolver.resolveTxt(hostname), callback);
}
reverse(ip, callback) {
callbackPromise1(this.resolver.reverse(ip), callback);
}
cancel() {
this.resolver.cancel().catch((e) => log("Error while cancelling", e));
}
});
const CB_RESOLVER = new Resolver(PROMISE_RESOLVER);
promoteMethods(CB_RESOLVER, module.exports);
debug("export", module.exports);