Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 33 additions & 14 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ import mcpUtilsRoutes from './routes/mcp-utils.js';
import commandsRoutes from './routes/commands.js';
import settingsRoutes from './routes/settings.js';
import agentRoutes from './routes/agent.js';
import projectsRoutes, { FORBIDDEN_PATHS } from './routes/projects.js';
import projectsRoutes, { FORBIDDEN_PATHS, getAllowedPaths, isPathAllowed } from './routes/projects.js';
import cliAuthRoutes from './routes/cli-auth.js';
import userRoutes from './routes/user.js';
import codexRoutes from './routes/codex.js';
Expand Down Expand Up @@ -488,29 +488,46 @@ app.post('/api/projects/create', authenticateToken, async (req, res) => {
app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
try {
const { path: dirPath } = req.query;

// Default to home directory if no path provided
const allowedPaths = getAllowedPaths();

// Default to home directory or first allowed path if no path provided
const homeDir = os.homedir();
let targetPath = dirPath ? dirPath.replace('~', homeDir) : homeDir;

let targetPath;
if (dirPath) {
targetPath = dirPath.replace('~', homeDir);
} else if (allowedPaths && allowedPaths.length > 0) {
// Default to first allowed path when ALLOWED_PATHS is set
targetPath = allowedPaths[0];
} else {
targetPath = homeDir;
}

// Resolve and normalize the path
targetPath = path.resolve(targetPath);


// Check ALLOWED_PATHS restriction (with symlink protection)
if (!(await isPathAllowed(targetPath))) {
return res.status(403).json({
error: `Access restricted to: ${allowedPaths.join(', ')}`,
allowedPaths: allowedPaths
});
}

// Security check - ensure path is accessible
try {
await fs.promises.access(targetPath);
const stats = await fs.promises.stat(targetPath);

if (!stats.isDirectory()) {
return res.status(400).json({ error: 'Path is not a directory' });
}
} catch (err) {
return res.status(404).json({ error: 'Directory not accessible' });
}

// Use existing getFileTree function with shallow depth (only direct children)
const fileTree = await getFileTree(targetPath, 1, 0, false); // maxDepth=1, showHidden=false

// Filter only directories and format for suggestions
const directories = fileTree
.filter(item => item.type === 'directory')
Expand All @@ -526,24 +543,26 @@ app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
if (!aHidden && bHidden) return -1;
return a.name.localeCompare(b.name);
});

// Add common directories if browsing home directory
const suggestions = [];
if (targetPath === homeDir) {
const commonDirs = ['Desktop', 'Documents', 'Projects', 'Development', 'Dev', 'Code', 'workspace'];
const existingCommon = directories.filter(dir => commonDirs.includes(dir.name));
const otherDirs = directories.filter(dir => !commonDirs.includes(dir.name));

suggestions.push(...existingCommon, ...otherDirs);
} else {
suggestions.push(...directories);
}

res.json({
path: targetPath,
suggestions: suggestions
suggestions: suggestions,
restricted: !!(allowedPaths && allowedPaths.length > 0),
allowedPaths: allowedPaths || []
});

} catch (error) {
console.error('Error browsing filesystem:', error);
res.status(500).json({ error: 'Failed to browse filesystem' });
Expand Down
19 changes: 15 additions & 4 deletions server/projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import crypto from 'crypto';
import sqlite3 from 'sqlite3';
import { open } from 'sqlite';
import os from 'os';
import { isPathAllowed } from './routes/projects.js';

// Import TaskMaster detection functions
async function detectTaskMasterFolder(projectPath) {
Expand Down Expand Up @@ -420,10 +421,15 @@ async function getProjects(progressCallback = null) {
}

const projectPath = path.join(claudeDir, entry.name);

// Extract actual project directory from JSONL sessions
const actualProjectDir = await extractProjectDirectory(entry.name);


// Check ALLOWED_PATHS restriction
if (actualProjectDir && !(await isPathAllowed(actualProjectDir))) {
continue; // Skip projects outside allowed paths
}

// Get display name from config or generate one
const customName = config[entry.name]?.displayName;
const autoDisplayName = await generateDisplayName(entry.name, actualProjectDir);
Expand Down Expand Up @@ -524,8 +530,13 @@ async function getProjects(progressCallback = null) {
actualProjectDir = projectName.replace(/-/g, '/');
}
}

const project = {

// Check ALLOWED_PATHS restriction for manual projects
if (actualProjectDir && !(await isPathAllowed(actualProjectDir))) {
continue; // Skip projects outside allowed paths
}

const project = {
name: projectName,
path: actualProjectDir,
displayName: projectConfig.displayName || await generateDisplayName(projectName, actualProjectDir),
Expand Down
112 changes: 112 additions & 0 deletions server/routes/projects.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,118 @@ import { addProjectManually } from '../projects.js';

const router = express.Router();

/**
* Cache for ALLOWED_PATHS to avoid repeated parsing.
* @type {string[]|null}
* @private
*/
let _allowedPathsCache = null;

/**
* Flag to track if ALLOWED_PATHS has been logged.
* @type {boolean}
* @private
*/
let _allowedPathsLogged = false;

/**
* Retrieves the list of allowed paths from the ALLOWED_PATHS environment variable.
*
* This function provides path-based access restrictions for the application.
* When ALLOWED_PATHS is set, only directories within these paths can be accessed.
* The value is parsed once and cached for performance.
*
* @function getAllowedPaths
* @returns {string[]|null} Array of allowed path strings, or null if not configured
* @example
* // Environment: ALLOWED_PATHS=/home/user/projects,/home/user/work
* const paths = getAllowedPaths();
* // Returns: ['/home/user/projects', '/home/user/work']
*
* @example
* // Environment: ALLOWED_PATHS not set
* const paths = getAllowedPaths();
* // Returns: null (all paths accessible)
*/
export function getAllowedPaths() {
if (_allowedPathsCache === null && process.env.ALLOWED_PATHS) {
_allowedPathsCache = process.env.ALLOWED_PATHS
.split(',')
.map(p => p.trim())
.filter(Boolean);
}

// Log once on first access
if (!_allowedPathsLogged) {
_allowedPathsLogged = true;
if (_allowedPathsCache && _allowedPathsCache.length > 0) {
console.log('[INFO] ALLOWED_PATHS restriction enabled:', _allowedPathsCache);
} else {
console.log('[INFO] ALLOWED_PATHS not set - all paths accessible');
}
}

return _allowedPathsCache;
}

/**
* Checks if a given path is within the allowed paths using real path resolution.
*
* This function resolves both the candidate path and allowed paths to their
* real filesystem paths (following symlinks) before comparison. This prevents
* symlink-based bypass attacks.
*
* @async
* @function isPathAllowed
* @param {string} candidatePath - The path to check
* @returns {Promise<boolean>} True if path is allowed, false otherwise
* @example
* // With ALLOWED_PATHS=/home/user/projects
* await isPathAllowed('/home/user/projects/myapp'); // true
* await isPathAllowed('/home/user/other'); // false
*/
export async function isPathAllowed(candidatePath) {
const allowedPaths = getAllowedPaths();

// If no restrictions, allow all
if (!allowedPaths || allowedPaths.length === 0) {
return true;
}

try {
// Resolve the candidate path to its real path (following symlinks)
let realCandidate;
try {
realCandidate = await fs.realpath(candidatePath);
} catch (err) {
// Path doesn't exist - use resolved path
realCandidate = path.resolve(candidatePath);
}

// Check against each allowed path
for (const allowedPath of allowedPaths) {
let realAllowed;
try {
realAllowed = await fs.realpath(allowedPath);
} catch (err) {
// Allowed path doesn't exist - use resolved path
realAllowed = path.resolve(allowedPath);
}

// Check if candidate is within allowed path
if (realCandidate === realAllowed ||
realCandidate.startsWith(realAllowed + path.sep)) {
return true;
}
}

return false;
} catch (err) {
console.warn('[ALLOWED_PATHS] Error checking path:', err.message);
return false;
}
}

function sanitizeGitError(message, token) {
if (!message || !token) return message;
return message.replace(new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '***');
Expand Down