1- import path from " path" ;
1+ import path from ' path' ;
22
33/**
44 * Sanitizes a filename by removing unsafe characters.
@@ -8,7 +8,7 @@ import path from "path";
88 * @returns A safe, sanitized filename.
99 */
1010const sanitizeFilename = ( filename : string ) : string => {
11- return path . basename ( filename ) . replace ( / [ ^ a - z A - Z 0 - 9 _ . \s - ] / g, "" ) ;
11+ return path . basename ( filename ) . replace ( / [ ^ a - z A - Z 0 - 9 _ . \s - ] / g, '' ) ;
1212} ;
1313
1414/**
@@ -22,7 +22,7 @@ const sanitizeFilename = (filename: string): string => {
2222export const getSafePath = ( inputPath : string , baseDir ?: string ) : string => {
2323 try {
2424 // Resolve the absolute path (handles path.join(), path.resolve(), and full paths)
25- const resolvedPath = path . resolve ( baseDir || "" , inputPath ) ;
25+ const resolvedPath = path . resolve ( baseDir || '' , inputPath ) ;
2626
2727 // Ensure only the last segment (filename) is sanitized
2828 const dirPath = path . dirname ( resolvedPath ) ;
@@ -34,15 +34,28 @@ export const getSafePath = (inputPath: string, baseDir?: string): string => {
3434 // Ensure the path remains inside baseDir (if provided)
3535 if ( baseDir ) {
3636 const safeBaseDir = path . resolve ( baseDir ) ;
37- if ( ! safePath . startsWith ( safeBaseDir ) ) {
38- console . warn ( "Invalid file path detected, using default safe path." ) ;
39- return path . join ( safeBaseDir , "default.log" ) ;
37+
38+ // Use path.relative to securely check path containment
39+ const relativePath = path . relative ( safeBaseDir , safePath ) ;
40+
41+ // If relativePath starts with '..' or is absolute, it's trying to escape
42+ if (
43+ relativePath === '' ||
44+ relativePath === '.' ||
45+ ( ! relativePath . startsWith ( '..' ) && ! path . isAbsolute ( relativePath ) )
46+ ) {
47+ // Path is safely within the base directory
48+ return safePath ;
49+ } else {
50+ // Path is trying to escape the base directory
51+ console . warn ( 'Invalid file path detected, using default safe path.' ) ;
52+ return path . join ( safeBaseDir , 'default.log' ) ;
4053 }
4154 }
4255
4356 return safePath ;
4457 } catch ( error ) {
45- console . error ( " Error generating safe path:" , error ) ;
46- return baseDir ? path . join ( baseDir , " default.log" ) : " default.log" ;
58+ console . error ( ' Error generating safe path:' , error ) ;
59+ return baseDir ? path . join ( baseDir , ' default.log' ) : ' default.log' ;
4760 }
4861} ;
0 commit comments