Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(errors): log request route + unwrap err.cause on route errors (#275)

[._.]/ Adam Eivya7e0474024c8
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.js
index 0ed688defe..454231d06a 100644
--- a/server/lib/errorHandler.js
+++ b/server/lib/errorHandler.js
@@ -8,6 +8,24 @@ import { EventEmitter } from 'events';
// Global error event emitter for broadcasting errors
export const errorEvents = new EventEmitter();
+// Fields commonly attached to Node system errors (e.g. ECONNREFUSED, ENOTFOUND)
+// — preserved when unwrapping err.cause for diagnostic logging.
+const SYSTEM_ERROR_KEYS = ['code', 'errno', 'syscall', 'hostname', 'address', 'port'];
+
+const causeSuffix = (error) =>
+ error.context?.causeChain ? ` ← ${error.context.causeChain}` : '';
+
+/**
+ * Build the path portion of a request URL for logging — strips the query
+ * string so tokens (e.g. `?access_token=…`) don't leak into server logs.
+ * Falls back through `originalUrl` → `url` → '/'.
+ */
+const routePath = (req) => {
+ const raw = req.originalUrl || req.url || '/';
+ const qIndex = raw.indexOf('?');
+ return qIndex === -1 ? raw : raw.slice(0, qIndex);
+};
+
/**
* Enhanced error object with metadata
*/
@@ -47,9 +65,11 @@ export function asyncHandler(fn) {
const error = normalizeError(err);
// Log the error (skip stack traces for upstream platform issues)
- const logMsg = `❌ Route error: ${error.message}`;
+ const route = `${req.method} ${routePath(req)}`;
+ const suffix = causeSuffix(error);
+ const logMsg = `❌ Route error [${route}]: ${error.message}${suffix}`;
if (error.code === 'PLATFORM_UNAVAILABLE') {
- console.warn(`⚠️ Platform unavailable: ${error.message}`);
+ console.warn(`⚠️ Platform unavailable [${route}]: ${error.message}${suffix}`);
} else if (error.severity === 'warning') {
// Expected high-volume 404s (e.g. speculative media-job archive
// lookups) — already classified as benign; don't pollute server logs.
@@ -60,22 +80,49 @@ export function asyncHandler(fn) {
console.error(details ? `${logMsg}: ${JSON.stringify(details)}` : logMsg);
}
- // Emit Socket.IO event for UI notification
+ const safeContext = sanitizeContext(error.context);
+
if (io) {
- emitErrorEvent(io, error);
+ emitErrorEvent(io, error, safeContext);
}
- // Send error response
return res.status(error.status).json({
error: error.message,
code: error.code,
timestamp: error.timestamp,
- ...(error.context && Object.keys(error.context).length > 0 && { context: error.context })
+ ...(safeContext && Object.keys(safeContext).length > 0 && { context: safeContext })
});
});
};
}
+/**
+ * Walk an Error's `cause` chain (Node's native fetch wraps the actual reason
+ * in `err.cause` — without unwrapping, server logs show only "fetch failed").
+ * Returns context fields ready to merge: { causeChain: "Foo: msg → Bar: msg",
+ * cause: [{ name, message, ...SYSTEM_ERROR_KEYS }] }, or an empty object when
+ * there is no cause — callers can spread the result unconditionally.
+ */
+function describeCauseChain(err) {
+ const cause = [];
+ const labels = [];
+ let current = err?.cause;
+ const seen = new Set();
+ while (current && !seen.has(current) && cause.length < 5) {
+ seen.add(current);
+ const name = current?.constructor?.name || current?.name || 'Unknown';
+ const message = current?.message ?? String(current);
+ labels.push(`${name}: ${message}`);
+ const entry = { name, message };
+ for (const key of SYSTEM_ERROR_KEYS) {
+ if (current[key] !== undefined) entry[key] = current[key];
+ }
+ cause.push(entry);
+ current = current.cause;
+ }
+ return cause.length ? { causeChain: labels.join(' → '), cause } : {};
+}
+
/**
* Normalize different error types to ServerError
*/
@@ -87,11 +134,8 @@ export function normalizeError(err) {
if (err instanceof Error) {
const status = err.status || 500;
const code = err.code || getErrorCode(status);
- return new ServerError(err.message, {
- status,
- code,
- context: { originalError: err.constructor.name }
- });
+ const context = { originalError: err.constructor.name, ...describeCauseChain(err) };
+ return new ServerError(err.message, { status, code, context });
}
// Handle string or other error types
@@ -121,9 +165,11 @@ function getErrorCode(status) {
/**
* Strip sensitive fields from error context before broadcasting to clients.
- * Full context is still available in server-side console logs.
+ * Full context is still available in server-side console logs. Exported so
+ * socket-side listeners can defensively sanitize when they receive an error
+ * that was emitted directly (bypassing `emitErrorEvent`).
*/
-function sanitizeContext(context) {
+export function sanitizeContext(context) {
if (!context || typeof context !== 'object') return context;
const sensitive = ['apikey', 'token', 'secret', 'password', 'credential', 'authorization', 'bearer', 'envvars', 'secretenvvars'];
const visited = new WeakSet();
@@ -146,12 +192,21 @@ function sanitizeContext(context) {
}
/**
- * Emit error event via Socket.IO to alert UI
+ * Emit error event via Socket.IO to alert UI.
+ * `precomputedSafeContext` lets callers sanitize once and share with the HTTP
+ * response so the two channels can't drift on what's stripped.
+ *
+ * `errorEvents` listeners receive `(error, safeContext)` — server-side
+ * subscribers (e.g. autoFixer) can read full `error.context` for diagnostics,
+ * but any subscriber that re-broadcasts to clients (e.g. `socket.js`) MUST
+ * use `safeContext` to avoid leaking sensitive fields.
*/
-export function emitErrorEvent(io, error) {
- errorEvents.emit('error', error);
+export function emitErrorEvent(io, error, precomputedSafeContext) {
+ const safeContext = precomputedSafeContext !== undefined
+ ? precomputedSafeContext
+ : sanitizeContext(error.context);
- const safeContext = sanitizeContext(error.context);
+ errorEvents.emit('error', error, safeContext);
// Broadcast to all connected clients
io.emit('error:occurred', {
@@ -184,7 +239,8 @@ export function errorMiddleware(err, req, res, next) {
const error = normalizeError(err);
// Log the error
- const logMsg = `❌ Server error: ${error.message}`;
+ const route = `${req.method} ${routePath(req)}`;
+ const logMsg = `❌ Server error [${route}]: ${error.message}${causeSuffix(error)}`;
if (error.status >= 500) {
console.error(logMsg);
if (err.stack) console.error(err.stack);
@@ -214,7 +270,7 @@ export function setupProcessErrorHandlers(io) {
const error = normalizeError(reason);
error.severity = 'critical';
- console.error(`❌ Unhandled Promise Rejection: ${error.message}`);
+ console.error(`❌ Unhandled Promise Rejection: ${error.message}${causeSuffix(error)}`);
if (reason instanceof Error) {
console.error(reason.stack);
}
diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.js
index f332986ba8..9e50c3f6b9 100644
--- a/server/lib/errorHandler.test.js
+++ b/server/lib/errorHandler.test.js
@@ -118,6 +118,35 @@ describe('errorHandler.js', () => {
const normalized = normalizeError(error);
expect(normalized.code).toBe('INTERNAL_ERROR');
});
+
+ it('should unwrap err.cause chain and capture system fields', () => {
+ const root = Object.assign(new Error('getaddrinfo ENOTFOUND foo.example'), {
+ code: 'ENOTFOUND',
+ errno: -3008,
+ syscall: 'getaddrinfo',
+ hostname: 'foo.example'
+ });
+ const wrapped = Object.assign(new TypeError('fetch failed'), { cause: root });
+ const normalized = normalizeError(wrapped);
+ expect(normalized.message).toBe('fetch failed');
+ expect(normalized.context.causeChain).toContain('getaddrinfo ENOTFOUND foo.example');
+ expect(normalized.context.cause[0]).toMatchObject({
+ message: 'getaddrinfo ENOTFOUND foo.example',
+ code: 'ENOTFOUND',
+ errno: -3008,
+ syscall: 'getaddrinfo',
+ hostname: 'foo.example'
+ });
+ });
+
+ it('should not loop on self-referential cause chains', () => {
+ const a = new Error('a');
+ const b = new Error('b');
+ a.cause = b;
+ b.cause = a;
+ const normalized = normalizeError(a);
+ expect(normalized.context.cause.length).toBeLessThanOrEqual(5);
+ });
});
describe('emitErrorEvent', () => {
@@ -132,7 +161,26 @@ describe('errorHandler.js', () => {
emitErrorEvent(mockIo, error);
- expect(listener).toHaveBeenCalledWith(error);
+ // Listener receives (error, safeContext) — sensitive fields stripped so
+ // socket.js subscribers can safely re-broadcast.
+ expect(listener).toHaveBeenCalledWith(error, expect.any(Object));
+ errorEvents.off('error', listener);
+ });
+
+ it('should pass sanitized context to errorEvents listeners', () => {
+ const listener = vi.fn();
+ errorEvents.on('error', listener);
+
+ const mockIo = { emit: vi.fn() };
+ const error = new ServerError('Test error', {
+ context: { apiKey: 'secret-123', safe: 'visible' },
+ });
+
+ emitErrorEvent(mockIo, error);
+
+ const safeContext = listener.mock.calls[0][1];
+ expect(safeContext).toEqual({ safe: 'visible' });
+ expect(safeContext.apiKey).toBeUndefined();
errorEvents.off('error', listener);
});
});
diff --git a/server/services/socket.js b/server/services/socket.js
index e60c2ca50d..44cf7fc2eb 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -2,7 +2,7 @@ import { spawnPm2 } from './pm2.js';
import { streamDetection } from './streamingDetect.js';
import { cosEvents } from './cosEvents.js';
import { appsEvents } from './apps.js';
-import { errorEvents } from '../lib/errorHandler.js';
+import { errorEvents, sanitizeContext } from '../lib/errorHandler.js';
import { handleErrorRecovery } from './autoFixer.js';
import * as pm2Standardizer from './pm2Standardizer.js';
import { notificationEvents } from './notifications.js';
@@ -637,15 +637,22 @@ function setupCosEventForwarding() {
// Set up error event forwarding
function setupErrorEventForwarding() {
- // Forward error events to error subscribers
- errorEvents.on('error', (error) => {
+ // Forward error events to error subscribers. Use `safeContext` (second arg
+ // from emitErrorEvent) — `error.context` may contain sensitive fields like
+ // apiKey/token that must not be broadcast to clients. When the caller emits
+ // directly (bypassing `emitErrorEvent`), `safeContext` is undefined; in that
+ // case sanitize the raw context defensively rather than passing it through.
+ errorEvents.on('error', (error, safeContext) => {
+ const context = safeContext !== undefined
+ ? safeContext
+ : sanitizeContext(error.context);
broadcastToErrors('error:notified', {
message: error.message,
code: error.code,
severity: error.severity,
timestamp: error.timestamp,
canAutoFix: error.canAutoFix,
- context: error.context
+ context
});
});
}