Explorar el Código

feat(settings): orchestration menu opt-in, hidden by default (#129)

The orchestration menu (write operations on routers: plan, apply, rollback)
is a powerful surface. Show it only when the admin opts in, off by default.

Backend:
- kv flag settings.orchestration_enabled (kvGetBool/kvSetBool helpers; kvGet
  already existed in config.go).
- GET/PUT /api/settings/orchestration (admin).
- Overview.orchestration bool (omitempty), injected in handleOverview so the
  frontend can decide nav visibility without touching the poller adapter.

Frontend:
- Layout.useVisibleNavItems hides /orchestration unless orchestration is set.
- Settings AdminBar gains an Orchestration switch (i18n es+en).

Closes #121

Co-authored-by: gnacho <hnacho@proton.me>
Nacho hace 3 meses
padre
commit
c9c1baa7e4

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

@@ -644,7 +644,9 @@
   },
   "settings": {
     "admin": {
-      "title": "Administration"
+      "title": "Administration",
+      "orchestration": "Network orchestration",
+      "orchestrationDesc": "Shows the orchestration menu (apply and roll back changes on routers). It is a write surface, so it is off until you enable it."
     },
     "adoption": {
       "title": "Agent adoption",

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

@@ -644,7 +644,9 @@
   },
   "settings": {
     "admin": {
-      "title": "Administración"
+      "title": "Administración",
+      "orchestration": "Orquestación de red",
+      "orchestrationDesc": "Muestra el menú de orquestación (aplicar y revertir cambios en routers). Es una superficie de escritura; se activa solo si lo quieres."
     },
     "adoption": {
       "title": "Adopción de agentes",

+ 9 - 3
app/src/components/Layout.tsx

@@ -174,11 +174,17 @@ function GatewayStatus() {
 
 /** Items de nav visibles según el overview. /roaming solo si hay DAWN. */
 function useVisibleNavItems(): NavItem[] {
-  const { dawn } = useNetPulse()
+  const { dawn, orchestration } = useNetPulse()
   const dawnAvailable = !!dawn?.available
   return useMemo(
-    () => NAV_ITEMS.filter((it) => it.to !== '/roaming' || dawnAvailable),
-    [dawnAvailable],
+    () =>
+      NAV_ITEMS.filter(
+        (it) =>
+          (it.to !== '/roaming' || dawnAvailable) &&
+          // Orquestación: opt-in del admin (#121). Oculto por defecto.
+          (it.to !== '/orchestration' || !!orchestration),
+      ),
+    [dawnAvailable, orchestration],
   )
 }
 

+ 3 - 0
app/src/data/DataProvider.tsx

@@ -98,6 +98,8 @@ export interface NetPulseData {
   topology?: TopoSemantics
   /** Disponibilidad de DAWN (roaming); ausente = no mostrar /roaming. */
   dawn?: { available: boolean }
+  /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
+  orchestration?: boolean
 }
 
 export interface NetPulseApi extends NetPulseData {
@@ -374,6 +376,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       vm,
       topology: o.topology,
       dawn: o.dawn,
+      orchestration: o.orchestration,
     }))
   }, [])
 

+ 2 - 0
app/src/data/types.ts

@@ -309,6 +309,8 @@ export interface OverviewBundle {
   topology?: TopoSemantics
   /** Disponibilidad de DAWN (roaming/band-steering); ausente = no mostrar /roaming. */
   dawn?: { available: boolean }
+  /** Menú de orquestación activado por el admin (#121); ausente = oculto. */
+  orchestration?: boolean
   ts: number
 }
 

+ 47 - 2
app/src/pages/Settings.tsx

@@ -1824,12 +1824,43 @@ function AdoptionCard() {
 export default function Settings() {
   const { t, i18n } = useTranslation()
   const reduce = useReducedMotion() ?? false
-  const { devices, routers, wan, isDemo } = useNetPulse()
+  const { devices, routers, wan, isDemo, refresh: refreshOverview } = useNetPulse()
   const auth = useAuth()
   // SPEC-65 D65-7c: la tarjeta AdGuard entera desaparece si el servicio está oculto
   const [services] = useServicesVisibility()
   const [adminPanel, setAdminPanel] = useState<'users' | null>(null)
 
+  // ——— Orquestación (issue #121): toggle opt-in en la AdminBar ———
+  const [orchOn, setOrchOn] = useState(false)
+  const [orchBusy, setOrchBusy] = useState(false)
+  useEffect(() => {
+    let alive = true
+    void fetch('/api/settings/orchestration')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((d) => {
+        if (alive && d) setOrchOn(!!d.enabled)
+      })
+      .catch(() => undefined)
+    return () => {
+      alive = false
+    }
+  }, [])
+  const toggleOrchestration = useCallback(async (enabled: boolean) => {
+    setOrchBusy(true)
+    try {
+      const res = await fetch('/api/settings/orchestration', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ enabled }),
+      })
+      if (!res.ok) return
+      setOrchOn(enabled)
+      refreshOverview() // el overview propaga el flag → el nav se actualiza
+    } finally {
+      setOrchBusy(false)
+    }
+  }, [refreshOverview])
+
   // ——— Idioma ('auto' por defecto sigue al navegador; elección explícita persistida) ———
   const [lang, setLang] = useState<'auto' | 'es' | 'en'>(() => {
     const raw = localStorage.getItem('netpulse-lang')
@@ -2522,7 +2553,21 @@ export default function Settings() {
                   />
                 </button>
 
-                {/* 3. Modo demo a la derecha */}
+                {/* 3. Orquestación (issue #121): opt-in, oculto por defecto */}
+                <label
+                  className="inline-flex h-9 shrink-0 cursor-pointer items-center gap-2 rounded-xl border border-border bg-elevated px-3 text-[13px] font-medium text-text-secondary transition-colors hover:bg-hover hover:text-text-primary"
+                  title={t('settings.admin.orchestrationDesc')}
+                >
+                  <span className="hidden sm:inline">{t('settings.admin.orchestration')}</span>
+                  <Switch
+                    checked={orchOn}
+                    onCheckedChange={(v) => void toggleOrchestration(v)}
+                    disabled={orchBusy}
+                    aria-label={t('settings.admin.orchestration')}
+                  />
+                </label>
+
+                {/* 4. Modo demo a la derecha */}
                 <div className="ml-auto">
                   <DemoCard reduce={reduce} onSaved={notify} />
                 </div>

+ 4 - 0
server-go/internal/adapters/types.go

@@ -277,6 +277,10 @@ type Overview struct {
 	// app muestra la entrada /roaming. Puntero: ausente en snapshots viejos y
 	// cuando ningún router tiene DAWN → nil = no mostrar la página.
 	Dawn *DawnOverview `json:"dawn,omitempty"`
+	// Orchestration: el menú de orquestación (escritura en routers) está
+	// oculto por defecto y solo se muestra si el admin lo activa en Ajustes
+	// (#121). Default false (omitempty).
+	Orchestration bool `json:"orchestration,omitempty"`
 	// VM: versión del view-model (SPEC-65 D65-4). SIEMPRE presente.
 	VM int   `json:"vm"`
 	Ts int64 `json:"ts"` // floor(now/1000) — SEGUNDOS

+ 3 - 0
server-go/internal/httpapi/data.go

@@ -114,6 +114,9 @@ func (s *server) handleOverview(w http.ResponseWriter, r *http.Request) {
 	engine := s.adapter.AlertsEngine()
 	out.Alerts = engine.List()
 	out.UnreadAlerts = engine.UnreadCount()
+	// Menú de orquestación: opt-in por admin (#121). Se expone aquí (no en el
+	// adapter) porque el kv vive en el server, no en el poller.
+	out.Orchestration = kvGetBool(s.db.DB, orchestrationKey)
 	writeJSON(w, http.StatusOK, &out)
 }
 

+ 3 - 0
server-go/internal/httpapi/server.go

@@ -234,6 +234,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Orquestación (Fase 10; solo admin) ---
 	s.registerOrchestrRoutes(mux, d.Orchestr)
 
+	// --- Ajustes globales en kv (issue #121: orchestration opt-in) ---
+	s.registerSettingsRoutes(mux)
+
 	// --- SSE ---
 	mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
 

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

@@ -0,0 +1,53 @@
+// settings.go — ajustes globales persistidos en kv (issue #121).
+//
+// Por ahora solo el flag de orquestación: 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"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// orchestrationKey es la clave kv que activa el menú de orquestación (#121).
+const orchestrationKey = "settings.orchestration_enabled"
+
+// 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
+}
+
+// registerSettingsRoutes: GET/PUT /api/settings/orchestration (admin).
+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 !readJSONBody(r, &body) {
+			writeError(w, http.StatusBadRequest, "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})
+	})))
+}

+ 57 - 0
server-go/internal/httpapi/settings_internal_test.go

@@ -0,0 +1,57 @@
+package httpapi
+
+import (
+	"database/sql"
+	"testing"
+
+	_ "modernc.org/sqlite"
+)
+
+func newTestKV(t *testing.T) *sql.DB {
+	t.Helper()
+	db, err := sql.Open("sqlite", ":memory:")
+	if err != nil {
+		t.Fatalf("sql.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = db.Close() })
+	if _, err := db.Exec(`CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT)`); err != nil {
+		t.Fatalf("create kv: %v", err)
+	}
+	return db
+}
+
+// TestKVGetBoolDefault: ausente → false (opt-in off por defecto, #121).
+func TestKVGetBoolDefault(t *testing.T) {
+	db := newTestKV(t)
+	if kvGetBool(db, orchestrationKey) {
+		t.Error("esperaba false para clave ausente")
+	}
+}
+
+// TestKVSetBoolRoundtrip: set true → get true; set false → get false.
+func TestKVSetBoolRoundtrip(t *testing.T) {
+	db := newTestKV(t)
+	if err := kvSetBool(db, orchestrationKey, true); err != nil {
+		t.Fatalf("kvSetBool(true): %v", err)
+	}
+	if !kvGetBool(db, orchestrationKey) {
+		t.Error("esperaba true tras set true")
+	}
+	if err := kvSetBool(db, orchestrationKey, false); err != nil {
+		t.Fatalf("kvSetBool(false): %v", err)
+	}
+	if kvGetBool(db, orchestrationKey) {
+		t.Error("esperaba false tras set false")
+	}
+}
+
+// TestKVGetBoolLegacyValue: un valor "true" en el kv también cuenta como activo.
+func TestKVGetBoolLegacyValue(t *testing.T) {
+	db := newTestKV(t)
+	if _, err := db.Exec(`INSERT INTO kv (key, value) VALUES (?, 'true')`, orchestrationKey); err != nil {
+		t.Fatalf("insert: %v", err)
+	}
+	if !kvGetBool(db, orchestrationKey) {
+		t.Error("esperaba true para valor 'true'")
+	}
+}