diff --git a/src/lib/commands/curl.test.ts b/src/lib/commands/curl.test.ts new file mode 100644 index 00000000..1297579c --- /dev/null +++ b/src/lib/commands/curl.test.ts @@ -0,0 +1,342 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { CurlCommand } from './curl'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock fetch +const mockFetch = vi.fn(); +global.fetch = mockFetch; + +// Mock filesystem +const mockFS: JSRuntimeFS = { + writeFile: vi.fn(), + readFile: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + rmdir: vi.fn(), + unlink: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}; + +describe('CurlCommand', () => { + let curlCommand: CurlCommand; + + beforeEach(() => { + curlCommand = new CurlCommand(mockFS); + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.clearAllTimers(); + }); + + it('should have correct name and description', () => { + expect(curlCommand.name).toBe('curl'); + expect(curlCommand.description).toBe('Transfer data from or to a server using HTTP/HTTPS'); + expect(curlCommand.usage).toBe('curl [options] '); + }); + + it('should return error when no URL is provided', async () => { + const result = await curlCommand.execute([], '/test'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('no URL specified'); + }); + + it('should return error for invalid URL', async () => { + const result = await curlCommand.execute(['invalid-url'], '/test'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid URL'); + }); + + it('should return error for unsupported protocol', async () => { + const result = await curlCommand.execute(['ftp://example.com'], '/test'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('unsupported protocol'); + }); + + it('should make a basic GET request', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('Hello World'), + headers: new Map([['content-type', 'text/plain']]), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute(['https://example.com'], '/test'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('Hello World'); + expect(mockFetch).toHaveBeenCalledWith('https://example.com/', expect.objectContaining({ + method: 'GET', + headers: expect.objectContaining({ + 'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)' + }) + })); + }); + + it('should handle POST request with data', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com/api', + text: vi.fn().mockResolvedValue('{"success": true}'), + headers: new Map([['content-type', 'application/json']]), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute([ + '-d', '{"name": "test"}', + 'https://example.com/api' + ], '/test'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe('{"success": true}'); + expect(mockFetch).toHaveBeenCalledWith('https://example.com/api', expect.objectContaining({ + method: 'POST', + body: '{"name": "test"}', + headers: expect.objectContaining({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + })); + }); + + it('should handle custom headers', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('OK'), + headers: new Map(), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute([ + '-H', 'Authorization: Bearer token123', + '-H', 'Content-Type: application/json', + 'https://example.com' + ], '/test'); + + expect(result.exitCode).toBe(0); + expect(mockFetch).toHaveBeenCalledWith('https://example.com/', expect.objectContaining({ + headers: expect.objectContaining({ + 'Authorization': 'Bearer token123', + 'Content-Type': 'application/json', + 'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)' + }) + })); + }); + + it('should include response headers when -i flag is used', async () => { + const mockHeaders = new Map([ + ['content-type', 'text/plain'], + ['content-length', '11'] + ]); + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('Hello World'), + headers: mockHeaders, + redirected: false, + }; + mockResponse.headers.forEach = vi.fn((callback) => { + callback('text/plain', 'content-type'); + callback('11', 'content-length'); + }); + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute(['-i', 'https://example.com'], '/test'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('HTTP/1.1 200 OK'); + expect(result.stdout).toContain('content-type: text/plain'); + expect(result.stdout).toContain('Hello World'); + }); + + it('should save output to file when -o flag is used', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('File content'), + headers: new Map(), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute([ + '-o', 'output.txt', + 'https://example.com' + ], '/test'); + + expect(result.exitCode).toBe(0); + expect(mockFS.writeFile).toHaveBeenCalledWith('/test/output.txt', 'File content', 'utf8'); + expect(result.stdout).toContain('100 12 100 12'); + }); + + it('should be silent when -s flag is used', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('Hello World'), + headers: new Map(), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute(['-s', 'https://example.com'], '/test'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + }); + + it('should handle HTTP error responses', async () => { + const mockResponse = { + ok: false, + status: 404, + statusText: 'Not Found', + url: 'https://example.com/notfound', + text: vi.fn().mockResolvedValue('Page not found'), + headers: new Map(), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute(['https://example.com/notfound'], '/test'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('HTTP 404: Not Found'); + expect(result.stderr).toContain('Page not found'); + }); + + it('should handle custom method with -X flag', async () => { + const mockResponse = { + ok: true, + status: 204, + statusText: 'No Content', + url: 'https://example.com', + text: vi.fn().mockResolvedValue(''), + headers: new Map(), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute([ + '-X', 'DELETE', + 'https://example.com' + ], '/test'); + + expect(result.exitCode).toBe(0); + expect(mockFetch).toHaveBeenCalledWith('https://example.com/', expect.objectContaining({ + method: 'DELETE', + headers: expect.objectContaining({ + 'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)' + }) + })); + }); + + it('should handle combined short flags', async () => { + const mockHeaders = new Map([['content-type', 'text/plain']]); + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('Hello World'), + headers: mockHeaders, + redirected: false, + }; + mockResponse.headers.forEach = vi.fn((callback) => { + callback('text/plain', 'content-type'); + }); + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute(['-si', 'https://example.com'], '/test'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // Silent mode + }); + + it('should handle write-out format', async () => { + const mockResponse = { + ok: true, + status: 200, + statusText: 'OK', + url: 'https://example.com', + text: vi.fn().mockResolvedValue('Hello World'), + headers: new Map([['content-type', 'text/plain']]), + redirected: false, + }; + mockFetch.mockResolvedValue(mockResponse); + + const result = await curlCommand.execute([ + '-w', '%{http_code}\\n', + 'https://example.com' + ], '/test'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Hello World'); + expect(result.stdout).toContain('200'); + }); + + it('should handle network errors', async () => { + mockFetch.mockRejectedValue(new Error('Network error')); + + const result = await curlCommand.execute(['https://example.com'], '/test'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Network error'); + }); + + it('should handle timeout', async () => { + vi.useFakeTimers(); + + const mockController = { + abort: vi.fn(), + signal: { aborted: false } + }; + global.AbortController = vi.fn(() => mockController) as unknown as typeof AbortController; + + // Mock fetch to reject with AbortError after timeout + mockFetch.mockImplementation(() => { + return new Promise((_, reject) => { + setTimeout(() => { + const error = new Error('This operation was aborted'); + error.name = 'AbortError'; + reject(error); + }, 1100); // Slightly longer than timeout + }); + }); + + const promise = curlCommand.execute(['-m', '1', 'https://example.com'], '/test'); + + // Fast-forward time to trigger timeout + vi.advanceTimersByTime(1100); + + const result = await promise; + + expect(mockController.abort).toHaveBeenCalled(); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('operation timed out after 1 seconds'); + + vi.useRealTimers(); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/curl.ts b/src/lib/commands/curl.ts new file mode 100644 index 00000000..2d04bfd5 --- /dev/null +++ b/src/lib/commands/curl.ts @@ -0,0 +1,413 @@ +import { join } from "@std/path"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Parsed curl options + */ +interface CurlOptions { + url?: string; + method: string; + headers: Record; + data?: string; + output?: string; + includeHeaders: boolean; + followRedirects: boolean; + silent: boolean; + verbose: boolean; + userAgent?: string; + timeout?: number; + maxRedirects: number; + showProgress: boolean; + writeOut?: string; +} + +/** + * Implementation of the 'curl' command + * Transfer data from or to a server using HTTP/HTTPS + */ +export class CurlCommand implements ShellCommand { + name = 'curl'; + description = 'Transfer data from or to a server using HTTP/HTTPS'; + usage = 'curl [options] '; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string, _input?: string): Promise { + try { + const options = this.parseOptions(args); + + if (!options.url) { + return createErrorResult(`${this.name}: no URL specified\nUsage: ${this.usage}`); + } + + // Validate URL + let url: URL; + try { + url = new URL(options.url); + } catch { + return createErrorResult(`${this.name}: invalid URL: ${options.url}`); + } + + // Only allow HTTP and HTTPS protocols + if (!['http:', 'https:'].includes(url.protocol)) { + return createErrorResult(`${this.name}: unsupported protocol: ${url.protocol}`); + } + + // Prepare request + const requestInit: RequestInit = { + method: options.method, + headers: options.headers, + }; + + // Add body for POST, PUT, PATCH requests + if (options.data && ['POST', 'PUT', 'PATCH'].includes(options.method)) { + requestInit.body = options.data; + + // Set default content-type if not specified + if (!options.headers['content-type'] && !options.headers['Content-Type']) { + options.headers['Content-Type'] = 'application/x-www-form-urlencoded'; + } + } + + // Set User-Agent + if (options.userAgent) { + options.headers['User-Agent'] = options.userAgent; + } else if (!options.headers['user-agent'] && !options.headers['User-Agent']) { + options.headers['User-Agent'] = 'curl/8.0.0 (compatible; JavaScript fetch)'; + } + + // Handle timeout + const controller = new AbortController(); + let timeoutId: ReturnType | undefined; + + if (options.timeout) { + timeoutId = setTimeout(() => controller.abort(), options.timeout * 1000); + requestInit.signal = controller.signal; + } + + try { + if (options.verbose && !options.silent) { + console.log(`* Trying ${url.hostname}...`); + console.log(`> ${options.method} ${url.pathname}${url.search} HTTP/1.1`); + console.log(`> Host: ${url.hostname}`); + for (const [key, value] of Object.entries(options.headers)) { + console.log(`> ${key}: ${value}`); + } + if (options.data) { + console.log(`> `); + console.log(options.data); + } + } + + // Make the request + const response = await fetch(url.toString(), requestInit); + + if (timeoutId) { + clearTimeout(timeoutId); + } + + // Handle redirects manually if followRedirects is false + if (!options.followRedirects && response.redirected) { + return createErrorResult(`${this.name}: redirect not followed (use -L to follow redirects)`); + } + + let output = ''; + + // Include response headers if requested + if (options.includeHeaders) { + output += `HTTP/1.1 ${response.status} ${response.statusText}\n`; + response.headers.forEach((value, key) => { + output += `${key}: ${value}\n`; + }); + output += '\n'; + } + + // Get response body + const responseText = await response.text(); + + if (options.verbose && !options.silent) { + console.log(`< HTTP/1.1 ${response.status} ${response.statusText}`); + response.headers.forEach((value, key) => { + console.log(`< ${key}: ${value}`); + }); + } + + // Handle non-success status codes + if (!response.ok && !options.silent) { + const errorMsg = `HTTP ${response.status}: ${response.statusText}`; + if (options.output) { + // Still write to file even on error + await this.writeToFile(options.output, responseText, cwd); + return createErrorResult(errorMsg); + } else { + output += responseText; + return createErrorResult(`${errorMsg}\n${output}`); + } + } + + output += responseText; + + // Write to file if output option is specified + if (options.output) { + await this.writeToFile(options.output, responseText, cwd); + if (!options.silent) { + return createSuccessResult(` % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 ${responseText.length} 100 ${responseText.length} 0 0 ${Math.round(responseText.length / 0.1)} 0 --:--:-- --:--:-- --:--:-- ${Math.round(responseText.length / 0.1)}`); + } else { + return createSuccessResult(''); + } + } + + // Handle write-out format + if (options.writeOut) { + const writeOutResult = this.formatWriteOut(options.writeOut, response, responseText); + if (options.silent) { + return createSuccessResult(writeOutResult); + } else { + output += '\n' + writeOutResult; + } + } + + return createSuccessResult(options.silent ? '' : output); + + } catch (error) { + if (timeoutId) { + clearTimeout(timeoutId); + } + + if (error instanceof Error) { + if (error.name === 'AbortError') { + return createErrorResult(`${this.name}: operation timed out after ${options.timeout} seconds`); + } else if (error.message.includes('fetch')) { + return createErrorResult(`${this.name}: failed to connect to ${url.hostname}: ${error.message}`); + } else { + return createErrorResult(`${this.name}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: unknown error occurred`); + } + } + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + /** + * Parse curl command line options + */ + private parseOptions(args: string[]): CurlOptions { + const options: CurlOptions = { + method: 'GET', + headers: {}, + includeHeaders: false, + followRedirects: true, + silent: false, + verbose: false, + maxRedirects: 50, + showProgress: true, + }; + + let i = 0; + while (i < args.length) { + const arg = args[i]; + + if (arg.startsWith('-')) { + // Handle options + switch (arg) { + case '-X': + case '--request': + i++; + if (i < args.length) { + options.method = args[i].toUpperCase(); + } + break; + + case '-H': + case '--header': + i++; + if (i < args.length) { + const header = args[i]; + const colonIndex = header.indexOf(':'); + if (colonIndex > 0) { + const key = header.substring(0, colonIndex).trim(); + const value = header.substring(colonIndex + 1).trim(); + options.headers[key] = value; + } + } + break; + + case '-d': + case '--data': + case '--data-raw': + i++; + if (i < args.length) { + options.data = args[i]; + if (options.method === 'GET') { + options.method = 'POST'; + } + } + break; + + case '-o': + case '--output': + i++; + if (i < args.length) { + options.output = args[i]; + } + break; + + case '-i': + case '--include': + options.includeHeaders = true; + break; + + case '-L': + case '--location': + options.followRedirects = true; + break; + + case '-s': + case '--silent': + options.silent = true; + options.showProgress = false; + break; + + case '-v': + case '--verbose': + options.verbose = true; + break; + + case '-A': + case '--user-agent': + i++; + if (i < args.length) { + options.userAgent = args[i]; + } + break; + + case '-m': + case '--max-time': + i++; + if (i < args.length) { + options.timeout = parseInt(args[i], 10); + } + break; + + case '--max-redirs': + i++; + if (i < args.length) { + options.maxRedirects = parseInt(args[i], 10); + } + break; + + case '-w': + case '--write-out': + i++; + if (i < args.length) { + options.writeOut = args[i]; + } + break; + + case '--no-progress-meter': + options.showProgress = false; + break; + + default: + // Handle combined short options like -sL + if (arg.startsWith('-') && arg.length > 2 && !arg.startsWith('--')) { + for (let j = 1; j < arg.length; j++) { + const shortOpt = '-' + arg[j]; + switch (shortOpt) { + case '-s': + options.silent = true; + options.showProgress = false; + break; + case '-L': + options.followRedirects = true; + break; + case '-i': + options.includeHeaders = true; + break; + case '-v': + options.verbose = true; + break; + } + } + } + break; + } + } else { + // This should be the URL + if (!options.url) { + options.url = arg; + } + } + + i++; + } + + return options; + } + + /** + * Write response to a file + */ + 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'); + } + + const absolutePath = join(cwd, filename); + + await this.fs.writeFile(absolutePath, content, 'utf8'); + } catch (error) { + throw new Error(`failed to write to file ${filename}: ${error instanceof Error ? error.message : 'unknown error'}`); + } + } + + /** + * Format write-out variables + */ + private formatWriteOut(format: string, response: Response, responseText: string): string { + const variables: Record = { + 'http_code': response.status, + 'response_code': response.status, + 'http_version': '1.1', + 'size_download': responseText.length, + 'size_upload': 0, + 'time_total': 0.1, // Placeholder since we don't track timing + 'time_namelookup': 0.01, + 'time_connect': 0.02, + 'time_appconnect': 0.03, + 'time_pretransfer': 0.04, + 'time_redirect': 0.0, + 'time_starttransfer': 0.05, + 'url_effective': response.url, + 'content_type': response.headers.get('content-type') || '', + }; + + let result = format; + + // Replace variables + for (const [key, value] of Object.entries(variables)) { + const regex = new RegExp(`%\\{${key}\\}`, 'g'); + result = result.replace(regex, String(value)); + } + + // Handle escape sequences + result = result.replace(/\\n/g, '\n'); + result = result.replace(/\\t/g, '\t'); + result = result.replace(/\\r/g, '\r'); + result = result.replace(/\\\\/g, '\\'); + + return result; + } +} \ No newline at end of file diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index 4e9f0024..a5da02d3 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -3,6 +3,7 @@ export { CatCommand } from './cat'; export { CdCommand } from './cd'; export { ClearCommand } from './clear'; export { CpCommand } from './cp'; +export { CurlCommand } from './curl'; export { CutCommand } from './cut'; export { DateCommand } from './date'; export { DiffCommand } from './diff'; diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index 09b3234b..bf3309a3 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -28,7 +28,7 @@ describe('ShellTool', () => { }); it('should have correct tool properties', () => { - expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git. Supports compound commands with &&, ||, ;, and | operators'); + expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators'); expect(shellTool.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index 710e1f27..96c3a280 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -7,6 +7,7 @@ import { CdCommand, ClearCommand, CpCommand, + CurlCommand, CutCommand, DateCommand, DiffCommand, @@ -43,11 +44,11 @@ export class ShellTool implements Tool { private cwd: string; private commands: Map; - readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git. Supports compound commands with &&, ||, ;, and | operators"; + readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators"; readonly inputSchema = z.object({ command: z.string().describe( - 'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'"' + 'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'", "curl -X GET https://api.example.com", "curl -H \'Content-Type: application/json\' -d \'{"key":"value"}\' https://api.example.com". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'"' ), }); @@ -61,6 +62,7 @@ export class ShellTool implements Tool { this.registerCommand(new CdCommand(fs)); this.registerCommand(new ClearCommand()); this.registerCommand(new CpCommand(fs)); + this.registerCommand(new CurlCommand(fs)); this.registerCommand(new CutCommand(fs)); this.registerCommand(new DateCommand()); this.registerCommand(new DiffCommand(fs));