273 lines
7.3 KiB
JavaScript
273 lines
7.3 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 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 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'
|
|
});
|
|
}
|
|
|
|
// --- Terminal Endpoints ---
|
|
async getTerminalInfo() {
|
|
return this.request('/terminal/info', { method: 'GET' });
|
|
}
|
|
|
|
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' });
|
|
}
|
|
|
|
// --- 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;
|