settings.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. )
  15. // orchestrationKey es la clave kv que activa el menú de orquestación (#121).
  16. const orchestrationKey = "settings.orchestration_enabled"
  17. // adguardServiceKey: si el usuario monitoriza AdGuard (#813). Ausente = SÍ
  18. // (compat: instalaciones previas no tenían este flag). Ajustes > Servicios.
  19. const adguardServiceKey = "settings.services.adguard"
  20. // Claves kv de la velocidad WAN contratada (#151).
  21. const (
  22. wanSpeedDownKey = "settings.wan.speed_down"
  23. wanSpeedUpKey = "settings.wan.speed_up"
  24. )
  25. // maxContractMbps es el techo de sanidad de la velocidad contratada (1 Gbps
  26. // simétrico → 100000 Mbps; por encima es casi seguro un error de entrada).
  27. const maxContractMbps = 100000.0
  28. // kvGetBool lee un flag "1"/"0" del kv. Ausente o inválido → false.
  29. func kvGetBool(db *sql.DB, key string) bool {
  30. return kvGet(db, key) == "1" || kvGet(db, key) == "true"
  31. }
  32. // kvSetBool escribe un flag "1"/"0" en el kv (UPSERT).
  33. func kvSetBool(db *sql.DB, key string, val bool) error {
  34. v := "0"
  35. if val {
  36. v = "1"
  37. }
  38. _, err := db.Exec(
  39. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  40. key, v)
  41. return err
  42. }
  43. // kvGetDefaultOn lee un flag "1"/"0" con default TRUE cuando la clave está
  44. // ausente o vacía (a diferencia de kvGetBool, cuyo default es false). Se usa
  45. // para servicios que se monitorizan salvo que el usuario los desactive (#813).
  46. func kvGetDefaultOn(db *sql.DB, key string) bool {
  47. raw := kvGet(db, key)
  48. return raw != "0" && raw != "false"
  49. }
  50. // kvGetFloat lee un número del kv. Devuelve (valor, false) si la clave está
  51. // ausente o no es un número válido (→ "no configurado").
  52. func kvGetFloat(db *sql.DB, key string) (float64, bool) {
  53. raw := kvGet(db, key)
  54. if raw == "" {
  55. return 0, false
  56. }
  57. v, err := strconv.ParseFloat(raw, 64)
  58. if err != nil || v <= 0 {
  59. return 0, false
  60. }
  61. return v, true
  62. }
  63. // kvSetFloat escribe un número en el kv (UPSERT).
  64. func kvSetFloat(db *sql.DB, key string, val float64) error {
  65. _, err := db.Exec(
  66. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  67. key, strconv.FormatFloat(val, 'f', -1, 64))
  68. return err
  69. }
  70. // wanSpeedResponse es la forma JSON de GET /api/settings/wanspeed. Los campos
  71. // son punteros: null cuando la velocidad no está configurada.
  72. type wanSpeedResponse struct {
  73. DownMbps *float64 `json:"downMbps"`
  74. UpMbps *float64 `json:"upMbps"`
  75. }
  76. // validWanSpeed valida una velocidad contratada (> 0, ≤ maxContractMbps).
  77. func validWanSpeed(v float64) bool {
  78. return v > 0 && v <= maxContractMbps
  79. }
  80. // WanContractDown expone el plan contratado de bajada (#151) fuera del
  81. // paquete: lo usa cmd/netpulse para inyectárselo al scheduler del speedtest
  82. // (#511) sin duplicar la clave kv.
  83. func WanContractDown(handle *sql.DB) (float64, bool) {
  84. return kvGetFloat(handle, wanSpeedDownKey)
  85. }
  86. // registerSettingsRoutes: GET/PUT /api/settings/orchestration (admin) y
  87. // GET/PUT /api/settings/wanspeed (admin, #151).
  88. func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
  89. mux.Handle("GET /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  90. writeJSON(w, http.StatusOK, map[string]bool{"enabled": kvGetBool(s.db.DB, orchestrationKey)})
  91. })))
  92. mux.Handle("PUT /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  93. var body struct {
  94. Enabled bool `json:"enabled"`
  95. }
  96. if st := readJSONBody(w, r, &body); st != 0 {
  97. writeBodyError(w, st, "invalid_body", "")
  98. return
  99. }
  100. if err := kvSetBool(s.db.DB, orchestrationKey, body.Enabled); err != nil {
  101. writeError(w, http.StatusInternalServerError, "kv_error")
  102. return
  103. }
  104. writeJSON(w, http.StatusOK, map[string]bool{"enabled": body.Enabled})
  105. })))
  106. // GET /api/settings/services — servicios monitorizados (#813). Ausente = activo.
  107. mux.Handle("GET /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  108. writeJSON(w, http.StatusOK, map[string]bool{"adguard": kvGetDefaultOn(s.db.DB, adguardServiceKey)})
  109. })))
  110. // PUT /api/settings/services — activa/desactiva AdGuard. Desactivado: el
  111. // poller deja de sondearlo y la salud no aplica la penalización (#813).
  112. mux.Handle("PUT /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  113. var body struct {
  114. Adguard *bool `json:"adguard"`
  115. }
  116. if st := readJSONBody(w, r, &body); st != 0 {
  117. writeBodyError(w, st, "invalid_body", "")
  118. return
  119. }
  120. if body.Adguard == nil {
  121. writeError(w, http.StatusBadRequest, "invalid_input", "adguard is required")
  122. return
  123. }
  124. if err := kvSetBool(s.db.DB, adguardServiceKey, *body.Adguard); err != nil {
  125. writeError(w, http.StatusInternalServerError, "kv_error")
  126. return
  127. }
  128. if s.pollNow != nil {
  129. s.pollNow()
  130. }
  131. writeJSON(w, http.StatusOK, map[string]bool{"adguard": *body.Adguard})
  132. })))
  133. // GET /api/settings/wanspeed — velocidad contratada declarada (#151).
  134. mux.Handle("GET /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  135. res := wanSpeedResponse{}
  136. if v, ok := kvGetFloat(s.db.DB, wanSpeedDownKey); ok {
  137. res.DownMbps = &v
  138. }
  139. if v, ok := kvGetFloat(s.db.DB, wanSpeedUpKey); ok {
  140. res.UpMbps = &v
  141. }
  142. writeJSON(w, http.StatusOK, res)
  143. })))
  144. // PUT /api/settings/wanspeed — guarda ambas velocidades (down y up).
  145. mux.Handle("PUT /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  146. var body wanSpeedResponse
  147. if st := readJSONBody(w, r, &body); st != 0 {
  148. writeBodyError(w, st, "invalid_body", "")
  149. return
  150. }
  151. if body.DownMbps == nil || body.UpMbps == nil {
  152. writeError(w, http.StatusBadRequest, "invalid_input", "downMbps and upMbps are required")
  153. return
  154. }
  155. if !validWanSpeed(*body.DownMbps) || !validWanSpeed(*body.UpMbps) {
  156. writeError(w, http.StatusBadRequest, "invalid_input", "velocidad contratada debe ser mayor que 0 y como máximo 100000 Mbps")
  157. return
  158. }
  159. if err := kvSetFloat(s.db.DB, wanSpeedDownKey, *body.DownMbps); err != nil {
  160. writeError(w, http.StatusInternalServerError, "kv_error")
  161. return
  162. }
  163. if err := kvSetFloat(s.db.DB, wanSpeedUpKey, *body.UpMbps); err != nil {
  164. writeError(w, http.StatusInternalServerError, "kv_error")
  165. return
  166. }
  167. writeJSON(w, http.StatusOK, wanSpeedResponse{DownMbps: body.DownMbps, UpMbps: body.UpMbps})
  168. })))
  169. s.registerKnownMacsRoutes(mux)
  170. s.registerTelegramRoutes(mux)
  171. s.registerNtfyRoutes(mux)
  172. s.registerAlertsLangRoutes(mux)
  173. }
  174. // knownMacItem es la forma JSON de una entrada de la allowlist (#196).
  175. type knownMacItem struct {
  176. MAC string `json:"mac"`
  177. Name string `json:"name"`
  178. Note string `json:"note,omitempty"`
  179. }
  180. // validMAC normaliza y valida una dirección MAC (AA:BB:CC:DD:EE:FF).
  181. func validMAC(raw string) (string, bool) {
  182. m := strings.ToUpper(strings.TrimSpace(raw))
  183. if len(m) != 17 {
  184. return "", false
  185. }
  186. for i := 0; i < 17; i++ {
  187. if i%3 == 2 {
  188. if m[i] != ':' {
  189. return "", false
  190. }
  191. } else if !isHex(m[i]) {
  192. return "", false
  193. }
  194. }
  195. return m, true
  196. }
  197. func isHex(c byte) bool {
  198. return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
  199. }
  200. // registerKnownMacsRoutes: GET/PUT/DELETE /api/settings/known-macs (admin,
  201. // issue #196) — allowlist de dispositivos confiables que no alertan como
  202. // "desconocido" y cuyo nombre se usa como alias.
  203. func (s *server) registerKnownMacsRoutes(mux *http.ServeMux) {
  204. // GET /api/settings/known-macs — lista completa de la allowlist.
  205. mux.Handle("GET /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  206. items, err := s.db.ListKnownMacs()
  207. if err != nil {
  208. writeError(w, http.StatusInternalServerError, "db_error")
  209. return
  210. }
  211. out := make([]knownMacItem, 0, len(items))
  212. for _, k := range items {
  213. out = append(out, knownMacItem{MAC: k.MAC, Name: k.Name, Note: k.Note})
  214. }
  215. writeJSON(w, http.StatusOK, map[string][]knownMacItem{"items": out})
  216. })))
  217. // PUT /api/settings/known-macs — alta o actualización de una MAC.
  218. mux.Handle("PUT /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  219. var body knownMacItem
  220. if st := readJSONBody(w, r, &body); st != 0 {
  221. writeBodyError(w, st, "invalid_body", "")
  222. return
  223. }
  224. mac, ok := validMAC(body.MAC)
  225. if !ok {
  226. writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
  227. return
  228. }
  229. if err := s.db.UpsertKnownMac(db.KnownMac{MAC: mac, Name: body.Name, Note: body.Note}); err != nil {
  230. writeError(w, http.StatusInternalServerError, "db_error")
  231. return
  232. }
  233. writeJSON(w, http.StatusOK, knownMacItem{MAC: mac, Name: body.Name, Note: body.Note})
  234. })))
  235. // DELETE /api/settings/known-macs/{mac} — baja de la allowlist.
  236. mux.Handle("DELETE /api/settings/known-macs/{mac}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  237. mac, ok := validMAC(r.PathValue("mac"))
  238. if !ok {
  239. writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
  240. return
  241. }
  242. if err := s.db.DeleteKnownMac(mac); err != nil {
  243. writeError(w, http.StatusInternalServerError, "db_error")
  244. return
  245. }
  246. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  247. })))
  248. }