import ky from "ky"; import { CorpConfig } from "../../core/config/types.js"; import { createAuthClient } from "../../core/http/factory.js"; import { AuthenticationError } from "../../core/errors.js"; import { resolveCorpCluster } from "./easo.js"; const PIPER_BASE_URL = "https://piper.ekuaibao.com"; const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com"; const EKB_BASE_URL = "https://app.ekuaibao.com"; // 内存缓存 const piperMemoryCache = new Map< string, { jwt: string; hoseToken: string; expiresAt: number } >(); function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean { return Date.now() >= entry.expiresAt - refreshTtl * 1000; } async function fetchHoseToken( accessToken: string, corpId: string, environment: string = "app" ): Promise { const response = await ky .get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, { searchParams: { corpId, ekbAccessToken: accessToken, environment, }, }) .json<{ data: string }>(); if (!response.data) { throw new AuthenticationError("Failed to fetch hose-access-token"); } return response.data; } async function fetchEasoJwt( accessToken: string, corpId: string, staffId: string, baseUrl: string = EKB_BASE_URL ): Promise { const response = await ky .get(`${baseUrl}/api/engine/realm/$EASO/actions/jwt`, { searchParams: { corpId }, headers: { accesstoken: accessToken, corpid: corpId, staffid: staffId, }, }) .json<{ id?: string; value?: string }>(); const token = response.id || response.value; if (!token) { throw new AuthenticationError("Failed to fetch EASO JWT"); } return token; } export async function getPiperClient( corp: CorpConfig, platformId: string ): Promise> { const refreshTtl = corp.auth?.refreshTtl ?? 300; const cacheKey = `${corp.id}:${platformId}:piper`; // 检查内存缓存 const mem = piperMemoryCache.get(cacheKey); if (mem && !isExpired(mem, refreshTtl)) { return createAuthClient({ prefixUrl: PIPER_BASE_URL, getHeaders: () => ({ Authorization: `Bearer ${mem.jwt}`, platformid: platformId, }), onUnauthorized: () => { piperMemoryCache.delete(cacheKey); }, }); } const corpId = corp.corpId || corp.credentials.corpId; const staffId = corp.staffId || corp.credentials.staffId; const environment = resolveCorpCluster(corp); const baseUrl = corp.baseUrl || EKB_BASE_URL; // 重新换取 const hoseToken = await fetchHoseToken( corp.credentials.accessToken, corpId, environment ); const easoJwt = await fetchEasoJwt( corp.credentials.accessToken, corpId, staffId, baseUrl ); const entry = { jwt: easoJwt, hoseToken, expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时 }; piperMemoryCache.set(cacheKey, entry); return createAuthClient({ prefixUrl: PIPER_BASE_URL, getHeaders: () => ({ Authorization: `Bearer ${easoJwt}`, platformid: platformId, hoseaccesstoken: hoseToken, }), onUnauthorized: () => { piperMemoryCache.delete(cacheKey); }, }); }