2189 lines
69 KiB
TypeScript
2189 lines
69 KiB
TypeScript
import crypto from "crypto";
|
||
import ky from "ky";
|
||
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, saveMultipleCorpConfigs, resolveWritableEnterprisesDir } from "../config/loader.js";
|
||
import { resolveCorpCluster } from "../http/unity-client.js";
|
||
import {
|
||
saveAccount,
|
||
getAccount,
|
||
listAccounts,
|
||
getActiveAccount,
|
||
setActiveAccount,
|
||
AccountEntry,
|
||
} from "./account-store.js";
|
||
import {
|
||
CorporationItem,
|
||
CorporationItemSchema,
|
||
IdpOAuthTokenResponse,
|
||
PasswordLoginParams,
|
||
SendSmsCodeParams,
|
||
SmsCodeLoginParams,
|
||
SyncBrowserLoginParams,
|
||
} from "./types.js";
|
||
|
||
const DEFAULT_BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
|
||
const DEFAULT_IDP_URL = "https://idp.hosecloud.com";
|
||
const DEFAULT_WEBBRIDGE_URL = "http://127.0.0.1:10086";
|
||
const DEFAULT_EKB_BASE_URL = "https://app.ekuaibao.com";
|
||
|
||
// ── 基础工具函数 ─────────────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* 获取业务中心 RSA 登录公钥 (Base64)
|
||
*/
|
||
export async function fetchPublicKey(
|
||
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
|
||
): Promise<string> {
|
||
const res = await ky
|
||
.get(`${businessCenterUrl}/cloud-auth/public/auth/public-key`)
|
||
.json<{ data?: { base64?: string } }>();
|
||
|
||
const base64 = res.data?.base64;
|
||
if (!base64) {
|
||
throw new AuthenticationError("获取登录加密公钥失败");
|
||
}
|
||
return base64;
|
||
}
|
||
|
||
/**
|
||
* 使用 RSA 公钥 (PKCS#1) 加密密码
|
||
*/
|
||
export function encryptPassword(password: string, publicKeyBase64: string): string {
|
||
const pem = `-----BEGIN PUBLIC KEY-----\n${publicKeyBase64}\n-----END PUBLIC KEY-----`;
|
||
return crypto
|
||
.publicEncrypt(
|
||
{
|
||
key: pem,
|
||
padding: crypto.constants.RSA_PKCS1_PADDING,
|
||
},
|
||
Buffer.from(password)
|
||
)
|
||
.toString("base64");
|
||
}
|
||
|
||
/**
|
||
* 格式化手机号/用户名(如 86-13800000000)
|
||
*/
|
||
export function formatAccount(phone: string, areaCode: string = "86"): string {
|
||
const clean = phone.trim();
|
||
if (clean.includes("-")) return clean;
|
||
return `${areaCode}-${clean}`;
|
||
}
|
||
|
||
// ── 模式 1:账号密码登录 ──────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* 账号密码登录获取 cloudAuthToken
|
||
*/
|
||
export async function loginByPassword(
|
||
params: PasswordLoginParams
|
||
): Promise<{ cloudAuthToken: string }> {
|
||
const businessCenterUrl = params.businessCenterUrl || DEFAULT_BUSINESS_CENTER_URL;
|
||
const areaCode = params.areaCode || "86";
|
||
const deviceType = params.deviceType || "desktop";
|
||
|
||
// 1. 获取公钥并加密密码
|
||
const pubKey = await fetchPublicKey(businessCenterUrl);
|
||
const encryptedPassword = encryptPassword(params.password, pubKey);
|
||
|
||
// 2. 发起账密登录
|
||
const res = await ky
|
||
.post(`${businessCenterUrl}/cloud-auth/public/auth/login-by-password`, {
|
||
json: {
|
||
deviceType,
|
||
username: formatAccount(params.phone, areaCode),
|
||
password: encryptedPassword,
|
||
},
|
||
})
|
||
.json<{ data?: string; errorCode?: number; errorMessage?: string }>();
|
||
|
||
if (!res.data) {
|
||
throw new AuthenticationError(res.errorMessage || "账号或密码错误");
|
||
}
|
||
|
||
return { cloudAuthToken: res.data };
|
||
}
|
||
|
||
// ── 模式 2:短信验证码登录 ────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* 发送短信验证码
|
||
*/
|
||
export async function sendSmsVerificationCode(
|
||
params: SendSmsCodeParams
|
||
): Promise<{ codeId?: string }> {
|
||
const businessCenterUrl = params.businessCenterUrl || DEFAULT_BUSINESS_CENTER_URL;
|
||
const areaCode = params.areaCode || "86";
|
||
|
||
const payload: Record<string, unknown> = {
|
||
bizType: "LOGIN",
|
||
account: formatAccount(params.phone, areaCode),
|
||
channelType: "SMS",
|
||
...params.captchaParams,
|
||
};
|
||
|
||
const res = await ky
|
||
.post(`${businessCenterUrl}/cloud-auth/public/auth/send-verification-code`, {
|
||
json: payload,
|
||
})
|
||
.json<{ data?: { codeId?: string }; errorCode?: number; errorMessage?: string }>();
|
||
|
||
if (res.errorCode) {
|
||
throw new AuthenticationError(res.errorMessage || "发送验证码失败");
|
||
}
|
||
|
||
return { codeId: res.data?.codeId };
|
||
}
|
||
|
||
/**
|
||
* 提交短信验证码登录获取 cloudAuthToken
|
||
*/
|
||
export async function loginBySmsCode(
|
||
params: SmsCodeLoginParams
|
||
): Promise<{ cloudAuthToken: string }> {
|
||
const businessCenterUrl = params.businessCenterUrl || DEFAULT_BUSINESS_CENTER_URL;
|
||
const areaCode = params.areaCode || "86";
|
||
const deviceType = params.deviceType || "desktop";
|
||
|
||
const res = await ky
|
||
.post(`${businessCenterUrl}/cloud-auth/public/auth/login-by-code`, {
|
||
json: {
|
||
username: formatAccount(params.phone, areaCode),
|
||
code: params.code.trim(),
|
||
codeId: params.codeId,
|
||
deviceType,
|
||
},
|
||
})
|
||
.json<{ data?: string; errorCode?: number; errorMessage?: string }>();
|
||
|
||
if (!res.data) {
|
||
throw new AuthenticationError(res.errorMessage || "验证码错误或已过期");
|
||
}
|
||
|
||
return { cloudAuthToken: res.data };
|
||
}
|
||
|
||
// ── 模式 3:浏览器会话同步 ────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* 从本地运行的 Kimi WebBridge 或浏览器会话中提取鉴权 Token
|
||
*/
|
||
export async function syncFromBrowserSession(
|
||
params: SyncBrowserLoginParams = {}
|
||
): Promise<{ cloudAuthToken?: string; activeSession?: { accessToken: string; corpId: string; staffId?: string } }> {
|
||
const webbridgeUrl = params.webbridgeUrl || DEFAULT_WEBBRIDGE_URL;
|
||
|
||
try {
|
||
const res = await ky
|
||
.post(`${webbridgeUrl}/command`, {
|
||
json: {
|
||
action: "evaluate",
|
||
args: {
|
||
code: `(() => {
|
||
const sessionStr = localStorage.getItem("session");
|
||
const cloudAuthToken = localStorage.getItem("cloudAuthToken");
|
||
let sessionObj = null;
|
||
try { sessionObj = JSON.parse(sessionStr || "{}"); } catch {}
|
||
return {
|
||
cloudAuthToken,
|
||
accessToken: sessionObj?.user?.accessToken || localStorage.getItem("accessToken"),
|
||
corpId: sessionObj?.user?.corpId || localStorage.getItem("corpId"),
|
||
staffId: sessionObj?.user?.staffId || sessionObj?.staff?.id || localStorage.getItem("staffId"),
|
||
};
|
||
})()`,
|
||
},
|
||
session: "ekb-sync-auth",
|
||
},
|
||
})
|
||
.json<{ ok?: boolean; data?: { value?: { cloudAuthToken?: string; accessToken?: string; corpId?: string; staffId?: string } } }>();
|
||
|
||
const val = res.data?.value;
|
||
if (!val || (!val.cloudAuthToken && !val.accessToken)) {
|
||
throw new AuthenticationError("未能从当前浏览器会话中获取到合思登录凭证,请确保网页已登录");
|
||
}
|
||
|
||
return {
|
||
cloudAuthToken: val.cloudAuthToken,
|
||
activeSession: val.accessToken && val.corpId ? {
|
||
accessToken: val.accessToken,
|
||
corpId: val.corpId,
|
||
staffId: val.staffId,
|
||
} : undefined,
|
||
};
|
||
} catch (error) {
|
||
if (error instanceof AuthenticationError) throw error;
|
||
throw new AuthenticationError(`连接浏览器 WebBridge 失败: ${error instanceof Error ? error.message : String(error)}`);
|
||
}
|
||
}
|
||
|
||
// ── 模式 4:F12 / cURL / 手动直接导入单企业凭证 ───────────────────────────────
|
||
|
||
export interface F12ImportParams {
|
||
accessToken: string;
|
||
corpId: string;
|
||
staffId?: string;
|
||
name?: string;
|
||
baseUrl?: string;
|
||
cluster?: string;
|
||
source?: import("../config/types.js").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;
|
||
}
|
||
|
||
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,
|
||
};
|
||
}
|
||
|
||
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 {
|
||
createdConfig = null;
|
||
}
|
||
}
|
||
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,
|
||
};
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/**
|
||
* 解析从 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: import("../config/types.js").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,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 为已配置企业提取并持久化 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);
|
||
}
|
||
|
||
let 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;
|
||
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 expiresIn = options.expiresIn && options.expiresIn > 0 ? options.expiresIn : 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);
|
||
}
|
||
|
||
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 = 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 重新导入。`
|
||
);
|
||
}
|
||
|
||
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.floor((expMs - Date.now()) / 1000)),
|
||
expiresAt: formatBeijingIso(expMs),
|
||
persistent: canRefreshCorpAccessToken(corp),
|
||
method: "session-token",
|
||
};
|
||
}
|
||
|
||
// 保持历史命名兼容
|
||
export const importF12Credentials = importCredentials;
|
||
|
||
// ── 企业管理与主站 OAuth2 令牌换取 ─────────────────────────────────────────────
|
||
|
||
/**
|
||
* 列出当前账号名下的所有企业
|
||
*/
|
||
export async function listUserCorporations(
|
||
cloudAuthToken: string,
|
||
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
|
||
): Promise<CorporationItem[]> {
|
||
const res = await ky
|
||
.get(`${businessCenterUrl}/cloud-auth/public/auth/list-corporations`, {
|
||
headers: {
|
||
"cloud-auth-token": cloudAuthToken,
|
||
},
|
||
})
|
||
.json<{ data?: { items?: unknown[]; externalItems?: unknown[] }; errorCode?: number; errorMessage?: string }>();
|
||
|
||
if (!res.data?.items) {
|
||
throw new AuthenticationError(res.errorMessage || "获取企业列表失败");
|
||
}
|
||
|
||
const allItems = [...(res.data.items || []), ...(res.data.externalItems || [])];
|
||
return allItems.map((item) => CorporationItemSchema.parse(item));
|
||
}
|
||
|
||
/**
|
||
* 选定企业并换取主站 30 天有效期的 access_token
|
||
*/
|
||
export async function switchCorporationAndExchangeToken(
|
||
cloudAuthToken: string,
|
||
corp: CorporationItem,
|
||
accountId?: string,
|
||
idpUrl: string = DEFAULT_IDP_URL,
|
||
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL
|
||
): Promise<{ accessToken: string; refreshToken?: string; expiresIn: number; corpConfig: CorpConfig }> {
|
||
// 1. 在业务中心切换企业获取 authCode
|
||
const switchRes = await ky
|
||
.post(`${businessCenterUrl}/cloud-auth/public/auth/switch-corporation`, {
|
||
headers: {
|
||
"cloud-auth-token": cloudAuthToken,
|
||
},
|
||
json: {
|
||
corporationId: corp.corporationId,
|
||
userId: corp.userId,
|
||
cluster: corp.cluster,
|
||
},
|
||
})
|
||
.json<{ data?: { accessToken?: string }; errorCode?: number; errorMessage?: string }>();
|
||
|
||
const authCode = switchRes.data?.accessToken;
|
||
if (!authCode) {
|
||
throw new AuthenticationError(switchRes.errorMessage || `切换到企业 ${corp.corporationName} 失败`);
|
||
}
|
||
|
||
// 2. 用 authCode 向 IDP 换取真正的主站 access_token
|
||
const idpRes = await ky
|
||
.post(`${idpUrl}/api/idp/public/oauth2/token`, {
|
||
json: {
|
||
clientId: corp.clientId || "whispered-app",
|
||
grantType: "authorization_code",
|
||
code: authCode,
|
||
withIdToken: false,
|
||
},
|
||
})
|
||
.json<IdpOAuthTokenResponse>();
|
||
|
||
if (!idpRes.access_token) {
|
||
throw new AuthenticationError(`换取企业 ${corp.corporationName} 访问令牌失败`);
|
||
}
|
||
|
||
let resolvedAppKey: string | undefined;
|
||
let resolvedAppSecurity: string | undefined;
|
||
try {
|
||
const keys = await fetchOpenApiKeysBySession({
|
||
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||
accessToken: idpRes.access_token,
|
||
corpId: corp.corporationId,
|
||
});
|
||
if (keys.length > 0) {
|
||
const selected = selectOpenApiKey(keys, corp.corporationId, { force: true });
|
||
resolvedAppKey = selected.appKey;
|
||
resolvedAppSecurity = selected.appSecurity;
|
||
}
|
||
} catch {
|
||
// 非管理员或无密钥读取权限时静默跳过,保留账号级换票能力
|
||
}
|
||
|
||
const corpConfig: CorpConfig = {
|
||
id: corp.corporationId,
|
||
name: corp.corporationName,
|
||
corpId: corp.corporationId,
|
||
userId: corp.userId,
|
||
staffId: corp.staffId,
|
||
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||
source: "account",
|
||
accountId,
|
||
credentials: {
|
||
accessToken: idpRes.access_token,
|
||
corpId: corp.corporationId,
|
||
staffId: corp.staffId,
|
||
...(resolvedAppKey ? { appKey: resolvedAppKey } : {}),
|
||
...(resolvedAppSecurity ? { appSecurity: resolvedAppSecurity } : {}),
|
||
},
|
||
auth: {
|
||
refreshTtl: 300,
|
||
refreshToken: idpRes.refresh_token,
|
||
expiresAt: Date.now() + idpRes.expires_in * 1000,
|
||
},
|
||
};
|
||
|
||
return {
|
||
accessToken: idpRes.access_token,
|
||
refreshToken: idpRes.refresh_token,
|
||
expiresIn: idpRes.expires_in,
|
||
corpConfig,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 针对单个企业凭证进行静默无感自动续杯
|
||
* 支持双通道续期:
|
||
* 1. 用户级主账号 (IDP cloudAuthToken -> 30天 access_token)
|
||
* 2. 企业级开放平台持久化密钥 (appKey + appSecurity -> getProvisionalAuth 临时会话)
|
||
*/
|
||
export async function refreshSingleCorpAccessToken(
|
||
corp: CorpConfig,
|
||
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
|
||
idpUrl: string = DEFAULT_IDP_URL
|
||
): Promise<boolean> {
|
||
if (!canRefreshCorpAccessToken(corp)) return false;
|
||
|
||
// 通道 1:用户级主账号 IDP 换票
|
||
if (corp.source === "account" && !corp.session?.isShortTermToken && corp.accountId) {
|
||
const account = getAccount(corp.accountId);
|
||
if (account?.cloudAuthToken) {
|
||
try {
|
||
const corpItem: CorporationItem = {
|
||
corporationId: corp.corpId || corp.credentials.corpId,
|
||
corporationName: corp.name,
|
||
cluster: corp.cluster || "app",
|
||
clientId: "whispered-app",
|
||
staffId: corp.staffId || corp.credentials.staffId,
|
||
userId: corp.userId || account.userId || "",
|
||
baseUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||
external: false,
|
||
needAuth: false,
|
||
};
|
||
|
||
const res = await switchCorporationAndExchangeToken(
|
||
account.cloudAuthToken,
|
||
corpItem,
|
||
corp.accountId,
|
||
idpUrl,
|
||
businessCenterUrl
|
||
);
|
||
|
||
corp.credentials.accessToken = res.accessToken;
|
||
if (!corp.auth) corp.auth = { refreshTtl: 300 };
|
||
corp.auth.refreshToken = res.refreshToken;
|
||
corp.auth.expiresAt = Date.now() + res.expiresIn * 1000;
|
||
|
||
saveCorpConfig(corp);
|
||
return true;
|
||
} catch (err) {
|
||
if (!hasOpenApiPersistentCredentials(corp)) {
|
||
console.warn(`[auth] 自动续杯刷新企业 ${corp.name} 失败:`, err instanceof Error ? err.message : String(err));
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 通道 2:企业级 OpenAPI 持久化密钥 (appKey + appSecurity) 换取 Provisional Session
|
||
const openApiCreds = getCorpOpenApiCredentials(corp);
|
||
if (openApiCreds) {
|
||
try {
|
||
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
|
||
const corpId = corp.corpId || corp.credentials.corpId;
|
||
const staffId = corp.staffId || corp.credentials.staffId;
|
||
const openapiToken = await fetchHoseOpenApiAccessToken({
|
||
appKey: openApiCreds.appKey,
|
||
appSecurity: openApiCreds.appSecurity,
|
||
baseUrl,
|
||
});
|
||
const provisional = await fetchHoseProvisionalAuth({
|
||
baseUrl,
|
||
openapiToken,
|
||
corpId,
|
||
staffId,
|
||
expiresIn: 7200,
|
||
});
|
||
|
||
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);
|
||
return true;
|
||
} catch (err) {
|
||
console.warn(
|
||
`[auth] OpenAPI 持久化密钥续杯企业 ${corp.name} 失败:`,
|
||
err instanceof Error ? err.message : String(err)
|
||
);
|
||
return false;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
// ── 全流程一站式高阶函数 ─────────────────────────────────────────────────────
|
||
|
||
export interface FullLoginOptions {
|
||
targetCorpId?: string;
|
||
saveAll?: boolean;
|
||
enterprisesDir?: string;
|
||
idpUrl?: string;
|
||
businessCenterUrl?: string;
|
||
}
|
||
|
||
export interface FullLoginResult {
|
||
selectedCorp: CorpConfig;
|
||
allCorps: CorpConfig[];
|
||
cloudAuthToken: string;
|
||
accountId: string;
|
||
}
|
||
|
||
/**
|
||
* 账密登录全流程(登录 ➔ 存账号 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
|
||
*/
|
||
export async function fullPasswordLogin(
|
||
params: PasswordLoginParams & FullLoginOptions
|
||
): Promise<FullLoginResult> {
|
||
const { cloudAuthToken } = await loginByPassword(params);
|
||
const accountId = formatAccount(params.phone, params.areaCode);
|
||
return exchangeAndSaveCorporations(accountId, cloudAuthToken, params);
|
||
}
|
||
|
||
/**
|
||
* 短信验证码登录全流程(提交验证码 ➔ 存账号 ➔ 拉取企业 ➔ 换取 Token ➔ 保存配置)
|
||
*/
|
||
export async function fullSmsLogin(
|
||
params: SmsCodeLoginParams & FullLoginOptions
|
||
): Promise<FullLoginResult> {
|
||
const { cloudAuthToken } = await loginBySmsCode(params);
|
||
const accountId = formatAccount(params.phone, params.areaCode);
|
||
return exchangeAndSaveCorporations(accountId, cloudAuthToken, params);
|
||
}
|
||
|
||
/**
|
||
* 浏览器同步全流程(从浏览器提取 ➔ 换取 Token ➔ 保存配置)
|
||
*/
|
||
export async function fullBrowserSyncLogin(
|
||
options: FullLoginOptions & SyncBrowserLoginParams = {}
|
||
): Promise<FullLoginResult> {
|
||
const { cloudAuthToken, activeSession } = await syncFromBrowserSession(options);
|
||
|
||
if (cloudAuthToken) {
|
||
const accountId = "browser_session";
|
||
return exchangeAndSaveCorporations(accountId, cloudAuthToken, options);
|
||
}
|
||
|
||
if (activeSession) {
|
||
const singleCorp: CorpConfig = {
|
||
id: activeSession.corpId,
|
||
name: "当前浏览器企业",
|
||
baseUrl: "https://app.ekuaibao.com",
|
||
source: "browser",
|
||
credentials: {
|
||
accessToken: activeSession.accessToken,
|
||
corpId: activeSession.corpId,
|
||
staffId: activeSession.staffId || `${activeSession.corpId}:admin`,
|
||
},
|
||
};
|
||
saveCorpConfig(singleCorp, options.enterprisesDir);
|
||
return {
|
||
selectedCorp: singleCorp,
|
||
allCorps: [singleCorp],
|
||
cloudAuthToken: "",
|
||
accountId: "browser_session",
|
||
};
|
||
}
|
||
|
||
throw new AuthenticationError("未能同步到有效登录会话");
|
||
}
|
||
|
||
/**
|
||
* 刷新指定账号下的所有企业 Token
|
||
*/
|
||
export async function refreshAccountCorporations(
|
||
accountId?: string,
|
||
options: FullLoginOptions = {}
|
||
): Promise<FullLoginResult> {
|
||
let account: AccountEntry | undefined;
|
||
if (accountId) {
|
||
account = getAccount(accountId);
|
||
} else {
|
||
account = getActiveAccount();
|
||
}
|
||
|
||
if (!account || !account.cloudAuthToken) {
|
||
throw new AuthenticationError(
|
||
accountId ? `未找到账号 ${accountId} 的登录凭证` : "当前无活跃账号,请先登录"
|
||
);
|
||
}
|
||
|
||
return exchangeAndSaveCorporations(account.accountId, account.cloudAuthToken, {
|
||
...options,
|
||
saveAll: true,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 内部统一:根据 cloudAuthToken 批量换票并保存账号与企业配置
|
||
*/
|
||
async function exchangeAndSaveCorporations(
|
||
accountId: string,
|
||
cloudAuthToken: string,
|
||
options: FullLoginOptions
|
||
): Promise<FullLoginResult> {
|
||
const corporations = await listUserCorporations(cloudAuthToken, options.businessCenterUrl);
|
||
if (corporations.length === 0) {
|
||
throw new AuthenticationError("该账号名下未找到任何可用企业");
|
||
}
|
||
|
||
// 1. 确定目标企业
|
||
let target = corporations.find((c) => c.corporationId === options.targetCorpId);
|
||
if (!target) {
|
||
target = corporations[0];
|
||
}
|
||
|
||
// 2. 保存账号根索引到 accounts.json
|
||
const accountEntry: AccountEntry = {
|
||
accountId,
|
||
userId: corporations[0]?.userId,
|
||
cloudAuthToken,
|
||
activeCorpId: target.corporationId,
|
||
createdAt: Date.now(),
|
||
updatedAt: Date.now(),
|
||
corporations: corporations.map((c) => ({
|
||
id: c.corporationId,
|
||
name: c.corporationName,
|
||
staffId: c.staffId,
|
||
cluster: c.cluster,
|
||
baseUrl: c.baseUrl,
|
||
})),
|
||
};
|
||
saveAccount(accountEntry);
|
||
|
||
const allConfigs: CorpConfig[] = [];
|
||
let selectedCorpConfig: CorpConfig | null = null;
|
||
|
||
if (options.saveAll !== false) {
|
||
// 换取全部企业的 Token 并保存
|
||
for (const corp of corporations) {
|
||
try {
|
||
const { corpConfig } = await switchCorporationAndExchangeToken(
|
||
cloudAuthToken,
|
||
corp,
|
||
accountId,
|
||
options.idpUrl,
|
||
options.businessCenterUrl
|
||
);
|
||
allConfigs.push(corpConfig);
|
||
if (corp.corporationId === target.corporationId) {
|
||
selectedCorpConfig = corpConfig;
|
||
}
|
||
} catch (err) {
|
||
console.warn(`[auth] 跳过企业 ${corp.corporationName}:`, err instanceof Error ? err.message : String(err));
|
||
}
|
||
}
|
||
saveMultipleCorpConfigs(allConfigs, options.enterprisesDir);
|
||
} else {
|
||
// 仅换取选定的目标企业
|
||
const { corpConfig } = await switchCorporationAndExchangeToken(
|
||
cloudAuthToken,
|
||
target,
|
||
accountId,
|
||
options.idpUrl,
|
||
options.businessCenterUrl
|
||
);
|
||
selectedCorpConfig = corpConfig;
|
||
allConfigs.push(corpConfig);
|
||
saveCorpConfig(corpConfig, options.enterprisesDir);
|
||
}
|
||
|
||
return {
|
||
selectedCorp: selectedCorpConfig || allConfigs[0],
|
||
allCorps: allConfigs,
|
||
cloudAuthToken,
|
||
accountId,
|
||
};
|
||
}
|