-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
203 lines (167 loc) · 5.55 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
// index.js
// Dependencies
const ObjectKeyCache = require('@outofsync/object-key-cache');
const isNil = require('lodash.isnil');
const merge = require('lodash.merge');
const LogStub = require('logstub');
function defaultBlacklistFn(_req, res) {
// Send an empty 403 response to blacklisted ips
res.status(403);
res.send(null);
}
class IPBlacklist {
constructor(namespace, config, cache, log) {
const defaults = {
lookup: [],
count: 250,
// 250 request
expire: 1000 * 60 * 60,
// every 60 minute window
whitelist: () => {
return false;
},
onBlacklist: null,
noip: false
};
if (isNil(namespace)) {
throw new Error('The IP Blacklist cache namespace can not be omitted.');
}
this.namespace = namespace;
this.cache = cache;
// Default the cache to a memory cache if unset
if (isNil(this.cache)) {
this.cache = new ObjectKeyCache();
this.cache.connect();
}
// Default to a logstub if not provided
this.log = log || new LogStub();
this.config = merge(Object.assign(defaults), config);
}
calcLookups(req, res) {
// check and set lookup
let looks = [];
if (typeof this.config.lookup === 'function') {
looks = this.config.lookup(req, res);
}
// Make sure that the lookups are an array if unset
if (!isNil(this.config.lookup)) {
// Convert to Array if not already
looks = Array.isArray(this.config.lookup) ? this.config.lookup.splice(0) : [this.config.lookup];
}
// Push the IP Address of the requestor into the array
// This should always be done except when the `noip` flag is true
if (!this.config.noip) {
looks.push(req.headers['x-forwarded-for'] || req.connection.remoteAddress);
}
// merge lookup options
return looks.join(':');
}
checkWhitelist(req) {
if (Array.isArray(this.config.whitelist)) {
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
return this.config.whitelist.includes(ip);
}
if (typeof this.config.whitelist === 'function') {
return this.config.whitelist(req);
}
return false;
}
increment(req, res, next, closure) {
let parsedLimit;
// Skip if this passes the whitelist
if (this.checkWhitelist(req)) {
this.log.debug('Skipping Blacklist Increment -- IP is whitelisted');
return next ? next() : undefined;
}
const lookups = this.calcLookups(req, res);
const key = `ipblacklist:${lookups}`;
const timestamp = Date.now();
const defaultLimit = {
total: this.config.count,
remaining: this.config.count,
reset: timestamp + this.config.expire
};
this.cache
.hgetAsync(this.namespace, key)
.then((limit) => {
try {
parsedLimit = JSON.parse(limit);
} catch (err) {}
parsedLimit = parsedLimit || defaultLimit;
// Check if the blacklist cache has expired and reset if it has
if (timestamp > parsedLimit.reset) {
parsedLimit.remaining = this.config.count;
}
// another increment moves the expiration window on the requests
parsedLimit.reset = timestamp + this.config.expire;
// subtract one from attempts remainins and do not allow negative remaining
parsedLimit.remaining = Math.max(Number(parsedLimit.remaining) - 1, -1);
// increment counter
return this.cache.hsetAsync(this.namespace, key, JSON.stringify(parsedLimit));
})
.then(() => {
// Do nothing
if (closure) {
closure();
}
})
.catch((err) => {
// There was som error trying to retrieve the rate limit cache data
// Log the error and skip
this.log.error(err.stack || err);
});
return next ? next() : undefined;
}
checkBlacklist(req, res, next) {
let parsedLimit;
// Skip if this passes the whitelist
if (this.checkWhitelist(req)) {
this.log.debug('Skipping Blacklist Check -- IP is whitelisted');
return next();
}
// Set onRateLimited function
const onBlacklistType = typeof this.config.onBlacklist;
this.config.onBlacklist = (onBlacklistType === 'function') ? this.config.onBlacklist : defaultBlacklistFn;
const lookups = this.calcLookups(req, res);
const key = `ipblacklist:${lookups}`;
const timestamp = Date.now();
const defaultLimit = {
total: this.config.count,
remaining: this.config.count,
reset: timestamp + this.config.expire
};
this.cache
.hgetAsync(this.namespace, key)
.then((limit) => {
// No record, skip
if (!limit) {
return next();
}
try {
parsedLimit = JSON.parse(limit);
} catch (err) {}
parsedLimit = parsedLimit || defaultLimit;
// Check if the blacklist cache has expired and reset if it has
if (timestamp > parsedLimit.reset) {
parsedLimit.reset = timestamp + this.config.expire;
parsedLimit.remaining = this.config.count;
}
if (parsedLimit.remaining >= 0) {
// Not blacklisted
return next();
}
// Blacklisted
const after = (parsedLimit.reset - Date.now()) / 1000;
res.set('Retry-After', after);
this.config.onBlacklist(req, res, next);
})
.catch((err) => {
// There was some error trying to retrieve the blacklist cache data
// Log the error and skip
this.log.error(err.stack || err);
return next();
});
return undefined;
}
}
module.exports = IPBlacklist;