-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (48 loc) · 1.38 KB
/
index.js
File metadata and controls
53 lines (48 loc) · 1.38 KB
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
const http = require('http');
const https = require('https');
const ipaddr = require('ipaddr.js');
const checkIp = (ip) => {
if (!ipaddr.isValid(ip)) {
return true;
}
try {
const addr = ipaddr.parse(ip);
const range = addr.range();
if (range !== 'unicast') {
return false; // Private IP Range
}
} catch (err) {
return false;
}
return true;
};
// prevent memory leak
const ACTIVE = Symbol('active');
const requestFilterHandler = (agent)=>{
if (agent[ACTIVE]) return agent;
agent[ACTIVE] = true;
const {createConnection} = agent;
agent.createConnection = function(options, func) {
const {host: address} = options;
if (!checkIp(address)) {
throw new Error(`Call to ${address} is blocked.`);
}
const socket = createConnection.call(this, options, func);
socket.on('lookup', (error, address) => {
if (error || checkIp(address)) {
return false;
}
return socket.destroy(new Error(`Call to ${address} is blocked.`));
});
return socket;
};
return agent;
};
const manageConnection = (url) => {
const httpAgent = new http.Agent();
const httpsAgent = new https.Agent();
const agent = url.startsWith('https') ? httpsAgent : httpAgent;
return requestFilterHandler(agent);
};
module.exports = (url) => manageConnection(url);
module.exports.requestFilterHandler = (agent) => requestFilterHandler(agent);