Pilot for the command-directory form: 1077-line corps.ts becomes
corps/{index,shared,query,context,link,credentials,probe}.ts with
verbatim code moves. index.ts keeps the dispatch switch plus
re-exports so auth.ts and registry.ts consumers stay source-compatible.
No behavior change: tsc clean, 316 tests pass.
396 lines
13 KiB
TypeScript
396 lines
13 KiB
TypeScript
import { join } from "node:path";
|
||
import {
|
||
elevateCorpWithOpenApiKey,
|
||
extractOpenApiKeysFromLink,
|
||
hasOpenApiPersistentCredentials,
|
||
maskOpenApiSecurity,
|
||
onboardHosePersistent,
|
||
syncOpenApiFromSealUse,
|
||
} from "../../../core/auth/login.js";
|
||
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
|
||
import { stringOption, booleanOption } from "../../parser.js";
|
||
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } 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 handleAddPersistent(
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
let jsonPayload: Record<string, unknown> = {};
|
||
const rawJsonArg = stringOption(parsed.options, ["data"]) || (parsed.args[0]?.trim().startsWith("{") ? parsed.args[0] : undefined);
|
||
if (rawJsonArg) {
|
||
try {
|
||
jsonPayload = JSON.parse(rawJsonArg);
|
||
} catch {
|
||
return { stdout: "", stderr: "错误:提供的 JSON 参数无法解析\n", exitCode: 1 };
|
||
}
|
||
}
|
||
|
||
const appKey =
|
||
stringOption(parsed.options, ["app-key", "appKey", "key"]) ||
|
||
(typeof jsonPayload.appKey === "string" ? jsonPayload.appKey : undefined);
|
||
const appSecurity =
|
||
stringOption(parsed.options, ["app-security", "appSecurity", "secret", "password"]) ||
|
||
(typeof jsonPayload.appSecurity === "string" ? jsonPayload.appSecurity : undefined);
|
||
const domain =
|
||
stringOption(parsed.options, ["domain", "base-url", "baseUrl"]) ||
|
||
(typeof jsonPayload.domain === "string" ? jsonPayload.domain : undefined);
|
||
const corpId =
|
||
stringOption(parsed.options, ["corp-id", "corpId", "corp"]) ||
|
||
(typeof jsonPayload.corpId === "string" ? jsonPayload.corpId : undefined);
|
||
const staffId =
|
||
stringOption(parsed.options, ["staff-id", "staffId", "proxyStaffBizId"]) ||
|
||
(typeof jsonPayload.staffId === "string" ? jsonPayload.staffId : undefined);
|
||
const staffName =
|
||
stringOption(parsed.options, ["staff-name", "staffName"]) ||
|
||
(typeof jsonPayload.staffName === "string" ? jsonPayload.staffName : undefined);
|
||
const staffPhone =
|
||
stringOption(parsed.options, ["staff-phone", "staffPhone"]) ||
|
||
(typeof jsonPayload.staffPhone === "string" ? jsonPayload.staffPhone : undefined);
|
||
const role =
|
||
stringOption(parsed.options, ["role"]) ||
|
||
(typeof jsonPayload.role === "string" ? jsonPayload.role : undefined);
|
||
const name =
|
||
stringOption(parsed.options, ["name"]) ||
|
||
(typeof jsonPayload.name === "string" ? jsonPayload.name : undefined);
|
||
const overwrite = booleanOption(parsed.options, ["overwrite"], Boolean(jsonPayload.overwrite));
|
||
const force = booleanOption(parsed.options, ["force", "f"], Boolean(jsonPayload.force));
|
||
|
||
if (!appKey || !appSecurity) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "错误:必须提供 appKey 与 appSecurity!用法: hose-use corps add-persistent --app-key=<key> --app-security=<secret> [--staff-id=<id>] [--force] [--overwrite] --yes\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "通过 OpenAPI 持久化密钥接入企业", name || corpId || appKey, {
|
||
source: "openapi",
|
||
appKey,
|
||
domain: domain || "auto-probe",
|
||
staffId: staffId || "auto-discover",
|
||
overwrite,
|
||
});
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"通过 OpenAPI 持久化密钥接入企业",
|
||
`hose-use corps add-persistent --app-key=${appKey} --app-security=<redacted> --yes`
|
||
);
|
||
|
||
const saved = await onboardHosePersistent({
|
||
name,
|
||
appKey,
|
||
appSecurity,
|
||
domain,
|
||
corpId,
|
||
staffId,
|
||
staffName,
|
||
staffPhone,
|
||
role,
|
||
force,
|
||
overwrite,
|
||
});
|
||
|
||
if (runtime.jsonMode) {
|
||
return { stdout: printJson(saved, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||
}
|
||
|
||
const targetDir = resolveWritableEnterprisesDir();
|
||
const savedPath = join(targetDir, `${saved.id}.json`);
|
||
const summaryText = printKeyValue({
|
||
"企业名称": saved.name,
|
||
"企业 ID": saved.id,
|
||
"服务节点": saved.baseUrl,
|
||
"员工工号": saved.credentials.staffId,
|
||
"员工姓名": saved.staffName || saved.session?.staffName || "-",
|
||
"接入账号 (appKey)": saved.credentials.appKey,
|
||
"凭证来源": formatSourceLabel(saved.source, true),
|
||
"保存路径": savedPath,
|
||
});
|
||
|
||
return {
|
||
stdout: `[SUCCESS] 成功接入并持久化企业 OpenAPI 凭证!\n${summaryText}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
export async function handleExtractKeys(
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
const linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
|
||
if (!linkUrl) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "用法: hose-use corps extract-keys <https://.../web/thirdparty.html?...> [--reveal] [--save] [--app-key <key>] [--key-id <id>] [--overwrite]\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
const reveal = booleanOption(parsed.options, ["reveal", "r", "plain"], false);
|
||
const save = booleanOption(parsed.options, ["save", "add", "persist"], false);
|
||
const name = stringOption(parsed.options, ["name"]);
|
||
const overwrite = booleanOption(parsed.options, ["overwrite"], true);
|
||
const force = booleanOption(parsed.options, ["force", "f"], false);
|
||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||
|
||
if (save) {
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "从协助链接提取并持久化 OpenAPI 密钥", name || "待解析企业", {
|
||
save: true,
|
||
overwrite,
|
||
appKey: appKey || "auto-select",
|
||
});
|
||
}
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"从协助链接提取并持久化 OpenAPI 密钥",
|
||
`hose-use corps extract-keys "<url>" --save --yes`
|
||
);
|
||
}
|
||
|
||
const extracted = await extractOpenApiKeysFromLink(linkUrl, {
|
||
save,
|
||
name,
|
||
overwrite,
|
||
force,
|
||
appKey,
|
||
keyId,
|
||
});
|
||
|
||
const formattedKeys = extracted.keys.map((k) => ({
|
||
id: k.id,
|
||
name: k.name || "-",
|
||
appKey: k.appKey,
|
||
appSecurity: reveal ? k.appSecurity : maskOpenApiSecurity(k.appSecurity),
|
||
active: k.active,
|
||
createTime: k.createTime,
|
||
updateTime: k.updateTime,
|
||
}));
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(
|
||
{
|
||
corpId: extracted.corpId,
|
||
corpName: extracted.corpName || extracted.corpId,
|
||
baseUrl: extracted.baseUrl,
|
||
staffId: extracted.staffId,
|
||
keyCount: formattedKeys.length,
|
||
keys: formattedKeys,
|
||
...(extracted.savedCorp ? { saved: true, savedCorpId: extracted.savedCorp.id } : {}),
|
||
},
|
||
runtime.outputOptions
|
||
),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
preserveSensitiveStdout: reveal,
|
||
};
|
||
}
|
||
|
||
const rows = formattedKeys.map((k, i) => [
|
||
i + 1,
|
||
k.name,
|
||
k.appKey,
|
||
k.appSecurity,
|
||
k.active ? "🟢 启用" : "⚪ 停用",
|
||
]);
|
||
const table = printTable(["#", "应用名称", "appKey", "appSecurity", "状态"], rows);
|
||
const savedNotice = extracted.savedCorp
|
||
? `\n[SUCCESS] 已将密钥 (${extracted.selectedKey?.appKey}) 持久化保存至企业 [${extracted.savedCorp.name} (${extracted.savedCorp.id})]`
|
||
: "";
|
||
|
||
return {
|
||
stdout: `====== 协助链接 OpenAPI 密钥提取结果 (${extracted.corpName || extracted.corpId}) ======\n${table}${savedNotice}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
preserveSensitiveStdout: reveal,
|
||
};
|
||
}
|
||
|
||
export async function handleElevateCorp(
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
const elevateAll = booleanOption(parsed.options, ["all", "a"], false);
|
||
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
|
||
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
|
||
const force = booleanOption(parsed.options, ["force", "f"], true);
|
||
|
||
if (elevateAll) {
|
||
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
|
||
? runtime.corpContext.getAllCorps()
|
||
: [];
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "批量提取并持久化全部企业 OpenAPI 密钥", `共 ${allCorps.length} 家企业`, {
|
||
count: allCorps.length,
|
||
});
|
||
}
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"批量提取并持久化全部企业 OpenAPI 密钥",
|
||
`hose-use corps elevate --all --yes`
|
||
);
|
||
|
||
const results: Array<{ corpId: string; name: string; appKey?: string; status: string }> = [];
|
||
for (const corp of allCorps) {
|
||
if (hasOpenApiPersistentCredentials(corp)) {
|
||
results.push({ corpId: corp.id, name: corp.name, appKey: corp.credentials.appKey, status: "✅ 已持久化" });
|
||
continue;
|
||
}
|
||
const selected = await elevateCorpWithOpenApiKey(corp, { force: true, silent: true });
|
||
if (selected) {
|
||
results.push({ corpId: corp.id, name: corp.name, appKey: selected.appKey, status: "✨ 新提权成功" });
|
||
} else {
|
||
results.push({ corpId: corp.id, name: corp.name, status: "⚪ 无密钥或会话过期" });
|
||
}
|
||
}
|
||
|
||
if (runtime.jsonMode) {
|
||
return { stdout: printJson({ results }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||
}
|
||
|
||
const rows = results.map((r, i) => [i + 1, r.corpId, r.name, r.appKey || "-", r.status]);
|
||
return {
|
||
stdout: `====== 批量提权企业 OpenAPI 持久化密钥结果 ======\n${printTable(["#", "企业 ID", "企业名称", "appKey", "状态"], rows)}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const targetCorp = resolveTargetCorpByArgOrContext(parsed.args[0], runtime);
|
||
if (!targetCorp) {
|
||
return {
|
||
stdout: "",
|
||
stderr: "未找到目标企业,请通过 --corp=<id> 或参数指定企业,或使用 --all 批量提权\n",
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "提取并持久化企业 OpenAPI 密钥", `${targetCorp.name} (${targetCorp.id})`, {
|
||
corpId: targetCorp.id,
|
||
appKey: appKey || "auto-select",
|
||
});
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"提取并持久化企业 OpenAPI 密钥",
|
||
`hose-use corps elevate ${targetCorp.id} --yes`
|
||
);
|
||
|
||
const selected = await elevateCorpWithOpenApiKey(targetCorp, {
|
||
appKey,
|
||
keyId,
|
||
force,
|
||
});
|
||
|
||
if (!selected) {
|
||
return {
|
||
stdout: "",
|
||
stderr: `未能为企业 [${targetCorp.name}] 提取到可用的 OpenAPI 密钥\n`,
|
||
exitCode: 1,
|
||
};
|
||
}
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(
|
||
{
|
||
corpId: targetCorp.id,
|
||
corpName: targetCorp.name,
|
||
appKey: selected.appKey,
|
||
appSecurity: maskOpenApiSecurity(selected.appSecurity),
|
||
keyName: selected.name || "-",
|
||
persistent: true,
|
||
},
|
||
runtime.outputOptions
|
||
),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
return {
|
||
stdout: `[SUCCESS] 已将企业 [${targetCorp.name} (${targetCorp.id})] 提权为 OpenAPI 持久化配置 (appKey: ${selected.appKey})!\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
export async function handleSyncFromSeal(
|
||
parsed: CliParsedArgs,
|
||
runtime: CliRuntime
|
||
): Promise<CliResult> {
|
||
const filter = parsed.args[0] || stringOption(parsed.options, ["corp", "filter", "keyword"]);
|
||
const sealDir = stringOption(parsed.options, ["seal-dir", "sealDir"]);
|
||
const verify = booleanOption(parsed.options, ["verify"], false);
|
||
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], true);
|
||
|
||
if (isDryRun(parsed, runtime)) {
|
||
return mutationPreview(parsed, runtime, "从 seal-use 同步企业 OpenAPI 持久化密钥", filter || "全部合思企业", {
|
||
filter: filter || null,
|
||
verify,
|
||
overwrite,
|
||
});
|
||
}
|
||
|
||
requireMutationConfirmation(
|
||
parsed,
|
||
runtime,
|
||
"从 seal-use 同步企业 OpenAPI 持久化密钥",
|
||
`hose-use corps sync-seal${filter ? ` ${filter}` : ""} --yes`
|
||
);
|
||
|
||
const synced = await syncOpenApiFromSealUse({
|
||
filter,
|
||
sealEnterprisesDir: sealDir,
|
||
verify,
|
||
overwrite,
|
||
});
|
||
|
||
if (runtime.jsonMode) {
|
||
return {
|
||
stdout: printJson(synced, runtime.outputOptions),
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
if (synced.items.length === 0) {
|
||
return {
|
||
stdout: `未在 ${synced.sealDir} 中找到可同步的合思 OpenAPI 持久化密钥配置${filter ? ` (过滤条件: ${filter})` : ""}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|
||
|
||
const rows = synced.items.map((item, idx) => [
|
||
idx + 1,
|
||
item.corpId,
|
||
item.name,
|
||
item.appKey,
|
||
item.staffId,
|
||
item.action === "merged" ? "🔄 合并增强" : item.action === "created" ? "✨ 新增企业" : "⏭️ 跳过",
|
||
]);
|
||
const table = printTable(["#", "企业 ID", "企业名称", "appKey", "默认工号", "同步动作"], rows);
|
||
|
||
return {
|
||
stdout: `[SUCCESS] 已从 seal-use 同步 ${synced.items.length} 家企业的 OpenAPI 持久化凭证!\n${table}\n`,
|
||
stderr: "",
|
||
exitCode: 0,
|
||
};
|
||
}
|