-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
40 lines (38 loc) · 1.12 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
function clientID(req) {
return req.connection.remoteAddress;
}
function connectBruteForce(options) {
var self = this;
options = options || {};
options.banMax = options.banMax || 30 * 1000;
options.banFactor = options.banFactor || 2 * 1000;
this.db = {};
function delayResponse(req, res, next) {
var factor = Math.min(req.delayed.counter * options.banFactor, options.banMax);
setTimeout(function (next) {
next();
}, factor, next);
}
this.prevent = function (req, res, next) {
req.delayed = self.db[clientID(req)];
if (req.delayed) {
delayResponse(req, res, next);
} else {
next();
}
};
}
exports = module.exports = connectBruteForce;
connectBruteForce.prototype.ban = function (req) {
var client = clientID(req),
delay = this.db[client] || (this.db[client] = {
at: new Date(),
counter: 0
});
delay.counter++;
delay.lastTimeBanned = new Date();
};
connectBruteForce.prototype.unban = function (req) {
delete this.db[clientID(req)];
delete req.delayed;
};