I also ran into this problem. This was my decision as spam emits (using a malicious socket) ..
var spamData = new Object(); var spamCheckFunctions = ["updateUsers","moreEmits"]; // anti-spam will check these socket emits var antiSpam = 3000; // anti spam check per milliseconds var antiSpamRemove = 3; // -spam points per antiSpam check var maxSpam = 9; // Max spam points before disconnect is thrown to the socket io.sockets.on('connection', function (socket) { // Spam Check, this binds to all emits var emit = socket.emit; socket.emit = function() { data = Array.prototype.slice.call(arguments); if(spamCheckFunctions.contains(data[0])){ addSpam(socket); }; emit.apply(socket, arguments); }; var $emit = socket.$emit; socket.$emit = function() { data = Array.prototype.slice.call(arguments); if(spamCheckFunctions.contains(data[0])){ addSpam(socket); } $emit.apply(socket, arguments); }; }); function maxSpamCheck(socket){ if(spamData[socket.username].spamScore>=maxSpam && !socket.spamViolated){ socket.spamViolated = true; socket.disconnect(); } } function checkSpam(){ for(user in spamData){ if(spamData[user].spamScore>=1) spamData[user].spamScore-=antiSpamRemove; } return; } setInterval(checkSpam,antiSpam); function addSpam(socket){ if(socket.spamViolated) return; spamData[socket.username].spamScore+=1; maxSpamCheck(socket); } // Then add this where your user is authenticated function authenticate(socket){ socket.username = username // here you define username socket.spamViolated = false; spamData[socket.username] = { spamScore: 0 } } Array.prototype.contains = function(k) { for(var p in this) if(this[p] === k) return true; return false; };
basically contacts all emissions and checks if the emit name is contained in spamCheckFunctions if it adds a spam point if the user exceeds the spam count ( maxSpam ); he will be disconnected. And for every milliseconds defined in antiSpam , the user spam score defined in antiSpam will be underestimated
I'm sure there are cleaner solutions, but this option is very good for me :)
Just make sure you verify / authenticate users.
so I authenticate them (not using nodejs as a web server, but had django):
io.configure(function(){ io.set('authorization', function(data, accept){ if(data.headers.cookie){ data.cookie = cookie_reader.parse(data.headers.cookie); return accept(null, true); } return accept('error', false); }); });
now you can access socket.handshake.cookie['sessionid'] (in my case it worked with django) then map socket.handshake.cookie['sessionid'] to the entry where your sessions are stored on the web server
GiveMeAllYourCats
source share