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:
1 parent
62afd6906e
commit
c9e0fba265
6 files changed
+151
-62
No files matched your search
+36
-12
@@ -1,19 +1,26 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { getCorpTokens, setCorpTokens } from "../../core/auth/token-store.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";
|
||||
|
||||
// 内存缓存
|
||||
const easoMemoryCache = new Map<string, { token: string; hoseToken: string; expiresAt: number }>();
|
||||
const easoMemoryCache = new Map<
|
||||
string,
|
||||
{ token: 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): 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: {
|
||||
@@ -23,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;
|
||||
}
|
||||
|
||||
@@ -41,7 +51,11 @@ async function fetchUnityJwt(
|
||||
},
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
return response.id || response.value || "";
|
||||
const token = response.id || response.value;
|
||||
if (!token) {
|
||||
throw new AuthenticationError("Failed to fetch UNITY JWT");
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
async function fetchEasoRealmToken(
|
||||
@@ -58,11 +72,15 @@ async function fetchEasoRealmToken(
|
||||
},
|
||||
})
|
||||
.json<{ value?: { accessToken?: string } }>();
|
||||
return response.value?.accessToken || "";
|
||||
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: typeof ky;
|
||||
client: ReturnType<typeof createAuthClient>;
|
||||
}> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:easo`;
|
||||
@@ -71,13 +89,16 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
const mem = easoMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return {
|
||||
client: ky.create({
|
||||
prefix: EASO_BASE_URL,
|
||||
headers: {
|
||||
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);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -108,13 +129,16 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
easoMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return {
|
||||
client: ky.create({
|
||||
prefix: EASO_BASE_URL,
|
||||
headers: {
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${easoToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
easoMemoryCache.delete(cacheKey);
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CorpConfig } from "../config/types";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { createClient } from "../http/factory.js";
|
||||
|
||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
return {
|
||||
@@ -7,3 +8,10 @@ export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
staffid: corp.credentials.staffId,
|
||||
};
|
||||
}
|
||||
|
||||
export function createEkbClient(corp: CorpConfig) {
|
||||
return createClient({
|
||||
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
headers: getEkbHeaders(corp),
|
||||
});
|
||||
}
|
||||
+28
-10
@@ -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);
|
||||
},
|
||||
});
|
||||
}
|
||||
+26
-4
@@ -1,7 +1,9 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../config/types";
|
||||
import { TokenEntry } from "./types";
|
||||
import { getCorpTokens, setCorpTokens, clearCorpTokens } from "./token-store";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { createAuthClient } from "../http/factory.js";
|
||||
import { TokenEntry } from "./types.js";
|
||||
import { getCorpTokens, setCorpTokens, clearCorpTokens } from "./token-store.js";
|
||||
import { AuthenticationError } from "../errors.js";
|
||||
|
||||
// 内存缓存
|
||||
const memoryCache = new Map<string, TokenEntry>();
|
||||
@@ -28,7 +30,8 @@ export async function getSealaiToken(corp: CorpConfig): Promise<string> {
|
||||
}
|
||||
|
||||
// 3. 重新换取
|
||||
const sealaiUrl = corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
const sealaiUrl =
|
||||
corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
const response = await ky
|
||||
.get(`${sealaiUrl}/api/auth/oauth2/session/oem-hosecloud`, {
|
||||
@@ -39,6 +42,10 @@ export async function getSealaiToken(corp: CorpConfig): Promise<string> {
|
||||
})
|
||||
.json<{ token: string; expiresIn: number }>();
|
||||
|
||||
if (!response.token) {
|
||||
throw new AuthenticationError("Failed to exchange SealAI token");
|
||||
}
|
||||
|
||||
const entry: TokenEntry = {
|
||||
token: response.token,
|
||||
expiresAt: Date.now() + response.expiresIn * 1000,
|
||||
@@ -59,3 +66,18 @@ export function clearSealaiToken(corpId: string): void {
|
||||
memoryCache.delete(cacheKey);
|
||||
clearCorpTokens(corpId);
|
||||
}
|
||||
|
||||
export async function createSealaiClient(corp: CorpConfig) {
|
||||
const sealaiUrl =
|
||||
corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
return createAuthClient({
|
||||
prefixUrl: sealaiUrl,
|
||||
getHeaders: async () => ({
|
||||
Authorization: `Bearer ${await getSealaiToken(corp)}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
clearSealaiToken(corp.id);
|
||||
},
|
||||
});
|
||||
}
|
||||
+48
-31
@@ -1,38 +1,55 @@
|
||||
import ky, { KyInstance } from "ky";
|
||||
import { CorpConfig } from "../config/types.js";
|
||||
import { getEkbHeaders } from "../auth/ekb.js";
|
||||
import { getSealaiToken, clearSealaiToken } from "../auth/sealai.js";
|
||||
|
||||
type ClientType = "ekb" | "sealai";
|
||||
export interface CreateClientOptions {
|
||||
prefixUrl: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export async function createClient(
|
||||
corp: CorpConfig,
|
||||
type: ClientType
|
||||
): Promise<KyInstance> {
|
||||
if (type === "sealai") {
|
||||
const sealaiUrl =
|
||||
corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
return ky.create({
|
||||
prefix: sealaiUrl,
|
||||
headers: {
|
||||
Authorization: `Bearer ${await getSealaiToken(corp)}`,
|
||||
},
|
||||
hooks: {
|
||||
beforeError: [
|
||||
(error: any) => {
|
||||
if (error.response?.status === 401) {
|
||||
clearSealaiToken(corp.id);
|
||||
}
|
||||
return error;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
export interface CreateAuthClientOptions {
|
||||
prefixUrl: string;
|
||||
getHeaders: () => Promise<Record<string, string>> | Record<string, string>;
|
||||
onUnauthorized?: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
export function createClient(options: CreateClientOptions): KyInstance {
|
||||
return ky.create({
|
||||
prefix: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
headers: getEkbHeaders(corp),
|
||||
prefix: options.prefixUrl,
|
||||
headers: options.headers,
|
||||
});
|
||||
}
|
||||
|
||||
export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
|
||||
return ky.create({
|
||||
prefix: options.prefixUrl,
|
||||
retry: {
|
||||
limit: 1,
|
||||
methods: ["get", "post", "put", "delete", "patch"],
|
||||
statusCodes: [401],
|
||||
},
|
||||
hooks: {
|
||||
beforeRequest: [
|
||||
async ({ request }) => {
|
||||
const headers = await options.getHeaders();
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (value !== undefined) {
|
||||
request.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
beforeRetry: [
|
||||
async ({ request }) => {
|
||||
if (options.onUnauthorized) {
|
||||
await options.onUnauthorized();
|
||||
}
|
||||
const headers = await options.getHeaders();
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (value !== undefined) {
|
||||
request.headers.set(key, value);
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
+4
-4
@@ -6,9 +6,9 @@ import {
|
||||
} from "@modelcontextprotocol/sdk/types.js";
|
||||
import { loadCorpConfigs } from "./core/config/loader.js";
|
||||
import { CorpContext } from "./core/config/manager.js";
|
||||
import { createClient } from "./core/http/factory.js";
|
||||
import { createEkbClient } from "./core/auth/ekb.js";
|
||||
import { getEasoClient } from "./core/auth/easo.js";
|
||||
import { getPiperClient } from "./core/auth/piper.js";
|
||||
import { createSealaiClient } from "./core/auth/sealai.js";
|
||||
import { sealaiTools } from "./domains/sealai/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
|
||||
@@ -102,7 +102,7 @@ async function main() {
|
||||
// SealAI 工具
|
||||
const sealaiTool = sealaiTools.find((t) => t.name === name);
|
||||
if (sealaiTool) {
|
||||
const client = await createClient(currentCorp, "sealai");
|
||||
const client = await createSealaiClient(currentCorp);
|
||||
const result = await sealaiTool.handler(client, args as never);
|
||||
return {
|
||||
content: [
|
||||
@@ -117,7 +117,7 @@ async function main() {
|
||||
// Platform 工具
|
||||
const platformTool = platformTools.find((t) => t.name === name);
|
||||
if (platformTool) {
|
||||
const ekbClient = await createClient(currentCorp, "ekb");
|
||||
const ekbClient = await createEkbClient(currentCorp);
|
||||
const { client: easoClient } = await getEasoClient(currentCorp);
|
||||
const result = await platformTool.handler(
|
||||
{ corp: currentCorp, ekbClient, easoClient },
|
||||
|
||||
Reference in new issue
Block a user