feat: better colab
This commit is contained in:
27
server.js
27
server.js
@ -8,9 +8,36 @@ const app = express();
|
||||
const server = http.createServer(app);
|
||||
const io = new Server(server);
|
||||
|
||||
const eventTimestamps = {};
|
||||
const EVENT_LIMIT = 100; // Max events per second per user
|
||||
const TIME_FRAME = 1000; // 1 second in milliseconds
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
console.log('a user connected');
|
||||
|
||||
// Middleware to check for event spamming
|
||||
socket.use((packet, next) => {
|
||||
const userId = socket.id;
|
||||
const eventName = packet[0];
|
||||
const now = Date.now();
|
||||
|
||||
if (!eventTimestamps[userId]) {
|
||||
eventTimestamps[userId] = [];
|
||||
}
|
||||
|
||||
// Remove timestamps older than the time frame
|
||||
eventTimestamps[userId] = eventTimestamps[userId].filter(ts => now - ts < TIME_FRAME);
|
||||
|
||||
// Check if the user has exceeded the event limit
|
||||
if (eventTimestamps[userId].length >= EVENT_LIMIT) {
|
||||
console.warn(`User ${userId} is sending too many events (${eventName}). Throttling.`);
|
||||
return next(new Error('Too many events'));
|
||||
}
|
||||
|
||||
eventTimestamps[userId].push(now);
|
||||
next();
|
||||
});
|
||||
|
||||
socket.on('join', (room) => {
|
||||
socket.join(room);
|
||||
console.log(`User joined room: ${room}`);
|
||||
|
Reference in New Issue
Block a user