import vm from "node:vm"; import type { TestCase } from "./types"; // --------------------------------------------------------------------------- // JavaScript sandbox test harness // --------------------------------------------------------------------------- // // Executes untrusted user code against a set of test cases inside a Node `vm` // context. This powers test-driven grading for the code-creation and // debugging problem types: the user's code is "correct" when it passes the // hidden tests, exactly like a TDD suite going green. // // Security note: Node's `vm` is NOT a hardened security boundary. This is a // single-user, local-first app, so the threat model is "stop my own buggy // code from hanging the request", not "run hostile code". We harden what we // cheaply can — a stripped global context, no `require`/`process`, and a hard // wall-clock timeout that kills infinite loops. export interface TestResult { name: string; passed: boolean; expected: unknown; /** The value the function returned (omitted when it threw). */ actual?: unknown; /** Error message when the call threw or timed out. */ error?: string; } export interface TestRunResult { passed: number; total: number; allPassed: boolean; results: TestResult[]; /** Lines captured from `console.log` during the run. */ stdout: string[]; /** * Set when the code failed to compile, the entry function was missing, or * the whole run hit the wall-clock timeout. When present, no tests ran. */ compileError?: string; } export interface RunOptions { /** Wall-clock budget for the entire run, in milliseconds. */ timeoutMs?: number; } const DEFAULT_TIMEOUT_MS = 1500; /** Structural deep equality with NaN === NaN. Runs inside the sandbox. */ function deepEqualSource(): string { return `function __deepEqual(a, b) { if (a === b) return true; if (typeof a === "number" && typeof b === "number") { return a !== a && b !== b; // NaN === NaN } if (a === null || b === null || typeof a !== "object" || typeof b !== "object") { return false; } var aArr = Array.isArray(a), bArr = Array.isArray(b); if (aArr !== bArr) return false; if (aArr) { if (a.length !== b.length) return false; for (var i = 0; i < a.length; i++) if (!__deepEqual(a[i], b[i])) return false; return true; } var ak = Object.keys(a), bk = Object.keys(b); if (ak.length !== bk.length) return false; for (var j = 0; j < ak.length; j++) { var k = ak[j]; if (!Object.prototype.hasOwnProperty.call(b, k)) return false; if (!__deepEqual(a[k], b[k])) return false; } return true; }`; } /** * Run `userCode` (which must define `entryFunction`) against `tests`. * * Each test calls `entryFunction(...input)` and deep-equal compares the result * against `expected`. Returns a structured result that never throws — compile * errors, missing functions, runtime throws, and timeouts are all reported via * the result object so callers can grade uniformly. */ export function runJavaScriptTests( userCode: string, entryFunction: string, tests: TestCase[], options: RunOptions = {}, ): TestRunResult { const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; const stdout: string[] = []; const sandbox: Record = { __TESTS: tests.map((t) => ({ name: t.name, input: t.input, expected: t.expected, })), console: { log: (...args: unknown[]) => { stdout.push(args.map((a) => formatLogArg(a)).join(" ")); }, error: (...args: unknown[]) => { stdout.push(args.map((a) => formatLogArg(a)).join(" ")); }, warn: (...args: unknown[]) => { stdout.push(args.map((a) => formatLogArg(a)).join(" ")); }, info: (...args: unknown[]) => { stdout.push(args.map((a) => formatLogArg(a)).join(" ")); }, }, }; const context = vm.createContext(sandbox); // Wrap user code in an IIFE so its declarations stay local, then evaluate a // reference to the entry function so it is in scope for the test runner. const script = ` ${deepEqualSource()} (function () { ${userCode} if (typeof ${entryFunction} === "undefined") { return { __missing: true }; } var __fn = ${entryFunction}; if (typeof __fn !== "function") { return { __notFunction: true }; } var __out = []; for (var __i = 0; __i < __TESTS.length; __i++) { var __t = __TESTS[__i]; try { var __actual = __fn.apply(null, __t.input); __out.push({ name: __t.name, passed: __deepEqual(__actual, __t.expected), expected: __t.expected, actual: __actual, }); } catch (__e) { __out.push({ name: __t.name, passed: false, expected: __t.expected, error: (__e && __e.message) ? String(__e.message) : String(__e), }); } } return { __results: __out }; })() `; let raw: { __results?: TestResult[]; __missing?: boolean; __notFunction?: boolean; }; try { raw = vm.runInContext(script, context, { timeout: timeoutMs }) as typeof raw; } catch (err) { return { passed: 0, total: tests.length, allPassed: false, results: [], stdout, compileError: err instanceof Error ? err.message : String(err), }; } if (raw && raw.__missing) { return { passed: 0, total: tests.length, allPassed: false, results: [], stdout, compileError: `Function "${entryFunction}" is not defined.`, }; } if (raw && raw.__notFunction) { return { passed: 0, total: tests.length, allPassed: false, results: [], stdout, compileError: `"${entryFunction}" is not a function.`, }; } const results = raw.__results ?? []; const passed = results.filter((r) => r.passed).length; return { passed, total: tests.length, allPassed: tests.length > 0 && passed === tests.length, results, stdout, }; } function formatLogArg(arg: unknown): string { if (typeof arg === "string") return arg; try { return JSON.stringify(arg); } catch { return String(arg); } }