feat: add immutable root superadmin, risk-aware subdomain editing, XAMPP file manager, remote terminal and full VPS monitor

This commit is contained in:
GeronimoGc 2026-11-20 08:34:18 -05:00
parent 562c3f9ca1
commit aa6bd6c9f3
30 changed files with 4647 additions and 139 deletions

View File

@ -9,10 +9,10 @@ APACHE_SITES_AVAILABLE=/etc/apache2/sites-available
APACHE_SITES_ENABLED=/etc/apache2/sites-enabled
SYSTEM_USER=ggc
# Autenticación y Credenciales
ADMIN_USER=admin
ADMIN_PASS=cambiar_password_segura
ADMIN_FULL_NAME=Administrador Principal
# Autenticación y Credenciales (Superadministrador Inmutable)
ADMIN_USER=root
ADMIN_PASS=ddEMVJ-N8T5mZG
ADMIN_FULL_NAME=root
SESSION_SECRET=minimo_32_caracteres_aleatorios_para_cookies_o_jwt
# Restricciones

View File

@ -1311,3 +1311,811 @@
width: 48px;
}
}
/* ==========================================================================
Nuevas Interfaces y Módulos: Terminal, Monitor, File Manager y Editor
========================================================================== */
/* Diálogo Extra Ancho para File Manager y Code Editor */
.modal-dialog-xl {
max-width: 1040px;
width: 95vw;
}
/* ==========================================================================
1. MÓDULO TERMINAL (CONSOLA BASH INTERACTIVA)
========================================================================== */
.terminal-quick-actions-bar {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
flex-wrap: wrap;
padding: 0.75rem 1rem;
background: var(--bg-surface);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-lg);
backdrop-filter: blur(12px);
}
.quick-actions-label {
font-size: 0.8rem;
font-weight: 600;
color: var(--text-secondary);
white-space: nowrap;
}
.quick-buttons-wrapper {
display: flex;
align-items: center;
gap: 0.45rem;
flex-wrap: wrap;
}
.btn-quick-cmd {
padding: 0.35rem 0.65rem;
font-family: ui-monospace, 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.78rem;
color: var(--text-secondary);
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--border-subtle);
border-radius: var(--radius-sm);
cursor: pointer;
transition: all var(--transition-fast);
white-space: nowrap;
}
.btn-quick-cmd:hover {
color: var(--accent-lime);
background: rgba(163, 230, 53, 0.08);
border-color: var(--accent-lime-hover);
transform: translateY(-1px);
}
.terminal-window-card {
background: #060907;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: var(--radius-lg);
overflow: hidden;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.6), inset 0 1px 0 rgba(255, 255, 255, 0.08);
display: flex;
flex-direction: column;
}
.terminal-window-topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1rem;
background: rgba(18, 26, 20, 0.95);
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}
.terminal-dots-indicator {
display: flex;
align-items: center;
gap: 0.45rem;
}
.dot-circle {
width: 11px;
height: 11px;
border-radius: 50%;
display: inline-block;
}
.dot-red { background: #ef4444; }
.dot-yellow { background: #f59e0b; }
.dot-green { background: #10b981; }
.terminal-window-title {
font-family: ui-monospace, 'JetBrains Mono', monospace;
font-size: 0.82rem;
font-weight: 600;
color: var(--text-secondary);
}
.terminal-window-meta {
display: flex;
align-items: center;
gap: 0.5rem;
}
.terminal-meta-tag {
font-size: 0.72rem;
padding: 0.2rem 0.5rem;
background: rgba(16, 185, 129, 0.12);
color: var(--accent-emerald);
border: 1px solid rgba(16, 185, 129, 0.25);
border-radius: var(--radius-sm);
}
.terminal-screen-body {
height: 480px;
max-height: 55vh;
overflow-y: auto;
padding: 1.25rem 1.25rem 0.75rem;
font-family: ui-monospace, 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
font-size: 0.88rem;
line-height: 1.55;
color: #e2e8f0;
display: flex;
flex-direction: column;
gap: 0.85rem;
}
.terminal-banner {
padding: 0.85rem 1rem;
background: rgba(255, 255, 255, 0.02);
border: 1px dashed rgba(255, 255, 255, 0.12);
border-radius: var(--radius-md);
margin-bottom: 0.5rem;
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.terminal-banner-brand {
color: var(--accent-lime);
font-weight: 700;
font-size: 0.88rem;
}
.terminal-banner-sub {
color: var(--text-muted);
font-size: 0.78rem;
}
.terminal-entry {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.terminal-cmd-row {
display: flex;
align-items: center;
gap: 0.5rem;
color: var(--accent-lime);
font-weight: 600;
word-break: break-all;
}
.terminal-prompt-sym {
color: var(--text-muted);
}
.terminal-output-block {
padding: 0.65rem 0.85rem;
background: rgba(0, 0, 0, 0.35);
border-radius: var(--radius-sm);
border-left: 3px solid var(--accent-lime);
white-space: pre-wrap;
word-break: break-word;
font-size: 0.84rem;
color: #cbd5e1;
}
.terminal-output-block.has-error {
border-left-color: #ef4444;
background: rgba(239, 68, 68, 0.05);
}
.terminal-stderr-text {
color: #fca5a5;
margin-top: 0.35rem;
}
.terminal-entry-footer {
display: flex;
align-items: center;
gap: 0.75rem;
font-size: 0.72rem;
color: var(--text-muted);
margin-top: 0.15rem;
}
.terminal-badge-ok {
color: #4ade80;
background: rgba(74, 222, 128, 0.12);
padding: 0.15rem 0.4rem;
border-radius: 4px;
}
.terminal-badge-err {
color: #f87171;
background: rgba(248, 113, 113, 0.12);
padding: 0.15rem 0.4rem;
border-radius: 4px;
}
.terminal-cli-form {
display: flex;
align-items: center;
gap: 0.65rem;
padding: 0.75rem 1rem;
background: rgba(14, 22, 16, 0.95);
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.terminal-prompt-prefix {
font-family: ui-monospace, 'JetBrains Mono', monospace;
font-size: 0.88rem;
font-weight: 700;
color: var(--accent-lime);
white-space: nowrap;
}
.terminal-cli-input {
flex: 1;
background: transparent;
border: none;
font-family: ui-monospace, 'JetBrains Mono', monospace;
font-size: 0.88rem;
color: #f8fafc;
outline: none;
caret-color: var(--accent-lime);
}
.terminal-cli-input::placeholder {
color: rgba(255, 255, 255, 0.25);
font-size: 0.82rem;
}
.terminal-execute-btn {
display: inline-flex;
align-items: center;
gap: 0.45rem;
padding: 0.4rem 0.85rem;
font-size: 0.8rem;
}
.kbd-hint {
font-family: ui-monospace, monospace;
font-size: 0.68rem;
background: rgba(0, 0, 0, 0.3);
padding: 0.1rem 0.35rem;
border-radius: 3px;
border: 1px solid rgba(255, 255, 255, 0.15);
}
/* ==========================================================================
2. MÓDULO MONITOR DEL SERVIDOR
========================================================================== */
.auto-refresh-selector-wrap {
display: flex;
align-items: center;
gap: 0.5rem;
}
.monitor-cards-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.25rem;
margin-bottom: 1.5rem;
}
.monitor-metric-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;
gap: 0.85rem;
transition: transform var(--transition-fast), border-color var(--transition-fast);
}
.monitor-metric-card:hover {
transform: translateY(-2px);
border-color: var(--border-medium);
}
.metric-card-header {
display: flex;
align-items: center;
gap: 0.75rem;
}
.metric-card-icon-wrap {
width: 36px;
height: 36px;
border-radius: var(--radius-md);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.metric-card-title-wrap {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
.metric-title {
font-size: 0.9rem;
font-weight: 700;
color: var(--text-primary);
}
.metric-subtitle {
font-size: 0.75rem;
color: var(--text-muted);
}
.metric-percentage {
font-size: 1.25rem;
font-weight: 800;
color: var(--text-primary);
}
.metric-progress-track {
width: 100%;
height: 8px;
background: rgba(255, 255, 255, 0.06);
border-radius: var(--radius-full);
overflow: hidden;
position: relative;
}
.metric-progress-fill {
height: 100%;
background: linear-gradient(90deg, #38bdf8, #0ea5e9);
border-radius: var(--radius-full);
transition: width 400ms ease;
box-shadow: 0 0 10px rgba(56, 189, 248, 0.3);
}
.metric-progress-fill.fill-lime {
background: linear-gradient(90deg, #10b981, #a3e635);
box-shadow: 0 0 10px rgba(163, 230, 53, 0.3);
}
.metric-progress-fill.fill-purple {
background: linear-gradient(90deg, #a855f7, #c084fc);
box-shadow: 0 0 10px rgba(192, 132, 252, 0.3);
}
.metric-progress-fill.fill-orange {
background: linear-gradient(90deg, #f97316, #fb923c);
box-shadow: 0 0 10px rgba(251, 146, 60, 0.3);
}
.metric-progress-fill.fill-warning {
background: linear-gradient(90deg, #f59e0b, #fbbf24) !important;
box-shadow: 0 0 12px rgba(245, 158, 11, 0.4) !important;
}
.metric-progress-fill.fill-danger {
background: linear-gradient(90deg, #ef4444, #f87171) !important;
box-shadow: 0 0 14px rgba(239, 68, 68, 0.5) !important;
}
.metric-card-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding-top: 0.4rem;
border-top: 1px solid rgba(255, 255, 255, 0.05);
}
.metric-stat-item {
display: flex;
align-items: center;
gap: 0.35rem;
font-size: 0.76rem;
}
.stat-name {
color: var(--text-muted);
}
.stat-value {
color: var(--text-secondary);
}
/* Badges de Procesos del VPS */
.process-cmd-badge {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.2rem 0.55rem;
border-radius: var(--radius-sm);
font-family: ui-monospace, monospace;
font-size: 0.78rem;
font-weight: 600;
}
.proc-apache {
background: rgba(56, 189, 248, 0.12);
color: #38bdf8;
border: 1px solid rgba(56, 189, 248, 0.25);
}
.proc-node {
background: rgba(74, 222, 128, 0.12);
color: #4ade80;
border: 1px solid rgba(74, 222, 128, 0.25);
}
.proc-gitea {
background: rgba(192, 132, 252, 0.12);
color: #c084fc;
border: 1px solid rgba(192, 132, 252, 0.25);
}
.proc-mysql {
background: rgba(251, 146, 60, 0.12);
color: #fb923c;
border: 1px solid rgba(251, 146, 60, 0.25);
}
.proc-system {
background: rgba(255, 255, 255, 0.06);
color: var(--text-muted);
border: 1px solid var(--border-subtle);
}
/* ==========================================================================
3. GESTOR DE ARCHIVOS (FILE MANAGER)
========================================================================== */
.fm-path-subtitle {
font-family: ui-monospace, monospace;
font-size: 0.76rem;
color: var(--accent-lime);
}
.fm-breadcrumbs-bar {
display: flex;
align-items: center;
gap: 0.35rem;
padding: 0.65rem 1.25rem;
background: rgba(0, 0, 0, 0.35);
border-bottom: 1px solid var(--border-subtle);
overflow-x: auto;
white-space: nowrap;
}
.fm-breadcrumb-item {
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-size: 0.82rem;
color: var(--text-muted);
background: transparent;
border: none;
cursor: pointer;
padding: 0.2rem 0.45rem;
border-radius: 4px;
transition: all var(--transition-fast);
}
.fm-breadcrumb-item:hover {
color: var(--accent-lime);
background: rgba(163, 230, 53, 0.08);
}
.fm-breadcrumb-active {
color: var(--text-primary);
font-weight: 700;
pointer-events: none;
}
.fm-breadcrumb-separator {
color: rgba(255, 255, 255, 0.2);
font-size: 0.75rem;
}
.fm-toolbar-container {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.75rem 1.25rem;
background: var(--bg-surface);
border-bottom: 1px solid var(--border-subtle);
gap: 0.75rem;
flex-wrap: wrap;
}
.fm-toolbar-left, .fm-toolbar-right {
display: flex;
align-items: center;
gap: 0.5rem;
}
.fm-create-item-panel {
padding: 0.75rem 1.25rem;
background: rgba(16, 185, 129, 0.05);
border-bottom: 1px solid rgba(16, 185, 129, 0.2);
}
.fm-create-item-form {
display: flex;
align-items: center;
gap: 0.65rem;
}
.fm-create-input {
max-width: 320px;
height: 34px;
font-size: 0.85rem;
}
.fm-modal-body {
padding: 0;
max-height: 480px;
overflow-y: auto;
}
.fm-table {
width: 100%;
}
.fm-table tbody tr {
cursor: default;
}
.fm-table tbody tr.fm-dir-row {
cursor: pointer;
}
.fm-file-name-cell {
display: flex;
align-items: center;
gap: 0.65rem;
}
.fm-icon-folder { color: #f59e0b; }
.fm-icon-php { color: #60a5fa; }
.fm-icon-js { color: #facc15; }
.fm-icon-html { color: #fb923c; }
.fm-icon-css { color: #38bdf8; }
.fm-icon-json { color: #4ade80; }
.fm-icon-img { color: #f472b6; }
.fm-icon-default { color: var(--text-muted); }
.fm-folder-link {
font-weight: 600;
color: var(--text-primary);
text-decoration: none;
}
.fm-folder-link:hover {
color: var(--accent-lime);
text-decoration: underline;
}
/* ==========================================================================
4. EDITOR DE CÓDIGO
========================================================================== */
.code-editor-dialog {
display: flex;
flex-direction: column;
height: 85vh;
}
.code-editor-header {
padding: 0.85rem 1.25rem;
}
.code-editor-path {
font-family: ui-monospace, monospace;
font-size: 0.74rem;
color: var(--text-muted);
}
.code-editor-header-actions {
display: flex;
align-items: center;
gap: 0.75rem;
}
.code-editor-status-tag {
font-size: 0.74rem;
padding: 0.25rem 0.55rem;
border-radius: var(--radius-sm);
font-weight: 600;
}
.status-clean {
color: var(--text-muted);
background: rgba(255, 255, 255, 0.05);
}
.status-dirty {
color: #fbbf24;
background: rgba(245, 158, 11, 0.15);
border: 1px solid rgba(245, 158, 11, 0.3);
}
.status-saving {
color: #38bdf8;
background: rgba(56, 189, 248, 0.15);
}
.status-saved {
color: #4ade80;
background: rgba(74, 222, 128, 0.15);
}
.code-editor-body {
flex: 1;
padding: 0;
overflow: hidden;
background: #080c09;
}
.code-editor-workspace {
display: flex;
height: 100%;
width: 100%;
overflow: hidden;
position: relative;
}
.code-editor-gutter {
width: 52px;
background: #050806;
border-right: 1px solid rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.3);
font-family: ui-monospace, 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.85rem;
line-height: 1.6;
text-align: right;
padding: 0.75rem 0.5rem 0.75rem 0.25rem;
user-select: none;
overflow: hidden;
white-space: pre;
}
.code-editor-textarea {
flex: 1;
height: 100%;
background: transparent;
border: none;
color: #e2e8f0;
font-family: ui-monospace, 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.85rem;
line-height: 1.6;
padding: 0.75rem 1rem;
outline: none;
resize: none;
white-space: pre;
overflow: auto;
tab-size: 2;
caret-color: var(--accent-lime);
}
.code-editor-footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.65rem 1.25rem;
background: var(--bg-surface-elevated);
}
.code-editor-footer-left {
display: flex;
align-items: center;
gap: 1rem;
}
.code-editor-shortcut-hint {
font-size: 0.72rem;
color: var(--text-muted);
}
/* ==========================================================================
5. RIESGOS DE SUBDOMINIOS Y USUARIOS INMUTABLES
========================================================================== */
.risk-alert-container {
margin: 1rem 0;
padding: 0.9rem 1rem;
background: rgba(239, 68, 68, 0.08);
border: 1px solid rgba(239, 68, 68, 0.3);
border-radius: var(--radius-md);
display: flex;
flex-direction: column;
gap: 0.65rem;
}
.risk-alert-header {
display: flex;
align-items: center;
gap: 0.65rem;
}
.risk-alert-badge {
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.05em;
padding: 0.2rem 0.45rem;
border-radius: 4px;
background: #ef4444;
color: #fff;
}
.risk-alert-title {
font-size: 0.88rem;
color: #fca5a5;
}
.risk-alert-list {
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.risk-alert-item {
font-size: 0.8rem;
line-height: 1.45;
color: #fecaca;
padding: 0.45rem 0.65rem;
background: rgba(0, 0, 0, 0.25);
border-left: 3px solid #ef4444;
border-radius: 4px;
}
.risk-alert-item.risk-warning {
border-left-color: #f59e0b;
color: #fde68a;
}
.risk-confirmation-box {
display: flex;
align-items: flex-start;
gap: 0.75rem;
padding: 0.85rem 1rem;
margin: 0.85rem 0;
background: rgba(245, 158, 11, 0.08);
border: 1px solid rgba(245, 158, 11, 0.35);
border-radius: var(--radius-md);
}
.risk-checkbox {
margin-top: 0.25rem;
width: 17px;
height: 17px;
accent-color: var(--accent-lime);
cursor: pointer;
}
.risk-checkbox-label {
display: flex;
flex-direction: column;
gap: 0.15rem;
font-size: 0.84rem;
color: var(--text-primary);
cursor: pointer;
}
.risk-checkbox-sub {
font-size: 0.74rem;
color: var(--text-muted);
}
/* Badge de Usuario Inmutable / Root */
.badge-immutable {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.25rem 0.6rem;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.04em;
color: #d8b4fe;
background: rgba(168, 85, 247, 0.16);
border: 1px solid rgba(168, 85, 247, 0.45);
border-radius: var(--radius-sm);
box-shadow: 0 0 10px rgba(168, 85, 247, 0.2);
}

View File

@ -539,3 +539,11 @@ body {
transform: translateY(0);
}
}
/* Clases Utilitarias */
.text-xs { font-size: 0.75rem; }
.text-sm { font-size: 0.85rem; }
.text-muted { color: var(--text-muted); }
.text-accent { color: var(--accent-lime); }
.tabular-nums { font-variant-numeric: tabular-nums; }
.truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

View File

@ -121,6 +121,24 @@
<span id="folders-count-badge" class="tab-badge tabular-nums">0</span>
</button>
</li>
<li role="presentation">
<button type="button" class="tab-btn" role="tab" id="tab-btn-terminal" aria-selected="false" aria-controls="tab-panel-terminal" data-tab="terminal">
<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="4 17 10 11 4 5"></polyline>
<line x1="12" y1="19" x2="20" y2="19"></line>
</svg>
<span>🖥️ Terminal</span>
</button>
</li>
<li role="presentation">
<button type="button" class="tab-btn" role="tab" id="tab-btn-monitor" aria-selected="false" aria-controls="tab-panel-monitor" data-tab="monitor">
<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 3v14a1 1 0 0 0 1 1h13"></path>
<path stroke-linecap="round" stroke-linejoin="round" d="m18 8-5 5-4-4-4 4"></path>
</svg>
<span>📊 Monitor del Servidor</span>
</button>
</li>
<li role="presentation">
<button type="button" class="tab-btn" role="tab" id="tab-btn-users" aria-selected="false" aria-controls="tab-panel-users" data-tab="users">
<svg viewBox="0 0 20 20" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
@ -278,7 +296,328 @@
</section>
<!-- =====================================================================
Pestaña 3: Operadores & Usuarios
Pestaña 3: 🖥️ Terminal Remota del Sistema (Bash)
===================================================================== -->
<section id="tab-panel-terminal" class="tab-panel" role="tabpanel" aria-labelledby="tab-btn-terminal">
<div class="panel-toolbar">
<div class="toolbar-left">
<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)
</strong>
</div>
<span class="badge badge-mode-proxy" id="terminal-status-badge">Sesión Activa</span>
</div>
<div class="toolbar-right">
<button type="button" id="terminal-btn-clear" class="btn btn-secondary" title="Limpiar la salida de la consola">
<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>Limpiar Consola</span>
</button>
</div>
</div>
<!-- Botones de Acceso Rápido a Comandos Comunes del VPS -->
<div class="terminal-quick-actions-bar" aria-label="Comandos rápidos del sistema">
<span class="quick-actions-label">Comandos Rápidos:</span>
<div class="quick-buttons-wrapper">
<button type="button" class="btn-quick-cmd" data-cmd="apache2ctl -S">apache2ctl -S</button>
<button type="button" class="btn-quick-cmd" data-cmd="pm2 list">pm2 list</button>
<button type="button" class="btn-quick-cmd" data-cmd="free -m">free -m</button>
<button type="button" class="btn-quick-cmd" data-cmd="df -h">df -h</button>
<button type="button" class="btn-quick-cmd" data-cmd="systemctl status apache2">systemctl status apache2</button>
<button type="button" class="btn-quick-cmd" data-cmd="ls -la /var/www">ls -la /var/www</button>
<button type="button" class="btn-quick-cmd" data-cmd="php -v">php -v</button>
<button type="button" class="btn-quick-cmd" data-cmd="uptime">uptime</button>
</div>
</div>
<!-- Ventana de Consola Terminal Negra / Estilo Xterm -->
<div class="terminal-window-card">
<div class="terminal-window-topbar">
<div class="terminal-dots-indicator" aria-hidden="true">
<span class="dot-circle dot-red"></span>
<span class="dot-circle dot-yellow"></span>
<span class="dot-circle dot-green"></span>
</div>
<div class="terminal-window-title" id="terminal-topbar-title">
bash — ggc@vps-jose:/var/www
</div>
<div class="terminal-window-meta">
<span class="terminal-meta-tag">Aislamiento Seguro (Timeout 30s)</span>
</div>
</div>
<div id="terminal-screen" class="terminal-screen-body" tabindex="0" role="region" aria-label="Salida de la consola terminal" aria-live="polite">
<div class="terminal-banner">
<span class="terminal-banner-brand">a2host Remote Web Terminal v1.0 [Linux 6.x / VPS elingejose.com]</span>
<span class="terminal-banner-sub">Escribe un comando o selecciona una acción rápida superior. Usa las flechas ↑/↓ para navegar en el historial.</span>
</div>
</div>
<form id="terminal-command-form" class="terminal-cli-form" autocomplete="off">
<div class="terminal-prompt-prefix" id="terminal-prompt-label">ggc@vps:~$</div>
<input
type="text"
id="terminal-input"
class="terminal-cli-input"
placeholder="Escribe un comando (ej: apache2ctl -S, free -m, ls -la)..."
autocomplete="off"
autocorrect="off"
autocapitalize="off"
spellcheck="false"
required
>
<button type="submit" id="terminal-btn-execute" class="btn btn-primary btn-sm terminal-execute-btn">
<span>Ejecutar</span>
<kbd class="kbd-hint">Enter</kbd>
</button>
</form>
</div>
</section>
<!-- =====================================================================
Pestaña 4: 📊 Monitor del Servidor VPS
===================================================================== -->
<section id="tab-panel-monitor" class="tab-panel" role="tabpanel" aria-labelledby="tab-btn-monitor">
<div class="panel-toolbar">
<div class="toolbar-left">
<div>
<span class="telemetry-label">Monitoreo de Recursos:</span>
<strong style="color: var(--accent-lime); font-size: 0.95rem;">VPS 1 GB RAM &middot; elingejose.com</strong>
</div>
<span id="monitor-last-updated-text" class="text-xs text-muted">Actualizado hace un momento</span>
</div>
<div class="toolbar-right">
<div class="auto-refresh-selector-wrap">
<label for="monitor-interval-select" class="form-label" style="margin: 0; font-size: 0.78rem;">Auto-refresco:</label>
<select id="monitor-interval-select" class="select-filter" style="padding-right: 1.8rem; font-size: 0.8rem;">
<option value="0">Manual (Sin auto-refresco)</option>
<option value="3000">Cada 3 segundos</option>
<option value="5000" selected>Cada 5 segundos</option>
<option value="10000">Cada 10 segundos</option>
<option value="30000">Cada 30 segundos</option>
</select>
</div>
<button type="button" id="btn-refresh-monitor" class="btn btn-secondary" title="Actualizar métricas del sistema">
<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="M14 8A6 6 0 1 1 9.5 2.5M14 2.5v4h-4"></path>
</svg>
<span>Refrescar Ahora</span>
</button>
</div>
</div>
<!-- Grid de Tarjetas de Rendimiento con Barras de Progreso -->
<div class="monitor-cards-grid">
<!-- Tarjeta 1: CPU & Load Average -->
<div class="monitor-metric-card">
<div class="metric-card-header">
<div class="metric-card-icon-wrap" style="color: #38bdf8; background: rgba(56, 189, 248, 0.12);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<rect x="4" y="4" width="12" height="12" rx="2"></rect>
<path d="M7 1v3M13 1v3M7 16v3M13 16v3M1 7h3M1 13h3M16 7h3M16 13h3"></path>
</svg>
</div>
<div class="metric-card-title-wrap">
<span class="metric-title">CPU & Carga Promedio</span>
<span id="monitor-cpu-model-text" class="metric-subtitle">Cores: --</span>
</div>
<span id="monitor-cpu-percent" class="metric-percentage tabular-nums">0%</span>
</div>
<div class="metric-progress-track" aria-label="Uso de CPU">
<div id="monitor-cpu-bar" class="metric-progress-fill" style="width: 0%;"></div>
</div>
<div class="metric-card-footer">
<div class="metric-stat-item">
<span class="stat-name">Load 1m:</span>
<strong id="monitor-load-1m" class="stat-value tabular-nums">0.00</strong>
</div>
<div class="metric-stat-item">
<span class="stat-name">Load 5m:</span>
<strong id="monitor-load-5m" class="stat-value tabular-nums">0.00</strong>
</div>
<div class="metric-stat-item">
<span class="stat-name">Load 15m:</span>
<strong id="monitor-load-15m" class="stat-value tabular-nums">0.00</strong>
</div>
</div>
</div>
<!-- Tarjeta 2: RAM Detallada del VPS -->
<div class="monitor-metric-card">
<div class="metric-card-header">
<div class="metric-card-icon-wrap" style="color: #a3e635; background: rgba(163, 230, 53, 0.12);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="4" width="14" height="12" rx="2"></rect>
<path stroke-linecap="round" d="M6 2v2M14 2v2M6 16v2M14 16v2"></path>
</svg>
</div>
<div class="metric-card-title-wrap">
<span class="metric-title">Memoria RAM del VPS</span>
<span id="monitor-ram-used-text" class="metric-subtitle">-- / --</span>
</div>
<span id="monitor-ram-percent" class="metric-percentage tabular-nums">0%</span>
</div>
<div class="metric-progress-track" aria-label="Uso de memoria RAM">
<div id="monitor-ram-bar" class="metric-progress-fill fill-lime" style="width: 0%;"></div>
</div>
<div class="metric-card-footer">
<div class="metric-stat-item">
<span class="stat-name">Libre:</span>
<strong id="monitor-ram-free" class="stat-value tabular-nums">--</strong>
</div>
<div class="metric-stat-item">
<span class="stat-name">Buffers/Caché:</span>
<strong id="monitor-ram-cache" class="stat-value tabular-nums">--</strong>
</div>
</div>
</div>
<!-- Tarjeta 3: Memoria Swap -->
<div class="monitor-metric-card">
<div class="metric-card-header">
<div class="metric-card-icon-wrap" style="color: #c084fc; background: rgba(192, 132, 252, 0.12);">
<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="M17 10H3M13 6l4 4-4 4M7 14l-4-4 4-4"></path>
</svg>
</div>
<div class="metric-card-title-wrap">
<span class="metric-title">Espacio Swap</span>
<span id="monitor-swap-used-text" class="metric-subtitle">-- / --</span>
</div>
<span id="monitor-swap-percent" class="metric-percentage tabular-nums">0%</span>
</div>
<div class="metric-progress-track" aria-label="Uso de espacio swap">
<div id="monitor-swap-bar" class="metric-progress-fill fill-purple" style="width: 0%;"></div>
</div>
<div class="metric-card-footer">
<div class="metric-stat-item">
<span class="stat-name">Libre:</span>
<strong id="monitor-swap-free" class="stat-value tabular-nums">--</strong>
</div>
<div class="metric-stat-item">
<span class="stat-name">Total Swap:</span>
<strong id="monitor-swap-total" class="stat-value tabular-nums">--</strong>
</div>
</div>
</div>
<!-- Tarjeta 4: Almacenamiento Raíz / -->
<div class="monitor-metric-card">
<div class="metric-card-header">
<div class="metric-card-icon-wrap" style="color: #fb923c; background: rgba(251, 146, 60, 0.12);">
<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>
<div class="metric-card-title-wrap">
<span class="metric-title">Disco Raíz (/)</span>
<span id="monitor-disk-used-text" class="metric-subtitle">-- / --</span>
</div>
<span id="monitor-disk-percent" class="metric-percentage tabular-nums">0%</span>
</div>
<div class="metric-progress-track" aria-label="Uso de disco">
<div id="monitor-disk-bar" class="metric-progress-fill fill-orange" style="width: 0%;"></div>
</div>
<div class="metric-card-footer">
<div class="metric-stat-item">
<span class="stat-name">Disponible:</span>
<strong id="monitor-disk-free" class="stat-value tabular-nums">--</strong>
</div>
<div class="metric-stat-item">
<span class="stat-name">Total:</span>
<strong id="monitor-disk-total" class="stat-value tabular-nums">--</strong>
</div>
</div>
</div>
<!-- Tarjeta 5: Proceso a2host (Node/PM2 vs Tope 120M) -->
<div class="monitor-metric-card">
<div class="metric-card-header">
<div class="metric-card-icon-wrap" style="color: #4ade80; background: rgba(74, 222, 128, 0.12);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<circle cx="10" cy="10" r="7"></circle>
<polygon points="9 7 13 10 9 13 9 7" fill="currentColor"></polygon>
</svg>
</div>
<div class="metric-card-title-wrap">
<span class="metric-title">Proceso a2host (PM2)</span>
<span id="monitor-pm2-used-text" class="metric-subtitle">-- / 120 MB</span>
</div>
<span id="monitor-pm2-percent" class="metric-percentage tabular-nums">0%</span>
</div>
<div class="metric-progress-track" aria-label="Memoria RSS frente al límite de 120MB de PM2">
<div id="monitor-pm2-bar" class="metric-progress-fill fill-lime" style="width: 0%;"></div>
</div>
<div class="metric-card-footer">
<div class="metric-stat-item">
<span class="stat-name">Heap Usado:</span>
<strong id="monitor-pm2-heap" class="stat-value tabular-nums">--</strong>
</div>
<div class="metric-stat-item">
<span class="stat-name">Límite Estricto:</span>
<strong class="stat-value text-accent" style="color: var(--accent-lime);">120.0 MB</strong>
</div>
</div>
</div>
</div>
<!-- Tabla de Top Procesos del VPS -->
<div class="processes-section-wrap" style="margin-top: 1.5rem;">
<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 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2">
<rect x="2" y="2" width="12" height="12" rx="2"></rect>
<path d="M5 8h6M8 5v6"></path>
</svg>
<span>Top Procesos Activos en VPS (Ordenados por Consumo)</span>
</h3>
</div>
<div class="toolbar-right">
<input
type="search"
id="search-processes-input"
class="input-search"
placeholder="Filtrar por comando o PID..."
style="max-width: 260px;"
aria-label="Filtrar procesos"
>
</div>
</div>
<div class="table-glass-card">
<div class="table-responsive">
<table class="data-table">
<thead>
<tr>
<th style="width: 80px;">PID</th>
<th>Usuario</th>
<th>CPU %</th>
<th>Memoria %</th>
<th>Memoria RSS</th>
<th>Comando / Proceso</th>
</tr>
</thead>
<tbody id="processes-table-body">
<!-- Se llena dinámicamente con app.js -->
</tbody>
</table>
</div>
</div>
<div id="processes-mobile-list" class="mobile-cards-grid">
<!-- Mobile -->
</div>
</div>
</section>
<!-- =====================================================================
Pestaña 5: Operadores & Usuarios
===================================================================== -->
<section id="tab-panel-users" class="tab-panel" role="tabpanel" aria-labelledby="tab-btn-users">
<div class="panel-toolbar">
@ -446,6 +785,26 @@
<div id="subdomain-port-feedback" class="input-feedback"></div>
</div>
<!-- Caja de Alerta de Riesgo Dinámico (Site Risk Assessment) -->
<div id="subdomain-risk-container" class="risk-alert-container" style="display: none;">
<div class="risk-alert-header">
<div class="risk-alert-badge" id="subdomain-risk-level-badge">CRÍTICO</div>
<strong class="risk-alert-title">Riesgo de Reconfiguración Detectado</strong>
</div>
<div id="subdomain-risk-list" class="risk-alert-list">
<!-- Se puebla dinámicamente al validar riesgos -->
</div>
</div>
<!-- Checkbox Obligatorio para Confirmar Impacto de Riesgo -->
<div id="subdomain-risk-confirmation" class="risk-confirmation-box" style="display: none;">
<input type="checkbox" id="chk-confirm-subdomain-risk" class="risk-checkbox">
<label for="chk-confirm-subdomain-risk" class="risk-checkbox-label">
<strong>Comprendo el impacto y confirmo que deseo aplicar esta reconfiguración</strong>
<span class="risk-checkbox-sub">Esta acción reconfigurará Apache2 y validará la sintaxis antes del reload.</span>
</label>
</div>
<!-- Terminal de Diagnóstico de Rollback (RFC 7807 Stderr) -->
<div id="rollback-terminal" class="rollback-terminal-container">
<div class="terminal-header">
@ -521,25 +880,109 @@
</div>
<!-- =======================================================================
Modal: Inspección de Archivos de Carpeta (/var/www/:name)
Modal: Gestor de Archivos (File Manager) para /var/www/<subdominio>
======================================================================= -->
<div id="modal-folder-files" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="folder-files-modal-title">
<div class="modal-dialog" style="max-width: 680px;">
<div id="modal-file-manager" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="fm-modal-title">
<div class="modal-dialog modal-dialog-xl">
<div class="modal-header">
<div class="modal-title-wrap">
<div class="modal-icon-badge">
<div class="modal-icon-badge" style="background: rgba(163, 230, 53, 0.12); color: var(--accent-lime); border-color: rgba(163, 230, 53, 0.25);">
<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="M3 4a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-6l-2-2H3z"></path>
</svg>
</div>
<h2 id="folder-files-modal-title" class="modal-title">Archivos de Carpeta</h2>
<div>
<h2 id="fm-modal-title" class="modal-title">Gestor de Archivos</h2>
<div id="fm-current-path-display" class="fm-path-subtitle">/var/www/subdominio</div>
</div>
</div>
<button type="button" class="modal-close-btn" aria-label="Cerrar modal">&times;</button>
</div>
<div class="modal-body">
<div id="folder-files-list-container" class="table-responsive" style="max-height: 400px; overflow-y: auto;">
<!-- Se llena dinámicamente -->
<!-- Breadcrumbs de Navegación Interactiva -->
<nav id="fm-breadcrumbs" class="fm-breadcrumbs-bar" aria-label="Ruta de carpetas">
<!-- Generado dinámicamente -->
</nav>
<!-- Barra de Herramientas del File Manager -->
<div class="fm-toolbar-container">
<div class="fm-toolbar-left">
<!-- Input oculto para subida de archivos -->
<input type="file" id="fm-file-input" style="display: none;">
<button type="button" id="fm-btn-upload" class="btn btn-primary btn-sm">
<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 12V2M4 6l4-4 4 4M2 14h12"></path>
</svg>
<span>Subir Archivo</span>
</button>
<button type="button" id="fm-btn-new-file" class="btn btn-secondary btn-sm">
<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 3v10M3 8h10"></path>
</svg>
<span>Nuevo Archivo</span>
</button>
<button type="button" id="fm-btn-new-folder" class="btn btn-secondary btn-sm">
<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 3h4l2 2h6v8H2zM8 7v4M6 9h4"></path>
</svg>
<span>Nueva Carpeta</span>
</button>
<button type="button" id="fm-btn-up-dir" class="btn btn-secondary btn-sm" title="Subir un nivel de carpeta">
<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 13V3M4 7l4-4 4 4"></path>
</svg>
<span>Subir Nivel</span>
</button>
</div>
<div class="fm-toolbar-right">
<span id="fm-items-count-text" class="text-xs text-muted">0 elementos</span>
<button type="button" id="fm-btn-refresh" class="btn btn-secondary btn-sm" title="Refrescar contenido">
<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M14 8A6 6 0 1 1 9.5 2.5M14 2.5v4h-4"></path>
</svg>
<span>Refrescar</span>
</button>
</div>
</div>
<!-- Fila de creación de nuevo elemento (archivo o carpeta) -->
<div id="fm-new-item-row" class="fm-create-item-panel" style="display: none;">
<div class="fm-create-item-form">
<span id="fm-create-type-label" class="badge badge-mode-static">Archivo</span>
<input
type="text"
id="fm-new-item-name-input"
class="form-input fm-create-input"
placeholder="nombre-archivo.php"
autocomplete="off"
>
<button type="button" id="fm-btn-confirm-create-item" class="btn btn-primary btn-sm">Crear</button>
<button type="button" id="fm-btn-cancel-create-item" class="btn btn-secondary btn-sm">Cancelar</button>
</div>
</div>
<div class="modal-body fm-modal-body">
<div class="table-responsive fm-table-wrap">
<table class="data-table fm-table">
<thead>
<tr>
<th>Nombre</th>
<th>Tipo</th>
<th>Tamaño</th>
<th>Permisos</th>
<th>Última Modificación</th>
<th style="text-align: right;">Acciones</th>
</tr>
</thead>
<tbody id="fm-files-table-body">
<!-- Se puebla dinámicamente -->
</tbody>
</table>
</div>
</div>
@ -549,6 +992,74 @@
</div>
</div>
<!-- =======================================================================
Modal: Editor de Código para Archivos Web (.php, .html, .css, .js, etc.)
======================================================================= -->
<div id="modal-code-editor" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="code-editor-file-title">
<div class="modal-dialog modal-dialog-xl code-editor-dialog">
<div class="modal-header code-editor-header">
<div class="modal-title-wrap">
<div class="modal-icon-badge" style="background: rgba(56, 189, 248, 0.12); color: #38bdf8; border-color: rgba(56, 189, 248, 0.25);">
<svg viewBox="0 0 20 20" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="14 4 18 8 14 12"></polyline>
<polyline points="6 16 2 12 6 8"></polyline>
<line x1="12" y1="2" x2="8" y2="18"></line>
</svg>
</div>
<div>
<h2 id="code-editor-file-title" class="modal-title">index.php</h2>
<div id="code-editor-file-path" class="code-editor-path">/var/www/app/index.php</div>
</div>
</div>
<div class="code-editor-header-actions">
<div id="code-editor-save-status" class="code-editor-status-tag status-clean">Sin cambios</div>
<button type="button" id="code-editor-btn-save" class="btn btn-primary btn-sm">
<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="M13 14H3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h7l4 4v7a1 1 0 0 1-1 1zM11 2v4H5V2M5 14v-5h6v5"></path>
</svg>
<span>Guardar Archivo</span>
</button>
<button type="button" id="code-editor-btn-close" class="modal-close-btn" aria-label="Cerrar editor">&times;</button>
</div>
</div>
<div class="modal-body code-editor-body">
<div class="code-editor-workspace">
<!-- Columna Izquierda: Números de Línea Sincronizados -->
<div id="code-editor-linenumbers" class="code-editor-gutter" aria-hidden="true">
1
</div>
<!-- Área de Código -->
<textarea
id="code-editor-textarea"
class="code-editor-textarea"
placeholder="Contenido del archivo..."
spellcheck="false"
autocomplete="off"
autocorrect="off"
autocapitalize="off"
wrap="off"
></textarea>
</div>
</div>
<div class="modal-footer code-editor-footer">
<div class="code-editor-footer-left">
<span id="code-editor-cursor-pos" class="text-xs text-muted tabular-nums">Línea 1, Col 1</span>
<span id="code-editor-char-count" class="text-xs text-muted tabular-nums">0 caracteres</span>
<span class="code-editor-shortcut-hint"><kbd>Ctrl + S</kbd> para guardar rápidamente</span>
</div>
<div class="code-editor-footer-right">
<button type="button" class="btn btn-secondary btn-modal-cancel">Cerrar</button>
<button type="button" id="code-editor-btn-save-bottom" class="btn btn-primary">
Guardar Cambios
</button>
</div>
</div>
</div>
</div>
<!-- =======================================================================
Modal: Crear / Editar Usuario
======================================================================= -->

View File

@ -134,6 +134,13 @@ class ApiClient {
return this.request(`/subdomains/${encodeURIComponent(name)}`, { method: 'GET' });
}
async validateSubdomain(name, data) {
return this.request(`/subdomains/${encodeURIComponent(name)}/validate`, {
method: 'POST',
body: data
});
}
async createSubdomain(data) {
return this.request('/subdomains', {
method: 'POST',
@ -167,15 +174,65 @@ class ApiClient {
return this.request('/folders', { method: 'GET' });
}
async getFolderFiles(name) {
return this.request(`/folders/${encodeURIComponent(name)}/files`, { method: 'GET' });
async getFolderFiles(name, path = '') {
const query = path ? `?path=${encodeURIComponent(path)}` : '';
return this.request(`/folders/${encodeURIComponent(name)}/files${query}`, { method: 'GET' });
}
// --- System Stats Endpoint ---
async getFileContent(name, path) {
return this.request(`/folders/${encodeURIComponent(name)}/file?path=${encodeURIComponent(path)}`, {
method: 'GET'
});
}
async saveFileContent(name, path, content) {
return this.request(`/folders/${encodeURIComponent(name)}/file`, {
method: 'PUT',
body: { path, content }
});
}
async uploadFile(name, path, fileName, base64Content) {
return this.request(`/folders/${encodeURIComponent(name)}/upload`, {
method: 'POST',
body: { path, fileName, base64Content }
});
}
async createFolderItem(name, path, itemName, type) {
return this.request(`/folders/${encodeURIComponent(name)}/item`, {
method: 'POST',
body: { path, name: itemName, type }
});
}
async deleteFolderItem(name, path) {
return this.request(`/folders/${encodeURIComponent(name)}/item?path=${encodeURIComponent(path)}`, {
method: 'DELETE'
});
}
// --- Terminal Endpoints ---
async getTerminalInfo() {
return this.request('/terminal/info', { method: 'GET' });
}
async executeCommand(command, cwd) {
return this.request('/terminal/execute', {
method: 'POST',
body: { command, cwd }
});
}
// --- System Stats & Processes Endpoints ---
async getSystemStats() {
return this.request('/system/stats', { method: 'GET' });
}
async getSystemProcesses() {
return this.request('/system/processes', { method: 'GET' });
}
// --- Users Endpoints ---
async getUsers() {
return this.request('/users', { method: 'GET' });

File diff suppressed because it is too large Load Diff

View File

@ -19,6 +19,23 @@ class StateStore {
foldersLoading: false,
foldersSearch: '',
selectedFolderFiles: null,
fileManager: {
folderName: '',
currentPath: '',
files: [],
loading: false
},
codeEditor: {
folderName: '',
filePath: '',
fileName: '',
content: '',
isDirty: false
},
terminalInfo: null,
terminalHistory: [],
monitorProcesses: [],
monitorIntervalId: null,
users: [],
usersLoading: false,
stats: null,

View File

@ -1,4 +1,5 @@
import defaultFolderService from '../services/folder.service.js';
import { sendSuccess } from '../utils/response.util.js';
export class FolderController {
constructor(folderService) {
@ -16,12 +17,75 @@ export class FolderController {
listFiles = async (req, res, next) => {
try {
const result = await this.folderService.listFilesInFolder(req.params.name);
const subPath = req.query.path || '';
const result = await this.folderService.listFilesInFolder(req.params.name, subPath);
return res.json(result);
} catch (err) {
next(err);
}
};
getFile = async (req, res, next) => {
try {
const filePath = req.query.path;
const result = await this.folderService.readFileContent(req.params.name, filePath);
return sendSuccess(res, 200, result);
} catch (err) {
next(err);
}
};
saveFile = async (req, res, next) => {
try {
const { path: filePath, content } = req.body || {};
const result = await this.folderService.saveFileContent(req.params.name, filePath, content);
return sendSuccess(res, 200, {
message: `Archivo '${result.name}' guardado exitosamente`,
...result
});
} catch (err) {
next(err);
}
};
uploadFile = async (req, res, next) => {
try {
const { path: targetDir = '', fileName, base64Content } = req.body || {};
const result = await this.folderService.uploadFile(req.params.name, targetDir, fileName, base64Content);
return sendSuccess(res, 201, {
message: `Archivo '${result.name}' subido exitosamente`,
...result
});
} catch (err) {
next(err);
}
};
createItem = async (req, res, next) => {
try {
const { path: targetDir = '', name, type } = req.body || {};
const result = await this.folderService.createItem(req.params.name, targetDir, name, type);
return sendSuccess(res, 201, {
message: `${result.type === 'directory' ? 'Directorio' : 'Archivo'} '${result.name}' creado exitosamente`,
...result
});
} catch (err) {
next(err);
}
};
deleteItem = async (req, res, next) => {
try {
const itemPath = req.query.path || req.body?.path;
const result = await this.folderService.deleteItem(req.params.name, itemPath);
return sendSuccess(res, 200, {
message: `${result.type === 'directory' ? 'Directorio' : 'Archivo'} '${result.name}' eliminado exitosamente`,
...result
});
} catch (err) {
next(err);
}
};
}
export const defaultFolderController = new FolderController();

View File

@ -38,10 +38,24 @@ export class SubdomainController {
}
};
update = async (req, res, next) => {
validateRisk = async (req, res, next) => {
try {
const { type, port } = req.body || {};
const updated = await this.siteService.updateSubdomain(req.params.name, { type, port });
const riskReport = await this.siteService.validateSubdomainRisk(req.params.name, { type, port });
return sendSuccess(res, 200, riskReport);
} catch (err) {
next(err);
}
};
update = async (req, res, next) => {
try {
const { type, port, forceConfirmed } = req.body || {};
const updated = await this.siteService.updateSubdomain(req.params.name, {
type,
port,
forceConfirmed: forceConfirmed === true || forceConfirmed === 'true'
});
return sendSuccess(res, 200, {
message: `Subdominio '${updated.name}' actualizado exitosamente`,

View File

@ -13,6 +13,15 @@ export class SystemController {
next(err);
}
};
processes = async (req, res, next) => {
try {
const procs = await this.systemService.getTopProcesses();
return res.json(procs);
} catch (err) {
next(err);
}
};
}
export const defaultSystemController = new SystemController();

View File

@ -0,0 +1,30 @@
import defaultTerminalService from '../services/terminal.service.js';
import { sendSuccess } from '../utils/response.util.js';
export class TerminalController {
constructor(terminalService) {
this.terminalService = terminalService || defaultTerminalService;
}
execute = async (req, res, next) => {
try {
const { command, cwd } = req.body || {};
const result = await this.terminalService.executeCommand(command, { cwd });
return sendSuccess(res, 200, result);
} catch (err) {
next(err);
}
};
info = async (req, res, next) => {
try {
const info = this.terminalService.getTerminalInfo();
return sendSuccess(res, 200, info);
} catch (err) {
next(err);
}
};
}
export const defaultTerminalController = new TerminalController();
export default defaultTerminalController;

View File

@ -48,42 +48,41 @@ export class UserStore {
}
/**
* Asegura que exista al menos un usuario administrador activo.
* Asegura que exista el superadministrador inmutable de .env.
*/
async ensureSuperAdmin() {
const hasAdmin = this.users.some((u) => u.role === 'admin' && u.active);
if (!hasAdmin) {
const defaultUsername = config.adminUser || 'admin';
const existingUserIndex = this.users.findIndex(
(u) => u.username.toLowerCase() === defaultUsername.toLowerCase()
);
const rootUsername = config.adminUser || 'root';
const rootPass = config.adminPass || 'ddEMVJ-N8T5mZG';
const existingIndex = this.users.findIndex(
(u) => u.username.toLowerCase() === rootUsername.toLowerCase()
);
const passwordHash = await hashPassword(config.adminPass || 'admin123456');
const now = new Date().toISOString();
const passwordHash = await hashPassword(rootPass);
const now = new Date().toISOString();
if (existingUserIndex >= 0) {
// Promover y reactivar si ya existía el username
this.users[existingUserIndex].role = 'admin';
this.users[existingUserIndex].active = true;
this.users[existingUserIndex].passwordHash = passwordHash;
this.users[existingUserIndex].updatedAt = now;
} else {
const superAdmin = {
id: `u-${crypto.randomUUID().slice(0, 8)}`,
username: defaultUsername,
passwordHash,
role: 'admin',
fullName: config.adminFullName || 'Administrador Principal',
active: true,
createdAt: now,
updatedAt: now,
lastLogin: null
};
this.users.unshift(superAdmin);
}
this.saveSync();
if (existingIndex >= 0) {
this.users[existingIndex].username = rootUsername;
this.users[existingIndex].role = 'admin';
this.users[existingIndex].active = true;
this.users[existingIndex].fullName = config.adminFullName || rootUsername;
this.users[existingIndex].passwordHash = passwordHash;
this.users[existingIndex].updatedAt = now;
} else {
const superAdmin = {
id: `u-${crypto.randomUUID().slice(0, 8)}`,
username: rootUsername,
passwordHash,
role: 'admin',
fullName: config.adminFullName || rootUsername,
active: true,
createdAt: now,
updatedAt: now,
lastLogin: null
};
this.users.unshift(superAdmin);
}
this.saveSync();
}
/**
@ -206,6 +205,35 @@ export class UserStore {
}
}
const isRoot = current.username.toLowerCase() === (config.adminUser || 'admin').toLowerCase();
if (isRoot) {
if (partial.username && partial.username.toLowerCase() !== current.username.toLowerCase()) {
const error = new Error(`El superadministrador '${current.username}' es inmutable y no se puede renombrar.`);
error.status = 403;
error.code = 'IMMUTABLE_USER_PROTECTED';
throw error;
}
if (partial.role && partial.role !== 'admin') {
const error = new Error(`El rol del superadministrador '${current.username}' no puede ser modificado.`);
error.status = 403;
error.code = 'IMMUTABLE_USER_PROTECTED';
throw error;
}
if (partial.active === false) {
const error = new Error(`El superadministrador '${current.username}' no puede ser desactivado.`);
error.status = 403;
error.code = 'IMMUTABLE_USER_PROTECTED';
throw error;
}
if (partial.passwordHash) {
const error = new Error(`La contraseña de '${current.username}' se gestiona exclusivamente en el archivo .env del servidor.`);
error.status = 403;
error.code = 'IMMUTABLE_USER_PROTECTED';
throw error;
}
}
// Verificar colisión de username si se modifica
if (partial.username && partial.username.toLowerCase() !== current.username.toLowerCase()) {
const collision = this.findByUsername(partial.username);
@ -252,6 +280,13 @@ export class UserStore {
throw error;
}
if (user.username.toLowerCase() === (config.adminUser || 'admin').toLowerCase()) {
const error = new Error(`El superadministrador '${user.username}' es inmutable y no puede ser eliminado.`);
error.status = 403;
error.code = 'IMMUTABLE_USER_PROTECTED';
throw error;
}
this.users = this.users.filter((u) => u.id !== id);
this.saveSync();
return true;
@ -265,6 +300,7 @@ export class UserStore {
sanitizeUser(user) {
if (!user) return null;
const { passwordHash, ...safe } = user;
safe.isImmutable = safe.username.toLowerCase() === (config.adminUser || 'root').toLowerCase();
return safe;
}
}

View File

@ -17,7 +17,8 @@ export function errorHandler(err, req, res, next) {
detail: err.detail || err.message || 'Error interno del servidor',
code,
instance: req.originalUrl || req.url,
rollbackExecuted: Boolean(err.rollbackExecuted)
rollbackExecuted: Boolean(err.rollbackExecuted),
...(err.riskReport ? { riskReport: err.riskReport } : {})
});
}

View File

@ -9,6 +9,11 @@ export function createFolderRoutes(folderController = defaultFolderController) {
router.get('/', folderController.list);
router.get('/:name/files', folderController.listFiles);
router.get('/:name/file', folderController.getFile);
router.put('/:name/file', folderController.saveFile);
router.post('/:name/upload', folderController.uploadFile);
router.post('/:name/item', folderController.createItem);
router.delete('/:name/item', folderController.deleteItem);
return router;
}

View File

@ -5,6 +5,7 @@ import userRoutes from './user.routes.js';
import folderRoutes from './folder.routes.js';
import systemRoutes from './system.routes.js';
import docsRoutes from './docs.routes.js';
import terminalRoutes from './terminal.routes.js';
export function createApiRouter() {
const router = Router();
@ -15,6 +16,7 @@ export function createApiRouter() {
router.use('/folders', folderRoutes);
router.use('/system', systemRoutes);
router.use('/docs', docsRoutes);
router.use('/terminal', terminalRoutes);
return router;
}

View File

@ -11,6 +11,7 @@ export function createSubdomainRoutes(subdomainController = defaultSubdomainCont
router.get('/', subdomainController.list);
router.post('/', subdomainController.create);
router.get('/:name', subdomainController.getByName);
router.post('/:name/validate', subdomainController.validateRisk);
router.put('/:name', subdomainController.update);
router.post('/:name/toggle', subdomainController.toggle);

View File

@ -8,6 +8,7 @@ export function createSystemRoutes(systemController = defaultSystemController) {
router.use(authenticate);
router.get('/stats', systemController.stats);
router.get('/processes', systemController.processes);
return router;
}

View File

@ -0,0 +1,18 @@
import { Router } from 'express';
import defaultTerminalController from '../controllers/terminal.controller.js';
import { authenticate, requireRole } from '../middlewares/auth.middleware.js';
export function createTerminalRoutes(terminalController = defaultTerminalController) {
const router = Router();
// Acceso restringido exclusivamente a administradores autenticados
router.use(authenticate);
router.use(requireRole('admin'));
router.post('/execute', terminalController.execute);
router.get('/info', terminalController.info);
return router;
}
export default createTerminalRoutes();

View File

@ -4,6 +4,30 @@ import config from '../config/env.js';
import DriverFactory from '../infrastructure/apache/driver.factory.js';
import { validateSubdomainName, sanitizePath } from '../utils/validation.util.js';
const TEXT_EXTENSIONS = new Set([
'.html', '.htm', '.php', '.phtml', '.css', '.scss', '.less',
'.js', '.mjs', '.cjs', '.ts', '.json', '.xml', '.svg',
'.txt', '.md', '.markdown', '.env', '.htaccess', '.conf',
'.ini', '.yaml', '.yml', '.sql', '.sh', '.bash', '.log'
]);
function isTextFile(fileName) {
const ext = path.extname(fileName).toLowerCase();
return TEXT_EXTENSIONS.has(ext) || !ext;
}
function applyPermissions(itemPath, isDirectory = false) {
try {
fs.chmodSync(itemPath, isDirectory ? 0o2775 : 0o664);
} catch {
try {
fs.chmodSync(itemPath, isDirectory ? 0o775 : 0o664);
} catch {
// Ignorar en entornos donde el sistema de archivos no soporte permisos octales
}
}
}
export class FolderService {
/**
* @param {import('../infrastructure/apache/apache.driver.interface.js').IApacheDriver} [driver]
@ -83,12 +107,12 @@ export class FolderService {
}
/**
* Lista los archivos contenidos dentro de una carpeta web específica.
* Protegido rigurosamente contra ataques de Path Traversal.
* Lista los archivos y subdirectorios dentro de una carpeta web específica.
* @param {string} folderName
* @param {string} [subPath='']
* @returns {Promise<object>}
*/
async listFilesInFolder(folderName) {
async listFilesInFolder(folderName, subPath = '') {
const cleanName = validateSubdomainName(folderName);
const webRoot = this.getWebRoot();
const folderPath = sanitizePath(webRoot, cleanName);
@ -108,33 +132,399 @@ export class FolderService {
throw error;
}
const entries = fs.readdirSync(folderPath);
const targetDir = subPath ? sanitizePath(folderPath, subPath) : folderPath;
if (!fs.existsSync(targetDir)) {
const error = new Error(`La ruta '${subPath}' no existe en '${cleanName}'.`);
error.status = 404;
error.code = 'PATH_NOT_FOUND';
throw error;
}
const targetStat = fs.statSync(targetDir);
if (!targetStat.isDirectory()) {
const error = new Error(`La ruta '${subPath}' no es un directorio.`);
error.status = 400;
error.code = 'NOT_A_DIRECTORY';
throw error;
}
const entries = fs.readdirSync(targetDir);
const files = [];
for (const entry of entries) {
const entryPath = path.join(folderPath, entry);
const entryPath = path.join(targetDir, entry);
try {
const itemStat = fs.statSync(entryPath);
const modeOctal = (itemStat.mode & 0o7777).toString(8).padStart(4, '0');
const isDir = itemStat.isDirectory();
const relPath = path.relative(folderPath, entryPath).replace(/\\/g, '/');
files.push({
name: entry,
type: itemStat.isDirectory() ? 'directory' : 'file',
path: relPath,
type: isDir ? 'directory' : 'file',
sizeBytes: itemStat.size,
sizeFormatted: formatBytes(itemStat.size),
permissions: modeOctal,
lastModified: itemStat.mtime.toISOString()
lastModified: itemStat.mtime.toISOString(),
isEditable: !isDir && itemStat.size <= 2 * 1024 * 1024 && isTextFile(entry)
});
} catch {
// Ignorar
// Ignorar elementos sin permisos de lectura
}
}
const currentRelative = path.relative(folderPath, targetDir).replace(/\\/g, '/');
return {
folder: cleanName,
path: currentRelative,
files
};
}
/**
* Lee el contenido de un archivo de texto dentro de una carpeta web (límite 2MB).
* @param {string} folderName
* @param {string} filePath
* @returns {Promise<object>}
*/
async readFileContent(folderName, filePath) {
const cleanName = validateSubdomainName(folderName);
const webRoot = this.getWebRoot();
const folderPath = sanitizePath(webRoot, cleanName);
if (!fs.existsSync(folderPath)) {
const error = new Error(`La carpeta web '${cleanName}' no existe.`);
error.status = 404;
error.code = 'FOLDER_NOT_FOUND';
throw error;
}
if (!filePath || typeof filePath !== 'string') {
const error = new Error("El parámetro 'filePath' es obligatorio y debe ser una cadena de texto.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
const targetFile = sanitizePath(folderPath, filePath);
if (!fs.existsSync(targetFile)) {
const error = new Error(`El archivo '${filePath}' no existe.`);
error.status = 404;
error.code = 'FILE_NOT_FOUND';
throw error;
}
const stat = fs.statSync(targetFile);
if (stat.isDirectory()) {
const error = new Error(`'${filePath}' es un directorio, no un archivo legible.`);
error.status = 400;
error.code = 'NOT_A_FILE';
throw error;
}
const maxBytes = 2 * 1024 * 1024; // 2 MB
if (stat.size > maxBytes) {
const error = new Error(`El archivo excede el tamaño máximo permitido para lectura (${formatBytes(maxBytes)}).`);
error.status = 400;
error.code = 'FILE_TOO_LARGE';
throw error;
}
const content = fs.readFileSync(targetFile, 'utf-8');
const modeOctal = (stat.mode & 0o7777).toString(8).padStart(4, '0');
const relPath = path.relative(folderPath, targetFile).replace(/\\/g, '/');
return {
folder: cleanName,
path: relPath,
name: path.basename(targetFile),
content,
sizeBytes: stat.size,
permissions: modeOctal
};
}
/**
* Guarda o actualiza el contenido de un archivo de texto con permisos 0664 y grupo www-data.
* @param {string} folderName
* @param {string} filePath
* @param {string} content
* @returns {Promise<object>}
*/
async saveFileContent(folderName, filePath, content) {
const cleanName = validateSubdomainName(folderName);
const webRoot = this.getWebRoot();
const folderPath = sanitizePath(webRoot, cleanName);
if (!fs.existsSync(folderPath)) {
const error = new Error(`La carpeta web '${cleanName}' no existe.`);
error.status = 404;
error.code = 'FOLDER_NOT_FOUND';
throw error;
}
if (!filePath || typeof filePath !== 'string') {
const error = new Error("El parámetro 'filePath' es obligatorio.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
if (content === undefined || content === null || typeof content !== 'string') {
const error = new Error("El contenido debe ser una cadena de texto.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
const targetFile = sanitizePath(folderPath, filePath);
if (fs.existsSync(targetFile)) {
const stat = fs.statSync(targetFile);
if (stat.isDirectory()) {
const error = new Error(`No es posible sobrescribir el directorio '${filePath}' como archivo.`);
error.status = 400;
error.code = 'CANNOT_OVERWRITE_DIRECTORY';
throw error;
}
}
const parentDir = path.dirname(targetFile);
if (!fs.existsSync(parentDir)) {
fs.mkdirSync(parentDir, { recursive: true });
applyPermissions(parentDir, true);
}
fs.writeFileSync(targetFile, content, 'utf-8');
applyPermissions(targetFile, false); // 0664
applyPermissions(parentDir, true); // 2775
const finalStat = fs.statSync(targetFile);
const modeOctal = (finalStat.mode & 0o7777).toString(8).padStart(4, '0');
const relPath = path.relative(folderPath, targetFile).replace(/\\/g, '/');
return {
folder: cleanName,
path: relPath,
name: path.basename(targetFile),
sizeBytes: finalStat.size,
permissions: modeOctal,
savedAt: new Date().toISOString()
};
}
/**
* Sube y decodifica un archivo en base64 en la carpeta especificada con permisos correctos.
* @param {string} folderName
* @param {string} targetDir
* @param {string} fileName
* @param {string} base64Content
* @returns {Promise<object>}
*/
async uploadFile(folderName, targetDir = '', fileName, base64Content) {
const cleanName = validateSubdomainName(folderName);
const webRoot = this.getWebRoot();
const folderPath = sanitizePath(webRoot, cleanName);
if (!fs.existsSync(folderPath)) {
const error = new Error(`La carpeta web '${cleanName}' no existe.`);
error.status = 404;
error.code = 'FOLDER_NOT_FOUND';
throw error;
}
if (!fileName || typeof fileName !== 'string') {
const error = new Error("El parámetro 'fileName' es obligatorio.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
if (base64Content === undefined || base64Content === null || typeof base64Content !== 'string') {
const error = new Error("El contenido en base64 es obligatorio.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
const safeFileName = path.basename(fileName.trim());
if (!safeFileName || safeFileName === '.' || safeFileName === '..') {
const error = new Error('Nombre de archivo inválido.');
error.status = 400;
error.code = 'INVALID_FILE_NAME';
throw error;
}
const destDir = targetDir ? sanitizePath(folderPath, targetDir) : folderPath;
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
applyPermissions(destDir, true);
}
const targetFile = path.join(destDir, safeFileName);
const buffer = Buffer.from(base64Content, 'base64');
fs.writeFileSync(targetFile, buffer);
applyPermissions(targetFile, false); // 0664
applyPermissions(destDir, true); // 2775
const stat = fs.statSync(targetFile);
const modeOctal = (stat.mode & 0o7777).toString(8).padStart(4, '0');
const relPath = path.relative(folderPath, targetFile).replace(/\\/g, '/');
return {
folder: cleanName,
path: relPath,
name: safeFileName,
sizeBytes: stat.size,
sizeFormatted: formatBytes(stat.size),
permissions: modeOctal
};
}
/**
* Crea un nuevo archivo o directorio con los permisos del sistema.
* @param {string} folderName
* @param {string} targetDir
* @param {string} name
* @param {'file'|'dir'} type
* @returns {Promise<object>}
*/
async createItem(folderName, targetDir = '', name, type) {
const cleanName = validateSubdomainName(folderName);
const webRoot = this.getWebRoot();
const folderPath = sanitizePath(webRoot, cleanName);
if (!fs.existsSync(folderPath)) {
const error = new Error(`La carpeta web '${cleanName}' no existe.`);
error.status = 404;
error.code = 'FOLDER_NOT_FOUND';
throw error;
}
if (!name || typeof name !== 'string') {
const error = new Error("El parámetro 'name' es obligatorio.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
if (type !== 'file' && type !== 'dir') {
const error = new Error("El parámetro 'type' debe ser 'file' o 'dir'.");
error.status = 400;
error.code = 'INVALID_TYPE';
throw error;
}
const safeName = path.basename(name.trim());
if (!safeName || safeName === '.' || safeName === '..') {
const error = new Error('Nombre de elemento no válido.');
error.status = 400;
error.code = 'INVALID_NAME';
throw error;
}
const destDir = targetDir ? sanitizePath(folderPath, targetDir) : folderPath;
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
applyPermissions(destDir, true);
}
const targetItem = path.join(destDir, safeName);
if (fs.existsSync(targetItem)) {
const error = new Error(`El elemento '${safeName}' ya existe en esta ubicación.`);
error.status = 409;
error.code = 'ITEM_ALREADY_EXISTS';
throw error;
}
if (type === 'dir') {
fs.mkdirSync(targetItem, { recursive: true });
applyPermissions(targetItem, true); // 2775
} else {
fs.writeFileSync(targetItem, '', 'utf-8');
applyPermissions(targetItem, false); // 0664
}
const stat = fs.statSync(targetItem);
const modeOctal = (stat.mode & 0o7777).toString(8).padStart(4, '0');
const relPath = path.relative(folderPath, targetItem).replace(/\\/g, '/');
return {
folder: cleanName,
path: relPath,
name: safeName,
type: type === 'dir' ? 'directory' : 'file',
permissions: modeOctal
};
}
/**
* Elimina un archivo o directorio de forma segura dentro de la carpeta del subdominio.
* @param {string} folderName
* @param {string} itemPath
* @returns {Promise<object>}
*/
async deleteItem(folderName, itemPath) {
const cleanName = validateSubdomainName(folderName);
const webRoot = this.getWebRoot();
const folderPath = sanitizePath(webRoot, cleanName);
if (!fs.existsSync(folderPath)) {
const error = new Error(`La carpeta web '${cleanName}' no existe.`);
error.status = 404;
error.code = 'FOLDER_NOT_FOUND';
throw error;
}
if (itemPath === undefined || itemPath === null || typeof itemPath !== 'string') {
const error = new Error("El parámetro 'itemPath' es obligatorio.");
error.status = 400;
error.code = 'VALIDATION_FAILED';
throw error;
}
const trimmed = itemPath.trim();
if (!trimmed || trimmed === '/' || trimmed === '.') {
const error = new Error('No está permitido eliminar la carpeta raíz del subdominio mediante el gestor de archivos.');
error.status = 403;
error.code = 'FORBIDDEN_OPERATION';
throw error;
}
const targetItem = sanitizePath(folderPath, trimmed);
if (targetItem === folderPath) {
const error = new Error('No está permitido eliminar la carpeta raíz del subdominio mediante el gestor de archivos.');
error.status = 403;
error.code = 'FORBIDDEN_OPERATION';
throw error;
}
if (!fs.existsSync(targetItem)) {
const error = new Error(`El elemento '${itemPath}' no existe.`);
error.status = 404;
error.code = 'ITEM_NOT_FOUND';
throw error;
}
const stat = fs.statSync(targetItem);
const isDir = stat.isDirectory();
const relPath = path.relative(folderPath, targetItem).replace(/\\/g, '/');
fs.rmSync(targetItem, { recursive: true, force: true });
return {
folder: cleanName,
path: relPath,
name: path.basename(targetItem),
deleted: true,
type: isDir ? 'directory' : 'file'
};
}
}
function formatBytes(bytes) {

View File

@ -33,13 +33,32 @@ export class SiteService {
/**
* Verifica si un sitio está en la lista de sitios protegidos e inmutables del sistema.
* @param {string} name
* @throws {Error} 403 Forbidden si está protegido
* @param {'delete'|'update'|'toggle'|'create'} [action='delete']
* @throws {Error} 403 Forbidden si la acción no está permitida para este sitio
*/
assertNotProtected(name) {
assertNotProtected(name, action = 'delete') {
const cleanName = this.normalizeName(name).toLowerCase();
const confName = `${cleanName}.conf`;
if (this.protectedSites.has(cleanName) || this.protectedSites.has(confName)) {
if (action === 'update') {
// Para 'update': NO bloquear ciegamente 'panel' o 'git'.
// Solo bloquear '000-default' y 'default-ssl' que son plantillas internas de Apache.
if (cleanName === '000-default' || cleanName === 'default-ssl') {
const error = new Error(`El sitio '${cleanName}' es una plantilla interna del servidor Apache2 y no puede ser alterado.`);
error.status = 403;
error.code = 'SITE_PROTECTED';
throw error;
}
return;
}
// Para 'delete' (y otras acciones): proteger estrictamente '000-default', 'default-ssl', 'panel' y 'git'.
const strictlyProtected = new Set(['000-default', 'default-ssl', 'panel', 'git']);
if (
strictlyProtected.has(cleanName) ||
this.protectedSites.has(cleanName) ||
this.protectedSites.has(confName)
) {
const error = new Error(`El sitio '${cleanName}' está protegido por el sistema y no puede ser alterado ni eliminado.`);
error.status = 403;
error.code = 'SITE_PROTECTED';
@ -311,16 +330,161 @@ export class SiteService {
}
/**
* Actualiza el tipo o destino de un subdominio existente con rollback.
* Evalúa y analiza los riesgos potenciales asociados a la modificación de un subdominio.
* @param {string} name
* @param {object} params
* @param {'static'|'proxy'} params.type
* @param {number} [params.port]
* @param {'static'|'proxy'} [params.type]
* @param {number|string} [params.port]
* @returns {Promise<object>}
*/
async updateSubdomain(name, { type, port }) {
async validateSubdomainRisk(name, { type, port } = {}) {
const cleanName = validateSubdomainName(name);
this.assertNotProtected(cleanName);
const existingSites = await this.listSubdomains();
const currentSite = existingSites.find((s) => s.name.toLowerCase() === cleanName.toLowerCase());
if (!currentSite) {
const error = new Error(`El subdominio '${cleanName}' no existe.`);
error.status = 404;
error.code = 'SUBDOMAIN_NOT_FOUND';
throw error;
}
const currentType = currentSite.type || 'static';
const currentPort = currentSite.port ? parseInt(currentSite.port, 10) : null;
const targetType = type ? type.toLowerCase() : currentType;
let targetPort = null;
if (targetType === 'proxy') {
if (port !== undefined && port !== null && port !== '') {
targetPort = parseInt(port, 10);
} else {
targetPort = currentPort;
}
}
const isSelfPanel = cleanName === 'panel' || cleanName === 'a2host';
const isGitea = cleanName === 'git' || cleanName === 'gitea';
const risks = [];
// 1. Detectar si es el propio panel ('panel' o 'a2host') y si se intenta cambiar su puerto o pasar a estático (riesgo crítico de auto-bloqueo)
if (isSelfPanel) {
if (targetType === 'static') {
risks.push({
level: 'critical',
code: 'SELF_PANEL_STATIC',
message: 'Cambiar el panel de administración a modo estático provocará la pérdida inmediata de acceso a la interfaz web de a2host (auto-bloqueo).'
});
} else if (targetType === 'proxy' && targetPort !== config.port) {
risks.push({
level: 'critical',
code: 'SELF_PANEL_PORT',
message: `Cambiar el puerto del panel de control (${config.port} -> ${targetPort}) provocará la pérdida inmediata de acceso a la interfaz web.`
});
}
}
// 2. Detectar si es 'git' y se cambia su puerto (3000) o modo (riesgo de desconectar Gitea)
if (isGitea) {
if (targetType === 'static') {
risks.push({
level: 'critical',
code: 'GITEA_STATIC',
message: 'Cambiar el subdominio de Git a modo estático desconectará el servicio de repositorios Gitea.'
});
} else if (targetType === 'proxy' && targetPort !== 3000) {
risks.push({
level: 'high',
code: 'GITEA_PORT',
message: `Cambiar el puerto de Git (3000 -> ${targetPort}) desconectará el acceso al servidor de repositorios Gitea.`
});
}
}
// 3. Detectar cambio de modo arquitectónico (de Proxy a Estático o viceversa)
if (currentType !== targetType) {
risks.push({
level: 'warning',
code: 'ARCHITECTURE_MODE_CHANGE',
message: `Cambio de modo arquitectónico de ${currentType.toUpperCase()} a ${targetType.toUpperCase()}. ${
targetType === 'static'
? 'El backend proxy dejará de recibir tráfico en este subdominio.'
: 'Los archivos estáticos de la carpeta web ya no serán servidos por Apache.'
}`
});
}
// 4. Detectar colisión con puertos en uso o puertos reservados del sistema
if (targetType === 'proxy') {
if (!targetPort || Number.isNaN(targetPort)) {
risks.push({
level: 'critical',
code: 'PORT_INVALID',
message: 'Se requiere un puerto numérico válido para el modo proxy.'
});
} else {
if (targetPort < 1024 || targetPort > 65535) {
risks.push({
level: 'critical',
code: 'PORT_OUT_OF_RANGE',
message: `El puerto ${targetPort} está fuera del rango no privilegiado permitido (1024 - 65535).`
});
}
const isLegitOwnPort =
(isSelfPanel && targetPort === config.port) ||
(isGitea && targetPort === 3000);
if (!isLegitOwnPort && config.reservedPorts.includes(targetPort)) {
risks.push({
level: 'critical',
code: 'PORT_RESERVED',
message: `El puerto ${targetPort} es un puerto reservado del sistema (${config.reservedPorts.join(', ')}).`
});
}
const collidingSite = existingSites.find(
(s) => s.name.toLowerCase() !== cleanName.toLowerCase() && s.type === 'proxy' && s.port === targetPort
);
if (collidingSite) {
risks.push({
level: 'high',
code: 'PORT_IN_USE',
message: `El puerto ${targetPort} ya se encuentra asignado al subdominio '${collidingSite.name}'.`
});
}
}
}
const hasRisk = risks.length > 0;
const requiresConfirmation = hasRisk;
return {
subdomain: cleanName,
currentType,
currentPort,
targetType,
targetPort,
hasRisk,
risks,
isSelfPanel,
isGitea,
requiresConfirmation
};
}
/**
* Actualiza el tipo o destino de un subdominio existente con rollback atómico y control de riesgos.
* @param {string} name
* @param {object} params
* @param {'static'|'proxy'} [params.type]
* @param {number|string} [params.port]
* @param {boolean} [params.forceConfirmed=false]
* @returns {Promise<object>}
*/
async updateSubdomain(name, { type, port, forceConfirmed = false } = {}) {
const cleanName = validateSubdomainName(name);
this.assertNotProtected(cleanName, 'update');
const driver = this.getDriver();
const existingSites = await this.listSubdomains();
@ -333,18 +497,35 @@ export class SiteService {
throw error;
}
const previousConf = await driver.readVirtualHost(cleanName);
const riskReport = await this.validateSubdomainRisk(cleanName, { type, port });
if (riskReport.requiresConfirmation && !forceConfirmed) {
const error = new Error(`La modificación del subdominio '${cleanName}' requiere confirmación explícita debido a riesgos detectados.`);
error.status = 428;
error.code = 'PRECONDITION_REQUIRED';
error.riskReport = riskReport;
throw error;
}
const targetType = riskReport.targetType;
let validatedPort = null;
if (type === 'proxy') {
if (targetType === 'proxy') {
const activePorts = existingSites
.filter((s) => s.name.toLowerCase() !== cleanName.toLowerCase() && s.type === 'proxy' && s.port)
.map((s) => s.port);
validatedPort = validatePort(port, config.reservedPorts, activePorts);
if ((riskReport.isSelfPanel && riskReport.targetPort === config.port) || (riskReport.isGitea && riskReport.targetPort === 3000)) {
validatedPort = riskReport.targetPort;
} else {
validatedPort = validatePort(riskReport.targetPort, config.reservedPorts, activePorts);
}
}
const previousConf = await driver.readVirtualHost(cleanName);
let newContent = '';
if (type === 'static') {
if (targetType === 'static') {
await driver.ensureWebDirectory(cleanName);
newContent = this.templateService.renderStaticSiteTemplate({
subdomain: cleanName,
@ -380,8 +561,8 @@ export class SiteService {
return {
name: cleanName,
fullDomain: `${cleanName}.${config.baseDomain}`,
type,
target: type === 'static' ? `${config.webRoot}/${cleanName}` : `http://127.0.0.1:${validatedPort}`,
type: targetType,
target: targetType === 'static' ? `${config.webRoot}/${cleanName}` : `http://127.0.0.1:${validatedPort}`,
port: validatedPort,
enabled: currentSite.enabled,
protected: false

View File

@ -1,5 +1,7 @@
import fs from 'node:fs';
import os from 'node:os';
import process from 'node:process';
import { execFile } from 'node:child_process';
import config from '../config/env.js';
import DriverFactory from '../infrastructure/apache/driver.factory.js';
@ -16,23 +18,128 @@ export class SystemService {
}
/**
* Genera una instantánea de telemetría y salud del sistema.
* 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.
* @returns {Promise<object>}
*/
async getSystemStats() {
const driver = this.getDriver();
// Memoria del host
const hostTotal = os.totalmem();
const hostFree = os.freemem();
const hostUsed = hostTotal - hostFree;
const hostUsedPercent = parseFloat(((hostUsed / hostTotal) * 100).toFixed(1));
// 1. CPU usage y loadavg
const loadavg = os.loadavg();
const cpus = os.cpus() || [];
const cpuCount = cpus.length;
// Memoria del proceso Node.js (vs límite PM2 de 120MB)
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();
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;
}
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
// Información de Apache
// 3. Disco: uso de '/' usando fs.statfsSync('/') nativo
let disk = {
totalBytes: 0,
totalFormatted: '0 B',
freeBytes: 0,
freeFormatted: '0 B',
usedBytes: 0,
usedFormatted: '0 B',
usedPercent: 0
};
try {
if (typeof fs.statfsSync === 'function') {
const stat = fs.statfsSync('/');
const diskTotal = stat.bsize * stat.blocks;
const diskFree = stat.bsize * stat.bavail;
const diskUsed = diskTotal - diskFree;
const diskPercent = diskTotal > 0 ? parseFloat(((diskUsed / diskTotal) * 100).toFixed(1)) : 0;
disk = {
totalBytes: diskTotal,
totalFormatted: formatBytes(diskTotal),
freeBytes: diskFree,
freeFormatted: formatBytes(diskFree),
usedBytes: diskUsed,
usedFormatted: formatBytes(diskUsed),
usedPercent: diskPercent
};
}
} catch {
// Ignorar si fs.statfsSync no está disponible en la plataforma
}
// 4. Información de Apache
const isMock = config.mockApache || typeof driver.cleanupMock === 'function';
const isInstalled = await driver.isInstalled();
const isActive = await driver.isActive();
@ -58,10 +165,27 @@ export class SystemService {
uptimeFormatted: formatUptime(os.uptime()),
processUptimeSeconds: Math.floor(process.uptime())
},
cpu: {
cores: cpuCount,
model: cpus[0]?.model || 'Generic CPU',
speedMhz: cpus[0]?.speed || 0,
loadavg1m: parseFloat(loadavg[0].toFixed(2)),
loadavg5m: parseFloat(loadavg[1].toFixed(2)),
loadavg15m: parseFloat(loadavg[2].toFixed(2)),
loadavgFormatted: `${loadavg[0].toFixed(2)}, ${loadavg[1].toFixed(2)}, ${loadavg[2].toFixed(2)}`,
usagePercent: cpuUsagePercent
},
memory: {
hostTotalBytes: hostTotal,
hostFreeBytes: hostFree,
hostUsedBytes: hostUsed,
hostTotalBytes,
hostTotalFormatted: formatBytes(hostTotalBytes),
hostFreeBytes,
hostFreeFormatted: formatBytes(hostFreeBytes),
hostAvailableBytes,
hostAvailableFormatted: formatBytes(hostAvailableBytes),
buffersCacheBytes,
buffersCacheFormatted: formatBytes(buffersCacheBytes),
hostUsedBytes,
hostUsedFormatted: formatBytes(hostUsedBytes),
hostUsedPercent,
processRssBytes: memUsage.rss,
processRssFormatted: formatBytes(memUsage.rss),
@ -71,6 +195,16 @@ export class SystemService {
pm2LimitFormatted: '120 MB',
rssPercentageOfLimit: parseFloat(((memUsage.rss / pm2LimitBytes) * 100).toFixed(1))
},
swap: {
totalBytes: swapTotalBytes,
totalFormatted: formatBytes(swapTotalBytes),
freeBytes: swapFreeBytes,
freeFormatted: formatBytes(swapFreeBytes),
usedBytes: swapUsedBytes,
usedFormatted: formatBytes(swapUsedBytes),
usedPercent: swapUsedPercent
},
disk,
apache: {
installed: isInstalled,
mockMode: isMock,
@ -80,6 +214,96 @@ export class SystemService {
}
};
}
/**
* Retorna los 8 procesos con mayor consumo de memoria en el sistema.
* @returns {Promise<Array<object>>}
*/
async getTopProcesses() {
return new Promise((resolve) => {
execFile(
'/bin/bash',
['-c', 'ps -eo pid,user,%cpu,%mem,rss,comm --sort=-rss | head -n 9'],
{ timeout: 5000 },
(err, stdout) => {
if (err || !stdout) {
return resolve(this.getMockProcesses());
}
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;
const parts = line.split(/\s+/);
if (parts.length >= 6) {
const pid = parseInt(parts[0], 10);
const user = parts[1];
const cpu = parseFloat(parts[2]);
const mem = parseFloat(parts[3]);
const rssKb = parseInt(parts[4], 10);
const comm = parts.slice(5).join(' ');
processes.push({
pid: Number.isNaN(pid) ? 0 : pid,
user: user || 'root',
cpuPercent: Number.isNaN(cpu) ? 0 : cpu,
memPercent: Number.isNaN(mem) ? 0 : mem,
rssBytes: Number.isNaN(rssKb) ? 0 : rssKb * 1024,
rssFormatted: formatBytes(Number.isNaN(rssKb) ? 0 : rssKb * 1024),
command: comm
});
}
}
if (processes.length === 0) {
return resolve(this.getMockProcesses());
}
resolve(processes);
}
);
});
}
/**
* Fallback de procesos simulados para entornos locales o sin comando ps.
* @returns {Array<object>}
*/
getMockProcesses() {
const memUsage = process.memoryUsage();
return [
{
pid: process.pid,
user: config.systemUser || 'ggc',
cpuPercent: 0.5,
memPercent: 3.2,
rssBytes: memUsage.rss,
rssFormatted: formatBytes(memUsage.rss),
command: 'node /src/index.js'
},
{
pid: 1042,
user: 'root',
cpuPercent: 0.1,
memPercent: 1.8,
rssBytes: 18 * 1024 * 1024,
rssFormatted: '18.0 MB',
command: 'systemd'
},
{
pid: 1450,
user: 'www-data',
cpuPercent: 0.0,
memPercent: 1.2,
rssBytes: 12 * 1024 * 1024,
rssFormatted: '12.0 MB',
command: 'apache2'
}
];
}
}
function formatBytes(bytes) {

View File

@ -21,6 +21,7 @@ export class TemplateService {
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
DirectoryIndex index.php index.html index.htm
</Directory>
ErrorLog \${APACHE_LOG_DIR}/${subdomain}_error.log

View File

@ -0,0 +1,114 @@
import { execFile } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import config from '../config/env.js';
export class TerminalService {
constructor(defaultCwd) {
this.defaultCwd = defaultCwd || config.webRoot;
}
getShellBinary() {
if (fs.existsSync('/bin/bash')) return '/bin/bash';
return process.env.SHELL || '/bin/sh';
}
/**
* Ejecuta un comando en el servidor con aislamiento y límites de recursos.
* @param {string} command Comando bash a ejecutar
* @param {object} [options]
* @param {string} [options.cwd] Directorio de trabajo
* @returns {Promise<object>} { stdout, stderr, exitCode, executionTimeMs, cwd }
*/
async executeCommand(command, { cwd } = {}) {
if (!command || typeof command !== 'string') {
const error = new Error("El parámetro 'command' es obligatorio y debe ser una cadena de texto.");
error.status = 400;
error.code = 'INVALID_COMMAND';
throw error;
}
let effectiveCwd = cwd || this.defaultCwd;
if (!fs.existsSync(effectiveCwd)) {
effectiveCwd = this.defaultCwd;
}
if (!fs.existsSync(effectiveCwd)) {
effectiveCwd = process.cwd();
}
const shell = this.getShellBinary();
const startTime = Date.now();
return new Promise((resolve) => {
execFile(
shell,
['-c', command],
{
timeout: 30000,
maxBuffer: 2 * 1024 * 1024,
cwd: effectiveCwd
},
(error, stdout, stderr) => {
const executionTimeMs = Date.now() - startTime;
let exitCode = 0;
let outStr = stdout || '';
let errStr = stderr || '';
if (error) {
if (error.killed && error.signal === 'SIGTERM') {
exitCode = 124;
errStr = errStr ? `${errStr}\nComando abortado por timeout (30s)` : 'Comando abortado por timeout (30s)';
} else if (typeof error.code === 'number') {
exitCode = error.code;
} else {
exitCode = error.status || 1;
}
if (!errStr && !outStr && error.message) {
errStr = error.message;
}
}
resolve({
stdout: outStr,
stderr: errStr,
exitCode,
executionTimeMs,
cwd: effectiveCwd
});
}
);
});
}
/**
* Retorna información contextual del entorno para la terminal.
* @returns {object}
*/
getTerminalInfo() {
let username = config.systemUser || 'ggc';
try {
const userInfo = os.userInfo();
if (userInfo && userInfo.username) {
username = userInfo.username;
}
} catch {
// Ignorar en entornos restringidos
}
let effectiveCwd = this.defaultCwd;
if (!fs.existsSync(effectiveCwd)) {
effectiveCwd = process.cwd();
}
return {
user: username,
cwd: effectiveCwd,
hostname: os.hostname(),
shell: this.getShellBinary()
};
}
}
export const defaultTerminalService = new TerminalService();
export default defaultTerminalService;

View File

@ -9,7 +9,8 @@ export function sendProblem(res, {
code = 'INTERNAL_ERROR',
instance,
type,
rollbackExecuted = false
rollbackExecuted = false,
...extra
}) {
const errorType = type || `https://a2host.elingejose.com/errors/${code.toLowerCase().replace(/_/g, '-')}`;
@ -21,7 +22,8 @@ export function sendProblem(res, {
instance: instance || res.req?.originalUrl || res.req?.url || '/api',
code,
rollbackExecuted,
timestamp: new Date().toISOString()
timestamp: new Date().toISOString(),
...extra
};
res.status(status);
@ -46,6 +48,7 @@ function defaultTitleForStatus(status) {
case 404: return 'Recurso No Encontrado';
case 409: return 'Conflicto de Recursos';
case 422: return 'Entidad No Procesable';
case 428: return 'Condición Previa Requerida';
case 429: return 'Demasiadas Solicitudes';
case 500: return 'Error Interno del Servidor';
default: return 'Error';

View File

@ -0,0 +1,355 @@
import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { createApp } from '../../src/app.js';
import { MockApacheDriver } from '../../src/infrastructure/apache/mock.apache.driver.js';
import DriverFactory from '../../src/infrastructure/apache/driver.factory.js';
import defaultUserStore from '../../src/infrastructure/storage/user.store.js';
import config from '../../src/config/env.js';
describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)', () => {
const testTmpDir = path.resolve(process.cwd(), '.tmp/test-new-endpoints');
const testUserDataPath = path.join(testTmpDir, 'users.json');
let server;
let baseUrl;
let adminCookie;
let operatorCookie;
let mockDriver;
before(async () => {
if (fs.existsSync(testTmpDir)) {
fs.rmSync(testTmpDir, { recursive: true, force: true });
}
fs.mkdirSync(testTmpDir, { recursive: true });
mockDriver = new MockApacheDriver(testTmpDir);
DriverFactory.setDriver(mockDriver);
defaultUserStore.filePath = testUserDataPath;
await defaultUserStore.init({ seedAdmin: true });
const app = createApp();
await new Promise((resolve) => {
server = app.listen(0, '127.0.0.1', () => {
const addr = server.address();
baseUrl = `http://127.0.0.1:${addr.port}`;
resolve();
});
});
// Login Admin
const adminLoginRes = await fetch(`${baseUrl}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'admin', password: config.adminPass })
});
adminCookie = adminLoginRes.headers.get('set-cookie')?.split(';')[0];
// Crear operador para validar permisos
await fetch(`${baseUrl}/api/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({
username: 'operator1',
password: 'OperatorPass123!',
fullName: 'Operador de Pruebas',
role: 'operator'
})
});
// Login Operator
const operatorLoginRes = await fetch(`${baseUrl}/api/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'operator1', password: 'OperatorPass123!' })
});
operatorCookie = operatorLoginRes.headers.get('set-cookie')?.split(';')[0];
});
after(async () => {
await new Promise((resolve) => {
if (server) {
server.close(resolve);
} else {
resolve();
}
});
DriverFactory.resetDriver();
if (fs.existsSync(testTmpDir)) {
fs.rmSync(testTmpDir, { recursive: true, force: true });
}
});
describe('1. Subdomain Risk & Update API', () => {
it('POST /api/subdomains/:name/validate - Debe evaluar riesgos y retornar riskReport (200)', async () => {
const res = await fetch(`${baseUrl}/api/subdomains/git/validate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ type: 'static' })
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.subdomain, 'git');
assert.equal(data.isGitea, true);
assert.equal(data.hasRisk, true);
assert.equal(data.requiresConfirmation, true);
assert.ok(data.risks.some((r) => r.code === 'GITEA_STATIC'));
});
it('PUT /api/subdomains/:name - Debe rechazar con 428 si hay riesgos y no se confirma', async () => {
const res = await fetch(`${baseUrl}/api/subdomains/git`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ type: 'static' })
});
assert.equal(res.status, 428);
const data = await res.json();
assert.equal(data.code, 'PRECONDITION_REQUIRED');
assert.ok(data.riskReport);
assert.equal(data.riskReport.requiresConfirmation, true);
});
it('PUT /api/subdomains/:name - Debe permitir actualizar con forceConfirmed: true (200)', async () => {
// Crear un subdominio de prueba
await fetch(`${baseUrl}/api/subdomains`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ name: 'my-service', type: 'static' })
});
// Modificarlo a proxy confirmando explícitamente
const res = await fetch(`${baseUrl}/api/subdomains/my-service`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({
type: 'proxy',
port: 8888,
forceConfirmed: true
})
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.subdomain.type, 'proxy');
assert.equal(data.subdomain.port, 8888);
});
});
describe('2. File Manager API (/api/folders)', () => {
const folder = 'site-files';
before(async () => {
await fetch(`${baseUrl}/api/subdomains`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ name: folder, type: 'static' })
});
});
it('POST /api/folders/:name/item - Debe crear un nuevo archivo o subdirectorio (201)', async () => {
const dirRes = await fetch(`${baseUrl}/api/folders/${folder}/item`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ path: '', name: 'src', type: 'dir' })
});
assert.equal(dirRes.status, 201);
const fileRes = await fetch(`${baseUrl}/api/folders/${folder}/item`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ path: 'src', name: 'app.js', type: 'file' })
});
assert.equal(fileRes.status, 201);
});
it('PUT /api/folders/:name/file - Debe guardar contenido de archivo (200)', async () => {
const res = await fetch(`${baseUrl}/api/folders/${folder}/file`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({
path: 'src/app.js',
content: 'console.log("Servidor iniciado");'
})
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.name, 'app.js');
});
it('GET /api/folders/:name/file - Debe leer el contenido del archivo (200)', async () => {
const res = await fetch(`${baseUrl}/api/folders/${folder}/file?path=src/app.js`, {
headers: { Cookie: adminCookie }
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.content, 'console.log("Servidor iniciado");');
});
it('POST /api/folders/:name/upload - Debe subir un archivo codificado en base64 (201)', async () => {
const content = 'Contenido subido por base64';
const base64 = Buffer.from(content, 'utf-8').toString('base64');
const res = await fetch(`${baseUrl}/api/folders/${folder}/upload`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({
path: '',
fileName: 'uploaded-test.txt',
base64Content: base64
})
});
assert.equal(res.status, 201);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.name, 'uploaded-test.txt');
});
it('GET /api/folders/:name/files - Debe listar archivos con soporte para query ?path= (200)', async () => {
const res = await fetch(`${baseUrl}/api/folders/${folder}/files?path=src`, {
headers: { Cookie: adminCookie }
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.folder, folder);
assert.equal(data.path, 'src');
assert.ok(data.files.some((f) => f.name === 'app.js'));
});
it('DELETE /api/folders/:name/item - Debe eliminar archivo de forma segura (200)', async () => {
const res = await fetch(`${baseUrl}/api/folders/${folder}/item`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ path: 'uploaded-test.txt' })
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.deleted, true);
});
});
describe('3. Remote Web Terminal API (/api/terminal)', () => {
it('POST /api/terminal/execute - Operador debe ser rechazado con 403 Forbidden', async () => {
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: operatorCookie
},
body: JSON.stringify({ command: 'whoami' })
});
assert.equal(res.status, 403);
});
it('POST /api/terminal/execute - Administrador puede ejecutar comandos y recibir output (200)', async () => {
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: adminCookie
},
body: JSON.stringify({ command: 'echo "a2host terminal execution test"' })
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.equal(data.exitCode, 0);
assert.ok(data.stdout.includes('a2host terminal execution test'));
assert.equal(typeof data.executionTimeMs, 'number');
});
it('GET /api/terminal/info - Debe retornar información del entorno de shell (200)', async () => {
const res = await fetch(`${baseUrl}/api/terminal/info`, {
headers: { Cookie: adminCookie }
});
assert.equal(res.status, 200);
const data = await res.json();
assert.equal(data.success, true);
assert.ok(data.user);
assert.ok(data.cwd);
assert.ok(data.hostname);
assert.ok(data.shell);
});
});
describe('4. Extended System & Processes API (/api/system)', () => {
it('GET /api/system/stats - Debe retornar estadísticas extendidas de CPU, Swap y Disco (200)', async () => {
const res = await fetch(`${baseUrl}/api/system/stats`, {
headers: { Cookie: adminCookie }
});
assert.equal(res.status, 200);
const stats = await res.json();
assert.ok(stats.cpu);
assert.ok(stats.swap);
assert.ok(stats.disk);
assert.ok(stats.memory.hostTotalBytes > 0);
});
it('GET /api/system/processes - Debe retornar top procesos por memoria (200)', async () => {
const res = await fetch(`${baseUrl}/api/system/processes`, {
headers: { Cookie: adminCookie }
});
assert.equal(res.status, 200);
const procs = await res.json();
assert.ok(Array.isArray(procs));
assert.ok(procs.length > 0);
assert.ok(procs[0].pid !== undefined);
assert.ok(procs[0].user);
assert.ok(procs[0].rssBytes !== undefined);
});
});
});

View File

@ -151,7 +151,8 @@ describe('Integration Tests: Atomic Rollback Transaction (rollback.test.js)', ()
try {
await updateService.updateSubdomain('update-target', {
type: 'proxy',
port: 9090
port: 9090,
forceConfirmed: true
});
assert.fail('Debió fallar con error de sintaxis');
} catch (err) {

View File

@ -0,0 +1,191 @@
import { describe, it, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { MockApacheDriver } from '../../src/infrastructure/apache/mock.apache.driver.js';
import { FolderService } from '../../src/services/folder.service.js';
describe('Unit Tests: Folder Service & File Manager (folder.service.js)', () => {
const testTmpDir = path.resolve(process.cwd(), '.tmp/test-folder-manager');
let mockDriver;
let folderService;
let testWebRoot;
beforeEach(() => {
if (fs.existsSync(testTmpDir)) {
fs.rmSync(testTmpDir, { recursive: true, force: true });
}
mockDriver = new MockApacheDriver(testTmpDir);
testWebRoot = mockDriver.webRoot;
folderService = new FolderService(mockDriver);
});
afterEach(() => {
if (fs.existsSync(testTmpDir)) {
fs.rmSync(testTmpDir, { recursive: true, force: true });
}
});
it('listFilesInFolder: debe listar archivos en la raíz y en subdirectorios con metadatos completos', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
const subDir = path.join(siteDir, 'css');
fs.mkdirSync(subDir, { recursive: true });
fs.writeFileSync(path.join(siteDir, 'index.html'), '<h1>Hola</h1>', 'utf-8');
fs.writeFileSync(path.join(subDir, 'style.css'), 'body { margin: 0; }', 'utf-8');
// Listar raíz
const rootList = await folderService.listFilesInFolder('my-site');
assert.equal(rootList.folder, 'my-site');
assert.equal(rootList.path, '');
assert.equal(rootList.files.length, 2);
const indexFile = rootList.files.find((f) => f.name === 'index.html');
assert.ok(indexFile);
assert.equal(indexFile.type, 'file');
assert.equal(indexFile.isEditable, true);
const cssFolder = rootList.files.find((f) => f.name === 'css');
assert.ok(cssFolder);
assert.equal(cssFolder.type, 'directory');
// Listar subdirectorio
const subList = await folderService.listFilesInFolder('my-site', 'css');
assert.equal(subList.folder, 'my-site');
assert.equal(subList.path, 'css');
assert.equal(subList.files.length, 1);
assert.equal(subList.files[0].name, 'style.css');
});
it('readFileContent: debe leer el contenido de texto hasta 2MB', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
const content = '<?php echo "Hello World"; ?>';
fs.writeFileSync(path.join(siteDir, 'info.php'), content, 'utf-8');
const result = await folderService.readFileContent('my-site', 'info.php');
assert.equal(result.folder, 'my-site');
assert.equal(result.name, 'info.php');
assert.equal(result.content, content);
assert.ok(result.sizeBytes > 0);
});
it('readFileContent: debe rechazar la lectura si el archivo supera los 2MB', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
const largeFile = path.join(siteDir, 'huge.dat');
// Crear archivo de 2.5 MB
const buffer = Buffer.alloc(2.5 * 1024 * 1024);
fs.writeFileSync(largeFile, buffer);
await assert.rejects(
async () => folderService.readFileContent('my-site', 'huge.dat'),
(err) => {
assert.equal(err.status, 400);
assert.equal(err.code, 'FILE_TOO_LARGE');
return true;
}
);
});
it('saveFileContent: debe guardar contenido y aplicar permisos 0664', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
const result = await folderService.saveFileContent('my-site', 'app.js', 'console.log("ok");');
assert.equal(result.name, 'app.js');
assert.equal(result.path, 'app.js');
const filePath = path.join(siteDir, 'app.js');
assert.ok(fs.existsSync(filePath));
const savedContent = fs.readFileSync(filePath, 'utf-8');
assert.equal(savedContent, 'console.log("ok");');
});
it('uploadFile: debe decodificar contenido base64 y guardarlo correctamente', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
const rawText = 'Hello from base64 upload!';
const base64 = Buffer.from(rawText, 'utf-8').toString('base64');
const uploaded = await folderService.uploadFile('my-site', '', 'uploaded.txt', base64);
assert.equal(uploaded.name, 'uploaded.txt');
const filePath = path.join(siteDir, 'uploaded.txt');
assert.ok(fs.existsSync(filePath));
assert.equal(fs.readFileSync(filePath, 'utf-8'), rawText);
});
it('createItem: debe crear archivos y directorios con validación de colisiones', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
// Crear directorio
const dirItem = await folderService.createItem('my-site', '', 'assets', 'dir');
assert.equal(dirItem.type, 'directory');
assert.ok(fs.existsSync(path.join(siteDir, 'assets')));
// Crear archivo dentro de assets
const fileItem = await folderService.createItem('my-site', 'assets', 'main.css', 'file');
assert.equal(fileItem.type, 'file');
assert.ok(fs.existsSync(path.join(siteDir, 'assets/main.css')));
// Debe rechazar duplicados
await assert.rejects(
async () => folderService.createItem('my-site', 'assets', 'main.css', 'file'),
(err) => {
assert.equal(err.status, 409);
assert.equal(err.code, 'ITEM_ALREADY_EXISTS');
return true;
}
);
});
it('deleteItem: debe eliminar archivos y directorios de forma segura', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
const targetFile = path.join(siteDir, 'trash.txt');
fs.mkdirSync(siteDir, { recursive: true });
fs.writeFileSync(targetFile, 'delete me');
const res = await folderService.deleteItem('my-site', 'trash.txt');
assert.equal(res.deleted, true);
assert.equal(fs.existsSync(targetFile), false);
});
it('deleteItem: debe impedir la eliminación de la raíz del subdominio', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
await assert.rejects(
async () => folderService.deleteItem('my-site', ''),
(err) => {
assert.equal(err.status, 403);
assert.equal(err.code, 'FORBIDDEN_OPERATION');
return true;
}
);
});
it('debe proteger contra intentos de Path Traversal en todas las operaciones', async () => {
const siteDir = path.join(testWebRoot, 'my-site');
fs.mkdirSync(siteDir, { recursive: true });
await assert.rejects(
async () => folderService.readFileContent('my-site', '../../../../etc/passwd'),
(err) => {
assert.equal(err.status, 403);
assert.equal(err.code, 'PATH_TRAVERSAL_DETECTED');
return true;
}
);
await assert.rejects(
async () => folderService.saveFileContent('my-site', '../../../../etc/malicious', 'hacked'),
(err) => {
assert.equal(err.status, 403);
assert.equal(err.code, 'PATH_TRAVERSAL_DETECTED');
return true;
}
);
});
});

View File

@ -0,0 +1,198 @@
import { describe, it, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { MockApacheDriver } from '../../src/infrastructure/apache/mock.apache.driver.js';
import { SiteService } from '../../src/services/site.service.js';
import { TemplateService } from '../../src/services/template.service.js';
import config from '../../src/config/env.js';
describe('Unit Tests: Subdomain Risk Validation & Protection Policies', () => {
const testTmpDir = path.resolve(process.cwd(), '.tmp/test-risk');
let mockDriver;
let siteService;
beforeEach(() => {
if (fs.existsSync(testTmpDir)) {
fs.rmSync(testTmpDir, { recursive: true, force: true });
}
mockDriver = new MockApacheDriver(testTmpDir);
siteService = new SiteService(mockDriver, new TemplateService());
});
afterEach(() => {
if (fs.existsSync(testTmpDir)) {
fs.rmSync(testTmpDir, { recursive: true, force: true });
}
});
describe('1. assertNotProtected(name, action)', () => {
it("para 'delete': debe proteger estrictamente '000-default', 'default-ssl', 'panel' y 'git'", () => {
const protectedNames = ['000-default', 'default-ssl', 'panel', 'git'];
for (const name of protectedNames) {
assert.throws(
() => siteService.assertNotProtected(name, 'delete'),
(err) => {
assert.equal(err.status, 403);
assert.equal(err.code, 'SITE_PROTECTED');
return true;
},
`Debe bloquear 'delete' sobre ${name}`
);
}
});
it("para 'update': NO debe bloquear 'panel' ni 'git'", () => {
assert.doesNotThrow(() => {
siteService.assertNotProtected('panel', 'update');
});
assert.doesNotThrow(() => {
siteService.assertNotProtected('git', 'update');
});
});
it("para 'update': SOLO debe bloquear '000-default' y 'default-ssl'", () => {
assert.throws(
() => siteService.assertNotProtected('000-default', 'update'),
(err) => {
assert.equal(err.status, 403);
assert.equal(err.code, 'SITE_PROTECTED');
return true;
}
);
assert.throws(
() => siteService.assertNotProtected('default-ssl', 'update'),
(err) => {
assert.equal(err.status, 403);
assert.equal(err.code, 'SITE_PROTECTED');
return true;
}
);
});
});
describe('2. validateSubdomainRisk(name, { type, port })', () => {
it('debe detectar riesgo crítico de auto-bloqueo si es panel y se cambia a estático', async () => {
await mockDriver.createVirtualHost(
'panel',
`<VirtualHost *:80>
ServerName panel.${config.baseDomain}
ProxyPass / http://127.0.0.1:${config.port}/
</VirtualHost>`
);
const risk = await siteService.validateSubdomainRisk('panel', { type: 'static' });
assert.equal(risk.subdomain, 'panel');
assert.equal(risk.isSelfPanel, true);
assert.equal(risk.hasRisk, true);
assert.equal(risk.requiresConfirmation, true);
assert.ok(risk.risks.some((r) => r.code === 'SELF_PANEL_STATIC' && r.level === 'critical'));
});
it('debe detectar riesgo crítico de auto-bloqueo si es panel y se cambia su puerto', async () => {
await mockDriver.createVirtualHost(
'panel',
`<VirtualHost *:80>
ServerName panel.${config.baseDomain}
ProxyPass / http://127.0.0.1:${config.port}/
</VirtualHost>`
);
const risk = await siteService.validateSubdomainRisk('panel', { type: 'proxy', port: 8080 });
assert.equal(risk.isSelfPanel, true);
assert.equal(risk.hasRisk, true);
assert.equal(risk.requiresConfirmation, true);
assert.ok(risk.risks.some((r) => r.code === 'SELF_PANEL_PORT' && r.level === 'critical'));
});
it('debe detectar riesgo crítico si es git y se intenta cambiar a estático', async () => {
const risk = await siteService.validateSubdomainRisk('git', { type: 'static' });
assert.equal(risk.isGitea, true);
assert.equal(risk.hasRisk, true);
assert.equal(risk.requiresConfirmation, true);
assert.ok(risk.risks.some((r) => r.code === 'GITEA_STATIC' && r.level === 'critical'));
});
it('debe detectar riesgo si es git y se intenta cambiar su puerto de 3000 a otro', async () => {
const risk = await siteService.validateSubdomainRisk('git', { type: 'proxy', port: 4000 });
assert.equal(risk.isGitea, true);
assert.equal(risk.hasRisk, true);
assert.equal(risk.requiresConfirmation, true);
assert.ok(risk.risks.some((r) => r.code === 'GITEA_PORT' && r.level === 'high'));
});
it('debe detectar cambio de modo arquitectónico de Static a Proxy', async () => {
await siteService.createSubdomain({ name: 'blog', type: 'static' });
const risk = await siteService.validateSubdomainRisk('blog', { type: 'proxy', port: 8080 });
assert.equal(risk.currentType, 'static');
assert.equal(risk.targetType, 'proxy');
assert.equal(risk.hasRisk, true);
assert.equal(risk.requiresConfirmation, true);
assert.ok(risk.risks.some((r) => r.code === 'ARCHITECTURE_MODE_CHANGE'));
});
it('debe detectar colisión con puertos reservados del sistema', async () => {
await siteService.createSubdomain({ name: 'api-service', type: 'proxy', port: 8080 });
// Intentar cambiar a puerto 3306 (MySQL reservado)
const risk = await siteService.validateSubdomainRisk('api-service', { type: 'proxy', port: 3306 });
assert.equal(risk.hasRisk, true);
assert.ok(risk.risks.some((r) => r.code === 'PORT_RESERVED'));
});
it('debe detectar colisión con puertos ya en uso por otros subdominios', async () => {
await siteService.createSubdomain({ name: 'app1', type: 'proxy', port: 5000 });
await siteService.createSubdomain({ name: 'app2', type: 'proxy', port: 6000 });
// Intentar cambiar app2 al puerto 5000 usado por app1
const risk = await siteService.validateSubdomainRisk('app2', { type: 'proxy', port: 5000 });
assert.equal(risk.hasRisk, true);
assert.ok(risk.risks.some((r) => r.code === 'PORT_IN_USE'));
});
});
describe('3. updateSubdomain con confirmación atómica', () => {
it('debe rechazar con 428 Precondition Required si requiresConfirmation y !forceConfirmed', async () => {
await siteService.createSubdomain({ name: 'service-a', type: 'static' });
let caught = null;
try {
await siteService.updateSubdomain('service-a', {
type: 'proxy',
port: 7000,
forceConfirmed: false
});
} catch (err) {
caught = err;
}
assert.ok(caught);
assert.equal(caught.status, 428);
assert.equal(caught.code, 'PRECONDITION_REQUIRED');
assert.ok(caught.riskReport);
assert.equal(caught.riskReport.requiresConfirmation, true);
});
it('debe proceder exitosamente si forceConfirmed === true', async () => {
await siteService.createSubdomain({ name: 'service-b', type: 'static' });
const updated = await siteService.updateSubdomain('service-b', {
type: 'proxy',
port: 7001,
forceConfirmed: true
});
assert.equal(updated.name, 'service-b');
assert.equal(updated.type, 'proxy');
assert.equal(updated.port, 7001);
});
});
});

View File

@ -0,0 +1,67 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { SystemService } from '../../src/services/system.service.js';
import { MockApacheDriver } from '../../src/infrastructure/apache/mock.apache.driver.js';
describe('Unit Tests: Extended System Service & Telemetry (system.service.js)', () => {
const mockDriver = new MockApacheDriver();
const systemService = new SystemService(mockDriver);
it('getSystemStats: debe retornar telemetría completa de CPU, RAM, Swap y Disco', async () => {
const stats = await systemService.getSystemStats();
// CPU
assert.ok(stats.cpu);
assert.ok(stats.cpu.cores > 0);
assert.equal(typeof stats.cpu.loadavg1m, 'number');
assert.equal(typeof stats.cpu.loadavg5m, 'number');
assert.equal(typeof stats.cpu.loadavg15m, 'number');
assert.equal(typeof stats.cpu.usagePercent, 'number');
// RAM detallada
assert.ok(stats.memory);
assert.ok(stats.memory.hostTotalBytes > 0);
assert.ok(stats.memory.hostTotalFormatted);
assert.equal(typeof stats.memory.hostFreeBytes, 'number');
assert.equal(typeof stats.memory.hostAvailableBytes, 'number');
assert.equal(typeof stats.memory.buffersCacheBytes, 'number');
assert.equal(typeof stats.memory.hostUsedBytes, 'number');
assert.equal(typeof stats.memory.hostUsedPercent, 'number');
// Swap
assert.ok(stats.swap);
assert.equal(typeof stats.swap.totalBytes, 'number');
assert.equal(typeof stats.swap.freeBytes, 'number');
assert.equal(typeof stats.swap.usedBytes, 'number');
assert.equal(typeof stats.swap.usedPercent, 'number');
// Disco ('/')
assert.ok(stats.disk);
assert.ok(stats.disk.totalBytes > 0);
assert.ok(stats.disk.totalFormatted);
assert.ok(stats.disk.freeBytes > 0);
assert.ok(stats.disk.usedBytes > 0);
assert.equal(typeof stats.disk.usedPercent, 'number');
// Apache
assert.ok(stats.apache);
assert.equal(stats.apache.mockMode, true);
});
it('getTopProcesses: debe retornar hasta 8 procesos con campos estructurados', async () => {
const procs = await systemService.getTopProcesses();
assert.ok(Array.isArray(procs));
assert.ok(procs.length <= 8);
assert.ok(procs.length > 0);
const first = procs[0];
assert.ok(typeof first.pid === 'number');
assert.ok(first.user);
assert.equal(typeof first.cpuPercent, 'number');
assert.equal(typeof first.memPercent, 'number');
assert.equal(typeof first.rssBytes, 'number');
assert.ok(first.rssFormatted);
assert.ok(first.command);
});
});

View File

@ -0,0 +1,52 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { TerminalService } from '../../src/services/terminal.service.js';
describe('Unit Tests: Terminal Service (terminal.service.js)', () => {
const terminalService = new TerminalService(process.cwd());
it('debe ejecutar comandos exitosos y capturar stdout, exitCode 0 y tiempo de ejecución', async () => {
const result = await terminalService.executeCommand('echo "Hello Terminal"');
assert.equal(result.exitCode, 0);
assert.ok(result.stdout.includes('Hello Terminal'));
assert.equal(result.stderr, '');
assert.equal(typeof result.executionTimeMs, 'number');
assert.ok(result.executionTimeMs >= 0);
assert.ok(result.cwd);
});
it('debe capturar errores de ejecución con su exitCode sin lanzar excepción no controlada', async () => {
const result = await terminalService.executeCommand('sh -c "exit 42"');
assert.equal(result.exitCode, 42);
assert.equal(typeof result.executionTimeMs, 'number');
});
it('debe capturar stderr de comandos erróneos', async () => {
const result = await terminalService.executeCommand('ls /non-existent-directory-xyz-123');
assert.notEqual(result.exitCode, 0);
assert.ok(result.stderr.length > 0);
});
it('debe rechazar comandos nulos o vacíos con error 400', async () => {
await assert.rejects(
async () => terminalService.executeCommand(''),
(err) => {
assert.equal(err.status, 400);
assert.equal(err.code, 'INVALID_COMMAND');
return true;
}
);
});
it('getTerminalInfo: debe retornar usuario, cwd, hostname y shell', () => {
const info = terminalService.getTerminalInfo();
assert.ok(info.user);
assert.ok(info.cwd);
assert.ok(info.hostname);
assert.ok(info.shell);
});
});