import { readFile, stat } from 'node:fs/promises'; import { homedir } from 'node:os'; import { join } from 'node:path'; export type Config = { httpBaseUrl: string; socketBaseUrl: string; workspaceName: string; token?: string; email?: string; password?: string; stateFile: string; hermesBin: string; hermesTimeoutMs: number; hermesMaxOutputBytes: number; }; const SECRET_PATH = join(homedir(), '.hermes/secrets/colanode-family-bot.env'); export async function loadConfig(): Promise { const secrets = await readSecretEnv(SECRET_PATH); const env = { ...process.env, ...secrets }; return { httpBaseUrl: stripTrailingSlash(env.COLANODE_BASE_URL ?? 'https://colanode.reynafamily.com/client'), socketBaseUrl: stripTrailingSlash(env.COLANODE_SOCKET_BASE_URL ?? 'wss://colanode.reynafamily.com/client'), workspaceName: env.COLANODE_WORKSPACE_NAME ?? 'FamReynaWorkspace', token: emptyToUndefined(env.COLANODE_TOKEN ?? env.COLANODE_BOT_TOKEN), email: emptyToUndefined(env.COLANODE_EMAIL ?? env.COLANODE_BOT_EMAIL), password: emptyToUndefined(env.COLANODE_PASSWORD ?? env.COLANODE_BOT_PASSWORD), stateFile: env.STATE_FILE ?? join(homedir(), '.hermes/colanode-family-bot-state.json'), hermesBin: env.HERMES_BIN ?? 'hermes', hermesTimeoutMs: Number(env.HERMES_TIMEOUT_MS ?? 60_000), hermesMaxOutputBytes: Number(env.HERMES_MAX_OUTPUT_BYTES ?? 12_000) }; } async function readSecretEnv(path: string): Promise> { const info = await stat(path); if ((info.mode & 0o777) !== 0o600) { throw new Error(`Secret file must be mode 0600: ${path}`); } const text = await readFile(path, 'utf8'); const result: Record = {}; for (const rawLine of text.split(/\r?\n/)) { const line = rawLine.trim(); if (!line || line.startsWith('#')) continue; const eq = line.indexOf('='); if (eq <= 0) continue; const key = line.slice(0, eq).trim(); let value = line.slice(eq + 1).trim(); if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1); } result[key] = value; } return result; } function stripTrailingSlash(value: string): string { return value.replace(/\/+$/, ''); } function emptyToUndefined(value: string | undefined): string | undefined { return value && value.length > 0 ? value : undefined; }