import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { writeSecureFile } from "../secure-file.js"; import { SEAL_CONFIG_DIR } from "../paths.js"; import { CorpTokenCache, HoseAuthCache, SealDelegateAuthCache, SealSession, TokenStore, TokenStoreSchema } from "./types.js"; const PRIMARY_TOKEN_STORE = join(SEAL_CONFIG_DIR, "tokens.json"); const MIGRATION_TOKEN_STORE = join(SEAL_CONFIG_DIR, "sealTokens.json"); function resolveReadStorePath(): string { const configured = (process.env.SEAL_USE_TOKEN_STORE ?? process.env.SEAL_HOME_TOKEN_STORE)?.trim(); if (configured) return configured; if (existsSync(PRIMARY_TOKEN_STORE)) return PRIMARY_TOKEN_STORE; if (existsSync(MIGRATION_TOKEN_STORE)) return MIGRATION_TOKEN_STORE; return PRIMARY_TOKEN_STORE; } function resolveWriteStorePath(): string { const configured = (process.env.SEAL_USE_TOKEN_STORE ?? process.env.SEAL_HOME_TOKEN_STORE)?.trim(); if (configured) return configured; return PRIMARY_TOKEN_STORE; } function readStore(): TokenStore { const path = resolveReadStorePath(); if (!existsSync(path)) { return {}; } try { return TokenStoreSchema.parse(JSON.parse(readFileSync(path, "utf-8"))); } catch { return {}; } } function writeStore(store: TokenStore): void { const path = resolveWriteStorePath(); writeSecureFile(path, JSON.stringify(store, null, 2)); } export function getSealSession(corpId: string): SealSession | undefined { return readStore()[corpId]?.seal; } export function setSealSession(corpId: string, session: SealSession): void { const store = readStore(); writeStore({ ...store, [corpId]: { ...store[corpId], seal: session } }); } export function clearSealSession(corpId: string): void { const store = readStore(); const current = store[corpId]; if (!current) return; writeStore({ ...store, [corpId]: { ...current, seal: undefined } }); } export function getCorpTokenCache(corpId: string): CorpTokenCache { return readStore()[corpId] ?? {}; } export function getHoseAuthCache(corpId: string): HoseAuthCache { return readStore()[corpId]?.hose ?? {}; } export function setHoseAuthCache(corpId: string, hose: HoseAuthCache): void { const store = readStore(); writeStore({ ...store, [corpId]: { ...store[corpId], hose } }); } export function getSealDelegateAuthCache(corpId: string): SealDelegateAuthCache { return readStore()[corpId]?.sealDelegate ?? {}; } export function setSealDelegateAuthCache(corpId: string, sealDelegate: SealDelegateAuthCache): void { const store = readStore(); writeStore({ ...store, [corpId]: { ...store[corpId], sealDelegate } }); } export function clearCorpTokenCache(corpId: string): void { const store = readStore(); delete store[corpId]; writeStore(store); }