fix(sheets-import): increase express payload limit to 50MB and add comprehensive incident diagnosis and system error audit
This commit is contained in:
+201
-23
@@ -68,9 +68,9 @@ app.post('/auth/login', authLimiter);
|
||||
app.post('/auth/moodle', authLimiter);
|
||||
app.use('/api', generalLimiter);
|
||||
|
||||
// Configuración de middlewares
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
// Configuración de middlewares con soporte para importaciones masivas y payloads extensos
|
||||
app.use(express.json({ limit: '50mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
|
||||
app.use(cookieParser());
|
||||
|
||||
// Configuración de archivos estáticos
|
||||
@@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
||||
});
|
||||
|
||||
// Versiones institucionales del sistema
|
||||
const APP_VERSION = '3.4.8';
|
||||
const FRONTEND_VERSION = '3.4.8';
|
||||
const BACKEND_VERSION = '3.4.8';
|
||||
const APP_VERSION = '3.4.9';
|
||||
const FRONTEND_VERSION = '3.4.9';
|
||||
const BACKEND_VERSION = '3.4.9';
|
||||
|
||||
env.addGlobal('app_version', APP_VERSION);
|
||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||
@@ -587,37 +587,215 @@ app.use((req, res) => {
|
||||
`);
|
||||
});
|
||||
|
||||
// Middleware Global de Error 500
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('Error no capturado en BFF:', err);
|
||||
res.status(500).send(`
|
||||
// Middleware Global de Error 500 & Diagnóstico Institucional
|
||||
app.use(async (err, req, res, next) => {
|
||||
const incidentId = 'INC-' + new Date().toISOString().slice(0, 10).replace(/-/g, '') + '-' + Math.random().toString(36).substring(2, 7).toUpperCase();
|
||||
const timestampStr = new Date().toLocaleString('es-AR', { timeZone: 'America/Argentina/Buenos_Aires' });
|
||||
const userEmail = req.user?.email || (req.cookies?.refresh_token ? 'Usuario con sesión activa' : 'No autenticado');
|
||||
const reqPath = `${req.method} ${req.originalUrl || req.url}`;
|
||||
const clientIp = req.headers['x-forwarded-for'] || req.ip || req.socket?.remoteAddress || '-';
|
||||
|
||||
console.error(`[BFF Error ${incidentId}] en ${reqPath}:`, err);
|
||||
|
||||
// Clasificación y mensaje amigable
|
||||
let statusCode = err.status || err.statusCode || 500;
|
||||
let errorTitle = 'Eventualidad en la Aplicación';
|
||||
let errorSummary = 'Ocurrió un error inesperado al procesar la operación solicitada.';
|
||||
let errorResolution = 'Por favor intente nuevamente o comuníquese con Soporte / Bedelía indicando el código de incidente.';
|
||||
|
||||
if (err.type === 'entity.too.large' || statusCode === 413) {
|
||||
statusCode = 413;
|
||||
errorTitle = 'Tamaño de Datos Excedido (Payload Too Large)';
|
||||
const lengthKb = err.length ? (err.length / 1024).toFixed(1) + ' KB' : 'desconocido';
|
||||
const limitKb = err.limit ? (err.limit / 1024).toFixed(1) + ' KB' : 'desconocido';
|
||||
errorSummary = `El volumen de datos enviado (${lengthKb}) superó la capacidad de recepción configurada (${limitKb}).`;
|
||||
errorResolution = 'Si está importando planillas masivas de Google Sheets, aplique filtros por día o carrera, o solicite a Soporte que amplíe el límite de transferencia.';
|
||||
} else if (err.code === 'ECONNREFUSED' || err.code === 'ETIMEDOUT') {
|
||||
statusCode = 503;
|
||||
errorTitle = 'Fallo de Comunicación con Backend Core';
|
||||
errorSummary = 'No fue posible conectarse con la API central de Edu-Space en el puerto 5000.';
|
||||
errorResolution = 'El servicio backend podría estar reiniciándose o en mantenimiento. Aguarde unos segundos y vuelva a intentar.';
|
||||
} else if (err.response && err.response.data) {
|
||||
errorTitle = `Respuesta del Servidor Central (${err.response.status})`;
|
||||
errorSummary = err.response.data.message || err.response.data.error || err.message;
|
||||
errorResolution = 'Revise los parámetros ingresados o consulte el registro de auditoría si posee permisos de administrador.';
|
||||
} else if (err.message) {
|
||||
errorSummary = err.message;
|
||||
}
|
||||
|
||||
// Registro asíncrono no bloqueante en AuditLog del backend
|
||||
try {
|
||||
const backendBase = process.env.BACKEND_URL || 'http://localhost:5000/api/v1';
|
||||
axios.post(`${backendBase}/admin/log-error`, {
|
||||
incident_id: incidentId,
|
||||
error_title: errorTitle,
|
||||
error_message: err.message || errorSummary,
|
||||
status_code: statusCode,
|
||||
path: reqPath,
|
||||
user_email: userEmail,
|
||||
ip_address: clientIp,
|
||||
stack: err.stack ? err.stack.slice(0, 1000) : null
|
||||
}, { timeout: 3000 }).catch(() => {});
|
||||
} catch (_) {}
|
||||
|
||||
// Si la petición espera JSON, responder en JSON estructurado
|
||||
if (req.xhr || (req.headers.accept && req.headers.accept.includes('application/json'))) {
|
||||
return res.status(statusCode).json({
|
||||
status: 'error',
|
||||
incident_id: incidentId,
|
||||
title: errorTitle,
|
||||
message: errorSummary,
|
||||
resolution: errorResolution,
|
||||
path: reqPath,
|
||||
timestamp: timestampStr
|
||||
});
|
||||
}
|
||||
|
||||
// Renderizar pantalla institucional de diagnóstico
|
||||
res.status(statusCode).send(`
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Error del Sistema — Edu-Space</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Error del Sistema — Edu-Space UniCABA</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
||||
<style>
|
||||
body { background: #0f172a; color: #f8fafc; font-family: system-ui, -apple-system, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; margin: 0; }
|
||||
.card-error { background: #1e293b; border: 1px solid #334155; border-radius: 16px; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5); }
|
||||
:root { --bs-body-bg: #0f172a; --bs-body-color: #f8fafc; }
|
||||
body { background: #0f172a; color: #f8fafc; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 1.5rem; }
|
||||
.card-diagnostic { background: #1e293b; border: 1px solid #334155; border-radius: 16px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.7); max-width: 760px; width: 100%; }
|
||||
.code-box { background: #0b1120; border: 1px solid #334155; color: #38bdf8; border-radius: 8px; font-family: monospace; font-size: 0.85rem; }
|
||||
.incident-badge { background: #3b82f6; color: white; letter-spacing: 0.05em; font-family: monospace; }
|
||||
.accordion-button { background: #1e293b; color: #94a3b8; }
|
||||
.accordion-button:not(.collapsed) { background: #0f172a; color: #f8fafc; }
|
||||
.accordion-item { border-color: #334155; background: transparent; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container text-center p-4" style="max-width: 520px;">
|
||||
<div class="card card-error p-4 p-md-5">
|
||||
<div class="mb-3 text-danger">
|
||||
<i class="bi bi-exclamation-triangle-fill fs-1"></i>
|
||||
<div class="card card-diagnostic p-4 p-md-5">
|
||||
<!-- Header con branding institucional -->
|
||||
<div class="d-flex align-items-center justify-content-between border-bottom border-secondary pb-3 mb-4 flex-wrap gap-2">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span class="fs-4 fw-bold text-primary">Edu-Space</span>
|
||||
<span class="badge bg-secondary-subtle text-secondary border border-secondary font-monospace">UniCABA</span>
|
||||
</div>
|
||||
<h1 class="h3 fw-bold mb-2">Error en la Aplicación</h1>
|
||||
<p class="text-secondary small mb-4">
|
||||
Ocurrió una eventualidad procesando la solicitud. Nuestro equipo técnico ha sido notificado.
|
||||
<div>
|
||||
<span class="badge incident-badge px-3 py-2 rounded-pill fs-6" id="badgeIncidentId">
|
||||
<i class="bi bi-ticket-perforated me-1"></i>${incidentId}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Título y síntesis del incidente -->
|
||||
<div class="text-center mb-4">
|
||||
<div class="mb-3">
|
||||
<span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-danger-subtle text-danger p-3" style="width: 64px; height: 64px;">
|
||||
<i class="bi bi-exclamation-triangle-fill fs-2"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="d-flex align-items-center justify-content-center gap-2 mb-2">
|
||||
<span class="badge bg-danger">HTTP ${statusCode}</span>
|
||||
<h1 class="h4 fw-bold mb-0 text-white">${errorTitle}</h1>
|
||||
</div>
|
||||
<p class="text-light fs-6 mb-2 text-start bg-dark p-3 rounded border border-secondary-subtle">
|
||||
<i class="bi bi-info-circle text-info me-2"></i>${errorSummary}
|
||||
</p>
|
||||
<a href="/dashboard" class="btn btn-primary px-4 fw-semibold">
|
||||
<i class="bi bi-house-door me-1"></i>Volver al Panel
|
||||
</a>
|
||||
<p class="text-secondary small mb-0 text-start">
|
||||
<strong>Acción recomendada:</strong> ${errorResolution}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Sección colapsable de Diagnóstico Técnico -->
|
||||
<div class="accordion mb-4" id="diagnosticAccordion">
|
||||
<div class="accordion-item rounded overflow-hidden">
|
||||
<h2 class="accordion-header" id="headingOne">
|
||||
<button class="accordion-button collapsed py-2 small fw-semibold" type="button" data-bs-toggle="collapse" data-bs-target="#collapseDiag" aria-expanded="false" aria-controls="collapseDiag">
|
||||
<i class="bi bi-cpu me-2"></i>Detalles Técnicos y Diagnóstico del Servidor
|
||||
</button>
|
||||
</h2>
|
||||
<div id="collapseDiag" class="accordion-collapse collapse" aria-labelledby="headingOne" data-bs-parent="#diagnosticAccordion">
|
||||
<div class="accordion-body p-3 bg-dark">
|
||||
<div class="row g-2 small mb-3">
|
||||
<div class="col-sm-6">
|
||||
<span class="text-secondary">Ruta / Solicitud:</span>
|
||||
<div class="font-monospace text-light">${reqPath}</div>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<span class="text-secondary">Fecha y Hora:</span>
|
||||
<div class="font-monospace text-light">${timestampStr}</div>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<span class="text-secondary">Usuario Actuante:</span>
|
||||
<div class="font-monospace text-light">${userEmail}</div>
|
||||
</div>
|
||||
<div class="col-sm-6">
|
||||
<span class="text-secondary">Dirección IP:</span>
|
||||
<div class="font-monospace text-light">${clientIp}</div>
|
||||
</div>
|
||||
</div>
|
||||
<label class="text-secondary small fw-bold mb-1">Traza de Error (Stack Trace):</label>
|
||||
<pre class="code-box p-3 mb-0" style="max-height: 180px; overflow-y: auto;">${(err.stack || err.message || 'Sin traza disponible').replace(/</g, '<').replace(/>/g, '>')}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Acciones Rápidas y Copia de Reporte -->
|
||||
<div class="d-flex flex-wrap gap-2 justify-content-between align-items-center pt-2 border-top border-secondary">
|
||||
<div class="d-flex gap-2 flex-wrap">
|
||||
<button type="button" class="btn btn-outline-info btn-sm fw-semibold" onclick="copyDiagnosticReport()">
|
||||
<i class="bi bi-clipboard-check me-1"></i>Copiar Reporte para Soporte
|
||||
</button>
|
||||
<a href="/admin/audit_logs" class="btn btn-outline-secondary btn-sm">
|
||||
<i class="bi bi-shield-check me-1"></i>Ver Auditoría
|
||||
</a>
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="button" class="btn btn-secondary btn-sm" onclick="history.back()">
|
||||
<i class="bi bi-arrow-left me-1"></i>Atrás
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-light btn-sm" onclick="location.reload()">
|
||||
<i class="bi bi-arrow-clockwise me-1"></i>Reintentar
|
||||
</button>
|
||||
<a href="/dashboard" class="btn btn-primary btn-sm fw-semibold">
|
||||
<i class="bi bi-house-door me-1"></i>Panel Principal
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
function copyDiagnosticReport() {
|
||||
const report = [
|
||||
'=== REPORTE DE INCIDENTE EDU-SPACE (UniCABA) ===',
|
||||
'Código: ' + '${incidentId}',
|
||||
'Fecha/Hora: ' + '${timestampStr}',
|
||||
'Estado HTTP: ' + '${statusCode}',
|
||||
'Título: ' + '${errorTitle}',
|
||||
'Resumen: ' + '${errorSummary.replace(/'/g, "\\'")}',
|
||||
'Ruta Solicitada: ' + '${reqPath}',
|
||||
'Usuario: ' + '${userEmail}',
|
||||
'IP Cliente: ' + '${clientIp}',
|
||||
'Error Stack:',
|
||||
'${(err.stack || err.message || '').replace(/'/g, "\\'").replace(/\n/g, '\\n')}',
|
||||
'=================================================='
|
||||
].join('\\n');
|
||||
|
||||
navigator.clipboard.writeText(report).then(() => {
|
||||
alert('Reporte copiado al portapapeles. Puede pegarlo y enviarlo al equipo de Soporte IT o Bedelía.');
|
||||
}).catch(() => {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = report;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(ta);
|
||||
alert('Reporte copiado al portapapeles.');
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`);
|
||||
|
||||
Reference in New Issue
Block a user