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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: wire CoS runner into shared process-level error net as defense-in-depth (#1878)
[._.]/ Adam Eivy0b6f2e886256
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c72f5aedfb..f5a0c9b4be 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,10 @@- **[issue-1854] Beat-quantized timeline arranger: drag-snap scenes to the beat grid.** The director board's scene list now sits above an interactive **beat-grid timeline** (built from the project's cached audio analysis) showing section bands, beats, and downbeats. Drag a scene's left/right edge to trim its in/out point — or drag its body to reposition it — and it snaps to the nearest beat, downbeat, or section boundary within a small tolerance; an unsnapped drop is left exactly where you placed it. Confirmed (snapped) scenes are marked **beat-aligned** and now render *exactly* as arranged: the render's beat-snap step (`beatSnapClips`) honors a beat-aligned scene's saved `startSec`/`endSec` outright instead of re-deriving the cut from whichever beats happen to be nearby at render time. Auto-arranging scenes across the song's sections by energy is filed as a follow-up (#1915). (Closes #1854)+## Architecture++- **[issue-1878] CoS runner now wires the process-level `unhandledRejection`/`uncaughtException` net (defense-in-depth).** The main server (`server/index.js`) already registered a process-level net via the shared `setupProcessErrorHandlers()` helper (`server/lib/errorHandler.js`) — but the standalone CoS runner (`server/cos-runner/index.js`), a separate long-lived PM2 process that spawns and supervises child agents, had none, so a stray async handler that rejected/threw outside the request lifecycle would crash it with Node's default unhandled output. The runner now calls the same shared helper, giving it the identical, already-tested convention: log via the emoji-prefixed `console.error` style, log-and-stay-alive on an unhandled rejection, and log-then-exit-cleanly on an uncaught exception (after flushing, so PM2 restarts a process that would otherwise be left in an undefined state and reaps any orphaned agents on boot). Reusing the shared helper (rather than rolling inline handlers) keeps the two long-lived processes consistent and routes arbitrary non-Error throw values through `normalizeError`, so the net can't itself throw on a `reason` with no `.stack`. This is the backstop for the per-handler try/catch wrapping done in #1825 — not a replacement for it. While wiring this up, hardened the shared helper's `uncaughtException` branch, which dereferenced `error.stack` on the raw thrown value — a non-Error throw (`throw null`) made the net itself throw, masking the original exception and skipping the clean exit/flush; it now guards `error instanceof Error` (mirroring the existing `unhandledRejection` branch). A regression test (`server/process-safety-net.test.js`) asserts the shared helper registers both handlers, that both entry processes wire it up, and that the `uncaughtException` listener tolerates a non-Error throw value. (Closes #1878)+## Security- **`safeUrlFetch` SSRF guard now pins the vetted IP at connect time, closing a DNS-rebinding TOCTOU** — `isPublicHttpUrlSafe` resolved a hostname's DNS to validate it was public, but the subsequent `fetch` re-resolved the same hostname at connect time, so a rebinding host could answer a public address for the check and a loopback/link-local/cloud-metadata address for the actual connection, slipping past the guard. The guard now resolves once and the connection is pinned to that exact validated address via a per-request undici `Agent` whose `connect.lookup` always returns the vetted IP — while Host header and TLS SNI stay the original hostname, so cert validation is unaffected. Every redirect hop is still independently re-validated and re-pinned. (Low real-world exploitability — PortOS is single-user on a private network and URL sources are user-pasted Pinterest boards / stored feeds — but the connect-time re-resolution is now eliminated.) (#1859)diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex d10824b59d..57ac964862 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -22,6 +22,20 @@ import { loadState, saveState, withState } from './runnerState.js';import { getProcessStats, checkProcessRunning } from './processStats.js';import { ALLOWED_COMMANDS, isAllowedCommand } from './allowedCommands.js';import { PORTS } from '../lib/ports.js';+import { setupProcessErrorHandlers } from '../lib/errorHandler.js';++// Process-level safety net (defense-in-depth, see issue #1878). The main server+// (server/index.js) already wires this same shared helper via+// setupProcessErrorHandlers(io); the CoS runner — a separate long-lived PM2+// process that spawns and supervises child agents — had no such net, so a stray+// async handler that rejected/threw outside the request lifecycle would crash it+// with Node's default unhandled output. Reusing the shared helper gives the runner+// the identical, already-tested convention: log via the emoji-prefixed console.error+// style, and on an uncaughtException exit cleanly after flushing so PM2 restarts a+// process that would otherwise be left in an undefined state (boot then reaps any+// orphaned agents). Called with no `io` — the runner's socket server fans agent+// output to portos-server, not the error-alert UI, so the UI emit is skipped.+setupProcessErrorHandlers();// Timing constants for process termination/cleanup (ms). Named so the grace// windows are obvious at each call site instead of bare literals.diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex 78c37a003d..98bfd02ede 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -311,7 +311,12 @@ export function setupProcessErrorHandlers(io) {serverError.canAutoFix = true; // Could be auto-fixableconsole.error(`💥 Uncaught Exception: ${serverError.message}`);- console.error(error.stack);+ // Guard the raw-throw deref — a non-Error throw value (e.g. `throw null`)+ // has no `.stack`, and the safety net itself must never throw while handling+ // a failure (it would mask the original and skip the clean exit/flush below).+ if (error instanceof Error) {+ console.error(error.stack);+ }if (io) {emitErrorEvent(io, serverError);diff --git a/server/process-safety-net.test.js b/server/process-safety-net.test.jsnew file mode 100644index 0000000000..608eb64c6e--- /dev/null+++ b/server/process-safety-net.test.js@@ -0,0 +1,62 @@+import { describe, it, expect, vi } from 'vitest';+import { readFileSync } from 'fs';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';+import { setupProcessErrorHandlers } from './lib/errorHandler.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const read = (rel) => readFileSync(join(__dirname, rel), 'utf8');++// Defense-in-depth process-level net (issue #1878). Both long-lived processes —+// the main server and the standalone CoS runner — must wire the SHARED+// setupProcessErrorHandlers helper so the NEXT unguarded async handler surfaces as+// a logged warning instead of Node's default crash. We assert via a source scan+// rather than by importing the entry files (both boot on import — they call+// server.listen) and rather than by importing the helper and mutating the live+// test process's listener set.+describe('process-level safety net (#1878)', () => {+ it('shared helper registers both unhandledRejection and uncaughtException', () => {+ const src = read('lib/errorHandler.js');+ expect(src).toMatch(/export function setupProcessErrorHandlers/);+ expect(src).toMatch(/process\.on\(\s*['"]unhandledRejection['"]/);+ expect(src).toMatch(/process\.on\(\s*['"]uncaughtException['"]/);+ });++ it('shared helper normalizes arbitrary (non-Error) rejection reasons', () => {+ // Guards against the raw `reason.stack.split()` footgun — non-Error throw+ // values must not make the safety-net handler itself throw.+ const src = read('lib/errorHandler.js');+ expect(src).toMatch(/normalizeError/);+ });++ for (const rel of ['index.js', 'cos-runner/index.js']) {+ it(`${rel} wires up setupProcessErrorHandlers`, () => {+ expect(read(rel)).toMatch(/setupProcessErrorHandlers\s*\(/);+ });+ }++ // The net must never throw while handling a failure — a non-Error throw value+ // (`throw null`) has no `.stack`, and a deref there would mask the original and+ // skip the clean exit/flush. Invoke the actual registered uncaughtException+ // listener with `null`, with the exit timer stubbed so the test process survives.+ it('uncaughtException handler tolerates a non-Error throw value (e.g. null)', () => {+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout').mockImplementation(() => 0);+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const newListeners = (event, before) =>+ process.listeners(event).filter((l) => !before.includes(l));+ const beforeExc = process.listeners('uncaughtException');+ const beforeRej = process.listeners('unhandledRejection');+ setupProcessErrorHandlers(); // no io — skips the UI emit+ const addedExc = newListeners('uncaughtException', beforeExc);+ const addedRej = newListeners('unhandledRejection', beforeRej);+ try {+ expect(addedExc).toHaveLength(1);+ expect(() => addedExc[0](null)).not.toThrow();+ } finally {+ addedExc.forEach((l) => process.removeListener('uncaughtException', l));+ addedRej.forEach((l) => process.removeListener('unhandledRejection', l));+ setTimeoutSpy.mockRestore();+ errorSpy.mockRestore();+ }+ });+});