375 lines
9.9 KiB
TypeScript
375 lines
9.9 KiB
TypeScript
import ky from "ky";
|
|
import type { CorpConfig } from "../config/types.js";
|
|
import { createAuthClient } from "./factory.js";
|
|
import { AuthenticationError } from "../errors.js";
|
|
import {
|
|
canRefreshCorpAccessToken,
|
|
refreshSingleCorpAccessToken,
|
|
} from "../auth/login.js";
|
|
import {
|
|
clearCorpTokens,
|
|
getCorpTokens,
|
|
setCorpTokens,
|
|
} from "../auth/token-store.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";
|
|
}
|
|
|
|
// 内存缓存 (L1)
|
|
const easoMemoryCache = new Map<
|
|
string,
|
|
{ token: string; unityJwt?: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
|
>();
|
|
|
|
const unityMemoryCache = new Map<
|
|
string,
|
|
{ token: string; expiresAt: number; sourceAccessToken?: string }
|
|
>();
|
|
|
|
export function clearUnityClientCache(corpId?: string): void {
|
|
if (!corpId) {
|
|
easoMemoryCache.clear();
|
|
unityMemoryCache.clear();
|
|
return;
|
|
}
|
|
easoMemoryCache.delete(`${corpId}:easo`);
|
|
unityMemoryCache.delete(`${corpId}:unity`);
|
|
clearCorpTokens(corpId);
|
|
}
|
|
|
|
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<string> {
|
|
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<string> {
|
|
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<string> {
|
|
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;
|
|
}
|
|
|
|
function invalidateEasoCache(corpId: string): void {
|
|
easoMemoryCache.delete(`${corpId}:easo`);
|
|
const persisted = getCorpTokens(corpId);
|
|
if (persisted?.eas) {
|
|
const next = { ...persisted };
|
|
delete next.eas;
|
|
setCorpTokens(corpId, next);
|
|
}
|
|
}
|
|
|
|
function invalidateUnityCache(corpId: string): void {
|
|
unityMemoryCache.delete(`${corpId}:unity`);
|
|
const persisted = getCorpTokens(corpId);
|
|
if (persisted?.unity) {
|
|
const next = { ...persisted };
|
|
delete next.unity;
|
|
setCorpTokens(corpId, next);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取 EASO 授权客户端 (用于请求 EASO 体系资源)
|
|
*/
|
|
export async function getEasoClient(corp: CorpConfig): Promise<{
|
|
client: ReturnType<typeof createAuthClient>;
|
|
}> {
|
|
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
|
const cacheKey = `${corp.id}:easo`;
|
|
const corpId = corp.corpId || corp.credentials.corpId;
|
|
|
|
// 1. 检查 L1 内存缓存
|
|
let mem = easoMemoryCache.get(cacheKey);
|
|
|
|
// 2. 若 L1 未命中,检查 L2 持久化 TokenStore (跨 CLI 进程复用)
|
|
if (!mem) {
|
|
const persisted = getCorpTokens(corp.id)?.eas;
|
|
if (
|
|
persisted &&
|
|
persisted.sourceAccessToken === corp.credentials.accessToken &&
|
|
!isExpired(persisted, refreshTtl)
|
|
) {
|
|
mem = {
|
|
token: persisted.easToken,
|
|
unityJwt: persisted.unityJwt,
|
|
hoseToken: persisted.hoseToken,
|
|
expiresAt: persisted.expiresAt,
|
|
sourceAccessToken: persisted.sourceAccessToken,
|
|
};
|
|
easoMemoryCache.set(cacheKey, mem);
|
|
}
|
|
}
|
|
|
|
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
|
const cachedToken = mem.token;
|
|
const cachedHoseToken = mem.hoseToken;
|
|
return {
|
|
client: createAuthClient({
|
|
prefixUrl: EASO_BASE_URL,
|
|
getHeaders: () => ({
|
|
Authorization: `Bearer ${cachedToken}`,
|
|
accesstoken: corp.credentials.accessToken,
|
|
corporationid: corpId,
|
|
hoseaccesstoken: cachedHoseToken,
|
|
}),
|
|
onUnauthorized: () => {
|
|
invalidateEasoCache(corp.id);
|
|
},
|
|
}),
|
|
};
|
|
}
|
|
|
|
if (canRefreshCorpAccessToken(corp)) {
|
|
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
|
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
|
await refreshSingleCorpAccessToken(corp);
|
|
}
|
|
}
|
|
|
|
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 expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
|
const entry = {
|
|
token: easoToken,
|
|
unityJwt,
|
|
hoseToken,
|
|
expiresAt,
|
|
sourceAccessToken: corp.credentials.accessToken,
|
|
};
|
|
|
|
easoMemoryCache.set(cacheKey, entry);
|
|
unityMemoryCache.set(`${corp.id}:unity`, {
|
|
token: unityJwt,
|
|
expiresAt,
|
|
sourceAccessToken: corp.credentials.accessToken,
|
|
});
|
|
|
|
const existingTokens = getCorpTokens(corp.id) ?? {};
|
|
setCorpTokens(corp.id, {
|
|
...existingTokens,
|
|
eas: {
|
|
hoseToken,
|
|
unityJwt,
|
|
easToken: easoToken,
|
|
expiresAt,
|
|
sourceAccessToken: corp.credentials.accessToken,
|
|
},
|
|
unity: {
|
|
unityJwt,
|
|
expiresAt,
|
|
sourceAccessToken: corp.credentials.accessToken,
|
|
},
|
|
});
|
|
|
|
return {
|
|
client: createAuthClient({
|
|
prefixUrl: EASO_BASE_URL,
|
|
getHeaders: () => ({
|
|
Authorization: `Bearer ${easoToken}`,
|
|
accesstoken: corp.credentials.accessToken,
|
|
corporationid: corpId,
|
|
hoseaccesstoken: hoseToken,
|
|
}),
|
|
onUnauthorized: () => {
|
|
invalidateEasoCache(corp.id);
|
|
},
|
|
}),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 获取 Unity 应用中心与开放微服务集群客户端 (Unity Client)
|
|
* 适用于应用商店、已购应用查询等场景
|
|
*/
|
|
export async function getUnityClient(corp: CorpConfig): Promise<{
|
|
client: ReturnType<typeof createAuthClient>;
|
|
unityJwt: string;
|
|
}> {
|
|
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
|
const cacheKey = `${corp.id}:unity`;
|
|
|
|
let mem = unityMemoryCache.get(cacheKey);
|
|
if (!mem) {
|
|
const persisted = getCorpTokens(corp.id);
|
|
const persistedUnity = persisted?.unity ?? (persisted?.eas ? {
|
|
unityJwt: persisted.eas.unityJwt,
|
|
expiresAt: persisted.eas.expiresAt,
|
|
sourceAccessToken: persisted.eas.sourceAccessToken,
|
|
} : undefined);
|
|
if (
|
|
persistedUnity &&
|
|
persistedUnity.sourceAccessToken === corp.credentials.accessToken &&
|
|
!isExpired(persistedUnity, refreshTtl)
|
|
) {
|
|
mem = {
|
|
token: persistedUnity.unityJwt,
|
|
expiresAt: persistedUnity.expiresAt,
|
|
sourceAccessToken: persistedUnity.sourceAccessToken,
|
|
};
|
|
unityMemoryCache.set(cacheKey, mem);
|
|
}
|
|
}
|
|
|
|
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
|
const cachedJwt = mem.token;
|
|
return {
|
|
unityJwt: cachedJwt,
|
|
client: createAuthClient({
|
|
prefixUrl: EASO_BASE_URL,
|
|
getHeaders: () => ({
|
|
Authorization: `Bearer ${cachedJwt}`,
|
|
}),
|
|
onUnauthorized: () => {
|
|
invalidateUnityCache(corp.id);
|
|
},
|
|
}),
|
|
};
|
|
}
|
|
|
|
if (canRefreshCorpAccessToken(corp)) {
|
|
const expiresAt = corp.auth?.expiresAt || corp.session?.expTime;
|
|
if (!corp.credentials.accessToken || (expiresAt && Date.now() >= expiresAt - refreshTtl * 1000)) {
|
|
await refreshSingleCorpAccessToken(corp);
|
|
}
|
|
}
|
|
|
|
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 expiresAt = Date.now() + 2 * 60 * 60 * 1000;
|
|
const entry = {
|
|
token: unityJwt,
|
|
expiresAt,
|
|
sourceAccessToken: corp.credentials.accessToken,
|
|
};
|
|
unityMemoryCache.set(cacheKey, entry);
|
|
|
|
const existingTokens = getCorpTokens(corp.id) ?? {};
|
|
setCorpTokens(corp.id, {
|
|
...existingTokens,
|
|
unity: {
|
|
unityJwt,
|
|
expiresAt,
|
|
sourceAccessToken: corp.credentials.accessToken,
|
|
},
|
|
});
|
|
|
|
return {
|
|
unityJwt,
|
|
client: createAuthClient({
|
|
prefixUrl: EASO_BASE_URL,
|
|
getHeaders: () => ({
|
|
Authorization: `Bearer ${unityJwt}`,
|
|
}),
|
|
onUnauthorized: () => {
|
|
invalidateUnityCache(corp.id);
|
|
},
|
|
}),
|
|
};
|
|
}
|