feat: better colab

This commit is contained in:
2025-07-08 14:57:44 +02:00
parent e9d8a1a818
commit d5a744652d
2 changed files with 37 additions and 4 deletions

View File

@ -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}`);