refactor: 将 ekb-mcp 上移到根目录
项目结构重构: - 将 ekb-mcp/ 子目录内容上移到项目根目录 - 更新 AGENTS.md 反映新的 TS + MCP 架构 - 更新 README.md 为 ekb-mcp 项目说明 - 保留 docs/ 文档目录 新的项目结构: - src/core/ - 基础设施(auth, config, http) - src/domains/ - 业务域(sealai, platform) - src/server.ts - MCP Server 入口 - enterprises/ - 企业配置
This commit is contained in:
1 parent
955f56114f
commit
f9eb6a4844
30 files changed
+384
-422
No files matched your search
@@ -0,0 +1,124 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { getCorpTokens, setCorpTokens } from "../../core/auth/token-store.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 }>();
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
async function fetchHoseToken(accessToken: string, corpId: string): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async function fetchUnityJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$UNITY/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
return response.id || response.value || "";
|
||||
}
|
||||
|
||||
async function fetchEasoRealmToken(
|
||||
corpId: string,
|
||||
unityJwt: string,
|
||||
hoseToken: string
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EASO_BASE_URL}/api/realms/EASO`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
hoseaccesstoken: hoseToken,
|
||||
},
|
||||
})
|
||||
.json<{ value?: { accessToken?: string } }>();
|
||||
return response.value?.accessToken || "";
|
||||
}
|
||||
|
||||
export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
client: typeof ky;
|
||||
corpId: string;
|
||||
}> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:easo`;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = easoMemoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return {
|
||||
client: ky.create({
|
||||
prefix: EASO_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${mem.token}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: mem.hoseToken,
|
||||
},
|
||||
}),
|
||||
corpId: corp.credentials.corpId,
|
||||
};
|
||||
}
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId
|
||||
);
|
||||
const unityJwt = await fetchUnityJwt(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId,
|
||||
corp.credentials.staffId
|
||||
);
|
||||
const easoToken = await fetchEasoRealmToken(
|
||||
corp.credentials.corpId,
|
||||
unityJwt,
|
||||
hoseToken
|
||||
);
|
||||
|
||||
const entry = {
|
||||
token: easoToken,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
};
|
||||
|
||||
easoMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return {
|
||||
client: ky.create({
|
||||
prefix: EASO_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${easoToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: hoseToken,
|
||||
},
|
||||
}),
|
||||
corpId: corp.credentials.corpId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { CorpConfig } from "../config/types";
|
||||
|
||||
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
|
||||
return {
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corpid: corp.credentials.corpId,
|
||||
staffid: corp.credentials.staffId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../../core/config/types.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): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${BUSINESS_CENTER_URL}/auth/oauth2/grant/ekb/accessToken`, {
|
||||
searchParams: {
|
||||
corpId,
|
||||
ekbAccessToken: accessToken,
|
||||
environment: "app",
|
||||
},
|
||||
})
|
||||
.json<{ data: string }>();
|
||||
return response.data;
|
||||
}
|
||||
|
||||
async function fetchEasoJwt(
|
||||
accessToken: string,
|
||||
corpId: string,
|
||||
staffId: string
|
||||
): Promise<string> {
|
||||
const response = await ky
|
||||
.get(`${EKB_BASE_URL}/api/engine/realm/$EASO/actions/jwt`, {
|
||||
searchParams: { corpId },
|
||||
headers: {
|
||||
accesstoken: accessToken,
|
||||
corpid: corpId,
|
||||
staffid: staffId,
|
||||
},
|
||||
})
|
||||
.json<{ id?: string; value?: string }>();
|
||||
return response.id || response.value || "";
|
||||
}
|
||||
|
||||
export async function getPiperClient(
|
||||
corp: CorpConfig,
|
||||
platformId: string
|
||||
): Promise<typeof ky> {
|
||||
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: {
|
||||
Authorization: `Bearer ${mem.jwt}`,
|
||||
platformid: platformId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 重新换取
|
||||
const hoseToken = await fetchHoseToken(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId
|
||||
);
|
||||
const easoJwt = await fetchEasoJwt(
|
||||
corp.credentials.accessToken,
|
||||
corp.credentials.corpId,
|
||||
corp.credentials.staffId
|
||||
);
|
||||
|
||||
const entry = {
|
||||
jwt: easoJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
};
|
||||
|
||||
piperMemoryCache.set(cacheKey, entry);
|
||||
|
||||
return ky.create({
|
||||
prefix: PIPER_BASE_URL,
|
||||
headers: {
|
||||
Authorization: `Bearer ${easoJwt}`,
|
||||
platformid: platformId,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import ky from "ky";
|
||||
import { CorpConfig } from "../config/types";
|
||||
import { TokenEntry } from "./types";
|
||||
import { getCorpTokens, setCorpTokens, clearCorpTokens } from "./token-store";
|
||||
|
||||
// 内存缓存
|
||||
const memoryCache = new Map<string, TokenEntry>();
|
||||
|
||||
function isExpired(entry: TokenEntry, refreshTtl: number): boolean {
|
||||
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
|
||||
}
|
||||
|
||||
export async function getSealaiToken(corp: CorpConfig): Promise<string> {
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:sealai`;
|
||||
|
||||
// 1. 检查内存缓存
|
||||
const mem = memoryCache.get(cacheKey);
|
||||
if (mem && !isExpired(mem, refreshTtl)) {
|
||||
return mem.token;
|
||||
}
|
||||
|
||||
// 2. 检查持久化缓存
|
||||
const stored = getCorpTokens(corp.id);
|
||||
if (stored?.sealai && !isExpired(stored.sealai, refreshTtl)) {
|
||||
memoryCache.set(cacheKey, stored.sealai);
|
||||
return stored.sealai.token;
|
||||
}
|
||||
|
||||
// 3. 重新换取
|
||||
const sealaiUrl = corp.sealaiUrl || `https://${corp.credentials.corpId.toLowerCase()}.sealai.cc`;
|
||||
|
||||
const response = await ky
|
||||
.get(`${sealaiUrl}/api/auth/oauth2/session/oem-hosecloud`, {
|
||||
searchParams: {
|
||||
token: corp.credentials.accessToken,
|
||||
returnToken: "1",
|
||||
},
|
||||
})
|
||||
.json<{ token: string; expiresIn: number }>();
|
||||
|
||||
const entry: TokenEntry = {
|
||||
token: response.token,
|
||||
expiresAt: Date.now() + response.expiresIn * 1000,
|
||||
};
|
||||
|
||||
// 4. 更新内存 + 持久化
|
||||
memoryCache.set(cacheKey, entry);
|
||||
setCorpTokens(corp.id, {
|
||||
...stored,
|
||||
sealai: entry,
|
||||
});
|
||||
|
||||
return entry.token;
|
||||
}
|
||||
|
||||
export function clearSealaiToken(corpId: string): void {
|
||||
const cacheKey = `${corpId}:sealai`;
|
||||
memoryCache.delete(cacheKey);
|
||||
clearCorpTokens(corpId);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
||||
import { join, dirname } from "path";
|
||||
import { homedir } from "os";
|
||||
import { TokenStore, TokenStoreSchema } from "./types";
|
||||
|
||||
const TOKEN_CACHE_PATH = join(
|
||||
homedir(),
|
||||
".cache",
|
||||
"ekb-mcp",
|
||||
"tokens.json"
|
||||
);
|
||||
|
||||
function ensureDir(path: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
}
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
try {
|
||||
const content = readFileSync(TOKEN_CACHE_PATH, "utf-8");
|
||||
return TokenStoreSchema.parse(JSON.parse(content));
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function saveTokenStore(store: TokenStore): void {
|
||||
ensureDir(TOKEN_CACHE_PATH);
|
||||
writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(store, null, 2));
|
||||
}
|
||||
|
||||
export function getCorpTokens(corpId: string): TokenStore[string] | undefined {
|
||||
const store = loadTokenStore();
|
||||
return store[corpId];
|
||||
}
|
||||
|
||||
export function setCorpTokens(corpId: string, tokens: TokenStore[string]): void {
|
||||
const store = loadTokenStore();
|
||||
store[corpId] = tokens;
|
||||
saveTokenStore(store);
|
||||
}
|
||||
|
||||
export function clearCorpTokens(corpId: string): void {
|
||||
const store = loadTokenStore();
|
||||
delete store[corpId];
|
||||
saveTokenStore(store);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const TokenEntrySchema = z.object({
|
||||
token: z.string(),
|
||||
expiresAt: z.number(), // timestamp (ms)
|
||||
});
|
||||
|
||||
export const CorpTokensSchema = z.object({
|
||||
sealai: TokenEntrySchema.optional(),
|
||||
eas: z.object({
|
||||
hoseToken: z.string(),
|
||||
unityJwt: z.string(),
|
||||
easToken: z.string(),
|
||||
expiresAt: z.number(),
|
||||
}).optional(),
|
||||
piper: z.object({
|
||||
hoseToken: z.string(),
|
||||
easJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
export const TokenStoreSchema = z.record(z.string(), CorpTokensSchema);
|
||||
|
||||
export type TokenEntry = z.infer<typeof TokenEntrySchema>;
|
||||
export type CorpTokens = z.infer<typeof CorpTokensSchema>;
|
||||
export type TokenStore = z.infer<typeof TokenStoreSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readFileSync, readdirSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { CorpConfig, CorpConfigSchema } from "./types";
|
||||
|
||||
const ENTERPRISES_DIR = "./enterprises";
|
||||
|
||||
export function loadCorpConfigs(): CorpConfig[] {
|
||||
try {
|
||||
const files = readdirSync(ENTERPRISES_DIR).filter((f) =>
|
||||
f.endsWith(".json")
|
||||
);
|
||||
|
||||
return files.map((file) => {
|
||||
const content = readFileSync(join(ENTERPRISES_DIR, file), "utf-8");
|
||||
const parsed = JSON.parse(content);
|
||||
return CorpConfigSchema.parse(parsed);
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { CorpConfig } from "./types";
|
||||
|
||||
export class CorpContext {
|
||||
private current: CorpConfig | null = null;
|
||||
private corps: Map<string, CorpConfig> = new Map();
|
||||
|
||||
constructor(corps: CorpConfig[]) {
|
||||
for (const corp of corps) {
|
||||
this.corps.set(corp.id, corp);
|
||||
}
|
||||
if (corps.length > 0) {
|
||||
this.current = corps[0];
|
||||
}
|
||||
}
|
||||
|
||||
getCurrent(): CorpConfig | null {
|
||||
return this.current;
|
||||
}
|
||||
|
||||
switchCorp(corpId: string): boolean {
|
||||
const corp = this.corps.get(corpId);
|
||||
if (!corp) return false;
|
||||
this.current = corp;
|
||||
return true;
|
||||
}
|
||||
|
||||
listCorps(): Array<{ id: string; name: string; current: boolean }> {
|
||||
return Array.from(this.corps.values()).map((corp) => ({
|
||||
id: corp.id,
|
||||
name: corp.name,
|
||||
current: corp.id === this.current?.id,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const CorpCredentialsSchema = z.object({
|
||||
accessToken: z.string(),
|
||||
corpId: z.string(),
|
||||
staffId: z.string(),
|
||||
});
|
||||
|
||||
export const CorpAuthConfigSchema = z.object({
|
||||
refreshTtl: z.number().default(300), // 提前多少秒刷新,默认 5 分钟
|
||||
});
|
||||
|
||||
export const CorpConfigSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
baseUrl: z.string().url().optional(), // 默认 https://app.ekuaibao.com
|
||||
sealaiUrl: z.string().optional(), // 默认 https://{corpId}.sealai.cc
|
||||
credentials: CorpCredentialsSchema,
|
||||
auth: CorpAuthConfigSchema.optional(),
|
||||
});
|
||||
|
||||
export type CorpCredentials = z.infer<typeof CorpCredentialsSchema>;
|
||||
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
|
||||
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
|
||||
@@ -0,0 +1,22 @@
|
||||
export class EkbError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly code: string,
|
||||
public readonly status?: number
|
||||
) {
|
||||
super(message);
|
||||
this.name = "EkbError";
|
||||
}
|
||||
}
|
||||
|
||||
export class NotLoggedInError extends EkbError {
|
||||
constructor(message = "No corp selected") {
|
||||
super(message, "NOT_LOGGED_IN", 401);
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthenticationError extends EkbError {
|
||||
constructor(message = "Authentication failed") {
|
||||
super(message, "AUTH_FAILED", 401);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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 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;
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return ky.create({
|
||||
prefix: corp.baseUrl || "https://app.ekuaibao.com",
|
||||
headers: getEkbHeaders(corp),
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user