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(services): guard 8 unprotected JSON.parse calls with safeJSONParse
Adam Eivyf6ea2e60d5b4
diff --git a/.changelog/v0.18.x.md b/.changelog/v0.18.x.mdnew file mode 100644index 0000000000..ac5a976ab5--- /dev/null+++ b/.changelog/v0.18.x.md@@ -0,0 +1,14 @@+# Release v0.18.x - Changelog++Released: YYYY-MM-DD++## Overview++Continued reliability improvements and codebase hardening.++## Improvements++### Guard remaining unprotected JSON.parse calls (S7 complete)+- Replaced bare `JSON.parse` with `safeJSONParse` in 7 more files (8 call sites): `agentContentGenerator.js`, `pm2Standardizer.js`, `automationScheduler.js`, `git.js` (2 locations), `aiDetect.js`, `memoryClassifier.js`, `clinvar.js`+- Continues the v0.17.8 effort that converted 5 services — all remaining unprotected JSON.parse calls on external/file data are now guarded+- Corrupted schedule files, malformed git log output, bad LLM responses, and damaged ClinVar index now gracefully return defaults or clear error messages instead of crashing the processdiff --git a/PLAN.md b/PLAN.mdindex fececce6e1..af1addc009 100644--- a/PLAN.md+++ b/PLAN.md@@ -180,11 +180,10 @@ PortOS is an internal/VPN app so auth, CORS, rate limiting, and HTTPS are out of- **File:** `server/lib/errorHandler.js:113-121`- **Complexity:** Simple-### S7: Guard unprotected JSON.parse calls-- 10+ locations call `JSON.parse` on external/file data without try-catch-- Wrap in safe parser or add try-catch-- **Files:** `server/services/digital-twin.js` (11 locations), `server/services/cos.js:273`, `server/lib/taskParser.js:106`-- **Complexity:** Simple+### ~~S7: Guard unprotected JSON.parse calls~~ ✅+- ~~10+ locations call `JSON.parse` on external/file data without try-catch~~+- Fixed: replaced bare `JSON.parse` with `safeJSONParse` from `lib/fileUtils.js` in 7 files (8 call sites): `agentContentGenerator.js`, `pm2Standardizer.js`, `automationScheduler.js`, `git.js` (2), `aiDetect.js`, `memoryClassifier.js`, `clinvar.js`+- `digital-twin.js` and `cos.js` were already using `safeJSONParse`### S8: Add iteration limit to cron parser- `eventScheduler.js` loops minute-by-minute for up to 2 years — invalid cron expressions cause CPU spindiff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.jsindex 744a8b5d59..c7f809ac2c 100644--- a/server/services/agentContentGenerator.js+++ b/server/services/agentContentGenerator.js@@ -8,6 +8,7 @@import { executeApiRun, executeCliRun, createRun } from './runner.js';import { getActiveProvider, getProviderById } from './providers.js';import * as agentActivity from './agentActivity.js';+import { safeJSONParse } from '../lib/fileUtils.js';/*** Parse JSON from AI response text (handles markdown blocks, extra text)@@ -31,7 +32,9 @@ export function parseAIJsonResponse(text) {jsonStr = objectMatch[0];}- return JSON.parse(jsonStr);+ const parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'AI JSON response' });+ if (!parsed) throw new Error('AI returned invalid JSON');+ return parsed;}/**diff --git a/server/services/aiDetect.js b/server/services/aiDetect.jsindex c7eb71bd90..a41a043830 100644--- a/server/services/aiDetect.js+++ b/server/services/aiDetect.js@@ -3,6 +3,7 @@ import { existsSync } from 'fs';import { join, basename } from 'path';import { getActiveProvider, getProviderById } from './providers.js';import { spawn } from 'child_process';+import { safeJSONParse } from '../lib/fileUtils.js';/*** Gather project context for AI analysis@@ -198,7 +199,9 @@ function parseAiResponse(response) {jsonStr = objectMatch[0];}- return JSON.parse(jsonStr);+ const parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'AI app detection' });+ if (!parsed) throw new Error('Failed to parse AI detection response');+ return parsed;}/**diff --git a/server/services/automationScheduler.js b/server/services/automationScheduler.jsindex a7cb4900ec..c239247260 100644--- a/server/services/automationScheduler.js+++ b/server/services/automationScheduler.js@@ -10,7 +10,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { v4 as uuidv4 } from 'uuid';import EventEmitter from 'events';-import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';import * as eventScheduler from './eventScheduler.js';import * as agentActivity from './agentActivity.js';@@ -48,7 +48,7 @@ async function loadSchedules() {}const content = await readFile(SCHEDULES_FILE, 'utf-8');- cache = JSON.parse(content);+ cache = safeJSONParse(content, { schedules: {} }, { logError: true, context: 'automation schedules' });cacheTimestamp = now;return cache;}diff --git a/server/services/clinvar.js b/server/services/clinvar.jsindex bdd45b1403..106fc9d8d6 100644--- a/server/services/clinvar.js+++ b/server/services/clinvar.js@@ -4,7 +4,7 @@ import { join } from 'path';import { createGunzip } from 'zlib';import { createInterface } from 'readline';import { pipeline } from 'stream/promises';-import { PATHS, ensureDir } from '../lib/fileUtils.js';+import { PATHS, ensureDir, safeJSONParse } from '../lib/fileUtils.js';const GENOME_DIR = PATHS.digitalTwin;const CLINVAR_GZ = join(GENOME_DIR, 'clinvar-raw.txt.gz');@@ -293,7 +293,8 @@ async function loadClinvarIndex() {const raw = await readFile(CLINVAR_INDEX, 'utf-8').catch(() => null);if (!raw) return null;- clinvarIndex = JSON.parse(raw);+ clinvarIndex = safeJSONParse(raw, null, { logError: true, context: 'ClinVar index' });+ if (!clinvarIndex) return null;console.log(`🧬 ClinVar index loaded: ${Object.keys(clinvarIndex).length.toLocaleString()} variants`);return clinvarIndex;}diff --git a/server/services/git.js b/server/services/git.jsindex 958fc75094..ac06251b7c 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -1,6 +1,7 @@import { spawn } from 'child_process';import { existsSync } from 'fs';import { join } from 'path';+import { safeJSONParse } from '../lib/fileUtils.js';/*** Execute a git command safely using spawn (prevents shell injection)@@ -104,9 +105,9 @@ export async function getCommits(dir, limit = 10) {const format = '--format={"hash":"%h","message":"%s","author":"%an","date":"%cI"}';const result = await execGit(['log', format, '-n', String(safeLimit)], dir);- const commits = result.stdout.trim().split('\n').filter(Boolean).map(line => {- return JSON.parse(line);- });+ const commits = result.stdout.trim().split('\n').filter(Boolean)+ .map(line => safeJSONParse(line, null))+ .filter(Boolean);return commits;}@@ -279,7 +280,8 @@ export async function getBranchComparison(dir, baseBranch = 'main', headBranch =const commits = logResult.stdout.trim().split('\n').filter(Boolean)- .map(line => JSON.parse(line));+ .map(line => safeJSONParse(line, null))+ .filter(Boolean);const statResult = await execGit(['diff', '--stat', `${baseBranch}...${headBranch}`], dir, { ignoreExitCode: true }diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.jsindex 05458dbc5b..4ccc0f1320 100644--- a/server/services/memoryClassifier.js+++ b/server/services/memoryClassifier.js@@ -10,6 +10,7 @@ import { existsSync } from 'fs';import { join, dirname } from 'path';import { fileURLToPath } from 'url';import { getStageTemplate } from './promptService.js';+import { safeJSONParse } from '../lib/fileUtils.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -197,7 +198,8 @@ function parseLLMResponse(response) {console.log('⚠️ Extracted JSON appears malformed');return { memories: [], rejected: [], parseError: true };}- parsed = JSON.parse(jsonStr);+ parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'memory classification' });+ if (!parsed) return { memories: [], rejected: [], parseError: true };// Validate structureif (!Array.isArray(parsed.memories)) {diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex d93969a6d4..c52a3b79fd 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -5,6 +5,7 @@ import { exec } from 'child_process';import { promisify } from 'util';import { getActiveProvider, getProviderById } from './providers.js';import { spawn } from 'child_process';+import { safeJSONParse } from '../lib/fileUtils.js';const execAsync = promisify(exec);@@ -260,7 +261,9 @@ function parseAnalysisResponse(response) {jsonStr = objectMatch[0];}- return JSON.parse(jsonStr);+ const parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'PM2 standardizer analysis' });+ if (!parsed) throw new Error('Failed to parse LLM analysis response');+ return parsed;}/**