Files
hose-use/src/cli/commands/config.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

303 lines
12 KiB
TypeScript

import { resolve } from "node:path";
import {
loadGlobalConfig,
saveGlobalConfig,
resolveGlobalConfigFile,
resolveEnterprisesDirs,
resolveWritableEnterprisesDir,
getEnterprisesDirCandidates,
} from "../../core/config/loader.js";
import { booleanOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleConfigCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const action = parsed.action || "paths";
switch (action) {
case "paths":
case "path":
case "dirs":
case "show":
case "list":
return handlePaths(parsed, runtime);
case "get":
case "status":
case "info":
return handleShow(parsed, runtime);
case "mode":
return handleMode(parsed, runtime);
case "test-dir":
case "test-enterprises-dir":
return handleTestDir(parsed, runtime);
case "set":
return handleSet(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 config 子命令: ${action}。支持: paths, show, get, mode <stateful|stateless>, test-dir <path|--clear>, set <key> <val>\n`,
exitCode: 1,
};
}
}
async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const globalConfig = loadGlobalConfig();
const currentCorp = runtime.selectedCorp;
const configPath = resolveGlobalConfigFile();
const summaryObj = {
mode: globalConfig.stateful ? "stateful" : "stateless",
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId || null,
defaultAccountId: globalConfig.defaultAccountId || null,
testEnterprisesDir: globalConfig.testEnterprisesDir || null,
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
updateRepo: globalConfig.updateRepo || null,
updateSource: globalConfig.updateSource || "auto",
configFile: configPath,
};
if (runtime.jsonMode) {
return { stdout: printJson(summaryObj), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
"测试企业目录": 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 choose 形态: hose-use config set chooseSerialization <frontend|pure>\n`,
stderr: "",
exitCode: 0,
};
}
async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const targetMode = parsed.args[0]?.toLowerCase();
if (!targetMode || (targetMode !== "stateful" && targetMode !== "stateless")) {
return {
stdout: "",
stderr: "用法: hose-use config mode <stateful|stateless>\n",
exitCode: 1,
};
}
const isStateful = targetMode === "stateful";
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "切换全局运行模式", targetMode, { stateful: isStateful });
}
requireMutationConfirmation(parsed, runtime, "切换全局运行模式", `hose-use config mode ${targetMode} --yes`);
const updated = saveGlobalConfig({ stateful: isStateful });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
}
return {
stdout: `[SUCCESS] 全局运行模式已切换为: ${isStateful ? "有状态模式 (Stateful)" : "无状态模式 (Stateless)"}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleTestDir(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const isClear = booleanOption(parsed.options, ["clear"]) || parsed.args[0] === "--clear" || parsed.args[0] === "clear";
const globalConfig = loadGlobalConfig();
if (isClear) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "清除测试企业目录配置", globalConfig.testEnterprisesDir || "当前未设置", { testEnterprisesDir: null });
}
requireMutationConfirmation(parsed, runtime, "清除测试企业目录配置", "hose-use config test-dir --clear --yes");
const updated = saveGlobalConfig({ testEnterprisesDir: undefined });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
}
return {
stdout: "[SUCCESS] 已清除测试企业目录配置,恢复默认全局目录。\n",
stderr: "",
exitCode: 0,
};
}
const dirArg = parsed.args[0];
if (!dirArg) {
const info = {
testEnterprisesDir: globalConfig.testEnterprisesDir || null,
configFile: resolveGlobalConfigFile(),
};
if (runtime.jsonMode) {
return { stdout: printJson(info), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前测试企业目录": globalConfig.testEnterprisesDir || "未配置 (当前只读全局企业目录)",
"全局配置文件路径": resolveGlobalConfigFile(),
});
return {
stdout: `====== 测试企业目录配置 ======\n${output}\n\n提示:\n 设置测试目录: hose-use config test-dir <path>\n 清除测试目录: hose-use config test-dir --clear\n`,
stderr: "",
exitCode: 0,
};
}
const resolved = resolve(dirArg);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "设置测试企业目录", resolved, { testEnterprisesDir: resolved });
}
requireMutationConfirmation(parsed, runtime, "设置测试企业目录", `hose-use config test-dir ${dirArg} --yes`);
const updated = saveGlobalConfig({ testEnterprisesDir: resolved });
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
}
return {
stdout: `[SUCCESS] 测试企业目录已设置为: ${resolved}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const rawKey = parsed.args[0];
const val = parsed.args[1];
if (!rawKey || val === undefined) {
return {
stdout: "",
stderr: "用法: hose-use config set <key> <val> (如 hose-use config set defaultCorpId uzU7pcWfScck00)\n",
exitCode: 1,
};
}
const keyLower = rawKey.toLowerCase();
const partial: Record<string, unknown> = {};
let resolvedKey = rawKey;
if (keyLower === "stateful") {
resolvedKey = "stateful";
partial.stateful = val === "true" || val === "1";
} else if (keyLower === "defaultcorpid") {
resolvedKey = "defaultCorpId";
partial.defaultCorpId = val;
} else if (keyLower === "defaultaccountid") {
resolvedKey = "defaultAccountId";
partial.defaultAccountId = val;
} else if (keyLower === "testenterprisesdir" || keyLower === "testdir") {
resolvedKey = "testEnterprisesDir";
if (val === "clear" || val === "none" || val === "" || val === "null") {
partial.testEnterprisesDir = undefined;
} else {
partial.testEnterprisesDir = resolve(val);
}
} else if (keyLower === "updaterepo") {
resolvedKey = "updateRepo";
partial.updateRepo = val;
} else if (keyLower === "updatesource") {
resolvedKey = "updateSource";
const srcLower = val.toLowerCase();
if (srcLower !== "auto" && srcLower !== "github" && srcLower !== "gitea") {
return {
stdout: "",
stderr: `不支持的 updateSource 值: ${val}。可选: auto, github, gitea\n`,
exitCode: 1,
};
}
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, chooseSerialization\n`,
exitCode: 1,
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "更新全局配置", resolvedKey, partial);
}
requireMutationConfirmation(parsed, runtime, "更新全局配置", `hose-use config set ${rawKey} ${val} --yes`);
const updated = saveGlobalConfig(partial);
if (runtime.jsonMode) {
return { stdout: printJson(updated), stderr: "", exitCode: 0 };
}
return {
stdout: `[SUCCESS] 配置已更新: ${resolvedKey} = ${val}\n`,
stderr: "",
exitCode: 0,
};
}
async function handlePaths(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const envDir = process.env.HOSE_ENTERPRISES_DIR;
const envUserDir = process.env.HOSE_USER_ENTERPRISES_DIR;
const envConfigFile = process.env.HOSE_CONFIG_FILE;
const existingDirs = resolveEnterprisesDirs();
const writableDir = resolveWritableEnterprisesDir();
const configFile = resolveGlobalConfigFile();
const candidates = getEnterprisesDirCandidates();
const globalConfig = loadGlobalConfig();
const currentCorp = runtime.selectedCorp;
const data = {
configFile,
writableDir,
existingDirs,
mode: globalConfig.stateful ? "stateful" : "stateless",
stateful: globalConfig.stateful,
defaultCorpId: globalConfig.defaultCorpId || null,
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
env: {
HOSE_ENTERPRISES_DIR: envDir || null,
HOSE_USER_ENTERPRISES_DIR: envUserDir || null,
HOSE_CONFIG_FILE: envConfigFile || null,
},
candidates,
};
if (runtime.jsonMode) {
return { stdout: printJson(data, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const output = printKeyValue({
"当前生效配置文件": configFile,
"凭证保存写入目录": writableDir,
"已发现企业目录": existingDirs.length ? existingDirs.join("\n ") : "无 (未发现任何有效企业目录)",
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
"环境变量指定目录": envDir || "未设置 (HOSE_ENTERPRISES_DIR)",
"全部目录候选链": candidates.join("\n "),
});
return {
stdout: `====== 配置路径诊断 (Config Paths) ======\n${output}\n`,
stderr: "",
exitCode: 0,
};
}