const https = require('https'); const http = require('http'); const ENDPOINT = process.env.ERROR_REPORTING_URL || 'https://api.siax-system.net/api/errores'; const API_KEY = process.env.WEBCONTROL_API_KEY || ''; const APP_ORIGEN = 'Help Desk'; const VERSION = '1.0.0'; // Deduplicación en memoria: evitar inundar el endpoint con el mismo error repetido const cacheErrores = new Map(); const THROTTLE_MS = 10 * 60 * 1000; // 10 minutos /** * Reporta un error de runtime hacia API-SIGMA-WEBCONTROL (POST https://api.siax-system.net/api/errores) */ async function reportarError({ mensaje, detalle = '', categoria = 'sistema', // red, bd, auth, validacion, sistema, desconocido nivel = 'error', codigo = null, clase = null, metodo = null, usuario = null, cuenta = null }) { try { if (!mensaje) return; // Control de throttle por firma const firma = `${categoria}:${mensaje}:${codigo || ''}`; const ahora = Date.now(); const ultimoEnvio = cacheErrores.get(firma); if (ultimoEnvio && (ahora - ultimoEnvio) < THROTTLE_MS) { console.log(`[errorReporter] Error en ventana de throttle (${firma}), ignorando duplicado.`); return; } cacheErrores.set(firma, ahora); if (!API_KEY) { console.warn(`[errorReporter] WEBCONTROL_API_KEY no configurada. Error no enviado a ${ENDPOINT}: ${mensaje}`); return; } const payload = JSON.stringify({ app_origen: APP_ORIGEN, mensaje: String(mensaje).substring(0, 500), detalle: typeof detalle === 'object' ? JSON.stringify(detalle, null, 2) : String(detalle || ''), categoria, nivel, codigo: codigo ? String(codigo) : null, clase, metodo, usuario, cuenta, entorno: process.env.NODE_ENV || 'development', version: VERSION, fecha_evento: new Date().toISOString() }); const url = new URL(ENDPOINT); const client = url.protocol === 'https:' ? https : http; const options = { hostname: url.hostname, port: url.port || (url.protocol === 'https:' ? 443 : 80), path: url.pathname + url.search, method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload), 'x-api-key': API_KEY }, timeout: 5000 }; const req = client.request(options, (res) => { let body = ''; res.on('data', (d) => body += d); res.on('end', () => { if (res.statusCode >= 200 && res.statusCode < 300) { console.log(`[errorReporter] Error reportado exitosamente (${res.statusCode}): ${mensaje}`); } else { console.warn(`[errorReporter] Fallo al reportar a ${ENDPOINT}: HTTP ${res.statusCode} - ${body}`); } }); }); req.on('error', (e) => { console.warn(`[errorReporter] Error de conexión al reportar a la bitácora:`, e.message); }); req.on('timeout', () => { req.destroy(); console.warn(`[errorReporter] Timeout al conectar con ${ENDPOINT}`); }); req.write(payload); req.end(); } catch (err) { console.error(`[errorReporter] Excepción en reporter:`, err.message); } } /** * Consulta errores reportados por esta app en API-SIGMA-WEBCONTROL (GET https://api.siax-system.net/api/errores) */ async function consultarErrores({ page = 1, limit = 20, categoria = null } = {}) { return new Promise((resolve, reject) => { if (!API_KEY) { return reject(new Error('WEBCONTROL_API_KEY no configurada en las variables de entorno.')); } const url = new URL(ENDPOINT); url.searchParams.set('app_origen', APP_ORIGEN); url.searchParams.set('page', String(page)); url.searchParams.set('limit', String(limit)); if (categoria) url.searchParams.set('categoria', categoria); const client = url.protocol === 'https:' ? https : http; const options = { hostname: url.hostname, port: url.port || (url.protocol === 'https:' ? 443 : 80), path: url.pathname + url.search, method: 'GET', headers: { 'Accept': 'application/json', 'x-api-key': API_KEY }, timeout: 10000 }; const req = client.request(options, (res) => { let data = ''; res.on('data', (chunk) => data += chunk); res.on('end', () => { try { const json = JSON.parse(data); resolve({ statusCode: res.statusCode, data: json }); } catch (e) { resolve({ statusCode: res.statusCode, raw: data }); } }); }); req.on('error', reject); req.on('timeout', () => { req.destroy(); reject(new Error('Timeout al consultar API de errores')); }); req.end(); }); } module.exports = { reportarError, consultarErrores, APP_ORIGEN };