File size: 6,353 Bytes
9580dce | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | 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<string, unknown> = {
__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);
}
}
|