perf(http,auth): persist EASO, Unity, and Piper tokens across CLI invocations via token-store
This commit is contained in:
1 parent
76f7832522
commit
2d744d283b
5 files changed
+248
-32
No files matched your search
@@ -12,7 +12,11 @@ export const PRIMARY_TOKEN_CACHE_PATH = join(
|
||||
|
||||
export const TOKEN_CACHE_PATH = PRIMARY_TOKEN_CACHE_PATH;
|
||||
|
||||
function resolveTokenCachePath(): string {
|
||||
export function resolveTokenCachePath(): string {
|
||||
const envFile = process.env.HOSE_TOKENS_FILE?.trim();
|
||||
if (envFile) return envFile;
|
||||
const stateDir = process.env.HOSE_STATE_DIR?.trim();
|
||||
if (stateDir) return join(stateDir, "tokens.json");
|
||||
return PRIMARY_TOKEN_CACHE_PATH;
|
||||
}
|
||||
|
||||
@@ -28,9 +32,15 @@ function ensureDir(path: string): void {
|
||||
|
||||
let memoryTokenCache: TokenStore | null = null;
|
||||
let lastMtimeMs = 0;
|
||||
let lastResolvedPath = "";
|
||||
|
||||
export function loadTokenStore(): TokenStore {
|
||||
const filePath = resolveTokenCachePath();
|
||||
if (filePath !== lastResolvedPath) {
|
||||
memoryTokenCache = null;
|
||||
lastMtimeMs = 0;
|
||||
lastResolvedPath = filePath;
|
||||
}
|
||||
|
||||
if (existsSync(filePath)) {
|
||||
try {
|
||||
@@ -53,8 +63,9 @@ export function loadTokenStore(): TokenStore {
|
||||
}
|
||||
|
||||
export function saveTokenStore(store: TokenStore): void {
|
||||
const targetPath = resolveTokenCachePath();
|
||||
memoryTokenCache = store;
|
||||
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
|
||||
lastResolvedPath = targetPath;
|
||||
ensureDir(targetPath);
|
||||
|
||||
// MAJ-03: 强制写入 0o600 保护敏感凭证
|
||||
|
||||
@@ -11,11 +11,18 @@ export const CorpTokensSchema = z.object({
|
||||
unityJwt: z.string(),
|
||||
easToken: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
unity: z.object({
|
||||
unityJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
piper: z.object({
|
||||
hoseToken: z.string(),
|
||||
easJwt: z.string(),
|
||||
expiresAt: z.number(),
|
||||
sourceAccessToken: z.string().optional(),
|
||||
}).optional(),
|
||||
});
|
||||
|
||||
|
||||
@@ -13,8 +13,12 @@ import {
|
||||
createOpenApiClient,
|
||||
getOpenApiHeaders,
|
||||
} from "./openapi-client.js";
|
||||
import { resolveCorpCluster } from "./unity-client.js";
|
||||
import { resolveCorpCluster, getEasoClient, getUnityClient, clearUnityClientCache } from "./unity-client.js";
|
||||
import { getScriptEngineClient } from "./script-engine-client.js";
|
||||
import { setCorpTokens, resetTokenStoreMemory } from "../auth/token-store.js";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CorpConfig } from "../config/types.js";
|
||||
|
||||
function mockCorp(overrides: Partial<CorpConfig> = {}): CorpConfig {
|
||||
@@ -109,4 +113,41 @@ describe("core/http/unity-client & script-engine-client", () => {
|
||||
it("getScriptEngineClient is defined and callable", () => {
|
||||
expect(getScriptEngineClient).toBeDefined();
|
||||
});
|
||||
|
||||
it("reuses persisted EASO and Unity tokens from token-store across CLI runs without network calls", async () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "hose-tokens-test-"));
|
||||
const prevTokensFile = process.env.HOSE_TOKENS_FILE;
|
||||
process.env.HOSE_TOKENS_FILE = join(tempDir, "tokens.json");
|
||||
|
||||
try {
|
||||
clearUnityClientCache();
|
||||
resetTokenStoreMemory();
|
||||
|
||||
const corp = mockCorp({ id: "corp-persisted" });
|
||||
setCorpTokens("corp-persisted", {
|
||||
eas: {
|
||||
hoseToken: "persisted-hose-token",
|
||||
unityJwt: "persisted-unity-jwt",
|
||||
easToken: "persisted-easo-token",
|
||||
expiresAt: Date.now() + 3600 * 1000,
|
||||
sourceAccessToken: "mock-access-token",
|
||||
},
|
||||
});
|
||||
|
||||
// Simulate fresh process memory
|
||||
resetTokenStoreMemory();
|
||||
|
||||
const easo = await getEasoClient(corp);
|
||||
expect(easo.client).toBeDefined();
|
||||
|
||||
const unity = await getUnityClient(corp);
|
||||
expect(unity.unityJwt).toBe("persisted-unity-jwt");
|
||||
} finally {
|
||||
if (prevTokensFile === undefined) delete process.env.HOSE_TOKENS_FILE;
|
||||
else process.env.HOSE_TOKENS_FILE = prevTokensFile;
|
||||
resetTokenStoreMemory();
|
||||
clearUnityClientCache();
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,10 @@ import {
|
||||
canRefreshCorpAccessToken,
|
||||
refreshSingleCorpAccessToken,
|
||||
} from "../auth/login.js";
|
||||
import {
|
||||
getCorpTokens,
|
||||
setCorpTokens,
|
||||
} from "../auth/token-store.js";
|
||||
|
||||
export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com";
|
||||
|
||||
@@ -23,17 +27,31 @@ const scriptEngineMemoryCache = new Map<
|
||||
{ jwt: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
function invalidateScriptEngineCache(corpId: string, cacheKey?: string): void {
|
||||
if (cacheKey) {
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
} else {
|
||||
const prefix = `${corpId}:`;
|
||||
for (const key of scriptEngineMemoryCache.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
scriptEngineMemoryCache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
const persisted = getCorpTokens(corpId);
|
||||
if (persisted?.piper) {
|
||||
const next = { ...persisted };
|
||||
delete next.piper;
|
||||
setCorpTokens(corpId, next);
|
||||
}
|
||||
}
|
||||
|
||||
export function clearScriptEngineClientCache(corpId?: string): void {
|
||||
if (!corpId) {
|
||||
scriptEngineMemoryCache.clear();
|
||||
return;
|
||||
}
|
||||
const prefix = `${corpId}:`;
|
||||
for (const key of scriptEngineMemoryCache.keys()) {
|
||||
if (key.startsWith(prefix)) {
|
||||
scriptEngineMemoryCache.delete(key);
|
||||
}
|
||||
}
|
||||
invalidateScriptEngineCache(corpId);
|
||||
}
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
@@ -74,17 +92,39 @@ export async function getScriptEngineClient(
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:${platformId}:script-engine`;
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = scriptEngineMemoryCache.get(cacheKey);
|
||||
// 1. 检查 L1 内存缓存
|
||||
let mem = scriptEngineMemoryCache.get(cacheKey);
|
||||
|
||||
// 2. 检查 L2 持久化 TokenStore
|
||||
if (!mem) {
|
||||
const persisted = getCorpTokens(corp.id)?.piper;
|
||||
if (
|
||||
persisted &&
|
||||
persisted.sourceAccessToken === corp.credentials.accessToken &&
|
||||
!isExpired(persisted, refreshTtl)
|
||||
) {
|
||||
mem = {
|
||||
jwt: persisted.easJwt,
|
||||
hoseToken: persisted.hoseToken,
|
||||
expiresAt: persisted.expiresAt,
|
||||
sourceAccessToken: persisted.sourceAccessToken,
|
||||
};
|
||||
scriptEngineMemoryCache.set(cacheKey, mem);
|
||||
}
|
||||
}
|
||||
|
||||
if (mem && mem.sourceAccessToken === corp.credentials.accessToken && !isExpired(mem, refreshTtl)) {
|
||||
const cachedJwt = mem.jwt;
|
||||
const cachedHoseToken = mem.hoseToken;
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.jwt}`,
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
platformid: platformId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -114,15 +154,27 @@ export async function getScriptEngineClient(
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
||||
const entry = {
|
||||
jwt: easoJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
};
|
||||
|
||||
scriptEngineMemoryCache.set(cacheKey, entry);
|
||||
|
||||
const existingTokens = getCorpTokens(corp.id) ?? {};
|
||||
setCorpTokens(corp.id, {
|
||||
...existingTokens,
|
||||
piper: {
|
||||
hoseToken,
|
||||
easJwt: easoJwt,
|
||||
expiresAt,
|
||||
sourceAccessToken: corp.credentials.accessToken,
|
||||
},
|
||||
});
|
||||
|
||||
return createAuthClient({
|
||||
prefixUrl: SCRIPT_ENGINE_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
@@ -131,7 +183,7 @@ export async function getScriptEngineClient(
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
scriptEngineMemoryCache.delete(cacheKey);
|
||||
invalidateScriptEngineCache(corp.id, cacheKey);
|
||||
},
|
||||
});
|
||||
}
|
||||
+122
-17
@@ -6,6 +6,11 @@ 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";
|
||||
@@ -30,10 +35,10 @@ export function resolveCorpCluster(corp: { cluster?: string; baseUrl?: string })
|
||||
return "app";
|
||||
}
|
||||
|
||||
// 内存缓存
|
||||
// 内存缓存 (L1)
|
||||
const easoMemoryCache = new Map<
|
||||
string,
|
||||
{ token: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
{ token: string; unityJwt?: string; hoseToken: string; expiresAt: number; sourceAccessToken?: string }
|
||||
>();
|
||||
|
||||
const unityMemoryCache = new Map<
|
||||
@@ -49,6 +54,7 @@ export function clearUnityClientCache(corpId?: string): void {
|
||||
}
|
||||
easoMemoryCache.delete(`${corpId}:easo`);
|
||||
unityMemoryCache.delete(`${corpId}:unity`);
|
||||
clearCorpTokens(corpId);
|
||||
}
|
||||
|
||||
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
|
||||
@@ -119,6 +125,26 @@ export async function fetchEasoRealmToken(
|
||||
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 体系资源)
|
||||
*/
|
||||
@@ -127,21 +153,44 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
}> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// 检查内存缓存
|
||||
const mem = easoMemoryCache.get(cacheKey);
|
||||
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 ${mem.token}`,
|
||||
Authorization: `Bearer ${cachedToken}`,
|
||||
accesstoken: corp.credentials.accessToken,
|
||||
corporationid: corp.credentials.corpId,
|
||||
hoseaccesstoken: mem.hoseToken,
|
||||
corporationid: corpId,
|
||||
hoseaccesstoken: cachedHoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
easoMemoryCache.delete(cacheKey);
|
||||
invalidateEasoCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -154,7 +203,6 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
}
|
||||
}
|
||||
|
||||
const corpId = corp.corpId || corp.credentials.corpId;
|
||||
const staffId = corp.staffId || corp.credentials.staffId;
|
||||
const environment = resolveCorpCluster(corp);
|
||||
const baseUrl = corp.baseUrl || EKB_BASE_URL;
|
||||
@@ -177,14 +225,38 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
hoseToken
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时
|
||||
const entry = {
|
||||
token: easoToken,
|
||||
unityJwt,
|
||||
hoseToken,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
|
||||
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({
|
||||
@@ -196,7 +268,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{
|
||||
hoseaccesstoken: hoseToken,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
easoMemoryCache.delete(cacheKey);
|
||||
invalidateEasoCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -213,17 +285,39 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
const refreshTtl = corp.auth?.refreshTtl ?? 300;
|
||||
const cacheKey = `${corp.id}:unity`;
|
||||
|
||||
const mem = unityMemoryCache.get(cacheKey);
|
||||
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: mem.token,
|
||||
unityJwt: cachedJwt,
|
||||
client: createAuthClient({
|
||||
prefixUrl: EASO_BASE_URL,
|
||||
getHeaders: () => ({
|
||||
Authorization: `Bearer ${mem.token}`,
|
||||
Authorization: `Bearer ${cachedJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
unityMemoryCache.delete(cacheKey);
|
||||
invalidateUnityCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
@@ -247,13 +341,24 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
baseUrl
|
||||
);
|
||||
|
||||
const expiresAt = Date.now() + 2 * 60 * 60 * 1000;
|
||||
const entry = {
|
||||
token: unityJwt,
|
||||
expiresAt: Date.now() + 2 * 60 * 60 * 1000,
|
||||
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({
|
||||
@@ -262,7 +367,7 @@ export async function getUnityClient(corp: CorpConfig): Promise<{
|
||||
Authorization: `Bearer ${unityJwt}`,
|
||||
}),
|
||||
onUnauthorized: () => {
|
||||
unityMemoryCache.delete(cacheKey);
|
||||
invalidateUnityCache(corp.id);
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user