Files
hose-use/src/cli/commands/probe.ts
T
gitea af1e11c018 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 类型检查
2026-10-16 12:30:08 +08:00

137 lines
4.9 KiB
TypeScript

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, formatCorpEnvLabel } from "../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleProbeCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未配置任何企业,请先运行 hose-use auth login 或使用 --corp 指定\n",
exitCode: 1,
};
}
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
const isPersistent = canRefreshCorpAccessToken(currentCorp);
const results: Record<string, unknown> = {
enterprise: {
id: currentCorp.id,
name: currentCorp.name,
env: currentCorp.env,
isTest: currentCorp.isTest,
staffId: currentCorp.credentials.staffId,
baseUrl: currentCorp.baseUrl,
source: currentCorp.source,
accountId: currentCorp.accountId,
persistent: isPersistent,
hasOpenApiKey: hasOpenApi,
},
ekbSession: { status: "pending" },
easoToken: { status: "pending" },
platformAccess: { status: "pending" },
};
// 1. 独立测试 EKB 主站 Session
let sessionClient: Awaited<ReturnType<typeof createSessionClient>> | null = null;
try {
sessionClient = await createSessionClient(currentCorp);
const sessionRes = await sessionClient
.get("api/account/v2/session")
.json<{ value?: { userId?: string; loginStaffId?: string; expTime?: number } }>();
results.ekbSession = {
status: "ok",
userId: sessionRes.value?.userId,
loginStaffId: sessionRes.value?.loginStaffId,
expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined,
};
} catch (e) {
results.ekbSession = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
// 2. 独立测试自建应用列表访问
let platforms: any[] = [];
if (sessionClient) {
try {
platforms = await api.listPlatforms(sessionClient, currentCorp.credentials.corpId);
results.platformAccess = {
status: "ok",
totalPlatforms: platforms.length,
};
} catch (e) {
results.platformAccess = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
} else {
results.platformAccess = {
status: "error",
error: "主站客户端未能初始化",
};
}
// 3. 独立测试 EASO Token 换取
try {
const { client: easoClient } = await getEasoClient(currentCorp);
const targetPlatformId = platforms[0]?.id || currentCorp.credentials.corpId;
await api.getWorkflowStats(easoClient, targetPlatformId);
results.easoToken = {
status: "ok",
message: "EASO 四步换票握手成功",
};
} catch (e) {
results.easoToken = {
status: "error",
error: e instanceof Error ? e.message : String(e),
};
}
if (runtime.jsonMode) {
return { stdout: printJson(results), stderr: "", exitCode: 0 };
}
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),
"持久化状态": isPersistent
? hasOpenApi
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp.source),
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
};
if (currentCorp.session?.isAssistPlatform) {
probePairs["协助操作人"] = `${currentCorp.session.operationUserName || ""} (${currentCorp.session.operationUserId || ""})`.trim();
if (currentCorp.session.assistId) {
probePairs["协助会话 ID"] = currentCorp.session.assistId;
}
}
const summary = printKeyValue(probePairs);
return {
stdout: `====== 诊断结果 (Enterprise Probe) ======\n${summary}\n`,
stderr: "",
exitCode: 0,
};
}