feat(workflow): 增强 MVEL 脚本条件块变量首次赋值与 break 静态拦截

- 在 `lintMvelCode` 中新增 `mvel-unscoped-block-assignment` 规则,检测在 if/else/switch/catch 等条件分支块内首次赋值但未在外部预先初始化的变量,提前防范 MVEL2 优化编译模式下的 `unresolvable property or identifier` 运行时反射异常
- 新增 `mvel-unsupported-break` 规则,拦截 MVEL2 循环中不支持的 `break` 控制流关键字,引导改用条件标志位控制终止
- 在 `workflow save` 草稿保存前自动注入工作流全节点脚本静态健康度扫描,及时透出代码告警
- 补充对应的单元测试用例,覆盖块内未声明赋值、预声明/三元表达式放行及 break 拦截场景
This commit is contained in:
gitea committed 2026-11-13 17:49:06 +08:00
1 parent 75a0611f0e
commit e00adbe5a8
3 files changed
+158 -1

No files matched your search

+18 -1
View File
@@ -1,6 +1,6 @@
import { readFileSync, writeFileSync } from "node:fs";
import { EkbError } from "../../../core/errors.js";
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/workflow/services.js";
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow, lintWorkflowScripts } from "../../../domains/platform/workflow/services.js";
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/management/save-error.js";
import { WorkflowDetailSchema } from "../../../domains/platform/workflow/types.js";
import {
@@ -99,6 +99,22 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
const forceWrite = booleanOption(parsed.options, ["force-write", "forceWrite"]);
const syncFile = booleanOption(parsed.options, ["in-place", "inPlace"]);
// 保存前静态代码健康度检查
const scriptLintReport = lintWorkflowScripts(parsedWorkflow as any);
const scriptWarnings: string[] = [];
if (scriptLintReport.totalCodeNodes > 0) {
for (const node of scriptLintReport.reports) {
if (node.issues.length > 0) {
for (const iss of node.issues) {
const icon = iss.level === "error" ? "❌" : "⚠️";
const loc = iss.line ? `(L${iss.line})` : "";
scriptWarnings.push(`${icon} 节点 [${node.nodeName}] ${loc}: [${iss.rule}] ${iss.message}`);
}
}
}
}
requireMutationConfirmation(
parsed,
runtime,
@@ -112,6 +128,7 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
tasksVersion: parsedWorkflow.tasksVersion,
forceWrite,
syncFile,
...(scriptWarnings.length > 0 ? { scriptWarnings } : {}),
});
}
@@ -89,6 +89,59 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
expect(res.issues).toHaveLength(0);
expect(res.referencedNodes[0].exists).toBe(true);
});
it("flags unscoped block assignment in MVEL conditional branches", () => {
const badCode = `
var upstream = action_calc;
while (upstream != null) {
if (upstream > 0) {
pEnd = 100;
} else {
pEnd = 200;
}
}
return pEnd;
`;
const existing = new Set(["action_calc"]);
const res = lintMvelCode(badCode, existing);
const branchIssue = res.issues.find((i) => i.rule === "mvel-unscoped-block-assignment");
expect(branchIssue).toBeDefined();
expect(branchIssue?.message).toContain("pEnd");
expect(branchIssue?.level).toBe("warning");
});
it("passes MVEL code when branch variable is initialized at outer scope or uses ternary", () => {
const safeCode = `
var upstream = action_calc;
pEnd = 0;
while (upstream != null) {
if (upstream > 0) {
pEnd = 100;
}
}
return pEnd;
`;
const existing = new Set(["action_calc"]);
const res = lintMvelCode(safeCode, existing);
expect(res.issues.some((i) => i.rule === "mvel-unscoped-block-assignment")).toBe(false);
});
it("detects unsupported break keyword in MVEL code", () => {
const codeWithBreak = `
var upstream = action_calc;
while (upstream != null) {
if (upstream > 10) {
break;
}
}
return upstream;
`;
const res = lintMvelCode(codeWithBreak, new Set(["action_calc"]));
const breakIssue = res.issues.find((i) => i.rule === "mvel-unsupported-break");
expect(breakIssue).toBeDefined();
expect(breakIssue?.level).toBe("error");
expect(breakIssue?.message).toContain("break");
});
});
describe("lintWorkflowScripts", () => {
@@ -154,9 +154,96 @@ export function lintMvelCode(
}
}
// 3. 检查条件分支块 (if / else / switch / case / catch) 内部首次赋值但未在外部作用域预先声明的变量
// 杜绝 MVEL2 ReflectiveAccessorOptimizer 误将局部变量当属性反射而触发 unresolvable property or identifier 运行时异常
checkMvelUnscopedBlockAssignments(executableCode, issues);
// 4. 检查 MVEL2 不支持的 break 控制流关键字
// MVEL2 解释器在循环中不支持 break,会误触发属性查找并抛出 unresolvable property or identifier: break
const breakRegex = /\bbreak\b/g;
let breakMatch: RegExpExecArray | null;
while ((breakMatch = breakRegex.exec(executableCode)) !== null) {
const textBefore = executableCode.slice(0, breakMatch.index);
const lineNum = textBefore.split("\n").length;
const lastNewline = textBefore.lastIndexOf("\n");
const colNum = breakMatch.index - (lastNewline >= 0 ? lastNewline : 0);
issues.push({
level: "error",
line: lineNum,
column: colNum,
rule: "mvel-unsupported-break",
message: "MVEL2 运行时不支持 break 关键字,在循环内使用 break 会被解析器当成未声明属性查找而抛出 'unresolvable property or identifier: break' 致命异常;请改用 boolean 标志位条件控制循环终止",
});
}
return { issues, referencedNodes, hasReturn: hasRet };
}
/**
* 检查条件分支块内部首次赋值但未在外部预先初始化的变量
*/
function checkMvelUnscopedBlockAssignments(executableCode: string, issues: ScriptIssue[]): void {
const lines = executableCode.split(/\r?\n/);
const knownVars = new Set([
"bill", "result", "items", "success", "message", "System",
"true", "false", "null", "Double", "Integer", "Long", "Float", "String", "Math", "Calendar", "Date",
]);
let inBranchBlock = 0;
const branchBraceDepths: number[] = [];
let pendingBranch = false;
for (let l = 0; l < lines.length; l++) {
const line = lines[l];
if (/\b(if|else|catch|switch|case)\b/.test(line)) {
pendingBranch = true;
}
for (let c = 0; c < line.length; c++) {
const ch = line[c];
if (ch === "{") {
if (pendingBranch) {
branchBraceDepths.push(branchBraceDepths.length + 1);
inBranchBlock++;
pendingBranch = false;
} else {
branchBraceDepths.push(0);
}
} else if (ch === "}") {
if (branchBraceDepths.length > 0) {
const depth = branchBraceDepths.pop();
if (depth && depth > 0) inBranchBlock--;
}
}
}
const assignRegex = /(?:^|[^\w$.])([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=(?!=)/g;
let m: RegExpExecArray | null;
while ((m = assignRegex.exec(line)) !== null) {
const varName = m[1];
if (["if", "else", "while", "for", "return", "new", "throw", "try", "catch", "finally", "switch", "case"].includes(varName)) {
continue;
}
if (inBranchBlock > 0) {
if (!knownVars.has(varName)) {
issues.push({
level: "warning",
line: l + 1,
column: m.index + 1,
rule: "mvel-unscoped-block-assignment",
message: `变量 [${varName}] 在条件分支块内部首次被赋值,但在外层作用域未预先声明或初始化;在 MVEL2 优化编译模式下极易触发 'unresolvable property or identifier' 运行时异常,建议在外部提前声明/初始化 (如: ${varName} = null;) 或改用三元表达式`,
});
knownVars.add(varName);
}
} else {
knownVars.add(varName);
}
}
}
}
/**
* 递归收集工作流任务树中所有节点标识
*/