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): prevent command injection vulnerabilities
Adam Eivy850629db25d0
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 361cf72ac5..e4d43ae087 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -123,13 +123,19 @@ app.get('/health', (req, res) => {* Get process stats (CPU, memory) for a PID*/async function getProcessStats(pid) {+ // Security: Ensure PID is a valid integer to prevent command injection+ const safePid = parseInt(pid, 10);+ if (isNaN(safePid) || safePid <= 0) {+ return { active: false, pid, cpu: 0, memoryKb: 0, state: 'invalid' };+ }+const { exec } = await import('child_process');const { promisify } = await import('util');const execAsync = promisify(exec);// Get process stats using ps command// %cpu = CPU percentage, rss = resident set size in KB- const result = await execAsync(`ps -p ${pid} -o pid=,pcpu=,rss=,state= 2>/dev/null`).catch(() => ({ stdout: '' }));+ const result = await execAsync(`ps -p ${safePid} -o pid=,pcpu=,rss=,state= 2>/dev/null`).catch(() => ({ stdout: '' }));const line = result.stdout.trim();if (!line) {@@ -669,11 +675,17 @@ async function cleanupOrphanedAgents() {* Check if a process is running by PID*/async function checkProcessRunning(pid) {+ // Security: Ensure PID is a valid integer to prevent command injection+ const safePid = parseInt(pid, 10);+ if (isNaN(safePid) || safePid <= 0) {+ return false;+ }+const { exec } = await import('child_process');const { promisify } = await import('util');const execAsync = promisify(exec);- const result = await execAsync(`ps -p ${pid} -o pid=`).catch(() => ({ stdout: '' }));+ const result = await execAsync(`ps -p ${safePid} -o pid=`).catch(() => ({ stdout: '' }));return result.stdout.trim() !== '';}diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex e562f84f34..926625ea29 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -144,10 +144,17 @@ async function scaffoldApp(req, res) {// Generate project files based on templateif (template === 'vite-react' || template === 'vite-express') {// Create using npm create vite- const { stderr } = await execAsync(- `npm create vite@latest ${dirName} -- --template react`,- { cwd: parentDir }- ).catch(err => ({ stderr: err.message }));+ // Security: Use spawn with array args instead of execAsync to prevent shell injection+ const { stderr } = await new Promise((resolve) => {+ const child = spawn('npm', ['create', 'vite@latest', dirName, '--', '--template', 'react'], {+ cwd: parentDir,+ shell: false+ });+ let stderr = '';+ child.stderr.on('data', (data) => { stderr += data.toString(); });+ child.on('close', () => resolve({ stderr }));+ child.on('error', (err) => resolve({ stderr: err.message }));+ });if (stderr && !stderr.includes('npm warn')) {addStep('Create Vite project', 'error', stderr);@@ -313,12 +320,17 @@ app.listen(PORT, '0.0.0.0', () => {// Create GitHub repo if requestedif (createGitHubRepo) {- const ghArgs = githubOrg- ? `repo create ${githubOrg}/${dirName} --source=. --push --private`- : `repo create ${dirName} --source=. --push --private`;-- const { stderr: ghErr } = await execAsync(`gh ${ghArgs}`, { cwd: repoPath })- .catch(err => ({ stderr: err.message }));+ // Security: Use spawn with array args to prevent shell injection from githubOrg/dirName+ const repoName = githubOrg ? `${githubOrg}/${dirName}` : dirName;+ const ghArgs = ['repo', 'create', repoName, '--source=.', '--push', '--private'];++ const { stderr: ghErr } = await new Promise((resolve) => {+ const child = spawn('gh', ghArgs, { cwd: repoPath, shell: false });+ let stderr = '';+ child.stderr.on('data', (data) => { stderr += data.toString(); });+ child.on('close', () => resolve({ stderr }));+ child.on('error', (err) => resolve({ stderr: err.message }));+ });if (ghErr && !ghErr.includes('Created repository')) {addStep('Create GitHub repo', 'error', ghErr);diff --git a/server/services/agents.js b/server/services/agents.jsindex 6793900404..a11ea9c1fd 100644--- a/server/services/agents.js+++ b/server/services/agents.js@@ -236,15 +236,21 @@ function formatRuntime(ms) {* Kill a process by PID*/export async function killProcess(pid) {+ // Security: Ensure PID is a valid integer to prevent command injection+ const safePid = parseInt(pid, 10);+ if (isNaN(safePid) || safePid <= 0) {+ throw new Error('Invalid PID provided');+ }+const platform = process.platform;if (platform === 'win32') {- await execAsync(`taskkill /PID ${pid} /F`);+ await execAsync(`taskkill /PID ${safePid} /F`);} else {- await execAsync(`kill -9 ${pid}`);+ await execAsync(`kill -9 ${safePid}`);}- console.log(`🔪 Killed process ${pid}`);+ console.log(`🔪 Killed process ${safePid}`);return true;}@@ -252,10 +258,16 @@ export async function killProcess(pid) {* Get detailed info for a specific process*/export async function getProcessInfo(pid) {+ // Security: Ensure PID is a valid integer to prevent command injection+ const safePid = parseInt(pid, 10);+ if (isNaN(safePid) || safePid <= 0) {+ return null;+ }+const platform = process.platform;if (platform === 'darwin' || platform === 'linux') {- const cmd = `ps -ww -p ${pid} -o pid,ppid,%cpu,%mem,etime,command`;+ const cmd = `ps -ww -p ${safePid} -o pid,ppid,%cpu,%mem,etime,command`;const result = await execAsync(cmd).catch(() => null);if (!result) return null;diff --git a/server/services/commands.js b/server/services/commands.jsindex 3bb4283655..53848dccaa 100644--- a/server/services/commands.js+++ b/server/services/commands.js@@ -15,33 +15,61 @@ const ALLOWED_COMMANDS = new Set(['brew']);+// Shell metacharacters that could be used for command injection+// Security: Reject any command containing these to prevent injection via pipes, chaining, etc.+const DANGEROUS_SHELL_CHARS = /[;|&`$(){}[\]<>\\!#*?~]/;+// Track active commandsconst activeCommands = new Map();/*** Execute a shell command with safety checks+ *+ * Security measures:+ * 1. Base command must be in allowlist+ * 2. Command cannot contain shell metacharacters that enable injection+ * 3. Command executed via spawn with shell:false where possible*/export function executeCommand(command, workspacePath, onData, onComplete) {const commandId = Date.now().toString(36) + Math.random().toString(36).substr(2);+ // Security: Reject empty or whitespace-only commands+ const trimmedCommand = command?.trim();+ if (!trimmedCommand) {+ const error = 'Empty command provided';+ onComplete?.({ success: false, error, exitCode: 1 });+ return null;+ }+// Parse command to check allowlist- const parts = command.trim().split(/\s+/);+ const parts = trimmedCommand.split(/\s+/);const baseCommand = parts[0];if (!ALLOWED_COMMANDS.has(baseCommand)) {const error = `Command '${baseCommand}' is not in the allowlist`;onComplete?.({ success: false, error, exitCode: 1 });- logAction('command', null, command.substring(0, 50), { command, workspacePath }, false, error);+ logAction('command', null, trimmedCommand.substring(0, 50), { command: trimmedCommand, workspacePath }, false, error);+ return null;+ }++ // Security: Check for dangerous shell metacharacters that could enable command injection+ // This prevents attacks like: npm; rm -rf / or npm && malicious_cmd or npm | cat /etc/passwd+ if (DANGEROUS_SHELL_CHARS.test(trimmedCommand)) {+ const error = 'Command contains disallowed shell characters (security restriction)';+ onComplete?.({ success: false, error, exitCode: 1 });+ logAction('command', null, trimmedCommand.substring(0, 50), { command: trimmedCommand, workspacePath }, false, error);return null;}const startTime = Date.now();let output = '';- // Use shell to handle pipes, redirects, etc.- const child = spawn('sh', ['-c', command], {+ // Security: Use spawn with array of args (shell:false) to prevent shell injection+ // The DANGEROUS_SHELL_CHARS check above ensures no metacharacters slip through+ const child = spawn(baseCommand, parts.slice(1), {cwd: workspacePath || process.cwd(),- env: { ...process.env, FORCE_COLOR: '1' }+ env: { ...process.env, FORCE_COLOR: '1' },+ shell: false});activeCommands.set(commandId, child);diff --git a/server/services/scriptRunner.js b/server/services/scriptRunner.jsindex 2144ac2b51..4715158382 100644--- a/server/services/scriptRunner.js+++ b/server/services/scriptRunner.js@@ -36,9 +36,17 @@ const ALLOWED_SCRIPT_COMMANDS = new Set(['brew']);+// Shell metacharacters that could be used for command injection+// Security: Reject any command containing these to prevent injection via pipes, chaining, etc.+const DANGEROUS_SHELL_CHARS = /[;|&`$(){}[\]<>\\!#*?~]/;+/*** Validate a script command against the allowlist- * Returns { valid: boolean, error?: string, baseCommand?: string }+ * Returns { valid: boolean, error?: string, baseCommand?: string, args?: string[] }+ *+ * Security measures:+ * 1. Base command must be in allowlist+ * 2. Command cannot contain shell metacharacters that enable injection*/function validateScriptCommand(command) {if (!command || typeof command !== 'string') {@@ -50,7 +58,16 @@ function validateScriptCommand(command) {return { valid: false, error: 'Command cannot be empty' };}- // Extract the base command (first word before space or pipe)+ // Security: Check for dangerous shell metacharacters that could enable command injection+ // This prevents attacks like: npm; rm -rf / or npm && malicious_cmd or npm | cat /etc/passwd+ if (DANGEROUS_SHELL_CHARS.test(trimmed)) {+ return {+ valid: false,+ error: 'Command contains disallowed shell characters (security restriction). Pipes, semicolons, and other shell operators are not allowed.'+ };+ }++ // Extract the base command (first word before space)const parts = trimmed.split(/\s+/);const baseCommand = parts[0];@@ -61,7 +78,7 @@ function validateScriptCommand(command) {};}- return { valid: true, baseCommand };+ return { valid: true, baseCommand, args: parts.slice(1) };}// Schedule presets to cron expressions@@ -310,9 +327,12 @@ export async function executeScript(scriptId) {const startTime = Date.now();return new Promise((resolve) => {- const child = spawn('sh', ['-c', script.command], {+ // Security: Use spawn with array of args (shell:false) to prevent shell injection+ // The validation function ensures no metacharacters are present+ const child = spawn(validation.baseCommand, validation.args || [], {cwd: join(__dirname, '../../'),- timeout: 60000 // 1 minute timeout+ timeout: 60000, // 1 minute timeout+ shell: false});let output = '';