File size: 1,768 Bytes
4c41b3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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<SandboxResult> {
  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
    }
  }
}