feat(workflow): add docs domain and unlicensed powerCode diagnostics, webhook sample injector, and snapshot sanitizer

This commit is contained in:
gitea committed 2026-10-21 11:42:50 +08:00
1 parent 60d0b8ffc1
commit 6e40faccff
14 files changed
+640 -10

No files matched your search

+1
View File
@@ -218,6 +218,7 @@ hose-use workflow nodes --all # 对照官方 108
hose-use workflow nodes grant code-js2 # 申请开通灰度节点(支持免密模式或 --password 预留密码管控)
hose-use workflow create --name="风险推送" --trigger=webhook --yes # 从零新建工作流 (支持 new, add, 自动分配 Webhook UUID, 强制草稿 state=0)
hose-use workflow copy wf_01k83y... --name="监控克隆版" --yes # 复制工作流为新草稿 (支持 cp, clone, 自动重置 Webhook urlPath)
hose-use workflow webhook send wf_01k83y... --bill=<单号> --yes # 向 Webhook 发送测试载荷(解决【获取更多数据样本】无事件问题)
hose-use workflow delete wf_01k83y... --yes # 安全删除工作流 (支持 rm, remove, 带 --dry-run 预览)
hose-use workflow node list wf_01k83y... # 树形层级索引查看工作流任务节点树与摘要 (别名 ls)
hose-use workflow node get wf_01k83y... <节点name或#序号> # 查看指定节点的完整配置 (别名 show, info)
+25
View File
@@ -150,6 +150,8 @@ hose-use workflow toggle wf_01k83y... --disable
- **⛔ 硬门禁**(必挂致命缺陷):
- `PERMISSION_MISSING_NODE`:使用了租户未开通的灰度节点(如未开通时的 `code-js2`);
- `MISPLACED_FORMULA_IN_DATALINK_MAPPING`:在底层 DataLink 数据写入节点中配置了前端表单公式(如 `AddMonths(...)`);
- `DOCS_DOMAIN_USED`:HTTP 节点误配开放平台文档域名 `docs.ekuaibao.com`(接口实际网关为 `app.ekuaibao.com`);
- `UNLICENSED_POWER_CODE`:HTTP 节点携带了未开通功能代码(如 `TICKET_AUDIT_switch`),网关将返回 403 Forbidden;
- `EMPTY_CODE`:代码节点缺少可执行脚本;
- `DEADLOCK_TRIGGER_STATE_FILTER` / `DEADLOCK_CONDITION_STATE_FILTER`:单据状态误配置导致事件静默丢弃或条件恒假;
- `INVALID_ACTION_ENUM_TEXT_VALUE`:枚举字段误配纯中文文本导致无法匹配。
@@ -416,3 +418,26 @@ hose-use workflow eval-script --code="console.log(items); return items.filter(x
- 执行 `hose-use bill spec <specificationId>`(或直接看 `workflow analyze` 的 `LINKAGE_PRIORITY_OVERRIDE` 告警);
- 若单据模板中某业务对象字段(如 `u_关联合同流程`)开启了联动赋值,且目标字段的优先级为 `LINKAGE_ASSIGNMENT (自动联动) > MANUALLY_FILL_IN (手动填写/工作流传入)`,则单据保存时会用被关联主表(如《合同流程》)上的字段值强行覆盖工作流传入的值;若主表对应字段为空,工作流传入的值就会被清空!
- 定位到缺失字段的台账记录后,使用 `hose-use platform audit <应用> <对象> --check-fields="..."` 巡检全量存量数据,并用 `hose-use platform record edit` / `batch-edit`(先 `--dry-run` 再 `--yes`)安全修复。
---
## 19. Webhook 触发器测试样本打桩与注入 (`workflow webhook send`)
当在合思 Web 控制台复制或新建 Webhook 触发的工作流时,经常遇到点击【获取更多数据样本】一直转圈等待外部事件打过来的情况。`hose-use` 提供了直接向工作流专属 Webhook 发送测试载荷的注入命令:
```bash
# 1. 抓取真实单据数据作为测试载荷发送,立即生成最新数据样本
hose-use workflow webhook send <pipelineId> --bill=<单号或ID> --yes
# 2. 发送自定义 JSON 请求体
hose-use workflow webhook send <pipelineId> --body='{"event":"test","amount":100}' --yes
# 3. 从文件读取载荷
hose-use workflow webhook send <pipelineId> --file=./mock_payload.json --yes
# 4. 预演检查(查看目标 Webhook 真实地址与组装后的 Payload)
hose-use workflow webhook send <pipelineId> --bill=<单号> --dry-run
```
发送成功后,Piper 后端立刻捕获该记录,在 Web 界面点击【获取更多数据样本】即可秒级看到该样本;在命令行也可以直接用 `hose-use workflow test <pipelineId> --sample=1` 进行沙箱调测。
+23 -1
View File
@@ -38,7 +38,29 @@ export async function handleAnalyze(parsed: CliParsedArgs, runtime: CliRuntime):
// 离线或受限网络环境下忽略探针失败
}
const result = analyzeWorkflow(detail, { specifications, availableNodeTypes });
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 = item.status?.toUpperCase() === "OPENED" || item.onLineStatus?.toUpperCase() === "ONLINE";
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;
} catch {
// 离线或无商店应用查询权限时忽略
}
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;
+6 -1
View File
@@ -15,6 +15,7 @@ import { handleNodeCommand } from "./node.js";
import { handleWorkflowTailCommand } from "./tail.js";
import { handleWorkflowLintScript, handleWorkflowEvalScript } from "./script.js";
import { handleWorkflowEnum } from "./enum.js";
import { handleWebhookCommand } from "./webhook.js";
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -114,10 +115,14 @@ export async function handleWorkflowCommand(
case "dictionary":
case "dict":
return handleWorkflowEnum(parsed, runtime);
case "webhook":
case "webhook-send":
case "webhooks":
return handleWebhookCommand(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
exitCode: 1,
};
}
+10 -3
View File
@@ -71,14 +71,21 @@ export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Pro
return { stdout: printJson(detail, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const isDraft = detail.state === 0;
const tasksVersion = (detail as Record<string, unknown>).tasksVersion;
const summary = printKeyValue({
"工作流 ID": detail.id,
"工作流名称": detail.label,
"状态": detail.state === 1 ? "🟢 启用" : "⚪ 停用",
"版本号": detail.version || "-",
"当前状态": detail.state === 1 ? "🟢 线上启用 (state=1)" : "⚪ 停用/未发布草稿 (state=0)",
"发布版本 (version)": detail.version || "-",
...(tasksVersion !== undefined ? { "草稿版本 (tasksVersion)": String(tasksVersion) } : {}),
"节点总数": detail.tasks?.length ?? 0,
});
const draftNotice = isDraft
? `\n💡 提示: 该工作流当前处于未发布草稿态 (state=0)。草稿与生产流程共享同一实例 ID 和历史记录;直接修改草稿将在发布后覆盖线上逻辑。如需安全隔离测试,请先执行: hose-use workflow copy ${detail.id}\n`
: "";
let taskList = "";
if (detail.tasks && detail.tasks.length > 0) {
const taskRows = detail.tasks.map((t, i) => [
@@ -92,7 +99,7 @@ export async function handleGet(parsed: CliParsedArgs, runtime: CliRuntime): Pro
}
return {
stdout: `====== 工作流详情 ======\n${summary}\n${taskList}\n`,
stdout: `====== 工作流详情 ======\n${summary}\n${draftNotice}${taskList}\n`,
stderr: "",
exitCode: 0,
};
+131
View File
@@ -0,0 +1,131 @@
import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handleWebhookCommand } from "./webhook.js";
import * as shared from "./shared.js";
import * as services from "../../../domains/platform/services.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
function createMockRuntime(overrides: Partial<CliRuntime> = {}): CliRuntime {
const corp: any = {
id: "corp-1",
name: "测试企业",
corpId: "corp-1",
env: "test",
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: {
corpId: "corp-1",
accessToken: "token-1",
staffId: "user-1",
},
};
return {
corpContext: {
listCorps: () => [corp],
getCurrent: () => corp,
switchCorp: () => true,
resolve: () => corp,
} as any,
selectedCorp: corp,
jsonMode: false,
outputOptions: {},
...overrides,
};
}
describe("workflow webhook command", () => {
let spies: ReturnType<typeof spyOn>[] = [];
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("prints usage when pipelineId is not provided", async () => {
const parsed: CliParsedArgs = {
area: "workflow",
action: "webhook",
args: [],
options: {},
raw: ["webhook"],
};
const runtime = createMockRuntime();
const result = await handleWebhookCommand(parsed, runtime);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("用法: hose-use workflow webhook");
});
it("previews webhook payload in dry-run mode", async () => {
const parsed: CliParsedArgs = {
area: "workflow",
action: "webhook",
args: ["send", "881196955148578838"],
options: { "dry-run": true, body: '{"foo":"bar"}' },
raw: ["send", "881196955148578838", "--dry-run"],
};
const runtime = createMockRuntime();
const mockDetail = {
id: "881196955148578838",
label: "测试 Webhook 工作流",
tasks: [
{
name: "trigger_webhook",
type: "webhook",
label: "Webhook 触发器",
urlPath: "test-token-12345",
},
],
};
spies.push(
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({
client: {} as any,
clients: { ekbClient: {} as any } as any,
}),
spyOn(services, "getWorkflowDetail").mockResolvedValue(mockDetail as any)
);
const result = await handleWebhookCommand(parsed, runtime);
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain("[DRY-RUN]");
expect(result.stdout).toContain("881196955148578838");
expect(result.stdout).toContain("https://piper.ekuaibao.com/api/webhook/test-token-12345");
});
it("rejects non-webhook workflows with clear error", async () => {
const parsed: CliParsedArgs = {
area: "workflow",
action: "webhook",
args: ["881196955148578838"],
options: { yes: true },
raw: ["881196955148578838", "--yes"],
};
const runtime = createMockRuntime();
const mockDetail = {
id: "881196955148578838",
label: "定时触发流程",
tasks: [
{
name: "trigger_clock",
type: "clock",
label: "定时触发器",
},
],
};
spies.push(
spyOn(shared, "createWorkflowDetailClient").mockResolvedValue({
client: {} as any,
clients: { ekbClient: {} as any } as any,
}),
spyOn(services, "getWorkflowDetail").mockResolvedValue(mockDetail as any)
);
const result = await handleWebhookCommand(parsed, runtime);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("首节点不是 Webhook 触发器");
});
});
+227
View File
@@ -0,0 +1,227 @@
import { existsSync, readFileSync } from "node:fs";
import ky from "ky";
import { getWorkflowDetail } from "../../../domains/platform/services.js";
import { getBillByCodeOrId } from "../../../domains/bill/tools.js";
import { stringOption } from "../../parser.js";
import { printJson, printKeyValue } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
export async function handleWebhookCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const firstArg = parsed.args[0]?.toLowerCase();
const isActionVerb = firstArg === "send" || firstArg === "trigger" || firstArg === "post";
const pipelineId =
(isActionVerb ? parsed.args[1] : parsed.args[0]) ||
stringOption(parsed.options, ["id", "pipelineId", "source"]);
if (!pipelineId) {
return {
stdout: "",
stderr: [
"用法: hose-use workflow webhook [send] <pipelineId> [选项]",
"",
"说明:",
" 向工作流的 Webhook 触发器地址发送测试数据,生成新的数据样本。",
" 可彻底解决 Web 控制台复制或新建工作流后【获取更多数据样本】收不到事件的问题。",
"",
"选项:",
" --body='{...}' 指定自定义 JSON 请求体",
" --file=<path.json> 从 JSON 文件读取请求体",
" --bill=<单号|单据ID> 抓取真实单据数据作为测试载荷发送",
" --dry-run 仅预览目标 Webhook 地址与载荷,不实际发送",
" --yes 确认发送网络请求",
"",
"示例:",
" hose-use workflow webhook send 881196955148578838 --bill=spWC2AmbRbovsQ --yes",
" hose-use workflow webhook 881196955148578838 --body='{\"event\":\"test\"}' --yes",
].join("\n") + "\n",
exitCode: 1,
};
}
const { client, clients } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const triggerNode =
detail.tasks?.find(
(t) => t.type === "webhook" || t.type === "datalink-button-trigger"
) || detail.tasks?.[0];
const triggerType = triggerNode?.type || "unknown";
if (triggerType !== "webhook" && triggerType !== "datalink-button-trigger") {
return {
stdout: "",
stderr: `❌ 工作流 [${detail.label || pipelineId}] 的首节点不是 Webhook 触发器 (当前类型: ${triggerType})。\n该命令仅适用于以 Webhook 或外部事件为触发源的工作流。\n`,
exitCode: 1,
};
}
const rawNode = triggerNode as Record<string, unknown>;
const rawPath =
(typeof rawNode.urlPath === "string" && rawNode.urlPath) ||
(typeof rawNode.url === "string" && rawNode.url) ||
(typeof rawNode.path === "string" && rawNode.path);
if (!rawPath) {
return {
stdout: "",
stderr: `❌ 未能在 Webhook 触发器节点 [${triggerNode?.name || "-"}] 中找到有效的调用路径 (urlPath)。\n`,
exitCode: 1,
};
}
const webhookUrl = rawPath.startsWith("http")
? rawPath
: `https://piper.ekuaibao.com/api/webhook/${rawPath.replace(/^\/+/, "")}`;
let payload: Record<string, unknown> = {};
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
const filePath = stringOption(parsed.options, ["file", "path"]);
const billId = stringOption(parsed.options, ["bill", "flow", "code"]);
if (billId) {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
try {
const bills = await getBillByCodeOrId(clients.ekbClient, corpId, billId);
if (!bills.length) {
return {
stdout: "",
stderr: `❌ 未找到单号/ID 为 [${billId}] 的单据\n`,
exitCode: 1,
};
}
const bill = bills[0];
payload = {
event: "flow.submit",
action: "flow.submit",
flowId: bill.billId,
code: bill.billCode,
title: bill.title,
data: bill,
mockTimestamp: Date.now(),
};
} catch (err: unknown) {
return {
stdout: "",
stderr: `❌ 抓取单据 [${billId}] 失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
} else if (rawBody) {
try {
payload = JSON.parse(rawBody);
} catch (e: unknown) {
return {
stdout: "",
stderr: `❌ --body 参数不是合法的 JSON 格式: ${e instanceof Error ? e.message : String(e)}\n`,
exitCode: 1,
};
}
} else if (filePath) {
if (!existsSync(filePath)) {
return {
stdout: "",
stderr: `❌ 指定的 Payload 文件不存在: ${filePath}\n`,
exitCode: 1,
};
}
try {
payload = JSON.parse(readFileSync(filePath, "utf-8"));
} catch (e: unknown) {
return {
stdout: "",
stderr: `❌ 读取并解析文件 [${filePath}] 失败: ${e instanceof Error ? e.message : String(e)}\n`,
exitCode: 1,
};
}
} else {
payload = {
event: "manual_sample_test",
pipelineId,
triggerType,
timestamp: Date.now(),
message: "Sample event injected via hose-use workflow webhook send",
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "发送 Webhook 测试事件", pipelineId, {
pipelineId,
pipelineName: detail.label,
targetUrl: webhookUrl,
payload,
});
}
requireMutationConfirmation(
parsed,
runtime,
"发送 Webhook 测试事件",
`hose-use workflow webhook send ${pipelineId}${billId ? ` --bill=${billId}` : ""} --yes`
);
let responseText = "";
let responseStatus = 200;
try {
const res = await ky.post(webhookUrl, {
json: payload,
timeout: 15000,
throwHttpErrors: false,
});
responseStatus = res.status;
responseText = await res.text();
} catch (err: unknown) {
return {
stdout: "",
stderr: `❌ 发送 Webhook 请求失败: ${err instanceof Error ? err.message : String(err)}\n`,
exitCode: 1,
};
}
const isSuccess = responseStatus >= 200 && responseStatus < 300;
const resultData = {
pipelineId,
pipelineName: detail.label,
webhookUrl,
statusCode: responseStatus,
payloadSize: JSON.stringify(payload).length,
response: responseText,
success: isSuccess,
};
if (runtime.jsonMode) {
return {
stdout: printJson(resultData, runtime.outputOptions),
stderr: "",
exitCode: isSuccess ? 0 : 2,
};
}
const out = [
isSuccess ? "✅ Webhook 测试样本已成功发送!" : "⚠️ Webhook 请求已发送但服务端返回非 2xx 状态码:",
printKeyValue({
"工作流 ID": pipelineId,
"工作流名称": detail.label,
"Webhook 目标地址": webhookUrl,
"HTTP 状态码": String(responseStatus),
"载荷字节大小": `${resultData.payloadSize} bytes`,
}),
"",
"服务端响应体:",
responseText || "(空响应体)",
"",
"下一步操作建议:",
" 1. Web 控制台: 在工作流首节点触发器中点击【获取更多数据样本】,直接选取刚刚注入的样本;",
` 2. 命令行调试: 执行 hose-use workflow test ${pipelineId} --sample=1 进行沙箱运行。`,
].join("\n");
return {
stdout: `${out}\n`,
stderr: "",
exitCode: isSuccess ? 0 : 2,
};
}
+24 -2
View File
@@ -46,8 +46,30 @@ export function getWorkflowDetail(...args: Parameters<typeof api.getWorkflowDeta
return api.getWorkflowDetail(...args);
}
export function updateWorkflow(...args: Parameters<typeof api.updateWorkflow>) {
return api.updateWorkflow(...args);
export function sanitizeWorkflowSnapshot(
detail: import("./types.js").WorkflowDetail
): import("./types.js").WorkflowDetail {
const cloned = JSON.parse(JSON.stringify(detail)) as import("./types.js").WorkflowDetail;
if (Array.isArray(cloned.$snapshot)) {
cloned.$snapshot = cloned.$snapshot.map((entry) => {
if (typeof entry.value === "string" && entry.value.includes("docs.ekuaibao.com")) {
return {
...entry,
value: entry.value.replaceAll("docs.ekuaibao.com", "app.ekuaibao.com"),
};
}
return entry;
});
}
return cloned;
}
export function updateWorkflow(
client: KyInstance,
workflow: import("./types.js").WorkflowDetail
) {
const sanitized = sanitizeWorkflowSnapshot(workflow);
return api.updateWorkflow(client, sanitized);
}
export async function copyWorkflow(
+1 -1
View File
@@ -411,7 +411,7 @@ export const WorkflowTaskExecutionSchema = z
currentLoopPath: z.string().nullable().optional(),
error: WorkflowExecutionErrorSchema.nullable().optional(),
output: z.any().optional(),
form: z.record(z.string(), z.any()).nullable().optional(),
form: z.union([z.record(z.string(), z.any()), z.array(z.any())]).nullable().optional(),
details: z.record(z.string(), z.any()).nullable().optional(),
executionLogs: z.array(z.any()).optional(),
})
@@ -13,6 +13,7 @@ hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
hose-use workflow diff-job <jobId1> <jobId2> [--json]
hose-use workflow webhook send <pipelineId> [--bill=<单号>] [--body='{...}'] [--dry-run|--yes]
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
hose-use workflow debug <pipelineId> --flow=<单号> --yes
hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flowform] [--file=<JSON模板>] [--dry-run|--yes]
@@ -151,3 +152,10 @@ hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
公式诊断仅对完整公式表达式且具有明确数值/日期字段类型的映射执行硬阻断;类型未知降为软建议,明确文本类型及备注中的公式样式词语不构成阻断。
节点删除命令始终保护工作流首个触发器,包括仅包含触发器的新建草稿;移除普通动作节点不受影响。触发器结构变更仍通过完整草稿保存或设计器进行。
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断,防止运行时直接返回 403 Forbidden;
3. **前端富文本 `$snapshot` 自动清洗**:在 SDK `updateWorkflow` 时,自动递归遍历 `$snapshot` 字典并将陈旧的 `docs.ekuaibao.com` 替换为 `app.ekuaibao.com`,避免 Web 控制台用户重新点开节点保存时产生配置倒退;
4. **Webhook 样本注入 (`workflow webhook send`)**:支持向工作流专属 Webhook 地址直接模拟打桩发送 JSON 报文或关联单据真实载荷,彻底解决新建/复制工作流后 Web 界面“获取更多数据样本”等待卡死的问题。
@@ -313,6 +313,15 @@ function checkMisplacedFormulasInDatalink(
}
}
const WELL_KNOWN_POWER_CODES: Record<string, string> = {
ticket_audit_switch: "单据审批 (TICKET_AUDIT_switch)",
staff_sync_switch: "通讯录同步 (STAFF_SYNC_switch)",
payment_switch: "资金付款 (PAYMENT_switch)",
invoice_switch: "发票管理 (INVOICE_switch)",
budget_switch: "预算管控 (BUDGET_switch)",
contract_switch: "合同管理 (CONTRACT_switch)",
};
export function analyzeWorkflow(
detail: WorkflowDetail,
options: AnalyzeWorkflowOptions = {}
@@ -330,6 +339,15 @@ export function analyzeWorkflow(
)
: undefined;
const openedPowerCodeSet: Set<string> | undefined = options.openedPowerCodes
? new Set(
(Array.isArray(options.openedPowerCodes)
? options.openedPowerCodes
: Array.from(options.openedPowerCodes)
).map((p) => p.trim().toLowerCase())
)
: undefined;
if (detail.state === 0) {
addDiagnostic(diagnostics, {
severity: "warning",
@@ -566,21 +584,63 @@ export function analyzeWorkflow(
}
}
// 诊断 6: HTTP 自动审批节点 URL 与中括号校验 (MISSING_BACKLOG_DATA_BRACKETS)
// 诊断 6: HTTP 节点域名、中括号与功能权限校验
if (task.type === "http") {
const url = String((task as Record<string, unknown>).url || "");
// 6.1 拦截文档站点域名 docs.ekuaibao.com (DOCS_DOMAIN_USED)
if (url.includes("docs.ekuaibao.com")) {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "DOCS_DOMAIN_USED",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 的 URL 错误配置了开放平台文档站点域名 (docs.ekuaibao.com)。合思生产 API 网关域名为 app.ekuaibao.com,请求发往文档站点会导致 404/DNS 错误。请将 URL 修正为以 https://app.ekuaibao.com 开头的标准接口地址。`,
});
}
// 6.2 审批节点路径参数缺少中括号 (MISSING_BACKLOG_DATA_BRACKETS)
if (url.includes("api/openapi/v1/backlog/data")) {
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
const segment = match ? match[1] : "";
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
addDiagnostic(diagnostics, {
severity: "warning",
category: "soft_advice",
code: "MISSING_BACKLOG_DATA_BRACKETS",
path,
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
});
}
}
// 6.3 权限代码 (powerCode) 开通状态校验 (UNLICENSED_POWER_CODE / POWER_CODE_DEPENDENCY)
const powerCodeMatch = url.match(/[?&]powerCode=([^&#]+)/);
if (powerCodeMatch) {
const powerCode = decodeURIComponent(powerCodeMatch[1]);
const powerCodeKey = powerCode.trim().toLowerCase();
const appName = WELL_KNOWN_POWER_CODES[powerCodeKey] || `权限代码 [${powerCode}] 对应的应用`;
if (openedPowerCodeSet !== undefined) {
if (!openedPowerCodeSet.has(powerCodeKey)) {
addDiagnostic(diagnostics, {
severity: "error",
category: "hard_block",
code: "UNLICENSED_POWER_CODE",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}',但当前企业尚未开通对应功能/应用(如 ${appName})。运行时合思开放平台网关将直接返回 403 Forbidden(未开通功能,无权访问)。请先在开放平台/应用商城中开通该应用,或更换为已开通的等价接口。`,
});
}
} else {
addDiagnostic(diagnostics, {
severity: "warning",
category: "soft_advice",
code: "POWER_CODE_DEPENDENCY",
path,
message: `HTTP 任务 [${task.label || task.name}] (${task.name}) 携带了权限代码 'powerCode=${powerCode}'。调用此接口要求企业已开通 [${appName}],否则运行时将返回 403 Forbidden。`,
});
}
}
}
visit(task.tasks || [], path, insideEvery || task.type === "every");
@@ -263,5 +263,103 @@ describe("Workflow static analysis", () => {
expect(emptyBranch?.category).toBe("soft_advice");
expect(emptyBranch?.severity).toBe("warning");
});
it("detects DOCS_DOMAIN_USED as a hard block when docs.ekuaibao.com is used in HTTP tasks", () => {
const wf = {
id: "wf-docs-domain",
label: "测试域名诊断",
state: 1,
version: "1",
tasks: [
{
name: "action_approve_wrong",
type: "http",
label: "审批节点",
url: "https://docs.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]",
},
],
};
const result = analyzeWorkflow(wf as any);
const diag = result.diagnostics.find((d) => d.code === "DOCS_DOMAIN_USED");
expect(diag).toBeDefined();
expect(diag?.category).toBe("hard_block");
expect(diag?.severity).toBe("error");
expect(diag?.message).toContain("docs.ekuaibao.com");
expect(diag?.message).toContain("app.ekuaibao.com");
expect(result.summary.hardBlocks).toBeGreaterThanOrEqual(1);
expect(result.summary.passed).toBe(false);
});
it("detects UNLICENSED_POWER_CODE when enterprise has not opened powerCode application", () => {
const wf = {
id: "wf-power-code",
label: "测试权限诊断",
state: 1,
version: "1",
tasks: [
{
name: "action_audit",
type: "http",
label: "调用单据审批",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=TICKET_AUDIT_switch",
},
],
};
// openedPowerCodes does NOT include ticket_audit_switch
const result = analyzeWorkflow(wf 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?.message).toContain("TICKET_AUDIT_switch");
expect(diag?.message).toContain("403 Forbidden");
expect(result.summary.passed).toBe(false);
});
it("passes UNLICENSED_POWER_CODE when enterprise has opened powerCode application", () => {
const wf = {
id: "wf-power-code-ok",
label: "已开通应用流程",
state: 1,
version: "1",
tasks: [
{
name: "action_audit",
type: "http",
label: "调用单据审批",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=TICKET_AUDIT_switch",
},
],
};
const result = analyzeWorkflow(wf as any, {
openedPowerCodes: ["ticket_audit_switch"],
});
const hardBlock = result.diagnostics.find((d) => d.code === "UNLICENSED_POWER_CODE");
expect(hardBlock).toBeUndefined();
});
it("provides POWER_CODE_DEPENDENCY soft advice when openedPowerCodes is not provided", () => {
const wf = {
id: "wf-power-code-offline",
label: "离线分析流程",
state: 1,
version: "1",
tasks: [
{
name: "action_audit",
type: "http",
label: "调用单据审批",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=TICKET_AUDIT_switch",
},
],
};
const result = analyzeWorkflow(wf as any);
const diag = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
expect(diag).toBeDefined();
expect(diag?.category).toBe("soft_advice");
expect(diag?.severity).toBe("warning");
});
});
@@ -59,4 +59,5 @@ export interface WorkflowFormSpecLike {
export interface AnalyzeWorkflowOptions {
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
availableNodeTypes?: Set<string> | string[];
openedPowerCodes?: Set<string> | string[];
}
@@ -20,13 +20,14 @@ import {
listWorkflowSnapshots,
listWorkflowLogs,
toggleWorkflow,
updateWorkflow,
} from "../../api.js";
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
isTaskExecutionFailed,
updateWorkflow,
sanitizeWorkflowSnapshot,
} from "../../services.js";
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
import { WorkflowAlertStore } from "../alert/index.js";
@@ -77,6 +78,28 @@ describe("workflow draft state machine", () => {
expect(result["$snapshot"]).toEqual([{ key: "tasks.0", value: "{}" }]);
});
it("automatically purges docs.ekuaibao.com domain from $snapshot during update", async () => {
let sentWorkflow: WorkflowDetail | undefined;
const client = {
put: async (url: string, options: { json: WorkflowDetail }) => {
sentWorkflow = options.json;
return { json: async () => ({ data: options.json }) };
},
} as any;
const input = workflow({
"$snapshot": [
{
key: "tasks.0",
value: JSON.stringify({ url: "https://docs.ekuaibao.com/api/openapi/v1/backlog" }),
},
],
});
const result = await updateWorkflow(client, input);
expect(sentWorkflow?.$snapshot?.[0].value).toContain("https://app.ekuaibao.com/api/openapi/v1/backlog");
expect(sentWorkflow?.$snapshot?.[0].value).not.toContain("docs.ekuaibao.com");
expect(result["$snapshot"]?.[0].value).toContain("app.ekuaibao.com");
});
it("reads snapshot history and accepts the web API's serialized inputs", async () => {
let request: { url: string; options: any } | undefined;
const client = {