Skip to content

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

security: validate workspace roots on git/scaffold paths, drop env from shell allowlist

[._.]/ Adam Eivy04f4192579ca
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fa818232fa..25229c1c13 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,8 @@
## Fixed
+- **Workspace-root validation on git/scaffold routes** — git operations and app scaffolding refuse paths outside allowed workspace roots; file staging uses literal pathspecs (no git glob expansion); `env` removed from the shell command allowlist so process secrets can't land in persisted job output.
+
- **A watched TUI run no longer false-times-out after finishing its work** — companion fix to *Live TUI runs are now viewable AND drivable in the Shell page* (above). One-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) write their completed answer to a response file and then return to an interactive prompt **without exiting**. The runner only auto-completed such a run via output-idle — which is paused while you watch it in the Shell page (so it isn't snapped shut mid-read). With the process never exiting and idle paused, a watched run had no terminus but the 10-minute hard timeout — at which point it was marked **failed**, its already-written result was **discarded**, and a useless fallback retry ran in its place. The runner now watches for the response file as the model's authoritative "done" signal and completes the run the moment it's written — even while you're watching — since once the file exists the task is genuinely finished. A second safety net salvages the file on hard timeout: if the result was written but completion stalled for any other reason, the run finishes as **success** with that result instead of throwing it away and falling back. So a long editorial pass you keep open in the Shell tab now lands its findings when the model finishes, instead of silently dying at 10 minutes. (`server/lib/tuiPromptRunner.js`)
- **Catalog user-type sync now converges instead of re-applying every cycle** — federated catalog *user-defined types* used an at-or-newer (`>=`) last-write-wins comparison, so a peer re-sending a type you already held at the same timestamp was re-adopted, re-written, and re-counted as a change on every sync cycle. The logs showed a constant non-zero count (e.g. `Synced with <peer>: 3 catalog changes`) once a minute forever, and the slice was rewritten needlessly each pass. The merge now uses strict-newer (`>`), matching the SQL LWW guard every other catalog kind already uses (`EXCLUDED.updated_at > …updated_at`): an equal-clock echo is a skip, so the merge is idempotent and the cycle settles to zero changes. (`server/services/catalogSync.js`)
diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.js
index f9a8d32b60..8bd37979d3 100644
--- a/server/lib/commandSecurity.js
+++ b/server/lib/commandSecurity.js
@@ -5,7 +5,7 @@ export const ALLOWED_COMMANDS = new Set([
'git', 'gh',
'pm2',
'ls', 'cat', 'head', 'tail', 'grep', 'find', 'wc',
- 'pwd', 'which', 'echo', 'env',
+ 'pwd', 'which', 'echo',
'curl', 'wget',
'docker', 'docker-compose',
'make', 'cargo', 'go', 'python', 'python3', 'pip', 'pip3',
diff --git a/server/lib/commandSecurity.test.js b/server/lib/commandSecurity.test.js
index 487d040f16..6b0db8b4a9 100644
--- a/server/lib/commandSecurity.test.js
+++ b/server/lib/commandSecurity.test.js
@@ -10,21 +10,30 @@ import {
describe('commandSecurity', () => {
describe('ALLOWED_COMMANDS', () => {
- it('should be a Set containing expected base commands', () => {
- expect(ALLOWED_COMMANDS).toBeInstanceOf(Set)
- expect(ALLOWED_COMMANDS.has('npm')).toBe(true)
- expect(ALLOWED_COMMANDS.has('git')).toBe(true)
- expect(ALLOWED_COMMANDS.has('node')).toBe(true)
- expect(ALLOWED_COMMANDS.has('docker')).toBe(true)
- expect(ALLOWED_COMMANDS.has('pm2')).toBe(true)
- })
-
- it('should not contain dangerous commands', () => {
- expect(ALLOWED_COMMANDS.has('rm')).toBe(false)
- expect(ALLOWED_COMMANDS.has('sudo')).toBe(false)
- expect(ALLOWED_COMMANDS.has('chmod')).toBe(false)
- expect(ALLOWED_COMMANDS.has('chown')).toBe(false)
- expect(ALLOWED_COMMANDS.has('kill')).toBe(false)
+ // Behavioral tests via validateCommand — avoid tautological Set.has() checks.
+ it.each([
+ 'npm', 'git', 'node', 'docker', 'pm2'
+ ])('allows %s through validateCommand', (cmd) => {
+ expect(validateCommand(`${cmd} --version`).valid).toBe(true)
+ })
+
+ it.each([
+ ['rm', 'rm -rf /'],
+ ['sudo', 'sudo su'],
+ ['chmod', 'chmod 777 /etc'],
+ ['chown', 'chown root /etc'],
+ ['kill', 'kill -9 1'],
+ ['env', 'env']
+ ])('rejects %s through validateCommand', (_label, cmd) => {
+ const result = validateCommand(cmd)
+ expect(result.valid).toBe(false)
+ expect(result.error).toMatch(/not in the allowlist|disallowed shell/)
+ })
+
+ it('env is not in the allowlist (dumps process secrets)', () => {
+ const result = validateCommand('env')
+ expect(result.valid).toBe(false)
+ expect(result.error).toContain("Command 'env' is not in the allowlist")
})
})
diff --git a/server/lib/gitArgs.js b/server/lib/gitArgs.js
index 63ef09eeac..a06f76d20a 100644
--- a/server/lib/gitArgs.js
+++ b/server/lib/gitArgs.js
@@ -9,6 +9,12 @@ export const PROTECTED_BRANCHES = ['main', 'master', 'dev', 'develop', 'release'
* Validate file paths to prevent command injection and path traversal.
* Throws on null bytes / shell metacharacters, absolute paths, or `..` traversal.
* Accepts a single path or an array; always returns an array of the sanitized paths.
+ *
+ * Glob characters (* ? [) are deliberately NOT rejected — legitimate filenames
+ * contain them (Next.js/SvelteKit `[id].jsx` dynamic routes). Wildcard
+ * expansion is neutralized at the call site instead: services/git.js prefixes
+ * each path with `toLiteralPathspec` so git never glob-expands them.
+ *
* @param {string|string[]} files - File path(s)
* @returns {string[]} - Sanitized file paths
*/
@@ -26,3 +32,16 @@ export function validateFilePaths(files) {
return f;
});
}
+
+/**
+ * Wrap a validated repo-relative path in git's `:(literal)` pathspec magic so
+ * pathspec wildcards (`*`, `?`, `[...]`) are treated as literal filename
+ * characters instead of glob patterns. Without this, staging `app/[id].jsx`
+ * either errors ("did not match any files") or silently matches the WRONG
+ * file (`app/i.jsx`), and a crafted `*` pathspec would stage everything.
+ * @param {string} path - Repo-relative file path (already validated)
+ * @returns {string} - Pathspec with literal magic applied
+ */
+export function toLiteralPathspec(path) {
+ return `:(literal)${path}`;
+}
diff --git a/server/lib/gitArgs.test.js b/server/lib/gitArgs.test.js
index 997a23f17d..e9ee643625 100644
--- a/server/lib/gitArgs.test.js
+++ b/server/lib/gitArgs.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { PROTECTED_BRANCHES, validateFilePaths } from './gitArgs.js';
+import { PROTECTED_BRANCHES, validateFilePaths, toLiteralPathspec } from './gitArgs.js';
describe('PROTECTED_BRANCHES', () => {
it('lists the branches that must never be deleted', () => {
@@ -29,4 +29,18 @@ describe('validateFilePaths', () => {
expect(() => validateFilePaths(['../secrets'])).toThrow(/Invalid file path/);
expect(() => validateFilePaths(['a/../b'])).toThrow(/Invalid file path/);
});
+
+ it('accepts filenames containing pathspec wildcards (Next.js dynamic routes etc.)', () => {
+ // Glob-expansion safety lives in toLiteralPathspec at the call site, not
+ // in rejection here — these are legitimate on-disk filenames.
+ expect(validateFilePaths(['app/[id].jsx'])).toEqual(['app/[id].jsx']);
+ expect(validateFilePaths(['what?.md', 'star*.txt'])).toEqual(['what?.md', 'star*.txt']);
+ });
+});
+
+describe('toLiteralPathspec', () => {
+ it('prefixes the path with the :(literal) pathspec magic', () => {
+ expect(toLiteralPathspec('app/[id].jsx')).toBe(':(literal)app/[id].jsx');
+ expect(toLiteralPathspec('src/a.js')).toBe(':(literal)src/a.js');
+ });
});
diff --git a/server/routes/git.js b/server/routes/git.js
index 16b0681465..8f3140e3cb 100644
--- a/server/routes/git.js
+++ b/server/routes/git.js
@@ -1,8 +1,39 @@
import { Router } from 'express';
+import { existsSync, statSync, realpathSync } from 'fs';
+import { resolve } from 'path';
import * as git from '../services/git.js';
import * as appsService from '../services/apps.js';
import { getAgents } from '../services/cosAgents.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';
+
+/**
+ * Assert that a caller-supplied workspace path exists, is a directory, and
+ * resolves (after symlinks) within an allowed root. Mirrors the pattern in
+ * routes/commands.js:23-45. Throws ServerError 400/403 on failure.
+ */
+function assertAllowedWorkspace(path) {
+ if (!path || typeof path !== 'string') {
+ throw new ServerError('path must be a non-empty string', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ const resolvedPath = resolve(path);
+ if (!existsSync(resolvedPath)) {
+ throw new ServerError('path does not exist', { status: 400, code: 'INVALID_PATH' });
+ }
+ let realPath;
+ try {
+ if (!statSync(resolvedPath).isDirectory()) {
+ throw new ServerError('path is not a directory', { status: 400, code: 'INVALID_PATH' });
+ }
+ realPath = realpathSync(resolvedPath);
+ } catch (err) {
+ if (err instanceof ServerError) throw err;
+ throw new ServerError('path is not accessible', { status: 400, code: 'INVALID_PATH' });
+ }
+ if (!isWithinAllowedRoots(realPath)) {
+ throw new ServerError('path is outside allowed directories', { status: 403, code: 'FORBIDDEN' });
+ }
+}
/**
* Collect branch names actively used by running CoS agents.
@@ -62,11 +93,7 @@ router.get('/:appId', asyncHandler(async (req, res) => {
// POST /api/git/status - Get status for a path
router.post('/status', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const status = await git.getStatus(path);
res.json(status);
}));
@@ -74,11 +101,7 @@ router.post('/status', asyncHandler(async (req, res) => {
// POST /api/git/diff - Get diff for a path
router.post('/diff', asyncHandler(async (req, res) => {
const { path, staged } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const diff = await git.getDiff(path, staged);
res.json({ diff });
}));
@@ -86,11 +109,7 @@ router.post('/diff', asyncHandler(async (req, res) => {
// POST /api/git/commits - Get recent commits
router.post('/commits', asyncHandler(async (req, res) => {
const { path, limit = 10 } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const commits = await git.getCommits(path, limit);
res.json({ commits });
}));
@@ -98,11 +117,10 @@ router.post('/commits', asyncHandler(async (req, res) => {
// POST /api/git/stage - Stage files
router.post('/stage', asyncHandler(async (req, res) => {
const { path, files } = req.body;
-
- if (!path || !files) {
- throw new ServerError('path and files are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!files) {
+ throw new ServerError('files is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
await git.stageFiles(path, files);
res.json({ success: true });
}));
@@ -110,11 +128,10 @@ router.post('/stage', asyncHandler(async (req, res) => {
// POST /api/git/unstage - Unstage files
router.post('/unstage', asyncHandler(async (req, res) => {
const { path, files } = req.body;
-
- if (!path || !files) {
- throw new ServerError('path and files are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!files) {
+ throw new ServerError('files is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
await git.unstageFiles(path, files);
res.json({ success: true });
}));
@@ -122,11 +139,10 @@ router.post('/unstage', asyncHandler(async (req, res) => {
// POST /api/git/commit - Create a commit
router.post('/commit', asyncHandler(async (req, res) => {
const { path, message } = req.body;
-
- if (!path || !message) {
- throw new ServerError('path and message are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!message) {
+ throw new ServerError('message is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
const result = await git.commit(path, message);
res.json(result);
}));
@@ -134,11 +150,7 @@ router.post('/commit', asyncHandler(async (req, res) => {
// POST /api/git/update-branches - Fetch and merge latest dev and main
router.post('/update-branches', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const result = await git.updateBranches(path);
res.json(result);
}));
@@ -146,11 +158,7 @@ router.post('/update-branches', asyncHandler(async (req, res) => {
// POST /api/git/branch-comparison - Compare two branches
router.post('/branch-comparison', asyncHandler(async (req, res) => {
const { path, base, head } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const baseBranch = base || await git.getDefaultBranch(path, { allowRemote: false }).catch(() => null) || 'main';
const result = await git.getBranchComparison(path, baseBranch, head || 'dev');
res.json(result);
@@ -159,11 +167,7 @@ router.post('/branch-comparison', asyncHandler(async (req, res) => {
// POST /api/git/push - Push to origin
router.post('/push', asyncHandler(async (req, res) => {
const { path, branch } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const result = await git.push(path, branch);
res.json(result);
}));
@@ -171,11 +175,7 @@ router.post('/push', asyncHandler(async (req, res) => {
// POST /api/git/push-all - Push all branches with unpushed commits
router.post('/push-all', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const result = await git.pushAll(path);
res.json(result);
}));
@@ -183,11 +183,7 @@ router.post('/push-all', asyncHandler(async (req, res) => {
// POST /api/git/info - Get full git info for a path
router.post('/info', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const info = await git.getGitInfo(path);
res.json(info);
}));
@@ -195,11 +191,7 @@ router.post('/info', asyncHandler(async (req, res) => {
// POST /api/git/branches - Get all local branches
router.post('/branches', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const branches = await git.getBranches(path);
res.json({ branches });
}));
@@ -207,11 +199,10 @@ router.post('/branches', asyncHandler(async (req, res) => {
// POST /api/git/checkout - Switch to a branch
router.post('/checkout', asyncHandler(async (req, res) => {
const { path, branch } = req.body;
-
- if (!path || !branch) {
- throw new ServerError('path and branch are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!branch) {
+ throw new ServerError('branch is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
const result = await git.checkout(path, branch);
res.json(result);
}));
@@ -219,11 +210,7 @@ router.post('/checkout', asyncHandler(async (req, res) => {
// POST /api/git/pull - Pull changes from remote
router.post('/pull', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const result = await git.pull(path);
res.json(result);
}));
@@ -231,11 +218,7 @@ router.post('/pull', asyncHandler(async (req, res) => {
// POST /api/git/sync - Sync branch (pull then push)
router.post('/sync', asyncHandler(async (req, res) => {
const { path, branch } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const result = await git.syncBranch(path, branch);
res.json(result);
}));
@@ -243,11 +226,7 @@ router.post('/sync', asyncHandler(async (req, res) => {
// POST /api/git/remote-branches - Get remote branches with merge status
router.post('/remote-branches', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const result = await git.getRemoteBranches(path);
res.json(result);
}));
@@ -255,11 +234,10 @@ router.post('/remote-branches', asyncHandler(async (req, res) => {
// POST /api/git/merge - Merge a branch into the current branch
router.post('/merge', asyncHandler(async (req, res) => {
const { path, branch } = req.body;
-
- if (!path || !branch) {
- throw new ServerError('path and branch are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!branch) {
+ throw new ServerError('branch is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
const result = await git.mergeBranch(path, branch);
res.json(result);
}));
@@ -267,11 +245,10 @@ router.post('/merge', asyncHandler(async (req, res) => {
// POST /api/git/checkout-remote - Checkout a remote branch locally
router.post('/checkout-remote', asyncHandler(async (req, res) => {
const { path, branch } = req.body;
-
- if (!path || !branch) {
- throw new ServerError('path and branch are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!branch) {
+ throw new ServerError('branch is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
const result = await git.checkoutRemoteBranch(path, branch);
res.json(result);
}));
@@ -279,11 +256,7 @@ router.post('/checkout-remote', asyncHandler(async (req, res) => {
// POST /api/git/cleanup-merged - Delete all merged branches (local + remote)
router.post('/cleanup-merged', asyncHandler(async (req, res) => {
const { path } = req.body;
-
- if (!path) {
- throw new ServerError('path is required', { status: 400, code: 'VALIDATION_ERROR' });
- }
-
+ assertAllowedWorkspace(path);
const excludeBranches = await getActiveAgentBranches();
const result = await git.deleteMergedBranches(path, { excludeBranches });
res.json(result);
@@ -292,15 +265,13 @@ router.post('/cleanup-merged', asyncHandler(async (req, res) => {
// POST /api/git/delete-branch - Delete a branch locally and/or remotely
router.post('/delete-branch', asyncHandler(async (req, res) => {
const { path, branch, local, remote } = req.body;
-
- if (!path || !branch) {
- throw new ServerError('path and branch are required', { status: 400, code: 'VALIDATION_ERROR' });
+ assertAllowedWorkspace(path);
+ if (!branch) {
+ throw new ServerError('branch is required', { status: 400, code: 'VALIDATION_ERROR' });
}
-
if (!local && !remote) {
throw new ServerError('at least one of local or remote must be true', { status: 400, code: 'VALIDATION_ERROR' });
}
-
const excludeBranches = await getActiveAgentBranches();
const result = await git.deleteBranch(path, branch, { local, remote, excludeBranches });
res.json(result);
diff --git a/server/routes/git.test.js b/server/routes/git.test.js
new file mode 100644
index 0000000000..e942b39774
--- /dev/null
+++ b/server/routes/git.test.js
@@ -0,0 +1,284 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import gitRoutes from './git.js';
+
+// Mock the git service — tests are guard-focused, not service-coverage.
+vi.mock('../services/git.js', () => ({
+ getStatus: vi.fn().mockResolvedValue({ files: [] }),
+ getDiff: vi.fn().mockResolvedValue(''),
+ getCommits: vi.fn().mockResolvedValue([]),
+ stageFiles: vi.fn().mockResolvedValue(undefined),
+ unstageFiles: vi.fn().mockResolvedValue(undefined),
+ commit: vi.fn().mockResolvedValue({ sha: 'abc123' }),
+ push: vi.fn().mockResolvedValue({ pushed: true }),
+ getGitInfo: vi.fn().mockResolvedValue({}),
+ getBranches: vi.fn().mockResolvedValue([]),
+ getSubmodules: vi.fn().mockResolvedValue([]),
+ getSubmodulePaths: vi.fn().mockResolvedValue([]),
+ updateSubmodule: vi.fn().mockResolvedValue('abc'),
+ getAppById: vi.fn(),
+ updateBranches: vi.fn().mockResolvedValue({}),
+ getBranchComparison: vi.fn().mockResolvedValue({}),
+ pushAll: vi.fn().mockResolvedValue({}),
+ getDefaultBranch: vi.fn().mockResolvedValue('main'),
+ checkout: vi.fn().mockResolvedValue({}),
+ pull: vi.fn().mockResolvedValue({}),
+ syncBranch: vi.fn().mockResolvedValue({}),
+ getRemoteBranches: vi.fn().mockResolvedValue([]),
+ mergeBranch: vi.fn().mockResolvedValue({}),
+ checkoutRemoteBranch: vi.fn().mockResolvedValue({}),
+ deleteMergedBranches: vi.fn().mockResolvedValue({}),
+ deleteBranch: vi.fn().mockResolvedValue({})
+}));
+
+vi.mock('../services/apps.js', () => ({
+ getAppById: vi.fn()
+}));
+
+vi.mock('../services/cosAgents.js', () => ({
+ getAgents: vi.fn().mockResolvedValue([])
+}));
+
+// Mock workspace-roots so we control which paths are "allowed" without
+// touching the real filesystem.
+vi.mock('../lib/workspaceRoots.js', () => ({
+ isWithinAllowedRoots: vi.fn()
+}));
+
+// Mock fs functions used by assertAllowedWorkspace.
+vi.mock('fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ existsSync: vi.fn(),
+ statSync: vi.fn(),
+ realpathSync: vi.fn()
+ };
+});
+
+import { existsSync, statSync, realpathSync } from 'fs';
+import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';
+import * as cosAgentsService from '../services/cosAgents.js';
+import * as gitService from '../services/git.js';
+
+function makeApp() {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/git', gitRoutes);
+ // Minimal error handler so ServerError shapes propagate cleanly.
+ app.use((err, _req, res, _next) => {
+ res.status(err.status ?? 500).json({ error: err.message, code: err.code });
+ });
+ return app;
+}
+
+describe('git routes — workspace root validation', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('path outside allowed roots → 403', () => {
+ it.each([
+ ['POST /status', '/status', { path: '/etc/passwd' }],
+ ['POST /diff', '/diff', { path: '/etc' }],
+ ['POST /commits', '/commits', { path: '/etc' }],
+ ['POST /push', '/push', { path: '/etc' }],
+ ['POST /pull', '/pull', { path: '/etc' }],
+ ['POST /info', '/info', { path: '/etc' }],
+ ['POST /branches', '/branches', { path: '/etc' }]
+ ])('%s', async (_label, route, body) => {
+ existsSync.mockReturnValue(true);
+ statSync.mockReturnValue({ isDirectory: () => true });
+ realpathSync.mockReturnValue(body.path);
+ isWithinAllowedRoots.mockReturnValue(false);
+
+ const app = makeApp();
+ const res = await request(app).post(`/api/git${route}`).send(body);
+
+ expect(res.status).toBe(403);
+ expect(res.body.code).toBe('FORBIDDEN');
+ });
+ });
+
+ describe('path within allowed roots → handler reached (200)', () => {
+ it.each([
+ ['POST /status', '/status', { path: '/Users/me/project' }],
+ ['POST /diff', '/diff', { path: '/Users/me/project' }],
+ ['POST /commits', '/commits', { path: '/Users/me/project' }],
+ ['POST /push', '/push', { path: '/Users/me/project' }],
+ ['POST /pull', '/pull', { path: '/Users/me/project' }],
+ ['POST /info', '/info', { path: '/Users/me/project' }],
+ ['POST /branches', '/branches', { path: '/Users/me/project' }]
+ ])('%s', async (_label, route, body) => {
+ existsSync.mockReturnValue(true);
+ statSync.mockReturnValue({ isDirectory: () => true });
+ realpathSync.mockReturnValue(body.path);
+ isWithinAllowedRoots.mockReturnValue(true);
+
+ const app = makeApp();
+ const res = await request(app).post(`/api/git${route}`).send(body);
+
+ expect(res.status).toBe(200);
+ });
+ });
+
+ describe('missing / null path → 400', () => {
+ it.each([
+ ['POST /status', '/status'],
+ ['POST /diff', '/diff'],
+ ['POST /push', '/push']
+ ])('%s', async (_label, route) => {
+ const app = makeApp();
+ const res = await request(app).post(`/api/git${route}`).send({});
+
+ expect(res.status).toBe(400);
+ });
+ });
+
+ it('path that does not exist → 400', async () => {
+ existsSync.mockReturnValue(false);
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/status')
+ .send({ path: '/nonexistent/path' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('INVALID_PATH');
+ });
+});
+
+// Helper: configure the workspace mocks to allow a path through
+function allowWorkspace(path = '/Users/me/project') {
+ existsSync.mockReturnValue(true);
+ statSync.mockReturnValue({ isDirectory: () => true });
+ realpathSync.mockReturnValue(path);
+ isWithinAllowedRoots.mockReturnValue(true);
+}
+
+describe('git routes — active agent branch exclusion', () => {
+ const WORKSPACE = '/Users/me/project';
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ allowWorkspace(WORKSPACE);
+ });
+
+ describe('POST /api/git/cleanup-merged — active agent branches are passed to service', () => {
+ it('passes the active agent worktreeBranch as an excludeBranches Set to deleteMergedBranches', async () => {
+ cosAgentsService.getAgents.mockResolvedValue([
+ { status: 'running', metadata: { worktreeBranch: 'feature/agent-work' } },
+ { status: 'stopped', metadata: { worktreeBranch: 'feature/done-work' } },
+ ]);
+ gitService.deleteMergedBranches.mockResolvedValue({ deleted: [], protected: ['feature/agent-work'] });
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/cleanup-merged')
+ .send({ path: WORKSPACE });
+
+ expect(res.status).toBe(200);
+ expect(gitService.deleteMergedBranches).toHaveBeenCalledWith(
+ WORKSPACE,
+ expect.objectContaining({
+ excludeBranches: expect.any(Set),
+ })
+ );
+ const { excludeBranches } = gitService.deleteMergedBranches.mock.calls[0][1];
+ // Running agent branch is excluded
+ expect(excludeBranches.has('feature/agent-work')).toBe(true);
+ // Stopped agent branch is NOT excluded (only running agents protect branches)
+ expect(excludeBranches.has('feature/done-work')).toBe(false);
+ });
+
+ it('passes an empty Set when no agents are running', async () => {
+ cosAgentsService.getAgents.mockResolvedValue([]);
+ gitService.deleteMergedBranches.mockResolvedValue({ deleted: [] });
+
+ const app = makeApp();
+ await request(app)
+ .post('/api/git/cleanup-merged')
+ .send({ path: WORKSPACE });
+
+ const { excludeBranches } = gitService.deleteMergedBranches.mock.calls[0][1];
+ expect(excludeBranches.size).toBe(0);
+ });
+
+ it('still passes an empty Set when getAgents rejects (catch guard)', async () => {
+ cosAgentsService.getAgents.mockRejectedValue(new Error('service down'));
+ gitService.deleteMergedBranches.mockResolvedValue({ deleted: [] });
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/cleanup-merged')
+ .send({ path: WORKSPACE });
+
+ // Should not 500 — getAgents failure is swallowed via .catch(() => [])
+ expect(res.status).toBe(200);
+ const { excludeBranches } = gitService.deleteMergedBranches.mock.calls[0][1];
+ expect(excludeBranches.size).toBe(0);
+ });
+ });
+
+ describe('POST /api/git/delete-branch — active agent branches are excluded', () => {
+ it('passes the active agent branches as excludeBranches to deleteBranch', async () => {
+ cosAgentsService.getAgents.mockResolvedValue([
+ { status: 'running', metadata: { worktreeBranch: 'feature/agent-active' } },
+ ]);
+ gitService.deleteBranch.mockResolvedValue({ branch: 'feature/other', results: { local: 'deleted' } });
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/delete-branch')
+ .send({ path: WORKSPACE, branch: 'feature/other', local: true });
+
+ expect(res.status).toBe(200);
+ expect(gitService.deleteBranch).toHaveBeenCalledWith(
+ WORKSPACE,
+ 'feature/other',
+ expect.objectContaining({
+ excludeBranches: expect.any(Set),
+ })
+ );
+ const { excludeBranches } = gitService.deleteBranch.mock.calls[0][2];
+ expect(excludeBranches.has('feature/agent-active')).toBe(true);
+ });
+
+ it('returns 400 when branch param is missing', async () => {
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/delete-branch')
+ .send({ path: WORKSPACE, local: true });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(gitService.deleteBranch).not.toHaveBeenCalled();
+ });
+
+ it('returns 400 when neither local nor remote is true', async () => {
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/delete-branch')
+ .send({ path: WORKSPACE, branch: 'feature/x' });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(gitService.deleteBranch).not.toHaveBeenCalled();
+ });
+
+ it('service error propagates as 500', async () => {
+ cosAgentsService.getAgents.mockResolvedValue([]);
+ gitService.deleteBranch.mockRejectedValue(
+ Object.assign(new Error('Cannot delete branch in active use by an agent: feature/agent-active'), { status: 500 })
+ );
+
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/git/delete-branch')
+ .send({ path: WORKSPACE, branch: 'feature/agent-active', local: true });
+
+ expect(res.status).toBe(500);
+ });
+ });
+});
diff --git a/server/routes/scaffold.js b/server/routes/scaffold.js
index 473e243a0f..951aa9dfc1 100644
--- a/server/routes/scaffold.js
+++ b/server/routes/scaffold.js
@@ -1,6 +1,6 @@
import { Router } from 'express';
import { writeFile, readdir, stat } from 'fs/promises';
-import { existsSync } from 'fs';
+import { existsSync, realpathSync } from 'fs';
import { join, dirname, resolve, sep } from 'path';
import { fileURLToPath } from 'url';
import { exec, spawn } from 'child_process';
@@ -9,6 +9,7 @@ import { platform } from 'os';
import { createApp, getReservedPorts } from '../services/apps.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { ensureDir, expandHome } from '../lib/fileUtils.js';
+import { isWithinAllowedRoots } from '../lib/workspaceRoots.js';
import { scaffoldVite } from './scaffoldVite.js';
import { scaffoldExpress } from './scaffoldExpress.js';
import { scaffoldIOS } from './scaffoldIOS.js';
@@ -256,6 +257,18 @@ async function scaffoldApp(req, res) {
});
}
+ // Assert parentDir resolves within an allowed workspace root (mirrors commands.js pattern).
+ // realpathSync throws on permission/TOCTOU edges — convert to a clean 400.
+ let realParentDir;
+ try {
+ realParentDir = realpathSync(resolve(parentDir));
+ } catch {
+ throw new ServerError('parentDir is not accessible', { status: 400, code: 'INVALID_PARENT' });
+ }
+ if (!isWithinAllowedRoots(realParentDir)) {
+ throw new ServerError('parentDir is outside allowed directories', { status: 403, code: 'FORBIDDEN' });
+ }
+
// Check target doesn't exist
if (existsSync(repoPath)) {
throw new ServerError('Directory already exists', {
diff --git a/server/services/git.js b/server/services/git.js
index 3837e0f1aa..467ef4dd86 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -18,7 +18,7 @@ import {
detectForgeCli,
parsePullRequestUrl
} from '../lib/gitForge.js';
-import { PROTECTED_BRANCHES, validateFilePaths } from '../lib/gitArgs.js';
+import { PROTECTED_BRANCHES, validateFilePaths, toLiteralPathspec } from '../lib/gitArgs.js';
// Re-export so callers that used to import from services/git.js keep working.
export { execGit };
@@ -109,19 +109,21 @@ export async function getDiffStats(dir) {
}
/**
- * Stage files
+ * Stage files. Paths are passed with `:(literal)` pathspec magic so git
+ * treats wildcard characters as literal filename bytes — `[id].jsx` stages
+ * that exact file, and a crafted `*` can't expand to the whole tree.
*/
export async function stageFiles(dir, files) {
- const safePaths = validateFilePaths(files);
+ const safePaths = validateFilePaths(files).map(toLiteralPathspec);
await execGit(['add', '--', ...safePaths], dir);
return true;
}
/**
- * Unstage files
+ * Unstage files (same literal-pathspec handling as stageFiles).
*/
export async function unstageFiles(dir, files) {
- const safePaths = validateFilePaths(files);
+ const safePaths = validateFilePaths(files).map(toLiteralPathspec);
await execGit(['reset', 'HEAD', '--', ...safePaths], dir);
return true;
}