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
security: better audit remediation
Adam Eivyc72d86c76951
diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsxindex a6445b6bb8..9ed7e9026e 100644--- a/client/src/components/messages/MessageDetail.jsx+++ b/client/src/components/messages/MessageDetail.jsx@@ -14,11 +14,14 @@ function SafeHtmlBody({ html }) {const iframe = iframeRef.current;if (!iframe) return;- // Strip script tags and event handlers from HTML+ // Strip script tags, event handlers, meta tags, SVG content, and javascript: URIsconst sanitized = html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')+ .replace(/<meta\b[^>]*>/gi, '')+ .replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi, '').replace(/\s+on\w+\s*=\s*["'][^"']*["']/gi, '')- .replace(/\s+on\w+\s*=\s*\S+/gi, '');+ .replace(/\s+on\w+\s*=\s*\S+/gi, '')+ .replace(/(href|src)\s*=\s*["']\s*javascript:[^"']*/gi, '$1="#"');const doc = iframe.contentDocument;if (!doc) return;@@ -49,7 +52,7 @@ function SafeHtmlBody({ html }) {return (<iframeref={iframeRef}- sandbox="allow-same-origin"+ sandbox=""className="w-full border-0 min-h-[100px]"style={{ background: 'transparent' }}title="Email content"diff --git a/server/routes/commands.js b/server/routes/commands.jsindex 4b38117d41..60f3a41a7c 100644--- a/server/routes/commands.js+++ b/server/routes/commands.js@@ -1,10 +1,16 @@import { Router } from 'express';+import { existsSync, statSync } from 'fs';+import { resolve } from 'path';+import { homedir } from 'os';import * as commands from '../services/commands.js';import * as pm2Service from '../services/pm2.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();+// Allowed workspace roots: user home and /tmp+const ALLOWED_WORKSPACE_ROOTS = [homedir(), '/tmp'];+// POST /api/commands/execute - Execute a commandrouter.post('/execute', asyncHandler(async (req, res) => {const { command, workspacePath } = req.body;@@ -13,6 +19,21 @@ router.post('/execute', asyncHandler(async (req, res) => {throw new ServerError('Command is required', { status: 400, code: 'MISSING_COMMAND' });}+ // Validate workspacePath if provided: must exist, be a directory, and resolve within allowed roots+ if (workspacePath) {+ const resolvedPath = resolve(workspacePath);+ const isAllowed = ALLOWED_WORKSPACE_ROOTS.some(root => resolvedPath === root || resolvedPath.startsWith(root + '/'));+ if (!isAllowed) {+ throw new ServerError('workspacePath is outside allowed directories', { status: 400, code: 'INVALID_PATH' });+ }+ if (!existsSync(resolvedPath)) {+ throw new ServerError('workspacePath does not exist', { status: 400, code: 'INVALID_PATH' });+ }+ if (!statSync(resolvedPath).isDirectory()) {+ throw new ServerError('workspacePath is not a directory', { status: 400, code: 'INVALID_PATH' });+ }+ }+const io = req.app.get('io');const commandId = commands.executeCommand(diff --git a/server/routes/database.js b/server/routes/database.jsindex 7e9e188d25..b96dd176be 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -101,7 +101,9 @@ async function getNativeStats() {const parts = result.stdout.trim().split(/\s+/);// ps aux columns: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDif (parts.length < 6) return null;- const pid = parts[1];+ const pidRaw = parseInt(parts[1], 10);+ if (!Number.isInteger(pidRaw) || pidRaw <= 0) return null;+ const pid = String(pidRaw);// Get all postgres child processesconst childResult = await runCmd('bash', ['-c',`ps -o pid=,pcpu=,pmem=,rss= -p $(pgrep -P ${pid} | tr '\\n' ',')${pid} 2>/dev/null`@@ -460,8 +462,11 @@ router.post('/export', asyncHandler(async (req, res) => {const dumpDir = join(rootDir, 'data', 'db-dumps');await runCmd('mkdir', ['-p', dumpDir], 5_000);const dumpFile = join(dumpDir, `portos-${backend}-${label}.sql`);- const result = await runCmd('bash', ['-c',- `pg_dump -h localhost -p ${port} -U ${pgUser} -d ${pgDb} --no-owner --no-privileges --if-exists --clean > "${dumpFile}"`+ // Use -f flag to write output directly — no shell redirect needed, avoids shell injection+ const pgDumpBin = pg17Bin ? `${pg17Bin}/pg_dump` : 'pg_dump';+ const result = await runCmd(pgDumpBin, [+ '-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,+ '--no-owner', '--no-privileges', '--if-exists', '--clean', '-f', dumpFile], 120_000, env);if (result.exitCode !== 0) {return res.status(500).json({ error: 'Export failed', details: result.stderr || result.stdout });diff --git a/server/routes/scaffold.js b/server/routes/scaffold.jsindex 4ab5a776fd..a23758fdf8 100644--- a/server/routes/scaffold.js+++ b/server/routes/scaffold.js@@ -492,8 +492,16 @@ Thumbs.db}await writeFile(join(repoPath, '.gitignore'), gitignoreContent);- await execAsync('git add -A', { cwd: repoPath, windowsHide: true });- await execAsync('git commit -m "Initial commit"', { cwd: repoPath, windowsHide: true });+ // Use spawn with shell:false to avoid shell injection+ const spawnGit = (args) => new Promise((resolve, reject) => {+ const proc = spawn('git', args, { cwd: repoPath, shell: false, windowsHide: true });+ let stderr = '';+ proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });+ proc.on('close', (code) => code === 0 ? resolve() : reject(new Error(`git ${args[0]} failed: ${stderr.trim()}`)));+ proc.on('error', reject);+ });+ await spawnGit(['add', '-A']);+ await spawnGit(['commit', '-m', 'Initial commit']);addStep('Initialize git', 'done');// Create GitHub repo if requesteddiff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex fa25b9e5ef..2e7098805e 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -7,7 +7,7 @@import { join } from 'path';import { writeFile, mkdir } from 'fs/promises';import { existsSync } from 'fs';-import { execSync } from 'child_process';+import { spawnSync } from 'child_process';import { v4 as uuidv4 } from '../lib/uuid.js';import { recordSession, recordMessages } from './usage.js';import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';@@ -69,15 +69,12 @@ export function checkForTaskCommit(taskId, workspacePath) {const gitDir = join(workspacePath, '.git');if (!existsSync(gitDir)) return false;- try {- const searchPattern = `[task-${taskId}]`;- const result = execSync(`git log --all --oneline --grep="${searchPattern}" -1`, {- cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true- }).trim();- return result.length > 0;- } catch {- return false;- }+ const searchPattern = `[task-${taskId}]`;+ const result = spawnSync('git', ['log', '--all', '--oneline', '--grep', searchPattern, '-1'], {+ cwd: workspacePath, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, shell: false+ });+ if (result.status !== 0 || result.error) return false;+ return (result.stdout?.trim().length ?? 0) > 0;}/**diff --git a/server/services/backup.js b/server/services/backup.jsindex 425aac283e..adffcaf5a5 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -10,7 +10,7 @@ import { spawn } from 'child_process';import { createHash } from 'crypto';import { createReadStream } from 'fs';import { access, readFile, readdir, stat, writeFile } from 'fs/promises';-import { join } from 'path';+import { join, resolve } from 'path';import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { getEvent } from './eventScheduler.js';import { checkHealth } from '../lib/db.js';@@ -285,7 +285,16 @@ export async function listSnapshots(destPath) {* @param {string|null} [options.subdirFilter=null] - Limit restore to a subdirectory*/export async function restoreSnapshot(destPath, snapshotId, { dryRun = true, subdirFilter = null } = {}) {+ // Validate snapshotId to prevent path traversal+ if (!snapshotId || !/^[\w\-.:T]+$/.test(snapshotId)) {+ throw new Error(`Invalid snapshotId: ${snapshotId}`);+ }const srcDir = join(destPath, 'snapshots', snapshotId, 'data');+ // Containment check: resolved path must stay within the snapshots directory+ const snapshotsRoot = resolve(join(destPath, 'snapshots'));+ if (!resolve(srcDir).startsWith(snapshotsRoot + '/')) {+ throw new Error(`Path traversal detected for snapshotId: ${snapshotId}`);+ }const flags = ['--itemize-changes'];if (dryRun) flags.push('--dry-run');diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex cf1da0fcb2..2694333d5e 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -328,7 +328,14 @@ export async function createGitBackup(repoPath) {const branch = `portos-backup-${timestamp}`;// Create backup branch from current HEAD (captures committed state without stashing)- await execAsync(`git branch ${branch}`, { cwd: repoPath, windowsHide: true });+ // Use spawn with shell:false to avoid shell injection via branch name+ await new Promise((resolve, reject) => {+ const proc = spawn('git', ['branch', branch], { cwd: repoPath, shell: false, windowsHide: true });+ let stderr = '';+ proc.stderr.on('data', (chunk) => { stderr += chunk.toString(); });+ proc.on('close', (code) => code === 0 ? resolve() : reject(new Error(`git branch failed: ${stderr.trim()}`)));+ proc.on('error', reject);+ });return { success: true, branch };}