Files
hose-use/src/cli/commands/workflow/analyze.ts
T
gitea 7a19fa8337 feat(workflow): 保存期接口权限预检与 choose 表达式序列化开关
## 一、保存期「接口 → 应用」权限预检

工作流 HTTP 节点调用某些开放接口前,企业必须先开通对应应用,否则运行时
返回 403「未开通功能,无权访问」,而该报文字段里完全看不出缺哪个应用。
真实案例:某客户「单据审批」应用未开通,流程跑到第 9 步才被网关拦下,
排查成本极高。

本次在保存/静态分析阶段按接口路径反推所需应用:

- 新增 `analysis/openapi-app-requirements.ts`:接口路径 → 所需应用的映射表
  (首条 `/api/openapi/v1/backlog/data/` + POST/PUT/PATCH → 「单据审批」
  `TICKET_AUDIT_switch`、productId `o0hMBw000000g0`),配套
  `extractStaticUrlPath`(去域名、截断到第一个 `@{`、去 query/hash)与
  `matchAppRequirement`。
- `analysis/analyzer.ts` 6.3 节重构:以路径反查为主,节点显式声明的
  `powerCode`(`params` / URL query)作为交叉印证;两者指向同一权限时走
  路径规则,以便报文带上接口名、应用名、productId 与判定依据路径。显式
  声明了其它 `powerCode` 时以声明为准,避免两套规则打架。
- 新增保存期钩子 `preflightNodeAppRequirements` / `renderAppRequirementAlerts`
  (`cli/commands/workflow/shared.ts`),接入 `node add` / `node edit`:
  只检查本次写入的 HTTP 节点,未开通则输出 ⛔ 段并在 JSON 模式落到
  `appRequirementAlerts`;读不到企业应用清单时降级为 ⚠️,不阻断写入。
- `domains/store/tools.ts` 抽出 `isClientGoodOpened` 与
  `fetchOpenedPowerCodes`,`workflow analyze` 改为复用,移除内联汇总逻辑
  (`isClientGoodOpened` 仍从 `analyze.ts` 再导出以保持既有契约)。

判定边界(刻意收紧,宁可漏报不误报):只对 HTTP 节点生效;URL 若整体由
上游节点变量拼接则完全不判断;无法静态读出接口路径时不做任何猜测性告警。

## 二、choose 表达式序列化开关

合思前端序列化模板字符串时多写了一个右花括号,产出 `...}')}` 形态;
后端 Jackson 默认未开启 `FAIL_ON_TRAILING_TOKENS`,尾随 `}` 被静默忽略,
因此该形态在引擎侧可正常执行。

- 新增 `models/choose-serialization.ts`:`frontend` / `pure` 双模式序列化,
  以及 `parseChoosePayloadLoose`(逐个剥离尾部多余 `}` 再解析)。
- 全局配置新增 `chooseSerialization`,默认 `frontend`(与设计器字节一致),
  可用 `--choose-serialization` 单次覆盖;读取侧永远双形态兼容。
- 修复 `branch/explain.ts` 的 `parseChooseTag` 在 `}}` 形态下静默返回 null
  的缺陷,该缺陷会导致真实数据上的分支解释与字段引用分析失效。

## 测试

新增 24 个用例,覆盖:
- `choose-serialization.test.ts`:双模式序列化与宽松解析
- `openapi-app-requirements.test.ts`:静态路径提取、路径命中、方法不符跳过、
  纯变量 URL 跳过、非 HTTP 节点不判断、未开通/已开通/无清单三种诊断
- `shared.app-preflight.test.ts`:预检只处理 HTTP 节点、动态 URL 跳过、
  读不到清单降级不阻断、告警分级渲染

`bun test` 1068 pass / 0 fail;`bun run check` 零错误;`check:readme` 通过。

## 实机核对(全部只读,未触碰任何生产流程配置)

- 真实流程的两个 HTTP 节点均命中「单据审批」;同时确认设计器确实会把
  `powerCode` 写入节点 `params`,因此显式声明与路径反推两条规则都需要保留。
- 已开通该应用的企业 → 无诊断;未开通的企业 → 精确打出硬门禁并指向具体
  节点 key 与判定依据路径。
2026-11-04 16:43:34 +08:00

97 lines
4.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { getWorkflowDetail, getWorkflowAvailableNodes } from "../../../domains/platform/workflow/services.js";
import {
analyzeWorkflow,
extractWorkflowSpecificationIds,
type WorkflowFormSpecLike,
} from "../../../domains/platform/workflow/analysis/index.js";
import { getFormSpecification } from "../../../domains/bill/tools.js";
import { stringOption, booleanOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
import { isClientGoodOpened } from "../../../domains/store/tools.js";
export { isClientGoodOpened };
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow analyze <pipelineId>\n", exitCode: 1 };
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const specIds = extractWorkflowSpecificationIds(detail);
const specifications: Record<string, WorkflowFormSpecLike | undefined> = {};
const evidenceErrors: Array<{ source: string; message: string }> = [];
if (specIds.length > 0) {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
await Promise.all(
specIds.map(async (specId) => {
try {
const spec = await getFormSpecification(clients.ekbClient, corpId, specId);
if (spec) specifications[specId] = spec;
else evidenceErrors.push({ source: `specification:${specId}`, message: "未返回表单规格" });
} catch (error) {
evidenceErrors.push({ source: `specification:${specId}`, message: error instanceof Error ? error.message : String(error) });
}
})
);
}
let availableNodeTypes: Set<string> | undefined;
try {
const available = await getWorkflowAvailableNodes(client);
availableNodeTypes = available.allTypes;
} catch (error) {
evidenceErrors.push({ source: "availableNodeTypes", message: error instanceof Error ? error.message : String(error) });
}
let openedPowerCodes: Set<string> | undefined;
try {
const { fetchOpenedPowerCodes } = await import("../../../domains/store/tools.js");
openedPowerCodes = await fetchOpenedPowerCodes(runtime.selectedCorp!);
} catch (error) {
evidenceErrors.push({ source: "openedPowerCodes", message: error instanceof Error ? error.message : String(error) });
}
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes, openedPowerCodes });
const failOnAlert = booleanOption(parsed.options, ["fail", "fail-on-alert", "failOnAlert"]);
const exitCode = failOnAlert && !result.summary.passed ? 2 : 0;
if (runtime.jsonMode) return { stdout: printJson({ ...result, evidenceComplete: evidenceErrors.length === 0, evidenceErrors }, runtime.outputOptions), stderr: "", exitCode };
const gateDecision =
result.summary.hardBlocks > 0
? `❌ 发现 ${result.summary.hardBlocks} 项硬门禁阻断 (禁止发布上线)`
: result.summary.softAdvices > 0
? `⚠️ 硬门禁全通过,存在 ${result.summary.softAdvices} 项优化建议`
: "✅ 已执行的静态检查未发现阻断项";
const diagnosticRows = result.diagnostics.map((item) => [
item.category === "hard_block" ? "⛔ 硬门禁" : "💡 软建议",
item.severity,
item.code,
item.path,
item.message,
]);
const dependencyRows = result.dependencies.map((item) => [item.path, item.taskType, item.references.join(", ")]);
return {
stdout: [
`====== 工作流静态分析 (${detail.label || detail.id}) ======`,
printKeyValue({
"工作流 ID": detail.id,
"状态": detail.state === 1 ? "🟢 启用 (state=1)" : "⚪ 停用/草稿 (state=0)",
"门禁裁决": gateDecision,
"硬门禁数": `${result.summary.hardBlocks} 项 (致命配置/无权限/崩溃)`,
"软建议数": `${result.summary.softAdvices} 项 (规范与最佳实践)`,
"根节点数": result.ast.length,
"依赖节点数": result.dependencies.length,
}),
`\n依赖引用:\n${dependencyRows.length ? printTable(["节点路径", "类型", "引用"], dependencyRows) : "暂无代码引用"}`,
`\n诊断列表 (硬门禁 ⛔ / 软建议 💡):\n${diagnosticRows.length ? printTable(["分类", "级别", "代码", "节点路径", "说明"], diagnosticRows) : "未发现明显配置问题"}`,
...(evidenceErrors.length ? [`\n⚠️ 分析证据不完整:${evidenceErrors.map((item) => `${item.source}: ${item.message}`).join(";")}`] : []),
"",
].join("\n"),
stderr: "",
exitCode,
};
}