(filePath: string)
| 21 | * contain path traversal sequences. Throws if the path is unsafe. |
| 22 | */ |
| 23 | export function assertTrustedPath(filePath: string): void { |
| 24 | const normalized = path.resolve(filePath); |
| 25 | |
| 26 | // Reject path traversal |
| 27 | const segments = filePath.replaceAll('\\', '/').split('/'); |
| 28 | if (segments.includes('..')) { |
| 29 | throw new Error(`Path traversal detected: ${filePath}`); |
| 30 | } |
| 31 | |
| 32 | const trustedRoots = getTrustedRoots(); |
| 33 | const isTrusted = trustedRoots.some(root => normalized.startsWith(root + path.sep) || normalized === root); |
| 34 | if (!isTrusted) { |
| 35 | throw new Error(`Path is outside trusted directories: ${filePath}`); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | function getTrustedRoots(): string[] { |
| 40 | const roots: string[] = []; |
no test coverage detected