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
fix(security): add Zod validation to all Socket.IO event handlers
Adam Eivye114cfa0d3e3
diff --git a/.changelog/v0.16.x.md b/.changelog/v0.16.x.mdindex 0a410d8a1b..c0eeded469 100644--- a/.changelog/v0.16.x.md+++ b/.changelog/v0.16.x.md@@ -8,6 +8,12 @@ Agent persistence, reliability, and decision transparency improvements.## Security+### Socket.IO event handlers now validate all input with Zod+- **Previously**, all Socket.IO event handlers accepted raw client input without validation, allowing malformed or malicious data to reach business logic (PM2 process spawning, shell sessions, error recovery)+- **Now uses Zod schemas** for every event that accepts data: `detect:start`, `standardize:start`, `logs:subscribe`, `error:recover`, `shell:input`, `shell:resize`, `shell:stop`+- **Validation helper** (`validateSocketData`) returns parsed data on success or emits `${event}:error` with structured issue details on failure, matching the pattern used by HTTP route validation+- Schemas enforce type safety on path traversal inputs (`path`, `repoPath`), shell session IDs, terminal dimensions (`cols`/`rows` as positive integers), and process names+### PTY shell sessions no longer leak environment secrets- **Previously**, `pty.spawn()` spread the entire `process.env` into shell sessions, exposing API keys, tokens, and other secrets to anyone running `env` in the terminal- **Now uses an explicit allowlist** of safe environment variable prefixes (`PATH`, `HOME`, `SHELL`, toolchain vars like `NVM_`, `GOPATH`, etc.) so only standard/non-sensitive variables are passed throughdiff --git a/server/lib/socketValidation.js b/server/lib/socketValidation.jsnew file mode 100644index 0000000000..6f9f0622f5--- /dev/null+++ b/server/lib/socketValidation.js@@ -0,0 +1,70 @@+import { z } from 'zod';++// =============================================================================+// SOCKET EVENT SCHEMAS+// =============================================================================++// detect:start — path to scan+export const detectStartSchema = z.object({+ path: z.string().min(1, 'path is required')+});++// standardize:start — repo path and optional provider+export const standardizeStartSchema = z.object({+ repoPath: z.string().min(1, 'repoPath is required'),+ providerId: z.string().min(1).optional()+});++// logs:subscribe — process name and optional line count+export const logsSubscribeSchema = z.object({+ processName: z.string().min(1, 'processName is required'),+ lines: z.number().int().positive().max(10000).default(100)+});++// error:recover — error code and context+export const errorRecoverSchema = z.object({+ code: z.string().min(1, 'error code is required'),+ context: z.record(z.unknown()).optional().default({})+});++// shell:input — session ID and input data+export const shellInputSchema = z.object({+ sessionId: z.string().min(1, 'sessionId is required'),+ data: z.string()+});++// shell:resize — session ID with cols and rows+export const shellResizeSchema = z.object({+ sessionId: z.string().min(1, 'sessionId is required'),+ cols: z.number().int().positive().max(500),+ rows: z.number().int().positive().max(500)+});++// shell:stop — session ID+export const shellStopSchema = z.object({+ sessionId: z.string().min(1, 'sessionId is required')+});++// =============================================================================+// VALIDATION HELPER+// =============================================================================++/**+ * Validate socket event data against a Zod schema.+ * Emits `${event}:error` on failure and returns null.+ * Returns the parsed (and defaulted) data on success.+ */+export function validateSocketData(schema, data, socket, event) {+ const result = schema.safeParse(data);+ if (!result.success) {+ socket.emit(`${event}:error`, {+ message: 'Validation failed',+ details: result.error.issues.map(i => ({+ path: i.path.join('.'),+ message: i.message+ }))+ });+ return null;+ }+ return result.data;+}diff --git a/server/services/socket.js b/server/services/socket.jsindex c7fb2bb686..4bbfab8fe5 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -15,6 +15,16 @@ import { brainEvents } from './brainStorage.js';import { moltworldWsEvents } from './moltworldWs.js';import { queueEvents } from './moltworldQueue.js';import * as shellService from './shell.js';+import {+ validateSocketData,+ detectStartSchema,+ standardizeStartSchema,+ logsSubscribeSchema,+ errorRecoverSchema,+ shellInputSchema,+ shellResizeSchema,+ shellStopSchema+} from '../lib/socketValidation.js';// Store active log streams per socketconst activeStreams = new Map();@@ -34,13 +44,18 @@ export function initSocket(io) {console.log(`🔌 Client connected: ${socket.id}`);// Handle streaming app detection- socket.on('detect:start', async ({ path }) => {- console.log(`🔍 Starting detection: ${path}`);- await streamDetection(socket, path);+ socket.on('detect:start', async (rawData) => {+ const data = validateSocketData(detectStartSchema, rawData, socket, 'detect:start');+ if (!data) return;+ console.log(`🔍 Starting detection: ${data.path}`);+ await streamDetection(socket, data.path);});// Handle PM2 standardization- socket.on('standardize:start', async ({ repoPath, providerId }) => {+ socket.on('standardize:start', async (rawData) => {+ const data = validateSocketData(standardizeStartSchema, rawData, socket, 'standardize:start');+ if (!data) return;+ const { repoPath, providerId } = data;console.log(`🔧 Starting PM2 standardization: ${repoPath}`);const emit = (step, status, data = {}) => {@@ -110,7 +125,11 @@ export function initSocket(io) {});// Handle log streaming requests- socket.on('logs:subscribe', ({ processName, lines = 100 }) => {+ socket.on('logs:subscribe', (rawData) => {+ const data = validateSocketData(logsSubscribeSchema, rawData, socket, 'logs:subscribe');+ if (!data) return;+ const { processName, lines } = data;+// Clean up any existing stream for this socketcleanupStream(socket.id);@@ -220,7 +239,10 @@ export function initSocket(io) {});// Handle error recovery requests (can trigger auto-fix agents)- socket.on('error:recover', async ({ code, context }) => {+ socket.on('error:recover', async (rawData) => {+ const data = validateSocketData(errorRecoverSchema, rawData, socket, 'error:recover');+ if (!data) return;+ const { code, context } = data;console.log(`🔧 Error recovery requested: ${code}`);// Create auto-fix task@@ -245,18 +267,24 @@ export function initSocket(io) {}});- socket.on('shell:input', ({ sessionId, data }) => {- if (!shellService.writeToSession(sessionId, data)) {- socket.emit('shell:error', { sessionId, error: 'Session not found' });+ socket.on('shell:input', (rawData) => {+ const validated = validateSocketData(shellInputSchema, rawData, socket, 'shell:input');+ if (!validated) return;+ if (!shellService.writeToSession(validated.sessionId, validated.data)) {+ socket.emit('shell:error', { sessionId: validated.sessionId, error: 'Session not found' });}});- socket.on('shell:resize', ({ sessionId, cols, rows }) => {- shellService.resizeSession(sessionId, cols, rows);+ socket.on('shell:resize', (rawData) => {+ const validated = validateSocketData(shellResizeSchema, rawData, socket, 'shell:resize');+ if (!validated) return;+ shellService.resizeSession(validated.sessionId, validated.cols, validated.rows);});- socket.on('shell:stop', ({ sessionId }) => {- shellService.killSession(sessionId);+ socket.on('shell:stop', (rawData) => {+ const validated = validateSocketData(shellStopSchema, rawData, socket, 'shell:stop');+ if (!validated) return;+ shellService.killSession(validated.sessionId);});// Cleanup on disconnect