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: address code review — safe JSON parsing, race conditions, security hardening, route fixes

Adam Eivy20f41406d85d
diff --git a/.changelog/v1.1.x.md b/.changelog/v1.1.x.md
index 0100e7e21f..b018872fad 100644
--- a/.changelog/v1.1.x.md
+++ b/.changelog/v1.1.x.md
@@ -14,6 +14,23 @@ Configurable embedding provider for the memory system, plus HealthTab layout imp
- ConfigTab has a new "Memory Embeddings" section for permanent provider/model selection
- Server reinitializes embedding config automatically when provider or model changes
+## Fixes
+
+### Code review remediation (30 files)
+- Replace bare `JSON.parse` with `safeJSONParse` across 8 server files and client `Security.jsx`
+- Fix broken app lookup in `git.js` routes — use `appsService.getAppById()` instead of `req.app.get('apps')`
+- Wrap async handlers in `scripts.js` and `media.js` with `asyncHandler`
+- Remove scaffold double-mount in `index.js`; update client API paths to `/scaffold/templates`
+- Add `deviceId` regex validation in `mediaService.js` to prevent injection
+- Replace `exec` with `execFile` in `autofixer/server.js` and `cos.js` for shell safety
+- Add mutex locks + atomic writes (temp-then-rename) to `notifications.js`, `taskLearning.js`, `autonomousJobs.js`
+- Extract shared `commandSecurity.js` module from duplicated constants in `commands.js` and `scriptRunner.js`
+- Add `MAX_SESSIONS_PER_SOCKET` limit in `shell.js`
+- Replace hardcoded `localhost:5555` with configurable `PORTOS_UI_URL` in 3 service files
+- Add peer IP `.refine()` validation in `instances.js` rejecting loopback/link-local
+- Add TLS warning log in `jira.js` when `allowSelfSigned` is enabled
+- Delete dead code `logger.example.js`
+
## Improvements
### HealthTab layout refresh
diff --git a/autofixer/server.js b/autofixer/server.js
index e6680112c3..2d72c8e527 100644
--- a/autofixer/server.js
+++ b/autofixer/server.js
@@ -3,9 +3,9 @@ import { readFile, writeFile, mkdir, access } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { promisify } from 'util';
-import { exec as execCb } from 'child_process';
+import { execFile as execFileCb } from 'child_process';
-const exec = promisify(execCb);
+const execFileAsync = promisify(execFileCb);
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -98,7 +98,7 @@ async function saveSession(sessionId, prompt, output, metadata) {
// Get PM2 process list
async function getProcessList() {
- const { stdout } = await exec('pm2 jlist');
+ const { stdout } = await execFileAsync('pm2', ['jlist']);
const stripped = stdout.replace(/\x1b\[[0-9;]*m/g, '');
const jsonStart = stripped.indexOf('[{');
const jsonEnd = stripped.lastIndexOf('}]');
@@ -113,8 +113,8 @@ async function getProcessList() {
// Get error logs for a process
async function getProcessLogs(processName) {
- const { stdout: errLogs } = await exec(`pm2 logs ${processName} --lines 100 --nostream --err`).catch(() => ({ stdout: '' }));
- const { stdout: outLogs } = await exec(`pm2 logs ${processName} --lines 50 --nostream --out`).catch(() => ({ stdout: '' }));
+ const { stdout: errLogs } = await execFileAsync('pm2', ['logs', processName, '--lines', '100', '--nostream', '--err']).catch(() => ({ stdout: '' }));
+ const { stdout: outLogs } = await execFileAsync('pm2', ['logs', processName, '--lines', '50', '--nostream', '--out']).catch(() => ({ stdout: '' }));
return { errLogs, outLogs };
}
diff --git a/client/package-lock.json b/client/package-lock.json
index bef0e852a5..fb8b2c47da 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos-client",
- "version": "1.0.3",
+ "version": "1.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos-client",
- "version": "1.0.3",
+ "version": "1.1.1",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
diff --git a/client/package.json b/client/package.json
index 00e746811d..6962610fa0 100644
--- a/client/package.json
+++ b/client/package.json
@@ -1,6 +1,6 @@
{
"name": "portos-client",
- "version": "1.0.3",
+ "version": "1.1.1",
"private": true,
"type": "module",
"scripts": {
diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsx
index d180c397c8..931be6e551 100644
--- a/client/src/pages/Security.jsx
+++ b/client/src/pages/Security.jsx
@@ -27,9 +27,13 @@ export default function Security() {
useEffect(() => {
const saved = localStorage.getItem(MEDIA_CONSTRAINTS_KEY);
if (saved) {
- const { videoDeviceId, audioDeviceId } = JSON.parse(saved);
- if (videoDeviceId) setSelectedVideo(videoDeviceId);
- if (audioDeviceId) setSelectedAudio(audioDeviceId);
+ try {
+ const { videoDeviceId, audioDeviceId } = JSON.parse(saved);
+ if (videoDeviceId) setSelectedVideo(videoDeviceId);
+ if (audioDeviceId) setSelectedAudio(audioDeviceId);
+ } catch {
+ localStorage.removeItem(MEDIA_CONSTRAINTS_KEY);
+ }
}
}, []);
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 0abe2d72fa..db710d71ee 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -108,11 +108,11 @@ export const detectWithAi = (path, providerId) => request('/detect/ai', {
});
// Templates & Scaffold
-export const getTemplates = () => request('/templates');
+export const getTemplates = () => request('/scaffold/templates');
export const getDirectories = (path = null) => {
const params = path ? `?path=${encodeURIComponent(path)}` : '';
- return request(`/directories${params}`);
+ return request(`/scaffold/directories${params}`);
};
export const scaffoldApp = (data) => request('/scaffold', {
@@ -120,7 +120,7 @@ export const scaffoldApp = (data) => request('/scaffold', {
body: JSON.stringify(data)
});
-export const createFromTemplate = (data) => request('/templates/create', {
+export const createFromTemplate = (data) => request('/scaffold/templates/create', {
method: 'POST',
body: JSON.stringify(data)
});
diff --git a/docs/features/app-wizard.md b/docs/features/app-wizard.md
index 28a6fb9c7c..a638f15271 100644
--- a/docs/features/app-wizard.md
+++ b/docs/features/app-wizard.md
@@ -56,7 +56,7 @@ Scaffold a new project from template:
|-------|-------------|
| POST /api/apps | Register existing app |
| POST /api/scaffold | Create new app from template |
-| GET /api/templates | List available templates |
+| GET /api/scaffold/templates | List available templates |
| POST /api/detect/ports | Detect process on port |
| POST /api/detect/repo | Validate repo path, detect type |
diff --git a/package-lock.json b/package-lock.json
index 8b7865cae7..300b44b9bd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "1.1.0",
+ "version": "1.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "1.1.0",
+ "version": "1.1.1",
"license": "MIT",
"workspaces": [
"packages/*",
@@ -29,6 +29,7 @@
},
"client": {
"name": "portos-client",
+ "version": "1.1.1",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
@@ -9238,6 +9239,7 @@
},
"server": {
"name": "portos-server",
+ "version": "1.1.1",
"dependencies": {
"axios": "^1.7.9",
"cors": "^2.8.5",
diff --git a/package.json b/package.json
index 137a1d0bf1..b4252ec03b 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,6 @@
{
"name": "portos",
-
- "version": "1.1.0",
+ "version": "1.1.1",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/index.js b/server/index.js
index e764b6e41a..0bc068ba12 100644
--- a/server/index.js
+++ b/server/index.js
@@ -173,7 +173,6 @@ app.use('/api/ports', portsRoutes);
app.use('/api/logs', logsRoutes);
app.use('/api/detect', detectRoutes);
app.use('/api/scaffold', scaffoldRoutes);
-app.use('/api', scaffoldRoutes); // Also mount at /api for /api/templates
// AI Toolkit routes with PortOS extensions
app.use('/api/providers', createPortOSProviderRoutes(aiToolkit));
diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.js
new file mode 100644
index 0000000000..a088a6bb00
--- /dev/null
+++ b/server/lib/commandSecurity.js
@@ -0,0 +1,17 @@
+// Allowlist of safe commands
+export const ALLOWED_COMMANDS = new Set([
+ 'npm', 'npx', 'pnpm', 'yarn', 'bun',
+ 'node', 'deno',
+ 'git', 'gh',
+ 'pm2',
+ 'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',
+ 'pwd', 'which', 'echo', 'env',
+ 'curl', 'wget',
+ 'docker', 'docker-compose',
+ 'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3',
+ 'brew'
+]);
+
+// Shell metacharacters that could be used for command injection
+// Security: Reject any command containing these to prevent injection via pipes, chaining, etc.
+export const DANGEROUS_SHELL_CHARS = /[;|&`$(){}[\]<>\\!#*?~]/;
diff --git a/server/lib/logger.example.js b/server/lib/logger.example.js
deleted file mode 100644
index 7290dca5df..0000000000
--- a/server/lib/logger.example.js
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Example usage of the logger utility
- */
-import * as logger from './logger.js';
-
-// Startup message
-logger.startup('Server running at http://localhost:5554');
-
-// Processing operations
-logger.process('Processing 15 items');
-
-// Success message
-logger.success('Operation completed successfully');
-
-// Configuration updates
-logger.config('Updated configuration settings');
-
-// Feature announcements
-logger.feature('New dashboard feature enabled');
-
-// Bug reports
-logger.bug('Detected memory leak in cache module');
-
-// Information
-logger.info('System health check passed');
-
-// Warnings
-logger.warning('API rate limit approaching threshold');
-
-// Debug messages (new type added for testing)
-logger.debug('Debug trace: user session initialized');
-
-// Error messages
-logger.error('Failed to connect to database');
diff --git a/server/package-lock.json b/server/package-lock.json
index d5d09c676e..9d9372bb95 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos-server",
- "version": "1.0.3",
+ "version": "1.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos-server",
- "version": "1.0.3",
+ "version": "1.1.1",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/server/package.json b/server/package.json
index fcab2c21b5..8f6cf0321c 100644
--- a/server/package.json
+++ b/server/package.json
@@ -1,6 +1,6 @@
{
"name": "portos-server",
- "version": "1.0.3",
+ "version": "1.1.1",
"private": true,
"type": "module",
"scripts": {
diff --git a/server/routes/git.js b/server/routes/git.js
index a042ec0a41..c45c2fccbb 100644
--- a/server/routes/git.js
+++ b/server/routes/git.js
@@ -1,5 +1,6 @@
import { Router } from 'express';
import * as git from '../services/git.js';
+import * as appsService from '../services/apps.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
const router = Router();
@@ -8,9 +9,7 @@ const router = Router();
router.get('/:appId', asyncHandler(async (req, res) => {
const { appId } = req.params;
- // Get app to find its path
- const apps = req.app.get('apps');
- const app = apps?.find(a => a.id === appId);
+ const app = await appsService.getAppById(appId);
if (!app) {
throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/routes/instances.js b/server/routes/instances.js
index 1b21d73efc..624f79ce3d 100644
--- a/server/routes/instances.js
+++ b/server/routes/instances.js
@@ -13,7 +13,9 @@ const router = Router();
// Validation schemas
const addPeerSchema = z.object({
- address: z.string().regex(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, 'Must be a valid IP address'),
+ address: z.string()
+ .regex(/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, 'Must be a valid IP address')
+ .refine(ip => !ip.startsWith('127.') && !ip.startsWith('169.254.'), 'Loopback and link-local addresses are not allowed'),
port: z.number().int().min(1).max(65535).default(5554),
name: z.string().optional()
});
diff --git a/server/routes/media.js b/server/routes/media.js
index 8e542efc5f..985bb36fea 100644
--- a/server/routes/media.js
+++ b/server/routes/media.js
@@ -1,6 +1,7 @@
import express from 'express';
import { z } from 'zod';
import mediaService from '../services/mediaService.js';
+import { asyncHandler } from '../lib/errorHandler.js';
const router = express.Router();
@@ -13,10 +14,10 @@ const startMediaSchema = z.object({
});
// List available media devices
-router.get('/devices', async (req, res) => {
+router.get('/devices', asyncHandler(async (req, res) => {
const devices = await mediaService.listDevices();
res.json(devices);
-});
+}));
// Get current streaming status
router.get('/status', (req, res) => {
@@ -27,7 +28,7 @@ router.get('/status', (req, res) => {
});
// Start media streaming
-router.post('/start', async (req, res) => {
+router.post('/start', asyncHandler(async (req, res) => {
const { videoDeviceId = '0', audioDeviceId = '0', video = true, audio = true } = startMediaSchema.parse(req.body);
if (video) {
@@ -43,7 +44,7 @@ router.post('/start', async (req, res) => {
video: mediaService.isVideoStreaming(),
audio: mediaService.isAudioStreaming()
});
-});
+}));
// Stop media streaming
router.post('/stop', (req, res) => {
diff --git a/server/routes/scripts.js b/server/routes/scripts.js
index 4881001fd4..472ea8dbdb 100644
--- a/server/routes/scripts.js
+++ b/server/routes/scripts.js
@@ -6,14 +6,15 @@
import { Router } from 'express';
import * as scriptRunner from '../services/scriptRunner.js';
+import { asyncHandler } from '../lib/errorHandler.js';
const router = Router();
// GET /api/cos/scripts - List all scripts
-router.get('/', async (req, res, next) => {
- const scripts = await scriptRunner.listScripts().catch(next);
- if (scripts) res.json({ scripts });
-});
+router.get('/', asyncHandler(async (req, res) => {
+ const scripts = await scriptRunner.listScripts();
+ res.json({ scripts });
+}));
// GET /api/cos/scripts/presets - Get available schedule presets
router.get('/presets', (req, res) => {
@@ -31,7 +32,7 @@ router.get('/jobs', (req, res) => {
});
// POST /api/cos/scripts - Create a new script
-router.post('/', async (req, res, next) => {
+router.post('/', asyncHandler(async (req, res) => {
const { name, description, command, schedule, cronExpression, enabled, triggerAction, triggerPrompt, triggerPriority } = req.body;
if (!name) {
@@ -52,61 +53,61 @@ router.post('/', async (req, res, next) => {
triggerAction,
triggerPrompt,
triggerPriority
- }).catch(next);
+ });
- if (script) res.status(201).json(script);
-});
+ res.status(201).json(script);
+}));
// GET /api/cos/scripts/:id - Get a specific script
-router.get('/:id', async (req, res, next) => {
- const script = await scriptRunner.getScript(req.params.id).catch(next);
+router.get('/:id', asyncHandler(async (req, res) => {
+ const script = await scriptRunner.getScript(req.params.id);
if (script === null) {
return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
}
- if (script) res.json(script);
-});
+ res.json(script);
+}));
// PUT /api/cos/scripts/:id - Update a script
-router.put('/:id', async (req, res, next) => {
- const script = await scriptRunner.updateScript(req.params.id, req.body).catch(next);
+router.put('/:id', asyncHandler(async (req, res) => {
+ const script = await scriptRunner.updateScript(req.params.id, req.body);
if (script === null) {
return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
}
- if (script) res.json(script);
-});
+ res.json(script);
+}));
// DELETE /api/cos/scripts/:id - Delete a script
-router.delete('/:id', async (req, res, next) => {
- const deleted = await scriptRunner.deleteScript(req.params.id).catch(next);
+router.delete('/:id', asyncHandler(async (req, res) => {
+ const deleted = await scriptRunner.deleteScript(req.params.id);
if (deleted === false) {
return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
}
- if (deleted) res.status(204).send();
-});
+ res.status(204).send();
+}));
// POST /api/cos/scripts/:id/run - Execute a script immediately
-router.post('/:id/run', async (req, res, next) => {
- const result = await scriptRunner.executeScript(req.params.id).catch(next);
+router.post('/:id/run', asyncHandler(async (req, res) => {
+ const result = await scriptRunner.executeScript(req.params.id);
if (result?.error === 'Script not found') {
return res.status(404).json({ error: 'Script not found', code: 'NOT_FOUND' });
}
- if (result) res.json(result);
-});
+ res.json(result);
+}));
// GET /api/cos/scripts/:id/runs - Get script run history
-router.get('/:id/runs', async (req, res, next) => {
+router.get('/:id/runs', asyncHandler(async (req, res) => {
const limit = parseInt(req.query.limit, 10) || 10;
- const runs = await scriptRunner.getScriptRuns(req.params.id, limit).catch(next);
+ const runs = await scriptRunner.getScriptRuns(req.params.id, limit);
- if (runs) res.json({ runs });
-});
+ res.json({ runs });
+}));
export default router;
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index f70a818108..f32d8b59fc 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -14,12 +14,13 @@
* - Custom user-defined jobs
*/
-import { writeFile, readFile } from 'fs/promises'
+import { writeFile, readFile, rename } from 'fs/promises'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'
import { v4 as uuidv4 } from 'uuid'
import { cosEvents } from './cosEvents.js'
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js'
+import { createMutex } from '../lib/asyncMutex.js'
import { checkAndPrompt as autobiographyCheckAndPrompt } from './autobiography.js'
/**
@@ -35,6 +36,7 @@ const __dirname = dirname(__filename)
const DATA_DIR = PATHS.cos
const JOBS_FILE = join(DATA_DIR, 'autonomous-jobs.json')
const JOBS_SKILLS_DIR = join(__dirname, '../../data/prompts/skills/jobs')
+const withLock = createMutex()
/**
* Map job IDs to their skill template filenames
@@ -322,7 +324,9 @@ function mergeWithDefaults(loaded) {
async function saveJobs(data) {
await ensureDataDir()
data.lastUpdated = new Date().toISOString()
- await writeFile(JOBS_FILE, JSON.stringify(data, null, 2))
+ const tmp = JOBS_FILE + '.tmp'
+ await writeFile(tmp, JSON.stringify(data, null, 2))
+ await rename(tmp, JOBS_FILE)
}
/**
@@ -418,35 +422,37 @@ async function getDueJobs() {
* @returns {Promise<Object>} Created job
*/
async function createJob(jobData) {
- const data = await loadJobs()
- const now = new Date().toISOString()
-
- const job = {
- id: jobData.id || `job-${uuidv4().slice(0, 8)}`,
- name: jobData.name,
- description: jobData.description || '',
- category: jobData.category || 'custom',
- interval: jobData.interval || 'weekly',
- intervalMs: resolveIntervalMs(jobData.interval || 'weekly', jobData.intervalMs),
- scheduledTime: jobData.scheduledTime || null,
- weekdaysOnly: jobData.weekdaysOnly || false,
- enabled: jobData.enabled !== undefined ? jobData.enabled : false,
- priority: jobData.priority || 'MEDIUM',
- autonomyLevel: jobData.autonomyLevel || 'manager',
- promptTemplate: jobData.promptTemplate || '',
- lastRun: null,
- runCount: 0,
- createdAt: now,
- updatedAt: now
- }
+ return withLock(async () => {
+ const data = await loadJobs()
+ const now = new Date().toISOString()
+
+ const job = {
+ id: jobData.id || `job-${uuidv4().slice(0, 8)}`,
+ name: jobData.name,
+ description: jobData.description || '',
+ category: jobData.category || 'custom',
+ interval: jobData.interval || 'weekly',
+ intervalMs: resolveIntervalMs(jobData.interval || 'weekly', jobData.intervalMs),
+ scheduledTime: jobData.scheduledTime || null,
+ weekdaysOnly: jobData.weekdaysOnly || false,
+ enabled: jobData.enabled !== undefined ? jobData.enabled : false,
+ priority: jobData.priority || 'MEDIUM',
+ autonomyLevel: jobData.autonomyLevel || 'manager',
+ promptTemplate: jobData.promptTemplate || '',
+ lastRun: null,
+ runCount: 0,
+ createdAt: now,
+ updatedAt: now
+ }
- data.jobs.push(job)
- await saveJobs(data)
+ data.jobs.push(job)
+ await saveJobs(data)
- console.log(`🤖 Autonomous job created: ${job.name}`)
- cosEvents.emit('jobs:created', { id: job.id, name: job.name })
+ console.log(`🤖 Autonomous job created: ${job.name}`)
+ cosEvents.emit('jobs:created', { id: job.id, name: job.name })
- return job
+ return job
+ })
}
/**
@@ -456,33 +462,35 @@ async function createJob(jobData) {
* @returns {Promise<Object|null>} Updated job or null
*/
async function updateJob(jobId, updates) {
- const data = await loadJobs()
- const job = data.jobs.find(j => j.id === jobId)
- if (!job) return null
-
- const updatableFields = [
- 'name', 'description', 'category', 'interval', 'intervalMs',
- 'scheduledTime', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate'
- ]
-
- for (const field of updatableFields) {
- if (updates[field] !== undefined) {
- job[field] = updates[field]
+ return withLock(async () => {
+ const data = await loadJobs()
+ const job = data.jobs.find(j => j.id === jobId)
+ if (!job) return null
+
+ const updatableFields = [
+ 'name', 'description', 'category', 'interval', 'intervalMs',
+ 'scheduledTime', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate'
+ ]
+
+ for (const field of updatableFields) {
+ if (updates[field] !== undefined) {
+ job[field] = updates[field]
+ }
}
- }
- // Recalculate intervalMs if interval changed
- if (updates.interval) {
- job.intervalMs = resolveIntervalMs(updates.interval, updates.intervalMs)
- }
+ // Recalculate intervalMs if interval changed
+ if (updates.interval) {
+ job.intervalMs = resolveIntervalMs(updates.interval, updates.intervalMs)
+ }
- job.updatedAt = new Date().toISOString()
- await saveJobs(data)
+ job.updatedAt = new Date().toISOString()
+ await saveJobs(data)
- console.log(`🤖 Autonomous job updated: ${job.name}`)
- cosEvents.emit('jobs:updated', { id: job.id, updates })
+ console.log(`🤖 Autonomous job updated: ${job.name}`)
+ cosEvents.emit('jobs:updated', { id: job.id, updates })
- return job
+ return job
+ })
}
/**
@@ -491,17 +499,19 @@ async function updateJob(jobId, updates) {
* @returns {Promise<boolean>}
*/
async function deleteJob(jobId) {
- const data = await loadJobs()
- const idx = data.jobs.findIndex(j => j.id === jobId)
- if (idx === -1) return false
+ return withLock(async () => {
+ const data = await loadJobs()
+ const idx = data.jobs.findIndex(j => j.id === jobId)
+ if (idx === -1) return false
- const deleted = data.jobs.splice(idx, 1)[0]
- await saveJobs(data)
+ const deleted = data.jobs.splice(idx, 1)[0]
+ await saveJobs(data)
- console.log(`🗑️ Autonomous job deleted: ${deleted.name}`)
- cosEvents.emit('jobs:deleted', { id: jobId })
+ console.log(`🗑️ Autonomous job deleted: ${deleted.name}`)
+ cosEvents.emit('jobs:deleted', { id: jobId })
- return true
+ return true
+ })
}
/**
@@ -510,20 +520,22 @@ async function deleteJob(jobId) {
* @returns {Promise<Object|null>} Updated job
*/
async function recordJobExecution(jobId) {
- const data = await loadJobs()
- const job = data.jobs.find(j => j.id === jobId)
- if (!job) return null
+ return withLock(async () => {
+ const data = await loadJobs()
+ const job = data.jobs.find(j => j.id === jobId)
+ if (!job) return null
- job.lastRun = new Date().toISOString()
- job.runCount = (job.runCount || 0) + 1
- job.updatedAt = job.lastRun
+ job.lastRun = new Date().toISOString()
+ job.runCount = (job.runCount || 0) + 1
+ job.updatedAt = job.lastRun
- await saveJobs(data)
+ await saveJobs(data)
- console.log(`🤖 Job executed: ${job.name} (run #${job.runCount})`)
- cosEvents.emit('jobs:executed', { id: jobId, runCount: job.runCount })
+ console.log(`🤖 Job executed: ${job.name} (run #${job.runCount})`)
+ cosEvents.emit('jobs:executed', { id: jobId, runCount: job.runCount })
- return job
+ return job
+ })
}
/**
@@ -532,20 +544,22 @@ async function recordJobExecution(jobId) {
* @returns {Promise<Object|null>}
*/
async function toggleJob(jobId) {
- const data = await loadJobs()
- const job = data.jobs.find(j => j.id === jobId)
- if (!job) return null
+ return withLock(async () => {
+ const data = await loadJobs()
+ const job = data.jobs.find(j => j.id === jobId)
+ if (!job) return null
- job.enabled = !job.enabled
- job.updatedAt = new Date().toISOString()
+ job.enabled = !job.enabled
+ job.updatedAt = new Date().toISOString()
- await saveJobs(data)
+ await saveJobs(data)
- const stateLabel = job.enabled ? 'enabled' : 'disabled'
- console.log(`🤖 Autonomous job ${stateLabel}: ${job.name}`)
- cosEvents.emit('jobs:toggled', { id: jobId, enabled: job.enabled })
+ const stateLabel = job.enabled ? 'enabled' : 'disabled'
+ console.log(`🤖 Autonomous job ${stateLabel}: ${job.name}`)
+ cosEvents.emit('jobs:toggled', { id: jobId, enabled: job.enabled })
- return job
+ return job
+ })
}
/**
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index 54e98aa847..69280ec78d 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -13,7 +13,8 @@ vi.mock('../lib/fileUtils.js', () => ({
vi.mock('fs/promises', () => ({
writeFile: vi.fn().mockResolvedValue(),
- readFile: vi.fn().mockResolvedValue('{}')
+ readFile: vi.fn().mockResolvedValue('{}'),
+ rename: vi.fn().mockResolvedValue()
}))
vi.mock('./autobiography.js', () => ({
diff --git a/server/services/brain.js b/server/services/brain.js
index b8546196b2..c5cd3e65f8 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -134,7 +134,11 @@ function parseJsonResponse(content) {
jsonStr = objectMatch[0];
}
- return JSON.parse(jsonStr);
+ try {
+ return JSON.parse(jsonStr);
+ } catch (err) {
+ throw new Error(`Failed to parse AI JSON response: ${err.message}`);
+ }
}
/**
diff --git a/server/services/browserService.js b/server/services/browserService.js
index b435899bbc..267994f9a4 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -8,6 +8,7 @@ import { readFile, writeFile, mkdir } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { EventEmitter } from 'events';
+import { safeJSONParse } from '../lib/fileUtils.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -36,7 +37,8 @@ let cachedConfig = null;
export async function loadConfig() {
if (cachedConfig) return cachedConfig;
const raw = await readFile(CONFIG_FILE, 'utf-8').catch(() => null);
- cachedConfig = raw ? { ...DEFAULT_CONFIG, ...JSON.parse(raw) } : { ...DEFAULT_CONFIG };
+ const parsed = safeJSONParse(raw, null);
+ cachedConfig = parsed ? { ...DEFAULT_CONFIG, ...parsed } : { ...DEFAULT_CONFIG };
return cachedConfig;
}
@@ -134,7 +136,7 @@ export async function getProcessStatus() {
const execFileAsync = promisify(execFile);
const { stdout } = await execFileAsync('pm2', ['jlist']);
- const processes = JSON.parse(stdout);
+ const processes = safeJSONParse(stdout, [], { allowArray: true });
const browserProc = processes.find(p => p.name === 'portos-browser');
if (!browserProc) {
diff --git a/server/services/commands.js b/server/services/commands.js
index 4fda189d5d..2a985b7a66 100644
--- a/server/services/commands.js
+++ b/server/services/commands.js
@@ -1,23 +1,6 @@
import { spawn } from 'child_process';
import { logAction } from './history.js';
-
-// Allowlist of safe commands
-const ALLOWED_COMMANDS = new Set([
- 'npm', 'npx', 'pnpm', 'yarn', 'bun',
- 'node', 'deno',
- 'git', 'gh',
- 'pm2',
- 'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',
- 'pwd', 'which', 'echo', 'env',
- 'curl', 'wget',
- 'docker', 'docker-compose',
- 'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3',
- '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 = /[;|&`$(){}[\]<>\\!#*?~]/;
+import { ALLOWED_COMMANDS, DANGEROUS_SHELL_CHARS } from '../lib/commandSecurity.js';
// Track active commands
const activeCommands = new Map();
diff --git a/server/services/cos.js b/server/services/cos.js
index 057380a9a1..fa0e13ac53 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -28,6 +28,8 @@ import { recordDecision, DECISION_TYPES } from './decisionLog.js';
import { cosEvents as _cosEvents } from './cosEvents.js';
export const cosEvents = _cosEvents;
+const PORTOS_UI_URL = `http://localhost:${process.env.PORT_UI || 5555}`;
+
const execAsync = promisify(exec);
const execFileAsync = promisify(execFile);
@@ -1612,7 +1614,7 @@ function getSelfImprovementTaskDescriptions() {
Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:
-1. Navigate to http://localhost:5555/
+1. Navigate to ${PORTOS_UI_URL}/
2. Check each main route: /, /apps, /cos, /cos/tasks, /cos/agents, /devtools, /devtools/history, /providers, /usage
3. For each route:
- Take a browser_snapshot to see the page structure
@@ -1627,7 +1629,7 @@ Use model: claude-opus-4-5-20251101 for thorough analysis`,
Use Playwright MCP to test PortOS at different viewport sizes:
-1. browser_resize to mobile (375x812), then navigate to http://localhost:5555/
+1. browser_resize to mobile (375x812), then navigate to ${PORTOS_UI_URL}/
2. Take browser_snapshot and analyze for:
- Text overflow or truncation
- Buttons too small to tap (< 44px)
@@ -1692,7 +1694,7 @@ Use model: claude-opus-4-5-20251101 for quality refactoring`,
Use Playwright MCP to audit PortOS accessibility:
-1. Navigate to http://localhost:5555/
+1. Navigate to ${PORTOS_UI_URL}/
2. Use browser_snapshot to get accessibility tree
3. Check each main route for:
- Missing ARIA labels
@@ -1711,7 +1713,7 @@ Use model: claude-opus-4-5-20251101 for comprehensive a11y fixes`,
Use Playwright MCP to find and fix console errors:
-1. Navigate to http://localhost:5555/
+1. Navigate to ${PORTOS_UI_URL}/
2. Call browser_console_messages with level: "error"
3. Visit each route and capture errors:
- /, /apps, /cos, /cos/tasks, /cos/agents
@@ -2772,10 +2774,10 @@ export async function getAgentProcessStats(agentId) {
*/
async function isPidAlive(pid) {
if (!pid) return false;
- const { exec } = await import('child_process');
+ const { execFile } = await import('child_process');
const { promisify } = await import('util');
- const execAsync = promisify(exec);
- const result = await execAsync(`ps -p ${pid} -o pid= 2>/dev/null`).catch(() => ({ stdout: '' }));
+ const execFileAsync = promisify(execFile);
+ const result = await execFileAsync('ps', ['-p', String(pid), '-o', 'pid=']).catch(() => ({ stdout: '' }));
return result.stdout.trim() !== '';
}
diff --git a/server/services/epigenetic.js b/server/services/epigenetic.js
index 9672e581ea..06774ad34a 100644
--- a/server/services/epigenetic.js
+++ b/server/services/epigenetic.js
@@ -1,7 +1,7 @@
import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
const DATA_DIR = PATHS.digitalTwin;
const EPIGENETIC_FILE = join(DATA_DIR, 'epigenetic.json');
@@ -194,7 +194,7 @@ async function loadData() {
await ensureDir(DATA_DIR);
const raw = await readFile(EPIGENETIC_FILE, 'utf-8').catch(() => null);
if (!raw) return { ...DEFAULT_DATA };
- return JSON.parse(raw);
+ return safeJSONParse(raw, { ...DEFAULT_DATA });
}
async function saveData(data) {
diff --git a/server/services/genome.js b/server/services/genome.js
index f5d8123ca6..add9118409 100644
--- a/server/services/genome.js
+++ b/server/services/genome.js
@@ -1,7 +1,7 @@
import { readFile, writeFile, unlink } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';
import { CURATED_MARKERS, MARKER_CATEGORIES, classifyGenotype, formatGenotype, resolveApoeHaplotype } from '../lib/curatedGenomeMarkers.js';
const GENOME_DIR = PATHS.digitalTwin;
@@ -31,7 +31,7 @@ async function loadMeta() {
await ensureGenomeDir();
const raw = await readFile(META_FILE, 'utf-8').catch(() => null);
if (!raw) return { ...DEFAULT_META };
- return JSON.parse(raw);
+ return safeJSONParse(raw, { ...DEFAULT_META });
}
async function saveMeta(meta) {
diff --git a/server/services/jira.js b/server/services/jira.js
index df312a1df7..5af354fbfa 100644
--- a/server/services/jira.js
+++ b/server/services/jira.js
@@ -78,6 +78,10 @@ export async function deleteInstance(instanceId) {
* Create axios client for JIRA instance
*/
function createJiraClient(instance) {
+ if (instance.allowSelfSigned) {
+ console.warn(`⚠️ JIRA instance ${instance.name || instance.id} using allowSelfSigned — TLS verification disabled`);
+ }
+
const client = axios.create({
baseURL: instance.baseUrl,
headers: {
diff --git a/server/services/mediaService.js b/server/services/mediaService.js
index 340e46dc15..2cd96b57ee 100644
--- a/server/services/mediaService.js
+++ b/server/services/mediaService.js
@@ -67,6 +67,7 @@ class MediaService {
}
startVideoStream(deviceId = '0') {
+ if (!/^\d+$/.test(deviceId)) throw new Error('Invalid device ID');
if (this.videoProcess) {
this.stopVideoStream();
}
@@ -106,6 +107,7 @@ class MediaService {
}
startAudioStream(deviceId = '0') {
+ if (!/^\d+$/.test(deviceId)) throw new Error('Invalid device ID');
if (this.audioProcess) {
this.stopAudioStream();
}
diff --git a/server/services/memoryBM25.js b/server/services/memoryBM25.js
index 4ad83db410..028c49b1bb 100644
--- a/server/services/memoryBM25.js
+++ b/server/services/memoryBM25.js
@@ -62,7 +62,15 @@ async function loadIndex() {
indexCache = createEmptyIndex()
return indexCache
}
- indexCache = deserializeIndex(JSON.parse(data))
+ let parsed
+ try {
+ parsed = JSON.parse(data)
+ } catch {
+ console.log('⚠️ BM25 index file has invalid JSON, creating fresh index')
+ indexCache = createEmptyIndex()
+ return indexCache
+ }
+ indexCache = deserializeIndex(parsed)
return indexCache
}
diff --git a/server/services/notifications.js b/server/services/notifications.js
index d387141ad2..7d62089d24 100644
--- a/server/services/notifications.js
+++ b/server/services/notifications.js
@@ -8,11 +8,14 @@
* - Health issues
*/
-import { writeFile } from 'fs/promises';
+import { writeFile, rename } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import { EventEmitter } from 'events';
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
+
+const withLock = createMutex();
const DATA_DIR = PATHS.data;
const NOTIFICATIONS_FILE = join(DATA_DIR, 'notifications.json');
@@ -66,7 +69,9 @@ async function loadNotifications() {
async function saveNotifications(data) {
await ensureDirectory();
notificationsCache = data;
- await writeFile(NOTIFICATIONS_FILE, JSON.stringify(data, null, 2));
+ const tmp = `${NOTIFICATIONS_FILE}.tmp`;
+ await writeFile(tmp, JSON.stringify(data, null, 2));
+ await rename(tmp, NOTIFICATIONS_FILE);
}
/**
@@ -129,55 +134,59 @@ export async function getCountsByType() {
* Add a new notification
*/
export async function addNotification(notification) {
- const data = await loadNotifications();
-
- const newNotification = {
- id: uuidv4(),
- type: notification.type,
- title: notification.title,
- description: notification.description || '',
- priority: notification.priority || PRIORITY_LEVELS.MEDIUM,
- timestamp: new Date().toISOString(),
- link: notification.link || null,
- read: false,
- metadata: notification.metadata || {}
- };
-
- data.notifications.push(newNotification);
-
- // Keep only the most recent 500 notifications
- if (data.notifications.length > 500) {
- data.notifications = data.notifications.slice(-500);
- }
+ return withLock(async () => {
+ const data = await loadNotifications();
+
+ const newNotification = {
+ id: uuidv4(),
+ type: notification.type,
+ title: notification.title,
+ description: notification.description || '',
+ priority: notification.priority || PRIORITY_LEVELS.MEDIUM,
+ timestamp: new Date().toISOString(),
+ link: notification.link || null,
+ read: false,
+ metadata: notification.metadata || {}
+ };
+
+ data.notifications.push(newNotification);
+
+ // Keep only the most recent 500 notifications
+ if (data.notifications.length > 500) {
+ data.notifications = data.notifications.slice(-500);
+ }
- await saveNotifications(data);
+ await saveNotifications(data);
- console.log(`🔔 Notification added: ${newNotification.type} - ${newNotification.title}`);
- notificationEvents.emit('added', newNotification);
- notificationEvents.emit('count-changed', await getUnreadCount());
+ console.log(`🔔 Notification added: ${newNotification.type} - ${newNotification.title}`);
+ notificationEvents.emit('added', newNotification);
+ notificationEvents.emit('count-changed', await getUnreadCount());
- return newNotification;
+ return newNotification;
+ });
}
/**
* Remove a notification by ID
*/
export async function removeNotification(id) {
- const data = await loadNotifications();
- const index = data.notifications.findIndex(n => n.id === id);
+ return withLock(async () => {
+ const data = await loadNotifications();
+ const index = data.notifications.findIndex(n => n.id === id);
- if (index === -1) {
- return { success: false, error: 'Notification not found' };
- }
+ if (index === -1) {
+ return { success: false, error: 'Notification not found' };
+ }
- const removed = data.notifications.splice(index, 1)[0];
- await saveNotifications(data);
+ const removed = data.notifications.splice(index, 1)[0];
+ await saveNotifications(data);
- console.log(`🔔 Notification removed: ${id}`);
- notificationEvents.emit('removed', { id });
- notificationEvents.emit('count-changed', await getUnreadCount());
+ console.log(`🔔 Notification removed: ${id}`);
+ notificationEvents.emit('removed', { id });
+ notificationEvents.emit('count-changed', await getUnreadCount());
- return { success: true, notification: removed };
+ return { success: true, notification: removed };
+ });
}
/**
@@ -185,79 +194,87 @@ export async function removeNotification(id) {
* Useful for removing notifications when the underlying item is handled
*/
export async function removeByMetadata(field, value) {
- const data = await loadNotifications();
- const before = data.notifications.length;
+ return withLock(async () => {
+ const data = await loadNotifications();
+ const before = data.notifications.length;
- data.notifications = data.notifications.filter(n => n.metadata[field] !== value);
+ data.notifications = data.notifications.filter(n => n.metadata[field] !== value);
- const removed = before - data.notifications.length;
- if (removed > 0) {
- await saveNotifications(data);
- console.log(`🔔 Removed ${removed} notifications with ${field}=${value}`);
- notificationEvents.emit('count-changed', await getUnreadCount());
- }
+ const removed = before - data.notifications.length;
+ if (removed > 0) {
+ await saveNotifications(data);
+ console.log(`🔔 Removed ${removed} notifications with ${field}=${value}`);
+ notificationEvents.emit('count-changed', await getUnreadCount());
+ }
- return { success: true, removed };
+ return { success: true, removed };
+ });
}
/**
* Mark a notification as read
*/
export async function markAsRead(id) {
- const data = await loadNotifications();
- const notification = data.notifications.find(n => n.id === id);
+ return withLock(async () => {
+ const data = await loadNotifications();
+ const notification = data.notifications.find(n => n.id === id);
- if (!notification) {
- return { success: false, error: 'Notification not found' };
- }
+ if (!notification) {
+ return { success: false, error: 'Notification not found' };
+ }
- if (!notification.read) {
- notification.read = true;
- await saveNotifications(data);
+ if (!notification.read) {
+ notification.read = true;
+ await saveNotifications(data);
- notificationEvents.emit('updated', notification);
- notificationEvents.emit('count-changed', await getUnreadCount());
- }
+ notificationEvents.emit('updated', notification);
+ notificationEvents.emit('count-changed', await getUnreadCount());
+ }
- return { success: true, notification };
+ return { success: true, notification };
+ });
}
/**
* Mark all notifications as read
*/
export async function markAllAsRead() {
- const data = await loadNotifications();
- let updated = 0;
-
- for (const notification of data.notifications) {
- if (!notification.read) {
- notification.read = true;
- updated++;
+ return withLock(async () => {
+ const data = await loadNotifications();
+ let updated = 0;
+
+ for (const notification of data.notifications) {
+ if (!notification.read) {
+ notification.read = true;
+ updated++;
+ }
}
- }
- if (updated > 0) {
- await saveNotifications(data);
- notificationEvents.emit('count-changed', 0);
- }
+ if (updated > 0) {
+ await saveNotifications(data);
+ notificationEvents.emit('count-changed', 0);
+ }
- return { success: true, updated };
+ return { success: true, updated };
+ });
}
/**
* Clear all notifications
*/
export async function clearAll() {
- const data = await loadNotifications();
- const count = data.notifications.length;
+ return withLock(async () => {
+ const data = await loadNotifications();
+ const count = data.notifications.length;
- data.notifications = [];
- await saveNotifications(data);
+ data.notifications = [];
+ await saveNotifications(data);
- notificationEvents.emit('cleared');
- notificationEvents.emit('count-changed', 0);
+ notificationEvents.emit('cleared');
+ notificationEvents.emit('count-changed', 0);
- return { success: true, cleared: count };
+ return { success: true, cleared: count };
+ });
}
/**
diff --git a/server/services/scriptRunner.js b/server/services/scriptRunner.js
index 34daeef819..b164862411 100644
--- a/server/services/scriptRunner.js
+++ b/server/services/scriptRunner.js
@@ -14,6 +14,7 @@ import { v4 as uuidv4 } from 'uuid';
import Cron from 'croner';
import { cosEvents } from './cosEvents.js';
import { readJSONFile } from '../lib/fileUtils.js';
+import { ALLOWED_COMMANDS, DANGEROUS_SHELL_CHARS } from '../lib/commandSecurity.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -26,24 +27,6 @@ const scheduledJobs = new Map();
// Execution lock to prevent duplicate runs (tracks last execution time)
const executionLock = new Map();
-// Allowlist of safe commands for scripts (mirrors commands.js allowlist)
-const ALLOWED_SCRIPT_COMMANDS = new Set([
- 'npm', 'npx', 'pnpm', 'yarn', 'bun',
- 'node', 'deno',
- 'git', 'gh',
- 'pm2',
- 'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',
- 'pwd', 'which', 'echo', 'env',
- 'curl', 'wget',
- 'docker', 'docker-compose',
- 'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3',
- '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 = /[;|&`$(){}[\]<>\\!#*?~]/;
-
// Patterns matching sensitive environment variable values in command output (e.g., pm2 jlist)
// Keys must be underscore-delimited segments to avoid false positives like "monkey" or "keymetrics"
const SENSITIVE_ENV_PATTERN = /("(?:[a-z0-9]+_)*(?:KEY|SECRET|TOKEN|PASSWORD|PASSPHRASE|MACAROON|CERT|CREDENTIAL|AUTH)(?:_[a-z0-9]+)*":\s*)"[^"]+"/gi;
@@ -88,10 +71,10 @@ function validateScriptCommand(command) {
const parts = trimmed.split(/\s+/);
const baseCommand = parts[0];
- if (!ALLOWED_SCRIPT_COMMANDS.has(baseCommand)) {
+ if (!ALLOWED_COMMANDS.has(baseCommand)) {
return {
valid: false,
- error: `Command '${baseCommand}' is not in the allowlist. Allowed: ${Array.from(ALLOWED_SCRIPT_COMMANDS).sort().join(', ')}`
+ error: `Command '${baseCommand}' is not in the allowlist. Allowed: ${Array.from(ALLOWED_COMMANDS).sort().join(', ')}`
};
}
@@ -495,5 +478,5 @@ export function getScheduledJobs() {
* Get list of allowed commands for scripts
*/
export function getAllowedScriptCommands() {
- return Array.from(ALLOWED_SCRIPT_COMMANDS).sort();
+ return Array.from(ALLOWED_COMMANDS).sort();
}
diff --git a/server/services/selfImprovement.js b/server/services/selfImprovement.js
index a340f14420..45aa5f1df5 100644
--- a/server/services/selfImprovement.js
+++ b/server/services/selfImprovement.js
@@ -14,6 +14,8 @@
import { cosEvents, getConfig } from './cos.js';
+const PORTOS_UI_URL = `http://localhost:${process.env.PORT_UI || 5555}`;
+
// Known routes to analyze
const ROUTES = [
{ path: '/', name: 'Dashboard', critical: true },
@@ -103,7 +105,7 @@ export async function runSelfImprovementCycle() {
*/
async function generateSelfImprovementTask(analysisType) {
const taskDescriptions = {
- [ANALYSIS_TYPES.UI_BUGS]: `Analyze PortOS UI at http://localhost:5555 for bugs and issues
+ [ANALYSIS_TYPES.UI_BUGS]: `Analyze PortOS UI at ${PORTOS_UI_URL} for bugs and issues
Use Playwright MCP to:
1. Navigate to each main route (/, /apps, /cos, /devtools, /providers, /usage)
@@ -116,7 +118,7 @@ Model: claude-opus-4-5-20251101`,
[ANALYSIS_TYPES.MOBILE_RESPONSIVE]: `Analyze PortOS UI for mobile responsiveness issues
Use Playwright MCP to:
-1. Navigate to http://localhost:5555 and its sub-routes
+1. Navigate to ${PORTOS_UI_URL} and its sub-routes
2. Test at mobile (375px), tablet (768px), and desktop (1440px) viewports
3. Capture snapshots at each viewport size
4. Identify layout issues, overflow, touch targets, font sizes
@@ -156,7 +158,7 @@ Model: claude-opus-4-5-20251101`,
[ANALYSIS_TYPES.ACCESSIBILITY]: `Accessibility audit of PortOS UI
Use Playwright MCP to:
-1. Navigate to http://localhost:5555 and sub-routes
+1. Navigate to ${PORTOS_UI_URL} and sub-routes
2. Capture accessibility snapshots
3. Check for missing ARIA labels, alt text, keyboard navigation
4. Verify color contrast ratios
@@ -169,7 +171,7 @@ Model: claude-opus-4-5-20251101`,
[ANALYSIS_TYPES.CONSOLE_ERRORS]: `Check PortOS for console errors and warnings
Use Playwright MCP to:
-1. Navigate to http://localhost:5555
+1. Navigate to ${PORTOS_UI_URL}
2. Open each main route and interact with key features
3. Capture all console messages (errors, warnings)
4. Identify the source of each error
diff --git a/server/services/settings.js b/server/services/settings.js
index 6a1bfe3807..09e87b6882 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -1,13 +1,14 @@
import { readFile, writeFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
+import { safeJSONParse } from '../lib/fileUtils.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const SETTINGS_FILE = join(__dirname, '..', '..', 'data', 'settings.json');
const load = async () => {
const raw = await readFile(SETTINGS_FILE, 'utf-8').catch(() => '{}');
- return JSON.parse(raw);
+ return safeJSONParse(raw, {});
};
const save = async (settings) => {
diff --git a/server/services/shell.js b/server/services/shell.js
index 1a4395c447..283b3e8493 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -5,6 +5,8 @@ import { v4 as uuidv4 } from 'uuid';
// Store active shell sessions
const shellSessions = new Map();
+const MAX_SESSIONS_PER_SOCKET = 3;
+
// Allowlist of safe environment variable prefixes to pass to PTY sessions
// Prevents leaking secrets (API keys, tokens) to the shell
const SAFE_ENV_PREFIXES = [
@@ -40,6 +42,13 @@ function getDefaultShell() {
* Create a new shell session
*/
export function createShellSession(socket, options = {}) {
+ const existing = getSessionsForSocket(socket);
+ if (existing.length >= MAX_SESSIONS_PER_SOCKET) {
+ console.warn(`🐚 Socket ${socket.id} exceeded max sessions (${MAX_SESSIONS_PER_SOCKET})`);
+ socket.emit('shell:error', { error: `Max ${MAX_SESSIONS_PER_SOCKET} shell sessions per connection` });
+ return null;
+ }
+
const sessionId = uuidv4();
const shell = options.shell || getDefaultShell();
const cwd = options.cwd || os.homedir();
diff --git a/server/services/taskLearning.js b/server/services/taskLearning.js
index d81a78c0e4..d873f4388e 100644
--- a/server/services/taskLearning.js
+++ b/server/services/taskLearning.js
@@ -6,12 +6,15 @@
* to provide smarter task prioritization and model selection.
*/
-import { writeFile, mkdir } from 'fs/promises';
+import { writeFile, mkdir, rename } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { cosEvents, emitLog } from './cos.js';
import { readJSONFile } from '../lib/fileUtils.js';
+import { createMutex } from '../lib/asyncMutex.js';
+
+const withLock = createMutex();
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -75,7 +78,9 @@ async function saveLearningData(data) {
}
}
- await writeFile(LEARNING_FILE, JSON.stringify(data, null, 2));
+ const tmp = `${LEARNING_FILE}.tmp`;
+ await writeFile(tmp, JSON.stringify(data, null, 2));
+ await rename(tmp, LEARNING_FILE);
}
/**
@@ -142,6 +147,7 @@ function extractTaskType(task) {
* Record a completed task for learning
*/
export async function recordTaskCompletion(agent, task) {
+ return withLock(async () => {
const data = await loadLearningData();
const taskType = extractTaskType(task);
@@ -281,6 +287,7 @@ export async function recordTaskCompletion(agent, task) {
}, '[TaskLearning]');
return data;
+ });
}
/**
@@ -625,24 +632,26 @@ export async function getPerformanceSummary() {
* Stores observations about what works and what doesn't
*/
export async function recordLearningInsight(insight) {
- const data = await loadLearningData();
+ return withLock(async () => {
+ const data = await loadLearningData();
- if (!data.insights) {
- data.insights = [];
- }
+ if (!data.insights) {
+ data.insights = [];
+ }
- data.insights.push({
- ...insight,
- recordedAt: new Date().toISOString()
- });
+ data.insights.push({
+ ...insight,
+ recordedAt: new Date().toISOString()
+ });
- // Keep only last 50 insights
- if (data.insights.length > 50) {
- data.insights = data.insights.slice(-50);
- }
+ // Keep only last 50 insights
+ if (data.insights.length > 50) {
+ data.insights = data.insights.slice(-50);
+ }
- await saveLearningData(data);
- return insight;
+ await saveLearningData(data);
+ return insight;
+ });
}
/**
@@ -892,6 +901,7 @@ export async function getSkippedTaskTypesWithStatus(gracePeriodMs = 7 * 24 * 60
* @returns {Object} Summary of what was reset
*/
export async function resetTaskTypeLearning(taskType) {
+ return withLock(async () => {
const data = await loadLearningData();
const metrics = data.byTaskType[taskType];
@@ -975,6 +985,7 @@ export async function resetTaskTypeLearning(taskType) {
successRate: metrics.successRate
}
};
+ });
}
/**
@@ -1083,6 +1094,7 @@ export async function getAllTaskDurations() {
* @returns {Object} Summary of changes made
*/
export async function recalculateModelTierMetrics() {
+ return withLock(async () => {
const data = await loadLearningData();
const routingData = data.routingAccuracy || {};
const oldTiers = data.byModelTier || {};
@@ -1154,6 +1166,7 @@ export async function recalculateModelTierMetrics() {
}
return { recalculated: changes.length > 0, changes };
+ });
}
/**
diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.js
index 00b9fd07ef..ebafba628f 100644
--- a/server/services/taskLearning.test.js
+++ b/server/services/taskLearning.test.js
@@ -4,7 +4,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('fs/promises', () => ({
readFile: vi.fn(),
writeFile: vi.fn(),
- mkdir: vi.fn()
+ mkdir: vi.fn(),
+ rename: vi.fn()
}));
vi.mock('fs', () => ({
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index c4c9a45a4a..bb72d338de 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -25,6 +25,8 @@ import { readJSONFile } from '../lib/fileUtils.js';
import { getAdaptiveCooldownMultiplier } from './taskLearning.js';
import { isTaskTypeEnabledForApp, getAppTaskTypeInterval, getActiveApps, getAppTaskTypeOverrides } from './apps.js';
+const PORTOS_UI_URL = `http://localhost:${process.env.PORT_UI || 5555}`;
+
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const DATA_DIR = join(__dirname, '../../data/cos');
@@ -120,7 +122,7 @@ const DEFAULT_SELF_IMPROVEMENT_PROMPTS = {
Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages) to analyze PortOS UI:
-1. Navigate to http://localhost:5555/
+1. Navigate to ${PORTOS_UI_URL}/
2. Check each main route: /, /apps, /cos, /cos/tasks, /cos/agents, /devtools, /devtools/history, /providers, /usage
3. For each route:
- Take a browser_snapshot to see the page structure
@@ -133,7 +135,7 @@ Use Playwright MCP (browser_navigate, browser_snapshot, browser_console_messages
Use Playwright MCP to test PortOS at different viewport sizes:
-1. browser_resize to mobile (375x812), then navigate to http://localhost:5555/
+1. browser_resize to mobile (375x812), then navigate to ${PORTOS_UI_URL}/
2. Take browser_snapshot and analyze for:
- Text overflow or truncation
- Buttons too small to tap (< 44px)
@@ -192,7 +194,7 @@ Refactor issues found and commit improvements.`,
Use Playwright MCP to find and fix console errors:
-1. Navigate to http://localhost:5555/
+1. Navigate to ${PORTOS_UI_URL}/
2. Call browser_console_messages with level: "error"
3. Visit each route and capture errors:
- /, /apps, /cos, /cos/tasks, /cos/agents
@@ -346,7 +348,7 @@ Think critically about what we have before adding more.`,
Use Playwright MCP to audit PortOS accessibility:
-1. Navigate to http://localhost:5555/
+1. Navigate to ${PORTOS_UI_URL}/
2. Use browser_snapshot to get accessibility tree
3. Check each main route for:
- Missing ARIA labels
diff --git a/server/services/taste-questionnaire.js b/server/services/taste-questionnaire.js
index 16758a0f45..5a55a9516b 100644
--- a/server/services/taste-questionnaire.js
+++ b/server/services/taste-questionnaire.js
@@ -11,6 +11,7 @@ import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { v4 as uuidv4 } from 'uuid';
+import { safeJSONParse } from '../lib/fileUtils.js';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import { digitalTwinEvents } from './digital-twin.js';
@@ -284,7 +285,18 @@ async function loadTasteProfile() {
}
const raw = await readFile(TASTE_PROFILE_FILE, 'utf-8');
- profileCache = JSON.parse(raw);
+ const defaultProfile = {
+ version: '1.0.0',
+ createdAt: null,
+ updatedAt: null,
+ sections: {},
+ profileSummary: null,
+ lastSessionAt: null
+ };
+ for (const sectionId of Object.keys(TASTE_SECTIONS)) {
+ defaultProfile.sections[sectionId] = { status: 'pending', responses: [], summary: null };
+ }
+ profileCache = safeJSONParse(raw, defaultProfile);
return profileCache;
}