feat(corps): 企业配置增加环境属性与生产安全保护机制
- Schema 扩展: CorpConfigSchema 增加 env ('prod' | 'test' | 'demo') 与 isTest 字段,未知企业保守兜底为 prod
- 智能初判与归一化: inferCorpEnvFromName 依据名称初判环境,normalizeCorpConfig 确保配置持久化时环境对齐
- CLI 视图升级: corps list 与 search 增加「环境」列 (🏭 正式 / 🧪 测试 / 🎪 演示),支持 --test/--prod/--env 筛选
- 环境打标与迁移: 新增 hose-use corps tag 命令,支持单个企业标记与 --migrate-all 批量显式升级持久化
- 生产安全阻断: workflow test 等敏感调试在正式生产环境 (prod) 阻断执行,需显式附加 --force 确认生产风险
- 上下文与探针增强: context、probe、corps current 全面输出企业环境属性
- 测试与文档补全: 覆盖 489 项全量测试并通过 tsc 类型检查
This commit is contained in:
1 parent
908286c1df
commit
af1e11c018
15 files changed
+775
-28
No files matched your search
@@ -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)"}`,
|
||||
|
||||
@@ -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 家");
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user