I'm stuck trying to answer what would happen if emit doesn't have any registered listeners.
Can it cause to vulnerability if the client is spaming by emits without any listeners?
while(true){
socket.emit('not_registered_event_string');
}
It does not cause any problem if you .emit()
without any listeners. The EventEmitter
object will just check the message name you passed in for a list of listeners and will find none and thus will do nothing.
However, this loop in a server:
while(true){
socket.emit('not_registered_event_string');
}
is an infinite loop and will prevent your node.js process from doing ANYTHING else. It will be stuck forever in that loop and will be unable to process any other events or do anything else.
This is because node.js runs your Javascript in a single thread so as long as that single thread is looping in your above while
loop, it can't process any other messages or do anything else. node.js is an event driven environment. You receive an event, you process the event, you return control back to the system and then the system can process the next event. If you loop forever, then no events ever get processed and your node.js process will appear hung (even though your loop may still be running).
That same loop in a client will just send a flood of messages to your server. The server can probably process them just fine because there's basically nothing to do when they are received if there is no listener for them. But, it will rob bandwidth and CPU from your server just dealing with the empty messages.
If you wanted to protect your server from a client spamming events, you can "rate limit" a client and if it exceeds a certain rate of messages per second or messages per minute, you can just drop its connection. Rate limiting is a well researched topic that many articles have been written about and there are numerous schemes with pre-built packages for node.js to aid in implementing rate limiting. A common one I've read about is the "leaky bucket" algorithm.
Rate limiting is a common way that servers protect themselves from rogue clients. With continued abuse, you might even suspend or revoke the account access to your web site so the account cannot even log in to your web site. Folks like Google use rate limiting on most (perhaps all) of their services to protect them from accidental or purposeful overload attacks.