a2host/public/js/app.js

1436 lines
50 KiB
JavaScript

/**
* 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();
// 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 === 'subdomains') loadSubdomains();
if (tabName === 'folders') loadFolders();
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 => `
<tr>
<td>
<a href="https://${item.fullDomain || `${item.name}.${BASE_DOMAIN}`}" target="_blank" rel="noopener noreferrer" class="subdomain-link">
<span>${escapeHtml(item.name)}</span>
<svg class="external-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4h-4m4 0v4m0-4L7 9m-1-4H3a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1v-3"></path>
</svg>
</a>
<div style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(item.fullDomain || `${item.name}.${BASE_DOMAIN}`)}</div>
</td>
<td>
${item.type === 'proxy'
? `<span class="badge badge-mode-proxy">Modo B • Proxy</span>`
: `<span class="badge badge-mode-static">Modo A • Estático</span>`
}
</td>
<td>
${item.type === 'proxy'
? `<span class="badge-port">:${item.port || '—'}</span> <span style="font-size: 0.78rem; color: var(--text-muted);">${escapeHtml(item.target || '')}</span>`
: `<span style="font-size: 0.8rem; color: var(--text-secondary); font-family: ui-monospace, monospace;">${escapeHtml(item.target || `/var/www/${item.name}`)}</span>`
}
</td>
<td>
<label class="switch-label">
<input
type="checkbox"
class="switch-input subdomain-toggle-switch"
data-name="${escapeHtml(item.name)}"
${item.enabled ? 'checked' : ''}
${item.protected ? 'disabled' : ''}
aria-label="Alternar estado de ${escapeHtml(item.name)}"
>
<span class="switch-slider"></span>
<span style="font-size: 0.75rem; color: ${item.enabled ? 'var(--accent-lime)' : 'var(--text-muted)'};">
${item.enabled ? 'Activo' : 'Pausado'}
</span>
</label>
</td>
<td>
${item.protected
? `<span class="badge badge-protected" title="Archivo de configuración protegido del sistema">Protegido</span>`
: `<span class="badge badge-status-active">Normal</span>`
}
</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.4rem;">
<button
type="button"
class="btn-icon btn-edit-subdomain"
data-name="${escapeHtml(item.name)}"
${item.protected ? 'disabled title="Sitio protegido no editable"' : 'title="Editar subdominio"'}
>
<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="M11 2a1.5 1.5 0 0 1 2 2L4.5 12.5 2 13l.5-2.5L11 2z"></path>
</svg>
</button>
<button
type="button"
class="btn-icon btn-icon-danger btn-delete-subdomain"
data-name="${escapeHtml(item.name)}"
data-domain="${escapeHtml(item.fullDomain || item.name)}"
data-type="${item.type}"
${item.protected ? 'disabled title="Sitio protegido no eliminable"' : 'title="Eliminar subdominio"'}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
</button>
</div>
</td>
</tr>
`).join('');
}
// Renderizar Tarjetas Mobile
if (mobileContainer) {
mobileContainer.innerHTML = filtered.map(item => `
<div class="mobile-card">
<div class="mobile-card-header">
<a href="https://${item.fullDomain || `${item.name}.${BASE_DOMAIN}`}" target="_blank" rel="noopener noreferrer" class="subdomain-link">
<span>${escapeHtml(item.name)}</span>
<svg class="external-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4h-4m4 0v4m0-4L7 9m-1-4H3a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1v-3"></path>
</svg>
</a>
<label class="switch-label">
<input
type="checkbox"
class="switch-input subdomain-toggle-switch"
data-name="${escapeHtml(item.name)}"
${item.enabled ? 'checked' : ''}
${item.protected ? 'disabled' : ''}
aria-label="Alternar estado de ${escapeHtml(item.name)}"
>
<span class="switch-slider"></span>
</label>
</div>
<div class="mobile-card-body">
<div class="mobile-card-row">
<span>Tipo / Modo:</span>
${item.type === 'proxy'
? `<span class="badge badge-mode-proxy">Modo B • Proxy :${item.port}</span>`
: `<span class="badge badge-mode-static">Modo A • Estático</span>`
}
</div>
<div class="mobile-card-row">
<span>Destino:</span>
<span style="font-family: ui-monospace, monospace; font-size: 0.78rem;">${escapeHtml(item.target || '')}</span>
</div>
<div class="mobile-card-row">
<span>Seguridad:</span>
${item.protected
? `<span class="badge badge-protected">Protegido</span>`
: `<span class="badge badge-status-active">Normal</span>`
}
</div>
</div>
<div class="mobile-card-actions">
<button
type="button"
class="btn btn-secondary btn-edit-subdomain"
data-name="${escapeHtml(item.name)}"
style="min-height: 38px; padding: 0.4rem 0.85rem;"
${item.protected ? 'disabled' : ''}
>
Editar
</button>
<button
type="button"
class="btn btn-danger btn-delete-subdomain"
data-name="${escapeHtml(item.name)}"
data-domain="${escapeHtml(item.fullDomain || item.name)}"
data-type="${item.type}"
style="min-height: 38px; padding: 0.4rem 0.85rem;"
${item.protected ? 'disabled' : ''}
>
Eliminar
</button>
</div>
</div>
`).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
========================================================================== */
let currentSubdomainModalMode = 'create'; // 'create' | 'edit'
let selectedSubdomainType = 'static'; // 'static' | 'proxy'
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();
});
modeBtnProxy.addEventListener('click', () => {
selectedSubdomainType = 'proxy';
modeBtnProxy.classList.add('active');
modeBtnStatic.classList.remove('active');
if (proxyPortGroup) proxyPortGroup.style.display = 'flex';
validateSubdomainFormLive();
});
}
// Validación en vivo del nombre y preview de URL
const inputName = document.getElementById('subdomain-name-input');
const inputPort = document.getElementById('subdomain-port-input');
if (inputName) {
inputName.addEventListener('input', () => {
validateSubdomainFormLive();
});
}
if (inputPort) {
inputPort.addEventListener('input', () => {
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';
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');
if (title) title.textContent = 'Crear Nuevo 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';
// Ocultar terminal de rollback previo
if (terminal) terminal.classList.remove('active');
validateSubdomainFormLive();
openModal('modal-subdomain');
inputName?.focus();
}
function openEditSubdomainModal(name) {
const subdomains = store.getState('subdomains') || [];
const item = subdomains.find(s => s.name === name);
if (!item) return;
currentSubdomainModalMode = 'edit';
selectedSubdomainType = item.type || 'static';
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');
if (title) title.textContent = `Editar Subdominio: ${name}`;
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 (terminal) terminal.classList.remove('active');
validateSubdomainFormLive();
openModal('modal-subdomain');
}
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 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');
}
if (btnSubmit) {
btnSubmit.disabled = !(isNameValid && isPortValid);
}
return isNameValid && isPortValid;
}
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
});
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 = `<tr><td colspan="7" style="text-align: center; color: var(--text-muted); padding: 2rem;">No se encontraron carpetas en /var/www</td></tr>`;
if (mobileContainer) mobileContainer.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 2rem;">No se encontraron carpetas en /var/www</div>`;
return;
}
// Renderizar Desktop
if (tableBody) {
tableBody.innerHTML = folders.map(f => {
const isSGID = f.isSGID || f.permissions === '2775';
return `
<tr>
<td>
<div style="font-weight: 600; color: var(--text-primary);">${escapeHtml(f.folderName)}</div>
<div style="font-size: 0.74rem; color: var(--text-muted); font-family: ui-monospace, monospace;">${escapeHtml(f.path)}</div>
</td>
<td>${f.sizeFormatted || '—'}</td>
<td>${f.fileCount ?? 0} ficheros</td>
<td><code style="font-size: 0.78rem;">${escapeHtml(f.owner)}:${escapeHtml(f.group)}</code></td>
<td><code style="font-size: 0.78rem;">${escapeHtml(f.permissions)}</code></td>
<td>
${isSGID
? `<span class="badge badge-sgid-ok" title="Bit SGID 2775 activo: hereda grupo www-data">SGID 2775 OK</span>`
: `<span class="badge badge-sgid-warn" title="Alerta: se recomienda chmod 2775">Sin SGID 2775</span>`
}
</td>
<td style="text-align: right;">
<button
type="button"
class="btn btn-secondary btn-inspect-folder"
data-name="${escapeHtml(f.folderName)}"
style="min-height: 34px; padding: 0.35rem 0.75rem; font-size: 0.8rem;"
>
Archivos
</button>
</td>
</tr>
`;
}).join('');
}
// Renderizar Mobile
if (mobileContainer) {
mobileContainer.innerHTML = folders.map(f => {
const isSGID = f.isSGID || f.permissions === '2775';
return `
<div class="mobile-card">
<div class="mobile-card-header">
<div>
<div style="font-weight: 600;">${escapeHtml(f.folderName)}</div>
<div style="font-size: 0.72rem; color: var(--text-muted);">${escapeHtml(f.path)}</div>
</div>
${isSGID
? `<span class="badge badge-sgid-ok">SGID 2775</span>`
: `<span class="badge badge-sgid-warn">Sin SGID</span>`
}
</div>
<div class="mobile-card-body">
<div class="mobile-card-row">
<span>Tamaño:</span>
<strong>${f.sizeFormatted || '—'}</strong>
</div>
<div class="mobile-card-row">
<span>Archivos:</span>
<span>${f.fileCount ?? 0} elementos</span>
</div>
<div class="mobile-card-row">
<span>Permisos:</span>
<code>${escapeHtml(f.owner)}:${escapeHtml(f.group)} (${f.permissions})</code>
</div>
</div>
<div class="mobile-card-actions">
<button
type="button"
class="btn btn-secondary btn-inspect-folder"
data-name="${escapeHtml(f.folderName)}"
style="width: 100%; min-height: 38px;"
>
Inspeccionar Archivos
</button>
</div>
</div>
`;
}).join('');
}
// Eventos de inspección de archivos
document.querySelectorAll('.btn-inspect-folder').forEach(btn => {
btn.addEventListener('click', () => {
const folderName = btn.getAttribute('data-name');
openFolderFilesModal(folderName);
});
});
const btnRefresh = document.getElementById('btn-refresh-folders');
if (btnRefresh) {
btnRefresh.onclick = () => {
loadFolders();
toast.info('Actualizando carpetas', 'Escaneando /var/www...');
};
}
}
async function openFolderFilesModal(folderName) {
const modal = document.getElementById('modal-folder-files');
const title = document.getElementById('folder-files-modal-title');
const container = document.getElementById('folder-files-list-container');
if (title) title.textContent = `/var/www/${folderName}`;
if (container) {
container.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 2rem;">Cargando lista de archivos...</div>`;
}
openModal('modal-folder-files');
try {
const res = await api.getFolderFiles(folderName);
const files = res.files || [];
if (files.length === 0) {
container.innerHTML = `<div style="text-align: center; color: var(--text-muted); padding: 2rem;">La carpeta está vacía.</div>`;
return;
}
container.innerHTML = `
<table class="data-table">
<thead>
<tr>
<th>Nombre</th>
<th>Tipo</th>
<th>Tamaño</th>
<th>Permisos</th>
</tr>
</thead>
<tbody>
${files.map(file => `
<tr>
<td>
<span style="font-weight: 500;">${escapeHtml(file.name)}</span>
</td>
<td><span style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(file.type || 'file')}</span></td>
<td>${file.sizeFormatted || '—'}</td>
<td><code>${escapeHtml(file.permissions || '—')}</code></td>
</tr>
`).join('')}
</tbody>
</table>
`;
} catch (err) {
if (container) {
container.innerHTML = `<div style="color: var(--color-danger); padding: 1.5rem; text-align: center;">Error al leer carpeta: ${escapeHtml(err.message)}</div>`;
}
}
}
/* ==========================================================================
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;
return `
<tr>
<td>
<div style="font-weight: 600;">${escapeHtml(u.fullName || u.username)}</div>
<div style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(u.username)}</div>
</td>
<td>
<span class="user-role-tag role-${u.role}">${escapeHtml(u.role)}</span>
</td>
<td>
<span class="badge ${u.active ? 'badge-status-active' : 'badge-status-disabled'}">
${u.active ? 'Activo' : 'Inactivo'}
</span>
</td>
<td style="font-size: 0.78rem; color: var(--text-muted);">
${u.lastLogin ? new Date(u.lastLogin).toLocaleString() : 'Nunca'}
</td>
<td style="text-align: right;">
<div style="display: inline-flex; gap: 0.4rem;">
<button
type="button"
class="btn-icon btn-edit-user"
data-id="${escapeHtml(u.id)}"
title="Editar Usuario"
>
<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="M11 2a1.5 1.5 0 0 1 2 2L4.5 12.5 2 13l.5-2.5L11 2z"></path>
</svg>
</button>
<button
type="button"
class="btn-icon btn-icon-danger btn-delete-user"
data-id="${escapeHtml(u.id)}"
data-username="${escapeHtml(u.username)}"
${isSelf ? 'disabled title="No puedes eliminar tu propia cuenta activa"' : 'title="Eliminar Usuario"'}
>
<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 4h10M6 4V2.5A1.5 1.5 0 0 1 7.5 1h1A1.5 1.5 0 0 1 10 2.5V4M5 4v9a1.5 1.5 0 0 0 1.5 1.5h3A1.5 1.5 0 0 0 11 13V4"></path>
</svg>
</button>
</div>
</td>
</tr>
`;
}).join('');
}
// Tarjetas Mobile
if (mobileContainer) {
mobileContainer.innerHTML = users.map(u => {
const isSelf = currentUser && currentUser.id === u.id;
return `
<div class="mobile-card">
<div class="mobile-card-header">
<div>
<div style="font-weight: 600;">${escapeHtml(u.fullName || u.username)}</div>
<div style="font-size: 0.75rem; color: var(--text-muted);">${escapeHtml(u.username)}</div>
</div>
<span class="user-role-tag role-${u.role}">${escapeHtml(u.role)}</span>
</div>
<div class="mobile-card-actions">
<button
type="button"
class="btn btn-secondary btn-edit-user"
data-id="${escapeHtml(u.id)}"
style="padding: 0.4rem 0.85rem;"
>
Editar
</button>
<button
type="button"
class="btn btn-danger btn-delete-user"
data-id="${escapeHtml(u.id)}"
data-username="${escapeHtml(u.username)}"
${isSelf ? 'disabled' : ''}
style="padding: 0.4rem 0.85rem;"
>
Eliminar
</button>
</div>
</div>
`;
}).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 += `
<div style="margin-bottom: 0.85rem;">
<div class="docs-category-title">${escapeHtml(title)}</div>
<ul class="docs-nav-list">
${items.map(item => `
<li>
<button
type="button"
class="docs-nav-item-btn"
data-doc-id="${escapeHtml(item.id)}"
>
<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M3 2.5A1.5 1.5 0 0 1 4.5 1h5l4 4v8.5a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 13.5v-11z"></path>
</svg>
<span class="truncate">${escapeHtml(item.title || item.id)}</span>
</button>
</li>
`).join('')}
</ul>
</div>
`;
}
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 = `<div style="text-align: center; color: var(--text-muted); padding: 3rem;">Cargando documento...</div>`;
try {
const docData = await api.getDoc(docId);
store.setState({ selectedDoc: docData });
const htmlContent = renderMarkdown(docData.content);
contentViewer.innerHTML = `
<div class="docs-header-bar">
<div>
<span class="badge badge-mode-static" style="margin-bottom: 0.4rem;">Doc ID: ${escapeHtml(docData.id)}</span>
<h2 style="font-size: 1.4rem; font-weight: 700;">${escapeHtml(docData.title)}</h2>
</div>
<div style="font-size: 0.76rem; color: var(--text-muted);">
Actualizado: ${new Date(docData.lastModified).toLocaleDateString()}
</div>
</div>
<div class="docs-rendered-body">
${htmlContent}
</div>
`;
// 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 = `<span>¡Copiado!</span>`;
setTimeout(() => {
btn.innerHTML = original;
}, 1500);
});
});
});
} catch (err) {
contentViewer.innerHTML = `<div style="color: var(--color-danger); padding: 2rem;">Error al cargar documento: ${escapeHtml(err.message)}</div>`;
}
}
/* ==========================================================================
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;
}