All files / src websocket.js

0% Statements 0/314
0% Branches 0/178
0% Functions 0/49
0% Lines 0/279

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 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Serveur WebSocket — Streaming des métriques dashboard en temps réel.
 *
 * Flux :
 *   1. Le client ouvre une connexion WS (les cookies sont envoyés automatiquement)
 *   2. Le client envoie : { type: 'subscribe', serverId: '...' }
 *   3. Le serveur vérifie l'auth via le cookie, valide la propriété du serveur
 *   4. Le serveur envoie les métriques toutes les 5 secondes
 *
 * Sécurité :
 *   - Authentification via cookie httpOnly (ou token dans le message en fallback)
 *   - Vérification que le serveur appartient à l'utilisateur
 *   - Rate limiting des connexions (max 10 par IP par minute)
 *   - Messages d'erreur génériques (pas de fuite d'info)
 *
 * @module websocket
 */
 
const { WebSocketServer, OPEN } = require('ws');
const jwt = require('jsonwebtoken');
const cookie = require('cookie');
const { exec, shell, getConnection } = require('./services/ssh');
const { pool: db } = require('./db');
const { getPlanLimits } = require('./config/plans');
const { validateContainerName } = require('./utils/pathValidator');
const { shellEscape } = require('./utils/shell');
const { resolveGroupContext, satisfiesLevel } = require('./helpers/groupAccess');
 
// ─── Rate limiting des connexions WebSocket ──────────────────────────────────
// Stocke le nombre de connexions par IP dans une fenêtre d'une minute.
const wsConnectionCounts = new Map();
const WS_RATE_LIMIT = 30;         // Max connexions par IP par fenêtre
const WS_RATE_WINDOW_MS = 60000;  // Fenêtre d'une minute
 
/**
 * Vérifie que l'IP n'a pas dépassé la limite de connexions WS.
 * @param {string} ip
 * @returns {boolean} true si autorisé
 */
function checkWsRateLimit(ip) {
  const now = Date.now();
  const entry = wsConnectionCounts.get(ip);
 
  if (!entry || now - entry.start > WS_RATE_WINDOW_MS) {
    wsConnectionCounts.set(ip, { count: 1, start: now });
    return true;
  }
 
  entry.count++;
  return entry.count <= WS_RATE_LIMIT;
}
 
// Nettoyage périodique du rate limiter (toutes les 5 minutes)
setInterval(() => {
  const now = Date.now();
  for (const [ip, entry] of wsConnectionCounts) {
    if (now - entry.start > WS_RATE_WINDOW_MS) {
      wsConnectionCounts.delete(ip);
    }
  }
}, 5 * 60 * 1000);
 
// ─── Parsers de métriques système ────────────────────────────────────────────
 
/**
 * Parse la sortie de `free -m` pour extraire l'utilisation mémoire.
 */
function parseFree(raw) {
  const memLine = raw.split('\n').find((l) => l.startsWith('Mem:'));
  if (!memLine) return null;
  const parts = memLine.split(/\s+/);
  const total = Number.parseInt(parts[1]);
  const used = Number.parseInt(parts[2]);
  return { total_mb: total, used_mb: used, use_percent: Math.round((used / total) * 100) };
}
 
/**
 * Parse la sortie de `top -bn1` pour extraire le pourcentage CPU.
 */
function parseCpu(raw) {
  const cpuLine = raw.split('\n').find((l) => l.includes('%Cpu(s)'));
  if (!cpuLine) return null;
  // ReDoS-safe : \d+ et \.\d+ sont disjoints (le point separe), backtracking lineaire O(n).
  // De plus, l'entree provient de `top -bn1` (sortie bornee d'une commande systeme).
  const idleMatch = cpuLine.match(/(\d+(?:\.\d+)?)\s+id/); // NOSONAR — regex safe (classes disjointes, entree bornee)
  const idle = idleMatch ? Number.parseFloat(idleMatch[1]) : null;
  return idle == null ? null : { use_percent: Math.round(100 - idle) };
}
 
/**
 * Récupère les métriques système du serveur en parallèle.
 */
async function fetchMetrics(userId, serverId) {
  const [cpuRes, memRes, loadRes] = await Promise.allSettled([
    exec(userId, serverId, String.raw`top -bn1 | grep '%Cpu\|cpu'`),
    exec(userId, serverId, 'free -m'),
    exec(userId, serverId, 'cat /proc/loadavg'),
  ]);
 
  const get = (r) => (r.status === 'fulfilled' ? r.value.stdout : '');
  const loadRaw = get(loadRes).trim().split(' ');
 
  return {
    cpu: parseCpu(get(cpuRes)),
    memory: parseFree(get(memRes)),
    load: {
      '1m': Number.parseFloat(loadRaw[0]) || null,
      '5m': Number.parseFloat(loadRaw[1]) || null,
    },
    ts: Date.now(),
  };
}
 
// ─── Authentification WebSocket ──────────────────────────────────────────────
 
/**
 * Authentifie un client WebSocket.
 * Essaie d'abord le cookie httpOnly (automatique), puis le token dans le message.
 *
 * @param {import('ws').WebSocket} ws — La connexion WebSocket
 * @param {import('http').IncomingMessage} req — La requête HTTP d'upgrade
 * @param {string} [msgToken] — Token envoyé dans le message subscribe (fallback)
 * @returns {string|null} — L'ID utilisateur ou null si l'auth échoue
 */
function authenticateWs(ws, req, msgToken) {
  // 1. Essayer le cookie httpOnly
  const cookies = cookie.parse(req.headers.cookie || '');
  const token = cookies.access_token || msgToken;
 
  if (!token) {
    ws.send(JSON.stringify({ type: 'error', message: 'Authentification requise.' }));
    ws.close();
    return null;
  }
 
  try {
    const payload = jwt.verify(token, process.env.JWT_SECRET);
    return payload.sub;
  } catch {
    ws.send(JSON.stringify({ type: 'error', message: 'Token invalide.' }));
    ws.close();
    return null;
  }
}
 
/**
 * Vérifie que le serveur appartient à l'utilisateur.
 */
async function verifyServerOwnership(userId, serverId) {
  const result = await db.query(
    'SELECT id FROM servers WHERE id = $1 AND user_id = $2',
    [serverId, userId],
  );
  return result.rows.length > 0;
}
 
/**
 * Verifie l'acces a un serveur via un groupe (si groupId fourni).
 * Retourne true si l'acces est accorde, false sinon (avec message d'erreur envoye au client).
 *
 * @param {import('ws').WebSocket} ws
 * @param {string} userId
 * @param {string} serverId
 * @param {string} [groupId] — Si present, verification groupe-aware
 * @param {string} [zone] — Zone de permission requise (ex: 'terminal', 'docker')
 * @param {string} [minLevel] — Niveau minimum ('read' ou 'write')
 * @returns {Promise<boolean>}
 */
async function verifyServerAccess(ws, userId, serverId, groupId, zone, minLevel) {
  if (!groupId) {
    // Mode classique — verification ownership directe
    const owns = await verifyServerOwnership(userId, serverId);
    if (!owns) {
      ws.send(JSON.stringify({ type: 'error', message: 'Serveur non autorisé.' }));
    }
    return owns;
  }
 
  // Mode groupe — verification via resolveGroupContext
  const access = await resolveGroupContext(userId, groupId);
  if (!access) {
    ws.send(JSON.stringify({ type: 'error', message: 'Acces refuse a ce groupe.' }));
    return false;
  }
 
  // Verifier que le serveur est dans le groupe
  if (!access.serverIds.includes(serverId)) {
    ws.send(JSON.stringify({ type: 'error', message: 'Serveur non lie a ce groupe.' }));
    return false;
  }
 
  // Verifier la permission de zone (si demandee)
  if (zone && minLevel && !access.isOwner) {
    const actual = access.permissions[zone] || 'none';
    if (!satisfiesLevel(actual, minLevel)) {
      ws.send(JSON.stringify({
        type: 'error',
        code: 'GROUP_PERMISSION_DENIED',
        message: `Permission insuffisante : ${zone} requiert ${minLevel}.`,
      }));
      return false;
    }
  }
 
  return true;
}
 
/**
 * Verifie qu'une feature est disponible pour le plan de l'utilisateur.
 * @param {string} userId
 * @param {string} feature
 * @returns {Promise<boolean>}
 */
async function checkWsFeature(userId, feature, groupId) {
  // En mode groupe, utiliser le plan du proprietaire du groupe
  let effectiveUserId = userId;
  if (groupId) {
    const { rows: groupRows } = await db.query('SELECT owner_user_id FROM access_groups WHERE id = $1', [groupId]);
    if (groupRows.length > 0 && groupRows[0].owner_user_id !== userId) {
      effectiveUserId = groupRows[0].owner_user_id;
    }
  }
  const { rows } = await db.query('SELECT plan FROM users WHERE id = $1', [effectiveUserId]);
  const plan = rows[0]?.plan || 'free';
  const limits = await getPlanLimits(plan);
  return !!limits[feature];
}
 
// ─── Helpers partagés par les handlers ──────────────────────────────────────
 
/**
 * Vérifie qu'une feature du plan est disponible, sinon envoie une erreur au client.
 *
 * @param {import('ws').WebSocket} ws
 * @param {string} userId
 * @param {string} feature — Clé de la feature dans le plan
 * @param {string} featureLabel — Libellé lisible pour le message d'erreur
 * @returns {Promise<boolean>} true si la feature est disponible
 */
async function requirePlanFeature(ws, userId, feature, featureLabel, groupId) {
  const hasFeature = await checkWsFeature(userId, feature, groupId);
  if (hasFeature) return true;
 
  ws.send(JSON.stringify({
    type: 'error',
    code: 'PLAN_FEATURE_REQUIRED',
    message: `${featureLabel} necessite un plan Pro ou superieur.`,
    upgrade_url: '/settings#billing',
  }));
  return false;
}
 
/**
 * Authentifie l'utilisateur, vérifie la présence du serverId et la propriété.
 * Envoie les erreurs au client et ferme la connexion si nécessaire.
 *
 * @param {import('ws').WebSocket} ws
 * @param {import('http').IncomingMessage} req
 * @param {object} msg — Le message parsé
 * @param {object} ctx — Le contexte mutable de la connexion
 * @returns {Promise<boolean>} true si tout est valide
 */
async function authenticateAndVerifyOwnership(ws, req, msg, ctx, zone, minLevel) {
  ctx.userId = authenticateWs(ws, req, msg.token);
  if (!ctx.userId) return false;
 
  if (!msg.serverId) {
    ws.send(JSON.stringify({ type: 'error', message: 'serverId requis.' }));
    return false;
  }
 
  const hasAccess = await verifyServerAccess(ws, ctx.userId, msg.serverId, msg.groupId, zone, minLevel);
  if (!hasAccess) {
    ws.close();
    return false;
  }
 
  return true;
}
 
/**
 * Enregistre une action dans les logs d'audit (fire and forget).
 */
function auditLog(userId, action, target, details, ip) {
  db.query(
    `INSERT INTO audit_logs (user_id, action, category, target, details, ip)
     VALUES ($1, $2, $3, $4, $5, $6)`,
    [userId, action, 'terminal', target, JSON.stringify(details), ip],
  ).catch(() => {});
}
 
/**
 * Ferme tous les streams de logs Docker en cours.
 */
function closeAllDockerLogStreams(ctx) {
  for (const s of ctx.dockerLogStreams) {
    try { s.close(); } catch {}
  }
  ctx.dockerLogStreams = [];
}
 
/**
 * Nettoie toutes les ressources d'une connexion WS (interval, SSH, Docker logs).
 */
function cleanupConnection(ctx) {
  if (ctx.interval) clearInterval(ctx.interval);
  if (ctx.sshStream) {
    try { ctx.sshStream.end(); } catch {}
    ctx.sshStream = null;
  }
  closeAllDockerLogStreams(ctx);
}
 
// ─── Handlers de messages WebSocket ─────────────────────────────────────────
 
/**
 * Configure les listeners sur un stream SSH pour relayer les données au client WS.
 */
function setupSshStreamListeners(ws, ctx) {
  ctx.sshStream.on('data', (data) => {
    if (ws.readyState === OPEN) ws.send(data.toString('binary'));
  });
 
  ctx.sshStream.stderr.on('data', (data) => {
    if (ws.readyState === OPEN) ws.send(data.toString('binary'));
  });
 
  ctx.sshStream.on('close', () => {
    ctx.sshStream = null;
    if (ws.readyState === OPEN) {
      ws.send(JSON.stringify({ type: 'terminal-closed' }));
    }
  });
}
 
/**
 * Gère l'ouverture d'un terminal SSH interactif (type: terminal-open).
 *
 * Owner : shell SSH complet sur le serveur.
 * Membre de groupe : docker exec dans un container specifique (msg.containerId requis).
 */
async function handleTerminalOpen(ws, req, msg, ctx, ip) {
  if (!await authenticateAndVerifyOwnership(ws, req, msg, ctx, 'terminal', 'write')) return;
  if (!await requirePlanFeature(ws, ctx.userId, 'terminal_ssh', 'Le terminal SSH', msg.groupId)) return;
 
  try {
    // Verifier si c'est un membre de groupe (pas owner)
    const groupId = msg.groupId;
    let isGroupMember = false;
    if (groupId) {
      const access = await resolveGroupContext(ctx.userId, groupId);
      if (access && !access.isOwner) {
        isGroupMember = true;
      }
    }
 
    if (isGroupMember) {
      // Terminal Docker : exec dans un container du groupe
      if (!msg.containerId) {
        ws.send(JSON.stringify({ type: 'error', message: 'Selectionnez un container pour ouvrir le terminal.' }));
        return;
      }
 
      // Verifier que le container est dans les docker_targets du groupe
      const { loadGroupTargets, matchesTargets } = require('./helpers/dockerTargets');
      const targets = await loadGroupTargets(groupId, msg.serverId);
      if (!matchesTargets(msg.containerId, targets)) {
        ws.send(JSON.stringify({ type: 'error', message: 'Container non autorise.' }));
        return;
      }
 
      // Resoudre le vrai nom du container (Swarm ajoute un suffixe)
      const safeContainer = shellEscape(msg.containerId);
      const { stdout: cid } = await exec(ctx.userId, msg.serverId,
        `docker ps -q --filter name=${safeContainer} | head -1`,
      );
      const containerId = cid.trim();
      if (!containerId) {
        ws.send(JSON.stringify({ type: 'error', message: 'Container introuvable ou arrete.' }));
        return;
      }
 
      // Ouvrir un docker exec -it via SSH
      const safeId = shellEscape(containerId);
      const cols = msg.cols || 80;
      const rows = msg.rows || 24;
      ctx.sshStream = await shell(ctx.userId, msg.serverId, { cols, rows });
 
      // Envoyer docker exec + clear pour masquer le prompt SSH
      ctx.sshStream.write(`docker exec -it ${safeId} sh -c 'if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi' && exit\nclear\n`);
 
      setupSshStreamListeners(ws, ctx);
      ws.send(JSON.stringify({ type: 'terminal-ready' }));
      auditLog(ctx.userId, 'Ouverture terminal Docker', msg.serverId, { container: msg.containerId, cols, rows }, ip);
    } else {
      // Owner : shell SSH complet
      ctx.sshStream = await shell(ctx.userId, msg.serverId, {
        cols: msg.cols || 80,
        rows: msg.rows || 24,
      });
 
      setupSshStreamListeners(ws, ctx);
      ws.send(JSON.stringify({ type: 'terminal-ready' }));
      auditLog(ctx.userId, 'Ouverture terminal SSH', msg.serverId, { cols: msg.cols, rows: msg.rows }, ip);
    }
  } catch {
    ws.send(JSON.stringify({ type: 'error', message: 'Impossible d\'ouvrir le terminal.' }));
  }
}
 
/**
 * Gère la fermeture du terminal SSH (type: terminal-close).
 */
function handleTerminalClose(ctx, ip) {
  if (ctx.sshStream) {
    ctx.sshStream.end();
    ctx.sshStream = null;
  }
  if (ctx.userId) {
    auditLog(ctx.userId, 'Fermeture terminal', ctx.serverId, {}, ip);
  }
}
 
/**
 * Attache un stream SSH aux listeners de logs Docker avec buffering.
 */
function attachDockerLogStream(ws, ctx, stream, flushBuffer, bufferState) {
  ctx.dockerLogStreams.push(stream);
 
  const onData = (data) => {
    if (ws.readyState !== OPEN) return;
    bufferState.buffer += data.toString('utf-8');
    if (!bufferState.flushTimer) {
      bufferState.flushTimer = setTimeout(flushBuffer, 100);
    }
  };
 
  stream.on('data', onData);
  stream.stderr.on('data', onData);
 
  stream.on('close', () => {
    flushBuffer();
    ctx.dockerLogStreams = ctx.dockerLogStreams.filter((s) => s !== stream);
    if (ctx.dockerLogStreams.length === 0 && ws.readyState === OPEN) {
      ws.send(JSON.stringify({ type: 'docker-logs-closed' }));
    }
  });
}
 
/**
 * Démarre le tail des fichiers de logs internes au container.
 * Résout d'abord le vrai container ID (Swarm renomme les containers),
 * puis lance `docker exec tail -f` sur les fichiers trouvés.
 */
function startInternalLogTail({ ws, ctx, client, serviceName, filePaths, tail, flushBuffer, bufferState }) {
  if (filePaths.length === 0) return;
 
  const safePaths = filePaths.map((p) => shellEscape(p)).join(' ');
 
  client.exec(
    `docker ps -q --filter name=${shellEscape(serviceName)} | head -1`,
    (resolveErr, resolveStream) => {
      if (resolveErr) return;
      let cid = '';
      resolveStream.on('data', (d) => { cid += d.toString().trim(); });
      resolveStream.on('close', () => {
        if (!cid) return;
        client.exec(
          `docker exec ${shellEscape(cid)} tail -f -n ${tail} ${safePaths} 2>&1`,
          (tailErr, tailStream) => {
            if (tailErr) return;
            attachDockerLogStream(ws, ctx, tailStream, flushBuffer, bufferState);
            if (ws.readyState === OPEN) {
              ws.send(JSON.stringify({
                type: 'docker-logs-info',
                message: `Fichiers suivis : ${filePaths.join(', ')}`,
              }));
            }
          },
        );
      });
    },
  );
}
 
/**
 * Lance un auto-scan des fichiers .log dans le container puis démarre le tail.
 */
function autoScanAndTailLogs({ ws, ctx, client, safeContainer, serviceName, tail, flushBuffer, bufferState }) {
  client.exec(
    String.raw`docker exec ${safeContainer} sh -c "find / -name '*.log' -type f -size +0c -mmin -1440 ! -path '/proc/*' ! -path '/sys/*' 2>/dev/null | grep -vE '(apt/|dpkg|alternatives|bootstrap|fontconfig|apk\.log|npm/)' | head -10" 2>/dev/null`,
    (scanErr, scanStream) => {
      if (scanErr) return;
      let found = '';
      scanStream.on('data', (d) => { found += d.toString(); });
      scanStream.on('close', () => {
        const paths = found.trim().split('\n').filter(Boolean);
        startInternalLogTail({ ws, ctx, client, serviceName, filePaths: paths, tail, flushBuffer, bufferState });
      });
    },
  );
}
 
/**
 * Gère l'abonnement au streaming des logs Docker (type: docker-logs-subscribe).
 */
async function handleDockerLogsSubscribe(ws, req, msg, ctx) {
  ctx.userId = authenticateWs(ws, req, msg.token);
  if (!ctx.userId) return;
 
  if (!msg.serverId || !msg.containerId) {
    ws.send(JSON.stringify({ type: 'error', message: 'serverId et containerId requis.' }));
    return;
  }
 
  if (!await requirePlanFeature(ws, ctx.userId, 'docker_logs_streaming', 'Le streaming des logs Docker', msg.groupId)) return;
 
  const containerCheck = validateContainerName(msg.containerId);
  if (!containerCheck.valid) {
    ws.send(JSON.stringify({ type: 'error', message: containerCheck.reason }));
    return;
  }
 
  const hasAccess = await verifyServerAccess(ws, ctx.userId, msg.serverId, msg.groupId, 'docker', 'read');
  if (!hasAccess) {
    ws.close();
    return;
  }
 
  closeAllDockerLogStreams(ctx);
 
  try {
    const tail = Math.max(1, Math.min(Number.parseInt(msg.tail) || 100, 500));
    const safeContainer = shellEscape(msg.containerId);
    const client = await getConnection(ctx.userId, msg.serverId);
 
    // Buffer partagé pour tous les streams
    const bufferState = { buffer: '', flushTimer: null };
 
    const flushBuffer = () => {
      if (bufferState.buffer && ws.readyState === OPEN) {
        ws.send(JSON.stringify({ type: 'docker-logs', data: bufferState.buffer }));
        bufferState.buffer = '';
      }
      bufferState.flushTimer = null;
    };
 
    // 1) docker logs --follow (stdout/stderr du container) — toujours
    client.exec(
      `docker logs --follow --timestamps --tail ${tail} ${safeContainer} 2>&1`,
      (err, stream) => {
        if (!err) attachDockerLogStream(ws, ctx, stream, flushBuffer, bufferState);
      },
    );
 
    // 2) Chercher les fichiers de logs internes au container
    //    Priorité 1 : log_paths configurés en base (docker-file)
    //    Priorité 2 : auto-scan universel dans le container
    const serviceName = msg.containerId.split('.')[0];
 
    // Priorité 1 : log_paths en base
    const { rows: logPaths } = await db.query(
      `SELECT lp.path FROM log_paths lp
       JOIN servers s ON s.id = lp.server_id AND s.user_id = $1
       WHERE lp.type = 'docker-file' AND lp.path LIKE $2`,
      [ctx.userId, `${serviceName}:%`],
    );
 
    if (logPaths.length > 0) {
      const filePaths = logPaths.map((lp) => lp.path.split(':').slice(1).join(':'));
      startInternalLogTail({ ws, ctx, client, serviceName, filePaths, tail, flushBuffer, bufferState });
    } else {
      // Priorité 2 : auto-scan universel (tous les .log non-vides modifiés < 24h)
      autoScanAndTailLogs({ ws, ctx, client, safeContainer, serviceName, tail, flushBuffer, bufferState });
    }
 
    ws.send(JSON.stringify({ type: 'docker-logs-ready', containerId: msg.containerId }));
  } catch {
    ws.send(JSON.stringify({ type: 'error', message: 'Impossible de démarrer le streaming des logs.' }));
  }
}
 
/**
 * Gère l'abonnement au streaming de métriques (type: subscribe).
 */
async function handleMetricsSubscribe(ws, req, msg, ctx) {
  ctx.userId = authenticateWs(ws, req, msg.token);
  if (!ctx.userId) return;
 
  ctx.serverId = msg.serverId;
  if (!ctx.serverId) {
    ws.send(JSON.stringify({ type: 'error', message: 'serverId requis.' }));
    return;
  }
 
  const hasAccess = await verifyServerAccess(ws, ctx.userId, ctx.serverId, msg.groupId, 'dashboard', 'read');
  if (!hasAccess) {
    ws.close();
    return;
  }
 
  const push = async () => {
    if (ws.readyState !== OPEN) return;
    try {
      const data = await fetchMetrics(ctx.userId, ctx.serverId);
      ws.send(JSON.stringify({ type: 'metrics', data }));
    } catch {
      // Erreur SSH — message générique (pas de fuite d'info)
      ws.send(JSON.stringify({ type: 'error', message: 'Erreur de collecte des métriques.' }));
    }
  };
 
  // Envoi immédiat puis toutes les 5 secondes
  push();
  ctx.interval = setInterval(push, 5000);
}
 
// ─── Serveur WebSocket ───────────────────────────────────────────────────────
 
/**
 * Attache un serveur WebSocket à une instance http.Server.
 *
 * @param {import('http').Server} httpServer
 * @returns {import('ws').WebSocketServer}
 */
function createWebSocketServer(httpServer) {
  const wss = new WebSocketServer({ server: httpServer, path: '/ws' });
 
  wss.on('connection', (ws, req) => {
    // ─── Rate limiting ─────────────────────────────────────────────────
    const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket.remoteAddress;
    if (!checkWsRateLimit(ip)) {
      ws.send(JSON.stringify({ type: 'error', message: 'Trop de connexions.' }));
      ws.close();
      return;
    }
 
    // Contexte mutable partagé entre les handlers de cette connexion
    const ctx = {
      interval: null,
      userId: null,
      serverId: null,
      sshStream: null,
      dockerLogStreams: [],
    };
 
    ws.on('message', async (raw) => {
      // Terminal : données binaires ou texte brut (stdin)
      if (ctx.sshStream && !raw.toString().startsWith('{')) {
        ctx.sshStream.write(raw.toString());
        return;
      }
 
      let msg;
      try {
        msg = JSON.parse(raw.toString());
      } catch {
        // Si un shell est ouvert, envoyer en tant qu'input
        if (ctx.sshStream) { ctx.sshStream.write(raw.toString()); }
        return;
      }
 
      // Routage des messages vers les handlers dédiés
      switch (msg.type) {
        case 'terminal-open':
          await handleTerminalOpen(ws, req, msg, ctx, ip);
          break;
 
        case 'terminal-input':
          if (ctx.sshStream) ctx.sshStream.write(msg.data);
          break;
 
        case 'terminal-resize':
          if (ctx.sshStream) ctx.sshStream.setWindow(msg.rows || 24, msg.cols || 80, 0, 0);
          break;
 
        case 'terminal-close':
          handleTerminalClose(ctx, ip);
          break;
 
        case 'docker-logs-subscribe':
          await handleDockerLogsSubscribe(ws, req, msg, ctx);
          break;
 
        case 'docker-logs-unsubscribe':
          closeAllDockerLogStreams(ctx);
          break;
 
        case 'subscribe':
          await handleMetricsSubscribe(ws, req, msg, ctx);
          break;
 
        case 'unsubscribe':
          if (ctx.interval) {
            clearInterval(ctx.interval);
            ctx.interval = null;
          }
          break;
 
        default:
          break;
      }
    });
 
    // Nettoyage à la déconnexion
    ws.on('close', () => cleanupConnection(ctx));
    ws.on('error', () => cleanupConnection(ctx));
  });
 
  return wss;
}
 
module.exports = { createWebSocketServer };