refactor(core): 抽象语义化 HTTP 客户端与统一防爬指纹管理
This commit is contained in:
1 parent
1322e2eab9
commit
aa69b50e6e
11 files changed
+834
-401
No files matched your search
@@ -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<string, { token: string; expiresAt: number }>();
|
||||
|
||||
/**
|
||||
* 通过开放平台应用凭据 (appKey + appSecurity) 获取 app-token
|
||||
*/
|
||||
export async function fetchOpenApiToken(
|
||||
auth: OpenApiAuthConfig
|
||||
): Promise<string> {
|
||||
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<string, string> {
|
||||
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<KyInstance> {
|
||||
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");
|
||||
}
|
||||
Reference in new issue
Block a user