316 lines
12 KiB
TypeScript
316 lines
12 KiB
TypeScript
import { existsSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import {
|
|
getCorpProvisionalAuthLink,
|
|
hasOpenApiPersistentCredentials,
|
|
importFromLink,
|
|
} from "../../../core/auth/login.js";
|
|
import {
|
|
DEFAULT_EKB_BASE_URL,
|
|
fetchHoseOpenApiAccessToken,
|
|
fetchHoseStaffDetails,
|
|
getCorpOpenApiCredentials,
|
|
listHoseStaffsByOpenApi,
|
|
normalizeBaseUrl,
|
|
} from "../../../core/auth/openapi-v1.js";
|
|
import { searchStaffs } from "../../../domains/contact/tools.js";
|
|
import { NotFoundError, ValidationError } from "../../../core/errors.js";
|
|
import type { CorpConfig } from "../../../core/config/types.js";
|
|
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
|
|
import { stringOption, booleanOption } from "../../parser.js";
|
|
import { prompt } from "../../helpers.js";
|
|
import { printJson, printKeyValue, 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 resolveStaffForLink(
|
|
corp: CorpConfig,
|
|
staffQuery: string
|
|
): Promise<{ staffId: string; staffName?: string }> {
|
|
const q = staffQuery.trim();
|
|
if (!q) {
|
|
throw new ValidationError("员工检索条件不能为空");
|
|
}
|
|
|
|
const corpId = corp.corpId || corp.credentials.corpId;
|
|
|
|
// 1. 如果输入本身就是完整 staffId 或 ID01 开头的工号
|
|
if (q.includes(":") || (q.startsWith("ID01") && !q.includes(" "))) {
|
|
const fullId = q.includes(":") ? q : `${corpId}:${q}`;
|
|
const openApiCreds = getCorpOpenApiCredentials(corp);
|
|
if (openApiCreds) {
|
|
try {
|
|
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
|
const openapiToken = await fetchHoseOpenApiAccessToken({
|
|
appKey: openApiCreds.appKey,
|
|
appSecurity: openApiCreds.appSecurity,
|
|
baseUrl,
|
|
});
|
|
const details = await fetchHoseStaffDetails(baseUrl, openapiToken, [fullId]);
|
|
if (details.length > 0 && details[0]?.name) {
|
|
return { staffId: fullId, staffName: details[0].name };
|
|
}
|
|
} catch {
|
|
// fallback to using fullId
|
|
}
|
|
}
|
|
return { staffId: fullId };
|
|
}
|
|
|
|
// 2. 若企业已配置 OpenAPI 密钥,优先在管理员(admin 角色)中查找
|
|
const openApiCreds = getCorpOpenApiCredentials(corp);
|
|
if (openApiCreds) {
|
|
try {
|
|
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
|
const staffRes = await listHoseStaffsByOpenApi({
|
|
appKey: openApiCreds.appKey,
|
|
appSecurity: openApiCreds.appSecurity,
|
|
domain: baseUrl,
|
|
role: "admin",
|
|
});
|
|
|
|
// 优先级 1: 姓名或手机号精确匹配
|
|
const exactMatch = staffRes.staffs.find(
|
|
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
|
|
);
|
|
if (exactMatch) {
|
|
return { staffId: exactMatch.id, staffName: exactMatch.name };
|
|
}
|
|
|
|
// 优先级 2: 姓名包含模糊匹配
|
|
const fuzzyMatch = staffRes.staffs.find((s) => s.name && s.name.includes(q));
|
|
if (fuzzyMatch) {
|
|
return { staffId: fuzzyMatch.id, staffName: fuzzyMatch.name };
|
|
}
|
|
} catch {
|
|
// 容错并回退至通讯录查询
|
|
}
|
|
}
|
|
|
|
// 3. 通道 3: 通讯录常规检索
|
|
try {
|
|
const matchedStaffs = await searchStaffs(corp, { keyword: q, limit: 10 });
|
|
if (matchedStaffs.length > 0) {
|
|
const exact = matchedStaffs.find(
|
|
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
|
|
);
|
|
const chosen = exact || matchedStaffs[0];
|
|
const normalizedId = chosen.id.includes(":") ? chosen.id : `${corpId}:${chosen.id}`;
|
|
return { staffId: normalizedId, staffName: chosen.name };
|
|
}
|
|
} catch {
|
|
// 忽略通讯录未配置异常
|
|
}
|
|
|
|
throw new NotFoundError(
|
|
`未在企业 [${corp.name}] 中找到匹配 "${q}" 的员工或管理员。请核对姓名/手机号,或直接传入完整员工工号 (staffId)。`
|
|
);
|
|
}
|
|
|
|
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 =
|
|
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
|
|
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
|
|
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
|
|
const staffInput = stringOption(parsed.options, ["staff", "user", "operator"]);
|
|
const persistStaff = booleanOption(parsed.options, ["persist", "save", "save-staff"]);
|
|
|
|
let resolvedStaff: { staffId: string; staffName?: string } | undefined;
|
|
if (staffInput) {
|
|
resolvedStaff = await resolveStaffForLink(targetCorp, staffInput);
|
|
}
|
|
|
|
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
|
|
expiresIn,
|
|
pageType,
|
|
force,
|
|
staffId: resolvedStaff?.staffId,
|
|
staffName: resolvedStaff?.staffName,
|
|
persistStaff,
|
|
});
|
|
|
|
const isSwitched = Boolean(resolvedStaff);
|
|
const persistSaved = Boolean(persistStaff && isSwitched);
|
|
|
|
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,
|
|
dynamicStaff: isSwitched,
|
|
persisted: persistSaved,
|
|
},
|
|
runtime.outputOptions
|
|
),
|
|
stderr: "",
|
|
exitCode: 0,
|
|
preserveSensitiveStdout: true,
|
|
};
|
|
}
|
|
|
|
const lines = [
|
|
`====== 合思企业 Web 免密登录直达链接 ======`,
|
|
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
|
|
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}${isSwitched ? " (🔄 动态换签)" : ""}`,
|
|
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
|
|
` 过期时间 : ${linkRes.expiresAt}`,
|
|
...(persistSaved ? [` 配置持久化: ✅ 已保存为该企业默认操作人`] : []),
|
|
` 直达链接 :`,
|
|
` ${linkRes.url}`,
|
|
``,
|
|
`Markdown 链接: [打开 ${linkRes.corpName} 合思后台](${linkRes.url})`,
|
|
];
|
|
|
|
return {
|
|
stdout: `${lines.join("\n")}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
preserveSensitiveStdout: true,
|
|
};
|
|
}
|
|
|
|
export 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: ");
|
|
}
|
|
|
|
if (!linkUrl) {
|
|
return {
|
|
stdout: "",
|
|
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--elevate] [--ttl 3d|--expires 3] [--overwrite]\n",
|
|
exitCode: 1,
|
|
};
|
|
}
|
|
|
|
let targetCorpId = "";
|
|
try {
|
|
const parsedUrl = new URL(linkUrl);
|
|
targetCorpId = parsedUrl.searchParams.get("ekbCorpId") || "";
|
|
} catch {}
|
|
|
|
const targetDir = resolveWritableEnterprisesDir();
|
|
const existsAlready = Boolean(targetCorpId && existsSync(join(targetDir, `${targetCorpId}.json`)));
|
|
|
|
if (isDryRun(parsed, runtime)) {
|
|
return mutationPreview(
|
|
parsed,
|
|
runtime,
|
|
"从协助链接导入企业凭证",
|
|
name || (targetCorpId ? `企业 [${targetCorpId}]` : "待解析企业"),
|
|
{
|
|
source: "assistance-link",
|
|
elevate: elevate ? "required" : noElevate ? "disabled" : "auto-best-effort",
|
|
overwrite,
|
|
alreadyExists: existsAlready,
|
|
ttl: ttl || null,
|
|
expires: expires || null,
|
|
note: existsAlready && !overwrite ? "检测到本地已存在该企业配置,导入执行时请带上 --overwrite 参数" : undefined,
|
|
}
|
|
);
|
|
}
|
|
|
|
const nextConfirmCmd = existsAlready && !overwrite
|
|
? `hose-use corps add-link <url> --overwrite --yes`
|
|
: `hose-use corps add-link <url> --yes`;
|
|
|
|
const confirmOp = existsAlready && !overwrite
|
|
? `从协助链接导入企业凭证(检测到目标企业 [${targetCorpId}] 已存在,需覆盖更新)`
|
|
: "从协助链接导入企业凭证";
|
|
|
|
requireMutationConfirmation(parsed, runtime, confirmOp, nextConfirmCmd);
|
|
|
|
try {
|
|
const corp = await importFromLink(linkUrl, {
|
|
name,
|
|
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 savedPath = join(targetDir, `${corp.id}.json`);
|
|
const hasOpenApi = hasOpenApiPersistentCredentials(corp);
|
|
|
|
const summaryPairs: Record<string, unknown> = {
|
|
"企业名称": corp.name,
|
|
"企业 ID": corp.id,
|
|
"集群环境": corp.cluster || "app",
|
|
"员工工号": corp.credentials.staffId,
|
|
"员工姓名": corp.staffName || corp.session?.staffName || "-",
|
|
"手机号码": corp.session?.cellphone || "-",
|
|
"是否管理": corp.session?.isAdmin ? "是" : "否",
|
|
"凭证来源": formatSourceLabel(corp.source, hasOpenApi),
|
|
"持久化密钥": hasOpenApi ? `✅ 已自动提权持久化 (appKey: ${corp.credentials.appKey})` : "⚪ 未提取到 OpenAPI 密钥 (短期会话)",
|
|
"服务节点": corp.baseUrl,
|
|
"过期时间": formatExpiresAt(corp.auth?.expiresAt || corp.session?.expTime, hasOpenApi),
|
|
"保存路径": savedPath,
|
|
};
|
|
|
|
if (corp.session?.isAssistPlatform) {
|
|
summaryPairs["协助平台"] = "是 (Assist Platform 调试授权)";
|
|
if (corp.session.operationUserName || corp.session.operationUserId) {
|
|
summaryPairs["协助操作人"] = `${corp.session.operationUserName || ""} (${corp.session.operationUserId || ""})`.trim();
|
|
}
|
|
if (corp.session.assistId) {
|
|
summaryPairs["协助会话 ID"] = corp.session.assistId;
|
|
}
|
|
}
|
|
|
|
const summaryText = printKeyValue(summaryPairs);
|
|
|
|
return {
|
|
stdout: `[SUCCESS] 成功导入并保存企业凭证!\n${summaryText}\n`,
|
|
stderr: "",
|
|
exitCode: 0,
|
|
};
|
|
} catch (error) {
|
|
return {
|
|
stdout: "",
|
|
stderr: `[ERROR] 导入协助链接失败: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
exitCode: 1,
|
|
};
|
|
}
|
|
}
|