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: harden upload path containment and stop leaking absolute FS paths (#2518)
Adam Eivye968b9b29a0e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 00e8a76a66..7b55bfd820 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Security- **[issue-2514] Harden AI provider custom endpoints against SSRF / API-key exfiltration.** A provider's `endpoint` is a free-form URL, and model-refresh / API-run paths attached the paid `Authorization: Bearer <apiKey>` and fetched that host with no host checks — a hostile or mistyped endpoint could receive the user's paid LLM key and prompts, or be pointed at a cloud-metadata service (`169.254.169.254`). A new `endpointGuard` now gates every secret-bearing request: loopback/LAN (Tailscale) and known paid-provider hosts are allowed, cloud-metadata hosts are always blocked, and any other host requires the new per-provider **Allow custom endpoint** opt-in. Keyless local-LLM calls (Ollama/LM Studio) are unaffected.+- **[issue-2518] Harden upload path containment and stop leaking absolute FS paths.** The upload/attachment/screenshot routes guarded writes with a bare `resolvedPath.startsWith(DIR)` (no trailing separator, so a sibling like `data/uploads-evil/` string-matched) and the attachment/screenshot responses echoed the absolute on-disk `path` back to the client, leaking the install layout / home-directory username segment. Containment now goes through a shared `isPathInsideDir()` helper (anchored `resolvePath(dir) + sep` prefix, matching `makePathResolver`), responses return only API-relative URLs (`/api/screenshots/<file>`), and the CoS prompt builder resolves those refs back to absolute paths at render time (legacy absolute values pass through unchanged). The `moltbook-claim.mjs` script now logs only the token length + short prefix instead of the full bearer token.## Fixeddiff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 6fa2546955..9e7b751669 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -994,6 +994,30 @@ export function assertSafeFilename(filename, { extensions, subject = 'filename',}}+/**+ * True when `candidatePath` resolves to a location strictly inside `dir`.+ *+ * Uses the same anchored-prefix containment idiom as `makePathResolver`+ * (`resolvePath(dir) + PATH_SEP`): appending the platform separator to the+ * resolved root means a sibling directory whose name merely *starts with* the+ * root (e.g. `/data/uploads-evil` vs `/data/uploads`) can't slip past a bare+ * `startsWith(root)` check. This is stricter than the `resolvedPath.startsWith(DIR)`+ * guard the upload/attachment/screenshot routes used before. The root itself is+ * NOT reported as "inside" (there's no trailing separator on the bare root),+ * which is the desired behavior for file-containment checks.+ *+ * @param {string} dir - the containing directory (absolute or relative)+ * @param {string} candidatePath - the path to test+ * @returns {boolean}+ */+export function isPathInsideDir(dir, candidatePath) {+ if (typeof dir !== 'string' || typeof candidatePath !== 'string' || !dir || !candidatePath) {+ return false;+ }+ const rootPrefix = resolvePath(dir) + PATH_SEP;+ return resolvePath(candidatePath).startsWith(rootPrefix);+}+/*** Build a single-root path resolver that returns a function with the same* signature as `resolveGalleryImage` / `resolveImageRef` / `resolveTemplateAsset`.diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 2231c4a66d..ffd465afbf 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -32,6 +32,7 @@ import {sha256File,resolveImageInputPath,resolveScreenshot,+ isPathInsideDir,PATHS,sanitizeFilename,getFileExtension,@@ -434,6 +435,34 @@ describe('fileUtils', () => {});});+ describe('isPathInsideDir', () => {+ it('accepts a file directly inside the directory', () => {+ expect(isPathInsideDir('/data/uploads', '/data/uploads/foo.png')).toBe(true);+ expect(isPathInsideDir('/data/uploads', '/data/uploads/sub/foo.png')).toBe(true);+ });++ it('rejects a traversal that escapes the directory', () => {+ expect(isPathInsideDir('/data/uploads', '/data/uploads/../etc/passwd')).toBe(false);+ expect(isPathInsideDir('/data/uploads', '/etc/passwd')).toBe(false);+ });++ it('rejects a sibling dir whose name merely starts with the root (the trailing-sep bug)', () => {+ // The old `startsWith(DIR)` check without a trailing separator let+ // `/data/uploads-evil/x` slip through because the string prefix matched.+ expect(isPathInsideDir('/data/uploads', '/data/uploads-evil/x.png')).toBe(false);+ });++ it('rejects the root itself (no trailing separator on the bare root)', () => {+ expect(isPathInsideDir('/data/uploads', '/data/uploads')).toBe(false);+ });++ it('returns false for non-string / empty inputs', () => {+ expect(isPathInsideDir('/data/uploads', '')).toBe(false);+ expect(isPathInsideDir('', '/data/uploads/foo.png')).toBe(false);+ expect(isPathInsideDir(null, undefined)).toBe(false);+ });+ });+describe('assertSafeFilename', () => {it('accepts a safe basename with an allowlisted extension', () => {expect(() => assertSafeFilename('foo.png', { extensions: ['.png'] })).not.toThrow();diff --git a/server/routes/attachments.js b/server/routes/attachments.jsindex 2a749128d3..36c690131a 100644--- a/server/routes/attachments.js+++ b/server/routes/attachments.js@@ -10,7 +10,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {ensureDir, pathExists, PATHS, RISKY_MIME_TYPES,- sanitizeFilename, getFileExtension, getMimeType, ATTACHMENT_ALLOWED_EXTENSIONS,+ sanitizeFilename, getFileExtension, getMimeType, ATTACHMENT_ALLOWED_EXTENSIONS, isPathInsideDir,} from '../lib/fileUtils.js';const ATTACHMENTS_DIR = PATHS.cosAttachments;@@ -65,8 +65,7 @@ router.post('/', asyncHandler(async (req, res) => {const filepath = join(ATTACHMENTS_DIR, fname);// Double-check path is within attachments directory (defense in depth)- const resolvedPath = resolve(filepath);- if (!resolvedPath.startsWith(ATTACHMENTS_DIR)) {+ if (!isPathInsideDir(ATTACHMENTS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}@@ -80,7 +79,8 @@ router.post('/', asyncHandler(async (req, res) => {id,filename: fname,originalName: filename,- path: filepath,+ // API-relative URL only — never the absolute FS path (leaks install layout).+ path: `/api/attachments/${encodeURIComponent(fname)}`,size: buffer.length,mimeType});@@ -94,7 +94,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {const filepath = resolve(ATTACHMENTS_DIR, safeFilename);// Verify the resolved path is within attachments directory- if (!filepath.startsWith(ATTACHMENTS_DIR)) {+ if (!isPathInsideDir(ATTACHMENTS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}@@ -120,7 +120,7 @@ router.delete('/:filename', asyncHandler(async (req, res) => {const filepath = resolve(ATTACHMENTS_DIR, safeFilename);// Verify the resolved path is within attachments directory- if (!filepath.startsWith(ATTACHMENTS_DIR)) {+ if (!isPathInsideDir(ATTACHMENTS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}@@ -148,7 +148,8 @@ router.get('/', asyncHandler(async (req, res) => {const ext = getFileExtension(filename);return {filename,- path: filepath,+ // API-relative URL only — never the absolute FS path (leaks install layout).+ path: `/api/attachments/${encodeURIComponent(filename)}`,size: stats.size,mimeType: getMimeType(ext),createdAt: stats.birthtimediff --git a/server/routes/attachments.test.js b/server/routes/attachments.test.jsnew file mode 100644index 0000000000..d2bab9f6a2--- /dev/null+++ b/server/routes/attachments.test.js@@ -0,0 +1,67 @@+import { describe, it, expect, vi, afterAll } from 'vitest';+import express from 'express';+import { rmSync } from 'fs';+import { dirname } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Point the attachments root at a throwaway temp dir but keep every real+// helper. Temp dir created inside the (hoisted) factory to avoid a TDZ.+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ const { mkdtempSync } = await import('fs');+ const { tmpdir } = await import('os');+ const { join } = await import('path');+ const root = mkdtempSync(join(tmpdir(), 'portos-attachments-'));+ return { ...actual, PATHS: { ...actual.PATHS, cosAttachments: join(root, 'attachments') } };+});++import { PATHS } from '../lib/fileUtils.js';+import attachmentRoutes from './attachments.js';++const buildApp = () => {+ const app = express();+ app.use(express.json({ limit: '20mb' }));+ app.use('/api/attachments', attachmentRoutes);+ app.use(errorMiddleware);+ return app;+};++describe('attachments routes (#2518)', () => {+ afterAll(() => rmSync(dirname(PATHS.cosAttachments), { recursive: true, force: true }));++ it('POST returns an API-relative URL, never an absolute FS path', async () => {+ const res = await request(buildApp())+ .post('/api/attachments')+ .send({ data: Buffer.from('hello doc').toString('base64'), filename: 'notes.txt' });++ expect(res.status).toBe(200);+ expect(res.body.path).toMatch(/^\/api\/attachments\//);+ expect(res.body.path).not.toContain(PATHS.cosAttachments);+ expect(res.body.path).toBe(`/api/attachments/${encodeURIComponent(res.body.filename)}`);+ });++ it('GET list returns API-relative URLs, never absolute FS paths', async () => {+ const app = buildApp();+ await request(app)+ .post('/api/attachments')+ .send({ data: Buffer.from('another doc').toString('base64'), filename: 'more.txt' });++ const res = await request(app).get('/api/attachments');+ expect(res.status).toBe(200);+ expect(Array.isArray(res.body.attachments)).toBe(true);+ expect(res.body.attachments.length).toBeGreaterThan(0);+ for (const att of res.body.attachments) {+ expect(att.path).toMatch(/^\/api\/attachments\//);+ expect(att.path).not.toContain(PATHS.cosAttachments);+ }+ });++ it('rejects a disallowed extension', async () => {+ const res = await request(buildApp())+ .post('/api/attachments')+ .send({ data: Buffer.from('x').toString('base64'), filename: 'evil.exe' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('INVALID_FILE_TYPE');+ });+});diff --git a/server/routes/screenshots.js b/server/routes/screenshots.jsindex 901423d79d..b104923133 100644--- a/server/routes/screenshots.js+++ b/server/routes/screenshots.js@@ -4,7 +4,7 @@ import { existsSync } from 'fs';import { join, resolve } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { ensureDir, PATHS, sanitizeFilename } from '../lib/fileUtils.js';+import { ensureDir, PATHS, sanitizeFilename, isPathInsideDir } from '../lib/fileUtils.js';const SCREENSHOTS_DIR = PATHS.screenshots;@@ -77,8 +77,7 @@ router.post('/', asyncHandler(async (req, res) => {const filepath = join(SCREENSHOTS_DIR, fname);// Double-check path is within screenshots directory (defense in depth)- const resolvedPath = resolve(filepath);- if (!resolvedPath.startsWith(SCREENSHOTS_DIR)) {+ if (!isPathInsideDir(SCREENSHOTS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}@@ -89,7 +88,8 @@ router.post('/', asyncHandler(async (req, res) => {res.json({id,filename: fname,- path: filepath,+ // API-relative URL only — never the absolute FS path (leaks install layout).+ path: `/api/screenshots/${encodeURIComponent(fname)}`,size: buffer.length});}));@@ -102,7 +102,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {const filepath = resolve(SCREENSHOTS_DIR, safeFilename);// Verify the resolved path is within screenshots directory- if (!filepath.startsWith(SCREENSHOTS_DIR)) {+ if (!isPathInsideDir(SCREENSHOTS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}diff --git a/server/routes/screenshots.test.js b/server/routes/screenshots.test.jsnew file mode 100644index 0000000000..1e3ec3e678--- /dev/null+++ b/server/routes/screenshots.test.js@@ -0,0 +1,56 @@+import { describe, it, expect, vi, afterAll } from 'vitest';+import express from 'express';+import { rmSync } from 'fs';+import { dirname } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++// Point the screenshots root at a throwaway temp dir but keep every real+// helper (sanitizeFilename, isPathInsideDir, ensureDir, ...). The temp dir is+// created inside the (hoisted) factory to avoid a TDZ on an outer const.+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ const { mkdtempSync } = await import('fs');+ const { tmpdir } = await import('os');+ const { join } = await import('path');+ const root = mkdtempSync(join(tmpdir(), 'portos-screenshots-'));+ return { ...actual, PATHS: { ...actual.PATHS, screenshots: join(root, 'screenshots') } };+});++import { PATHS } from '../lib/fileUtils.js';+import screenshotRoutes from './screenshots.js';++const buildApp = () => {+ const app = express();+ app.use(express.json({ limit: '20mb' }));+ app.use('/api/screenshots', screenshotRoutes);+ app.use(errorMiddleware);+ return app;+};++// Minimal valid PNG: 89 50 4E 47 magic + padding to clear the 12-byte floor.+const pngBase64 = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d]).toString('base64');++describe('screenshots routes (#2518)', () => {+ afterAll(() => rmSync(dirname(PATHS.screenshots), { recursive: true, force: true }));++ it('returns an API-relative URL, never an absolute FS path', async () => {+ const res = await request(buildApp())+ .post('/api/screenshots')+ .send({ data: pngBase64, filename: 'shot.png' });++ expect(res.status).toBe(200);+ expect(res.body.path).toMatch(/^\/api\/screenshots\//);+ // The response must not leak the on-disk location.+ expect(res.body.path).not.toContain(PATHS.screenshots);+ expect(res.body.path).toBe(`/api/screenshots/${encodeURIComponent(res.body.filename)}`);+ });++ it('rejects non-image content (magic-byte guard)', async () => {+ const res = await request(buildApp())+ .post('/api/screenshots')+ .send({ data: Buffer.from('not an image at all here').toString('base64'), filename: 'x.png' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('INVALID_FILE_TYPE');+ });+});diff --git a/server/routes/uploads.js b/server/routes/uploads.jsindex be644e5179..957f7669ec 100644--- a/server/routes/uploads.js+++ b/server/routes/uploads.js@@ -9,7 +9,7 @@ import { existsSync } from 'fs';import { join, resolve } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { ensureDir, PATHS, RISKY_MIME_TYPES, sanitizeFilename, getFileExtension, getMimeType } from '../lib/fileUtils.js';+import { ensureDir, PATHS, RISKY_MIME_TYPES, sanitizeFilename, getFileExtension, getMimeType, isPathInsideDir } from '../lib/fileUtils.js';const UPLOADS_DIR = PATHS.uploads;@@ -59,8 +59,7 @@ router.post('/', asyncHandler(async (req, res) => {const filepath = join(UPLOADS_DIR, fname);// Double-check path is within uploads directory (defense in depth)- const resolvedPath = resolve(filepath);- if (!resolvedPath.startsWith(UPLOADS_DIR)) {+ if (!isPathInsideDir(UPLOADS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}@@ -125,7 +124,7 @@ router.get('/:filename', asyncHandler(async (req, res) => {const safeFilename = sanitizeFilename(filename);const filepath = resolve(UPLOADS_DIR, safeFilename);- if (!filepath.startsWith(UPLOADS_DIR)) {+ if (!isPathInsideDir(UPLOADS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}@@ -150,7 +149,7 @@ router.delete('/:filename', asyncHandler(async (req, res) => {const safeFilename = sanitizeFilename(filename);const filepath = resolve(UPLOADS_DIR, safeFilename);- if (!filepath.startsWith(UPLOADS_DIR)) {+ if (!isPathInsideDir(UPLOADS_DIR, filepath)) {throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });}diff --git a/server/scripts/moltbook-claim.mjs b/server/scripts/moltbook-claim.mjsindex e034530a61..3f0c8a8d4c 100644--- a/server/scripts/moltbook-claim.mjs+++ b/server/scripts/moltbook-claim.mjs@@ -27,8 +27,12 @@ if (!token || !tweetUrl) {const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));+// Never print the full claim token — it's a bearer credential. Log only its+// length and a short prefix so the run is identifiable without leaking it.+const tokenHint = `${token.slice(0, 6)}… (${token.length} chars)`;+console.log(`🦞 Moltbook Claim Bot`);-console.log(`🔑 Token: ${token}`);+console.log(`🔑 Token: ${tokenHint}`);console.log(`🐦 Tweet: ${tweetUrl}`);console.log(`⏱️ Backoff: ${BACKOFF_MS / 1000}s between attempts`);console.log(`🔁 Max attempts: ${MAX_ATTEMPTS}\n`);diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex cefc6b2610..241f4078d0 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -6,7 +6,7 @@* Also handles JIRA ticket creation and app workspace resolution.*/-import { join } from 'path';+import { join, basename } from 'path';import { stat } from 'fs/promises';import { homedir } from 'os';import { getMemorySection } from './memoryRetriever.js';@@ -222,10 +222,10 @@ export function buildTaskBlock(task, { screenshotsAsList = false } = {}) {const targetApp = app && app !== PORTOS_APP_ID ? `**Target App**: ${app}` : '';const screenshots = renderFileListField('Screenshots', task.metadata?.screenshots,- (s) => `\`${s}\``, (s) => s, screenshotsAsList+ (s) => `\`${resolveTaskFileRef(s)}\``, (s) => resolveTaskFileRef(s), screenshotsAsList);const label = (f) => (f?.originalName || f?.filename || f?.path || '').toString();- const path = (f) => (f?.path || '').toString();+ const path = (f) => resolveTaskFileRef((f?.path || '').toString());const attachments = renderFileListField('Attachments', task.metadata?.attachments,(f) => `\`${path(f)}\` (${label(f)})`, (f) => `${label(f)} (${path(f)})`, screenshotsAsList@@ -233,6 +233,35 @@ export function buildTaskBlock(task, { screenshotsAsList = false } = {}) {return { description, targetApp, screenshots, attachments };}+// Map for API-relative upload URLs → the on-disk root the agent should read.+const TASK_REF_ROOTS = {+ '/api/screenshots/': PATHS.screenshots,+ '/api/attachments/': PATHS.cosAttachments,+ '/api/uploads/': PATHS.uploads,+};++/**+ * Resolve a stored screenshot/attachment reference to an absolute filesystem+ * path the CoS agent can open with its filesystem tools.+ *+ * Uploads now return API-relative URLs (`/api/screenshots/<file>`) instead of+ * absolute paths (issue #2518 — absolute paths leaked the install layout in the+ * HTTP response), so tasks created after that change store the relative URL.+ * Convert those back to an absolute path here, at prompt-build time, where the+ * absolute path is local-only and never persisted or published. Legacy tasks+ * that stored an absolute path (or any non-`/api/` value) are passed through+ * unchanged so existing queues keep rendering the same path.+ */+function resolveTaskFileRef(ref) {+ if (typeof ref !== 'string' || !ref) return ref;+ for (const [prefix, root] of Object.entries(TASK_REF_ROOTS)) {+ if (ref.startsWith(prefix)) {+ return join(root, basename(decodeURIComponent(ref)));+ }+ }+ return ref;+}+/*** Undo the COS-TASKS.md round-trip split before rendering. The queue path in* `cosTaskGenerator.js` persists a generated multi-line prompt by moving thediff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 7d07ae8e8f..4bd17e9a83 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -14,6 +14,8 @@*/import { describe, it, expect, vi } from 'vitest';+import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';// Mock heavy dependencies used by the full (api) prompt path so the API-routing// regression test doesn't try to hit the memory DB, digital-twin services, or@@ -209,6 +211,29 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/`\/tmp\/attachments\/b-456\.png` \(photo-two\.png\)/);});+ it('resolves API-relative screenshot URLs (#2518) to absolute FS paths so the agent can read them', () => {+ // Uploads now return `/api/screenshots/<file>` instead of an absolute+ // path (no install-layout leak in the HTTP response); the prompt builder+ // must map that back to an on-disk path for the agent's filesystem tools.+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { screenshots: ['/api/screenshots/abcd1234-shot.png'] } }),+ '/r', null, isTruthyMeta);+ const abs = join(PATHS.screenshots, 'abcd1234-shot.png');+ expect(prompt).toContain(`\`${abs}\``);+ expect(prompt).not.toMatch(/`\/api\/screenshots\//);+ });++ it('resolves API-relative attachment URLs (#2518) to absolute FS paths for the agent', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { attachments: [+ { filename: 'a-123.png', originalName: 'photo-one.png', path: '/api/attachments/a-123.png' },+ ] } }),+ '/r', null, isTruthyMeta);+ const abs = join(PATHS.cosAttachments, 'a-123.png');+ expect(prompt).toContain(`\`${abs}\` (photo-one.png)`);+ expect(prompt).not.toMatch(/`\/api\/attachments\//);+ });+it('renders the worktree block with branch + path when worktreeInfo is present', () => {const wt = {branchName: 'cos/test-1',