refactor(corps): normalize credential categories and format workflow history logs

This commit is contained in:
gitea committed 2026-10-14 18:19:13 +08:00
1 parent f91a80f9dd
commit 0499ccb2cc
9 files changed
+150 -38

No files matched your search

+1 -1
View File
@@ -253,7 +253,7 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
: "✅ 统一认证主账号自动换票" : "✅ 统一认证主账号自动换票"
: "⚪ 短期会话", : "⚪ 短期会话",
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接", "Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent), "Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp?.source),
}; };
if (currentCorp?.session) { if (currentCorp?.session) {
+1 -1
View File
@@ -135,7 +135,7 @@ export async function handleContextCommand(
` 当前操作员工 : ${corpStaffId}`, ` 当前操作员工 : ${corpStaffId}`,
` 员工真实姓名 : ${corpStaffName}`, ` 员工真实姓名 : ${corpStaffName}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`, ` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`, ` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`, ` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`, ` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
` AI PRO 规约库 : ${scopesStr}`, ` AI PRO 规约库 : ${scopesStr}`,
+1 -1
View File
@@ -55,7 +55,7 @@ export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime):
"员工姓名": current.staffName || current.session?.staffName || "-", "员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source, hasOpenApi), "凭证来源": formatSourceLabel(current.source, hasOpenApi),
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话", "持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent), "Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent, hasOpenApi ? "openapi" : current.source),
"所属账号": current.accountId || "-", "所属账号": current.accountId || "-",
"主站地址": current.baseUrl || "https://app.ekuaibao.com", "主站地址": current.baseUrl || "https://app.ekuaibao.com",
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境", "适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
+14 -6
View File
@@ -1,6 +1,6 @@
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js"; import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
import { stringOption } from "../../parser.js"; import { stringOption } from "../../parser.js";
import { printJson, printTable, formatExpiresAt } from "../../printer.js"; import { printJson, printTable, formatExpiresAt, formatSourceLabel } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js"; import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
const FIELD_LABEL_MAP: Record<string, string> = { const FIELD_LABEL_MAP: Record<string, string> = {
@@ -30,7 +30,12 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
: null; : null;
const normalizedCorps = rawCorps const normalizedCorps = rawCorps
? rawCorps.map((c) => ({ ? rawCorps.map((c) => {
const hasOpenApi = Boolean(
(c.credentials?.appKey || c.auth?.appKey) &&
(c.credentials?.appSecurity || c.auth?.appSecurity)
);
return {
id: c.id, id: c.id,
name: c.name, name: c.name,
corpId: c.corpId || c.credentials?.corpId || c.id, corpId: c.corpId || c.credentials?.corpId || c.id,
@@ -42,7 +47,9 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
current: c.id === runtime.selectedCorp?.id, current: c.id === runtime.selectedCorp?.id,
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined), expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
persistent: canRefreshCorpAccessToken(c), persistent: canRefreshCorpAccessToken(c),
})) hasOpenApi,
};
})
: runtime.corpContext.listCorps().map((c) => ({ : runtime.corpContext.listCorps().map((c) => ({
id: c.id, id: c.id,
name: c.name, name: c.name,
@@ -55,6 +62,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
current: c.current || c.id === runtime.selectedCorp?.id, current: c.current || c.id === runtime.selectedCorp?.id,
expiresAt: c.expiresAt, expiresAt: c.expiresAt,
persistent: c.persistent, persistent: c.persistent,
hasOpenApi: c.hasOpenApi,
})); }));
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = []; const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
@@ -134,7 +142,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-", m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-", m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
matchLabels.map((l) => `命中${l}`).join(", "), matchLabels.map((l) => `命中${l}`).join(", "),
formatExpiresAt(m.expiresAt, m.persistent), formatExpiresAt(m.expiresAt, m.persistent, m.hasOpenApi ? "openapi" : m.source),
]; ];
}); });
@@ -176,8 +184,8 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
c.id, c.id,
c.name, c.name,
c.staffId, c.staffId,
c.source || "manual", formatSourceLabel(c.source, c.hasOpenApi),
formatExpiresAt(c.expiresAt, c.persistent), formatExpiresAt(c.expiresAt, c.persistent, c.hasOpenApi ? "openapi" : c.source),
c.accountId || "-", c.accountId || "-",
]); ]);
+1 -1
View File
@@ -110,7 +110,7 @@ export async function handleProbeCommand(
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})` ? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
: "✅ 统一认证主账号自动换票" : "✅ 统一认证主账号自动换票"
: "⚪ 短期会话", : "⚪ 短期会话",
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent), "Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp.source),
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常", "主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败", "EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败", "自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
+14 -10
View File
@@ -38,10 +38,14 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
endTime: stringOption(parsed.options, ["end-time", "endTime"]), endTime: stringOption(parsed.options, ["end-time", "endTime"]),
}); });
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]); const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
const isJobError = (job: any): boolean => {
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
if (job.state === "FAILED" || job.status === "FAILED") return true;
return false;
};
const filteredJobList = hasErrorFilter const filteredJobList = hasErrorFilter
? rawResult.jobList.filter( ? rawResult.jobList.filter(isJobError)
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
)
: rawResult.jobList; : rawResult.jobList;
const result = hasErrorFilter const result = hasErrorFilter
? { ...rawResult, jobList: filteredJobList } ? { ...rawResult, jobList: filteredJobList }
@@ -49,15 +53,15 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 }; if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = result.jobList.map((job, idx) => [ const rows = result.jobList.map((job: any, idx) => [
idx + 1, idx + 1,
job.id, job.jobId || job.id || "-",
job.state, job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
job.successTaskCount, job.successTaskCount ?? 0,
job.errorTaskCount, job.errorTaskCount ?? 0,
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)", isJobError(job) ? "⚠️ 包含错误" : "正常",
job.durationTime ?? "-", job.durationTime ?? "-",
job.startTime || "-", job.executeTime || job.startTime || "-",
]); ]);
const tableStr = rows.length const tableStr = rows.length
? printTable( ? printTable(
+58
View File
@@ -7,6 +7,8 @@ import {
protectLargeOutput, protectLargeOutput,
printJson, printJson,
redactSensitiveText, redactSensitiveText,
formatSourceLabel,
formatExpiresAt,
} from "./printer.js"; } from "./printer.js";
describe("cli/printer - 上下文防爆与敏感脱敏", () => { describe("cli/printer - 上下文防爆与敏感脱敏", () => {
@@ -114,4 +116,60 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
expect(savedContent[0].id).toBe("id-0"); expect(savedContent[0].id).toBe("id-0");
}); });
}); });
describe("formatSourceLabel 4大凭证类别规范格式化", () => {
test("企业开放接口 (OpenAPI 密钥)", () => {
expect(formatSourceLabel("openapi")).toBe("企业开放接口 (OpenAPI 密钥)");
expect(formatSourceLabel("account", true)).toBe("企业开放接口 (OpenAPI 密钥)");
expect(formatSourceLabel("link", true)).toBe("企业开放接口 (OpenAPI 密钥)");
});
test("个人账号凭证 (手机号)", () => {
expect(formatSourceLabel("account")).toBe("个人账号凭证 (手机号)");
});
test("合思协助平台授权链接 (协助链接)", () => {
expect(formatSourceLabel("link")).toBe("合思协助平台授权链接 (协助链接)");
expect(formatSourceLabel("assist")).toBe("合思协助平台授权链接 (协助链接)");
});
test("网页临时抓包凭证 (Cookie)", () => {
expect(formatSourceLabel("curl")).toBe("网页临时抓包凭证 (Cookie)");
expect(formatSourceLabel("browser")).toBe("网页临时抓包凭证 (Cookie)");
expect(formatSourceLabel("f12")).toBe("网页临时抓包凭证 (Cookie)");
});
test("兜底处理", () => {
expect(formatSourceLabel("manual")).toBe("手动配置");
expect(formatSourceLabel("other")).toBe("其他 (other)");
expect(formatSourceLabel(undefined)).toBe("未知来源");
});
});
describe("formatExpiresAt 过期状态精准描述", () => {
test("长期有效凭据", () => {
expect(formatExpiresAt(undefined, true, "openapi")).toBe("长期有效 (OpenAPI 密钥)");
expect(formatExpiresAt(0, false)).toBe("长期有效 / 服务端未显式限制");
});
test("已过期但具备自动续期能力的凭据", () => {
const pastTime = Date.now() - 3600000;
expect(formatExpiresAt(pastTime, true, "account")).toContain("(🔄 随主账号自动换票)");
expect(formatExpiresAt(pastTime, true, "openapi")).toContain("(🔄 OpenAPI 密钥自动续期)");
expect(formatExpiresAt(pastTime, true)).toContain("(🔄 自动续期)");
});
test("已过期且不可续期的凭据精准告警", () => {
const pastTime = Date.now() - 3600000;
expect(formatExpiresAt(pastTime, false, "link")).toContain("(⚠️ 协助授权已失效)");
expect(formatExpiresAt(pastTime, false, "curl")).toContain("(⚠️ Cookie 已失效)");
expect(formatExpiresAt(pastTime, false, "manual")).toContain("(⚠️ 已过期)");
});
test("未来有效期的剩余提示", () => {
const futureMins = Date.now() + 30 * 60000;
expect(formatExpiresAt(futureMins, true, "account")).toContain("支持主账号自动换票");
expect(formatExpiresAt(futureMins, true, "openapi")).toContain("支持 OpenAPI 密钥自动续期");
});
});
}); });
+58 -18
View File
@@ -42,48 +42,88 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
} }
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string { export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : ""; if (persistentOpenApi || source === "openapi") {
return "企业开放接口 (OpenAPI 密钥)";
}
switch (source) { switch (source) {
case "openapi":
return "开放平台持久化密钥 (OpenAPI AppKey)";
case "assist":
return `官方协助/代客平台 (Assist Platform)${suffix}`;
case "account": case "account":
return `统一认证中心 (IDP 账密/短信)${suffix}`; return "个人账号凭证 (手机号)";
case "browser": case "assist":
return `浏览器会话同步 (WebBridge)${suffix}`;
case "link": case "link":
return `协助/免密链接导入 (Assistance Link)${suffix}`; return "合思协助平台授权链接 (协助链接)";
case "browser":
case "curl": case "curl":
case "f12": case "f12":
return `cURL 抓包导入 (cURL/F12)${suffix}`; return "网页临时抓包凭证 (Cookie)";
case "manual": case "manual":
return `手动配置${suffix}`; return "手动配置";
default: default:
return (source || "未知来源") + suffix; return source ? `其他 (${source})` : "未知来源";
} }
} }
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string { export function formatExpiresAt(
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制"; expiresAt?: number | null,
persistent?: boolean,
source?: string
): string {
if (!expiresAt || expiresAt <= 0) {
if (source === "openapi") {
return "长期有效 (OpenAPI 密钥)";
}
return "长期有效 / 服务端未显式限制";
}
const diffMs = expiresAt - Date.now(); const diffMs = expiresAt - Date.now();
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false }); const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
if (diffMs <= 0) { if (diffMs <= 0) {
if (persistent) { if (persistent) {
return `${dateStr} (🔄 持久化密钥自动续期)`; if (source === "account") {
return `${dateStr} (🔄 随主账号自动换票)`;
}
if (source === "openapi") {
return `${dateStr} (🔄 OpenAPI 密钥自动续期)`;
}
return `${dateStr} (🔄 自动续期)`;
}
if (source === "link" || source === "assist") {
return `${dateStr} (⚠️ 协助授权已失效)`;
}
if (source === "curl" || source === "browser" || source === "f12") {
return `${dateStr} (⚠️ Cookie 已失效)`;
} }
return `${dateStr} (⚠️ 已过期)`; return `${dateStr} (⚠️ 已过期)`;
} }
const diffMins = Math.floor(diffMs / 60000); const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) { if (diffMins < 60) {
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`; const renewSuffix = persistent
? source === "account"
? ",支持主账号自动换票"
: source === "openapi"
? ",支持 OpenAPI 密钥自动续期"
: ",支持自动续期"
: "";
return `${dateStr} (约剩余 ${diffMins} 分钟${renewSuffix})`;
} }
const diffHours = (diffMs / 3600000).toFixed(1); const diffHours = (diffMs / 3600000).toFixed(1);
if (Number(diffHours) < 24) { if (Number(diffHours) < 24) {
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`; const renewSuffix = persistent
? source === "account"
? ",支持主账号自动换票"
: source === "openapi"
? ",支持 OpenAPI 密钥自动续期"
: ",支持自动续期"
: "";
return `${dateStr} (约剩余 ${diffHours} 小时${renewSuffix})`;
} }
const diffDays = Math.floor(diffMs / 86400000); const diffDays = Math.floor(diffMs / 86400000);
return `${dateStr} (约剩余 ${diffDays} 天)`; const renewSuffix = persistent
? source === "account"
? ",支持主账号自动换票"
: source === "openapi"
? ",支持 OpenAPI 密钥自动续期"
: ""
: "";
return `${dateStr} (约剩余 ${diffDays} 天${renewSuffix})`;
} }
export function printKeyValue(pairs: Record<string, unknown>): string { export function printKeyValue(pairs: Record<string, unknown>): string {
+2
View File
@@ -20,6 +20,7 @@ export interface CorpSummary {
current: boolean; current: boolean;
expiresAt?: number; expiresAt?: number;
persistent?: boolean; persistent?: boolean;
hasOpenApi?: boolean;
} }
export function resolveCorpConfig( export function resolveCorpConfig(
@@ -172,6 +173,7 @@ export class CorpContext {
current: corp.id === this.current?.id, current: corp.id === this.current?.id,
expiresAt: getCorpExpiresAt(corp), expiresAt: getCorpExpiresAt(corp),
persistent: hasOpenApiKeys || hasAccountBinding, persistent: hasOpenApiKeys || hasAccountBinding,
hasOpenApi: hasOpenApiKeys,
}; };
}); });
} }