feat: add Projects module, FTP management with ZIP extraction, VPS credentialed Terminal, and full Settings with custom JSON themes

This commit is contained in:
GeronimoGc 2026-11-20 09:52:37 -05:00
parent aa6bd6c9f3
commit a2c4df71b3
21 changed files with 5091 additions and 214 deletions

View File

@ -2119,3 +2119,878 @@
border-radius: var(--radius-sm); border-radius: var(--radius-sm);
box-shadow: 0 0 10px rgba(168, 85, 247, 0.2); box-shadow: 0 0 10px rgba(168, 85, 247, 0.2);
} }
/* ==========================================================================
Módulo 1: Proyectos Web (/var/www/<proyecto>)
========================================================================== */
.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);
}

File diff suppressed because it is too large Load Diff

View File

@ -38,9 +38,11 @@ class ApiClient {
const url = `${this.baseUrl}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`; const url = `${this.baseUrl}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`;
const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('a2host_token') : null; const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('a2host_token') : null;
const terminalToken = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('a2host_terminal_token') : null;
const headers = { const headers = {
'Accept': 'application/json, application/problem+json', 'Accept': 'application/json, application/problem+json',
...(token ? { 'Authorization': `Bearer ${token}` } : {}), ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
...(terminalToken ? { 'x-terminal-token': terminalToken } : {}),
...(options.headers || {}) ...(options.headers || {})
}; };
@ -66,8 +68,13 @@ class ApiClient {
); );
} }
// Si es 401 y no estamos en la página de login, redirigir // 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')) { if (
response.status === 401 &&
!window.location.pathname.endsWith('login.html') &&
!endpoint.includes('/terminal/') &&
!endpoint.includes('/auth/login')
) {
window.location.href = '/login.html'; window.location.href = '/login.html';
return; 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 --- // --- Terminal Endpoints ---
async getTerminalInfo() { async getTerminalInfo() {
return this.request('/terminal/info', { method: 'GET' }); 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) { async executeCommand(command, cwd) {
return this.request('/terminal/execute', { return this.request('/terminal/execute', {
method: 'POST', method: 'POST',
@ -266,6 +377,51 @@ class ApiClient {
async getDoc(docId) { async getDoc(docId) {
return this.request(`/docs/${encodeURI(docId)}`, { method: 'GET' }); 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(); export const api = new ApiClient();

File diff suppressed because it is too large Load Diff

View File

@ -32,12 +32,32 @@ class StateStore {
content: '', content: '',
isDirty: false 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, terminalInfo: null,
terminalHistory: [], terminalHistory: [],
monitorProcesses: [], monitorProcesses: [],
monitorIntervalId: null, monitorIntervalId: null,
// Users & Settings
users: [], users: [],
usersLoading: false, usersLoading: false,
settingsSubtab: 'users', // 'users' | 'themes' | 'identity'
themes: [],
activeThemeId: 'obsidian-emerald',
activeTheme: null,
identity: null,
stats: null, stats: null,
docs: [], docs: [],
selectedDoc: null, selectedDoc: null,

View File

@ -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;

View File

@ -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;

View File

@ -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;

View File

@ -6,20 +6,45 @@ export class TerminalController {
this.terminalService = terminalService || defaultTerminalService; this.terminalService = terminalService || defaultTerminalService;
} }
execute = async (req, res, next) => { getInfo = async (req, res, next) => {
try { try {
const { command, cwd } = req.body || {}; const token = req.headers['x-terminal-token'] || req.query.terminalToken;
const result = await this.terminalService.executeCommand(command, { cwd }); const info = this.terminalService.getTerminalInfo(token);
return sendSuccess(res, 200, result); return res.json(info);
} catch (err) { } catch (err) {
next(err); next(err);
} }
}; };
info = async (req, res, next) => { login = async (req, res, next) => {
try { try {
const info = this.terminalService.getTerminalInfo(); const { vpsUser, vpsPassword } = req.body || {};
return sendSuccess(res, 200, info); 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) { } catch (err) {
next(err); next(err);
} }

20
src/routes/ftp.routes.js Normal file
View File

@ -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();

View File

@ -6,17 +6,23 @@ import folderRoutes from './folder.routes.js';
import systemRoutes from './system.routes.js'; import systemRoutes from './system.routes.js';
import docsRoutes from './docs.routes.js'; import docsRoutes from './docs.routes.js';
import terminalRoutes from './terminal.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() { export function createApiRouter() {
const router = Router(); const router = Router();
router.use('/auth', authRoutes); router.use('/auth', authRoutes);
router.use('/subdomains', subdomainRoutes); router.use('/subdomains', subdomainRoutes);
router.use('/projects', projectRoutes);
router.use('/ftp', ftpRoutes);
router.use('/users', userRoutes); router.use('/users', userRoutes);
router.use('/folders', folderRoutes); router.use('/folders', folderRoutes);
router.use('/system', systemRoutes); router.use('/system', systemRoutes);
router.use('/docs', docsRoutes); router.use('/docs', docsRoutes);
router.use('/terminal', terminalRoutes); router.use('/terminal', terminalRoutes);
router.use('/settings', settingsRoutes);
return router; return router;
} }

View File

@ -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();

View File

@ -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();

View File

@ -2,15 +2,17 @@ import { Router } from 'express';
import defaultTerminalController from '../controllers/terminal.controller.js'; import defaultTerminalController from '../controllers/terminal.controller.js';
import { authenticate, requireRole } from '../middlewares/auth.middleware.js'; import { authenticate, requireRole } from '../middlewares/auth.middleware.js';
export function createTerminalRoutes(terminalController = defaultTerminalController) { export function createTerminalRoutes(controller = defaultTerminalController) {
const router = Router(); 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(authenticate);
router.use(requireRole('admin')); router.use(requireRole('admin'));
router.post('/execute', terminalController.execute); router.get('/info', controller.getInfo);
router.get('/info', terminalController.info); router.post('/login', controller.login);
router.post('/logout', controller.logout);
router.post('/execute', controller.execute);
return router; return router;
} }

247
src/services/ftp.service.js Normal file
View File

@ -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()}/<proyecto>'.`
};
}
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/<project>/<relativePath>
* 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'), '<h1>Extracted Sample</h1>', '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;

View File

@ -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/<projectName>
*/
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 = `<VirtualHost *:80>
ServerName ${subdomain}.${config.baseDomain}
DocumentRoot ${docRoot}
<Directory ${docRoot}>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
DirectoryIndex index.php index.html index.htm
</Directory>
ErrorLog \${APACHE_LOG_DIR}/${subdomain}_error.log
CustomLog \${APACHE_LOG_DIR}/${subdomain}_access.log combined
</VirtualHost>
`;
} else {
confContent = `<VirtualHost *:80>
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
</VirtualHost>
`;
}
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/<name>
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;

View File

@ -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;

View File

@ -1,11 +1,14 @@
import { execFile } from 'node:child_process'; import { execFile, spawn } from 'node:child_process';
import fs from 'node:fs'; import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import crypto from 'node:crypto';
import config from '../config/env.js'; import config from '../config/env.js';
import { signSession, verifySession } from '../utils/crypto.util.js';
export class TerminalService { export class TerminalService {
constructor(defaultCwd) { constructor(defaultCwd) {
this.defaultCwd = defaultCwd || config.webRoot; this.defaultCwd = defaultCwd || config.webRoot;
this.terminalSessions = new Map(); // token -> { vpsUser, expiresAt }
} }
getShellBinary() { getShellBinary() {
@ -14,35 +17,186 @@ export class TerminalService {
} }
/** /**
* Ejecuta un comando en el servidor con aislamiento y límites de recursos. * Autentica las credenciales de un usuario del sistema operativo (Linux VPS)
* @param {string} command Comando bash a ejecutar * @param {string} vpsUser Nombre del usuario en el VPS (ej. ggc, root, etc.)
* @param {object} [options] * @param {string} vpsPassword Contraseña del usuario en el VPS
* @param {string} [options.cwd] Directorio de trabajo * @returns {Promise<object>} { success: true, vpsUser, terminalToken }
* @returns {Promise<object>} { stdout, stderr, exitCode, executionTimeMs, cwd }
*/ */
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<object>} { stdout, stderr, exitCode, executionTimeMs, cwd, vpsUser }
*/
async executeCommand(command, { cwd, terminalToken } = {}) {
if (!command || typeof command !== 'string') { 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.status = 400;
error.code = 'INVALID_COMMAND'; error.code = 'INVALID_COMMAND';
throw error; throw error;
} }
let effectiveCwd = cwd || this.defaultCwd; const session = this.verifyTerminalToken(terminalToken);
if (!fs.existsSync(effectiveCwd)) { if (!session) {
effectiveCwd = this.defaultCwd; const error = new Error('Se requiere autenticación con credenciales del usuario del VPS para usar la terminal.');
} error.status = 401;
if (!fs.existsSync(effectiveCwd)) { error.code = 'TERMINAL_AUTH_REQUIRED';
effectiveCwd = process.cwd(); 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 shell = this.getShellBinary();
const startTime = Date.now(); const startTime = Date.now();
return new Promise((resolve) => { return new Promise((resolve) => {
let runCmd = command;
let args = ['-c', runCmd];
let execBinary = shell;
if (!isMock && vpsUser !== (config.systemUser || 'ggc')) {
// Ejecutar bajo el usuario autenticado del VPS
execBinary = 'sudo';
args = ['-u', vpsUser, shell, '-c', command];
}
execFile( execFile(
shell, execBinary,
['-c', command], args,
{ {
timeout: 30000, timeout: 30000,
maxBuffer: 2 * 1024 * 1024, maxBuffer: 2 * 1024 * 1024,
@ -74,38 +228,35 @@ export class TerminalService {
stderr: errStr, stderr: errStr,
exitCode, exitCode,
executionTimeMs, executionTimeMs,
cwd: effectiveCwd cwd: effectiveCwd,
vpsUser
}); });
} }
); );
}); });
} }
/** getTerminalInfo(terminalToken) {
* Retorna información contextual del entorno para la terminal. const session = this.verifyTerminalToken(terminalToken);
* @returns {object} const authenticated = Boolean(session);
*/ const vpsUser = session ? session.vpsUser : null;
getTerminalInfo() {
let username = config.systemUser || 'ggc';
try {
const userInfo = os.userInfo();
if (userInfo && userInfo.username) {
username = userInfo.username;
}
} catch {
// Ignorar en entornos restringidos
}
let effectiveCwd = this.defaultCwd; let defaultDir = this.defaultCwd;
if (!fs.existsSync(effectiveCwd)) { if (vpsUser) {
effectiveCwd = process.cwd(); let home = vpsUser === 'root' ? '/root' : `/home/${vpsUser}`;
if (fs.existsSync(home)) defaultDir = home;
}
if (!fs.existsSync(defaultDir)) {
defaultDir = process.cwd();
} }
return { return {
user: username, authenticated,
cwd: effectiveCwd, user: vpsUser,
cwd: defaultDir,
hostname: os.hostname(), hostname: os.hostname(),
shell: this.getShellBinary() shell: this.getShellBinary(),
instructions: 'Para utilizar la terminal, ingrese sus credenciales de usuario del sistema operativo del VPS.'
}; };
} }
} }

View File

@ -277,12 +277,33 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)'
}); });
describe('3. Remote Web Terminal API (/api/terminal)', () => { describe('3. Remote Web Terminal API (/api/terminal)', () => {
let terminalToken = null;
it('POST /api/terminal/login - 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 () => { it('POST /api/terminal/execute - Operador debe ser rechazado con 403 Forbidden', async () => {
const res = await fetch(`${baseUrl}/api/terminal/execute`, { const res = await fetch(`${baseUrl}/api/terminal/execute`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Cookie: operatorCookie Cookie: operatorCookie,
'x-terminal-token': terminalToken
}, },
body: JSON.stringify({ command: 'whoami' }) body: JSON.stringify({ command: 'whoami' })
}); });
@ -290,12 +311,13 @@ describe('Integration Tests: Extended Backend Endpoints (new-endpoints.test.js)'
assert.equal(res.status, 403); assert.equal(res.status, 403);
}); });
it('POST /api/terminal/execute - Administrador puede ejecutar comandos 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`, { const res = await fetch(`${baseUrl}/api/terminal/execute`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Cookie: adminCookie Cookie: adminCookie,
'x-terminal-token': terminalToken
}, },
body: JSON.stringify({ command: 'echo "a2host terminal execution test"' }) body: JSON.stringify({ command: 'echo "a2host terminal execution test"' })
}); });
@ -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 () => { it('GET /api/terminal/info - Debe retornar información del entorno de shell (200)', async () => {
const res = await fetch(`${baseUrl}/api/terminal/info`, { const res = await fetch(`${baseUrl}/api/terminal/info`, {
headers: { Cookie: adminCookie } headers: {
Cookie: adminCookie,
'x-terminal-token': terminalToken
}
}); });
assert.equal(res.status, 200); assert.equal(res.status, 200);
const data = await res.json(); const data = await res.json();
assert.equal(data.success, true); assert.equal(data.authenticated, true);
assert.ok(data.user); assert.equal(data.user, 'ggc');
assert.ok(data.cwd); assert.ok(data.cwd);
assert.ok(data.hostname); assert.ok(data.hostname);
assert.ok(data.shell); assert.ok(data.shell);

View File

@ -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);
});
});
});

View File

@ -5,34 +5,73 @@ import { TerminalService } from '../../src/services/terminal.service.js';
describe('Unit Tests: Terminal Service (terminal.service.js)', () => { describe('Unit Tests: Terminal Service (terminal.service.js)', () => {
const terminalService = new TerminalService(process.cwd()); const terminalService = new TerminalService(process.cwd());
it('debe ejecutar comandos exitosos y capturar stdout, exitCode 0 y tiempo de ejecución', async () => { it('debe autenticar credenciales de usuario del VPS y emitir token de terminal', async () => {
const result = await terminalService.executeCommand('echo "Hello Terminal"'); 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.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.stderr, '');
assert.equal(result.vpsUser, 'ggc');
assert.equal(typeof result.executionTimeMs, 'number'); 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 () => { 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(result.exitCode, 42);
assert.equal(typeof result.executionTimeMs, 'number'); assert.equal(typeof result.executionTimeMs, 'number');
}); });
it('debe capturar stderr de comandos erróneos', async () => { it('debe capturar stderr de comandos erróneos', async () => {
const 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.notEqual(result.exitCode, 0);
assert.ok(result.stderr.length > 0); assert.ok(result.stderr.length > 0);
}); });
it('debe rechazar comandos nulos o vacíos con error 400', async () => { it('debe rechazar comandos nulos o vacíos con error 400', async () => {
const auth = await terminalService.authenticateVpsUser('ggc', 'valid');
await assert.rejects( await assert.rejects(
async () => terminalService.executeCommand(''), async () => terminalService.executeCommand('', { terminalToken: auth.terminalToken }),
(err) => { (err) => {
assert.equal(err.status, 400); assert.equal(err.status, 400);
assert.equal(err.code, 'INVALID_COMMAND'); 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', () => { it('getTerminalInfo: debe retornar estado de autenticación y datos de shell', async () => {
const info = terminalService.getTerminalInfo(); const unauthInfo = terminalService.getTerminalInfo();
assert.equal(unauthInfo.authenticated, false);
assert.ok(info.user); const auth = await terminalService.authenticateVpsUser('ggc', 'valid');
assert.ok(info.cwd); const authInfo = terminalService.getTerminalInfo(auth.terminalToken);
assert.ok(info.hostname);
assert.ok(info.shell); assert.equal(authInfo.authenticated, true);
assert.equal(authInfo.user, 'ggc');
assert.ok(authInfo.hostname);
assert.ok(authInfo.shell);
}); });
}); });