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
review: guard symlink escape in custom sources, route layeredIntelligence PUT through merge helper (#2262)
Adam Eivye58741b4170c
diff --git a/server/routes/apps.js b/server/routes/apps.jsindex e9c21c2d24..452bcece15 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -591,12 +591,24 @@ router.put('/:id', asyncHandler(async (req, res, next) => {}}- const app = await appsService.updateApp(req.params.id, data);+ // layeredIntelligence must go through the dedicated merge helper — the generic+ // updateApp shallow-REPLACES the nested object, so a partial patch like+ // { layeredIntelligence: { enabled: true } } would wipe stored sources /+ // allowedScopes / providerId / lastRunAt. Pull it out, apply the rest, then+ // merge-apply the config so untouched fields are preserved.+ const { layeredIntelligence: liUpdate, ...rest } = data;+ const app = await appsService.updateApp(req.params.id, rest);if (!app) {throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });}+ if (liUpdate !== undefined) {+ const merged = await appsService.updateAppLayeredIntelligence(req.params.id, liUpdate);+ res.json(merged || app);+ return;+ }+res.json(app);}));diff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex 1aa8bc742b..3f582ea22f 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -13,6 +13,7 @@ vi.mock('../services/apps.js', () => ({archiveApp: vi.fn(),updateAppTaskTypeOverride: vi.fn(),getAppTaskTypeOverrides: vi.fn(),+ updateAppLayeredIntelligence: vi.fn(),toggleAllAppTaskTypes: vi.fn(),notifyAppsChanged: vi.fn(),PORTOS_APP_ID: 'portos-default'@@ -261,6 +262,22 @@ describe('Apps Routes', () => {expect(response.status).toBe(404);});+ it('routes a layeredIntelligence update through the dedicated merge helper (not the shallow updateApp)', async () => {+ appsService.updateApp.mockResolvedValue({ id: 'app-001', name: 'App' });+ appsService.updateAppLayeredIntelligence.mockResolvedValue({ id: 'app-001', layeredIntelligence: { enabled: true, sources: { goals: true } } });++ const response = await request(app)+ .put('/api/apps/app-001')+ .send({ layeredIntelligence: { enabled: true } });++ expect(response.status).toBe(200);+ // The nested config must NOT be passed to the shallow updateApp (which would wipe it)…+ expect(appsService.updateApp).toHaveBeenCalledWith('app-001', expect.not.objectContaining({ layeredIntelligence: expect.anything() }));+ // …it goes through the preserving merge helper instead.+ expect(appsService.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-001', { enabled: true });+ expect(response.body.layeredIntelligence.enabled).toBe(true);+ });+it('writes changed ports back to the ecosystem config (source of truth)', async () => {// repoPath must exist on disk so the pathExists guard passes.const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173, uiPort: 5174 };diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex c6f885eee6..83da94837e 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -21,7 +21,7 @@import { spawn } from 'child_process';import { join, resolve, relative, isAbsolute } from 'path';-import { readFile, writeFile, appendFile } from 'fs/promises';+import { readFile, writeFile, appendFile, realpath } from 'fs/promises';import { existsSync } from 'fs';import { DAY, tryReadFile, readJSONFile, safeJSONParse, PATHS } from '../lib/fileUtils.js';@@ -335,22 +335,39 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {}for (const custom of src.custom || []) {if (custom?.type === 'file' && typeof custom.ref === 'string' && repo) {- // Confine the ref to the app repo: an absolute path or a `../` escape must- // not leak arbitrary readable files into the LLM prompt. resolve() +- // relative() rejects anything that lands outside repoPath.- const abs = resolve(repo, custom.ref);- const rel = relative(repo, abs);- if (rel.startsWith('..') || isAbsolute(rel)) {+ const safe = await confineToRepo(repo, custom.ref);+ if (!safe) {console.warn(`⚠️ Layered Intelligence: custom source "${custom.ref}" escapes repo — skipped`);continue;}- const content = await tryReadFile(abs);+ const content = await tryReadFile(safe);if (content) out[`custom:${custom.ref}`] = content.slice(0, 8000);}}return out;}+/**+ * Confine a custom file `ref` to within `repo` so a hostile/hand-edited config+ * can't read arbitrary files into the LLM prompt. Returns the safe absolute path,+ * or null when it escapes. Guards BOTH lexical traversal (`..` / absolute) AND+ * symlink escape — a symlink inside the repo pointing outside is resolved via+ * realpath and rejected. Missing files return null (nothing to read).+ */+export async function confineToRepo(repo, ref) {+ const abs = resolve(repo, ref);+ const rel = relative(repo, abs);+ if (rel.startsWith('..') || isAbsolute(rel)) return null;+ // Resolve symlinks on both sides; a link inside the repo that points outside+ // is caught here (lexical check above only sees the link's own path).+ const realRepo = await realpath(repo).catch(() => null);+ const realAbs = await realpath(abs).catch(() => null);+ if (!realRepo || !realAbs) return null;+ const realRel = relative(realRepo, realAbs);+ if (realRel.startsWith('..') || isAbsolute(realRel)) return null;+ return realAbs;+}+/*** Normalize a forge issue state to `open` / `closed`. GitLab reports `opened`* (and `closed`/`locked`); GitHub reports `open`/`closed`. Anything that isn't adiff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex b822116c63..04eb668673 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -425,6 +425,31 @@ describe('gatherSources custom file confinement', () => {);expect(Object.keys(out).some(k => k.startsWith('custom:'))).toBe(false);});++ it('refuses a symlink inside the repo that points OUTSIDE it', async () => {+ const { mkdir, symlink } = await import('fs/promises');+ const repo = join(dir, 'repo');+ await mkdir(repo, { recursive: true });+ const secret = join(dir, 'outside-secret.txt');+ await writeFile(secret, 'OUTSIDE_SECRET');+ await symlink(secret, join(repo, 'inside-link'));+ const out = await gatherSources(+ { repoPath: repo },+ { sources: { custom: [{ type: 'file', ref: 'inside-link' }] } }+ );+ expect(Object.keys(out).some(k => k.startsWith('custom:'))).toBe(false);+ });++ it('allows a symlink that resolves to a file INSIDE the repo', async () => {+ const { symlink } = await import('fs/promises');+ await writeFile(join(dir, 'real.md'), 'INSIDE');+ await symlink(join(dir, 'real.md'), join(dir, 'link.md'));+ const out = await gatherSources(+ { repoPath: dir },+ { sources: { custom: [{ type: 'file', ref: 'link.md' }] } }+ );+ expect(out['custom:link.md']).toBe('INSIDE');+ });});describe('forge I/O (injected exec)', () => {