diff --git a/src/lib/commands/cp.test.ts b/src/lib/commands/cp.test.ts index 7b56f121..eeadf536 100644 --- a/src/lib/commands/cp.test.ts +++ b/src/lib/commands/cp.test.ts @@ -118,11 +118,11 @@ describe('CpCommand', () => { expect(result.stderr).toContain('No such file or directory'); }); - it('should reject absolute paths', async () => { - const result = await cpCommand.execute(['/absolute/source', 'dest'], testCwd); + it('should reject absolute destination paths outside allowed directories', async () => { + const result = await cpCommand.execute(['src/test.txt', '/absolute/dest'], testCwd); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('absolute paths are not supported'); + expect(result.stderr).toContain('write access denied'); }); it('should return error when missing operands', async () => { diff --git a/src/lib/commands/cp.ts b/src/lib/commands/cp.ts index ef3793e7..e4589c04 100644 --- a/src/lib/commands/cp.ts +++ b/src/lib/commands/cp.ts @@ -2,6 +2,7 @@ import { join, dirname, basename } from "@std/path"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; import { createSuccessResult, createErrorResult } from "./ShellCommand"; +import { isAbsolutePath, validateWritePath } from "../security"; /** * Implementation of the 'cp' command @@ -33,14 +34,20 @@ export class CpCommand implements ShellCommand { const sources = paths.slice(0, -1); const destination = paths[paths.length - 1]; - // Check for absolute paths - for (const path of [...sources, destination]) { - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - return createErrorResult(`${this.name}: absolute paths are not supported: ${path}`); - } + // Check write permissions for destination (sources can be read from anywhere) + try { + validateWritePath(destination, this.name); + } catch (error) { + return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } - const destAbsolutePath = join(cwd, destination); + // Handle both absolute and relative paths for destination + let destAbsolutePath: string; + if (isAbsolutePath(destination)) { + destAbsolutePath = destination; + } else { + destAbsolutePath = join(cwd, destination); + } // Check if destination exists and is a directory let destIsDir = false; @@ -58,7 +65,13 @@ export class CpCommand implements ShellCommand { for (const source of sources) { try { - const sourceAbsolutePath = join(cwd, source); + // Handle both absolute and relative paths for source + let sourceAbsolutePath: string; + if (isAbsolutePath(source)) { + sourceAbsolutePath = source; + } else { + sourceAbsolutePath = join(cwd, source); + } const sourceStats = await this.fs.stat(sourceAbsolutePath); let targetPath: string; diff --git a/src/lib/commands/curl.ts b/src/lib/commands/curl.ts index b19babc0..51b0d33f 100644 --- a/src/lib/commands/curl.ts +++ b/src/lib/commands/curl.ts @@ -2,6 +2,7 @@ import { join } from "@std/path"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; import { createSuccessResult, createErrorResult } from "./ShellCommand"; +import { isAbsolutePath, validateWritePath } from "../security"; /** * Parsed curl options @@ -364,12 +365,16 @@ export class CurlCommand implements ShellCommand { */ private async writeToFile(filename: string, content: string, cwd: string): Promise { try { - // Handle absolute paths - if (filename.startsWith('/') || filename.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filename)) { - throw new Error('absolute paths are not supported'); - } + // Validate write permissions for absolute paths + validateWritePath(filename, 'curl'); - const absolutePath = join(cwd, filename); + // Handle both absolute and relative paths + let absolutePath: string; + if (isAbsolutePath(filename)) { + absolutePath = filename; + } else { + absolutePath = join(cwd, filename); + } await this.fs.writeFile(absolutePath, content, 'utf8'); } catch (error) { diff --git a/src/lib/commands/mkdir.test.ts b/src/lib/commands/mkdir.test.ts index ba167738..e7eb8f8f 100644 --- a/src/lib/commands/mkdir.test.ts +++ b/src/lib/commands/mkdir.test.ts @@ -39,56 +39,56 @@ describe('MkdirCommand', () => { it('should create new directory', async () => { const result = await command.execute(['newdir'], '/project'); - + expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); }); it('should handle existing directory error', async () => { const result = await command.execute(['existing'], '/project'); - + expect(result.exitCode).toBe(1); expect(result.stderr).toContain('File exists'); }); it('should handle existing file error', async () => { const result = await command.execute(['file.txt'], '/project'); - + expect(result.exitCode).toBe(1); expect(result.stderr).toContain('File exists'); }); it('should create parent directories with -p', async () => { const result = await command.execute(['-p', 'deep/nested'], '/project'); - + expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); }); it('should handle missing parent directory without -p', async () => { const result = await command.execute(['nonexistent/newdir'], '/project'); - + expect(result.exitCode).toBe(1); expect(result.stderr).toContain('No such file or directory'); }); it('should require directory operand', async () => { const result = await command.execute([], '/project'); - + expect(result.exitCode).toBe(1); expect(result.stderr).toContain('missing operand'); }); - it('should reject absolute paths', async () => { + it('should reject absolute paths outside allowed directories', async () => { const result = await command.execute(['/absolute/path'], '/project'); - + expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('absolute paths are not supported'); + expect(result.stderr).toContain('write access denied'); }); it('should handle multiple directories', async () => { const result = await command.execute(['newdir', 'deep'], '/project'); - + expect(result.exitCode).toBe(0); expect(result.stdout).toBe(''); }); diff --git a/src/lib/commands/mkdir.ts b/src/lib/commands/mkdir.ts index 458dc534..c0646216 100644 --- a/src/lib/commands/mkdir.ts +++ b/src/lib/commands/mkdir.ts @@ -2,6 +2,7 @@ import { join, dirname } from "@std/path"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; import { createSuccessResult, createErrorResult } from "./ShellCommand"; +import { isAbsolutePath, validateWritePath } from "../security"; /** * Implementation of the 'mkdir' command @@ -32,12 +33,20 @@ export class MkdirCommand implements ShellCommand { try { for (const dirPath of directories) { try { - // Handle absolute paths - if (dirPath.startsWith('/') || dirPath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(dirPath)) { - return createErrorResult(`${this.name}: absolute paths are not supported: ${dirPath}`); + // Validate write permissions for absolute paths + try { + validateWritePath(dirPath, this.name); + } catch (error) { + return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } - const absolutePath = join(cwd, dirPath); + // Handle both absolute and relative paths + let absolutePath: string; + if (isAbsolutePath(dirPath)) { + absolutePath = dirPath; + } else { + absolutePath = join(cwd, dirPath); + } if (options.parents) { // Create parent directories as needed (-p option) diff --git a/src/lib/commands/mv.test.ts b/src/lib/commands/mv.test.ts index 06ff24f0..9d4032d7 100644 --- a/src/lib/commands/mv.test.ts +++ b/src/lib/commands/mv.test.ts @@ -104,11 +104,11 @@ describe('MvCommand', () => { expect(result.stderr).toContain('File exists'); }); - it('should reject absolute paths', async () => { + it('should reject absolute paths outside allowed directories', async () => { const result = await mvCommand.execute(['/absolute/source', 'dest'], testCwd); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('absolute paths are not supported'); + expect(result.stderr).toContain('write access denied'); }); it('should return error when missing operands', async () => { diff --git a/src/lib/commands/mv.ts b/src/lib/commands/mv.ts index b7f9de4f..66d7e69f 100644 --- a/src/lib/commands/mv.ts +++ b/src/lib/commands/mv.ts @@ -2,6 +2,7 @@ import { join, dirname, basename } from "@std/path"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; import { createSuccessResult, createErrorResult } from "./ShellCommand"; +import { isAbsolutePath, validateWritePath } from "../security"; /** * Implementation of the 'mv' command @@ -27,14 +28,23 @@ export class MvCommand implements ShellCommand { const sources = args.slice(0, -1); const destination = args[args.length - 1]; - // Check for absolute paths - for (const path of [...sources, destination]) { - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - return createErrorResult(`${this.name}: absolute paths are not supported: ${path}`); + // Check write permissions for destination and sources (since mv deletes the source) + const pathsToValidate = [destination, ...sources]; + for (const path of pathsToValidate) { + try { + validateWritePath(path, this.name); + } catch (error) { + return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } } - const destAbsolutePath = join(cwd, destination); + // Handle both absolute and relative paths for destination + let destAbsolutePath: string; + if (isAbsolutePath(destination)) { + destAbsolutePath = destination; + } else { + destAbsolutePath = join(cwd, destination); + } // Check if destination exists and is a directory let destIsDir = false; @@ -52,7 +62,13 @@ export class MvCommand implements ShellCommand { for (const source of sources) { try { - const sourceAbsolutePath = join(cwd, source); + // Handle both absolute and relative paths for source + let sourceAbsolutePath: string; + if (isAbsolutePath(source)) { + sourceAbsolutePath = source; + } else { + sourceAbsolutePath = join(cwd, source); + } // Check if source exists await this.fs.stat(sourceAbsolutePath); diff --git a/src/lib/commands/rm.test.ts b/src/lib/commands/rm.test.ts index abe64df2..7d8c3d88 100644 --- a/src/lib/commands/rm.test.ts +++ b/src/lib/commands/rm.test.ts @@ -89,11 +89,11 @@ describe('RmCommand', () => { expect(result.exitCode).toBe(0); }); - it('should reject absolute paths', async () => { + it('should reject absolute paths outside allowed directories', async () => { const result = await rmCommand.execute(['/absolute/path'], testCwd); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('absolute paths are not supported'); + expect(result.stderr).toContain('write access denied'); }); it('should reject removing current or parent directory', async () => { diff --git a/src/lib/commands/rm.ts b/src/lib/commands/rm.ts index d4d35a35..83dade02 100644 --- a/src/lib/commands/rm.ts +++ b/src/lib/commands/rm.ts @@ -2,6 +2,7 @@ import { join } from "@std/path"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; import { createSuccessResult, createErrorResult } from "./ShellCommand"; +import { isAbsolutePath, validateWritePath } from "../security"; /** * Implementation of the 'rm' command @@ -32,9 +33,19 @@ export class RmCommand implements ShellCommand { for (const path of paths) { try { - // Handle absolute paths - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - return createErrorResult(`${this.name}: absolute paths are not supported: ${path}`); + // Validate write permissions for absolute paths + try { + validateWritePath(path, this.name); + } catch (error) { + return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); + } + + // Handle both absolute and relative paths + let absolutePath: string; + if (isAbsolutePath(path)) { + absolutePath = path; + } else { + absolutePath = join(cwd, path); } // Prevent removing current directory or parent directory @@ -42,7 +53,7 @@ export class RmCommand implements ShellCommand { return createErrorResult(`${this.name}: cannot remove '${path}': Invalid argument`); } - const absolutePath = join(cwd, path); + try { const stats = await this.fs.stat(absolutePath); diff --git a/src/lib/commands/touch.test.ts b/src/lib/commands/touch.test.ts index 590f2ef8..b633e16a 100644 --- a/src/lib/commands/touch.test.ts +++ b/src/lib/commands/touch.test.ts @@ -65,11 +65,11 @@ describe('TouchCommand', () => { expect(result.stderr).toContain('missing file operand'); }); - it('should reject absolute paths', async () => { + it('should reject absolute paths outside allowed directories', async () => { const result = await command.execute(['/absolute/path'], '/project'); expect(result.exitCode).toBe(1); - expect(result.stderr).toContain('absolute paths are not supported'); + expect(result.stderr).toContain('write access denied'); }); it('should handle missing parent directory', async () => { diff --git a/src/lib/commands/touch.ts b/src/lib/commands/touch.ts index 6d854149..7bb11b8d 100644 --- a/src/lib/commands/touch.ts +++ b/src/lib/commands/touch.ts @@ -2,6 +2,7 @@ import { join, dirname } from "@std/path"; import type { JSRuntimeFS } from "../JSRuntime"; import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; import { createSuccessResult, createErrorResult } from "./ShellCommand"; +import { isAbsolutePath, validateWritePath } from "../security"; /** * Implementation of the 'touch' command @@ -26,12 +27,20 @@ export class TouchCommand implements ShellCommand { try { for (const filePath of args) { try { - // Handle absolute paths - if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { - return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`); + // Validate write permissions for absolute paths + try { + validateWritePath(filePath, this.name); + } catch (error) { + return createErrorResult(error instanceof Error ? error.message : 'Unknown error'); } - const absolutePath = join(cwd, filePath); + // Handle both absolute and relative paths + let absolutePath: string; + if (isAbsolutePath(filePath)) { + absolutePath = filePath; + } else { + absolutePath = join(cwd, filePath); + } try { // Check if file exists diff --git a/src/lib/security.test.ts b/src/lib/security.test.ts new file mode 100644 index 00000000..90bc3068 --- /dev/null +++ b/src/lib/security.test.ts @@ -0,0 +1,93 @@ +import { describe, it, expect } from 'vitest'; +import { + isAbsolutePath, + isWriteAllowed, + validateWritePath, + createWriteAccessDeniedError +} from './security'; + +describe('security', () => { + describe('isAbsolutePath', () => { + it('should detect Unix absolute paths', () => { + expect(isAbsolutePath('/tmp/file.txt')).toBe(true); + expect(isAbsolutePath('/home/user/file.txt')).toBe(true); + expect(isAbsolutePath('/absolute/path')).toBe(true); + }); + + it('should detect Windows absolute paths', () => { + expect(isAbsolutePath('C:\\temp\\file.txt')).toBe(true); + expect(isAbsolutePath('D:/folder/file.txt')).toBe(true); + expect(isAbsolutePath('\\\\server\\share')).toBe(true); + }); + + it('should detect relative paths', () => { + expect(isAbsolutePath('src/index.ts')).toBe(false); + expect(isAbsolutePath('./src/index.ts')).toBe(false); + expect(isAbsolutePath('../parent/file.txt')).toBe(false); + expect(isAbsolutePath('file.txt')).toBe(false); + }); + }); + + describe('isWriteAllowed', () => { + it('should allow writes to /tmp/', () => { + expect(isWriteAllowed('/tmp')).toBe(true); + expect(isWriteAllowed('/tmp/')).toBe(true); + expect(isWriteAllowed('/tmp/file.txt')).toBe(true); + expect(isWriteAllowed('/tmp/subdir/file.txt')).toBe(true); + }); + + it('should deny writes to other absolute paths', () => { + expect(isWriteAllowed('/home/user/file.txt')).toBe(false); + expect(isWriteAllowed('/var/log/file.txt')).toBe(false); + expect(isWriteAllowed('/absolute/path')).toBe(false); + expect(isWriteAllowed('/etc/passwd')).toBe(false); + }); + }); + + describe('validateWritePath', () => { + it('should allow relative paths', () => { + expect(() => validateWritePath('src/index.ts', 'test')).not.toThrow(); + expect(() => validateWritePath('./file.txt', 'test')).not.toThrow(); + expect(() => validateWritePath('../parent/file.txt', 'test')).not.toThrow(); + }); + + it('should allow /tmp/ absolute paths', () => { + expect(() => validateWritePath('/tmp/file.txt', 'test')).not.toThrow(); + expect(() => validateWritePath('/tmp/subdir/file.txt', 'test')).not.toThrow(); + }); + + it('should reject other absolute paths', () => { + expect(() => validateWritePath('/absolute/path', 'test')).toThrow('write access denied'); + expect(() => validateWritePath('/home/user/file.txt', 'test')).toThrow('write access denied'); + }); + + it('should include operation name in error message', () => { + expect(() => validateWritePath('/absolute/path', 'mkdir')).toThrow('mkdir: write access denied'); + }); + + it('should include current working directory in error message', () => { + expect(() => validateWritePath('/absolute/path', 'test', '/project')).toThrow('/project'); + }); + }); + + describe('createWriteAccessDeniedError', () => { + it('should create formatted error message without tool name', () => { + const error = createWriteAccessDeniedError('/absolute/path'); + expect(error).toContain('Write access denied to /absolute/path'); + expect(error).toContain('Write operations are only allowed in:'); + expect(error).toContain('- Current project directory (relative paths)'); + expect(error).toContain('- /tmp/ directory and its subdirectories'); + expect(error).toContain('šŸ’” Examples of allowed paths:'); + }); + + it('should create formatted error message with tool name', () => { + const error = createWriteAccessDeniedError('/absolute/path', 'TextEditor'); + expect(error).toContain('āŒ Write access denied to "/absolute/path"'); + }); + + it('should include current working directory when provided', () => { + const error = createWriteAccessDeniedError('/absolute/path', undefined, '/project'); + expect(error).toContain('Current working directory: /project'); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/security.ts b/src/lib/security.ts new file mode 100644 index 00000000..e0041f9a --- /dev/null +++ b/src/lib/security.ts @@ -0,0 +1,69 @@ +/** + * Security utilities for path validation and access control + */ + +/** + * Check if the given path is an absolute path + */ +export function isAbsolutePath(path: string): boolean { + return path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path); +} + +/** + * Check if write operations are allowed for the given absolute path + * + * Write operations are only allowed in: + * - /tmp/ directory and its subdirectories + * - Current project directory (handled via relative paths) + */ +export function isWriteAllowed(absolutePath: string): boolean { + // Allow writes to /tmp/ and its subdirectories + if (absolutePath.startsWith('/tmp/') || absolutePath === '/tmp') { + return true; + } + + // For other absolute paths, deny write access + return false; +} + +/** + * Validate a path for write operations and throw descriptive errors + * + * @param path - The path to validate (can be absolute or relative) + * @param operationName - Name of the operation for error messages (e.g., 'touch', 'mkdir') + * @param cwd - Current working directory for context in error messages + * @throws Error if the path is not allowed for write operations + */ +export function validateWritePath(path: string, operationName: string, cwd?: string): void { + if (isAbsolutePath(path) && !isWriteAllowed(path)) { + const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : ''; + throw new Error( + `${operationName}: write access denied to ${path}. ` + + `Write operations are only allowed in project directory and /tmp/${cwdInfo}` + ); + } +} + +/** + * Create a standardized error message for write access denial + * + * @param path - The path that was denied + * @param toolName - Name of the tool/command for context + * @param cwd - Current working directory for context + * @returns Formatted error message + */ +export function createWriteAccessDeniedError(path: string, toolName?: string, cwd?: string): string { + const prefix = toolName ? `āŒ Write access denied to "${path}".` : `Write access denied to ${path}.`; + const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : ''; + + return ( + `${prefix}\n\n` + + `Write operations are only allowed in:\n` + + `- Current project directory (relative paths)\n` + + `- /tmp/ directory and its subdirectories\n\n` + + `šŸ’” Examples of allowed paths:\n` + + `- "src/index.ts" (relative to current directory)\n` + + `- "/tmp/temp-file.txt" (temporary files)\n` + + `- "/tmp/workspace/file.js" (temporary workspace)${cwdInfo}` + ); +} \ No newline at end of file diff --git a/src/lib/tools/TextEditorStrReplaceTool.test.ts b/src/lib/tools/TextEditorStrReplaceTool.test.ts index cdabf289..3b7df782 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.test.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.test.ts @@ -134,7 +134,21 @@ describe('TextEditorStrReplaceTool', () => { path: '/absolute/path/test.ts', old_str: 'old', new_str: 'new' - })).rejects.toThrow('āŒ Absolute paths are not supported'); + })).rejects.toThrow('Write access denied'); + }); + + it('should allow writes to /tmp/ directory', async () => { + // First create the file in /tmp/ + await mockFS.writeFile('/tmp/temp-file.txt', 'original content'); + + const result = await tool.execute({ + path: '/tmp/temp-file.txt', + old_str: 'original', + new_str: 'modified' + }); + + expect(result).toContain('String successfully replaced'); + expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('modified content'); }); it('should handle whitespace normalization', async () => { diff --git a/src/lib/tools/TextEditorStrReplaceTool.ts b/src/lib/tools/TextEditorStrReplaceTool.ts index ded5f1b1..fe33c6f7 100644 --- a/src/lib/tools/TextEditorStrReplaceTool.ts +++ b/src/lib/tools/TextEditorStrReplaceTool.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import type { Tool } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; +import { isAbsolutePath, createWriteAccessDeniedError } from "../security"; interface TextEditorStrReplaceParams { path: string; @@ -31,12 +32,27 @@ export class TextEditorStrReplaceTool implements Tool { const { path, old_str, new_str, normalize_whitespace = true } = args; - // Check for absolute paths and provide helpful error - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - throw new Error(`āŒ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\nšŸ’” Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`); + // Check for absolute paths and validate write permissions + if (isAbsolutePath(path)) { + if (!this.isWriteAllowed(path)) { + throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); + } } // Ban editing dependencies in package.json @@ -60,7 +76,14 @@ export class TextEditorStrReplaceTool implements Tool { expect(mockFS.getFileContent('/project/src/test.ts')).toBe('console.log("test");'); }); - it('should reject absolute paths with helpful error message', async () => { + it('should reject absolute paths outside allowed directories', async () => { await expect(tool.execute({ path: '/absolute/path/test.ts', file_text: 'test content' - })).rejects.toThrow('āŒ Absolute paths are not supported'); + })).rejects.toThrow('Write access denied'); + }); + + it('should allow writes to /tmp/ directory', async () => { + const result = await tool.execute({ + path: '/tmp/temp-file.txt', + file_text: 'temporary content' + }); + + expect(result).toContain('File successfully written to /tmp/temp-file.txt'); + expect(mockFS.hasFile('/tmp/temp-file.txt')).toBe(true); + expect(mockFS.getFileContent('/tmp/temp-file.txt')).toBe('temporary content'); }); it('should reject package.json writes', async () => { diff --git a/src/lib/tools/TextEditorWriteTool.ts b/src/lib/tools/TextEditorWriteTool.ts index e094386a..d09bec2d 100644 --- a/src/lib/tools/TextEditorWriteTool.ts +++ b/src/lib/tools/TextEditorWriteTool.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import type { Tool } from "./Tool"; import type { JSRuntimeFS } from "../JSRuntime"; +import { isAbsolutePath, createWriteAccessDeniedError } from "../security"; interface TextEditorWriteParams { path: string; @@ -27,12 +28,27 @@ export class TextEditorWriteTool implements Tool { this.cwd = cwd; } + /** + * Check if write operations are allowed for the given absolute path + */ + private isWriteAllowed(absolutePath: string): boolean { + // Allow writes to /tmp/ and its subdirectories + if (absolutePath.startsWith('/tmp/') || absolutePath === '/tmp') { + return true; + } + + // For other absolute paths, deny write access + return false; + } + async execute(args: TextEditorWriteParams): Promise { const { path, file_text } = args; - // Check for absolute paths and provide helpful error - if (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path)) { - throw new Error(`āŒ Absolute paths are not supported.\n\nThe path "${path}" appears to be an absolute path.\n\nšŸ’” Please use a relative path instead. Examples:\n- "src/index.ts" (relative to current directory)\n- "./src/index.ts" (explicit relative path)\n- "../other-project/src/index.ts" (relative to parent directory)\n\nCurrent working directory: ${this.cwd}`); + // Check for absolute paths and validate write permissions + if (isAbsolutePath(path)) { + if (!this.isWriteAllowed(path)) { + throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd)); + } } if ( @@ -43,7 +59,14 @@ export class TextEditorWriteTool implements Tool { } try { - const absolutePath = join(this.cwd, path); + // Handle both absolute and relative paths + let absolutePath: string; + if (isAbsolutePath(path)) { + absolutePath = path; + } else { + absolutePath = join(this.cwd, path); + } + await this.fs.mkdir(dirname(absolutePath), { recursive: true }); await this.fs.writeFile(absolutePath, file_text, "utf8"); return `File successfully written to ${path}`;