import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { homedir } from "node:os"; import { CorpTokenCache, HoseAuthCache, SealSession, TokenStore, TokenStoreSchema } from "./types.js"; const PRIMARY_TOKEN_STORE = join(homedir(), ".config", "seal-use", "seal_tokens.json"); const LEGACY_TOKEN_STORE = join(homedir(), ".config", "seal-home", "seal_tokens.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(LEGACY_TOKEN_STORE)) return LEGACY_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(); mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); writeFileSync(path, JSON.stringify(store, null, 2), { mode: 0o600 }); } 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 clearCorpTokenCache(corpId: string): void { const store = readStore(); delete store[corpId]; writeStore(store); }