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: safe JSON parsing, null guards, and secret redaction in script output
Adam Eivyb2a694b35c78
diff --git a/.changelog/v0.15.x.md b/.changelog/v0.15.x.mdindex 8dd5ce88c6..e3f1df2d88 100644--- a/.changelog/v0.15.x.md+++ b/.changelog/v0.15.x.md@@ -6,6 +6,14 @@ Released: YYYY-MM-DDPlan cleanup and documentation reorganization.+## Fixes++### Hardening: Safe JSON parsing & output redaction+- **Replaced raw `JSON.parse` with `readJSONFile`** in `apps.js`, `socialAccounts.js`, `scriptRunner.js` -- corrupted data files no longer crash the server+- **Added null guard** on `data?.apps?.[id]` in `apps.js` to prevent undefined access+- **Added `.catch()` handler** on fire-and-forget `cloneRepoInBackground()` in `brain.js` to prevent unhandled promise rejections+- **Added sensitive output redaction** in `scriptRunner.js` -- env vars containing keys, tokens, passwords, and secrets are now `[REDACTED]` before persisting to `scripts-state.json`+## Improvements### Plan & Documentation Cleanupdiff --git a/server/routes/brain.js b/server/routes/brain.jsindex 3150b8ef72..aefd421148 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -642,7 +642,9 @@ router.post('/links', asyncHandler(async (req, res) => {// If GitHub repo and auto-clone enabled, start clone in backgroundif (isGitHubRepo && autoClone !== false) {- cloneRepoInBackground(link.id, url);+ cloneRepoInBackground(link.id, url).catch(err => {+ console.error(`❌ Background clone setup failed for ${link.id}: ${err.message}`);+ });}res.status(201).json(link);diff --git a/server/services/apps.js b/server/services/apps.jsindex 999ac9e622..588145cd42 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -1,9 +1,8 @@-import { readFile, writeFile } from 'fs/promises';-import { existsSync } from 'fs';+import { writeFile } from 'fs/promises';import { join } from 'path';import { v4 as uuidv4 } from 'uuid';import EventEmitter from 'events';-import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';const DATA_DIR = PATHS.data;const APPS_FILE = join(DATA_DIR, 'apps.json');@@ -36,14 +35,7 @@ async function loadApps() {await ensureDataDir();- if (!existsSync(APPS_FILE)) {- appsCache = { apps: {} };- cacheTimestamp = now;- return appsCache;- }-- const content = await readFile(APPS_FILE, 'utf-8');- appsCache = JSON.parse(content);+ appsCache = await readJSONFile(APPS_FILE, { apps: {} });cacheTimestamp = now;return appsCache;}@@ -103,7 +95,7 @@ export async function getActiveApps() {*/export async function getAppById(id) {const data = await loadApps();- const app = data.apps[id];+ const app = data?.apps?.[id];return app ? { id, ...app } : null;}diff --git a/server/services/scriptRunner.js b/server/services/scriptRunner.jsindex 233b31c767..ec28caea34 100644--- a/server/services/scriptRunner.js+++ b/server/services/scriptRunner.js@@ -8,11 +8,11 @@import { spawn } from 'child_process';import { join, dirname } from 'path';import { fileURLToPath } from 'url';-import { writeFile, readFile, mkdir, readdir, rm } from 'fs/promises';-import { existsSync } from 'fs';+import { writeFile, mkdir, readdir, rm } from 'fs/promises';import { v4 as uuidv4 } from 'uuid';import Cron from 'croner';import { cosEvents } from './cosEvents.js';+import { readJSONFile } from '../lib/fileUtils.js';const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -43,6 +43,18 @@ const ALLOWED_SCRIPT_COMMANDS = new Set([// 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)+const SENSITIVE_ENV_PATTERN = /("[^"]*(?:KEY|SECRET|TOKEN|PASS|PASSWORD|APIKEY|API_KEY|APISEC|API_SEC|MACAROON|CERT|CREDENTIAL|AUTH)[^"]*":\s*)"[^"]+"/gi;++/**+ * Redact sensitive env vars from command output before persisting.+ * Matches JSON key-value pairs where the key contains secret-like words.+ */+function redactSensitiveOutput(output) {+ if (!output) return output;+ return output.replace(SENSITIVE_ENV_PATTERN, '$1"[REDACTED]"');+}+/*** Validate a script command against the allowlist* Returns { valid: boolean, error?: string, baseCommand?: string, args?: string[] }@@ -126,11 +138,7 @@ async function ensureScriptsDir() {* Load scripts state*/async function loadScriptsState() {- if (!existsSync(SCRIPTS_STATE_FILE)) {- return { scripts: {} };- }- const content = await readFile(SCRIPTS_STATE_FILE, 'utf-8');- return JSON.parse(content);+ return readJSONFile(SCRIPTS_STATE_FILE, { scripts: {} });}/**@@ -366,7 +374,7 @@ export async function executeScript(scriptId) {// Update script statescript.lastRun = new Date().toISOString();- script.lastOutput = fullOutput.substring(0, 10000); // Limit stored output+ script.lastOutput = redactSensitiveOutput(fullOutput.substring(0, 10000));script.lastExitCode = code;script.runCount = (script.runCount || 0) + 1;diff --git a/server/services/socialAccounts.js b/server/services/socialAccounts.jsindex 94c6edb900..5b61d4adb8 100644--- a/server/services/socialAccounts.js+++ b/server/services/socialAccounts.js@@ -9,12 +9,11 @@* - Future account management automation*/-import { readFile, writeFile } from 'fs/promises';-import { existsSync } from 'fs';+import { writeFile } from 'fs/promises';import { join } from 'path';import { v4 as uuidv4 } from 'uuid';import EventEmitter from 'events';-import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';const DATA_FILE = join(PATHS.digitalTwin, 'social-accounts.json');@@ -135,14 +134,7 @@ async function loadAccounts() {await ensureDir(PATHS.digitalTwin);- if (!existsSync(DATA_FILE)) {- cache = { accounts: {} };- cacheTimestamp = now;- return cache;- }-- const content = await readFile(DATA_FILE, 'utf-8');- cache = JSON.parse(content);+ cache = await readJSONFile(DATA_FILE, { accounts: {} });cacheTimestamp = now;return cache;}