a2host/public/js/api.js

460 lines
12 KiB
JavaScript

/**
* a2host - API Client (ES Module)
* Gestiona peticiones REST contra el backend Express con credenciales HttpOnly,
* decodificación RFC 7807 (Problem Details) y redirección automática ante 401.
*/
export class ApiError extends Error {
/**
* @param {string} message
* @param {number} status
* @param {object} problemData
*/
constructor(message, status = 500, problemData = {}) {
super(message);
this.name = 'ApiError';
this.status = status;
this.title = problemData.title || 'Error del Servidor';
this.detail = problemData.detail || message;
this.code = problemData.code || 'UNKNOWN_ERROR';
this.rollbackExecuted = Boolean(problemData.rollbackExecuted);
this.type = problemData.type || null;
this.timestamp = problemData.timestamp || new Date().toISOString();
}
}
class ApiClient {
constructor(baseUrl = '/api') {
this.baseUrl = baseUrl;
}
/**
* Realiza una petición HTTP fetch asegurando cabeceras y decodificación
* @param {string} endpoint
* @param {RequestInit} options
* @returns {Promise<any>}
*/
async request(endpoint, options = {}) {
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 || {})
};
if (options.body && typeof options.body === 'object' && !(options.body instanceof FormData)) {
headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(options.body);
}
const config = {
...options,
headers,
credentials: 'same-origin' // Envía la cookie HttpOnly a2host_session
};
let response;
try {
response = await fetch(url, config);
} catch (networkError) {
throw new ApiError(
'No se pudo conectar con el servidor a2host. Verifique la conexión.',
0,
{ title: 'Error de Red', code: 'NETWORK_ERROR', detail: networkError.message }
);
}
// 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;
}
let responseData = null;
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json') || contentType.includes('application/problem+json')) {
try {
responseData = await response.json();
} catch {
responseData = null;
}
} else {
const textData = await response.text();
responseData = { message: textData };
}
if (!response.ok) {
const detail = responseData?.detail || responseData?.message || `HTTP ${response.status} ${response.statusText}`;
const title = responseData?.title || 'Error en la solicitud';
throw new ApiError(detail, response.status, responseData || { detail, title });
}
return responseData;
}
// --- Auth Endpoints ---
async login(credentials) {
const res = await this.request('/auth/login', {
method: 'POST',
body: credentials
});
if (res && res.token && typeof sessionStorage !== 'undefined') {
sessionStorage.setItem('a2host_token', res.token);
}
return res;
}
async logout() {
try {
await this.request('/auth/logout', {
method: 'POST'
});
} finally {
if (typeof sessionStorage !== 'undefined') {
sessionStorage.removeItem('a2host_token');
}
}
}
async getMe() {
return this.request('/auth/me', {
method: 'GET'
});
}
// --- Subdomains Endpoints ---
async getSubdomains() {
return this.request('/subdomains', { method: 'GET' });
}
async getSubdomain(name) {
return this.request(`/subdomains/${encodeURIComponent(name)}`, { method: 'GET' });
}
async validateSubdomain(name, data) {
return this.request(`/subdomains/${encodeURIComponent(name)}/validate`, {
method: 'POST',
body: data
});
}
async createSubdomain(data) {
return this.request('/subdomains', {
method: 'POST',
body: data
});
}
async updateSubdomain(name, data) {
return this.request(`/subdomains/${encodeURIComponent(name)}`, {
method: 'PUT',
body: data
});
}
async toggleSubdomain(name, enabled) {
return this.request(`/subdomains/${encodeURIComponent(name)}/toggle`, {
method: 'POST',
body: { enabled }
});
}
async deleteSubdomain(name, deleteFiles = false) {
const query = deleteFiles ? '?deleteFiles=true' : '';
return this.request(`/subdomains/${encodeURIComponent(name)}${query}`, {
method: 'DELETE'
});
}
// --- Folders Endpoints ---
async getFolders() {
return this.request('/folders', { method: 'GET' });
}
async getFolderFiles(name, path = '') {
const query = path ? `?path=${encodeURIComponent(path)}` : '';
return this.request(`/folders/${encodeURIComponent(name)}/files${query}`, { method: 'GET' });
}
async getFileContent(name, path) {
return this.request(`/folders/${encodeURIComponent(name)}/file?path=${encodeURIComponent(path)}`, {
method: 'GET'
});
}
async saveFileContent(name, path, content) {
return this.request(`/folders/${encodeURIComponent(name)}/file`, {
method: 'PUT',
body: { path, content }
});
}
async uploadFile(name, path, fileName, base64Content) {
return this.request(`/folders/${encodeURIComponent(name)}/upload`, {
method: 'POST',
body: { path, fileName, base64Content }
});
}
async createFolderItem(name, path, itemName, type) {
return this.request(`/folders/${encodeURIComponent(name)}/item`, {
method: 'POST',
body: { path, name: itemName, type }
});
}
async deleteFolderItem(name, path) {
return this.request(`/folders/${encodeURIComponent(name)}/item?path=${encodeURIComponent(path)}`, {
method: 'DELETE'
});
}
// --- 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',
body: { command, cwd }
});
}
// --- System Stats & Processes Endpoints ---
async getSystemStats() {
return this.request('/system/stats', { method: 'GET' });
}
async getSystemProcesses() {
return this.request('/system/processes', { method: 'GET' });
}
// --- Resource Cleaner & Maintenance Endpoints ---
async cleanRam() {
return this.request('/system/clean-ram', { method: 'POST' });
}
async cleanDisk() {
return this.request('/system/clean-disk', { method: 'POST' });
}
async getDiskBreakdown() {
return this.request('/system/disk-breakdown', { method: 'GET' });
}
async killProcess(pid, signal = 'SIGTERM') {
return this.request('/system/process/kill', {
method: 'POST',
body: { pid, signal }
});
}
async restartSystemService(serviceName) {
return this.request('/system/service/restart', {
method: 'POST',
body: { serviceName }
});
}
async getFirewallStatus() {
return this.request('/system/firewall', { method: 'GET' });
}
// --- Users Endpoints ---
async getUsers() {
return this.request('/users', { method: 'GET' });
}
async createUser(userData) {
return this.request('/users', {
method: 'POST',
body: userData
});
}
async updateUser(id, userData) {
return this.request(`/users/${encodeURIComponent(id)}`, {
method: 'PUT',
body: userData
});
}
async deleteUser(id) {
return this.request(`/users/${encodeURIComponent(id)}`, {
method: 'DELETE'
});
}
// --- Docs Endpoints ---
async getDocs() {
return this.request('/docs', { method: 'GET' });
}
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();
export default api;