refactor(auth,config): split 2260-line login.ts into focused modules and normalize CorpConfig fields
This commit is contained in:
1 parent
2d744d283b
commit
2b220bc5d9
7 files changed
+1786
-1661
No files matched your search
@@ -0,0 +1,612 @@
|
||||
import ky from "ky";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig, CredentialSource } from "../config/types.js";
|
||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster, clearUnityClientCache } from "../http/unity-client.js";
|
||||
import { clearScriptEngineClientCache } from "../http/script-engine-client.js";
|
||||
import { clearCorpTokens } from "./token-store.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
HoseOpenApiKeyItem,
|
||||
fetchOpenApiKeysBySession,
|
||||
selectOpenApiKey,
|
||||
} from "./openapi-v1.js";
|
||||
|
||||
// ── 模式 4:F12 / cURL / 手动直接导入单企业凭证 ───────────────────────────────
|
||||
|
||||
export interface F12ImportParams {
|
||||
accessToken: string;
|
||||
corpId: string;
|
||||
staffId?: string;
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
cluster?: string;
|
||||
source?: CredentialSource;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
keyId?: string;
|
||||
elevate?: boolean;
|
||||
autoElevate?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
export interface ImportFromLinkOptions {
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
enterprisesDir?: string;
|
||||
overwrite?: boolean;
|
||||
ttl?: string | number;
|
||||
expires?: string | number;
|
||||
appKey?: string;
|
||||
appSecurity?: string;
|
||||
keyId?: string;
|
||||
elevate?: boolean;
|
||||
autoElevate?: boolean;
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
|
||||
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2];
|
||||
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
|
||||
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
export function resolveLinkExpiresAt(
|
||||
options: { ttl?: string | number; expires?: string | number },
|
||||
baseTime = Date.now()
|
||||
): number | undefined {
|
||||
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
|
||||
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseExpiresInSeconds(
|
||||
value?: string | number,
|
||||
fallbackSeconds = 7200
|
||||
): number {
|
||||
if (value === undefined || value === null || String(value).trim() === "") {
|
||||
return fallbackSeconds;
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new AuthenticationError(`有效期秒数必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
return Math.round(value);
|
||||
}
|
||||
const raw = String(value).trim().toLowerCase();
|
||||
const match = raw.match(
|
||||
/^(\d+(?:\.\d+)?)\s*(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days)?$/
|
||||
);
|
||||
if (!match) {
|
||||
throw new AuthenticationError(
|
||||
`无效的有效期参数: ${value}(支持秒数如 86400,或带单位如 30m、24h、3d)`
|
||||
);
|
||||
}
|
||||
const amount = Number(match[1]);
|
||||
if (!Number.isFinite(amount) || amount <= 0) {
|
||||
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
|
||||
}
|
||||
const unit = match[2] || "s";
|
||||
if (["s", "sec", "secs", "second", "seconds"].includes(unit)) {
|
||||
return Math.round(amount);
|
||||
}
|
||||
if (["m", "min", "mins", "minute", "minutes"].includes(unit)) {
|
||||
return Math.round(amount * 60);
|
||||
}
|
||||
if (["h", "hr", "hrs", "hour", "hours"].includes(unit)) {
|
||||
return Math.round(amount * 3600);
|
||||
}
|
||||
return Math.round(amount * 86400);
|
||||
}
|
||||
|
||||
export function invalidateCorpSubdomainTokenCaches(corp: CorpConfig): void {
|
||||
try {
|
||||
const keys = new Set<string>(
|
||||
[corp.id, corp.corpId, corp.credentials?.corpId].filter((v): v is string => Boolean(v))
|
||||
);
|
||||
for (const key of keys) {
|
||||
clearCorpTokens(key);
|
||||
clearUnityClientCache(key);
|
||||
clearScriptEngineClientCache(key);
|
||||
}
|
||||
} catch {
|
||||
// Ignore cache cleanup errors in restricted environments
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析从 F12 抓包复制出来的 Request Headers、cURL 命令或 URL 字符串
|
||||
*/
|
||||
export function parseHeadersOrCurl(rawInput: string): Partial<F12ImportParams> {
|
||||
const result: Partial<F12ImportParams> = {};
|
||||
if (!rawInput) return result;
|
||||
|
||||
// 0. 尝试匹配完整 URL(包含 http:// 或 https://)
|
||||
const urlMatch = /(https?:\/\/[^\s"'<>]+)/i.exec(rawInput);
|
||||
if (urlMatch) {
|
||||
try {
|
||||
const parsedUrl = new URL(urlMatch[1]);
|
||||
result.baseUrl = `${parsedUrl.protocol}//${parsedUrl.host}`;
|
||||
const tokenParam =
|
||||
parsedUrl.searchParams.get("accessToken") ||
|
||||
parsedUrl.searchParams.get("token");
|
||||
if (tokenParam) result.accessToken = tokenParam;
|
||||
const corpParam =
|
||||
parsedUrl.searchParams.get("ekbCorpId") ||
|
||||
parsedUrl.searchParams.get("corpId") ||
|
||||
parsedUrl.searchParams.get("corporationId");
|
||||
if (corpParam) result.corpId = corpParam;
|
||||
const staffParam = parsedUrl.searchParams.get("staffId");
|
||||
if (staffParam) result.staffId = staffParam;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// 1. 尝试匹配各种 -H / --header 参数:-H 'header: value' 或 -H "header: value"
|
||||
const headerRegex = /(?:-H|--header)\s+['"]([^'"]+)['"]/gi;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = headerRegex.exec(rawInput)) !== null) {
|
||||
const headerStr = match[1];
|
||||
const colonIdx = headerStr.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const key = headerStr.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
|
||||
const val = headerStr.slice(colonIdx + 1).trim();
|
||||
if (key === "accesstoken") result.accessToken = val;
|
||||
if (key === "corpid" || key === "corporationid") result.corpId = val;
|
||||
if (key === "staffid") result.staffId = val;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 逐行匹配标准 HTTP Headers (如 accesstoken: xxx)
|
||||
const lines = rawInput.split("\n");
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
const colonIdx = trimmed.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const key = trimmed.slice(0, colonIdx).trim().toLowerCase().replace(/[^a-z]/g, "");
|
||||
const val = trimmed.slice(colonIdx + 1).trim().replace(/^['"]|['"]$/g, "");
|
||||
if (key === "accesstoken" && !result.accessToken) result.accessToken = val;
|
||||
if ((key === "corpid" || key === "corporationid") && !result.corpId) result.corpId = val;
|
||||
if (key === "staffid" && !result.staffId) result.staffId = val;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 从 URL/Query 中提取 query 参数(例如 ?corpId=xxx 或 &corpId=xxx 或 ekbCorpId=xxx)
|
||||
if (!result.corpId) {
|
||||
const urlCorpMatch = /(?:[?&](?:ekbCorpId|corpId|corporationId)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlCorpMatch) {
|
||||
result.corpId = decodeURIComponent(urlCorpMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.accessToken) {
|
||||
const urlTokenMatch = /(?:[?&](?:accessToken|token)=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlTokenMatch) {
|
||||
result.accessToken = decodeURIComponent(urlTokenMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.staffId) {
|
||||
const urlStaffMatch = /(?:[?&]staffId=)([^&'"\s]+)/i.exec(rawInput);
|
||||
if (urlStaffMatch) {
|
||||
result.staffId = decodeURIComponent(urlStaffMatch[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 从 Cookie (-b / Cookie header) 中提取 ekb-access-token 或 corpId
|
||||
if (!result.accessToken) {
|
||||
const cookieTokenMatch = /ekb-access-token=([^;'"\s]+)/i.exec(rawInput);
|
||||
if (cookieTokenMatch) {
|
||||
result.accessToken = decodeURIComponent(cookieTokenMatch[1]);
|
||||
}
|
||||
}
|
||||
if (!result.corpId) {
|
||||
const cookieCorpMatch = /(?:^|;\s*)corpId=([^;'"\s]+)/i.exec(rawInput);
|
||||
if (cookieCorpMatch) {
|
||||
result.corpId = decodeURIComponent(cookieCorpMatch[1]);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并导入单个抓包/手动凭证,自动探测官方 Session 平台类型并保存到企业配置
|
||||
*/
|
||||
export async function importCredentials(
|
||||
params: F12ImportParams
|
||||
): Promise<CorpConfig> {
|
||||
const { accessToken, corpId } = params;
|
||||
let staffId = params.staffId;
|
||||
const baseUrl = params.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("导入凭证失败:accessToken 与 corpId 均为必填项");
|
||||
}
|
||||
|
||||
// 检查已存在保护:当明确要求不覆盖 (overwrite === false) 且文件已存在时拦截
|
||||
const targetDir = params.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${corpId}.json`);
|
||||
if (params.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
// 1. 若 staffId 缺失,优先通过 $UNITY JWT 自动探测 staffId、企业名与身份
|
||||
let corpName = params.name;
|
||||
let staffName: string | undefined;
|
||||
let cellphone: string | undefined;
|
||||
let isAdmin: boolean | undefined;
|
||||
let sourceChannel: string | undefined;
|
||||
let jwtExpMs: number | undefined;
|
||||
const requestedExpiresAt = resolveLinkExpiresAt(params);
|
||||
|
||||
try {
|
||||
const jwtHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
jwtHeaders.staffid = staffId;
|
||||
}
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: jwtHeaders,
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
const token = jwtRes.id || jwtRes.value;
|
||||
if (token) {
|
||||
const parts = token.split(".");
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1], "base64").toString("utf-8"));
|
||||
if (!staffId && payload.staffId) {
|
||||
staffId = payload.staffId;
|
||||
}
|
||||
if (!corpName && payload.corporationName) {
|
||||
corpName = payload.corporationName;
|
||||
}
|
||||
if (payload.staffName) {
|
||||
staffName = payload.staffName;
|
||||
}
|
||||
if (payload.cellphone) {
|
||||
cellphone = payload.cellphone;
|
||||
}
|
||||
if (payload.isAdmin !== undefined) {
|
||||
isAdmin = payload.isAdmin === "true" || payload.isAdmin === true;
|
||||
}
|
||||
if (payload.sourceChannel) {
|
||||
sourceChannel = payload.sourceChannel;
|
||||
}
|
||||
if (payload.exp) {
|
||||
jwtExpMs = Number(payload.exp) * 1000;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 探测失败则继续后续降级流程
|
||||
}
|
||||
|
||||
// 2. 验证凭证有效性并提取官方服务端 Session 元数据
|
||||
let sessionData: {
|
||||
id?: string;
|
||||
userId?: string;
|
||||
loginStaffId?: string;
|
||||
corporationId?: string;
|
||||
platform?: string;
|
||||
isAssistPlatform?: boolean;
|
||||
isShortTermToken?: boolean;
|
||||
assistId?: string;
|
||||
operationUserId?: string;
|
||||
operationUserName?: string;
|
||||
privilege?: string;
|
||||
deviceType?: string;
|
||||
loginAccountType?: string;
|
||||
loginTime?: number;
|
||||
expTime?: number;
|
||||
} | undefined;
|
||||
|
||||
try {
|
||||
const sessionHeaders: Record<string, string> = {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
};
|
||||
if (staffId) {
|
||||
sessionHeaders.staffid = staffId;
|
||||
}
|
||||
const res = await ky
|
||||
.get(`${baseUrl}/api/account/v2/session`, {
|
||||
headers: sessionHeaders,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
id?: string;
|
||||
userId?: string;
|
||||
loginStaffId?: string;
|
||||
corporationId?: string;
|
||||
platform?: string;
|
||||
isAssistPlatform?: boolean;
|
||||
isShortTermToken?: boolean;
|
||||
assistId?: string;
|
||||
operationUserId?: string;
|
||||
operationUserName?: string;
|
||||
privilege?: string;
|
||||
deviceType?: string;
|
||||
loginAccountType?: string;
|
||||
loginTime?: number;
|
||||
expTime?: number;
|
||||
};
|
||||
}>();
|
||||
|
||||
sessionData = res.value;
|
||||
if (!sessionData || (!sessionData.corporationId && !sessionData.id && !sessionData.userId)) {
|
||||
throw new Error("服务端未返回有效 Session");
|
||||
}
|
||||
|
||||
if (!staffId && sessionData.loginStaffId) {
|
||||
staffId = sessionData.loginStaffId;
|
||||
}
|
||||
if (!staffName && sessionData.privilege) {
|
||||
staffName = sessionData.privilege;
|
||||
}
|
||||
} catch (err) {
|
||||
throw new AuthenticationError(`凭证校验失败,请检查 token 是否已过期: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
|
||||
// 兜底 staffId:若依然为空,退化为 corpId:admin
|
||||
if (!staffId) {
|
||||
staffId = `${corpId}:admin`;
|
||||
}
|
||||
|
||||
// 3. 自动或显式提取 OpenAPI 密钥实现持久化提权 (appKey + appSecurity)
|
||||
let resolvedAppKey = params.appKey;
|
||||
let resolvedAppSecurity = params.appSecurity;
|
||||
|
||||
if ((!resolvedAppKey || !resolvedAppSecurity) && params.elevate !== false && params.autoElevate !== false) {
|
||||
if (params.elevate === true || params.keyId || (params.appKey && !params.appSecurity)) {
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
const selected = selectOpenApiKey(keys, corpId, {
|
||||
appKey: params.appKey,
|
||||
keyId: params.keyId,
|
||||
force: params.force,
|
||||
});
|
||||
resolvedAppKey = selected.appKey;
|
||||
resolvedAppSecurity = selected.appSecurity;
|
||||
} else {
|
||||
// 默认最佳努力自动提权:若当前身份可读取 OpenAPI 密钥则自动挂载持久化
|
||||
try {
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
if (keys.length > 0) {
|
||||
const picked = keys.find((k) => k.active !== false) ?? keys[0];
|
||||
if (picked) {
|
||||
resolvedAppKey = picked.appKey;
|
||||
resolvedAppSecurity = picked.appSecurity;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 无权限或未开通开放平台时静默降级为普通会话
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 智能判断语义化凭证来源与集群环境
|
||||
let source: CredentialSource = params.source || "curl";
|
||||
if (!params.source) {
|
||||
if (sessionData?.isAssistPlatform || sessionData?.platform === "ASSIST") {
|
||||
source = "assist";
|
||||
}
|
||||
}
|
||||
|
||||
const cluster = params.cluster || resolveCorpCluster({ cluster: params.cluster, baseUrl });
|
||||
|
||||
// 5. 计算 Token 过期时间戳 (ms)
|
||||
let expiresAt: number | undefined;
|
||||
if (sessionData?.expTime && sessionData.expTime > 0) {
|
||||
expiresAt = sessionData.expTime;
|
||||
} else if (jwtExpMs && jwtExpMs > 0) {
|
||||
expiresAt = jwtExpMs;
|
||||
} else if (requestedExpiresAt) {
|
||||
expiresAt = requestedExpiresAt;
|
||||
}
|
||||
|
||||
const corpConfig: CorpConfig = {
|
||||
id: corpId,
|
||||
name: corpName || `企业-${corpId}`,
|
||||
baseUrl,
|
||||
cluster,
|
||||
source,
|
||||
staffName,
|
||||
credentials: {
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
...(resolvedAppKey && resolvedAppSecurity
|
||||
? {
|
||||
appKey: resolvedAppKey,
|
||||
appSecurity: resolvedAppSecurity,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
expiresAt,
|
||||
},
|
||||
session: {
|
||||
platform: sessionData?.platform,
|
||||
isAssistPlatform: sessionData?.isAssistPlatform,
|
||||
isShortTermToken: sessionData?.isShortTermToken,
|
||||
assistId: sessionData?.assistId,
|
||||
operationUserId: sessionData?.operationUserId,
|
||||
operationUserName: sessionData?.operationUserName,
|
||||
staffName,
|
||||
cellphone,
|
||||
isAdmin,
|
||||
deviceType: sessionData?.deviceType,
|
||||
loginAccountType: sessionData?.loginAccountType,
|
||||
loginTime: sessionData?.loginTime,
|
||||
expTime: expiresAt || sessionData?.expTime,
|
||||
sourceChannel,
|
||||
},
|
||||
};
|
||||
|
||||
saveCorpConfig(corpConfig, params.enterprisesDir);
|
||||
return corpConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接通过第三方协助/免密链接 (thirdparty.html / assistance link) 一键导入企业
|
||||
*/
|
||||
export async function importFromLink(
|
||||
linkUrl: string,
|
||||
options: ImportFromLinkOptions = {}
|
||||
): Promise<CorpConfig> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = options.baseUrl || parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 accessToken 参数");
|
||||
}
|
||||
if (!corpId) {
|
||||
throw new AuthenticationError("未能从提供的链接中提取到 ekbCorpId 或 corpId 参数");
|
||||
}
|
||||
|
||||
return await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId: parsed.staffId,
|
||||
name: options.name,
|
||||
baseUrl,
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
overwrite: options.overwrite,
|
||||
source: "link",
|
||||
ttl: options.ttl,
|
||||
expires: options.expires,
|
||||
appKey: options.appKey,
|
||||
appSecurity: options.appSecurity,
|
||||
keyId: options.keyId,
|
||||
elevate: options.elevate,
|
||||
autoElevate: options.autoElevate,
|
||||
force: options.force,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 从协助链接提取 OpenAPI 密钥列表(可选保存为持久化企业配置)
|
||||
*/
|
||||
export async function extractOpenApiKeysFromLink(
|
||||
linkUrl: string,
|
||||
options: {
|
||||
save?: boolean;
|
||||
name?: string;
|
||||
overwrite?: boolean;
|
||||
force?: boolean;
|
||||
appKey?: string;
|
||||
keyId?: string;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
corpName?: string;
|
||||
baseUrl: string;
|
||||
staffId: string;
|
||||
keys: HoseOpenApiKeyItem[];
|
||||
selectedKey?: HoseOpenApiKeyItem;
|
||||
savedCorp?: CorpConfig;
|
||||
}> {
|
||||
const parsed = parseHeadersOrCurl(linkUrl);
|
||||
const accessToken = parsed.accessToken;
|
||||
const corpId = parsed.corpId;
|
||||
const baseUrl = parsed.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
if (!accessToken || !corpId) {
|
||||
throw new AuthenticationError("无效的合思协助链接:缺少 accessToken 或 ekbCorpId 参数");
|
||||
}
|
||||
|
||||
let staffId = parsed.staffId;
|
||||
let corpName = options.name;
|
||||
|
||||
try {
|
||||
const jwtRes = await ky
|
||||
.get(`${baseUrl}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: { accesstoken: accessToken, corpid: corpId },
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
const token = jwtRes.id || jwtRes.value;
|
||||
if (token) {
|
||||
const parts = token.split(".");
|
||||
if (parts.length >= 2) {
|
||||
const payload = JSON.parse(Buffer.from(parts[1]!, "base64").toString("utf-8"));
|
||||
if (!staffId && payload.staffId) staffId = payload.staffId;
|
||||
if (!corpName && payload.corporationName) corpName = payload.corporationName;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
if (!staffId) staffId = `${corpId}:admin`;
|
||||
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken,
|
||||
});
|
||||
|
||||
if (!options.save) {
|
||||
return { corpId, corpName, baseUrl, staffId, keys };
|
||||
}
|
||||
|
||||
const selectedKey = selectOpenApiKey(keys, corpId, {
|
||||
appKey: options.appKey,
|
||||
keyId: options.keyId,
|
||||
force: options.force,
|
||||
});
|
||||
|
||||
const savedCorp = await importCredentials({
|
||||
accessToken,
|
||||
corpId,
|
||||
staffId,
|
||||
name: corpName,
|
||||
baseUrl,
|
||||
overwrite: options.overwrite ?? true,
|
||||
source: "link",
|
||||
enterprisesDir: options.enterprisesDir,
|
||||
appKey: selectedKey.appKey,
|
||||
appSecurity: selectedKey.appSecurity,
|
||||
autoElevate: false,
|
||||
});
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: savedCorp.name,
|
||||
baseUrl,
|
||||
staffId: savedCorp.credentials.staffId,
|
||||
keys,
|
||||
selectedKey,
|
||||
savedCorp,
|
||||
};
|
||||
}
|
||||
|
||||
// 保持历史命名兼容
|
||||
export const importF12Credentials = importCredentials;
|
||||
+18
-1648
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,523 @@
|
||||
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig, CorpConfigSchema } from "../config/types.js";
|
||||
import { saveCorpConfig, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||||
import { resolveCorpCluster } from "../http/unity-client.js";
|
||||
import {
|
||||
DEFAULT_EKB_BASE_URL,
|
||||
HoseOpenApiKeyItem,
|
||||
canRefreshCorpAccessToken,
|
||||
fetchHoseOpenApiAccessToken,
|
||||
fetchHoseProvisionalAuth,
|
||||
fetchHoseRoleDefGroups,
|
||||
fetchHoseRoleStaffs,
|
||||
fetchHoseStaffDetails,
|
||||
fetchOpenApiKeysBySession,
|
||||
formatBeijingIso,
|
||||
getCorpOpenApiCredentials,
|
||||
hasOpenApiPersistentCredentials,
|
||||
normalizeBaseUrl,
|
||||
probeHoseDomain,
|
||||
selectOpenApiKey,
|
||||
} from "./openapi-v1.js";
|
||||
import {
|
||||
importCredentials,
|
||||
invalidateCorpSubdomainTokenCaches,
|
||||
parseExpiresInSeconds,
|
||||
} from "./link-import.js";
|
||||
import { refreshSingleCorpAccessToken } from "./login.js";
|
||||
|
||||
export interface OnboardHosePersistentParams {
|
||||
id?: string;
|
||||
name?: string;
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
domain?: string;
|
||||
baseUrl?: string;
|
||||
corpId?: string;
|
||||
staffId?: string;
|
||||
staffName?: string;
|
||||
staffPhone?: string;
|
||||
role?: string;
|
||||
force?: boolean;
|
||||
overwrite?: boolean;
|
||||
enterprisesDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过开放平台持久化密钥 (appKey + appSecurity) 自动探测域名、管理员并导入企业配置
|
||||
*/
|
||||
export async function onboardHosePersistent(
|
||||
input: OnboardHosePersistentParams
|
||||
): Promise<CorpConfig> {
|
||||
const explicitDomain = input.domain || input.baseUrl;
|
||||
const probe = await probeHoseDomain(input.appKey, input.appSecurity, explicitDomain);
|
||||
const domain = probe.domain;
|
||||
const corpId = input.corpId || probe.corpId;
|
||||
let corpName = input.name || probe.corpName;
|
||||
let staffId = input.staffId;
|
||||
let staffName = input.staffName;
|
||||
|
||||
const targetDir = input.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
const targetFile = join(targetDir, `${input.id || corpId}.json`);
|
||||
if (input.overwrite === false && existsSync(targetFile)) {
|
||||
throw new AuthenticationError(`企业 [${input.id || corpId}] 配置文件已存在。若要更新覆盖,请附加 --overwrite 参数。`);
|
||||
}
|
||||
|
||||
if (!staffId) {
|
||||
const roleQuery = input.role ?? "admin";
|
||||
const roleGroups = await fetchHoseRoleDefGroups(domain, probe.openapiToken).catch(() => []);
|
||||
let targetRoleId: string | undefined;
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id.endsWith(`:${roleQuery}`) || role.name === roleQuery || role.id === roleQuery) {
|
||||
targetRoleId = role.id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleId) break;
|
||||
}
|
||||
if (!targetRoleId) {
|
||||
targetRoleId = roleGroups
|
||||
.find((group) => group.roleDefs.some((role) => role.id.endsWith(":admin")))
|
||||
?.roleDefs.find((role) => role.id.endsWith(":admin"))?.id;
|
||||
}
|
||||
|
||||
if (targetRoleId) {
|
||||
const roleStaffs = await fetchHoseRoleStaffs(domain, probe.openapiToken, targetRoleId).catch(() => ({ staffs: [] }));
|
||||
const staffDetails = await fetchHoseStaffDetails(domain, probe.openapiToken, roleStaffs.staffs).catch(() => []);
|
||||
if (input.staffName || input.staffPhone) {
|
||||
const matches = staffDetails.filter((staff) => {
|
||||
if (input.staffName && staff.name !== input.staffName && !staff.name.includes(input.staffName)) return false;
|
||||
if (input.staffPhone && (!staff.cellphone || !staff.cellphone.includes(input.staffPhone))) return false;
|
||||
return true;
|
||||
});
|
||||
if (matches.length === 1 && matches[0]) {
|
||||
staffId = matches[0].id;
|
||||
staffName = matches[0].name;
|
||||
} else if (matches.length > 1) {
|
||||
throw new AuthenticationError(
|
||||
`匹配到多位管理员候选人 (${matches.map((s) => `${s.name}[${s.id}]`).join(", ")}),请通过 --staff-id 精确指定。`
|
||||
);
|
||||
} else {
|
||||
throw new AuthenticationError(
|
||||
`未找到匹配 '${input.staffName ?? input.staffPhone}' 的管理员,请检查姓名/手机号或显式指定 --staff-id。`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const activeStaffs = staffDetails.filter((s) => s.active);
|
||||
if (staffDetails.length === 1 && staffDetails[0]) {
|
||||
staffId = staffDetails[0].id;
|
||||
staffName = staffDetails[0].name;
|
||||
} else if (activeStaffs.length === 1 && activeStaffs[0]) {
|
||||
staffId = activeStaffs[0].id;
|
||||
staffName = activeStaffs[0].name;
|
||||
} else if (input.force && (activeStaffs[0] || staffDetails[0])) {
|
||||
const picked = activeStaffs[0] ?? staffDetails[0]!;
|
||||
staffId = picked.id;
|
||||
staffName = picked.name;
|
||||
} else if (staffDetails.length > 1) {
|
||||
const candidates = staffDetails.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
cellphone: s.cellphone ? s.cellphone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : undefined,
|
||||
active: s.active,
|
||||
}));
|
||||
throw new AuthenticationError(
|
||||
`检测到多位主管理员候选人,请通过 --staff-id、--staff-name 指定,或追加 --force 自动选择第一位在职管理员: ${JSON.stringify(candidates)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!staffId) {
|
||||
throw new AuthenticationError(
|
||||
"缺少员工工号 (staffId),且未能从主管理员角色自动发现,请通过 --staff-id 显式指定。"
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedStaffId = staffId.includes(":") ? staffId : `${corpId}:${staffId}`;
|
||||
|
||||
// 使用 getProvisionalAuth 签发初始会话并走 importCredentials 完整探测企业全称与 Session 元数据
|
||||
const provisional = await fetchHoseProvisionalAuth({
|
||||
baseUrl: domain,
|
||||
openapiToken: probe.openapiToken,
|
||||
corpId,
|
||||
staffId: normalizedStaffId,
|
||||
expiresIn: 7200,
|
||||
});
|
||||
|
||||
const imported = await importCredentials({
|
||||
accessToken: provisional.token,
|
||||
corpId,
|
||||
staffId: normalizedStaffId,
|
||||
name: corpName,
|
||||
baseUrl: domain,
|
||||
source: "openapi",
|
||||
enterprisesDir: input.enterprisesDir,
|
||||
overwrite: true,
|
||||
appKey: input.appKey,
|
||||
appSecurity: input.appSecurity,
|
||||
autoElevate: false,
|
||||
});
|
||||
|
||||
if (staffName && !imported.staffName) {
|
||||
imported.staffName = staffName;
|
||||
saveCorpConfig(imported, input.enterprisesDir);
|
||||
}
|
||||
|
||||
return imported;
|
||||
}
|
||||
|
||||
export interface SyncFromSealUseOptions {
|
||||
filter?: string;
|
||||
sealEnterprisesDir?: string;
|
||||
enterprisesDir?: string;
|
||||
verify?: boolean;
|
||||
overwrite?: boolean;
|
||||
}
|
||||
|
||||
export interface SyncFromSealUseItemResult {
|
||||
corpId: string;
|
||||
name: string;
|
||||
appKey: string;
|
||||
domain: string;
|
||||
staffId: string;
|
||||
action: "merged" | "created" | "skipped";
|
||||
}
|
||||
|
||||
export async function syncOpenApiFromSealUse(
|
||||
options: SyncFromSealUseOptions = {}
|
||||
): Promise<{
|
||||
sealDir: string;
|
||||
targetDir: string;
|
||||
items: SyncFromSealUseItemResult[];
|
||||
}> {
|
||||
const sealDir =
|
||||
options.sealEnterprisesDir ||
|
||||
process.env.SEAL_USE_ENTERPRISES_DIR?.trim() ||
|
||||
join(homedir(), ".config", "seal-use", "enterprises");
|
||||
const targetDir = options.enterprisesDir || resolveWritableEnterprisesDir();
|
||||
|
||||
if (!existsSync(sealDir)) {
|
||||
throw new AuthenticationError(`未找到 seal-use 企业配置目录: ${sealDir}`);
|
||||
}
|
||||
|
||||
const files = readdirSync(sealDir).filter((f) => f.endsWith(".json") && !f.startsWith("example."));
|
||||
const kw = options.filter?.trim().toLowerCase();
|
||||
const items: SyncFromSealUseItemResult[] = [];
|
||||
|
||||
for (const file of files) {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(join(sealDir, file), "utf-8"));
|
||||
const sourceObj = raw?.source?.hose || raw?.source || raw?.hose;
|
||||
const appKey = sourceObj?.appKey;
|
||||
const appSecurity = sourceObj?.appSecurity;
|
||||
if (!appKey || !appSecurity) continue;
|
||||
|
||||
const corpId: string = sourceObj.corpId || raw.id;
|
||||
const sealName: string = raw.name || corpId;
|
||||
const domain = normalizeBaseUrl(sourceObj.domain || DEFAULT_EKB_BASE_URL);
|
||||
const rawStaffId: string = sourceObj.staffId || `${corpId}:admin`;
|
||||
const staffId = rawStaffId.includes(":") ? rawStaffId : `${corpId}:${rawStaffId}`;
|
||||
|
||||
if (kw) {
|
||||
const matched =
|
||||
corpId.toLowerCase().includes(kw) ||
|
||||
sealName.toLowerCase().includes(kw) ||
|
||||
String(raw.id || "").toLowerCase().includes(kw);
|
||||
if (!matched) continue;
|
||||
}
|
||||
|
||||
const targetPath = join(targetDir, `${corpId}.json`);
|
||||
if (existsSync(targetPath)) {
|
||||
const existing = CorpConfigSchema.parse(JSON.parse(readFileSync(targetPath, "utf-8")));
|
||||
if (hasOpenApiPersistentCredentials(existing) && options.overwrite === false) {
|
||||
items.push({
|
||||
corpId,
|
||||
name: existing.name,
|
||||
appKey: existing.credentials.appKey || appKey,
|
||||
domain: existing.baseUrl || domain,
|
||||
staffId: existing.credentials.staffId,
|
||||
action: "skipped",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
existing.credentials.appKey = appKey;
|
||||
existing.credentials.appSecurity = appSecurity;
|
||||
if (!existing.baseUrl) existing.baseUrl = domain;
|
||||
if (!existing.credentials.staffId) existing.credentials.staffId = staffId;
|
||||
if (options.verify) {
|
||||
await refreshSingleCorpAccessToken(existing);
|
||||
} else {
|
||||
saveCorpConfig(existing, targetDir);
|
||||
}
|
||||
items.push({
|
||||
corpId,
|
||||
name: existing.name,
|
||||
appKey,
|
||||
domain: existing.baseUrl || domain,
|
||||
staffId: existing.credentials.staffId,
|
||||
action: "merged",
|
||||
});
|
||||
} else {
|
||||
let createdConfig: CorpConfig | null = null;
|
||||
if (options.verify) {
|
||||
try {
|
||||
createdConfig = await onboardHosePersistent({
|
||||
id: corpId,
|
||||
name: sealName,
|
||||
appKey,
|
||||
appSecurity,
|
||||
domain,
|
||||
corpId,
|
||||
staffId,
|
||||
overwrite: true,
|
||||
enterprisesDir: targetDir,
|
||||
});
|
||||
} catch {
|
||||
// fallback to saving raw OpenAPI credentials below
|
||||
}
|
||||
}
|
||||
if (!createdConfig) {
|
||||
createdConfig = {
|
||||
id: corpId,
|
||||
name: sealName,
|
||||
corpId,
|
||||
staffId,
|
||||
source: "openapi",
|
||||
baseUrl: domain,
|
||||
cluster: resolveCorpCluster({ baseUrl: domain }),
|
||||
credentials: {
|
||||
accessToken: "",
|
||||
corpId,
|
||||
staffId,
|
||||
appKey,
|
||||
appSecurity,
|
||||
},
|
||||
auth: {
|
||||
refreshTtl: 300,
|
||||
},
|
||||
};
|
||||
saveCorpConfig(createdConfig, targetDir);
|
||||
}
|
||||
items.push({
|
||||
corpId,
|
||||
name: createdConfig.name,
|
||||
appKey,
|
||||
domain: createdConfig.baseUrl || domain,
|
||||
staffId: createdConfig.credentials.staffId,
|
||||
action: "created",
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// ignore invalid file
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sealDir,
|
||||
targetDir,
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已配置企业提取并持久化 OpenAPI 密钥
|
||||
*/
|
||||
export async function elevateCorpWithOpenApiKey(
|
||||
corp: CorpConfig,
|
||||
options: {
|
||||
appKey?: string;
|
||||
keyId?: string;
|
||||
force?: boolean;
|
||||
silent?: boolean;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<HoseOpenApiKeyItem | undefined> {
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = corp.baseUrl || DEFAULT_EKB_BASE_URL;
|
||||
|
||||
try {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expMs = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
|
||||
const keys = await fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken: corp.credentials.accessToken,
|
||||
}).catch(async (err) => {
|
||||
if (canRefreshCorpAccessToken(corp)) {
|
||||
const refreshed = await refreshSingleCorpAccessToken(corp);
|
||||
if (refreshed) {
|
||||
return fetchOpenApiKeysBySession({
|
||||
baseUrl,
|
||||
corpId,
|
||||
staffId,
|
||||
accessToken: corp.credentials.accessToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
throw err;
|
||||
});
|
||||
|
||||
if (keys.length === 0) {
|
||||
if (options.silent) return undefined;
|
||||
throw new AuthenticationError(`企业 [${corp.name}] 暂未创建 OpenAPI 密钥`);
|
||||
}
|
||||
const selected = selectOpenApiKey(keys, corpId, {
|
||||
appKey: options.appKey,
|
||||
keyId: options.keyId,
|
||||
force: options.force ?? options.silent,
|
||||
});
|
||||
corp.credentials.appKey = selected.appKey;
|
||||
corp.credentials.appSecurity = selected.appSecurity;
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
return selected;
|
||||
} catch (err) {
|
||||
if (options.silent) return undefined;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成指定企业的合思 Web 免密登录直达链接 (thirdparty.html)
|
||||
* 优先走 OpenAPI getProvisionalAuth 签发独立授权链接;若无 OpenAPI 密钥则尝试自动提权,最后回退当前有效会话 Token。
|
||||
*/
|
||||
export async function getCorpProvisionalAuthLink(
|
||||
corp: CorpConfig,
|
||||
options: {
|
||||
expiresIn?: number | string;
|
||||
ttl?: number | string;
|
||||
pageType?: string;
|
||||
force?: boolean;
|
||||
syncLocalSession?: boolean;
|
||||
enterprisesDir?: string;
|
||||
} = {}
|
||||
): Promise<{
|
||||
corpId: string;
|
||||
corpName: string;
|
||||
staffId: string;
|
||||
staffName?: string;
|
||||
url: string;
|
||||
token: string;
|
||||
expiresIn: number;
|
||||
expiresAt: string;
|
||||
persistent: boolean;
|
||||
method: "provisional-openapi" | "session-token";
|
||||
}> {
|
||||
const explicitDuration = options.expiresIn ?? options.ttl;
|
||||
const expiresIn = parseExpiresInSeconds(explicitDuration, 7200);
|
||||
const pageType = options.pageType || "home";
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
|
||||
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
|
||||
if (!hasOpenApiPersistentCredentials(corp)) {
|
||||
const ttlMs = (corp.auth?.refreshTtl || 300) * 1000;
|
||||
const expMs = corp.auth?.expiresAt || corp.session?.expTime;
|
||||
if (canRefreshCorpAccessToken(corp) && (!corp.credentials.accessToken || (expMs && Date.now() >= expMs - ttlMs))) {
|
||||
await refreshSingleCorpAccessToken(corp);
|
||||
}
|
||||
if (corp.credentials.accessToken) {
|
||||
await elevateCorpWithOpenApiKey(corp, { silent: true, force: true, enterprisesDir: options.enterprisesDir });
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 若具备 OpenAPI 持久化密钥,直接走 getProvisionalAuth 签发标准免密链接
|
||||
const openApiCreds = getCorpOpenApiCredentials(corp);
|
||||
if (openApiCreds) {
|
||||
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||||
appKey: openApiCreds.appKey,
|
||||
appSecurity: openApiCreds.appSecurity,
|
||||
baseUrl,
|
||||
forceRefresh: options.force,
|
||||
});
|
||||
const provisional = await fetchHoseProvisionalAuth({
|
||||
baseUrl,
|
||||
openapiToken,
|
||||
corpId,
|
||||
staffId,
|
||||
expiresIn,
|
||||
pageType,
|
||||
});
|
||||
|
||||
if (options.syncLocalSession !== false) {
|
||||
corp.credentials.accessToken = provisional.token;
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = provisional.expiresAt;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = provisional.expiresAt;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
invalidateCorpSubdomainTokenCaches(corp);
|
||||
}
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId: provisional.uid,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
url: provisional.url,
|
||||
token: provisional.token,
|
||||
expiresIn: provisional.expiresIn,
|
||||
expiresAt: formatBeijingIso(provisional.expiresAt),
|
||||
persistent: true,
|
||||
method: "provisional-openapi",
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 回退路径:无 OpenAPI 密钥时,使用主账号或现有有效 Session Token 拼装免密链接
|
||||
if (!corp.credentials.accessToken) {
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corp.name}] 缺少可用访问令牌且未配置 OpenAPI 持久化密钥,请重新登录或导入链接。`
|
||||
);
|
||||
}
|
||||
|
||||
const expMs =
|
||||
explicitDuration !== undefined
|
||||
? Date.now() + expiresIn * 1000
|
||||
: corp.auth?.expiresAt || corp.session?.expTime || Date.now() + expiresIn * 1000;
|
||||
if (expMs <= Date.now() && !canRefreshCorpAccessToken(corp)) {
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corp.name}] 临时凭证已过期且未配置持久化密钥,请使用 hose-use corps add-link 重新导入。`
|
||||
);
|
||||
}
|
||||
|
||||
if (explicitDuration !== undefined && options.syncLocalSession !== false) {
|
||||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||||
corp.auth.expiresAt = expMs;
|
||||
if (corp.session) {
|
||||
corp.session.expTime = expMs;
|
||||
}
|
||||
saveCorpConfig(corp, options.enterprisesDir);
|
||||
}
|
||||
|
||||
const url = `${baseUrl}/web/thirdparty.html?accessToken=${encodeURIComponent(
|
||||
corp.credentials.accessToken
|
||||
)}&ekbCorpId=${encodeURIComponent(corpId)}&pageType=${encodeURIComponent(
|
||||
pageType
|
||||
)}&overdueTokenRedirect=&noPathCache=true`;
|
||||
|
||||
return {
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
url,
|
||||
token: corp.credentials.accessToken,
|
||||
expiresIn: Math.max(1, Math.round((expMs - Date.now()) / 1000)),
|
||||
expiresAt: formatBeijingIso(expMs),
|
||||
persistent: canRefreshCorpAccessToken(corp),
|
||||
method: "session-token",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
import ky from "ky";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
|
||||
export const DEFAULT_EKB_BASE_URL = "https://app.ekuaibao.com";
|
||||
|
||||
export const HOSE_STANDARD_DOMAINS = [
|
||||
"https://app.ekuaibao.com",
|
||||
"https://dd2.hosecloud.com",
|
||||
"https://wx2.ekuaibao.com",
|
||||
"https://kdcloud2.ekuaibao.com",
|
||||
"https://ddenterprise.ekuaibao.com",
|
||||
"https://feishu.ekuaibao.com",
|
||||
] as const;
|
||||
|
||||
export function normalizeBaseUrl(url: string): string {
|
||||
return url.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function formatBeijingIso(timestampMs: number): string {
|
||||
const shanghaiMs = timestampMs + 8 * 60 * 60 * 1000;
|
||||
const iso = new Date(shanghaiMs).toISOString();
|
||||
return `${iso.slice(0, 19)}+08:00`;
|
||||
}
|
||||
|
||||
export function maskOpenApiSecurity(secret: string): string {
|
||||
if (!secret) return "-";
|
||||
if (secret.length <= 12) return "******";
|
||||
return `${secret.slice(0, 8)}...${secret.slice(-4)}`;
|
||||
}
|
||||
|
||||
export function getCorpOpenApiCredentials(
|
||||
corp?: CorpConfig | null
|
||||
): { appKey: string; appSecurity: string } | undefined {
|
||||
if (!corp) return undefined;
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
if (appKey && appSecurity) {
|
||||
return { appKey, appSecurity };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function hasOpenApiPersistentCredentials(corp?: CorpConfig | null): boolean {
|
||||
return Boolean(getCorpOpenApiCredentials(corp));
|
||||
}
|
||||
|
||||
export function canRefreshCorpAccessToken(corp?: CorpConfig | null): boolean {
|
||||
if (!corp) return false;
|
||||
if (hasOpenApiPersistentCredentials(corp)) {
|
||||
return true;
|
||||
}
|
||||
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
|
||||
}
|
||||
|
||||
// ── OpenAPI v1 持久凭据换票、免密链接签发与提权 ──────────────────────────────
|
||||
|
||||
export interface HoseOpenApiKeyItem {
|
||||
id: string;
|
||||
name?: string;
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
active: boolean;
|
||||
corporationId?: string;
|
||||
createTime?: number;
|
||||
updateTime?: number;
|
||||
}
|
||||
|
||||
export interface HoseProbeDomainResult {
|
||||
domain: string;
|
||||
corpId: string;
|
||||
corpName?: string;
|
||||
openapiToken: string;
|
||||
expireTime?: number;
|
||||
}
|
||||
|
||||
export interface HoseRoleDef {
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
sourceType?: string;
|
||||
sourceTypeValue?: string | null;
|
||||
groupId?: string;
|
||||
groupName?: string;
|
||||
}
|
||||
|
||||
export interface HoseRoleDefGroup {
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
roleDefs: HoseRoleDef[];
|
||||
}
|
||||
|
||||
export interface HoseStaffDetail {
|
||||
id: string;
|
||||
name: string;
|
||||
nickName?: string | null;
|
||||
code?: string;
|
||||
departments?: string[];
|
||||
defaultDepartment?: string;
|
||||
cellphone?: string;
|
||||
active: boolean;
|
||||
userId?: string;
|
||||
email?: string | null;
|
||||
showEmail?: string | null;
|
||||
external?: boolean;
|
||||
authState?: boolean;
|
||||
}
|
||||
|
||||
const openapiV1TokenCache = new Map<string, { token: string; expiresAt: number }>();
|
||||
const openapiV1TokenInflight = new Map<string, Promise<string>>();
|
||||
|
||||
export async function fetchHoseOpenApiAccessToken(params: {
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
baseUrl?: string;
|
||||
forceRefresh?: boolean;
|
||||
}): Promise<string> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const cacheKey = `${params.appKey}@${baseUrl}`;
|
||||
|
||||
if (!params.forceRefresh) {
|
||||
const cached = openapiV1TokenCache.get(cacheKey);
|
||||
if (cached && Date.now() < cached.expiresAt - 60_000) {
|
||||
return cached.token;
|
||||
}
|
||||
const inflight = openapiV1TokenInflight.get(cacheKey);
|
||||
if (inflight) return inflight;
|
||||
}
|
||||
|
||||
const req = (async () => {
|
||||
const res = await ky
|
||||
.post(`${baseUrl}/api/openapi/v1/auth/getAccessToken`, {
|
||||
json: {
|
||||
appKey: params.appKey,
|
||||
appSecurity: params.appSecurity,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{
|
||||
value?: {
|
||||
accessToken?: string;
|
||||
corporationId?: string;
|
||||
expireTime?: number;
|
||||
errorCode?: number;
|
||||
errorMessage?: string;
|
||||
};
|
||||
accessToken?: string;
|
||||
token?: string;
|
||||
}>();
|
||||
|
||||
if (res.value?.errorCode) {
|
||||
throw new AuthenticationError(
|
||||
res.value.errorMessage || `OpenAPI 换票失败 (errorCode: ${res.value.errorCode})`
|
||||
);
|
||||
}
|
||||
|
||||
const token = res.value?.accessToken ?? res.accessToken ?? res.token;
|
||||
if (!token) {
|
||||
throw new AuthenticationError("合思 OpenAPI getAccessToken 未返回有效 accessToken");
|
||||
}
|
||||
|
||||
openapiV1TokenCache.set(cacheKey, {
|
||||
token,
|
||||
expiresAt: Date.now() + 3600 * 1000,
|
||||
});
|
||||
return token;
|
||||
})().finally(() => {
|
||||
openapiV1TokenInflight.delete(cacheKey);
|
||||
});
|
||||
|
||||
openapiV1TokenInflight.set(cacheKey, req);
|
||||
return req;
|
||||
}
|
||||
|
||||
export async function fetchHoseProvisionalAuth(params: {
|
||||
baseUrl?: string;
|
||||
openapiToken: string;
|
||||
corpId: string;
|
||||
staffId: string;
|
||||
expiresIn?: number;
|
||||
pageType?: string;
|
||||
}): Promise<{
|
||||
url: string;
|
||||
token: string;
|
||||
uid: string;
|
||||
expiresIn: number;
|
||||
expiresAt: number;
|
||||
}> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const expiresIn = params.expiresIn && params.expiresIn > 0 ? params.expiresIn : 7200;
|
||||
const pageType = params.pageType || "home";
|
||||
const uid = params.staffId.includes(":")
|
||||
? params.staffId
|
||||
: `${params.corpId}:${params.staffId}`;
|
||||
|
||||
const response = await ky
|
||||
.post(`${baseUrl}/api/openapi/v1.1/provisional/getProvisionalAuth`, {
|
||||
searchParams: {
|
||||
accessToken: params.openapiToken,
|
||||
},
|
||||
json: {
|
||||
uid,
|
||||
pageType,
|
||||
expireDate: expiresIn,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ value?: { message?: string } }>();
|
||||
|
||||
const url = response.value?.message;
|
||||
if (!url) {
|
||||
throw new AuthenticationError("合思 getProvisionalAuth 未返回免密授权链接");
|
||||
}
|
||||
|
||||
const token = new URL(url).searchParams.get("accessToken");
|
||||
if (!token) {
|
||||
throw new AuthenticationError("合思免密授权链接缺少 accessToken 参数");
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
token,
|
||||
uid,
|
||||
expiresIn,
|
||||
expiresAt: Date.now() + expiresIn * 1000,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchOpenApiKeysBySession(params: {
|
||||
baseUrl?: string;
|
||||
corpId: string;
|
||||
staffId?: string;
|
||||
accessToken: string;
|
||||
}): Promise<HoseOpenApiKeyItem[]> {
|
||||
const baseUrl = normalizeBaseUrl(params.baseUrl || DEFAULT_EKB_BASE_URL);
|
||||
const staffId = params.staffId || `${params.corpId}:admin`;
|
||||
const response = await ky
|
||||
.get(`${baseUrl}/api/innerapi/v1/key`, {
|
||||
searchParams: { corpId: params.corpId },
|
||||
headers: {
|
||||
accesstoken: params.accessToken,
|
||||
corpid: params.corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
timeout: 15000,
|
||||
})
|
||||
.json<{ items?: unknown[] }>();
|
||||
|
||||
const rawItems = response.items ?? [];
|
||||
const keys: HoseOpenApiKeyItem[] = [];
|
||||
for (const raw of rawItems) {
|
||||
if (typeof raw === "object" && raw !== null) {
|
||||
const item = raw as Record<string, unknown>;
|
||||
if (typeof item.appKey === "string" && typeof item.appSecurity === "string") {
|
||||
keys.push({
|
||||
id: String(item.id ?? item.appKey),
|
||||
name: typeof item.name === "string" ? item.name : undefined,
|
||||
appKey: item.appKey,
|
||||
appSecurity: item.appSecurity,
|
||||
active: typeof item.active === "boolean" ? item.active : true,
|
||||
corporationId: typeof item.corporationId === "string" ? item.corporationId : params.corpId,
|
||||
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
|
||||
updateTime: typeof item.updateTime === "number" ? item.updateTime : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export function selectOpenApiKey(
|
||||
keys: HoseOpenApiKeyItem[],
|
||||
corpId: string,
|
||||
selection: { appKey?: string; keyId?: string; force?: boolean } = {}
|
||||
): HoseOpenApiKeyItem {
|
||||
if (keys.length === 0) {
|
||||
throw new AuthenticationError(
|
||||
`未能从企业 [${corpId}] 中提取到 OpenAPI 密钥凭据。请确认该企业在合思开放平台已创建应用密钥,且当前员工具有管理员权限。`
|
||||
);
|
||||
}
|
||||
if (selection.keyId || selection.appKey) {
|
||||
const matched = keys.find(
|
||||
(k) =>
|
||||
(selection.keyId && k.id === selection.keyId) ||
|
||||
(selection.appKey && k.appKey === selection.appKey)
|
||||
);
|
||||
if (!matched) {
|
||||
const candidates = keys
|
||||
.map((k) => ` • "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${k.active ? "🟢 启用" : "⚪ 停用"})`)
|
||||
.join("\n");
|
||||
throw new AuthenticationError(
|
||||
`指定的合思密钥不存在,请从候选列表中选择正确的 --app-key 或 --key-id:\n${candidates}`
|
||||
);
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
const activeKeys = keys.filter((k) => k.active !== false);
|
||||
if (keys.length === 1) return keys[0]!;
|
||||
if (activeKeys.length === 1) return activeKeys[0]!;
|
||||
if (selection.force) {
|
||||
return activeKeys[0] ?? keys[0]!;
|
||||
}
|
||||
const candidates = keys
|
||||
.map(
|
||||
(k, idx) =>
|
||||
` [${idx + 1}] "${k.name || "未命名应用"}" (appKey: ${k.appKey}, keyId: ${k.id}, 状态: ${k.active ? "🟢 启用" : "⚪ 停用"})`
|
||||
)
|
||||
.join("\n");
|
||||
throw new AuthenticationError(
|
||||
`企业 [${corpId}] 存在多套 (${keys.length} 套) OpenAPI 应用密钥凭据:\n${candidates}\n请通过 --app-key <key> 或 --key-id <id> 显式指定,或追加 --force 自动选用第一套启用密钥。`
|
||||
);
|
||||
}
|
||||
|
||||
export async function probeHoseDomain(
|
||||
appKey: string,
|
||||
appSecurity: string,
|
||||
explicitDomain?: string
|
||||
): Promise<HoseProbeDomainResult> {
|
||||
if (explicitDomain) {
|
||||
const normalized = normalizeBaseUrl(explicitDomain);
|
||||
const result = await testSingleHoseDomain(normalized, appKey, appSecurity);
|
||||
if (!result) {
|
||||
throw new AuthenticationError(
|
||||
`在指定域名 ${normalized} 上校验 OpenAPI 凭据失败,请检查 appKey/appSecurity 与域名连通性。`
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const results = await Promise.all(
|
||||
HOSE_STANDARD_DOMAINS.map((domain) =>
|
||||
testSingleHoseDomain(domain, appKey, appSecurity).catch(() => undefined)
|
||||
)
|
||||
);
|
||||
const matched = results.find((item): item is HoseProbeDomainResult => Boolean(item));
|
||||
if (matched) return matched;
|
||||
|
||||
throw new AuthenticationError(
|
||||
`在全部 6 个标准合思域名 (${HOSE_STANDARD_DOMAINS.join(", ")}) 上均未能通过 appKey/appSecurity 鉴权。若为私有化或独立域名,请通过 --domain 显式指定。`
|
||||
);
|
||||
}
|
||||
|
||||
async function testSingleHoseDomain(
|
||||
domain: string,
|
||||
appKey: string,
|
||||
appSecurity: string
|
||||
): Promise<HoseProbeDomainResult | undefined> {
|
||||
try {
|
||||
const response = await fetch(`${domain}/api/openapi/v1/auth/getAccessToken`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ appKey, appSecurity }),
|
||||
signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!response.ok) return undefined;
|
||||
const data = (await response.json()) as {
|
||||
value?: {
|
||||
accessToken?: string;
|
||||
corporationId?: string;
|
||||
corporation?: { id?: string; name?: string };
|
||||
expireTime?: number;
|
||||
errorCode?: number;
|
||||
};
|
||||
accessToken?: string;
|
||||
};
|
||||
if (data.value?.errorCode) return undefined;
|
||||
const openapiToken = data.value?.accessToken ?? data.accessToken;
|
||||
const corpId = data.value?.corporationId ?? data.value?.corporation?.id;
|
||||
if (!openapiToken || !corpId) return undefined;
|
||||
return {
|
||||
domain,
|
||||
corpId,
|
||||
corpName: data.value?.corporation?.name,
|
||||
openapiToken,
|
||||
expireTime: data.value?.expireTime,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchHoseRoleDefGroups(
|
||||
domain: string,
|
||||
openapiToken: string
|
||||
): Promise<HoseRoleDefGroup[]> {
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roleDefGroups?accessToken=${encodeURIComponent(openapiToken)}`;
|
||||
const response = await fetch(url, {
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取合思角色定义组失败: ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
items?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
roleDefs?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
enName?: string | null;
|
||||
sourceType?: string;
|
||||
sourceTypeValue?: string | null;
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
return (json.items ?? []).map((g) => ({
|
||||
id: g.id,
|
||||
name: g.name,
|
||||
enName: g.enName,
|
||||
roleDefs: (g.roleDefs ?? []).map((r) => ({
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
enName: r.enName,
|
||||
sourceType: r.sourceType,
|
||||
sourceTypeValue: r.sourceTypeValue,
|
||||
groupId: g.id,
|
||||
groupName: g.name,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function fetchHoseRoleStaffs(
|
||||
domain: string,
|
||||
openapiToken: string,
|
||||
roledefId: string,
|
||||
staffBy = "id"
|
||||
): Promise<{ id: string; name: string; count: number; staffs: string[] }> {
|
||||
const cleanId = roledefId.startsWith("$") ? roledefId.slice(1) : roledefId;
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/roledefs/$${cleanId}?accessToken=${encodeURIComponent(openapiToken)}&staffBy=${encodeURIComponent(staffBy)}&pathType=name`;
|
||||
const response = await fetch(url, {
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取角色成员失败 (${cleanId}): ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as {
|
||||
value?: {
|
||||
id: string;
|
||||
name: string;
|
||||
count?: number;
|
||||
contents?: Array<{ staffs?: string[] }>;
|
||||
};
|
||||
};
|
||||
const val = json.value;
|
||||
if (!val) throw new AuthenticationError(`角色成员查询返回为空 (${cleanId})`);
|
||||
const allStaffs: string[] = [];
|
||||
for (const c of val.contents ?? []) {
|
||||
for (const s of c.staffs ?? []) {
|
||||
if (s && !allStaffs.includes(s)) allStaffs.push(s);
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: val.id ?? cleanId,
|
||||
name: val.name ?? "",
|
||||
count: val.count ?? allStaffs.length,
|
||||
staffs: allStaffs,
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchHoseStaffDetails(
|
||||
domain: string,
|
||||
openapiToken: string,
|
||||
staffIds: string[]
|
||||
): Promise<HoseStaffDetail[]> {
|
||||
if (staffIds.length === 0) return [];
|
||||
const url = `${normalizeBaseUrl(domain)}/api/openapi/v1/staffs/getStaffIds?accessToken=${encodeURIComponent(openapiToken)}`;
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({
|
||||
type: "STAFFID",
|
||||
conditionIds: staffIds.slice(0, 100),
|
||||
}),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => "");
|
||||
throw new AuthenticationError(`获取合思员工详情失败: ${response.status} ${text}`);
|
||||
}
|
||||
const json = (await response.json()) as { items?: HoseStaffDetail[] };
|
||||
return json.items ?? [];
|
||||
}
|
||||
|
||||
export async function listHoseStaffsByOpenApi(input: {
|
||||
appKey: string;
|
||||
appSecurity: string;
|
||||
domain?: string;
|
||||
role?: string;
|
||||
roleDefId?: string;
|
||||
}) {
|
||||
const probe = await probeHoseDomain(input.appKey, input.appSecurity, input.domain);
|
||||
const roleQuery = input.role ?? input.roleDefId ?? "admin";
|
||||
const roleGroups = await fetchHoseRoleDefGroups(probe.domain, probe.openapiToken);
|
||||
let targetRoleDefId: string | undefined;
|
||||
let targetRoleName: string | undefined;
|
||||
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id === roleQuery || role.id === `${probe.corpId}:${roleQuery}`) {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
|
||||
if (!targetRoleDefId && (roleQuery === "admin" || roleQuery === "主管理员")) {
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.id.endsWith(":admin") || role.name === "主管理员") {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetRoleDefId) {
|
||||
for (const group of roleGroups) {
|
||||
for (const role of group.roleDefs) {
|
||||
if (role.name.toLowerCase().includes(roleQuery.toLowerCase())) {
|
||||
targetRoleDefId = role.id;
|
||||
targetRoleName = role.name;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetRoleDefId) break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!targetRoleDefId) {
|
||||
throw new AuthenticationError(`未找到匹配 '${roleQuery}' 的角色定义`);
|
||||
}
|
||||
|
||||
const roleStaffs = await fetchHoseRoleStaffs(probe.domain, probe.openapiToken, targetRoleDefId);
|
||||
const staffs = await fetchHoseStaffDetails(probe.domain, probe.openapiToken, roleStaffs.staffs);
|
||||
return {
|
||||
domain: probe.domain,
|
||||
corpId: probe.corpId,
|
||||
corpName: probe.corpName ?? probe.corpId,
|
||||
roleId: targetRoleDefId,
|
||||
roleName: targetRoleName,
|
||||
staffs,
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema, normalizeCorpConfig } from "./types.js";
|
||||
|
||||
const CONFIG_ENV = "HOSE_ENTERPRISES_DIR";
|
||||
const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||
@@ -194,7 +194,7 @@ export function loadCorpConfigs(overrideDirs?: string[]): CorpConfig[] {
|
||||
try {
|
||||
const content = readFileSync(join(dir, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
const corp = CorpConfigSchema.parse(parsed);
|
||||
const corp = normalizeCorpConfig(CorpConfigSchema.parse(parsed));
|
||||
// 相同企业 ID 以先出现的为准(工作区优先于全局,全局优先于历史)
|
||||
if (!byId.has(corp.id)) {
|
||||
byId.set(corp.id, corp);
|
||||
@@ -238,7 +238,7 @@ export function saveCorpConfig(config: CorpConfig, dir?: string): string {
|
||||
// ignore malformed existing file
|
||||
}
|
||||
}
|
||||
const validated = CorpConfigSchema.parse(config);
|
||||
const validated = normalizeCorpConfig(CorpConfigSchema.parse(config));
|
||||
const filePath = join(targetDir, `${validated.id}.json`);
|
||||
writeSecureFile(filePath, JSON.stringify(validated, null, 2));
|
||||
return filePath;
|
||||
|
||||
+12
-10
@@ -1,4 +1,10 @@
|
||||
import { CorpConfig, GlobalConfig } from "./types.js";
|
||||
import {
|
||||
CorpConfig,
|
||||
getCorpExpiresAt,
|
||||
getCorpPhysicalId,
|
||||
getCorpStaffId,
|
||||
getCorpStaffName,
|
||||
} from "./types.js";
|
||||
import { saveGlobalConfig } from "./loader.js";
|
||||
|
||||
export interface CorpSummary {
|
||||
@@ -35,11 +41,7 @@ export function resolveCorpConfig(
|
||||
let corp = corps.find((item) => item.id === selectedCorpId);
|
||||
// 2. 其次按企业物理 ID 匹配 (如 uzU7pcWfScck00)
|
||||
if (!corp) {
|
||||
corp = corps.find(
|
||||
(item) =>
|
||||
item.corpId === selectedCorpId ||
|
||||
item.credentials.corpId === selectedCorpId
|
||||
);
|
||||
corp = corps.find((item) => getCorpPhysicalId(item) === selectedCorpId);
|
||||
}
|
||||
if (corp) return corp;
|
||||
throw new Error(`未找到企业或身份标识为 [${selectedCorpId}] 的企业配置`);
|
||||
@@ -160,14 +162,14 @@ export class CorpContext {
|
||||
return {
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
corpId: corp.corpId || corp.credentials.corpId,
|
||||
staffId: corp.credentials.staffId,
|
||||
staffName: corp.staffName || corp.session?.staffName || undefined,
|
||||
corpId: getCorpPhysicalId(corp),
|
||||
staffId: getCorpStaffId(corp),
|
||||
staffName: getCorpStaffName(corp),
|
||||
source: corp.source || "manual",
|
||||
accountId: corp.accountId,
|
||||
baseUrl: corp.baseUrl,
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: corp.auth?.expiresAt || (corp.session?.expTime ?? undefined),
|
||||
expiresAt: getCorpExpiresAt(corp),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -66,6 +66,69 @@ export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
|
||||
/**
|
||||
* 获取企业真实物理 corpId(统一收敛 corp.corpId / corp.credentials.corpId / corp.id)
|
||||
*/
|
||||
export function getCorpPhysicalId(corp: CorpConfig): string {
|
||||
return corp.corpId || corp.credentials.corpId || corp.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业内当前员工工号 staffId(统一收敛 corp.credentials.staffId / corp.staffId)
|
||||
*/
|
||||
export function getCorpStaffId(corp: CorpConfig): string {
|
||||
return corp.credentials.staffId || corp.staffId || "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取企业内当前员工姓名(统一收敛 corp.staffName / corp.session?.staffName)
|
||||
*/
|
||||
export function getCorpStaffName(corp: CorpConfig): string | undefined {
|
||||
return corp.staffName || corp.session?.staffName || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取凭证过期时间戳 ms(统一收敛 corp.auth?.expiresAt / corp.session?.expTime)
|
||||
*/
|
||||
export function getCorpExpiresAt(corp: CorpConfig): number | undefined {
|
||||
return corp.auth?.expiresAt || (corp.session?.expTime ?? undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 CorpConfig 冗余字段,确保顶层与嵌套凭证/会话字段保持一致
|
||||
*/
|
||||
export function normalizeCorpConfig(corp: CorpConfig): CorpConfig {
|
||||
const physicalCorpId = getCorpPhysicalId(corp);
|
||||
const staffId = getCorpStaffId(corp);
|
||||
const staffName = getCorpStaffName(corp);
|
||||
const expiresAt = getCorpExpiresAt(corp);
|
||||
const appKey = corp.credentials?.appKey || corp.auth?.appKey;
|
||||
const appSecurity = corp.credentials?.appSecurity || corp.auth?.appSecurity;
|
||||
|
||||
return {
|
||||
...corp,
|
||||
corpId: physicalCorpId,
|
||||
...(staffId ? { staffId } : {}),
|
||||
...(staffName ? { staffName } : {}),
|
||||
credentials: {
|
||||
...corp.credentials,
|
||||
corpId: corp.credentials.corpId || physicalCorpId,
|
||||
staffId,
|
||||
...(appKey ? { appKey } : {}),
|
||||
...(appSecurity ? { appSecurity } : {}),
|
||||
},
|
||||
...(corp.auth || expiresAt
|
||||
? {
|
||||
auth: {
|
||||
refreshTtl: corp.auth?.refreshTtl ?? 300,
|
||||
...corp.auth,
|
||||
...(expiresAt ? { expiresAt } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── 全局运行配置(有状态/无状态模式)─────────────────────────────────────────
|
||||
|
||||
export const GlobalConfigSchema = z.object({
|
||||
@@ -79,3 +142,4 @@ export const GlobalConfigSchema = z.object({
|
||||
|
||||
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
|
||||
|
||||
|
||||
Reference in new issue
Block a user