Files
hose-use/src/cli/commands/keys.ts
T

175 lines
5.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
import { selectOpenApiKey } from "../../core/auth/login.js";
import { saveCorpConfig } from "../../core/config/loader.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function formatDate(ts: number): string {
if (!ts) return "-";
const d = new Date(ts);
if (isNaN(d.getTime())) return "-";
const Y = d.getFullYear();
const M = String(d.getMonth() + 1).padStart(2, "0");
const D = String(d.getDate()).padStart(2, "0");
const h = String(d.getHours()).padStart(2, "0");
const m = String(d.getMinutes()).padStart(2, "0");
return `${Y}/${M}/${D} ${h}:${m}`;
}
function maskSecret(secret: string): string {
if (!secret) return "-";
if (secret.length <= 12) return "******";
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
}
export async function handleKeysCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const currentCorp = runtime.selectedCorp;
if (!currentCorp) {
return {
stdout: "",
stderr: "未选中企业,请先通过 hose-use corps switch 或 --corp 指定企业\n",
exitCode: 1,
};
}
const reveal =
booleanOption(parsed.options, ["reveal", "r", "plain"]) ||
parsed.action === "reveal" ||
parsed.args[0] === "reveal";
const save =
booleanOption(parsed.options, ["save", "persist", "elevate"]) ||
parsed.action === "save" ||
parsed.args[0] === "save";
const appKeyOpt = stringOption(parsed.options, ["app-key", "appKey"]);
const keyIdOpt = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"]);
if (save) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${currentCorp.name} (${currentCorp.id})`, {
corpId: currentCorp.id,
appKey: appKeyOpt || "auto-select",
keyId: keyIdOpt || null,
});
}
requireMutationConfirmation(
parsed,
runtime,
"提取并持久化企业 OpenAPI 密钥",
`hose-use keys --corp=${currentCorp.id} --save --yes`
);
}
try {
const keys = await fetchOpenApiKeys(currentCorp);
if (save) {
const selected = selectOpenApiKey(
keys.map((k) => ({
id: k.id,
name: k.name || undefined,
appKey: k.appKey,
appSecurity: k.appSecurity,
active: k.active,
createTime: k.createTime,
updateTime: k.updateTime,
})),
currentCorp.id,
{ appKey: appKeyOpt, keyId: keyIdOpt, force }
);
currentCorp.credentials.appKey = selected.appKey;
currentCorp.credentials.appSecurity = selected.appSecurity;
const savedPath = saveCorpConfig(currentCorp);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
saved: true,
corpId: currentCorp.id,
corpName: currentCorp.name,
appKey: selected.appKey,
appSecurity: reveal ? selected.appSecurity : maskSecret(selected.appSecurity),
keyName: selected.name || "-",
path: savedPath,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
return {
stdout: `[SUCCESS] 已为企业 [${currentCorp.name}] 持久化保存 OpenAPI 密钥 (appKey: ${selected.appKey})!\n保存路径: ${savedPath}\n`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
if (runtime.jsonMode) {
const outputData = reveal
? keys
: keys.map((k) => ({
...k,
appSecurity: maskSecret(k.appSecurity),
}));
return {
stdout: printJson(outputData, runtime.outputOptions),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
if (keys.length === 0) {
return {
stdout: `企业 [${currentCorp.name}] 暂未创建 OpenAPI 密钥凭证\n`,
stderr: "",
exitCode: 0,
};
}
const rows = keys.map((k, i) => [
i + 1,
k.name || "-",
k.appKey,
reveal ? k.appSecurity : maskSecret(k.appSecurity),
k.active ? "🟢 启用" : "⚪ 停用",
formatDate(k.createTime),
]);
const table = printTable(
["#", "密钥备注", "接入账号 (appKey)", "接入密码 (appSecurity)", "状态", "创建时间"],
rows
);
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
const hint = reveal
? ""
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;附加 --save --yes 可持久化到当前企业配置;使用 --json 可输出完整结构。\n";
return {
stdout: `${title}\n\n${table}\n${hint}`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
} catch (err: any) {
return {
stdout: "",
stderr: `获取企业 OpenAPI 密钥失败: ${err?.message || err}\n`,
exitCode: 1,
};
}
}