socket.io
socket.io copied to clipboard
sendPacket Middleware
Is your feature request related to a problem? Please describe. Right now I want to implement certain authentication functionalities at the packet level to prevent the server from emitting events depending on the user. However there is no way currently of handling this at the packet emit level
Describe the solution you'd like
Something like
socket.sendPacket.use((type,data,options,next) => { next(err) //Use err to cancel sending of packet })
A clear and concise description of what you want to happen.
Describe alternatives you've considered I've considered monkey patching to support a middleware functionality
I don't mind contributing to this feature, if it makes sense for you guys
Hi! I don't think this should be implemented at this level, Engine.IO is meant for handling the low-level plumbing.
You can use the Room feature of Socket.IO to only send to authorized users:
io.to("authorized_users").emit("hello");
Reference: https://socket.io/docs/v4/rooms/
Hey Darra, here's my use case that rooms does not support (to my knowledge)
Example
Database update (User id 1 now has property isAdmin = true) 🔽 Save context of update with async local storage 🔽 Send update to all users where User isAdmin
So I could make a room where I add authorized_users, but the problem with that is then if I want to programmatically make rules, then I would have an infinite number of rules for an infinite number of arbitrary rooms
Another reason why I want to implement this is because I want to implement the rule checking at the packet sending level, so that future people working on the codebase will not make the mistake of sending data to an unauthorized room
I'm happy to hear thoughts on the second reason of checking auth at the packet creation level too, the idea behind it is similar to firebase security rules
Thanks for the explanation!
In that case, it might make sense to implement it at the Socket.IO level, we already have something like that for incoming packets:
socket.use(([event, ...args], next) => {
// do something with the packet (logging, authorization, rate limiting...)
// do not forget to call next() at the end
next();
});
Documentation: https://socket.io/docs/v4/server-socket-instance/#socket-middlewares