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(); const openapiV1TokenInflight = new Map>(); export async function fetchHoseOpenApiAccessToken(params: { appKey: string; appSecurity: string; baseUrl?: string; forceRefresh?: boolean; }): Promise { 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 { 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; 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-id 显式指定,或追加 --force 自动选用第一套启用密钥。` ); } export async function probeHoseDomain( appKey: string, appSecurity: string, explicitDomain?: string ): Promise { 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 { 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 { 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 { 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, }; }