config.go 29 KB

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