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 与判定依据路径。
This commit is contained in:
gitea committed 2026-11-04 16:43:34 +08:00
1 parent 33f3275acb
commit 7a19fa8337
14 files changed
+1003 -36

No files matched your search

+1 -1
View File
@@ -334,7 +334,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"url": "link",
"web": "link"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
"summary": "单据检索、表单规格诊断与审批动作",
+16 -2
View File
@@ -73,11 +73,14 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
"测试企业目录": globalConfig.testEnterprisesDir || "未配置 (仅读全局用户企业)",
"默认自更新仓库": globalConfig.updateRepo || "官方默认 (yunyingk/hose-use)",
"自更新源偏好": globalConfig.updateSource || "auto (自动择优)",
"choose 表达式形态": globalConfig.chooseSerialization === "pure"
? "pure (配平形态, JSON 合法)"
: "frontend (百分百模拟设计器, 多一个右花括号 — 默认)",
"配置文件路径": configPath,
});
return {
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 配置测试目录: hose-use config test-dir <dir> (或 --clear)\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n`,
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose-use config mode <stateful|stateless>\n 指定企业: hose-use corps switch <corpId>\n 配置测试目录: hose-use config test-dir <dir> (或 --clear)\n 更新源设置: hose-use config set updateSource <auto|github|gitea>\n choose 形态: hose-use config set chooseSerialization <frontend|pure>\n`,
stderr: "",
exitCode: 0,
};
@@ -214,10 +217,21 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
};
}
partial.updateSource = srcLower;
} else if (keyLower === "chooseserialization" || keyLower === "choose") {
resolvedKey = "chooseSerialization";
const modeLower = val.toLowerCase();
if (modeLower !== "frontend" && modeLower !== "pure") {
return {
stdout: "",
stderr: `不支持的 chooseSerialization 值: ${val}。可选: frontend (默认, 与设计器产出一致, 多一个右花括号), pure (配平形态)\n`,
exitCode: 1,
};
}
partial.chooseSerialization = modeLower;
} else {
return {
stdout: "",
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, testEnterprisesDir, updateRepo, updateSource\n`,
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, testEnterprisesDir, updateRepo, updateSource, chooseSerialization\n`,
exitCode: 1,
};
}
+4 -19
View File
@@ -9,10 +9,9 @@ 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 function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
return item.status?.toUpperCase() === "OPENED";
}
export { isClientGoodOpened };
export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
@@ -46,22 +45,8 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
let openedPowerCodes: Set<string> | undefined;
try {
const { fetchClientGoods } = await import("../../../domains/store/tools.js");
const goods = await fetchClientGoods(runtime.selectedCorp!, { isAll: true });
const codes = new Set<string>();
for (const item of goods) {
const isOpened = isClientGoodOpened(item);
if (isOpened && Array.isArray(item.powers)) {
for (const power of item.powers) {
if (typeof power === "string") {
codes.add(power.toLowerCase());
} else if (power && typeof power === "object" && power.powerCode) {
codes.add(power.powerCode.toLowerCase());
}
}
}
}
openedPowerCodes = codes;
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) });
}
+21 -4
View File
@@ -15,7 +15,7 @@ import { stringOption, numberOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient, formatWorkflowVersion } from "./shared.js";
import { createWorkflowDetailClient, formatWorkflowVersion, resolveChooseSerialization, normalizeNodeExpressionFields, preflightNodeAppRequirements, renderAppRequirementAlerts } from "./shared.js";
import { handleGrantNodes, handleListAvailableNodes } from "./node-catalog.js";
async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0], original: WorkflowDetail, updated: WorkflowDetail, platformId?: string) {
@@ -319,6 +319,10 @@ async function handleAddNode(
}
}
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
const chooseMode = resolveChooseSerialization(parsed);
normalizeNodeExpressionFields(extra, chooseMode);
requireMutationConfirmation(
parsed,
runtime,
@@ -351,11 +355,15 @@ async function handleAddNode(
extra: Object.keys(extra).length ? extra : undefined,
});
const appPreflight = await preflightNodeAppRequirements(runtime, [
newTask as unknown as Record<string, any>,
]);
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult }, runtime.outputOptions),
stdout: printJson({ success: true, pipelineId, newTask, workflow: saveResult, appRequirementAlerts: appPreflight.alerts }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
@@ -372,6 +380,7 @@ async function handleAddNode(
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
"工作流版本": formatWorkflowVersion(saveResult),
}),
renderAppRequirementAlerts(appPreflight.alerts),
].join("\n");
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
@@ -445,6 +454,10 @@ async function handleEditNode(
}
}
// choose 表达式形态归一化:默认与设计器产出一致(多一个右花括号),可切换为配平形态
const chooseMode = resolveChooseSerialization(parsed);
normalizeNodeExpressionFields(customSet, chooseMode);
const mappingFile = stringOption(parsed.options, ["mapping-file", "mapping", "json-file"]);
if (mappingFile) {
const fs = await import("fs/promises");
@@ -488,11 +501,15 @@ async function handleEditNode(
});
const descManaged = desc !== undefined && isServerManagedDescType(editedTask.type);
const appPreflight = await preflightNodeAppRequirements(runtime, [
editedTask as unknown as Record<string, any>,
]);
const saveResult = await saveNodeChanges(client, detail, updatedWorkflow, platformId);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult, descIgnored: descManaged }, runtime.outputOptions),
stdout: printJson({ success: true, pipelineId, editedTask, workflow: saveResult, descIgnored: descManaged, appRequirementAlerts: appPreflight.alerts }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
@@ -510,7 +527,7 @@ async function handleEditNode(
: "";
return {
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n${codeTip}${labelTip}${descTip}`,
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n📌 ${formatWorkflowVersion(saveResult)}\n${codeTip}${labelTip}${descTip}${renderAppRequirementAlerts(appPreflight.alerts)}`,
stderr: "",
exitCode: 0,
};
@@ -0,0 +1,90 @@
import { describe, expect, it } from "bun:test";
import {
preflightNodeAppRequirements,
renderAppRequirementAlerts,
type NodeAppRequirementAlert,
} from "./shared.js";
const BACKLOG_URL =
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_1\"}')}]";
const noCorpRuntime = { selectedCorp: undefined } as any;
function alert(overrides: Partial<NodeAppRequirementAlert> = {}): NodeAppRequirementAlert {
return {
taskName: "action_pyrg",
taskLabel: "提交审批",
apiName: "单据审批(执行单据动作:同意 / 驳回 / 加签)",
appName: "单据审批",
powerCode: "TICKET_AUDIT_switch",
productId: "o0hMBw000000g0",
staticPath: "/api/openapi/v1/backlog/data/[",
verified: true,
unlicensed: true,
message: "节点 [提交审批] (action_pyrg) 调用单据审批,但当前企业尚未开通该应用。",
...overrides,
};
}
describe("保存期应用权限预检", () => {
it("非 HTTP 节点不触发任何检查", async () => {
const result = await preflightNodeAppRequirements(noCorpRuntime, [
{ name: "action_code", type: "code-js2", code: `return "${BACKLOG_URL}";` },
]);
expect(result.alerts).toEqual([]);
expect(result.verifyError).toBeUndefined();
});
it("URL 无法静态判断(上游节点拼接)时不产生告警", async () => {
const result = await preflightNodeAppRequirements(noCorpRuntime, [
{ name: "action_dyn", type: "http", method: "POST", url: "@{choose('{\"key\":\"action_prev.url\"}')}" },
]);
expect(result.alerts).toEqual([]);
});
it("命中接口但读不到企业清单 → verified=false,且不阻断", async () => {
const result = await preflightNodeAppRequirements(noCorpRuntime, [
{ name: "action_pyrg", type: "http", method: "POST", url: BACKLOG_URL },
]);
expect(result.alerts).toHaveLength(1);
const item = result.alerts[0]!;
expect(item.verified).toBe(false);
expect(item.unlicensed).toBe(false);
expect(item.powerCode).toBe("TICKET_AUDIT_switch");
expect(item.productId).toBe("o0hMBw000000g0");
expect(item.staticPath).toBe("/api/openapi/v1/backlog/data/[");
expect(item.message).toContain("未能读取企业应用清单");
expect(result.verifyError).toContain("未选择企业");
});
it("非 http 与 http 混排时只检查 http 节点", async () => {
const result = await preflightNodeAppRequirements(noCorpRuntime, [
{ name: "trigger", type: "webhook", url: BACKLOG_URL },
{ name: "action_pyrg", type: "http", method: "POST", url: BACKLOG_URL },
null,
]);
expect(result.alerts.map((item) => item.taskName)).toEqual(["action_pyrg"]);
});
});
describe("预检结果渲染", () => {
it("无告警时输出空串,不污染正常输出", () => {
expect(renderAppRequirementAlerts([])).toBe("");
});
it("未开通 → ⛔ 段并带判定依据路径", () => {
const text = renderAppRequirementAlerts([alert()]);
expect(text).toContain("⛔ 应用权限预检未通过");
expect(text).toContain("action_pyrg");
expect(text).toContain("判定依据: URL 静态路径 '/api/openapi/v1/backlog/data/['");
expect(text).not.toContain("⚠️");
});
it("未核对 → ⚠️ 段,不出现 ⛔", () => {
const text = renderAppRequirementAlerts([
alert({ verified: false, unlicensed: false, message: "节点 [提交审批] 未能读取企业应用清单" }),
]);
expect(text).toContain("⚠️ 应用权限未能核对");
expect(text).not.toContain("⛔");
});
});
+157
View File
@@ -1,4 +1,12 @@
import { flattenExecutionTree, listAllWorkflows } from "../../../domains/platform/workflow/services.js";
import {
DEFAULT_CHOOSE_SERIALIZATION,
normalizeChooseTags,
type ChooseSerialization,
} from "../../../domains/platform/workflow/models/choose-serialization.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
import { matchAppRequirement } from "../../../domains/platform/workflow/analysis/openapi-app-requirements.js";
import { fetchOpenedPowerCodes } from "../../../domains/store/tools.js";
import { stringOption } from "../../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
@@ -171,3 +179,152 @@ export function formatCodeNodeSummariesCard(
return lines;
}
// ── choose 表达式序列化模式 ────────────────────────────────────────────────────
/**
* 解析本轮写入使用的 choose 序列化模式。
*
* 优先级:命令行 --choose-serialization > 全局配置 chooseSerialization > 默认 frontend。
*
* 说明:该模式只影响 CLI 往服务端写入的字节形态,读取侧永远同时容忍两种形态。
* 详细背景见 src/domains/platform/workflow/models/choose-serialization.ts 顶部注释。
*/
export function resolveChooseSerialization(parsed: CliParsedArgs): ChooseSerialization {
const explicit = stringOption(parsed.options, ["choose-serialization"]);
if (explicit === "frontend" || explicit === "pure") {
return explicit;
}
return loadGlobalConfig().chooseSerialization ?? DEFAULT_CHOOSE_SERIALIZATION;
}
/**
* 归一化对象中所有形如 `url` 的字段(目前只有 http 节点的 `url`),
* 让 CLI 写出的结果与设计器保持一致。
*/
export function normalizeNodeExpressionFields(
target: Record<string, any>,
mode: ChooseSerialization
): { changed: boolean; before?: string; after?: string } {
if (!target || typeof target.url !== "string") return { changed: false };
const normalized = normalizeChooseTags(target.url, mode);
if (normalized === target.url) return { changed: false };
const before = target.url;
target.url = normalized;
return { changed: true, before, after: normalized };
}
// ── 保存期:接口所需企业应用的自动开通状态预检 ──────────────────────────────
export interface NodeAppRequirementAlert {
taskName: string;
taskLabel: string;
/** 接口的人类可读名称 */
apiName: string;
/** 所需应用名称 */
appName: string;
powerCode: string;
productId?: string;
/** 静态路径(判断依据) */
staticPath: string;
/** 是否真的读到了企业应用清单 */
verified: boolean;
/** 已核对且确认未开通 */
unlicensed: boolean;
message: string;
}
/**
* 保存节点时的权限预检:只看**本次写入的节点**,命中已知「接口 → 应用」映射时
* 去应用商店核对企业是否已开通。
*
* 边界(与静态分析保持一致):
* - 只处理 http 节点;
* - URL 读不出静态路径(整体由上游节点变量拼接)时直接跳过,不猜测;
* - 读不到企业应用清单时降级为「无法确认」,不阻断保存。
*
* 读清单失败不会抛错,也不会卡住写入 —— 这是提示性检查,不是门禁。
*/
export async function preflightNodeAppRequirements(
runtime: CliRuntime,
tasks: Array<Record<string, any> | undefined | null>
): Promise<{ alerts: NodeAppRequirementAlert[]; verifyError?: string }> {
const candidates: Array<{
task: Record<string, any>;
matched: NonNullable<ReturnType<typeof matchAppRequirement>>;
}> = [];
for (const task of tasks) {
if (!task || typeof task !== "object") continue;
if (String(task.type || "").trim().toLowerCase() !== "http") continue;
const matched = matchAppRequirement(task.url, task.method);
if (matched) candidates.push({ task, matched });
}
if (!candidates.length) return { alerts: [] };
let opened: Set<string> | undefined;
let verifyError: string | undefined;
try {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("当前未选择企业");
opened = await fetchOpenedPowerCodes(corp);
} catch (error) {
verifyError = error instanceof Error ? error.message : String(error);
}
const alerts = candidates.map(({ task, matched }) => {
const { requirement, staticPath } = matched;
const verified = opened !== undefined;
const unlicensed = verified && !opened!.has(requirement.powerCode.trim().toLowerCase());
const taskName = String(task.name || "");
const taskLabel = String(task.label || task.displayName || "");
const where = requirement.productId
? `「${requirement.appName}」(productId=${requirement.productId})`
: `「${requirement.appName}」`;
const head = `节点 [${taskLabel || taskName}] (${taskName}) 调用 ${requirement.apiName},需要应用${where},powerCode=${requirement.powerCode}`;
const message = !verified
? `${head};未能读取企业应用清单(${verifyError}),请自行到应用商店确认已开通,否则运行时会返回 403。`
: unlicensed
? `${head},但当前企业尚未开通该应用。流程跑到这个节点必然返回 403「未开通功能,无权访问」,请先到应用商店开通再发布。`
: `${head},企业已开通 ✅`;
return {
taskName,
taskLabel,
apiName: requirement.apiName,
appName: requirement.appName,
powerCode: requirement.powerCode,
productId: requirement.productId,
staticPath,
verified,
unlicensed,
message,
};
});
return { alerts, verifyError };
}
/** 把预检结果渲染成命令行提示块;无告警时返回空串。 */
export function renderAppRequirementAlerts(alerts: NodeAppRequirementAlert[]): string {
if (!alerts.length) return "";
const lines: string[] = [];
const blocked = alerts.filter((a) => a.unlicensed);
if (blocked.length) {
lines.push("");
lines.push("⛔ 应用权限预检未通过(发布后运行到这里必然 403):");
for (const alert of blocked) {
lines.push(` • ${alert.message}`);
lines.push(` 判定依据: URL 静态路径 '${alert.staticPath}'`);
}
}
const unknown = alerts.filter((a) => !a.verified);
for (const alert of unknown) {
lines.push("");
lines.push(`⚠️ 应用权限未能核对:${alert.message}`);
lines.push(` 判定依据: URL 静态路径 '${alert.staticPath}'`);
}
return lines.join("\n");
}
+15
View File
@@ -190,6 +190,18 @@ export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
// ── 全局运行配置(有状态/无状态模式)─────────────────────────────────────────
/**
* CLI 写出的 `@{choose('…')}` 表达式形态。
*
* - `frontend`(默认):百分百模拟合思设计器产出,choose 参数里的 JSON 会多一个右花括号。
* 这是平台的稳定输出形态,引擎侧完全兼容(见 docs/合思前端-表达式序列化缺陷-2026-11-04.md)。
* - `pure`:写出配平形态,JSON 合法;代价是 UI 下次保存会改回 `frontend` 形态。
*
* 该配置只影响「CLI 往服务端写什么」,读取侧永远同时容忍两种形态。
*/
export const ChooseSerializationSchema = z.enum(["frontend", "pure"]);
export type ChooseSerialization = z.infer<typeof ChooseSerializationSchema>;
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(true).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),
defaultCorpId: z.string().optional().describe("默认工作企业 ID"),
@@ -197,6 +209,9 @@ export const GlobalConfigSchema = z.object({
testEnterprisesDir: z.string().min(1).optional().describe("测试/自定义企业目录(仅用于开发测试重载,优先于全局用户目录)"),
updateRepo: z.string().optional().describe("默认自更新的 GitHub 仓库 (owner/repo)"),
updateSource: z.enum(["auto", "github", "gitea"]).optional().default("auto").describe("默认自更新源通道偏好 (auto/github/gitea)"),
chooseSerialization: ChooseSerializationSchema.optional()
.default("frontend")
.describe("choose 表达式序列化形态: frontend(默认, 与设计器产出完全一致, 多一个右花括号) / pure(配平形态)"),
});
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
@@ -11,6 +11,7 @@ import type {
AnalyzeWorkflowOptions,
} from "./types.js";
import { isKnownGrayNodeType } from "../nodes/gray-nodes-catalog.js";
import { matchAppRequirement } from "./openapi-app-requirements.js";
const KNOWN_TYPES = new Set([
"webhook",
@@ -721,13 +722,43 @@ export function analyzeWorkflow(
}
}
// 6.3 权限代码 (powerCode) 开通状态校验 (UNLICENSED_POWER_CODE / POWER_CODE_DEPENDENCY)
// 6.3 开放接口 → 所需企业应用 开通状态校验
//
// ── 判定边界(重要,别放宽)────────────────────────────────────
// 1. 只对 HTTP 节点生效;
// 2. 只对「能静态读出接口路径」的 URL 生效 —— URL 若整体由上游节点
// 变量拼接(以 @{...} 开头),运行前无人知道会打到哪个接口,
// 一律跳过,不做任何猜测性告警;
// 3. 路径必须命中 OPENAPI_APP_REQUIREMENTS 里的已知映射才判断。
//
// 真实事故驱动:任子行「单据审批」应用未开通,流程跑到第 9 步才被网关
// 403「未开通功能,无权访问」拦下,而 403 报文里完全看不出缺哪个应用。
//
// 优先级:节点自己显式声明的 powerCode(params / URL query)优先;
// 没有显式声明时,才用接口路径去反查所需应用。
const httpMethod = String((task as Record<string, unknown>).method || "");
const paramPowerCodes: string[] = [];
const rawParams = (task as Record<string, unknown>).params;
if (Array.isArray(rawParams)) {
for (const param of rawParams) {
if (!param || typeof param !== "object") continue;
const entry = param as { key?: unknown; value?: unknown };
if (String(entry.key ?? "").trim().toLowerCase() !== "powercode") continue;
if (typeof entry.value !== "string") continue;
const value = entry.value.trim();
if (value) paramPowerCodes.push(value);
}
}
let urlPowerCode: string | undefined;
let powerCodeEncodingBroken = false;
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
if (powerCodeMatch) {
let powerCode: string | undefined;
try {
powerCode = decodeURIComponent(powerCodeMatch[1]);
urlPowerCode = decodeURIComponent(powerCodeMatch[1]);
} catch {
powerCodeEncodingBroken = true;
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
@@ -736,10 +767,66 @@ export function analyzeWorkflow(
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 中 powerCode 参数包含无效的百分号转义 [${powerCodeMatch[1]}],无法校验功能权限。请修正为有效的 URL 编码。`,
});
}
}
if (powerCode !== undefined) {
const powerCodeKey = powerCode.trim().toLowerCase();
const explicitPowerCodes = powerCodeEncodingBroken
? []
: Array.from(
new Map(
[...paramPowerCodes, ...(urlPowerCode ? [urlPowerCode] : [])].map(
(code) => [code.trim().toLowerCase(), code.trim()] as const
)
).values()
).filter(Boolean);
// 没有显式声明、或显式声明的正是该接口要求的那一个 → 走「接口路径反查」,
// 这样报文里能带上应用名、productId 与判定依据路径(比只有 powerCode 更好排查)。
// 显式声明了别的 powerCode 时以声明为准,避免两套规则打架。
const matched = powerCodeEncodingBroken ? null : matchAppRequirement(url, httpMethod);
const preferPathRule =
matched !== null &&
(explicitPowerCodes.length === 0 ||
explicitPowerCodes.some(
(code) => code.toLowerCase() === matched.requirement.powerCode.toLowerCase()
));
if (matched && preferPathRule) {
// 6.3.1 按接口路径反查所需应用。
const { requirement, staticPath } = matched;
const powerCodeKey = requirement.powerCode.trim().toLowerCase();
const where = requirement.productId
? `「${requirement.appName}」(productId=${requirement.productId})`
: `「${requirement.appName}」`;
const evidence = `判定依据:URL 静态路径 '${staticPath}'`;
const methodLabel = httpMethod ? `${httpMethod.toUpperCase()} ` : "";
const hintSuffix = requirement.hint ? ` ${requirement.hint}` : "";
const declaredNote = explicitPowerCodes.length
? `(节点 ${paramPowerCodes.length ? "params" : "URL query"} 中已显式声明 powerCode=${requirement.powerCode})`
: "";
if (openedPowerCodeSet === undefined) {
addDiagnostic(diagnostics, {
severity: "warning",
category: "soft_advice",
code: "POWER_CODE_DEPENDENCY",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 调用的接口 [${requirement.apiName}](${methodLabel}${staticPath}…)属于${where}的开放能力,需要权限代码 powerCode=${requirement.powerCode}${declaredNote}。当前未提供企业已开通应用清单,无法确认是否可用;若未开通,运行时将返回 403 Forbidden。${evidence}。${hintSuffix}`,
});
} else if (!openedPowerCodeSet.has(powerCodeKey)) {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "UNLICENSED_POWER_CODE",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 调用的接口 [${requirement.apiName}](${methodLabel}${staticPath}…)属于${where}的开放能力${declaredNote},但当前企业尚未开通该应用(powerCode=${requirement.powerCode})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问),且报文不会提示缺哪个应用。请先在应用商店开通「${requirement.appName}」(或更换为已开通的等价接口)后重新发布。${evidence}。${hintSuffix}`,
});
}
} else if (explicitPowerCodes.length > 0) {
// 6.3.2 节点显式声明了该接口之外的 powerCode,以显式声明为准
for (const powerCode of explicitPowerCodes) {
const powerCodeKey = powerCode.toLowerCase();
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
const sourceHint = paramPowerCodes.includes(powerCode) ? "params" : "URL query";
if (openedPowerCodeSet !== undefined) {
if (!openedPowerCodeSet.has(powerCodeKey)) {
@@ -748,7 +835,7 @@ export function analyzeWorkflow(
category: "hard_block",
code: "UNLICENSED_POWER_CODE",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'(声明于 ${sourceHint}),但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
});
}
} else {
@@ -757,7 +844,7 @@ export function analyzeWorkflow(
category: "soft_advice",
code: "POWER_CODE_DEPENDENCY",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'(声明于 ${sourceHint})。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
});
}
}
@@ -0,0 +1,173 @@
import { describe, expect, it } from "bun:test";
import {
extractStaticUrlPath,
matchAppRequirement,
OPENAPI_APP_REQUIREMENTS,
} from "./openapi-app-requirements.js";
import { analyzeWorkflow } from "./index.js";
describe("extractStaticUrlPath", () => {
it("保留到第一个变量之前的静态路径前缀", () => {
expect(
extractStaticUrlPath(
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_x\"}')}]"
)
).toBe("/api/openapi/v1/backlog/data/[");
});
it("无变量的完整 URL 去掉 query 与 hash", () => {
expect(
extractStaticUrlPath("https://app.ekuaibao.com/api/openapi/v1/backlog/data/abc123?x=1#frag")
).toBe("/api/openapi/v1/backlog/data/abc123");
});
it("纯变量开头的 URL 无法静态判断,返回 null", () => {
expect(extractStaticUrlPath("@{choose('{\"key\":\"action_prev.url\"}')}")).toBeNull();
expect(extractStaticUrlPath("@{choose('{\"key\":\"action_prev.url\"}')}/api/openapi/v1/backlog/data/x")).toBeNull();
});
it("空值一律返回 null", () => {
expect(extractStaticUrlPath("")).toBeNull();
expect(extractStaticUrlPath(" ")).toBeNull();
expect(extractStaticUrlPath(undefined)).toBeNull();
expect(extractStaticUrlPath(null)).toBeNull();
expect(extractStaticUrlPath(123)).toBeNull();
});
});
describe("matchAppRequirement", () => {
it("命中:单据审批接口的静态 URL", () => {
const matched = matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]", "POST");
expect(matched).not.toBeNull();
expect(matched?.requirement.appName).toBe("单据审批");
expect(matched?.requirement.powerCode).toBe("TICKET_AUDIT_switch");
expect(matched?.staticPath).toBe("/api/openapi/v1/backlog/data/[{flowId}]");
});
it("命中:设计器真实形态([@{choose(...)}] 后缀)", () => {
const matched = matchAppRequirement(
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_x\",\"properties\":[]}')}]",
"post"
);
expect(matched?.requirement.powerCode).toBe("TICKET_AUDIT_switch");
});
it("命中:节点未写 method 时不排除(路径已是强信号)", () => {
expect(matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/backlog/data/x")).not.toBeNull();
});
it("跳过:method 明确不符", () => {
expect(matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/backlog/data/x", "GET")).toBeNull();
});
it("跳过:URL 由上游节点变量整体拼接,无法判断", () => {
expect(matchAppRequirement("@{choose('{\"key\":\"action_prev.url\"}')}", "POST")).toBeNull();
});
it("跳过:路径不在已知映射表里", () => {
expect(matchAppRequirement("https://app.ekuaibao.com/api/openapi/v1/departments/all", "GET")).toBeNull();
});
it("映射表条目字段完整", () => {
for (const item of OPENAPI_APP_REQUIREMENTS) {
expect(item.apiName.length).toBeGreaterThan(0);
expect(item.appName.length).toBeGreaterThan(0);
expect(item.powerCode.length).toBeGreaterThan(0);
}
});
});
describe("按接口路径反查应用开通状态(analyzer 集成)", () => {
const build = (url: string, extra: Record<string, unknown> = {}) => ({
id: "wf-app-requirement",
label: "单据审批调用",
state: 1,
version: "1",
tasks: [
{
name: "action_pyrg",
type: "http",
label: "提交审批",
method: "POST",
url,
...extra,
},
],
});
const REAL_URL =
"https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose('{\"key\":\"webhook_1\",\"properties\":[]}')}]";
it("企业未开通「单据审批」→ 硬门禁,并给出应用与判定依据", () => {
const result = analyzeWorkflow(build(REAL_URL) as any, {
openedPowerCodes: ["staff_sync_switch"],
});
const diag = result.diagnostics.find((d) => d.code === "UNLICENSED_POWER_CODE");
expect(diag).toBeDefined();
expect(diag?.category).toBe("hard_block");
expect(diag?.severity).toBe("error");
expect(diag?.path).toBe("0");
expect(diag?.message).toContain("单据审批");
expect(diag?.message).toContain("TICKET_AUDIT_switch");
expect(diag?.message).toContain("productId=o0hMBw000000g0");
expect(diag?.message).toContain("/api/openapi/v1/backlog/data/[");
expect(diag?.message).toContain("403 Forbidden");
// 节点 key 必须出现在报文里,实施同学才能直接定位到画布上的节点
expect(diag?.message).toContain("action_pyrg");
expect(result.summary.passed).toBe(false);
});
it("企业已开通「单据审批」→ 不产生任何权限诊断", () => {
const result = analyzeWorkflow(build(REAL_URL) as any, {
openedPowerCodes: ["TICKET_AUDIT_switch"],
});
expect(result.diagnostics.some((d) => d.code === "UNLICENSED_POWER_CODE")).toBe(false);
expect(result.diagnostics.some((d) => d.code === "POWER_CODE_DEPENDENCY")).toBe(false);
});
it("未提供已开通清单 → 软建议而非硬门禁", () => {
const result = analyzeWorkflow(build(REAL_URL) as any);
const diag = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
expect(diag?.category).toBe("soft_advice");
expect(diag?.severity).toBe("warning");
expect(diag?.message).toContain("单据审批");
});
it("URL 整体由上游节点拼接 → 完全跳过,不猜测", () => {
const result = analyzeWorkflow(
build("@{choose('{\"key\":\"action_prev.url\"}')}") as any,
{ openedPowerCodes: [] }
);
expect(result.diagnostics.some((d) => d.code === "UNLICENSED_POWER_CODE")).toBe(false);
expect(result.diagnostics.some((d) => d.code === "POWER_CODE_DEPENDENCY")).toBe(false);
});
it("非 HTTP 节点即使 url 字段形似也不判断", () => {
const wf = {
id: "wf-non-http",
label: "代码节点",
state: 1,
version: "1",
tasks: [
{
name: "action_code",
type: "code-js2",
label: "拼 URL",
code: `const u = "${REAL_URL}"; return u;`,
},
],
};
const result = analyzeWorkflow(wf as any, { openedPowerCodes: [] });
expect(result.diagnostics.some((d) => d.code === "UNLICENSED_POWER_CODE")).toBe(false);
});
it("显式声明的 powerCode 优先于路径反查", () => {
const result = analyzeWorkflow(
build("https://app.ekuaibao.com/api/openapi/v1/backlog/data/x?powerCode=CUSTOM_AUDIT_switch") as any,
{ openedPowerCodes: [] }
);
const diags = result.diagnostics.filter((d) => d.code === "UNLICENSED_POWER_CODE");
expect(diags).toHaveLength(1);
expect(diags[0]?.message).toContain("CUSTOM_AUDIT_switch");
});
});
@@ -0,0 +1,128 @@
/**
* 合思开放平台接口 → 所需企业应用 的权限映射。
*
* ── 为什么需要这张表 ────────────────────────────────────────────────
*
* 工作流 HTTP 节点调用某些开放接口时,企业必须先开通对应的「应用商店」应用,
* 否则运行时会直接返回:
*
* HTTP 403 未开通功能,无权访问
*
* 这个 403 发生在流程跑到一半的时候,报错信息本身不含「缺哪个应用」,
* 排查成本极高(真实案例:任子行「单据审批」未开通,链路跑到第 9 步才炸)。
*
* 所以要在**保存/静态分析阶段**就根据接口路径反推所需应用,提前告警。
*
* ── 判定边界(重要)────────────────────────────────────────────────
*
* 只有 HTTP 节点、且 URL 里存在**静态可读的接口路径**时才判断。
* URL 若整体由上游节点变量拼接(如 `@{choose(...)}` 开头),运行前无人知道
* 会打到哪个接口,这类情况一律跳过,不做任何猜测性告警。
*/
export interface OpenApiAppRequirement {
/** 接口的人类可读名称 */
apiName: string;
/** 静态路径匹配正则(作用在去掉域名、去掉变量段之后的路径上) */
pathPattern: RegExp;
/** 需要校验的 HTTP 方法;省略表示不限方法 */
methods?: string[];
/** 所需应用名称 */
appName: string;
/** 应用提供的权限代码,用于与已开通应用交叉核验 */
powerCode: string;
/** 应用商店商品 ID,便于在告警里直接给出定位信息 */
productId?: string;
/** 补充说明 */
hint?: string;
}
/**
* 已知需要企业应用授权的开放接口。
*
* 新增条目时请以线上真实工作流抓到的请求为准(URL + method + powerCode 三者一起核)。
*/
export const OPENAPI_APP_REQUIREMENTS: OpenApiAppRequirement[] = [
{
apiName: "单据审批(执行单据动作:同意 / 驳回 / 加签)",
// POST /api/openapi/v1/backlog/data/{flowId}
// 设计器里 flowId 通常写成 [@{choose(...)}],静态前缀到 backlog/data/ 为止
pathPattern: /^\/api\/openapi\/v1\/backlog\/data\//i,
methods: ["POST", "PUT", "PATCH"],
appName: "单据审批",
powerCode: "TICKET_AUDIT_switch",
productId: "o0hMBw000000g0",
hint: "接口行为等效于在单据上手动点击「同意 / 驳回 / 加签」,会真实改变单据状态。",
},
];
/**
* 从 HTTP 节点的 URL 中提取「静态可判断的路径前缀」。
*
* 规则:
* - 去掉协议与域名;
* - 截断到第一个 `@{...}` 变量之前;
* - 去掉 query 与 hash。
*
* 若 URL 本身以变量开头(完全没有静态路径),返回 `null` —— 表示无法静态判断。
*
* 示例:
* ```
* https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[@{choose(...)}]
* → /api/openapi/v1/backlog/data/[
*
* @{choose(...)}
* → null(纯变量拼接,放弃判断)
* ```
*/
export function extractStaticUrlPath(url: unknown): string | null {
if (typeof url !== "string") return null;
const trimmed = url.trim();
if (!trimmed) return null;
let rest = trimmed;
const schemeMatch = rest.match(/^https?:\/\/[^/]+/i);
if (schemeMatch) {
rest = rest.slice(schemeMatch[0].length);
} else if (rest.startsWith("@{") || rest.startsWith("${")) {
// 纯变量开头,没有可读的静态路径
return null;
}
const varIndex = rest.indexOf("@{");
const staticPart = varIndex === -1 ? rest : rest.slice(0, varIndex);
if (!staticPart) return null;
const path = staticPart.split("?")[0].split("#")[0].trim();
return path || null;
}
export interface MatchedAppRequirement {
requirement: OpenApiAppRequirement;
/** 提取到的静态路径,便于在诊断信息里展示判断依据 */
staticPath: string;
}
/**
* 根据 URL 与 HTTP 方法匹配「需要应用授权」的接口规则。
*
* 只有能提取出静态路径、且方法命中时才返回结果;否则返回 `null`(不判断、不告警)。
*/
export function matchAppRequirement(url: unknown, method?: unknown): MatchedAppRequirement | null {
const staticPath = extractStaticUrlPath(url);
if (!staticPath) return null;
const normalizedMethod = typeof method === "string" ? method.trim().toUpperCase() : "";
for (const requirement of OPENAPI_APP_REQUIREMENTS) {
// 方法:节点没写 method 时不作为排除条件(路径已是足够强的信号);
// 写了 method 但与规则不符才跳过。
if (requirement.methods && requirement.methods.length > 0 && normalizedMethod) {
if (!requirement.methods.includes(normalizedMethod)) continue;
}
if (!requirement.pathPattern.test(staticPath)) continue;
return { requirement, staticPath };
}
return null;
}
@@ -1,5 +1,6 @@
import type { WorkflowTaskExecution } from "../types.js";
import { indexExecutionContexts } from "../execution/context.js";
import { parseChoosePayloadLoose } from "../models/choose-serialization.js";
import type { ConditionBranchExplanation, ConditionRuleExplanation } from "./types.js";
export const OP_MAP: Record<string, string> = {
@@ -18,7 +19,14 @@ export const OP_MAP: Record<string, string> = {
};
/**
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签。
*
* 载荷解析走 `parseChoosePayloadLoose`,同时兼容两种形态:
* - 设计器产出的 `{"k":"v"}}`(多一个右花括号,平台统一形态)
* - 配平形态 `{"k":"v"}`
*
* 早期实现直接用 `JSON.parse`,遇到设计器产出的数据会静默返回 null,
* 导致 `}}` 形态配置的分支解释全部失效。
*/
export function parseChooseTag(tag: string): {
upstreamNode: string;
@@ -26,10 +34,12 @@ export function parseChooseTag(tag: string): {
label: string;
} | null {
if (typeof tag !== "string") return null;
const match = tag.match(/@\{choose\('(.*)'\)\}/);
const match = tag.match(/@\{choose\('([\s\S]*?)'\)\}/);
if (!match) return null;
const normalized = parseChoosePayloadLoose(match[1]);
if (normalized === null) return null;
try {
const parsed = JSON.parse(match[1]);
const parsed = JSON.parse(normalized);
const upstreamNode = parsed.key || "";
const upstreamProp = (parsed.properties ?? []).map((property: { key?: string }) => property.key).filter(Boolean).join(".");
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
@@ -0,0 +1,131 @@
import { describe, expect, test } from "bun:test";
import {
inspectChooseTags,
normalizeChooseTags,
parseChoosePayloadLoose,
serializeChooseTag,
} from "./choose-serialization.js";
import { parseChooseTag } from "../branch/explain.js";
const payload = {
key: "action_detail",
properties: [{ key: "id", label: "单据ID", type: "TEXT" }],
label: "查询单据详情.单据ID",
};
const json = JSON.stringify(payload);
describe("parseChoosePayloadLoose", () => {
test("解析配平形态", () => {
expect(parseChoosePayloadLoose(json)).toBe(json);
});
test("解析设计器产出的多余右花括号形态", () => {
expect(parseChoosePayloadLoose(`${json}}`)).toBe(json);
});
test("解析多个多余右花括号", () => {
expect(parseChoosePayloadLoose(`${json}}}`)).toBe(json);
});
test("嵌套对象仍能正确剥离", () => {
const nested = JSON.stringify({ key: "a", properties: [{ key: "b", meta: { x: 1 } }] });
expect(parseChoosePayloadLoose(`${nested}}`)).toBe(nested);
});
test("非 JSON 载荷(旧式路径写法)返回 null,不猜测", () => {
expect(parseChoosePayloadLoose("body.details")).toBeNull();
expect(parseChoosePayloadLoose("action_missing.data")).toBeNull();
});
test("空载荷返回 null", () => {
expect(parseChoosePayloadLoose("")).toBeNull();
});
});
describe("serializeChooseTag", () => {
test("frontend 模式多一个右花括号", () => {
expect(serializeChooseTag(json, "frontend")).toBe(`@{choose('${json}}')}`);
});
test("pure 模式花括号配平", () => {
expect(serializeChooseTag(json, "pure")).toBe(`@{choose('${json}')}`);
});
test("frontend 产出可被再次解析(不累加)", () => {
const once = serializeChooseTag(json, "frontend");
const twice = normalizeChooseTags(once, "frontend");
expect(twice).toBe(once);
});
});
describe("normalizeChooseTags", () => {
const prefix = "https://wx2.ekuaibao.com/api/openapi/v1/backlog/data/[";
const suffix = "]";
test("frontend 模式补齐前端形态", () => {
const pureUrl = `${prefix}@{choose('${json}')}${suffix}`;
expect(normalizeChooseTags(pureUrl, "frontend")).toBe(`${prefix}@{choose('${json}}')}${suffix}`);
});
test("pure 模式去掉多余花括号", () => {
const frontendUrl = `${prefix}@{choose('${json}}')}${suffix}`;
expect(normalizeChooseTags(frontendUrl, "pure")).toBe(`${prefix}@{choose('${json}')}${suffix}`);
});
test("静态前缀与后缀完整保留", () => {
const frontendUrl = `${prefix}@{choose('${json}}')}${suffix}`;
const out = normalizeChooseTags(frontendUrl, "frontend");
expect(out.startsWith(prefix)).toBe(true);
expect(out.endsWith(suffix)).toBe(true);
});
test("同一字符串内多个标签全部归一化", () => {
const text = `a@{choose('${json}')}b@{choose('${json}')}c`;
const out = normalizeChooseTags(text, "frontend");
expect(out).toBe(`a@{choose('${json}}')}b@{choose('${json}}')}c`);
});
test("不含 choose 标签的字符串原样返回", () => {
expect(normalizeChooseTags("https://example.com/plain", "frontend")).toBe("https://example.com/plain");
});
test("旧式非 JSON 载荷原样保留,不被破坏", () => {
const legacy = "@{choose('body.details')}";
expect(normalizeChooseTags(legacy, "frontend")).toBe(legacy);
expect(normalizeChooseTags(legacy, "pure")).toBe(legacy);
});
});
describe("inspectChooseTags", () => {
test("区分配平与多花括号形态", () => {
const text = `@{choose('${json}}')} @{choose('${json}')} @{choose('body.x')}`;
expect(inspectChooseTags(text)).toEqual({
total: 3,
balanced: 1,
extraBrace: 1,
unparsable: 1,
});
});
});
describe("parseChooseTag 兼容设计器产出形态", () => {
test("配平形态可解析", () => {
expect(parseChooseTag(`@{choose('${json}')}`)).toEqual({
upstreamNode: "action_detail",
upstreamProp: "id",
label: "查询单据详情.单据ID",
});
});
test("多花括号形态同样可解析(回归:早期实现直接 JSON.parse 会失败)", () => {
expect(parseChooseTag(`@{choose('${json}}')}`)).toEqual({
upstreamNode: "action_detail",
upstreamProp: "id",
label: "查询单据详情.单据ID",
});
});
test("非 JSON 载荷返回 null", () => {
expect(parseChooseTag("@{choose('body.details')}")).toBeNull();
});
});
@@ -0,0 +1,126 @@
import {
ChooseSerializationSchema,
type ChooseSerialization,
} from "../../../../core/config/types.js";
/**
* `@{choose('…')}` 标签的序列化形态。
*
* ── 背景(务必先读这里,否则很容易把正常数据当脏数据改坏)─────────────────
*
* 合思设计器的「请求 URL」是 Lexical 富文本字段,前端把富文本序列化成扁平字符串时,
* 模板字符串多写了一个右花括号:
*
* `@{choose('${JSON.stringify(x)}}')}` // 注意 }}) 这一处,多了一个 }
* ↑
* 正确写法应为 `@{choose('${JSON.stringify(x)}')}`
*
* 因此 UI 保存出来的 `tasks[i].url` 里,choose 参数中的 JSON 永远是 `{"k":"v"}}`
* (`{` 2 个、`}` 3 个,不配平)。这是**平台稳定输出形态**,不是偶发脏数据。
*
* 后端引擎能正常处理它:choose 载荷最终交给 Jackson 反序列化,而 Jackson 的
* `FAIL_ON_TRAILING_TOKENS` 默认关闭,尾随的那个 `}` 被静默忽略。已用实机三组
* 对照验证过(双 `}` / 单 `}` / 双 `}` + 后缀,全部 COMPLETED,求值结果逐字符一致),
* 详见 `docs/合思前端-表达式序列化缺陷-2026-11-04.md` 第 8 章。
*
* ── 所以这个开关是干什么的 ────────────────────────────────────────────
*
* - `frontend`(默认):CLI 写出的表达式与 UI 产出一致,都带那个多余的 `}`。
* 好处是「CLI 改完 → 人去设计器再点一次保存」不会发生形态漂移,diff 干净,
* 也不会让设计器把变量节点降级成纯文本。
* - `pure`:CLI 写出配平形态。JSON 合法,适合离线分析、文档示例、或对接做了
* 严格 JSON 校验的下游。代价是 UI 下次保存会把它改回 `frontend` 形态。
*
* 注意:**读取侧永远同时容忍两种形态**,与写入模式无关。模式只影响「CLI 往服务端
* 写的字节长什么样」,不影响 CLI 如何理解已存在的数据。
*/
export { ChooseSerializationSchema };
export type { ChooseSerialization };
/** 默认百分百模拟真实前端。 */
export const DEFAULT_CHOOSE_SERIALIZATION: ChooseSerialization = "frontend";
const CHOOSE_TAG_START = "@{choose('";
/**
* 匹配 `@{choose('…')}` 标签。非贪婪,因为同一字符串里可能有多个标签。
* 载荷里出现 `')}` 之外的字符(含换行、引号)都能吃进去。
*/
const CHOOSE_TAG_PATTERN = /@\{choose\('([\s\S]*?)'\)\}/g;
/**
* 容错解析 choose 标签内的 JSON 载荷,返回规范化后的 JSON 文本。
*
* 依次尝试:
* 1. 原样 `JSON.parse`(配平形态,即 `pure` 产出)
* 2. 逐个剥离尾部多余的 `}` 后再解析(`frontend` 产出的多花括号形态)
*
* 无法解析时返回 `null`,调用方应原样保留标签,避免破坏旧式写法
* (如 `@{choose('body.details')}`,其载荷不是 JSON)。
*/
export function parseChoosePayloadLoose(raw: string): string | null {
let candidate = raw.trim();
while (candidate.length > 0) {
try {
return JSON.stringify(JSON.parse(candidate));
} catch {
if (!candidate.endsWith("}")) return null;
candidate = candidate.slice(0, -1).trimEnd();
}
}
return null;
}
/**
* 按指定模式序列化一个 choose 标签。
*
* - `frontend` → `@{choose('{"k":"v"}}')}`(多一个 `}`)
* - `pure` → `@{choose('{"k":"v"}')}`
*/
export function serializeChooseTag(json: string, mode: ChooseSerialization = DEFAULT_CHOOSE_SERIALIZATION): string {
const tail = mode === "frontend" ? "}')}" : "')}";
return `${CHOOSE_TAG_START}${json}${tail}`;
}
/**
* 归一化字符串中所有 `@{choose('…')}` 标签的形态。
*
* 只改写能成功解析为 JSON 的标签;解析不了的(旧式路径写法、人工手写的非 JSON 载荷)
* 原样保留,绝不猜测。
*/
export function normalizeChooseTags(text: string, mode: ChooseSerialization = DEFAULT_CHOOSE_SERIALIZATION): string {
if (typeof text !== "string" || !text.includes(CHOOSE_TAG_START)) return text;
return text.replace(CHOOSE_TAG_PATTERN, (whole, payload: string) => {
const json = parseChoosePayloadLoose(payload);
if (json === null) return whole;
return serializeChooseTag(json, mode);
});
}
/**
* 统计字符串里 choose 标签的形态分布,用于诊断与文档输出。
*/
export function inspectChooseTags(text: string): {
total: number;
balanced: number;
extraBrace: number;
unparsable: number;
} {
const result = { total: 0, balanced: 0, extraBrace: 0, unparsable: 0 };
if (typeof text !== "string" || !text.includes(CHOOSE_TAG_START)) return result;
const pattern = new RegExp(CHOOSE_TAG_PATTERN.source, "g");
let match: RegExpExecArray | null;
while ((match = pattern.exec(text)) !== null) {
result.total += 1;
const payload = match[1].trim();
if (parseChoosePayloadLoose(payload) === null) {
result.unparsable += 1;
} else if (payload.endsWith("}}")) {
result.extraBrace += 1;
} else {
result.balanced += 1;
}
}
return result;
}
+34
View File
@@ -50,6 +50,40 @@ export async function fetchClientGoods(
return items;
}
/**
* 应用是否处于「已开通」状态。
*
* 只看 `status`,不看 `onLineStatus` —— 后者表示应用是否在架,
* 已购买但已下架的应用仍然可以正常调用其开放接口。
*/
export function isClientGoodOpened(item: { status?: string | null; onLineStatus?: string | null }): boolean {
return item.status?.toUpperCase() === "OPENED";
}
/**
* 汇总当前企业**已开通**应用所提供的权限代码(统一小写,便于大小写不敏感比对)。
*
* 用于在保存工作流时判断「节点要调的接口,企业到底有没有买对应的应用」。
* 典型场景:调用 `/api/openapi/v1/backlog/data/*`(单据审批)需要
* `TICKET_AUDIT_switch`,未开通时运行期只会返回 403「未开通功能,无权访问」。
*/
export async function fetchOpenedPowerCodes(corp: CorpConfig): Promise<Set<string>> {
const goods = await fetchClientGoods(corp, { isAll: true });
const codes = new Set<string>();
for (const item of goods) {
if (!isClientGoodOpened(item)) continue;
for (const power of item.powers ?? []) {
if (typeof power === "string") {
if (power.trim()) codes.add(power.trim().toLowerCase());
continue;
}
const code = power?.powerCode;
if (code && code.trim()) codes.add(code.trim().toLowerCase());
}
}
return codes;
}
export async function searchGoods(
corp: CorpConfig,
options: { keyword?: string; start?: number; count?: number } = {}