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: close git argument injection and path traversal in ungated record routes
[._.]/ Adam Eivy7d076d815191
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex a7ccd23c2b..2de8d1c883 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -106,6 +106,17 @@ export function createRunnerService(config = {}) {const RUNS_PATH = join(dataDir, runsDir);const activeRuns = new Map();+ // A run id arrives from an HTTP route param (`DELETE /api/runs/:id`), and+ // Express decodes `%2F`, so `..%2Fbrain` would otherwise `join` out of+ // RUNS_PATH and `rm -r` a sibling data directory. Minted ids are UUIDs; accept+ // only a single plain segment and treat anything else as "no such run".+ const SAFE_RUN_ID = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;+ const existingRunDir = (runId) => {+ if (typeof runId !== 'string' || !SAFE_RUN_ID.test(runId)) return null;+ const runDir = join(RUNS_PATH, runId);+ return existsSync(runDir) ? runDir : null;+ };+// ── Declared extension points ────────────────────────────────────────────// PortOS supplies a CLI runner that knows per-CLI argv conventions (Codex// `exec -`, Antigravity `agy --print`, Claude Code `-p -`) and a TUI runner@@ -939,23 +950,23 @@ export function createRunnerService(config = {}) {},async getRun(runId) {- const runDir = join(RUNS_PATH, runId);- if (!existsSync(runDir)) return null;+ const runDir = existingRunDir(runId);+ if (!runDir) return null;const metadata = safeJsonParse(await readFile(join(runDir, 'metadata.json'), 'utf-8').catch(() => '{}'));return metadata;},async getRunOutput(runId) {- const runDir = join(RUNS_PATH, runId);- if (!existsSync(runDir)) return null;+ const runDir = existingRunDir(runId);+ if (!runDir) return null;return readFile(join(runDir, 'output.txt'), 'utf-8');},async getRunPrompt(runId) {- const runDir = join(RUNS_PATH, runId);- if (!existsSync(runDir)) return null;+ const runDir = existingRunDir(runId);+ if (!runDir) return null;return readFile(join(runDir, 'prompt.txt'), 'utf-8');},@@ -998,8 +1009,8 @@ export function createRunnerService(config = {}) {await service.stopRun(runId);}- const runDir = join(RUNS_PATH, runId);- if (!existsSync(runDir)) return false;+ const runDir = existingRunDir(runId);+ if (!runDir) return false;await withAssetPublication(() => rm(runDir, { recursive: true }));return true;diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex f18ecf4444..083494ed67 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -1956,6 +1956,30 @@ describe('AI Toolkit runner — declared extension points', () => {await rm(dataDir, { recursive: true, force: true });});++ it('treats a run id that climbs out of the runs directory as an unknown run', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-trav-'));+ await mkdir(join(dataDir, 'runs', 'real'), { recursive: true });+ await writeFile(join(dataDir, 'runs', 'real', 'output.txt'), 'out');+ await mkdir(join(dataDir, 'brain'), { recursive: true });+ await writeFile(join(dataDir, 'brain', 'output.txt'), 'secret');+ const runner = createRunnerService({ dataDir });++ // Express decodes %2F in :id, so these are the literal strings a route hands over.+ for (const id of ['../brain', '..', 'real/../../brain', '..\\brain']) {+ expect(await runner.deleteRun(id)).toBe(false);+ expect(await runner.getRunOutput(id)).toBeNull();+ expect(await runner.getRunPrompt(id)).toBeNull();+ expect(await runner.getRun(id)).toBeNull();+ }+ expect(await readFile(join(dataDir, 'brain', 'output.txt'), 'utf-8')).toBe('secret');++ // A genuine run id still resolves and deletes.+ expect(await runner.getRunOutput('real')).toBe('out');+ expect(await runner.deleteRun('real')).toBe(true);++ await rm(dataDir, { recursive: true, force: true });+ });});describe('AI Toolkit runner — built-in executeCliRun spawn (#1865)', () => {diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 9eceeb6b07..4247d9bcd7 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -604,8 +604,9 @@ export const restoreRecommendationSchema = z.object({id: z.string().min(1),});+// weekId becomes the digest filename (`<weekId>.json`), so it must be exactly an ISO week id.export const generateWeeklyDigestSchema = z.object({- weekId: z.string().optional(),+ weekId: z.string().regex(/^\d{4}-W\d{2}$/, 'Invalid weekId format. Use YYYY-WXX (e.g., 2026-W02)').optional(),});// =============================================================================diff --git a/server/routes/cosLearningRoutes.test.js b/server/routes/cosLearningRoutes.test.jsindex c63f81a384..7b8c465305 100644--- a/server/routes/cosLearningRoutes.test.js+++ b/server/routes/cosLearningRoutes.test.js@@ -425,6 +425,17 @@ describe('CoS Learning Routes', () => {expect(response.status).toBe(200);});+ it('rejects a weekId that is not an ISO week id before it can name a file', async () => {+ weeklyDigest.generateWeeklyDigest.mockClear();++ const response = await request(app)+ .post('/api/cos/digest/generate')+ .send({ weekId: '../../brain/memory' });++ expect(response.status).toBe(400);+ expect(weeklyDigest.generateWeeklyDigest).not.toHaveBeenCalled();+ });+it('should generate for current week if weekId not provided', async () => {weeklyDigest.generateWeeklyDigest.mockResolvedValue({ weekId: '2026-W14' });diff --git a/server/services/agentDrafts.js b/server/services/agentDrafts.jsindex e72a350eab..0f20012800 100644--- a/server/services/agentDrafts.js+++ b/server/services/agentDrafts.js@@ -8,10 +8,17 @@import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, PATHS, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { isTopLevelEntryName } from '../lib/pathSafety.js';+import { ServerError } from '../lib/errorHandler.js';const DRAFTS_DIR = join(PATHS.agentPersonalities, 'drafts');async function getDraftsPath(agentId) {+ // agentId comes straight from a query string / body; it names the file, so it+ // must be a single path segment (no `../` walk out of the drafts directory).+ if (!isTopLevelEntryName(agentId)) {+ throw new ServerError('Invalid agentId', { status: 400, code: 'VALIDATION_ERROR' });+ }await ensureDir(DRAFTS_DIR);return join(DRAFTS_DIR, `${agentId}.json`);}diff --git a/server/services/agentDrafts.test.js b/server/services/agentDrafts.test.jsindex 96933a7a79..1f6eb84a20 100644--- a/server/services/agentDrafts.test.js+++ b/server/services/agentDrafts.test.js@@ -124,4 +124,10 @@ describe('agentDrafts service', () => {expect(a[0].content).toBe('A');expect(b[0].content).toBe('B');});++ it.each(['../../video-history', '..', 'a/b', 'a\\b', ''])('refuses agentId %j rather than reading or writing outside the drafts directory', async (agentId) => {+ await expect(listDrafts(agentId)).rejects.toMatchObject({ status: 400 });+ await expect(createDraft(agentId, { type: 'post', content: 'x' })).rejects.toMatchObject({ status: 400 });+ expect(fileStore.size).toBe(0);+ });});diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex c58e31bed3..f6a54348ec 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -33,6 +33,7 @@ import { ensureDir, expandHome, PATHS } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';import { execGit } from '../lib/execGit.js';+import { isSafeGitRef } from '../lib/gitArgs.js';import {getAppById,updateApp,@@ -125,6 +126,21 @@ const rejectCredentialedUrl = (url) => {}};+// `repoUrl` and `branch` are caller text that becomes bare git argv. A value+// shaped like an option (`--upload-pack=<cmd>` as the branch of+// `git fetch --prune origin <branch>`) is executed by git's local/ssh+// transport — host code execution from a route that only edits a record.+// Validated when written AND when used, since apps.json already holds records+// saved before this check (and is hand-editable).+const assertGitArgsSafe = ({ repoUrl, branch }) => {+ if (typeof repoUrl === 'string' && repoUrl.trim().startsWith('-')) {+ throw new ServerError('repoUrl must not start with "-"', { status: 400, code: 'REFERENCE_REPO_BAD_URL' });+ }+ if (typeof branch === 'string' && branch.trim() && !isSafeGitRef(branch.trim())) {+ throw new ServerError('branch is not a valid git branch name', { status: 400, code: 'REFERENCE_REPO_BAD_BRANCH' });+ }+};+// Patterns that indicate the user's config is wrong (so the right HTTP// status is 4xx, not 5xx). Order matters — first match wins. Codes here// surface to the UI via `lastError`, so the strings are user-facing.@@ -198,10 +214,11 @@ const ensureClone = async (ref) => {await ensureDir(REFERENCE_REPOS_ROOT);const dest = cloneDir(ref.id);if (existsSync(join(dest, '.git'))) return dest;+ assertGitArgsSafe(ref);// No clone yet → bring one down. --depth 1 would lose the diff window we// need for `git log lastReviewedSha..HEAD`, so do a full clone.console.log(`📦 Cloning reference repo "${ref.name}" → ${dest}`);- await runGit(REFERENCE_REPOS_ROOT, ['clone', ref.repoUrl, ref.id], { timeoutMs: 600_000 });+ await runGit(REFERENCE_REPOS_ROOT, ['clone', '--', ref.repoUrl, ref.id], { timeoutMs: 600_000 });return dest;};@@ -211,13 +228,14 @@ const ensureClone = async (ref) => {*/const fetchHead = async (ref) => {const cwd = await ensureClone(ref);+ assertGitArgsSafe(ref);const branch = ref.branch || 'main';// For URL-based refs, fetch the latest from origin so rev-parse picks// up new commits. Local-path refs are the user's own working tree —// skip fetch (the user manages their tree directly) and read the// branch tip in place.if (!isLocalPath(ref.repoUrl)) {- await runGit(cwd, ['fetch', '--prune', 'origin', branch]);+ await runGit(cwd, ['fetch', '--prune', 'origin', '--', branch]);}const headRef = isLocalPath(ref.repoUrl) ? branch : `origin/${branch}`;const head = await runGit(cwd, ['rev-parse', headRef]);@@ -331,6 +349,7 @@ export async function addReferenceRepo(appId, { name, repoUrl, branch, notes })if (!app) throw new ServerError(`App not found: ${appId}`, { status: 404, code: 'APP_NOT_FOUND' });const trimmedUrl = repoUrl.trim();rejectCredentialedUrl(trimmedUrl);+ assertGitArgsSafe({ repoUrl: trimmedUrl, branch });const existing = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];const ref = {id: uuidv4(),@@ -371,6 +390,7 @@ export async function updateReferenceRepo(appId, refId, patch) {// PATCH must enforce the same credential-in-URL rejection as POST —// otherwise a user could sidestep the ingest check by editing the URL// afterwards and persisting `https://token@host/repo` into apps.json.+ assertGitArgsSafe(patch);if (typeof patch.repoUrl === 'string') {rejectCredentialedUrl(patch.repoUrl.trim());}@@ -435,7 +455,7 @@ export async function updateReferenceRepo(appId, refId, patch) {if (typeof patch.repoUrl === 'string' && patch.repoUrl.trim() !== oldRef.repoUrl && !isLocalPath(patch.repoUrl)) {const dest = cloneDir(oldRef.id);if (existsSync(join(dest, '.git'))) {- const result = await execGit(['remote', 'set-url', 'origin', patch.repoUrl.trim()], dest, { timeout: 10_000 })+ const result = await execGit(['remote', 'set-url', 'origin', '--', patch.repoUrl.trim()], dest, { timeout: 10_000 }).catch((err) => ({ error: err }));if (result && result.error) {// Don't fail the patch outright — the user can manually deletediff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.jsindex 7d4d40a011..e391a5f49b 100644--- a/server/services/referenceRepos.test.js+++ b/server/services/referenceRepos.test.js@@ -117,6 +117,33 @@ describe('addReferenceRepo', () => {});});+describe('git argument injection guards', () => {+ const OPTION_SHAPED = ['--upload-pack=touch /tmp/pwn', '-ouploadpack', '--config=core.fsmonitor=x'];++ it.each(OPTION_SHAPED)('refuses option-shaped branch %j on add and update', async (branch) => {+ seedApp('app-1', [{ id: 'r1', name: 'n', repoUrl: 'https://github.com/x/y.git', branch: 'main', status: 'ok' }]);+ await expect(svc.addReferenceRepo('app-1', { name: 'n', repoUrl: 'https://github.com/x/y.git', branch })).rejects.toMatchObject({ status: 400 });+ await expect(svc.updateReferenceRepo('app-1', 'r1', { branch })).rejects.toMatchObject({ status: 400 });+ expect(mockApps.get('app-1').referenceRepos).toHaveLength(1);+ expect(mockApps.get('app-1').referenceRepos[0].branch).toBe('main');+ });++ it('refuses an option-shaped repoUrl on add and update', async () => {+ seedApp('app-1', [{ id: 'r1', name: 'n', repoUrl: 'https://github.com/x/y.git', branch: 'main', status: 'ok' }]);+ await expect(svc.addReferenceRepo('app-1', { name: 'n', repoUrl: '--upload-pack=touch /tmp/pwn ://x' })).rejects.toMatchObject({ status: 400 });+ await expect(svc.updateReferenceRepo('app-1', 'r1', { repoUrl: '--upload-pack=touch /tmp/pwn ://x' })).rejects.toMatchObject({ status: 400 });+ });++ it('never runs git for a stored record that already carries an option-shaped branch', async () => {+ // apps.json is hand-editable and held such records before the write-time check existed.+ seedApp('app-1', [{ id: 'r1', name: 'n', repoUrl: 'https://github.com/x/y.git', branch: '--upload-pack=touch /tmp/pwn', status: 'ok' }]);+ existsMock.mockImplementation(() => true); // managed clone exists+ execGitMock.mockClear();+ await expect(svc.checkReferenceRepo('app-1', 'r1')).rejects.toMatchObject({ status: 400 });+ expect(execGitMock).not.toHaveBeenCalled();+ });+});+describe('updateReferenceRepo', () => {it('updates allowed fields only and bumps lastCheckedAt when SHA is pinned manually', async () => {seedApp('app-1', [{ id: 'r1', name: 'old', repoUrl: 'u', branch: 'main', notes: '', lastReviewedSha: null, status: 'ok' }]);@@ -205,7 +232,7 @@ describe('checkReferenceRepo', () => {expect(snapshot.commits[0].subject).toBe('first commit');// The first execGitMock call should have been `git clone <url> <id>`- expect(execGitMock.mock.calls[0][0]).toEqual(['clone', 'https://github.com/x/y.git', 'r1']);+ expect(execGitMock.mock.calls[0][0]).toEqual(['clone', '--', 'https://github.com/x/y.git', 'r1']);// Persisted status must reflect the successful run.const persisted = mockApps.get('app-1').referenceRepos[0];expect(persisted.status).toBe('ok');