import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto"; import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; // --------------------------------------------------------------------------- // Master key resolution // --------------------------------------------------------------------------- // // Strategy (ordered): // 1. `LLM_CONFIG_ENC_KEY` env var (32 bytes encoded as hex or base64). // 2. Persisted random key at `~/.tablestore-agent/.enc-key` (0600 perms). // // The auto-generated fallback is the same pattern Vercel AI Chatbot / // LibreChat / OpenWebUI use for local developer setups: a deterministic // file that rotates only when the user explicitly removes it. The file // permission is forced to 0600 so other local users cannot read it. const CONFIG_DIR = join(homedir(), ".tablestore-agent"); const ENC_KEY_FILE = join(CONFIG_DIR, ".enc-key"); const KEY_BYTES = 32; let cachedKey: Buffer | null = null; function decodeEnvKey(raw: string): Buffer | null { const trimmed = raw.trim(); if (!trimmed) return null; // Try hex first (64 chars of [0-9a-f]). if (/^[0-9a-fA-F]{64}$/.test(trimmed)) { return Buffer.from(trimmed, "hex"); } // Then base64 (with or without padding). try { const buf = Buffer.from(trimmed, "base64"); if (buf.length === KEY_BYTES) return buf; } catch { // fall through } return null; } function readOrCreatePersistedKey(): Buffer { if (existsSync(ENC_KEY_FILE)) { const raw = readFileSync(ENC_KEY_FILE, "utf8").trim(); const decoded = decodeEnvKey(raw); if (!decoded) { throw new Error( `Corrupted master key at ${ENC_KEY_FILE}; delete the file to regenerate (existing LLM provider secrets will become unreadable)`, ); } return decoded; } if (!existsSync(CONFIG_DIR)) { mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); } const fresh = randomBytes(KEY_BYTES); writeFileSync(ENC_KEY_FILE, fresh.toString("base64"), { encoding: "utf8", mode: 0o600, }); try { chmodSync(ENC_KEY_FILE, 0o600); } catch { // Windows or restricted FS; the write above already set the mode. } console.warn( `[llm-crypto] Generated a new master key at ${ENC_KEY_FILE}. Back it up or set LLM_CONFIG_ENC_KEY in the environment to avoid losing stored LLM provider secrets.`, ); return fresh; } export function getMasterKey(): Buffer { if (cachedKey) return cachedKey; const envRaw = process.env.LLM_CONFIG_ENC_KEY; if (envRaw && envRaw.trim()) { const decoded = decodeEnvKey(envRaw); if (!decoded) { throw new Error( "LLM_CONFIG_ENC_KEY must be 32 bytes encoded as hex (64 chars) or base64", ); } cachedKey = decoded; return cachedKey; } cachedKey = readOrCreatePersistedKey(); return cachedKey; } /** Test-only reset so unit tests can force re-resolution. */ export function __resetMasterKeyCacheForTests(): void { cachedKey = null; } // --------------------------------------------------------------------------- // AES-256-GCM // --------------------------------------------------------------------------- // // Encoded format: `v1:::`. // The `v1` tag lets us migrate the scheme later without ambiguity. const SCHEME_VERSION = "v1"; const IV_BYTES = 12; export function encryptSecret(plaintext: string): string { const key = getMasterKey(); const iv = randomBytes(IV_BYTES); const cipher = createCipheriv("aes-256-gcm", key, iv); const encrypted = Buffer.concat([ cipher.update(plaintext, "utf8"), cipher.final(), ]); const authTag = cipher.getAuthTag(); return [ SCHEME_VERSION, iv.toString("hex"), authTag.toString("hex"), encrypted.toString("hex"), ].join(":"); } export function decryptSecret(encoded: string): string { const parts = encoded.split(":"); if (parts.length !== 4 || parts[0] !== SCHEME_VERSION) { throw new Error("Unsupported ciphertext format"); } const [, ivHex, tagHex, dataHex] = parts; const key = getMasterKey(); const decipher = createDecipheriv( "aes-256-gcm", key, Buffer.from(ivHex, "hex"), ); decipher.setAuthTag(Buffer.from(tagHex, "hex")); const decrypted = Buffer.concat([ decipher.update(Buffer.from(dataHex, "hex")), decipher.final(), ]); return decrypted.toString("utf8"); } /** * Produce a display-safe preview such as `sk-****abcd`. For keys shorter * than 8 characters we just return the fixed mask to avoid leaking the * secret. */ export function maskApiKey(raw: string): string { const s = raw.trim(); if (s.length <= 8) return "****"; const tail = s.slice(-4); const prefix = s.startsWith("sk-") ? "sk-" : s.slice(0, 3); return `${prefix}****${tail}`; }