Просмотр исходного кода

fix(settings): make the Services toggle control AdGuard monitoring (#814)

* fix(settings): let AdGuard be disabled so it stops penalizing health

A configured but unreachable AdGuard could not be turned off: the Services
toggle only hides the card client-side and the AdGuard config card had no
disable action (unlike Proxmox). The server kept polling it every cycle and
computeHealth kept subtracting 5 points as "AdGuard inactivo".

- add DELETE /api/config/adguard (admin) that clears the adguard_* kv keys
  and forces an immediate poll
- add a Disable button to the AdGuard config card
- hide the Home AdGuard card when there is no config
- tests: TestAdGuardConfigDisable (clear + idempotent + admin-only)

Closes #813

* fix(settings): make the Services toggle control AdGuard monitoring

The AdGuard config card is gated by the Services visibility toggle and the
toggle was client-only, so unchecking "AdGuard Home" hid the card (the only
place with a disable action) while the server kept polling AdGuard and
penalizing the health score with "AdGuard inactivo".

- persist the AdGuard service flag server-side (settings.services.adguard,
  default on) via GET/PUT /api/settings/services
- pollAdGuard returns nil when the service is disabled: no polling and no
  "AdGuard inactivo" health penalty
- the Services toggle reads and writes the server setting
- clarify the section caption/note ("shown and monitored")
- test: TestServicesAdguardToggle

Refs #813

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
9586a273ce

+ 3 - 2
app/public/locales/en/translation.json

@@ -1207,6 +1207,7 @@
       "pass": "Password",
       "passKeep": "Saved (type to change)",
       "edit": "Edit",
+      "disable": "Disable",
       "configured": "Configured",
       "notConfigured": "Not configured",
       "save": "Save",
@@ -1449,14 +1450,14 @@
     "saved": "Preferences saved",
     "services": {
       "title": "Services",
-      "caption": "Which services are shown on the dashboard",
+      "caption": "Which services are shown and monitored",
       "adguardCaption": "Filtered DNS on the gateway",
       "wireguardCaption": "WireGuard VPN tunnels",
       "openvpnCaption": "OpenVPN tunnels (coming soon)",
       "labs": "Labs (experimental features)",
       "labsCaption": "Enable features in development: orchestration, scrapers, and more",
       "orchestrationHint": "Manage routers from the UI (AdGuard, guest Wi-Fi, DDNS…)",
-      "note": "Only checked cards are shown. More services coming soon."
+      "note": "Only checked services are shown and monitored. More services coming soon."
     },
     "session": {
       "active": "Active session on this device",

+ 3 - 2
app/public/locales/es/translation.json

@@ -1207,6 +1207,7 @@
       "pass": "Contraseña",
       "passKeep": "Guardada (escribe para cambiar)",
       "edit": "Editar",
+      "disable": "Desactivar",
       "configured": "Configurado",
       "notConfigured": "Sin configurar",
       "save": "Guardar",
@@ -1449,14 +1450,14 @@
     "saved": "Preferencias guardadas",
     "services": {
       "title": "Servicios",
-      "caption": "Qué servicios se muestran en el panel",
+      "caption": "Qué servicios se muestran y monitorizan",
       "adguardCaption": "DNS filtrado en la puerta de enlace",
       "wireguardCaption": "Túneles VPN WireGuard",
       "openvpnCaption": "Túneles VPN OpenVPN (próximamente)",
       "labs": "Labs (aplicaciones experimentales)",
       "labsCaption": "Activa funcionalidades en desarrollo: orquestación, scrapers y más",
       "orchestrationHint": "Permite gestionar routers desde la interfaz (AdGuard, WiFi invitados, DDNS…)",
-      "note": "Solo se muestran las tarjetas marcadas. Más servicios próximamente."
+      "note": "Solo se muestran y se monitorizan los servicios marcados. Más servicios próximamente."
     },
     "session": {
       "active": "Sesión activa en este dispositivo",

+ 65 - 3
app/src/pages/Settings.tsx

@@ -28,6 +28,7 @@ import {
   Moon,
   Pencil,
   Plus,
+  Power,
   Lock,
    Radar,
    RefreshCw,
@@ -1470,6 +1471,7 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [passSet, setPassSet] = useState(false)
   const [editing, setEditing] = useState(false)
   const [saving, setSaving] = useState(false)
+  const [disabling, setDisabling] = useState(false)
   const [error, setError] = useState<string | null>(null)
 
   useEffect(() => {
@@ -1539,6 +1541,27 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     }
   }
 
+  // DELETE /api/config/adguard: desactiva AdGuard (borra la config) para que
+  // deje de sondearse y de penalizar la salud (#813).
+  const disable = async () => {
+    if (disabling) return
+    setDisabling(true)
+    setError(null)
+    try {
+      const res = await fetch('/api/config/adguard', { method: 'DELETE' })
+      if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
+      setPassSet(false)
+      setPassword('')
+      setHost('')
+      setEditing(false)
+      onSaved()
+    } catch {
+      setError(t('settings.adguard.errorGeneric'))
+    } finally {
+      setDisabling(false)
+    }
+  }
+
   // SPEC-65 D65-7c: configurado y sin editar → vista compacta (icono + host +
   // chip ok + Editar). Sin configurar → form directo como antes.
   if (passSet && !editing) {
@@ -1559,7 +1582,18 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           >
             <Pencil className="h-4 w-4" strokeWidth={1.75} />
           </button>
+          <button
+            type="button"
+            onClick={() => void disable()}
+            disabled={disabling}
+            aria-label={t('settings.adguard.disable')}
+            title={t('settings.adguard.disable')}
+            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-danger/30 text-danger transition-colors duration-150 hover:border-danger/60 hover:bg-danger/10 disabled:opacity-40"
+          >
+            <Power className="h-4 w-4" strokeWidth={1.75} />
+          </button>
         </div>
+        {error && <p className="mt-2 text-caption text-danger">{error}</p>}
         <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.adguard.hint')}</p>
       </Card>
     )
@@ -2983,6 +3017,34 @@ function ServicesCard({
     { key: 'wireguard', label: 'WireGuard', caption: t('settings.services.wireguardCaption') },
     { key: 'openvpn', label: 'OpenVPN', caption: t('settings.services.openvpnCaption') },
   ]
+
+  // AdGuard (#813): el toggle de Servicios también controla el sondeo y la
+  // penalización EN EL SERVIDOR. Se lee al montar (coherencia entre
+  // navegadores) y se escribe al cambiar.
+  useEffect(() => {
+    let alive = true
+    void fetch('/api/settings/services')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((d) => {
+        if (alive && d && typeof d.adguard === 'boolean') setService('adguard', d.adguard)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [setService])
+
+  const onServiceToggle = (key: keyof ServicesVisibility, v: boolean) => {
+    setService(key, v)
+    if (key === 'adguard') {
+      void fetch('/api/settings/services', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ adguard: v }),
+      }).catch(() => undefined)
+    }
+  }
+
   return (
     <Card title={t('settings.services.title')} caption={t('settings.services.caption')} index={3} reduce={reduce}>
       <div className="grid grid-cols-1 gap-x-6 gap-y-0 sm:grid-cols-2">
@@ -2993,7 +3055,7 @@ function ServicesCard({
             checked={services[rows[0]!.key]}
             disabled={disabled}
             onCheckedChange={(v) => {
-              setService(rows[0]!.key, v)
+              onServiceToggle(rows[0]!.key, v)
               onSaved()
             }}
           />
@@ -3003,7 +3065,7 @@ function ServicesCard({
             checked={services[rows[1]!.key]}
             disabled={disabled}
             onCheckedChange={(v) => {
-              setService(rows[1]!.key, v)
+              onServiceToggle(rows[1]!.key, v)
               onSaved()
             }}
           />
@@ -3015,7 +3077,7 @@ function ServicesCard({
             checked={services[rows[2]!.key]}
             disabled={disabled}
             onCheckedChange={(v) => {
-              setService(rows[2]!.key, v)
+              onServiceToggle(rows[2]!.key, v)
               onSaved()
             }}
           />

+ 4 - 0
app/src/sections/GatewayServices.tsx

@@ -95,6 +95,10 @@ export function AdGuardCard({ index = 0 }: { index?: number }) {
   const { adguard } = useNetPulse()
   const maxBlocked = Math.max(...adguard.topBlocked.map((d) => d.count))
 
+  // Sin config (host vacío) la tarjeta no aplica: al desactivar AdGuard (#813)
+  // desaparece en vez de quedarse en "inactivo".
+  if (!adguard.host) return null
+
   return (
       <ServicePanel
         icon={ShieldCheck}

+ 8 - 0
server-go/internal/adapters/live.go

@@ -1774,6 +1774,14 @@ func (l *Live) recordPortSamples(routerID string, ports []EthPort) {
 
 // pollAdGuard: stats del cliente configurado; fallback inactivo si falla.
 func (l *Live) pollAdGuard(ctx context.Context) *AdGuardStats {
+	// Servicio desactivado en Ajustes > Servicios (#813): ni sondeo ni
+	// penalización. Clave ausente = activo (compat).
+	if l.db != nil {
+		var v string
+		if err := l.db.QueryRow("SELECT value FROM kv WHERE key = 'settings.services.adguard'").Scan(&v); err == nil && (v == "0" || v == "false") {
+			return nil
+		}
+	}
 	std, gl := l.getAdguardClient()
 	if std == nil && gl == nil {
 		return nil

+ 18 - 0
server-go/internal/httpapi/config.go

@@ -39,6 +39,7 @@ func (s *server) registerConfigRoutes(mux *http.ServeMux) {
 	mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
 	mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
 	mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
+	mux.Handle("DELETE /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteAdguardConfig)))
 	mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
 	mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
 	mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
@@ -495,6 +496,23 @@ func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request)
 	w.WriteHeader(http.StatusNoContent)
 }
 
+// DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
+// (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
+// salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
+// Idempotente: 204 aunque no hubiera nada configurado.
+func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
+	for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
+		if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+	}
+	if s.pollNow != nil {
+		s.pollNow()
+	}
+	w.WriteHeader(http.StatusNoContent)
+}
+
 // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
 // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
 // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version

+ 44 - 0
server-go/internal/httpapi/config_test.go

@@ -448,6 +448,50 @@ func TestAdGuardConfigPort(t *testing.T) {
 	}
 }
 
+// TestAdGuardConfigDisable cubre DELETE /api/config/adguard (#813): borra la
+// config para que AdGuard deje de sondearse y de penalizar la salud.
+func TestAdGuardConfigDisable(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// Configurar AdGuard (modo glinet, como en producción).
+	res := doReq(t, "PUT", srv.URL+"/api/config/adguard", cookie,
+		`{"mode":"glinet","host":"192.168.1.1","port":0,"user":"root","password":"secret"}`)
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("PUT adguard: %d %v", res.StatusCode, body)
+	}
+	res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
+	body := readJSON(t, res)
+	if body["host"] != "192.168.1.1" || body["passSet"] != true {
+		t.Fatalf("config previa al DELETE: %+v", body)
+	}
+
+	// DELETE limpia la config (host y password fuera).
+	res = doReq(t, "DELETE", srv.URL+"/api/config/adguard", cookie, "")
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("DELETE adguard: %d %v", res.StatusCode, body)
+	}
+	res = doReq(t, "GET", srv.URL+"/api/config/adguard", cookie, "")
+	body = readJSON(t, res)
+	if body["host"] != "" || body["passSet"] != false {
+		t.Fatalf("config tras DELETE: %+v", body)
+	}
+
+	// Idempotente: un segundo DELETE sigue devolviendo 204.
+	res = doReq(t, "DELETE", srv.URL+"/api/config/adguard", cookie, "")
+	if res.StatusCode != 204 {
+		t.Fatalf("DELETE idempotente: got %d", res.StatusCode)
+	}
+
+	// Solo admin: sin sesión no puede desactivar.
+	res = doReq(t, "DELETE", srv.URL+"/api/config/adguard", "", "")
+	if res.StatusCode < 400 {
+		t.Fatalf("DELETE sin sesión debería fallar, got %d", res.StatusCode)
+	}
+}
+
 func TestConfigRoutersSNMP(t *testing.T) {
 	srv := makeTestServer(t)
 	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")

+ 40 - 0
server-go/internal/httpapi/settings.go

@@ -18,6 +18,10 @@ import (
 // orchestrationKey es la clave kv que activa el menú de orquestación (#121).
 const orchestrationKey = "settings.orchestration_enabled"
 
+// 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"
@@ -45,6 +49,14 @@ func kvSetBool(db *sql.DB, key string, val bool) error {
 	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) {
@@ -107,6 +119,34 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 		writeJSON(w, http.StatusOK, map[string]bool{"enabled": body.Enabled})
 	})))
 
+	// 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{}

+ 60 - 0
server-go/internal/httpapi/settings_services_test.go

@@ -0,0 +1,60 @@
+// settings_services_test.go — GET/PUT /api/settings/services (#813): el toggle
+// de Servicios controla la monitorización de AdGuard (default: activo).
+package httpapi_test
+
+import (
+	"net/http"
+	"testing"
+)
+
+func TestServicesAdguardToggle(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	if cookie == "" {
+		t.Fatal("login no devolvió cookie")
+	}
+
+	// Default: activo (clave kv ausente en una instalación nueva).
+	res, body := wanSpeedRequest(t, "GET", srv.URL, "/api/settings/services", cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET: status %d, esperado 200", res.StatusCode)
+	}
+	if body["adguard"] != true {
+		t.Fatalf("adguard default: %v, esperado true", body["adguard"])
+	}
+
+	// Desactivar.
+	res, body = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/services", cookie, `{"adguard":false}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT false: status %d (%v)", res.StatusCode, body)
+	}
+	if body["adguard"] != false {
+		t.Fatalf("PUT false echo: %v", body)
+	}
+	_, body = wanSpeedRequest(t, "GET", srv.URL, "/api/settings/services", cookie, "")
+	if body["adguard"] != false {
+		t.Fatalf("GET tras desactivar: %v, esperado false", body["adguard"])
+	}
+
+	// Reactivar.
+	res, _ = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/services", cookie, `{"adguard":true}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT true: status %d", res.StatusCode)
+	}
+	_, body = wanSpeedRequest(t, "GET", srv.URL, "/api/settings/services", cookie, "")
+	if body["adguard"] != true {
+		t.Fatalf("GET tras reactivar: %v, esperado true", body["adguard"])
+	}
+
+	// Sin el campo adguard → 400.
+	res, _ = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/services", cookie, `{}`)
+	if res.StatusCode != http.StatusBadRequest {
+		t.Fatalf("PUT sin adguard: status %d, esperado 400", res.StatusCode)
+	}
+
+	// Sin sesión → 401.
+	res, _ = wanSpeedRequest(t, "GET", srv.URL, "/api/settings/services", "", "")
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("GET sin auth: status %d, esperado 401", res.StatusCode)
+	}
+}