a2host/src/services/terminal.service.js

266 lines
8.4 KiB
JavaScript

import { execFile, spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import crypto from 'node:crypto';
import config from '../config/env.js';
import { signSession, verifySession } from '../utils/crypto.util.js';
export class TerminalService {
constructor(defaultCwd) {
this.defaultCwd = defaultCwd || config.webRoot;
this.terminalSessions = new Map(); // token -> { vpsUser, expiresAt }
}
getShellBinary() {
if (fs.existsSync('/bin/bash')) return '/bin/bash';
return process.env.SHELL || '/bin/sh';
}
/**
* Autentica las credenciales de un usuario del sistema operativo (Linux VPS)
* @param {string} vpsUser Nombre del usuario en el VPS (ej. ggc, root, etc.)
* @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 (!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 {object} options
* @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 }
*/
async executeCommand(command, { cwd, terminalToken } = {}) {
if (!command || typeof command !== 'string') {
const error = new Error("El parámetro 'command' es obligatorio.");
error.status = 400;
error.code = 'INVALID_COMMAND';
throw error;
}
const session = this.verifyTerminalToken(terminalToken);
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 vpsUser = session.vpsUser;
let effectiveCwd = cwd;
if (!effectiveCwd || !fs.existsSync(effectiveCwd)) {
let homeDir = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`;
if (!fs.existsSync(homeDir)) homeDir = this.defaultCwd;
if (!fs.existsSync(homeDir)) homeDir = process.cwd();
effectiveCwd = homeDir;
}
const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/bin/bash');
const shell = this.getShellBinary();
const startTime = Date.now();
return new Promise((resolve) => {
let runCmd = command;
let args = ['-c', runCmd];
let execBinary = shell;
if (!isMock && vpsUser !== (config.systemUser || 'ggc')) {
// Ejecutar bajo el usuario autenticado del VPS
execBinary = 'sudo';
args = ['-u', vpsUser, shell, '-c', command];
}
execFile(
execBinary,
args,
{
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,
vpsUser
});
}
);
});
}
getTerminalInfo(terminalToken) {
const session = this.verifyTerminalToken(terminalToken);
const authenticated = Boolean(session);
const vpsUser = session ? session.vpsUser : null;
let defaultDir = this.defaultCwd;
if (vpsUser) {
let home = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`;
if (fs.existsSync(home)) defaultDir = home;
}
if (!fs.existsSync(defaultDir)) {
defaultDir = process.cwd();
}
return {
authenticated,
user: vpsUser,
cwd: defaultDir,
hostname: os.hostname(),
shell: this.getShellBinary(),
instructions: 'Para utilizar la terminal, ingrese sus credenciales de usuario del sistema operativo del VPS.'
};
}
}
export const defaultTerminalService = new TerminalService();
export default defaultTerminalService;