/** * 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} */ async request(endpoint, options = {}) { const url = `${this.baseUrl}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`; const token = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('a2host_token') : null; const headers = { 'Accept': 'application/json, application/problem+json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}), ...(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 la página de login, redirigir if (response.status === 401 && !window.location.pathname.endsWith('login.html')) { 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 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) { return this.request(`/folders/${encodeURIComponent(name)}/files`, { method: 'GET' }); } // --- System Stats Endpoint --- async getSystemStats() { return this.request('/system/stats', { 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' }); } } export const api = new ApiClient(); export default api;