All files / src/lib/socket server.ts

0% Statements 0/311
100% Branches 0/0
0% Functions 0/1
0% Lines 0/311

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Socket.IO Server
 *
 * Server-side WebSocket initialization with authentication middleware
 * and room-based channel management for real-time features.
 */

import { Server as HTTPServer } from 'http';
import { Server as SocketServer, Socket } from 'socket.io';
import { decode } from 'next-auth/jwt';
import { logger } from '@/lib/logging';
import type {
  ServerToClientEvents,
  ClientToServerEvents,
  InterServerEvents,
  SocketData,
  ChannelType,
  ConnectedPayload,
} from './types';

// Type for the Socket.IO server with our typed events
type TypedSocketServer = SocketServer<
  ClientToServerEvents,
  ServerToClientEvents,
  InterServerEvents,
  SocketData
>;

// Type for an individual socket with our typed events
type TypedSocket = Socket<
  ClientToServerEvents,
  ServerToClientEvents,
  InterServerEvents,
  SocketData
>;

// Singleton socket server instance
let io: TypedSocketServer | null = null;

/**
 * Initialize the Socket.IO server
 */
export function initSocketServer(httpServer: HTTPServer): TypedSocketServer {
  if (io) {
    return io;
  }

  io = new SocketServer<
    ClientToServerEvents,
    ServerToClientEvents,
    InterServerEvents,
    SocketData
  >(httpServer, {
    cors: {
      origin: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
      credentials: true,
    },
    transports: ['websocket', 'polling'],
    pingTimeout: 60000,
    pingInterval: 25000,
    connectionStateRecovery: {
      // Enable connection state recovery
      maxDisconnectionDuration: 2 * 60 * 1000, // 2 minutes
      skipMiddlewares: true,
    },
  });

  // Authentication middleware
  io.use(authMiddleware);

  // Connection handler
  io.on('connection', handleConnection);

  return io;
}

/**
 * Authentication middleware for Socket.IO connections
 */
async function authMiddleware(
  socket: TypedSocket,
  next: (err?: Error) => void
): Promise<void> {
  try {
    const token = socket.handshake.auth.token as string | undefined;

    if (!token) {
      return next(new Error('Authentication required'));
    }

    // Verify JWT token from NextAuth
    const session = await verifySocketToken(token);

    if (!session || !session.userId) {
      return next(new Error('Invalid session'));
    }

    // Attach user data to socket
    socket.data.userId = session.userId;
    socket.data.role = session.role || 'USER';
    socket.data.sessionId = session.sessionId || socket.id;
    socket.data.connectedAt = new Date();

    next();
  } catch (error) {
    logger.error('Socket authentication error', error instanceof Error ? error : new Error(String(error)), {
      category: 'EXTERNAL',
    });
    next(new Error('Authentication failed'));
  }
}

/**
 * Verify the socket token using NextAuth JWT decoding
 */
async function verifySocketToken(token: string): Promise<{
  userId: string;
  role: string;
  sessionId: string;
} | null> {
  try {
    const secret = process.env.NEXTAUTH_SECRET;

    if (!secret) {
      logger.error('NEXTAUTH_SECRET not configured', new Error('Missing NEXTAUTH_SECRET'), {
        category: 'EXTERNAL',
      });
      return null;
    }

    // Decode the JWT token using NextAuth's decode function
    // NextAuth v5 uses a different parameter structure
    const decoded = await decode({
      token,
      secret,
      salt: 'authjs.session-token', // Default salt for NextAuth v5
    });

    if (!decoded || !decoded.id) {
      return null;
    }

    return {
      userId: String(decoded.id),
      role: (decoded.role as string) || 'USER',
      sessionId: (decoded.jti as string) || '',
    };
  } catch (error) {
    logger.error('Token verification failed', error instanceof Error ? error : new Error(String(error)), {
      category: 'EXTERNAL',
    });
    return null;
  }
}

/**
 * Handle new socket connections
 */
function handleConnection(socket: TypedSocket): void {
  const { userId, role } = socket.data;

  // Join user-specific room
  socket.join(`user:${userId}`);

  // Admin users join admin-specific rooms
  if (role === 'ADMIN') {
    socket.join('admin');
    socket.join('orders');
    socket.join('inventory');
  }

  // Emit connected confirmation
  const connectedPayload: ConnectedPayload = {
    userId,
    connectedAt: new Date().toISOString(),
  };
  socket.emit('connected', connectedPayload);

  // Handle channel subscriptions
  socket.on('subscribe', (channels: string[]) => {
    channels.forEach((channel) => {
      if (canAccessChannel(userId, role, channel as ChannelType)) {
        socket.join(channel);
      } else {
        socket.emit('error', {
          message: `Access denied to channel: ${channel}`,
          code: 'CHANNEL_ACCESS_DENIED',
        });
      }
    });
  });

  // Handle channel unsubscriptions
  socket.on('unsubscribe', (channels: string[]) => {
    channels.forEach((channel) => {
      socket.leave(channel);
    });
  });

  // Handle notification mark as read
  socket.on('markRead', () => {
    // This will be handled by the notification service
    // The event is emitted for cross-device sync
  });

  // Handle order tracking - join order room
  socket.on('joinOrder', (orderId: string) => {
    // Validate user can access this order (admin or order owner)
    // For now, allow joining - validation should happen in order lookup
    socket.join(`order:${orderId}`);
  });

  // Handle order tracking - leave order room
  socket.on('leaveOrder', (orderId: string) => {
    socket.leave(`order:${orderId}`);
  });

  // Handle cart sync across devices
  socket.on('syncCart', (cartData) => {
    // Broadcast to other sockets for this user
    socket.to(`user:${userId}`).emit('cartSync', cartData);
  });

  // Handle disconnection
  socket.on('disconnect', () => {
    // Connection cleanup handled automatically
  });

  // Handle errors
  socket.on('error', () => {
    // Socket errors handled silently
  });
}

/**
 * Check if user can access a specific channel
 */
function canAccessChannel(
  userId: string,
  role: string,
  channel: ChannelType | string
): boolean {
  // Admin can access all channels
  if (role === 'ADMIN') {
    return true;
  }

  // Users can access their own user channel
  if (channel === `user:${userId}`) {
    return true;
  }

  // Users can access order channels (ownership validated separately)
  if (channel.startsWith('order:')) {
    return true;
  }

  // Users cannot access admin-only channels
  if (channel === 'admin' || channel === 'orders' || channel === 'inventory') {
    return false;
  }

  return false;
}

/**
 * Get the singleton Socket.IO server instance
 */
export function getSocketServer(): TypedSocketServer | null {
  return io;
}

/**
 * Close the Socket.IO server
 */
export function closeSocketServer(): void {
  if (io) {
    io.close();
    io = null;
  }
}

/**
 * Get the number of connected clients
 */
export async function getConnectedClientsCount(): Promise<number> {
  if (!io) return 0;
  const sockets = await io.fetchSockets();
  return sockets.length;
}

/**
 * Get the number of clients in a specific room
 */
export async function getRoomClientsCount(room: string): Promise<number> {
  if (!io) return 0;
  const sockets = await io.in(room).fetchSockets();
  return sockets.length;
}

/**
 * Disconnect a specific user from all their sockets
 */
export async function disconnectUser(userId: string): Promise<void> {
  if (!io) return;

  const sockets = await io.in(`user:${userId}`).fetchSockets();
  sockets.forEach((socket) => {
    socket.disconnect(true);
  });
}