import { exec } from "child_process"; import { promisify } from "util"; import fs from "fs/promises"; import path from "path"; const execAsync = promisify(exec); const SANDBOX_DIR = path.join(process.cwd(), "temp_sandbox"); export interface SandboxResult { success: boolean; output: string; error?: string; executionTime: number; } /** * Executes code in a restricted environment. * For this implementation, we'll use a local temporary directory and limited execution time. * In a production environment, this should use Docker containers. */ export async function runCodeInSandbox(code: string, language: string = "python"): Promise { const startTime = Date.now(); const fileName = `test_code_${Date.now()}.${language === "python" ? "py" : "js"}`; const filePath = path.join(SANDBOX_DIR, fileName); try { // Ensure sandbox directory exists await fs.mkdir(SANDBOX_DIR, { recursive: true }); // Write code to file await fs.writeFile(filePath, code); let command = ""; if (language === "python") { command = `python3 ${filePath}`; } else if (language === "javascript") { command = `node ${filePath}`; } // Execute with a 5-second timeout const { stdout, stderr } = await execAsync(command, { timeout: 5000 }); return { success: !stderr, output: stdout, error: stderr, executionTime: Date.now() - startTime, }; } catch (error: any) { return { success: false, output: error.stdout || "", error: error.message || "Execution failed", executionTime: Date.now() - startTime, }; } finally { // Cleanup try { await fs.unlink(filePath); } catch (e) { // Ignore cleanup errors } } }