import * as fs from 'fs'; import * as path from 'path'; import { appstash, DIRECTORY_MODE, resolve } from './index'; export interface ContextTargetEndpoint { endpoint: string; } export interface ContextConfig { name: string; endpoint: string; targets?: Record; createdAt: string; updatedAt: string; } export interface ContextCredentials { token: string; expiresAt?: string; refreshToken?: string; /** Identity the token belongs to. */ userId?: string; email?: string; /** Long-lived API key minted for this context, and its server-side id. */ apiKey?: string; keyId?: string; apiKeyExpiresAt?: string; /** Epoch millis of the sign-in that produced these credentials. */ signedInAt?: number; } /** * At-rest transform for the secret-bearing fields of stored credentials * (`token`, `refreshToken`, `apiKey`). Hosts with a keychain supply one — e.g. * Electron `safeStorage` — so the same on-disk layout can be encrypted without * the store knowing how. `decode` receives exactly what `encode` produced. */ export interface SecretCodec { /** Recorded on disk, so a file written by a different codec is detected. */ name: string; encode(plaintext: string): string; decode(encoded: string): string; } const SECRET_FIELDS = ['token', 'refreshToken', 'apiKey'] as const; const PLAINTEXT_CODEC = 'plaintext'; export interface Credentials { tokens: Record; /** Name of the codec that encoded the secret fields. */ codec?: string; } export interface GlobalSettings { currentContext?: string; } export interface ConfigStoreOptions { baseDir?: string; /** * Directory identity to store under, when it differs from the tool name. * Several CLIs that are one product — a generated SDK CLI, an agent CLI, a * desktop app — pass the same `stashName`, so signing in through one signs * you in everywhere, while `toolName` still drives env-var prefixes and the * commands named in error messages. Defaults to `toolName`. */ stashName?: string; /** At-rest transform for secret fields. Defaults to plaintext. */ codec?: SecretCodec; } export interface ClientConfig { endpoint: string; headers: Record; } export interface ConfigStore { loadSettings(): GlobalSettings; saveSettings(settings: GlobalSettings): void; createContext(name: string, options: { endpoint: string; targets?: Record }): ContextConfig; loadContext(name: string): ContextConfig | null; listContexts(): ContextConfig[]; deleteContext(name: string): boolean; getCurrentContext(): ContextConfig | null; setCurrentContext(name: string): boolean; getTargetEndpoint(targetName: string, contextName?: string): string | null; setCredentials(contextName: string, creds: ContextCredentials): void; getCredentials(contextName: string): ContextCredentials | null; removeCredentials(contextName: string): boolean; hasValidCredentials(contextName: string): boolean; setVar(key: string, value: string, contextName?: string): void; getVar(key: string, contextName?: string): string | null; deleteVar(key: string, contextName?: string): boolean; listVars(contextName?: string): Record; getClientConfig(targetName: string, contextName?: string): ClientConfig; } /** * Read stored JSON, or `fallback` when the file does not exist. A file that * exists but does not parse is a real problem — a half-written credential file, * a hand-edit gone wrong — so it throws with the path instead of quietly * resetting the caller's configuration. */ function readJson(filePath: string, fallback: T): T { let raw: string; try { raw = fs.readFileSync(filePath, 'utf8'); } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') { return JSON.parse(JSON.stringify(fallback)); } throw err; } try { return JSON.parse(raw); } catch (err) { throw new Error(`Malformed JSON in ${filePath}: ${(err as Error).message}`); } } /** * Write JSON atomically: a temp file in the destination directory, then * `rename`. A crash or a concurrent reader mid-write can never observe a * truncated file. `mode` is applied to the temp file before the rename so the * contents are never briefly world-readable. */ function writeJson(filePath: string, data: unknown, mode = 0o600): void { const dir = path.dirname(filePath); fs.mkdirSync(dir, { recursive: true, mode: DIRECTORY_MODE }); const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`); try { fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode }); fs.renameSync(tmp, filePath); } catch (err) { try { fs.unlinkSync(tmp); } catch { // the temp file may not exist; the original error is what matters } throw err; } } // `\` separates paths on Windows; NUL ends a path in the system calls. const PATH_CHARACTERS = ['/', '\\', '\0']; /** * Throws when `name` could reach a file outside the store's directory, because a context name becomes part of a * file path. Any other name is the caller's choice. */ export function assertContextName(name: string): void { if (typeof name === 'string' && name !== '' && name !== '.' && name !== '..' && !PATH_CHARACTERS.some((c) => name.includes(c))) return; const shown = typeof name === 'string' && name.length > 100 ? `${name.slice(0, 100)}...` : name; throw new Error( `${JSON.stringify(shown)} is not a valid context name, because a context name becomes a file name in the store. ` + 'Use a name that is not empty, is not "." or "..", and has no "/", "\\" or NUL character.' ); } const ownValue = (map: Record, key: string): T | undefined => Object.hasOwn(map, key) ? map[key] : undefined; /** A map the store writes by a caller's key; with no prototype, a key such as `__proto__` is a plain entry. */ const keyedMap = (entries: Record): Record => Object.assign(Object.create(null), entries); export function createConfigStore(toolName: string, options?: ConfigStoreOptions): ConfigStore { const stashName = options?.stashName ?? toolName; const codec = options?.codec; const codecName = codec?.name ?? PLAINTEXT_CODEC; const dirs = appstash(stashName, { ensure: true, baseDir: options?.baseDir }); // Directories that already exist may be readable by others; tighten only the ones this store owns. const owned = [dirs.root, dirs.config, dirs.cache, dirs.data, dirs.logs, resolve(dirs, 'config', 'contexts'), resolve(dirs, 'config', 'vars')]; const skipped: string[] = []; for (const dir of new Set(owned)) { if (skipped.some((parent) => dir.startsWith(parent + path.sep))) continue; const stat = fs.lstatSync(dir, { throwIfNoEntry: false }); if (!stat?.isDirectory()) { skipped.push(dir); continue; } if ((stat.mode & 0o777) !== DIRECTORY_MODE) fs.chmodSync(dir, DIRECTORY_MODE); } function settingsPath(): string { return resolve(dirs, 'config', 'settings.json'); } function credentialsPath(): string { return resolve(dirs, 'config', 'credentials.json'); } function contextPath(name: string): string { assertContextName(name); const contextsDir = resolve(dirs, 'config', 'contexts'); if (!fs.existsSync(contextsDir)) { fs.mkdirSync(contextsDir, { recursive: true, mode: DIRECTORY_MODE }); } return path.join(contextsDir, `${name}.json`); } function loadSettings(): GlobalSettings { return readJson(settingsPath(), {}); } function saveSettings(settings: GlobalSettings): void { writeJson(settingsPath(), settings); } function loadContext(name: string): ContextConfig | null { return readJson(contextPath(name), null); } function createContext(name: string, options: { endpoint: string; targets?: Record }): ContextConfig { const now = new Date().toISOString(); const context: ContextConfig = { name, endpoint: options.endpoint, createdAt: now, updatedAt: now, }; if (options.targets) { context.targets = options.targets; } writeJson(contextPath(name), context); return context; } function listContexts(): ContextConfig[] { const contextsDir = resolve(dirs, 'config', 'contexts'); if (!fs.existsSync(contextsDir)) { return []; } return fs .readdirSync(contextsDir) .filter(f => f.endsWith('.json')) .map(f => readJson(path.join(contextsDir, f), null)) .filter((ctx): ctx is ContextConfig => ctx !== null); } function deleteContext(name: string): boolean { const p = contextPath(name); if (fs.existsSync(p)) { fs.unlinkSync(p); const settings = loadSettings(); if (settings.currentContext === name) { settings.currentContext = undefined; saveSettings(settings); } return true; } return false; } function getCurrentContext(): ContextConfig | null { const settings = loadSettings(); if (settings.currentContext) { return loadContext(settings.currentContext); } return null; } function setCurrentContext(name: string): boolean { const context = loadContext(name); if (!context) { return false; } const settings = loadSettings(); settings.currentContext = name; saveSettings(settings); return true; } /** Map the secret fields of one entry through `transform`. */ function mapSecrets( creds: ContextCredentials, transform: (value: string) => string ): ContextCredentials { const mapped: ContextCredentials = { ...creds }; for (const field of SECRET_FIELDS) { const value = mapped[field]; if (typeof value === 'string') mapped[field] = transform(value); } return mapped; } /** Stored credentials, still encoded. */ function loadCredentials(): Credentials { const credentials = readJson(credentialsPath(), { tokens: {} }); credentials.tokens = keyedMap(credentials.tokens); const fileCodec = credentials.codec ?? PLAINTEXT_CODEC; if (Object.keys(credentials.tokens).length > 0 && fileCodec !== codecName) { throw new Error( `Credentials in ${credentialsPath()} were written with the "${fileCodec}" codec, ` + `but this store uses "${codecName}". Sign in again to rewrite them.` ); } return credentials; } function saveCredentials(credentials: Credentials): void { writeJson(credentialsPath(), { ...credentials, codec: codecName }, 0o600); } function setCredentials(contextName: string, creds: ContextCredentials): void { assertContextName(contextName); const credentials = loadCredentials(); credentials.tokens[contextName] = codec ? mapSecrets(creds, codec.encode) : creds; saveCredentials(credentials); } function getCredentials(contextName: string): ContextCredentials | null { assertContextName(contextName); const credentials = loadCredentials(); const stored = ownValue(credentials.tokens, contextName); if (!stored) return null; return codec ? mapSecrets(stored, codec.decode) : stored; } function removeCredentials(contextName: string): boolean { assertContextName(contextName); const credentials = loadCredentials(); if (ownValue(credentials.tokens, contextName)) { delete credentials.tokens[contextName]; saveCredentials(credentials); return true; } return false; } function hasValidCredentials(contextName: string): boolean { const creds = getCredentials(contextName); if (!creds || !creds.token) { return false; } if (creds.expiresAt) { const expiresAt = new Date(creds.expiresAt); if (expiresAt <= new Date()) { return false; } } return true; } function getTargetEndpoint(targetName: string, contextName?: string): string | null { let ctx: ContextConfig | null; if (contextName) { ctx = loadContext(contextName); } else { ctx = getCurrentContext(); } if (!ctx) return null; const target = ctx.targets && ownValue(ctx.targets, targetName); return target ? target.endpoint : ctx.endpoint; } function varsPath(ctxName: string): string { assertContextName(ctxName); const varsDir = resolve(dirs, 'config', 'vars'); if (!fs.existsSync(varsDir)) { fs.mkdirSync(varsDir, { recursive: true, mode: DIRECTORY_MODE }); } return path.join(varsDir, `${ctxName}.json`); } function loadVars(ctxName: string): Record { return keyedMap(readJson>(varsPath(ctxName), {})); } function saveVars(ctxName: string, vars: Record): void { writeJson(varsPath(ctxName), vars); } function resolveContextName(contextName?: string): string | null { if (contextName) { assertContextName(contextName); return contextName; } const settings = loadSettings(); return settings.currentContext || null; } function setVar(key: string, value: string, contextName?: string): void { const ctxName = resolveContextName(contextName); if (!ctxName) { throw new Error('No active context. Run "context create" or "context use" first.'); } const vars = loadVars(ctxName); vars[key] = value; saveVars(ctxName, vars); } function getVar(key: string, contextName?: string): string | null { const ctxName = resolveContextName(contextName); if (!ctxName) return null; const vars = loadVars(ctxName); return ownValue(vars, key) ?? null; } function deleteVar(key: string, contextName?: string): boolean { const ctxName = resolveContextName(contextName); if (!ctxName) return false; const vars = loadVars(ctxName); if (Object.hasOwn(vars, key)) { delete vars[key]; saveVars(ctxName, vars); return true; } return false; } function listVars(contextName?: string): Record { const ctxName = resolveContextName(contextName); if (!ctxName) return {}; return { ...loadVars(ctxName) }; } function getClientConfig(targetName: string, contextName?: string): ClientConfig { const envPrefix = toolName.toUpperCase().replace(/[^A-Z0-9]/g, '_'); const targetSuffix = targetName.toUpperCase().replace(/[^A-Z0-9]/g, '_'); // Tier 1: Try appstash store const ctx = contextName ? loadContext(contextName) : getCurrentContext(); if (ctx) { const endpoint = getTargetEndpoint(targetName, ctx.name); const headers: Record = {}; if (hasValidCredentials(ctx.name)) { const creds = getCredentials(ctx.name); if (creds?.token) { headers['Authorization'] = `Bearer ${creds.token}`; } } if (endpoint) { return { endpoint, headers }; } } // Tier 2: Try env vars const envToken = process.env[`${envPrefix}_TOKEN`]; const envEndpoint = process.env[`${envPrefix}_${targetSuffix}_ENDPOINT`] || process.env[`${envPrefix}_ENDPOINT`]; if (envEndpoint) { const headers: Record = {}; if (envToken) { headers['Authorization'] = `Bearer ${envToken}`; } return { endpoint: envEndpoint, headers }; } // Tier 3: Throw with actionable error throw new Error( `No configuration found for target "${targetName}". ` + `Set up a context with "${toolName} context create" and authenticate with "${toolName} auth", ` + `or set ${envPrefix}_${targetSuffix}_ENDPOINT and ${envPrefix}_TOKEN environment variables.` ); } return { loadSettings, saveSettings, createContext, loadContext, listContexts, deleteContext, getCurrentContext, setCurrentContext, getTargetEndpoint, setCredentials, getCredentials, removeCredentials, hasValidCredentials, setVar, getVar, deleteVar, listVars, getClientConfig, }; }