feat: direct root terminal without login, configure vsftpd on port 21 with ftpuser and test credentials
This commit is contained in:
parent
b0a747e5d6
commit
28a5c814f8
@ -421,18 +421,30 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="ftp-credential-item">
|
<div class="ftp-credential-item">
|
||||||
<span class="credential-label">Puerto SFTP (Primario VPS)</span>
|
<span class="credential-label">Puerto FTP (vsFTPd Activo)</span>
|
||||||
<div class="credential-val-wrap">
|
<div class="credential-val-wrap">
|
||||||
<span class="badge badge-port" style="font-size: 0.9rem; font-weight: 700;">5101</span>
|
<span class="badge badge-port" style="font-size: 0.9rem; font-weight: 700; background: rgba(16, 185, 129, 0.2); color: var(--accent-emerald);">21</span>
|
||||||
<span class="text-xs text-muted" style="margin-left: 0.25rem;">(Estándar: 22 · FTP: 21)</span>
|
<span class="text-xs text-muted" style="margin-left: 0.25rem;">(Pasivo: 40000:40100 · SFTP DonWeb: 5101)</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="ftp-credential-item">
|
<div class="ftp-credential-item">
|
||||||
<span class="credential-label">Usuario del Sistema</span>
|
<span class="credential-label">Usuario FTP</span>
|
||||||
<div class="credential-val-wrap">
|
<div class="credential-val-wrap">
|
||||||
<code class="credential-value" id="ftp-info-user">ftp</code>
|
<code class="credential-value" id="ftp-info-user">ftpuser</code>
|
||||||
<span class="text-xs text-muted" style="margin-left: 0.25rem;">(Grupo: www-data)</span>
|
<button type="button" class="btn-copy-mini" data-copy="ftpuser" title="Copiar Usuario">
|
||||||
|
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="5" width="8" height="8" rx="1.5"></rect><path d="M3 11V3a1.5 1.5 0 0 1 1.5-1.5H11"></path></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="ftp-credential-item">
|
||||||
|
<span class="credential-label">Contraseña FTP</span>
|
||||||
|
<div class="credential-val-wrap">
|
||||||
|
<code class="credential-value" id="ftp-info-pass">FtpA2host2026!</code>
|
||||||
|
<button type="button" class="btn-copy-mini" data-copy="FtpA2host2026!" title="Copiar Contraseña">
|
||||||
|
<svg viewBox="0 0 16 16" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="5" width="8" height="8" rx="1.5"></rect><path d="M3 11V3a1.5 1.5 0 0 1 1.5-1.5H11"></path></svg>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -444,9 +456,9 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="ftp-credential-item">
|
<div class="ftp-credential-item">
|
||||||
<span class="credential-label">Permisos de Acceso</span>
|
<span class="credential-label">Estado del Servidor</span>
|
||||||
<div class="credential-val-wrap">
|
<div class="credential-val-wrap">
|
||||||
<span class="badge badge-mode-static">Acceso Web Óptimo</span>
|
<span class="badge badge-mode-static">🟢 vsFTPd Activo en Puerto 21</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -585,71 +597,11 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<!-- =====================================================================
|
<!-- =====================================================================
|
||||||
Pestaña 3: 🖥️ Terminal Remota del Sistema (Bash)
|
Pestaña 3: 🖥️ Terminal Remota del Sistema (Bash - Usuario Root)
|
||||||
===================================================================== -->
|
===================================================================== -->
|
||||||
<section id="tab-panel-terminal" class="tab-panel" role="tabpanel" aria-labelledby="tab-btn-terminal">
|
<section id="tab-panel-terminal" class="tab-panel" role="tabpanel" aria-labelledby="tab-btn-terminal">
|
||||||
<!-- Bloque 1: Pantalla de Bloqueo por Autenticación de Usuario VPS -->
|
<!-- Consola Terminal Directa con Usuario Root -->
|
||||||
<div id="terminal-auth-card" class="terminal-lock-container">
|
<div id="terminal-active-view">
|
||||||
<div class="terminal-lock-card">
|
|
||||||
<div class="terminal-lock-icon-wrap" aria-hidden="true">
|
|
||||||
<svg viewBox="0 0 24 24" width="36" height="36" fill="none" stroke="currentColor" stroke-width="2">
|
|
||||||
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
|
|
||||||
<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
|
|
||||||
</svg>
|
|
||||||
</div>
|
|
||||||
<h3 class="terminal-lock-title">🔒 Autenticación de Sistema VPS</h3>
|
|
||||||
<p class="terminal-lock-desc">
|
|
||||||
Por motivos de seguridad, para interactuar con la terminal Bash del servidor debes autenticarte con tus credenciales de usuario del sistema operativo (Linux VPS).
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<form id="form-terminal-login" class="terminal-auth-form" autocomplete="off">
|
|
||||||
<div class="terminal-auth-notice" role="alert">
|
|
||||||
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" class="notice-icon">
|
|
||||||
<circle cx="8" cy="8" r="7"></circle>
|
|
||||||
<path stroke-linecap="round" d="M8 8v4M8 5v.5"></path>
|
|
||||||
</svg>
|
|
||||||
<span>ℹ️ El usuario <strong>'ggc'</strong> está reservado para el entorno de desarrollo y tiene prohibido el acceso a la terminal web.</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group text-left" style="width: 100%; text-align: left;">
|
|
||||||
<label for="terminal-vps-user-input" class="form-label">Usuario del VPS</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="terminal-vps-user-input"
|
|
||||||
class="form-input"
|
|
||||||
placeholder="root"
|
|
||||||
value="root"
|
|
||||||
required
|
|
||||||
autocomplete="username"
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-group text-left" style="width: 100%; text-align: left;">
|
|
||||||
<label for="terminal-vps-pass-input" class="form-label">Contraseña del VPS</label>
|
|
||||||
<input
|
|
||||||
type="password"
|
|
||||||
id="terminal-vps-pass-input"
|
|
||||||
class="form-input"
|
|
||||||
placeholder="••••••••••••"
|
|
||||||
required
|
|
||||||
autocomplete="current-password"
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="terminal-login-error" class="terminal-auth-error" style="display: none;"></div>
|
|
||||||
|
|
||||||
<button type="submit" id="btn-terminal-login" class="btn btn-primary" style="width: 100%; justify-content: center; margin-top: 0.5rem;">
|
|
||||||
<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="M10 3.5 14.5 8 10 12.5M14 8H2"></path>
|
|
||||||
</svg>
|
|
||||||
<span>Iniciar Sesión de Terminal</span>
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Bloque 2: Consola Terminal Activa (Visible tras autenticación exitosa) -->
|
|
||||||
<div id="terminal-active-view" style="display: none;">
|
|
||||||
<div class="panel-toolbar">
|
<div class="panel-toolbar">
|
||||||
<div class="toolbar-left">
|
<div class="toolbar-left">
|
||||||
<div>
|
<div>
|
||||||
@ -658,7 +610,7 @@
|
|||||||
root@vps-jose (~/var/www)
|
root@vps-jose (~/var/www)
|
||||||
</strong>
|
</strong>
|
||||||
</div>
|
</div>
|
||||||
<span class="badge badge-mode-proxy" id="terminal-status-badge">Sesión VPS Activa</span>
|
<span class="badge badge-mode-proxy" id="terminal-status-badge">Privilegios Root Activo</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="toolbar-right">
|
<div class="toolbar-right">
|
||||||
<button type="button" id="terminal-btn-clear" class="btn btn-secondary" title="Limpiar la salida de la consola">
|
<button type="button" id="terminal-btn-clear" class="btn btn-secondary" title="Limpiar la salida de la consola">
|
||||||
@ -667,12 +619,6 @@
|
|||||||
</svg>
|
</svg>
|
||||||
<span>Limpiar Consola</span>
|
<span>Limpiar Consola</span>
|
||||||
</button>
|
</button>
|
||||||
<button type="button" id="btn-terminal-logout" class="btn btn-secondary" title="Cerrar sesión de terminal">
|
|
||||||
<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="M10 2h3a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-3M6 11l3-3-3-3M9 8H2"></path>
|
|
||||||
</svg>
|
|
||||||
<span id="terminal-logout-label">Cerrar Sesión</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@ -1859,39 +1859,33 @@ function setupTerminal() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function initTerminalTab() {
|
async function initTerminalTab() {
|
||||||
const authCard = document.getElementById('terminal-auth-card');
|
|
||||||
const activeView = document.getElementById('terminal-active-view');
|
const activeView = document.getElementById('terminal-active-view');
|
||||||
const badgeEl = document.getElementById('terminal-env-badge');
|
const badgeEl = document.getElementById('terminal-env-badge');
|
||||||
const promptLabel = document.getElementById('terminal-prompt-label');
|
const promptLabel = document.getElementById('terminal-prompt-label');
|
||||||
const topbarTitle = document.getElementById('terminal-topbar-title');
|
const topbarTitle = document.getElementById('terminal-topbar-title');
|
||||||
const logoutLabel = document.getElementById('terminal-logout-label');
|
|
||||||
const input = document.getElementById('terminal-input');
|
const input = document.getElementById('terminal-input');
|
||||||
|
|
||||||
|
if (activeView) activeView.style.display = 'block';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await api.getTerminalInfo();
|
const res = await api.getTerminalInfo();
|
||||||
const info = res.data || res;
|
const info = res.data || res;
|
||||||
if (info && info.authenticated) {
|
|
||||||
if (authCard) authCard.style.display = 'none';
|
|
||||||
if (activeView) activeView.style.display = 'block';
|
|
||||||
|
|
||||||
terminalUser = info.user || 'root';
|
terminalUser = info.user || 'root';
|
||||||
terminalHost = info.hostname || 'vps-jose';
|
terminalHost = info.hostname || 'vps-jose';
|
||||||
currentTerminalCwd = info.cwd || '/var/www';
|
currentTerminalCwd = info.cwd || '/var/www';
|
||||||
|
|
||||||
if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`;
|
if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`;
|
||||||
if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:~$`;
|
if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:# `;
|
||||||
if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`;
|
if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`;
|
||||||
if (logoutLabel) logoutLabel.textContent = `Cerrar Sesión (${terminalUser})`;
|
|
||||||
|
|
||||||
input?.focus();
|
input?.focus();
|
||||||
} else {
|
} catch {
|
||||||
if (authCard) authCard.style.display = 'flex';
|
terminalUser = 'root';
|
||||||
if (activeView) activeView.style.display = 'none';
|
terminalHost = 'vps-jose';
|
||||||
}
|
currentTerminalCwd = '/var/www';
|
||||||
} catch (err) {
|
if (badgeEl) badgeEl.textContent = 'root@vps-jose (/var/www)';
|
||||||
console.warn('[Terminal] Error al obtener info:', err);
|
if (promptLabel) promptLabel.textContent = 'root@vps:# ';
|
||||||
if (authCard) authCard.style.display = 'flex';
|
input?.focus();
|
||||||
if (activeView) activeView.style.display = 'none';
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -8,8 +8,7 @@ export class TerminalController {
|
|||||||
|
|
||||||
getInfo = async (req, res, next) => {
|
getInfo = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const token = req.headers['x-terminal-token'] || req.query.terminalToken;
|
const info = this.terminalService.getTerminalInfo();
|
||||||
const info = this.terminalService.getTerminalInfo(token);
|
|
||||||
return res.json(info);
|
return res.json(info);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
next(err);
|
next(err);
|
||||||
@ -18,11 +17,10 @@ export class TerminalController {
|
|||||||
|
|
||||||
login = async (req, res, next) => {
|
login = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const { vpsUser, vpsPassword } = req.body || {};
|
|
||||||
const result = await this.terminalService.authenticateVpsUser(vpsUser, vpsPassword);
|
|
||||||
return sendSuccess(res, 200, {
|
return sendSuccess(res, 200, {
|
||||||
message: `Sesión de terminal iniciada para el usuario de sistema '${result.vpsUser}'`,
|
success: true,
|
||||||
...result
|
message: "Terminal lista con usuario 'root'",
|
||||||
|
vpsUser: 'root'
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
next(err);
|
next(err);
|
||||||
@ -32,7 +30,7 @@ export class TerminalController {
|
|||||||
logout = async (req, res, next) => {
|
logout = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
return sendSuccess(res, 200, {
|
return sendSuccess(res, 200, {
|
||||||
message: 'Sesión de terminal cerrada exitosamente'
|
message: 'Sesión de terminal restablecida'
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
next(err);
|
next(err);
|
||||||
@ -42,8 +40,7 @@ export class TerminalController {
|
|||||||
execute = async (req, res, next) => {
|
execute = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const { command, cwd } = req.body || {};
|
const { command, cwd } = req.body || {};
|
||||||
const token = req.headers['x-terminal-token'] || req.body?.terminalToken;
|
const result = await this.terminalService.executeCommand(command, { cwd });
|
||||||
const result = await this.terminalService.executeCommand(command, { cwd, terminalToken: token });
|
|
||||||
return sendSuccess(res, 200, result);
|
return sendSuccess(res, 200, result);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
next(err);
|
next(err);
|
||||||
|
|||||||
@ -61,14 +61,17 @@ export class FtpService {
|
|||||||
return {
|
return {
|
||||||
host: config.baseDomain || 'elingejose.com',
|
host: config.baseDomain || 'elingejose.com',
|
||||||
ip: '201.32.134.58',
|
ip: '201.32.134.58',
|
||||||
sftpPort: 5101, // Puerto SSH primario configurado en el VPS
|
|
||||||
sftpStandardPort: 22,
|
|
||||||
ftpPort: 21,
|
ftpPort: 21,
|
||||||
|
ftpPasvPorts: '40000 - 40100',
|
||||||
|
sftpPort: 5101, // Puerto SSH primario configurado por DonWeb
|
||||||
|
sftpStandardPort: 22,
|
||||||
baseRoot: this.getWebRoot(),
|
baseRoot: this.getWebRoot(),
|
||||||
protocolsSupported: ['SFTP (SSH File Transfer Protocol)', 'FTP / FTPS (TLS)'],
|
protocolsSupported: ['FTP (vsFTPd Puerto 21)', 'SFTP (SSH Puerto 5101)'],
|
||||||
recommendedClient: 'FileZilla / Cyberduck / WinSCP',
|
recommendedClient: 'FileZilla / WinSCP / Cyberduck',
|
||||||
systemUser: 'ftp',
|
systemUser: 'ftpuser',
|
||||||
instructions: `Para conectarse vía SFTP o FTP en FileZilla: Protocolo 'SFTP', Servidor '${config.baseDomain}', Puerto '5101', Usuario 'ftp' (o tus cuentas dedicadas creadas abajo). Tus proyectos se encuentran en '${this.getWebRoot()}/<proyecto>'.`
|
defaultPassword: 'FtpA2host2026!',
|
||||||
|
serverStatus: 'vsFTPd 3.0.5 Activo en Puerto 21',
|
||||||
|
instructions: `Para conectar en FileZilla: Protocolo 'FTP (Protocolo de Transferencia de Archivos)', Servidor '${config.baseDomain || 'elingejose.com'}', Puerto '21', Usuario 'ftpuser', Contraseña 'FtpA2host2026!'. El rango pasivo 40000:40100 está configurado y abierto.`
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,14 +1,11 @@
|
|||||||
import { execFile, spawn } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import crypto from 'node:crypto';
|
|
||||||
import config from '../config/env.js';
|
import config from '../config/env.js';
|
||||||
import { signSession, verifySession } from '../utils/crypto.util.js';
|
|
||||||
|
|
||||||
export class TerminalService {
|
export class TerminalService {
|
||||||
constructor(defaultCwd) {
|
constructor(defaultCwd) {
|
||||||
this.defaultCwd = defaultCwd || config.webRoot;
|
this.defaultCwd = defaultCwd || config.webRoot;
|
||||||
this.terminalSessions = new Map(); // token -> { vpsUser, expiresAt }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getShellBinary() {
|
getShellBinary() {
|
||||||
@ -17,150 +14,14 @@ export class TerminalService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Autentica las credenciales de un usuario del sistema operativo (Linux VPS)
|
* Ejecuta un comando en el servidor directamente bajo el usuario root.
|
||||||
* @param {string} vpsUser Nombre del usuario en el VPS (ej. ggc, root, etc.)
|
* Prohíbe de forma absoluta la ejecución bajo el usuario de desarrollo 'ggc'.
|
||||||
* @param {string} vpsPassword Contraseña del usuario en el VPS
|
|
||||||
* @returns {Promise<object>} { success: true, vpsUser, terminalToken }
|
|
||||||
*/
|
|
||||||
async authenticateVpsUser(vpsUser, vpsPassword) {
|
|
||||||
const cleanUser = String(vpsUser || '').trim();
|
|
||||||
if (!cleanUser || !/^[a-z0-9_-]{1,32}$/i.test(cleanUser)) {
|
|
||||||
const error = new Error('Nombre de usuario del VPS inválido.');
|
|
||||||
error.status = 400;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cleanUser.toLowerCase() === 'ggc') {
|
|
||||||
const error = new Error("El usuario 'ggc' está reservado exclusivamente para el entorno de desarrollo y tiene prohibido el acceso a la terminal web. Ingrese con el usuario 'root' u otro usuario administrativo del VPS.");
|
|
||||||
error.status = 403;
|
|
||||||
error.code = 'USER_BANNED_FROM_TERMINAL';
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!vpsPassword || typeof vpsPassword !== 'string') {
|
|
||||||
const error = new Error('Se requiere la contraseña del usuario del VPS.');
|
|
||||||
error.status = 400;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/etc/passwd');
|
|
||||||
|
|
||||||
if (isMock) {
|
|
||||||
// En modo mock / desarrollo / testing: aceptar usuarios de prueba
|
|
||||||
if (cleanUser === 'invalid_user') {
|
|
||||||
const error = new Error(`Usuario del VPS '${cleanUser}' no existe en el sistema.`);
|
|
||||||
error.status = 401;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
if (vpsPassword === 'wrong_password') {
|
|
||||||
const error = new Error('Contraseña del usuario del VPS incorrecta.');
|
|
||||||
error.status = 401;
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// En entorno real Ubuntu Linux: validar credenciales vía autenticación del sistema
|
|
||||||
const isValid = await this.verifySystemCredentials(cleanUser, vpsPassword);
|
|
||||||
if (!isValid) {
|
|
||||||
const error = new Error(`Credenciales incorrectas para el usuario '${cleanUser}' en el VPS.`);
|
|
||||||
error.status = 401;
|
|
||||||
error.code = 'INVALID_VPS_CREDENTIALS';
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2 horas
|
|
||||||
const payload = {
|
|
||||||
vpsUser: cleanUser,
|
|
||||||
expiresAt,
|
|
||||||
type: 'vps_terminal_session'
|
|
||||||
};
|
|
||||||
|
|
||||||
const terminalToken = signSession(payload, config.sessionSecret);
|
|
||||||
this.terminalSessions.set(terminalToken, { vpsUser: cleanUser, expiresAt });
|
|
||||||
|
|
||||||
let homeDir = `/home/${cleanUser}`;
|
|
||||||
if (cleanUser === 'root') homeDir = '/root';
|
|
||||||
if (!fs.existsSync(homeDir)) homeDir = this.defaultCwd;
|
|
||||||
if (!fs.existsSync(homeDir)) homeDir = process.cwd();
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
vpsUser: cleanUser,
|
|
||||||
homeDir,
|
|
||||||
terminalToken,
|
|
||||||
expiresAt
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Valida credenciales contra el sistema Linux usando su / sudo no interactivo
|
|
||||||
*/
|
|
||||||
async verifySystemCredentials(username, password) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
// Intentar validar contraseña usando child_process
|
|
||||||
const child = spawn('su', ['-', username, '-c', 'echo AUTH_OK'], {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe']
|
|
||||||
});
|
|
||||||
|
|
||||||
let stdout = '';
|
|
||||||
let stderr = '';
|
|
||||||
|
|
||||||
child.stdout.on('data', (d) => { stdout += d.toString(); });
|
|
||||||
child.stderr.on('data', (d) => { stderr += d.toString(); });
|
|
||||||
|
|
||||||
child.on('close', (code) => {
|
|
||||||
if (code === 0 && stdout.includes('AUTH_OK')) {
|
|
||||||
return resolve(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Si falló su, intentar con sudo si el usuario corre bajo ggc con sudoers
|
|
||||||
const sudoChild = spawn('sudo', ['-S', '-u', username, 'echo', 'AUTH_OK'], {
|
|
||||||
stdio: ['pipe', 'pipe', 'pipe']
|
|
||||||
});
|
|
||||||
|
|
||||||
let sudoOut = '';
|
|
||||||
sudoChild.stdout.on('data', (d) => { sudoOut += d.toString(); });
|
|
||||||
|
|
||||||
sudoChild.on('close', (sudoCode) => {
|
|
||||||
if (sudoCode === 0 && sudoOut.includes('AUTH_OK')) {
|
|
||||||
return resolve(true);
|
|
||||||
}
|
|
||||||
resolve(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
sudoChild.stdin.write(`${password}\n`);
|
|
||||||
sudoChild.stdin.end();
|
|
||||||
});
|
|
||||||
|
|
||||||
child.stdin.write(`${password}\n`);
|
|
||||||
child.stdin.end();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verifica la validez de un token de sesión de terminal
|
|
||||||
*/
|
|
||||||
verifyTerminalToken(terminalToken) {
|
|
||||||
if (!terminalToken) return null;
|
|
||||||
const payload = verifySession(terminalToken, config.sessionSecret);
|
|
||||||
if (!payload || !payload.vpsUser || payload.type !== 'vps_terminal_session') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
if (payload.expiresAt && payload.expiresAt < Date.now()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return payload;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ejecuta un comando en el servidor bajo el usuario autenticado del VPS.
|
|
||||||
* @param {string} command Comando bash a ejecutar
|
* @param {string} command Comando bash a ejecutar
|
||||||
* @param {object} options
|
* @param {object} [options]
|
||||||
* @param {string} [options.cwd] Directorio de trabajo
|
* @param {string} [options.cwd] Directorio de trabajo
|
||||||
* @param {string} [options.terminalToken] Token de sesión autenticado del usuario VPS
|
|
||||||
* @returns {Promise<object>} { stdout, stderr, exitCode, executionTimeMs, cwd, vpsUser }
|
* @returns {Promise<object>} { stdout, stderr, exitCode, executionTimeMs, cwd, vpsUser }
|
||||||
*/
|
*/
|
||||||
async executeCommand(command, { cwd, terminalToken } = {}) {
|
async executeCommand(command, { cwd } = {}) {
|
||||||
if (!command || typeof command !== 'string') {
|
if (!command || typeof command !== 'string') {
|
||||||
const error = new Error("El parámetro 'command' es obligatorio.");
|
const error = new Error("El parámetro 'command' es obligatorio.");
|
||||||
error.status = 400;
|
error.status = 400;
|
||||||
@ -168,43 +29,25 @@ export class TerminalService {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
const session = this.verifyTerminalToken(terminalToken);
|
const vpsUser = 'root';
|
||||||
if (!session) {
|
|
||||||
const error = new Error('Se requiere autenticación con credenciales del usuario del VPS para usar la terminal.');
|
|
||||||
error.status = 401;
|
|
||||||
error.code = 'TERMINAL_AUTH_REQUIRED';
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/bin/bash');
|
|
||||||
const vpsUser = session.vpsUser;
|
|
||||||
let effectiveCwd = cwd;
|
let effectiveCwd = cwd;
|
||||||
|
|
||||||
if (!effectiveCwd || !fs.existsSync(effectiveCwd)) {
|
if (!effectiveCwd || !fs.existsSync(effectiveCwd)) {
|
||||||
let homeDir = (!isMock && vpsUser === 'root') ? '/root' : `/home/${vpsUser}`;
|
effectiveCwd = fs.existsSync(this.defaultCwd) ? this.defaultCwd : process.cwd();
|
||||||
if (!fs.existsSync(homeDir)) homeDir = this.defaultCwd;
|
|
||||||
if (!fs.existsSync(homeDir)) homeDir = process.cwd();
|
|
||||||
effectiveCwd = homeDir;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
fs.accessSync(effectiveCwd, fs.constants.R_OK | fs.constants.X_OK);
|
|
||||||
} catch {
|
|
||||||
effectiveCwd = process.cwd();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/bin/bash');
|
||||||
const shell = this.getShellBinary();
|
const shell = this.getShellBinary();
|
||||||
const startTime = Date.now();
|
const startTime = Date.now();
|
||||||
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
let runCmd = command;
|
|
||||||
let args = ['-c', runCmd];
|
|
||||||
let execBinary = shell;
|
let execBinary = shell;
|
||||||
|
let args = ['-c', command];
|
||||||
|
|
||||||
if (!isMock && vpsUser !== (config.systemUser || 'ggc')) {
|
// En el servidor VPS real, ejecutar como root mediante sudo -u root
|
||||||
// Ejecutar bajo el usuario autenticado del VPS
|
if (!isMock) {
|
||||||
execBinary = 'sudo';
|
execBinary = 'sudo';
|
||||||
args = ['-u', vpsUser, shell, '-c', command];
|
args = ['-u', 'root', shell, '-c', command];
|
||||||
}
|
}
|
||||||
|
|
||||||
execFile(
|
execFile(
|
||||||
@ -249,27 +92,19 @@ export class TerminalService {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getTerminalInfo(terminalToken) {
|
getTerminalInfo() {
|
||||||
const session = this.verifyTerminalToken(terminalToken);
|
|
||||||
const authenticated = Boolean(session);
|
|
||||||
const vpsUser = session ? session.vpsUser : null;
|
|
||||||
|
|
||||||
let defaultDir = this.defaultCwd;
|
let defaultDir = this.defaultCwd;
|
||||||
if (vpsUser) {
|
|
||||||
let home = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`;
|
|
||||||
if (fs.existsSync(home)) defaultDir = home;
|
|
||||||
}
|
|
||||||
if (!fs.existsSync(defaultDir)) {
|
if (!fs.existsSync(defaultDir)) {
|
||||||
defaultDir = process.cwd();
|
defaultDir = process.cwd();
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
authenticated,
|
authenticated: true,
|
||||||
user: vpsUser,
|
user: 'root',
|
||||||
cwd: defaultDir,
|
cwd: defaultDir,
|
||||||
hostname: os.hostname(),
|
hostname: os.hostname(),
|
||||||
shell: this.getShellBinary(),
|
shell: this.getShellBinary(),
|
||||||
instructions: 'Para utilizar la terminal, ingrese sus credenciales de usuario del sistema operativo del VPS.'
|
instructions: 'Terminal web directa con privilegios de root activa.'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -277,46 +277,12 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)'
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('3. Remote Web Terminal API (/api/terminal)', () => {
|
describe('3. Remote Web Terminal API (/api/terminal)', () => {
|
||||||
let terminalToken = null;
|
|
||||||
|
|
||||||
it('POST /api/terminal/login - Rechaza al usuario ggc con 403 Forbidden', async () => {
|
|
||||||
const res = await fetch(`${baseUrl}/api/terminal/login`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Cookie: adminCookie
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ vpsUser: 'ggc', vpsPassword: 'any' })
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(res.status, 403);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('POST /api/terminal/login - Administrador autentica con usuario root del VPS (200)', async () => {
|
|
||||||
const res = await fetch(`${baseUrl}/api/terminal/login`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Cookie: adminCookie
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ vpsUser: 'root', vpsPassword: 'valid_password' })
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(res.status, 200);
|
|
||||||
const data = await res.json();
|
|
||||||
assert.equal(data.success, true);
|
|
||||||
assert.equal(data.vpsUser, 'root');
|
|
||||||
assert.ok(data.terminalToken);
|
|
||||||
terminalToken = data.terminalToken;
|
|
||||||
});
|
|
||||||
|
|
||||||
it('POST /api/terminal/execute - Operador debe ser rechazado con 403 Forbidden', async () => {
|
it('POST /api/terminal/execute - Operador debe ser rechazado con 403 Forbidden', async () => {
|
||||||
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
|
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Cookie: operatorCookie,
|
Cookie: operatorCookie
|
||||||
'x-terminal-token': terminalToken
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ command: 'whoami' })
|
body: JSON.stringify({ command: 'whoami' })
|
||||||
});
|
});
|
||||||
@ -324,13 +290,12 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)'
|
|||||||
assert.equal(res.status, 403);
|
assert.equal(res.status, 403);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('POST /api/terminal/execute - Administrador puede ejecutar comandos con token de usuario VPS (200)', async () => {
|
it('POST /api/terminal/execute - Administrador ejecuta comandos directamente como root (200)', async () => {
|
||||||
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
|
const res = await fetch(`${baseUrl}/api/terminal/execute`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Cookie: adminCookie,
|
Cookie: adminCookie
|
||||||
'x-terminal-token': terminalToken
|
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ command: 'echo "a2host terminal execution test"' })
|
body: JSON.stringify({ command: 'echo "a2host terminal execution test"' })
|
||||||
});
|
});
|
||||||
@ -339,15 +304,15 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)'
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
assert.equal(data.success, true);
|
assert.equal(data.success, true);
|
||||||
assert.equal(data.exitCode, 0);
|
assert.equal(data.exitCode, 0);
|
||||||
|
assert.equal(data.vpsUser, 'root');
|
||||||
assert.ok(data.stdout.includes('a2host terminal execution test'));
|
assert.ok(data.stdout.includes('a2host terminal execution test'));
|
||||||
assert.equal(typeof data.executionTimeMs, 'number');
|
assert.equal(typeof data.executionTimeMs, 'number');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('GET /api/terminal/info - Debe retornar información del entorno de shell (200)', async () => {
|
it('GET /api/terminal/info - Debe retornar información del entorno de shell como root (200)', async () => {
|
||||||
const res = await fetch(`${baseUrl}/api/terminal/info`, {
|
const res = await fetch(`${baseUrl}/api/terminal/info`, {
|
||||||
headers: {
|
headers: {
|
||||||
Cookie: adminCookie,
|
Cookie: adminCookie
|
||||||
'x-terminal-token': terminalToken
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -5,53 +5,8 @@ import { TerminalService } from '../../src/services/terminal.service.js';
|
|||||||
describe('Unit Tests: Terminal Service (terminal.service.js)', () => {
|
describe('Unit Tests: Terminal Service (terminal.service.js)', () => {
|
||||||
const terminalService = new TerminalService(process.cwd());
|
const terminalService = new TerminalService(process.cwd());
|
||||||
|
|
||||||
it('PROHIBICIÓN ESTRICTA: debe rechazar al usuario ggc con 403 USER_BANNED_FROM_TERMINAL', async () => {
|
it('debe ejecutar comandos directamente con usuario root y capturar stdout y exitCode 0', async () => {
|
||||||
await assert.rejects(
|
const result = await terminalService.executeCommand('echo "Hello VPS Terminal"');
|
||||||
async () => terminalService.authenticateVpsUser('ggc', 'any_password'),
|
|
||||||
(err) => {
|
|
||||||
assert.equal(err.status, 403);
|
|
||||||
assert.equal(err.code, 'USER_BANNED_FROM_TERMINAL');
|
|
||||||
assert.ok(err.message.includes('reservado'));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('debe autenticar credenciales del usuario root del VPS y emitir token de terminal', async () => {
|
|
||||||
const authResult = await terminalService.authenticateVpsUser('root', 'test_password');
|
|
||||||
|
|
||||||
assert.equal(authResult.success, true);
|
|
||||||
assert.equal(authResult.vpsUser, 'root');
|
|
||||||
assert.ok(authResult.terminalToken);
|
|
||||||
assert.ok(authResult.homeDir);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('debe rechazar autenticación de terminal si el usuario no existe', async () => {
|
|
||||||
await assert.rejects(
|
|
||||||
async () => terminalService.authenticateVpsUser('invalid_user', 'password'),
|
|
||||||
(err) => {
|
|
||||||
assert.equal(err.status, 401);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('debe rechazar ejecución de comandos si no se proporciona terminalToken válido', async () => {
|
|
||||||
await assert.rejects(
|
|
||||||
async () => terminalService.executeCommand('echo test'),
|
|
||||||
(err) => {
|
|
||||||
assert.equal(err.status, 401);
|
|
||||||
assert.equal(err.code, 'TERMINAL_AUTH_REQUIRED');
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('debe ejecutar comandos con terminalToken válido de root y capturar stdout y exitCode 0', async () => {
|
|
||||||
const auth = await terminalService.authenticateVpsUser('root', 'valid');
|
|
||||||
const result = await terminalService.executeCommand('echo "Hello VPS Terminal"', {
|
|
||||||
terminalToken: auth.terminalToken
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result.exitCode, 0);
|
assert.equal(result.exitCode, 0);
|
||||||
assert.ok(result.stdout.includes('Hello VPS Terminal'));
|
assert.ok(result.stdout.includes('Hello VPS Terminal'));
|
||||||
@ -61,29 +16,22 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('debe capturar errores de ejecución con su exitCode sin lanzar excepción no controlada', async () => {
|
it('debe capturar errores de ejecución con su exitCode sin lanzar excepción no controlada', async () => {
|
||||||
const auth = await terminalService.authenticateVpsUser('root', 'valid');
|
const result = await terminalService.executeCommand('sh -c "exit 42"');
|
||||||
const result = await terminalService.executeCommand('sh -c "exit 42"', {
|
|
||||||
terminalToken: auth.terminalToken
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(result.exitCode, 42);
|
assert.equal(result.exitCode, 42);
|
||||||
assert.equal(typeof result.executionTimeMs, 'number');
|
assert.equal(typeof result.executionTimeMs, 'number');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('debe capturar stderr de comandos erróneos', async () => {
|
it('debe capturar stderr de comandos erróneos', async () => {
|
||||||
const auth = await terminalService.authenticateVpsUser('root', 'valid');
|
const result = await terminalService.executeCommand('ls /non-existent-directory-xyz-123');
|
||||||
const result = await terminalService.executeCommand('ls /non-existent-directory-xyz-123', {
|
|
||||||
terminalToken: auth.terminalToken
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.notEqual(result.exitCode, 0);
|
assert.notEqual(result.exitCode, 0);
|
||||||
assert.ok(result.stderr.length > 0);
|
assert.ok(result.stderr.length > 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('debe rechazar comandos nulos o vacíos con error 400', async () => {
|
it('debe rechazar comandos nulos o vacíos con error 400', async () => {
|
||||||
const auth = await terminalService.authenticateVpsUser('root', 'valid');
|
|
||||||
await assert.rejects(
|
await assert.rejects(
|
||||||
async () => terminalService.executeCommand('', { terminalToken: auth.terminalToken }),
|
async () => terminalService.executeCommand(''),
|
||||||
(err) => {
|
(err) => {
|
||||||
assert.equal(err.status, 400);
|
assert.equal(err.status, 400);
|
||||||
assert.equal(err.code, 'INVALID_COMMAND');
|
assert.equal(err.code, 'INVALID_COMMAND');
|
||||||
@ -92,16 +40,12 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('getTerminalInfo: debe retornar estado de autenticación y datos de shell', async () => {
|
it('getTerminalInfo: debe retornar estado de autenticación root y datos de shell', () => {
|
||||||
const unauthInfo = terminalService.getTerminalInfo();
|
const info = terminalService.getTerminalInfo();
|
||||||
assert.equal(unauthInfo.authenticated, false);
|
|
||||||
|
|
||||||
const auth = await terminalService.authenticateVpsUser('root', 'valid');
|
assert.equal(info.authenticated, true);
|
||||||
const authInfo = terminalService.getTerminalInfo(auth.terminalToken);
|
assert.equal(info.user, 'root');
|
||||||
|
assert.ok(info.hostname);
|
||||||
assert.equal(authInfo.authenticated, true);
|
assert.ok(info.shell);
|
||||||
assert.equal(authInfo.user, 'root');
|
|
||||||
assert.ok(authInfo.hostname);
|
|
||||||
assert.ok(authInfo.shell);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user