( basePath: string, relativePath: string, )
| 85 | * @throws Error if the path would escape the base directory |
| 86 | */ |
| 87 | export function validatePathWithinBase( |
| 88 | basePath: string, |
| 89 | relativePath: string, |
| 90 | ): string { |
| 91 | const resolvedPath = resolve(basePath, relativePath) |
| 92 | const normalizedBase = resolve(basePath) + sep |
| 93 | |
| 94 | // Check if the resolved path starts with the base path |
| 95 | // Adding sep ensures we don't match partial directory names |
| 96 | // e.g., /foo/bar should not match /foo/barbaz |
| 97 | if ( |
| 98 | !resolvedPath.startsWith(normalizedBase) && |
| 99 | resolvedPath !== resolve(basePath) |
| 100 | ) { |
| 101 | throw new Error( |
| 102 | `Path traversal detected: "${relativePath}" would escape the base directory`, |
| 103 | ) |
| 104 | } |
| 105 | |
| 106 | return resolvedPath |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Cache a plugin (local or external) and add it to installed_plugins.json |
no test coverage detected