import * as apiApplications from "../../domains/platform/applications/services.js"; import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js"; import { createSessionClient, getEasoClient } from "../../core/http/index.js"; import * as api from "../../domains/platform/workflow/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 { 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 = { enterprise: { id: currentCorp.id, name: currentCorp.name, env: currentCorp.env, isTest: currentCorp.isTest, staffId: currentCorp.credentials.staffId, staffName: currentCorp.staffName || currentCorp.session?.staffName, 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> | 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, }; // 自愈补全员工姓名 (Self-Healing Profile Hydration) if (!currentCorp.staffName && !currentCorp.session?.staffName) { if (hasOpenApi && currentCorp.credentials.appKey && currentCorp.credentials.appSecurity && currentCorp.credentials.staffId) { try { const { fetchHoseOpenApiAccessToken, fetchHoseStaffDetails } = await import("../../core/auth/openapi-v1.js"); const openapiToken = await fetchHoseOpenApiAccessToken({ baseUrl: currentCorp.baseUrl, appKey: currentCorp.credentials.appKey, appSecurity: currentCorp.credentials.appSecurity, }); const details = await fetchHoseStaffDetails(currentCorp.baseUrl || "https://app.ekuaibao.com", openapiToken, [currentCorp.credentials.staffId]); if (details[0]?.name) { currentCorp.staffName = details[0].name; if (!currentCorp.session) { currentCorp.session = { staffName: details[0].name } as any; } else { currentCorp.session.staffName = details[0].name; } if (details[0].cellphone && currentCorp.session) { currentCorp.session.cellphone = details[0].cellphone; } (results.enterprise as any).staffName = details[0].name; const { saveCorpConfig } = await import("../../core/config/loader.js"); saveCorpConfig(currentCorp); } } catch {} } } } catch (e) { results.ekbSession = { status: "error", error: e instanceof Error ? e.message : String(e), }; } // 2. 独立测试自建应用列表访问 let platforms: any[] = []; if (sessionClient) { try { platforms = await apiApplications.listBasicPlatforms(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 = { "企业名称": 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, }; }