settings.go 15 KB

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