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: sanitize screenshots[] paths in aiToolkit runner to block arbitrary file read (#1870)
[._.]/ Adam Eivy91c68bd9b7e9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 59f7cdb00f..08bfff7d0e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -9,6 +9,7 @@- **Backup restore/delete path validation hardened** — `subdirFilter` on `POST /api/backup/restore` was an unconstrained string interpolated into an rsync `--include=${subdirFilter}/***` arg, so `*` could override the filter chain (restoring everything over live data) and `../foo` could traverse out of the snapshot subdir; it now validates against a relative path pattern that rejects wildcard, `..`, and absolute-path segments, with a mirrored defense-in-depth guard in `restoreSnapshot` for non-route callers. `deleteBackup` previously validated `filename.replace(/[.]/g,'')` (so the real dotted filename was never checked, leaving only the `startsWith(backupDir)` guard) — it now validates the raw filename directly and explicitly rejects `..`. (#1822)- **Settings API no longer leaks third-party API tokens** — `GET` and `PUT /api/settings` redacted only the top-level `secrets` key, so `imageGen.hfToken` (HuggingFace) and `civitai.apiKey` were returned in full on both initial load and after any save. Both responses now run through a single sanitizer that strips those tokens (sibling config preserved), matching how the Settings UI already reads only token *presence* from the dedicated `/image-gen/setup/hf-token-status` and `/loras/auth/civitai` status routes. On-disk values are untouched. (#1821)- **Vision-test endpoint no longer reads arbitrary files** — `POST /api/providers/:id/test-vision` took `imagePath` straight from the request body, so a `../` traversal or absolute path could have any readable file base64-encoded and forwarded to the configured external vision provider. The image loader now allowlists `imagePath` to a real image basename under `data/screenshots` (via the canonical `resolveScreenshot` path resolver), rejecting traversal and absolute-path escapes before any file is read or forwarded. (#1820)+- **`POST /api/runs` vision screenshots no longer read arbitrary files** — the same unsanitized-`imagePath` gap as #1820 lived in the vendored aiToolkit runner: `screenshots[]` was validated only as `z.array(z.string())` and passed straight to `loadImageAsBase64`, which did `imagePath.startsWith('/') ? imagePath : join(screenshotsDir, imagePath)` — so `{ "screenshots": ["../../../../etc/passwd"] }` (or an absolute path) could have any readable file base64-encoded and forwarded to the configured external vision provider. Because the toolkit is self-contained (no imports out to PortOS modules), the loader now applies a basename + image-extension allowlist + `resolve().startsWith(screenshotsDir)` containment guard inline — mirroring `resolveScreenshot`'s semantics — and rejects anything outside the screenshots root before any file is read. Rejected paths are logged and skipped (matching the existing missing-image handling), so a bad entry never crashes the out-of-request runner. (#1870)## Addeddiff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex b715a550a0..de51053089 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -1,7 +1,7 @@import { mkdir, readFile, readdir, rm } from 'fs/promises';import { atomicWrite } from './internal/atomicWrite.js';import { existsSync } from 'fs';-import { join, extname } from 'path';+import { join, extname, basename, resolve, sep } from 'path';import { spawn } from 'child_process';import { randomUUID } from 'crypto';import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';@@ -66,8 +66,40 @@ export function createRunnerService(config = {}) {return mimeTypes[ext] || 'image/png';}+ // Allow-list of image extensions a screenshot may carry. Mirrors getMimeType's+ // keys — a path with any other extension (or none) is rejected before we read+ // it off disk.+ const ALLOWED_SCREENSHOT_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);++ // Resolve a caller-supplied screenshot reference to an absolute path that is+ // provably contained in screenshotsDir, or return null. `screenshots[]` on+ // POST /api/runs is unauthenticated user input, so without this guard a value+ // like `../../../../etc/passwd` (or an absolute path) would have any readable+ // file base64-encoded and forwarded to the configured external vision+ // provider — an arbitrary-file-read exfiltration. Mirrors the basename ++ // extension-allow-list + `resolve().startsWith(root)` containment semantics of+ // PortOS's resolveScreenshot (server/lib/fileUtils.js), reimplemented here+ // because the aiToolkit is self-contained and must not import out to PortOS.+ function resolveScreenshotPath(imagePath) {+ if (typeof imagePath !== 'string' || !imagePath) return null;+ // basename strips every directory component, so `../`-traversal and+ // absolute paths collapse to a bare filename before we touch disk.+ const safe = basename(imagePath);+ if (!safe || safe === '.' || safe === '..') return null;+ if (!ALLOWED_SCREENSHOT_EXTENSIONS.has(extname(safe).toLowerCase())) return null;+ const fullPath = resolve(join(screenshotsDir, safe));+ // Defense-in-depth: even after basename, confirm the resolved path stays+ // under the screenshots root before reading it.+ const rootPrefix = resolve(screenshotsDir) + sep;+ if (!fullPath.startsWith(rootPrefix)) return null;+ return fullPath;+ }+async function loadImageAsBase64(imagePath) {- const fullPath = imagePath.startsWith('/') ? imagePath : join(screenshotsDir, imagePath);+ const fullPath = resolveScreenshotPath(imagePath);+ if (!fullPath) {+ throw new Error(`Invalid or disallowed screenshot path: ${imagePath}`);+ }if (!existsSync(fullPath)) {throw new Error(`Image not found: ${fullPath}`);diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex c7963f3ac2..3215c2c17a 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -1,5 +1,5 @@import { describe, it, expect, afterEach, vi } from 'vitest';-import { mkdtemp, rm, readFile } from 'fs/promises';+import { mkdtemp, rm, readFile, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';import { createRunnerService } from './runner.js';@@ -125,6 +125,59 @@ describe('AI Toolkit runner service', () => {expect(fetch).toHaveBeenCalledTimes(1);expect('num_ctx' in JSON.parse(fetch.mock.calls[0][1].body)).toBe(false);});++ it('rejects traversal / absolute screenshot paths and only forwards in-dir images to the vision API', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ const screenshotsDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-shots-'));+ const secretsDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-secret-'));+ tempDirs.push(dataDir, screenshotsDir, secretsDir);++ // A legitimate in-dir screenshot, plus a file outside the screenshots root+ // a traversal/absolute path would try to exfiltrate.+ await writeFile(join(screenshotsDir, 'valid.png'), 'PNGDATA');+ await writeFile(join(secretsDir, 'passwd'), 'root:x:0:0');++ const fetch = stubStreamingFetch();+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const runner = createRunnerService({+ dataDir,+ screenshotsDir,+ hooks: { ensureProviderReady: async () => ({ success: true }) }+ });++ let done;+ const completed = new Promise((resolve) => { done = resolve; });+ await runner.executeApiRun({+ runId: 'run-screenshot-guard',+ provider: runReady(),+ model: null,+ prompt: 'describe these',+ workspacePath: process.cwd(),+ screenshots: [+ 'valid.png',+ '../../../../etc/passwd',+ join(secretsDir, 'passwd'), // absolute path outside the screenshots root+ 'notes.txt' // disallowed extension, even though basename is in-dir+ ],+ onData: undefined,+ onComplete: () => done()+ });+ await completed;++ expect(fetch).toHaveBeenCalledTimes(1);+ const sentContent = JSON.parse(fetch.mock.calls[0][1].body).messages[0].content;+ const imageParts = sentContent.filter((p) => p.type === 'image_url');+ // Only the valid in-dir screenshot is forwarded; the traversal, absolute,+ // and disallowed-extension entries are skipped.+ expect(imageParts).toHaveLength(1);+ expect(imageParts[0].image_url.url.startsWith('data:image/png;base64,')).toBe(true);+ // The secret file's contents are never base64-encoded into the payload.+ const secretB64 = Buffer.from('root:x:0:0').toString('base64');+ expect(JSON.stringify(sentContent)).not.toContain(secretB64);++ errSpy.mockRestore();+ });});describe('AI Toolkit runner — declared extension points', () => {