Real-time chat on BHULink: the bug that taught me sockets can't trust the client
REST owns durable state, Socket.IO owns delivery — until I discovered any anonymous client could join another user's room. How the auth model was rebuilt around the JWT handshake, and what it cost.
BHULink is a campus social platform for Bule Hora University — posts, reels, announcements, and real-time 1:1 and group chat. The chat is the feature people remember, and it's also where I made my most instructive mistake. This post is about the architecture that worked, the security hole I found in my own design, and the trade-offs behind both.
The boundary: REST owns state, sockets own delivery
The first decision was drawing a hard line: messages are persisted through the REST API; the socket layer only relays events. The socket server never writes to the database. Every open client converges on the same state by re-fetching through REST, and the socket's job is purely to say "something changed, look now."
The alternative — making sockets bidirectional read-write paths — collapses two transports into one code path, and then you're maintaining two versions of every authorization rule. With the boundary, the socket relay code stays small enough to audit line by line. That auditability turned out to matter more than I knew at the time.
Express controllers reach the Socket.IO server through the app instance; nothing else couples them.
The bug: sockets trusted whoever knocked
The original design authenticated the REST API properly — JWT on every request. But the socket layer had a different, looser model: the client emitted a setup event with its user ID, and the server joined that socket to the matching room. No token. No verification.
Which means: any anonymous client could emit setup with someone else's user ID and start receiving their private messages. The REST API was locked; the socket path was a side door into the same house.
The fix removed client-supplied identity entirely. Authentication moved to the Socket.IO handshake, where it belongs:
const authenticateSocket = async (socket, next) => {
const token =
socket.handshake?.auth?.token ||
socket.handshake?.headers?.authorization?.split(" ")[1] ||
socket.handshake?.query?.token;
if (!token) {
return next(new Error("Authentication required"));
}
let userId;
try {
userId = getUserIdFromToken(token);
} catch {
return next(new Error("Invalid or expired token"));
}
const user = userId ? await User.findById(userId).select("_id") : null;
if (!user) return next(new Error("Invalid or expired token"));
socket.userId = String(user._id);
next();
};
Now every socket is bound to a verified user before it can do anything, and each socket joins exactly one room: its own user's room.
The deeper fix: recipients come from the database, not the client
Handshake auth alone wasn't the whole story. When a message is relayed, the old reflex is to trust the payload's recipient list. Instead, the relay handler resolves everything server-side:
const newMessageHandler = async (newMessageReceived) => {
const chatId = newMessageReceived?.chat?._id || newMessageReceived?.chat || null;
if (!chatId) return;
// Only a participant may relay a message, and recipients are taken
// from the database, not from the client-supplied payload.
const access = await loadChatForMember(chatId, socket.userId);
if (access.status !== 200) return;
access.chat.users.forEach((user) => {
const recipientId = String(user?._id || user);
if (recipientId === socket.userId) return;
io.to(recipientId).emit("message received", newMessageReceived);
});
};
Three rules fall out of this pattern:
- A socket may only act where its verified user is a member — checked against the database, every event.
- Delivery targets come from the chat document, never from the client.
- The socket's own room is the only room it joins by default — joining a conversation room re-checks membership and leaves the previous room, so a socket can't lurk in several chats it's joined over time.
The trade-off is latency: every socket event now pays a database membership check. A fire-and-forget relay would be faster. It would also mean the correctness of private-message delivery depends on client behavior — the exact assumption that created the bug. For a campus platform where the content is private messages between real students, the DB round-trip is the cheap side of that trade.
Typing indicators, clear-chat, and chat-created/deleted events follow the same rule: the emitting socket must be a member of the room it's addressing, verified server-side.
The regression net
The fix came with tests that make the side door permanently locked: socketAuth.test.js asserts that a handshake without a token is rejected, and a separate authorization suite covers the privileged-path checks across the REST API — added after an audit pass found endpoints reachable without authentication. CI runs both on every push, so the classes of bug I actually shipped are the classes the suite watches for.
Honest limits: sockets and serverless don't mix
Socket.IO wants a long-running server; serverless functions don't give you one. Alongside the main path there's a Server-Sent-Events adapter built for serverless hosting — degraded mode: broadcast-only, no per-user rooms, no typing. It exists so a cheap deployment is possible, and it's honest about being a fallback. The real deployment target is a long-running host where the full room model works. The lesson generalizes: real-time over serverless is a compromise you should design for explicitly, not discover in production.
What I took from it
Two things stuck. First, transport boundaries need their own auth model — "the API is secure" means nothing if a second transport quietly reopens the same data. Second, the server-side relay pattern — resolve identity and recipients from the database on every event — is the socket version of a rule I already knew from REST: the client is a suggestion, the database is the truth.