settings.go 14 KB

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