feat: server socket management for multiple browsers

This commit is contained in:
Rohit
2025-03-08 17:09:33 +05:30
parent a0e7404d25
commit 6de4cfcafe
6 changed files with 186 additions and 70 deletions

View File

@@ -1,6 +1,60 @@
import { Namespace, Socket } from 'socket.io';
import { IncomingMessage } from 'http';
import { verify, JwtPayload } from 'jsonwebtoken';
import logger from "../logger";
import registerInputHandlers from '../browser-management/inputHandlers'
import registerInputHandlers from '../browser-management/inputHandlers';
interface AuthenticatedIncomingMessage extends IncomingMessage {
user?: JwtPayload | string;
}
interface AuthenticatedSocket extends Socket {
request: AuthenticatedIncomingMessage;
}
/**
* Socket.io middleware for authentication
* This is a socket.io specific auth handler that doesn't rely on Express middleware
*/
const socketAuthMiddleware = (socket: Socket, next: (err?: Error) => void) => {
const cookies = socket.handshake.headers.cookie;
if (!cookies) {
return next(new Error('Authentication required'));
}
const tokenMatch = cookies.split(';').find(c => c.trim().startsWith('token='));
if (!tokenMatch) {
return next(new Error('Authentication required'));
}
const token = tokenMatch.split('=')[1];
if (!token) {
return next(new Error('Authentication required'));
}
const secret = process.env.JWT_SECRET;
if (!secret) {
return next(new Error('Server configuration error'));
}
verify(token, secret, (err: any, user: any) => {
if (err) {
logger.log('warn', 'JWT verification error:', err);
return next(new Error('Authentication failed'));
}
// Normalize payload key
if (user.userId && !user.id) {
user.id = user.userId;
delete user.userId; // temporary: del the old key for clarity
}
// Attach user to socket request
const authSocket = socket as AuthenticatedSocket;
authSocket.request.user = user;
next();
});
};
/**
* Opens a websocket canal for duplex data transfer and registers all handlers for this data for the recording session.
@@ -13,6 +67,8 @@ export const createSocketConnection = (
io: Namespace,
callback: (socket: Socket) => void,
) => {
io.use(socketAuthMiddleware);
const onConnection = async (socket: Socket) => {
logger.log('info', "Client connected " + socket.id);
registerInputHandlers(socket);
@@ -34,6 +90,8 @@ export const createSocketConnectionForRun = (
io: Namespace,
callback: (socket: Socket) => void,
) => {
io.use(socketAuthMiddleware);
const onConnection = async (socket: Socket) => {
logger.log('info', "Client connected " + socket.id);
socket.on('disconnect', () => logger.log('info', "Client disconnected " + socket.id));
@@ -41,4 +99,4 @@ export const createSocketConnectionForRun = (
}
io.on('connection', onConnection);
};
};