-
Notifications
You must be signed in to change notification settings - Fork 73k
Expand file tree
/
Copy pathdelaylist.js
More file actions
60 lines (49 loc) · 1.47 KB
/
delaylist.js
File metadata and controls
60 lines (49 loc) · 1.47 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
54
55
56
57
58
59
60
'use strict';
const _ = require('lodash');
function init (env) {
const ipDelayList = {};
const rawAuthFailDelay = _.get(env, 'settings.authFailDelay');
const parsedAuthFailDelay = Number(rawAuthFailDelay);
const DELAY_ON_FAIL = Number.isFinite(parsedAuthFailDelay) && parsedAuthFailDelay > 0 ? parsedAuthFailDelay : 5000;
const FAIL_AGE = 60000;
ipDelayList.addFailedRequest = function addFailedRequest (ip) {
const ipString = String(ip);
let entry = ipDelayList[ipString];
const now = Date.now();
if (!entry) {
ipDelayList[ipString] = now + DELAY_ON_FAIL;
return;
}
if (now >= entry) { entry = now; }
ipDelayList[ipString] = entry + DELAY_ON_FAIL;
};
ipDelayList.shouldDelayRequest = function shouldDelayRequest (ip) {
const ipString = String(ip);
const entry = ipDelayList[ipString];
let now = Date.now();
if (entry) {
if (now < entry) {
return entry - now;
}
}
return false;
};
ipDelayList.requestSucceeded = function requestSucceeded (ip) {
const ipString = String(ip);
if (ipDelayList[ipString]) {
delete ipDelayList[ipString];
}
};
// Clear items older than a minute
setTimeout(function clearList () {
for (var key in ipDelayList) {
if (ipDelayList.hasOwnProperty(key)) {
if (Date.now() > ipDelayList[key] + FAIL_AGE) {
delete ipDelayList[key];
}
}
}
}, 30000);
return ipDelayList;
}
module.exports = init;