fix(workflow): isolate local scripts in bounded QuickJS runtime
This commit is contained in:
1 parent
fac81b08e8
commit
2844fd49dd
7 files changed
+771
-696
No files matched your search
@@ -1,6 +1,13 @@
|
||||
import vm from "node:vm";
|
||||
import variant from "@jitl/quickjs-singlefile-cjs-release-sync";
|
||||
import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
|
||||
import type { ScriptEvalResult, ScriptEvalLog } from "./types.js";
|
||||
|
||||
const MAX_MEMORY_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_VALUE_BYTES = 1024 * 1024;
|
||||
const MAX_LOG_BYTES = 64 * 1024;
|
||||
const MAX_LOG_ENTRIES = 500;
|
||||
let engine: ReturnType<typeof newQuickJSWASMModuleFromVariant> | undefined;
|
||||
|
||||
/**
|
||||
* 在隔离沙箱中执行 JavaScript 代码节点,仿真合思云端运行时并捕获输出与异常
|
||||
*/
|
||||
@@ -12,89 +19,101 @@ export async function executeJavaScriptSandbox(
|
||||
const timeoutMs = options.timeoutMs ?? 3000;
|
||||
const logs: ScriptEvalLog[] = [];
|
||||
const start = performance.now();
|
||||
|
||||
const recordLog = (level: "log" | "warn" | "error", ...args: unknown[]) => {
|
||||
const message = args
|
||||
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
|
||||
.join(" ");
|
||||
logs.push({ level, message, timestamp: Date.now() });
|
||||
};
|
||||
|
||||
const sandboxConsole = {
|
||||
log: (...args: unknown[]) => recordLog("log", ...args),
|
||||
info: (...args: unknown[]) => recordLog("log", ...args),
|
||||
warn: (...args: unknown[]) => recordLog("warn", ...args),
|
||||
error: (...args: unknown[]) => recordLog("error", ...args),
|
||||
};
|
||||
|
||||
// 创建安全的执行沙箱上下文
|
||||
const sandboxContext = vm.createContext({
|
||||
...inputs,
|
||||
console: sandboxConsole,
|
||||
Date,
|
||||
Math,
|
||||
JSON,
|
||||
RegExp,
|
||||
Array,
|
||||
Object,
|
||||
Number,
|
||||
String,
|
||||
Boolean,
|
||||
parseInt,
|
||||
parseFloat,
|
||||
isNaN,
|
||||
isFinite,
|
||||
encodeURI,
|
||||
decodeURI,
|
||||
encodeURIComponent,
|
||||
decodeURIComponent,
|
||||
});
|
||||
|
||||
// 包裹立即执行函数体 (IIFE),既允许顶层 return 语句,又能直接受 vm timeout 保护
|
||||
const wrappedCode = `(function() {\n${code}\n})()`;
|
||||
let timedOut = false;
|
||||
let logBytes = 0;
|
||||
let runtime: ReturnType<Awaited<ReturnType<typeof newQuickJSWASMModuleFromVariant>>["newRuntime"]> | undefined;
|
||||
let context: ReturnType<NonNullable<typeof runtime>["newContext"]> | undefined;
|
||||
|
||||
try {
|
||||
const returnValue = vm.runInContext(wrappedCode, sandboxContext, {
|
||||
timeout: timeoutMs,
|
||||
displayErrors: true,
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("timeoutMs must be a positive finite number");
|
||||
const inputJson = JSON.stringify(inputs);
|
||||
if (Buffer.byteLength(inputJson) > MAX_VALUE_BYTES) throw new Error("Sandbox inputs exceed 1MB");
|
||||
const module = await (engine ??= newQuickJSWASMModuleFromVariant(variant));
|
||||
runtime = module.newRuntime();
|
||||
runtime.setMemoryLimit(MAX_MEMORY_BYTES);
|
||||
runtime.setMaxStackSize(512 * 1024);
|
||||
const deadline = performance.now() + timeoutMs;
|
||||
runtime.setInterruptHandler(() => {
|
||||
timedOut = performance.now() >= deadline;
|
||||
return timedOut;
|
||||
});
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
durationMs,
|
||||
returnValue,
|
||||
logs,
|
||||
inputs,
|
||||
// 创建安全的执行沙箱上下文:所有对象均属于独立 WASM 运行时,不共享宿主构造器。
|
||||
const vm = context = runtime.newContext();
|
||||
const parsed = vm.evalCode(`JSON.parse(${JSON.stringify(inputJson)})`);
|
||||
if (parsed.error) {
|
||||
const error = vm.dump(parsed.error); parsed.error.dispose(); throw error;
|
||||
}
|
||||
const protectedNames = new Set(["console", "Date", "Math", "JSON", "RegExp", "Array", "Object", "Number", "String", "Boolean", "parseInt", "parseFloat", "isNaN", "isFinite", "encodeURI", "decodeURI", "encodeURIComponent", "decodeURIComponent"]);
|
||||
try {
|
||||
for (const key of Object.keys(inputs)) {
|
||||
if (protectedNames.has(key)) continue;
|
||||
const value = vm.getProp(parsed.value, key);
|
||||
try { vm.setProp(vm.global, key, value); } finally { value.dispose(); }
|
||||
}
|
||||
} finally { parsed.value.dispose(); }
|
||||
|
||||
const recordLog = (args: Parameters<typeof vm.dump>) => {
|
||||
const copy = args[0].dup();
|
||||
try {
|
||||
const value = vm.dump(copy);
|
||||
return typeof value === "object" ? JSON.stringify(value) : String(value);
|
||||
} finally { if (copy.alive) copy.dispose(); }
|
||||
};
|
||||
const sandboxConsole = vm.newObject();
|
||||
try {
|
||||
for (const [method, level] of [["log", "log"], ["info", "log"], ["warn", "warn"], ["error", "error"]] as const) {
|
||||
const log = vm.newFunction(method, (...args) => {
|
||||
try {
|
||||
const message = args.map(arg => recordLog([arg])).join(" ");
|
||||
logBytes += Buffer.byteLength(message);
|
||||
if (logs.length >= MAX_LOG_ENTRIES || logBytes > MAX_LOG_BYTES) throw new Error("Sandbox log limit exceeded");
|
||||
logs.push({ level, message, timestamp: Date.now() });
|
||||
} catch (error) { throw error instanceof Error ? error : new Error("Unable to serialize sandbox log"); }
|
||||
});
|
||||
try { vm.setProp(sandboxConsole, method, log); } finally { log.dispose(); }
|
||||
}
|
||||
vm.setProp(vm.global, "console", sandboxConsole);
|
||||
} finally { sandboxConsole.dispose(); }
|
||||
|
||||
// 包裹立即执行函数体 (IIFE),既允许顶层 return 语句,又能直接受 vm timeout 保护
|
||||
const wrappedCode = `(function() {\n${code}\n})()`;
|
||||
const result = vm.evalCode(wrappedCode, "workflow-script.js");
|
||||
if (result.error) {
|
||||
const error = vm.dump(result.error); result.error.dispose(); throw error;
|
||||
}
|
||||
let returnValue: unknown;
|
||||
try {
|
||||
const state = vm.getPromiseState(result.value);
|
||||
if (!(state.type === "fulfilled" && state.notAPromise)) {
|
||||
if (state.type === "fulfilled") state.value.dispose();
|
||||
if (state.type === "rejected") state.error.dispose();
|
||||
throw new Error("Sandbox only supports synchronous return values");
|
||||
}
|
||||
returnValue = vm.dump(result.value);
|
||||
const serialized = JSON.stringify(returnValue);
|
||||
if (serialized !== undefined && Buffer.byteLength(serialized) > MAX_VALUE_BYTES) throw new Error("Sandbox return value exceeds 1MB");
|
||||
} finally { result.value.dispose(); }
|
||||
return { success: true, durationMs: Number((performance.now() - start).toFixed(2)), returnValue, logs, inputs };
|
||||
} catch (err: any) {
|
||||
const durationMs = Number((performance.now() - start).toFixed(2));
|
||||
const msg = err?.message || String(err);
|
||||
const msg = timedOut ? "Script execution timed out" : err?.message || String(err);
|
||||
let line: number | undefined;
|
||||
let column: number | undefined;
|
||||
|
||||
const stack = err?.stack || "";
|
||||
// 匹配包裹函数内的行号(第 1 行是包裹头,因此需要 -1)
|
||||
const match = stack.match(/evalmachine\.<anonymous>:(\d+):(\d+)/);
|
||||
const match = stack.match(/workflow-script\.js:(\d+)(?::(\d+))?/);
|
||||
if (match) {
|
||||
const rawLine = Number(match[1]);
|
||||
line = Math.max(1, rawLine - 1);
|
||||
column = Number(match[2]);
|
||||
column = match[2] ? Number(match[2]) : undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
durationMs,
|
||||
returnValue: undefined,
|
||||
logs,
|
||||
error: {
|
||||
name: err?.name || "ExecutionError",
|
||||
message: msg,
|
||||
stack,
|
||||
line,
|
||||
column,
|
||||
},
|
||||
inputs,
|
||||
};
|
||||
return { success: false, durationMs, returnValue: undefined, logs,
|
||||
error: { name: err?.name || "ExecutionError", message: msg, stack, line, column }, inputs };
|
||||
} finally {
|
||||
context?.dispose();
|
||||
runtime?.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user