config.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. // Package config — configuración por entorno, validada (fail-fast).
  2. // Paridad con server/src/config.js: parser .env propio (no pisa el entorno),
  3. // mismas variables, defaults y validaciones (SPEC §8.1).
  4. package config
  5. import (
  6. "encoding/json"
  7. "fmt"
  8. "net"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. const bindModeFile = ".bind-mode"
  17. const (
  18. bindModeLoopback = "loopback"
  19. bindModeLAN = "lan"
  20. )
  21. func readBindMode(path string) string {
  22. b, err := os.ReadFile(path)
  23. if err != nil {
  24. return ""
  25. }
  26. switch mode := strings.TrimSpace(string(b)); mode {
  27. case bindModeLoopback, bindModeLAN:
  28. return mode
  29. default:
  30. return ""
  31. }
  32. }
  33. func writeBindMode(path, mode string) {
  34. if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
  35. return
  36. }
  37. _ = os.WriteFile(path, []byte(mode+"\n"), 0o600)
  38. }
  39. // RouterSeed es una entrada de ROUTERS_JSON (semilla opcional de la tabla routers).
  40. type RouterSeed struct {
  41. ID string `json:"id"`
  42. Name string `json:"name"`
  43. Host string `json:"host"`
  44. Type string `json:"type"` // "glinet" | "openwrt" (default "openwrt")
  45. }
  46. // AdGuard configura el cliente estándar (env). Nil si no hay ADGUARD_URL.
  47. type AdGuard struct {
  48. URL string
  49. User string
  50. Pass string
  51. }
  52. // Webhook configura el notificador saliente de alertas (Fase 8.7b). Vacío si
  53. // no hay WEBHOOK_URL: el webhook se desactiva y el motor sigue igual.
  54. type Webhook struct {
  55. URL string
  56. Secret string
  57. Timeout time.Duration
  58. Retries int
  59. RetryDelay time.Duration
  60. Enabled bool
  61. }
  62. // Config es la config normalizada (equivalente al objeto de loadConfig).
  63. type Config struct {
  64. Port int
  65. BindAddr string // listener HTTP; loopback por defecto sin TLS
  66. NodeEnv string
  67. StaticDir string // resuelta (absoluta)
  68. DataDir string // resuelta (absoluta)
  69. DBDir string // DB_DIR resuelta (absoluta); def. DATA_DIR
  70. SessionSecret string // "" si falta (autogenerado en kv)
  71. AuthUser string
  72. AuthPass string
  73. DemoMode bool
  74. MaxSSEClients int
  75. Routers []RouterSeed
  76. SSHKeyPath string
  77. Adguard *AdGuard
  78. Webhook *Webhook
  79. WGInterface string
  80. CookieSecure string // "auto" | "always" | "never"
  81. TrustProxy bool // confiar en X-Forwarded-For/-Proto (detrás de proxy)
  82. MaxTsDriftSec int // ventana frescura ts agente en s (0 → default 5 min)
  83. GithubRepo string
  84. GithubToken string
  85. ServerRoot string
  86. AutoRearm bool // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
  87. AutoReinstall bool // NETPULSE_AUTO_REINSTALL=1: el supervisor escala rearm→reinstall (#457); exige PUBLIC_URL
  88. PublicURL string // NETPULSE_PUBLIC_URL: URL base con la que los routers alcanzan al server (reinstall/self-heal)
  89. AgentURL string // NETPULSE_AGENT_URL: URL base preferente SOLO para agentes (install line, reinstall, reemit, auto-reinstall); manda sobre PublicURL (#1335)
  90. BeaconListen string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140"
  91. AgentAutoenroll bool // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
  92. // NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS=1: envía comandos privilegiados
  93. // a agentes conectados por HTTP. Solo para la transición a HTTPS.
  94. AllowInsecureAgentCommands bool
  95. Onbox bool // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
  96. GhostPortEnabled bool // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
  97. MCPEnabled bool // NETPULSE_MCP_ENABLED=1: servidor MCP embebido en /mcp (#1114); default false
  98. // NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT,
  99. // default 443) junto al HTTP de PORT. Opt-in: sin la variable, arranque
  100. // idéntico al actual. El modo on-box ya sirve HTTPS en PORT (Fase 9) y no
  101. // necesita esta variable (#696).
  102. TLSEnabled bool
  103. TLSPort int
  104. // TLSPortSet (#978): true cuando NETPULSE_TLS_PORT venía en el entorno -
  105. // el puerto queda fijado por el env y Ajustes lo muestra bloqueado.
  106. TLSPortSet bool
  107. TLSCert string // NETPULSE_TLS_CERT: path del cert del usuario (opcional; junto a TLSKey)
  108. TLSKey string // NETPULSE_TLS_KEY: path de la clave del usuario (opcional; junto a TLSCert)
  109. // FORK: HTTPS with the server's own private CA (internal/tlsmode).
  110. // NETPULSE_TLS_ENABLED=1 with NETPULSE_TLS_CA=1 turns it on and locks
  111. // the switch in Settings > HTTPS; NETPULSE_HTTP_MODE locks the mode.
  112. // Anything else leaves both to the admin there.
  113. TLSCA bool // NETPULSE_TLS_CA=1: the extra listener serves a leaf of the private CA
  114. TLSNames []string // NETPULSE_TLS_NAMES: extra names/addresses for the certificate
  115. HTTPMode string // NETPULSE_HTTP_MODE: full | migrate | redirect ("" = from the UI)
  116. // RTLConsolePass (NETPULSE_RTL_PASS): contraseña web de la consola de
  117. // switches RTLPlayground (KP-9000, #639) para el sondeo HTTP de firmware
  118. // y uptime. Default "1234" (la que trae el firmware tras flasheo).
  119. RTLConsolePass string
  120. // RTLConsolePollSec (NETPULSE_RTL_POLL_S): cadencia del sondeo HTTP de la
  121. // consola RTLPlayground en segundos. 0/ausente → 300 (5 min).
  122. RTLConsolePollSec int
  123. // PollIntervalSec (NETPULSE_POLL_INTERVAL): cadencia del sondeo SSH del
  124. // poller en segundos. Default 30 (antes 5 s hardcoded, #715). Entero > 0.
  125. PollIntervalSec int
  126. // DBRollbackJournal (NETPULSE_DB_ROLLBACK_JOURNAL=1): fuerza el motor de
  127. // journal DELETE+FULL del on-box previo a #1700. El default para TODOS
  128. // los despliegues es WAL+NORMAL (el DELETE+FULL triplicaba las
  129. // escrituras medidas en flash/USB).
  130. DBRollbackJournal bool
  131. // DBTempStore (NETPULSE_DB_TEMP_STORE): 'memory'|'file'|'default'.
  132. // Default 'memory' (#1700): las agregaciones dejan de hacer spill a
  133. // ficheros temporales etilqs_* (~9 GB/día medidos en el reporte).
  134. DBTempStore string
  135. }
  136. // LoadDotEnv parsea un .env: KEY=VALUE por línea, '#' comentarios (línea
  137. // completa), comillas simples/dobles opcionales. NO pisa variables ya
  138. // presentes en el entorno (paridad con config.js:13-27).
  139. func LoadDotEnv(envPath string) {
  140. data, err := os.ReadFile(envPath)
  141. if err != nil {
  142. return
  143. }
  144. for _, rawLine := range strings.Split(string(data), "\n") {
  145. line := strings.TrimSpace(rawLine)
  146. if line == "" || strings.HasPrefix(line, "#") {
  147. continue
  148. }
  149. eq := strings.Index(line, "=")
  150. if eq == -1 {
  151. continue
  152. }
  153. key := strings.TrimSpace(line[:eq])
  154. value := strings.TrimSpace(line[eq+1:])
  155. if len(value) >= 2 {
  156. if (value[0] == '"' && value[len(value)-1] == '"') || (value[0] == '\'' && value[len(value)-1] == '\'') {
  157. value = value[1 : len(value)-1]
  158. }
  159. }
  160. if _, exists := os.LookupEnv(key); !exists {
  161. os.Setenv(key, value)
  162. }
  163. }
  164. }
  165. type issue struct {
  166. path, message string
  167. }
  168. // ValidationError es el error fail-fast de configuración (mismo formato que
  169. // config.js:67-70).
  170. type ValidationError struct{ issues []issue }
  171. func (e *ValidationError) Error() string {
  172. var b strings.Builder
  173. b.WriteString("[netpulse] Configuración inválida (revisa server/.env):")
  174. for _, i := range e.issues {
  175. fmt.Fprintf(&b, "\n - %s: %s", i.path, i.message)
  176. }
  177. return b.String()
  178. }
  179. // Load valida el entorno y devuelve la config normalizada.
  180. // env es un mapa key→value (normalmente leído de os.Environ); serverRoot es
  181. // el directorio base para resolver STATIC_DIR/DATA_DIR relativos (en Node es
  182. // server/; en Go el working directory del proceso — ver cmd/netpulse).
  183. // Fail-fast: devuelve error si falta algo crítico o ROUTERS_JSON es inválido.
  184. func Load(env map[string]string, serverRoot string) (*Config, error) {
  185. var errs ValidationError
  186. // PORT: int 1..65535, default 3000
  187. port := 3000
  188. if v, ok := env["PORT"]; ok && v != "" {
  189. n, err := strconv.Atoi(strings.TrimSpace(v))
  190. if err != nil || n < 1 || n > 65535 {
  191. errs.issues = append(errs.issues, issue{"PORT", "Expected int 1..65535"})
  192. } else {
  193. port = n
  194. }
  195. }
  196. // NODE_ENV: development|production|test, default development
  197. nodeEnv := "development"
  198. if v, ok := env["NODE_ENV"]; ok && v != "" {
  199. switch v {
  200. case "development", "production", "test":
  201. nodeEnv = v
  202. default:
  203. errs.issues = append(errs.issues, issue{"NODE_ENV", "Invalid enum value. Expected 'development' | 'production' | 'test'"})
  204. }
  205. }
  206. resolve := func(key, def string) string {
  207. p := def
  208. if v, ok := env[key]; ok && v != "" {
  209. p = v
  210. }
  211. if filepath.IsAbs(p) {
  212. return filepath.Clean(p)
  213. }
  214. return filepath.Join(serverRoot, p)
  215. }
  216. staticDir := resolve("STATIC_DIR", "../app/dist")
  217. dataDir := resolve("DATA_DIR", "./data")
  218. dbDir := resolve("DB_DIR", dataDir)
  219. // SESSION_SECRET: min 32, opcional
  220. sessionSecret := ""
  221. if v, ok := env["SESSION_SECRET"]; ok && v != "" {
  222. if len(v) < 32 {
  223. errs.issues = append(errs.issues, issue{"SESSION_SECRET", "String must contain at least 32 character(s)"})
  224. } else {
  225. sessionSecret = v
  226. }
  227. }
  228. authUser := "admin"
  229. if v, ok := env["AUTH_USER"]; ok && v != "" {
  230. authUser = v
  231. }
  232. // NETPULSE_ONBOX: '0'|'1', opcional — modo on-box (Fase 9, SPEC R4/R5):
  233. // la config llega vía UCI (LoadUCIEnv) y AUTH_PASS pasa a ser opcional
  234. // (bootstrap con contraseña aleatoria en el primer arranque). Sin la
  235. // variable, el binario se comporta exactamente como hoy (CT).
  236. onbox := false
  237. if v, ok := env["NETPULSE_ONBOX"]; ok && v != "" {
  238. switch v {
  239. case "0":
  240. case "1":
  241. onbox = true
  242. default:
  243. errs.issues = append(errs.issues, issue{"NETPULSE_ONBOX", "Invalid enum value. Expected '0' | '1'"})
  244. }
  245. }
  246. // NETPULSE_DB_ROLLBACK_JOURNAL: '0'|'1', opcional (#1700). 1 restaura el
  247. // journal DELETE+FULL del on-box previo a #1700; el default para todos
  248. // los despliegues es WAL+NORMAL (ver internal/db).
  249. rollbackJournal := false
  250. if v, ok := env["NETPULSE_DB_ROLLBACK_JOURNAL"]; ok && v != "" {
  251. switch v {
  252. case "0":
  253. case "1":
  254. rollbackJournal = true
  255. default:
  256. errs.issues = append(errs.issues, issue{"NETPULSE_DB_ROLLBACK_JOURNAL", "Invalid enum value. Expected '0' | '1'"})
  257. }
  258. }
  259. // NETPULSE_DB_TEMP_STORE: 'memory'|'file'|'default' (#1700). Default
  260. // 'memory' en todos los despliegues: los spills de temp b-tree a fichero
  261. // eran la mayor fuente de escrituras medida. 'file'/'default' quedan
  262. // para diagnosticar con el comportamiento clásico.
  263. dbTempStore := "memory"
  264. if v, ok := env["NETPULSE_DB_TEMP_STORE"]; ok && v != "" {
  265. switch strings.ToLower(v) {
  266. case "memory":
  267. case "file":
  268. dbTempStore = "file"
  269. case "default":
  270. dbTempStore = "default"
  271. default:
  272. errs.issues = append(errs.issues, issue{"NETPULSE_DB_TEMP_STORE", "Invalid enum value. Expected 'memory' | 'file' | 'default'"})
  273. }
  274. }
  275. // AUTH_PASS: obligatoria (fail-fast) aunque ya existan usuarios — salvo
  276. // en on-box, donde el bootstrap R4 genera una si falta (cmd/netpulse).
  277. // Longitud mínima 10, igual que la policy de los endpoints de cambio
  278. // (issue #216): un seed corto crearía un admin con contraseña trivial sin
  279. // que nadie lo valide después.
  280. authPass := ""
  281. if v, ok := env["AUTH_PASS"]; ok && v != "" {
  282. if len(v) < 10 {
  283. errs.issues = append(errs.issues, issue{"AUTH_PASS", "String must contain at least 10 character(s)"})
  284. } else {
  285. authPass = v
  286. }
  287. } else if !onbox {
  288. errs.issues = append(errs.issues, issue{"AUTH_PASS", "Required"})
  289. }
  290. // Placeholder detection (30-Ago-2026, leccion Yuvomi #937): rechazar
  291. // valores del .env.example en secretos criticos.
  292. placeholderMarkers := []string{"cambia", "changeme", "change-me", "example", "placeholder", "your-secret", "replace_me"}
  293. for _, kv := range []struct{ key, val string }{
  294. {"AUTH_PASS", authPass},
  295. {"SESSION_SECRET", sessionSecret},
  296. } {
  297. low := strings.ToLower(kv.val)
  298. for _, m := range placeholderMarkers {
  299. if kv.val != "" && strings.Contains(low, m) {
  300. errs.issues = append(errs.issues, issue{kv.key, "contains a placeholder value from .env.example; generate a real secret"})
  301. break
  302. }
  303. }
  304. }
  305. // DEMO_MODE: '0'|'1', opcional (demo solo si === '1')
  306. demoMode := false
  307. if v, ok := env["DEMO_MODE"]; ok && v != "" {
  308. switch v {
  309. case "0":
  310. case "1":
  311. demoMode = true
  312. default:
  313. errs.issues = append(errs.issues, issue{"DEMO_MODE", "Invalid enum value. Expected '0' | '1'"})
  314. }
  315. }
  316. // NETPULSE_AUTO_REARM: '0'|'1', opcional (solo rearma si === '1').
  317. // Opt-in explícito: nada autónomo sobre equipamiento de red sin
  318. // confirmación del usuario (regla Fase 10).
  319. autoRearm := false
  320. if v, ok := env["NETPULSE_AUTO_REARM"]; ok && v != "" {
  321. switch v {
  322. case "0":
  323. case "1":
  324. autoRearm = true
  325. default:
  326. errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REARM", "Invalid enum value. Expected '0' | '1'"})
  327. }
  328. }
  329. // NETPULSE_AUTO_REINSTALL: '0'|'1', opcional (#457). El supervisor
  330. // escala rearm→reinstall cuando el reinicio no recupera el agente.
  331. // Exige NETPULSE_PUBLIC_URL: sin ella no hay forma fiable de decirle al
  332. // router desde dónde descargar el binario.
  333. autoReinstall := false
  334. if v, ok := env["NETPULSE_AUTO_REINSTALL"]; ok && v != "" {
  335. switch v {
  336. case "0":
  337. case "1":
  338. autoReinstall = true
  339. default:
  340. errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "Invalid enum value. Expected '0' | '1'"})
  341. }
  342. }
  343. // NETPULSE_PUBLIC_URL: URL base (http(s)://host[:port]) con la que los
  344. // ROUTERS alcanzan al servidor. Opcional; la usan el reinstall (manual y
  345. // del supervisor) como fuente preferente.
  346. publicURL := strings.TrimSpace(env["NETPULSE_PUBLIC_URL"])
  347. if publicURL != "" {
  348. if !strings.HasPrefix(publicURL, "http://") && !strings.HasPrefix(publicURL, "https://") {
  349. errs.issues = append(errs.issues, issue{"NETPULSE_PUBLIC_URL", "String must contain a http:// or https:// prefix"})
  350. } else {
  351. publicURL = strings.TrimRight(publicURL, "/")
  352. }
  353. }
  354. // NETPULSE_AGENT_URL: URL base (http(s)://host[:port]) con la que los
  355. // AGENTES deben alcanzar al servidor, p. ej. una URL de la LAN
  356. // (http://192.168.1.50:8080) cuando el server se sirve tras un reverse
  357. // proxy con dominio público (#1335). Opcional; manda sobre
  358. // NETPULSE_PUBLIC_URL en todo lo que configura la conexión agente ->
  359. // server (install line, reinstall, reemit, auto-reinstall).
  360. agentURL := strings.TrimSpace(env["NETPULSE_AGENT_URL"])
  361. if agentURL != "" {
  362. if !strings.HasPrefix(agentURL, "http://") && !strings.HasPrefix(agentURL, "https://") {
  363. errs.issues = append(errs.issues, issue{"NETPULSE_AGENT_URL", "String must contain a http:// or https:// prefix"})
  364. } else {
  365. agentURL = strings.TrimRight(agentURL, "/")
  366. }
  367. }
  368. if autoReinstall && publicURL == "" && agentURL == "" {
  369. errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "NETPULSE_PUBLIC_URL or NETPULSE_AGENT_URL is required when auto-reinstall is enabled"})
  370. }
  371. // MAX_SSE_CLIENTS: int 1..100, default 10
  372. maxSSE := 10
  373. if v, ok := env["MAX_SSE_CLIENTS"]; ok && v != "" {
  374. n, err := strconv.Atoi(strings.TrimSpace(v))
  375. if err != nil || n < 1 || n > 100 {
  376. errs.issues = append(errs.issues, issue{"MAX_SSE_CLIENTS", "Expected int 1..100"})
  377. } else {
  378. maxSSE = n
  379. }
  380. }
  381. // COOKIE_SECURE: auto|always|never, default auto
  382. cookieSecure := "auto"
  383. if v, ok := env["COOKIE_SECURE"]; ok && v != "" {
  384. switch v {
  385. case "auto", "always", "never":
  386. cookieSecure = v
  387. default:
  388. errs.issues = append(errs.issues, issue{"COOKIE_SECURE", "Invalid enum value. Expected 'auto' | 'always' | 'never'"})
  389. }
  390. }
  391. // TRUST_PROXY: '1' solo cuando el servidor va detrás de un proxy/reverse
  392. // que setea X-Forwarded-For/-Proto (p. ej. NPM/Tailscale). Por defecto NO
  393. // se confía: la IP del socket es la real (auditoría de seguridad #1).
  394. trustProxy := false
  395. if v, ok := env["TRUST_PROXY"]; ok && v != "" {
  396. switch v {
  397. case "0":
  398. case "1":
  399. trustProxy = true
  400. default:
  401. errs.issues = append(errs.issues, issue{"TRUST_PROXY", "Invalid enum value. Expected '0' | '1'"})
  402. }
  403. }
  404. // AGENT_MAX_TS_DRIFT_S: ventana de frescura del ts del agente en segundos
  405. // (anti-replay, auditoría de seguridad #2). 0 → default 5 min.
  406. maxTsDriftSec := 0
  407. if v, ok := env["AGENT_MAX_TS_DRIFT_S"]; ok && v != "" {
  408. n, err := strconv.Atoi(strings.TrimSpace(v))
  409. if err != nil || n < 0 {
  410. errs.issues = append(errs.issues, issue{"AGENT_MAX_TS_DRIFT_S", "Expected int >= 0"})
  411. } else {
  412. maxTsDriftSec = n
  413. }
  414. }
  415. // WG_INTERFACE: interfaz(es) WireGuard a sondear. Vacío o "auto" → se
  416. // descubren TODAS las interfaces del router (`wg show interfaces`) y se
  417. // agregan sus peers (#713). Un valor explícito (una interfaz o una lista
  418. // separada por comas, p. ej. "wg0" o "wg0,wg1") actúa como filtro/override
  419. // y solo se sondean esas interfaces. Un "wg0" explícito conserva el
  420. // comportamiento anterior.
  421. wgInterface := "auto"
  422. if v, ok := env["WG_INTERFACE"]; ok && v != "" {
  423. wgInterface = v
  424. }
  425. githubRepo := "gnacho/netpulse"
  426. if v, ok := env["GITHUB_REPO"]; ok && v != "" {
  427. githubRepo = v
  428. }
  429. githubToken := env["GITHUB_TOKEN"]
  430. // NETPULSE_BEACON_LISTEN: opcional. Dirección UDP para el listener de
  431. // beacons de pushers embebidos (#291); "" u "off" lo deshabilitan.
  432. beaconListen := strings.TrimSpace(env["NETPULSE_BEACON_LISTEN"])
  433. if beaconListen == "off" || beaconListen == "0" {
  434. beaconListen = ""
  435. }
  436. // AGENT_AUTOENROLL: '0'|'1', opcional (#367). Con '1' el responder de
  437. // descubrimiento UDP entrega un token de alta de red y /api/agents/pair
  438. // lo acepta (solo para slugs NUEVOS). Opt-in explícito: sin él, el
  439. // responder anuncia el server sin token.
  440. agentAutoenroll := false
  441. if v, ok := env["AGENT_AUTOENROLL"]; ok && v != "" {
  442. switch v {
  443. case "0":
  444. case "1":
  445. agentAutoenroll = true
  446. default:
  447. errs.issues = append(errs.issues, issue{"AGENT_AUTOENROLL", "Invalid enum value. Expected '0' | '1'"})
  448. }
  449. }
  450. // NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS: '0'|'1', opcional. Permite
  451. // enviar comandos privilegiados a agentes que siguen en HTTP. Solo para
  452. // la transición a HTTPS; el default los rechaza con 409.
  453. allowInsecureAgentCommands := false
  454. if v, ok := env["NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS"]; ok && v != "" {
  455. switch v {
  456. case "0":
  457. case "1":
  458. allowInsecureAgentCommands = true
  459. default:
  460. errs.issues = append(errs.issues, issue{"NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS", "Invalid enum value. Expected '0' | '1'"})
  461. }
  462. }
  463. // ADGUARD_*: cliente estándar solo si hay URL válida
  464. var adguard *AdGuard
  465. if v, ok := env["ADGUARD_URL"]; ok && v != "" {
  466. if u, err := url.Parse(v); err != nil || u.Scheme == "" || u.Host == "" {
  467. errs.issues = append(errs.issues, issue{"ADGUARD_URL", "Invalid url"})
  468. } else {
  469. user := "admin"
  470. if w, ok := env["ADGUARD_USER"]; ok && w != "" {
  471. user = w
  472. }
  473. adguard = &AdGuard{URL: strings.TrimSuffix(v, "/"), User: user, Pass: env["ADGUARD_PASS"]}
  474. }
  475. }
  476. // WEBHOOK_*: notificador saliente de alertas solo si hay URL válida.
  477. // Timeout/retries/retry_delay con defaults si no vienen.
  478. var webhook *Webhook
  479. if v, ok := env["WEBHOOK_URL"]; ok && v != "" {
  480. if u, err := url.Parse(v); err != nil || u.Scheme == "" || u.Host == "" {
  481. errs.issues = append(errs.issues, issue{"WEBHOOK_URL", "Invalid url"})
  482. } else {
  483. timeout := 10 * time.Second
  484. if w, ok := env["WEBHOOK_TIMEOUT"]; ok && w != "" {
  485. if d, err := time.ParseDuration(w); err == nil && d > 0 {
  486. timeout = d
  487. }
  488. }
  489. retries := 3
  490. if w, ok := env["WEBHOOK_RETRIES"]; ok && w != "" {
  491. if n, err := strconv.Atoi(w); err == nil && n >= 0 {
  492. retries = n
  493. }
  494. }
  495. delay := 2 * time.Second
  496. if w, ok := env["WEBHOOK_RETRY_DELAY"]; ok && w != "" {
  497. if d, err := time.ParseDuration(w); err == nil && d > 0 {
  498. delay = d
  499. }
  500. }
  501. webhook = &Webhook{
  502. URL: v,
  503. Secret: env["WEBHOOK_SECRET"],
  504. Timeout: timeout,
  505. Retries: retries,
  506. RetryDelay: delay,
  507. Enabled: true,
  508. }
  509. }
  510. }
  511. // GHOST_PORT_ENABLED: '0'|'1', opcional - default false. Activa las alertas
  512. // de ghost port; mientras este desactivado, PortMonitor no evalua ni emite
  513. // alertas de puerto fantasma (#419).
  514. ghostPortEnabled := false
  515. if v, ok := env["GHOST_PORT_ENABLED"]; ok && v != "" {
  516. switch v {
  517. case "0":
  518. case "1":
  519. ghostPortEnabled = true
  520. default:
  521. errs.issues = append(errs.issues, issue{"GHOST_PORT_ENABLED", "Invalid enum value. Expected '0' | '1'"})
  522. }
  523. }
  524. // NETPULSE_MCP_ENABLED: '0'|'1', opcional (#1114) - default false. Activa
  525. // el endpoint /mcp (streamable-HTTP) para asistentes AI; SOLO auth por API
  526. // token Bearer, nunca cookie de sesión. El puerto debe quedar en LAN.
  527. mcpEnabled := false
  528. if v, ok := env["NETPULSE_MCP_ENABLED"]; ok && v != "" {
  529. switch v {
  530. case "0":
  531. case "1":
  532. mcpEnabled = true
  533. default:
  534. errs.issues = append(errs.issues, issue{"NETPULSE_MCP_ENABLED", "Invalid enum value. Expected '0' | '1'"})
  535. }
  536. }
  537. // NETPULSE_RTL_PASS / NETPULSE_RTL_POLL_S: sondeo HTTP de la consola de
  538. // switches RTLPlayground (KP-9000) para firmware + uptime (#639). La pass
  539. // por defecto es la del firmware tras flasheo; la cadencia 300 s (5 min).
  540. rtlPass := strings.TrimSpace(env["NETPULSE_RTL_PASS"])
  541. if rtlPass == "" {
  542. rtlPass = "1234"
  543. }
  544. rtlPollSec := 300
  545. if v, ok := env["NETPULSE_RTL_POLL_S"]; ok && v != "" {
  546. n, err := strconv.Atoi(v)
  547. if err != nil || n <= 0 {
  548. errs.issues = append(errs.issues, issue{"NETPULSE_RTL_POLL_S", "Expected a positive integer"})
  549. } else {
  550. rtlPollSec = n
  551. }
  552. }
  553. // NETPULSE_POLL_INTERVAL: cadencia del sondeo SSH del poller en segundos
  554. // (#715). Entero > 0; default 30 (antes 5 s hardcoded).
  555. pollIntervalSec := 30
  556. if v, ok := env["NETPULSE_POLL_INTERVAL"]; ok && v != "" {
  557. n, err := strconv.Atoi(strings.TrimSpace(v))
  558. if err != nil || n <= 0 {
  559. errs.issues = append(errs.issues, issue{"NETPULSE_POLL_INTERVAL", "Expected a positive integer"})
  560. } else {
  561. pollIntervalSec = n
  562. }
  563. }
  564. // NETPULSE_TLS_ENABLED: '0'|'1', opcional — HTTPS adicional en un listener
  565. // propio (#696). Opt-in explícito: sin la variable, el binario se comporta
  566. // exactamente como hoy (solo HTTP en PORT). El modo on-box ya sirve HTTPS
  567. // en PORT y no necesita esta variable.
  568. tlsEnabled := false
  569. if v, ok := env["NETPULSE_TLS_ENABLED"]; ok && v != "" {
  570. switch v {
  571. case "0":
  572. case "1":
  573. tlsEnabled = true
  574. default:
  575. errs.issues = append(errs.issues, issue{"NETPULSE_TLS_ENABLED", "Invalid enum value. Expected '0' | '1'"})
  576. }
  577. }
  578. // NETPULSE_TLS_PORT: int 1..65535, default 443 (solo relevante si TLS
  579. // está habilitado).
  580. tlsPort := 443
  581. tlsPortSet := false
  582. if v, ok := env["NETPULSE_TLS_PORT"]; ok && v != "" {
  583. n, err := strconv.Atoi(strings.TrimSpace(v))
  584. if err != nil || n < 1 || n > 65535 {
  585. errs.issues = append(errs.issues, issue{"NETPULSE_TLS_PORT", "Expected int 1..65535"})
  586. } else {
  587. tlsPort = n
  588. tlsPortSet = true
  589. }
  590. }
  591. // NETPULSE_BIND: dirección del listener HTTP. Sin TLS, sin on-box y en una
  592. // instalación nueva el default es loopback (#1607). Si ya existe la base de
  593. // datos se trata de una actualización, así que se conserva el listener
  594. // histórico en todas las interfaces para no cortar el acceso (#1647). La
  595. // decisión se guarda en data/.bind-mode: así un reinicio no vuelve a
  596. // abrir una instalación nueva que ya creó la base de datos. Un valor
  597. // explícito manda siempre.
  598. bindModePath := filepath.Join(dataDir, bindModeFile)
  599. bindMode := readBindMode(bindModePath)
  600. if bindMode == "" {
  601. if _, err := os.Stat(filepath.Join(dbDir, "netpulse.db")); err == nil {
  602. bindMode = bindModeLAN
  603. } else {
  604. bindMode = bindModeLoopback
  605. }
  606. writeBindMode(bindModePath, bindMode)
  607. }
  608. bindAddr := "127.0.0.1"
  609. if bindMode == bindModeLAN {
  610. bindAddr = ""
  611. }
  612. if tlsEnabled || onbox {
  613. bindAddr = ""
  614. }
  615. if v := strings.TrimSpace(env["NETPULSE_BIND"]); v != "" {
  616. if v == "localhost" || net.ParseIP(v) != nil {
  617. bindAddr = v
  618. } else {
  619. errs.issues = append(errs.issues, issue{"NETPULSE_BIND", "Expected an IP address or localhost"})
  620. }
  621. }
  622. // NETPULSE_TLS_CERT / NETPULSE_TLS_KEY: paths del cert del usuario. Ambos
  623. // o ninguno (fail-fast si solo viene uno).
  624. tlsCert := strings.TrimSpace(env["NETPULSE_TLS_CERT"])
  625. tlsKey := strings.TrimSpace(env["NETPULSE_TLS_KEY"])
  626. if (tlsCert == "") != (tlsKey == "") {
  627. errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CERT/NETPULSE_TLS_KEY", "both must be set together"})
  628. }
  629. // FORK: the private CA and what plain HTTP may do (internal/tlsmode).
  630. tlsCA := false
  631. switch v := strings.TrimSpace(env["NETPULSE_TLS_CA"]); v {
  632. case "", "0":
  633. case "1":
  634. tlsCA = true
  635. switch {
  636. case !tlsEnabled:
  637. errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "needs NETPULSE_TLS_ENABLED=1 (or leave both unset and turn HTTPS on in Settings)"})
  638. case tlsCert != "":
  639. 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"})
  640. }
  641. default:
  642. errs.issues = append(errs.issues, issue{"NETPULSE_TLS_CA", "Invalid enum value. Expected '0' | '1'"})
  643. }
  644. var tlsNames []string
  645. for _, n := range strings.Split(env["NETPULSE_TLS_NAMES"], ",") {
  646. if n = strings.TrimSpace(n); n != "" {
  647. tlsNames = append(tlsNames, n)
  648. }
  649. }
  650. httpMode := strings.TrimSpace(env["NETPULSE_HTTP_MODE"])
  651. switch httpMode {
  652. case "", "full":
  653. case "migrate", "redirect":
  654. // Only the private-CA HTTPS knows how to restrict plain HTTP; with
  655. // HTTPS configured otherwise the setting would be silently ignored.
  656. if onbox || (tlsEnabled && !tlsCA) {
  657. 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)"})
  658. }
  659. default:
  660. errs.issues = append(errs.issues, issue{"NETPULSE_HTTP_MODE", "Invalid enum value. Expected 'full' | 'migrate' | 'redirect'"})
  661. }
  662. if len(errs.issues) > 0 {
  663. return nil, &errs
  664. }
  665. // ROUTERS_JSON: array de {id, name?, host, type?}; inválido → fail-fast
  666. var routers []RouterSeed
  667. if v, ok := env["ROUTERS_JSON"]; ok && v != "" {
  668. var raw []RouterSeed
  669. if err := json.Unmarshal([]byte(v), &raw); err != nil {
  670. return nil, fmt.Errorf("[netpulse] invalid ROUTERS_JSON: %w", err)
  671. }
  672. for i, r := range raw {
  673. if r.ID == "" || r.Host == "" {
  674. return nil, fmt.Errorf("[netpulse] invalid ROUTERS_JSON: entry %d requires id and host", i)
  675. }
  676. if r.Type == "" {
  677. raw[i].Type = "openwrt"
  678. } else if r.Type != "glinet" && r.Type != "openwrt" {
  679. return nil, fmt.Errorf("[netpulse] invalid ROUTERS_JSON: type must be glinet|openwrt")
  680. }
  681. }
  682. routers = raw
  683. }
  684. sshKeyPath := ""
  685. if v, ok := env["SSH_KEY_PATH"]; ok && v != "" {
  686. home, _ := os.UserHomeDir()
  687. if strings.HasPrefix(v, "~") {
  688. v = home + v[1:]
  689. }
  690. sshKeyPath = v
  691. } else {
  692. sshKeyPath = filepath.Join(dataDir, ".ssh", "id_ed25519")
  693. }
  694. return &Config{
  695. Port: port,
  696. BindAddr: bindAddr,
  697. NodeEnv: nodeEnv,
  698. StaticDir: staticDir,
  699. DataDir: dataDir,
  700. DBDir: dbDir,
  701. SessionSecret: sessionSecret,
  702. AuthUser: authUser,
  703. AuthPass: authPass,
  704. DemoMode: demoMode,
  705. MaxSSEClients: maxSSE,
  706. Routers: routers,
  707. SSHKeyPath: sshKeyPath,
  708. Adguard: adguard,
  709. Webhook: webhook,
  710. WGInterface: wgInterface,
  711. CookieSecure: cookieSecure,
  712. TrustProxy: trustProxy,
  713. MaxTsDriftSec: maxTsDriftSec,
  714. GithubRepo: githubRepo,
  715. GithubToken: githubToken,
  716. ServerRoot: serverRoot,
  717. AutoRearm: autoRearm,
  718. AutoReinstall: autoReinstall,
  719. PublicURL: publicURL,
  720. AgentURL: agentURL,
  721. BeaconListen: beaconListen,
  722. AgentAutoenroll: agentAutoenroll,
  723. AllowInsecureAgentCommands: allowInsecureAgentCommands,
  724. Onbox: onbox,
  725. GhostPortEnabled: ghostPortEnabled,
  726. MCPEnabled: mcpEnabled,
  727. RTLConsolePass: rtlPass,
  728. RTLConsolePollSec: rtlPollSec,
  729. PollIntervalSec: pollIntervalSec,
  730. DBRollbackJournal: rollbackJournal,
  731. DBTempStore: dbTempStore,
  732. TLSEnabled: tlsEnabled,
  733. TLSPort: tlsPort,
  734. TLSPortSet: tlsPortSet,
  735. TLSCert: tlsCert,
  736. TLSKey: tlsKey,
  737. TLSCA: tlsCA,
  738. TLSNames: tlsNames,
  739. HTTPMode: httpMode,
  740. }, nil
  741. }
  742. // FromEnviron construye el mapa de entorno del proceso.
  743. func FromEnviron() map[string]string {
  744. env := map[string]string{}
  745. for _, kv := range os.Environ() {
  746. if eq := strings.Index(kv, "="); eq > 0 {
  747. env[kv[:eq]] = kv[eq+1:]
  748. }
  749. }
  750. return env
  751. }