Merge pull request #117 from yunyingk/feat/corp-env-flag

feat(corps): 企业配置增加环境属性与生产安全保护机制
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-16 12:46:00 +08:00
commit 627e17e0f2
15 files changed
+775 -28

No files matched your search

+1
View File
@@ -10,6 +10,7 @@
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
- `service.ts`:常驻守护进程管理(安装/启停/状态)。
- `help.ts`:帮助文本组织。
+11 -3
View File
@@ -8,7 +8,7 @@ import {
} from "../../core/config/loader.js";
import { ApprovalRepository } from "../../domains/approval/index.js";
import { VERSION } from "../../version.js";
import { formatExpiresAt, formatSourceLabel, printJson } from "../printer.js";
import { formatExpiresAt, formatSourceLabel, formatCorpEnvLabel, printJson } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleContextCommand(
@@ -75,6 +75,8 @@ export async function handleContextCommand(
? {
id: currentCorp.id,
name: currentCorp.name,
env: currentCorp.env,
isTest: currentCorp.isTest,
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
source: currentCorp.source,
@@ -93,6 +95,9 @@ export async function handleContextCommand(
total: allCorps.length,
validCount: validCorps.length,
expiredCount: expiredCorps.length,
prodCount: allCorps.filter((c) => c.env === "prod").length,
testCount: allCorps.filter((c) => c.env === "test").length,
demoCount: allCorps.filter((c) => c.env === "demo").length,
activeCorpId: currentCorp?.id || null,
},
aiProGateway: {
@@ -122,6 +127,9 @@ export async function handleContextCommand(
const corpStaffId = currentCorp?.credentials?.staffId || currentCorp?.staffId || "-";
const corpStaffName = currentCorp?.staffName || currentCorp?.session?.staffName || "-";
const corpExpiresAt = currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime;
const prodCount = allCorps.filter((c) => c.env === "prod").length;
const testCount = allCorps.filter((c) => c.env === "test").length;
const demoCount = allCorps.filter((c) => c.env === "demo").length;
const scopesStr =
scopes.length > 0
@@ -131,13 +139,13 @@ export async function handleContextCommand(
const lines = [
`====== 全局运行上下文与身份诊断 (hose-use v${VERSION}) ======`,
` 当前活跃账号 : ${accountStr}${userIdStr}`,
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id}) [${formatCorpEnvLabel(currentCorp.env)}]` : "⚠️ 未激活任何企业"}`,
` 当前操作员工 : ${corpStaffId}`,
` 员工真实姓名 : ${corpStaffName}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
` 已配置企业总数: ${allCorps.length} 家 (🏭 正式: ${prodCount} 家, 🧪 测试: ${testCount} 家, 🎪 演示: ${demoCount} 家)`,
` AI PRO 规约库 : ${scopesStr}`,
` AI PRO 待决断 : ${pendingRunsCount} 个待决断会话 (当前企业历史总会话: ${totalRunsCount} 个)`,
` 运行模式设置 : ${isStateful ? "有状态模式 (Stateful - 自动记忆当前企业)" : "无状态模式 (Stateless)"}`,
+199
View File
@@ -0,0 +1,199 @@
import { describe, expect, it } from "bun:test";
import { handleCorpsCommand } from "./corps/index.js";
import { handleContextCommand } from "./context.js";
import { CorpContext } from "../../core/config/manager.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { CliRuntime } from "../types.js";
const sampleCorps: CorpConfig[] = [
{
id: "corp_prod",
name: "新转转集团",
env: "prod",
isTest: false,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: { corpId: "corp_prod", staffId: "staff_1", accessToken: "t1" },
},
{
id: "corp_test",
name: "HAB对公测试环境",
env: "test",
isTest: true,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: { corpId: "corp_test", staffId: "staff_2", accessToken: "t2" },
},
{
id: "corp_demo",
name: "营销中心演示企业",
env: "demo",
isTest: true,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: { corpId: "corp_demo", staffId: "staff_3", accessToken: "t3" },
},
];
function createMockRuntime(corps: CorpConfig[] = sampleCorps): CliRuntime {
const context = new CorpContext(corps, { stateful: true, defaultCorpId: "corp_prod" });
return {
corpContext: context,
selectedCorp: context.getCurrent()!,
jsonMode: false,
outputOptions: {},
};
}
describe("CLI - corps environment attributes & filtering", () => {
it("corps list displays environment column with emoji labels", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "list",
args: [],
options: {},
raw: ["corps", "list"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("环境");
expect(res.stdout).toContain("🏭 正式");
expect(res.stdout).toContain("🧪 测试");
expect(res.stdout).toContain("🎪 演示");
expect(res.stdout).toContain("共 3 家企业 (🏭 正式 1 家, 🧪 测试 1 家, 🎪 演示 1 家)");
});
it("corps list --test filters only test and demo enterprises", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "list",
args: [],
options: { test: true },
raw: ["corps", "list", "--test"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("HAB对公测试环境");
expect(res.stdout).toContain("营销中心演示企业");
expect(res.stdout).not.toContain("新转转集团");
expect(res.stdout).toContain("已筛选显示 2 家");
});
it("corps list --prod filters only production enterprises", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "list",
args: [],
options: { prod: true },
raw: ["corps", "list", "--prod"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("新转转集团");
expect(res.stdout).not.toContain("HAB对公测试环境");
expect(res.stdout).not.toContain("营销中心演示企业");
expect(res.stdout).toContain("已筛选显示 1 家");
});
it("corps list --env=demo filters precisely demo enterprises", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "list",
args: [],
options: { env: "demo" },
raw: ["corps", "list", "--env=demo"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("营销中心演示企业");
expect(res.stdout).not.toContain("新转转集团");
expect(res.stdout).not.toContain("HAB对公测试环境");
});
it("corps tag requires mutation confirmation unless confirmed or dry-run", async () => {
const runtime = createMockRuntime();
await expect(
handleCorpsCommand(
{
area: "corps",
action: "tag",
args: ["corp_prod"],
options: { test: true },
raw: ["corps", "tag", "corp_prod", "--test"],
},
runtime
)
).rejects.toThrow("拒绝执行设置企业环境属性");
});
it("corps tag previews change under --dry-run", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "tag",
args: ["corp_prod"],
options: { test: true, "dry-run": true },
raw: ["corps", "tag", "corp_prod", "--test", "--dry-run"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("[DRY-RUN]");
expect(res.stdout).toContain("设置企业环境属性");
expect(res.stdout).toContain("newEnv: test");
});
it("corps current displays environment attribute label", async () => {
const runtime = createMockRuntime();
const res = await handleCorpsCommand(
{
area: "corps",
action: "current",
args: [],
options: {},
raw: ["corps", "current"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("环境属性");
expect(res.stdout).toContain("🏭 正式");
});
it("context command reports environment counts and current corp env tag", async () => {
const runtime = createMockRuntime();
const res = await handleContextCommand(
{
area: "context",
action: "",
args: [],
options: {},
raw: ["context"],
},
runtime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("新转转集团 (corp_prod) [🏭 正式]");
expect(res.stdout).toContain("🏭 正式: 1 家, 🧪 测试: 1 家, 🎪 演示: 1 家");
});
});
+4 -2
View File
@@ -1,6 +1,6 @@
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../../core/auth/login.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../../printer.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt, formatCorpEnvLabel } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
@@ -28,8 +28,9 @@ export async function handleSwitch(parsed: CliParsedArgs, runtime: CliRuntime):
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const envLabel = formatCorpEnvLabel(current?.env);
return {
stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id})\n`,
stdout: `[SUCCESS] 已切换到企业: ${current?.name} (${current?.id}) [${envLabel}]\n`,
stderr: "",
exitCode: 0,
};
@@ -51,6 +52,7 @@ export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime):
const pairs: Record<string, unknown> = {
"企业 ID": current.id,
"企业名称": current.name,
"环境属性": formatCorpEnvLabel(current.env),
"员工工号": current.credentials.staffId,
"员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
+18 -11
View File
@@ -5,11 +5,13 @@ import { handleSwitch, handleCurrent } from "./context.js";
import { handleGenerateCorpLink, handleAddLink } from "./link.js";
import { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
import { handleProbeHose, handleHoseStaffs } from "./probe.js";
import { handleTagCorp } from "./tag.js";
import { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
// 供 auth.ts 等跨命令复用的 handler 与 helper 维持原有命名导出。
export { handleGenerateCorpLink } from "./link.js";
export { handleAddPersistent, handleExtractKeys, handleElevateCorp, handleSyncFromSeal } from "./credentials.js";
export { handleTagCorp } from "./tag.js";
export { isHttpUrl, resolveTargetCorpByArgOrContext } from "./shared.js";
export async function handleCorpsCommand(
@@ -27,6 +29,10 @@ export async function handleCorpsCommand(
case "query":
case "filter":
return handleSearch(parsed, runtime);
case "tag":
case "set-env":
case "mark":
return handleTagCorp(parsed, runtime);
case "switch":
case "use":
return handleSwitch(parsed, runtime);
@@ -75,7 +81,7 @@ export async function handleCorpsCommand(
default:
return {
stdout: "",
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
stderr: `未知 corps 子命令: ${action}。支持: list, search, tag, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
exitCode: 1,
};
}
@@ -87,8 +93,9 @@ export function printCorpsHelp(): string {
hose-use corps <子命令> [参数] [选项]
子命令:
list 列出本地已保存的所有企业配置 (别名: ls)
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
list 列出本地已保存的所有企业配置 (支持 --test, --prod, --demo, --env 筛选,别名: ls)
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId, env,别名: find)
tag [企业ID] 标记企业环境属性 (--test / --prod / --demo / --env=<env>) 或 --migrate-all 批量升级持久化 (别名: set-env)
switch <企业ID> 切换当前激活的工作企业 (别名: use)
current 查看当前激活的企业配置与凭证详情
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
@@ -101,19 +108,19 @@ export function printCorpsHelp(): string {
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
选项:
--test 筛选测试环境企业 (corps list)
--prod 筛选正式生产企业 (corps list)
--demo 筛选演示/POC企业 (corps list)
--json, -j 以 JSON 格式输出
--help, -h 查看帮助信息
示例:
hose-use corps list
hose-use corps search 某企业
hose-use corps search 17718556446
hose-use corps switch ID01MCcOgJl1td
hose-use corps link 新转转集团
hose-use corps link 新转转集团 --staff="合思-姜尧"
hose-use corps link 新转转集团 --staff="17865187018" --persist
hose-use corps add-link "<url>" --elevate --yes
hose-use corps add-persistent --app-key=... --app-security=... --yes
hose-use corps list --test
hose-use corps list --prod
hose-use corps tag ID01uzxB4x07fh --test --yes
hose-use corps tag ID01PH4Q5CJboX --prod --yes
hose-use corps tag --migrate-all --yes
`.trim();
}
+63 -9
View File
@@ -1,6 +1,7 @@
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
import { stringOption } from "../../parser.js";
import { printJson, printTable, formatExpiresAt, formatSourceLabel } from "../../printer.js";
import { getCorpEnv, isCorpTest } from "../../../core/config/types.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printTable, formatExpiresAt, formatSourceLabel, formatCorpEnvLabel } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
const FIELD_LABEL_MAP: Record<string, string> = {
@@ -10,6 +11,7 @@ const FIELD_LABEL_MAP: Record<string, string> = {
staffId: "员工工号",
staffName: "员工姓名",
accountId: "所属账号",
env: "环境属性",
};
export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
@@ -35,6 +37,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
(c.credentials?.appKey || c.auth?.appKey) &&
(c.credentials?.appSecurity || c.auth?.appSecurity)
);
const env = getCorpEnv(c);
const test = isCorpTest(c);
return {
id: c.id,
name: c.name,
@@ -48,6 +52,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
persistent: canRefreshCorpAccessToken(c),
hasOpenApi,
env,
isTest: test,
};
})
: runtime.corpContext.listCorps().map((c) => ({
@@ -63,6 +69,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
expiresAt: c.expiresAt,
persistent: c.persistent,
hasOpenApi: c.hasOpenApi,
env: c.env || (c.isTest ? "test" : "prod"),
isTest: c.isTest ?? (c.env !== "prod"),
}));
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
@@ -88,6 +96,9 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
if (corp.accountId && corp.accountId.toLowerCase().includes(kw)) {
matchedFields.push("accountId");
}
if (corp.env && (corp.env.toLowerCase() === kw || (kw === "正式" && corp.env === "prod") || (kw === "测试" && corp.env === "test") || (kw === "演示" && corp.env === "demo"))) {
matchedFields.push("env");
}
if (matchedFields.length > 0) {
matches.push({ ...corp, matchedFields });
@@ -105,6 +116,8 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
id: m.id,
name: m.name,
corpId: m.corpId,
env: m.env,
isTest: m.isTest,
staffId: m.staffId,
staffName: m.staffName || undefined,
accountId: m.accountId || undefined,
@@ -136,6 +149,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
const matchLabels = m.matchedFields.map((f) => FIELD_LABEL_MAP[f] || f);
return [
isCurrent ? `* ${i + 1}` : ` ${i + 1}`,
formatCorpEnvLabel(m.env),
m.matchedFields.includes("id") || m.matchedFields.includes("corpId") ? `[${m.id}]` : m.id,
m.matchedFields.includes("name") ? `[${m.name}]` : m.name,
m.matchedFields.includes("staffId") ? `[${m.staffId}]` : m.staffId,
@@ -147,7 +161,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
});
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
["#", "环境", "企业 ID", "企业名称", "员工工号", "员工姓名", "所属账号", "匹配项", "Token 过期时间"],
rows
);
@@ -159,14 +173,41 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
}
export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const corps = runtime.corpContext.listCorps();
const allCorps = runtime.corpContext.listCorps();
const filterTest = booleanOption(parsed.options, ["test", "t"]);
const filterProd = booleanOption(parsed.options, ["prod", "production", "p"]);
const filterDemo = booleanOption(parsed.options, ["demo"]);
const filterEnv = stringOption(parsed.options, ["env", "e"])?.toLowerCase();
let filteredCorps = allCorps;
if (filterTest) {
filteredCorps = filteredCorps.filter((c) => c.isTest || c.env === "test" || c.env === "demo");
} else if (filterProd) {
filteredCorps = filteredCorps.filter((c) => c.env === "prod");
} else if (filterDemo) {
filteredCorps = filteredCorps.filter((c) => c.env === "demo");
} else if (filterEnv) {
filteredCorps = filteredCorps.filter((c) => c.env === filterEnv);
}
const prodCount = allCorps.filter((c) => c.env === "prod").length;
const testCount = allCorps.filter((c) => c.env === "test").length;
const demoCount = allCorps.filter((c) => c.env === "demo").length;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
activeCorpId: runtime.selectedCorp?.id,
corporations: corps,
total: allCorps.length,
count: filteredCorps.length,
summary: {
prodCount,
testCount,
demoCount,
},
corporations: filteredCorps,
},
runtime.outputOptions
),
@@ -175,12 +216,21 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
};
}
if (corps.length === 0) {
if (allCorps.length === 0) {
return { stdout: "未找到任何企业配置,请先运行 hose-use auth login\n", stderr: "", exitCode: 0 };
}
const rows = corps.map((c, i) => [
if (filteredCorps.length === 0) {
return {
stdout: `没有找到符合筛选条件的企业 (总计 ${allCorps.length} 家: 🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)\n`,
stderr: "",
exitCode: 0,
};
}
const rows = filteredCorps.map((c, i) => [
c.current ? `* ${i + 1}` : ` ${i + 1}`,
formatCorpEnvLabel(c.env),
c.id,
c.name,
c.staffId,
@@ -190,12 +240,16 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
]);
const table = printTable(
["#", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
["#", "环境", "企业 ID", "企业名称", "员工工号", "来源", "Token 过期时间", "所属账号"],
rows
);
const filterHint = (filteredCorps.length !== allCorps.length)
? `已筛选显示 ${filteredCorps.length} 家 (总计 ${allCorps.length} 家: 🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)`
: `共 ${allCorps.length} 家企业 (🏭 正式 ${prodCount} 家, 🧪 测试 ${testCount} 家, 🎪 演示 ${demoCount} 家)`;
return {
stdout: `====== 已配置企业列表 (${corps.length} 家) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
stdout: `====== 已配置企业列表 (${filterHint}) ======\n${table}\n\n提示:\n - 标记 * 为当前激活企业(同时作为 hose-use 与 hose-aipro 的统一默认执行上下文)\n - 支持筛选: --test (仅测试/演示), --prod (仅正式生产), --env=<prod|test|demo>\n - 使用 hose-use corps switch <企业ID> 切换工作企业\n`,
stderr: "",
exitCode: 0,
};
+216
View File
@@ -0,0 +1,216 @@
import { saveCorpConfig } from "../../../core/config/loader.js";
import { CorpEnv, getCorpEnv } from "../../../core/config/types.js";
import { booleanOption, stringOption } from "../../parser.js";
import { formatCorpEnvLabel, printJson, printKeyValue, printTable } from "../../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
export async function handleTagCorp(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const isMigrateAll = booleanOption(parsed.options, ["migrate-all", "all", "upgrade-all", "a"]);
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
? runtime.corpContext.getAllCorps()
: [];
if (isMigrateAll) {
if (allCorps.length === 0) {
return { stdout: "未找到任何企业配置可供迁移升级。\n", stderr: "", exitCode: 0 };
}
const previewList = allCorps.map((corp) => {
const deducedEnv = getCorpEnv(corp);
return {
id: corp.id,
name: corp.name,
currentEnv: corp.env || "(未显式声明)",
targetEnv: deducedEnv,
targetIsTest: deducedEnv !== "prod",
};
});
if (isDryRun(parsed, runtime)) {
return mutationPreview(
parsed,
runtime,
"批量显式持久化升级所有企业环境属性",
`共 ${allCorps.length} 家企业`,
{
total: allCorps.length,
preview: previewList,
}
);
}
requireMutationConfirmation(
parsed,
runtime,
"批量显式持久化升级所有企业环境属性",
"hose-use corps tag --migrate-all --yes"
);
const savedPaths: string[] = [];
for (const corp of allCorps) {
const targetEnv = getCorpEnv(corp);
const updated = {
...corp,
env: targetEnv,
isTest: targetEnv !== "prod",
};
const filePath = saveCorpConfig(updated);
savedPaths.push(filePath);
runtime.corpContext.upsertCorp(updated, corp.id === runtime.selectedCorp?.id);
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
migrated: true,
count: savedPaths.length,
corporations: previewList,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const rows = previewList.map((item, i) => [
i + 1,
formatCorpEnvLabel(item.targetEnv),
item.id,
item.name,
item.targetEnv,
item.targetIsTest ? "是" : "否",
]);
const table = printTable(["#", "环境属性", "企业 ID", "企业名称", "写入环境值", "isTest"], rows);
return {
stdout: `[SUCCESS] 成功完成 ${savedPaths.length} 家企业配置环境属性的显式持久化升级:\n\n${table}\n`,
stderr: "",
exitCode: 0,
};
}
// 单个企业打标
const targetArg = parsed.args[0] || stringOption(parsed.options, ["id", "corp", "corpId"]);
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
if (!targetCorp) {
return {
stdout: "",
stderr: [
"用法:",
" hose-use corps tag <企业ID|名称> [--test | --prod | --demo | --env=<prod|test|demo>] [--yes]",
" hose-use corps tag --migrate-all [--yes] # 一键按名称智能初判持久化升级所有企业配置",
"",
"选项:",
" --test, -t 标记为测试环境 (test)",
" --prod, -p 标记为正式生产环境 (prod)",
" --demo 标记为演示/POC环境 (demo)",
" --env=<env> 显式指定环境属性 (prod / test / demo)",
" --migrate-all 批量智能推导并持久化所有企业配置",
" --dry-run 仅预览变更,不写入磁盘",
" --yes, -y 确认执行写入",
].join("\n") + "\n",
exitCode: 1,
};
}
const optTest = booleanOption(parsed.options, ["test", "t"]);
const optProd = booleanOption(parsed.options, ["prod", "production", "p"]);
const optDemo = booleanOption(parsed.options, ["demo"]);
const optEnv = stringOption(parsed.options, ["env", "e"])?.toLowerCase();
let targetEnv: CorpEnv | undefined;
if (optTest) {
targetEnv = "test";
} else if (optProd) {
targetEnv = "prod";
} else if (optDemo) {
targetEnv = "demo";
} else if (optEnv) {
if (["prod", "test", "demo"].includes(optEnv)) {
targetEnv = optEnv as CorpEnv;
} else {
return {
stdout: "",
stderr: `错误: 非法的环境属性 "${optEnv}",仅支持 prod (正式生产), test (测试环境), demo (演示/POC)\n`,
exitCode: 1,
};
}
}
if (!targetEnv) {
return {
stdout: "",
stderr: `请指定要标记的环境属性 (--test, --prod, --demo 或 --env=<prod|test|demo>)。\n例如: hose-use corps tag ${targetCorp.id} --test --yes\n`,
exitCode: 1,
};
}
const changes = {
corpId: targetCorp.id,
name: targetCorp.name,
currentEnv: targetCorp.env,
newEnv: targetEnv,
newIsTest: targetEnv !== "prod",
};
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "设置企业环境属性", `${targetCorp.name} (${targetCorp.id})`, changes);
}
requireMutationConfirmation(
parsed,
runtime,
"设置企业环境属性",
`hose-use corps tag ${targetCorp.id} --env=${targetEnv} --yes`
);
const updatedCorp = {
...targetCorp,
env: targetEnv,
isTest: targetEnv !== "prod",
};
const filePath = saveCorpConfig(updatedCorp);
runtime.corpContext.upsertCorp(updatedCorp, targetCorp.id === runtime.selectedCorp?.id);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: true,
corpId: updatedCorp.id,
name: updatedCorp.name,
env: updatedCorp.env,
isTest: updatedCorp.isTest,
configFile: filePath,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const summary = printKeyValue({
"企业名称": updatedCorp.name,
"企业 ID": updatedCorp.id,
"环境属性": `${formatCorpEnvLabel(updatedCorp.env)} (${updatedCorp.env})`,
"是否测试企业 (isTest)": updatedCorp.isTest ? "是" : "否",
"持久化配置文件": filePath,
});
return {
stdout: `[SUCCESS] 企业环境属性设置成功:\n\n${summary}\n`,
stderr: "",
exitCode: 0,
};
}
+4 -1
View File
@@ -1,7 +1,7 @@
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
import * as api from "../../domains/platform/services.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt, formatCorpEnvLabel } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleProbeCommand(
@@ -24,6 +24,8 @@ export async function handleProbeCommand(
enterprise: {
id: currentCorp.id,
name: currentCorp.name,
env: currentCorp.env,
isTest: currentCorp.isTest,
staffId: currentCorp.credentials.staffId,
baseUrl: currentCorp.baseUrl,
source: currentCorp.source,
@@ -102,6 +104,7 @@ export async function handleProbeCommand(
const probePairs: Record<string, unknown> = {
"企业名称": currentCorp.name,
"企业 ID": currentCorp.id,
"环境属性": formatCorpEnvLabel(currentCorp.env),
"员工工号": currentCorp.credentials.staffId,
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
"凭证来源": formatSourceLabel(currentCorp.source, hasOpenApi),
+20 -1
View File
@@ -5,7 +5,10 @@ import * as services from "../../domains/platform/services.js";
import type { CliParsedArgs, CliRuntime } from "../types.js";
import type { WorkflowTestReport } from "../../domains/platform/types.js";
const runtime = { selectedCorp: { id: "mock-corp" }, jsonMode: true } as CliRuntime;
const runtime = {
selectedCorp: { id: "mock-corp", name: "Mock测试企业", env: "test", isTest: true } as any,
jsonMode: true,
} as CliRuntime;
const args = (options: Record<string, string | boolean> = {}): CliParsedArgs => ({ area: "workflow", action: "test", args: ["pipe"], options: { flow: "ID01-record", ...options }, raw: ["workflow", "test", "pipe", "--flow=ID01-record"] });
const completed: WorkflowTestReport = { jobId: "job", pipelineId: "pipe", status: "COMPLETED", outcome: "completed", timedOut: false, diagnosticsComplete: true, diagnosticsErrors: [], runType: "DEBUG", targetEntityId: "record", executionTree: [], failedExecutions: [], conditionDiagnoses: [] };
@@ -94,4 +97,20 @@ describe("workflow debug mutation and result contract", () => {
expect(result.stdout).toContain("FAILED");
});
}
it("blocks workflow test without --force when selected corp is production environment", async () => {
const { run } = setup();
const prodRuntime = {
selectedCorp: { id: "prod-corp", name: "生产正式企业", env: "prod", isTest: false },
jsonMode: false,
} as any;
const blocked = await handleWorkflowTest(args({ yes: true }), prodRuntime);
expect(blocked.exitCode).toBe(1);
expect(blocked.stderr).toContain("生产环境安全阻断");
expect(run).not.toHaveBeenCalled();
const allowed = await handleWorkflowTest(args({ yes: true, force: true }), prodRuntime);
expect(allowed.exitCode).toBe(0);
expect(run).toHaveBeenCalledTimes(1);
});
});
+26
View File
@@ -1,4 +1,5 @@
import { existsSync, readFileSync } from "node:fs";
import { isCorpProd } from "../../../core/config/types.js";
import {
classifyWorkflowTrigger,
getWorkflowDebugSource,
@@ -33,6 +34,7 @@ export async function handleWorkflowTest(
"通用选项:",
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
" --auto-publish 是否自动发布测试快照 (默认 false)",
" --force, -f 允许在正式生产环境 (env: prod) 下执行调试",
" --dry-run 只预览,不发起调试",
" --yes/--confirm 确认执行真实工作流节点",
"",
@@ -49,8 +51,13 @@ export async function handleWorkflowTest(
const filePath = stringOption(parsed.options, ["file", "path"]);
const isEmpty = booleanOption(parsed.options, ["empty", "none"]);
const sampleOption = stringOption(parsed.options, ["sample", "sample-id", "sampleId"]);
const forceProd = booleanOption(parsed.options, ["force", "f", "allow-prod", "allow-production"]);
const isProductionCorp = Boolean(runtime.selectedCorp && isCorpProd(runtime.selectedCorp));
const warnings = ["调试会在真实环境执行工作流节点,可能改变业务数据、发送通知并生成快照;auto-publish 还可能发布流程。"];
if (isProductionCorp) {
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
}
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
@@ -314,6 +321,25 @@ export async function handleWorkflowTest(
// 3. 执行端到端调试测试
confirmExecution();
if (isProductionCorp && !forceProd) {
return {
stdout: "",
stderr: [
`🛑 生产环境安全阻断 (Production Safeguard):`,
`当前工作企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 被标记为【🏭 正式生产环境】(env: prod)!`,
`在正式生产企业执行工作流调试可能产生不可逆的单据流转、第三方系统调用与真实业务变更。`,
``,
`如确需在生产环境进行带副作用的真实调试,必须显式附加 --force 参数确认生产风险:`,
` hose-use workflow test ${pipelineId} ${parsed.raw.filter((a) => !["--yes", "-y", "--dry-run"].includes(a)).slice(2).join(" ")} --yes --force`,
``,
`建议切换至测试企业进行调试:`,
` hose-use corps switch <测试企业ID>`,
].join("\n") + "\n",
exitCode: 1,
};
}
const execution = await runWorkflowDebugTest(client, pipelineId, {
flowCodeOrId: targetId,
data: customPayload,
+12
View File
@@ -48,6 +48,18 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
return json;
}
export function formatCorpEnvLabel(env?: string): string {
switch (env) {
case "test":
return "🧪 测试";
case "demo":
return "🎪 演示";
case "prod":
default:
return "🏭 正式";
}
}
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
if (persistentOpenApi || source === "openapi") {
return "企业开放接口 (OpenAPI 密钥)";
+7 -1
View File
@@ -34,10 +34,16 @@ src/core/
├── config/ # 企业配置管理
│ ├── loader.ts # 全局与多企业配置读写(强制 0o600 权限与字段归一化)
│ ├── manager.ts # CorpContext 多企业上下文与身份解析
│ └── types.ts # CorpConfig / GlobalConfig Schema 与统一字段访问器
│ └── types.ts # CorpConfig / GlobalConfig Schema 与统一字段访问器(支持 env 生产/测试/演示环境与智能推导)
└── errors.ts # 统一异常语义(EkbError / NotLoggedInError / AuthenticationError / PermissionError / NotFoundError / ValidationError / BusinessError / EkbApiError)
```
## 企业环境属性与安全兜底 (env & isTest)
- `CorpConfigSchema` 显式扩展 `env: "prod" | "test" | "demo"` 与 `isTest: boolean`
- 智能初判规则(`inferCorpEnvFromName`):企业名称/标识包含“测试”或“test”归为 `test`,包含“演示”/“POC”/“demo”归为 `demo`;**未知企业一律默认且保守归为正式生产环境 `prod`**,绝不允许将生产企业误放行。
- 归一化(`normalizeCorpConfig`):在配置加载与写入时确保 `env` 与 `isTest` 对齐,旧版未标注配置自动平滑升级并持久化。
## 分层约束
- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一
+134
View File
@@ -0,0 +1,134 @@
import { describe, expect, it } from "bun:test";
import {
CorpConfig,
CorpConfigSchema,
getCorpEnv,
inferCorpEnvFromName,
isCorpProd,
isCorpTest,
normalizeCorpConfig,
} from "./types.js";
describe("CorpConfig Environment Attributes & Deduction", () => {
it("inferCorpEnvFromName deduces environment conservatively based on name and id", () => {
// 包含“测试”或“test”
expect(inferCorpEnvFromName("HAB对公测试环境", "ID01uzxB4x07fh")).toBe("test");
expect(inferCorpEnvFromName("Finance Test Corp", "ID_TEST_01")).toBe("test");
expect(inferCorpEnvFromName(undefined, "test-corp-id")).toBe("test");
// 包含“演示”或“POC”或“demo”
expect(inferCorpEnvFromName("合思POC演示企业", "ID01demo")).toBe("demo");
expect(inferCorpEnvFromName("Demo Corporation", "ID01")).toBe("demo");
// 真实生产企业一律保守识别为正式环境 prod
expect(inferCorpEnvFromName("新转转集团", "ID01PH4Q5CJboX")).toBe("prod");
expect(inferCorpEnvFromName("美年大健康产业控股股份有限公司", "ID01MCcOgJl1td")).toBe("prod");
expect(inferCorpEnvFromName("北京某科技有限公司", "ID01abc")).toBe("prod");
expect(inferCorpEnvFromName("", "")).toBe("prod");
expect(inferCorpEnvFromName(undefined, undefined)).toBe("prod");
});
it("getCorpEnv respects explicit env, falls back to isTest, and finally infers", () => {
const explicitTest = {
id: "c1",
name: "普通企业名",
env: "test" as const,
credentials: { corpId: "c1", staffId: "s1", accessToken: "t1" },
};
expect(getCorpEnv(explicitTest as CorpConfig)).toBe("test");
const explicitProd = {
id: "c2",
name: "虽然名字叫测试但显式指定了正式",
env: "prod" as const,
credentials: { corpId: "c2", staffId: "s2", accessToken: "t2" },
};
expect(getCorpEnv(explicitProd as CorpConfig)).toBe("prod");
const legacyIsTest = {
id: "c3",
name: "旧企业无env",
isTest: true,
credentials: { corpId: "c3", staffId: "s3", accessToken: "t3" },
};
expect(getCorpEnv(legacyIsTest as CorpConfig)).toBe("test");
const legacyNoEnv = {
id: "c4",
name: "新转转集团",
credentials: { corpId: "c4", staffId: "s4", accessToken: "t4" },
};
expect(getCorpEnv(legacyNoEnv as CorpConfig)).toBe("prod");
});
it("isCorpTest and isCorpProd maintain consistent boundaries", () => {
const testCorp: CorpConfig = {
id: "t1",
name: "测试企业",
env: "test",
isTest: true,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: { corpId: "t1", staffId: "s1", accessToken: "token" },
};
expect(isCorpTest(testCorp)).toBe(true);
expect(isCorpProd(testCorp)).toBe(false);
const demoCorp: CorpConfig = {
id: "d1",
name: "演示企业",
env: "demo",
isTest: true,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: { corpId: "d1", staffId: "s1", accessToken: "token" },
};
expect(isCorpTest(demoCorp)).toBe(true);
expect(isCorpProd(demoCorp)).toBe(false);
const prodCorp: CorpConfig = {
id: "p1",
name: "新转转集团",
env: "prod",
isTest: false,
baseUrl: "https://app.ekuaibao.com",
source: "manual",
credentials: { corpId: "p1", staffId: "s1", accessToken: "token" },
};
expect(isCorpTest(prodCorp)).toBe(false);
expect(isCorpProd(prodCorp)).toBe(true);
});
it("normalizeCorpConfig injects env and isTest into legacy configs seamlessly", () => {
const legacyRaw = {
id: "ID01PH4Q5CJboX",
name: "新转转集团",
credentials: {
accessToken: "token_123",
corpId: "ID01PH4Q5CJboX",
staffId: "s_123",
},
};
const parsed = CorpConfigSchema.parse(legacyRaw);
const normalized = normalizeCorpConfig(parsed);
expect(normalized.env).toBe("prod");
expect(normalized.isTest).toBe(false);
expect(isCorpProd(normalized)).toBe(true);
const legacyTestRaw = {
id: "ID01uzxB4x07fh",
name: "HAB对公测试环境",
credentials: {
accessToken: "token_test",
corpId: "ID01uzxB4x07fh",
staffId: "s_test",
},
};
const normalizedTest = normalizeCorpConfig(CorpConfigSchema.parse(legacyTestRaw));
expect(normalizedTest.env).toBe("test");
expect(normalizedTest.isTest).toBe(true);
expect(isCorpTest(normalizedTest)).toBe(true);
});
});
+9
View File
@@ -1,9 +1,12 @@
import {
CorpConfig,
CorpEnv,
getCorpEnv,
getCorpExpiresAt,
getCorpPhysicalId,
getCorpStaffId,
getCorpStaffName,
isCorpTest,
} from "./types.js";
import { NotFoundError, NotLoggedInError, ValidationError } from "../errors.js";
import { saveGlobalConfig } from "./loader.js";
@@ -21,6 +24,8 @@ export interface CorpSummary {
expiresAt?: number;
persistent?: boolean;
hasOpenApi?: boolean;
env: CorpEnv;
isTest: boolean;
}
export function resolveCorpConfig(
@@ -161,6 +166,8 @@ export class CorpContext {
(corp.credentials?.appSecurity || corp.auth?.appSecurity)
);
const hasAccountBinding = corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
const env = getCorpEnv(corp);
const test = isCorpTest(corp);
return {
id: corp.id,
name: corp.name,
@@ -174,6 +181,8 @@ export class CorpContext {
expiresAt: getCorpExpiresAt(corp),
persistent: hasOpenApiKeys || hasAccountBinding,
hasOpenApi: hasOpenApiKeys,
env,
isTest: test,
};
});
}
+51
View File
@@ -12,6 +12,9 @@ export const CredentialSourceSchema = z.enum([
]);
export type CredentialSource = z.infer<typeof CredentialSourceSchema>;
export const CorpEnvSchema = z.enum(["prod", "test", "demo"]);
export type CorpEnv = z.infer<typeof CorpEnvSchema>;
export const CorpCredentialsSchema = z.object({
accessToken: z.string().default("").describe("主站访问令牌"),
corpId: z.string().describe("企业 ID"),
@@ -50,6 +53,8 @@ export const CorpConfigSchema = z.object({
id: z.string().describe("配置/身份唯一标识 (默认等于 corpId,同企业多身份时形如 corpId@accountId 或 corpId:staffId)"),
name: z.string().describe("企业名称"),
corpId: z.string().optional().describe("底层企业物理 ID (未填时默认等于 id)"),
env: CorpEnvSchema.optional().describe("企业环境属性: prod(正式生产) / test(测试环境) / demo(演示/POC)"),
isTest: z.boolean().optional().describe("是否为测试或演示企业(非正式生产)"),
userId: z.string().optional().describe("所属用户 ID"),
staffId: z.string().optional().describe("员工工号 (默认取 credentials.staffId)"),
staffName: z.string().optional().describe("员工真实姓名"),
@@ -66,6 +71,48 @@ export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
/**
* 根据企业名称或标识智能推导企业环境属性(未命中一律保守归为正式生产 prod)
*/
export function inferCorpEnvFromName(name?: string, id?: string): CorpEnv {
const text = `${name || ""} ${id || ""}`.toLowerCase();
if (text.includes("测试") || text.includes("test")) {
return "test";
}
if (text.includes("演示") || text.includes("poc") || text.includes("demo")) {
return "demo";
}
return "prod";
}
/**
* 获取企业环境属性 (prod / test / demo)
*/
export function getCorpEnv(corp: CorpConfig): CorpEnv {
if (corp.env && ["prod", "test", "demo"].includes(corp.env)) {
return corp.env;
}
if (corp.isTest !== undefined) {
return corp.isTest ? "test" : "prod";
}
return inferCorpEnvFromName(corp.name, corp.id);
}
/**
* 判断企业是否为非正式环境(测试环境或演示环境)
*/
export function isCorpTest(corp: CorpConfig): boolean {
const env = getCorpEnv(corp);
return env === "test" || env === "demo" || corp.isTest === true;
}
/**
* 判断企业是否为正式生产环境 (prod)
*/
export function isCorpProd(corp: CorpConfig): boolean {
return !isCorpTest(corp);
}
/**
* 获取企业真实物理 corpId(统一收敛 corp.corpId / corp.credentials.corpId / corp.id)
*/
@@ -104,9 +151,13 @@ export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
const expiresAt = getCorpExpiresAt(corp);
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
const env = getCorpEnv(corp);
const isTest = env !== "prod";
return {
...corp,
env,
isTest,
corpId: physicalCorpId,
...(staffId ? { staffId } : {}),
...(staffName ? { staffName } : {}),