// Package config — configuración por entorno, validada (fail-fast). // Paridad con server/src/config.js: parser .env propio (no pisa el entorno), // mismas variables, defaults y validaciones (SPEC §8.1). package config import ( "encoding/json" "fmt" "net" "net/url" "os" "path/filepath" "strconv" "strings" "time" ) const bindModeFile = ".bind-mode" const ( bindModeLoopback = "loopback" bindModeLAN = "lan" ) func readBindMode(path string) string { b, err := os.ReadFile(path) if err != nil { return "" } switch mode := strings.TrimSpace(string(b)); mode { case bindModeLoopback, bindModeLAN: return mode default: return "" } } func writeBindMode(path, mode string) { if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return } _ = os.WriteFile(path, []byte(mode+"\n"), 0o600) } // RouterSeed es una entrada de ROUTERS_JSON (semilla opcional de la tabla routers). type RouterSeed struct { ID string `json:"id"` Name string `json:"name"` Host string `json:"host"` Type string `json:"type"` // "glinet" | "openwrt" (default "openwrt") } // AdGuard configura el cliente estándar (env). Nil si no hay ADGUARD_URL. type AdGuard struct { URL string User string Pass string } // Webhook configura el notificador saliente de alertas (Fase 8.7b). Vacío si // no hay WEBHOOK_URL: el webhook se desactiva y el motor sigue igual. type Webhook struct { URL string Secret string Timeout time.Duration Retries int RetryDelay time.Duration Enabled bool } // Config es la config normalizada (equivalente al objeto de loadConfig). type Config struct { Port int BindAddr string // listener HTTP; loopback por defecto sin TLS NodeEnv string StaticDir string // resuelta (absoluta) DataDir string // resuelta (absoluta) DBDir string // DB_DIR resuelta (absoluta); def. DATA_DIR SessionSecret string // "" si falta (autogenerado en kv) AuthUser string AuthPass string DemoMode bool MaxSSEClients int Routers []RouterSeed SSHKeyPath string Adguard *AdGuard Webhook *Webhook WGInterface string CookieSecure string // "auto" | "always" | "never" TrustProxy bool // confiar en X-Forwarded-For/-Proto (detrás de proxy) MaxTsDriftSec int // ventana frescura ts agente en s (0 → default 5 min) GithubRepo string GithubToken string ServerRoot string AutoRearm bool // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos AutoReinstall bool // NETPULSE_AUTO_REINSTALL=1: el supervisor escala rearm→reinstall (#457); exige PUBLIC_URL PublicURL string // NETPULSE_PUBLIC_URL: URL base con la que los routers alcanzan al server (reinstall/self-heal) AgentURL string // NETPULSE_AGENT_URL: URL base preferente SOLO para agentes (install line, reinstall, reemit, auto-reinstall); manda sobre PublicURL (#1335) BeaconListen string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140" AgentAutoenroll bool // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367) // NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS=1: envía comandos privilegiados // a agentes conectados por HTTP. Solo para la transición a HTTPS. AllowInsecureAgentCommands bool Onbox bool // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS) GhostPortEnabled bool // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false MCPEnabled bool // NETPULSE_MCP_ENABLED=1: servidor MCP embebido en /mcp (#1114); default false // NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT, // default 443) junto al HTTP de PORT. Opt-in: sin la variable, arranque // idéntico al actual. El modo on-box ya sirve HTTPS en PORT (Fase 9) y no // necesita esta variable (#696). TLSEnabled bool TLSPort int // TLSPortSet (#978): true cuando NETPULSE_TLS_PORT venía en el entorno - // el puerto queda fijado por el env y Ajustes lo muestra bloqueado. TLSPortSet bool TLSCert string // NETPULSE_TLS_CERT: path del cert del usuario (opcional; junto a TLSKey) TLSKey string // NETPULSE_TLS_KEY: path de la clave del usuario (opcional; junto a TLSCert) // FORK: HTTPS with the server's own private CA (internal/tlsmode). // NETPULSE_TLS_ENABLED=1 with NETPULSE_TLS_CA=1 turns it on and locks // the switch in Settings > HTTPS; NETPULSE_HTTP_MODE locks the mode. // Anything else leaves both to the admin there. TLSCA bool // NETPULSE_TLS_CA=1: the extra listener serves a leaf of the private CA TLSNames []string // NETPULSE_TLS_NAMES: extra names/addresses for the certificate HTTPMode string // NETPULSE_HTTP_MODE: full | migrate | redirect ("" = from the UI) // RTLConsolePass (NETPULSE_RTL_PASS): contraseña web de la consola de // switches RTLPlayground (KP-9000, #639) para el sondeo HTTP de firmware // y uptime. Default "1234" (la que trae el firmware tras flasheo). RTLConsolePass string // RTLConsolePollSec (NETPULSE_RTL_POLL_S): cadencia del sondeo HTTP de la // consola RTLPlayground en segundos. 0/ausente → 300 (5 min). RTLConsolePollSec int // PollIntervalSec (NETPULSE_POLL_INTERVAL): cadencia del sondeo SSH del // poller en segundos. Default 30 (antes 5 s hardcoded, #715). Entero > 0. PollIntervalSec int // DBRollbackJournal (NETPULSE_DB_ROLLBACK_JOURNAL=1): fuerza el motor de // journal DELETE+FULL del on-box previo a #1700. El default para TODOS // los despliegues es WAL+NORMAL (el DELETE+FULL triplicaba las // escrituras medidas en flash/USB). DBRollbackJournal bool // DBTempStore (NETPULSE_DB_TEMP_STORE): 'memory'|'file'|'default'. // Default 'memory' (#1700): las agregaciones dejan de hacer spill a // ficheros temporales etilqs_* (~9 GB/día medidos en el reporte). DBTempStore string } // LoadDotEnv parsea un .env: KEY=VALUE por línea, '#' comentarios (línea // completa), comillas simples/dobles opcionales. NO pisa variables ya // presentes en el entorno (paridad con config.js:13-27). func LoadDotEnv(envPath string) { data, err := os.ReadFile(envPath) if err != nil { return } for _, rawLine := range strings.Split(string(data), "\n") { line := strings.TrimSpace(rawLine) if line == "" || strings.HasPrefix(line, "#") { continue } eq := strings.Index(line, "=") if eq == -1 { continue } key := strings.TrimSpace(line[:eq]) value := strings.TrimSpace(line[eq+1:]) if len(value) >= 2 { if (value[0] == '"' && value[len(value)-1] == '"') || (value[0] == '\'' && value[len(value)-1] == '\'') { value = value[1 : len(value)-1] } } if _, exists := os.LookupEnv(key); !exists { os.Setenv(key, value) } } } type issue struct { path, message string } // ValidationError es el error fail-fast de configuración (mismo formato que // config.js:67-70). type ValidationError struct{ issues []issue } func (e *ValidationError) Error() string { var b strings.Builder b.WriteString("[netpulse] Configuración inválida (revisa server/.env):") for _, i := range e.issues { fmt.Fprintf(&b, "\n - %s: %s", i.path, i.message) } return b.String() } // Load valida el entorno y devuelve la config normalizada. // env es un mapa key→value (normalmente leído de os.Environ); serverRoot es // el directorio base para resolver STATIC_DIR/DATA_DIR relativos (en Node es // server/; en Go el working directory del proceso — ver cmd/netpulse). // Fail-fast: devuelve error si falta algo crítico o ROUTERS_JSON es inválido. func Load(env map[string]string, serverRoot string) (*Config, error) { var errs ValidationError // PORT: int 1..65535, default 3000 port := 3000 if v, ok := env["PORT"]; ok && v != "" { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil || n < 1 || n > 65535 { errs.issues = append(errs.issues, issue{"PORT", "Expected int 1..65535"}) } else { port = n } } // NODE_ENV: development|production|test, default development nodeEnv := "development" if v, ok := env["NODE_ENV"]; ok && v != "" { switch v { case "development", "production", "test": nodeEnv = v default: errs.issues = append(errs.issues, issue{"NODE_ENV", "Invalid enum value. Expected 'development' | 'production' | 'test'"}) } } resolve := func(key, def string) string { p := def if v, ok := env[key]; ok && v != "" { p = v } if filepath.IsAbs(p) { return filepath.Clean(p) } return filepath.Join(serverRoot, p) } staticDir := resolve("STATIC_DIR", "../app/dist") dataDir := resolve("DATA_DIR", "./data") dbDir := resolve("DB_DIR", dataDir) // SESSION_SECRET: min 32, opcional sessionSecret := "" if v, ok := env["SESSION_SECRET"]; ok && v != "" { if len(v) < 32 { errs.issues = append(errs.issues, issue{"SESSION_SECRET", "String must contain at least 32 character(s)"}) } else { sessionSecret = v } } authUser := "admin" if v, ok := env["AUTH_USER"]; ok && v != "" { authUser = v } // NETPULSE_ONBOX: '0'|'1', opcional — modo on-box (Fase 9, SPEC R4/R5): // la config llega vía UCI (LoadUCIEnv) y AUTH_PASS pasa a ser opcional // (bootstrap con contraseña aleatoria en el primer arranque). Sin la // variable, el binario se comporta exactamente como hoy (CT). onbox := false if v, ok := env["NETPULSE_ONBOX"]; ok && v != "" { switch v { case "0": case "1": onbox = true default: errs.issues = append(errs.issues, issue{"NETPULSE_ONBOX", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_DB_ROLLBACK_JOURNAL: '0'|'1', opcional (#1700). 1 restaura el // journal DELETE+FULL del on-box previo a #1700; el default para todos // los despliegues es WAL+NORMAL (ver internal/db). rollbackJournal := false if v, ok := env["NETPULSE_DB_ROLLBACK_JOURNAL"]; ok && v != "" { switch v { case "0": case "1": rollbackJournal = true default: errs.issues = append(errs.issues, issue{"NETPULSE_DB_ROLLBACK_JOURNAL", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_DB_TEMP_STORE: 'memory'|'file'|'default' (#1700). Default // 'memory' en todos los despliegues: los spills de temp b-tree a fichero // eran la mayor fuente de escrituras medida. 'file'/'default' quedan // para diagnosticar con el comportamiento clásico. dbTempStore := "memory" if v, ok := env["NETPULSE_DB_TEMP_STORE"]; ok && v != "" { switch strings.ToLower(v) { case "memory": case "file": dbTempStore = "file" case "default": dbTempStore = "default" default: errs.issues = append(errs.issues, issue{"NETPULSE_DB_TEMP_STORE", "Invalid enum value. Expected 'memory' | 'file' | 'default'"}) } } // AUTH_PASS: obligatoria (fail-fast) aunque ya existan usuarios — salvo // en on-box, donde el bootstrap R4 genera una si falta (cmd/netpulse). // Longitud mínima 10, igual que la policy de los endpoints de cambio // (issue #216): un seed corto crearía un admin con contraseña trivial sin // que nadie lo valide después. authPass := "" if v, ok := env["AUTH_PASS"]; ok && v != "" { if len(v) < 10 { errs.issues = append(errs.issues, issue{"AUTH_PASS", "String must contain at least 10 character(s)"}) } else { authPass = v } } else if !onbox { errs.issues = append(errs.issues, issue{"AUTH_PASS", "Required"}) } // Placeholder detection (30-Ago-2026, leccion Yuvomi #937): rechazar // valores del .env.example en secretos criticos. placeholderMarkers := []string{"cambia", "changeme", "change-me", "example", "placeholder", "your-secret", "replace_me"} for _, kv := range []struct{ key, val string }{ {"AUTH_PASS", authPass}, {"SESSION_SECRET", sessionSecret}, } { low := strings.ToLower(kv.val) for _, m := range placeholderMarkers { if kv.val != "" && strings.Contains(low, m) { errs.issues = append(errs.issues, issue{kv.key, "contains a placeholder value from .env.example; generate a real secret"}) break } } } // DEMO_MODE: '0'|'1', opcional (demo solo si === '1') demoMode := false if v, ok := env["DEMO_MODE"]; ok && v != "" { switch v { case "0": case "1": demoMode = true default: errs.issues = append(errs.issues, issue{"DEMO_MODE", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_AUTO_REARM: '0'|'1', opcional (solo rearma si === '1'). // Opt-in explícito: nada autónomo sobre equipamiento de red sin // confirmación del usuario (regla Fase 10). autoRearm := false if v, ok := env["NETPULSE_AUTO_REARM"]; ok && v != "" { switch v { case "0": case "1": autoRearm = true default: errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REARM", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_AUTO_REINSTALL: '0'|'1', opcional (#457). El supervisor // escala rearm→reinstall cuando el reinicio no recupera el agente. // Exige NETPULSE_PUBLIC_URL: sin ella no hay forma fiable de decirle al // router desde dónde descargar el binario. autoReinstall := false if v, ok := env["NETPULSE_AUTO_REINSTALL"]; ok && v != "" { switch v { case "0": case "1": autoReinstall = true default: errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_PUBLIC_URL: URL base (http(s)://host[:port]) con la que los // ROUTERS alcanzan al servidor. Opcional; la usan el reinstall (manual y // del supervisor) como fuente preferente. publicURL := strings.TrimSpace(env["NETPULSE_PUBLIC_URL"]) if publicURL != "" { if !strings.HasPrefix(publicURL, "http://") && !strings.HasPrefix(publicURL, "https://") { errs.issues = append(errs.issues, issue{"NETPULSE_PUBLIC_URL", "String must contain a http:// or https:// prefix"}) } else { publicURL = strings.TrimRight(publicURL, "/") } } // NETPULSE_AGENT_URL: URL base (http(s)://host[:port]) con la que los // AGENTES deben alcanzar al servidor, p. ej. una URL de la LAN // (http://192.168.1.50:8080) cuando el server se sirve tras un reverse // proxy con dominio público (#1335). Opcional; manda sobre // NETPULSE_PUBLIC_URL en todo lo que configura la conexión agente -> // server (install line, reinstall, reemit, auto-reinstall). agentURL := strings.TrimSpace(env["NETPULSE_AGENT_URL"]) if agentURL != "" { if !strings.HasPrefix(agentURL, "http://") && !strings.HasPrefix(agentURL, "https://") { errs.issues = append(errs.issues, issue{"NETPULSE_AGENT_URL", "String must contain a http:// or https:// prefix"}) } else { agentURL = strings.TrimRight(agentURL, "/") } } if autoReinstall && publicURL == "" && agentURL == "" { errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "NETPULSE_PUBLIC_URL or NETPULSE_AGENT_URL is required when auto-reinstall is enabled"}) } // MAX_SSE_CLIENTS: int 1..100, default 10 maxSSE := 10 if v, ok := env["MAX_SSE_CLIENTS"]; ok && v != "" { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil || n < 1 || n > 100 { errs.issues = append(errs.issues, issue{"MAX_SSE_CLIENTS", "Expected int 1..100"}) } else { maxSSE = n } } // COOKIE_SECURE: auto|always|never, default auto cookieSecure := "auto" if v, ok := env["COOKIE_SECURE"]; ok && v != "" { switch v { case "auto", "always", "never": cookieSecure = v default: errs.issues = append(errs.issues, issue{"COOKIE_SECURE", "Invalid enum value. Expected 'auto' | 'always' | 'never'"}) } } // TRUST_PROXY: '1' solo cuando el servidor va detrás de un proxy/reverse // que setea X-Forwarded-For/-Proto (p. ej. NPM/Tailscale). Por defecto NO // se confía: la IP del socket es la real (auditoría de seguridad #1). trustProxy := false if v, ok := env["TRUST_PROXY"]; ok && v != "" { switch v { case "0": case "1": trustProxy = true default: errs.issues = append(errs.issues, issue{"TRUST_PROXY", "Invalid enum value. Expected '0' | '1'"}) } } // AGENT_MAX_TS_DRIFT_S: ventana de frescura del ts del agente en segundos // (anti-replay, auditoría de seguridad #2). 0 → default 5 min. maxTsDriftSec := 0 if v, ok := env["AGENT_MAX_TS_DRIFT_S"]; ok && v != "" { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil || n < 0 { errs.issues = append(errs.issues, issue{"AGENT_MAX_TS_DRIFT_S", "Expected int >= 0"}) } else { maxTsDriftSec = n } } // WG_INTERFACE: interfaz(es) WireGuard a sondear. Vacío o "auto" → se // descubren TODAS las interfaces del router (`wg show interfaces`) y se // agregan sus peers (#713). Un valor explícito (una interfaz o una lista // separada por comas, p. ej. "wg0" o "wg0,wg1") actúa como filtro/override // y solo se sondean esas interfaces. Un "wg0" explícito conserva el // comportamiento anterior. wgInterface := "auto" if v, ok := env["WG_INTERFACE"]; ok && v != "" { wgInterface = v } githubRepo := "gnacho/netpulse" if v, ok := env["GITHUB_REPO"]; ok && v != "" { githubRepo = v } githubToken := env["GITHUB_TOKEN"] // NETPULSE_BEACON_LISTEN: opcional. Dirección UDP para el listener de // beacons de pushers embebidos (#291); "" u "off" lo deshabilitan. beaconListen := strings.TrimSpace(env["NETPULSE_BEACON_LISTEN"]) if beaconListen == "off" || beaconListen == "0" { beaconListen = "" } // AGENT_AUTOENROLL: '0'|'1', opcional (#367). Con '1' el responder de // descubrimiento UDP entrega un token de alta de red y /api/agents/pair // lo acepta (solo para slugs NUEVOS). Opt-in explícito: sin él, el // responder anuncia el server sin token. agentAutoenroll := false if v, ok := env["AGENT_AUTOENROLL"]; ok && v != "" { switch v { case "0": case "1": agentAutoenroll = true default: errs.issues = append(errs.issues, issue{"AGENT_AUTOENROLL", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS: '0'|'1', opcional. Permite // enviar comandos privilegiados a agentes que siguen en HTTP. Solo para // la transición a HTTPS; el default los rechaza con 409. allowInsecureAgentCommands := false if v, ok := env["NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS"]; ok && v != "" { switch v { case "0": case "1": allowInsecureAgentCommands = true default: errs.issues = append(errs.issues, issue{"NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS", "Invalid enum value. Expected '0' | '1'"}) } } // ADGUARD_*: cliente estándar solo si hay URL válida var adguard *AdGuard if v, ok := env["ADGUARD_URL"]; ok && v != "" { if u, err := url.Parse(v); err != nil || u.Scheme == "" || u.Host == "" { errs.issues = append(errs.issues, issue{"ADGUARD_URL", "Invalid url"}) } else { user := "admin" if w, ok := env["ADGUARD_USER"]; ok && w != "" { user = w } adguard = &AdGuard{URL: strings.TrimSuffix(v, "/"), User: user, Pass: env["ADGUARD_PASS"]} } } // WEBHOOK_*: notificador saliente de alertas solo si hay URL válida. // Timeout/retries/retry_delay con defaults si no vienen. var webhook *Webhook if v, ok := env["WEBHOOK_URL"]; ok && v != "" { if u, err := url.Parse(v); err != nil || u.Scheme == "" || u.Host == "" { errs.issues = append(errs.issues, issue{"WEBHOOK_URL", "Invalid url"}) } else { timeout := 10 * time.Second if w, ok := env["WEBHOOK_TIMEOUT"]; ok && w != "" { if d, err := time.ParseDuration(w); err == nil && d > 0 { timeout = d } } retries := 3 if w, ok := env["WEBHOOK_RETRIES"]; ok && w != "" { if n, err := strconv.Atoi(w); err == nil && n >= 0 { retries = n } } delay := 2 * time.Second if w, ok := env["WEBHOOK_RETRY_DELAY"]; ok && w != "" { if d, err := time.ParseDuration(w); err == nil && d > 0 { delay = d } } webhook = &Webhook{ URL: v, Secret: env["WEBHOOK_SECRET"], Timeout: timeout, Retries: retries, RetryDelay: delay, Enabled: true, } } } // GHOST_PORT_ENABLED: '0'|'1', opcional - default false. Activa las alertas // de ghost port; mientras este desactivado, PortMonitor no evalua ni emite // alertas de puerto fantasma (#419). ghostPortEnabled := false if v, ok := env["GHOST_PORT_ENABLED"]; ok && v != "" { switch v { case "0": case "1": ghostPortEnabled = true default: errs.issues = append(errs.issues, issue{"GHOST_PORT_ENABLED", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_MCP_ENABLED: '0'|'1', opcional (#1114) - default false. Activa // el endpoint /mcp (streamable-HTTP) para asistentes AI; SOLO auth por API // token Bearer, nunca cookie de sesión. El puerto debe quedar en LAN. mcpEnabled := false if v, ok := env["NETPULSE_MCP_ENABLED"]; ok && v != "" { switch v { case "0": case "1": mcpEnabled = true default: errs.issues = append(errs.issues, issue{"NETPULSE_MCP_ENABLED", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_RTL_PASS / NETPULSE_RTL_POLL_S: sondeo HTTP de la consola de // switches RTLPlayground (KP-9000) para firmware + uptime (#639). La pass // por defecto es la del firmware tras flasheo; la cadencia 300 s (5 min). rtlPass := strings.TrimSpace(env["NETPULSE_RTL_PASS"]) if rtlPass == "" { rtlPass = "1234" } rtlPollSec := 300 if v, ok := env["NETPULSE_RTL_POLL_S"]; ok && v != "" { n, err := strconv.Atoi(v) if err != nil || n <= 0 { errs.issues = append(errs.issues, issue{"NETPULSE_RTL_POLL_S", "Expected a positive integer"}) } else { rtlPollSec = n } } // NETPULSE_POLL_INTERVAL: cadencia del sondeo SSH del poller en segundos // (#715). Entero > 0; default 30 (antes 5 s hardcoded). pollIntervalSec := 30 if v, ok := env["NETPULSE_POLL_INTERVAL"]; ok && v != "" { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil || n <= 0 { errs.issues = append(errs.issues, issue{"NETPULSE_POLL_INTERVAL", "Expected a positive integer"}) } else { pollIntervalSec = n } } // NETPULSE_TLS_ENABLED: '0'|'1', opcional — HTTPS adicional en un listener // propio (#696). Opt-in explícito: sin la variable, el binario se comporta // exactamente como hoy (solo HTTP en PORT). El modo on-box ya sirve HTTPS // en PORT y no necesita esta variable. tlsEnabled := false if v, ok := env["NETPULSE_TLS_ENABLED"]; ok && v != "" { switch v { case "0": case "1": tlsEnabled = true default: errs.issues = append(errs.issues, issue{"NETPULSE_TLS_ENABLED", "Invalid enum value. Expected '0' | '1'"}) } } // NETPULSE_TLS_PORT: int 1..65535, default 443 (solo relevante si TLS // está habilitado). tlsPort := 443 tlsPortSet := false if v, ok := env["NETPULSE_TLS_PORT"]; ok && v != "" { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil || n < 1 || n > 65535 { errs.issues = append(errs.issues, issue{"NETPULSE_TLS_PORT", "Expected int 1..65535"}) } else { tlsPort = n tlsPortSet = true } } // NETPULSE_BIND: dirección del listener HTTP. Sin TLS, sin on-box y en una // instalación nueva el default es loopback (#1607). Si ya existe la base de // datos se trata de una actualización, así que se conserva el listener // histórico en todas las interfaces para no cortar el acceso (#1647). La // decisión se guarda en data/.bind-mode: así un reinicio no vuelve a // abrir una instalación nueva que ya creó la base de datos. Un valor // explícito manda siempre. bindModePath := filepath.Join(dataDir, bindModeFile) bindMode := readBindMode(bindModePath) if bindMode == "" { if _, err := os.Stat(filepath.Join(dbDir, "netpulse.db")); err == nil { bindMode = bindModeLAN } else { bindMode = bindModeLoopback } writeBindMode(bindModePath, bindMode) } bindAddr := "127.0.0.1" if bindMode == bindModeLAN { bindAddr = "" } if tlsEnabled || onbox { bindAddr = "" } if v := strings.TrimSpace(env["NETPULSE_BIND"]); v != "" { if v == "localhost" || net.ParseIP(v) != nil { bindAddr = v } else { errs.issues = append(errs.issues, issue{"NETPULSE_BIND", "Expected an IP address or localhost"}) } } // NETPULSE_TLS_CERT / NETPULSE_TLS_KEY: paths del cert del usuario. Ambos // o ninguno (fail-fast si solo viene uno). tlsCert := strings.TrimSpace(env["NETPULSE_TLS_CERT"]) tlsKey := strings.TrimSpace(env["NETPULSE_TLS_KEY"]) if (tlsCert == "") != (tlsKey == "") { errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CERT/NETPULSE_TLS_KEY", "both must be set together"}) } // FORK: the private CA and what plain HTTP may do (internal/tlsmode). tlsCA := false switch v := strings.TrimSpace(env["NETPULSE_TLS_CA"]); v { case "", "0": case "1": tlsCA = true switch { case !tlsEnabled: errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "needs NETPULSE_TLS_ENABLED=1 (or leave both unset and turn HTTPS on in Settings)"}) case tlsCert != "": errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "cannot be used with NETPULSE_TLS_CERT/NETPULSE_TLS_KEY: the certificate comes from one or the other"}) } default: errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "Invalid enum value. Expected '0' | '1'"}) } var tlsNames []string for _, n := range strings.Split(env["NETPULSE_TLS_NAMES"], ",") { if n = strings.TrimSpace(n); n != "" { tlsNames = append(tlsNames, n) } } httpMode := strings.TrimSpace(env["NETPULSE_HTTP_MODE"]) switch httpMode { case "", "full": case "migrate", "redirect": // Only the private-CA HTTPS knows how to restrict plain HTTP; with // HTTPS configured otherwise the setting would be silently ignored. if onbox || (tlsEnabled && !tlsCA) { errs.issues = append(errs.issues, issue{"NETPULSE_HTTP_MODE", "only applies to HTTPS with the private CA (NETPULSE_TLS_CA=1, or HTTPS turned on in Settings)"}) } default: errs.issues = append(errs.issues, issue{"NETPULSE_HTTP_MODE", "Invalid enum value. Expected 'full' | 'migrate' | 'redirect'"}) } if len(errs.issues) > 0 { return nil, &errs } // ROUTERS_JSON: array de {id, name?, host, type?}; inválido → fail-fast var routers []RouterSeed if v, ok := env["ROUTERS_JSON"]; ok && v != "" { var raw []RouterSeed if err := json.Unmarshal([]byte(v), &raw); err != nil { return nil, fmt.Errorf("[netpulse] invalid ROUTERS_JSON: %w", err) } for i, r := range raw { if r.ID == "" || r.Host == "" { return nil, fmt.Errorf("[netpulse] invalid ROUTERS_JSON: entry %d requires id and host", i) } if r.Type == "" { raw[i].Type = "openwrt" } else if r.Type != "glinet" && r.Type != "openwrt" { return nil, fmt.Errorf("[netpulse] invalid ROUTERS_JSON: type must be glinet|openwrt") } } routers = raw } sshKeyPath := "" if v, ok := env["SSH_KEY_PATH"]; ok && v != "" { home, _ := os.UserHomeDir() if strings.HasPrefix(v, "~") { v = home + v[1:] } sshKeyPath = v } else { sshKeyPath = filepath.Join(dataDir, ".ssh", "id_ed25519") } return &Config{ Port: port, BindAddr: bindAddr, NodeEnv: nodeEnv, StaticDir: staticDir, DataDir: dataDir, DBDir: dbDir, SessionSecret: sessionSecret, AuthUser: authUser, AuthPass: authPass, DemoMode: demoMode, MaxSSEClients: maxSSE, Routers: routers, SSHKeyPath: sshKeyPath, Adguard: adguard, Webhook: webhook, WGInterface: wgInterface, CookieSecure: cookieSecure, TrustProxy: trustProxy, MaxTsDriftSec: maxTsDriftSec, GithubRepo: githubRepo, GithubToken: githubToken, ServerRoot: serverRoot, AutoRearm: autoRearm, AutoReinstall: autoReinstall, PublicURL: publicURL, AgentURL: agentURL, BeaconListen: beaconListen, AgentAutoenroll: agentAutoenroll, AllowInsecureAgentCommands: allowInsecureAgentCommands, Onbox: onbox, GhostPortEnabled: ghostPortEnabled, MCPEnabled: mcpEnabled, RTLConsolePass: rtlPass, RTLConsolePollSec: rtlPollSec, PollIntervalSec: pollIntervalSec, DBRollbackJournal: rollbackJournal, DBTempStore: dbTempStore, TLSEnabled: tlsEnabled, TLSPort: tlsPort, TLSPortSet: tlsPortSet, TLSCert: tlsCert, TLSKey: tlsKey, TLSCA: tlsCA, TLSNames: tlsNames, HTTPMode: httpMode, }, nil } // FromEnviron construye el mapa de entorno del proceso. func FromEnviron() map[string]string { env := map[string]string{} for _, kv := range os.Environ() { if eq := strings.Index(kv, "="); eq > 0 { env[kv[:eq]] = kv[eq+1:] } } return env }