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

feat(agents): standalone config backup command and UI button (#1462)

New SSE event config_backup with an Options.OnConfigBackup hook; the agent snapshots with sysupgrade -b and uploads through the firmware-backup contract. Admin endpoint POST /api/agents/{slug}/backup sends the command (202 sent, 409 not connected, no queueing). Backup config button on the unit row confirms by polling the unit backup list. Also unbreaks the firmware-flow backup upload: the route was missing from the agent report allowlist, so it answered 401 silently.

Closes #1462
Closes #1465
Nacho 1 месяц назад
Родитель
Сommit
1664ebddb1

+ 31 - 0
agent/runtime/config_backup.go

@@ -0,0 +1,31 @@
+package runtime
+
+// Handler del comando config_backup (#1462): snapshot standalone de la
+// config, independiente del flujo de firmware. El servidor envía el evento
+// SSE cuando alguien pulsa "Backup config" en la tarjeta de la unidad; el
+// agente genera el tar.gz con sysupgrade -b y lo sube con el mismo contrato
+// que el backup del flujo de firmware (#1414), así la entrada aparece donde
+// la UI ya lista backups (GET /api/firmware-backups/{routerId}).
+// Best-effort: los fallos van a log, la UI descubre el resultado viendo
+// aparecer (o no) la entrada nueva.
+
+import (
+	"fmt"
+	"net/http"
+	"path/filepath"
+	"time"
+)
+
+func handleConfigBackup(opts Options, transport http.RoundTripper) {
+	log := opts.logger()
+	backupPath := filepath.Join(firmwareTmpDir, fmt.Sprintf("netpulse-config-backup-%d.tar.gz", time.Now().Unix()))
+	if err := backupConfig(backupPath); err != nil {
+		log.Error("[netpulse-agent] config_backup: snapshot falló", "err", err)
+		return
+	}
+	if err := uploadBackup(opts, transport, backupPath); err != nil {
+		log.Error("[netpulse-agent] config_backup: subida falló", "err", err)
+		return
+	}
+	log.Info("[netpulse-agent] config_backup: backup subido", "path", backupPath)
+}

+ 13 - 0
agent/runtime/runtime.go

@@ -93,6 +93,12 @@ type Options struct {
 	// OnUpgrade sustituye el self-upgrade integrado (evento SSE "upgrade").
 	// nil usa el comportamiento estándar: descargar binario + swap + restart.
 	OnUpgrade func(data string)
+
+	// OnConfigBackup sustituye el backup de config integrado (evento SSE
+	// "config_backup", #1462). nil usa el estándar: sysupgrade -b + subida a
+	// POST /api/config-backup. Los embedders (NetGrip) lo sobreescriben para
+	// usar su propio módulo de snapshots (netgrip#553).
+	OnConfigBackup func(data string)
 }
 
 // Status es una foto del agente para que el embedder pinte estado.
@@ -226,6 +232,13 @@ func Run(ctx context.Context, opts Options) error {
 				if ev.Name == "firmware_upgrade" && ev.Data != "" {
 					go handleFirmwareUpgrade(opts, transport, ev.Data)
 				}
+				if ev.Name == "config_backup" {
+					if opts.OnConfigBackup != nil {
+						go opts.OnConfigBackup(ev.Data)
+					} else {
+						go handleConfigBackup(opts, transport)
+					}
+				}
 				log.Debug("[netpulse-agent] SSE evento", "event", ev.Name)
 			})
 		sse.SetLogger(func(format string, args ...any) { log.Debug("[netpulse-agent] " + fmt.Sprintf(format, args)) })

+ 8 - 0
app/public/locales/en/translation.json

@@ -1067,6 +1067,14 @@
       "stepQueued": "waiting for connection",
       "upgradeQueued": "Queued",
       "upgradeQueuedTip": "The agent is offline: the upgrade will be sent when it reconnects",
+      "backup": "Backup config",
+      "backupTip": "Takes a config snapshot on the router (sysupgrade -b) and stores it on the server, independent of any upgrade",
+      "backupSent": "Requesting backup",
+      "backupWaiting": "Waiting for the backup...",
+      "backupDone": "Backup saved",
+      "backupTimeout": "The backup did not arrive",
+      "backupNotConnected": "Agent not connected",
+      "backupFail": "Could not request it",
       "timeline": "Upgrade",
       "timelineDone": "completed",
       "stepVerifying": "Verifying integrity",

+ 8 - 0
app/public/locales/es/translation.json

@@ -1067,6 +1067,14 @@
       "stepQueued": "esperando conexión",
       "upgradeQueued": "En cola",
       "upgradeQueuedTip": "El agente no está conectado: la actualización se enviará cuando vuelva a conectar",
+      "backup": "Copia de config",
+      "backupTip": "Hace una copia de la configuración en el router (sysupgrade -b) y la guarda en el servidor, independiente de cualquier actualización",
+      "backupSent": "Solicitando copia",
+      "backupWaiting": "Esperando la copia...",
+      "backupDone": "Copia guardada",
+      "backupTimeout": "La copia no llegó",
+      "backupNotConnected": "Agente no conectado",
+      "backupFail": "No se pudo solicitar",
       "timeline": "Actualización",
       "timelineDone": "completado",
       "stepVerifying": "Comprobando integridad",

+ 130 - 0
app/src/components/routers/AgentBackupButton.tsx

@@ -0,0 +1,130 @@
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Archive, Loader2 } from 'lucide-react'
+import { useNetPulse } from '@/data/DataProvider'
+import { useAuth } from '@/data/AuthContext'
+import type { AgentInfo } from '@/data/types'
+import { cn } from '@/lib/utils'
+
+interface AgentBackupButtonProps {
+  agent: AgentInfo | undefined
+  /** id del router: el resultado se confirma viendo aparecer la entrada en
+   *  GET /api/firmware-backups/{routerId}. */
+  routerId?: string
+  className?: string
+}
+
+type BackupState = 'idle' | 'busy' | 'waiting' | 'done' | 'timeout' | 'not_connected' | 'fail'
+
+/** Espera máxima del snapshot: sysupgrade -b + subida del tar.gz (#1462). */
+const BACKUP_WAIT_S = 45
+
+/**
+ * Botón «Copia de config» (#1462): snapshot standalone de la configuración,
+ * independiente del flujo de firmware. POST /api/agents/{slug}/backup envía
+ * el evento SSE "config_backup"; el agente hace sysupgrade -b y sube el
+ * tar.gz con el mismo contrato que el backup del flujo de upgrade (#1414),
+ * así la entrada aparece donde la UI ya lista backups.
+ *
+ * Estados:
+ *   waiting       → comando enviado, sondeando la lista de backups hasta que
+ *                   aparezca una entrada con ts posterior al clic
+ *   done          → la entrada apareció (flash verde)
+ *   timeout       → 45 s sin entrada nueva (el agente falló en silencio)
+ *   not_connected → 409, agente sin SSE (a diferencia del upgrade no se encola)
+ *   fail          → petición fallida (red, 4xx/5xx)
+ */
+export function AgentBackupButton({ agent, routerId, className }: AgentBackupButtonProps) {
+  const { t } = useTranslation()
+  const { backupAgent } = useNetPulse()
+  const auth = useAuth()
+  const [state, setState] = useState<BackupState>('idle')
+  const [clickTs, setClickTs] = useState(0)
+  const timerRef = useRef<number | null>(null)
+
+  const toIdle = (ms: number) => {
+    if (timerRef.current) window.clearTimeout(timerRef.current)
+    timerRef.current = window.setTimeout(() => setState('idle'), ms)
+  }
+
+  // Limpieza del timer al desmontar.
+  useEffect(() => () => {
+    if (timerRef.current) window.clearTimeout(timerRef.current)
+  }, [])
+
+  // Sondeo de la lista de backups mientras esperamos la entrada nueva.
+  useEffect(() => {
+    if (state !== 'waiting' || !routerId) return
+    const started = Date.now()
+    const poll = window.setInterval(async () => {
+      if (Date.now() - started > BACKUP_WAIT_S * 1000) {
+        window.clearInterval(poll)
+        setState('timeout')
+        toIdle(6000)
+        return
+      }
+      try {
+        const res = await fetch(`/api/firmware-backups/${encodeURIComponent(routerId)}`, {
+          signal: AbortSignal.timeout(10_000),
+        })
+        if (res.status === 401) return
+        if (!res.ok) return
+        const body = (await res.json()) as { ts: number }[]
+        if (body.some((b) => b.ts * 1000 >= clickTs)) {
+          window.clearInterval(poll)
+          setState('done')
+          toIdle(4000)
+        }
+      } catch {
+        /* reintento en el siguiente tick */
+      }
+    }, 3000)
+    return () => window.clearInterval(poll)
+  }, [state, routerId, clickTs])
+
+  if (auth?.role !== 'admin') return null
+  if (!agent || !routerId) return null
+
+  const label =
+    state === 'busy' ? t('routers.agent.backupSent')
+    : state === 'waiting' ? t('routers.agent.backupWaiting')
+    : state === 'done' ? t('routers.agent.backupDone')
+    : state === 'timeout' ? t('routers.agent.backupTimeout')
+    : state === 'not_connected' ? t('routers.agent.backupNotConnected')
+    : state === 'fail' ? t('routers.agent.backupFail')
+    : t('routers.agent.backup')
+
+  return (
+    <button
+      type="button"
+      onClick={async () => {
+        if (state === 'busy' || state === 'waiting') return
+        setState('busy')
+        const res = await backupAgent(agent.slug)
+        if (res === 'sent') {
+          setClickTs(Date.now())
+          setState('waiting')
+        } else if (res === 'not_connected') {
+          setState('not_connected')
+          toIdle(6000)
+        } else {
+          setState('fail')
+          toIdle(6000)
+        }
+      }}
+      disabled={state === 'busy' || state === 'waiting'}
+      title={t('routers.agent.backupTip')}
+      className={cn(
+        'inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] font-semibold transition-opacity hover:opacity-90 disabled:opacity-50',
+        state === 'done' ? 'bg-ok text-canvas'
+        : state === 'timeout' || state === 'not_connected' || state === 'fail' ? 'bg-danger text-canvas'
+        : 'bg-accent-soft text-accent',
+        className,
+      )}
+    >
+      {(state === 'busy' || state === 'waiting') && <Loader2 className="h-3 w-3 animate-spin" />}
+      {state === 'idle' && <Archive className="h-3 w-3" />}
+      {label}
+    </button>
+  )
+}

+ 5 - 0
app/src/components/routers/AgentsSection.tsx

@@ -19,6 +19,7 @@ import type { AgentInfo, Router } from '@/data/types'
 import { relTimeFromTs } from '@/i18n'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
 import { AgentUpgradeButton, activeUpgrade, upgradeStepText } from '@/components/routers/AgentUpgradeButton'
+import { AgentBackupButton } from '@/components/routers/AgentBackupButton'
 import { agentMatchesRouter, findRouterFor } from '@/lib/agentMatch'
 import { cn, copyToClipboard } from '@/lib/utils'
 
@@ -286,6 +287,10 @@ function AgentRow({ agent, router, nowSec }: { agent?: AgentInfo; router: Router
               NetGrip (#363): el evento SSE dispara el self-update del propio
               panel; el reinstall no aplica (no hay proceso standalone). */}
           <AgentUpgradeButton agent={agent} className="h-8" />
+          {/* #1462: snapshot standalone de la config (SSE config_backup);
+              el resultado se confirma al aparecer la entrada en la lista de
+              backups de la unidad. */}
+          <AgentBackupButton agent={agent} routerId={agent?.routerId} className="h-8" />
           {isNetgrip ? (
             // #363: NetGrip fresco se auto-actualiza desde su panel; el hint
             // lo explica. (El rearm por SSH de un NetGrip caído de #569 quedó

+ 10 - 0
app/src/components/routers/RouterDetailHeader.tsx

@@ -10,6 +10,7 @@ import { StatusPill } from '@/components/StatusPill'
 import { AgentBadge } from '@/components/routers/AgentBadge'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
 import { AgentUpgradeButton } from '@/components/routers/AgentUpgradeButton'
+import { AgentBackupButton } from '@/components/routers/AgentBackupButton'
 import { useAgentFor } from '@/hooks/useAgentFor'
 import { cn } from '@/lib/utils'
 
@@ -119,6 +120,15 @@ export function RouterDetailHeader({ router }: { router: Router }) {
                   <AgentUpgradeButton agent={agent} />
                 </motion.span>
               )}
+              {agent && (
+                <motion.span
+                  initial={reduce ? false : { opacity: 0, scale: 0.9 }}
+                  animate={{ opacity: 1, scale: 1 }}
+                  transition={{ duration: 0.2, delay: 0.15 + (pills.length + 3) * 0.06 }}
+                >
+                  <AgentBackupButton agent={agent} routerId={router.id} />
+                </motion.span>
+              )}
             </div>
           </div>
         </div>

+ 29 - 2
app/src/data/DataProvider.tsx

@@ -217,6 +217,13 @@ export interface NetPulseApi extends NetPulseData {
    * del envío; null si la petición falló (demo siempre null).
    */
   upgradeAgent: (slug: string) => Promise<'sent' | 'queued' | 'not_connected' | null>
+  /**
+   * #1462: POST /api/agents/{slug}/backup — pide al agente un snapshot
+   * standalone de su config (evento SSE "config_backup"). 202 enviado, 409 no
+   * conectado (a diferencia del upgrade NO se encola: un backup no es
+   * imperativo). null si la petición falló (demo siempre null).
+   */
+  backupAgent: (slug: string) => Promise<'sent' | 'not_connected' | null>
   /**
    * #251: POST /api/agents/upgrade-all — envía el upgrade a todos los agentes
    * con versión desactualizada. Devuelve el resumen por slug; null si falló.
@@ -1203,8 +1210,27 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
   }, [])
 
-  const upgradeAllAgents = useCallback(async (): Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null> => {
+  const backupAgent = useCallback(async (slug: string): Promise<'sent' | 'not_connected' | null> => {
     if (modeRef.current !== 'live') return null
+    try {
+      const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/backup`, {
+        method: 'POST',
+        signal: AbortSignal.timeout(30_000),
+      })
+      if (res.status === 401) redirectLogin()
+      if (res.status === 409) return 'not_connected'
+      if (!res.ok) return null
+      // 202: el comando salió por SSE. El resultado real se ve al aparecer
+      // la entrada nueva en GET /api/firmware-backups/{routerId} (el agente
+      // sube el tar.gz con el mismo contrato que el backup del flujo
+      // firmware, #1414); la UI lo sondea (AgentBackupButton).
+      return 'sent'
+    } catch {
+      return null
+    }
+  }, [])
+
+  const upgradeAllAgents = useCallback(async (): Promise<{ sent: number; total: number; message: string; agents: { slug: string; status: string }[] } | null> => {    if (modeRef.current !== 'live') return null
     try {
       const res = await fetch('/api/agents/upgrade-all', {
         method: 'POST',
@@ -1415,13 +1441,14 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       dismissAlert,
       rearmAgent,
       upgradeAgent,
+      backupAgent,
       upgradeAllAgents,
       reinstallAgent,
       uninstallAgent,
       removeAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, setPeerUrgent, dismissAlert, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, clearAllAlerts, silenceAlert, approveImpostorBssid, setPeerUrgent, dismissAlert, rearmAgent, upgradeAgent, backupAgent, upgradeAllAgents, reinstallAgent, uninstallAgent, removeAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

+ 33 - 0
server-go/internal/auth/agent_paths_test.go

@@ -0,0 +1,33 @@
+package auth
+
+import (
+	"net/http/httptest"
+	"testing"
+)
+
+// Regresión #1462: el agente sube el backup de config a
+// /api/agents/{slug}/firmware-backup con su Bearer. Si la ruta no está en la
+// allowlist de rutas de agente, RequireAuth la rechaza con 401 antes de que
+// el handler valide el token (el upload del flujo de firmware #1414 fallaba
+// en silencio por esto).
+func TestIsAgentReportPathFirmwareBackup(t *testing.T) {
+	cases := []string{
+		"/api/agents/rt4/firmware-backup",
+		"/api/agents/rt4/firmware-progress",
+		"/api/agents/rt4/firmware-result",
+		"/api/agents/rt4/upgrade-progress",
+		"/api/agents/rt4/binary",
+	}
+	for _, p := range cases {
+		if !isAgentReportPath(p) {
+			t.Errorf("%s debería ser ruta de agente", p)
+		}
+		if !IsAgentRequest(httptest.NewRequest("POST", p, nil)) {
+			t.Errorf("%s debería pasar el gate IsAgentRequest", p)
+		}
+	}
+	// Rutas de admin con el mismo prefijo NO deben colarse como agente.
+	if isAgentReportPath("/api/agents") {
+		t.Error("/api/agents no es una ruta de reporte")
+	}
+}

+ 2 - 2
server-go/internal/auth/middleware.go

@@ -57,13 +57,13 @@ func WriteError(w http.ResponseWriter, status int, code string, message ...strin
 	_, _ = w.Write(data)
 }
 
-// isAgentReportPath: /api/agents/{slug}/binary|stream|apply-result|upgrade-result|upgrade-progress|firmware-progress|firmware-result.
+// isAgentReportPath: /api/agents/{slug}/binary|stream|apply-result|upgrade-result|upgrade-progress|firmware-progress|firmware-result|firmware-backup.
 func isAgentReportPath(path string) bool {
 	return strings.HasPrefix(path, "/api/agents/") &&
 		(strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream") ||
 			strings.HasSuffix(path, "/apply-result") || strings.HasSuffix(path, "/upgrade-result") ||
 			strings.HasSuffix(path, "/upgrade-progress") || strings.HasSuffix(path, "/firmware-progress") ||
-			strings.HasSuffix(path, "/firmware-result"))
+			strings.HasSuffix(path, "/firmware-result") || strings.HasSuffix(path, "/firmware-backup"))
 }
 
 // IsAgentRequest reports whether r is a route agents and embedders call with

+ 106 - 0
server-go/internal/httpapi/backup_api_test.go

@@ -0,0 +1,106 @@
+// backup_api_test.go — #1462: snapshot standalone de la config por SSE.
+// Contrato de POST /api/agents/{slug}/backup (admin): igual de auth que el
+// upgrade, pero a diferencia de este NO se encola cuando el agente no está
+// conectado (409): un backup no es imperativo.
+package httpapi_test
+
+import (
+	"context"
+	"encoding/json"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+)
+
+func postBackup(t *testing.T, ts *upgradeTestServer, slug, cookie string) (int, map[string]any) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents/"+slug+"/backup", nil)
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("POST /backup: %v", err)
+	}
+	defer res.Body.Close()
+	var body map[string]any
+	_ = json.NewDecoder(res.Body).Decode(&body)
+	return res.StatusCode, body
+}
+
+// openStreamRec igual que openStream pero devuelve el recorder para leer el
+// evento enviado al stream.
+func openStreamRec(t *testing.T, ts *upgradeTestServer, slug, token string) (*httptest.ResponseRecorder, context.CancelFunc, chan struct{}) {
+	t.Helper()
+	ctx, cancel := context.WithCancel(context.Background())
+	req := httptest.NewRequest(http.MethodGet, ts.URL+"/api/agents/"+slug+"/stream", nil).WithContext(ctx)
+	req.SetPathValue("slug", slug)
+	req.Header.Set("Authorization", "Bearer "+token)
+	rec := httptest.NewRecorder()
+	done := make(chan struct{})
+	go func() {
+		ts.hub.HandleStream(rec, req)
+		close(done)
+	}()
+	time.Sleep(200 * time.Millisecond)
+	return rec, cancel, done
+}
+
+func TestBackupSinSesion401(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	status, body := postBackup(t, ts, "patio", "")
+	if status != 401 || body["error"] != "unauthorized" {
+		t.Fatalf("sin sesión: got %d %v", status, body)
+	}
+}
+
+func TestBackupSlugDesconocido404(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	status, body := postBackup(t, ts, "noexiste", ts.cookie)
+	if status != 404 || body["error"] != "not_found" {
+		t.Fatalf("slug desconocido: got %d %v", status, body)
+	}
+}
+
+// TestBackupNoConectado409: a diferencia del upgrade (#284) el backup NO se
+// encola: si el agente no está conectado por SSE se rechaza con 409.
+func TestBackupNoConectado409(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 || tok == "" {
+		t.Fatalf("create: %d", st)
+	}
+	status, body := postBackup(t, ts, "patio", ts.cookie)
+	if status != 409 || body["error"] != "not_connected" {
+		t.Fatalf("no conectado: got %d %v", status, body)
+	}
+}
+
+// TestBackupEnviado202: con el stream conectado el comando sale (202) y el
+// evento SSE "config_backup" llega al agente.
+func TestBackupEnviado202(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 || tok == "" {
+		t.Fatalf("create: %d", st)
+	}
+	rec, cancel, done := openStreamRec(t, ts, "patio", tok)
+	defer func() { cancel(); <-done }()
+
+	status, body := postBackup(t, ts, "patio", ts.cookie)
+	if status != 202 || body["status"] != "sent" {
+		t.Fatalf("enviado: got %d %v", status, body)
+	}
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		if strings.Contains(rec.Body.String(), "config_backup") {
+			return
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	data, _ := io.ReadAll(rec.Result().Body)
+	t.Fatalf("evento config_backup no llegó al stream; body: %q", string(data))
+}

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

@@ -509,6 +509,8 @@ func NewHandler(d Deps) http.Handler {
 		mux.Handle("POST /api/agents/{slug}/refresh", auth.RequireAdmin(http.HandlerFunc(s.handleAgentRefresh)))
 		// Self-update del agente vía SSE (admin; Fase 6.3, issue #243).
 		mux.Handle("POST /api/agents/{slug}/upgrade", auth.RequireAdmin(http.HandlerFunc(s.handleAgentUpgrade)))
+		// Snapshot standalone de la config vía SSE (admin; #1462).
+		mux.Handle("POST /api/agents/{slug}/backup", auth.RequireAdmin(http.HandlerFunc(s.handleAgentBackup)))
 	}
 
 	// --- Fase 9 R3: Pairing / adopción de agentes ---

+ 29 - 0
server-go/internal/httpapi/upgrade.go

@@ -287,6 +287,35 @@ func (s *server) FlushQueuedUpgrade(slug string) {
 	}
 }
 
+// handleAgentBackup (admin, #1462): pide a un agente conectado un snapshot
+// standalone de su config (evento SSE "config_backup"; el agente NetGrip lo
+// resuelve con su propio módulo de snapshots, netgrip#553). A diferencia del
+// upgrade no se encola: un backup no es imperativo, si el agente no está
+// conectado se rechaza y la UI lo muestra.
+//
+//	Códigos: 404 slug desconocido (sin token), 409 agente no conectado,
+//	         202 comando enviado, 503 sin AgentHub.
+func (s *server) handleAgentBackup(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	if !agentSlugRe.MatchString(slug) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	if s.agentHub == nil {
+		writeError(w, http.StatusServiceUnavailable, "unavailable", "SSE agentHub no configurado")
+		return
+	}
+	if !s.agentTokenExists(slug) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	if !s.agentHub.Send(slug, "config_backup", map[string]any{}) {
+		writeError(w, http.StatusConflict, "not_connected", "agente no conectado por SSE")
+		return
+	}
+	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "status": "sent"})
+}
+
 // handleAgentUpgradeProgress: el agente reporta un paso intermedio del
 // self-update (downloading/swapping/restarting). Auth por token de agente
 // (Bearer), igual que upgrade-result (#284).