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: release-gate findings (migration resumability, SSRF guard gaps, pm2Home, install race, audit coverage)
[._.]/ Adam Eivy77baae204541
diff --git a/scripts/migrations/202-neutral-sprite-run-dirs.js b/scripts/migrations/202-neutral-sprite-run-dirs.jsindex d2e477698f..e28b383a29 100644--- a/scripts/migrations/202-neutral-sprite-run-dirs.js+++ b/scripts/migrations/202-neutral-sprite-run-dirs.js@@ -42,10 +42,13 @@* are `runtime/…`, no `grok/`); reference anchors (`reference/…`).** Idempotency: gated per record on the presence of a `grok/` directory OR any- * residual `grok/` string in the selection/walk-set (crash-recovery of a run- * that moved the dirs but not the strings). A second run finds neither and- * skips. A move-target collision (`runs/<runId>` already exists) throws for- * that record — the run is left in `grok/` (still readable via the layout-+ * residual `grok/` string in the selection/walk-set/runtime-atlas manifests+ * (crash-recovery of a run that moved the dirs but not all of the strings —+ * including a crash between the walk-set rewrite and the runtime-manifest+ * rewrite, which would otherwise read as "already migrated" and strand the+ * runtime manifests). A second run finds none of these and skips. A+ * move-target collision (`runs/<runId>` already exists) throws for that+ * record — the run is left in `grok/` (still readable via the layout-* agnostic reader) and the migration stays PENDING for a retry, mirroring* migration 200's per-record aggregate-throw.*/@@ -103,6 +106,22 @@ async function listJsonFiles(dir) {return out;}+// True if any compiled-atlas manifest under runtime/vN/ still embeds a+// `grok/` path. Guards a crash between step 4 (walk-set rewritten, so+// selText/wsText already read clean) and step 5 (runtime manifests) from+// making the top-of-record gate see "already migrated" and skip the record+// forever, leaving stale grok/ provenance in the runtime manifests.+async function runtimeHasGrokResidue(runtimeDir) {+ for (const vDir of await readdir(runtimeDir, { withFileTypes: true }).catch(() => [])) {+ if (!vDir.isDirectory() || !/^v\d+$/.test(vDir.name)) continue;+ for (const abs of await listJsonFiles(join(runtimeDir, vDir.name))) {+ const text = await readFile(abs, 'utf8').catch(() => '');+ if (text.includes(`${LEGACY_DIR}/`)) return true;+ }+ }+ return false;+}+// Rewrite `grok/`→`runs/` in one JSON file, writing only when it changed.async function neutralizeJsonFile(abs) {const obj = await readJson(abs);@@ -142,7 +161,12 @@ async function migrateRecord(recDir, recordId) {const hasGrokDir = await exists(grokDir);const selText = await readFile(selAbs, 'utf8').catch(() => '');const wsText = await readFile(wsAbs, 'utf8').catch(() => '');- if (!hasGrokDir && !selText.includes(`${LEGACY_DIR}/`) && !wsText.includes(`${LEGACY_DIR}/`)) {+ if (+ !hasGrokDir &&+ !selText.includes(`${LEGACY_DIR}/`) &&+ !wsText.includes(`${LEGACY_DIR}/`) &&+ !(await runtimeHasGrokResidue(runtimeDir))+ ) {return false; // nothing native/grok here (imported/redraw-only, or already migrated)}diff --git a/scripts/migrations/203-heal-imported-grok-run-paths.js b/scripts/migrations/203-heal-imported-grok-run-paths.jsindex f6607dfd71..070f6ab566 100644--- a/scripts/migrations/203-heal-imported-grok-run-paths.js+++ b/scripts/migrations/203-heal-imported-grok-run-paths.js@@ -133,6 +133,11 @@ async function neutralizeDirectionEntries(recDir, id, directions) {}// True when any JSON state under the record still names `sprites/<id>/grok/`.+// Also scans runtime/vN/ atlas manifests — a crash between step 3 (walk-set+// rewritten) and step 4 (runtime manifests) would otherwise leave selection/+// walk-set/runs/ clean while the compiled-atlas provenance is still stale,+// and this gate reading only those would report "no residue" and skip the+// record forever.async function hasGrokResidue(recDir, id) {const selAbs = join(recDir, 'walk', `${id}-walk-selection-v1.json`);const wsAbs = join(recDir, 'walk', `${id}-walk-set-v1.json`);@@ -145,6 +150,14 @@ async function hasGrokResidue(recDir, id) {// eslint-disable-next-line no-await-in-loop -- short-circuits on first hitif ((await readFile(abs, 'utf8').catch(() => '')).includes(marker)) return true;}+ for (const vDir of await readdir(join(recDir, 'runtime'), { withFileTypes: true }).catch(() => [])) {+ if (!vDir.isDirectory() || !/^v\d+$/.test(vDir.name)) continue;+ // eslint-disable-next-line no-await-in-loop -- short-circuits on first hit+ for (const abs of await listJsonFiles(join(recDir, 'runtime', vDir.name))) {+ // eslint-disable-next-line no-await-in-loop -- short-circuits on first hit+ if ((await readFile(abs, 'utf8').catch(() => '')).includes(marker)) return true;+ }+ }return false;}diff --git a/server/lib/db/schema/audit.js b/server/lib/db/schema/audit.jsindex 11c35e5ca6..5dd1881e4a 100644--- a/server/lib/db/schema/audit.js+++ b/server/lib/db/schema/audit.js@@ -89,7 +89,7 @@ export const auditedTables = ['universes', 'universe_runs', 'pipeline_series', 'pipeline_issues','story_builder_sessions', 'writers_room_works', 'writers_room_folders','writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',- 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'mood_boards',+ 'catalog_user_types', 'creative_director_projects', 'threejs_models', 'image_to_3d_models', 'sprite_records', 'mood_boards','lora_training_runs', 'authors', 'artists', 'albums', 'tracks', 'tribe_people', 'tribe_touchpoints',];diff --git a/server/routes/imageTo3d.js b/server/routes/imageTo3d.jsindex 7d258e031b..a2f40cbd83 100644--- a/server/routes/imageTo3d.js+++ b/server/routes/imageTo3d.js@@ -137,8 +137,22 @@ async function handleTargetInstall(targetId, req, res) {installLog.cancel();// `close` also fires on normal completion; only a live handle means an// install was actually mid-flight.- if (currentKill) currentKill();- installsInFlight.delete(targetId);+ if (currentKill) {+ // A real install is tracked in installsInFlight. Ask the child to+ // terminate, but let the install promise's own `.finally()` (below)+ // release the slot once the kill actually lands — releasing it here,+ // before the child has exited, would let a second install for the same+ // target start while the first is still shutting down, and this+ // handler's own delete would then race the first install's delayed+ // `.finally()`, which could clobber the second install's slot when it+ // settles.+ currentKill();+ } else {+ // Nothing has spawned yet (still resolving env / adapter preflight) —+ // the code below will see `aborted` and bail without ever registering+ // a `.finally()`, so release the slot here or it would leak forever.+ installsInFlight.delete(targetId);+ }safeEnd();});diff --git a/server/routes/logs.js b/server/routes/logs.jsindex 60041c07fd..942a1ca6f1 100644--- a/server/routes/logs.js+++ b/server/routes/logs.js@@ -41,15 +41,15 @@ router.get('/:processName', asyncHandler(async (req, res) => {throw new ServerError('Invalid process name', { status: 400, code: 'INVALID_PROCESS_NAME' });}+ const pm2Home = await appsService.resolvePm2HomeForProcess(safeProcessName);+if (!follow) {// Static log fetch- const logs = await pm2Service.getLogs(safeProcessName, lines)+ const logs = await pm2Service.getLogs(safeProcessName, lines, pm2Home).catch(err => `Error: ${err.message}`);return res.json({ processName: safeProcessName, lines, logs });}- const pm2Home = await appsService.resolvePm2HomeForProcess(safeProcessName);-// SSE streaming — shared header boilerplate via openSseStream; this route// emits named `event:` frames directly so it uses safeEnd but not send.const { safeEnd } = openSseStream(res);diff --git a/server/routes/logs.test.js b/server/routes/logs.test.jsindex 6ea9ee85fe..4748c4e114 100644--- a/server/routes/logs.test.js+++ b/server/routes/logs.test.js@@ -71,6 +71,16 @@ describe('log routes PM2_HOME resolution', () => {expect(pm2Service.getLogs).toHaveBeenCalledWith('example-api', 100, undefined);});+ it('fetches static logs for a process from its resolved custom PM2 home', async () => {+ appsService.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');++ const response = await request(createApp()).get('/api/logs/example-api?lines=50');++ expect(response.status).toBe(200);+ expect(appsService.resolvePm2HomeForProcess).toHaveBeenCalledWith('example-api');+ expect(pm2Service.getLogs).toHaveBeenCalledWith('example-api', 50, '/tmp/example-pm2');+ });+it('follows a process from its resolved custom PM2 home', async () => {appsService.resolvePm2HomeForProcess.mockResolvedValue('/tmp/example-pm2');diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex b8bc1e2f08..f993f66920 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1354,6 +1354,8 @@ DROP TRIGGER IF EXISTS trg_threejs_models_audit ON threejs_models;CREATE TRIGGER trg_threejs_models_audit AFTER UPDATE OR DELETE ON threejs_models FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_image_to_3d_models_audit ON image_to_3d_models;CREATE TRIGGER trg_image_to_3d_models_audit AFTER UPDATE OR DELETE ON image_to_3d_models FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_sprite_records_audit ON sprite_records;+CREATE TRIGGER trg_sprite_records_audit AFTER UPDATE OR DELETE ON sprite_records FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_mood_boards_audit ON mood_boards;CREATE TRIGGER trg_mood_boards_audit AFTER UPDATE OR DELETE ON mood_boards FOR EACH ROW EXECUTE FUNCTION record_audit_log();DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex 823be8c4a5..83f3123633 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -23,6 +23,7 @@ import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { readResponseJson } from '../lib/readResponseJson.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';+import { evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';const DEFAULT_AI_TIMEOUT_MS = 300000;@@ -178,6 +179,17 @@ export async function callProviderAISimple(provider, model, prompt, { temperaturreturn { error: `Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}` };}+ // Never send the API key to an arbitrary/metadata host (SSRF / key+ // exfiltration). Keyless local-LLM calls skip this guard entirely.+ if (provider.apiKey) {+ const guard = evaluateSecretEndpoint(provider.endpoint, {+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+ if (!guard.allowed) {+ return { error: `Provider endpoint blocked: ${guard.reason}` };+ }+ }+const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;diff --git a/server/services/insightsService.test.js b/server/services/insightsService.test.jsindex 4721783bd1..ebe5b68eeb 100644--- a/server/services/insightsService.test.js+++ b/server/services/insightsService.test.js@@ -63,6 +63,40 @@ describe('insightsService.callProviderAISimple — non-JSON-body guard', () => {});});+describe('insightsService.callProviderAISimple — endpoint guard (SSRF / key-exfiltration)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('blocks a keyed provider pointed at a non-allowlisted endpoint and never calls fetch', async () => {+ const result = await callProviderAISimple(+ { ...PROVIDER, apiKey: 'secret-key', endpoint: 'https://not-an-allowlisted-host.example' },+ 'm', 'prompt',+ );+ expect(result.error).toContain('Provider endpoint blocked');+ expect(fetchWithTimeout).not.toHaveBeenCalled();+ });++ it('allows a keyed provider on a non-allowlisted host through when allowCustomEndpoint is true', async () => {+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ choices: [{ message: { content: 'hello' } }] }));+ const result = await callProviderAISimple(+ { ...PROVIDER, apiKey: 'secret-key', endpoint: 'https://not-an-allowlisted-host.example', allowCustomEndpoint: true },+ 'm', 'prompt',+ );+ expect(result).toEqual({ text: 'hello' });+ expect(fetchWithTimeout).toHaveBeenCalled();+ });++ it('allows a keyless provider on a non-allowlisted host through (guard only applies when apiKey is set)', async () => {+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ choices: [{ message: { content: 'hello' } }] }));+ const result = await callProviderAISimple(+ { ...PROVIDER, endpoint: 'https://not-an-allowlisted-host.example' },+ 'm', 'prompt',+ );+ expect(result).toEqual({ text: 'hello' });+ });+});+// Enforces the no-cold-bootstrap trigger contract documented at the generation// entry points: the cached-read paths the Insights page mounts with must be// disk-only and NEVER reach an AI provider. Only the user-triggered *refresh*diff --git a/server/services/visionTest.js b/server/services/visionTest.jsindex 09b2444847..646ae4edf7 100644--- a/server/services/visionTest.js+++ b/server/services/visionTest.js@@ -12,6 +12,7 @@ import { PATHS, resolveScreenshot } from '../lib/fileUtils.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';import { describeImageViaCli } from './visionCli.js';+import { assertSecretEndpoint, evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';const SCREENSHOTS_DIR = PATHS.screenshots;const DEFAULT_VISION_TIMEOUT_MS = 60000;@@ -69,7 +70,11 @@ async function loadImageAsBase64(imagePath) {* truncates mid-output and fails to parse.* @returns {Promise<Object>} - API response*/-async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, timeout = DEFAULT_VISION_TIMEOUT_MS, maxTokens = 500 }) {+async function callVisionAPI({ endpoint, apiKey, allowCustomEndpoint, model, imageDataUrl, prompt, timeout = DEFAULT_VISION_TIMEOUT_MS, maxTokens = 500 }) {+ // Never send the API key to an arbitrary/metadata host (SSRF / key+ // exfiltration). Keyless local-LLM calls skip this guard entirely.+ assertSecretEndpoint(endpoint, { hasSecret: Boolean(apiKey), allowCustomEndpoint: allowCustomEndpoint === true });+await ensureOllamaProviderReady({ endpoint }).then((ready) => {if (!ready.success) throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);});@@ -177,6 +182,7 @@ export async function testVision({ imagePath, prompt, expectedContent, providerIconst apiResponse = await callVisionAPI({endpoint: provider.endpoint,apiKey: provider.apiKey,+ allowCustomEndpoint: provider.allowCustomEndpoint,model: testModel,imageDataUrl,prompt,@@ -279,6 +285,7 @@ export async function describeImageDataUrlDetailed({ dataUrl, prompt, providerIdconst apiResponse = await callVisionAPI({endpoint: provider.endpoint,apiKey: provider.apiKey,+ allowCustomEndpoint: provider.allowCustomEndpoint,model: visionModel,imageDataUrl: dataUrl,prompt: prompt || 'Describe what you see in this image.',@@ -393,6 +400,19 @@ export async function checkVisionHealth(providerId = 'lmstudio') {return { available: false, error: 'Vision requires API provider' };}+ // Never send the API key to an arbitrary/metadata host (SSRF / key+ // exfiltration). Keyless local-LLM calls skip this guard entirely. This+ // function's convention is to return { available: false, error } rather+ // than throw, so evaluate (not assert) the guard.+ if (provider.apiKey) {+ const guard = evaluateSecretEndpoint(provider.endpoint, {+ allowCustomEndpoint: provider.allowCustomEndpoint === true,+ });+ if (!guard.allowed) {+ return { available: false, error: `Provider endpoint blocked: ${guard.reason}` };+ }+ }+// Check if endpoint is reachableconst response = await fetchWithTimeout(`${provider.endpoint}/models`, {headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {}diff --git a/server/services/visionTest.test.js b/server/services/visionTest.test.jsindex 8c1b828a0f..ffb17e3b31 100644--- a/server/services/visionTest.test.js+++ b/server/services/visionTest.test.js@@ -105,6 +105,22 @@ describe('Vision Test Service', () => {expect(result.error).toContain('No model specified');});+ it('blocks a keyed provider pointed at a non-allowlisted endpoint and never calls fetch', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ endpoint: 'https://not-an-allowlisted-host.example',+ });+ resolveScreenshot.mockReturnValue('/mock/screenshots/image.png');+ readFile.mockResolvedValue(mockImageBuffer);++ await expect(testVision({+ imagePath: '/test/image.png',+ prompt: 'Describe this image',+ expectedContent: ['test'],+ })).rejects.toThrow('Blocked outbound API-key request');+ expect(global.fetch).not.toHaveBeenCalled();+ });+it('should successfully test vision when API returns expected content', async () => {getProviderById.mockResolvedValue(mockProvider);resolveScreenshot.mockReturnValue('/mock/screenshots/image.png');@@ -415,5 +431,45 @@ describe('Vision Test Service', () => {expect(result.available).toBe(false);expect(result.error).toContain('not reachable');});++ it('blocks a keyed provider pointed at a cloud-metadata endpoint and never calls fetch', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ endpoint: 'http://169.254.169.254/latest/meta-data/',+ });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(false);+ expect(result.error).toContain('Provider endpoint blocked');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('blocks a keyed provider on a non-allowlisted host when allowCustomEndpoint is not set', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ endpoint: 'https://not-an-allowlisted-host.example',+ });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(false);+ expect(result.error).toContain('Provider endpoint blocked');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('allows a keyed provider on a non-allowlisted host through when allowCustomEndpoint is true', async () => {+ getProviderById.mockResolvedValue({+ ...mockProvider,+ endpoint: 'https://not-an-allowlisted-host.example',+ allowCustomEndpoint: true,+ });+ global.fetch.mockResolvedValue({ ok: true, json: () => Promise.resolve({ data: [] }) });++ const result = await checkVisionHealth('lmstudio');++ expect(result.available).toBe(true);+ expect(global.fetch).toHaveBeenCalled();+ });});});