| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405 |
- // settings.go — ajustes globales persistidos en kv (issue #121).
- //
- // Por ahora el flag de orquestación y la velocidad WAN contratada (issue
- // #151): el menú de orquestación (escritura en routers) está oculto por
- // defecto y se muestra solo si el admin lo activa.
- package httpapi
- import (
- "database/sql"
- "net/http"
- "strconv"
- "strings"
- "github.com/gnacho/netpulse/server-go/internal/auth"
- "github.com/gnacho/netpulse/server-go/internal/db"
- "github.com/gnacho/netpulse/server-go/internal/mqttpub"
- )
- // orchestrationKey es la clave kv que activa el menú de orquestación (#121).
- const orchestrationKey = "settings.orchestration_enabled"
- // integrationKeys: claves kv de los toggles de integraciones server-side
- // (#968). Ausente = activo (compat: instalaciones previas no tenían el flag).
- // MQTT no tiene clave propia aquí: reutiliza mqtt.enabled (#838).
- const (
- integrationNtfyKey = "settings.integrations.ntfy"
- integrationTelegramKey = "settings.integrations.telegram"
- integrationProxmoxKey = "settings.integrations.proxmox"
- // integrationMCPKey: toggle del endpoint /mcp (#1114). El endpoint solo
- // EXISTE si el env NETPULSE_MCP_ENABLED=1 (opt-in duro del despliegue);
- // esta clave (default activa) permite apagarlo desde Ajustes sin reinicio.
- integrationMCPKey = "settings.integrations.mcp"
- )
- // adguardServiceKey: si el usuario monitoriza AdGuard (#813). Ausente = SÍ
- // (compat: instalaciones previas no tenían este flag). Ajustes > Servicios.
- const adguardServiceKey = "settings.services.adguard"
- // Claves kv de la velocidad WAN contratada (#151).
- const (
- wanSpeedDownKey = "settings.wan.speed_down"
- wanSpeedUpKey = "settings.wan.speed_up"
- )
- // maxContractMbps es el techo de sanidad de la velocidad contratada (1 Gbps
- // simétrico → 100000 Mbps; por encima es casi seguro un error de entrada).
- const maxContractMbps = 100000.0
- // kvGetBool lee un flag "1"/"0" del kv. Ausente o inválido → false.
- func kvGetBool(db *sql.DB, key string) bool {
- return kvGet(db, key) == "1" || kvGet(db, key) == "true"
- }
- // kvSetBool escribe un flag "1"/"0" en el kv (UPSERT).
- func kvSetBool(db *sql.DB, key string, val bool) error {
- v := "0"
- if val {
- v = "1"
- }
- _, err := db.Exec(
- `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
- key, v)
- return err
- }
- // kvSetStr escribe una cadena en el kv (UPSERT).
- func kvSetStr(db *sql.DB, key, val string) error {
- _, err := db.Exec(
- `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
- key, val)
- return err
- }
- // kvGetDefaultOn lee un flag "1"/"0" con default TRUE cuando la clave está
- // ausente o vacía (a diferencia de kvGetBool, cuyo default es false). Se usa
- // para servicios que se monitorizan salvo que el usuario los desactive (#813).
- func kvGetDefaultOn(db *sql.DB, key string) bool {
- raw := kvGet(db, key)
- return raw != "0" && raw != "false"
- }
- // kvGetFloat lee un número del kv. Devuelve (valor, false) si la clave está
- // ausente o no es un número válido (→ "no configurado").
- func kvGetFloat(db *sql.DB, key string) (float64, bool) {
- raw := kvGet(db, key)
- if raw == "" {
- return 0, false
- }
- v, err := strconv.ParseFloat(raw, 64)
- if err != nil || v <= 0 {
- return 0, false
- }
- return v, true
- }
- // kvSetFloat escribe un número en el kv (UPSERT).
- func kvSetFloat(db *sql.DB, key string, val float64) error {
- _, err := db.Exec(
- `INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
- key, strconv.FormatFloat(val, 'f', -1, 64))
- return err
- }
- // wanSpeedResponse es la forma JSON de GET /api/settings/wanspeed. Los campos
- // son punteros: null cuando la velocidad no está configurada.
- type wanSpeedResponse struct {
- DownMbps *float64 `json:"downMbps"`
- UpMbps *float64 `json:"upMbps"`
- }
- // validWanSpeed valida una velocidad contratada (> 0, ≤ maxContractMbps).
- func validWanSpeed(v float64) bool {
- return v > 0 && v <= maxContractMbps
- }
- // WanContractDown expone el plan contratado de bajada (#151) fuera del
- // paquete: lo usa cmd/netpulse para inyectárselo al scheduler del speedtest
- // (#511) sin duplicar la clave kv.
- func WanContractDown(handle *sql.DB) (float64, bool) {
- return kvGetFloat(handle, wanSpeedDownKey)
- }
- // registerSettingsRoutes: GET/PUT /api/settings/orchestration (admin) y
- // GET/PUT /api/settings/wanspeed (admin, #151).
- func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
- mux.Handle("GET /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- writeJSON(w, http.StatusOK, map[string]bool{"enabled": kvGetBool(s.db.DB, orchestrationKey)})
- })))
- mux.Handle("PUT /api/settings/orchestration", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var body struct {
- Enabled bool `json:"enabled"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "")
- return
- }
- if err := kvSetBool(s.db.DB, orchestrationKey, body.Enabled); err != nil {
- writeError(w, http.StatusInternalServerError, "kv_error")
- return
- }
- writeJSON(w, http.StatusOK, map[string]bool{"enabled": body.Enabled})
- })))
- // GET /api/settings/integrations - toggles server-side de integraciones
- // (#968): ntfy/telegram/proxmox (ausente = activo) y mqtt (lee la clave
- // existente mqtt.enabled via el manager, que ya fusiona env + kv).
- mux.Handle("GET /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- writeJSON(w, http.StatusOK, s.integrationsView())
- })))
- // PUT /api/settings/integrations - parche parcial: SOLO se escriben las
- // claves presentes en el body (un toggle no pisa el resto). Los gates
- // leen la kv por evento, así que el cambio aplica sin reiniciar.
- mux.Handle("PUT /api/settings/integrations", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var body struct {
- Ntfy *bool `json:"ntfy"`
- Telegram *bool `json:"telegram"`
- Proxmox *bool `json:"proxmox"`
- MQTT *bool `json:"mqtt"`
- MCP *bool `json:"mcp"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "")
- return
- }
- if body.Ntfy == nil && body.Telegram == nil && body.Proxmox == nil && body.MQTT == nil && body.MCP == nil {
- writeError(w, http.StatusBadRequest, "invalid_input", "at least one integration key is required")
- return
- }
- for _, p := range []struct {
- flag *bool
- key string
- // channelKey: clave "enabled" propia del canal (ntfy.enabled,
- // telegram.enabled). El toggle de la fila es la ÚNICA fuente de
- // verdad (#1016/#1017): se espeja aquí para que el path de envío
- // (que lee la clave del canal) y el integrationGate nunca desincronicen.
- channelKey string
- }{
- {body.Ntfy, integrationNtfyKey, "ntfy.enabled"},
- {body.Telegram, integrationTelegramKey, "telegram.enabled"},
- {body.Proxmox, integrationProxmoxKey, ""},
- {body.MCP, integrationMCPKey, ""},
- } {
- if p.flag == nil {
- continue
- }
- // Formato "true"/"false" (como mqtt.enabled): los gates de
- // main.go y del adapter leen "false" literal.
- if err := kvSetStr(s.db.DB, p.key, strconv.FormatBool(*p.flag)); err != nil {
- writeError(w, http.StatusInternalServerError, "kv_error")
- return
- }
- if p.channelKey != "" {
- if err := kvSetStr(s.db.DB, p.channelKey, strconv.FormatBool(*p.flag)); err != nil {
- writeError(w, http.StatusInternalServerError, "kv_error")
- return
- }
- }
- }
- if body.MQTT != nil {
- if err := s.setMQTTEnabled(*body.MQTT); err != nil {
- writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
- return
- }
- }
- writeJSON(w, http.StatusOK, s.integrationsView())
- })))
- // GET /api/settings/services — servicios monitorizados (#813). Ausente = activo.
- mux.Handle("GET /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- writeJSON(w, http.StatusOK, map[string]bool{"adguard": kvGetDefaultOn(s.db.DB, adguardServiceKey)})
- })))
- // PUT /api/settings/services — activa/desactiva AdGuard. Desactivado: el
- // poller deja de sondearlo y la salud no aplica la penalización (#813).
- mux.Handle("PUT /api/settings/services", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var body struct {
- Adguard *bool `json:"adguard"`
- }
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "")
- return
- }
- if body.Adguard == nil {
- writeError(w, http.StatusBadRequest, "invalid_input", "adguard is required")
- return
- }
- if err := kvSetBool(s.db.DB, adguardServiceKey, *body.Adguard); err != nil {
- writeError(w, http.StatusInternalServerError, "kv_error")
- return
- }
- if s.pollNow != nil {
- s.pollNow()
- }
- writeJSON(w, http.StatusOK, map[string]bool{"adguard": *body.Adguard})
- })))
- // GET /api/settings/wanspeed — velocidad contratada declarada (#151).
- mux.Handle("GET /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- res := wanSpeedResponse{}
- if v, ok := kvGetFloat(s.db.DB, wanSpeedDownKey); ok {
- res.DownMbps = &v
- }
- if v, ok := kvGetFloat(s.db.DB, wanSpeedUpKey); ok {
- res.UpMbps = &v
- }
- writeJSON(w, http.StatusOK, res)
- })))
- // PUT /api/settings/wanspeed — guarda ambas velocidades (down y up).
- mux.Handle("PUT /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var body wanSpeedResponse
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "")
- return
- }
- if body.DownMbps == nil || body.UpMbps == nil {
- writeError(w, http.StatusBadRequest, "invalid_input", "downMbps and upMbps are required")
- return
- }
- if !validWanSpeed(*body.DownMbps) || !validWanSpeed(*body.UpMbps) {
- writeError(w, http.StatusBadRequest, "invalid_input", "velocidad contratada debe ser mayor que 0 y como máximo 100000 Mbps")
- return
- }
- if err := kvSetFloat(s.db.DB, wanSpeedDownKey, *body.DownMbps); err != nil {
- writeError(w, http.StatusInternalServerError, "kv_error")
- return
- }
- if err := kvSetFloat(s.db.DB, wanSpeedUpKey, *body.UpMbps); err != nil {
- writeError(w, http.StatusInternalServerError, "kv_error")
- return
- }
- writeJSON(w, http.StatusOK, wanSpeedResponse{DownMbps: body.DownMbps, UpMbps: body.UpMbps})
- })))
- s.registerKnownMacsRoutes(mux)
- s.registerTelegramRoutes(mux)
- s.registerNtfyRoutes(mux)
- s.registerAlertsLangRoutes(mux)
- s.registerRoamingSettingsRoutes(mux)
- s.registerThresholdsRoutes(mux)
- }
- // integrationsView: estado efectivo de los toggles server-side (#968).
- // Ausente = activo para ntfy/telegram/proxmox; MQTT refleja la config
- // efectiva del manager (env + kv). MCP (#1114): false con mcpLocked=true
- // cuando el despliegue no lo habilitó por env (el endpoint no existe).
- func (s *server) integrationsView() map[string]any {
- mqtt := kvGet(s.db.DB, "mqtt.enabled") == "true"
- if s.mqtt != nil {
- mqtt = s.mqtt.Config().Enabled
- }
- return map[string]any{
- "ntfy": kvGetDefaultOn(s.db.DB, integrationNtfyKey),
- "telegram": kvGetDefaultOn(s.db.DB, integrationTelegramKey),
- "proxmox": kvGetDefaultOn(s.db.DB, integrationProxmoxKey),
- "mqtt": mqtt,
- "mcp": s.mcpMounted() && kvGetDefaultOn(s.db.DB, integrationMCPKey),
- "mcpLocked": !s.mcpMounted(),
- }
- }
- // mcpMounted: el endpoint /mcp existe en este proceso (opt-in duro por env,
- // #1114). El toggle de integración solo puede apagarlo, nunca montarlo.
- func (s *server) mcpMounted() bool {
- return s.cfg != nil && s.cfg.MCPEnabled && s.mcp != nil
- }
- // setMQTTEnabled cambia SOLO el flag enabled del publisher MQTT (#968): carga
- // la config efectiva, conmuta y reaplica (sin tocar host/credenciales). Sin
- // manager (tests) cae a escribir la clave kv directamente.
- func (s *server) setMQTTEnabled(enabled bool) error {
- if s.mqtt == nil {
- return kvSetStr(s.db.DB, "mqtt.enabled", strconv.FormatBool(enabled))
- }
- cfg := s.mqtt.Config()
- cfg.Enabled = enabled
- if err := mqttpub.SaveConfig(&dbKVAdapter{db: s.db.DB}, cfg); err != nil {
- return err
- }
- s.mqtt.Apply(cfg)
- return nil
- }
- // knownMacItem es la forma JSON de una entrada de la allowlist (#196).
- type knownMacItem struct {
- MAC string `json:"mac"`
- Name string `json:"name"`
- Note string `json:"note,omitempty"`
- }
- // validMAC normaliza y valida una dirección MAC (AA:BB:CC:DD:EE:FF).
- func validMAC(raw string) (string, bool) {
- m := strings.ToUpper(strings.TrimSpace(raw))
- if len(m) != 17 {
- return "", false
- }
- for i := 0; i < 17; i++ {
- if i%3 == 2 {
- if m[i] != ':' {
- return "", false
- }
- } else if !isHex(m[i]) {
- return "", false
- }
- }
- return m, true
- }
- func isHex(c byte) bool {
- return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
- }
- // registerKnownMacsRoutes: GET/PUT/DELETE /api/settings/known-macs (admin,
- // issue #196) — allowlist de dispositivos confiables que no alertan como
- // "desconocido" y cuyo nombre se usa como alias.
- func (s *server) registerKnownMacsRoutes(mux *http.ServeMux) {
- // GET /api/settings/known-macs — lista completa de la allowlist.
- mux.Handle("GET /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- items, err := s.db.ListKnownMacs()
- if err != nil {
- writeError(w, http.StatusInternalServerError, "db_error")
- return
- }
- out := make([]knownMacItem, 0, len(items))
- for _, k := range items {
- out = append(out, knownMacItem{MAC: k.MAC, Name: k.Name, Note: k.Note})
- }
- writeJSON(w, http.StatusOK, map[string][]knownMacItem{"items": out})
- })))
- // PUT /api/settings/known-macs — alta o actualización de una MAC.
- mux.Handle("PUT /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var body knownMacItem
- if st := readJSONBody(w, r, &body); st != 0 {
- writeBodyError(w, st, "invalid_body", "")
- return
- }
- mac, ok := validMAC(body.MAC)
- if !ok {
- writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
- return
- }
- if err := s.db.UpsertKnownMac(db.KnownMac{MAC: mac, Name: body.Name, Note: body.Note}); err != nil {
- writeError(w, http.StatusInternalServerError, "db_error")
- return
- }
- // #1278: re-alta manual quita la lápida (en el camino de éxito: en el
- // de error no se registró nada y la lápida debe quedarse).
- _ = s.db.DeleteDeletedClient(mac)
- writeJSON(w, http.StatusOK, knownMacItem{MAC: mac, Name: body.Name, Note: body.Note})
- })))
- // DELETE /api/settings/known-macs/{mac} — baja de la allowlist.
- mux.Handle("DELETE /api/settings/known-macs/{mac}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- mac, ok := validMAC(r.PathValue("mac"))
- if !ok {
- writeError(w, http.StatusBadRequest, "invalid_input", "dirección MAC inválida (AA:BB:CC:DD:EE:FF)")
- return
- }
- if err := s.db.DeleteKnownMac(mac); err != nil {
- writeError(w, http.StatusInternalServerError, "db_error")
- return
- }
- writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
- })))
- }
|