-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (65 loc) · 2.05 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
import dns from 'dns/promises';
let globalDebug = false;
const dnsCache = new Map();
const domainIndex = new Map();
async function getIPs(domain) {
try {
if (!dnsCache.has(domain)) {
const entries = await dns.lookup(domain, {all: true});
const addresses = [];
for (const entry of entries) {
addresses.push(entry.address);
}
if (globalDebug)
console.log(`DNS [MISS]: ${domain} -> `, addresses);
dnsCache.set(domain, addresses);
return addresses;
} else {
if (globalDebug)
console.log(`DNS [HIT]: ${domain} -> `, dnsCache.get(domain));
return dnsCache.get(domain);
}
} catch (error) {
if (globalDebug)
console.log(`DNS [FAIL]: ${domain} -> `, error);
return [];
}
}
async function getIP(domain) {
const ips = await getIPs(domain);
if (! ips.length) {
return null;
}
const index = domainIndex.get(domain) || 0;
domainIndex.set(domain, (index+1) % ips.length);
const ip = ips[index];
if (globalDebug) {
console.log(`DNS ${domain} -> ${ip} using index=${index}`);
}
return ip;
}
export default function (axiosInstance, debug=false) {
globalDebug = debug;
axiosInstance.interceptors.request.use(async config => {
// Extract the hostname from the URL
const url = new URL(config.url);
const domain = url.hostname;
// Get rotated IP
const ip = await getIP(domain);
if (! ip) {
return config;
}
// Update the URL in the config to use the selected IP
url.hostname = ip;
config.url = url.toString();
if (globalDebug) {
console.log(`DNS URL ${domain} => ${config.url}`);
}
// Set the Host header to the original domain
config.headers = config.headers || {};
config.headers.Host = domain;
return config;
}, error => {
return Promise.reject(error);
});
}