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
@@ -5,9 +5,11 @@
|
||||
"": {
|
||||
"name": "ekb-mcp",
|
||||
"dependencies": {
|
||||
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3",
|
||||
},
|
||||
@@ -19,6 +21,10 @@
|
||||
},
|
||||
},
|
||||
"packages": {
|
||||
"@jitl/quickjs-ffi-types": ["@jitl/quickjs-ffi-types@0.32.0", "", {}, "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg=="],
|
||||
|
||||
"@jitl/quickjs-singlefile-cjs-release-sync": ["@jitl/quickjs-singlefile-cjs-release-sync@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-NjUUcw26PoeJHND6nmflAH8nIvAJvxJ2qkSPi95wfiBqPim80GtcdWommroiWb8hh1/7fVettEwodAsGt2Mrsg=="],
|
||||
|
||||
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
|
||||
|
||||
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
|
||||
@@ -47,6 +53,8 @@
|
||||
|
||||
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
|
||||
|
||||
"quickjs-emscripten-core": ["quickjs-emscripten-core@0.32.0", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
Vendored
+632
-627
File diff suppressed because it is too large.
Load diff
@@ -40,9 +40,11 @@
|
||||
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@jitl/quickjs-singlefile-cjs-release-sync": "0.32.0",
|
||||
"@modelcontextprotocol/core": "^2.0.0",
|
||||
"@modelcontextprotocol/server": "^2.0.0",
|
||||
"ky": "^2.0.2",
|
||||
"quickjs-emscripten-core": "0.32.0",
|
||||
"yaml": "^2.9.0",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bun
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { resolve, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
@@ -23,6 +23,11 @@ try {
|
||||
const version = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "version", "--json"], { cwd, env, encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(version.status, 0, version.stderr);
|
||||
assert.ok(JSON.parse(version.stdout).version);
|
||||
writeFileSync(join(cwd, "smoke.json"), JSON.stringify({ id: "smoke", name: "Smoke", source: "manual", credentials: { accessToken: "fixture", corpId: "smoke", staffId: "smoke:staff" } }));
|
||||
const sandbox = spawnSync(command, [...prefix, ...(plugin ? ["--hose-use-cli"] : []), "workflow", "eval-script", "--code", 'return { total: items.reduce((a, b) => a + b, 0), host: typeof process };', "--input", '{"items":[1,2,3]}', "--corp", "smoke"], { cwd, env, encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(sandbox.status, 0, sandbox.stderr);
|
||||
assert.match(sandbox.stdout, /"total": 6/);
|
||||
assert.match(sandbox.stdout, /"host": "undefined"/);
|
||||
await client.connect(transport, { timeout: 5000 });
|
||||
const tools = await client.listTools();
|
||||
assert.deepEqual(tools.tools.map(tool => tool.name), ["hose_cli"]);
|
||||
|
||||
@@ -128,3 +128,8 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
|
||||
- 借助 Kimi 网桥(`kimi-webbridge`)建立真实微前端会话,自动探测并解析不同应用类型下的非费用类表单元数据;
|
||||
- 提取出动态列、关联实体 ID 与系统字段字典,在 CLI 层面提供对非费用类业务对象的只读探针与结构化校验能力。
|
||||
|
||||
|
||||
|
||||
## 本地 JavaScript 仿真隔离
|
||||
|
||||
`eval-script` 使用内嵌 QuickJS/WASM 独立运行时,输入经过 JSON 复制,脚本无法访问宿主的 `process`、`Bun`、文件或网络。保留同步 JavaScript、日志和结构化执行结果;Promise 返回值明确报错。执行时间默认 3000ms,内存上限 32MiB,输入和结果各不超过 1MiB,日志最多 500 条及 64KiB。WASM 随 MCP bundle 和单文件二进制一起分发,不需要额外运行时文件。
|
||||
@@ -224,3 +224,34 @@ describe("MVEL lexical boundaries", () => {
|
||||
expect(result.allValid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("isolated script runtime boundaries", () => {
|
||||
for (const code of [
|
||||
'return Object.constructor("return typeof process")();',
|
||||
'return console.log.constructor("return typeof Bun")();',
|
||||
'return items.constructor.constructor("return typeof fetch")();',
|
||||
]) {
|
||||
it(`does not expose the host through ${code}`, async () => {
|
||||
const result = await executeJavaScriptSandbox(code, { items: [] });
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.returnValue).toBe("undefined");
|
||||
});
|
||||
}
|
||||
it("does not mutate inputs or host prototypes", async () => {
|
||||
const inputs = { items: [{ amount: 1 }] };
|
||||
const result = await executeJavaScriptSandbox('items[0].amount = 9; Object.prototype.hoseProof = true; return items;', inputs);
|
||||
expect(result.returnValue).toEqual([{ amount: 9 }]);
|
||||
expect(inputs.items[0].amount).toBe(1);
|
||||
expect(({} as any).hoseProof).toBeUndefined();
|
||||
});
|
||||
it("bounds logs, allocations and synchronous return values", async () => {
|
||||
const logs = await executeJavaScriptSandbox('for (let i = 0; i < 1000; i++) console.log(i);');
|
||||
expect(logs.success).toBe(false);
|
||||
expect(logs.logs.length).toBeLessThanOrEqual(500);
|
||||
const memory = await executeJavaScriptSandbox('return "x".repeat(64 * 1024 * 1024);');
|
||||
expect(memory.success).toBe(false);
|
||||
expect((await executeJavaScriptSandbox('return Promise.resolve(1);')).success).toBe(false);
|
||||
expect((await executeJavaScriptSandbox('return 1;')).returnValue).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -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