63 lines
1.6 KiB
JavaScript
63 lines
1.6 KiB
JavaScript
'use strict';
|
|
|
|
const { Server } = require('socket.io');
|
|
const jwt = require('jsonwebtoken');
|
|
const logger = require('./logger');
|
|
|
|
let io;
|
|
|
|
function init(httpServer) {
|
|
io = new Server(httpServer, {
|
|
cors: {
|
|
origin: process.env.NODE_ENV === 'production'
|
|
? process.env.CORS_ORIGIN
|
|
: true,
|
|
credentials: true,
|
|
},
|
|
});
|
|
|
|
io.use((socket, next) => {
|
|
const token = socket.handshake.auth?.token;
|
|
if (!token) {
|
|
return next(new Error('Authentication required'));
|
|
}
|
|
|
|
jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] }, (err, decoded) => {
|
|
if (err) return next(new Error('Invalid token'));
|
|
socket.data.user = decoded;
|
|
next();
|
|
});
|
|
});
|
|
|
|
io.on('connection', (socket) => {
|
|
logger.debug({ userId: socket.data.user?.id }, 'Socket connected');
|
|
|
|
socket.on('timer:join', ({ sessionId } = {}) => {
|
|
if (!sessionId) return;
|
|
socket.join(sessionId);
|
|
// Lazy require avoids load-time circular dependency
|
|
const timerSvc = require('../modules/timers/service');
|
|
const engine = timerSvc.getSessionEngine(sessionId);
|
|
if (engine) socket.emit('timer:state', engine.getState());
|
|
});
|
|
|
|
socket.on('timer:leave', ({ sessionId } = {}) => {
|
|
if (sessionId) socket.leave(sessionId);
|
|
});
|
|
|
|
socket.on('disconnect', (reason) => {
|
|
logger.debug({ userId: socket.data.user?.id, reason }, 'Socket disconnected');
|
|
});
|
|
});
|
|
|
|
logger.info('Socket.io initialized');
|
|
return io;
|
|
}
|
|
|
|
function getIo() {
|
|
if (!io) throw new Error('Socket.io not initialized — call init() first');
|
|
return io;
|
|
}
|
|
|
|
module.exports = { init, getIo };
|