settings.go 15 KB

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