-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathrate_limiter.js
More file actions
67 lines (58 loc) · 1.53 KB
/
rate_limiter.js
File metadata and controls
67 lines (58 loc) · 1.53 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
61
62
63
64
65
66
67
"use strict";
var config = require('config');
var log = require('./log');
module.exports = function () {
// IP -> array of request timestamps
var requests = {};
// Periodically clean up stale entries to prevent memory leaks
var cleanupInterval = setInterval(function () {
let now = Date.now();
let windowMS = config.get('rateLimitWindow') * 1000;
for (let ip in requests) {
// Remove timestamps outside the window
requests[ip] = requests[ip].filter(function (ts) {
return now - ts < windowMS;
});
// Remove empty entries
if (!requests[ip].length) {
delete requests[ip];
}
}
}, 60 * 1000);
// Don't prevent process exit
if (cleanupInterval.unref) {
cleanupInterval.unref();
}
return {
/**
* Check whether a request from the given IP is within the rate limit.
*
* @param {String} ip
* @returns {Boolean} -- true if allowed, false if rate limited
*/
checkLimit: function (ip) {
let now = Date.now();
let maxRequests = config.get('rateLimitRequests');
let windowMS = config.get('rateLimitWindow') * 1000;
if (!requests[ip]) {
requests[ip] = [];
}
// Remove timestamps outside the sliding window
requests[ip] = requests[ip].filter(function (ts) {
return now - ts < windowMS;
});
if (requests[ip].length >= maxRequests) {
log.warn("Rate limit exceeded", { remoteAddress: ip });
return false;
}
requests[ip].push(now);
return true;
},
/**
* Reset all tracked state. Used by tests.
*/
reset: function () {
requests = {};
}
};
}();