settings.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. // Claves kv de la velocidad WAN contratada (#151).
  18. const (
  19. wanSpeedDownKey = "settings.wan.speed_down"
  20. wanSpeedUpKey = "settings.wan.speed_up"
  21. )
  22. // maxContractMbps es el techo de sanidad de la velocidad contratada (1 Gbps
  23. // simétrico → 100000 Mbps; por encima es casi seguro un error de entrada).
  24. const maxContractMbps = 100000.0
  25. // kvGetBool lee un flag "1"/"0" del kv. Ausente o inválido → false.
  26. func kvGetBool(db *sql.DB, key string) bool {
  27. return kvGet(db, key) == "1" || kvGet(db, key) == "true"
  28. }
  29. // kvSetBool escribe un flag "1"/"0" en el kv (UPSERT).
  30. func kvSetBool(db *sql.DB, key string, val bool) error {
  31. v := "0"
  32. if val {
  33. v = "1"
  34. }
  35. _, err := db.Exec(
  36. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  37. key, v)
  38. return err
  39. }
  40. // kvGetFloat lee un número del kv. Devuelve (valor, false) si la clave está
  41. // ausente o no es un número válido (→ "no configurado").
  42. func kvGetFloat(db *sql.DB, key string) (float64, bool) {
  43. raw := kvGet(db, key)
  44. if raw == "" {
  45. return 0, false
  46. }
  47. v, err := strconv.ParseFloat(raw, 64)
  48. if err != nil || v <= 0 {
  49. return 0, false
  50. }
  51. return v, true
  52. }
  53. // kvSetFloat escribe un número en el kv (UPSERT).
  54. func kvSetFloat(db *sql.DB, key string, val float64) error {
  55. _, err := db.Exec(
  56. `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
  57. key, strconv.FormatFloat(val, 'f', -1, 64))
  58. return err
  59. }
  60. // wanSpeedResponse es la forma JSON de GET /api/settings/wanspeed. Los campos
  61. // son punteros: null cuando la velocidad no está configurada.
  62. type wanSpeedResponse struct {
  63. DownMbps *float64 `json:"downMbps"`
  64. UpMbps *float64 `json:"upMbps"`
  65. }
  66. // validWanSpeed valida una velocidad contratada (> 0, ≤ maxContractMbps).
  67. func validWanSpeed(v float64) bool {
  68. return v > 0 && v <= maxContractMbps
  69. }
  70. // registerSettingsRoutes: GET/PUT /api/settings/orchestration (admin) y
  71. // GET/PUT /api/settings/wanspeed (admin, #151).
  72. func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
  73. mux.Handle("GET /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  74. writeJSON(w, http.StatusOK, map[string]bool{"enabled": kvGetBool(s.db.DB, orchestrationKey)})
  75. })))
  76. mux.Handle("PUT /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  77. var body struct {
  78. Enabled bool `json:"enabled"`
  79. }
  80. if st := readJSONBody(w, r, &body); st != 0 {
  81. writeBodyError(w, st, "invalid_body", "")
  82. return
  83. }
  84. if err := kvSetBool(s.db.DB, orchestrationKey, body.Enabled); err != nil {
  85. writeError(w, http.StatusInternalServerError, "kv_error")
  86. return
  87. }
  88. writeJSON(w, http.StatusOK, map[string]bool{"enabled": body.Enabled})
  89. })))
  90. // GET /api/settings/wanspeed — velocidad contratada declarada (#151).
  91. mux.Handle("GET /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  92. res := wanSpeedResponse{}
  93. if v, ok := kvGetFloat(s.db.DB, wanSpeedDownKey); ok {
  94. res.DownMbps = &v
  95. }
  96. if v, ok := kvGetFloat(s.db.DB, wanSpeedUpKey); ok {
  97. res.UpMbps = &v
  98. }
  99. writeJSON(w, http.StatusOK, res)
  100. })))
  101. // PUT /api/settings/wanspeed — guarda ambas velocidades (down y up).
  102. mux.Handle("PUT /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  103. var body wanSpeedResponse
  104. if st := readJSONBody(w, r, &body); st != 0 {
  105. writeBodyError(w, st, "invalid_body", "")
  106. return
  107. }
  108. if body.DownMbps == nil || body.UpMbps == nil {
  109. writeError(w, http.StatusBadRequest, "invalid_input", "downMbps and upMbps are required")
  110. return
  111. }
  112. if !validWanSpeed(*body.DownMbps) || !validWanSpeed(*body.UpMbps) {
  113. writeError(w, http.StatusBadRequest, "invalid_input", "velocidad contratada debe ser mayor que 0 y como máximo 100000 Mbps")
  114. return
  115. }
  116. if err := kvSetFloat(s.db.DB, wanSpeedDownKey, *body.DownMbps); err != nil {
  117. writeError(w, http.StatusInternalServerError, "kv_error")
  118. return
  119. }
  120. if err := kvSetFloat(s.db.DB, wanSpeedUpKey, *body.UpMbps); err != nil {
  121. writeError(w, http.StatusInternalServerError, "kv_error")
  122. return
  123. }
  124. writeJSON(w, http.StatusOK, wanSpeedResponse{DownMbps: body.DownMbps, UpMbps: body.UpMbps})
  125. })))
  126. s.registerKnownMacsRoutes(mux)
  127. s.registerTelegramRoutes(mux)
  128. }
  129. // knownMacItem es la forma JSON de una entrada de la allowlist (#196).
  130. type knownMacItem struct {
  131. MAC string `json:"mac"`
  132. Name string `json:"name"`
  133. Note string `json:"note,omitempty"`
  134. }
  135. // validMAC normaliza y valida una dirección MAC (AA:BB:CC:DD:EE:FF).
  136. func validMAC(raw string) (string, bool) {
  137. m := strings.ToUpper(strings.TrimSpace(raw))
  138. if len(m) != 17 {
  139. return "", false
  140. }
  141. for i := 0; i < 17; i++ {
  142. if i%3 == 2 {
  143. if m[i] != ':' {
  144. return "", false
  145. }
  146. } else if !isHex(m[i]) {
  147. return "", false
  148. }
  149. }
  150. return m, true
  151. }
  152. func isHex(c byte) bool {
  153. return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
  154. }
  155. // registerKnownMacsRoutes: GET/PUT/DELETE /api/settings/known-macs (admin,
  156. // issue #196) — allowlist de dispositivos confiables que no alertan como
  157. // "desconocido" y cuyo nombre se usa como alias.
  158. func (s *server) registerKnownMacsRoutes(mux *http.ServeMux) {
  159. // GET /api/settings/known-macs — lista completa de la allowlist.
  160. mux.Handle("GET /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  161. items, err := s.db.ListKnownMacs()
  162. if err != nil {
  163. writeError(w, http.StatusInternalServerError, "db_error")
  164. return
  165. }
  166. out := make([]knownMacItem, 0, len(items))
  167. for _, k := range items {
  168. out = append(out, knownMacItem{MAC: k.MAC, Name: k.Name, Note: k.Note})
  169. }
  170. writeJSON(w, http.StatusOK, map[string][]knownMacItem{"items": out})
  171. })))
  172. // PUT /api/settings/known-macs — alta o actualización de una MAC.
  173. mux.Handle("PUT /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  174. var body knownMacItem
  175. if st := readJSONBody(w, r, &body); st != 0 {
  176. writeBodyError(w, st, "invalid_body", "")
  177. return
  178. }
  179. mac, ok := validMAC(body.MAC)
  180. if !ok {
  181. writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
  182. return
  183. }
  184. if err := s.db.UpsertKnownMac(db.KnownMac{MAC: mac, Name: body.Name, Note: body.Note}); err != nil {
  185. writeError(w, http.StatusInternalServerError, "db_error")
  186. return
  187. }
  188. writeJSON(w, http.StatusOK, knownMacItem{MAC: mac, Name: body.Name, Note: body.Note})
  189. })))
  190. // DELETE /api/settings/known-macs/{mac} — baja de la allowlist.
  191. mux.Handle("DELETE /api/settings/known-macs/{mac}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  192. mac, ok := validMAC(r.PathValue("mac"))
  193. if !ok {
  194. writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
  195. return
  196. }
  197. if err := s.db.DeleteKnownMac(mac); err != nil {
  198. writeError(w, http.StatusInternalServerError, "db_error")
  199. return
  200. }
  201. writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
  202. })))
  203. }