( cwd: string, inputPath: string, )
| 36 | } |
| 37 | |
| 38 | export async function resolveSafePath( |
| 39 | cwd: string, |
| 40 | inputPath: string, |
| 41 | ): Promise<PathSafetyResult> { |
| 42 | |
| 43 | if (inputPath === '' || inputPath === '/') { |
| 44 | throw new FsPathEscapesError(inputPath, 'empty'); |
| 45 | } |
| 46 | |
| 47 | if (path.isAbsolute(inputPath)) { |
| 48 | throw new FsPathEscapesError(inputPath, 'absolute'); |
| 49 | } |
| 50 | |
| 51 | const segments = inputPath.split(/[/\\]+/); |
| 52 | if (segments.some((s) => s === '..')) { |
| 53 | throw new FsPathEscapesError(inputPath, 'dotdot_segment'); |
| 54 | } |
| 55 | |
| 56 | const realCwd = await fs.realpath(cwd); |
| 57 | |
| 58 | const candidate = path.resolve(realCwd, inputPath); |
| 59 | |
| 60 | const resolved = await realpathLongestExistingPrefix(candidate); |
| 61 | |
| 62 | if (!isInsideOrEqual(resolved, realCwd)) { |
| 63 | |
| 64 | const reason: FsPathEscapesError['reason'] = isInsideOrEqual(candidate, realCwd) |
| 65 | ? 'symlink_outside_cwd' |
| 66 | : 'resolved_outside_cwd'; |
| 67 | throw new FsPathEscapesError(inputPath, reason, resolved); |
| 68 | } |
| 69 | |
| 70 | return { |
| 71 | absolute: resolved, |
| 72 | relative: toPosixRelative(realCwd, resolved), |
| 73 | }; |
| 74 | } |
| 75 | |
| 76 | function isInsideOrEqual(child: string, parent: string): boolean { |
| 77 | const rel = path.relative(parent, child); |
no test coverage detected