Files
dashcaddy/status/js/live-events.js
Krystie e99413150e
CI / Test & Lint (push) Canceled after 0s
CI / Security audit (push) Canceled after 0s
[glm-grade=B] fix: dead dashboard WS, corrupted error.log, auth-polling storm, re-auth freeze + CVE bumps
Adversarial audit 2026-08-16 (GLM-5.3 delegate, 2 rounds, 141 tool calls):

P0-1: Dashboard WebSocket (/api/v1/ws) dead on EVERY boot since DC-076.
server.js passed module exports (DependencyManager class, {AutoRestartManager}
namespace, SSLMonitor class) instead of createApp()'s live instances — first
.on() threw ERR_INVALID_ARG_TYPE, catch swallowed it. Fix: app.locals.ctx
exposed in src/app.js; server.js passes all 8 real EventEmitter instances.

P0-2: error.log corrupted since 2026-07-14. errorMiddleware called
logError(FILE, SIZE, path, err, meta) — 5 args into a 3-arg wrapper —
logging 'Error: 5242880' garbage every ~60s and DISCARDING the real error
object. Fix: correct 3-arg call + legacy-shape guard in logErrorWrapper +
~74 log.error sites swept to pass real error objects (AST-verified scope-
safe 71/71, 29/29 modules load clean).

P0-3: auth-polling storm (stranded grade=B commit never landed in prod):
401/403 behind TOTP gate hammered /api/v1/services/status + SSE reconnect
every 2-8s, with misleading direct-probe fallback marking services 'up'.
Fix landed + B-round MEDIUM follow-up: TOTP re-auth success now clears
_dcAuthLost, resumes SSE (new _sseResume clears the latch), and refreshes.

Also: eslintignore static-sites/ (33→0 errors); nodemailer 8→9.0.5 and
sharp 0.33→0.35.3 (3 high CVEs killed; jest green on new majors);
dockerode@5/uuid deferred (semver-major, Docker API surface).

Verification: 80/80 suites, 1837/1837 tests; ESLint 0 errors/743 warnings;
node --check all changed files; bundles rebuilt + SW cache bumped.

Judges: Codex quota-dead until Aug 19 (verified live) — GLM adversarial
delegate per operator directive 2026-08-07. Round 1: 98-call mechanical
verification (timed out pre-verdict). Round 2 (this grade): B, one MEDIUM
(re-auth freeze) — fixed in this commit as prescribed.
2026-08-16 04:18:07 -07:00

151 lines
5.2 KiB
JavaScript

// ========== LIVE DASHBOARD EVENTS (SSE) ==========
(function() {
let es = null;
let reconnectDelay = 1000;
const MAX_RECONNECT = 30000;
let _sseFailCount = 0;
let _sseManuallyClosed = false;
function connect() {
if (es) { try { es.close(); } catch (_) {} }
if (_sseManuallyClosed) return; // auth-lost: don't reconnect
es = new EventSource('/api/v1/events/stream');
es.addEventListener('connected', () => {
reconnectDelay = 1000; // reset backoff
_sseFailCount = 0; // reset failure counter
debug('[SSE] Connected to event stream');
});
// Health status changes → update card dots/badges in real time
es.addEventListener('status-change', (e) => {
try {
const d = JSON.parse(e.data);
if (d.serviceId && typeof window.setBadge === 'function') {
const up = d.status === 'up' || d.status === 'healthy';
window.setBadge(d.serviceId, up, d.responseTime || null);
}
} catch (_) {}
});
// Resource alerts → toast notification
es.addEventListener('resource-alert', (e) => {
try {
const d = JSON.parse(e.data);
const msg = `${d.containerName || d.containerId}: ${d.metric} at ${d.value}% (threshold: ${d.threshold}%)`;
if (typeof showNotification === 'function') {
showNotification(msg, 'warning');
}
} catch (_) {}
});
// Container auto-restart
es.addEventListener('auto-restart', (e) => {
try {
const d = JSON.parse(e.data);
if (typeof showNotification === 'function') {
showNotification(`Container "${d.containerName}" was auto-restarted`, 'info');
}
} catch (_) {}
});
// Update available → show notification dot on Updates button
es.addEventListener('update-available', (e) => {
try {
const d = JSON.parse(e.data);
const updatesBtn = document.getElementById('updates-btn');
if (updatesBtn && !updatesBtn.querySelector('.sse-dot')) {
const dot = document.createElement('span');
dot.className = 'sse-dot';
dot.style.cssText = 'display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--accent);margin-left:6px;vertical-align:middle;';
updatesBtn.appendChild(dot);
}
if (typeof showNotification === 'function') {
showNotification(`Update available for ${d.containerName || d.containerId}`, 'info');
}
} catch (_) {}
});
// Update start/complete/failed
es.addEventListener('update-complete', (e) => {
try {
const d = JSON.parse(e.data);
if (typeof showNotification === 'function') {
showNotification(`Update completed: ${d.containerName || d.containerId}`, 'success');
}
// Trigger a dashboard refresh
if (typeof window.refreshAll === 'function') window.refreshAll();
} catch (_) {}
});
es.addEventListener('update-failed', (e) => {
try {
const d = JSON.parse(e.data);
if (typeof showNotification === 'function') {
showNotification(`Update failed: ${d.containerName || d.containerId}${d.error || 'unknown error'}`, 'error');
}
} catch (_) {}
});
// Incidents
es.addEventListener('incident', (e) => {
try {
const d = JSON.parse(e.data);
if (typeof showNotification === 'function') {
if (d.type === 'created') {
showNotification(`Incident: ${d.message || d.serviceId}`, 'error');
} else if (d.type === 'resolved') {
showNotification(`Resolved: ${d.serviceId || 'incident'}`, 'success');
}
}
} catch (_) {}
});
// Reconnect on error
es.onerror = () => {
es.close();
// If auth was explicitly lost (401/403 from the polling loop),
// don't attempt reconnection at all.
if (window._dcAuthLost || _sseManuallyClosed) {
console.warn('[SSE] Auth lost — stopping reconnection');
return;
}
// Transient failures: retry with exponential backoff, stop after 5
_sseFailCount++;
if (_sseFailCount > 5) {
console.warn('[SSE] Max reconnect attempts reached — stopping (server unreachable)');
return;
}
console.warn(`[SSE] Disconnected, reconnecting in ${reconnectDelay / 1000}s...`);
setTimeout(connect, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT);
};
}
// Called by grid.js when the polling loop detects auth loss (401/403)
function closeAndStop() {
_sseManuallyClosed = true;
if (es) { try { es.close(); } catch (_) {} }
}
// Called by totp-auth.js after a successful mid-session re-auth:
// clears the latch so connect() can proceed again and resets the
// failure backoff. (Plain _sseReconnect/connect() would early-return
// on the latch forever — the user would need a manual F5.)
function resumeAfterReauth() {
_sseManuallyClosed = false;
_sseFailCount = 0;
reconnectDelay = 1000;
connect();
}
// Start on page load
connect();
// Expose for debugging and cross-module coordination
window._sseReconnect = connect;
window._sseClose = closeAndStop;
window._sseResume = resumeAfterReauth;
})();