Files
hose-use/src/core/auth/token-store.ts
T
gitea 3a15b064fe refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations)
- 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖
- 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化)
- withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制)
- 收敛 dimension、role、bill 与 token-store 缓存逻辑
- 100% 保持现有 API 契约与零功能删除
2026-09-08 15:49:27 +08:00

106 lines
2.6 KiB
TypeScript

import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
import { TokenStore, TokenStoreSchema } from "./types";
export const PRIMARY_TOKEN_CACHE_PATH = join(
homedir(),
".config",
"hose-use",
"tokens.json"
);
export const LEGACY_TOKEN_CACHE_PATH = join(
homedir(),
".cache",
"ekb-mcp",
"tokens.json"
);
function resolveTokenCachePath(): string {
if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) {
return PRIMARY_TOKEN_CACHE_PATH;
}
if (existsSync(LEGACY_TOKEN_CACHE_PATH)) {
return LEGACY_TOKEN_CACHE_PATH;
}
return PRIMARY_TOKEN_CACHE_PATH;
}
function ensureDir(path: string): void {
const dir = dirname(path);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
try {
chmodSync(dir, 0o700);
} catch {}
}
let memoryTokenCache: TokenStore | null = null;
let lastMtimeMs = 0;
export function loadTokenStore(): TokenStore {
const filePath = resolveTokenCachePath();
if (existsSync(filePath)) {
try {
const stats = statSync(filePath);
if (memoryTokenCache && stats.mtimeMs === lastMtimeMs) {
return memoryTokenCache;
}
const content = readFileSync(filePath, "utf-8");
const parsed = TokenStoreSchema.parse(JSON.parse(content));
memoryTokenCache = parsed;
lastMtimeMs = stats.mtimeMs;
return parsed;
} catch {
// 若已有内存缓存则保留,避免解析失败直接冲刷为 {}
return memoryTokenCache ?? {};
}
}
return memoryTokenCache ?? {};
}
export function saveTokenStore(store: TokenStore): void {
memoryTokenCache = store;
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
ensureDir(targetPath);
// MAJ-03: 强制写入 0o600 保护敏感凭证
writeFileSync(targetPath, JSON.stringify(store, null, 2), {
encoding: "utf-8",
mode: 0o600,
});
try {
chmodSync(targetPath, 0o600);
lastMtimeMs = statSync(targetPath).mtimeMs;
} catch {}
}
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);
}
/**
* 重置内存 Token 缓存(测试隔离用)
*/
export function resetTokenStoreMemory(): void {
memoryTokenCache = null;
lastMtimeMs = 0;
}