From aa69b50e6e93a05fb7f8ce672c17abe52a4f9a9f Mon Sep 17 00:00:00 2001 From: yunyingk Date: Thu, 17 Sep 2026 15:32:56 +0800 Subject: [PATCH] =?UTF-8?q?refactor(core):=20=E6=8A=BD=E8=B1=A1=E8=AF=AD?= =?UTF-8?q?=E4=B9=89=E5=8C=96=20HTTP=20=E5=AE=A2=E6=88=B7=E7=AB=AF?= =?UTF-8?q?=E4=B8=8E=E7=BB=9F=E4=B8=80=E9=98=B2=E7=88=AC=E6=8C=87=E7=BA=B9?= =?UTF-8?q?=E7=AE=A1=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/README.core.md | 22 ++- src/core/auth/easo.ts | 244 ++------------------------ src/core/auth/ekb.ts | 50 ++---- src/core/auth/piper.ts | 133 ++------------ src/core/http/clients.test.ts | 116 ++++++++++++ src/core/http/fingerprint.ts | 48 +++++ src/core/http/index.ts | 55 ++++++ src/core/http/openapi-client.ts | 133 ++++++++++++++ src/core/http/script-engine-client.ts | 116 ++++++++++++ src/core/http/session-client.ts | 79 +++++++++ src/core/http/unity-client.ts | 239 +++++++++++++++++++++++++ 11 files changed, 834 insertions(+), 401 deletions(-) create mode 100644 src/core/http/clients.test.ts create mode 100644 src/core/http/fingerprint.ts create mode 100644 src/core/http/index.ts create mode 100644 src/core/http/openapi-client.ts create mode 100644 src/core/http/script-engine-client.ts create mode 100644 src/core/http/session-client.ts create mode 100644 src/core/http/unity-client.ts diff --git a/src/core/README.core.md b/src/core/README.core.md index 4b2275b..e766e62 100644 --- a/src/core/README.core.md +++ b/src/core/README.core.md @@ -6,15 +6,23 @@ Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存 ```text src/core/ -├── auth/ # 登录认证与 Token 获取、刷新、缓存 +├── auth/ # 登录认证协议与凭证存储(纯凭据层) │ ├── login.ts # 登录四矩阵(RSA账密登录、短信验证码、F12/cURL凭证导入、浏览器同步) │ ├── account-store.ts # 多账号持久化存储 (~/.cache/ekb-mcp/accounts.json) │ ├── tools.ts # MCP Auth Tools 注册与调度 -│ ├── ekb.ts # 快报主站三 Header 认证 -│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证 -│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证 │ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径) -│ └── types.ts +│ ├── types.ts +│ ├── ekb.ts # 【向后兼容桥接】re-export http/session-client.js +│ ├── easo.ts # 【向后兼容桥接】re-export http/unity-client.js +│ └── piper.ts # 【向后兼容桥接】re-export http/script-engine-client.js +├── http/ # 统一 HTTP 客户端装配与网络传输(语义化客户端) +│ ├── factory.ts # Ky 底层客户端工厂(超时、重试、错误钩子) +│ ├── fingerprint.ts # 统一浏览器指纹、User-Agent、Cookie 与 WAF 策略头 +│ ├── session-client.ts # 闭合用户会话客户端(三 Header + 指纹 + 401 续杯) +│ ├── openapi-client.ts # 开放平台应用客户端(appKey 换票与签名机制) +│ ├── unity-client.ts # 应用中心与动态集群寻址客户端 +│ ├── script-engine-client.ts # 工作流 MVEL/Python 脚本调试引擎客户端 +│ └── index.ts # 统一导出入口 ├── cache/ # 统一多级协同缓存 │ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理) │ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用) @@ -28,14 +36,12 @@ src/core/ │ ├── loader.ts │ ├── manager.ts │ └── types.ts -├── http/ # HTTP 客户端工厂 -│ └── factory.ts └── errors.ts # 统一异常语义(EkbError 子类) ``` ## 分层约束 -- `domains/*/api.ts` 只通过 `core/http/factory.ts` 或 `core/auth/*` 获取客户端 +- `domains/*` 优先通过 `core/http/` 获取语义化客户端(`createSessionClient`, `createOpenApiClient`, `getUnityClient`, `getScriptEngineClient`),保持底层网络与指纹统一 - `domains/*` 层只抛 `EkbError` 子类 - `server.ts` 负责把 `EkbError` 映射为 MCP error - 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面 diff --git a/src/core/auth/easo.ts b/src/core/auth/easo.ts index 49c39f3..f37abf0 100644 --- a/src/core/auth/easo.ts +++ b/src/core/auth/easo.ts @@ -1,230 +1,14 @@ -import ky from "ky"; -import { CorpConfig } from "../../core/config/types.js"; -import { createAuthClient } from "../../core/http/factory.js"; -import { AuthenticationError } from "../../core/errors.js"; - -const EASO_BASE_URL = "https://unity.ekuaibao.com"; -const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com"; -const EKB_BASE_URL = "https://app.ekuaibao.com"; - -export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string }): string { - if (corp.cluster && corp.cluster.trim()) { - return corp.cluster.trim(); - } - if (corp.baseUrl) { - try { - const url = new URL(corp.baseUrl); - const match = /^([a-z0-9-]+)\.ekuaibao\.com$/i.exec(url.hostname); - if (match && match[1]) { - return match[1].toLowerCase(); - } - } catch {} - } - return "app"; -} - -// 内存缓存 -const easoMemoryCache = new Map< - string, - { token: string; hoseToken: string; expiresAt: number } ->(); - -const unityMemoryCache = new Map< - string, - { token: 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; -} - -export async function fetchUnityJwt( - accessToken: string, - corpId: string, - staffId: string, - baseUrl: string = EKB_BASE_URL -): Promise { - const response = await ky - .get(`${baseUrl}/api/engine/realm/$UNITY/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 UNITY JWT"); - } - return token; -} - -async function fetchEasoRealmToken( - corpId: string, - unityJwt: string, - hoseToken: string -): Promise { - const response = await ky - .get(`${EASO_BASE_URL}/api/realms/EASO`, { - searchParams: { corpId }, - headers: { - Authorization: `Bearer ${unityJwt}`, - hoseaccesstoken: hoseToken, - }, - }) - .json<{ value?: { accessToken?: string } }>(); - const token = response.value?.accessToken; - if (!token) { - throw new AuthenticationError("Failed to fetch EASO realm token"); - } - return token; -} - -export async function getEasoClient(corp: CorpConfig): Promise<{ - client: ReturnType; -}> { - const refreshTtl = corp.auth?.refreshTtl ?? 300; - const cacheKey = `${corp.id}:easo`; - - // 检查内存缓存 - const mem = easoMemoryCache.get(cacheKey); - if (mem && !isExpired(mem, refreshTtl)) { - return { - client: createAuthClient({ - prefixUrl: EASO_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${mem.token}`, - accesstoken: corp.credentials.accessToken, - corporationid: corp.credentials.corpId, - hoseaccesstoken: mem.hoseToken, - }), - onUnauthorized: () => { - easoMemoryCache.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 unityJwt = await fetchUnityJwt( - corp.credentials.accessToken, - corpId, - staffId, - baseUrl - ); - const easoToken = await fetchEasoRealmToken( - corpId, - unityJwt, - hoseToken - ); - - const entry = { - token: easoToken, - hoseToken, - expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时 - }; - - easoMemoryCache.set(cacheKey, entry); - - return { - client: createAuthClient({ - prefixUrl: EASO_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${easoToken}`, - accesstoken: corp.credentials.accessToken, - corporationid: corpId, - hoseaccesstoken: hoseToken, - }), - onUnauthorized: () => { - easoMemoryCache.delete(cacheKey); - }, - }), - }; -} - -export async function getUnityClient(corp: CorpConfig): Promise<{ - client: ReturnType; - unityJwt: string; -}> { - const refreshTtl = corp.auth?.refreshTtl ?? 300; - const cacheKey = `${corp.id}:unity`; - - const mem = unityMemoryCache.get(cacheKey); - if (mem && !isExpired(mem, refreshTtl)) { - return { - unityJwt: mem.token, - client: createAuthClient({ - prefixUrl: EASO_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${mem.token}`, - }), - onUnauthorized: () => { - unityMemoryCache.delete(cacheKey); - }, - }), - }; - } - - const corpId = corp.corpId || corp.credentials.corpId; - const staffId = corp.staffId || corp.credentials.staffId; - const baseUrl = corp.baseUrl || EKB_BASE_URL; - - const unityJwt = await fetchUnityJwt( - corp.credentials.accessToken, - corpId, - staffId, - baseUrl - ); - - const entry = { - token: unityJwt, - expiresAt: Date.now() + 2 * 60 * 60 * 1000, - }; - unityMemoryCache.set(cacheKey, entry); - - return { - unityJwt, - client: createAuthClient({ - prefixUrl: EASO_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${unityJwt}`, - }), - onUnauthorized: () => { - unityMemoryCache.delete(cacheKey); - }, - }), - }; -} - +/** + * @deprecated 兼容历史导出。请优先从 "src/core/http/index.js" 导入 getUnityClient 与 getEasoClient + */ +export { + resolveCorpCluster, + fetchUnityJwt, + fetchHoseToken, + fetchEasoRealmToken, + getEasoClient, + getUnityClient, + EASO_BASE_URL, + BUSINESS_CENTER_URL, + EKB_BASE_URL, +} from "../http/unity-client.js"; diff --git a/src/core/auth/ekb.ts b/src/core/auth/ekb.ts index bb8fc53..fb87407 100644 --- a/src/core/auth/ekb.ts +++ b/src/core/auth/ekb.ts @@ -1,40 +1,10 @@ -import { CorpConfig } from "../config/types.js"; -import { AuthenticationError } from "../errors.js"; -import { createAuthClient } from "../http/factory.js"; -import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js"; - -export function getEkbHeaders(corp: CorpConfig): Record { - return { - accesstoken: corp.credentials.accessToken, - corpid: corp.corpId || corp.credentials.corpId, - staffid: corp.staffId || corp.credentials.staffId, - }; -} - -export async function createEkbClient(corp: CorpConfig) { - const canRefresh = canRefreshCorpAccessToken(corp); - - // 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯 - if (canRefresh && corp.auth?.expiresAt) { - const ttlMs = (corp.auth.refreshTtl || 300) * 1000; - if (Date.now() >= corp.auth.expiresAt - ttlMs) { - await refreshSingleCorpAccessToken(corp); - } - } - - // 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误 - return createAuthClient({ - prefixUrl: corp.baseUrl || "https://app.ekuaibao.com", - getHeaders: () => getEkbHeaders(corp), - retryUnauthorized: canRefresh, - ...(canRefresh - ? { - onUnauthorized: async () => { - await refreshSingleCorpAccessToken(corp); - }, - } - : { - onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"), - }), - }); -} +/** + * @deprecated 兼容历史导出。请优先从 "src/core/http/index.js" 导入 createSessionClient 与 getSessionHeaders + */ +export { + createSessionClient, + getSessionHeaders, + createEkbClient, + getEkbHeaders, + type CreateSessionClientOptions, +} from "../http/session-client.js"; diff --git a/src/core/auth/piper.ts b/src/core/auth/piper.ts index c3ae4a8..7b3435f 100644 --- a/src/core/auth/piper.ts +++ b/src/core/auth/piper.ts @@ -1,123 +1,10 @@ -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); - }, - }); -} +/** + * @deprecated 兼容历史导出。请优先从 "src/core/http/index.js" 导入 getScriptEngineClient 与 getPiperClient + */ +export { + getScriptEngineClient, + getPiperClient, + fetchEasoJwt, + SCRIPT_ENGINE_BASE_URL, + PIPER_BASE_URL, +} from "../http/script-engine-client.js"; diff --git a/src/core/http/clients.test.ts b/src/core/http/clients.test.ts new file mode 100644 index 0000000..8424a36 --- /dev/null +++ b/src/core/http/clients.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from "bun:test"; +import { + getBrowserFingerprintHeaders, + DEFAULT_USER_AGENT, + DEFAULT_REFERER, + DEFAULT_ORIGIN, +} from "./fingerprint.js"; +import { + getSessionHeaders, + createSessionClient, + createEkbClient, +} from "./session-client.js"; +import { + createOpenApiClient, + getOpenApiHeaders, +} from "./openapi-client.js"; +import { resolveCorpCluster } from "./unity-client.js"; +import { getScriptEngineClient, getPiperClient } from "./script-engine-client.js"; +import type { CorpConfig } from "../config/types.js"; + +function mockCorp(overrides: Partial = {}): CorpConfig { + return { + id: "mock-corp", + name: "测试企业", + source: "link", + credentials: { + accessToken: "mock-access-token", + corpId: "mock-corp-id", + staffId: "mock-staff-id", + }, + baseUrl: "https://app.ekuaibao.com", + ...overrides, + }; +} + +describe("core/http/fingerprint", () => { + it("generates default modern browser fingerprint headers", () => { + const headers = getBrowserFingerprintHeaders(); + expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT); + expect(headers["Referer"]).toBe(DEFAULT_REFERER); + expect(headers["Origin"]).toBe(DEFAULT_ORIGIN); + expect(headers["sec-ch-ua-platform"]).toBe('"macOS"'); + expect(headers["sec-ch-ua"]).toContain("Chrome"); + expect(headers["Cookie"]).toBeUndefined(); + }); + + it("supports custom cookie and referer", () => { + const headers = getBrowserFingerprintHeaders({ + cookie: "SESSION=abc123xyz; cloud_waf=token456", + referer: "https://custom.ekuaibao.com/flow", + }); + expect(headers["Cookie"]).toBe("SESSION=abc123xyz; cloud_waf=token456"); + expect(headers["Referer"]).toBe("https://custom.ekuaibao.com/flow"); + }); +}); + +describe("core/http/session-client", () => { + it("merges closed session headers with browser fingerprint", () => { + const corp = mockCorp(); + const headers = getSessionHeaders(corp); + + // 核心三 Header 校验 + expect(headers.accesstoken).toBe("mock-access-token"); + expect(headers.corpid).toBe("mock-corp-id"); + expect(headers.staffid).toBe("mock-staff-id"); + + // 统一防爬指纹校验 + expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT); + expect(headers["Origin"]).toBe(DEFAULT_ORIGIN); + }); + + it("createSessionClient and createEkbClient alias produce valid clients", async () => { + const corp = mockCorp(); + const client1 = await createSessionClient(corp); + const client2 = await createEkbClient(corp); + + expect(client1).toBeDefined(); + expect(client2).toBeDefined(); + }); +}); + +describe("core/http/openapi-client", () => { + it("builds correct OpenAPI request headers", () => { + const headers = getOpenApiHeaders("test-app-token-123"); + expect(headers["app-token"]).toBe("test-app-token-123"); + expect(headers["Authorization"]).toBe("Bearer test-app-token-123"); + expect(headers["User-Agent"]).toBe(DEFAULT_USER_AGENT); + }); + + it("creates OpenAPI client with static appToken", async () => { + const client = await createOpenApiClient({ + appToken: "static-token", + baseUrl: "https://app.ekuaibao.com", + }); + expect(client).toBeDefined(); + }); + + it("fails to create OpenAPI client when neither auth nor appToken is provided", async () => { + await expect(createOpenApiClient({})).rejects.toThrow( + "创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken" + ); + }); +}); + +describe("core/http/unity-client & script-engine-client", () => { + it("resolves corp cluster from cluster property or baseUrl", () => { + expect(resolveCorpCluster({ cluster: "shanghai" })).toBe("shanghai"); + expect(resolveCorpCluster({ baseUrl: "https://wx2.ekuaibao.com" })).toBe("wx2"); + expect(resolveCorpCluster({ baseUrl: "https://app.ekuaibao.com" })).toBe("app"); + expect(resolveCorpCluster({})).toBe("app"); + }); + + it("getPiperClient alias points to getScriptEngineClient", () => { + expect(getPiperClient).toBe(getScriptEngineClient); + }); +}); diff --git a/src/core/http/fingerprint.ts b/src/core/http/fingerprint.ts new file mode 100644 index 0000000..0605e11 --- /dev/null +++ b/src/core/http/fingerprint.ts @@ -0,0 +1,48 @@ +/** + * 统一浏览器指纹与请求头生成器 + * 用于防范 WAF 拦截 (如 CloudWAF 418/403) 及统一 Web 会话环境 + */ + +export interface BrowserFingerprintOptions { + /** 自定义 Cookie 字符串 */ + cookie?: string; + /** 自定义 Referer 来源 (默认 https://app.ekuaibao.com/) */ + referer?: string; + /** 自定义 Origin 域 (默认 https://app.ekuaibao.com) */ + origin?: string; + /** 是否禁用 Sec-Ch-Ua 等客户端提示头 (默认 false) */ + disableClientHints?: boolean; +} + +export const DEFAULT_USER_AGENT = + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"; + +export const DEFAULT_REFERER = "https://app.ekuaibao.com/"; +export const DEFAULT_ORIGIN = "https://app.ekuaibao.com"; + +/** + * 获取伪装现代浏览器的标准指纹请求头 + */ +export function getBrowserFingerprintHeaders( + options: BrowserFingerprintOptions = {} +): Record { + const headers: Record = { + "User-Agent": DEFAULT_USER_AGENT, + Accept: "application/json, text/plain, */*", + "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", + Referer: options.referer ?? DEFAULT_REFERER, + Origin: options.origin ?? DEFAULT_ORIGIN, + }; + + if (!options.disableClientHints) { + headers["sec-ch-ua"] = '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"'; + headers["sec-ch-ua-mobile"] = "?0"; + headers["sec-ch-ua-platform"] = '"macOS"'; + } + + if (options.cookie && options.cookie.trim()) { + headers["Cookie"] = options.cookie.trim(); + } + + return headers; +} diff --git a/src/core/http/index.ts b/src/core/http/index.ts new file mode 100644 index 0000000..983a546 --- /dev/null +++ b/src/core/http/index.ts @@ -0,0 +1,55 @@ +/** + * HTTP 客户端基础设施总入口 + * 包含基础 Ky 客户端工厂、浏览器指纹伪装、闭合用户会话客户端、开放平台客户端、集群客户端及脚本流引擎客户端。 + */ + +// 1. 底层 Ky 基础工厂 +export { + createClient, + createAuthClient, + type CreateClientOptions, + type CreateAuthClientOptions, +} from "./factory.js"; + +// 2. 统一浏览器指纹与防爬请求头 +export { + getBrowserFingerprintHeaders, + DEFAULT_USER_AGENT, + DEFAULT_REFERER, + DEFAULT_ORIGIN, + type BrowserFingerprintOptions, +} from "./fingerprint.js"; + +// 3. 闭合用户会话客户端 (Session Client) +export { + createSessionClient, + getSessionHeaders, + createEkbClient, + getEkbHeaders, + type CreateSessionClientOptions, +} from "./session-client.js"; + +// 4. 开放平台 OpenAPI 客户端 (OpenAPI Client) +export { + createOpenApiClient, + fetchOpenApiToken, + getOpenApiHeaders, + type OpenApiAuthConfig, + type CreateOpenApiClientOptions, +} from "./openapi-client.js"; + +// 5. 应用中心与集群寻址客户端 (Unity Client) +export { + getUnityClient, + getEasoClient, + resolveCorpCluster, + fetchUnityJwt, + fetchHoseToken, +} from "./unity-client.js"; + +// 6. 工作流脚本调试引擎客户端 (Script Engine Client) +export { + getScriptEngineClient, + getPiperClient, + fetchEasoJwt, +} from "./script-engine-client.js"; diff --git a/src/core/http/openapi-client.ts b/src/core/http/openapi-client.ts new file mode 100644 index 0000000..0250c02 --- /dev/null +++ b/src/core/http/openapi-client.ts @@ -0,0 +1,133 @@ +import ky, { type KyInstance } from "ky"; +import { createAuthClient, createClient } from "./factory.js"; +import { + getBrowserFingerprintHeaders, + type BrowserFingerprintOptions, +} from "./fingerprint.js"; +import { AuthenticationError } from "../errors.js"; + +export interface OpenApiAuthConfig { + /** 开放应用 AppKey */ + appKey: string; + /** 开放应用 AppSecurity / AppSecret */ + appSecurity: string; + /** 自定义网关基准地址 (默认 https://app.ekuaibao.com) */ + baseUrl?: string; +} + +export interface CreateOpenApiClientOptions { + /** 开放平台应用认证凭据 */ + auth?: OpenApiAuthConfig; + /** 直接传入已知且有效的 app-token */ + appToken?: string; + /** 基础 API URL (默认 https://app.ekuaibao.com) */ + baseUrl?: string; + /** 请求超时 (默认 30000ms) */ + timeout?: number | false; + /** 浏览器与网络指纹配置 */ + fingerprint?: BrowserFingerprintOptions; +} + +// 内存缓存:OpenAPI Token 缓存表 +const openApiTokenCache = new Map(); + +/** + * 通过开放平台应用凭据 (appKey + appSecurity) 获取 app-token + */ +export async function fetchOpenApiToken( + auth: OpenApiAuthConfig +): Promise { + const baseUrl = auth.baseUrl || "https://app.ekuaibao.com"; + const cacheKey = `${auth.appKey}:${baseUrl}`; + + const cached = openApiTokenCache.get(cacheKey); + if (cached && Date.now() < cached.expiresAt - 300 * 1000) { + return cached.token; + } + + try { + const response = await ky + .post(`${baseUrl}/api/openapi/v2/auth/token`, { + json: { + appKey: auth.appKey, + appSecurity: auth.appSecurity, + }, + timeout: 15000, + }) + .json<{ value?: string; token?: string; accessToken?: string }>(); + + const token = response.value || response.token || response.accessToken; + if (!token) { + throw new AuthenticationError("获取 OpenAPI app-token 失败: 返回值缺少 token"); + } + + // 默认缓存 110 分钟 (标准有效期通常为 2 小时) + openApiTokenCache.set(cacheKey, { + token, + expiresAt: Date.now() + 110 * 60 * 1000, + }); + + return token; + } catch (error: any) { + if (error instanceof AuthenticationError) throw error; + throw new AuthenticationError( + `OpenAPI 换票失败 (${auth.appKey}): ${error?.message || String(error)}` + ); + } +} + +/** + * 组装 OpenAPI 专属请求头 + */ +export function getOpenApiHeaders( + appToken?: string, + options?: BrowserFingerprintOptions +): Record { + const headers = getBrowserFingerprintHeaders(options); + if (appToken) { + headers["app-token"] = appToken; + headers["Authorization"] = `Bearer ${appToken}`; + } + return headers; +} + +/** + * 创建合思开放平台客户端 (OpenAPI Client) + * 适用于自建应用、OpenAPI 接口调用与机器系统对接 + */ +export async function createOpenApiClient( + options: CreateOpenApiClientOptions +): Promise { + const baseUrl = options.baseUrl || options.auth?.baseUrl || "https://app.ekuaibao.com"; + + // 若直接提供静态 token 且无自动换票凭据 + if (options.appToken && !options.auth) { + const staticToken = options.appToken; + return createClient({ + prefixUrl: baseUrl, + headers: getOpenApiHeaders(staticToken, options.fingerprint), + timeout: options.timeout, + }); + } + + // 若提供 appKey / appSecurity,则构建支持 401 自动换票重试的 Client + if (options.auth) { + const authConfig = options.auth; + let currentToken = options.appToken || (await fetchOpenApiToken(authConfig)); + + return createAuthClient({ + prefixUrl: baseUrl, + timeout: options.timeout, + getHeaders: () => getOpenApiHeaders(currentToken, options.fingerprint), + retryUnauthorized: true, + onUnauthorized: async () => { + const cacheKey = `${authConfig.appKey}:${authConfig.baseUrl || baseUrl}`; + openApiTokenCache.delete(cacheKey); + currentToken = await fetchOpenApiToken(authConfig); + }, + }); + } + + // 既无 token 又无 auth,抛出参数异常 + throw new AuthenticationError("创建 OpenAPI 客户端失败: 必须提供 auth 凭据或 appToken"); +} diff --git a/src/core/http/script-engine-client.ts b/src/core/http/script-engine-client.ts new file mode 100644 index 0000000..43702dc --- /dev/null +++ b/src/core/http/script-engine-client.ts @@ -0,0 +1,116 @@ +import ky from "ky"; +import type { CorpConfig } from "../config/types.js"; +import { createAuthClient } from "./factory.js"; +import { AuthenticationError } from "../errors.js"; +import { + resolveCorpCluster, + fetchHoseToken, + EKB_BASE_URL, +} from "./unity-client.js"; + +export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com"; + +// 兼容历史常量名 +export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL; + +// 内存缓存 +const scriptEngineMemoryCache = new Map< + string, + { jwt: string; hoseToken: string; expiresAt: number } +>(); + +function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean { + return Date.now() >= entry.expiresAt - refreshTtl * 1000; +} + +export 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; +} + +/** + * 获取工作流脚本执行引擎客户端 (Workflow Script Engine Client / Piper Client) + * 适用于 MVEL、Python 等工作流代码节点的在线执行与调试 + */ +export async function getScriptEngineClient( + corp: CorpConfig, + platformId: string +): Promise> { + const refreshTtl = corp.auth?.refreshTtl ?? 300; + const cacheKey = `${corp.id}:${platformId}:script-engine`; + + // 检查内存缓存 + const mem = scriptEngineMemoryCache.get(cacheKey); + if (mem && !isExpired(mem, refreshTtl)) { + return createAuthClient({ + prefixUrl: SCRIPT_ENGINE_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${mem.jwt}`, + platformid: platformId, + }), + onUnauthorized: () => { + scriptEngineMemoryCache.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小时 + }; + + scriptEngineMemoryCache.set(cacheKey, entry); + + return createAuthClient({ + prefixUrl: SCRIPT_ENGINE_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${easoJwt}`, + platformid: platformId, + hoseaccesstoken: hoseToken, + }), + onUnauthorized: () => { + scriptEngineMemoryCache.delete(cacheKey); + }, + }); +} + +// ── 向后兼容别名 ───────────────────────────────────────────────────────────── +/** @deprecated 推荐使用 getScriptEngineClient */ +export const getPiperClient = getScriptEngineClient; diff --git a/src/core/http/session-client.ts b/src/core/http/session-client.ts new file mode 100644 index 0000000..113026c --- /dev/null +++ b/src/core/http/session-client.ts @@ -0,0 +1,79 @@ +import type { CorpConfig } from "../config/types.js"; +import { AuthenticationError } from "../errors.js"; +import { createAuthClient } from "./factory.js"; +import { + getBrowserFingerprintHeaders, + type BrowserFingerprintOptions, +} from "./fingerprint.js"; +import { + canRefreshCorpAccessToken, + refreshSingleCorpAccessToken, +} from "../auth/login.js"; + +export interface CreateSessionClientOptions { + /** 额外的指纹或请求头配置 */ + fingerprint?: BrowserFingerprintOptions; + /** 超时毫秒数 (默认 30000) */ + timeout?: number | false; +} + +/** + * 获取闭合用户会话所必需的认证请求头与浏览器指纹 + */ +export function getSessionHeaders( + corp: CorpConfig, + fingerprintOptions?: BrowserFingerprintOptions +): Record { + const baseHeaders = getBrowserFingerprintHeaders(fingerprintOptions); + + return { + ...baseHeaders, + accesstoken: corp.credentials.accessToken, + corpid: corp.corpId || corp.credentials.corpId, + staffid: corp.staffId || corp.credentials.staffId, + }; +} + +/** + * 创建合思闭合用户会话客户端 (Session Client) + * 适用于内部单据台账、审批流、员工角色、配置等闭环操作 + */ +export async function createSessionClient( + corp: CorpConfig, + options: CreateSessionClientOptions = {} +) { + const canRefresh = canRefreshCorpAccessToken(corp); + + // 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯 + if (canRefresh && corp.auth?.expiresAt) { + const ttlMs = (corp.auth.refreshTtl || 300) * 1000; + if (Date.now() >= corp.auth.expiresAt - ttlMs) { + await refreshSingleCorpAccessToken(corp); + } + } + + // 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误 + return createAuthClient({ + prefixUrl: corp.baseUrl || "https://app.ekuaibao.com", + getHeaders: () => getSessionHeaders(corp, options.fingerprint), + timeout: options.timeout, + retryUnauthorized: canRefresh, + ...(canRefresh + ? { + onUnauthorized: async () => { + await refreshSingleCorpAccessToken(corp); + }, + } + : { + onAuthFailure: () => + new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"), + }), + }); +} + +// ── 向后兼容别名 ───────────────────────────────────────────────────────────── +/** @deprecated 推荐使用 getSessionHeaders */ +export const getEkbHeaders = getSessionHeaders; + +/** @deprecated 推荐使用 createSessionClient */ +export const createEkbClient = createSessionClient; diff --git a/src/core/http/unity-client.ts b/src/core/http/unity-client.ts new file mode 100644 index 0000000..24521b3 --- /dev/null +++ b/src/core/http/unity-client.ts @@ -0,0 +1,239 @@ +import ky from "ky"; +import type { CorpConfig } from "../config/types.js"; +import { createAuthClient } from "./factory.js"; +import { AuthenticationError } from "../errors.js"; + +export const EASO_BASE_URL = "https://unity.ekuaibao.com"; +export const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com"; +export const EKB_BASE_URL = "https://app.ekuaibao.com"; + +/** + * 根据企业配置动态解析部署集群 (如 app, wx2, shanghai 等) + */ +export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string }): string { + if (corp.cluster && corp.cluster.trim()) { + return corp.cluster.trim(); + } + if (corp.baseUrl) { + try { + const url = new URL(corp.baseUrl); + const match = /^([a-z0-9-]+)\.ekuaibao\.com$/i.exec(url.hostname); + if (match && match[1]) { + return match[1].toLowerCase(); + } + } catch {} + } + return "app"; +} + +// 内存缓存 +const easoMemoryCache = new Map< + string, + { token: string; hoseToken: string; expiresAt: number } +>(); + +const unityMemoryCache = new Map< + string, + { token: string; expiresAt: number } +>(); + +function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean { + return Date.now() >= entry.expiresAt - refreshTtl * 1000; +} + +export 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; +} + +export async function fetchUnityJwt( + accessToken: string, + corpId: string, + staffId: string, + baseUrl: string = EKB_BASE_URL +): Promise { + const response = await ky + .get(`${baseUrl}/api/engine/realm/$UNITY/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 UNITY JWT"); + } + return token; +} + +export async function fetchEasoRealmToken( + corpId: string, + unityJwt: string, + hoseToken: string +): Promise { + const response = await ky + .get(`${EASO_BASE_URL}/api/realms/EASO`, { + searchParams: { corpId }, + headers: { + Authorization: `Bearer ${unityJwt}`, + hoseaccesstoken: hoseToken, + }, + }) + .json<{ value?: { accessToken?: string } }>(); + const token = response.value?.accessToken; + if (!token) { + throw new AuthenticationError("Failed to fetch EASO realm token"); + } + return token; +} + +/** + * 获取 EASO 授权客户端 (用于请求 EASO 体系资源) + */ +export async function getEasoClient(corp: CorpConfig): Promise<{ + client: ReturnType; +}> { + const refreshTtl = corp.auth?.refreshTtl ?? 300; + const cacheKey = `${corp.id}:easo`; + + // 检查内存缓存 + const mem = easoMemoryCache.get(cacheKey); + if (mem && !isExpired(mem, refreshTtl)) { + return { + client: createAuthClient({ + prefixUrl: EASO_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${mem.token}`, + accesstoken: corp.credentials.accessToken, + corporationid: corp.credentials.corpId, + hoseaccesstoken: mem.hoseToken, + }), + onUnauthorized: () => { + easoMemoryCache.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 unityJwt = await fetchUnityJwt( + corp.credentials.accessToken, + corpId, + staffId, + baseUrl + ); + const easoToken = await fetchEasoRealmToken( + corpId, + unityJwt, + hoseToken + ); + + const entry = { + token: easoToken, + hoseToken, + expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时 + }; + + easoMemoryCache.set(cacheKey, entry); + + return { + client: createAuthClient({ + prefixUrl: EASO_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${easoToken}`, + accesstoken: corp.credentials.accessToken, + corporationid: corpId, + hoseaccesstoken: hoseToken, + }), + onUnauthorized: () => { + easoMemoryCache.delete(cacheKey); + }, + }), + }; +} + +/** + * 获取 Unity 应用中心与开放微服务集群客户端 (Unity Client) + * 适用于应用商店、已购应用查询等场景 + */ +export async function getUnityClient(corp: CorpConfig): Promise<{ + client: ReturnType; + unityJwt: string; +}> { + const refreshTtl = corp.auth?.refreshTtl ?? 300; + const cacheKey = `${corp.id}:unity`; + + const mem = unityMemoryCache.get(cacheKey); + if (mem && !isExpired(mem, refreshTtl)) { + return { + unityJwt: mem.token, + client: createAuthClient({ + prefixUrl: EASO_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${mem.token}`, + }), + onUnauthorized: () => { + unityMemoryCache.delete(cacheKey); + }, + }), + }; + } + + const corpId = corp.corpId || corp.credentials.corpId; + const staffId = corp.staffId || corp.credentials.staffId; + const baseUrl = corp.baseUrl || EKB_BASE_URL; + + const unityJwt = await fetchUnityJwt( + corp.credentials.accessToken, + corpId, + staffId, + baseUrl + ); + + const entry = { + token: unityJwt, + expiresAt: Date.now() + 2 * 60 * 60 * 1000, + }; + unityMemoryCache.set(cacheKey, entry); + + return { + unityJwt, + client: createAuthClient({ + prefixUrl: EASO_BASE_URL, + getHeaders: () => ({ + Authorization: `Bearer ${unityJwt}`, + }), + onUnauthorized: () => { + unityMemoryCache.delete(cacheKey); + }, + }), + }; +}