config.go 28 KB

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