/** * src/config.ts — T4: environment config loader * * Reads env vars once at startup, validates them, derives allowedOrigins from * local NIC IPs (M1 — NOT from bindHost; 0.0.0.0 is never a valid Origin), * and returns a frozen Config object. */ import os from 'node:os' import path from 'node:path' import type { Config, EnvLike } from './types.js' import { tmuxAvailable } from './session/tmux.js' /** USE_TMUX: '1'/'true'/'on' → on, '0'/'false'/'off' → off, else auto-detect tmux. */ function resolveUseTmux(raw: string | undefined): boolean { const v = raw?.trim().toLowerCase() if (v === '1' || v === 'true' || v === 'on') return true if (v === '0' || v === 'false' || v === 'off') return false return tmuxAvailable() // unset / 'auto' } // ── constants ───────────────────────────────────────────────────────────────── const DEFAULT_PORT = 3000 const DEFAULT_BIND_HOST = '0.0.0.0' const DEFAULT_IDLE_TTL_SEC = 24 * 60 * 60 // 24 hours in seconds const DEFAULT_SCROLLBACK_BYTES = 2 * 1024 * 1024 // 2 MB const DEFAULT_MAX_PAYLOAD_BYTES = 1 * 1024 * 1024 // 1 MB const DEFAULT_WS_PATH = '/term' const DEFAULT_MAX_SESSIONS = 50 const DEFAULT_MAX_MSGS_PER_SEC = 2000 const DEFAULT_PERM_TIMEOUT_MS = 5 * 60_000 // H3: hold a PermissionRequest for 5 min const DEFAULT_REAP_INTERVAL_MS = 60_000 // idle reaper sweeps every minute const DEFAULT_PREVIEW_BYTES = 24 * 1024 // manage-page preview: tail of scrollback const DEFAULT_PROJECT_SCAN_DEPTH = 4 // v0.6: how deep to scan roots for .git const DEFAULT_PROJECT_SCAN_TTL_MS = 10_000 // v0.6: /projects discovery cache TTL const DEFAULT_EDITOR_CMD = 'code' // v0.6: POST /open-in-editor launches this on the host // ── helpers ─────────────────────────────────────────────────────────────────── /** Parse a non-negative integer env value (0 allowed), or the fallback when unset. */ function parseNonNegativeInt( raw: string | undefined, label: string, fallback: number, ): number { if (raw === undefined) return fallback const n = Number(raw) if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) { throw new Error( `Invalid config: ${label}=${JSON.stringify(raw)} — must be a non-negative integer`, ) } return n } /** Parse a boolean env value ('1'/'true'/'on' → true, '0'/'false'/'off' → false), else fallback. */ function parseBool(raw: string | undefined, fallback: boolean): boolean { const v = raw?.trim().toLowerCase() if (v === undefined || v === '') return fallback if (v === '1' || v === 'true' || v === 'on') return true if (v === '0' || v === 'false' || v === 'off') return false return fallback } /** Parse PROJECT_ROOTS (comma-separated absolute paths); expand a leading '~' to homeDir. * Empty / unset → [homeDir]. */ function parseProjectRoots(raw: string | undefined, homeDir: string): readonly string[] { if (raw === undefined || raw.trim() === '') return Object.freeze([homeDir]) const roots = raw .split(',') .map((s) => s.trim()) .filter((s) => s !== '') .map((s) => (s === '~' ? homeDir : s.startsWith('~/') ? homeDir + s.slice(1) : s)) // Fail fast on relative roots: silently resolving them against the server's // CWD makes the scan target depend on where the process was launched (M1-style // "no surprising defaults"). Require absolute paths (after '~' expansion). for (const r of roots) { if (!path.isAbsolute(r)) { throw new Error( `Invalid config: PROJECT_ROOTS entry ${JSON.stringify(r)} — must be an absolute path (or '~' / '~/...').`, ) } } return Object.freeze(roots.length > 0 ? roots : [homeDir]) } function parsePort(raw: string | undefined): number { if (raw === undefined) return DEFAULT_PORT const n = Number(raw) if (!Number.isFinite(n) || !Number.isInteger(n) || n < 1 || n > 65535) { throw new Error( `Invalid config: PORT=${JSON.stringify(raw)} — must be an integer 1–65535`, ) } return n } function parseIdleTtl(raw: string | undefined): number { if (raw === undefined) return DEFAULT_IDLE_TTL_SEC * 1000 const n = Number(raw) if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) { throw new Error( `Invalid config: IDLE_TTL=${JSON.stringify(raw)} — must be a non-negative integer (seconds)`, ) } return n * 1000 } /** * Derive allowedOrigins from host NIC IPs (M1). * * Rules: * - Enumerate os.networkInterfaces(), pick IPv4 entries. * - Skip internal (loopback) entries — 127.0.0.1 / localhost are added explicitly. * - For every qualifying address, produce both http:// and https:// origins. * - Append ALLOWED_ORIGINS env-var items (comma-separated). * - Deduplicate. * - Never include 0.0.0.0 (wildcard listen address, never a browser Origin). */ /** True iff `value` parses as a URL with an http: or https: scheme (M1). */ function isHttpOrigin(value: string): boolean { try { const u = new URL(value) return u.protocol === 'http:' || u.protocol === 'https:' } catch { return false } } function deriveAllowedOrigins(port: number, extraEnv: string | undefined): readonly string[] { const set = new Set() // 1. Always include localhost / loopback const loopbackHosts = ['localhost', '127.0.0.1'] for (const host of loopbackHosts) { set.add(`http://${host}:${port}`) set.add(`https://${host}:${port}`) } // 2. Enumerate NIC IPv4 addresses — skip internal (loopback already handled above) const ifaces = os.networkInterfaces() for (const ifaceList of Object.values(ifaces)) { if (!ifaceList) continue for (const entry of ifaceList) { // Only IPv4, non-internal entries; never 0.0.0.0 if ( entry.family === 'IPv4' && !entry.internal && entry.address !== '0.0.0.0' ) { set.add(`http://${entry.address}:${port}`) set.add(`https://${entry.address}:${port}`) } } } // 3. Merge ALLOWED_ORIGINS env var (comma-separated list of origin strings). // Reject anything that is not a well-formed http(s) origin so an exotic // scheme (file:, data:, javascript:) can't slip into the whitelist (M1). if (extraEnv) { for (const raw of extraEnv.split(',')) { const trimmed = raw.trim() if (trimmed === '') continue if (isHttpOrigin(trimmed)) set.add(trimmed) } } return Object.freeze([...set]) } // ── loadConfig ──────────────────────────────────────────────────────────────── /** * Read and validate environment variables; fill in defaults for missing keys. * Invalid values (port out of range, TTL non-integer, etc.) throw immediately * so the server never starts in a misconfigured state (fail-fast). * * The returned Config is Object.freeze'd — immutable after construction. */ export function loadConfig(env: EnvLike): Config { const port = parsePort(env['PORT']) const bindHost = env['BIND_HOST'] ?? DEFAULT_BIND_HOST const shellPath = env['SHELL_PATH'] ?? (process.env['SHELL'] as string | undefined) ?? '/bin/zsh' const homeDir = os.homedir() const idleTtlMs = parseIdleTtl(env['IDLE_TTL']) const scrollbackBytes = parseNonNegativeInt( env['SCROLLBACK_BYTES'], 'SCROLLBACK_BYTES', DEFAULT_SCROLLBACK_BYTES, ) const maxPayloadBytes = parseNonNegativeInt( env['MAX_PAYLOAD_BYTES'], 'MAX_PAYLOAD_BYTES', DEFAULT_MAX_PAYLOAD_BYTES, ) const wsPath = env['WS_PATH'] ?? DEFAULT_WS_PATH const maxSessions = parseNonNegativeInt(env['MAX_SESSIONS'], 'MAX_SESSIONS', DEFAULT_MAX_SESSIONS) const maxMsgsPerSec = parseNonNegativeInt( env['MAX_MSGS_PER_SEC'], 'MAX_MSGS_PER_SEC', DEFAULT_MAX_MSGS_PER_SEC, ) const permTimeoutMs = parseNonNegativeInt( env['PERM_TIMEOUT_MS'], 'PERM_TIMEOUT_MS', DEFAULT_PERM_TIMEOUT_MS, ) const reapIntervalMs = parseNonNegativeInt( env['REAP_INTERVAL_MS'], 'REAP_INTERVAL_MS', DEFAULT_REAP_INTERVAL_MS, ) const previewBytes = parseNonNegativeInt(env['PREVIEW_BYTES'], 'PREVIEW_BYTES', DEFAULT_PREVIEW_BYTES) const useTmux = resolveUseTmux(env['USE_TMUX']) const allowedOrigins = deriveAllowedOrigins(port, env['ALLOWED_ORIGINS']) // v0.6 Project Manager — discovery config const projectRoots = parseProjectRoots(env['PROJECT_ROOTS'], homeDir) const projectScanDepth = parseNonNegativeInt( env['PROJECT_SCAN_DEPTH'], 'PROJECT_SCAN_DEPTH', DEFAULT_PROJECT_SCAN_DEPTH, ) const projectScanTtlMs = parseNonNegativeInt( env['PROJECT_SCAN_TTL'], 'PROJECT_SCAN_TTL', DEFAULT_PROJECT_SCAN_TTL_MS, ) const projectDirtyCheck = parseBool(env['PROJECT_DIRTY_CHECK'], true) const editorCmd = env['EDITOR_CMD']?.trim() || DEFAULT_EDITOR_CMD return Object.freeze({ port, bindHost, shellPath, homeDir, idleTtlMs, scrollbackBytes, maxPayloadBytes, wsPath, maxSessions, maxMsgsPerSec, permTimeoutMs, reapIntervalMs, previewBytes, useTmux, allowedOrigins, projectRoots, projectScanDepth, projectScanTtlMs, projectDirtyCheck, editorCmd, } satisfies Config) }