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
docs: better audit changelog entry + plan update
Adam Eivy8626fb1683f5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 27ace182a5..703c18ec6d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -45,6 +45,10 @@- **MortalLoom iCloud sync** — new Settings tab (Settings → MortalLoom) lets PortOS share Goals and Meatspace data with the MortalLoom iOS/macOS app by reading from and writing to the app's iCloud ubiquity container (`~/Library/Mobile Documents/iCloud~net~shadowpuppet~MeatSpaceTracker/Documents/MortalLoom.json`). When enabled, PortOS treats the iCloud file as the source of truth for alcohol drinks, nicotine entries, blood tests, body composition, epigenetic tests, eye exams, and goals — and every add/update/remove flow mirrors back to it so edits on either side stay in sync. Non-destructive one-shot "Import from MortalLoom" button for adopting the iCloud data into local PortOS stores by id-dedup. New `server/services/mortalLoomStore.js` exposes tight primitives (`readStore`, `updateStore`, `mlPush/mlPatchById/mlRemoveById/mlReplace`, `mlArrayIfEnabled`, `mlIdAtDateIndex`) used by `meatspaceHealth`, `meatspaceAlcohol`, `meatspaceNicotine`, and `identity`.- **MortalLoom promo banner on Meatspace + Goals pages** — dismissible banner (stored in `localStorage` as `mortalloom-banner-dismissed-v1`) linking to the App Store (`id6760883701`) and to the new Settings tab for iCloud sync configuration.+## Security++- **Dependency CVE sweep + SQL/JQL identifier escaping** — `/do:better` audit surfaced a handful of known-CVE dependency ranges and two string-interpolation sites. Upgraded `react-router-dom` 7.1.1 → 7.5.2 (GHSA-2w69-qvjg-hvjx + GHSA-8v8x-cx79-35w7 — XSS via `<Link to>` open redirect + SSR XSS). Added root `package.json` overrides to pin transitive deps against known issues: `socket.io-parser` >= 4.2.6 (GHSA-cqmj-92ph-6vvx binary-attachment OOM DoS), `path-to-regexp` >= 8.3.1 (GHSA-j3q9-mxjg-w52f ReDoS via Express 5's route matcher), `lodash` >= 4.17.21 (prototype pollution via `pm2`'s transitive dep), `basic-ftp` >= 5.2.3 (CRLF injection via `pm2`'s transitive dep), `follow-redirects` >= 1.15.12 (Authorization header forwarded on cross-origin redirects), and `brace-expansion` >= 2.0.2 (ReDoS). On the app code side, `server/routes/database.js` was building DDL like `CREATE USER ${pgUser} WITH PASSWORD '${pgPassword}'` via raw string interpolation — new `pgQuoteIdentifier()` / `pgEscapeString()` helpers double embedded quotes and wrap in standard SQL quoting before interpolation into `CREATE ROLE`/`CREATE DATABASE`/`DROP DATABASE`/`ALTER ROLE PASSWORD` and the `SELECT ... WHERE datname = ...` lookup. `server/services/jira.js`'s "find epic" JQL query (`project = "${projectKey}" AND summary ~ "${query}"`) escapes `"` in both values before interpolation. Even on a single-user Tailscale deployment, misconfigured env vars (`PGUSER`/`PGDATABASE` containing metacharacters) or pasted Jira search terms with quotes would have broken the statement or altered semantics — now they pass through as literal strings.+## Fixed- **Self-app "Launch" button opened an unreachable URL from the HTTP loopback mirror** — clicking Launch on `/apps/portos-default/overview` while browsing via `http://localhost:5553` built `http://localhost:5555` (hard-coded to the baseline app's `uiPort`), but port 5555 only speaks HTTPS when the Tailscale cert is active — so the tab opened to an empty reply. The tile grid (`AppTile.jsx`) and the detail view's Launch button (`AppDetailView.jsx`) now detect the self-app (`PORTOS_APP_ID`) and launch at `window.location.origin` so the scheme + port match the active session (HTTPS on 5555 or the HTTP loopback on 5553). Other apps still use `{protocol}//{hostname}:{uiPort}` as before.diff --git a/PLAN.md b/PLAN.mdindex aef775d1a3..443eb3e7da 100644--- a/PLAN.md+++ b/PLAN.md@@ -33,6 +33,95 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]---+## Better Audit — 2026-04-21++Summary: 70+ findings across 45+ files. 2 foundation utilities to extract. 6 PR categories: security, code-quality, dry, bugs-perf, stack-specific, tests. Architecture + Dep Freedom categories deferred (deep refactors / high conflict risk).++### Foundation — Shared Utilities++1. `server/lib/fileUtils.js` — export `atomicWrite(filePath, data)` replacing 12 inline `tmp + rename` sequences across service files.+2. `server/services/socket.js` — add `broadcastToSet` + `registerSubscriber` helpers to collapse 6× duplicated subscriber/broadcast boilerplate (also fixes the missing `shellService.unsubscribeSessionList` on disconnect).++### Security & Secrets+- [ ] **[HIGH]** `react-router` 7.1.1 (client) — XSS CVEs (GHSA-2w69-qvjg-hvjx, GHSA-8v8x-cx79-35w7); upgrade to >= 7.5.2+- [ ] **[HIGH]** `socket.io-parser` 4.2.5 (server + client) — OOM DoS (GHSA-cqmj-92ph-6vvx); upgrade socket.io family+- [ ] **[HIGH]** `path-to-regexp` 8.3.0 via Express 5 — ReDoS; add root-package override+- [ ] **[HIGH]** `lodash` 4.17.23 via pm2 — code injection + prototype pollution; add override+- [ ] **[HIGH]** `basic-ftp` via pm2 — CRLF injection; add override+- [ ] **[MEDIUM]** `server/routes/database.js:326,330,334,422` — DDL identifier string interpolation; add `pgQuoteIdentifier` helper+- [ ] **[MEDIUM]** `server/services/jira.js:414` — JQL injection via `projectKey`/`query` string interpolation; escape `"`+- [ ] **[MEDIUM]** `follow-redirects`, `brace-expansion` transitive ReDoS/credential-leak — add overrides++### Code Quality+- [ ] **[HIGH]** `server/services/cos.js:3033-3035` — remove `NODE_ENV !== 'test'` init guard (test-specific hack in prod)+- [ ] **[HIGH]** `autofixer/server.js`, `autofixer/ui.js` — 20+ console.log statements missing emoji prefix (production server)+- [ ] **[HIGH]** `client/src/components/settings/GeneralTab.jsx` + VoiceTab/ImageGenTab/BackupTab/MortalLoomTab/TelegramTab/DatabaseTab — inconsistent `await X.then().catch().finally()` patterns; convert to try/catch+- [ ] **[MEDIUM]** `server/services/visionTest.js`, `agentPersonalityGenerator.js` — multi-line log blocks; combine+- [ ] **[MEDIUM]** `server/services/agentCliSpawning.js:293-304` — try/catch swallows claude settings read error+- [ ] **[MEDIUM]** `server/services/moltworldWs.js` (4 sites), `messageSender.js:46`, `DatabaseTab.jsx:227` — `.catch(() => {})` empty swallow; add warn logs+- [ ] **[MEDIUM]** `server/services/visionTest.js:124`, `server/routes/voice.js:160` — brittle `err.message.includes`/`startsWith` checks; use typed errors+- [ ] **[MEDIUM]** `server/services/cos.js:166,357`, `lmStudioManager.js:66` — extract magic numbers (90, 500, 30000) to named constants+- [ ] **[MEDIUM]** `client/src/components/Layout.jsx:149-171` — alphabetize nav (Data before Dev Tools)+- [ ] **[MEDIUM]** `client/src/pages/DataDog.jsx`, `Jira.jsx` — prefix `console.error` with `❌ `+- [ ] **[MEDIUM]** `server/lib/fileUtils.js:181,192,224,287` — emoji prefix on 4 console.warn+- [ ] **[MEDIUM]** `server/services/character.js:197-212` — `console.log` → `console.warn` in swallow-and-continue catch blocks++### DRY & YAGNI+- [ ] **[HIGH]** `server/services/socket.js:595-814` — 6× duplicated `broadcastTo*` + `subscribe`/`unsubscribe` pairs; extract helpers+- [ ] **[HIGH]** 12 service files — atomic write (`tmp + rename`) pattern duplicated; extract `atomicWrite` to `server/lib/fileUtils.js`+- [ ] **[HIGH]** 8 client components — `formatBytes`/`formatTime`/`formatDuration`/`timeAgo`/`formatDate` locally redefined; import from `client/src/utils/formatters.js`+- [ ] **[HIGH]** `server/services/dataManager.js:8` — lone `join(process.cwd(), 'data')`; use `PATHS.data` from `fileUtils.js` like 20+ other services+- [ ] **[MEDIUM]** `server/services/digital-twin-meta.js:12-13` — remove unused `soulEvents` alias; emit on `digitalTwinEvents` directly+- [ ] **[MEDIUM]** `server/services/messageSync.js:233` — replace dynamic `await import('uuid')` with static `lib/uuid.js` import++### Bugs, Performance & Error Handling+- [ ] **[CRITICAL]** `server/services/brain.js:113-116` — `setTimeout` never cleared on CLI child close/error; leaks for up to 300s+- [ ] **[CRITICAL]** `server/lib/telegramClient.js:94` — `pollLoop().catch(() => {})` silently kills polling; add log + 5s retry+- [ ] **[HIGH]** `server/services/clinvar.js:62` — 100MB+ NCBI fetch has no AbortSignal; add 5-minute timeout+- [ ] **[HIGH]** `server/services/brain.js:126` — API provider fetch has no AbortSignal; add `provider.timeout || 300000`+- [ ] **[HIGH]** `server/services/socket.js` disconnect handler — missing `shellService.unsubscribeSessionList(socket)`; unbounded Set growth+- [ ] **[HIGH]** `server/services/loops.js:308` — floating `executeIteration(loop)` promise; errors silently lost+- [ ] **[MEDIUM]** `server/services/aiDetect.js:166`, `meatspacePostLlm.js:91`, `memoryEmbeddings.js:202,243`, `telegramBridge.js:102` — missing AbortSignal timeouts+- [ ] **[MEDIUM]** `server/lib/httpClient.js:38` — abort event listener never removed; closure leak+- [ ] **[MEDIUM]** `server/services/feeds.js:223-231` — sequential feed refresh; use concurrency-bounded `Promise.allSettled`+- [ ] **[MEDIUM]** `server/services/feeds.js:234-248` — full-sort-then-paginate on every request++### Stack-Specific+- [ ] **[MEDIUM]** `server/routes/systemHealth.js:13,32` — wrap async handlers with `asyncHandler`+- [ ] **[MEDIUM]** `server/index.js` — no SIGTERM/SIGINT handler; add graceful pool.close() + httpServer.close() on shutdown+- [ ] **[MEDIUM]** `client/src/components/messages/MessageDetail.jsx:50` — iframe image `'load'` listeners never removed; use `{ once: true }`++### Test Quality & Coverage (Phase 4c)+- [ ] **[CRITICAL][VACUOUS]** `server/services/agents.test.js` — entire file re-implements agent logic inline; never imports `agents.js`. Rewrite against real exports.+- [ ] **[CRITICAL][VACUOUS]** `server/services/socket.test.js` — entire file tests local vars; never imports `socket.js`. Rewrite against real `initSocket`.+- [ ] **[CRITICAL][MISSING]** `server/services/cos.js` — 3035-line god file, no test sibling. Add tests for `evaluateTasks` priority ordering + `dequeueNextTask` capacity guards.+- [ ] **[CRITICAL][MISSING]** `server/services/agentLifecycle.js` — no tests for `spawnAgentForTask` or `handleAgentCompletion`.+- [ ] **[HIGH][MISSING]** `server/services/loops.js`, `clinvar.js`, `telegramBridge.js` — create test files.+- [ ] **[HIGH][VACUOUS]** `server/services/usage.test.js` — asserts `typeof === 'number'`; mock I/O and assert exact streak values.+- [ ] **[HIGH][VACUOUS]** `server/services/cosRunnerClient.test.js:68-75` — "no throw" assertion is trivially true; fire mock event, assert handler called.+- [ ] **[HIGH][WEAK]** `server/routes/cos.test.js` — mocks full service; add tests where mocked functions throw.+- [ ] **[HIGH][WEAK]** `server/services/subAgentSpawner.test.js:14-260` — `selectModelForTask` re-implemented locally; import real function.+- [ ] **[MEDIUM]** `thinkingLevels.test.js`, `brainSyncLog.test.js`, `featureAgents.test.js`, `brain.test.js` — weak/vacuous assertions.++### Deferred to Backlog (too risky / too broad for auto-remediation)++**Architecture refactors** (tracked for human-led planning):+- `server/services/cos.js` — 3035-line god file split into cosTaskStore/cosTaskGenerator/cosJobScheduler/cosHealthMonitor+- `server/services/agentLifecycle.js` — 1271 lines; extract prepareAgentWorkspace/resolveProvider/processCompletion+- `server/services/identity.js` — 1917 lines mixing genomic markers + longevity + goals + todos+- `server/services/taskSchedule.js` — 2201 lines; extract prompt management to `taskPromptService.js`+- `server/services/socket.js` — fan-in coupling hub; split into domain-specific socket modules+- `server/routes/apps.js` — 1126 lines with inline `npm install` orchestration; extract to `appBuilder.js`+- `server/routes/scaffold.js` — scaffold generation logic belongs in `services/scaffolding/`+- `server/cos-runner/index.js:395-612` — 217-line inline /spawn handler; extract service+- `client/src/components/goals/GoalDetailPanel.jsx` — 1141-line god component+- `autofixer/ui.js` — 972-line file with inline HTML template+- API contract inconsistency — standardize error response shapes (`asyncHandler` + `ServerError` everywhere)+- Dependency inversion — extract `cosTaskStore.js` so `agentLifecycle.js` doesn't import from high-level `cos.js`++**Dep Freedom**:+- `server/lib/uuid.js` — local wrapper over `crypto.randomUUID()`; retiring requires updating 43 import sites — defer until naturally touched+## Depfree Audit — 2026-03-31 (Heavy Mode) ✅ COMPLETE**Summary:** Removed 13 of 15 targeted packages. 2 deferred (`@dnd-kit/*`, `recharts`) — replacement effort exceeds 300-line heavy-mode ceiling. ~1,100 lines of owned replacement code written across 9 new files.