1+ import * as fs from 'fs'
12import * as path from 'path'
23import { normalize_path } from './normalize-path'
34
@@ -9,17 +10,19 @@ import { normalize_path } from './normalize-path'
910 * @returns A sanitized version of the name with dangerous characters removed
1011 */
1112export const sanitize_file_name = ( name : string ) : string => {
12- // Remove path traversal sequences
13- let sanitized = name . replace ( / \. \. \/ / g, '' ) . replace ( / \. \. \\ / g, '' )
13+ if ( name . includes ( '..' ) ) {
14+ return ''
15+ }
16+
17+ const segments = name . split ( / [ / \\ ] / )
18+ if ( segments . some ( seg => seg === '.git' ) ) {
19+ return ''
20+ }
1421
15- // Remove leading slashes and backslashes to prevent absolute paths
16- // but preserve leading dots for hidden files
17- sanitized = sanitized . replace ( / ^ [ / \\ ] + / , '' )
22+ let sanitized = name . replace ( / ^ [ / \\ ] + / , '' )
1823
19- // Convert Windows-style backslashes to forward slashes for consistency
2024 sanitized = normalize_path ( sanitized )
2125
22- // Return the sanitized name, preserving valid path segments
2326 return sanitized
2427}
2528
@@ -39,10 +42,18 @@ export const create_safe_path = (
3942 return null // Return null if sanitization results in empty string
4043 }
4144
42- const full_path = path . join ( parent_path , sanitized_name )
45+ let resolved_parent : string
46+ try {
47+ resolved_parent = fs . realpathSync ( parent_path )
48+ } catch ( err ) {
49+ resolved_parent = path . resolve ( parent_path )
50+ }
51+
52+ const full_path = path . resolve ( resolved_parent , sanitized_name )
53+
54+ const relative_path = path . relative ( resolved_parent , full_path )
4355
44- // Verify the constructed path is still within the parent directory
45- if ( ! full_path . startsWith ( parent_path ) ) {
56+ if ( relative_path . startsWith ( '..' ) || path . isAbsolute ( relative_path ) ) {
4657 return null
4758 }
4859
0 commit comments