-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (40 loc) · 1.33 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
"use strict";
/*!
* Rate Limiter Middleware for the Prism Realtime Server
*
* This very basic rate limiter prevents malicious users from flooding the
* server with multiple requests per second (easy to do on the client if you
* use a while loop in the JS console).
*
* Primarily it serves as an example of how to create Request Middleware
*
* Copyright(c) 2013 Owen Barnes <[email protected]>
* MIT Licensed
*/
module.exports = function(options) {
options = options || {};
options.maxRequestsPerSecond = options.maxRequestsPerSecond || 8;
var rpsSocketIds = {};
var warnedSocketIds = {};
return function(server) {
// cleanup when socket disconnects
server.events.on('disconnect', function(socketId){
delete warnedSocketIds[socketId];
});
// reset request counters every second
setInterval(function(){ rpsSocketIds = {}; }, 1000);
return function(req, res, next) {
if (!rpsSocketIds[req.socketId]) rpsSocketIds[req.socketId] = 0;
var rps = ++rpsSocketIds[req.socketId];
// drop the request if client has exceeded its limit
if (rps > options.maxRequestsPerSecond) {
if (!warnedSocketIds[req.socketId]) {
warnedSocketIds[req.socketId] = true;
res('Request dropped by rate limiter');
}
return;
}
next();
};
};
};