forked from zerodytrash/TikTok-Chat-Reader
-
Notifications
You must be signed in to change notification settings - Fork 5
/
limiter.js
62 lines (48 loc) · 1.54 KB
/
limiter.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
let ipRequestCounts = {};
let maxIpConnections = 10;
let maxIpRequestsPerMinute = 5;
setInterval(() => {
ipRequestCounts = {};
}, 60 * 1000)
function clientBlocked(io, currentSocket) {
let ipCounts = getOverallIpConnectionCounts(io);
let currentIp = getSocketIp(currentSocket);
if (typeof currentIp !== 'string') {
console.info('LIMITER: Failed to retrieve socket IP.');
return false;
}
let currentIpConnections = ipCounts[currentIp] || 0;
let currentIpRequests = ipRequestCounts[currentIp] || 0;
ipRequestCounts[currentIp] = currentIpRequests + 1;
if (currentIpConnections > maxIpConnections) {
console.info(`LIMITER: Max connection count of ${maxIpConnections} exceeded for client ${currentIp}`);
return true;
}
if (currentIpRequests > maxIpRequestsPerMinute) {
console.info(`LIMITER: Max request count of ${maxIpRequestsPerMinute} exceeded for client ${currentIp}`);
return true;
}
return false;
}
function getOverallIpConnectionCounts(io) {
let ipCounts = {};
io.of('/').sockets.forEach(socket => {
let ip = getSocketIp(socket);
if (!ipCounts[ip]) {
ipCounts[ip] = 1;
} else {
ipCounts[ip] += 1;
}
})
return ipCounts;
}
function getSocketIp(socket) {
if (['::1', '::ffff:127.0.0.1'].includes(socket.handshake.address)) {
return socket.handshake.headers['x-forwarded-for'];
} else {
return socket.handshake.address;
}
}
module.exports = {
clientBlocked
}