settings.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // settings.go — ajustes globales persistidos en kv (issue #121).
  2. //
  3. // Por ahora el flag de orquestación y la velocidad WAN contratada (issue
  4. // #151): el menú de orquestación (escritura en routers) está oculto por
  5. // defecto y se muestra solo si el admin lo activa.
  6. package httpapi
  7. import (
  8. "database/sql"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "github.com/gnacho/netpulse/agent/macaddr"
  13. "github.com/gnacho/netpulse/server-go/internal/adapters"
  14. "github.com/gnacho/netpulse/server-go/internal/auth"
  15. "github.com/gnacho/netpulse/server-go/internal/db"
  16. "github.com/gnacho/netpulse/server-go/internal/mqttpub"
  17. )
  18. // orchestrationKey es la clave kv que activa el menú de orquestación (#121).
  19. const orchestrationKey = "settings.orchestration_enabled"
  20. // integrationKeys: claves kv de los toggles de integraciones server-side
  21. // (#968). Ausente = activo (compat: instalaciones previas no tenían el flag).
  22. // MQTT no tiene clave propia aquí: reutiliza mqtt.enabled (#838).
  23. const (
  24. integrationNtfyKey = "settings.integrations.ntfy"
  25. integrationTelegramKey = "settings.integrations.telegram"
  26. integrationProxmoxKey = "settings.integrations.proxmox"
  27. // integrationMCPKey: toggle del endpoint /mcp (#1114). El endpoint solo
  28. // EXISTE si el env NETPULSE_MCP_ENABLED=1 (opt-in duro del despliegue);
  29. // esta clave (default activa) permite apagarlo desde Ajustes sin reinicio.
  30. integrationMCPKey = "settings.integrations.mcp"
  31. // integrationExternalAgentsKey: toggle de la fila Agentes externos
  32. // (#1782). Ausente = activo, como el resto de toggles del grupo.
  33. integrationExternalAgentsKey = "settings.integrations.external_agents"
  34. )
  35. // adguardServiceKey: si el usuario monitoriza AdGuard (#813). Ausente = SÍ
  36. // (compat: instalaciones previas no tenían este flag). Ajustes > Servicios.
  37. const adguardServiceKey = "settings.services.adguard"
  38. // Claves kv de la velocidad WAN contratada (#151).
  39. const (
  40. wanSpeedDownKey = "settings.wan.speed_down"
  41. wanSpeedUpKey = "settings.wan.speed_up"
  42. )
  43. // maxContractMbps es el techo de sanidad de la velocidad contratada (1 Gbps
  44. // simétrico → 100000 Mbps; por encima es casi seguro un error de entrada).
  45. const maxContractMbps = 100000.0
  46. // kvGetBool lee un flag "1"/"0" del kv. Ausente o inválido → false.
  47. func kvGetBool(db *sql.DB, key string) bool {
  48. return kvGet(db, key) == "1" || kvGet(db, key) == "true"
  49. }
  50. // kvSetBool escribe un flag "1"/"0" en el kv (UPSERT).
  51. func kvSetBool(db *sql.DB, key string, val bool) error {
  52. v := "0"
  53. if val {
  54. v = "1"
  55. }
  56. _, err := db.Exec(
  57. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  58. key, v)
  59. return err
  60. }
  61. // kvSetStr escribe una cadena en el kv (UPSERT).
  62. func kvSetStr(db *sql.DB, key, val string) error {
  63. _, err := db.Exec(
  64. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  65. key, val)
  66. return err
  67. }
  68. // kvGetDefaultOn lee un flag "1"/"0" con default TRUE cuando la clave está
  69. // ausente o vacía (a diferencia de kvGetBool, cuyo default es false). Se usa
  70. // para servicios que se monitorizan salvo que el usuario los desactive (#813).
  71. func kvGetDefaultOn(db *sql.DB, key string) bool {
  72. raw := kvGet(db, key)
  73. return raw != "0" && raw != "false"
  74. }
  75. // kvGetFloat lee un número del kv. Devuelve (valor, false) si la clave está
  76. // ausente o no es un número válido (→ "no configurado").
  77. func kvGetFloat(db *sql.DB, key string) (float64, bool) {
  78. raw := kvGet(db, key)
  79. if raw == "" {
  80. return 0, false
  81. }
  82. v, err := strconv.ParseFloat(raw, 64)
  83. if err != nil || v <= 0 {
  84. return 0, false
  85. }
  86. return v, true
  87. }
  88. // kvSetFloat escribe un número en el kv (UPSERT).
  89. func kvSetString(db *sql.DB, key, val string) error {
  90. _, err := db.Exec(
  91. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  92. key, val)
  93. return err
  94. }
  95. func kvSetFloat(db *sql.DB, key string, val float64) error {
  96. _, err := db.Exec(
  97. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  98. key, strconv.FormatFloat(val, 'f', -1, 64))
  99. return err
  100. }
  101. // wanSpeedResponse es la forma JSON de GET /api/settings/wanspeed. Los campos
  102. // son punteros: null cuando la velocidad no está configurada.
  103. type wanSpeedResponse struct {
  104. DownMbps *float64 `json:"downMbps"`
  105. UpMbps *float64 `json:"upMbps"`
  106. }
  107. // validWanSpeed valida una velocidad contratada (> 0, ≤ maxContractMbps).
  108. func validWanSpeed(v float64) bool {
  109. return v > 0 && v <= maxContractMbps
  110. }
  111. // WanContractDown expone el plan contratado de bajada (#151) fuera del
  112. // paquete: lo usa cmd/netpulse para inyectárselo al scheduler del speedtest
  113. // (#511) sin duplicar la clave kv.
  114. func WanContractDown(handle *sql.DB) (float64, bool) {
  115. return kvGetFloat(handle, wanSpeedDownKey)
  116. }
  117. // registerSettingsRoutes: GET/PUT /api/settings/orchestration (admin) y
  118. // GET/PUT /api/settings/wanspeed (admin, #151).
  119. func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
  120. mux.Handle("GET /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  121. writeJSON(w, http.StatusOK, map[string]bool{"enabled": kvGetBool(s.db.DB, orchestrationKey)})
  122. })))
  123. mux.Handle("PUT /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  124. var body struct {
  125. Enabled bool `json:"enabled"`
  126. }
  127. if st := readJSONBody(w, r, &body); st != 0 {
  128. writeBodyError(w, st, "invalid_body", "")
  129. return
  130. }
  131. if err := kvSetBool(s.db.DB, orchestrationKey, body.Enabled); err != nil {
  132. writeError(w, http.StatusInternalServerError, "kv_error")
  133. return
  134. }
  135. writeJSON(w, http.StatusOK, map[string]bool{"enabled": body.Enabled})
  136. })))
  137. // GET /api/settings/integrations - toggles server-side de integraciones
  138. // (#968): ntfy/telegram/proxmox (ausente = activo) y mqtt (lee la clave
  139. // existente mqtt.enabled via el manager, que ya fusiona env + kv).
  140. // GET/PUT /api/settings/nameorder - preferencia global de fuentes de
  141. // nombre de cliente (#2163). Lista vacia = precedencia automatica.
  142. mux.Handle("GET /api/settings/nameorder", auth.RequireAdmin(http.HandlerFunc(s.handleSettingsNameOrderGet)))
  143. mux.Handle("PUT /api/settings/nameorder", auth.RequireAdmin(http.HandlerFunc(s.handleSettingsNameOrderPut)))
  144. mux.Handle("GET /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  145. writeJSON(w, http.StatusOK, s.integrationsView())
  146. })))
  147. // PUT /api/settings/integrations - parche parcial: SOLO se escriben las
  148. // claves presentes en el body (un toggle no pisa el resto). Los gates
  149. // leen la kv por evento, así que el cambio aplica sin reiniciar.
  150. mux.Handle("PUT /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  151. var body struct {
  152. Ntfy *bool `json:"ntfy"`
  153. Telegram *bool `json:"telegram"`
  154. Proxmox *bool `json:"proxmox"`
  155. MQTT *bool `json:"mqtt"`
  156. MCP *bool `json:"mcp"`
  157. ExternalAgents *bool `json:"externalAgents"`
  158. }
  159. if st := readJSONBody(w, r, &body); st != 0 {
  160. writeBodyError(w, st, "invalid_body", "")
  161. return
  162. }
  163. if body.Ntfy == nil && body.Telegram == nil && body.Proxmox == nil && body.MQTT == nil && body.MCP == nil && body.ExternalAgents == nil {
  164. writeError(w, http.StatusBadRequest, "invalid_input", "at least one integration key is required")
  165. return
  166. }
  167. for _, p := range []struct {
  168. flag *bool
  169. key string
  170. // channelKey: clave "enabled" propia del canal (ntfy.enabled,
  171. // telegram.enabled). El toggle de la fila es la ÚNICA fuente de
  172. // verdad (#1016/#1017): se espeja aquí para que el path de envío
  173. // (que lee la clave del canal) y el integrationGate nunca desincronicen.
  174. channelKey string
  175. }{
  176. {body.Ntfy, integrationNtfyKey, "ntfy.enabled"},
  177. {body.Telegram, integrationTelegramKey, "telegram.enabled"},
  178. {body.Proxmox, integrationProxmoxKey, ""},
  179. {body.MCP, integrationMCPKey, ""},
  180. {body.ExternalAgents, integrationExternalAgentsKey, ""},
  181. } {
  182. if p.flag == nil {
  183. continue
  184. }
  185. // Formato "true"/"false" (como mqtt.enabled): los gates de
  186. // main.go y del adapter leen "false" literal.
  187. if err := kvSetStr(s.db.DB, p.key, strconv.FormatBool(*p.flag)); err != nil {
  188. writeError(w, http.StatusInternalServerError, "kv_error")
  189. return
  190. }
  191. if p.channelKey != "" {
  192. if err := kvSetStr(s.db.DB, p.channelKey, strconv.FormatBool(*p.flag)); err != nil {
  193. writeError(w, http.StatusInternalServerError, "kv_error")
  194. return
  195. }
  196. }
  197. }
  198. if body.MQTT != nil {
  199. if err := s.setMQTTEnabled(*body.MQTT); err != nil {
  200. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  201. return
  202. }
  203. }
  204. writeJSON(w, http.StatusOK, s.integrationsView())
  205. })))
  206. // GET /api/settings/services — servicios monitorizados (#813). Ausente = activo.
  207. mux.Handle("GET /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  208. writeJSON(w, http.StatusOK, map[string]bool{"adguard": kvGetDefaultOn(s.db.DB, adguardServiceKey)})
  209. })))
  210. // PUT /api/settings/services — activa/desactiva AdGuard. Desactivado: el
  211. // poller deja de sondearlo y la salud no aplica la penalización (#813).
  212. mux.Handle("PUT /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  213. var body struct {
  214. Adguard *bool `json:"adguard"`
  215. }
  216. if st := readJSONBody(w, r, &body); st != 0 {
  217. writeBodyError(w, st, "invalid_body", "")
  218. return
  219. }
  220. if body.Adguard == nil {
  221. writeError(w, http.StatusBadRequest, "invalid_input", "adguard is required")
  222. return
  223. }
  224. if err := kvSetBool(s.db.DB, adguardServiceKey, *body.Adguard); err != nil {
  225. writeError(w, http.StatusInternalServerError, "kv_error")
  226. return
  227. }
  228. if s.pollNow != nil {
  229. s.pollNow()
  230. }
  231. writeJSON(w, http.StatusOK, map[string]bool{"adguard": *body.Adguard})
  232. })))
  233. // GET /api/settings/wanspeed — velocidad contratada declarada (#151).
  234. mux.Handle("GET /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  235. res := wanSpeedResponse{}
  236. if v, ok := kvGetFloat(s.db.DB, wanSpeedDownKey); ok {
  237. res.DownMbps = &v
  238. }
  239. if v, ok := kvGetFloat(s.db.DB, wanSpeedUpKey); ok {
  240. res.UpMbps = &v
  241. }
  242. writeJSON(w, http.StatusOK, res)
  243. })))
  244. // PUT /api/settings/wanspeed — guarda ambas velocidades (down y up).
  245. mux.Handle("PUT /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  246. var body wanSpeedResponse
  247. if st := readJSONBody(w, r, &body); st != 0 {
  248. writeBodyError(w, st, "invalid_body", "")
  249. return
  250. }
  251. if body.DownMbps == nil || body.UpMbps == nil {
  252. writeError(w, http.StatusBadRequest, "invalid_input", "downMbps and upMbps are required")
  253. return
  254. }
  255. if !validWanSpeed(*body.DownMbps) || !validWanSpeed(*body.UpMbps) {
  256. writeError(w, http.StatusBadRequest, "invalid_input", "velocidad contratada debe ser mayor que 0 y como máximo 100000 Mbps")
  257. return
  258. }
  259. if err := kvSetFloat(s.db.DB, wanSpeedDownKey, *body.DownMbps); err != nil {
  260. writeError(w, http.StatusInternalServerError, "kv_error")
  261. return
  262. }
  263. if err := kvSetFloat(s.db.DB, wanSpeedUpKey, *body.UpMbps); err != nil {
  264. writeError(w, http.StatusInternalServerError, "kv_error")
  265. return
  266. }
  267. writeJSON(w, http.StatusOK, wanSpeedResponse{DownMbps: body.DownMbps, UpMbps: body.UpMbps})
  268. })))
  269. s.registerKnownMacsRoutes(mux)
  270. s.registerTelegramRoutes(mux)
  271. s.registerNtfyRoutes(mux)
  272. s.registerAlertsLangRoutes(mux)
  273. s.registerRoamingSettingsRoutes(mux)
  274. s.registerThresholdsRoutes(mux)
  275. }
  276. // integrationsView: estado efectivo de los toggles server-side (#968).
  277. // Ausente = activo para ntfy/telegram/proxmox; MQTT refleja la config
  278. // efectiva del manager (env + kv). MCP (#1114): false con mcpLocked=true
  279. // cuando el despliegue no lo habilitó por env (el endpoint no existe).
  280. func (s *server) integrationsView() map[string]any {
  281. mqtt := kvGet(s.db.DB, "mqtt.enabled") == "true"
  282. if s.mqtt != nil {
  283. mqtt = s.mqtt.Config().Enabled
  284. }
  285. return map[string]any{
  286. "ntfy": kvGetDefaultOn(s.db.DB, integrationNtfyKey),
  287. "telegram": kvGetDefaultOn(s.db.DB, integrationTelegramKey),
  288. "proxmox": kvGetDefaultOn(s.db.DB, integrationProxmoxKey),
  289. "externalAgents": kvGetDefaultOn(s.db.DB, integrationExternalAgentsKey),
  290. "mqtt": mqtt,
  291. "mcp": s.mcpMounted() && kvGetDefaultOn(s.db.DB, integrationMCPKey),
  292. "mcpLocked": !s.mcpMounted(),
  293. }
  294. }
  295. // mcpMounted: el endpoint /mcp existe en este proceso (opt-in duro por env,
  296. // #1114). El toggle de integración solo puede apagarlo, nunca montarlo.
  297. func (s *server) mcpMounted() bool {
  298. return s.cfg != nil && s.cfg.MCPEnabled && s.mcp != nil
  299. }
  300. // setMQTTEnabled cambia SOLO el flag enabled del publisher MQTT (#968): carga
  301. // la config efectiva, conmuta y reaplica (sin tocar host/credenciales). Sin
  302. // manager (tests) cae a escribir la clave kv directamente.
  303. func (s *server) setMQTTEnabled(enabled bool) error {
  304. if s.mqtt == nil {
  305. return kvSetStr(s.db.DB, "mqtt.enabled", strconv.FormatBool(enabled))
  306. }
  307. cfg := s.mqtt.Config()
  308. cfg.Enabled = enabled
  309. if err := mqttpub.SaveConfig(&dbKVAdapter{db: s.db.DB}, cfg); err != nil {
  310. return err
  311. }
  312. s.mqtt.Apply(cfg)
  313. return nil
  314. }
  315. // knownMacItem es la forma JSON de una entrada de la allowlist (#196).
  316. type knownMacItem struct {
  317. MAC string `json:"mac"`
  318. Name string `json:"name"`
  319. Note string `json:"note,omitempty"`
  320. }
  321. // validMAC normaliza y valida una dirección MAC a su forma canónica
  322. // (AA:BB:CC:DD:EE:FF). Acepta ':' o '-' como separador y 12 hex sin separador.
  323. func validMAC(raw string) (string, bool) {
  324. m := macaddr.Normalize(raw)
  325. return m, m != ""
  326. }
  327. // registerKnownMacsRoutes: GET/PUT/DELETE /api/settings/known-macs (admin,
  328. // issue #196) — allowlist de dispositivos confiables que no alertan como
  329. // "desconocido" y cuyo nombre se usa como alias.
  330. func (s *server) registerKnownMacsRoutes(mux *http.ServeMux) {
  331. // GET /api/settings/known-macs — lista completa de la allowlist.
  332. mux.Handle("GET /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  333. items, err := s.db.ListKnownMacs()
  334. if err != nil {
  335. writeError(w, http.StatusInternalServerError, "db_error")
  336. return
  337. }
  338. out := make([]knownMacItem, 0, len(items))
  339. for _, k := range items {
  340. out = append(out, knownMacItem{MAC: k.MAC, Name: k.Name, Note: k.Note})
  341. }
  342. writeJSON(w, http.StatusOK, map[string][]knownMacItem{"items": out})
  343. })))
  344. // PUT /api/settings/known-macs — alta o actualización de una MAC.
  345. mux.Handle("PUT /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  346. var body knownMacItem
  347. if st := readJSONBody(w, r, &body); st != 0 {
  348. writeBodyError(w, st, "invalid_body", "")
  349. return
  350. }
  351. mac, ok := validMAC(body.MAC)
  352. if !ok {
  353. writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
  354. return
  355. }
  356. if err := s.db.UpsertKnownMac(db.KnownMac{MAC: mac, Name: body.Name, Note: body.Note}); err != nil {
  357. writeError(w, http.StatusInternalServerError, "db_error")
  358. return
  359. }
  360. // #1278: re-alta manual quita la lápida (en el camino de éxito: en el
  361. // de error no se registró nada y la lápida debe quedarse).
  362. _ = s.db.DeleteDeletedClient(mac)
  363. writeJSON(w, http.StatusOK, knownMacItem{MAC: mac, Name: body.Name, Note: body.Note})
  364. })))
  365. // DELETE /api/settings/known-macs/{mac} — baja de la allowlist.
  366. mux.Handle("DELETE /api/settings/known-macs/{mac}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  367. mac, ok := validMAC(r.PathValue("mac"))
  368. if !ok {
  369. writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
  370. return
  371. }
  372. if err := s.db.DeleteKnownMac(mac); err != nil {
  373. writeError(w, http.StatusInternalServerError, "db_error")
  374. return
  375. }
  376. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  377. })))
  378. }
  379. // handleSettingsNameOrderGet devuelve la preferencia global de fuentes de
  380. // nombre (#2163). Lista vacía = precedencia automática del servidor.
  381. func (s *server) handleSettingsNameOrderGet(w http.ResponseWriter, _ *http.Request) {
  382. // Siempre un array: null obligaria al cliente a distinguir dos vacios.
  383. sources := adapters.PreferredNameSources(kvGet(s.db.DB, adapters.NameOrderKey))
  384. if sources == nil {
  385. sources = []string{}
  386. }
  387. writeJSON(w, http.StatusOK, map[string]any{"sources": sources})
  388. }
  389. // handleSettingsNameOrderPut guarda la preferencia global. Solo admite las
  390. // fuentes reordenables: el nombre manual y el alias de una MAC conocida son
  391. // nombres escritos por el usuario y mandan siempre.
  392. func (s *server) handleSettingsNameOrderPut(w http.ResponseWriter, r *http.Request) {
  393. var body struct {
  394. Sources []string `json:"sources"`
  395. }
  396. if st := readJSONBody(w, r, &body); st != 0 {
  397. writeBodyError(w, st, "invalid_body", "")
  398. return
  399. }
  400. allowed := map[string]bool{}
  401. for _, src := range adapters.ReorderableNameSources {
  402. allowed[src] = true
  403. }
  404. seen := map[string]bool{}
  405. for _, src := range body.Sources {
  406. if !allowed[src] || seen[src] {
  407. writeError(w, http.StatusBadRequest, "invalid_name_source")
  408. return
  409. }
  410. seen[src] = true
  411. }
  412. if err := kvSetString(s.db.DB, adapters.NameOrderKey, strings.Join(body.Sources, ",")); err != nil {
  413. writeError(w, http.StatusInternalServerError, "kv_error")
  414. return
  415. }
  416. // Un sondeo inmediato para que el orden se vea en la siguiente vista.
  417. if s.pollNow != nil {
  418. s.pollNow()
  419. }
  420. sources := adapters.PreferredNameSources(strings.Join(body.Sources, ","))
  421. if sources == nil {
  422. sources = []string{}
  423. }
  424. writeJSON(w, http.StatusOK, map[string]any{"sources": sources})
  425. }