-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathindex.js
53 lines (44 loc) · 1.43 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
'use strict';
const dns = require('dns');
const arrify = require('arrify');
const got = require('got');
const isPortReachable = require('is-port-reachable');
const pAny = require('p-any');
const pify = require('pify');
const pn = require('port-numbers');
const pTimeout = require('p-timeout');
const prependHttp = require('prepend-http');
const routerIps = require('router-ips');
const URL = require('url-parse');
const checkRedirection = url => {
return got(url).then(res => {
return !routerIps.has((new URL(res.headers.location || '')).hostname);
}).catch(() => false);
};
function isTargetReachable(url) {
const uri = new URL(prependHttp(url));
const hostname = uri.hostname;
let protocol = uri.protocol;
const port = Number(uri.port) || pn.getPort(protocol.slice(0, -1)).port || 80;
if (!/^[a-z]+:\/\//.test(url) && port !== 80 && port !== 443) {
protocol = pn.getService(port).name + ':';
}
return pify(dns.lookup)(hostname).then(address => {
if (!address) {
return false;
}
if (routerIps.has(address)) {
return false;
}
if (protocol === 'http:' || protocol === 'https:') {
return checkRedirection(url);
}
return isPortReachable(port, {host: address});
}).catch(() => false);
}
module.exports = (dests, opts) => {
opts = opts || {};
opts.timeout = typeof opts.timeout === 'number' ? opts.timeout : 5000;
const p = pAny(arrify(dests).map(isTargetReachable));
return pTimeout(p, opts.timeout).catch(() => false);
};