import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import { randomUUID } from "node:crypto"; import type { CreateLLMProviderInput, LLMProvider, LLMProviderType, LLMProviderWithSecret, UpdateLLMProviderInput, } from "@/types/llm-provider"; import { decryptSecret, encryptSecret, maskApiKey } from "./llm-crypto"; // --------------------------------------------------------------------------- // Persistence // --------------------------------------------------------------------------- // // The file is written atomically via tmp-file + rename. A single Node process // serves the Dashboard so there is no cross-process write contention; we // still guard concurrent in-process callers with a simple promise chain. const CONFIG_DIR = join(homedir(), ".tablestore-agent"); const STORE_FILE = join(CONFIG_DIR, "llm-providers.json"); const TMP_FILE = `${STORE_FILE}.tmp`; interface StoredProvider { id: string; name: string; type: LLMProviderType; baseUrl: string; /** Encrypted with llm-crypto.encryptSecret. */ apiKeyEnc: string; defaultModel?: string; createdAt: string; updatedAt: string; } interface StoreFile { version: 1; providers: StoredProvider[]; } let writeChain: Promise = Promise.resolve(); function ensureDir(): void { if (!existsSync(CONFIG_DIR)) { mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); } } function readFile(): StoreFile { if (!existsSync(STORE_FILE)) { return { version: 1, providers: [] }; } try { const raw = readFileSync(STORE_FILE, "utf8"); const parsed = JSON.parse(raw) as StoreFile; if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.providers)) { throw new Error("Invalid llm-providers.json shape"); } return parsed; } catch (err) { throw new Error( `Failed to read ${STORE_FILE}: ${err instanceof Error ? err.message : String(err)}`, ); } } function writeFileAtomically(data: StoreFile): void { ensureDir(); writeFileSync(TMP_FILE, JSON.stringify(data, null, 2), { encoding: "utf8", mode: 0o600, }); renameSync(TMP_FILE, STORE_FILE); } function toPublic(stored: StoredProvider): LLMProvider { // Recover the mask from the encrypted value; the plaintext tail is cheap // to reproduce here because we only need the last 4 chars for the UI. let mask = "****"; try { mask = maskApiKey(decryptSecret(stored.apiKeyEnc)); } catch { // If decryption fails (e.g. master key rotated), fall back to a fixed // mask rather than breaking the list endpoint. mask = "****"; } return { id: stored.id, name: stored.name, type: stored.type, baseUrl: stored.baseUrl, apiKeyMasked: mask, defaultModel: stored.defaultModel, createdAt: stored.createdAt, updatedAt: stored.updatedAt, }; } function toPrivate(stored: StoredProvider): LLMProviderWithSecret { const apiKey = decryptSecret(stored.apiKeyEnc); return { ...toPublic(stored), apiKey, }; } // --------------------------------------------------------------------------- // Public API // --------------------------------------------------------------------------- function runExclusive(fn: () => T | Promise): Promise { const next = writeChain.then(() => fn()); // Swallow errors in the chain so subsequent callers are not blocked. writeChain = next.catch(() => undefined); return next; } export async function listProviders(): Promise { return runExclusive(() => readFile().providers.map(toPublic)); } export async function getProvider(id: string): Promise { return runExclusive(() => { const hit = readFile().providers.find((p) => p.id === id); return hit ? toPublic(hit) : null; }); } export async function getProviderWithSecret( id: string, ): Promise { return runExclusive(() => { const hit = readFile().providers.find((p) => p.id === id); return hit ? toPrivate(hit) : null; }); } export async function createProvider( input: CreateLLMProviderInput, ): Promise { return runExclusive(() => { const store = readFile(); const now = new Date().toISOString(); const stored: StoredProvider = { id: randomUUID(), name: input.name, type: input.type, baseUrl: normaliseBaseUrl(input.baseUrl), apiKeyEnc: encryptSecret(input.apiKey), defaultModel: input.defaultModel?.trim() || undefined, createdAt: now, updatedAt: now, }; store.providers.push(stored); writeFileAtomically(store); return toPublic(stored); }); } export async function updateProvider( id: string, patch: UpdateLLMProviderInput, ): Promise { return runExclusive(() => { const store = readFile(); const idx = store.providers.findIndex((p) => p.id === id); if (idx < 0) return null; const existing = store.providers[idx]; const next: StoredProvider = { ...existing, name: patch.name ?? existing.name, type: patch.type ?? existing.type, baseUrl: patch.baseUrl ? normaliseBaseUrl(patch.baseUrl) : existing.baseUrl, defaultModel: patch.defaultModel !== undefined ? patch.defaultModel.trim() || undefined : existing.defaultModel, updatedAt: new Date().toISOString(), }; // Only overwrite the secret when the caller sent a non-empty value. if (patch.apiKey && patch.apiKey.trim()) { next.apiKeyEnc = encryptSecret(patch.apiKey.trim()); } store.providers[idx] = next; writeFileAtomically(store); return toPublic(next); }); } export async function deleteProvider(id: string): Promise { return runExclusive(() => { const store = readFile(); const before = store.providers.length; store.providers = store.providers.filter((p) => p.id !== id); if (store.providers.length === before) return false; writeFileAtomically(store); return true; }); } /** Drop a trailing slash so `${baseUrl}/chat/completions` is always correct. */ function normaliseBaseUrl(raw: string): string { const trimmed = raw.trim(); return trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed; }