/** * a2host - Main Application Controller (ES Module) * Coordina la SPA sin frameworks pesados, con soporte reactivo, accesibilidad WCAG y manejo atómico de errores. */ import api, { ApiError } from './api.js'; import store from './state.js'; import toast from './toast.js'; import { validateSubdomainName, validatePort, validateUsername, validatePassword, RESERVED_PORTS_MAP } from './validators.js'; import { renderMarkdown } from './markdown.js'; // Constante de dominio base const BASE_DOMAIN = 'elingejose.com'; // Inicialización cuando el DOM esté listo document.addEventListener('DOMContentLoaded', () => { initApp(); }); async function initApp() { // 1. Verificar Autenticación try { const user = await api.getMe(); if (!user || !user.id) { window.location.href = '/login.html'; return; } store.setState({ currentUser: user }); setupUserProfileUI(user); } catch (err) { window.location.href = '/login.html'; return; } // 2. Configurar Navegación por Pestañas setupTabs(); // 3. Inicializar Telemetría con Polling cada 6 segundos fetchTelemetry(); setInterval(fetchTelemetry, 6000); // 4. Configurar Buscadores y Filtros setupFiltersAndSearch(); // 5. Configurar Modales setupModals(); setupFileManager(); setupCodeEditor(); setupTerminal(); setupMonitor(); // 6. Cargar datos iniciales loadSubdomains(); loadFolders(); if (store.getState('currentUser')?.role === 'admin') { loadUsers(); } loadDocs(); // 7. Configurar Botón de Logout const btnLogout = document.getElementById('btn-logout'); if (btnLogout) { btnLogout.addEventListener('click', handleLogout); } // Escuchar tecla Escape para cerrar modales document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closeAllModals(); } }); } /* ========================================================================== Perfil de Usuario y Telemetría ========================================================================== */ function setupUserProfileUI(user) { const userNameEl = document.getElementById('user-full-name'); const userRoleEl = document.getElementById('user-role-badge'); if (userNameEl) { userNameEl.textContent = user.fullName || user.username; } if (userRoleEl) { userRoleEl.textContent = user.role; userRoleEl.className = `user-role-tag role-${user.role}`; } // Si no es admin, ocultar botón de crear usuario o ajustar vista if (user.role !== 'admin') { const btnNewUser = document.getElementById('btn-open-create-user'); if (btnNewUser) btnNewUser.style.display = 'none'; } } async function fetchTelemetry() { try { const stats = await api.getSystemStats(); store.setState({ stats }); updateTelemetryUI(stats); } catch (err) { console.warn('[Telemetry] No se pudo obtener métricas:', err.message); } } function updateTelemetryUI(stats) { if (!stats) return; // 1. Memoria PM2 contra límite estricto de 120MB const rssBytes = stats.memory?.processRssBytes || 0; const pm2LimitBytes = 120 * 1024 * 1024; // 120 MB const percent = Math.min(100, Math.round((rssBytes / pm2LimitBytes) * 100)); const ramFill = document.getElementById('ram-bar-fill'); const ramText = document.getElementById('ram-usage-text'); if (ramFill) { ramFill.style.width = `${percent}%`; ramFill.classList.remove('ram-warning', 'ram-danger'); if (percent > 85) { ramFill.classList.add('ram-danger'); } else if (percent > 65) { ramFill.classList.add('ram-warning'); } } if (ramText) { const formatted = stats.memory?.processRssFormatted || `${(rssBytes / (1024 * 1024)).toFixed(1)} MB`; ramText.textContent = `${formatted} / 120 MB`; } // 2. Estado de Apache const apacheDot = document.getElementById('apache-status-dot'); const apacheText = document.getElementById('apache-status-text'); if (apacheDot && apacheText) { apacheDot.className = 'status-pulsing-dot'; if (stats.apache?.mockMode) { apacheDot.classList.add('mock'); apacheText.textContent = 'Apache (Mock)'; apacheText.title = 'Modo desarrollo simulado activo'; } else if (stats.apache?.active) { apacheText.textContent = 'Apache2 Activo'; apacheText.title = 'Servidor Apache2 operando en VPS'; } else { apacheDot.classList.add('offline'); apacheText.textContent = 'Apache2 Inactivo'; } } // 3. Sistema y Uptime const sysText = document.getElementById('system-uptime-text'); if (sysText && stats.server) { sysText.textContent = `${stats.server.hostname} • ${stats.server.uptimeFormatted || 'Activo'}`; } } async function handleLogout() { try { await api.logout(); toast.info('Sesión Finalizada', 'Hasta pronto'); setTimeout(() => { window.location.href = '/login.html'; }, 400); } catch (err) { window.location.href = '/login.html'; } } /* ========================================================================== Navegación por Pestañas (Tabs) ========================================================================== */ function setupTabs() { const tabButtons = document.querySelectorAll('.tab-btn'); const tabPanels = document.querySelectorAll('.tab-panel'); tabButtons.forEach(btn => { btn.addEventListener('click', () => { const targetTab = btn.getAttribute('data-tab'); switchTab(targetTab); }); }); store.subscribe('activeTab', (state) => { const active = state.activeTab; tabButtons.forEach(b => { const isActive = b.getAttribute('data-tab') === active; b.classList.toggle('active', isActive); b.setAttribute('aria-selected', isActive ? 'true' : 'false'); }); tabPanels.forEach(p => { p.classList.toggle('active', p.id === `tab-panel-${active}`); }); }); } function switchTab(tabName) { store.setState({ activeTab: tabName }); if (tabName !== 'monitor') { stopMonitorAutoRefresh(); } if (tabName === 'subdomains') loadSubdomains(); if (tabName === 'folders') loadFolders(); if (tabName === 'terminal') initTerminalTab(); if (tabName === 'monitor') initMonitorTab(); if (tabName === 'users') loadUsers(); if (tabName === 'docs') loadDocs(); } /* ========================================================================== Pestaña 1: Subdominios ========================================================================== */ async function loadSubdomains() { const tableBody = document.getElementById('subdomains-table-body'); const mobileContainer = document.getElementById('subdomains-mobile-list'); const badgeCount = document.getElementById('subdomains-count-badge'); store.setState({ subdomainsLoading: true }); try { const list = await api.getSubdomains(); store.setState({ subdomains: list, subdomainsLoading: false }); if (badgeCount) badgeCount.textContent = list.length; renderSubdomains(); } catch (err) { store.setState({ subdomainsLoading: false }); toast.error('Error al cargar subdominios', err.message); } } function renderSubdomains() { const subdomains = store.getState('subdomains') || []; const filter = store.getState('subdomainsFilter') || {}; const tableBody = document.getElementById('subdomains-table-body'); const mobileContainer = document.getElementById('subdomains-mobile-list'); const emptyState = document.getElementById('subdomains-empty-state'); // Filtrado reactivo const filtered = subdomains.filter(item => { // Búsqueda por texto if (filter.search) { const q = filter.search.toLowerCase(); const matchName = item.name.toLowerCase().includes(q); const matchDomain = (item.fullDomain || '').toLowerCase().includes(q); const matchTarget = (item.target || '').toLowerCase().includes(q); if (!matchName && !matchDomain && !matchTarget) return false; } // Filtro por modo if (filter.mode && filter.mode !== 'all') { if (item.type !== filter.mode) return false; } // Filtro por estado if (filter.status && filter.status !== 'all') { const isEnabled = filter.status === 'enabled'; if (item.enabled !== isEnabled) return false; } return true; }); if (filtered.length === 0) { if (tableBody) tableBody.innerHTML = ''; if (mobileContainer) mobileContainer.innerHTML = ''; if (emptyState) emptyState.style.display = 'flex'; return; } if (emptyState) emptyState.style.display = 'none'; // Renderizar Tabla Desktop if (tableBody) { tableBody.innerHTML = filtered.map(item => ` ${escapeHtml(item.name)}
${escapeHtml(item.fullDomain || `${item.name}.${BASE_DOMAIN}`)}
${item.type === 'proxy' ? `Modo B • Proxy` : `Modo A • Estático` } ${item.type === 'proxy' ? `:${item.port || '—'} ${escapeHtml(item.target || '')}` : `${escapeHtml(item.target || `/var/www/${item.name}`)}` } ${item.protected ? `Protegido` : `Normal` }
`).join(''); } // Renderizar Tarjetas Mobile if (mobileContainer) { mobileContainer.innerHTML = filtered.map(item => `
${escapeHtml(item.name)}
Tipo / Modo: ${item.type === 'proxy' ? `Modo B • Proxy :${item.port}` : `Modo A • Estático` }
Destino: ${escapeHtml(item.target || '')}
Seguridad: ${item.protected ? `Protegido` : `Normal` }
`).join(''); } // Vincular eventos a los nuevos elementos generados attachSubdomainRowEvents(); } function attachSubdomainRowEvents() { // Switches de estado document.querySelectorAll('.subdomain-toggle-switch').forEach(sw => { sw.addEventListener('change', async (e) => { const name = sw.getAttribute('data-name'); const targetState = sw.checked; sw.disabled = true; try { const res = await api.toggleSubdomain(name, targetState); toast.success( `Subdominio ${targetState ? 'habilitado' : 'pausado'}`, `'${name}' se encuentra ahora ${targetState ? 'activo' : 'inactivo'}.` ); loadSubdomains(); } catch (err) { // Revertir switch sw.checked = !targetState; toast.error('Error al alternar estado', err.detail || err.message); } finally { sw.disabled = false; } }); }); // Botones de editar document.querySelectorAll('.btn-edit-subdomain').forEach(btn => { btn.addEventListener('click', () => { const name = btn.getAttribute('data-name'); openEditSubdomainModal(name); }); }); // Botones de eliminar document.querySelectorAll('.btn-delete-subdomain').forEach(btn => { btn.addEventListener('click', () => { const name = btn.getAttribute('data-name'); const domain = btn.getAttribute('data-domain'); const type = btn.getAttribute('data-type'); openDeleteSubdomainModal(name, domain, type); }); }); } function setupFiltersAndSearch() { const inputSearch = document.getElementById('search-subdomains'); const selectMode = document.getElementById('filter-mode'); const selectStatus = document.getElementById('filter-status'); const btnRefresh = document.getElementById('btn-refresh-subdomains'); if (inputSearch) { inputSearch.addEventListener('input', (e) => { const filter = store.getState('subdomainsFilter'); store.setState({ subdomainsFilter: { ...filter, search: e.target.value.trim() } }); renderSubdomains(); }); } if (selectMode) { selectMode.addEventListener('change', (e) => { const filter = store.getState('subdomainsFilter'); store.setState({ subdomainsFilter: { ...filter, mode: e.target.value } }); renderSubdomains(); }); } if (selectStatus) { selectStatus.addEventListener('change', (e) => { const filter = store.getState('subdomainsFilter'); store.setState({ subdomainsFilter: { ...filter, status: e.target.value } }); renderSubdomains(); }); } if (btnRefresh) { btnRefresh.addEventListener('click', () => { loadSubdomains(); toast.info('Actualizando subdominios', 'Consultando configuración de Apache...'); }); } } /* ========================================================================== Modales: Crear / Editar Subdominio con Terminal de Rollback & Riesgo ========================================================================== */ let currentSubdomainModalMode = 'create'; // 'create' | 'edit' let selectedSubdomainType = 'static'; // 'static' | 'proxy' let currentEditingSubdomainName = ''; let currentRiskRequiresConfirmation = false; function setupModals() { // Botón abrir modal nuevo subdominio const btnOpenCreate = document.getElementById('btn-open-create-subdomain'); if (btnOpenCreate) { btnOpenCreate.addEventListener('click', () => { openCreateSubdomainModal(); }); } // Selector de Modo A vs Modo B const modeBtnStatic = document.getElementById('mode-btn-static'); const modeBtnProxy = document.getElementById('mode-btn-proxy'); const proxyPortGroup = document.getElementById('form-group-port'); if (modeBtnStatic && modeBtnProxy) { modeBtnStatic.addEventListener('click', () => { selectedSubdomainType = 'static'; modeBtnStatic.classList.add('active'); modeBtnProxy.classList.remove('active'); if (proxyPortGroup) proxyPortGroup.style.display = 'none'; validateSubdomainFormLive(); if (currentSubdomainModalMode === 'edit') { evaluateSubdomainRisk(currentEditingSubdomainName); } }); modeBtnProxy.addEventListener('click', () => { selectedSubdomainType = 'proxy'; modeBtnProxy.classList.add('active'); modeBtnStatic.classList.remove('active'); if (proxyPortGroup) proxyPortGroup.style.display = 'flex'; validateSubdomainFormLive(); if (currentSubdomainModalMode === 'edit') { evaluateSubdomainRisk(currentEditingSubdomainName); } }); } // Validación en vivo del nombre y preview de URL const inputName = document.getElementById('subdomain-name-input'); const inputPort = document.getElementById('subdomain-port-input'); const chkConfirmRisk = document.getElementById('chk-confirm-subdomain-risk'); if (inputName) { inputName.addEventListener('input', () => { validateSubdomainFormLive(); }); } if (inputPort) { inputPort.addEventListener('input', () => { validateSubdomainFormLive(); if (currentSubdomainModalMode === 'edit') { evaluateSubdomainRisk(currentEditingSubdomainName); } }); } if (chkConfirmRisk) { chkConfirmRisk.addEventListener('change', () => { validateSubdomainFormLive(); }); } // Enviar Formulario Subdominio const formSubdomain = document.getElementById('form-subdomain'); if (formSubdomain) { formSubdomain.addEventListener('submit', handleSubdomainFormSubmit); } // Botón Copiar Stderr en Terminal Rollback const btnCopyStderr = document.getElementById('btn-copy-terminal-stderr'); if (btnCopyStderr) { btnCopyStderr.addEventListener('click', () => { const text = document.getElementById('terminal-stderr-text')?.textContent || ''; navigator.clipboard.writeText(text).then(() => { toast.info('Copiado al Portapapeles', 'Detalles de error copiados.'); }); }); } // Botón Confirmar Eliminación const btnConfirmDelete = document.getElementById('btn-confirm-delete-subdomain'); if (btnConfirmDelete) { btnConfirmDelete.addEventListener('click', handleConfirmDeleteSubdomain); } // Botones de Cerrar Modales document.querySelectorAll('.modal-close-btn, .btn-modal-cancel').forEach(btn => { btn.addEventListener('click', closeAllModals); }); } function openCreateSubdomainModal() { currentSubdomainModalMode = 'create'; selectedSubdomainType = 'static'; currentEditingSubdomainName = ''; currentRiskRequiresConfirmation = false; const modal = document.getElementById('modal-subdomain'); const title = document.getElementById('modal-subdomain-title'); const inputName = document.getElementById('subdomain-name-input'); const inputPort = document.getElementById('subdomain-port-input'); const proxyPortGroup = document.getElementById('form-group-port'); const btnStatic = document.getElementById('mode-btn-static'); const btnProxy = document.getElementById('mode-btn-proxy'); const terminal = document.getElementById('rollback-terminal'); const btnSubmit = document.getElementById('btn-submit-subdomain'); const riskContainer = document.getElementById('subdomain-risk-container'); const riskConfirmation = document.getElementById('subdomain-risk-confirmation'); const chkConfirm = document.getElementById('chk-confirm-subdomain-risk'); if (title) title.textContent = 'Crear Nuevo Subdominio'; if (btnSubmit) btnSubmit.textContent = 'Crear Subdominio'; if (inputName) { inputName.value = ''; inputName.disabled = false; } if (inputPort) inputPort.value = ''; btnStatic?.classList.add('active'); btnProxy?.classList.remove('active'); if (proxyPortGroup) proxyPortGroup.style.display = 'none'; if (riskContainer) riskContainer.style.display = 'none'; if (riskConfirmation) riskConfirmation.style.display = 'none'; if (chkConfirm) chkConfirm.checked = false; // Ocultar terminal de rollback previo if (terminal) terminal.classList.remove('active'); validateSubdomainFormLive(); openModal('modal-subdomain'); inputName?.focus(); } async function openEditSubdomainModal(name) { const subdomains = store.getState('subdomains') || []; const item = subdomains.find(s => s.name === name); if (!item) return; currentSubdomainModalMode = 'edit'; currentEditingSubdomainName = name; selectedSubdomainType = item.type || 'static'; currentRiskRequiresConfirmation = false; const modal = document.getElementById('modal-subdomain'); const title = document.getElementById('modal-subdomain-title'); const inputName = document.getElementById('subdomain-name-input'); const inputPort = document.getElementById('subdomain-port-input'); const proxyPortGroup = document.getElementById('form-group-port'); const btnStatic = document.getElementById('mode-btn-static'); const btnProxy = document.getElementById('mode-btn-proxy'); const terminal = document.getElementById('rollback-terminal'); const btnSubmit = document.getElementById('btn-submit-subdomain'); const riskContainer = document.getElementById('subdomain-risk-container'); const riskConfirmation = document.getElementById('subdomain-risk-confirmation'); const chkConfirm = document.getElementById('chk-confirm-subdomain-risk'); if (title) title.textContent = `Editar Subdominio: ${name}`; if (btnSubmit) btnSubmit.textContent = 'Guardar Cambios'; if (inputName) { inputName.value = name; inputName.disabled = true; // El nombre en edición no se altera } if (item.type === 'proxy') { btnProxy?.classList.add('active'); btnStatic?.classList.remove('active'); if (proxyPortGroup) proxyPortGroup.style.display = 'flex'; if (inputPort) inputPort.value = item.port || ''; } else { btnStatic?.classList.add('active'); btnProxy?.classList.remove('active'); if (proxyPortGroup) proxyPortGroup.style.display = 'none'; if (inputPort) inputPort.value = ''; } if (riskContainer) riskContainer.style.display = 'none'; if (riskConfirmation) riskConfirmation.style.display = 'none'; if (chkConfirm) chkConfirm.checked = false; if (terminal) terminal.classList.remove('active'); validateSubdomainFormLive(); openModal('modal-subdomain'); // Evaluar riesgos en vivo await evaluateSubdomainRisk(name); } let riskDebounceTimer = null; async function evaluateSubdomainRisk(name) { if (currentSubdomainModalMode !== 'edit' || !name) return; clearTimeout(riskDebounceTimer); riskDebounceTimer = setTimeout(async () => { const inputPort = document.getElementById('subdomain-port-input'); const riskContainer = document.getElementById('subdomain-risk-container'); const riskList = document.getElementById('subdomain-risk-list'); const riskBadge = document.getElementById('subdomain-risk-level-badge'); const riskConfirmation = document.getElementById('subdomain-risk-confirmation'); const chkConfirm = document.getElementById('chk-confirm-subdomain-risk'); const portVal = selectedSubdomainType === 'proxy' && inputPort?.value ? Number(inputPort.value) : undefined; try { const response = await api.validateSubdomain(name, { type: selectedSubdomainType, port: portVal }); const report = response?.data || response; if (report && report.hasRisk && Array.isArray(report.risks) && report.risks.length > 0) { currentRiskRequiresConfirmation = true; if (riskContainer) riskContainer.style.display = 'flex'; if (riskConfirmation) riskConfirmation.style.display = 'flex'; const hasCritical = report.risks.some(r => r.level === 'critical'); const hasHigh = report.risks.some(r => r.level === 'high'); if (riskBadge) { if (hasCritical) { riskBadge.textContent = 'CRÍTICO'; riskBadge.style.background = '#ef4444'; } else if (hasHigh) { riskBadge.textContent = 'ALTO RIESGO'; riskBadge.style.background = '#f97316'; } else { riskBadge.textContent = 'ADVERTENCIA'; riskBadge.style.background = '#f59e0b'; } } if (riskList) { riskList.innerHTML = report.risks.map(r => `
[${(r.level || 'aviso').toUpperCase()}] ${escapeHtml(r.message)}
`).join(''); } } else { currentRiskRequiresConfirmation = false; if (riskContainer) riskContainer.style.display = 'none'; if (riskConfirmation) riskConfirmation.style.display = 'none'; if (chkConfirm) chkConfirm.checked = false; } } catch (err) { console.warn('[RiskValidation] Error al validar riesgos:', err.message); } validateSubdomainFormLive(); }, 200); } function validateSubdomainFormLive() { const inputName = document.getElementById('subdomain-name-input'); const inputPort = document.getElementById('subdomain-port-input'); const nameFeedback = document.getElementById('subdomain-name-feedback'); const portFeedback = document.getElementById('subdomain-port-feedback'); const urlPreview = document.getElementById('preview-url-domain'); const btnSubmit = document.getElementById('btn-submit-subdomain'); const chkConfirm = document.getElementById('chk-confirm-subdomain-risk'); const rawName = inputName?.value || ''; const rawPort = inputPort?.value || ''; let isNameValid = false; let isPortValid = true; // 1. Validar Nombre if (!rawName) { if (nameFeedback) nameFeedback.textContent = ''; if (urlPreview) urlPreview.textContent = `subdominio.${BASE_DOMAIN}`; inputName?.classList.remove('has-error'); } else { const res = validateSubdomainName(rawName); if (!res.valid) { if (nameFeedback) nameFeedback.textContent = res.error; inputName?.classList.add('has-error'); if (urlPreview) urlPreview.textContent = `${res.normalized || rawName}.${BASE_DOMAIN}`; } else { if (nameFeedback) nameFeedback.textContent = ''; inputName?.classList.remove('has-error'); if (urlPreview) urlPreview.textContent = `${res.normalized}.${BASE_DOMAIN}`; isNameValid = true; } } // 2. Validar Puerto si es Modo Proxy if (selectedSubdomainType === 'proxy') { const existing = store.getState('subdomains') || []; const currentName = currentSubdomainModalMode === 'edit' ? rawName : ''; const portRes = validatePort(rawPort, existing, currentName); if (!portRes.valid) { isPortValid = false; if (portFeedback) portFeedback.textContent = portRes.error; inputPort?.classList.add('has-error'); } else { isPortValid = true; if (portFeedback) portFeedback.textContent = ''; inputPort?.classList.remove('has-error'); } } else { if (portFeedback) portFeedback.textContent = ''; inputPort?.classList.remove('has-error'); } // 3. Validar Checkbox de Riesgo Obligatorio en Edición let isRiskConfirmed = true; if (currentSubdomainModalMode === 'edit' && currentRiskRequiresConfirmation) { isRiskConfirmed = Boolean(chkConfirm && chkConfirm.checked); } const formValid = isNameValid && isPortValid && isRiskConfirmed; if (btnSubmit) { btnSubmit.disabled = !formValid; } return formValid; } async function handleSubdomainFormSubmit(e) { e.preventDefault(); if (!validateSubdomainFormLive()) { return; } const inputName = document.getElementById('subdomain-name-input'); const inputPort = document.getElementById('subdomain-port-input'); const btnSubmit = document.getElementById('btn-submit-subdomain'); const terminal = document.getElementById('rollback-terminal'); const terminalText = document.getElementById('terminal-stderr-text'); const name = inputName.value.trim().toLowerCase(); const payload = { name, type: selectedSubdomainType, ...(selectedSubdomainType === 'proxy' ? { port: Number(inputPort.value) } : {}) }; btnSubmit.disabled = true; btnSubmit.textContent = 'Aplicando en Apache2...'; if (terminal) terminal.classList.remove('active'); try { if (currentSubdomainModalMode === 'create') { const res = await api.createSubdomain(payload); toast.success('Subdominio Aprovisionado', res.message || `Subdominio '${name}' creado exitosamente.`); } else { const res = await api.updateSubdomain(name, { type: payload.type, port: payload.port, forceConfirmed: true }); toast.success('Subdominio Actualizado', res.message || `Subdominio '${name}' reconfigurado.`); } closeAllModals(); loadSubdomains(); loadFolders(); // Si fue Modo A, refrescar carpetas } catch (err) { btnSubmit.disabled = false; btnSubmit.textContent = currentSubdomainModalMode === 'create' ? 'Crear Subdominio' : 'Guardar Cambios'; // Manejo de Error 422 / Rollback Atómico de Apache if (err.status === 422 || err.code === 'APACHE_CONFIGTEST_FAILED' || err.rollbackExecuted) { if (terminal && terminalText) { terminalText.textContent = err.detail || err.message || 'Error de sintaxis en archivo VirtualHost.'; terminal.classList.add('active'); terminal.scrollIntoView({ behavior: 'smooth' }); } toast.error( 'Fallo en validación de Apache2 (Rollback Ejecutado)', 'Se restauró el estado previo para mantener el servidor web intacto.', 8000 ); } else { toast.error('Error al guardar subdominio', err.detail || err.message); } } } let pendingDeleteSubdomain = null; function openDeleteSubdomainModal(name, domain, type) { pendingDeleteSubdomain = { name, domain, type }; const modal = document.getElementById('modal-delete-subdomain'); const targetText = document.getElementById('delete-subdomain-target-text'); const chkFiles = document.getElementById('chk-delete-files'); const filesContainer = document.getElementById('delete-files-checkbox-container'); if (targetText) { targetText.textContent = `${name}.${BASE_DOMAIN}`; } // Mostrar checkbox de archivos solo si es Modo A o tiene carpeta if (filesContainer) { filesContainer.style.display = type === 'static' ? 'flex' : 'none'; } if (chkFiles) { chkFiles.checked = false; } openModal('modal-delete-subdomain'); } async function handleConfirmDeleteSubdomain() { if (!pendingDeleteSubdomain) return; const btnConfirm = document.getElementById('btn-confirm-delete-subdomain'); const chkFiles = document.getElementById('chk-delete-files'); const deleteFiles = Boolean(chkFiles && chkFiles.checked); btnConfirm.disabled = true; btnConfirm.textContent = 'Eliminando...'; try { const res = await api.deleteSubdomain(pendingDeleteSubdomain.name, deleteFiles); toast.success('Subdominio Eliminado', res.message || 'Subdominio purgado exitosamente de Apache.'); closeAllModals(); loadSubdomains(); loadFolders(); } catch (err) { btnConfirm.disabled = false; btnConfirm.textContent = 'Confirmar Eliminación'; toast.error('Error al eliminar subdominio', err.detail || err.message); } } /* ========================================================================== Pestaña 2: Carpetas Web (/var/www) ========================================================================== */ async function loadFolders() { const tableBody = document.getElementById('folders-table-body'); const mobileContainer = document.getElementById('folders-mobile-list'); const badgeCount = document.getElementById('folders-count-badge'); const btnRefresh = document.getElementById('btn-refresh-folders'); store.setState({ foldersLoading: true }); try { const folders = await api.getFolders(); store.setState({ folders, foldersLoading: false }); if (badgeCount) badgeCount.textContent = folders.length; renderFolders(); } catch (err) { store.setState({ foldersLoading: false }); toast.error('Error al explorar /var/www', err.message); } } function renderFolders() { const folders = store.getState('folders') || []; const tableBody = document.getElementById('folders-table-body'); const mobileContainer = document.getElementById('folders-mobile-list'); if (folders.length === 0) { if (tableBody) tableBody.innerHTML = `No se encontraron carpetas en /var/www`; if (mobileContainer) mobileContainer.innerHTML = `
No se encontraron carpetas en /var/www
`; return; } // Renderizar Desktop if (tableBody) { tableBody.innerHTML = folders.map(f => { const isSGID = f.isSGID || f.permissions === '2775'; return `
${escapeHtml(f.folderName)}
${escapeHtml(f.path)}
${f.sizeFormatted || '—'} ${f.fileCount ?? 0} ficheros ${escapeHtml(f.owner)}:${escapeHtml(f.group)} ${escapeHtml(f.permissions)} ${isSGID ? `SGID 2775 OK` : `Sin SGID 2775` } `; }).join(''); } // Renderizar Mobile if (mobileContainer) { mobileContainer.innerHTML = folders.map(f => { const isSGID = f.isSGID || f.permissions === '2775'; return `
${escapeHtml(f.folderName)}
${escapeHtml(f.path)}
${isSGID ? `SGID 2775` : `Sin SGID` }
Tamaño: ${f.sizeFormatted || '—'}
Archivos: ${f.fileCount ?? 0} elementos
Permisos: ${escapeHtml(f.owner)}:${escapeHtml(f.group)} (${f.permissions})
`; }).join(''); } // Eventos de inspección de archivos -> Apertura de File Manager document.querySelectorAll('.btn-inspect-folder').forEach(btn => { btn.addEventListener('click', () => { const folderName = btn.getAttribute('data-name'); openFileManager(folderName, ''); }); }); const btnRefresh = document.getElementById('btn-refresh-folders'); if (btnRefresh) { btnRefresh.onclick = () => { loadFolders(); toast.info('Actualizando carpetas', 'Escaneando /var/www...'); }; } } /* ========================================================================== Gestor de Archivos (File Manager) para /var/www/ ========================================================================== */ let fmCurrentFolder = ''; let fmCurrentPath = ''; let fmFiles = []; let fmCreateType = 'file'; // 'file' | 'dir' function setupFileManager() { const btnUpload = document.getElementById('fm-btn-upload'); const fileInput = document.getElementById('fm-file-input'); const btnNewFile = document.getElementById('fm-btn-new-file'); const btnNewFolder = document.getElementById('fm-btn-new-folder'); const btnUpDir = document.getElementById('fm-btn-up-dir'); const btnRefresh = document.getElementById('fm-btn-refresh'); const btnConfirmCreate = document.getElementById('fm-btn-confirm-create-item'); const btnCancelCreate = document.getElementById('fm-btn-cancel-create-item'); const createInput = document.getElementById('fm-new-item-name-input'); if (btnUpload && fileInput) { btnUpload.addEventListener('click', () => { fileInput.value = ''; fileInput.click(); }); fileInput.addEventListener('change', async (e) => { const file = e.target.files?.[0]; if (!file) return; if (file.size > 20 * 1024 * 1024) { toast.error('Archivo demasiado grande', 'El tamaño máximo permitido es 20 MB.'); return; } toast.info('Subiendo archivo...', `Subiendo '${file.name}'`); const reader = new FileReader(); reader.onload = async () => { try { const result = reader.result; const base64Content = typeof result === 'string' && result.includes(',') ? result.split(',')[1] : result; await api.uploadFile(fmCurrentFolder, fmCurrentPath, file.name, base64Content); toast.success('Archivo Subido', `'${file.name}' se ha subido correctamente.`); loadFileManagerFiles(fmCurrentFolder, fmCurrentPath); } catch (err) { toast.error('Error al subir archivo', err.detail || err.message); } }; reader.onerror = () => { toast.error('Error de lectura', 'No se pudo leer el archivo seleccionado.'); }; reader.readAsDataURL(file); }); } if (btnNewFile) { btnNewFile.addEventListener('click', () => { fmCreateType = 'file'; const row = document.getElementById('fm-new-item-row'); const badge = document.getElementById('fm-create-type-label'); if (badge) { badge.textContent = 'Archivo'; badge.className = 'badge badge-mode-static'; } if (createInput) { createInput.value = ''; createInput.placeholder = 'ejemplo.php'; } if (row) row.style.display = 'block'; createInput?.focus(); }); } if (btnNewFolder) { btnNewFolder.addEventListener('click', () => { fmCreateType = 'dir'; const row = document.getElementById('fm-new-item-row'); const badge = document.getElementById('fm-create-type-label'); if (badge) { badge.textContent = 'Directorio'; badge.className = 'badge badge-mode-proxy'; } if (createInput) { createInput.value = ''; createInput.placeholder = 'nombre-carpeta'; } if (row) row.style.display = 'block'; createInput?.focus(); }); } if (btnCancelCreate) { btnCancelCreate.addEventListener('click', () => { const row = document.getElementById('fm-new-item-row'); if (row) row.style.display = 'none'; }); } if (btnConfirmCreate) { btnConfirmCreate.addEventListener('click', async () => { const name = createInput?.value?.trim(); if (!name) { toast.warning('Campo requerido', 'Ingresa un nombre para el nuevo elemento.'); return; } try { await api.createFolderItem(fmCurrentFolder, fmCurrentPath, name, fmCreateType); toast.success( fmCreateType === 'dir' ? 'Directorio Creado' : 'Archivo Creado', `'${name}' creado exitosamente.` ); const row = document.getElementById('fm-new-item-row'); if (row) row.style.display = 'none'; loadFileManagerFiles(fmCurrentFolder, fmCurrentPath); } catch (err) { toast.error('Error al crear elemento', err.detail || err.message); } }); if (createInput) { createInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); btnConfirmCreate.click(); } else if (e.key === 'Escape') { const row = document.getElementById('fm-new-item-row'); if (row) row.style.display = 'none'; } }); } } if (btnUpDir) { btnUpDir.addEventListener('click', () => { if (!fmCurrentPath) return; const parts = fmCurrentPath.split('/').filter(Boolean); parts.pop(); const parentPath = parts.join('/'); loadFileManagerFiles(fmCurrentFolder, parentPath); }); } if (btnRefresh) { btnRefresh.addEventListener('click', () => { loadFileManagerFiles(fmCurrentFolder, fmCurrentPath); toast.info('Actualizando', 'Contenido de carpeta actualizado.'); }); } } async function openFileManager(folderName, subPath = '') { fmCurrentFolder = folderName; fmCurrentPath = subPath; const row = document.getElementById('fm-new-item-row'); if (row) row.style.display = 'none'; openModal('modal-file-manager'); await loadFileManagerFiles(folderName, subPath); } async function loadFileManagerFiles(folderName, subPath = '') { fmCurrentFolder = folderName; fmCurrentPath = subPath; const modalTitle = document.getElementById('fm-modal-title'); const pathDisplay = document.getElementById('fm-current-path-display'); const tableBody = document.getElementById('fm-files-table-body'); const itemsCountText = document.getElementById('fm-items-count-text'); const btnUpDir = document.getElementById('fm-btn-up-dir'); if (modalTitle) modalTitle.textContent = `Gestor de Archivos: ${folderName}`; const fullDisplayPath = `/var/www/${folderName}${subPath ? `/${subPath}` : ''}`; if (pathDisplay) pathDisplay.textContent = fullDisplayPath; if (btnUpDir) { btnUpDir.disabled = !subPath; } // Renderizar Breadcrumbs renderBreadcrumbs(folderName, subPath); if (tableBody) { tableBody.innerHTML = `Cargando archivos...`; } try { const res = await api.getFolderFiles(folderName, subPath); const data = res.data || res; fmFiles = data.files || []; if (itemsCountText) { itemsCountText.textContent = `${fmFiles.length} elemento${fmFiles.length === 1 ? '' : 's'}`; } renderFileManagerTable(fmFiles); } catch (err) { if (tableBody) { tableBody.innerHTML = `Error al leer carpeta: ${escapeHtml(err.detail || err.message)}`; } } } function renderBreadcrumbs(folderName, subPath) { const container = document.getElementById('fm-breadcrumbs'); if (!container) return; const parts = subPath ? subPath.split('/').filter(Boolean) : []; let html = ` `; let accumulated = ''; parts.forEach((p, index) => { accumulated = accumulated ? `${accumulated}/${p}` : p; const isLast = index === parts.length - 1; html += ` / `; }); container.innerHTML = html; container.querySelectorAll('.fm-breadcrumb-item:not(.fm-breadcrumb-active)').forEach(btn => { btn.addEventListener('click', () => { const targetPath = btn.getAttribute('data-path') || ''; loadFileManagerFiles(fmCurrentFolder, targetPath); }); }); } function getFileIconSvg(file) { if (file.type === 'directory') { return ` `; } const ext = (file.name.includes('.') ? file.name.split('.').pop() : '').toLowerCase(); if (ext === 'php') { return ` `; } if (ext === 'js' || ext === 'mjs' || ext === 'ts') { return ` `; } if (ext === 'html' || ext === 'htm') { return ` `; } if (ext === 'css' || ext === 'scss' || ext === 'less') { return ` `; } if (ext === 'json') { return ` `; } if (['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'].includes(ext)) { return ` `; } return ` `; } function renderFileManagerTable(files) { const tableBody = document.getElementById('fm-files-table-body'); if (!tableBody) return; if (files.length === 0) { tableBody.innerHTML = `Esta carpeta está vacía. Sube archivos o crea uno nuevo usando la barra superior.`; return; } tableBody.innerHTML = files.map(file => { const isDir = file.type === 'directory'; const icon = getFileIconSvg(file); const dateFormatted = file.lastModified ? new Date(file.lastModified).toLocaleString() : '—'; return `
${icon} ${isDir ? `${escapeHtml(file.name)}/` : `${escapeHtml(file.name)}` }
${isDir ? 'Directorio' : 'Archivo'} ${isDir ? '—' : (file.sizeFormatted || '—')} ${escapeHtml(file.permissions || '—')} ${dateFormatted}
${file.isEditable ? `` : '' }
`; }).join(''); // Eventos en filas tableBody.querySelectorAll('.fm-folder-link').forEach(link => { link.addEventListener('click', (e) => { e.preventDefault(); const targetPath = link.getAttribute('data-path'); loadFileManagerFiles(fmCurrentFolder, targetPath); }); }); tableBody.querySelectorAll('.btn-fm-edit').forEach(btn => { btn.addEventListener('click', () => { const fileName = btn.getAttribute('data-name'); const filePath = btn.getAttribute('data-path'); openCodeEditor(fmCurrentFolder, filePath, fileName); }); }); tableBody.querySelectorAll('.btn-fm-delete').forEach(btn => { btn.addEventListener('click', async () => { const fileName = btn.getAttribute('data-name'); const filePath = btn.getAttribute('data-path'); const type = btn.getAttribute('data-type'); const isDir = type === 'directory'; const promptText = `¿Estás seguro de que deseas eliminar ${isDir ? 'el directorio' : 'el archivo'} '${fileName}'?`; if (!confirm(promptText)) return; try { await api.deleteFolderItem(fmCurrentFolder, filePath); toast.success( isDir ? 'Directorio Eliminado' : 'Archivo Eliminado', `'${fileName}' fue eliminado correctamente.` ); loadFileManagerFiles(fmCurrentFolder, fmCurrentPath); } catch (err) { toast.error('Error al eliminar', err.detail || err.message); } }); }); } /* ========================================================================== Editor de Código para Archivos Web (.php, .html, .css, .js, etc.) ========================================================================== */ let currentEditorFolder = ''; let currentEditorPath = ''; let currentEditorFileName = ''; let editorOriginalContent = ''; function setupCodeEditor() { const textarea = document.getElementById('code-editor-textarea'); const btnSaveTop = document.getElementById('code-editor-btn-save'); const btnSaveBottom = document.getElementById('code-editor-btn-save-bottom'); const btnClose = document.getElementById('code-editor-btn-close'); if (textarea) { textarea.addEventListener('input', () => { updateCodeEditorLineNumbers(); updateCodeEditorStatus(); updateCodeEditorCursorPos(); }); textarea.addEventListener('scroll', () => { const lineGutter = document.getElementById('code-editor-linenumbers'); if (lineGutter) { lineGutter.scrollTop = textarea.scrollTop; } }); textarea.addEventListener('click', updateCodeEditorCursorPos); textarea.addEventListener('keyup', updateCodeEditorCursorPos); // Tecla Tab e interceptación de Ctrl+S / Cmd+S textarea.addEventListener('keydown', (e) => { if (e.key === 'Tab') { e.preventDefault(); const start = textarea.selectionStart; const end = textarea.selectionEnd; textarea.value = textarea.value.substring(0, start) + ' ' + textarea.value.substring(end); textarea.selectionStart = textarea.selectionEnd = start + 2; updateCodeEditorLineNumbers(); updateCodeEditorStatus(); } else if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); saveCodeEditorFile(); } }); } if (btnSaveTop) btnSaveTop.addEventListener('click', saveCodeEditorFile); if (btnSaveBottom) btnSaveBottom.addEventListener('click', saveCodeEditorFile); if (btnClose) { btnClose.addEventListener('click', () => { const modal = document.getElementById('modal-code-editor'); if (modal) modal.classList.remove('active'); }); } } async function openCodeEditor(folderName, filePath, fileName) { currentEditorFolder = folderName; currentEditorPath = filePath; currentEditorFileName = fileName; const modal = document.getElementById('modal-code-editor'); const titleEl = document.getElementById('code-editor-file-title'); const pathEl = document.getElementById('code-editor-file-path'); const statusEl = document.getElementById('code-editor-save-status'); const textarea = document.getElementById('code-editor-textarea'); if (titleEl) titleEl.textContent = fileName; if (pathEl) pathEl.textContent = `/var/www/${folderName}/${filePath}`; if (statusEl) { statusEl.textContent = 'Cargando...'; statusEl.className = 'code-editor-status-tag status-clean'; } if (textarea) { textarea.value = ''; textarea.disabled = true; } openModal('modal-code-editor'); try { const res = await api.getFileContent(folderName, filePath); const data = res.data || res; const content = typeof data.content === 'string' ? data.content : ''; if (textarea) { textarea.value = content; textarea.disabled = false; editorOriginalContent = content; } updateCodeEditorLineNumbers(); updateCodeEditorStatus(); updateCodeEditorCursorPos(); textarea?.focus(); } catch (err) { if (statusEl) { statusEl.textContent = 'Error al cargar'; statusEl.className = 'code-editor-status-tag status-dirty'; } toast.error('Error al abrir archivo', err.detail || err.message); } } function updateCodeEditorLineNumbers() { const textarea = document.getElementById('code-editor-textarea'); const lineGutter = document.getElementById('code-editor-linenumbers'); if (!textarea || !lineGutter) return; const linesCount = (textarea.value.match(/\n/g) || []).length + 1; let numbersStr = ''; for (let i = 1; i <= linesCount; i++) { numbersStr += i + '\n'; } lineGutter.textContent = numbersStr; lineGutter.scrollTop = textarea.scrollTop; } function updateCodeEditorStatus() { const textarea = document.getElementById('code-editor-textarea'); const statusEl = document.getElementById('code-editor-save-status'); const charCountEl = document.getElementById('code-editor-char-count'); if (!textarea || !statusEl) return; const isDirty = textarea.value !== editorOriginalContent; if (isDirty) { statusEl.textContent = 'Modificado*'; statusEl.className = 'code-editor-status-tag status-dirty'; } else { statusEl.textContent = 'Sin cambios'; statusEl.className = 'code-editor-status-tag status-clean'; } if (charCountEl) { charCountEl.textContent = `${textarea.value.length} caracteres`; } } function updateCodeEditorCursorPos() { const textarea = document.getElementById('code-editor-textarea'); const posEl = document.getElementById('code-editor-cursor-pos'); if (!textarea || !posEl) return; const textToCursor = textarea.value.substring(0, textarea.selectionStart); const lines = textToCursor.split('\n'); const currentLine = lines.length; const currentCol = lines[lines.length - 1].length + 1; posEl.textContent = `Línea ${currentLine}, Col ${currentCol}`; } async function saveCodeEditorFile() { const textarea = document.getElementById('code-editor-textarea'); const statusEl = document.getElementById('code-editor-save-status'); const btnTop = document.getElementById('code-editor-btn-save'); const btnBottom = document.getElementById('code-editor-btn-save-bottom'); if (!textarea || !currentEditorFolder || !currentEditorPath) return; if (statusEl) { statusEl.textContent = 'Guardando...'; statusEl.className = 'code-editor-status-tag status-saving'; } if (btnTop) btnTop.disabled = true; if (btnBottom) btnBottom.disabled = true; try { await api.saveFileContent(currentEditorFolder, currentEditorPath, textarea.value); editorOriginalContent = textarea.value; if (statusEl) { statusEl.textContent = 'Guardado exitosamente'; statusEl.className = 'code-editor-status-tag status-saved'; } toast.success('Archivo Guardado', `'${currentEditorFileName}' se guardó en el servidor.`); updateCodeEditorStatus(); // Si el file manager está abierto en la misma carpeta, actualizar lista if (fmCurrentFolder === currentEditorFolder) { loadFileManagerFiles(fmCurrentFolder, fmCurrentPath); } } catch (err) { if (statusEl) { statusEl.textContent = 'Error al guardar'; statusEl.className = 'code-editor-status-tag status-dirty'; } toast.error('Error al guardar archivo', err.detail || err.message); } finally { if (btnTop) btnTop.disabled = false; if (btnBottom) btnBottom.disabled = false; } } /* ========================================================================== 🖥️ Pestaña 3: Terminal Remota del Sistema (Bash) ========================================================================== */ let terminalCommandHistory = []; let terminalHistoryIndex = -1; let currentTerminalCwd = '/var/www'; let terminalUser = 'ggc'; let terminalHost = 'vps-jose'; function setupTerminal() { const form = document.getElementById('terminal-command-form'); const input = document.getElementById('terminal-input'); const btnClear = document.getElementById('terminal-btn-clear'); if (form && input) { form.addEventListener('submit', async (e) => { e.preventDefault(); const cmd = input.value.trim(); if (!cmd) return; terminalCommandHistory.push(cmd); terminalHistoryIndex = -1; input.value = ''; await executeTerminalCommand(cmd); }); input.addEventListener('keydown', (e) => { if (e.key === 'ArrowUp') { e.preventDefault(); if (terminalCommandHistory.length === 0) return; if (terminalHistoryIndex === -1) { terminalHistoryIndex = terminalCommandHistory.length - 1; } else if (terminalHistoryIndex > 0) { terminalHistoryIndex--; } input.value = terminalCommandHistory[terminalHistoryIndex] || ''; } else if (e.key === 'ArrowDown') { e.preventDefault(); if (terminalHistoryIndex !== -1) { if (terminalHistoryIndex < terminalCommandHistory.length - 1) { terminalHistoryIndex++; input.value = terminalCommandHistory[terminalHistoryIndex] || ''; } else { terminalHistoryIndex = -1; input.value = ''; } } } }); } // Quick command buttons document.querySelectorAll('.btn-quick-cmd').forEach(btn => { btn.addEventListener('click', () => { const cmd = btn.getAttribute('data-cmd'); if (cmd && input) { input.value = cmd; if (form) { form.dispatchEvent(new Event('submit', { cancelable: true })); } } }); }); if (btnClear) { btnClear.addEventListener('click', () => { const screen = document.getElementById('terminal-screen'); if (screen) { screen.innerHTML = `
a2host Remote Web Terminal v1.0 [Linux 6.x / VPS elingejose.com] Escribe un comando o selecciona una acción rápida superior. Usa las flechas ↑/↓ para navegar en el historial.
`; } }); } } async function initTerminalTab() { const badgeEl = document.getElementById('terminal-env-badge'); const promptLabel = document.getElementById('terminal-prompt-label'); const topbarTitle = document.getElementById('terminal-topbar-title'); const input = document.getElementById('terminal-input'); try { const res = await api.getTerminalInfo(); const info = res.data || res; if (info) { terminalUser = info.user || 'ggc'; terminalHost = info.hostname || 'vps-jose'; currentTerminalCwd = info.cwd || '/var/www'; if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`; if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:~$`; if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`; } } catch (err) { console.warn('[Terminal] Error al obtener info:', err); } input?.focus(); } async function executeTerminalCommand(cmd) { const screen = document.getElementById('terminal-screen'); const input = document.getElementById('terminal-input'); if (!screen) return; const entryId = 'cmd-' + Date.now(); const promptText = `${terminalUser}@${terminalHost}:~${currentTerminalCwd}$`; const entryEl = document.createElement('div'); entryEl.className = 'terminal-entry'; entryEl.id = entryId; entryEl.innerHTML = `
${escapeHtml(promptText)} ${escapeHtml(cmd)}
Ejecutando proceso...
`; screen.appendChild(entryEl); screen.scrollTop = screen.scrollHeight; if (input) input.disabled = true; try { const response = await api.executeCommand(cmd, currentTerminalCwd); const result = response.data || response; const outBlock = document.getElementById(`output-${entryId}`); if (outBlock) { const stdout = result.stdout || ''; const stderr = result.stderr || ''; const exitCode = result.exitCode ?? 0; const ms = result.executionTimeMs ?? 0; let outHtml = ''; if (stdout) { outHtml += `
${escapeHtml(stdout)}
`; } if (stderr) { outHtml += `
${escapeHtml(stderr)}
`; } if (!stdout && !stderr) { outHtml += `(Sin salida)`; } outBlock.innerHTML = outHtml; if (exitCode !== 0) { outBlock.classList.add('has-error'); } // Añadir footer const footerEl = document.createElement('div'); footerEl.className = 'terminal-entry-footer'; footerEl.innerHTML = ` ⏱️ ${ms}ms exit ${exitCode} `; entryEl.appendChild(footerEl); if (result.cwd && result.cwd !== currentTerminalCwd) { currentTerminalCwd = result.cwd; const promptLabel = document.getElementById('terminal-prompt-label'); const badgeEl = document.getElementById('terminal-env-badge'); const topbarTitle = document.getElementById('terminal-topbar-title'); if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`; if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:~$`; if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`; } } } catch (err) { const outBlock = document.getElementById(`output-${entryId}`); if (outBlock) { outBlock.classList.add('has-error'); outBlock.innerHTML = `
Error de ejecución: ${escapeHtml(err.detail || err.message)}
`; } } finally { if (input) { input.disabled = false; input.focus(); } screen.scrollTop = screen.scrollHeight; } } /* ========================================================================== 📊 Pestaña 4: Monitor del Servidor VPS ========================================================================== */ let monitorAutoRefreshTimer = null; let currentTopProcesses = []; function setupMonitor() { const btnRefresh = document.getElementById('btn-refresh-monitor'); const selectInterval = document.getElementById('monitor-interval-select'); const searchInput = document.getElementById('search-processes-input'); if (btnRefresh) { btnRefresh.addEventListener('click', () => { loadMonitorMetrics(); toast.info('Monitor Actualizado', 'Métricas refrescadas.'); }); } if (selectInterval) { selectInterval.addEventListener('change', () => { restartMonitorAutoRefresh(); }); } if (searchInput) { searchInput.addEventListener('input', () => { renderProcessesTable(currentTopProcesses); }); } } function initMonitorTab() { loadMonitorMetrics(); restartMonitorAutoRefresh(); } function stopMonitorAutoRefresh() { if (monitorAutoRefreshTimer) { clearInterval(monitorAutoRefreshTimer); monitorAutoRefreshTimer = null; } } function restartMonitorAutoRefresh() { stopMonitorAutoRefresh(); const selectInterval = document.getElementById('monitor-interval-select'); const intervalMs = Number(selectInterval?.value || 0); if (intervalMs > 0) { monitorAutoRefreshTimer = setInterval(() => { if (store.getState('activeTab') === 'monitor') { loadMonitorMetrics(); } else { stopMonitorAutoRefresh(); } }, intervalMs); } } async function loadMonitorMetrics() { const lastUpdatedEl = document.getElementById('monitor-last-updated-text'); try { const [statsRes, procsRes] = await Promise.all([ api.getSystemStats(), api.getSystemProcesses().catch(() => []) ]); const stats = statsRes.data || statsRes; const procs = Array.isArray(procsRes) ? procsRes : (procsRes.data || []); currentTopProcesses = procs; updateMonitorUI(stats); renderProcessesTable(procs); if (lastUpdatedEl) { lastUpdatedEl.textContent = `Actualizado: ${new Date().toLocaleTimeString()}`; } } catch (err) { console.warn('[Monitor] Error al cargar telemetría:', err.message); } } function updateMonitorUI(stats) { if (!stats) return; // 1. CPU & Load Average const cpuPercent = stats.cpu?.usagePercent ?? 0; const cpuPercentEl = document.getElementById('monitor-cpu-percent'); const cpuBarEl = document.getElementById('monitor-cpu-bar'); const cpuModelEl = document.getElementById('monitor-cpu-model-text'); const load1mEl = document.getElementById('monitor-load-1m'); const load5mEl = document.getElementById('monitor-load-5m'); const load15mEl = document.getElementById('monitor-load-15m'); if (cpuPercentEl) cpuPercentEl.textContent = `${cpuPercent}%`; if (cpuBarEl) { cpuBarEl.style.width = `${Math.min(100, cpuPercent)}%`; cpuBarEl.className = 'metric-progress-fill'; if (cpuPercent > 80) cpuBarEl.classList.add('fill-danger'); else if (cpuPercent > 60) cpuBarEl.classList.add('fill-warning'); } if (cpuModelEl && stats.cpu) { cpuModelEl.textContent = `${stats.cpu.cores} Cores · ${stats.server?.arch || 'x64'}`; } if (load1mEl) load1mEl.textContent = stats.cpu?.loadavg?.[0]?.toFixed(2) ?? '0.00'; if (load5mEl) load5mEl.textContent = stats.cpu?.loadavg?.[1]?.toFixed(2) ?? '0.00'; if (load15mEl) load15mEl.textContent = stats.cpu?.loadavg?.[2]?.toFixed(2) ?? '0.00'; // 2. RAM del VPS const ramUsedEl = document.getElementById('monitor-ram-used-text'); const ramPercentEl = document.getElementById('monitor-ram-percent'); const ramBarEl = document.getElementById('monitor-ram-bar'); const ramFreeEl = document.getElementById('monitor-ram-free'); const ramCacheEl = document.getElementById('monitor-ram-cache'); if (stats.memory) { const mem = stats.memory; if (ramUsedEl) ramUsedEl.textContent = `${mem.usedFormatted || '0 B'} / ${mem.totalFormatted || '1 GB'}`; if (ramPercentEl) ramPercentEl.textContent = `${mem.usedPercent || 0}%`; if (ramBarEl) { ramBarEl.style.width = `${Math.min(100, mem.usedPercent || 0)}%`; ramBarEl.className = 'metric-progress-fill fill-lime'; if (mem.usedPercent > 85) ramBarEl.classList.add('fill-danger'); else if (mem.usedPercent > 65) ramBarEl.classList.add('fill-warning'); } if (ramFreeEl) ramFreeEl.textContent = mem.freeFormatted || '0 B'; if (ramCacheEl) ramCacheEl.textContent = mem.buffersCacheFormatted || mem.cachedFormatted || '—'; } // 3. Swap const swapUsedEl = document.getElementById('monitor-swap-used-text'); const swapPercentEl = document.getElementById('monitor-swap-percent'); const swapBarEl = document.getElementById('monitor-swap-bar'); const swapFreeEl = document.getElementById('monitor-swap-free'); const swapTotalEl = document.getElementById('monitor-swap-total'); if (stats.memory) { const mem = stats.memory; if (swapUsedEl) swapUsedEl.textContent = `${mem.swapUsedFormatted || '0 B'} / ${mem.swapTotalFormatted || '0 B'}`; if (swapPercentEl) swapPercentEl.textContent = `${mem.swapUsedPercent || 0}%`; if (swapBarEl) swapBarEl.style.width = `${Math.min(100, mem.swapUsedPercent || 0)}%`; if (swapFreeEl) swapFreeEl.textContent = mem.swapFreeFormatted || '—'; if (swapTotalEl) swapTotalEl.textContent = mem.swapTotalFormatted || '—'; } // 4. Disco / const diskUsedEl = document.getElementById('monitor-disk-used-text'); const diskPercentEl = document.getElementById('monitor-disk-percent'); const diskBarEl = document.getElementById('monitor-disk-bar'); const diskFreeEl = document.getElementById('monitor-disk-free'); const diskTotalEl = document.getElementById('monitor-disk-total'); if (stats.disk) { const d = stats.disk; if (diskUsedEl) diskUsedEl.textContent = `${d.usedFormatted || '0 B'} / ${d.totalFormatted || '0 B'}`; if (diskPercentEl) diskPercentEl.textContent = `${d.usedPercent || 0}%`; if (diskBarEl) diskBarEl.style.width = `${Math.min(100, d.usedPercent || 0)}%`; if (diskFreeEl) diskFreeEl.textContent = d.freeFormatted || '0 B'; if (diskTotalEl) diskTotalEl.textContent = d.totalFormatted || '0 B'; } // 5. Proceso a2host (PM2 vs 120M) const pm2UsedEl = document.getElementById('monitor-pm2-used-text'); const pm2PercentEl = document.getElementById('monitor-pm2-percent'); const pm2BarEl = document.getElementById('monitor-pm2-bar'); const pm2HeapEl = document.getElementById('monitor-pm2-heap'); if (stats.memory) { const mem = stats.memory; const rssBytes = mem.processRssBytes || 0; const pm2Limit = 120 * 1024 * 1024; const pm2Percent = Math.min(100, Math.round((rssBytes / pm2Limit) * 100)); if (pm2UsedEl) pm2UsedEl.textContent = `${mem.processRssFormatted || '0 MB'} / 120 MB`; if (pm2PercentEl) pm2PercentEl.textContent = `${pm2Percent}%`; if (pm2BarEl) { pm2BarEl.style.width = `${pm2Percent}%`; pm2BarEl.className = 'metric-progress-fill fill-lime'; if (pm2Percent > 85) pm2BarEl.classList.add('fill-danger'); else if (pm2Percent > 65) pm2BarEl.classList.add('fill-warning'); } if (pm2HeapEl) pm2HeapEl.textContent = `${mem.heapUsedFormatted || '—'} / ${mem.heapTotalFormatted || '—'}`; } } function getProcessBadgeClass(cmd) { const lower = (cmd || '').toLowerCase(); if (lower.includes('apache') || lower.includes('httpd')) return 'proc-apache'; if (lower.includes('node') || lower.includes('pm2')) return 'proc-node'; if (lower.includes('git')) return 'proc-gitea'; if (lower.includes('mysql') || lower.includes('mariadb')) return 'proc-mysql'; return 'proc-system'; } function renderProcessesTable(processes) { const tableBody = document.getElementById('processes-table-body'); const mobileContainer = document.getElementById('processes-mobile-list'); const searchInput = document.getElementById('search-processes-input'); const query = searchInput?.value?.trim().toLowerCase() || ''; const filtered = processes.filter(p => { if (!query) return true; return String(p.pid).includes(query) || (p.command || '').toLowerCase().includes(query) || (p.user || '').toLowerCase().includes(query); }); if (tableBody) { if (filtered.length === 0) { tableBody.innerHTML = `No se encontraron procesos coincidentes.`; } else { tableBody.innerHTML = filtered.map(p => { const badgeCls = getProcessBadgeClass(p.command); return ` ${p.pid} ${escapeHtml(p.user || 'root')} ${p.cpuPercent}% ${p.memPercent}% ${escapeHtml(p.rssFormatted || '—')} ${escapeHtml(p.command || '')} `; }).join(''); } } if (mobileContainer) { if (filtered.length === 0) { mobileContainer.innerHTML = `
No se encontraron procesos coincidentes.
`; } else { mobileContainer.innerHTML = filtered.map(p => { const badgeCls = getProcessBadgeClass(p.command); return `
${escapeHtml(p.command || '')} PID: ${p.pid}
Usuario: ${escapeHtml(p.user || 'root')}
CPU %: ${p.cpuPercent}%
Memoria %: ${p.memPercent}% (${p.rssFormatted || '—'})
`; }).join(''); } } } /* ========================================================================== Pestaña 3: Gestión de Usuarios ========================================================================== */ async function loadUsers() { const currentUser = store.getState('currentUser'); const tableBody = document.getElementById('users-table-body'); const mobileContainer = document.getElementById('users-mobile-list'); const restrictedNotice = document.getElementById('users-restricted-notice'); // Si no es admin, mostrar pantalla amigable de restricción if (currentUser?.role !== 'admin') { if (tableBody) tableBody.closest('.table-glass-card').style.display = 'none'; if (mobileContainer) mobileContainer.style.display = 'none'; if (restrictedNotice) restrictedNotice.style.display = 'flex'; return; } if (restrictedNotice) restrictedNotice.style.display = 'none'; if (tableBody) tableBody.closest('.table-glass-card').style.display = 'block'; try { const users = await api.getUsers(); store.setState({ users }); renderUsers(); } catch (err) { toast.error('Error al listar operadores', err.message); } } function renderUsers() { const users = store.getState('users') || []; const currentUser = store.getState('currentUser'); const tableBody = document.getElementById('users-table-body'); const mobileContainer = document.getElementById('users-mobile-list'); if (tableBody) { tableBody.innerHTML = users.map(u => { const isSelf = currentUser && currentUser.id === u.id; const isImmutable = Boolean(u.isImmutable); return `
${escapeHtml(u.fullName || u.username)} ${isImmutable ? `[SISTEMA / INMUTABLE]` : ''}
${escapeHtml(u.username)}
${escapeHtml(u.role)} ${u.active ? 'Activo' : 'Inactivo'} ${u.lastLogin ? new Date(u.lastLogin).toLocaleString() : 'Nunca'}
`; }).join(''); } // Tarjetas Mobile if (mobileContainer) { mobileContainer.innerHTML = users.map(u => { const isSelf = currentUser && currentUser.id === u.id; const isImmutable = Boolean(u.isImmutable); return `
${escapeHtml(u.fullName || u.username)} ${isImmutable ? `[SISTEMA / INMUTABLE]` : ''}
${escapeHtml(u.username)}
${escapeHtml(u.role)}
`; }).join(''); } attachUserEvents(); } function attachUserEvents() { const btnOpenCreateUser = document.getElementById('btn-open-create-user'); if (btnOpenCreateUser) { btnOpenCreateUser.onclick = () => openCreateUserModal(); } document.querySelectorAll('.btn-edit-user').forEach(btn => { btn.addEventListener('click', () => { const id = btn.getAttribute('data-id'); openEditUserModal(id); }); }); document.querySelectorAll('.btn-delete-user').forEach(btn => { btn.addEventListener('click', () => { const id = btn.getAttribute('data-id'); const username = btn.getAttribute('data-username'); confirmDeleteUser(id, username); }); }); } function openCreateUserModal() { const form = document.getElementById('form-user'); const title = document.getElementById('modal-user-title'); const usernameInput = document.getElementById('user-username-input'); const passwordInput = document.getElementById('user-password-input'); const fullNameInput = document.getElementById('user-fullname-input'); const roleSelect = document.getElementById('user-role-select'); const userIdInput = document.getElementById('user-id-hidden'); if (title) title.textContent = 'Crear Nuevo Operador'; if (userIdInput) userIdInput.value = ''; if (usernameInput) { usernameInput.value = ''; usernameInput.disabled = false; } if (passwordInput) { passwordInput.value = ''; passwordInput.required = true; passwordInput.placeholder = 'Mínimo 8 caracteres'; } if (fullNameInput) fullNameInput.value = ''; if (roleSelect) roleSelect.value = 'operator'; openModal('modal-user'); } function openEditUserModal(userId) { const users = store.getState('users') || []; const u = users.find(x => x.id === userId); if (!u) return; const title = document.getElementById('modal-user-title'); const usernameInput = document.getElementById('user-username-input'); const passwordInput = document.getElementById('user-password-input'); const fullNameInput = document.getElementById('user-fullname-input'); const roleSelect = document.getElementById('user-role-select'); const userIdInput = document.getElementById('user-id-hidden'); if (title) title.textContent = `Editar Usuario: ${u.username}`; if (userIdInput) userIdInput.value = u.id; if (usernameInput) { usernameInput.value = u.username; usernameInput.disabled = true; // No modificar username } if (passwordInput) { passwordInput.value = ''; passwordInput.required = false; passwordInput.placeholder = 'Dejar en blanco para no cambiarla'; } if (fullNameInput) fullNameInput.value = u.fullName || ''; if (roleSelect) roleSelect.value = u.role || 'operator'; openModal('modal-user'); } // Envío del Formulario de Usuario const formUser = document.getElementById('form-user'); if (formUser) { formUser.addEventListener('submit', async (e) => { e.preventDefault(); const userId = document.getElementById('user-id-hidden')?.value; const username = document.getElementById('user-username-input')?.value.trim(); const fullName = document.getElementById('user-fullname-input')?.value.trim(); const password = document.getElementById('user-password-input')?.value; const role = document.getElementById('user-role-select')?.value; const btnSubmit = document.getElementById('btn-submit-user'); btnSubmit.disabled = true; try { if (!userId) { // Crear const userVal = validateUsername(username); if (!userVal.valid) throw new Error(userVal.error); const passVal = validatePassword(password); if (!passVal.valid) throw new Error(passVal.error); await api.createUser({ username, password, fullName, role }); toast.success('Usuario Creado', `El operador '${username}' ha sido registrado.`); } else { // Editar const updateData = { fullName, role }; if (password) { const passVal = validatePassword(password); if (!passVal.valid) throw new Error(passVal.error); updateData.password = password; } await api.updateUser(userId, updateData); toast.success('Usuario Actualizado', 'Los datos del usuario han sido actualizados.'); } closeAllModals(); loadUsers(); } catch (err) { toast.error('Error al procesar usuario', err.detail || err.message); } finally { btnSubmit.disabled = false; } }); } async function confirmDeleteUser(id, username) { if (!confirm(`¿Está seguro de que desea eliminar la cuenta de usuario '${username}'? Esta acción no se puede deshacer.`)) { return; } try { await api.deleteUser(id); toast.success('Usuario Eliminado', `La cuenta '${username}' fue eliminada.`); loadUsers(); } catch (err) { toast.error('Error al eliminar usuario', err.detail || err.message); } } /* ========================================================================== Pestaña 4: Documentación Técnica (/docs) ========================================================================== */ async function loadDocs() { const sidebarNav = document.getElementById('docs-sidebar-nav'); const contentViewer = document.getElementById('docs-content-viewer'); try { const docs = await api.getDocs(); store.setState({ docs }); renderDocsSidebar(docs); // Cargar primer documento por defecto si no hay seleccionado if (docs.length > 0 && !store.getState('selectedDoc')) { loadDocContent(docs[0].id); } } catch (err) { console.error('Error al cargar índice de documentos:', err); } } function renderDocsSidebar(docs) { const sidebarNav = document.getElementById('docs-sidebar-nav'); if (!sidebarNav) return; // Agrupar por categoría const grouped = {}; docs.forEach(doc => { const cat = doc.category || 'general'; if (!grouped[cat]) grouped[cat] = []; grouped[cat].push(doc); }); const categoryTitles = { '01-requirements': '1. Requisitos del Sistema (SRS)', '02-architecture': '2. Arquitectura & Diseño (SDD)', '03-api': '3. Especificación API REST', '04-security': '4. Modelo de Seguridad', '05-deployment': '5. Guía de Despliegue VPS', '06-user-guides': '6. Manual de Administración', 'general': 'Documentos Generales' }; let html = ''; for (const [catKey, items] of Object.entries(grouped)) { const title = categoryTitles[catKey] || catKey.replace(/^\d+-/, '').toUpperCase(); html += `
${escapeHtml(title)}
`; } sidebarNav.innerHTML = html; // Vincular eventos sidebarNav.querySelectorAll('.docs-nav-item-btn').forEach(btn => { btn.addEventListener('click', () => { const docId = btn.getAttribute('data-doc-id'); loadDocContent(docId); }); }); } async function loadDocContent(docId) { const contentViewer = document.getElementById('docs-content-viewer'); if (!contentViewer) return; // Actualizar clase activa en sidebar document.querySelectorAll('.docs-nav-item-btn').forEach(b => { b.classList.toggle('active', b.getAttribute('data-doc-id') === docId); }); contentViewer.innerHTML = `
Cargando documento...
`; try { const docData = await api.getDoc(docId); store.setState({ selectedDoc: docData }); const htmlContent = renderMarkdown(docData.content); contentViewer.innerHTML = `
Doc ID: ${escapeHtml(docData.id)}

${escapeHtml(docData.title)}

Actualizado: ${new Date(docData.lastModified).toLocaleDateString()}
${htmlContent}
`; // Vincular botones para copiar código en los bloques renderizados contentViewer.querySelectorAll('.btn-copy-code').forEach(btn => { btn.addEventListener('click', () => { const rawCode = decodeURIComponent(btn.getAttribute('data-code')); navigator.clipboard.writeText(rawCode).then(() => { const original = btn.innerHTML; btn.innerHTML = `¡Copiado!`; setTimeout(() => { btn.innerHTML = original; }, 1500); }); }); }); } catch (err) { contentViewer.innerHTML = `
Error al cargar documento: ${escapeHtml(err.message)}
`; } } /* ========================================================================== Utilidades Globales de Modales y Helpers ========================================================================== */ function openModal(modalId) { const modal = document.getElementById(modalId); if (modal) { modal.classList.add('active'); document.body.style.overflow = 'hidden'; } } function closeAllModals() { document.querySelectorAll('.modal-backdrop').forEach(m => { m.classList.remove('active'); }); document.body.style.overflow = ''; } function escapeHtml(text) { if (text === null || text === undefined) return ''; const div = document.createElement('div'); div.textContent = String(text); return div.innerHTML; }