feat(auth): support OpenAPI persistent credentials, auto-refresh, and Web login link generation (v0.8.10)

This commit is contained in:
gitea committed 2026-09-28 16:50:18 +08:00
1 parent 1d825269f4
commit 96c5a3f242
27 files changed
+2994 -583

No files matched your search

+16
View File
@@ -64,4 +64,20 @@ describe("cli/commands/auth > aliases and subcommands", () => {
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("当前登录与企业状态");
});
it("supports auth sync-seal --dry-run", async () => {
const res = await handleAuthCommand(
{
area: "auth",
action: "sync-seal",
args: [],
options: { "dry-run": true },
raw: ["auth", "sync-seal", "--dry-run"],
},
dummyRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("从 seal-use 同步企业 OpenAPI 持久化密钥");
});
});
+119 -6
View File
@@ -1,13 +1,16 @@
import {
canRefreshCorpAccessToken,
fullPasswordLogin,
fullSmsLogin,
fullBrowserSyncLogin,
hasOpenApiPersistentCredentials,
sendSmsVerificationCode,
importCredentials,
importF12Credentials,
importFromLink,
parseHeadersOrCurl,
refreshAccountCorporations,
refreshSingleCorpAccessToken,
} from "../../core/auth/login.js";
import {
listAccounts,
@@ -19,8 +22,20 @@ import { stringOption, booleanOption } from "../parser.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { prompt } from "../helpers.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
import {
handleAddPersistent,
handleElevateCorp,
handleExtractKeys,
handleGenerateCorpLink,
handleSyncFromSeal,
resolveTargetCorpByArgOrContext,
} from "./corps.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
function isHttpUrl(val?: string): boolean {
return Boolean(val && /^https?:\/\//i.test(val.trim()));
}
export async function handleAuthCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -41,9 +56,36 @@ export async function handleAuthCommand(
case "add":
return handleImport(parsed, runtime);
case "add-link":
case "link":
case "import-link":
return handleAddLink(parsed, runtime);
case "link": {
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
if (isHttpUrl(maybeUrl)) {
return handleAddLink(parsed, runtime);
}
return handleGenerateCorpLink(parsed, runtime);
}
case "hose-link":
case "auth-link":
case "login-link":
return handleGenerateCorpLink(parsed, runtime);
case "add-persistent":
case "add-hose-persistent":
case "add-openapi":
case "add-hose":
return handleAddPersistent(parsed, runtime);
case "extract-keys":
case "extract-key":
case "hose-extract-keys":
case "extract-hose-keys":
return handleExtractKeys(parsed, runtime);
case "elevate":
case "elevate-hose":
return handleElevateCorp(parsed, runtime);
case "sync-seal":
case "sync-from-seal":
case "import-seal":
return handleSyncFromSeal(parsed, runtime);
case "accounts":
case "list":
case "account":
@@ -56,7 +98,7 @@ export async function handleAuthCommand(
default:
return {
stdout: "",
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, add-link, accounts, switch-account\n`,
stderr: `未知 auth 子命令: ${action}。支持: login, status, refresh, import, link, add-link, add-persistent, extract-keys, elevate, sync-seal, accounts, switch-account\n`,
exitCode: 1,
};
}
@@ -175,6 +217,9 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
}
}
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
const isPersistent = canRefreshCorpAccessToken(currentCorp);
const statusObj = {
activeAccount: activeAccount?.accountId || null,
currentCorp: currentCorp
@@ -184,6 +229,8 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
staffId: currentCorp.credentials.staffId,
source: currentCorp.source,
accountId: currentCorp.accountId,
persistent: isPersistent,
hasOpenApiKey: hasOpenApi,
tokenValid: sessionValid,
}
: null,
@@ -199,9 +246,14 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
"当前激活企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "未配置",
"当前员工工号": currentCorp?.credentials.staffId || "-",
"员工真实姓名": currentCorp?.staffName || currentCorp?.session?.staffName || "-",
"凭证来源类型": formatSourceLabel(currentCorp?.source),
"凭证来源类型": formatSourceLabel(currentCorp?.source, hasOpenApi),
"持久化状态": isPersistent
? hasOpenApi
? `✅ OpenAPI 持久化密钥 (${currentCorp?.credentials.appKey})`
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime),
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
};
if (currentCorp?.session) {
@@ -239,6 +291,53 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
async function handleRefresh(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const accountId = stringOption(parsed.options, ["account", "a"]);
const explicitCorp = parsed.args[0] || stringOption(parsed.options, ["corp"]);
const targetCorp = explicitCorp
? resolveTargetCorpByArgOrContext(explicitCorp, runtime)
: !accountId && !getActiveAccount() && runtime.selectedCorp && canRefreshCorpAccessToken(runtime.selectedCorp)
? runtime.selectedCorp
: null;
if (targetCorp && !accountId) {
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "刷新单企业凭证", `${targetCorp.name} (${targetCorp.id})`, {
corpId: targetCorp.id,
hasOpenApiKey: hasOpenApiPersistentCredentials(targetCorp),
});
}
requireMutationConfirmation(
parsed,
runtime,
"刷新单企业凭证",
`hose-use auth refresh ${targetCorp.id} --yes`
);
const newToken = await refreshSingleCorpAccessToken(targetCorp);
if (!newToken) {
return {
stdout: "",
stderr: `刷新企业 [${targetCorp.name} (${targetCorp.id})] AccessToken 失败:缺少可用的账号凭证或 OpenAPI 持久化密钥\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson({
corpId: targetCorp.id,
corpName: targetCorp.name,
refreshed: true,
expiresAt: targetCorp.auth?.expiresAt,
}),
stderr: "",
exitCode: 0,
};
}
return {
stdout: `[SUCCESS] 成功刷新企业 [${targetCorp.name} (${targetCorp.id})] 的 AccessToken!\n`,
stderr: "",
exitCode: 0,
};
}
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "刷新账号下企业凭证", accountId || "当前账号", { saveAll: true });
}
@@ -265,10 +364,16 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"], false);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "导入并保存企业凭证", corpId || "待解析企业", {
source: raw ? "captured-input" : "manual-input",
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
overwrite,
ttl: ttl || null,
expires: expires || null,
@@ -307,6 +412,11 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
overwrite,
ttl,
expires,
appKey,
keyId,
elevate: elevate ? true : noElevate ? false : undefined,
autoElevate: !noElevate,
force,
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
});
@@ -314,6 +424,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
return { stdout: printJson(imported, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const hasOpenApi = hasOpenApiPersistentCredentials(imported);
const summaryPairs: Record<string, unknown> = {
"企业名称": imported.name,
"企业 ID": imported.id,
@@ -322,9 +434,10 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
"员工姓名": imported.staffName || imported.session?.staffName || "-",
"手机号码": imported.session?.cellphone || "-",
"是否管理": imported.session?.isAdmin ? "是" : "否",
"凭证来源": formatSourceLabel(imported.source),
"凭证来源": formatSourceLabel(imported.source, hasOpenApi),
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${imported.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
"服务节点": imported.baseUrl,
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime),
"过期时间": formatExpiresAt(imported.auth?.expiresAt || imported.session?.expTime, hasOpenApi),
"保存路径": `enterprises/${imported.id}.json`,
};
+12 -8
View File
@@ -1,4 +1,5 @@
import { getActiveAccount } from "../../core/auth/account-store.js";
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
import {
resolveGlobalConfigFile,
resolvePrimaryEnterprisesDir,
@@ -47,8 +48,9 @@ export async function handleContextCommand(
}
const now = Date.now();
const validCorps = allCorps.filter((c) => !c.expiresAt || c.expiresAt > now);
const expiredCorps = allCorps.filter((c) => c.expiresAt && c.expiresAt <= now);
const validCorps = allCorps.filter((c) => c.persistent || !c.expiresAt || c.expiresAt > now);
const expiredCorps = allCorps.filter((c) => !c.persistent && c.expiresAt && c.expiresAt <= now);
const currentPersistent = currentCorp ? canRefreshCorpAccessToken(currentCorp) : false;
if (runtime.jsonMode) {
return {
@@ -76,11 +78,13 @@ export async function handleContextCommand(
staffId: currentCorp.credentials?.staffId || currentCorp.staffId,
userName: currentCorp.staffName || currentCorp.session?.staffName || null,
source: currentCorp.source,
persistent: currentPersistent,
expiresAt: currentCorp.auth?.expiresAt || currentCorp.session?.expTime,
expired:
(currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
: false,
expired: currentPersistent
? false
: (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)
? (currentCorp.auth?.expiresAt || currentCorp.session?.expTime)! <= now
: false,
baseUrl: currentCorp.baseUrl,
accountId: currentCorp.accountId || null,
}
@@ -130,8 +134,8 @@ export async function handleContextCommand(
` 当前激活企业 : ${currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "⚠️ 未激活任何企业"}`,
` 当前操作员工 : ${corpStaffId}`,
` 员工真实姓名 : ${corpStaffName}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt) : "-"}`,
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
` AI PRO 规约库 : ${scopesStr}`,
+48
View File
@@ -315,4 +315,52 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
expect(res.stdout).toContain("search <关键词>");
expect(res.stdout).toContain("find");
});
it("generates login link via corps link [corp] with preserveSensitiveStdout=true", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () =>
new Response(JSON.stringify({ items: [] }), {
status: 200,
headers: { "content-type": "application/json" },
})) as unknown as typeof fetch;
try {
const res = await handleCorpsCommand(
{
area: "corps",
action: "link",
args: ["corpAlpha"],
options: {},
raw: ["corps", "link", "corpAlpha"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.preserveSensitiveStdout).toBe(true);
expect(res.stdout).toContain("thirdparty.html?accessToken=token-alpha&ekbCorpId=alphaPhysicalId");
} finally {
globalThis.fetch = originalFetch;
}
});
it("supports corps add-persistent --dry-run", async () => {
const res = await handleCorpsCommand(
{
area: "corps",
action: "add-persistent",
args: [],
options: {
"app-key": "key-1",
"app-security": "sec-1",
"dry-run": true,
},
raw: ["corps", "add-persistent", "--app-key=key-1", "--app-security=sec-1", "--dry-run"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("通过 OpenAPI 持久化密钥接入企业");
});
});
+626 -13
View File
@@ -1,8 +1,22 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import { importFromLink } from "../../core/auth/login.js";
import {
canRefreshCorpAccessToken,
elevateCorpWithOpenApiKey,
extractOpenApiKeysFromLink,
fetchHoseRoleDefGroups,
getCorpProvisionalAuthLink,
hasOpenApiPersistentCredentials,
importFromLink,
listHoseStaffsByOpenApi,
maskOpenApiSecurity,
onboardHosePersistent,
probeHoseDomain,
syncOpenApiFromSealUse,
} from "../../core/auth/login.js";
import { resolveWritableEnterprisesDir } from "../../core/config/loader.js";
import { stringOption, booleanOption } from "../parser.js";
import type { CorpConfig } from "../../core/config/types.js";
import { stringOption, booleanOption, numberOption } from "../parser.js";
import { prompt } from "../helpers.js";
import { printJson, printKeyValue, printTable, formatSourceLabel, formatExpiresAt } from "../printer.js";
import { isDryRun, mutationPreview, requireMutationConfirmation } from "../mutation.js";
@@ -17,6 +31,34 @@ const FIELD_LABEL_MAP: Record<string, string> = {
accountId: "所属账号",
};
function isHttpUrl(val?: string): boolean {
return Boolean(val && /^https?:\/\//i.test(val.trim()));
}
export function resolveTargetCorpByArgOrContext(
targetArg: string | undefined,
runtime: CliRuntime
): CorpConfig | null {
if (targetArg && !isHttpUrl(targetArg)) {
try {
return runtime.corpContext.resolve(targetArg);
} catch {
const allCorps = typeof runtime.corpContext.getAllCorps === "function"
? runtime.corpContext.getAllCorps()
: [];
const kw = targetArg.trim().toLowerCase();
const matched = allCorps.find(
(c) =>
c.id.toLowerCase() === kw ||
(c.corpId && c.corpId.toLowerCase() === kw) ||
c.name.toLowerCase().includes(kw)
);
if (matched) return matched;
}
}
return runtime.selectedCorp;
}
export async function handleCorpsCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -41,15 +83,46 @@ export async function handleCorpsCommand(
case "active":
return handleCurrent(parsed, runtime);
case "add-link":
case "link":
case "import-link":
return handleAddLink(parsed, runtime);
case "link": {
const maybeUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
if (isHttpUrl(maybeUrl)) {
return handleAddLink(parsed, runtime);
}
return handleGenerateCorpLink(parsed, runtime);
}
case "hose-link":
case "auth-link":
case "login-link":
return handleGenerateCorpLink(parsed, runtime);
case "add-persistent":
case "add-hose-persistent":
case "add-openapi":
case "add-hose":
return handleAddPersistent(parsed, runtime);
case "extract-keys":
case "extract-key":
case "hose-extract-keys":
case "extract-hose-keys":
return handleExtractKeys(parsed, runtime);
case "elevate":
case "elevate-hose":
return handleElevateCorp(parsed, runtime);
case "sync-seal":
case "sync-from-seal":
case "import-seal":
return handleSyncFromSeal(parsed, runtime);
case "probe-hose":
return handleProbeHose(parsed, runtime);
case "hose-staffs":
return handleHoseStaffs(parsed, runtime);
case "help":
return handleCorpsHelp();
default:
return {
stdout: "",
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, add-link\n`,
stderr: `未知 corps 子命令: ${action}。支持: list, search, switch, current, link, add-link, add-persistent, extract-keys, elevate, sync-seal\n`,
exitCode: 1,
};
}
@@ -65,7 +138,12 @@ export function printCorpsHelp(): string {
search <关键词> 根据关键词模糊搜索企业(支持 id, name, corpId, staffId, staffName, accountId,别名: find)
switch <企业ID> 切换当前激活的工作企业 (别名: use)
current 查看当前激活的企业配置与凭证详情
add-link <URL> 从第三方协助/免密链接导入企业凭证
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
elevate [企业ID] 为已登录/已导入的企业提取并持久化保存 OpenAPI 密钥
sync-seal [关键词] 从本机 seal-use 配置目录同步企业级 OpenAPI 持久化密钥
选项:
--json, -j 以 JSON 格式输出
@@ -76,6 +154,9 @@ export function printCorpsHelp(): string {
hose-use corps search 某企业
hose-use corps search 17718556446
hose-use corps switch ID01MCcOgJl1td
hose-use corps link 新转转集团
hose-use corps add-link "<url>" --elevate --yes
hose-use corps add-persistent --app-key=... --app-security=... --yes
`.trim();
}
@@ -116,6 +197,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
baseUrl: c.baseUrl,
current: c.id === runtime.selectedCorp?.id,
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
persistent: canRefreshCorpAccessToken(c),
}))
: runtime.corpContext.listCorps().map((c) => ({
id: c.id,
@@ -128,6 +210,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
baseUrl: c.baseUrl,
current: c.current || c.id === runtime.selectedCorp?.id,
expiresAt: c.expiresAt,
persistent: c.persistent,
}));
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
@@ -177,6 +260,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
baseUrl: m.baseUrl,
current: m.current,
expiresAt: m.expiresAt,
persistent: m.persistent,
matchedFields: m.matchedFields,
})),
},
@@ -206,7 +290,7 @@ async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime): Promise
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
matchLabels.map((l) => `命中${l}`).join(", "),
formatExpiresAt(m.expiresAt),
formatExpiresAt(m.expiresAt, m.persistent),
];
});
@@ -249,7 +333,7 @@ async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
c.name,
c.staffId,
c.source || "manual",
formatExpiresAt(c.expiresAt),
formatExpiresAt(c.expiresAt, c.persistent),
c.accountId || "-",
]);
@@ -307,13 +391,17 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
return { stdout: printJson(current, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const hasOpenApi = hasOpenApiPersistentCredentials(current);
const isPersistent = canRefreshCorpAccessToken(current);
const pairs: Record<string, unknown> = {
"企业 ID": current.id,
"企业名称": current.name,
"员工工号": current.credentials.staffId,
"员工姓名": current.staffName || current.session?.staffName || "-",
"凭证来源": formatSourceLabel(current.source),
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime),
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
"所属账号": current.accountId || "-",
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
@@ -352,12 +440,84 @@ async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime): Promis
};
}
export async function handleGenerateCorpLink(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const targetArg = parsed.args[0];
const targetCorp = resolveTargetCorpByArgOrContext(targetArg, runtime);
if (!targetCorp) {
return {
stdout: "",
stderr: `未找到目标企业${targetArg ? ` [${targetArg}]` : ""}。请通过 --corp=<id> 或参数指定已配置的企业。\n`,
exitCode: 1,
};
}
const expiresIn = numberOption(parsed.options, ["expire", "expires", "ttl"]) ?? 7200;
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
expiresIn,
pageType,
force,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
corpId: linkRes.corpId,
corpName: linkRes.corpName,
staffId: linkRes.staffId,
...(linkRes.staffName ? { staffName: linkRes.staffName } : {}),
link: linkRes.url,
expiresAt: linkRes.expiresAt,
expiresIn: linkRes.expiresIn,
token: linkRes.token,
persistent: linkRes.persistent,
method: linkRes.method,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: true,
};
}
const lines = [
`====== 合思企业 Web 免密登录直达链接 ======`,
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
` 过期时间 : ${linkRes.expiresAt}`,
` 直达链接 :`,
` ${linkRes.url}`,
``,
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
];
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: true,
};
}
async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
const name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
const elevate = booleanOption(parsed.options, ["elevate", "elevate-hose", "as-hose"], false);
const noElevate = booleanOption(parsed.options, ["no-elevate"], false);
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const keyId = stringOption(parsed.options, ["key-id", "keyId"]);
const force = booleanOption(parsed.options, ["force", "f"], false);
if (!linkUrl && process.stdin.isTTY && !process.env.CI && process.env.NODE_ENV !== "test") {
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
@@ -366,7 +526,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
if (!linkUrl) {
return {
stdout: "",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
exitCode: 1,
};
}
@@ -388,6 +548,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
{
source: "assistance-link",
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
overwrite,
alreadyExists: existsAlready,
ttl: ttl || null,
@@ -413,14 +574,19 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
overwrite,
ttl,
expires,
appKey,
keyId,
elevate: elevate ? true : noElevate ? false : undefined,
autoElevate: !noElevate,
force,
});
if (runtime.jsonMode) {
return { stdout: printJson(corp, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const targetDir = resolveWritableEnterprisesDir();
const savedPath = join(targetDir, `${corp.id}.json`);
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
const summaryPairs: Record<string, unknown> = {
"企业名称": corp.name,
@@ -430,9 +596,10 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
"员工姓名": corp.staffName || corp.session?.staffName || "-",
"手机号码": corp.session?.cellphone || "-",
"是否管理": corp.session?.isAdmin ? "是" : "否",
"凭证来源": formatSourceLabel(corp.source),
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
"服务节点": corp.baseUrl,
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime),
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
"保存路径": savedPath,
};
@@ -461,3 +628,449 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
};
}
}
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,
};
}
async function handleProbeHose(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
const domain = stringOption(parsed.options, ["domain", "base-url"]);
if (!appKey || !appSecurity) {
return {
stdout: "",
stderr: "用法: hose-use corps probe-hose --app-key=<key> --app-security=<secret> [--domain=<url>]\n",
exitCode: 1,
};
}
const probe = await probeHoseDomain(appKey, appSecurity, domain);
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken).catch(() => []);
const payload = {
domain: probe.domain,
corpId: probe.corpId,
name: probe.corpName || probe.corpId,
roleCount: roleGroups.reduce((acc, g) => acc + g.roleDefs.length, 0),
roleGroups,
};
if (runtime.jsonMode) {
return { stdout: printJson(payload, runtime.outputOptions), stderr: "", exitCode: 0 };
}
return {
stdout: `====== OpenAPI 域名与企业探测结果 ======\n${printKeyValue({
"企业 ID": payload.corpId,
"企业名称": payload.name,
"服务节点": payload.domain,
"角色数量": payload.roleCount,
})}\n`,
stderr: "",
exitCode: 0,
};
}
async function handleHoseStaffs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const appKey = stringOption(parsed.options, ["app-key", "appKey"]);
const appSecurity = stringOption(parsed.options, ["app-security", "appSecurity", "secret"]);
const domain = stringOption(parsed.options, ["domain", "base-url"]);
const role = stringOption(parsed.options, ["role", "roleDefId"]);
if (!appKey || !appSecurity) {
return {
stdout: "",
stderr: "用法: hose-use corps hose-staffs --app-key=<key> --app-security=<secret> [--role=admin]\n",
exitCode: 1,
};
}
const res = await listHoseStaffsByOpenApi({ appKey, appSecurity, domain, role });
if (runtime.jsonMode) {
return { stdout: printJson(res, runtime.outputOptions), stderr: "", exitCode: 0 };
}
const rows = res.staffs.map((s, i) => [i + 1, s.id, s.name, s.cellphone || "-", s.active ? "在职" : "离职"]);
return {
stdout: `====== 角色成员列表 (${res.roleName || res.roleId}) ======\n${printTable(["#", "员工 ID", "姓名", "手机号", "状态"], rows)}\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,
};
}
+78 -2
View File
@@ -1,6 +1,9 @@
import { fetchOpenApiKeys } from "../../domains/store/tools.js";
import { booleanOption } from "../parser.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 {
@@ -39,9 +42,80 @@ export async function handleKeysCommand(
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
@@ -53,6 +127,7 @@ export async function handleKeysCommand(
stdout: printJson(outputData, runtime.outputOptions),
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
}
@@ -81,12 +156,13 @@ export async function handleKeysCommand(
const title = `====== [${currentCorp.name}] 企业 OpenAPI 接入密钥列表 (共 ${keys.length} 个) ======`;
const hint = reveal
? ""
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;使用 --json 可输出完整结构。\n";
: "\n提示: 接入密码默认脱敏,附加 --reveal (或 -r) 可查看完整明文;附加 --save --yes 可持久化到当前企业配置;使用 --json 可输出完整结构。\n";
return {
stdout: `${title}\n\n${table}\n${hint}`,
stderr: "",
exitCode: 0,
preserveSensitiveStdout: reveal,
};
} catch (err: any) {
return {
+13 -2
View File
@@ -1,3 +1,4 @@
import { canRefreshCorpAccessToken, hasOpenApiPersistentCredentials } from "../../core/auth/login.js";
import { createSessionClient, getEasoClient } from "../../core/http/index.js";
import * as api from "../../domains/platform/api.js";
import { printJson, printKeyValue, formatSourceLabel, formatExpiresAt } from "../printer.js";
@@ -16,6 +17,9 @@ export async function handleProbeCommand(
};
}
const hasOpenApi = hasOpenApiPersistentCredentials(currentCorp);
const isPersistent = canRefreshCorpAccessToken(currentCorp);
const results: Record<string, unknown> = {
enterprise: {
id: currentCorp.id,
@@ -24,6 +28,8 @@ export async function handleProbeCommand(
baseUrl: currentCorp.baseUrl,
source: currentCorp.source,
accountId: currentCorp.accountId,
persistent: isPersistent,
hasOpenApiKey: hasOpenApi,
},
ekbSession: { status: "pending" },
easoToken: { status: "pending" },
@@ -98,8 +104,13 @@ export async function handleProbeCommand(
"企业 ID": currentCorp.id,
"员工工号": currentCorp.credentials.staffId,
"员工姓名": currentCorp.staffName || currentCorp.session?.staffName || "-",
"凭证来源": formatSourceLabel(currentCorp.source),
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime),
"凭证来源": formatSourceLabel(currentCorp.source, hasOpenApi),
"持久化状态": isPersistent
? hasOpenApi
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
: "✅ 统一认证主账号自动换票"
: "⚪ 短期会话",
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent),
"主站 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} 个自建应用)` : "🔴 失败",
+32 -3
View File
@@ -7,8 +7,37 @@ export interface HelpTopic {
export const HELP_REGISTRY: Record<string, HelpTopic> = {
context: { summary: "全局运行上下文与身份诊断", usage: "hose-use context [--json]", commands: { context: "输出当前企业、账号、运行模式与认证状态" } },
auth: { summary: "认证与凭证管理", usage: "hose-use auth <子命令>", commands: { login: "登录并保存企业凭证", status: "查看当前认证状态", accounts: "列出已保存账号", "switch-account": "切换默认账号" } },
corps: { summary: "多企业租户管理", usage: "hose-use corps <子命令>", commands: { list: "列出本地企业配置", search: "搜索企业与员工", switch: "切换当前工作企业", current: "查看当前企业", "add-link": "从链接导入企业凭证" } },
auth: {
summary: "认证与凭证管理(支持主账号登录与企业级 OpenAPI 持久化)",
usage: "hose-use auth <子命令>",
commands: {
login: "登录并保存企业凭证",
status: "查看当前认证状态",
refresh: "刷新账号或企业 AccessToken",
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
"add-link": "从协助链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
"add-persistent": "通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业",
"extract-keys": "从协助链接提取 OpenAPI 密钥",
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
accounts: "列出已保存账号",
"switch-account": "切换默认账号",
},
},
corps: {
summary: "多企业租户管理",
usage: "hose-use corps <子命令>",
commands: {
list: "列出本地企业配置",
search: "搜索企业与员工",
switch: "切换当前工作企业",
current: "查看当前企业",
link: "生成企业 Web 免密登录直达链接 (别名: hose-link)",
"add-link": "从链接导入企业凭证(自动探测并持久化 OpenAPI 密钥)",
"add-persistent": "通过 OpenAPI 密钥持久化接入企业",
"extract-keys": "从协助链接提取 OpenAPI 密钥",
elevate: "为已配置企业提取并持久化保存 OpenAPI 密钥",
},
},
config: { summary: "全局运行模式与路径配置", usage: "hose-use config <子命令>", commands: { paths: "诊断配置目录链", get: "查看全局配置", mode: "切换 stateful/stateless", set: "更新指定配置项" } },
workflow: { summary: "工作流查询、草稿与生命周期管理", usage: "hose-use workflow <子命令> [参数] [选项]", commands: { list: "列出工作流", get: "查看工作流详情", find: "按节点类型搜索", analyze: "静态分析工作流", patch: "生成草稿字段补丁", save: "保存草稿到远端", toggle: "切换启停状态", publish: "发布并启用工作流", history: "查看版本历史", logs: "查看运行日志", check: "检查错误管道" }, options: ["--dry-run 只预览写操作", "--yes/--confirm 确认写操作", "--file=<workflow.json> 指定工作流快照"] },
bill: { summary: "单据检索与审批动作", usage: "hose-use bill <子命令> [单号|ID] [选项]", commands: { list: "查询单据", get: "查看单据详情", flow: "查看审批流程", approve: "同意审批", reject: "驳回审批", transfer: "转交审批", "add-node": "加签审批", comment: "添加评论" }, options: ["--dry-run 只预览审批动作", "--yes/--confirm 确认执行审批动作", "--comment=<原因> 驳回或评论内容"] },
@@ -25,7 +54,7 @@ export const HELP_REGISTRY: Record<string, HelpTopic> = {
app: { summary: "桌面端工作台应用管理", usage: "hose-use app <子命令>", commands: { list: "列出应用", get: "查看应用详情" } },
menu: { summary: "桌面端主导航菜单树", usage: "hose-use menu list", commands: { list: "查看主导航", apps: "查看应用入口" } },
openapi: { summary: "OpenAPI 规范导出与路径查询", usage: "hose-use openapi [paths|info|--raw|keys]", commands: { paths: "列出路径概要", info: "查看规范元数据", keys: "查看企业接入密钥" } },
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文"] },
keys: { summary: "企业 OpenAPI 接入凭证", usage: "hose-use keys [--json] [--reveal] [--save]", commands: { keys: "读取当前企业密钥(默认脱敏)" }, options: ["--reveal 仅在明确授权后查看明文", "--save --yes 提取并持久化保存到本地企业配置"] },
store: { summary: "已购应用与应用商店探查", usage: "hose-use store <list|search|get>", commands: { list: "列出已购应用", search: "搜索应用商店", get: "查看应用详情" } },
update: { summary: "版本自更新与发布记录", usage: "hose-use update [check|--changelog]", commands: { update: "检查并升级版本", check: "只检查可用版本", changelog: "查看发布记录" } },
skill: { summary: "Agent Skill 管理", usage: "hose-use skill <install|status|dump>", commands: { install: "安装内嵌 Skill", status: "查看安装状态", dump: "导出 Skill 文件" } },
+17 -11
View File
@@ -41,40 +41,46 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
return json;
}
export function formatSourceLabel(source?: string): string {
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : "";
switch (source) {
case "openapi":
return "开放平台持久化密钥 (OpenAPI AppKey)";
case "assist":
return "官方协助/代客平台 (Assist Platform)";
return `官方协助/代客平台 (Assist Platform)${suffix}`;
case "account":
return "统一认证中心 (IDP 账密/短信)";
return `统一认证中心 (IDP 账密/短信)${suffix}`;
case "browser":
return "浏览器会话同步 (WebBridge)";
return `浏览器会话同步 (WebBridge)${suffix}`;
case "link":
return "协助/免密链接导入 (Assistance Link)";
return `协助/免密链接导入 (Assistance Link)${suffix}`;
case "curl":
case "f12":
return "cURL 抓包导入 (cURL/F12)";
return `cURL 抓包导入 (cURL/F12)${suffix}`;
case "manual":
return "手动配置";
return `手动配置${suffix}`;
default:
return source || "未知来源";
return (source || "未知来源") + suffix;
}
}
export function formatExpiresAt(expiresAt?: number | null): string {
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string {
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
const diffMs = expiresAt - Date.now();
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
if (diffMs <= 0) {
if (persistent) {
return `${dateStr} (🔄 持久化密钥自动续期)`;
}
return `${dateStr} (⚠️ 已过期)`;
}
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) {
return `${dateStr} (约剩余 ${diffMins} 分钟)`;
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`;
}
const diffHours = (diffMs / 3600000).toFixed(1);
if (Number(diffHours) < 24) {
return `${dateStr} (约剩余 ${diffHours} 小时)`;
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`;
}
const diffDays = Math.floor(diffMs / 86400000);
return `${dateStr} (约剩余 ${diffDays} 天)`;
+5 -1
View File
@@ -82,10 +82,14 @@ async function runCliOnce(
const result = await dispatchCli(rawArgs, options);
const extraStdout = stdoutChunks.length ? `${stdoutChunks.join("\n")}\n` : "";
const extraStderr = stderrChunks.length ? `${stderrChunks.join("\n")}\n` : "";
const bodyStdout = result.preserveSensitiveStdout
? result.stdout || ""
: redactSensitiveText(result.stdout || "");
return {
stdout: redactSensitiveText(extraStdout + (result.stdout || "")),
stdout: redactSensitiveText(extraStdout) + bodyStdout,
stderr: redactSensitiveText(extraStderr + (result.stderr || "")),
exitCode: result.exitCode,
preserveSensitiveStdout: result.preserveSensitiveStdout,
};
} finally {
console.log = originalLog;
+1
View File
@@ -22,6 +22,7 @@ export interface CliResult {
stdout: string;
stderr: string;
exitCode: number;
preserveSensitiveStdout?: boolean;
}
export interface OutputOptions {