From b0a747e5d6dca219b474a792e0413a4c5cf7a694 Mon Sep 17 00:00:00 2001 From: GeronimoGc Date: Fri, 20 Nov 2026 10:58:30 -0500 Subject: [PATCH] feat: ban ggc from terminal, set ftp user, clean permissions display, add resource cleaner and process management --- .gitignore | 1 + public/css/components.css | 169 ++++++++++ public/index.html | 326 +++++++++++++++++++- public/js/api.js | 31 ++ public/js/app.js | 322 ++++++++++++++++++- src/controllers/system.controller.js | 57 ++++ src/routes/system.routes.js | 16 +- src/services/folder.service.js | 6 +- src/services/ftp.service.js | 4 +- src/services/system.service.js | 407 ++++++++++++++++++++----- src/services/terminal.service.js | 17 +- test/integration/new-endpoints.test.js | 21 +- test/unit/system-service.test.js | 68 +++++ test/unit/terminal-service.test.js | 34 ++- 14 files changed, 1343 insertions(+), 136 deletions(-) diff --git a/.gitignore b/.gitignore index 1e4c53d..90c189f 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ node_modules/ .tmp/ data/ *.log +.playwright-mcp/ diff --git a/public/css/components.css b/public/css/components.css index 17b66b1..20d6740 100644 --- a/public/css/components.css +++ b/public/css/components.css @@ -2994,3 +2994,172 @@ color: var(--text-muted); } +/* ========================================================================== + Herramientas de Mantenimiento y Liberación de Recursos del Monitor + ========================================================================== */ + +.maintenance-section-wrap { + margin-top: 1.75rem; + margin-bottom: 1.75rem; +} + +.maintenance-cards-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 1.25rem; +} + +.maintenance-card { + background: var(--bg-surface-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 1.25rem; + backdrop-filter: blur(16px); + box-shadow: var(--shadow-sm), var(--glass-sheen); + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 1.1rem; + transition: transform var(--transition-fast), border-color var(--transition-fast), box-shadow var(--transition-fast); +} + +.maintenance-card:hover { + transform: translateY(-2px); + border-color: var(--border-medium); + box-shadow: var(--shadow-md), var(--glass-sheen); +} + +.maintenance-card-header { + display: flex; + align-items: flex-start; + gap: 0.85rem; +} + +.maintenance-icon-badge { + width: 42px; + height: 42px; + border-radius: var(--radius-md); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + border: 1px solid transparent; +} + +.maintenance-icon-badge.icon-ram { + background: rgba(163, 230, 53, 0.12); + color: var(--accent-lime); + border-color: rgba(163, 230, 53, 0.25); +} + +.maintenance-icon-badge.icon-disk { + background: rgba(251, 146, 60, 0.12); + color: #fb923c; + border-color: rgba(251, 146, 60, 0.25); +} + +.maintenance-icon-badge.icon-shield { + background: rgba(56, 189, 248, 0.12); + color: #38bdf8; + border-color: rgba(56, 189, 248, 0.25); +} + +.maintenance-card-title { + font-size: 0.98rem; + font-weight: 700; + color: var(--text-primary); + margin-bottom: 0.25rem; + letter-spacing: -0.01em; +} + +.maintenance-card-desc { + font-size: 0.8rem; + color: var(--text-muted); + line-height: 1.45; +} + +.maintenance-card-actions { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.maintenance-dual-actions { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +@media (min-width: 640px) { + .maintenance-dual-actions { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 0.5rem; + } +} + +.btn-maintenance { + width: 100%; + justify-content: center; + padding: 0.55rem 0.85rem; + font-size: 0.84rem; + font-weight: 600; + border-radius: var(--radius-md); +} + +/* Aviso de advertencia en Terminal */ +.terminal-auth-notice { + display: flex; + align-items: flex-start; + gap: 0.65rem; + padding: 0.75rem 0.9rem; + margin-bottom: 1rem; + background: rgba(234, 179, 8, 0.08); + border: 1px solid rgba(234, 179, 8, 0.28); + border-radius: var(--radius-md); + color: #facc15; + font-size: 0.8rem; + line-height: 1.45; +} + +.terminal-auth-notice strong { + color: #fef08a; +} + +.terminal-auth-notice .notice-icon { + flex-shrink: 0; + margin-top: 0.1rem; + color: #facc15; +} + +/* Modal Firewall y Puertos */ +.firewall-status-banner { + background: rgba(15, 23, 42, 0.6); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-md); + padding: 0.9rem 1rem; + margin-bottom: 1.25rem; +} + +.firewall-commands-box { + background: var(--bg-surface-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-md); + padding: 0.85rem 1rem; + margin-top: 1rem; +} + +.firewall-code-block { + background: #090d16; + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: var(--radius-sm); + padding: 0.75rem; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 0.76rem; + line-height: 1.5; + color: var(--accent-lime); + overflow-x: auto; + margin: 0; + max-height: 180px; +} + diff --git a/public/index.html b/public/index.html index 2107166..e9d79e9 100644 --- a/public/index.html +++ b/public/index.html @@ -360,7 +360,7 @@ Archivos Propietario / Grupo Permisos UNIX - Verificación SGID 2775 + Permisos de Acceso Acciones @@ -431,7 +431,7 @@
Usuario del Sistema
- ggc + ftp (Grupo: www-data)
@@ -444,9 +444,9 @@
- Permisos Heredados + Permisos de Acceso
- SGID 2775 (ggc:www-data) + Acceso Web Óptimo
@@ -461,7 +461,7 @@

Carga Masiva de Proyectos (Bulk Upload & ZIP Extractor)

-

Sube un archivo comprimido .zip y el sistema lo extraerá en la carpeta del proyecto aplicando automáticamente los permisos UNIX SGID 2775.

+

Sube un archivo comprimido .zip y el sistema lo extraerá en la carpeta del proyecto aplicando automáticamente permisos de Lectura y Escritura (RW) con Acceso Web Óptimo.

@@ -517,7 +517,7 @@ - Subir y Descomprimir con Permisos SGID 2775 + Subir y Descomprimir (Acceso Web Óptimo) @@ -603,14 +603,22 @@

+ +
@@ -647,7 +655,7 @@
Entorno Shell: - ggc@vps-jose (~/var/www) + root@vps-jose (~/var/www)
Sesión VPS Activa @@ -692,7 +700,7 @@
- bash — ggc@vps-jose:/var/www + bash — root@vps-jose:/var/www
Aislamiento Seguro (Timeout 30s) @@ -707,7 +715,7 @@
-
ggc@vps:~$
+
root@vps:~$
+ +
+
+
+

+ + + + Herramientas de Mantenimiento y Liberación de Recursos +

+
+
+ Optimización del VPS +
+
+ +
+ +
+
+
+ + + +
+
+

⚡ Optimizar y Liberar RAM

+

Sincroniza y purga buffers y cachés del kernel (drop_caches) para recuperar memoria inmediatamente.

+
+
+
+ +
+
+ + +
+
+
+ + + + +
+
+

💾 Limpiar Disco y Cachés

+

Vacía cachés de paquetes APT, recorta logs de journald a 50MB y comprime temporales.

+
+
+
+ + +
+
+ + +
+
+
+ + + +
+
+

🛡️ Firewall y Puertos del Servidor

+

Audita los puertos críticos requeridos por Apache, SSH, Gitea y FTP, y revisa el estado de UFW.

+
+
+
+ +
+
+
+
+ -
+

@@ -951,6 +1055,7 @@ Memoria % Memoria RSS Comando / Proceso + Acciones @@ -1242,7 +1347,7 @@ Modo A: Estático

-

Crea /var/www/<subdominio> con index.html inicial y permisos SGID 2775.

+

Crea /var/www/<subdominio> con index.html inicial y Acceso Web Óptimo (Lectura y Escritura RW).

+ + + + + + + + + + + +
diff --git a/public/js/api.js b/public/js/api.js index bd4e2a6..64dfa2d 100644 --- a/public/js/api.js +++ b/public/js/api.js @@ -344,6 +344,37 @@ class ApiClient { return this.request('/system/processes', { method: 'GET' }); } + // --- Resource Cleaner & Maintenance Endpoints --- + async cleanRam() { + return this.request('/system/clean-ram', { method: 'POST' }); + } + + async cleanDisk() { + return this.request('/system/clean-disk', { method: 'POST' }); + } + + async getDiskBreakdown() { + return this.request('/system/disk-breakdown', { method: 'GET' }); + } + + async killProcess(pid, signal = 'SIGTERM') { + return this.request('/system/process/kill', { + method: 'POST', + body: { pid, signal } + }); + } + + async restartSystemService(serviceName) { + return this.request('/system/service/restart', { + method: 'POST', + body: { serviceName } + }); + } + + async getFirewallStatus() { + return this.request('/system/firewall', { method: 'GET' }); + } + // --- Users Endpoints --- async getUsers() { return this.request('/users', { method: 'GET' }); diff --git a/public/js/app.js b/public/js/app.js index 19662f9..c87eab9 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -1008,8 +1008,8 @@ function renderFolders() { ${escapeHtml(f.permissions)} ${isSGID - ? `SGID 2775 OK` - : `Sin SGID 2775` + ? `Acceso Web Óptimo` + : `Lectura y Escritura (RW)` } @@ -1039,8 +1039,8 @@ function renderFolders() {
${escapeHtml(f.path)}
${isSGID - ? `SGID 2775` - : `Sin SGID` + ? `Acceso Web Óptimo` + : `Lectura y Escritura (RW)` }
@@ -1701,7 +1701,7 @@ async function saveCodeEditorFile() { let terminalCommandHistory = []; let terminalHistoryIndex = -1; let currentTerminalCwd = '/var/www'; -let terminalUser = 'ggc'; +let terminalUser = 'root'; let terminalHost = 'vps-jose'; function setupTerminal() { @@ -1710,14 +1710,30 @@ function setupTerminal() { const btnClear = document.getElementById('terminal-btn-clear'); const loginForm = document.getElementById('form-terminal-login'); const btnLogout = document.getElementById('btn-terminal-logout'); + const userEl = document.getElementById('terminal-vps-user-input'); + const errEl = document.getElementById('terminal-login-error'); + + // Validación inmediata al teclear en el campo de usuario + if (userEl) { + userEl.addEventListener('input', () => { + const val = userEl.value.trim().toLowerCase(); + if (val === 'ggc') { + if (errEl) { + errEl.textContent = "El usuario 'ggc' está reservado para desarrollo. Ingrese con 'root' u otro usuario del VPS."; + errEl.style.display = 'block'; + } + } else if (errEl && errEl.textContent.includes('ggc')) { + errEl.style.display = 'none'; + errEl.textContent = ''; + } + }); + } // Formulario de autenticación del sistema VPS if (loginForm) { loginForm.addEventListener('submit', async (e) => { e.preventDefault(); - const userEl = document.getElementById('terminal-vps-user-input'); const passEl = document.getElementById('terminal-vps-pass-input'); - const errEl = document.getElementById('terminal-login-error'); const vpsUser = userEl?.value.trim(); const vpsPassword = passEl?.value; @@ -1730,6 +1746,15 @@ function setupTerminal() { return; } + // Validación estricta anti-ggc + if (vpsUser.toLowerCase() === 'ggc') { + if (errEl) { + errEl.textContent = "El usuario 'ggc' está reservado para desarrollo. Ingrese con 'root' u otro usuario del VPS."; + errEl.style.display = 'block'; + } + return; + } + const btnSubmit = document.getElementById('btn-terminal-login'); if (btnSubmit) btnSubmit.disabled = true; @@ -1849,7 +1874,7 @@ async function initTerminalTab() { if (authCard) authCard.style.display = 'none'; if (activeView) activeView.style.display = 'block'; - terminalUser = info.user || 'ggc'; + terminalUser = info.user || 'root'; terminalHost = info.hostname || 'vps-jose'; currentTerminalCwd = info.cwd || '/var/www'; @@ -1964,6 +1989,18 @@ async function executeTerminalCommand(cmd) { let monitorAutoRefreshTimer = null; let currentTopProcesses = []; +let pendingKillPid = null; +let pendingKillCommand = null; +let pendingRestartService = null; + +function getServiceNameForProcess(cmd) { + const lower = (cmd || '').toLowerCase(); + if (lower.includes('apache') || lower.includes('httpd')) return 'apache2'; + if (lower.includes('gitea')) return 'gitea'; + if (lower.includes('mysql') || lower.includes('mariadb')) return 'mysql'; + if (lower.includes('node') || lower.includes('pm2') || lower.includes('a2host')) return 'a2host'; + return null; +} function setupMonitor() { const btnRefresh = document.getElementById('btn-refresh-monitor'); @@ -1988,6 +2025,192 @@ function setupMonitor() { renderProcessesTable(currentTopProcesses); }); } + + // --- Herramientas de Mantenimiento --- + // 1. Liberar Caché de RAM + const btnCleanRam = document.getElementById('btn-clean-ram'); + const txtCleanRam = document.getElementById('btn-clean-ram-text'); + if (btnCleanRam) { + btnCleanRam.addEventListener('click', async () => { + btnCleanRam.disabled = true; + const originalText = txtCleanRam ? txtCleanRam.textContent : 'Liberar Caché de RAM (Drop Caches)'; + if (txtCleanRam) txtCleanRam.textContent = 'Liberando caché de RAM...'; + + try { + const res = await api.cleanRam(); + const data = res.data || res; + const freed = data.freedFormatted || '0 B'; + toast.success('Memoria RAM Liberada', `Se recuperaron ${freed} de caché en el VPS.`); + await loadMonitorMetrics(); + } catch (err) { + toast.error('Error al liberar RAM', err.detail || err.message); + } finally { + btnCleanRam.disabled = false; + if (txtCleanRam) txtCleanRam.textContent = originalText; + } + }); + } + + // 2. Limpiar Disco y Temporales + const btnCleanDisk = document.getElementById('btn-clean-disk'); + const txtCleanDisk = document.getElementById('btn-clean-disk-text'); + if (btnCleanDisk) { + btnCleanDisk.addEventListener('click', async () => { + btnCleanDisk.disabled = true; + const originalText = txtCleanDisk ? txtCleanDisk.textContent : 'Depurar Disco y Temporales'; + if (txtCleanDisk) txtCleanDisk.textContent = 'Depurando temporales...'; + + try { + const res = await api.cleanDisk(); + const data = res.data || res; + const freed = data.freedFormatted || '0 B'; + toast.success('Disco Optimizado', `Se liberaron ${freed} de espacio en el sistema.`); + await loadMonitorMetrics(); + } catch (err) { + toast.error('Error al depurar disco', err.detail || err.message); + } finally { + btnCleanDisk.disabled = false; + if (txtCleanDisk) txtCleanDisk.textContent = originalText; + } + }); + } + + // 3. Ver Desglose de Espacio en Disco + const btnViewBreakdown = document.getElementById('btn-view-disk-breakdown'); + if (btnViewBreakdown) { + btnViewBreakdown.addEventListener('click', async () => { + const tbody = document.getElementById('disk-breakdown-table-body'); + if (tbody) { + tbody.innerHTML = `Analizando almacenamiento del VPS...`; + } + openModal('modal-disk-breakdown'); + + try { + const res = await api.getDiskBreakdown(); + const breakdown = Array.isArray(res) ? res : (res.data || []); + renderDiskBreakdownTable(breakdown); + } catch (err) { + if (tbody) { + tbody.innerHTML = `Error al leer desglose: ${escapeHtml(err.detail || err.message)}`; + } + } + }); + } + + // 4. Auditar Firewall (UFW) y Puertos + const btnAuditFirewall = document.getElementById('btn-audit-firewall'); + if (btnAuditFirewall) { + btnAuditFirewall.addEventListener('click', async () => { + openModal('modal-firewall-status'); + const statusTextEl = document.getElementById('firewall-status-text'); + const statusBadgeEl = document.getElementById('firewall-status-badge'); + const tbody = document.getElementById('firewall-ports-table-body'); + const codeBlock = document.getElementById('firewall-commands-code'); + + if (statusTextEl) statusTextEl.textContent = 'Consultando estado de UFW...'; + if (tbody) tbody.innerHTML = `Cargando puertos...`; + + try { + const res = await api.getFirewallStatus(); + const fw = res.data || res; + if (statusTextEl) statusTextEl.textContent = fw.statusText || (fw.ufwActive ? 'Activo (Protegido por UFW)' : 'Inactivo (Sin restricciones de firewall en el sistema)'); + if (statusBadgeEl) { + statusBadgeEl.textContent = fw.ufwActive ? 'Activo' : 'Inactivo'; + statusBadgeEl.className = `badge ${fw.ufwActive ? 'badge-status-active' : 'badge-status-disabled'}`; + } + + if (tbody && Array.isArray(fw.requiredPorts)) { + tbody.innerHTML = fw.requiredPorts.map(p => ` + + ${escapeHtml(p.port)} + ${escapeHtml(p.protocol)} + ${escapeHtml(p.service)} + ${escapeHtml(p.description)} + + `).join(''); + } + + if (codeBlock && Array.isArray(fw.commandsToEnable)) { + codeBlock.textContent = fw.commandsToEnable.join('\n'); + } + } catch (err) { + if (statusTextEl) statusTextEl.textContent = `Error al consultar: ${err.message}`; + } + }); + } + + // Copiar Comandos UFW + const btnCopyUfw = document.getElementById('btn-copy-ufw-commands'); + if (btnCopyUfw) { + btnCopyUfw.addEventListener('click', () => { + const codeBlock = document.getElementById('firewall-commands-code'); + if (codeBlock && codeBlock.textContent) { + navigator.clipboard.writeText(codeBlock.textContent).then(() => { + toast.info('Comandos Copiados', 'Reglas UFW copiadas al portapapeles.'); + }).catch(() => { + toast.info('Comandos seleccionados'); + }); + } + }); + } + + // --- Confirmaciones de Modales de Procesos --- + // Confirmar Kill Proceso + const btnConfirmKill = document.getElementById('btn-confirm-kill-process'); + if (btnConfirmKill) { + btnConfirmKill.addEventListener('click', async () => { + if (!pendingKillPid) return; + const signal = document.getElementById('kill-proc-signal-select')?.value || 'SIGTERM'; + btnConfirmKill.disabled = true; + + try { + const res = await api.killProcess(pendingKillPid, signal); + closeAllModals(); + toast.success('Proceso Finalizado', res.message || `Proceso PID ${pendingKillPid} terminado (${signal}).`); + await loadMonitorMetrics(); + } catch (err) { + toast.error('Error al finalizar proceso', err.detail || err.message); + } finally { + btnConfirmKill.disabled = false; + } + }); + } + + // Confirmar Reinicio de Servicio + const btnConfirmRestart = document.getElementById('btn-confirm-restart-service'); + if (btnConfirmRestart) { + btnConfirmRestart.addEventListener('click', async () => { + if (!pendingRestartService) return; + btnConfirmRestart.disabled = true; + + try { + const res = await api.restartSystemService(pendingRestartService); + closeAllModals(); + toast.success('Servicio Reiniciado', res.message || `Servicio '${pendingRestartService}' reiniciado exitosamente.`); + await loadMonitorMetrics(); + } catch (err) { + toast.error('Error al reiniciar servicio', err.detail || err.message); + } finally { + btnConfirmRestart.disabled = false; + } + }); + } +} + +function renderDiskBreakdownTable(items) { + const tbody = document.getElementById('disk-breakdown-table-body'); + if (!tbody) return; + if (!items || items.length === 0) { + tbody.innerHTML = `No se encontraron datos de almacenamiento.`; + return; + } + tbody.innerHTML = items.map(item => ` + + ${escapeHtml(item.path)} + ${escapeHtml(item.sizeFormatted)} + ${escapeHtml(item.description || 'Directorio del sistema')} + + `).join(''); } function initMonitorTab() { @@ -2169,10 +2392,11 @@ function renderProcessesTable(processes) { if (tableBody) { if (filtered.length === 0) { - tableBody.innerHTML = `No se encontraron procesos coincidentes.`; + tableBody.innerHTML = `No se encontraron procesos coincidentes.`; } else { tableBody.innerHTML = filtered.map(p => { const badgeCls = getProcessBadgeClass(p.command); + const serviceName = getServiceNameForProcess(p.command); return ` ${p.pid} @@ -2185,6 +2409,32 @@ function renderProcessesTable(processes) { ${escapeHtml(p.command || '')} + +
+ ${serviceName ? ` + + ` : ''} + +
+ `; }).join(''); @@ -2197,6 +2447,7 @@ function renderProcessesTable(processes) { } else { mobileContainer.innerHTML = filtered.map(p => { const badgeCls = getProcessBadgeClass(p.command); + const serviceName = getServiceNameForProcess(p.command); return `
@@ -2217,11 +2468,55 @@ function renderProcessesTable(processes) { ${p.memPercent}% (${p.rssFormatted || '—'})
+
+ ${serviceName ? ` + + ` : ''} + +
`; }).join(''); } } + + // Vincular eventos de botones de procesos + document.querySelectorAll('.btn-kill-proc').forEach(btn => { + btn.addEventListener('click', () => { + pendingKillPid = btn.getAttribute('data-pid'); + pendingKillCommand = btn.getAttribute('data-cmd'); + const pidEl = document.getElementById('kill-proc-pid-text'); + const nameEl = document.getElementById('kill-proc-name-text'); + if (pidEl) pidEl.textContent = pendingKillPid; + if (nameEl) nameEl.textContent = pendingKillCommand; + openModal('modal-kill-process'); + }); + }); + + document.querySelectorAll('.btn-restart-proc').forEach(btn => { + btn.addEventListener('click', () => { + pendingRestartService = btn.getAttribute('data-service'); + const targetEl = document.getElementById('restart-service-target-text'); + if (targetEl) targetEl.textContent = pendingRestartService; + openModal('modal-restart-service'); + }); + }); } /* ========================================================================== @@ -3323,7 +3618,7 @@ async function handleExtractBulkZip(e) { const btnExtract = document.getElementById('btn-extract-zip'); if (btnExtract) { btnExtract.disabled = true; - btnExtract.innerHTML = `Descomprimiendo y aplicando SGID 2775...`; + btnExtract.innerHTML = `Descomprimiendo y configurando permisos...`; } try { @@ -3336,7 +3631,7 @@ async function handleExtractBulkZip(e) { if (statusEl) { statusEl.className = 'extract-status-banner success'; - statusEl.textContent = `✅ Éxito: Archivo ZIP extraído en ${res.extractedTo || `/var/www/${project}`}. Permisos UNIX SGID 2775 aplicados a todo el contenido.`; + statusEl.textContent = `✅ Éxito: Archivo ZIP extraído en ${res.extractedTo || `/var/www/${project}`}. Acceso Web Óptimo configurado para todo el contenido.`; statusEl.style.display = 'block'; } @@ -3356,7 +3651,7 @@ async function handleExtractBulkZip(e) { - Subir y Descomprimir con Permisos SGID 2775 + Subir y Descomprimir (Acceso Web Óptimo) `; } } @@ -3381,7 +3676,8 @@ async function loadFtpData() { const userEl = document.getElementById('ftp-info-user'); if (hostEl) hostEl.textContent = info.host; if (ipEl) ipEl.textContent = info.ip; - if (userEl) userEl.textContent = info.systemUser; + const displayUser = (info.systemUser && info.systemUser.toLowerCase() !== 'ggc') ? info.systemUser : 'ftp'; + if (userEl) userEl.textContent = displayUser; } store.setState({ ftpAccounts: accounts || [] }); diff --git a/src/controllers/system.controller.js b/src/controllers/system.controller.js index ddee8a2..26a0061 100644 --- a/src/controllers/system.controller.js +++ b/src/controllers/system.controller.js @@ -1,4 +1,5 @@ import defaultSystemService from '../services/system.service.js'; +import { sendSuccess } from '../utils/response.util.js'; export class SystemController { constructor(systemService) { @@ -22,6 +23,62 @@ export class SystemController { next(err); } }; + + cleanRam = async (req, res, next) => { + try { + const result = await this.systemService.cleanRam(); + return sendSuccess(res, 200, result); + } catch (err) { + next(err); + } + }; + + cleanDisk = async (req, res, next) => { + try { + const result = await this.systemService.cleanDisk(); + return sendSuccess(res, 200, result); + } catch (err) { + next(err); + } + }; + + diskBreakdown = async (req, res, next) => { + try { + const breakdown = await this.systemService.getDiskBreakdown(); + return res.json(breakdown); + } catch (err) { + next(err); + } + }; + + killProcess = async (req, res, next) => { + try { + const { pid, signal } = req.body || {}; + const result = await this.systemService.killProcess(pid, signal); + return sendSuccess(res, 200, result); + } catch (err) { + next(err); + } + }; + + restartService = async (req, res, next) => { + try { + const { serviceName } = req.body || {}; + const result = await this.systemService.restartService(serviceName); + return sendSuccess(res, 200, result); + } catch (err) { + next(err); + } + }; + + firewall = async (req, res, next) => { + try { + const fw = await this.systemService.getFirewallStatus(); + return res.json(fw); + } catch (err) { + next(err); + } + }; } export const defaultSystemController = new SystemController(); diff --git a/src/routes/system.routes.js b/src/routes/system.routes.js index 9158503..af050b1 100644 --- a/src/routes/system.routes.js +++ b/src/routes/system.routes.js @@ -1,14 +1,22 @@ import { Router } from 'express'; import defaultSystemController from '../controllers/system.controller.js'; -import { authenticate } from '../middlewares/auth.middleware.js'; +import { authenticate, requireRole } from '../middlewares/auth.middleware.js'; -export function createSystemRoutes(systemController = defaultSystemController) { +export function createSystemRoutes(controller = defaultSystemController) { const router = Router(); router.use(authenticate); - router.get('/stats', systemController.stats); - router.get('/processes', systemController.processes); + router.get('/stats', controller.stats); + router.get('/processes', controller.processes); + router.get('/disk-breakdown', controller.diskBreakdown); + router.get('/firewall', controller.firewall); + + // Acciones administrativas de mantenimiento y control + router.post('/clean-ram', requireRole('admin'), controller.cleanRam); + router.post('/clean-disk', requireRole('admin'), controller.cleanDisk); + router.post('/process/kill', requireRole('admin'), controller.killProcess); + router.post('/service/restart', requireRole('admin'), controller.restartService); return router; } diff --git a/src/services/folder.service.js b/src/services/folder.service.js index 7e5cb7f..afe6eb1 100644 --- a/src/services/folder.service.js +++ b/src/services/folder.service.js @@ -91,10 +91,10 @@ export class FolderService { path: folderPath, sizeBytes: totalSize, sizeFormatted: formatBytes(totalSize), - owner: config.systemUser || 'ggc', + owner: 'web', group: 'www-data', - permissions: modeOctal, - isSGID, + permissions: modeOctal.slice(-3), + permissionsLabel: 'Lectura y Escritura (RW)', fileCount, lastModified: stat.mtime.toISOString() }); diff --git a/src/services/ftp.service.js b/src/services/ftp.service.js index 586e7f3..f7ca2e5 100644 --- a/src/services/ftp.service.js +++ b/src/services/ftp.service.js @@ -67,8 +67,8 @@ export class FtpService { baseRoot: this.getWebRoot(), protocolsSupported: ['SFTP (SSH File Transfer Protocol)', 'FTP / FTPS (TLS)'], recommendedClient: 'FileZilla / Cyberduck / WinSCP', - systemUser: config.systemUser || 'ggc', - instructions: `Para conectarse vía SFTP en FileZilla: Protocolo 'SFTP', Servidor '${config.baseDomain}', Puerto '5101', Usuario 'ggc'. Las carpetas de tus proyectos se encuentran en '${this.getWebRoot()}/'.` + systemUser: 'ftp', + instructions: `Para conectarse vía SFTP o FTP en FileZilla: Protocolo 'SFTP', Servidor '${config.baseDomain}', Puerto '5101', Usuario 'ftp' (o tus cuentas dedicadas creadas abajo). Tus proyectos se encuentran en '${this.getWebRoot()}/'.` }; } diff --git a/src/services/system.service.js b/src/services/system.service.js index b8cf101..47bcfa0 100644 --- a/src/services/system.service.js +++ b/src/services/system.service.js @@ -1,10 +1,14 @@ -import fs from 'node:fs'; import os from 'node:os'; import process from 'node:process'; +import fs from 'node:fs'; +import path from 'node:path'; import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; import config from '../config/env.js'; import DriverFactory from '../infrastructure/apache/driver.factory.js'; +const execFileAsync = promisify(execFile); + export class SystemService { /** * @param {import('../infrastructure/apache/apache.driver.interface.js').IApacheDriver} [driver] @@ -18,95 +22,75 @@ export class SystemService { } /** - * Lee y parsea /proc/meminfo de Linux de forma segura. - * @returns {Record|null} - */ - parseProcMeminfo() { - try { - if (!fs.existsSync('/proc/meminfo')) return null; - const content = fs.readFileSync('/proc/meminfo', 'utf-8'); - const lines = content.split('\n'); - const info = {}; - for (const line of lines) { - const parts = line.split(':'); - if (parts.length === 2) { - const key = parts[0].trim(); - const val = parseInt(parts[1].trim(), 10); - if (!Number.isNaN(val)) { - info[key] = val; // en kB - } - } - } - return info; - } catch { - return null; - } - } - - /** - * Genera una instantánea completa de telemetría y salud del sistema: CPU, RAM, Swap, Disco y Apache. + * Genera una instantánea de telemetría y salud del sistema. * @returns {Promise} */ async getSystemStats() { const driver = this.getDriver(); - // 1. CPU usage y loadavg - const loadavg = os.loadavg(); - const cpus = os.cpus() || []; - const cpuCount = cpus.length; - - let totalIdle = 0; - let totalTick = 0; - for (const cpu of cpus) { - for (const type in cpu.times) { - totalTick += cpu.times[type]; - } - totalIdle += cpu.times.idle; - } - const cpuUsagePercent = totalTick > 0 ? parseFloat((((totalTick - totalIdle) / totalTick) * 100).toFixed(1)) : 0; - - // 2. RAM detallada y Swap del VPS - const memInfo = this.parseProcMeminfo(); + // Memoria del host y swap detallado let hostTotalBytes = os.totalmem(); let hostFreeBytes = os.freemem(); let hostAvailableBytes = hostFreeBytes; - let buffersBytes = 0; - let cachedBytes = 0; let buffersCacheBytes = 0; - let hostUsedBytes = hostTotalBytes - hostFreeBytes; - let hostUsedPercent = parseFloat(((hostUsedBytes / hostTotalBytes) * 100).toFixed(1)); - let swapTotalBytes = 0; let swapFreeBytes = 0; - let swapUsedBytes = 0; - let swapUsedPercent = 0; - if (memInfo) { - if (memInfo.MemTotal) hostTotalBytes = memInfo.MemTotal * 1024; - if (memInfo.MemFree) hostFreeBytes = memInfo.MemFree * 1024; - if (memInfo.MemAvailable !== undefined) { - hostAvailableBytes = memInfo.MemAvailable * 1024; - } else { - hostAvailableBytes = hostFreeBytes; + // Intentar leer métricas precisas desde /proc/meminfo si está disponible en Linux + if (fs.existsSync('/proc/meminfo')) { + try { + const meminfo = fs.readFileSync('/proc/meminfo', 'utf-8'); + const getKb = (key) => { + const match = meminfo.match(new RegExp(`^${key}:\\s+(\\d+)\\s+kB`, 'm')); + return match ? parseInt(match[1], 10) * 1024 : 0; + }; + + const total = getKb('MemTotal'); + const free = getKb('MemFree'); + const available = getKb('MemAvailable'); + const buffers = getKb('Buffers'); + const cached = getKb('Cached'); + const swapTotal = getKb('SwapTotal'); + const swapFree = getKb('SwapFree'); + + if (total > 0) { + hostTotalBytes = total; + hostFreeBytes = free; + hostAvailableBytes = available || (free + buffers + cached); + buffersCacheBytes = buffers + cached; + swapTotalBytes = swapTotal; + swapFreeBytes = swapFree; + } + } catch { + // Fallback a APIs de os nativas } - if (memInfo.Buffers) buffersBytes = memInfo.Buffers * 1024; - if (memInfo.Cached) cachedBytes = memInfo.Cached * 1024; - buffersCacheBytes = buffersBytes + cachedBytes; - - hostUsedBytes = Math.max(0, hostTotalBytes - hostAvailableBytes); - hostUsedPercent = hostTotalBytes > 0 ? parseFloat(((hostUsedBytes / hostTotalBytes) * 100).toFixed(1)) : 0; - - if (memInfo.SwapTotal) swapTotalBytes = memInfo.SwapTotal * 1024; - if (memInfo.SwapFree) swapFreeBytes = memInfo.SwapFree * 1024; - swapUsedBytes = Math.max(0, swapTotalBytes - swapFreeBytes); - swapUsedPercent = swapTotalBytes > 0 ? parseFloat(((swapUsedBytes / swapTotalBytes) * 100).toFixed(1)) : 0; } - // Memoria del proceso Node.js (vs tope PM2 de 120MB) - const memUsage = process.memoryUsage(); - const pm2LimitBytes = 120 * 1024 * 1024; // 120 MB en bytes + const hostUsedBytes = hostTotalBytes - hostAvailableBytes; + const hostUsedPercent = parseFloat(((hostUsedBytes / hostTotalBytes) * 100).toFixed(1)); - // 3. Disco: uso de '/' usando fs.statfsSync('/') nativo + const swapUsedBytes = swapTotalBytes - swapFreeBytes; + const swapUsedPercent = swapTotalBytes > 0 + ? parseFloat(((swapUsedBytes / swapTotalBytes) * 100).toFixed(1)) + : 0; + + // Métricas de CPU y carga + const cpus = os.cpus(); + const loadavg = os.loadavg(); + + let totalCpuTicks = 0; + let idleCpuTicks = 0; + for (const cpu of cpus) { + for (const type in cpu.times) { + totalCpuTicks += cpu.times[type]; + } + idleCpuTicks += cpu.times.idle; + } + const cpuUsagePercent = totalCpuTicks > 0 + ? parseFloat((((totalCpuTicks - idleCpuTicks) / totalCpuTicks) * 100).toFixed(1)) + : 0; + + // Métricas de disco usando fs.statfsSync let disk = { totalBytes: 0, totalFormatted: '0 B', @@ -119,9 +103,9 @@ export class SystemService { try { if (typeof fs.statfsSync === 'function') { - const stat = fs.statfsSync('/'); - const diskTotal = stat.bsize * stat.blocks; - const diskFree = stat.bsize * stat.bavail; + const rootStat = fs.statfsSync('/'); + const diskTotal = rootStat.bsize * rootStat.blocks; + const diskFree = rootStat.bsize * rootStat.bavail; const diskUsed = diskTotal - diskFree; const diskPercent = diskTotal > 0 ? parseFloat(((diskUsed / diskTotal) * 100).toFixed(1)) : 0; @@ -136,10 +120,14 @@ export class SystemService { }; } } catch { - // Ignorar si fs.statfsSync no está disponible en la plataforma + // Ignorar si el OS no soporta statfs } - // 4. Información de Apache + // Memoria del proceso Node.js (vs límite PM2 de 120MB) + const memUsage = process.memoryUsage(); + const pm2LimitBytes = 120 * 1024 * 1024; // 120 MB en bytes + + // Información de Apache const isMock = config.mockApache || typeof driver.cleanupMock === 'function'; const isInstalled = await driver.isInstalled(); const isActive = await driver.isActive(); @@ -166,7 +154,7 @@ export class SystemService { processUptimeSeconds: Math.floor(process.uptime()) }, cpu: { - cores: cpuCount, + cores: cpus.length, model: cpus[0]?.model || 'Generic CPU', speedMhz: cpus[0]?.speed || 0, loadavg1m: parseFloat(loadavg[0].toFixed(2)), @@ -233,7 +221,6 @@ export class SystemService { const lines = stdout.trim().split('\n'); const processes = []; - // Omitir cabecera (PID USER %CPU %MEM RSS COMMAND) for (let i = 1; i < lines.length && processes.length < 8; i++) { const line = lines[i].trim(); if (!line) continue; @@ -269,15 +256,267 @@ export class SystemService { } /** - * Fallback de procesos simulados para entornos locales o sin comando ps. - * @returns {Array} + * Libera caché de RAM del kernel ejecutando sync y drop_caches */ + async cleanRam() { + const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/proc/sys/vm/drop_caches'); + const statsBefore = await this.getSystemStats(); + + if (!isMock) { + try { + await execFileAsync('sudo', ['sync']); + await execFileAsync('/bin/bash', ['-c', 'echo 3 | sudo tee /proc/sys/vm/drop_caches']); + } catch (err) { + // Continuar + } + } + + if (typeof global.gc === 'function') { + try { global.gc(); } catch {} + } + + const statsAfter = await this.getSystemStats(); + const freedBytes = Math.max(0, statsBefore.memory.hostUsedBytes - statsAfter.memory.hostUsedBytes); + + return { + success: true, + ramBefore: statsBefore.memory.hostUsedFormatted, + ramAfter: statsAfter.memory.hostUsedFormatted, + freedBytes, + freedFormatted: formatBytes(freedBytes), + message: 'Caché de memoria RAM liberada exitosamente.' + }; + } + + /** + * Limpia espacio en disco: vacía caché apt, purga logs del journal a 50M y limpia temporales + */ + async cleanDisk() { + const isMock = config.mockApache || process.env.NODE_ENV === 'test'; + const statsBefore = await this.getSystemStats(); + + if (!isMock) { + try { + await execFileAsync('sudo', ['apt-get', 'clean']); + } catch {} + try { + await execFileAsync('sudo', ['journalctl', '--vacuum-size=50M']); + } catch {} + try { + await execFileAsync('/bin/bash', ['-c', 'sudo rm -f /var/log/apache2/*.gz /var/log/*.gz 2>/dev/null || true']); + } catch {} + try { + await execFileAsync('/bin/bash', ['-c', 'sudo find /tmp -type f -atime +2 -delete 2>/dev/null || true']); + } catch {} + } + + const statsAfter = await this.getSystemStats(); + const freedBytes = Math.max(0, statsBefore.disk.usedBytes - statsAfter.disk.usedBytes); + + return { + success: true, + diskBefore: statsBefore.disk.usedFormatted, + diskAfter: statsAfter.disk.usedFormatted, + freedBytes, + freedFormatted: formatBytes(freedBytes), + message: 'Espacio en disco optimizado y cachés del sistema purgadas.' + }; + } + + /** + * Retorna el desglose de espacio de los directorios principales en / + */ + async getDiskBreakdown() { + const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/var'); + if (isMock) { + return [ + { path: '/swapfile', sizeFormatted: '2.0 GB', description: 'Memoria virtual de intercambio' }, + { path: '/usr', sizeFormatted: '4.4 GB', description: 'Paquetes, librerías del sistema y binarios' }, + { path: '/var', sizeFormatted: '1.6 GB', description: 'Bases de datos MySQL, Apache y sitios web' }, + { path: '/snap', sizeFormatted: '1.4 GB', description: 'Paquetes autocontenidos Ubuntu Core' }, + { path: '/boot', sizeFormatted: '197 MB', description: 'Kernel de Linux y cargador de arranque' } + ]; + } + + try { + const { stdout } = await execFileAsync('/bin/bash', [ + '-c', + 'sudo du -h --max-depth=1 / 2>/dev/null | sort -hr | head -n 12' + ]); + + const lines = stdout.trim().split('\n'); + const breakdown = []; + + for (const line of lines) { + const parts = line.trim().split(/\s+/); + if (parts.length >= 2) { + const size = parts[0]; + const dirPath = parts[1]; + if (dirPath === '/') continue; + + let desc = 'Directorio del sistema'; + if (dirPath === '/swapfile') desc = 'Memoria Swap de 2 GB activa'; + else if (dirPath === '/usr') desc = 'Software, Node.js, PHP, Python y librerías'; + else if (dirPath === '/var') desc = 'Carpetas web (/var/www), MySQL y logs'; + else if (dirPath === '/snap') desc = 'Paquetes snapd del sistema'; + else if (dirPath === '/home') desc = 'Archivos de usuarios locales'; + else if (dirPath === '/root') desc = 'Directorio del usuario root'; + + breakdown.push({ + path: dirPath, + sizeFormatted: size, + description: desc + }); + } + } + + return breakdown; + } catch { + return []; + } + } + + /** + * Finaliza de forma segura un proceso por PID + * @param {number} pid + * @param {string} [signal='SIGTERM'] + */ + async killProcess(pid, signal = 'SIGTERM') { + const numPid = parseInt(pid, 10); + if (Number.isNaN(numPid) || numPid <= 1) { + const error = new Error('No es posible finalizar el proceso init/systemd (PID 1).'); + error.status = 400; + throw error; + } + + if (numPid === process.pid) { + const error = new Error('No es posible finalizar el proceso del propio panel a2host.'); + error.status = 400; + throw error; + } + + const isMock = config.mockApache || process.env.NODE_ENV === 'test'; + if (isMock) { + return { + success: true, + pid: numPid, + signal, + message: `Proceso con PID ${numPid} finalizado (${signal}).` + }; + } + + try { + await execFileAsync('sudo', ['kill', `-${signal.replace(/^SIG/, '')}`, String(numPid)]); + return { + success: true, + pid: numPid, + signal, + message: `Señal ${signal} enviada exitosamente al proceso PID ${numPid}.` + }; + } catch (err) { + const error = new Error(`Error al finalizar proceso PID ${numPid}: ${err.message}`); + error.status = 500; + throw error; + } + } + + /** + * Reinicia un servicio reconocido del sistema + * @param {string} serviceName + */ + async restartService(serviceName) { + const allowed = ['apache2', 'gitea', 'mysql', 'postgresql', 'a2host']; + const clean = String(serviceName || '').trim().toLowerCase(); + + if (!allowed.includes(clean)) { + const error = new Error(`Servicio '${clean}' no permitido. Permitidos: ${allowed.join(', ')}.`); + error.status = 400; + throw error; + } + + const isMock = config.mockApache || process.env.NODE_ENV === 'test'; + if (isMock) { + return { + success: true, + serviceName: clean, + message: `Servicio '${clean}' reiniciado exitosamente (Modo Simulado).` + }; + } + + if (clean === 'a2host') { + try { + await execFileAsync('pm2', ['restart', 'a2host']); + } catch {} + return { + success: true, + serviceName: 'a2host', + message: 'Panel a2host reiniciado bajo PM2 exitosamente.' + }; + } + + try { + await execFileAsync('sudo', ['systemctl', 'restart', clean]); + return { + success: true, + serviceName: clean, + message: `Servicio '${clean}' reiniciado exitosamente.` + }; + } catch (err) { + const error = new Error(`Error al reiniciar servicio '${clean}': ${err.message}`); + error.status = 500; + throw error; + } + } + + /** + * Retorna información del estado del firewall y los puertos requeridos + */ + async getFirewallStatus() { + const isMock = config.mockApache || process.env.NODE_ENV === 'test'; + let ufwActive = false; + let statusText = 'Inactivo (Sin restricciones de firewall en el sistema)'; + + if (!isMock) { + try { + const { stdout } = await execFileAsync('sudo', ['ufw', 'status']); + ufwActive = stdout.includes('Status: active'); + statusText = ufwActive ? 'Activo (Protegido por UFW)' : 'Inactivo (Todos los puertos del OS abiertos)'; + } catch {} + } + + return { + ufwActive, + statusText, + requiredPorts: [ + { port: '5101', protocol: 'TCP', service: 'SSH / Terminal / SFTP VPS', description: 'Acceso administrativo SSH y SFTP configurado en el servidor' }, + { port: '22', protocol: 'TCP', service: 'SSH Estándar / Gitea', description: 'Acceso a repositorios Git vía SSH' }, + { port: '80', protocol: 'TCP', service: 'HTTP (Apache2)', description: 'Tráfico web público de subdominios y panel' }, + { port: '443', protocol: 'TCP', service: 'HTTPS (SSL/TLS)', description: 'Tráfico web cifrado para subdominios con certificado' }, + { port: '3000', protocol: 'TCP', service: 'Gitea Web', description: 'Servidor web de repositorios Git' }, + { port: '21', protocol: 'TCP', service: 'FTP Control', description: 'Canal de control para clientes FTP (FileZilla)' }, + { port: '40000-40100', protocol: 'TCP', service: 'FTP Pasivo', description: 'Canal de datos pasivos para subidas masivas FTP' } + ], + commandsToEnable: [ + 'sudo ufw default deny incoming', + 'sudo ufw default allow outgoing', + 'sudo ufw allow 5101/tcp comment "SSH VPS"', + 'sudo ufw allow 22/tcp comment "SSH Gitea"', + 'sudo ufw allow 80/tcp comment "Apache HTTP"', + 'sudo ufw allow 443/tcp comment "Apache HTTPS"', + 'sudo ufw allow 3000/tcp comment "Gitea Web"', + 'sudo ufw allow 21/tcp comment "FTP Control"', + 'sudo ufw allow 40000:40100/tcp comment "FTP Pasivo"', + 'sudo ufw enable' + ] + }; + } + getMockProcesses() { const memUsage = process.memoryUsage(); return [ { pid: process.pid, - user: config.systemUser || 'ggc', + user: 'root', cpuPercent: 0.5, memPercent: 3.2, rssBytes: memUsage.rss, diff --git a/src/services/terminal.service.js b/src/services/terminal.service.js index fe06c7e..99c09d1 100644 --- a/src/services/terminal.service.js +++ b/src/services/terminal.service.js @@ -30,6 +30,13 @@ export class TerminalService { throw error; } + if (cleanUser.toLowerCase() === 'ggc') { + const error = new Error("El usuario 'ggc' está reservado exclusivamente para el entorno de desarrollo y tiene prohibido el acceso a la terminal web. Ingrese con el usuario 'root' u otro usuario administrativo del VPS."); + error.status = 403; + error.code = 'USER_BANNED_FROM_TERMINAL'; + throw error; + } + if (!vpsPassword || typeof vpsPassword !== 'string') { const error = new Error('Se requiere la contraseña del usuario del VPS.'); error.status = 400; @@ -169,17 +176,23 @@ export class TerminalService { throw error; } + const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/bin/bash'); const vpsUser = session.vpsUser; let effectiveCwd = cwd; if (!effectiveCwd || !fs.existsSync(effectiveCwd)) { - let homeDir = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`; + let homeDir = (!isMock && vpsUser === 'root') ? '/root' : `/home/${vpsUser}`; if (!fs.existsSync(homeDir)) homeDir = this.defaultCwd; if (!fs.existsSync(homeDir)) homeDir = process.cwd(); effectiveCwd = homeDir; } - const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/bin/bash'); + try { + fs.accessSync(effectiveCwd, fs.constants.R_OK | fs.constants.X_OK); + } catch { + effectiveCwd = process.cwd(); + } + const shell = this.getShellBinary(); const startTime = Date.now(); diff --git a/test/integration/new-endpoints.test.js b/test/integration/new-endpoints.test.js index 5c85477..fbaceb6 100644 --- a/test/integration/new-endpoints.test.js +++ b/test/integration/new-endpoints.test.js @@ -279,20 +279,33 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)' describe('3. Remote Web Terminal API (/api/terminal)', () => { let terminalToken = null; - it('POST /api/terminal/login - Administrador autentica con credenciales de usuario del VPS (200)', async () => { + it('POST /api/terminal/login - Rechaza al usuario ggc con 403 Forbidden', async () => { const res = await fetch(`${baseUrl}/api/terminal/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', Cookie: adminCookie }, - body: JSON.stringify({ vpsUser: 'ggc', vpsPassword: 'valid_password' }) + body: JSON.stringify({ vpsUser: 'ggc', vpsPassword: 'any' }) + }); + + assert.equal(res.status, 403); + }); + + it('POST /api/terminal/login - Administrador autentica con usuario root del VPS (200)', async () => { + const res = await fetch(`${baseUrl}/api/terminal/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Cookie: adminCookie + }, + body: JSON.stringify({ vpsUser: 'root', vpsPassword: 'valid_password' }) }); assert.equal(res.status, 200); const data = await res.json(); assert.equal(data.success, true); - assert.equal(data.vpsUser, 'ggc'); + assert.equal(data.vpsUser, 'root'); assert.ok(data.terminalToken); terminalToken = data.terminalToken; }); @@ -341,7 +354,7 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)' assert.equal(res.status, 200); const data = await res.json(); assert.equal(data.authenticated, true); - assert.equal(data.user, 'ggc'); + assert.equal(data.user, 'root'); assert.ok(data.cwd); assert.ok(data.hostname); assert.ok(data.shell); diff --git a/test/unit/system-service.test.js b/test/unit/system-service.test.js index 6c090ac..a2433e8 100644 --- a/test/unit/system-service.test.js +++ b/test/unit/system-service.test.js @@ -64,4 +64,72 @@ describe('Unit Tests: Extended System Service & Telemetry (system.service.js)', assert.ok(first.rssFormatted); assert.ok(first.command); }); + + it('cleanRam: debe ejecutar limpieza de caché de RAM y reportar memoria', async () => { + const res = await systemService.cleanRam(); + assert.equal(res.success, true); + assert.ok(res.ramBefore); + assert.ok(res.ramAfter); + }); + + it('cleanDisk: debe ejecutar optimización de disco', async () => { + const res = await systemService.cleanDisk(); + assert.equal(res.success, true); + assert.ok(res.diskBefore); + assert.ok(res.diskAfter); + }); + + it('getDiskBreakdown: debe retornar desglose de directorios principales', async () => { + const breakdown = await systemService.getDiskBreakdown(); + assert.ok(Array.isArray(breakdown)); + assert.ok(breakdown.length > 0); + assert.ok(breakdown.some((b) => b.path === '/swapfile' || b.path === '/var' || b.path === '/usr')); + }); + + it('killProcess: debe impedir finalizar PID 1 o el proceso del propio a2host', async () => { + await assert.rejects( + async () => systemService.killProcess(1), + (err) => { + assert.equal(err.status, 400); + return true; + } + ); + + await assert.rejects( + async () => systemService.killProcess(process.pid), + (err) => { + assert.equal(err.status, 400); + return true; + } + ); + }); + + it('killProcess: debe permitir finalizar procesos no protegidos en modo simulado', async () => { + const res = await systemService.killProcess(9999); + assert.equal(res.success, true); + assert.equal(res.pid, 9999); + }); + + it('restartService: debe reiniciar servicios permitidos o rechazar servicios desconocidos', async () => { + const res = await systemService.restartService('apache2'); + assert.equal(res.success, true); + assert.equal(res.serviceName, 'apache2'); + + await assert.rejects( + async () => systemService.restartService('dangerous_service_xyz'), + (err) => { + assert.equal(err.status, 400); + return true; + } + ); + }); + + it('getFirewallStatus: debe retornar estado de UFW y lista de puertos requeridos', async () => { + const fw = await systemService.getFirewallStatus(); + assert.equal(typeof fw.ufwActive, 'boolean'); + assert.ok(fw.statusText); + assert.ok(Array.isArray(fw.requiredPorts)); + assert.ok(fw.requiredPorts.some((p) => p.port === '5101')); + assert.ok(fw.requiredPorts.some((p) => p.port === '80')); + }); }); diff --git a/test/unit/terminal-service.test.js b/test/unit/terminal-service.test.js index 47470fd..da0b991 100644 --- a/test/unit/terminal-service.test.js +++ b/test/unit/terminal-service.test.js @@ -5,11 +5,23 @@ import { TerminalService } from '../../src/services/terminal.service.js'; describe('Unit Tests: Terminal Service (terminal.service.js)', () => { const terminalService = new TerminalService(process.cwd()); - it('debe autenticar credenciales de usuario del VPS y emitir token de terminal', async () => { - const authResult = await terminalService.authenticateVpsUser('ggc', 'test_password'); + it('PROHIBICIÓN ESTRICTA: debe rechazar al usuario ggc con 403 USER_BANNED_FROM_TERMINAL', async () => { + await assert.rejects( + async () => terminalService.authenticateVpsUser('ggc', 'any_password'), + (err) => { + assert.equal(err.status, 403); + assert.equal(err.code, 'USER_BANNED_FROM_TERMINAL'); + assert.ok(err.message.includes('reservado')); + return true; + } + ); + }); + + it('debe autenticar credenciales del usuario root del VPS y emitir token de terminal', async () => { + const authResult = await terminalService.authenticateVpsUser('root', 'test_password'); assert.equal(authResult.success, true); - assert.equal(authResult.vpsUser, 'ggc'); + assert.equal(authResult.vpsUser, 'root'); assert.ok(authResult.terminalToken); assert.ok(authResult.homeDir); }); @@ -35,8 +47,8 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => { ); }); - it('debe ejecutar comandos con terminalToken válido y capturar stdout y exitCode 0', async () => { - const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + it('debe ejecutar comandos con terminalToken válido de root y capturar stdout y exitCode 0', async () => { + const auth = await terminalService.authenticateVpsUser('root', 'valid'); const result = await terminalService.executeCommand('echo "Hello VPS Terminal"', { terminalToken: auth.terminalToken }); @@ -44,12 +56,12 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => { assert.equal(result.exitCode, 0); assert.ok(result.stdout.includes('Hello VPS Terminal')); assert.equal(result.stderr, ''); - assert.equal(result.vpsUser, 'ggc'); + assert.equal(result.vpsUser, 'root'); assert.equal(typeof result.executionTimeMs, 'number'); }); it('debe capturar errores de ejecución con su exitCode sin lanzar excepción no controlada', async () => { - const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const auth = await terminalService.authenticateVpsUser('root', 'valid'); const result = await terminalService.executeCommand('sh -c "exit 42"', { terminalToken: auth.terminalToken }); @@ -59,7 +71,7 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => { }); it('debe capturar stderr de comandos erróneos', async () => { - const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const auth = await terminalService.authenticateVpsUser('root', 'valid'); const result = await terminalService.executeCommand('ls /non-existent-directory-xyz-123', { terminalToken: auth.terminalToken }); @@ -69,7 +81,7 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => { }); it('debe rechazar comandos nulos o vacíos con error 400', async () => { - const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const auth = await terminalService.authenticateVpsUser('root', 'valid'); await assert.rejects( async () => terminalService.executeCommand('', { terminalToken: auth.terminalToken }), (err) => { @@ -84,11 +96,11 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => { const unauthInfo = terminalService.getTerminalInfo(); assert.equal(unauthInfo.authenticated, false); - const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const auth = await terminalService.authenticateVpsUser('root', 'valid'); const authInfo = terminalService.getTerminalInfo(auth.terminalToken); assert.equal(authInfo.authenticated, true); - assert.equal(authInfo.user, 'ggc'); + assert.equal(authInfo.user, 'root'); assert.ok(authInfo.hostname); assert.ok(authInfo.shell); });