@@ -72,12 +72,35 @@ export function createUnifiedDiff(originalContent: string, newContent: string, f
7272 ) ;
7373}
7474
75+ // Helper function to resolve relative paths against allowed directories
76+ function resolveRelativePathAgainstAllowedDirectories ( relativePath : string ) : string {
77+ if ( allowedDirectories . length === 0 ) {
78+ // Fallback to process.cwd() if no allowed directories are set
79+ return path . resolve ( process . cwd ( ) , relativePath ) ;
80+ }
81+
82+ // Try to resolve relative path against each allowed directory
83+ for ( const allowedDir of allowedDirectories ) {
84+ const candidate = path . resolve ( allowedDir , relativePath ) ;
85+ const normalizedCandidate = normalizePath ( candidate ) ;
86+
87+ // Check if the resulting path lies within any allowed directory
88+ if ( isPathWithinAllowedDirectories ( normalizedCandidate , allowedDirectories ) ) {
89+ return candidate ;
90+ }
91+ }
92+
93+ // If no valid resolution found, use the first allowed directory as base
94+ // This provides a consistent fallback behavior
95+ return path . resolve ( allowedDirectories [ 0 ] , relativePath ) ;
96+ }
97+
7598// Security & Validation Functions
7699export async function validatePath ( requestedPath : string ) : Promise < string > {
77100 const expandedPath = expandHome ( requestedPath ) ;
78101 const absolute = path . isAbsolute ( expandedPath )
79102 ? path . resolve ( expandedPath )
80- : path . resolve ( process . cwd ( ) , expandedPath ) ;
103+ : resolveRelativePathAgainstAllowedDirectories ( expandedPath ) ;
81104
82105 const normalizedRequested = normalizePath ( absolute ) ;
83106
0 commit comments