-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
68 lines (51 loc) · 1.7 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
'use strict'
const Assert = require('assert')
const Dns = require('dns')
const Http = require('http')
const Https = require('https')
const IPRangeCheck = require('ip-range-check')
const lookup = function (settings) {
Assert(settings.type === 'whitelist' || settings.type === 'blacklist', 'type must be whitelist or blacklist')
const filter = function (hostname, options, callback) {
if (arguments.length === 2) {
callback = options
options = {}
}
Dns.lookup(hostname, options, (err, address, family) => {
if (err) {
callback(err)
return
}
const ipTest = IPRangeCheck(address, settings.iplist)
if (ipTest && settings.type === 'whitelist') { // IP on whitelist, pass
callback(err, address, family)
return
}
if (!ipTest && settings.type === 'blacklist') { // IP not on blacklist, pass
callback(err, address, family)
return
}
// Fail
callback(new Error(`Connection to IP ${address} not allowed`))
})
}
return filter
}
exports.http = function (settings) {
const httpAgent = new Http.Agent(settings.agent)
httpAgent._oldCreateConnection_ = httpAgent.createConnection
httpAgent.createConnection = function (options, ...args) {
options.lookup = lookup(settings)
return this._oldCreateConnection_(options, ...args)
}
return httpAgent
}
exports.https = function (settings) {
const httpsAgent = new Https.Agent(settings.agent)
httpsAgent._oldCreateConnection_ = httpsAgent.createConnection
httpsAgent.createConnection = function (options, ...args) {
options.lookup = lookup(settings)
return this._oldCreateConnection_(options, ...args)
}
return httpsAgent
}