feat: ban ggc from terminal, set ftp user, clean permissions display, add resource cleaner and process management

This commit is contained in:
GeronimoGc 2026-11-20 10:58:30 -05:00
parent a2c4df71b3
commit b0a747e5d6
14 changed files with 1343 additions and 136 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ node_modules/
.tmp/
data/
*.log
.playwright-mcp/

View File

@ -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;
}

View File

@ -360,7 +360,7 @@
<th>Archivos</th>
<th>Propietario / Grupo</th>
<th>Permisos UNIX</th>
<th>Verificación SGID 2775</th>
<th>Permisos de Acceso</th>
<th style="text-align: right;">Acciones</th>
</tr>
</thead>
@ -431,7 +431,7 @@
<div class="ftp-credential-item">
<span class="credential-label">Usuario del Sistema</span>
<div class="credential-val-wrap">
<code class="credential-value" id="ftp-info-user">ggc</code>
<code class="credential-value" id="ftp-info-user">ftp</code>
<span class="text-xs text-muted" style="margin-left: 0.25rem;">(Grupo: www-data)</span>
</div>
</div>
@ -444,9 +444,9 @@
</div>
<div class="ftp-credential-item">
<span class="credential-label">Permisos Heredados</span>
<span class="credential-label">Permisos de Acceso</span>
<div class="credential-val-wrap">
<span class="badge badge-mode-static">SGID 2775 (ggc:www-data)</span>
<span class="badge badge-mode-static">Acceso Web Óptimo</span>
</div>
</div>
</div>
@ -461,7 +461,7 @@
</svg>
<div>
<h3 class="bulk-title">Carga Masiva de Proyectos (Bulk Upload & ZIP Extractor)</h3>
<p class="bulk-desc">Sube un archivo comprimido .zip y el sistema lo extraerá en la carpeta del proyecto aplicando automáticamente los permisos UNIX SGID 2775.</p>
<p class="bulk-desc">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.</p>
</div>
</div>
</div>
@ -517,7 +517,7 @@
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 2v10M3 7l5 5 5-5M2 14h12"></path>
</svg>
<span>Subir y Descomprimir con Permisos SGID 2775</span>
<span>Subir y Descomprimir (Acceso Web Óptimo)</span>
</button>
</div>
@ -603,14 +603,22 @@
</p>
<form id="form-terminal-login" class="terminal-auth-form" autocomplete="off">
<div class="terminal-auth-notice" role="alert">
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" class="notice-icon">
<circle cx="8" cy="8" r="7"></circle>
<path stroke-linecap="round" d="M8 8v4M8 5v.5"></path>
</svg>
<span>ℹ️ El usuario <strong>'ggc'</strong> está reservado para el entorno de desarrollo y tiene prohibido el acceso a la terminal web.</span>
</div>
<div class="form-group text-left" style="width: 100%; text-align: left;">
<label for="terminal-vps-user-input" class="form-label">Usuario del VPS</label>
<input
type="text"
id="terminal-vps-user-input"
class="form-input"
placeholder="ej: ggc o root"
value="ggc"
placeholder="root"
value="root"
required
autocomplete="username"
>
@ -647,7 +655,7 @@
<div>
<span class="telemetry-label">Entorno Shell:</span>
<strong id="terminal-env-badge" style="font-family: ui-monospace, monospace; color: var(--accent-lime); font-size: 0.9rem;">
ggc@vps-jose (~/var/www)
root@vps-jose (~/var/www)
</strong>
</div>
<span class="badge badge-mode-proxy" id="terminal-status-badge">Sesión VPS Activa</span>
@ -692,7 +700,7 @@
<span class="dot-circle dot-green"></span>
</div>
<div class="terminal-window-title" id="terminal-topbar-title">
bash — ggc@vps-jose:/var/www
bash — root@vps-jose:/var/www
</div>
<div class="terminal-window-meta">
<span class="terminal-meta-tag">Aislamiento Seguro (Timeout 30s)</span>
@ -707,7 +715,7 @@
</div>
<form id="terminal-command-form" class="terminal-cli-form" autocomplete="off">
<div class="terminal-prompt-prefix" id="terminal-prompt-label">ggc@vps:~$</div>
<div class="terminal-prompt-prefix" id="terminal-prompt-label">root@vps:~$</div>
<input
type="text"
id="terminal-input"
@ -916,8 +924,104 @@
</div>
</div>
<!-- Sección Destacada: Herramientas de Mantenimiento y Optimización del VPS -->
<div class="maintenance-section-wrap" style="margin-top: 1.75rem;">
<div class="panel-toolbar" style="margin-bottom: 0.85rem;">
<div class="toolbar-left">
<h3 style="font-size: 1.05rem; font-weight: 700; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem;">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" style="color: var(--accent-lime);">
<path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
</svg>
<span>Herramientas de Mantenimiento y Liberación de Recursos</span>
</h3>
</div>
<div class="toolbar-right">
<span class="badge badge-mode-proxy">Optimización del VPS</span>
</div>
</div>
<div class="maintenance-cards-grid">
<!-- Tarjeta 1: Optimizar y Liberar RAM -->
<div class="maintenance-card">
<div class="maintenance-card-header">
<div class="maintenance-icon-badge icon-ram">
<svg viewBox="0 0 20 20" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
</svg>
</div>
<div>
<h4 class="maintenance-card-title">⚡ Optimizar y Liberar RAM</h4>
<p class="maintenance-card-desc">Sincroniza y purga buffers y cachés del kernel (<code>drop_caches</code>) para recuperar memoria inmediatamente.</p>
</div>
</div>
<div class="maintenance-card-actions">
<button type="button" id="btn-clean-ram" class="btn btn-primary btn-maintenance">
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 2v4M8 10v4M2 8h4M10 8h4M3.75 3.75l2.83 2.83M9.42 9.42l2.83 2.83M3.75 12.25l2.83-2.83M9.42 6.58l2.83-2.83"></path>
</svg>
<span id="btn-clean-ram-text">Liberar Caché de RAM (Drop Caches)</span>
</button>
</div>
</div>
<!-- Tarjeta 2: Limpiar Disco y Cachés -->
<div class="maintenance-card">
<div class="maintenance-card-header">
<div class="maintenance-icon-badge icon-disk">
<svg viewBox="0 0 20 20" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2">
<ellipse cx="10" cy="5" rx="7" ry="2.5"></ellipse>
<path d="M3 5v5c0 1.38 3.13 2.5 7 2.5s7-1.12 7-2.5V5M3 10v5c0 1.38 3.13 2.5 7 2.5s7-1.12 7-2.5v-5"></path>
</svg>
</div>
<div>
<h4 class="maintenance-card-title">💾 Limpiar Disco y Cachés</h4>
<p class="maintenance-card-desc">Vacía cachés de paquetes APT, recorta logs de journald a 50MB y comprime temporales.</p>
</div>
</div>
<div class="maintenance-card-actions maintenance-dual-actions">
<button type="button" id="btn-clean-disk" class="btn btn-secondary btn-maintenance">
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
<span id="btn-clean-disk-text">Depurar Disco y Temporales</span>
</button>
<button type="button" id="btn-view-disk-breakdown" class="btn btn-secondary btn-maintenance">
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M2 13h12M4 10h8M6 7h4M7 4h2"></path>
</svg>
<span>Ver Desglose de Espacio en Disco</span>
</button>
</div>
</div>
<!-- Tarjeta 3: Firewall y Puertos del Servidor -->
<div class="maintenance-card">
<div class="maintenance-card-header">
<div class="maintenance-icon-badge icon-shield">
<svg viewBox="0 0 20 20" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M10 2s7 3 7 8c0 5-7 8-7 8s-7-3-7-8c0-5 7-8 7-8z"></path>
</svg>
</div>
<div>
<h4 class="maintenance-card-title">🛡️ Firewall y Puertos del Servidor</h4>
<p class="maintenance-card-desc">Audita los puertos críticos requeridos por Apache, SSH, Gitea y FTP, y revisa el estado de UFW.</p>
</div>
</div>
<div class="maintenance-card-actions">
<button type="button" id="btn-audit-firewall" class="btn btn-secondary btn-maintenance">
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="8" cy="8" r="6"></circle>
<path stroke-linecap="round" stroke-linejoin="round" d="M12.5 12.5l2.5 2.5M8 5v3l2 2"></path>
</svg>
<span>Auditar Firewall (UFW) y Puertos</span>
</button>
</div>
</div>
</div>
</div>
<!-- Tabla de Top Procesos del VPS -->
<div class="processes-section-wrap" style="margin-top: 1.5rem;">
<div class="processes-section-wrap" style="margin-top: 1.75rem;">
<div class="panel-toolbar" style="margin-bottom: 0.85rem;">
<div class="toolbar-left">
<h3 style="font-size: 1.05rem; font-weight: 700; color: var(--text-primary); display: flex; align-items: center; gap: 0.5rem;">
@ -951,6 +1055,7 @@
<th>Memoria %</th>
<th>Memoria RSS</th>
<th>Comando / Proceso</th>
<th style="text-align: right; min-width: 150px;">Acciones</th>
</tr>
</thead>
<tbody id="processes-table-body">
@ -1242,7 +1347,7 @@
</svg>
<span>Modo A: Estático</span>
</div>
<p class="mode-card-desc">Crea /var/www/&lt;subdominio&gt; con index.html inicial y permisos SGID 2775.</p>
<p class="mode-card-desc">Crea /var/www/&lt;subdominio&gt; con index.html inicial y Acceso Web Óptimo (Lectura y Escritura RW).</p>
</button>
<button type="button" id="mode-btn-proxy" class="mode-card-btn">
@ -1931,6 +2036,201 @@
</div>
</div>
<!-- =======================================================================
Modal: Desglose de Espacio en Disco (/)
======================================================================= -->
<div id="modal-disk-breakdown" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-disk-title">
<div class="modal-dialog modal-dialog-lg">
<div class="modal-header">
<div class="modal-title-wrap">
<div class="modal-icon-badge" style="background: rgba(251, 146, 60, 0.15); color: #fb923c; border-color: rgba(251, 146, 60, 0.3);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<ellipse cx="10" cy="5" rx="7" ry="2.5"></ellipse>
<path d="M3 5v5c0 1.38 3.13 2.5 7 2.5s7-1.12 7-2.5V5M3 10v5c0 1.38 3.13 2.5 7 2.5s7-1.12 7-2.5v-5"></path>
</svg>
</div>
<h2 id="modal-disk-title" class="modal-title">Desglose de Espacio en Disco (/)</h2>
</div>
<button type="button" class="modal-close-btn" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<p style="font-size: 0.88rem; color: var(--text-secondary); margin-bottom: 1rem;">
Distribución de almacenamiento de los directorios y archivos de sistema más pesados en la raíz <code>/</code> del VPS:
</p>
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th>Ruta / Directorio</th>
<th>Espacio Ocupado</th>
<th>Descripción y Contenido</th>
</tr>
</thead>
<tbody id="disk-breakdown-table-body">
<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">Cargando desglose de disco...</td></tr>
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-modal-cancel">Cerrar</button>
</div>
</div>
</div>
<!-- =======================================================================
Modal: Auditoría de Firewall (UFW) y Puertos del Servidor
======================================================================= -->
<div id="modal-firewall-status" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-firewall-title">
<div class="modal-dialog modal-dialog-lg">
<div class="modal-header">
<div class="modal-title-wrap">
<div class="modal-icon-badge" style="background: rgba(56, 189, 248, 0.15); color: #38bdf8; border-color: rgba(56, 189, 248, 0.3);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M10 2s7 3 7 8c0 5-7 8-7 8s-7-3-7-8c0-5 7-8 7-8z"></path>
</svg>
</div>
<h2 id="modal-firewall-title" class="modal-title">Auditoría de Firewall (UFW) y Puertos del Servidor</h2>
</div>
<button type="button" class="modal-close-btn" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<div class="firewall-status-banner">
<div style="display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap;">
<div>
<span class="telemetry-label">Estado de Protección UFW:</span>
<div id="firewall-status-text" style="font-weight: 600; color: var(--text-primary); margin-top: 0.2rem;">
Cargando estado...
</div>
</div>
<span id="firewall-status-badge" class="badge badge-status-disabled">Inactivo</span>
</div>
<p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 0.5rem; line-height: 1.45;">
El firewall UFW se encuentra actualmente inactivo en el VPS para garantizar conectividad en todos los servicios. En caso de activarse, deben permitirse explícitamente los puertos de la siguiente tabla para prevenir el bloqueo total de SSH o del servidor web.
</p>
</div>
<h4 style="font-size: 0.92rem; font-weight: 600; color: var(--text-primary); margin-bottom: 0.6rem;">
Puertos Requeridos por los Servicios Activos
</h4>
<div class="table-responsive" style="margin-bottom: 1.25rem;">
<table class="data-table">
<thead>
<tr>
<th>Puerto</th>
<th>Protocolo</th>
<th>Servicio Asociado</th>
<th>Descripción y Uso</th>
</tr>
</thead>
<tbody id="firewall-ports-table-body">
<!-- Se llena dinámicamente -->
</tbody>
</table>
</div>
<div class="firewall-commands-box">
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem;">
<span style="font-size: 0.8rem; font-weight: 600; color: var(--text-secondary);">Comandos recomendados para habilitar UFW de forma segura:</span>
<button type="button" id="btn-copy-ufw-commands" class="btn btn-secondary btn-sm" style="font-size: 0.76rem; padding: 0.25rem 0.6rem;">
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="5" width="8" height="8" rx="1.5"></rect><path d="M3 11V3a1.5 1.5 0 0 1 1.5-1.5H11"></path></svg>
<span>Copiar Comandos</span>
</button>
</div>
<pre id="firewall-commands-code" class="firewall-code-block"></pre>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-modal-cancel">Cerrar</button>
</div>
</div>
</div>
<!-- =======================================================================
Modal: Confirmación de Finalizar Proceso (Kill PID)
======================================================================= -->
<div id="modal-kill-process" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-kill-process-title">
<div class="modal-dialog">
<div class="modal-header">
<div class="modal-title-wrap">
<div class="modal-icon-badge" style="background: rgba(239, 68, 68, 0.15); color: #f87171; border-color: rgba(239, 68, 68, 0.3);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="10" cy="10" r="8"></circle>
<path stroke-linecap="round" stroke-linejoin="round" d="M7 7l6 6M13 7l-6 6"></path>
</svg>
</div>
<h2 id="modal-kill-process-title" class="modal-title">Finalizar Proceso</h2>
</div>
<button type="button" class="modal-close-btn" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<p style="font-size: 0.92rem; color: var(--text-secondary); line-height: 1.5;">
¿Deseas finalizar el proceso <strong id="kill-proc-name-text" style="color: var(--text-primary); font-family: ui-monospace, monospace;">--</strong> con PID <code id="kill-proc-pid-text" style="font-weight: 700; color: #f87171;">--</code>?
</p>
<div class="form-group" style="margin-top: 1rem;">
<label for="kill-proc-signal-select" class="form-label">Señal de terminación:</label>
<select id="kill-proc-signal-select" class="select-filter" style="width: 100%;">
<option value="SIGTERM" selected>SIGTERM (Terminación normal y segura)</option>
<option value="SIGKILL">SIGKILL (Forzar detención inmediata)</option>
</select>
</div>
<p style="font-size: 0.78rem; color: var(--text-muted); margin-top: 0.5rem; line-height: 1.4;">
Nota: Por seguridad del sistema operativo, el PID 1 (init/systemd) y el proceso propio del panel a2host no pueden ser finalizados.
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-modal-cancel">Cancelar</button>
<button type="button" id="btn-confirm-kill-process" class="btn btn-danger">
🛑 Finalizar Proceso
</button>
</div>
</div>
</div>
<!-- =======================================================================
Modal: Confirmación de Reinicio de Servicio
======================================================================= -->
<div id="modal-restart-service" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="modal-restart-service-title">
<div class="modal-dialog">
<div class="modal-header">
<div class="modal-title-wrap">
<div class="modal-icon-badge" style="background: rgba(56, 189, 248, 0.15); color: #38bdf8; border-color: rgba(56, 189, 248, 0.3);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 0 0 4.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 0 1-15.357-2m15.357 2H15"></path>
</svg>
</div>
<h2 id="modal-restart-service-title" class="modal-title">Reiniciar Servicio del Servidor</h2>
</div>
<button type="button" class="modal-close-btn" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<p style="font-size: 0.92rem; color: var(--text-secondary); line-height: 1.5;">
¿Confirmas el reinicio del servicio de sistema <strong id="restart-service-target-text" style="color: #38bdf8; font-family: ui-monospace, monospace;">--</strong> en el VPS?
</p>
<p style="font-size: 0.8rem; color: var(--text-muted); line-height: 1.45; margin-top: 0.6rem;">
Se ejecutará <code>systemctl restart &lt;servicio&gt;</code> (o <code>pm2 restart a2host</code>). El servicio experimentará una breve pausa de 1 a 2 segundos antes de reanudar el tráfico.
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-modal-cancel">Cancelar</button>
<button type="button" id="btn-confirm-restart-service" class="btn btn-primary">
🔄 Reiniciar Servicio
</button>
</div>
</div>
</div>
<!-- Contenedor Global de Toasts Flotantes -->
<div id="toast-container" class="toast-container" aria-live="polite" aria-atomic="true"></div>

View File

@ -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' });

View File

@ -1008,8 +1008,8 @@ function renderFolders() {
<td><code style="font-size: 0.78rem;">${escapeHtml(f.permissions)}</code></td>
<td>
${isSGID
? `<span class="badge badge-sgid-ok" title="Bit SGID 2775 activo: hereda grupo www-data">SGID 2775 OK</span>`
: `<span class="badge badge-sgid-warn" title="Alerta: se recomienda chmod 2775">Sin SGID 2775</span>`
? `<span class="badge badge-sgid-ok" title="Permisos óptimos de lectura y escritura">Acceso Web Óptimo</span>`
: `<span class="badge badge-sgid-warn" title="Permisos configurados">Lectura y Escritura (RW)</span>`
}
</td>
<td style="text-align: right;">
@ -1039,8 +1039,8 @@ function renderFolders() {
<div style="font-size: 0.72rem; color: var(--text-muted);">${escapeHtml(f.path)}</div>
</div>
${isSGID
? `<span class="badge badge-sgid-ok">SGID 2775</span>`
: `<span class="badge badge-sgid-warn">Sin SGID</span>`
? `<span class="badge badge-sgid-ok">Acceso Web Óptimo</span>`
: `<span class="badge badge-sgid-warn">Lectura y Escritura (RW)</span>`
}
</div>
<div class="mobile-card-body">
@ -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 = `<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">Analizando almacenamiento del VPS...</td></tr>`;
}
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 = `<tr><td colspan="3" style="text-align: center; color: var(--color-danger); padding: 1.5rem;">Error al leer desglose: ${escapeHtml(err.detail || err.message)}</td></tr>`;
}
}
});
}
// 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 = `<tr><td colspan="4" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">Cargando puertos...</td></tr>`;
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 => `
<tr>
<td><span class="badge badge-port">${escapeHtml(p.port)}</span></td>
<td><code style="font-size: 0.78rem;">${escapeHtml(p.protocol)}</code></td>
<td><strong style="color: var(--text-primary);">${escapeHtml(p.service)}</strong></td>
<td style="font-size: 0.82rem; color: var(--text-secondary);">${escapeHtml(p.description)}</td>
</tr>
`).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 = `<tr><td colspan="3" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No se encontraron datos de almacenamiento.</td></tr>`;
return;
}
tbody.innerHTML = items.map(item => `
<tr>
<td><code style="font-weight: 700; color: var(--accent-lime);">${escapeHtml(item.path)}</code></td>
<td><strong class="tabular-nums" style="color: var(--text-primary);">${escapeHtml(item.sizeFormatted)}</strong></td>
<td style="font-size: 0.82rem; color: var(--text-secondary);">${escapeHtml(item.description || 'Directorio del sistema')}</td>
</tr>
`).join('');
}
function initMonitorTab() {
@ -2169,10 +2392,11 @@ function renderProcessesTable(processes) {
if (tableBody) {
if (filtered.length === 0) {
tableBody.innerHTML = `<tr><td colspan="6" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No se encontraron procesos coincidentes.</td></tr>`;
tableBody.innerHTML = `<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 1.5rem;">No se encontraron procesos coincidentes.</td></tr>`;
} else {
tableBody.innerHTML = filtered.map(p => {
const badgeCls = getProcessBadgeClass(p.command);
const serviceName = getServiceNameForProcess(p.command);
return `
<tr>
<td><code style="font-weight: 700; color: var(--text-secondary);">${p.pid}</code></td>
@ -2185,6 +2409,32 @@ function renderProcessesTable(processes) {
${escapeHtml(p.command || '')}
</span>
</td>
<td style="text-align: right; white-space: nowrap;">
<div style="display: inline-flex; gap: 0.35rem; align-items: center; justify-content: flex-end;">
${serviceName ? `
<button
type="button"
class="btn btn-secondary btn-sm btn-restart-proc"
data-service="${serviceName}"
data-cmd="${escapeHtml(p.command || '')}"
title="Reiniciar servicio ${serviceName}"
style="padding: 0.25rem 0.6rem; font-size: 0.76rem;"
>
🔄 Reiniciar
</button>
` : ''}
<button
type="button"
class="btn btn-danger btn-sm btn-kill-proc"
data-pid="${p.pid}"
data-cmd="${escapeHtml(p.command || '')}"
title="Finalizar proceso PID ${p.pid}"
style="padding: 0.25rem 0.6rem; font-size: 0.76rem;"
>
🛑 Finalizar
</button>
</div>
</td>
</tr>
`;
}).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 `
<div class="mobile-card">
<div class="mobile-card-header">
@ -2217,11 +2468,55 @@ function renderProcessesTable(processes) {
<strong>${p.memPercent}% (${p.rssFormatted || '—'})</strong>
</div>
</div>
<div class="mobile-card-actions" style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">
${serviceName ? `
<button
type="button"
class="btn btn-secondary btn-sm btn-restart-proc"
data-service="${serviceName}"
data-cmd="${escapeHtml(p.command || '')}"
style="flex: 1; justify-content: center;"
>
🔄 Reiniciar
</button>
` : ''}
<button
type="button"
class="btn btn-danger btn-sm btn-kill-proc"
data-pid="${p.pid}"
data-cmd="${escapeHtml(p.command || '')}"
style="flex: 1; justify-content: center;"
>
🛑 Finalizar
</button>
</div>
</div>
`;
}).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 = `<span>Descomprimiendo y aplicando SGID 2775...</span>`;
btnExtract.innerHTML = `<span>Descomprimiendo y configurando permisos...</span>`;
}
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) {
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2">
<path stroke-linecap="round" stroke-linejoin="round" d="M8 2v10M3 7l5 5 5-5M2 14h12"></path>
</svg>
<span>Subir y Descomprimir con Permisos SGID 2775</span>
<span>Subir y Descomprimir (Acceso Web Óptimo)</span>
`;
}
}
@ -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 || [] });

View File

@ -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();

View File

@ -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;
}

View File

@ -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()
});

View File

@ -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()}/<proyecto>'.`
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()}/<proyecto>'.`
};
}

View File

@ -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<string, number>|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<object>}
*/
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<object>}
* 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,

View File

@ -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();

View File

@ -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);

View File

@ -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'));
});
});

View File

@ -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);
});