Files
dashcaddy/dashcaddy-api/src/utilities/error-handler.js
T
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

78 lines
2.4 KiB
JavaScript

/**
* DashCaddy Error Handler Middleware
* Centralizes error handling logic to eliminate duplicate catch blocks
*
* Logging: this middleware uses the unified logError from src/utils/logging.js
* (same one src/app.js uses), so all errors go to one log file. The legacy
* ./error-logger.js and its ./error.log file have been retired.
*/
const { AppError } = require('./errors');
const { logError: unifiedLogError, safeErrorMessage } = require('../utils/logging');
const { errorResponse } = require('../utils/responses');
/**
* Global error handling middleware
* MUST be registered after all routes in server.js
*/
function errorMiddleware(err, req, res, next) {
// Log all errors with request context (unified, same file the rest of the app uses)
unifiedLogError(
req.path,
err,
{
req,
method: req.method,
ip: req.ip,
userId: req.user?.id,
body: req.body
}
).catch(e => process.stderr.write(`[error-handler] Failed to write to error log: ${e.message}\n`));
// Determine if this is an operational error (AppError) or programming error
const isOperational = err.isOperational || err instanceof AppError;
// Status code
const statusCode = err.statusCode || 500;
// Error code (DC-XXX format)
const code = err.code || `DC-${statusCode}`;
// Build extras for response
const extras = { code };
// Add optional fields if present
if (err.requiresTotp) extras.requiresTotp = true;
if (err.retryAfter) extras.retryAfter = err.retryAfter;
if (err.field) extras.field = err.field;
if (err.resource) extras.resource = err.resource;
if (err.details && Object.keys(err.details).length > 0) extras.details = err.details;
// Development mode: include stack trace
if (process.env.NODE_ENV === 'development') {
extras.stack = err.stack;
}
// Send response
errorResponse(res, statusCode, isOperational ? safeErrorMessage(err) : 'Internal server error', extras);
// For non-operational errors, log as fatal
if (!isOperational) {
process.stderr.write(`[FATAL] Non-operational error detected: ${JSON.stringify({ error: err.message, stack: err.stack, path: req.path })}\n`);
}
}
/**
* 404 handler for routes not found
* Register this before the global error handler
*/
function notFoundHandler(req, res, next) {
const { NotFoundError } = require('./errors');
next(new NotFoundError(`Route ${req.method} ${req.path}`));
}
module.exports = {
errorMiddleware,
notFoundHandler
};