Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { Effect, Path } from 'effect'; |
| 2 | import { SafeOutputPathError } from 'src/generation/errors'; |
| 3 | |
| 4 | export { SafeOutputPathError }; |
| 5 | |
| 6 | /** |
| 7 | * Joins a generated filename to the output directory, ensuring the result stays |
| 8 | * within `outputDir`. |
| 9 | * |
| 10 | * Defense in depth against path traversal / arbitrary file write (CWE-22): even |
| 11 | * though toolkit slugs are validated at decode time, this guarantees that any |
| 12 | * filename derived from API-controlled data cannot escape the intended output |
| 13 | * directory via `..` segments or absolute paths. |
| 14 | * |
| 15 | * Fails if the resolved path is not contained within `outputDir`. |
| 16 | */ |
| 17 | export function safeOutputPath( |
| 18 | outputDir: string, |
| 19 | filename: string |
| 20 | ): Effect.Effect<string, SafeOutputPathError, Path.Path> { |
| 21 | return Effect.gen(function* () { |
| 22 | const path = yield* Path.Path; |
| 23 | const resolvedDir = path.resolve(outputDir); |
| 24 | const resolved = path.resolve(resolvedDir, filename); |
| 25 | const relative = path.relative(resolvedDir, resolved); |
| 26 | const isWithinOutputDir = |
| 27 | relative === '' || |
| 28 | (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative)); |
| 29 | |
| 30 | if (path.isAbsolute(filename) || !isWithinOutputDir) { |
| 31 | return yield* Effect.fail( |
| 32 | new SafeOutputPathError({ |
| 33 | filename, |
| 34 | outputDir, |
| 35 | resolvedPath: resolved, |
| 36 | message: `Refusing unsafe generated filename: ${filename} resolves to ${resolved}`, |
| 37 | }) |
| 38 | ); |
| 39 | } |
| 40 | |
| 41 | return path.join(outputDir, filename); |
| 42 | }); |
| 43 | } |