All files / server websockets.js

85.29% Statements 29/34
62.5% Branches 5/8
100% Functions 5/5
85.29% Lines 29/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63            3x 17x 17x   3x 14x 14x 14x 14x 14x             14x     14x 14x 14x   14x 14x 1x     8x 8x     14x 2x 2x 2x   1x               14x 1x 1x     14x 1x 1x        
import text0wnz from './text0wnz.js';
import { callout, sanitize, anonymizeIp } from './utils.js';
 
let debug;
let allClients;
 
const webSocketInit = (config, clients) => {
	debug = config.debug || false;
	allClients = clients;
};
const onWebSocketConnection = (ws, req) => {
	const anonID = req.sessionID.slice(0, req.sessionID.length / 2) + 'XXXXXX';
	callout('New WebSocket Connection');
	console.log(`- Timestamp: ${new Date().toISOString()}`);
	console.log(`- Session ID: ${anonID}`);
	Iif (debug) {
		const ip = req.connection.remoteAddress || req.ip;
		console.log(`- Remote IP: ${anonymizeIp(ip)}`);
		console.log(`- User-Agent: ${req.headers['user-agent']}`);
		console.log(`- Origin: ${req.headers['origin']}`);
		console.log(`- URL: ${req.url}`);
	}
	allClients.add(ws);
 
	// Send initial data
	try {
		const startData = text0wnz.getStart(req.sessionID);
		ws.send(startData);
 
		const imageData = text0wnz.getImageData();
		if (imageData?.data) {
			ws.send(imageData.data, { binary: true });
		}
	} catch (err) {
		console.error('Error sending initial data:', err);
		ws.close(1011, 'Server error during initialization');
	}
 
	ws.on('message', msg => {
		try {
			const parsedMsg = JSON.parse(msg);
			text0wnz.message(parsedMsg, req.sessionID, allClients);
		} catch (err) {
			console.error(
				'Error parsing message:',
				err,
				`[User message: ${sanitize(msg.toString())}]`,
			);
		}
	});
 
	ws.on('close', (_code, _reason) => {
		allClients.delete(ws);
		text0wnz.closeSession(req.sessionID, allClients);
	});
 
	ws.on('error', err => {
		console.error('WebSocket error:', err);
		allClients.delete(ws);
	});
};
export { webSocketInit, onWebSocketConnection };