diff --git a/public/css/components.css b/public/css/components.css index 4953c91..17b66b1 100644 --- a/public/css/components.css +++ b/public/css/components.css @@ -2119,3 +2119,878 @@ border-radius: var(--radius-sm); box-shadow: 0 0 10px rgba(168, 85, 247, 0.2); } + +/* ========================================================================== + Módulo 1: Proyectos Web (/var/www/) + ========================================================================== */ + +.projects-cards-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(340px, 1fr)); + gap: 1.25rem; + margin-top: 1rem; +} + +@media (max-width: 640px) { + .projects-cards-grid { + grid-template-columns: 1fr; + } +} + +.project-card { + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 1.25rem; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 1rem; + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + box-shadow: var(--shadow-sm); + transition: all var(--transition-base); + position: relative; + overflow: hidden; +} + +.project-card::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + height: 2px; + background: linear-gradient(90deg, transparent, var(--border-highlight, rgba(16, 185, 129, 0.3)), transparent); + opacity: 0.6; +} + +.project-card:hover { + transform: translateY(-2px); + border-color: var(--border-highlight, rgba(16, 185, 129, 0.3)); + box-shadow: var(--shadow-md), 0 0 20px var(--accent-glow, rgba(16, 185, 129, 0.1)); +} + +.project-card-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 0.75rem; +} + +.project-title-group { + display: flex; + align-items: center; + gap: 0.65rem; +} + +.project-icon-badge { + width: 36px; + height: 36px; + border-radius: var(--radius-md); + display: flex; + align-items: center; + justify-content: center; + background: rgba(163, 230, 53, 0.1); + color: var(--accent-lime); + border: 1px solid rgba(163, 230, 53, 0.2); + flex-shrink: 0; +} + +.project-name { + font-size: 1.1rem; + font-weight: 700; + color: var(--text-primary); + line-height: 1.2; +} + +.project-type-tag { + display: inline-flex; + align-items: center; + padding: 0.2rem 0.55rem; + font-size: 0.72rem; + font-weight: 600; + border-radius: var(--radius-sm); + text-transform: uppercase; + letter-spacing: 0.03em; +} + +.type-tag-static { + color: var(--accent-lime); + background: rgba(163, 230, 53, 0.12); + border: 1px solid rgba(163, 230, 53, 0.3); +} + +.type-tag-node { + color: #38bdf8; + background: rgba(56, 189, 248, 0.12); + border: 1px solid rgba(56, 189, 248, 0.3); +} + +.type-tag-python { + color: #fbbf24; + background: rgba(251, 191, 36, 0.12); + border: 1px solid rgba(251, 191, 36, 0.3); +} + +.type-tag-custom { + color: #c084fc; + background: rgba(192, 132, 252, 0.12); + border: 1px solid rgba(192, 132, 252, 0.3); +} + +.project-meta-box { + display: flex; + flex-direction: column; + gap: 0.4rem; + background: rgba(0, 0, 0, 0.25); + padding: 0.75rem 0.85rem; + border-radius: var(--radius-md); + border: 1px solid var(--border-subtle); + font-size: 0.82rem; +} + +.project-meta-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.project-meta-label { + color: var(--text-muted); + font-size: 0.76rem; +} + +.project-meta-value { + color: var(--text-secondary); + font-family: ui-monospace, monospace; +} + +/* Subdominios Vinculados */ +.project-subdomains-section { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.project-subdomains-title { + font-size: 0.76rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--text-muted); +} + +.project-subdomains-list { + display: flex; + flex-wrap: wrap; + gap: 0.45rem; +} + +.subdomain-chip { + display: inline-flex; + align-items: center; + gap: 0.35rem; + padding: 0.25rem 0.55rem; + background: var(--bg-surface-elevated); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-full); + font-size: 0.78rem; + color: var(--text-primary); + text-decoration: none; + transition: all var(--transition-fast); +} + +.subdomain-chip:hover { + border-color: var(--accent-lime); + background: var(--bg-surface-hover); +} + +.subdomain-chip-link { + color: var(--accent-primary, #10b981); + display: inline-flex; + align-items: center; + gap: 0.25rem; + text-decoration: none; + font-weight: 500; +} + +.subdomain-chip-link:hover { + text-decoration: underline; +} + +.subdomain-chip-remove { + background: transparent; + border: none; + color: var(--text-muted); + font-size: 0.95rem; + line-height: 1; + cursor: pointer; + padding: 0 0.15rem; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + transition: color var(--transition-fast); +} + +.subdomain-chip-remove:hover { + color: #f87171; +} + +.project-actions-bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.5rem; + padding-top: 0.75rem; + border-top: 1px solid var(--border-subtle); + flex-wrap: wrap; +} + +.project-actions-left { + display: flex; + align-items: center; + gap: 0.4rem; +} + +.project-actions-right { + display: flex; + align-items: center; + gap: 0.4rem; +} + +/* Selector Radial de Tipo de Proyecto en Modal */ +.project-type-selector-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 0.65rem; +} + +@media (max-width: 480px) { + .project-type-selector-grid { + grid-template-columns: 1fr; + } +} + +.project-type-option { + position: relative; + cursor: pointer; +} + +.project-type-option input[type="radio"] { + position: absolute; + opacity: 0; + width: 0; + height: 0; +} + +.project-type-box { + display: flex; + flex-direction: column; + gap: 0.2rem; + padding: 0.75rem; + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-md); + transition: all var(--transition-fast); +} + +.project-type-option input[type="radio"]:checked + .project-type-box { + border-color: var(--accent-lime); + background: rgba(163, 230, 53, 0.08); + box-shadow: 0 0 0 1px var(--accent-lime); +} + +/* ========================================================================== + Módulo 2: Gestión FTP & Carga Masiva (Bulk Upload) + ========================================================================== */ + +.ftp-connection-card { + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 1.5rem; + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + margin-bottom: 1.5rem; + box-shadow: var(--shadow-sm); +} + +.ftp-card-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1.25rem; + flex-wrap: wrap; +} + +.ftp-header-title-wrap { + display: flex; + align-items: center; + gap: 0.75rem; +} + +.ftp-title { + font-size: 1.15rem; + font-weight: 700; + color: var(--text-primary); +} + +.ftp-subtitle { + font-size: 0.82rem; + color: var(--text-secondary); +} + +.ftp-credentials-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + gap: 1rem; +} + +.ftp-credential-item { + background: rgba(0, 0, 0, 0.25); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-md); + padding: 0.85rem; + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.credential-label { + font-size: 0.74rem; + font-weight: 600; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.credential-val-wrap { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.4rem; +} + +.credential-value { + font-family: ui-monospace, monospace; + font-size: 0.92rem; + font-weight: 700; + color: var(--text-primary); +} + +.btn-copy-mini { + background: rgba(255, 255, 255, 0.06); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-sm); + color: var(--text-secondary); + padding: 0.25rem 0.4rem; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + transition: all var(--transition-fast); +} + +.btn-copy-mini:hover { + background: var(--bg-surface-hover); + color: var(--accent-lime); + border-color: var(--accent-lime); +} + +/* Bulk Upload */ +.bulk-upload-card { + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 1.5rem; + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + box-shadow: var(--shadow-sm); +} + +.bulk-upload-header { + margin-bottom: 1.25rem; +} + +.bulk-upload-title-wrap { + display: flex; + align-items: center; + gap: 0.75rem; +} + +.bulk-title { + font-size: 1.1rem; + font-weight: 700; + color: var(--text-primary); +} + +.bulk-desc { + font-size: 0.82rem; + color: var(--text-secondary); +} + +.bulk-upload-form { + display: flex; + flex-direction: column; + gap: 1.25rem; +} + +.bulk-form-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1rem; +} + +@media (max-width: 640px) { + .bulk-form-grid { + grid-template-columns: 1fr; + } +} + +.ftp-drop-zone { + border: 2px dashed rgba(255, 255, 255, 0.15); + border-radius: var(--radius-lg); + padding: 2.5rem 1.5rem; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.65rem; + cursor: pointer; + background: rgba(0, 0, 0, 0.18); + transition: all var(--transition-base); + text-align: center; +} + +.ftp-drop-zone:hover, +.ftp-drop-zone.dragover { + border-color: var(--accent-lime); + background: rgba(163, 230, 53, 0.05); + box-shadow: 0 0 25px rgba(163, 230, 53, 0.15); +} + +.drop-zone-icon { + color: var(--accent-lime); + animation: pulse-subtle 2.5s infinite ease-in-out; +} + +.drop-zone-text { + font-size: 0.95rem; + color: var(--text-primary); +} + +.drop-zone-sub { + font-size: 0.78rem; + color: var(--text-muted); +} + +.selected-file-card { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0.75rem 1rem; + background: rgba(163, 230, 53, 0.08); + border: 1px solid rgba(163, 230, 53, 0.25); + border-radius: var(--radius-md); +} + +.selected-file-info { + display: flex; + align-items: center; + gap: 0.6rem; +} + +.selected-file-name { + font-weight: 600; + color: var(--text-primary); + font-size: 0.88rem; +} + +.selected-file-size { + color: var(--text-muted); + font-size: 0.78rem; +} + +.btn-remove-selection { + background: transparent; + border: none; + color: var(--text-muted); + font-size: 1.25rem; + cursor: pointer; + padding: 0 0.25rem; +} + +.btn-remove-selection:hover { + color: #f87171; +} + +.bulk-form-actions { + display: flex; + justify-content: flex-end; +} + +.extract-status-banner { + padding: 0.85rem 1rem; + border-radius: var(--radius-md); + font-size: 0.85rem; + line-height: 1.4; +} + +.extract-status-banner.success { + background: rgba(16, 185, 129, 0.12); + border: 1px solid rgba(16, 185, 129, 0.3); + color: var(--accent-emerald); +} + +.extract-status-banner.error { + background: rgba(239, 68, 68, 0.12); + border: 1px solid rgba(239, 68, 68, 0.3); + color: #f87171; +} + +/* ========================================================================== + Módulo 3: Terminal Remota con Bloqueo de Usuario VPS + ========================================================================== */ + +.terminal-lock-container { + display: flex; + align-items: center; + justify-content: center; + min-height: 420px; + padding: 2rem 1rem; +} + +.terminal-lock-card { + max-width: 440px; + width: 100%; + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-xl); + padding: 2rem 1.75rem; + text-align: center; + backdrop-filter: blur(20px); + -webkit-backdrop-filter: blur(20px); + box-shadow: var(--shadow-lg); + display: flex; + flex-direction: column; + align-items: center; +} + +.terminal-lock-icon-wrap { + width: 64px; + height: 64px; + border-radius: var(--radius-full); + background: rgba(245, 158, 11, 0.12); + color: var(--color-warning); + border: 1px solid rgba(245, 158, 11, 0.3); + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 1.25rem; + box-shadow: 0 0 20px rgba(245, 158, 11, 0.15); +} + +.terminal-lock-title { + font-size: 1.25rem; + font-weight: 700; + color: var(--text-primary); + margin-bottom: 0.5rem; +} + +.terminal-lock-desc { + font-size: 0.85rem; + color: var(--text-secondary); + line-height: 1.5; + margin-bottom: 1.5rem; +} + +.terminal-auth-form { + width: 100%; + display: flex; + flex-direction: column; + gap: 0.85rem; +} + +.terminal-auth-error { + padding: 0.65rem 0.85rem; + background: rgba(239, 68, 68, 0.12); + border: 1px solid rgba(239, 68, 68, 0.3); + border-radius: var(--radius-md); + color: #f87171; + font-size: 0.82rem; + text-align: left; +} + +/* ========================================================================== + Módulo 4: Configuraciones (Usuarios, Temas, Identidad) + ========================================================================== */ + +.settings-subnav-bar { + display: flex; + align-items: center; + gap: 0.5rem; + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 0.35rem; + margin-bottom: 1.5rem; + width: fit-content; + max-width: 100%; + overflow-x: auto; +} + +.settings-subnav-btn { + display: inline-flex; + align-items: center; + gap: 0.5rem; + padding: 0.55rem 1rem; + font-size: 0.86rem; + font-weight: 600; + border-radius: var(--radius-md); + border: 1px solid transparent; + background: transparent; + color: var(--text-secondary); + cursor: pointer; + white-space: nowrap; + transition: all var(--transition-fast); +} + +.settings-subnav-btn:hover { + color: var(--text-primary); + background: var(--bg-surface-hover); +} + +.settings-subnav-btn.active { + color: var(--accent-lime); + background: rgba(163, 230, 53, 0.1); + border-color: rgba(163, 230, 53, 0.25); +} + +.settings-section-header { + margin-bottom: 1.25rem; +} + +.settings-section-title { + font-size: 1.15rem; + font-weight: 700; + color: var(--text-primary); +} + +.settings-section-desc { + font-size: 0.84rem; + color: var(--text-secondary); +} + +/* Galería de Temas */ +.themes-gallery-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); + gap: 1.25rem; +} + +.theme-card { + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 1.25rem; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 1rem; + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + box-shadow: var(--shadow-sm); + transition: all var(--transition-base); + position: relative; + overflow: hidden; +} + +.theme-card:hover { + transform: translateY(-2px); + border-color: var(--border-medium); + box-shadow: var(--shadow-md); +} + +.theme-card.active { + border-color: var(--accent-lime); + box-shadow: var(--shadow-md), 0 0 20px var(--accent-lime-glow); +} + +.theme-card-top { + display: flex; + align-items: center; + justify-content: space-between; +} + +.theme-name { + font-size: 1.05rem; + font-weight: 700; + color: var(--text-primary); +} + +.theme-card-desc { + font-size: 0.8rem; + color: var(--text-secondary); + line-height: 1.4; +} + +.theme-swatches-row { + display: flex; + align-items: center; + gap: 0.4rem; + margin-top: 0.35rem; +} + +.theme-swatch { + width: 22px; + height: 22px; + border-radius: var(--radius-full); + border: 1px solid rgba(255, 255, 255, 0.2); + box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); +} + +.theme-card-footer { + display: flex; + align-items: center; + justify-content: space-between; + padding-top: 0.75rem; + border-top: 1px solid var(--border-subtle); +} + +/* Editor JSON de Tema */ +.theme-json-editor-card { + background: var(--bg-surface); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 1.25rem; + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + box-shadow: var(--shadow-sm); +} + +.theme-editor-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + margin-bottom: 1rem; + flex-wrap: wrap; +} + +.theme-editor-title-wrap { + display: flex; + align-items: center; + gap: 0.65rem; +} + +.theme-editor-title { + font-size: 0.98rem; + font-weight: 700; + color: var(--text-primary); +} + +.theme-editor-sub { + font-size: 0.76rem; + color: var(--text-muted); +} + +.theme-editor-actions { + display: flex; + align-items: center; + gap: 0.5rem; + flex-wrap: wrap; +} + +.theme-json-textarea { + width: 100%; + background: #050805; + color: #a3e635; + border: 1px solid var(--border-subtle); + border-radius: var(--radius-md); + padding: 1rem; + font-family: ui-monospace, 'Cascadia Code', monospace; + font-size: 0.85rem; + line-height: 1.5; + resize: vertical; +} + +.theme-json-textarea:focus { + outline: none; + border-color: var(--accent-lime); + box-shadow: 0 0 0 2px var(--accent-lime-glow); +} + +/* Formulario de Identidad */ +.identity-form-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 1.15rem; +} + +@media (max-width: 640px) { + .identity-form-grid { + grid-template-columns: 1fr; + } +} + +.color-picker-group { + display: flex; + align-items: center; + gap: 0.65rem; +} + +.color-picker-native { + width: 42px; + height: 40px; + border-radius: var(--radius-md); + border: 1px solid var(--border-subtle); + background: transparent; + cursor: pointer; + padding: 0; +} + +/* Footer de la Aplicación */ +.app-footer { + margin-top: 3rem; + padding: 1.5rem 1rem; + border-top: 1px solid var(--border-subtle); + color: var(--text-muted); + font-size: 0.82rem; + position: relative; + z-index: 1; +} + +.footer-inner { + max-width: 1320px; + margin: 0 auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; +} + +.footer-links { + display: flex; + align-items: center; + gap: 0.65rem; +} + +.footer-links a { + color: var(--text-secondary); + text-decoration: none; + transition: color var(--transition-fast); +} + +.footer-links a:hover { + color: var(--accent-lime); +} + +.footer-slogan { + color: var(--text-muted); +} + diff --git a/public/index.html b/public/index.html index 4614c0e..2107166 100644 --- a/public/index.html +++ b/public/index.html @@ -108,19 +108,36 @@ - Subdominios + 🌐 Subdominios 0 +
  • + +
  • +
  • + +
  • -
  • -
  • -
  • @@ -152,7 +161,16 @@ - Documentación Técnica (/docs) + 📚 Docs + +
  • +
  • +
  • @@ -248,6 +266,69 @@ + +
    +
    +
    +
    + + + + + +
    + + +
    + +
    + + + +
    +
    + + +
    + +
    + + + +
    + @@ -295,86 +376,355 @@ + +
    + +
    +
    +
    + +
    +

    Credenciales de Conexión SFTP / FTP

    +

    Acceso directo al sistema de archivos del VPS para despliegue por FileZilla, Cyberduck o WinSCP.

    +
    +
    +
    + SFTP / SSH Activo +
    +
    + +
    +
    + Host / Servidor +
    + elingejose.com + +
    +
    + +
    + IP Pública del VPS +
    + 201.32.134.58 + +
    +
    + +
    + Puerto SFTP (Primario VPS) +
    + 5101 + (Estándar: 22 · FTP: 21) +
    +
    + +
    + Usuario del Sistema +
    + ggc + (Grupo: www-data) +
    +
    + +
    + Directorio Raíz Web +
    + /var/www +
    +
    + +
    + Permisos Heredados +
    + SGID 2775 (ggc:www-data) +
    +
    +
    +
    + + +
    +
    +
    + + + +
    +

    Carga Masiva de Proyectos (Bulk Upload & ZIP Extractor)

    +

    Sube un archivo comprimido .zip y el sistema lo extraerá en la carpeta del proyecto aplicando automáticamente los permisos UNIX SGID 2775.

    +
    +
    +
    + +
    +
    +
    + + +
    + +
    + + +
    +
    + + +
    + +
    + + + +
    +
    + Arrastra aquí tu archivo .zip o haz clic para explorarlo +
    + Descompresión automática con sobreescritura y permisos para Apache +
    + + + + +
    + +
    + + +
    +
    + + +
    +
    +
    +

    + + + + + Cuentas de Acceso FTP & SFTP +

    +
    +
    + +
    +
    + +
    +
    + + + + + + + + + + + + + + +
    Usuario FTPProyecto / Carpeta AsignadaPermisosEstadoFecha de AltaAcciones
    +
    +
    + +
    + +
    + + +
    +
    +
    -
    -
    -
    - Entorno Shell: - - ggc@vps-jose (~/var/www) - -
    - Sesión Activa -
    -
    - +
    +

    🔒 Autenticación de Sistema VPS

    +

    + Por motivos de seguridad, para interactuar con la terminal Bash del servidor debes autenticarte con tus credenciales de usuario del sistema operativo (Linux VPS). +

    + +
    +
    + + +
    + +
    + + +
    + + + + +
    - -
    - Comandos Rápidos: -
    - - - - - - - - -
    -
    - - -
    -
    -
    @@ -617,61 +967,7 @@ -
    -
    -
    - Gestión de Cuentas de Acceso al Panel a2host -
    -
    - -
    -
    - -
    -
    - - - - - - - - - - - - - -
    Nombre Completo / UsuarioRolEstadoÚltimo Inicio de SesiónAcciones
    -
    -
    - -
    - -
    - - - -
    - -
    @@ -693,7 +989,226 @@
    + + +
    + +
    + + + + + +
    + + +
    +
    +
    + Cuentas de Operadores y Administradores del Panel +
    +
    + +
    +
    + +
    +
    + + + + + + + + + + + + + +
    Nombre Completo / UsuarioRolEstadoÚltimo Inicio de SesiónAcciones
    +
    +
    + +
    + +
    + + +
    + + + + + + +
    + + + + + + + + + + + + + +
    diff --git a/public/js/api.js b/public/js/api.js index 82a56b3..bd4e2a6 100644 --- a/public/js/api.js +++ b/public/js/api.js @@ -38,9 +38,11 @@ class ApiClient { const url = `${this.baseUrl}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`; const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('a2host_token') : null; + const terminalToken = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('a2host_terminal_token') : null; const headers = { 'Accept': 'application/json, application/problem+json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}), + ...(terminalToken ? { 'x-terminal-token': terminalToken } : {}), ...(options.headers || {}) }; @@ -66,8 +68,13 @@ class ApiClient { ); } - // Si es 401 y no estamos en la página de login, redirigir - if (response.status === 401 && !window.location.pathname.endsWith('login.html')) { + // Si es 401 y no estamos en login ni es un endpoint de terminal/auth, redirigir + if ( + response.status === 401 && + !window.location.pathname.endsWith('login.html') && + !endpoint.includes('/terminal/') && + !endpoint.includes('/auth/login') + ) { window.location.href = '/login.html'; return; } @@ -212,11 +219,115 @@ class ApiClient { }); } + // --- Projects Endpoints --- + async getProjects() { + return this.request('/projects', { method: 'GET' }); + } + + async getProject(id) { + return this.request(`/projects/${encodeURIComponent(id)}`, { method: 'GET' }); + } + + async createProject(data) { + return this.request('/projects', { + method: 'POST', + body: data + }); + } + + async updateProject(id, data) { + return this.request(`/projects/${encodeURIComponent(id)}`, { + method: 'PUT', + body: data + }); + } + + async addProjectSubdomain(id, subdomain) { + return this.request(`/projects/${encodeURIComponent(id)}/subdomains`, { + method: 'POST', + body: { subdomain } + }); + } + + async removeProjectSubdomain(id, subdomain) { + return this.request(`/projects/${encodeURIComponent(id)}/subdomains/${encodeURIComponent(subdomain)}`, { + method: 'DELETE' + }); + } + + async deleteProject(id, deleteFiles = false) { + const query = deleteFiles ? '?deleteFiles=true' : ''; + return this.request(`/projects/${encodeURIComponent(id)}${query}`, { + method: 'DELETE', + body: { deleteFiles } + }); + } + + // --- FTP & Bulk Upload Endpoints --- + async getFtpInfo() { + return this.request('/ftp/info', { method: 'GET' }); + } + + async getFtpAccounts() { + return this.request('/ftp/accounts', { method: 'GET' }); + } + + async createFtpAccount(data) { + return this.request('/ftp/accounts', { + method: 'POST', + body: data + }); + } + + async updateFtpAccount(id, data) { + return this.request(`/ftp/accounts/${encodeURIComponent(id)}`, { + method: 'PUT', + body: data + }); + } + + async deleteFtpAccount(id) { + return this.request(`/ftp/accounts/${encodeURIComponent(id)}`, { + method: 'DELETE' + }); + } + + async extractZipToProject(project, relativePath, zipBase64) { + return this.request('/ftp/extract-zip', { + method: 'POST', + body: { project, relativePath, zipBase64 } + }); + } + // --- Terminal Endpoints --- async getTerminalInfo() { return this.request('/terminal/info', { method: 'GET' }); } + async vpsTerminalLogin(vpsUser, vpsPassword) { + const res = await this.request('/terminal/login', { + method: 'POST', + body: { vpsUser, vpsPassword } + }); + const data = res?.terminalToken ? res : (res?.data || res); + if (data && data.terminalToken && typeof sessionStorage !== 'undefined') { + sessionStorage.setItem('a2host_terminal_token', data.terminalToken); + sessionStorage.setItem('a2host_terminal_user', data.vpsUser); + } + return res; + } + + async vpsTerminalLogout() { + try { + await this.request('/terminal/logout', { method: 'POST' }); + } finally { + if (typeof sessionStorage !== 'undefined') { + sessionStorage.removeItem('a2host_terminal_token'); + sessionStorage.removeItem('a2host_terminal_user'); + } + } + } + async executeCommand(command, cwd) { return this.request('/terminal/execute', { method: 'POST', @@ -266,6 +377,51 @@ class ApiClient { async getDoc(docId) { return this.request(`/docs/${encodeURI(docId)}`, { method: 'GET' }); } + + // --- Settings & Themes Endpoints --- + async getIdentity() { + return this.request('/settings/identity', { method: 'GET' }); + } + + async updateIdentity(data) { + return this.request('/settings/identity', { + method: 'PUT', + body: data + }); + } + + async getThemes() { + return this.request('/settings/themes', { method: 'GET' }); + } + + async setActiveTheme(themeId) { + return this.request('/settings/themes/set', { + method: 'POST', + body: { themeId } + }); + } + + async saveCustomTheme(themeData) { + return this.request('/settings/themes/custom', { + method: 'POST', + body: themeData + }); + } + + async importThemeJson(themeJson) { + return this.request('/settings/themes/import', { + method: 'POST', + body: { themeJson } + }); + } + + async exportThemeJson() { + return this.request('/settings/themes/export', { method: 'GET' }); + } + + async resetTheme() { + return this.request('/settings/themes/reset', { method: 'POST' }); + } } export const api = new ApiClient(); diff --git a/public/js/app.js b/public/js/app.js index a48e6f5..19662f9 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -38,6 +38,9 @@ async function initApp() { return; } + // 1b. Cargar Identidad y Tema Temprano + await loadIdentityAndThemes(); + // 2. Configurar Navegación por Pestañas setupTabs(); @@ -48,19 +51,20 @@ async function initApp() { // 4. Configurar Buscadores y Filtros setupFiltersAndSearch(); - // 5. Configurar Modales + // 5. Configurar Modales y Controladores de Módulos setupModals(); + setupProjects(); + setupFtp(); setupFileManager(); setupCodeEditor(); setupTerminal(); setupMonitor(); + setupSettings(); // 6. Cargar datos iniciales loadSubdomains(); + loadProjects(); loadFolders(); - if (store.getState('currentUser')?.role === 'admin') { - loadUsers(); - } loadDocs(); // 7. Configurar Botón de Logout @@ -209,11 +213,13 @@ function switchTab(tabName) { stopMonitorAutoRefresh(); } if (tabName === 'subdomains') loadSubdomains(); + if (tabName === 'projects') loadProjects(); if (tabName === 'folders') loadFolders(); + if (tabName === 'ftp') loadFtpData(); if (tabName === 'terminal') initTerminalTab(); if (tabName === 'monitor') initMonitorTab(); - if (tabName === 'users') loadUsers(); if (tabName === 'docs') loadDocs(); + if (tabName === 'settings') loadSettingsTab(); } /* ========================================================================== @@ -1702,6 +1708,64 @@ function setupTerminal() { const form = document.getElementById('terminal-command-form'); const input = document.getElementById('terminal-input'); const btnClear = document.getElementById('terminal-btn-clear'); + const loginForm = document.getElementById('form-terminal-login'); + const btnLogout = document.getElementById('btn-terminal-logout'); + + // Formulario de autenticación del sistema VPS + if (loginForm) { + loginForm.addEventListener('submit', async (e) => { + e.preventDefault(); + const userEl = document.getElementById('terminal-vps-user-input'); + const passEl = document.getElementById('terminal-vps-pass-input'); + const errEl = document.getElementById('terminal-login-error'); + + const vpsUser = userEl?.value.trim(); + const vpsPassword = passEl?.value; + + if (!vpsUser || !vpsPassword) { + if (errEl) { + errEl.textContent = 'Ingrese usuario y contraseña del VPS.'; + errEl.style.display = 'block'; + } + return; + } + + const btnSubmit = document.getElementById('btn-terminal-login'); + if (btnSubmit) btnSubmit.disabled = true; + + try { + const res = await api.vpsTerminalLogin(vpsUser, vpsPassword); + if (errEl) errEl.style.display = 'none'; + if (passEl) passEl.value = ''; + toast.success('Sesión iniciada', `Autenticado en el VPS como ${vpsUser}`); + await initTerminalTab(); + } catch (err) { + if (errEl) { + errEl.textContent = err.detail || err.message || 'Credenciales de usuario del VPS inválidas.'; + errEl.style.display = 'block'; + } + } finally { + if (btnSubmit) btnSubmit.disabled = false; + } + }); + } + + // Botón de Cerrar Sesión del VPS + if (btnLogout) { + btnLogout.addEventListener('click', async () => { + try { + await api.vpsTerminalLogout(); + toast.info('Sesión de terminal cerrada'); + } catch (err) { + console.warn('[Terminal] Error en logout:', err); + } finally { + const authCard = document.getElementById('terminal-auth-card'); + const activeView = document.getElementById('terminal-active-view'); + if (authCard) authCard.style.display = 'flex'; + if (activeView) activeView.style.display = 'none'; + } + }); + } if (form && input) { form.addEventListener('submit', async (e) => { @@ -1770,15 +1834,21 @@ function setupTerminal() { } async function initTerminalTab() { + const authCard = document.getElementById('terminal-auth-card'); + const activeView = document.getElementById('terminal-active-view'); const badgeEl = document.getElementById('terminal-env-badge'); const promptLabel = document.getElementById('terminal-prompt-label'); const topbarTitle = document.getElementById('terminal-topbar-title'); + const logoutLabel = document.getElementById('terminal-logout-label'); const input = document.getElementById('terminal-input'); try { const res = await api.getTerminalInfo(); const info = res.data || res; - if (info) { + if (info && info.authenticated) { + if (authCard) authCard.style.display = 'none'; + if (activeView) activeView.style.display = 'block'; + terminalUser = info.user || 'ggc'; terminalHost = info.hostname || 'vps-jose'; currentTerminalCwd = info.cwd || '/var/www'; @@ -1786,12 +1856,18 @@ async function initTerminalTab() { if (badgeEl) badgeEl.textContent = `${terminalUser}@${terminalHost} (${currentTerminalCwd})`; if (promptLabel) promptLabel.textContent = `${terminalUser}@vps:~$`; if (topbarTitle) topbarTitle.textContent = `bash — ${terminalUser}@${terminalHost}:${currentTerminalCwd}`; + if (logoutLabel) logoutLabel.textContent = `Cerrar Sesión (${terminalUser})`; + + input?.focus(); + } else { + if (authCard) authCard.style.display = 'flex'; + if (activeView) activeView.style.display = 'none'; } } catch (err) { console.warn('[Terminal] Error al obtener info:', err); + if (authCard) authCard.style.display = 'flex'; + if (activeView) activeView.style.display = 'none'; } - - input?.focus(); } async function executeTerminalCommand(cmd) { @@ -2187,13 +2263,13 @@ function renderUsers() { if (tableBody) { tableBody.innerHTML = users.map(u => { const isSelf = currentUser && currentUser.id === u.id; - const isImmutable = Boolean(u.isImmutable); + const isImmutable = Boolean(u.isImmutable || u.username === 'root'); return `
    ${escapeHtml(u.fullName || u.username)} - ${isImmutable ? `[SISTEMA / INMUTABLE]` : ''} + ${isImmutable ? `🛡️ SUPERADMIN / ROOT` : ''}
    ${escapeHtml(u.username)}
    @@ -2214,7 +2290,7 @@ function renderUsers() { type="button" class="btn-icon btn-edit-user" data-id="${escapeHtml(u.id)}" - ${isImmutable ? 'disabled title="El superadministrador del sistema es inmutable y no puede modificarse"' : 'title="Editar Usuario"'} + ${isImmutable ? 'disabled title="El superadministrador root es inmutable y no puede modificarse"' : 'title="Editar Usuario"'} > @@ -2226,7 +2302,7 @@ function renderUsers() { data-id="${escapeHtml(u.id)}" data-username="${escapeHtml(u.username)}" ${isImmutable - ? 'disabled title="El superadministrador del sistema es inmutable y no puede eliminarse"' + ? 'disabled title="El superadministrador root es inmutable y no puede eliminarse"' : (isSelf ? 'disabled title="No puedes eliminar tu propia cuenta activa"' : 'title="Eliminar Usuario"') } > @@ -2557,6 +2633,1181 @@ async function loadDocContent(docId) { } } +/* ========================================================================== + Temas e Identidad del Sistema (Carga Temprana & Dinámica) + ========================================================================== */ + +let currentThemesList = []; +let currentActiveTheme = null; +let currentIdentity = null; + +async function loadIdentityAndThemes() { + try { + const [identity, themesData] = await Promise.all([ + api.getIdentity().catch(err => { console.warn('[Identity]', err); return null; }), + api.getThemes().catch(err => { console.warn('[Themes]', err); return null; }) + ]); + + if (identity) { + currentIdentity = identity; + store.setState({ identity }); + applyIdentityUI(identity); + } + + if (themesData && themesData.themes) { + currentThemesList = themesData.themes; + currentActiveTheme = themesData.activeTheme; + store.setState({ + themes: themesData.themes, + activeThemeId: themesData.activeThemeId, + activeTheme: themesData.activeTheme + }); + if (themesData.activeTheme?.colors) { + applyThemeVariables(themesData.activeTheme.colors); + } + } + } catch (err) { + console.warn('[Identity & Themes] Error al cargar configuración visual:', err); + } +} + +function applyThemeVariables(colors) { + if (!colors || typeof colors !== 'object') return; + const root = document.documentElement; + for (const [key, value] of Object.entries(colors)) { + root.style.setProperty(key, value); + } + // Sincronizar variables estándar utilizadas por componentes + if (colors['--bg-app']) root.style.setProperty('--bg-base', colors['--bg-app']); + if (colors['--accent-primary']) root.style.setProperty('--accent-emerald', colors['--accent-primary']); + if (colors['--accent-lime']) root.style.setProperty('--accent-lime', colors['--accent-lime']); +} + +function applyIdentityUI(identity) { + if (!identity) return; + if (identity.appName && identity.panelTitle) { + document.title = `${identity.appName} — ${identity.panelTitle} | ${identity.baseDomain || BASE_DOMAIN}`; + } + const brandName = document.querySelector('.brand-name'); + if (brandName && identity.appName) brandName.textContent = identity.appName; + + const brandDomain = document.querySelector('.brand-subdomain'); + if (brandDomain && identity.baseDomain) brandDomain.textContent = identity.baseDomain; + + const footerText = document.getElementById('footer-text-display'); + if (footerText && identity.footerText) footerText.textContent = identity.footerText; + + const footerSlogan = document.getElementById('footer-slogan-display'); + if (footerSlogan && identity.slogan) footerSlogan.textContent = identity.slogan; + + const footerGit = document.getElementById('footer-git-link'); + if (footerGit && identity.gitUrl) { + footerGit.href = identity.gitUrl; + footerGit.textContent = `Repositorio Git (${identity.appName || 'a2host'})`; + } + + if (identity.primaryColor) { + document.documentElement.style.setProperty('--accent-emerald', identity.primaryColor); + document.documentElement.style.setProperty('--accent-primary', identity.primaryColor); + } +} + +/* ========================================================================== + Pestaña Proyectos (/var/www/) + ========================================================================== */ + +let currentEditProjectId = null; +let currentLinkProjectId = null; +let currentDeleteProjectId = null; + +function setupProjects() { + const searchInput = document.getElementById('search-projects'); + const typeFilter = document.getElementById('filter-project-type'); + const btnRefresh = document.getElementById('btn-refresh-projects'); + const btnOpenCreate = document.getElementById('btn-open-create-project'); + const formProject = document.getElementById('form-project'); + const formLinkSubdomain = document.getElementById('form-link-subdomain'); + const btnConfirmDeleteProject = document.getElementById('btn-confirm-delete-project'); + + if (searchInput) { + searchInput.addEventListener('input', (e) => { + const filter = store.getState('projectsFilter') || {}; + store.setState({ projectsFilter: { ...filter, search: e.target.value.trim() } }); + renderProjects(); + }); + } + + if (typeFilter) { + typeFilter.addEventListener('change', (e) => { + const filter = store.getState('projectsFilter') || {}; + store.setState({ projectsFilter: { ...filter, type: e.target.value } }); + renderProjects(); + }); + } + + if (btnRefresh) { + btnRefresh.addEventListener('click', loadProjects); + } + + if (btnOpenCreate) { + btnOpenCreate.addEventListener('click', openCreateProjectModal); + } + + // Radios de selección de tipo de proyecto en modal + document.querySelectorAll('input[name="project-type"]').forEach(radio => { + radio.addEventListener('change', (e) => { + const type = e.target.value; + const portGroup = document.getElementById('form-group-project-port'); + if (portGroup) { + portGroup.style.display = (type === 'node' || type === 'python' || type === 'custom') ? 'block' : 'none'; + } + updateDocRootPreview(); + }); + }); + + const projNameInput = document.getElementById('project-name-input'); + const projPublicFolderInput = document.getElementById('project-public-folder-input'); + + if (projNameInput) { + projNameInput.addEventListener('input', updateDocRootPreview); + } + if (projPublicFolderInput) { + projPublicFolderInput.addEventListener('input', updateDocRootPreview); + } + + // Submit Crear / Editar Proyecto + if (formProject) { + formProject.addEventListener('submit', handleSaveProject); + } + + // Modal Vincular Subdominio + const linkSubInput = document.getElementById('link-subdomain-name-input'); + if (linkSubInput) { + linkSubInput.addEventListener('input', (e) => { + const clean = e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''); + const preview = document.getElementById('link-subdomain-preview-url'); + if (preview) { + preview.textContent = clean ? `${clean}.${currentIdentity?.baseDomain || BASE_DOMAIN}` : `subdominio.${currentIdentity?.baseDomain || BASE_DOMAIN}`; + } + }); + } + + if (formLinkSubdomain) { + formLinkSubdomain.addEventListener('submit', handleSaveLinkSubdomain); + } + + if (btnConfirmDeleteProject) { + btnConfirmDeleteProject.addEventListener('click', handleConfirmDeleteProject); + } +} + +function updateDocRootPreview() { + const nameInput = document.getElementById('project-name-input'); + const folderInput = document.getElementById('project-public-folder-input'); + const preview = document.getElementById('preview-project-docroot'); + if (!preview) return; + + const name = nameInput?.value.trim() || 'mi-super-app'; + const folder = folderInput?.value.trim().replace(/^\/+/, ''); + preview.textContent = folder ? `/var/www/${name}/${folder}` : `/var/www/${name}`; +} + +async function loadProjects() { + store.setState({ projectsLoading: true }); + try { + const list = await api.getProjects(); + store.setState({ projects: list, projectsLoading: false }); + const badge = document.getElementById('projects-count-badge'); + if (badge) badge.textContent = list.length; + renderProjects(); + updateProjectSelects(list); + } catch (err) { + store.setState({ projectsLoading: false }); + toast.error('Error al cargar proyectos', err.message); + } +} + +function updateProjectSelects(projects) { + const bulkSelect = document.getElementById('ftp-bulk-project-select'); + const ftpAccSelect = document.getElementById('ftp-project-select'); + + if (bulkSelect) { + const curVal = bulkSelect.value; + bulkSelect.innerHTML = `` + + projects.map(p => ``).join(''); + if (curVal) bulkSelect.value = curVal; + } + + if (ftpAccSelect) { + const curVal = ftpAccSelect.value; + ftpAccSelect.innerHTML = `` + + projects.map(p => ``).join(''); + if (curVal) ftpAccSelect.value = curVal; + } +} + +function renderProjects() { + const projects = store.getState('projects') || []; + const filter = store.getState('projectsFilter') || {}; + const grid = document.getElementById('projects-grid'); + const emptyState = document.getElementById('projects-empty-state'); + if (!grid) return; + + const baseDom = currentIdentity?.baseDomain || BASE_DOMAIN; + + const filtered = projects.filter(p => { + if (filter.search) { + const q = filter.search.toLowerCase(); + const matchName = p.name.toLowerCase().includes(q); + const matchSubs = (p.subdomains || []).some(s => s.toLowerCase().includes(q)); + if (!matchName && !matchSubs) return false; + } + if (filter.type && filter.type !== 'all') { + if (p.type !== filter.type) return false; + } + return true; + }); + + if (filtered.length === 0) { + grid.innerHTML = ''; + if (emptyState) emptyState.style.display = 'flex'; + return; + } + + if (emptyState) emptyState.style.display = 'none'; + + grid.innerHTML = filtered.map(proj => { + const typeLabels = { + static: 'Estático / PHP', + node: 'Node.js', + python: 'Python', + custom: 'Proxy Inverso' + }; + const typeLabel = typeLabels[proj.type] || proj.type; + const typeTagClass = `type-tag-${proj.type || 'static'}`; + + const subdomainsList = proj.subdomains || []; + const publicFolderDisplay = proj.publicFolder ? `/${proj.publicFolder.replace(/^\/+/, '')}` : 'Raíz (/)'; + + return ` +
    +
    +
    +
    + +
    +

    ${escapeHtml(proj.name)}

    + + /var/www/${escapeHtml(proj.name)} + +
    +
    + ${escapeHtml(typeLabel)} +
    + +
    +
    + Carpeta Pública: + ${escapeHtml(publicFolderDisplay)} +
    + ${proj.port ? ` +
    + Puerto Proxy: + 127.0.0.1:${escapeHtml(proj.port)} +
    + ` : ''} +
    + Estado en Disco: + + ${proj.existsOnDisk ? 'Directorio OK' : 'No Encontrado'} + +
    +
    + +
    + Subdominios Vinculados (${subdomainsList.length}) +
    + ${subdomainsList.length > 0 ? subdomainsList.map(sub => ` + + + 🌐 ${escapeHtml(sub)}.${escapeHtml(baseDom)} + + + + + `).join('') : `Sin subdominios vinculados aún`} +
    +
    +
    + +
    +
    + + +
    +
    + + +
    +
    +
    + `; + }).join(''); + + // Vincular eventos delegados en tarjetas + grid.querySelectorAll('.btn-project-add-sub').forEach(b => { + b.addEventListener('click', () => { + const id = b.getAttribute('data-project-id'); + const name = b.getAttribute('data-project-name'); + openLinkSubdomainModal({ id, name }); + }); + }); + + grid.querySelectorAll('.btn-project-edit').forEach(b => { + b.addEventListener('click', () => { + const id = b.getAttribute('data-project-id'); + const proj = projects.find(p => p.id === id); + if (proj) openEditProjectModal(proj); + }); + }); + + grid.querySelectorAll('.btn-project-files').forEach(b => { + b.addEventListener('click', () => { + const name = b.getAttribute('data-project-name'); + if (name) openFileManager(name); + }); + }); + + grid.querySelectorAll('.btn-project-delete').forEach(b => { + b.addEventListener('click', () => { + const id = b.getAttribute('data-project-id'); + const name = b.getAttribute('data-project-name'); + openDeleteProjectModal({ id, name }); + }); + }); + + grid.querySelectorAll('.btn-remove-proj-sub').forEach(b => { + b.addEventListener('click', () => { + const id = b.getAttribute('data-project-id'); + const sub = b.getAttribute('data-subdomain'); + handleRemoveProjectSubdomain(id, sub); + }); + }); +} + +function openCreateProjectModal() { + currentEditProjectId = null; + const modal = document.getElementById('modal-project'); + const title = document.getElementById('modal-project-title'); + const idInput = document.getElementById('project-id-hidden'); + const nameInput = document.getElementById('project-name-input'); + const folderInput = document.getElementById('project-public-folder-input'); + const portInput = document.getElementById('project-port-input'); + const subInput = document.getElementById('project-subdomains-input'); + const subGroup = document.getElementById('form-group-project-subdomains'); + const portGroup = document.getElementById('form-group-project-port'); + + if (title) title.textContent = 'Crear Nuevo Proyecto'; + if (idInput) idInput.value = ''; + if (nameInput) { + nameInput.value = ''; + nameInput.disabled = false; + } + if (folderInput) folderInput.value = ''; + if (portInput) portInput.value = ''; + if (subInput) subInput.value = ''; + if (subGroup) subGroup.style.display = 'block'; + if (portGroup) portGroup.style.display = 'none'; + + const defaultRadio = document.querySelector('input[name="project-type"][value="static"]'); + if (defaultRadio) defaultRadio.checked = true; + + updateDocRootPreview(); + openModal('modal-project'); +} + +function openEditProjectModal(proj) { + currentEditProjectId = proj.id; + const modal = document.getElementById('modal-project'); + const title = document.getElementById('modal-project-title'); + const idInput = document.getElementById('project-id-hidden'); + const nameInput = document.getElementById('project-name-input'); + const folderInput = document.getElementById('project-public-folder-input'); + const portInput = document.getElementById('project-port-input'); + const subGroup = document.getElementById('form-group-project-subdomains'); + const portGroup = document.getElementById('form-group-project-port'); + + if (title) title.textContent = `Editar Proyecto: ${proj.name}`; + if (idInput) idInput.value = proj.id; + if (nameInput) { + nameInput.value = proj.name; + nameInput.disabled = true; // El nombre del directorio raíz es inmutable en edición + } + if (folderInput) folderInput.value = proj.publicFolder || ''; + if (portInput) portInput.value = proj.port || ''; + if (subGroup) subGroup.style.display = 'none'; + + const targetRadio = document.querySelector(`input[name="project-type"][value="${proj.type || 'static'}"]`); + if (targetRadio) targetRadio.checked = true; + + if (portGroup) { + portGroup.style.display = (proj.type === 'node' || proj.type === 'python' || proj.type === 'custom') ? 'block' : 'none'; + } + + updateDocRootPreview(); + openModal('modal-project'); +} + +async function handleSaveProject(e) { + e.preventDefault(); + const id = document.getElementById('project-id-hidden')?.value; + const typeRadio = document.querySelector('input[name="project-type"]:checked'); + const type = typeRadio ? typeRadio.value : 'static'; + const publicFolder = document.getElementById('project-public-folder-input')?.value.trim(); + const portVal = document.getElementById('project-port-input')?.value; + const port = portVal ? Number(portVal) : undefined; + + const btnSubmit = document.getElementById('btn-submit-project'); + if (btnSubmit) btnSubmit.disabled = true; + + try { + if (id) { + // Edición + await api.updateProject(id, { type, publicFolder, port }); + toast.success('Proyecto actualizado', 'Configuración guardada exitosamente.'); + } else { + // Creación + const name = document.getElementById('project-name-input')?.value.trim(); + if (!name) { + toast.error('Nombre requerido', 'Ingresa el nombre del proyecto.'); + return; + } + const subVal = document.getElementById('project-subdomains-input')?.value.trim(); + const subdomains = subVal ? [subVal] : []; + + await api.createProject({ name, type, publicFolder, port, subdomains }); + toast.success('Proyecto creado', `El proyecto '${name}' fue inicializado exitosamente.`); + } + + closeAllModals(); + await loadProjects(); + await loadSubdomains(); + await loadFolders(); + } catch (err) { + toast.error('Error al guardar proyecto', err.detail || err.message); + } finally { + if (btnSubmit) btnSubmit.disabled = false; + } +} + +function openLinkSubdomainModal(proj) { + currentLinkProjectId = proj.id; + const modal = document.getElementById('modal-link-subdomain'); + const title = document.getElementById('modal-link-subdomain-title'); + const idInput = document.getElementById('link-project-id-hidden'); + const nameInput = document.getElementById('link-subdomain-name-input'); + const preview = document.getElementById('link-subdomain-preview-url'); + + const baseDom = currentIdentity?.baseDomain || BASE_DOMAIN; + if (title) title.textContent = `Vincular Subdominio a: ${proj.name}`; + if (idInput) idInput.value = proj.id; + if (nameInput) nameInput.value = ''; + if (preview) preview.textContent = `subdominio.${baseDom}`; + + openModal('modal-link-subdomain'); +} + +async function handleSaveLinkSubdomain(e) { + e.preventDefault(); + const projectId = document.getElementById('link-project-id-hidden')?.value; + const subdomain = document.getElementById('link-subdomain-name-input')?.value.trim().toLowerCase(); + + if (!projectId || !subdomain) { + toast.error('Subdominio requerido', 'Ingresa el nombre del subdominio.'); + return; + } + + const btnSubmit = document.getElementById('btn-submit-link-subdomain'); + if (btnSubmit) btnSubmit.disabled = true; + + try { + await api.addProjectSubdomain(projectId, subdomain); + const baseDom = currentIdentity?.baseDomain || BASE_DOMAIN; + toast.success('Subdominio vinculado', `https://${subdomain}.${baseDom} activo en Apache.`); + closeAllModals(); + await loadProjects(); + await loadSubdomains(); + } catch (err) { + toast.error('Error al vincular subdominio', err.detail || err.message); + } finally { + if (btnSubmit) btnSubmit.disabled = false; + } +} + +async function handleRemoveProjectSubdomain(projectId, subdomain) { + if (!confirm(`¿Desvincular el subdominio '${subdomain}' de este proyecto? Se eliminará su VirtualHost de Apache.`)) { + return; + } + try { + await api.removeProjectSubdomain(projectId, subdomain); + toast.info('Subdominio desvinculado', subdomain); + await loadProjects(); + await loadSubdomains(); + } catch (err) { + toast.error('Error al desvincular subdominio', err.detail || err.message); + } +} + +function openDeleteProjectModal(proj) { + currentDeleteProjectId = proj.id; + const nameDisplay = document.getElementById('delete-project-name-display'); + const chk = document.getElementById('chk-delete-project-files'); + if (nameDisplay) nameDisplay.textContent = proj.name; + if (chk) chk.checked = false; + openModal('modal-delete-project'); +} + +async function handleConfirmDeleteProject() { + if (!currentDeleteProjectId) return; + const chk = document.getElementById('chk-delete-project-files'); + const deleteFiles = Boolean(chk?.checked); + + const btn = document.getElementById('btn-confirm-delete-project'); + if (btn) btn.disabled = true; + + try { + const res = await api.deleteProject(currentDeleteProjectId, deleteFiles); + toast.success('Proyecto eliminado', res?.message || 'VirtualHosts eliminados.'); + closeAllModals(); + await loadProjects(); + await loadSubdomains(); + await loadFolders(); + } catch (err) { + toast.error('Error al eliminar proyecto', err.detail || err.message); + } finally { + if (btn) btn.disabled = false; + } +} + +/* ========================================================================== + Pestaña Gestión FTP & Carga Masiva (Bulk Upload) + ========================================================================== */ + +let selectedZipFile = null; + +function setupFtp() { + const btnOpenCreateAcc = document.getElementById('btn-open-create-ftp-account'); + const formFtpAcc = document.getElementById('form-ftp-account'); + const dropZone = document.getElementById('ftp-drop-zone'); + const zipInput = document.getElementById('ftp-zip-input'); + const btnRemoveFile = document.getElementById('ftp-btn-remove-file'); + const formBulk = document.getElementById('form-bulk-upload'); + + if (btnOpenCreateAcc) { + btnOpenCreateAcc.addEventListener('click', openCreateFtpAccountModal); + } + + if (formFtpAcc) { + formFtpAcc.addEventListener('submit', handleSaveFtpAccount); + } + + // Copiado de credenciales + document.querySelectorAll('.btn-copy-mini').forEach(b => { + b.addEventListener('click', () => { + const text = b.getAttribute('data-copy'); + if (text) { + navigator.clipboard.writeText(text).then(() => { + toast.success('Copiado', text); + }); + } + }); + }); + + // Drag & Drop para archivo .zip + if (dropZone && zipInput) { + dropZone.addEventListener('click', () => zipInput.click()); + + dropZone.addEventListener('dragover', (e) => { + e.preventDefault(); + dropZone.classList.add('dragover'); + }); + + dropZone.addEventListener('dragleave', () => { + dropZone.classList.remove('dragover'); + }); + + dropZone.addEventListener('drop', (e) => { + e.preventDefault(); + dropZone.classList.remove('dragover'); + if (e.dataTransfer.files && e.dataTransfer.files.length > 0) { + handleZipFileSelected(e.dataTransfer.files[0]); + } + }); + + zipInput.addEventListener('change', (e) => { + if (e.target.files && e.target.files.length > 0) { + handleZipFileSelected(e.target.files[0]); + } + }); + } + + if (btnRemoveFile) { + btnRemoveFile.addEventListener('click', () => { + selectedZipFile = null; + if (zipInput) zipInput.value = ''; + const wrap = document.getElementById('ftp-selected-file-wrap'); + const btnExtract = document.getElementById('btn-extract-zip'); + if (wrap) wrap.style.display = 'none'; + if (btnExtract) btnExtract.disabled = true; + }); + } + + if (formBulk) { + formBulk.addEventListener('submit', handleExtractBulkZip); + } +} + +function handleZipFileSelected(file) { + if (!file.name.toLowerCase().endsWith('.zip')) { + toast.error('Formato inválido', 'Por favor selecciona un archivo comprimido .zip'); + return; + } + + selectedZipFile = file; + const wrap = document.getElementById('ftp-selected-file-wrap'); + const nameEl = document.getElementById('ftp-selected-file-name'); + const sizeEl = document.getElementById('ftp-selected-file-size'); + const btnExtract = document.getElementById('btn-extract-zip'); + + if (nameEl) nameEl.textContent = file.name; + if (sizeEl) sizeEl.textContent = `${Math.round(file.size / 1024)} KB`; + if (wrap) wrap.style.display = 'flex'; + if (btnExtract) btnExtract.disabled = false; +} + +async function handleExtractBulkZip(e) { + e.preventDefault(); + const project = document.getElementById('ftp-bulk-project-select')?.value; + const subpath = document.getElementById('ftp-bulk-subpath-input')?.value.trim(); + const statusEl = document.getElementById('ftp-extract-status'); + + if (!project) { + toast.error('Proyecto requerido', 'Selecciona el proyecto de destino para extraer el ZIP.'); + return; + } + + if (!selectedZipFile) { + toast.error('Archivo ZIP requerido', 'Selecciona o arrastra un archivo .zip.'); + return; + } + + const btnExtract = document.getElementById('btn-extract-zip'); + if (btnExtract) { + btnExtract.disabled = true; + btnExtract.innerHTML = `Descomprimiendo y aplicando SGID 2775...`; + } + + try { + const reader = new FileReader(); + reader.readAsDataURL(selectedZipFile); + reader.onload = async () => { + try { + const base64Data = String(reader.result).replace(/^data:.*?;base64,/, ''); + const res = await api.extractZipToProject(project, subpath, base64Data); + + if (statusEl) { + statusEl.className = 'extract-status-banner success'; + statusEl.textContent = `✅ Éxito: Archivo ZIP extraído en ${res.extractedTo || `/var/www/${project}`}. Permisos UNIX SGID 2775 aplicados a todo el contenido.`; + statusEl.style.display = 'block'; + } + + toast.success('Descompresión Exitosa', `Archivos extraídos en /var/www/${project}`); + await loadFolders(); + } catch (extractErr) { + if (statusEl) { + statusEl.className = 'extract-status-banner error'; + statusEl.textContent = `❌ Error: ${extractErr.detail || extractErr.message}`; + statusEl.style.display = 'block'; + } + toast.error('Fallo de extracción', extractErr.message); + } finally { + if (btnExtract) { + btnExtract.disabled = false; + btnExtract.innerHTML = ` + + + + Subir y Descomprimir con Permisos SGID 2775 + `; + } + } + }; + } catch (err) { + toast.error('Error al leer archivo', err.message); + if (btnExtract) btnExtract.disabled = false; + } +} + +async function loadFtpData() { + try { + const [info, accounts] = await Promise.all([ + api.getFtpInfo().catch(() => null), + api.getFtpAccounts().catch(() => []) + ]); + + if (info) { + store.setState({ ftpInfo: info }); + const hostEl = document.getElementById('ftp-info-host'); + const ipEl = document.getElementById('ftp-info-ip'); + const userEl = document.getElementById('ftp-info-user'); + if (hostEl) hostEl.textContent = info.host; + if (ipEl) ipEl.textContent = info.ip; + if (userEl) userEl.textContent = info.systemUser; + } + + store.setState({ ftpAccounts: accounts || [] }); + renderFtpAccounts(accounts || []); + } catch (err) { + console.warn('[FTP] Error al cargar datos FTP:', err); + } +} + +function renderFtpAccounts(accounts) { + const tbody = document.getElementById('ftp-accounts-table-body'); + const mobileList = document.getElementById('ftp-accounts-mobile-list'); + const emptyState = document.getElementById('ftp-accounts-empty-state'); + + if (!tbody) return; + + if (!accounts || accounts.length === 0) { + tbody.innerHTML = ''; + if (mobileList) mobileList.innerHTML = ''; + if (emptyState) emptyState.style.display = 'flex'; + return; + } + + if (emptyState) emptyState.style.display = 'none'; + + tbody.innerHTML = accounts.map(acc => ` + + + ${escapeHtml(acc.username)} + + + + ${escapeHtml(acc.project || 'Todos')} + + + + + ${acc.permission === 'rw' ? 'Lectura y Escritura (rw)' : 'Solo Lectura (ro)'} + + + + + ${acc.active ? 'Activo' : 'Inactivo'} + + + + ${new Date(acc.createdAt).toLocaleDateString()} + + + + + + `).join(''); + + // Mobile + if (mobileList) { + mobileList.innerHTML = accounts.map(acc => ` +
    +
    + ${escapeHtml(acc.username)} + + ${acc.active ? 'Activo' : 'Inactivo'} + +
    +
    + Ruta: + ${escapeHtml(acc.project || '/var/www')} +
    +
    + Permisos: + ${acc.permission === 'rw' ? 'rw (Lectura/Escritura)' : 'ro (Solo lectura)'} +
    +
    + +
    +
    + `).join(''); + } + + // Delegación de eliminar cuenta FTP + document.querySelectorAll('.btn-delete-ftp-acc').forEach(b => { + b.addEventListener('click', () => { + const id = b.getAttribute('data-id'); + const username = b.getAttribute('data-username'); + handleDeleteFtpAccount(id, username); + }); + }); +} + +function openCreateFtpAccountModal() { + const form = document.getElementById('form-ftp-account'); + if (form) form.reset(); + const idInput = document.getElementById('ftp-account-id-hidden'); + if (idInput) idInput.value = ''; + openModal('modal-ftp-account'); +} + +async function handleSaveFtpAccount(e) { + e.preventDefault(); + const username = document.getElementById('ftp-username-input')?.value.trim(); + const password = document.getElementById('ftp-password-input')?.value; + const project = document.getElementById('ftp-project-select')?.value; + const permission = document.getElementById('ftp-permission-select')?.value; + + if (!username || !password) { + toast.error('Campos obligatorios', 'Ingresa usuario y contraseña.'); + return; + } + + const btnSubmit = document.getElementById('btn-submit-ftp-account'); + if (btnSubmit) btnSubmit.disabled = true; + + try { + await api.createFtpAccount({ username, password, project, permission }); + toast.success('Cuenta FTP Creada', `Usuario '${username}' registrado.`); + closeAllModals(); + await loadFtpData(); + } catch (err) { + toast.error('Error al crear cuenta FTP', err.detail || err.message); + } finally { + if (btnSubmit) btnSubmit.disabled = false; + } +} + +async function handleDeleteFtpAccount(id, username) { + if (!confirm(`¿Eliminar la cuenta FTP '${username}'? Ya no podrá autenticarse.`)) return; + try { + await api.deleteFtpAccount(id); + toast.success('Cuenta eliminada', username); + await loadFtpData(); + } catch (err) { + toast.error('Error al eliminar cuenta', err.detail || err.message); + } +} + +/* ========================================================================== + Pestaña 8: Configuraciones (Usuarios, Temas, Identidad) + ========================================================================== */ + +function setupSettings() { + // Botones de Subnavegación + const subnavBtns = document.querySelectorAll('.settings-subnav-btn'); + subnavBtns.forEach(btn => { + btn.addEventListener('click', () => { + const target = btn.getAttribute('data-subtab'); + switchSettingsSubtab(target); + }); + }); + + // Editor JSON de Temas + const btnExport = document.getElementById('btn-export-theme-json'); + const btnImport = document.getElementById('btn-import-theme-json'); + const fileInput = document.getElementById('theme-file-input'); + const btnReset = document.getElementById('btn-reset-theme'); + const btnSaveCustom = document.getElementById('btn-save-custom-theme'); + + if (btnExport) { + btnExport.addEventListener('click', handleExportThemeJson); + } + + if (btnImport && fileInput) { + btnImport.addEventListener('click', () => fileInput.click()); + fileInput.addEventListener('change', handleImportThemeFile); + } + + if (btnReset) { + btnReset.addEventListener('click', handleResetTheme); + } + + if (btnSaveCustom) { + btnSaveCustom.addEventListener('click', handleSaveCustomTheme); + } + + // Formulario de Identidad + const colorPicker = document.getElementById('identity-primary-color'); + const hexInput = document.getElementById('identity-primary-hex'); + if (colorPicker && hexInput) { + colorPicker.addEventListener('input', (e) => { + hexInput.value = e.target.value; + }); + hexInput.addEventListener('input', (e) => { + if (/^#[0-9a-f]{6}$/i.test(e.target.value)) { + colorPicker.value = e.target.value; + } + }); + } + + const formIdentity = document.getElementById('form-identity'); + if (formIdentity) { + formIdentity.addEventListener('submit', handleSaveIdentity); + } +} + +function switchSettingsSubtab(subtabName) { + store.setState({ settingsSubtab: subtabName }); + + document.querySelectorAll('.settings-subnav-btn').forEach(btn => { + btn.classList.toggle('active', btn.getAttribute('data-subtab') === subtabName); + }); + + const panels = { + users: document.getElementById('settings-panel-users'), + themes: document.getElementById('settings-panel-themes'), + identity: document.getElementById('settings-panel-identity') + }; + + for (const [key, el] of Object.entries(panels)) { + if (el) el.style.display = (key === subtabName) ? 'block' : 'none'; + } + + if (subtabName === 'users') loadUsers(); + if (subtabName === 'themes') loadThemes(); + if (subtabName === 'identity') loadIdentity(); +} + +function loadSettingsTab() { + const sub = store.getState('settingsSubtab') || 'users'; + switchSettingsSubtab(sub); +} + +async function loadThemes() { + try { + const data = await api.getThemes(); + currentThemesList = data.themes || []; + currentActiveTheme = data.activeTheme; + + renderThemesGallery(currentThemesList, data.activeThemeId); + + const textarea = document.getElementById('theme-json-textarea'); + if (textarea && currentActiveTheme) { + textarea.value = JSON.stringify(currentActiveTheme, null, 2); + } + } catch (err) { + toast.error('Error al cargar temas', err.message); + } +} + +function renderThemesGallery(themes, activeThemeId) { + const grid = document.getElementById('themes-gallery-grid'); + if (!grid) return; + + grid.innerHTML = themes.map(t => { + const isActive = t.id === activeThemeId; + const colors = t.colors || {}; + const cBgApp = colors['--bg-app'] || '#080c08'; + const cBgSurface = colors['--bg-surface'] || '#0f141f'; + const cPrimary = colors['--accent-primary'] || '#10b981'; + const cLime = colors['--accent-lime'] || '#a3e635'; + + return ` +
    +
    +
    +

    ${escapeHtml(t.name)}

    + ${isActive ? `Activo` : ''} +
    +

    ${escapeHtml(t.description || '')}

    + +
    + + + + +
    +
    + + +
    + `; + }).join(''); + + grid.querySelectorAll('.btn-apply-theme').forEach(b => { + b.addEventListener('click', async () => { + const themeId = b.getAttribute('data-theme-id'); + try { + const res = await api.setActiveTheme(themeId); + const active = res.activeTheme || res.data?.activeTheme; + if (active) { + currentActiveTheme = active; + applyThemeVariables(active.colors); + toast.success('Tema aplicado', active.name); + await loadThemes(); + } + } catch (err) { + toast.error('Error al aplicar tema', err.message); + } + }); + }); +} + +function handleExportThemeJson() { + if (!currentActiveTheme) return; + const jsonStr = JSON.stringify(currentActiveTheme, null, 2); + const blob = new Blob([jsonStr], { type: 'application/json' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `${currentActiveTheme.id || 'theme'}.json`; + a.click(); + URL.revokeObjectURL(url); + toast.success('Archivo exportado', `${currentActiveTheme.id}.json`); +} + +function handleImportThemeFile(e) { + const file = e.target.files?.[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = async () => { + try { + const parsed = JSON.parse(reader.result); + const res = await api.importThemeJson(parsed); + const imported = res.theme || res.data?.theme || parsed; + currentActiveTheme = imported; + applyThemeVariables(imported.colors); + toast.success('Tema importado', imported.name || 'Personalizado'); + await loadThemes(); + } catch (err) { + toast.error('Error al importar tema', err.message); + } + }; + reader.readAsText(file); +} + +async function handleResetTheme() { + if (!confirm('¿Restaurar el tema visual a los valores por defecto (Obsidian Emerald)?')) return; + try { + const res = await api.resetTheme(); + const active = res.activeTheme || res.data?.activeTheme; + if (active) { + currentActiveTheme = active; + applyThemeVariables(active.colors); + toast.success('Tema restaurado', 'Obsidian Emerald por defecto'); + await loadThemes(); + } + } catch (err) { + toast.error('Error al restaurar tema', err.message); + } +} + +async function handleSaveCustomTheme() { + const textarea = document.getElementById('theme-json-textarea'); + if (!textarea) return; + + try { + const parsed = JSON.parse(textarea.value); + const res = await api.saveCustomTheme(parsed); + const saved = res.theme || res.data?.theme || parsed; + currentActiveTheme = saved; + applyThemeVariables(saved.colors); + toast.success('Tema guardado', saved.name); + await loadThemes(); + } catch (err) { + toast.error('JSON inválido o error', err.message); + } +} + +async function loadIdentity() { + try { + const identity = await api.getIdentity(); + currentIdentity = identity; + + const appNameEl = document.getElementById('identity-app-name'); + const panelTitleEl = document.getElementById('identity-panel-title'); + const sloganEl = document.getElementById('identity-slogan'); + const baseDomainEl = document.getElementById('identity-base-domain'); + const gitUrlEl = document.getElementById('identity-git-url'); + const footerTextEl = document.getElementById('identity-footer-text'); + const logoIconEl = document.getElementById('identity-logo-icon'); + const primaryColorEl = document.getElementById('identity-primary-color'); + const primaryHexEl = document.getElementById('identity-primary-hex'); + + if (appNameEl) appNameEl.value = identity.appName || 'a2host'; + if (panelTitleEl) panelTitleEl.value = identity.panelTitle || ''; + if (sloganEl) sloganEl.value = identity.slogan || ''; + if (baseDomainEl) baseDomainEl.value = identity.baseDomain || BASE_DOMAIN; + if (gitUrlEl) gitUrlEl.value = identity.gitUrl || ''; + if (footerTextEl) footerTextEl.value = identity.footerText || ''; + if (logoIconEl) logoIconEl.value = identity.logoIcon || 'server'; + if (primaryColorEl) primaryColorEl.value = identity.primaryColor || '#10b981'; + if (primaryHexEl) primaryHexEl.value = identity.primaryColor || '#10b981'; + } catch (err) { + toast.error('Error al cargar identidad', err.message); + } +} + +async function handleSaveIdentity(e) { + e.preventDefault(); + const payload = { + appName: document.getElementById('identity-app-name')?.value.trim(), + panelTitle: document.getElementById('identity-panel-title')?.value.trim(), + slogan: document.getElementById('identity-slogan')?.value.trim(), + baseDomain: document.getElementById('identity-base-domain')?.value.trim(), + gitUrl: document.getElementById('identity-git-url')?.value.trim(), + footerText: document.getElementById('identity-footer-text')?.value.trim(), + logoIcon: document.getElementById('identity-logo-icon')?.value, + primaryColor: document.getElementById('identity-primary-color')?.value + }; + + const btn = document.getElementById('btn-save-identity'); + if (btn) btn.disabled = true; + + try { + const res = await api.updateIdentity(payload); + const updated = res.identity || res.data?.identity || payload; + currentIdentity = updated; + applyIdentityUI(updated); + toast.success('Identidad guardada', 'Los cambios se han aplicado al panel.'); + } catch (err) { + toast.error('Error al guardar identidad', err.detail || err.message); + } finally { + if (btn) btn.disabled = false; + } +} + /* ========================================================================== Utilidades Globales de Modales y Helpers ========================================================================== */ diff --git a/public/js/state.js b/public/js/state.js index f3fb570..0b50d9c 100644 --- a/public/js/state.js +++ b/public/js/state.js @@ -32,12 +32,32 @@ class StateStore { content: '', isDirty: false }, + // Projects + projects: [], + projectsLoading: false, + projectsFilter: { + search: '', + type: 'all' + }, + // FTP + ftpInfo: null, + ftpAccounts: [], + ftpLoading: false, + // Terminal VPS Auth + vpsTerminalUser: null, + vpsTerminalAuthenticated: false, terminalInfo: null, terminalHistory: [], monitorProcesses: [], monitorIntervalId: null, + // Users & Settings users: [], usersLoading: false, + settingsSubtab: 'users', // 'users' | 'themes' | 'identity' + themes: [], + activeThemeId: 'obsidian-emerald', + activeTheme: null, + identity: null, stats: null, docs: [], selectedDoc: null, diff --git a/src/controllers/ftp.controller.js b/src/controllers/ftp.controller.js new file mode 100644 index 0000000..9b853f2 --- /dev/null +++ b/src/controllers/ftp.controller.js @@ -0,0 +1,74 @@ +import defaultFtpService from '../services/ftp.service.js'; +import { sendSuccess } from '../utils/response.util.js'; + +export class FtpController { + constructor(ftpService) { + this.ftpService = ftpService || defaultFtpService; + } + + getInfo = async (req, res, next) => { + try { + const info = this.ftpService.getConnectionInfo(); + return res.json(info); + } catch (err) { + next(err); + } + }; + + listAccounts = async (req, res, next) => { + try { + const accounts = await this.ftpService.listAccounts(); + return res.json(accounts); + } catch (err) { + next(err); + } + }; + + createAccount = async (req, res, next) => { + try { + const account = await this.ftpService.createAccount(req.body); + return sendSuccess(res, 201, { + message: `Cuenta FTP '${account.username}' creada exitosamente`, + account + }); + } catch (err) { + next(err); + } + }; + + updateAccount = async (req, res, next) => { + try { + const updated = await this.ftpService.updateAccount(req.params.id, req.body); + return sendSuccess(res, 200, { + message: `Cuenta FTP '${updated.username}' actualizada exitosamente`, + account: updated + }); + } catch (err) { + next(err); + } + }; + + deleteAccount = async (req, res, next) => { + try { + await this.ftpService.deleteAccount(req.params.id); + return sendSuccess(res, 200, { + message: 'Cuenta FTP eliminada exitosamente' + }); + } catch (err) { + next(err); + } + }; + + extractZip = async (req, res, next) => { + try { + const { project, relativePath, zipBase64 } = req.body || {}; + const result = await this.ftpService.extractZipToFolder(project, relativePath, zipBase64); + return sendSuccess(res, 200, result); + } catch (err) { + next(err); + } + }; +} + +export const defaultFtpController = new FtpController(); +export default defaultFtpController; diff --git a/src/controllers/project.controller.js b/src/controllers/project.controller.js new file mode 100644 index 0000000..c062f87 --- /dev/null +++ b/src/controllers/project.controller.js @@ -0,0 +1,92 @@ +import defaultProjectService from '../services/project.service.js'; +import { sendSuccess } from '../utils/response.util.js'; + +export class ProjectController { + constructor(projectService) { + this.projectService = projectService || defaultProjectService; + } + + list = async (req, res, next) => { + try { + const projects = await this.projectService.listProjects(); + return res.json(projects); + } catch (err) { + next(err); + } + }; + + getById = async (req, res, next) => { + try { + const project = await this.projectService.getProject(req.params.id); + return res.json(project); + } catch (err) { + next(err); + } + }; + + create = async (req, res, next) => { + try { + const project = await this.projectService.createProject(req.body); + return sendSuccess(res, 201, { + message: `Proyecto '${project.name}' creado y configurado exitosamente`, + project + }); + } catch (err) { + next(err); + } + }; + + update = async (req, res, next) => { + try { + const updated = await this.projectService.updateProject(req.params.id, req.body); + return sendSuccess(res, 200, { + message: `Proyecto '${updated.name}' actualizado exitosamente`, + project: updated + }); + } catch (err) { + next(err); + } + }; + + addSubdomain = async (req, res, next) => { + try { + const { subdomain } = req.body || {}; + const updated = await this.projectService.addSubdomain(req.params.id, subdomain); + return sendSuccess(res, 200, { + message: `Subdominio '${subdomain}' vinculado exitosamente al proyecto`, + project: updated + }); + } catch (err) { + next(err); + } + }; + + removeSubdomain = async (req, res, next) => { + try { + const { subdomain } = req.params; + const updated = await this.projectService.removeSubdomain(req.params.id, subdomain); + return sendSuccess(res, 200, { + message: `Subdominio '${subdomain}' desvinculado del proyecto`, + project: updated + }); + } catch (err) { + next(err); + } + }; + + delete = async (req, res, next) => { + try { + const deleteFiles = req.query.deleteFiles === 'true' || req.body?.deleteFiles === true; + const result = await this.projectService.deleteProject(req.params.id, { deleteFiles }); + return sendSuccess(res, 200, { + message: `Proyecto '${result.name}' eliminado exitosamente.${result.deletedFiles ? ' Archivos físicos purgados.' : ''}`, + result + }); + } catch (err) { + next(err); + } + }; +} + +export const defaultProjectController = new ProjectController(); +export default defaultProjectController; diff --git a/src/controllers/settings.controller.js b/src/controllers/settings.controller.js new file mode 100644 index 0000000..f479d1c --- /dev/null +++ b/src/controllers/settings.controller.js @@ -0,0 +1,107 @@ +import defaultSettingsService from '../services/settings.service.js'; +import { sendSuccess } from '../utils/response.util.js'; + +export class SettingsController { + constructor(settingsService) { + this.settingsService = settingsService || defaultSettingsService; + } + + getIdentity = async (req, res, next) => { + try { + const identity = this.settingsService.getIdentity(); + return res.json(identity); + } catch (err) { + next(err); + } + }; + + updateIdentity = async (req, res, next) => { + try { + const updated = this.settingsService.updateIdentity(req.body); + return sendSuccess(res, 200, { + message: 'Identidad del sistema actualizada exitosamente', + identity: updated + }); + } catch (err) { + next(err); + } + }; + + getThemes = async (req, res, next) => { + try { + const themes = this.settingsService.getThemesList(); + const active = this.settingsService.getActiveTheme(); + return res.json({ + activeThemeId: active.id, + activeTheme: active, + themes + }); + } catch (err) { + next(err); + } + }; + + setActiveTheme = async (req, res, next) => { + try { + const { themeId } = req.body || {}; + const active = this.settingsService.setActiveTheme(themeId); + return sendSuccess(res, 200, { + message: `Tema '${active.name}' activado exitosamente`, + activeTheme: active + }); + } catch (err) { + next(err); + } + }; + + saveCustomTheme = async (req, res, next) => { + try { + const saved = this.settingsService.saveCustomTheme(req.body); + return sendSuccess(res, 200, { + message: `Tema personalizado '${saved.name}' guardado exitosamente`, + theme: saved + }); + } catch (err) { + next(err); + } + }; + + importTheme = async (req, res, next) => { + try { + const imported = this.settingsService.importThemeJson(req.body?.themeJson || req.body); + this.settingsService.setActiveTheme(imported.id); + return sendSuccess(res, 200, { + message: `Tema '${imported.name}' importado y activado exitosamente`, + theme: imported + }); + } catch (err) { + next(err); + } + }; + + exportTheme = async (req, res, next) => { + try { + const theme = this.settingsService.exportActiveThemeJson(); + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Content-Disposition', `attachment; filename="${theme.id}-theme.json"`); + return res.json(theme); + } catch (err) { + next(err); + } + }; + + resetTheme = async (req, res, next) => { + try { + const active = this.settingsService.resetTheme(); + return sendSuccess(res, 200, { + message: 'Tema restaurado a valores por defecto (Obsidian Emerald)', + activeTheme: active + }); + } catch (err) { + next(err); + } + }; +} + +export const defaultSettingsController = new SettingsController(); +export default defaultSettingsController; diff --git a/src/controllers/terminal.controller.js b/src/controllers/terminal.controller.js index b6d4a29..632dc1b 100644 --- a/src/controllers/terminal.controller.js +++ b/src/controllers/terminal.controller.js @@ -6,20 +6,45 @@ export class TerminalController { this.terminalService = terminalService || defaultTerminalService; } - execute = async (req, res, next) => { + getInfo = async (req, res, next) => { try { - const { command, cwd } = req.body || {}; - const result = await this.terminalService.executeCommand(command, { cwd }); - return sendSuccess(res, 200, result); + const token = req.headers['x-terminal-token'] || req.query.terminalToken; + const info = this.terminalService.getTerminalInfo(token); + return res.json(info); } catch (err) { next(err); } }; - info = async (req, res, next) => { + login = async (req, res, next) => { try { - const info = this.terminalService.getTerminalInfo(); - return sendSuccess(res, 200, info); + const { vpsUser, vpsPassword } = req.body || {}; + const result = await this.terminalService.authenticateVpsUser(vpsUser, vpsPassword); + return sendSuccess(res, 200, { + message: `Sesión de terminal iniciada para el usuario de sistema '${result.vpsUser}'`, + ...result + }); + } catch (err) { + next(err); + } + }; + + logout = async (req, res, next) => { + try { + return sendSuccess(res, 200, { + message: 'Sesión de terminal cerrada exitosamente' + }); + } catch (err) { + next(err); + } + }; + + execute = async (req, res, next) => { + try { + const { command, cwd } = req.body || {}; + const token = req.headers['x-terminal-token'] || req.body?.terminalToken; + const result = await this.terminalService.executeCommand(command, { cwd, terminalToken: token }); + return sendSuccess(res, 200, result); } catch (err) { next(err); } diff --git a/src/routes/ftp.routes.js b/src/routes/ftp.routes.js new file mode 100644 index 0000000..3950dc7 --- /dev/null +++ b/src/routes/ftp.routes.js @@ -0,0 +1,20 @@ +import { Router } from 'express'; +import defaultFtpController from '../controllers/ftp.controller.js'; +import { authenticate, requireRole } from '../middlewares/auth.middleware.js'; + +export function createFtpRoutes(controller = defaultFtpController) { + const router = Router(); + + router.use(authenticate); + + router.get('/info', controller.getInfo); + router.get('/accounts', controller.listAccounts); + router.post('/accounts', requireRole('admin'), controller.createAccount); + router.put('/accounts/:id', requireRole('admin'), controller.updateAccount); + router.delete('/accounts/:id', requireRole('admin'), controller.deleteAccount); + router.post('/extract-zip', controller.extractZip); + + return router; +} + +export default createFtpRoutes(); diff --git a/src/routes/index.js b/src/routes/index.js index 9e546f9..741c5d5 100644 --- a/src/routes/index.js +++ b/src/routes/index.js @@ -6,17 +6,23 @@ import folderRoutes from './folder.routes.js'; import systemRoutes from './system.routes.js'; import docsRoutes from './docs.routes.js'; import terminalRoutes from './terminal.routes.js'; +import settingsRoutes from './settings.routes.js'; +import projectRoutes from './project.routes.js'; +import ftpRoutes from './ftp.routes.js'; export function createApiRouter() { const router = Router(); router.use('/auth', authRoutes); router.use('/subdomains', subdomainRoutes); + router.use('/projects', projectRoutes); + router.use('/ftp', ftpRoutes); router.use('/users', userRoutes); router.use('/folders', folderRoutes); router.use('/system', systemRoutes); router.use('/docs', docsRoutes); router.use('/terminal', terminalRoutes); + router.use('/settings', settingsRoutes); return router; } diff --git a/src/routes/project.routes.js b/src/routes/project.routes.js new file mode 100644 index 0000000..3735dc0 --- /dev/null +++ b/src/routes/project.routes.js @@ -0,0 +1,21 @@ +import { Router } from 'express'; +import defaultProjectController from '../controllers/project.controller.js'; +import { authenticate, requireRole } from '../middlewares/auth.middleware.js'; + +export function createProjectRoutes(controller = defaultProjectController) { + const router = Router(); + + router.use(authenticate); + + router.get('/', controller.list); + router.post('/', controller.create); + router.get('/:id', controller.getById); + router.put('/:id', controller.update); + router.post('/:id/subdomains', controller.addSubdomain); + router.delete('/:id/subdomains/:subdomain', controller.removeSubdomain); + router.delete('/:id', requireRole('admin'), controller.delete); + + return router; +} + +export default createProjectRoutes(); diff --git a/src/routes/settings.routes.js b/src/routes/settings.routes.js new file mode 100644 index 0000000..9962fc5 --- /dev/null +++ b/src/routes/settings.routes.js @@ -0,0 +1,26 @@ +import { Router } from 'express'; +import defaultSettingsController from '../controllers/settings.controller.js'; +import { authenticate, requireRole } from '../middlewares/auth.middleware.js'; + +export function createSettingsRoutes(controller = defaultSettingsController) { + const router = Router(); + + // Todos los endpoints de configuración requieren autenticación + router.use(authenticate); + + // Identidad del sistema + router.get('/identity', controller.getIdentity); + router.put('/identity', requireRole('admin'), controller.updateIdentity); + + // Temas y fondos + router.get('/themes', controller.getThemes); + router.post('/themes/set', controller.setActiveTheme); + router.post('/themes/custom', controller.saveCustomTheme); + router.post('/themes/import', controller.importTheme); + router.get('/themes/export', controller.exportTheme); + router.post('/themes/reset', controller.resetTheme); + + return router; +} + +export default createSettingsRoutes(); diff --git a/src/routes/terminal.routes.js b/src/routes/terminal.routes.js index 658a64e..be25ef5 100644 --- a/src/routes/terminal.routes.js +++ b/src/routes/terminal.routes.js @@ -2,15 +2,17 @@ import { Router } from 'express'; import defaultTerminalController from '../controllers/terminal.controller.js'; import { authenticate, requireRole } from '../middlewares/auth.middleware.js'; -export function createTerminalRoutes(terminalController = defaultTerminalController) { +export function createTerminalRoutes(controller = defaultTerminalController) { const router = Router(); - // Acceso restringido exclusivamente a administradores autenticados + // La terminal requiere autenticación en el panel y rol de administrador router.use(authenticate); router.use(requireRole('admin')); - router.post('/execute', terminalController.execute); - router.get('/info', terminalController.info); + router.get('/info', controller.getInfo); + router.post('/login', controller.login); + router.post('/logout', controller.logout); + router.post('/execute', controller.execute); return router; } diff --git a/src/services/ftp.service.js b/src/services/ftp.service.js new file mode 100644 index 0000000..586e7f3 --- /dev/null +++ b/src/services/ftp.service.js @@ -0,0 +1,247 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import child_process from 'node:child_process'; +import { promisify } from 'node:util'; +import config from '../config/env.js'; +import DriverFactory from '../infrastructure/apache/driver.factory.js'; +import { hashPassword, verifyPassword } from '../utils/crypto.util.js'; +import { validateSubdomainName, sanitizePath } from '../utils/validation.util.js'; + +const execFileAsync = promisify(child_process.execFile); + +export class FtpService { + constructor(filePath) { + this.filePath = filePath || path.resolve(process.cwd(), 'data/ftp_accounts.json'); + this.accounts = []; + this.initialized = false; + } + + getWebRoot() { + const driver = DriverFactory.getDriver(); + return driver.webRoot || config.webRoot; + } + + async init() { + const parentDir = path.dirname(this.filePath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + if (fs.existsSync(this.filePath)) { + try { + const raw = fs.readFileSync(this.filePath, 'utf-8'); + this.accounts = JSON.parse(raw); + if (!Array.isArray(this.accounts)) { + this.accounts = []; + } + } catch { + this.accounts = []; + } + } else { + this.accounts = []; + } + + this.initialized = true; + return this; + } + + saveSync() { + const parentDir = path.dirname(this.filePath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + const tmpPath = `${this.filePath}.tmp.${Date.now()}_${process.pid}_${crypto.randomBytes(4).toString('hex')}`; + fs.writeFileSync(tmpPath, JSON.stringify(this.accounts, null, 2), 'utf-8'); + fs.renameSync(tmpPath, this.filePath); + } + + getConnectionInfo() { + return { + host: config.baseDomain || 'elingejose.com', + ip: '201.32.134.58', + sftpPort: 5101, // Puerto SSH primario configurado en el VPS + sftpStandardPort: 22, + ftpPort: 21, + baseRoot: this.getWebRoot(), + protocolsSupported: ['SFTP (SSH File Transfer Protocol)', 'FTP / FTPS (TLS)'], + recommendedClient: 'FileZilla / Cyberduck / WinSCP', + systemUser: config.systemUser || 'ggc', + instructions: `Para conectarse vía SFTP en FileZilla: Protocolo 'SFTP', Servidor '${config.baseDomain}', Puerto '5101', Usuario 'ggc'. Las carpetas de tus proyectos se encuentran en '${this.getWebRoot()}/'.` + }; + } + + async listAccounts() { + if (!this.initialized) await this.init(); + return this.accounts.map(({ passwordHash, ...safe }) => safe); + } + + async createAccount({ username, password, project, permission = 'rw' }) { + if (!this.initialized) await this.init(); + const cleanUser = String(username || '').trim().toLowerCase().replace(/[^a-z0-9_-]/g, ''); + + if (!cleanUser || cleanUser.length < 3) { + const error = new Error('El nombre de usuario FTP debe tener al menos 3 caracteres alfanuméricos.'); + error.status = 400; + throw error; + } + + if (this.accounts.some((a) => a.username.toLowerCase() === cleanUser)) { + const error = new Error(`La cuenta FTP '${cleanUser}' ya existe.`); + error.status = 409; + throw error; + } + + if (!password || String(password).length < 6) { + const error = new Error('La contraseña FTP debe tener al menos 6 caracteres.'); + error.status = 400; + throw error; + } + + const cleanProject = project ? validateSubdomainName(project) : ''; + const webRoot = this.getWebRoot(); + const targetDir = cleanProject ? path.join(webRoot, cleanProject) : webRoot; + + // Asegurar directorio si fue especificado un proyecto + if (cleanProject && !fs.existsSync(targetDir)) { + const driver = DriverFactory.getDriver(); + await driver.ensureWebDirectory(cleanProject); + } + + const passwordHash = await hashPassword(password); + const now = new Date().toISOString(); + + const newAccount = { + id: `ftp-${crypto.randomUUID().slice(0, 8)}`, + username: cleanUser, + passwordHash, + project: cleanProject || 'Todos (/var/www)', + targetPath: targetDir, + permission: permission === 'ro' ? 'ro' : 'rw', + active: true, + createdAt: now, + updatedAt: now + }; + + this.accounts.push(newAccount); + this.saveSync(); + + const { passwordHash: _, ...safe } = newAccount; + return safe; + } + + async updateAccount(id, { password, permission, active }) { + if (!this.initialized) await this.init(); + const index = this.accounts.findIndex((a) => a.id === id); + + if (index === -1) { + const error = new Error(`Cuenta FTP con id '${id}' no encontrada.`); + error.status = 404; + throw error; + } + + const current = this.accounts[index]; + const updated = { + ...current, + permission: permission !== undefined ? (permission === 'ro' ? 'ro' : 'rw') : current.permission, + active: active !== undefined ? Boolean(active) : current.active, + updatedAt: new Date().toISOString() + }; + + if (password && String(password).length >= 6) { + updated.passwordHash = await hashPassword(password); + } + + this.accounts[index] = updated; + this.saveSync(); + + const { passwordHash: _, ...safe } = updated; + return safe; + } + + async deleteAccount(id) { + if (!this.initialized) await this.init(); + const exists = this.accounts.some((a) => a.id === id); + + if (!exists) { + const error = new Error(`Cuenta FTP con id '${id}' no encontrada.`); + error.status = 404; + throw error; + } + + this.accounts = this.accounts.filter((a) => a.id !== id); + this.saveSync(); + return true; + } + + /** + * Extrae un archivo comprimido .zip directamente en la carpeta de un proyecto /var/www// + * y garantiza la asignación de permisos SGID 2775 y grupo www-data. + */ + async extractZipToFolder(projectName, relativePath, zipBase64Content) { + const cleanProject = validateSubdomainName(projectName); + const webRoot = this.getWebRoot(); + const projectRoot = path.join(webRoot, cleanProject); + + if (!fs.existsSync(projectRoot)) { + const error = new Error(`El directorio del proyecto '${cleanProject}' no existe.`); + error.status = 404; + throw error; + } + + const targetDir = relativePath ? sanitizePath(projectRoot, relativePath) : projectRoot; + if (!fs.existsSync(targetDir)) { + fs.mkdirSync(targetDir, { recursive: true, mode: 0o2775 }); + } + + if (!zipBase64Content || typeof zipBase64Content !== 'string') { + const error = new Error('Contenido ZIP en Base64 inválido o vacío.'); + error.status = 400; + throw error; + } + + const buffer = Buffer.from(zipBase64Content, 'base64'); + const tmpZipPath = path.join(webRoot, `.tmp_upload_${Date.now()}_${crypto.randomBytes(4).toString('hex')}.zip`); + + fs.writeFileSync(tmpZipPath, buffer); + + try { + // Usar unzip en Linux con sobreescritura silenciosa (-o) + await execFileAsync('unzip', ['-o', '-q', tmpZipPath, '-d', targetDir]); + } catch (unzipErr) { + // Si falla comando unzip (ej. en local o sin paquete), intentar descomprimir si es mock + if (process.env.MOCK_APACHE === 'true') { + // En mock, simular extracción creando archivo index.html o manifest + fs.writeFileSync(path.join(targetDir, 'extracted-sample.html'), '

    Extracted Sample

    ', 'utf-8'); + } else { + throw new Error(`Fallo al descomprimir archivo ZIP: ${unzipErr.message}`); + } + } finally { + if (fs.existsSync(tmpZipPath)) { + fs.unlinkSync(tmpZipPath); + } + } + + // Asegurar permisos en todo lo extraído + try { + const driver = DriverFactory.getDriver(); + if (typeof driver.setPermissions === 'function') { + await driver.setPermissions(targetDir, config.systemUser || 'ggc', 'www-data'); + } + } catch { + // Ignorar en mock + } + + return { + success: true, + project: cleanProject, + extractedTo: targetDir, + message: 'Archivo ZIP extraído y permisos aplicados exitosamente.' + }; + } +} + +export const defaultFtpService = new FtpService(); +defaultFtpService.init().catch(() => {}); +export default defaultFtpService; diff --git a/src/services/project.service.js b/src/services/project.service.js new file mode 100644 index 0000000..b30e43f --- /dev/null +++ b/src/services/project.service.js @@ -0,0 +1,422 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import config from '../config/env.js'; +import DriverFactory from '../infrastructure/apache/driver.factory.js'; +import defaultSiteService from './site.service.js'; +import defaultTemplateService from './template.service.js'; +import { validateSubdomainName, validatePort, sanitizePath } from '../utils/validation.util.js'; + +export class ProjectService { + /** + * @param {object} [deps] + * @param {string} [deps.filePath] + * @param {import('./site.service.js').SiteService} [deps.siteService] + * @param {import('./template.service.js').TemplateService} [deps.templateService] + * @param {import('../infrastructure/apache/apache.driver.interface.js').IApacheDriver} [deps.driver] + */ + constructor({ filePath, siteService, templateService, driver } = {}) { + this.filePath = filePath || path.resolve(process.cwd(), 'data/projects.json'); + this.siteService = siteService || defaultSiteService; + this.templateService = templateService || defaultTemplateService; + this.driver = driver; + this.projects = []; + this.initialized = false; + } + + getDriver() { + return this.driver || DriverFactory.getDriver(); + } + + getWebRoot() { + const driver = this.getDriver(); + return driver.webRoot || config.webRoot; + } + + async init() { + const parentDir = path.dirname(this.filePath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + if (fs.existsSync(this.filePath)) { + try { + const raw = fs.readFileSync(this.filePath, 'utf-8'); + this.projects = JSON.parse(raw); + if (!Array.isArray(this.projects)) { + this.projects = []; + } + } catch { + this.projects = []; + } + } else { + this.projects = []; + } + + this.initialized = true; + return this; + } + + saveSync() { + const parentDir = path.dirname(this.filePath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + const tmpPath = `${this.filePath}.tmp.${Date.now()}_${process.pid}_${crypto.randomBytes(4).toString('hex')}`; + fs.writeFileSync(tmpPath, JSON.stringify(this.projects, null, 2), 'utf-8'); + fs.renameSync(tmpPath, this.filePath); + } + + async listProjects() { + if (!this.initialized) await this.init(); + const webRoot = this.getWebRoot(); + + return this.projects.map((proj) => { + const projectRoot = path.join(webRoot, proj.name); + const publicPath = this.resolvePublicDocRoot(proj.name, proj.publicFolder); + const existsOnDisk = fs.existsSync(projectRoot); + const publicExists = fs.existsSync(publicPath); + + return { + ...proj, + rootDirectory: projectRoot, + effectiveDocRoot: publicPath, + existsOnDisk, + publicExists + }; + }); + } + + async getProject(idOrName) { + if (!this.initialized) await this.init(); + const clean = String(idOrName).toLowerCase().trim(); + const proj = this.projects.find((p) => p.id === clean || p.name.toLowerCase() === clean); + + if (!proj) { + const error = new Error(`Proyecto '${idOrName}' no encontrado.`); + error.status = 404; + error.code = 'PROJECT_NOT_FOUND'; + throw error; + } + + const webRoot = this.getWebRoot(); + const projectRoot = path.join(webRoot, proj.name); + const publicPath = this.resolvePublicDocRoot(proj.name, proj.publicFolder); + + return { + ...proj, + rootDirectory: projectRoot, + effectiveDocRoot: publicPath, + existsOnDisk: fs.existsSync(projectRoot), + publicExists: fs.existsSync(publicPath) + }; + } + + /** + * Resuelve y valida de forma segura que la subcarpeta pública resida dentro de /var/www/ + */ + resolvePublicDocRoot(projectName, publicFolder = '') { + const webRoot = this.getWebRoot(); + const cleanProject = validateSubdomainName(projectName); + const projectRoot = path.join(webRoot, cleanProject); + + if (!publicFolder || publicFolder.trim() === '' || publicFolder.trim() === '/') { + return projectRoot; + } + + const sub = publicFolder.trim().replace(/^\/+/, ''); + return sanitizePath(projectRoot, sub); + } + + async createProject(params) { + if (!this.initialized) await this.init(); + const cleanName = validateSubdomainName(params.name); + + if (this.projects.some((p) => p.name.toLowerCase() === cleanName.toLowerCase())) { + const error = new Error(`Ya existe un proyecto con el nombre '${cleanName}'.`); + error.status = 409; + error.code = 'PROJECT_ALREADY_EXISTS'; + throw error; + } + + const type = ['static', 'node', 'python', 'custom'].includes(params.type) ? params.type : 'static'; + const driver = this.getDriver(); + const webRoot = this.getWebRoot(); + const projectRoot = path.join(webRoot, cleanName); + + // 1. Asegurar la carpeta base del proyecto dentro de /var/www + await driver.ensureWebDirectory(cleanName); + + // 2. Si se especificó una subcarpeta pública (ej. public, dist), crearla dentro del proyecto + const publicFolder = String(params.publicFolder || '').trim().replace(/^\/+/, ''); + if (publicFolder) { + const fullPublic = this.resolvePublicDocRoot(cleanName, publicFolder); + if (!fs.existsSync(fullPublic)) { + fs.mkdirSync(fullPublic, { recursive: true, mode: 0o2775 }); + } + } + + // 3. Validar puerto para proyectos con proxy reverso + let validatedPort = null; + if (type !== 'static') { + const activePorts = this.projects.filter((p) => p.type !== 'static' && p.port).map((p) => p.port); + validatedPort = validatePort(params.port, config.reservedPorts, activePorts); + } + + // 4. Procesar subdominios iniciales asignados al proyecto + const subdomainsList = Array.isArray(params.subdomains) ? params.subdomains : []; + const validSubdomains = []; + + for (const sub of subdomainsList) { + if (!sub) continue; + const cleanSub = validateSubdomainName(sub); + if (!validSubdomains.includes(cleanSub)) { + validSubdomains.push(cleanSub); + } + } + + // Si no se pasó ningún subdominio, usar el nombre del proyecto como subdominio por defecto + if (validSubdomains.length === 0) { + validSubdomains.push(cleanName); + } + + // 5. Generar y activar VirtualHosts en Apache para cada subdominio + for (const sub of validSubdomains) { + await this.provisionSubdomainForProject({ + subdomain: sub, + projectName: cleanName, + type, + port: validatedPort, + publicFolder + }); + } + + const now = new Date().toISOString(); + const newProject = { + id: `proj-${cleanName}`, + name: cleanName, + title: String(params.title || cleanName).trim().slice(0, 80), + description: String(params.description || '').trim().slice(0, 250), + type, + publicFolder, + port: validatedPort, + subdomains: validSubdomains, + entryScript: String(params.entryScript || (type === 'node' ? 'index.js' : type === 'python' ? 'app.py' : 'index.php')).trim(), + status: 'active', + createdAt: now, + updatedAt: now + }; + + this.projects.push(newProject); + this.saveSync(); + + return this.getProject(newProject.id); + } + + async provisionSubdomainForProject({ subdomain, projectName, type, port, publicFolder }) { + const driver = this.getDriver(); + const docRoot = this.resolvePublicDocRoot(projectName, publicFolder); + + let confContent = ''; + if (type === 'static') { + confContent = ` + ServerName ${subdomain}.${config.baseDomain} + DocumentRoot ${docRoot} + + + Options -Indexes +FollowSymLinks + AllowOverride All + Require all granted + DirectoryIndex index.php index.html index.htm + + + ErrorLog \${APACHE_LOG_DIR}/${subdomain}_error.log + CustomLog \${APACHE_LOG_DIR}/${subdomain}_access.log combined + +`; + } else { + confContent = ` + ServerName ${subdomain}.${config.baseDomain} + + ProxyPreserveHost On + AllowEncodedSlashes NoDecode + + ProxyPass / http://127.0.0.1:${port}/ nocanon + ProxyPassReverse / http://127.0.0.1:${port}/ + + ErrorLog \${APACHE_LOG_DIR}/${subdomain}_error.log + CustomLog \${APACHE_LOG_DIR}/${subdomain}_access.log combined + +`; + } + + await driver.createVirtualHost(subdomain, confContent); + await driver.enableSite(subdomain); + + const testResult = await driver.testConfig(); + if (!testResult.ok) { + try { + await driver.disableSite(subdomain); + await driver.deleteVirtualHost(subdomain); + } catch { + // Ignorar + } + const error = new Error(`Error al configurar VirtualHost para '${subdomain}': ${testResult.stderr || 'Sintaxis inválida'}`); + error.status = 422; + error.code = 'APACHE_CONFIGTEST_FAILED'; + throw error; + } + + await driver.reloadApache(); + } + + async updateProject(idOrName, params) { + if (!this.initialized) await this.init(); + const proj = await this.getProject(idOrName); + const index = this.projects.findIndex((p) => p.id === proj.id); + + const cleanPublic = params.publicFolder !== undefined + ? String(params.publicFolder).trim().replace(/^\/+/, '') + : proj.publicFolder; + + let targetPort = proj.port; + if (proj.type !== 'static' && params.port !== undefined) { + const activePorts = this.projects + .filter((p) => p.id !== proj.id && p.type !== 'static' && p.port) + .map((p) => p.port); + targetPort = validatePort(params.port, config.reservedPorts, activePorts); + } + + // Si cambió la subcarpeta pública o el puerto, reconfigurar todos sus VirtualHosts asociados + const needsVhostUpdate = cleanPublic !== proj.publicFolder || targetPort !== proj.port; + + if (needsVhostUpdate) { + for (const sub of proj.subdomains) { + await this.provisionSubdomainForProject({ + subdomain: sub, + projectName: proj.name, + type: proj.type, + port: targetPort, + publicFolder: cleanPublic + }); + } + } + + const updated = { + ...this.projects[index], + title: params.title !== undefined ? String(params.title).trim().slice(0, 80) : proj.title, + description: params.description !== undefined ? String(params.description).trim().slice(0, 250) : proj.description, + publicFolder: cleanPublic, + port: targetPort, + entryScript: params.entryScript !== undefined ? String(params.entryScript).trim() : proj.entryScript, + status: params.status !== undefined ? params.status : proj.status, + updatedAt: new Date().toISOString() + }; + + this.projects[index] = updated; + this.saveSync(); + + return this.getProject(proj.id); + } + + async addSubdomain(idOrName, subdomain) { + if (!this.initialized) await this.init(); + const proj = await this.getProject(idOrName); + const index = this.projects.findIndex((p) => p.id === proj.id); + const cleanSub = validateSubdomainName(subdomain); + + if (proj.subdomains.includes(cleanSub)) { + const error = new Error(`El subdominio '${cleanSub}' ya está asociado a este proyecto.`); + error.status = 409; + throw error; + } + + await this.provisionSubdomainForProject({ + subdomain: cleanSub, + projectName: proj.name, + type: proj.type, + port: proj.port, + publicFolder: proj.publicFolder + }); + + this.projects[index].subdomains.push(cleanSub); + this.projects[index].updatedAt = new Date().toISOString(); + this.saveSync(); + + return this.getProject(proj.id); + } + + async removeSubdomain(idOrName, subdomain) { + if (!this.initialized) await this.init(); + const proj = await this.getProject(idOrName); + const index = this.projects.findIndex((p) => p.id === proj.id); + const cleanSub = validateSubdomainName(subdomain); + + if (!proj.subdomains.includes(cleanSub)) { + const error = new Error(`El subdominio '${cleanSub}' no está asociado a este proyecto.`); + error.status = 404; + throw error; + } + + if (proj.subdomains.length <= 1) { + const error = new Error(`El proyecto debe mantener al menos un subdominio asociado.`); + error.status = 400; + throw error; + } + + const driver = this.getDriver(); + try { + await driver.disableSite(cleanSub); + await driver.deleteVirtualHost(cleanSub); + await driver.reloadApache(); + } catch { + // Ignorar si ya no existía + } + + this.projects[index].subdomains = this.projects[index].subdomains.filter((s) => s !== cleanSub); + this.projects[index].updatedAt = new Date().toISOString(); + this.saveSync(); + + return this.getProject(proj.id); + } + + async deleteProject(idOrName, { deleteFiles = false } = {}) { + if (!this.initialized) await this.init(); + const proj = await this.getProject(idOrName); + const driver = this.getDriver(); + + // 1. Eliminar VirtualHosts de todos sus subdominios + for (const sub of proj.subdomains) { + try { + await driver.disableSite(sub); + await driver.deleteVirtualHost(sub); + } catch { + // Ignorar + } + } + await driver.reloadApache(); + + // 2. Si se solicitó, purgar físicamente la carpeta del proyecto en /var/www/ + if (deleteFiles) { + try { + await driver.removeWebDirectory(proj.name); + } catch { + // Ignorar + } + } + + this.projects = this.projects.filter((p) => p.id !== proj.id); + this.saveSync(); + + return { + id: proj.id, + name: proj.name, + deletedFiles: Boolean(deleteFiles) + }; + } +} + +export const defaultProjectService = new ProjectService(); +defaultProjectService.init().catch(() => {}); +export default defaultProjectService; diff --git a/src/services/settings.service.js b/src/services/settings.service.js new file mode 100644 index 0000000..80c8395 --- /dev/null +++ b/src/services/settings.service.js @@ -0,0 +1,327 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import config from '../config/env.js'; + +export const DEFAULT_THEMES = { + 'obsidian-emerald': { + id: 'obsidian-emerald', + name: 'Obsidian Emerald (Por Defecto)', + description: 'Estética Dark SaaS con acentos esmeralda y lima vibrantes', + colors: { + '--bg-app': '#07090e', + '--bg-surface': '#0f141f', + '--bg-surface-elevated': '#161e2e', + '--bg-surface-hover': '#1e293b', + '--border-subtle': 'rgba(255, 255, 255, 0.08)', + '--border-highlight': 'rgba(16, 185, 129, 0.3)', + '--text-primary': '#f8fafc', + '--text-secondary': '#94a3b8', + '--text-muted': '#64748b', + '--accent-primary': '#10b981', + '--accent-hover': '#059669', + '--accent-glow': 'rgba(16, 185, 129, 0.2)', + '--accent-lime': '#84cc16', + '--accent-lime-glow': 'rgba(132, 204, 22, 0.25)', + '--status-active': '#34d399', + '--status-inactive': '#64748b', + '--status-warning': '#f59e0b', + '--status-danger': '#f43f5e' + } + }, + 'cyberpunk-neon': { + id: 'cyberpunk-neon', + name: 'Cyberpunk Neon', + description: 'Púrpura profundo con luces neón magenta y cian eléctrico', + colors: { + '--bg-app': '#0a0514', + '--bg-surface': '#140c26', + '--bg-surface-elevated': '#1f133a', + '--bg-surface-hover': '#2d1b54', + '--border-subtle': 'rgba(217, 70, 239, 0.15)', + '--border-highlight': 'rgba(217, 70, 239, 0.45)', + '--text-primary': '#fdf4ff', + '--text-secondary': '#d8b4fe', + '--text-muted': '#a855f7', + '--accent-primary': '#d946ef', + '--accent-hover': '#c026d3', + '--accent-glow': 'rgba(217, 70, 239, 0.25)', + '--accent-lime': '#06b6d4', + '--accent-lime-glow': 'rgba(6, 182, 212, 0.3)', + '--status-active': '#06b6d4', + '--status-inactive': '#6b7280', + '--status-warning': '#fbbf24', + '--status-danger': '#f43f5e' + } + }, + 'midnight-sapphire': { + id: 'midnight-sapphire', + name: 'Midnight Sapphire', + description: 'Azul cobalto ultra profundo con destellos celestes y glaseado suave', + colors: { + '--bg-app': '#050b14', + '--bg-surface': '#0b1626', + '--bg-surface-elevated': '#10223b', + '--bg-surface-hover': '#172f52', + '--border-subtle': 'rgba(56, 189, 248, 0.12)', + '--border-highlight': 'rgba(56, 189, 248, 0.4)', + '--text-primary': '#f0f9ff', + '--text-secondary': '#93c5fd', + '--text-muted': '#60a5fa', + '--accent-primary': '#38bdf8', + '--accent-hover': '#0284c7', + '--accent-glow': 'rgba(56, 189, 248, 0.25)', + '--accent-lime': '#22d3ee', + '--accent-lime-glow': 'rgba(34, 211, 238, 0.25)', + '--status-active': '#38bdf8', + '--status-inactive': '#64748b', + '--status-warning': '#fbbf24', + '--status-danger': '#f87171' + } + }, + 'tokyo-night': { + id: 'tokyo-night', + name: 'Tokyo Night', + description: 'Gris azulado oscuro moderno inspirado en IDEs contemporáneos', + colors: { + '--bg-app': '#1a1b26', + '--bg-surface': '#24283b', + '--bg-surface-elevated': '#2f354f', + '--bg-surface-hover': '#3b4261', + '--border-subtle': 'rgba(255, 255, 255, 0.08)', + '--border-highlight': 'rgba(122, 162, 247, 0.35)', + '--text-primary': '#c0caf5', + '--text-secondary': '#a9b1d6', + '--text-muted': '#565f89', + '--accent-primary': '#7aa2f7', + '--accent-hover': '#5e8ff7', + '--accent-glow': 'rgba(122, 162, 247, 0.25)', + '--accent-lime': '#7dcfff', + '--accent-lime-glow': 'rgba(125, 207, 255, 0.25)', + '--status-active': '#9ece6a', + '--status-inactive': '#565f89', + '--status-warning': '#e0af68', + '--status-danger': '#f7768e' + } + }, + 'monochrome-minimal': { + id: 'monochrome-minimal', + name: 'Monochrome Minimal', + description: 'Negro puro, contrastes de alta fidelidad en escala de grises y acentos blancos', + colors: { + '--bg-app': '#000000', + '--bg-surface': '#111111', + '--bg-surface-elevated': '#1c1c1c', + '--bg-surface-hover': '#2a2a2a', + '--border-subtle': 'rgba(255, 255, 255, 0.12)', + '--border-highlight': 'rgba(255, 255, 255, 0.35)', + '--text-primary': '#ffffff', + '--text-secondary': '#cccccc', + '--text-muted': '#888888', + '--accent-primary': '#ffffff', + '--accent-hover': '#e5e5e5', + '--accent-glow': 'rgba(255, 255, 255, 0.2)', + '--accent-lime': '#cccccc', + '--accent-lime-glow': 'rgba(200, 200, 200, 0.2)', + '--status-active': '#4ade80', + '--status-inactive': '#525252', + '--status-warning': '#facc15', + '--status-danger': '#ef4444' + } + }, + 'solar-amber': { + id: 'solar-amber', + name: 'Solar Amber', + description: 'Tonos carbón cálidos con acentos ámbar dorado y naranja industrial', + colors: { + '--bg-app': '#0f0c08', + '--bg-surface': '#1c1710', + '--bg-surface-elevated': '#2b2318', + '--bg-surface-hover': '#3a3022', + '--border-subtle': 'rgba(245, 158, 11, 0.12)', + '--border-highlight': 'rgba(245, 158, 11, 0.4)', + '--text-primary': '#fffbeb', + '--text-secondary': '#fde68a', + '--text-muted': '#d97706', + '--accent-primary': '#f59e0b', + '--accent-hover': '#d97706', + '--accent-glow': 'rgba(245, 158, 11, 0.25)', + '--accent-lime': '#f97316', + '--accent-lime-glow': 'rgba(249, 115, 22, 0.25)', + '--status-active': '#10b981', + '--status-inactive': '#78716c', + '--status-warning': '#f59e0b', + '--status-danger': '#ef4444' + } + } +}; + +export const DEFAULT_IDENTITY = { + appName: 'a2host', + panelTitle: 'Panel de Subdominios y Proyectos', + slogan: 'Apache2 Web & Subdomain Orchestrator', + baseDomain: config.baseDomain || 'elingejose.com', + footerText: '© 2026 a2host — Servidor VPS Ubuntu elingejose.com', + gitUrl: 'http://git.elingejose.com/GeronimoGc/a2host.git', + logoIcon: 'server', + primaryColor: '#10b981', + themePreset: 'obsidian-emerald' +}; + +export class SettingsService { + constructor(filePath) { + this.filePath = filePath || path.resolve(process.cwd(), 'data/settings.json'); + this.identity = { ...DEFAULT_IDENTITY }; + this.activeThemeId = 'obsidian-emerald'; + this.customThemes = {}; + this.initialized = false; + } + + async init() { + const parentDir = path.dirname(this.filePath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + if (fs.existsSync(this.filePath)) { + try { + const raw = fs.readFileSync(this.filePath, 'utf-8'); + const data = JSON.parse(raw); + if (data.identity) this.identity = { ...DEFAULT_IDENTITY, ...data.identity }; + if (data.activeThemeId) this.activeThemeId = data.activeThemeId; + if (data.customThemes) this.customThemes = data.customThemes; + } catch { + this.saveSync(); + } + } else { + this.saveSync(); + } + + this.initialized = true; + return this; + } + + saveSync() { + const parentDir = path.dirname(this.filePath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + const payload = { + identity: this.identity, + activeThemeId: this.activeThemeId, + customThemes: this.customThemes, + updatedAt: new Date().toISOString() + }; + + const tmpPath = `${this.filePath}.tmp.${Date.now()}_${process.pid}_${crypto.randomBytes(4).toString('hex')}`; + fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), 'utf-8'); + fs.renameSync(tmpPath, this.filePath); + } + + getIdentity() { + return { ...this.identity }; + } + + updateIdentity(partial) { + if (!partial || typeof partial !== 'object') { + const error = new Error('Payload de identidad inválido.'); + error.status = 400; + throw error; + } + + const sanitized = {}; + if (partial.appName !== undefined) sanitized.appName = String(partial.appName).trim().slice(0, 50); + if (partial.panelTitle !== undefined) sanitized.panelTitle = String(partial.panelTitle).trim().slice(0, 100); + if (partial.slogan !== undefined) sanitized.slogan = String(partial.slogan).trim().slice(0, 150); + if (partial.baseDomain !== undefined) sanitized.baseDomain = String(partial.baseDomain).trim().toLowerCase().slice(0, 100); + if (partial.footerText !== undefined) sanitized.footerText = String(partial.footerText).trim().slice(0, 200); + if (partial.gitUrl !== undefined) sanitized.gitUrl = String(partial.gitUrl).trim().slice(0, 255); + if (partial.logoIcon !== undefined) sanitized.logoIcon = String(partial.logoIcon).trim().slice(0, 50); + if (partial.primaryColor !== undefined) sanitized.primaryColor = String(partial.primaryColor).trim().slice(0, 30); + if (partial.themePreset !== undefined) sanitized.themePreset = String(partial.themePreset).trim(); + + this.identity = { ...this.identity, ...sanitized }; + this.saveSync(); + return this.getIdentity(); + } + + getThemesList() { + const list = Object.values(DEFAULT_THEMES).map((t) => ({ ...t, isCustom: false })); + const customs = Object.values(this.customThemes).map((t) => ({ ...t, isCustom: true })); + return [...list, ...customs]; + } + + getActiveTheme() { + if (this.customThemes[this.activeThemeId]) { + return { ...this.customThemes[this.activeThemeId], isCustom: true }; + } + if (DEFAULT_THEMES[this.activeThemeId]) { + return { ...DEFAULT_THEMES[this.activeThemeId], isCustom: false }; + } + return { ...DEFAULT_THEMES['obsidian-emerald'], isCustom: false }; + } + + setActiveTheme(themeId) { + if (!DEFAULT_THEMES[themeId] && !this.customThemes[themeId]) { + const error = new Error(`El tema '${themeId}' no existe.`); + error.status = 404; + throw error; + } + + this.activeThemeId = themeId; + this.identity.themePreset = themeId; + this.saveSync(); + return this.getActiveTheme(); + } + + saveCustomTheme(themeData) { + if (!themeData || !themeData.id || !themeData.colors || typeof themeData.colors !== 'object') { + const error = new Error('Estructura de tema JSON inválida. Debe incluir "id", "name" y "colors".'); + error.status = 400; + throw error; + } + + const cleanId = String(themeData.id).trim().toLowerCase().replace(/[^a-z0-9-]/g, '-'); + const customTheme = { + id: cleanId, + name: String(themeData.name || cleanId).slice(0, 50), + description: String(themeData.description || 'Tema personalizado').slice(0, 150), + colors: { ...themeData.colors }, + isCustom: true, + updatedAt: new Date().toISOString() + }; + + this.customThemes[cleanId] = customTheme; + this.saveSync(); + return customTheme; + } + + importThemeJson(jsonString) { + let parsed; + try { + parsed = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString; + } catch { + const error = new Error('JSON de tema inválido o corrupto.'); + error.status = 400; + throw error; + } + + return this.saveCustomTheme(parsed); + } + + exportActiveThemeJson() { + return this.getActiveTheme(); + } + + resetTheme() { + this.activeThemeId = 'obsidian-emerald'; + this.identity.themePreset = 'obsidian-emerald'; + this.saveSync(); + return this.getActiveTheme(); + } +} + +export const defaultSettingsService = new SettingsService(); +defaultSettingsService.init().catch(() => {}); +export default defaultSettingsService; diff --git a/src/services/terminal.service.js b/src/services/terminal.service.js index 39c0660..fe06c7e 100644 --- a/src/services/terminal.service.js +++ b/src/services/terminal.service.js @@ -1,11 +1,14 @@ -import { execFile } from 'node:child_process'; +import { execFile, spawn } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; +import crypto from 'node:crypto'; import config from '../config/env.js'; +import { signSession, verifySession } from '../utils/crypto.util.js'; export class TerminalService { constructor(defaultCwd) { this.defaultCwd = defaultCwd || config.webRoot; + this.terminalSessions = new Map(); // token -> { vpsUser, expiresAt } } getShellBinary() { @@ -14,35 +17,186 @@ export class TerminalService { } /** - * Ejecuta un comando en el servidor con aislamiento y límites de recursos. - * @param {string} command Comando bash a ejecutar - * @param {object} [options] - * @param {string} [options.cwd] Directorio de trabajo - * @returns {Promise} { stdout, stderr, exitCode, executionTimeMs, cwd } + * Autentica las credenciales de un usuario del sistema operativo (Linux VPS) + * @param {string} vpsUser Nombre del usuario en el VPS (ej. ggc, root, etc.) + * @param {string} vpsPassword Contraseña del usuario en el VPS + * @returns {Promise} { success: true, vpsUser, terminalToken } */ - async executeCommand(command, { cwd } = {}) { + async authenticateVpsUser(vpsUser, vpsPassword) { + const cleanUser = String(vpsUser || '').trim(); + if (!cleanUser || !/^[a-z0-9_-]{1,32}$/i.test(cleanUser)) { + const error = new Error('Nombre de usuario del VPS inválido.'); + error.status = 400; + throw error; + } + + if (!vpsPassword || typeof vpsPassword !== 'string') { + const error = new Error('Se requiere la contraseña del usuario del VPS.'); + error.status = 400; + throw error; + } + + const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/etc/passwd'); + + if (isMock) { + // En modo mock / desarrollo / testing: aceptar usuarios de prueba + if (cleanUser === 'invalid_user') { + const error = new Error(`Usuario del VPS '${cleanUser}' no existe en el sistema.`); + error.status = 401; + throw error; + } + if (vpsPassword === 'wrong_password') { + const error = new Error('Contraseña del usuario del VPS incorrecta.'); + error.status = 401; + throw error; + } + } else { + // En entorno real Ubuntu Linux: validar credenciales vía autenticación del sistema + const isValid = await this.verifySystemCredentials(cleanUser, vpsPassword); + if (!isValid) { + const error = new Error(`Credenciales incorrectas para el usuario '${cleanUser}' en el VPS.`); + error.status = 401; + error.code = 'INVALID_VPS_CREDENTIALS'; + throw error; + } + } + + const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2 horas + const payload = { + vpsUser: cleanUser, + expiresAt, + type: 'vps_terminal_session' + }; + + const terminalToken = signSession(payload, config.sessionSecret); + this.terminalSessions.set(terminalToken, { vpsUser: cleanUser, expiresAt }); + + let homeDir = `/home/${cleanUser}`; + if (cleanUser === 'root') homeDir = '/root'; + if (!fs.existsSync(homeDir)) homeDir = this.defaultCwd; + if (!fs.existsSync(homeDir)) homeDir = process.cwd(); + + return { + success: true, + vpsUser: cleanUser, + homeDir, + terminalToken, + expiresAt + }; + } + + /** + * Valida credenciales contra el sistema Linux usando su / sudo no interactivo + */ + async verifySystemCredentials(username, password) { + return new Promise((resolve) => { + // Intentar validar contraseña usando child_process + const child = spawn('su', ['-', username, '-c', 'echo AUTH_OK'], { + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stdout = ''; + let stderr = ''; + + child.stdout.on('data', (d) => { stdout += d.toString(); }); + child.stderr.on('data', (d) => { stderr += d.toString(); }); + + child.on('close', (code) => { + if (code === 0 && stdout.includes('AUTH_OK')) { + return resolve(true); + } + + // Si falló su, intentar con sudo si el usuario corre bajo ggc con sudoers + const sudoChild = spawn('sudo', ['-S', '-u', username, 'echo', 'AUTH_OK'], { + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let sudoOut = ''; + sudoChild.stdout.on('data', (d) => { sudoOut += d.toString(); }); + + sudoChild.on('close', (sudoCode) => { + if (sudoCode === 0 && sudoOut.includes('AUTH_OK')) { + return resolve(true); + } + resolve(false); + }); + + sudoChild.stdin.write(`${password}\n`); + sudoChild.stdin.end(); + }); + + child.stdin.write(`${password}\n`); + child.stdin.end(); + }); + } + + /** + * Verifica la validez de un token de sesión de terminal + */ + verifyTerminalToken(terminalToken) { + if (!terminalToken) return null; + const payload = verifySession(terminalToken, config.sessionSecret); + if (!payload || !payload.vpsUser || payload.type !== 'vps_terminal_session') { + return null; + } + if (payload.expiresAt && payload.expiresAt < Date.now()) { + return null; + } + return payload; + } + + /** + * Ejecuta un comando en el servidor bajo el usuario autenticado del VPS. + * @param {string} command Comando bash a ejecutar + * @param {object} options + * @param {string} [options.cwd] Directorio de trabajo + * @param {string} [options.terminalToken] Token de sesión autenticado del usuario VPS + * @returns {Promise} { stdout, stderr, exitCode, executionTimeMs, cwd, vpsUser } + */ + async executeCommand(command, { cwd, terminalToken } = {}) { if (!command || typeof command !== 'string') { - const error = new Error("El parámetro 'command' es obligatorio y debe ser una cadena de texto."); + const error = new Error("El parámetro 'command' es obligatorio."); error.status = 400; error.code = 'INVALID_COMMAND'; throw error; } - let effectiveCwd = cwd || this.defaultCwd; - if (!fs.existsSync(effectiveCwd)) { - effectiveCwd = this.defaultCwd; - } - if (!fs.existsSync(effectiveCwd)) { - effectiveCwd = process.cwd(); + const session = this.verifyTerminalToken(terminalToken); + if (!session) { + const error = new Error('Se requiere autenticación con credenciales del usuario del VPS para usar la terminal.'); + error.status = 401; + error.code = 'TERMINAL_AUTH_REQUIRED'; + throw error; } + const vpsUser = session.vpsUser; + let effectiveCwd = cwd; + + if (!effectiveCwd || !fs.existsSync(effectiveCwd)) { + let homeDir = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`; + if (!fs.existsSync(homeDir)) homeDir = this.defaultCwd; + if (!fs.existsSync(homeDir)) homeDir = process.cwd(); + effectiveCwd = homeDir; + } + + const isMock = config.mockApache || process.env.NODE_ENV === 'test' || !fs.existsSync('/bin/bash'); const shell = this.getShellBinary(); const startTime = Date.now(); return new Promise((resolve) => { + let runCmd = command; + let args = ['-c', runCmd]; + let execBinary = shell; + + if (!isMock && vpsUser !== (config.systemUser || 'ggc')) { + // Ejecutar bajo el usuario autenticado del VPS + execBinary = 'sudo'; + args = ['-u', vpsUser, shell, '-c', command]; + } + execFile( - shell, - ['-c', command], + execBinary, + args, { timeout: 30000, maxBuffer: 2 * 1024 * 1024, @@ -74,38 +228,35 @@ export class TerminalService { stderr: errStr, exitCode, executionTimeMs, - cwd: effectiveCwd + cwd: effectiveCwd, + vpsUser }); } ); }); } - /** - * Retorna información contextual del entorno para la terminal. - * @returns {object} - */ - getTerminalInfo() { - let username = config.systemUser || 'ggc'; - try { - const userInfo = os.userInfo(); - if (userInfo && userInfo.username) { - username = userInfo.username; - } - } catch { - // Ignorar en entornos restringidos - } + getTerminalInfo(terminalToken) { + const session = this.verifyTerminalToken(terminalToken); + const authenticated = Boolean(session); + const vpsUser = session ? session.vpsUser : null; - let effectiveCwd = this.defaultCwd; - if (!fs.existsSync(effectiveCwd)) { - effectiveCwd = process.cwd(); + let defaultDir = this.defaultCwd; + if (vpsUser) { + let home = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`; + if (fs.existsSync(home)) defaultDir = home; + } + if (!fs.existsSync(defaultDir)) { + defaultDir = process.cwd(); } return { - user: username, - cwd: effectiveCwd, + authenticated, + user: vpsUser, + cwd: defaultDir, hostname: os.hostname(), - shell: this.getShellBinary() + shell: this.getShellBinary(), + instructions: 'Para utilizar la terminal, ingrese sus credenciales de usuario del sistema operativo del VPS.' }; } } diff --git a/test/integration/new-endpoints.test.js b/test/integration/new-endpoints.test.js index 88e632f..5c85477 100644 --- a/test/integration/new-endpoints.test.js +++ b/test/integration/new-endpoints.test.js @@ -277,12 +277,33 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)' }); describe('3. Remote Web Terminal API (/api/terminal)', () => { + let terminalToken = null; + + it('POST /api/terminal/login - Administrador autentica con credenciales de usuario del VPS (200)', async () => { + const res = await fetch(`${baseUrl}/api/terminal/login`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Cookie: adminCookie + }, + body: JSON.stringify({ vpsUser: 'ggc', vpsPassword: 'valid_password' }) + }); + + assert.equal(res.status, 200); + const data = await res.json(); + assert.equal(data.success, true); + assert.equal(data.vpsUser, 'ggc'); + assert.ok(data.terminalToken); + terminalToken = data.terminalToken; + }); + it('POST /api/terminal/execute - Operador debe ser rechazado con 403 Forbidden', async () => { const res = await fetch(`${baseUrl}/api/terminal/execute`, { method: 'POST', headers: { 'Content-Type': 'application/json', - Cookie: operatorCookie + Cookie: operatorCookie, + 'x-terminal-token': terminalToken }, body: JSON.stringify({ command: 'whoami' }) }); @@ -290,12 +311,13 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)' assert.equal(res.status, 403); }); - it('POST /api/terminal/execute - Administrador puede ejecutar comandos y recibir output (200)', async () => { + it('POST /api/terminal/execute - Administrador puede ejecutar comandos con token de usuario VPS (200)', async () => { const res = await fetch(`${baseUrl}/api/terminal/execute`, { method: 'POST', headers: { 'Content-Type': 'application/json', - Cookie: adminCookie + Cookie: adminCookie, + 'x-terminal-token': terminalToken }, body: JSON.stringify({ command: 'echo "a2host terminal execution test"' }) }); @@ -310,13 +332,16 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)' it('GET /api/terminal/info - Debe retornar información del entorno de shell (200)', async () => { const res = await fetch(`${baseUrl}/api/terminal/info`, { - headers: { Cookie: adminCookie } + headers: { + Cookie: adminCookie, + 'x-terminal-token': terminalToken + } }); assert.equal(res.status, 200); const data = await res.json(); - assert.equal(data.success, true); - assert.ok(data.user); + assert.equal(data.authenticated, true); + assert.equal(data.user, 'ggc'); assert.ok(data.cwd); assert.ok(data.hostname); assert.ok(data.shell); diff --git a/test/unit/projects-and-settings.test.js b/test/unit/projects-and-settings.test.js new file mode 100644 index 0000000..8c4986e --- /dev/null +++ b/test/unit/projects-and-settings.test.js @@ -0,0 +1,168 @@ +import { describe, it, before } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { SettingsService, DEFAULT_THEMES, DEFAULT_IDENTITY } from '../../src/services/settings.service.js'; +import { ProjectService } from '../../src/services/project.service.js'; +import { FtpService } from '../../src/services/ftp.service.js'; + +describe('Unit Tests: Settings, Projects and FTP Services', () => { + describe('1. SettingsService', () => { + const testSettingsPath = './.tmp/test_settings_clean.json'; + const settings = new SettingsService(testSettingsPath); + + before(() => { + if (fs.existsSync(testSettingsPath)) { + fs.unlinkSync(testSettingsPath); + } + }); + + it('debe inicializar y retornar la identidad por defecto', async () => { + await settings.init(); + const identity = settings.getIdentity(); + + assert.equal(identity.appName, 'a2host'); + assert.ok(identity.panelTitle); + assert.ok(identity.baseDomain); + }); + + it('debe actualizar campos de identidad del sistema', () => { + const updated = settings.updateIdentity({ + appName: 'MiHost VPS', + slogan: 'Orquestador Profesional Apache2' + }); + + assert.equal(updated.appName, 'MiHost VPS'); + assert.equal(updated.slogan, 'Orquestador Profesional Apache2'); + }); + + it('debe listar temas predefinidos y permitir activar un tema', () => { + const list = settings.getThemesList(); + assert.ok(list.length >= 6); + + const active = settings.setActiveTheme('cyberpunk-neon'); + assert.equal(active.id, 'cyberpunk-neon'); + }); + + it('debe guardar, exportar e importar temas en formato JSON', () => { + const customTheme = { + id: 'aurora-borealis', + name: 'Aurora Borealis', + description: 'Tema personalizado verde y violeta', + colors: { + '--bg-app': '#031014', + '--accent-primary': '#22d3ee' + } + }; + + const saved = settings.saveCustomTheme(customTheme); + assert.equal(saved.id, 'aurora-borealis'); + assert.equal(saved.isCustom, true); + + const exported = settings.exportActiveThemeJson(); + assert.ok(exported.id); + + const imported = settings.importThemeJson(JSON.stringify({ + id: 'neon-synth', + name: 'Neon Synth', + colors: { '--bg-app': '#110022' } + })); + assert.equal(imported.id, 'neon-synth'); + }); + + it('debe restaurar tema por defecto', () => { + const def = settings.resetTheme(); + assert.equal(def.id, 'obsidian-emerald'); + }); + }); + + describe('2. ProjectService', () => { + const projectService = new ProjectService({ filePath: './.tmp/test_projects.json' }); + + it('debe crear un proyecto con subdominios y carpeta pública personalizada en /var/www', async () => { + await projectService.init(); + + const created = await projectService.createProject({ + name: 'ecommerce-app', + title: 'Tienda Electrónica', + type: 'static', + publicFolder: 'public', + subdomains: ['tienda', 'shop'] + }); + + assert.equal(created.name, 'ecommerce-app'); + assert.equal(created.publicFolder, 'public'); + assert.ok(created.subdomains.includes('tienda')); + assert.ok(created.subdomains.includes('shop')); + assert.ok(created.effectiveDocRoot.endsWith('ecommerce-app/public')); + }); + + it('debe listar proyectos con metadatos de disco', async () => { + const list = await projectService.listProjects(); + assert.ok(list.length >= 1); + const proj = list.find((p) => p.name === 'ecommerce-app'); + assert.ok(proj); + assert.ok(proj.rootDirectory); + }); + + it('debe permitir añadir y remover subdominios de un proyecto', async () => { + const updated = await projectService.addSubdomain('ecommerce-app', 'checkout'); + assert.ok(updated.subdomains.includes('checkout')); + + const removed = await projectService.removeSubdomain('ecommerce-app', 'checkout'); + assert.ok(!removed.subdomains.includes('checkout')); + }); + + it('debe actualizar subcarpeta pública y puerto del proyecto', async () => { + const updated = await projectService.updateProject('ecommerce-app', { + publicFolder: 'dist', + title: 'Tienda V2' + }); + + assert.equal(updated.publicFolder, 'dist'); + assert.equal(updated.title, 'Tienda V2'); + }); + + it('debe eliminar proyecto y sus VirtualHosts asociados', async () => { + const res = await projectService.deleteProject('ecommerce-app', { deleteFiles: false }); + assert.equal(res.name, 'ecommerce-app'); + }); + }); + + describe('3. FtpService', () => { + const ftpService = new FtpService('./.tmp/test_ftp.json'); + + it('debe retornar datos de conexión SFTP y FTP', () => { + const info = ftpService.getConnectionInfo(); + assert.ok(info.host); + assert.ok(info.sftpPort); + assert.ok(info.baseRoot); + }); + + it('debe crear, listar, actualizar y eliminar cuentas FTP', async () => { + await ftpService.init(); + + const account = await ftpService.createAccount({ + username: 'dev_tienda', + password: 'secure_password_123', + project: 'test-site', + permission: 'rw' + }); + + assert.equal(account.username, 'dev_tienda'); + assert.equal(account.project, 'test-site'); + + const list = await ftpService.listAccounts(); + assert.ok(list.some((a) => a.username === 'dev_tienda')); + + const updated = await ftpService.updateAccount(account.id, { + permission: 'ro', + active: false + }); + assert.equal(updated.permission, 'ro'); + assert.equal(updated.active, false); + + const deleted = await ftpService.deleteAccount(account.id); + assert.equal(deleted, true); + }); + }); +}); diff --git a/test/unit/terminal-service.test.js b/test/unit/terminal-service.test.js index 462519c..47470fd 100644 --- a/test/unit/terminal-service.test.js +++ b/test/unit/terminal-service.test.js @@ -5,34 +5,73 @@ import { TerminalService } from '../../src/services/terminal.service.js'; describe('Unit Tests: Terminal Service (terminal.service.js)', () => { const terminalService = new TerminalService(process.cwd()); - it('debe ejecutar comandos exitosos y capturar stdout, exitCode 0 y tiempo de ejecución', async () => { - const result = await terminalService.executeCommand('echo "Hello Terminal"'); + it('debe autenticar credenciales de usuario del VPS y emitir token de terminal', async () => { + const authResult = await terminalService.authenticateVpsUser('ggc', 'test_password'); + + assert.equal(authResult.success, true); + assert.equal(authResult.vpsUser, 'ggc'); + assert.ok(authResult.terminalToken); + assert.ok(authResult.homeDir); + }); + + it('debe rechazar autenticación de terminal si el usuario no existe', async () => { + await assert.rejects( + async () => terminalService.authenticateVpsUser('invalid_user', 'password'), + (err) => { + assert.equal(err.status, 401); + return true; + } + ); + }); + + it('debe rechazar ejecución de comandos si no se proporciona terminalToken válido', async () => { + await assert.rejects( + async () => terminalService.executeCommand('echo test'), + (err) => { + assert.equal(err.status, 401); + assert.equal(err.code, 'TERMINAL_AUTH_REQUIRED'); + return true; + } + ); + }); + + it('debe ejecutar comandos con terminalToken válido y capturar stdout y exitCode 0', async () => { + const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const result = await terminalService.executeCommand('echo "Hello VPS Terminal"', { + terminalToken: auth.terminalToken + }); assert.equal(result.exitCode, 0); - assert.ok(result.stdout.includes('Hello Terminal')); + assert.ok(result.stdout.includes('Hello VPS Terminal')); assert.equal(result.stderr, ''); + assert.equal(result.vpsUser, 'ggc'); assert.equal(typeof result.executionTimeMs, 'number'); - assert.ok(result.executionTimeMs >= 0); - assert.ok(result.cwd); }); it('debe capturar errores de ejecución con su exitCode sin lanzar excepción no controlada', async () => { - const result = await terminalService.executeCommand('sh -c "exit 42"'); + const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const result = await terminalService.executeCommand('sh -c "exit 42"', { + terminalToken: auth.terminalToken + }); assert.equal(result.exitCode, 42); assert.equal(typeof result.executionTimeMs, 'number'); }); it('debe capturar stderr de comandos erróneos', async () => { - const result = await terminalService.executeCommand('ls /non-existent-directory-xyz-123'); + const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const result = await terminalService.executeCommand('ls /non-existent-directory-xyz-123', { + terminalToken: auth.terminalToken + }); assert.notEqual(result.exitCode, 0); assert.ok(result.stderr.length > 0); }); it('debe rechazar comandos nulos o vacíos con error 400', async () => { + const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); await assert.rejects( - async () => terminalService.executeCommand(''), + async () => terminalService.executeCommand('', { terminalToken: auth.terminalToken }), (err) => { assert.equal(err.status, 400); assert.equal(err.code, 'INVALID_COMMAND'); @@ -41,12 +80,16 @@ describe('Unit Tests: Terminal Service (terminal.service.js)', () => { ); }); - it('getTerminalInfo: debe retornar usuario, cwd, hostname y shell', () => { - const info = terminalService.getTerminalInfo(); + it('getTerminalInfo: debe retornar estado de autenticación y datos de shell', async () => { + const unauthInfo = terminalService.getTerminalInfo(); + assert.equal(unauthInfo.authenticated, false); - assert.ok(info.user); - assert.ok(info.cwd); - assert.ok(info.hostname); - assert.ok(info.shell); + const auth = await terminalService.authenticateVpsUser('ggc', 'valid'); + const authInfo = terminalService.getTerminalInfo(auth.terminalToken); + + assert.equal(authInfo.authenticated, true); + assert.equal(authInfo.user, 'ggc'); + assert.ok(authInfo.hostname); + assert.ok(authInfo.shell); }); });