refactor(core): 统一 HTTP 工厂与认证模块,支持 401 自动重试

- factory.ts 只负责创建 HTTP client 和 401 retry 逻辑
- auth 模块(ekb/easo/piper/sealai)只负责 token/header 获取
- ekb.ts 新增 createEkbClient
- sealai.ts 新增 createSealaiClient,内部使用 createAuthClient
- easo.ts/piper.ts 改用 createAuthClient,token 交换失败抛 AuthenticationError
- server.ts 使用 createEkbClient / createSealaiClient / getEasoClient
This commit is contained in:
gitea committed 2026-07-17 17:25:02 +08:00
1 parent 62afd6906e
commit c9e0fba265
6 files changed
+151 -62

No files matched your search

+28 -10
View File
@@ -1,5 +1,7 @@
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 PIPER_BASE_URL = "https://piper.ekuaibao.com";
const BUSINESS_CENTER_URL = "https://business-center.ekuaibao.com";
@@ -15,7 +17,10 @@ function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
}
async function fetchHoseToken(accessToken: string, corpId: string): Promise<string> {
async function fetchHoseToken(
accessToken: string,
corpId: string
): Promise<string> {
const response = await ky
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
searchParams: {
@@ -25,6 +30,9 @@ async function fetchHoseToken(accessToken: string, corpId: string): Promise<stri
},
})
.json<{ data: string }>();
if (!response.data) {
throw new AuthenticationError("Failed to fetch hose-access-token");
}
return response.data;
}
@@ -43,24 +51,31 @@ async function fetchEasoJwt(
},
})
.json<{ id?: string; value?: string }>();
return response.id || response.value || "";
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<typeof ky> {
): Promise<ReturnType<typeof createAuthClient>> {
const refreshTtl = corp.auth?.refreshTtl ?? 300;
const cacheKey = `${corp.id}:${platformId}:piper`;
// 检查内存缓存
const mem = piperMemoryCache.get(cacheKey);
if (mem && !isExpired(mem, refreshTtl)) {
return ky.create({
prefix: PIPER_BASE_URL,
headers: {
return createAuthClient({
prefixUrl: PIPER_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${mem.jwt}`,
platformid: platformId,
}),
onUnauthorized: () => {
piperMemoryCache.delete(cacheKey);
},
});
}
@@ -84,11 +99,14 @@ export async function getPiperClient(
piperMemoryCache.set(cacheKey, entry);
return ky.create({
prefix: PIPER_BASE_URL,
headers: {
Authorization: `Bearer ${easoJwt}`,
return createAuthClient({
prefixUrl: PIPER_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${easoJwt}`,
platformid: platformId,
}),
onUnauthorized: () => {
piperMemoryCache.delete(cacheKey);
},
});
}