فهرست منبع

feat(alerts): notification levels, one firmware alert per unit, fleet-mac impostor seeds (#1418)

* feat(alerts): category levels become notification policy; log everything (#1413)

* feat(alerts): firmware alert once per unit; version-aware target comparison (#1411, #1412)

* docs(manual): firmware upgrades page controls and owut flow (#1415)

* feat(topology): fan edge units' clients toward the open side of the canvas (#1416)

* fix(alerts): seed impostor own-bssids from fleet macs and radio derivatives (#1402)

* feat(firmware): per-unit method selector, stepped owut flow and local image upload (#1414)

* feat(firmware): upload config backups to the server with retention (#1414); agent 3.0.18
Nacho 1 ماه پیش
والد
کامیت
6d3a78016a

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.17
+3.0.18

+ 33 - 0
agent/runtime/firmware.go

@@ -82,6 +82,12 @@ func handleFirmwareUpgrade(opts Options, transport http.RoundTripper, data strin
 		reportFirmwareResult(opts, transport, cmd.UpgradeID, false, err.Error(), "", "")
 		return
 	}
+	// #1414: el backup también se sube al server (persistencia real: el /tmp
+	// local no sobrevive al reboot del flash). Best-effort: si falla, el
+	// upgrade continúa con el backup local.
+	if err := uploadBackup(opts, transport, backupPath); err != nil {
+		log.Warn("[netpulse-agent] firmware_upgrade: subida del backup al server falló (continúo)", "err", err)
+	}
 
 	if err := writePendingFirmware(pendingFirmware{UpgradeID: cmd.UpgradeID}); err != nil {
 		log.Error("[netpulse-agent] firmware_upgrade: no se pudo escribir pending", "err", err)
@@ -207,6 +213,33 @@ func currentOpenWrtVersion() string {
 	return strings.TrimSpace(string(out))
 }
 
+// uploadBackup (#1414) envía el backup de config al server para que lo
+// persista con retención (el /tmp del router se pierde en el reboot del
+// flash). POST crudo con Bearer, mismo contrato que firmware-progress.
+func uploadBackup(opts Options, transport http.RoundTripper, path string) error {
+	f, err := os.Open(path)
+	if err != nil {
+		return err
+	}
+	defer f.Close()
+	req, err := http.NewRequest("POST", opts.Server+"/api/agents/"+opts.Slug+"/firmware-backup", f)
+	if err != nil {
+		return err
+	}
+	req.Header.Set("Content-Type", "application/gzip")
+	req.Header.Set("Authorization", "Bearer "+opts.Token)
+	hc := &http.Client{Transport: transport, Timeout: 60 * time.Second}
+	resp, err := hc.Do(req)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode >= 300 {
+		return fmt.Errorf("status %d", resp.StatusCode)
+	}
+	return nil
+}
+
 func reportFirmwareProgress(opts Options, transport http.RoundTripper, upgradeID int64, status string, percent int, message string) {
 	m := map[string]any{
 		"upgradeId": upgradeID,

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

@@ -57,7 +57,7 @@
     "resolvesTitle_other": "Resolves {{count}} events",
     "configButton": "Configure alerts",
     "configTitle": "Alert settings",
-    "configDescription": "Choose which events are kept in your history and counted on the bell, per category.",
+    "configDescription": "Every event is kept in your history and counted on the bell. Choose what notifies you, per category.",
     "configSaved": "Saved",
     "configSaveError": "Could not save — please try again",
     "categories": {
@@ -293,6 +293,10 @@
       "snmp-recovered": {
         "title": "SNMP polling recovered on {{router}}",
         "description": "SNMP polling for {{router}} is responding again"
+      },
+      "firmware-downgrade-target": {
+        "title": "Firmware downgrade target",
+        "description": "{{router}}: the configured target \"{{target}}\" is older than the installed firmware \"{{firmware}}\""
       }
     },
     "viewDevice": "View device",
@@ -2265,7 +2269,25 @@
     "successTitle": "Upgrade completed!",
     "successBody": "The router is now on {{to}} in {{dur}} s: it rebooted and came back on its own, packages up to date. If you excluded a stack package, check its service is still running.",
     "successDismiss": "Got it",
-    "compatibleNote": "Only vanilla OpenWrt devices are shown; GL.iNet updates via its own channel."
+    "compatibleNote": "Only vanilla OpenWrt devices are shown; GL.iNet updates via its own channel.",
+    "method": "Upgrade method",
+    "methodAuto": "Auto (show everything)",
+    "methodOwut": "owut (ASU)",
+    "methodUrl": "Image URL",
+    "methodUpload": "Local upload",
+    "uploadTitle": "Upload an image",
+    "uploadHint": "Build an image with the OpenWrt ASU wizard (or download one) and upload it here. NetPulse stores it on the server and flashes it with a verified checksum.",
+    "uploadBusy": "Uploading...",
+    "uploadedInfo": "Uploaded: {{name}} ({{size}} MB). Click Upgrade now to flash it.",
+    "uploadedSaved": "An uploaded image is saved as the upgrade target. Click Upgrade now to flash it.",
+    "checkTooltip": "Runs 'owut check' on the router: what an upgrade would change, without changing anything",
+    "owutDownload": "Download image",
+    "owutDownloading": "Building and downloading...",
+    "owutDownloadOutput": "owut download output",
+    "owutInstallImage": "Install downloaded image",
+    "backupsTitle": "Config backups on the server",
+    "backupsEmpty": "No backups yet. One is uploaded automatically before each flash.",
+    "backupsDownload": "Download"
   },
   "orchestration": {
     "title": "Orchestration",

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

@@ -57,7 +57,7 @@
     "resolvesTitle_other": "Resuelve {{count}} eventos",
     "configButton": "Configurar alertas",
     "configTitle": "Configuración de alertas",
-    "configDescription": "Elige qué eventos entran en tu historial y cuentan en la campana, por categoría.",
+    "configDescription": "Todos los eventos quedan en tu historial y cuentan en la campana. Elige qué te notifica, por categoría.",
     "configSaved": "Guardado",
     "configSaveError": "No se pudo guardar — inténtalo de nuevo",
     "categories": {
@@ -293,6 +293,10 @@
       "snmp-recovered": {
         "title": "Sondeo SNMP recuperado en {{router}}",
         "description": "{{router}} vuelve a responder al sondeo SNMP"
+      },
+      "firmware-downgrade-target": {
+        "title": "Target de firmware inferior",
+        "description": "{{router}}: el target configurado \"{{target}}\" es más viejo que el firmware instalado \"{{firmware}}\""
       }
     },
     "viewDevice": "Ver dispositivo",
@@ -2265,7 +2269,25 @@
     "successTitle": "¡Actualización completada!",
     "successBody": "El router quedó en {{to}} en {{dur}} s: reinició y volvió solo, con los paquetes al día. Si excluiste algún paquete del stack, comprueba que su servicio sigue activo.",
     "successDismiss": "Entendido",
-    "compatibleNote": "Solo se muestran dispositivos con OpenWrt; los GL.iNet se actualizan por su propia vía."
+    "compatibleNote": "Solo se muestran dispositivos con OpenWrt; los GL.iNet se actualizan por su propia vía.",
+    "method": "Método de actualización",
+    "methodAuto": "Auto (mostrar todo)",
+    "methodOwut": "owut (ASU)",
+    "methodUrl": "URL de imagen",
+    "methodUpload": "Subida local",
+    "uploadTitle": "Subir una imagen",
+    "uploadHint": "Construye la imagen con el asistente ASU de OpenWrt (o descárgatela) y súbela aquí. NetPulse la guarda en el servidor y la flashea con checksum verificado.",
+    "uploadBusy": "Subiendo...",
+    "uploadedInfo": "Subida: {{name}} ({{size}} MB). Pulsa Actualizar ahora para flashearla.",
+    "uploadedSaved": "Hay una imagen subida guardada como objetivo. Pulsa Actualizar ahora para flashearla.",
+    "checkTooltip": "Ejecuta 'owut check' en el router: qué cambiaría una actualización sin cambiar nada",
+    "owutDownload": "Descargar imagen",
+    "owutDownloading": "Construyendo y descargando...",
+    "owutDownloadOutput": "salida de owut download",
+    "owutInstallImage": "Instalar imagen descargada",
+    "backupsTitle": "Copias de configuración en el servidor",
+    "backupsEmpty": "Todavía no hay copias. Se sube una automáticamente antes de cada flasheo.",
+    "backupsDownload": "Descargar"
   },
   "orchestration": {
     "title": "Orquestación",

+ 16 - 2
app/src/components/topology/model.ts

@@ -493,14 +493,28 @@ function ringLayoutCount<T extends { x: number; y: number; size?: number }>(
   const free = freeArcs(excludes)
   const totalFree = free.reduce((a, [s, e]) => a + (e - s), 0)
   if (totalFree <= 0) return 0
+  // #1416: unidad pegada a un borde lateral del lienzo → rellenar primero
+  // los arcos que apuntan hacia DENTRO (el lado con más sitio). Los chips de
+  // los arcos exteriores caen fuera del viewport y ensuciaban el centro del
+  // diagrama. El hint es el ángulo cardinal de ese lado; los arcos se
+  // reordenan por distancia angular de su punto medio al hint (los de su
+  // lado primero; orden estable en el resto). Unidades centradas: sin
+  // cambio (sideHint null conserva el orden documental 0°→360°).
+  const sideHint = node.x < VB_W / 3 ? 0 : node.x > (2 * VB_W) / 3 ? 180 : null
+  const arcMid = ([s, e]: [number, number]) => norm(s + (e - s) / 2)
+  const angDist = (a: number, b: number) => {
+    const d = norm(a - b)
+    return Math.min(d, 360 - d)
+  }
+  const fillArcs = sideHint === null ? free : [...free].sort((x, y) => angDist(arcMid(x), sideHint) - angDist(arcMid(y), sideHint))
   let idx = 0
   for (const ring of rings) {
     if (idx >= items.length) break
     const chipSize = items[idx]?.size ?? 24
     const minArcDeg = ((chipSize + CHIP_GAP) * 180) / (Math.PI * ring.r)
     let ringPlaced = 0
-    for (let ai = 0; ai < free.length && ringPlaced < ring.cap && idx < items.length; ai++) {
-      const [s, e] = free[ai]!
+    for (let ai = 0; ai < fillArcs.length && ringPlaced < ring.cap && idx < items.length; ai++) {
+      const [s, e] = fillArcs[ai]!
       const arcLen = e - s
       const maxFit = Math.max(1, Math.floor(arcLen / minArcDeg))
       const remaining = items.length - idx

+ 221 - 13
app/src/pages/FirmwareUpgrades.tsx

@@ -42,6 +42,8 @@ interface FirmwareItem {
   targetVersion: string
   targetUrl: string
   checksum: string
+  /** Método preferido de la tarjeta (#1414): auto/owut/url/upload. */
+  method?: string
   detectedModel?: string
   detectedBoard?: string
   detectedVersion?: string
@@ -140,6 +142,28 @@ export default function FirmwareUpgrades() {
   const [owutResult, setOwutResult] = useState<Record<string, OwutStatus>>({})
   // #761: versiones para el desplegable e instalación de owut.
   const [owutVersions, setOwutVersions] = useState<Record<string, OwutVersionsResp>>({})
+  // #1414: pasos owut por pasos (download) y subida de imagen local.
+  const [owutDlBusy, setOwutDlBusy] = useState<Record<string, boolean>>({})
+  const [owutDlOutput, setOwutDlOutput] = useState<Record<string, string>>({})
+  const [uploadBusy, setUploadBusy] = useState<Record<string, boolean>>({})
+  const [uploadInfo, setUploadInfo] = useState<Record<string, { name: string; size: number; checksum: string }>>({})
+  // #1414: backups de config en el server (lista perezosa por tarjeta).
+  const [fwBackups, setFwBackups] = useState<Record<string, { name: string; size: number; ts: number }[]>>({})
+  const [fwBackupsLoaded, setFwBackupsLoaded] = useState<Record<string, boolean>>({})
+
+  const loadFwBackups = async (id: string) => {
+    if (fwBackupsLoaded[id]) return
+    setFwBackupsLoaded((prev) => ({ ...prev, [id]: true }))
+    try {
+      const res = await fetch(`/api/firmware-backups/${encodeURIComponent(id)}`)
+      if (!res.ok) return
+      const body = (await res.json()) as { name: string; size: number; ts: number }[]
+      setFwBackups((prev) => ({ ...prev, [id]: body }))
+    } catch {
+      /* el bloque queda vacío; se reintenta al replegar de nuevo */
+      setFwBackupsLoaded((prev) => ({ ...prev, [id]: false }))
+    }
+  }
   const [versionsBusy, setVersionsBusy] = useState<Record<string, boolean>>({})
   const [installBusy, setInstallBusy] = useState<Record<string, boolean>>({})
   const [owutConfirmId, setOwutConfirmId] = useState<string | null>(null)
@@ -439,6 +463,80 @@ export default function FirmwareUpgrades() {
     }
   }
 
+  // #1414: método preferido de la tarjeta (selector auto/owut/url/upload).
+  const setMethod = async (id: string, method: string) => {
+    try {
+      const res = await fetch(`/api/firmware-upgrades/${encodeURIComponent(id)}/method`, {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ method }),
+      })
+      const body = await res.json().catch(() => ({}))
+      if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
+      await fetchItems()
+    } catch (err) {
+      setError(String(err))
+    }
+  }
+
+  // #1414: subir una imagen desde local. El server la guarda, calcula el
+  // sha256 y la deja como target del flujo clásico (URL servida por el
+  // propio server, alcanzable por el agente).
+  const uploadImage = async (id: string, file: File) => {
+    setUploadBusy((prev) => ({ ...prev, [id]: true }))
+    setError('')
+    try {
+      const fd = new FormData()
+      fd.append('image', file)
+      const res = await fetch(`/api/firmware-upgrades/${encodeURIComponent(id)}/image`, { method: 'POST', body: fd })
+      const body = await res.json().catch(() => ({}))
+      if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
+      setUploadInfo((prev) => ({ ...prev, [id]: { name: body.name ?? file.name, size: body.size ?? file.size, checksum: body.checksum ?? '' } }))
+      await fetchItems()
+    } catch (err) {
+      setError(String(err))
+    } finally {
+      setUploadBusy((prev) => ({ ...prev, [id]: false }))
+    }
+  }
+
+  // #1414: paso intermedio del flujo owut por pasos: construye y descarga la
+  // imagen en el router SIN flashear, para revisar antes de instalar.
+  const runOwutDownload = async (id: string) => {
+    const e = edits[id]
+    setOwutDlBusy((prev) => ({ ...prev, [id]: true }))
+    setError('')
+    try {
+      const res = await fetch(`/api/firmware-upgrades/${encodeURIComponent(id)}/owut-download`, {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ targetVersion: e?.targetVersion ?? '' }),
+      })
+      const body = await res.json().catch(() => ({}))
+      if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
+      setOwutDlOutput((prev) => ({ ...prev, [id]: String(body.output ?? '') }))
+    } catch (err) {
+      setError(String(err))
+    } finally {
+      setOwutDlBusy((prev) => ({ ...prev, [id]: false }))
+    }
+  }
+
+  // #1414: paso final del flujo owut por pasos: flashea la imagen descargada.
+  const runOwutInstallImage = async (id: string) => {
+    setBusy((prev) => ({ ...prev, [id]: 'upgrade' }))
+    try {
+      const res = await fetch(`/api/firmware-upgrades/${encodeURIComponent(id)}/owut-install-image`, { method: 'POST' })
+      const body = await res.json().catch(() => ({}))
+      if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `HTTP ${res.status}`)
+      await fetchItems()
+    } catch (err) {
+      setError(String(err))
+    } finally {
+      setBusy((prev) => ({ ...prev, [id]: '' }))
+    }
+  }
+
   // #761: guardar la programación recurrente (una vez / semanal / mensual).
   const saveRecurrence = async (id: string) => {
     setError('')
@@ -587,6 +685,11 @@ export default function FirmwareUpgrades() {
           const detectedModel = item.detectedBoard || item.detectedModel || ''
           const rec = recurrence[item.routerId]
           const targetSel = e.targetVersion ?? ''
+          // #1414: método de la tarjeta. auto = comportamiento actual (owut y
+          // URL visibles a la vez).
+          const m = item.method || 'auto'
+          const uploaded = uploadInfo[item.routerId]
+          const hasUploadedImage = (item.targetUrl ?? '').includes('/api/firmware-image/') || !!uploaded
           const majorWarn = majorJumpJS(detectedCurrent, targetSel)
           // Opciones del desplegable (#761): la instalada + superiores (si
           // las hubiera) + el target ya guardado (downgrade explícito previo).
@@ -751,6 +854,21 @@ export default function FirmwareUpgrades() {
                 )}
               </div>
 
+              <div className="mt-3 flex flex-wrap items-center gap-2">
+                <span className="text-caption text-text-muted">{t('firmwareUpgrades.method')}</span>
+                <select
+                  value={m}
+                  onChange={(ev) => void setMethod(item.routerId, ev.target.value)}
+                  disabled={!isAdmin}
+                  className="rounded-lg border border-border bg-canvas px-2.5 py-1.5 text-xs font-medium text-text-primary disabled:opacity-60"
+                >
+                  <option value="auto">{t('firmwareUpgrades.methodAuto')}</option>
+                  <option value="owut">{t('firmwareUpgrades.methodOwut')}</option>
+                  <option value="url">{t('firmwareUpgrades.methodUrl')}</option>
+                  <option value="upload">{t('firmwareUpgrades.methodUpload')}</option>
+                </select>
+              </div>
+
               <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                 <label className="flex flex-col gap-1">
                   <span className="text-caption text-text-muted">{t('firmwareUpgrades.model')} *</span>
@@ -818,7 +936,7 @@ export default function FirmwareUpgrades() {
                 </div>
               )}
 
-              {!vendorFw && (
+              {!vendorFw && (m === 'auto' || m === 'url') && (
               <details className="mt-3 rounded-lg border border-border bg-canvas px-3 py-2">
                 <summary className="cursor-pointer text-sm font-medium text-text-secondary">
                   {t('firmwareUpgrades.advanced')}
@@ -863,27 +981,27 @@ export default function FirmwareUpgrades() {
               </details>
               )}
 
-              {!active && owut && (
+              {!active && (m === 'auto' || m === 'owut') && (owut || owutDlOutput[item.routerId]) && (
                 <div className="mt-3 space-y-2">
-                  {owut.error && (
+                  {owut?.error && (
                     <div className="flex items-start gap-2 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-600 dark:text-rose-400">
                       <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
                       <span>{t('firmwareUpgrades.owutCheckFailed')}</span>
                     </div>
                   )}
-                  {owut.checkRan && owut.buildable && owut.upgradeAvailable && (
+                  {owut?.checkRan && owut.buildable && owut.upgradeAvailable && (
                     <div className="flex items-start gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/10 px-3 py-2.5 text-sm text-emerald-700 dark:text-emerald-300">
                       <ShieldCheck className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
                       <span>{t('firmwareUpgrades.owutUpgradeAvailable')}</span>
                     </div>
                   )}
-                  {owut.checkRan && owut.buildable && !owut.upgradeAvailable && (
+                  {owut?.checkRan && owut.buildable && !owut.upgradeAvailable && (
                     <div className="flex items-start gap-2 rounded-lg border border-border bg-canvas px-3 py-2.5 text-sm text-text-secondary">
                       <ShieldCheck className="mt-0.5 h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
                       <span>{t('firmwareUpgrades.owutUpToDate')}</span>
                     </div>
                   )}
-                  {owut.checkRan && !owut.buildable && (
+                  {owut?.checkRan && !owut.buildable && (
                     <div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-sm text-amber-700 dark:text-amber-300">
                       <TriangleAlert className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
                       <span>
@@ -895,7 +1013,7 @@ export default function FirmwareUpgrades() {
                       </span>
                     </div>
                   )}
-                  {owut.rawOutput && (
+                  {owut?.rawOutput && (
                     <details className="rounded-lg border border-border bg-canvas px-3 py-2">
                       <summary className="cursor-pointer text-sm font-medium text-text-secondary">
                         {t('firmwareUpgrades.owutOutput')}
@@ -905,11 +1023,77 @@ export default function FirmwareUpgrades() {
                       </pre>
                     </details>
                   )}
+                  {owutDlOutput[item.routerId] && (
+                    <details className="rounded-lg border border-border bg-canvas px-3 py-2">
+                      <summary className="cursor-pointer text-sm font-medium text-text-secondary">
+                        {t('firmwareUpgrades.owutDownloadOutput')}
+                      </summary>
+                      <pre className="mt-2 overflow-x-auto whitespace-pre-wrap break-all font-mono text-xs leading-relaxed text-text-secondary">
+                        {owutDlOutput[item.routerId]}
+                      </pre>
+                    </details>
+                  )}
+                </div>
+              )}
+
+              {!vendorFw && m === 'upload' && (
+                <div className="mt-3 rounded-lg border border-border bg-canvas px-3 py-2.5">
+                  <p className="text-sm font-medium text-text-secondary">{t('firmwareUpgrades.uploadTitle')}</p>
+                  <p className="mt-0.5 text-xs text-text-muted">{t('firmwareUpgrades.uploadHint')}</p>
+                  <div className="mt-2 flex flex-wrap items-center gap-2">
+                    <input
+                      type="file"
+                      accept=".bin,application/octet-stream"
+                      disabled={!isAdmin || uploadBusy[item.routerId]}
+                      onChange={(ev) => {
+                        const f = ev.target.files?.[0]
+                        if (f) void uploadImage(item.routerId, f)
+                        ev.target.value = ''
+                      }}
+                      className="text-xs text-text-secondary file:mr-2 file:rounded-lg file:border file:border-border file:bg-elevated file:px-3 file:py-1.5 file:text-xs file:font-medium file:text-text-primary"
+                    />
+                    {uploadBusy[item.routerId] && <span className="text-xs text-text-muted">{t('firmwareUpgrades.uploadBusy')}</span>}
+                  </div>
+                  {hasUploadedImage && (
+                    <p className="mt-2 text-xs text-emerald-700 dark:text-emerald-300">
+                      {uploaded
+                        ? t('firmwareUpgrades.uploadedInfo', { name: uploaded.name, size: Math.round((uploaded.size / 1024 / 1024) * 10) / 10 })
+                        : t('firmwareUpgrades.uploadedSaved')}
+                    </p>
+                  )}
                 </div>
               )}
 
-              {item.upgrade?.error && (
-                <div className="mt-4 flex items-center justify-between gap-3 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-600 dark:text-rose-400">
+              <details
+                className="mt-3 rounded-lg border border-border bg-canvas px-3 py-2"
+                onToggle={(ev) => {
+                  if ((ev.target as HTMLDetailsElement).open) void loadFwBackups(item.routerId)
+                }}
+              >
+                <summary className="cursor-pointer text-sm font-medium text-text-secondary">
+                  {t('firmwareUpgrades.backupsTitle')}
+                </summary>
+                <ul className="mt-2 space-y-1">
+                  {(fwBackups[item.routerId] ?? []).length === 0 && (
+                    <li className="text-xs text-text-muted">{t('firmwareUpgrades.backupsEmpty')}</li>
+                  )}
+                  {(fwBackups[item.routerId] ?? []).map((b) => (
+                    <li key={b.name} className="flex items-center justify-between gap-2 text-xs">
+                      <span className="truncate text-text-secondary">
+                        {new Date(b.ts * 1000).toLocaleString()} · {Math.round((b.size / 1024) * 10) / 10} KB
+                      </span>
+                      <a
+                        href={`/api/firmware-backups/${encodeURIComponent(item.routerId)}/file?name=${encodeURIComponent(b.name)}`}
+                        className="shrink-0 font-medium text-accent hover:underline"
+                      >
+                        {t('firmwareUpgrades.backupsDownload')}
+                      </a>
+                    </li>
+                  ))}
+                </ul>
+              </details>
+
+              {item.upgrade?.error && (                <div className="mt-4 flex items-center justify-between gap-3 rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-sm text-rose-600 dark:text-rose-400">
                   {/* Timestamp del fallo: un error antiguo NO debe leerse como
                       estado presente del agente (feedback #477). */}
                   <span>
@@ -932,7 +1116,7 @@ export default function FirmwareUpgrades() {
               {isAdmin && !vendorFw && (
                 <div className="mt-4 space-y-3 border-t border-border pt-3">
                   <div className="flex flex-wrap items-center gap-3">
-                    {!owutAvail && versions !== undefined && (
+                    {(m === 'auto' || m === 'owut') && !owutAvail && versions !== undefined && (
                       <button
                         type="button"
                         onClick={() => void installOwut(item.routerId)}
@@ -943,16 +1127,40 @@ export default function FirmwareUpgrades() {
                         {installBusy[item.routerId] ? t('firmwareUpgrades.installingOwut') : t('firmwareUpgrades.installOwut')}
                       </button>
                     )}
+                    {(m === 'auto' || m === 'owut') && (
                     <button
                       type="button"
                       onClick={() => void runOwutCheck(item.routerId)}
                       disabled={owutBusy[item.routerId] || !owutAvail}
-                      title={!owutAvail ? t('firmwareUpgrades.owutUnavailable') : undefined}
+                      title={!owutAvail ? t('firmwareUpgrades.owutUnavailable') : t('firmwareUpgrades.checkTooltip')}
                       className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                     >
                       <Terminal className={cn('h-4 w-4', owutBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
                       {owutBusy[item.routerId] ? t('firmwareUpgrades.owutBusy') : t('firmwareUpgrades.check')}
                     </button>
+                    )}
+                    {(m === 'auto' || m === 'owut') && owutAvail && (
+                      <>
+                        <button
+                          type="button"
+                          onClick={() => void runOwutDownload(item.routerId)}
+                          disabled={owutDlBusy[item.routerId] || !!active}
+                          className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
+                        >
+                          <Download className={cn('h-4 w-4', owutDlBusy[item.routerId] && 'animate-pulse')} strokeWidth={1.75} />
+                          {owutDlBusy[item.routerId] ? t('firmwareUpgrades.owutDownloading') : t('firmwareUpgrades.owutDownload')}
+                        </button>
+                        <button
+                          type="button"
+                          onClick={() => void runOwutInstallImage(item.routerId)}
+                          disabled={!!active || busy[item.routerId] === 'upgrade' || scheduled}
+                          className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
+                        >
+                          <Rocket className="h-4 w-4" strokeWidth={1.75} />
+                          {t('firmwareUpgrades.owutInstallImage')}
+                        </button>
+                      </>
+                    )}
                     <button
                       onClick={() => saveTarget(item.routerId)}
                       disabled={busy[item.routerId] === 'save' || !e.targetVersion || !e.model}
@@ -962,7 +1170,7 @@ export default function FirmwareUpgrades() {
                     </button>
                     <button
                       onClick={() => {
-                        if (owutAvail) {
+                        if (owutAvail && (m === 'auto' || m === 'owut')) {
                           const missing = owut?.missingPkgs ?? []
                           if (missing.length && !(removePkgs[item.routerId] ?? '').trim()) {
                             setRemovePkgs((prev) => ({ ...prev, [item.routerId]: missing.join(' ') }))
@@ -972,7 +1180,7 @@ export default function FirmwareUpgrades() {
                           setConfirmId(item.routerId)
                         }
                       }}
-                      disabled={active || busy[item.routerId] === 'upgrade' || scheduled || !targetSel}
+                      disabled={active || busy[item.routerId] === 'upgrade' || scheduled || (!targetSel && !(m === 'upload' && hasUploadedImage))}
                       className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-elevated px-4 text-sm font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
                     >
                       {active

+ 16 - 7
docs/manual.en.md

@@ -275,7 +275,7 @@ The map is built from the bridge FDB (for wired clients), LLDP when available (t
 ### What it shows
 
 - **Summary**: three counters (unread warnings, alerts today, critical) with a per-cause breakdown.
-- **Alert configuration**: per category, the desired level (Urgent only / All / None) and a custom rules manager.
+- **Alert configuration**: per category, the notification level (Urgent only / All / None) and a custom rules manager. Every event is always kept in the log regardless of the level; the level only controls what notifies you.
 - **Filters**: by severity, by kind, by category and "Unread only".
 - **Timeline feed** grouped by day, with severity by color and expandable context (a sparkline with a threshold line, or the WireGuard peer / affected device data).
 
@@ -292,14 +292,14 @@ Alerts are generated by the server from what it already monitors: temperature, a
 
 ### Design decisions
 
-- Configuration is **per category and per level**, not per alert: you can silence the whole "Clients" category without touching the rest.
+- Configuration is **per category and per level**, not per alert: the level is a notification policy (None / Urgent only / All). Events below the level are still recorded in the log and the feed; use the feed's category filters to hide them visually.
 - You can **silence** a specific alert for 1 hour, 24 hours or forever.
 - The **feed uses simulated infinite scroll**: reaching the bottom shows the end of history.
 
 ### Procedure: configure which alerts you want
 
 1. Open **Alerts** and click **Configuration**.
-2. For each category (Router, Internet, Clients, Signal, VPN, System) choose the level: **Urgent only**, **All** or **None**.
+2. For each category (Router, Internet, Clients, Signal, VPN, System) choose the notification level: **Urgent only**, **All** or **None**. All events are kept in the log and counted on the bell either way; the level only decides what pushes a notification.
 3. If you need custom rules (custom thresholds), use the **rules** manager at the bottom of the panel.
 4. Changes save instantly (you will see the confirmation).
 
@@ -393,15 +393,24 @@ The plan is computed from each radio's **neighbor scans**. There is a key differ
 
 ## Firmware upgrades
 
-**Route:** `/firmware-upgrades`. UI title: **Firmware upgrades**. Marked "labs" and admin only.
+**Route:** `/firmware-upgrades`. UI title: **Firmware upgrades**. Admin only.
 
 ### What it shows
 
-One card per router with the upgrade target fields (current version, target version, model/target, image URL, SHA256 checksum), the status of the last attempt and the actions to upgrade now or schedule.
+One card per router with the upgrade target fields (current version, target version, model/target, image URL, SHA256 checksum), the status of the last attempt and the actions to upgrade now or schedule. On top:
+
+- **Refresh**: re-reads the list of upgrades and their status from the server. It does not probe the routers by itself; while an upgrade is running the page auto-refreshes on its own.
+- **Detect image** (in the URL section): resolves the download URL of the official OpenWrt image from the "Detected system" the agent reports (board, target, version) for the target version you wrote. It fills model/target and URL for you; the checksum still has to be pasted.
+- **Check** (the terminal button, per unit): runs `owut check` on that router and shows whether the ASU server can build an upgrade image. It needs owut installed on the unit (the page offers the install when missing).
+
+The **target version** dropdown is populated from the versions the unit's own owut reports; without owut, the field is free text and nothing auto-fills it.
 
 ### What data it needs
 
-It is a managed flow: you must provide the OpenWrt image URL, the model/target and, recommended, the SHA256 checksum. The agent detects the router's system (model, board, version, target) and shows it as "Detected system" to help you fill the fields.
+Two engines, chosen per upgrade:
+
+- **URL + checksum**: you provide the OpenWrt image URL, the model/target and, recommended, the SHA256 checksum. The agent detects the router's system (model, board, version, target) and shows it as "Detected system" to help you fill the fields.
+- **owut (ASU)**: the unit runs owut against the OpenWrt attended-sysupgrade server. Use **Check** to review what would be built, **Install owut** if the unit does not have it, and **Upgrade now** to build, download and flash the image with your installed packages.
 
 ### How to read it
 
@@ -412,7 +421,7 @@ It is a managed flow: you must provide the OpenWrt image URL, the model/target a
 ### Design decisions
 
 - **Verify before flashing**: if there is a checksum and it does not match, the upgrade stops and the router is left untouched. Without a checksum, it flashes without verifying (you are warned).
-- **Automatic backup** of the config before flashing.
+- **Automatic backup** of the config before flashing (`sysupgrade -b`). The backup is written to the router's own `/tmp` and its path is reported with the result; grab it before a reboot if you want to keep it, because `/tmp` does not survive one. The server does not copy it.
 - You can **schedule** an unattended upgrade at a specific local time (and cancel it before it starts).
 - The target that gets flashed is the **saved** one, not the one you are mid-editing (the modal summarizes exactly what will be flashed).
 

+ 16 - 7
docs/manual.es.md

@@ -275,7 +275,7 @@ El mapa se construye con el bridge FDB (para clientes por cable), LLDP cuando es
 ### Qué muestra
 
 - **Resumen**: tres contadores (avisos sin leer, alertas de hoy, críticos) con un desglose por causa.
-- **Configuración de alertas**: por categoría, el nivel deseado (Solo urgentes / Todo / Nada) y un gestor de reglas personalizadas.
+- **Configuración de alertas**: por categoría, el nivel de notificación (Solo urgentes / Todo / Nada) y un gestor de reglas personalizadas. Todos los eventos se guardan siempre en el registro, con cualquier nivel; el nivel solo controla qué te notifica.
 - **Filtros**: por severidad, por tipo, por categoría y "Solo no leídas".
 - **Feed en línea de tiempo** agrupado por día, con severidad por color y contexto expandible (minigráfica con umbral, datos del peer WireGuard o del dispositivo afectado).
 
@@ -292,14 +292,14 @@ Las alertas las genera el servidor a partir de lo que ya monitoriza: temperatura
 
 ### Decisiones de diseño
 
-- La configuración es **por categoría y por nivel**, no alerta a alerta: puedes silenciar toda la categoría "Clientes" sin tocar el resto.
+- La configuración es **por categoría y por nivel**, no alerta a alerta: el nivel es una política de notificación (Nada / Solo urgentes / Todo). Los eventos por debajo del nivel siguen registrándose en el log y el feed; para ocultarlos visualmente usa los filtros de categoría del feed.
 - Puedes **silenciar** una alerta concreta 1 hora, 24 horas o para siempre.
 - El **feed usa scroll infinito simulado**: al llegar abajo se muestra el fin del historial.
 
 ### Procedimiento: configurar qué alertas quieres
 
 1. Abre **Alertas** y pulsa **Configuración**.
-2. Para cada categoría (Router, Internet, Clientes, Señal, VPN, Sistema) elige el nivel: **Solo urgentes**, **Todo** o **Nada**.
+2. Para cada categoría (Router, Internet, Clientes, Señal, VPN, Sistema) elige el nivel de notificación: **Solo urgentes**, **Todo** o **Nada**. Con cualquier nivel todos los eventos quedan en el registro y cuentan en la campana; el nivel solo decide cuál envía notificación.
 3. Si necesitas reglas propias (umbrales a medida), usa el gestor de **reglas** al final del panel.
 4. Los cambios se guardan al instante (verás la confirmación).
 
@@ -393,15 +393,24 @@ El plan se calcula con los **scans de vecinos** de cada radio. Aquí hay una dif
 
 ## Actualizaciones de firmware
 
-**Ruta:** `/firmware-upgrades`. Título en la interfaz: **Actualizaciones de firmware**. Marca "labs" y solo administradores.
+**Ruta:** `/firmware-upgrades`. Título en la interfaz: **Actualizaciones de firmware**. Solo administradores.
 
 ### Qué muestra
 
-Una tarjeta por router con los campos del objetivo de actualización (versión actual, versión objetivo, modelo/target, URL de la imagen, checksum SHA256), el estado del último intento y las acciones de actualizar ahora o programar.
+Una tarjeta por router con los campos del objetivo de actualización (versión actual, versión objetivo, modelo/target, URL de la imagen, checksum SHA256), el estado del último intento y las acciones de actualizar ahora o programar. En la parte superior:
+
+- **Refrescar**: vuelve a leer la lista de actualizaciones y sus estados desde el servidor. No sonda los routers por sí mismo; mientras hay una actualización en curso, la página se auto-refresca sola.
+- **Detectar imagen** (en la sección de URL): resuelve la URL de descarga de la imagen oficial de OpenWrt a partir del "Sistema detectado" que reporta el agente (placa, target, versión) para la versión objetivo que hayas escrito. Rellena modelo/target y URL; el checksum sigue teniendo que pegarlo tú.
+- **Comprobar** (el botón de terminal, por unidad): ejecuta `owut check` en ese router y muestra si el servidor ASU puede construir la imagen de actualización. Necesita owut instalado en la unidad (la página ofrece instalarlo si falta).
+
+El desplegable de **versión objetivo** se rellena con las versiones que reporta el propio owut de la unidad; sin owut, el campo es texto libre y nada lo rellena automáticamente.
 
 ### Qué datos necesita
 
-Es un flujo administrado: hay que indicar la URL de la imagen OpenWrt, el modelo/target y, recomendablemente, el checksum SHA256. El agente detecta el sistema del router (modelo, placa, versión, target) y lo muestra como "Sistema detectado" para ayudarte a rellenar los campos.
+Dos motores, elegidos por actualización:
+
+- **URL + checksum**: indicas la URL de la imagen OpenWrt, el modelo/target y, recomendablemente, el checksum SHA256. El agente detecta el sistema del router (modelo, placa, versión, target) y lo muestra como "Sistema detectado" para ayudarte a rellenar los campos.
+- **owut (ASU)**: la unidad ejecuta owut contra el servidor attended-sysupgrade de OpenWrt. Usa **Comprobar** para revisar qué se construiría, **Instalar owut** si la unidad no lo tiene, y **Actualizar ahora** para construir, descargar y flashear la imagen con tus paquetes instalados.
 
 ### Cómo leerlo
 
@@ -412,7 +421,7 @@ Es un flujo administrado: hay que indicar la URL de la imagen OpenWrt, el modelo
 ### Decisiones de diseño
 
 - **Verificación antes de flashear**: si hay checksum y no coincide, la actualización se detiene y el router no se toca. Sin checksum, flashea sin verificar (se te avisa).
-- **Respaldo automático** de la configuración antes de flashear.
+- **Respaldo automático** de la configuración antes de flashear (`sysupgrade -b`). La copia se escribe en el `/tmp` del propio router y su ruta se reporta con el resultado; descárgatela antes de un reinicio si quieres conservarla, porque `/tmp` no sobrevive a uno. El servidor no la copia.
 - Se puede **programar** una actualización desatendida a una hora local concreta (y cancelarla antes de que arranque).
 - El objetivo que se flashea es el **guardado**, no el que tienes a medio editar (el modal resume exactamente lo que se va a flashear).
 

+ 12 - 7
server-go/internal/adapters/alerts_live_test.go

@@ -83,24 +83,29 @@ func liveTestLive() *Live {
 
 func TestLiveRouterRecoveredTaxonomy(t *testing.T) {
 	l := liveTestLive()
-	// Con el default router:urgent el evento (urgent=false) se filtra EN
-	// CREACIÓN (semántica SPEC §2): es lo esperado.
+	// Semántica #1413: la config ya no filtra la ingesta, así que con el
+	// default router:urgent el evento (urgent=false) SE GUARDA igual.
 	l.mu.Lock()
 	l.emitRouterRecovered("patio", "Patio")
 	l.mu.Unlock()
-	if len(l.engine.List()) != 0 {
-		t.Fatal("con router:urgent, 'recuperado' (no urgente) debía filtrarse")
+	list := l.engine.List()
+	if len(list) != 1 {
+		t.Fatalf("alertas: %d, esperaba 1 (la ingesta ya no se filtra)", len(list))
 	}
-	// Con router:all pasa, con la taxonomía exacta del SPEC §1.
+	if a := list[0]; a.Category != alerts.CatRouter || a.Urgent || a.Severity != "ok" {
+		t.Fatalf("recuperado: (%s,%v,%s), esperaba (router,false,ok)", a.Category, a.Urgent, a.Severity)
+	}
+	// Con router:all la taxonomía es la misma (no cambia la ingesta, solo la
+	// notificación; el SPEC §1 se cumple en ambos niveles).
 	if err := l.engine.SetConfig(map[string]string{"router": "all"}); err != nil {
 		t.Fatal(err)
 	}
 	l.mu.Lock()
 	l.emitRouterRecovered("patio", "Patio")
 	l.mu.Unlock()
-	list := l.engine.List()
+	list = l.engine.List()
 	if len(list) != 1 {
-		t.Fatalf("alertas: %d", len(list))
+		t.Fatalf("alertas tras re-emitir: %d, esperaba 1 (mismo ID, update)", len(list))
 	}
 	a := list[0]
 	if a.Category != alerts.CatRouter || a.Urgent || a.Severity != "ok" {

+ 90 - 0
server-go/internal/adapters/firmware_cmp.go

@@ -0,0 +1,90 @@
+// Comparación firmware vs target configurado (issue #1412). Parsea la versión
+// de release de ambos lados y compara componente a componente; si alguno no
+// tiene formato parseable, cae al Contains insensible a mayúsculas de #241.
+package adapters
+
+import (
+	"regexp"
+	"strconv"
+	"strings"
+)
+
+// Resultados de la comparación firmware/target.
+const (
+	// fwMatch: target contenido o igual a lo instalado, sin alerta.
+	fwMatch = iota
+	// fwNewer: el target es más nuevo que lo instalado (firmware
+	// desactualizado; el aviso clásico de "hay firmware más reciente").
+	fwNewer
+	// fwOlder: el target es MÁS VIEJO que lo instalado. No es "desactualizado":
+	// apunta a un downgrade, casi siempre un target mal configurado.
+	fwOlder
+	// fwAmbiguous: no se pudieron parsear versiones y el Contains no casa.
+	// Se alerta como desactualizado (semántica previa a #1412) porque no hay
+	// base para decidir otra cosa.
+	fwAmbiguous
+)
+
+var releaseVersionRe = regexp.MustCompile(`\d+(?:\.\d+)+`)
+
+// parseReleaseVersion extrae la primera versión con puntos del string
+// ("OpenWrt 25.12.5 r33051-f5dae5ece4" -> "25.12.5"; "25.12.6" -> "25.12.6").
+// Vacío si no hay ninguna.
+func parseReleaseVersion(s string) string {
+	return releaseVersionRe.FindString(s)
+}
+
+// compareReleaseVersions compara dos versiones punto a punto numéricamente:
+// -1 si a < b, 0 si iguales (en los componentes presentes), 1 si a > b.
+// "25.12" vs "25.12.6": los componentes que faltan cuentan como 0, así que
+// "25.12" == "25.12.0" < "25.12.6".
+func compareReleaseVersions(a, b string) int {
+	as := strings.Split(a, ".")
+	bs := strings.Split(b, ".")
+	n := len(as)
+	if len(bs) > n {
+		n = len(bs)
+	}
+	for i := 0; i < n; i++ {
+		ai, bi := 0, 0
+		if i < len(as) {
+			ai, _ = strconv.Atoi(as[i])
+		}
+		if i < len(bs) {
+			bi, _ = strconv.Atoi(bs[i])
+		}
+		if ai != bi {
+			if ai < bi {
+				return -1
+			}
+			return 1
+		}
+	}
+	return 0
+}
+
+// firmwareCompare decide la relación entre el firmware instalado y el target
+// configurado (issue #1412). Target vacío -> fwMatch (no hay comprobación).
+func firmwareCompare(installed, target string) int {
+	target = strings.TrimSpace(target)
+	if target == "" {
+		return fwMatch
+	}
+	iv := parseReleaseVersion(installed)
+	tv := parseReleaseVersion(target)
+	if iv != "" && tv != "" {
+		switch compareReleaseVersions(tv, iv) {
+		case 1:
+			return fwNewer
+		case -1:
+			return fwOlder
+		}
+		return fwMatch
+	}
+	// Sin versiones parseables: Contains insensible a mayúsculas del TARGET
+	// COMPLETO (#241), no del fragmento parseado.
+	if strings.Contains(strings.ToLower(strings.TrimSpace(installed)), strings.ToLower(target)) {
+		return fwMatch
+	}
+	return fwAmbiguous
+}

+ 38 - 0
server-go/internal/adapters/impostor.go

@@ -49,6 +49,27 @@ const (
 	impostorEnabledKey = "alerts.impostor_enabled"
 )
 
+// macDerivatives (#1402): la MAC base de una unidad de flota y sus +1/+2
+// (las radios OpenWrt enumeran a partir de la MAC del bridge). Devuelve las
+// MAC normalizadas en mayúsculas; nil si la base no parsea.
+func macDerivatives(mac string) []string {
+	hw, err := net.ParseMAC(strings.TrimSpace(mac))
+	if err != nil || len(hw) != 6 {
+		return nil
+	}
+	var v uint64
+	for _, b := range hw {
+		v = v<<8 | uint64(b)
+	}
+	out := make([]string, 0, 3)
+	for n := uint64(0); n <= 2; n++ {
+		x := v + n
+		out = append(out, fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X",
+			byte(x>>40), byte(x>>32), byte(x>>24), byte(x>>16), byte(x>>8), byte(x)))
+	}
+	return out
+}
+
 // EvalSsidImpostors: una pasada sobre wifi_scans recientes. La llama el
 // handler de ingesta del agente tras guardar un scan nuevo (momento exacto
 // en que la evidencia cambia). Barata: una query acotada por ventana.
@@ -68,6 +89,23 @@ func (l *Live) EvalSsidImpostors() {
 	for _, b := range l.agents.LocalBssids() {
 		ownBssids[b] = true
 	}
+	// #1402: las MAC de la flota (routers.mac, aprendida en cada sondeo)
+	// también son propias, con sus radios derivadas (+1/+2, patrón OpenWrt).
+	// Cubre la unidad cuyo payload no trae ownBssids y que no se sondea por
+	// SSH: sin esta fuente sus propias balizas caerían en la regla como
+	// rogue APs. Consulta directa a BD: routers.mac es la fuente de verdad.
+	if rows, err := l.db.Query(`SELECT mac FROM routers WHERE mac IS NOT NULL AND mac != ''`); err == nil {
+		for rows.Next() {
+			var m string
+			if rows.Scan(&m) != nil {
+				continue
+			}
+			for _, b := range macDerivatives(m) {
+				ownBssids[b] = true
+			}
+		}
+		rows.Close()
+	}
 	// Las radios sondeadas por SSH (iwinfo) también son propias: sin esto un
 	// router sin agente anunciando el SSID de la flota sería falso positivo.
 	// Fuente: la caché de extras del último sondeo (radios con BSSID real).

+ 28 - 0
server-go/internal/adapters/impostor_test.go

@@ -124,6 +124,34 @@ func TestImpostorForeignSsidIgnored(t *testing.T) {
 	}
 }
 
+// #1402: la unidad cuyo payload no trae ownBssids (y no se sondea por SSH)
+// se reconoce por routers.mac: su bridge MAC y sus radios derivadas (+1/+2)
+// no deben alertar como impostor. Un BSSID realmente ajeno SÍ sigue alertando.
+func TestImpostorFleetMacSeeded(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	// Unidad de flota sin agente: solo su MAC conocida en routers.mac.
+	if _, err := l.db.Exec(
+		`INSERT INTO routers (id, name, host, type, created_at, mac) VALUES ('ap2', 'AP Dos', '192.168.8.3', 'openwrt', 1, 'aa:bb:cc:00:10:00')`,
+	); err != nil {
+		t.Fatalf("insert router: %v", err)
+	}
+	now := time.Now()
+	// Radio = mac+1 anunciando el SSID de la flota: propia, no impostor.
+	insertScan(t, l, "ap1", "AA:BB:CC:00:10:01", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "AA:BB:CC:00:10:01", "temiscira", now)
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 0 {
+		t.Fatalf("radio derivada de routers.mac no es impostor; alertas: %+v", got)
+	}
+	// BSSID realmente ajeno: la regla sigue viva.
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:09", "temiscira", now.Add(-40*time.Minute))
+	insertScan(t, l, "ap1", "DE:AD:BE:EF:00:09", "temiscira", now)
+	l.EvalSsidImpostors()
+	if got := impostorAlerts(l); len(got) != 1 {
+		t.Fatalf("BSSID ajeno debía alertar; alertas: %+v", got)
+	}
+}
+
 func TestImpostorSamePayloadFrozenDoesNotConfirm(t *testing.T) {
 	l, _ := newImpostorLive(t)
 	now := time.Now()

+ 86 - 16
server-go/internal/adapters/live.go

@@ -279,6 +279,13 @@ type Live struct {
 	// router RouterOS, para calcular bps por delta entre polls (igual que
 	// GetNetDev de OpenWrt sobre /proc/net/dev, routeros_api.go).
 	roNetPrev map[string]netByteSample
+	// fwAlert (#1411): estado de la alerta de firmware por unidad con target
+	// configurado: qué relación se alertó y contra qué versiones. Con eso la
+	// alerta es un episodio por unidad (se abre una vez, se actualiza solo si
+	// cambia la versión o el target, y se resuelve al coincidir). Protegido
+	// por mu.
+	fwAlert map[string]fwAlertState
+
 	// snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
 	// para loguear solo cuando el resultado cambia.
 	snmpFdbCount map[string]int
@@ -450,6 +457,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		now:                  time.Now,
 		lastGood:             map[string]*Router{},
 		lastStatus:           map[string]string{},
+		fwAlert:              map[string]fwAlertState{},
 		boardCache:           map[string]*BoardInfo{},
 		layoutCache:          map[string][]PortLayout{},
 		extrasCache:          map[string]*extrasSnapshot{},
@@ -1261,17 +1269,63 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	}, nil
 }
 
-// firmwareOutdated decide si el firmware instalado no cumple el target
-// configurado por el admin (issue #241). Comparación tolerante e
-// insensible a mayúsculas: el target debe aparecer (Contains) dentro de la
-// descripción del firmware ("OpenWrt 25.12.5 r33051..." contiene "25.12.5").
-// Sin target ("" tras trim) → false (no hay comprobación).
-func firmwareOutdated(installed, target string) bool {
-	target = strings.TrimSpace(target)
-	if target == "" {
-		return false
+// fwAlertState (#1411): episodio de alerta de firmware abierto para una
+// unidad. cmp es el resultado de firmwareCompare que se alertó; installed y
+// target recuerdan contra qué se abrió para detectar el cambio de episodio.
+type fwAlertState struct {
+	cmp       int
+	installed string
+	target    string
+}
+
+// evalFirmwareAlert (#1411/#1412) abre, refresca o resuelve la alerta de
+// firmware de una unidad con target configurado. Un episodio por unidad: se
+// emite al detectarse el mismatch (ID estable alert-firmware-<id>), se
+// actualiza en sitio (EmitOrUpdate = episodio nuevo notificado) si cambia la
+// versión instalada o el target, y se resuelve (modelo #1349) al volver a
+// coincidir. Mientras el episodio sigue igual NO se re-emite: el feed no se
+// re-firea cada ciclo. El downgrade (target más viejo) alerta con wording
+// propio (#1412).
+func (l *Live) evalFirmwareAlert(routerID, name, installed, target string, cmp int) {
+	id := "alert-firmware-" + routerID
+	l.mu.Lock()
+	if l.fwAlert == nil {
+		l.fwAlert = map[string]fwAlertState{}
+	}
+	st, active := l.fwAlert[routerID]
+	if cmp == fwMatch {
+		delete(l.fwAlert, routerID)
+		l.mu.Unlock()
+		if active {
+			l.engine.Resolve(id)
+		}
+		return
+	}
+	if active && st.cmp == cmp && st.installed == installed && st.target == target {
+		// Episodio en curso sin cambios: nada que hacer (#1411).
+		l.mu.Unlock()
+		return
+	}
+	l.fwAlert[routerID] = fwAlertState{cmp: cmp, installed: installed, target: target}
+	l.mu.Unlock()
+	ev := AlertEvent{
+		ID: id, Category: alerts.CatSystem, Urgent: false,
+		Severity: "warn", RouterID: routerID,
+		Vars: map[string]string{"router": name, "firmware": installed, "target": target},
+		Time: "just now",
+	}
+	if cmp == fwOlder {
+		ev.Title = "Firmware downgrade target"
+		ev.Description = fmt.Sprintf("%s: configured target %q is older than the installed firmware %q", name, target, installed)
+		ev.Type = alerts.HintFirmwareDowngrade
+		ev.Hint = alerts.HintFor(alerts.HintFirmwareDowngrade)
+	} else {
+		ev.Title = "Firmware outdated"
+		ev.Description = fmt.Sprintf("%s: firmware %q does not match the target %q", name, installed, target)
+		ev.Type = alerts.HintFirmware
+		ev.Hint = alerts.HintFor(alerts.HintFirmware)
 	}
-	return !strings.Contains(strings.ToLower(strings.TrimSpace(installed)), strings.ToLower(target))
+	l.engine.EmitOrUpdate(ev)
 }
 
 // buildRouter construye el Router del contrato (index.js:221-249).
@@ -1346,10 +1400,14 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 		health -= 15
 	}
 	// issue #241: firmware fuera del target configurado penaliza la salud.
-	outdatedFw := false
-	if p.cfg.FirmwareTarget != "" && p.board != nil && firmwareOutdated(p.board.Release.Description, p.cfg.FirmwareTarget) {
-		health -= 5
-		outdatedFw = true
+	// #1412: la comparación es por versión de release parseada; un target más
+	// viejo que lo instalado (downgrade) no se penaliza como "desactualizado".
+	fwCmp := fwMatch
+	if p.cfg.FirmwareTarget != "" && p.board != nil {
+		fwCmp = firmwareCompare(p.board.Release.Description, p.cfg.FirmwareTarget)
+		if fwCmp == fwNewer || fwCmp == fwAmbiguous {
+			health -= 5
+		}
 	}
 	if health < 0 {
 		health = 0
@@ -1432,9 +1490,14 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.firmwareAvailable != "" && r.FirmwareTarget == "" {
 		r.FirmwareTarget = p.firmwareAvailable
 	}
-	if outdatedFw || p.firmwareAvailable != "" {
+	// #1411/#1412: con target configurado la alerta es UN episodio por unidad
+	// (ID estable), no un re-fire por ciclo: se abre al detectar el mismatch,
+	// se actualiza si cambia la versión o el target, y se resuelve al
+	// coincidir. El downgrade (target más viejo) alerta con wording propio.
+	if p.firmwareAvailable != "" {
 		r.FirmwareOutdated = true
-		// Alerta no urgente (category system); el engine aplica dedup 5 min.
+		// Rama RouterOS (sondeo API): se conserva el aviso por ciclo como
+		// hasta #1411; la dedup de 5 min lo acota.
 		l.engine.Emit(AlertEvent{
 			ID:       fmt.Sprintf("alert-firmware-%s-%d", p.cfg.ID, time.Now().UnixMilli()),
 			Category: alerts.CatSystem, Urgent: false,
@@ -1446,6 +1509,13 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 			Vars:        map[string]string{"router": name, "firmware": r.Firmware, "target": p.cfg.FirmwareTarget},
 			Time:        "just now", RouterID: p.cfg.ID,
 		})
+	} else if p.cfg.FirmwareTarget != "" {
+		if fwCmp == fwNewer || fwCmp == fwAmbiguous {
+			r.FirmwareOutdated = true
+		}
+		if p.board != nil {
+			l.evalFirmwareAlert(p.cfg.ID, name, r.Firmware, p.cfg.FirmwareTarget, fwCmp)
+		}
 	}
 	if p.temp > thr {
 		r.HotMetric = "temp"

+ 95 - 14
server-go/internal/adapters/live_firmware_test.go

@@ -6,28 +6,33 @@ import (
 	"testing"
 )
 
-// TestFirmwareOutdated cubre la comparación pura (issue #241): Contains
-// normalizado en minúsculas sobre la descripción del firmware.
-func TestFirmwareOutdated(t *testing.T) {
+// TestFirmwareCompare cubre la comparación pura (issues #241 y #1412): con
+// versiones parseables compara componente a componente; si no, cae al
+// Contains insensible a mayúsculas (resultado fwAmbiguous).
+func TestFirmwareCompare(t *testing.T) {
 	cases := []struct {
 		name      string
 		installed string
 		target    string
-		want      bool
+		want      int
 	}{
-		{"sin target", "OpenWrt 23.05.5", "", false},
-		{"target solo espacios", "OpenWrt 23.05.5", "   ", false},
-		{"coincide exacto", "23.05.5", "23.05.5", false},
-		{"coincide dentro de descripción", "OpenWrt 25.12.5 r33051-abc", "25.12.5", false},
-		{"coincide sin distinguir mayúsculas", "OpenWrt 25.12.5", "OPENWRT 25.12.5", false},
-		{"no coincide", "OpenWrt 23.05.5", "24.10.1", true},
-		{"instalado vacío", "", "24.10.1", true},
-		{"target con espacios alrededor", "OpenWrt 23.05.5", " 23.05.5 ", false},
+		{"sin target", "OpenWrt 23.05.5", "", fwMatch},
+		{"target solo espacios", "OpenWrt 23.05.5", "   ", fwMatch},
+		{"coincide exacto", "23.05.5", "23.05.5", fwMatch},
+		{"coincide dentro de descripción", "OpenWrt 25.12.5 r33051-abc", "25.12.5", fwMatch},
+		{"target más nuevo", "OpenWrt 25.12.5 r33051-abc", "25.12.6", fwNewer},
+		{"target más viejo (downgrade)", "OpenWrt 25.12.5 r33051-abc", "25.12.4", fwOlder},
+		{"salto de major", "OpenWrt 23.05.5 r20134-abc", "24.10.1", fwNewer},
+		{"minor con patch", "OpenWrt 24.10.0", "24.10.1", fwNewer},
+		{"target con major y minor", "OpenWrt 25.12.5", "25.13", fwNewer},
+		{"instalado vacío", "", "24.10.1", fwAmbiguous},
+		{"target con espacios alrededor", "OpenWrt 23.05.5", " 23.05.5 ", fwMatch},
+		{"target no parseable legacy", "OpenWrt 23.05.5", "snapshot", fwAmbiguous},
 	}
 	for _, c := range cases {
 		t.Run(c.name, func(t *testing.T) {
-			if got := firmwareOutdated(c.installed, c.target); got != c.want {
-				t.Fatalf("firmwareOutdated(%q, %q) = %v, esperaba %v", c.installed, c.target, got, c.want)
+			if got := firmwareCompare(c.installed, c.target); got != c.want {
+				t.Fatalf("firmwareCompare(%q, %q) = %d, esperaba %d", c.installed, c.target, got, c.want)
 			}
 		})
 	}
@@ -114,6 +119,82 @@ func TestBuildRouterFirmwareTarget(t *testing.T) {
 	}
 }
 
+// TestBuildRouterFirmwareDowngrade (#1412): un target MÁS VIEJO que lo
+// instalado alerta con wording propio, NO marca FirmwareOutdated y NO
+// penaliza la salud.
+func TestBuildRouterFirmwareDowngrade(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "g", Host: "192.168.8.1", IsGateway: true}}, nil)
+	p := &routerPolled{
+		cfg:   RouterConfig{ID: "r5", Name: "Salón", Host: "192.168.8.2", FirmwareTarget: "25.12.4"},
+		board: boardWithDesc("OpenWrt 25.12.5 r33051-abc"),
+	}
+	r := l.buildRouter(p, nil)
+	if r.FirmwareOutdated {
+		t.Fatalf("downgrade no debe marcar FirmwareOutdated: %+v", r)
+	}
+	if r.Health != 100 {
+		t.Fatalf("Health=%d, esperaba 100 (el downgrade no penaliza como desactualizado)", r.Health)
+	}
+	list := l.AlertsEngine().List()
+	if len(list) != 1 {
+		t.Fatalf("alertas=%d, esperaba 1", len(list))
+	}
+	ev := list[0]
+	if ev.Title != "Firmware downgrade target" || ev.Type != "firmware-downgrade-target" {
+		t.Fatalf("alerta de downgrade mal formada: %+v", ev)
+	}
+	if !strings.Contains(ev.Description, "25.12.4") || !strings.Contains(ev.Description, "25.12.5") {
+		t.Fatalf("Description=%q", ev.Description)
+	}
+}
+
+// TestBuildRouterFirmwareOncePerUnit (#1411): la alerta de firmware es UN
+// episodio por unidad. Re-sondar la misma condición no re-firea; cambiar la
+// versión o el target actualiza la misma alerta; al coincidir se resuelve.
+func TestBuildRouterFirmwareOncePerUnit(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "g", Host: "192.168.8.1", IsGateway: true}}, nil)
+	p := &routerPolled{
+		cfg:   RouterConfig{ID: "r6", Name: "Salón", Host: "192.168.8.2", FirmwareTarget: "25.12.6"},
+		board: boardWithDesc("OpenWrt 25.12.5 r33051-abc"),
+	}
+	l.buildRouter(p, nil)
+	l.buildRouter(p, nil) // mismo ciclo: sin re-fire
+	list := l.AlertsEngine().List()
+	if len(list) != 1 {
+		t.Fatalf("alertas=%d tras re-sondar, esperaba 1 (episodio único)", len(list))
+	}
+	if list[0].ID != "alert-firmware-r6" {
+		t.Fatalf("ID=%q, esperaba ID estable alert-firmware-r6", list[0].ID)
+	}
+	// Cambia el target: misma alerta actualizada en sitio, no una copia.
+	p.cfg.FirmwareTarget = "25.13.0"
+	l.buildRouter(p, nil)
+	list = l.AlertsEngine().List()
+	if len(list) != 1 || !strings.Contains(list[0].Description, "25.13.0") {
+		t.Fatalf("tras cambio de target: %d alertas, %+v", len(list), list)
+	}
+	// Cambia la versión instalada: episodio nuevo en la misma alerta.
+	p.board = boardWithDesc("OpenWrt 25.12.7 r33051-abc")
+	l.buildRouter(p, nil)
+	list = l.AlertsEngine().List()
+	if len(list) != 1 || !strings.Contains(list[0].Description, "25.12.7") {
+		t.Fatalf("tras cambio de versión: %d alertas, %+v", len(list), list)
+	}
+	// El firmware alcanza el target: la alerta se resuelve y sale del feed.
+	p.cfg.FirmwareTarget = "25.12.7"
+	l.buildRouter(p, nil)
+	if n := len(l.AlertsEngine().List()); n != 0 {
+		t.Fatalf("alertas=%d tras resolver, esperaba 0", n)
+	}
+	// Reincidencia (mismatch otra vez): el mismo ID vuelve a alertar.
+	p.cfg.FirmwareTarget = "25.12.8"
+	l.buildRouter(p, nil)
+	list = l.AlertsEngine().List()
+	if len(list) != 1 || list[0].ID != "alert-firmware-r6" {
+		t.Fatalf("reincidencia: %d alertas, %+v", len(list), list)
+	}
+}
+
 // TestBuildRouterFirmwareSinBoard: target sin board (sin firmware leído) no
 // debe marcar outdated ni emitir (evita falsos positivos en sondeo parcial).
 func TestBuildRouterFirmwareSinBoard(t *testing.T) {

+ 79 - 80
server-go/internal/alerts/alerts.go

@@ -97,25 +97,28 @@ type AlertEvent struct {
 
 // Stable alert-type slugs (issue #310): keys of the Hints map.
 const (
-	HintAgentDown     = "agent-down"
-	HintAgentDownSSH  = "agent-down-ssh" // variante: satélite degrada a SSH (#671)
-	HintGatewayUnrch  = "gateway-unreachable"
-	HintHighTemp      = "high-temperature"
-	HintPortFlapping  = "port-flapping"
-	HintDeviceOffline = "device-offline"
-	HintUnknownDevice = "unknown-device"
-	HintSsidImpostor  = "wifi-ssid-impostor"
+	HintAgentDown       = "agent-down"
+	HintAgentDownSSH    = "agent-down-ssh" // variante: satélite degrada a SSH (#671)
+	HintGatewayUnrch    = "gateway-unreachable"
+	HintHighTemp        = "high-temperature"
+	HintPortFlapping    = "port-flapping"
+	HintDeviceOffline   = "device-offline"
+	HintUnknownDevice   = "unknown-device"
+	HintSsidImpostor    = "wifi-ssid-impostor"
 	HintNewNeighborSsid = "new-neighbor-ssid"
 	HintNewClient       = "new-client"
-	HintFirmware      = "firmware-outdated"
-	HintWanDown       = "wan-down"
-	HintWifiWeak      = "wifi-weak"
-	HintGhostPort     = "ghost-port"
-	HintDegradedLink  = "degraded-link"
-	HintAgentOutdated = "agent-outdated"
-	HintWanSlow       = "wan-slow"
-	HintUplinkSwitch  = "uplink-switched"
-	HintSnmpFailing   = "snmp-failing"
+	HintFirmware        = "firmware-outdated"
+	// #1412: el target configurado es MÁS VIEJO que lo instalado (posible
+	// downgrade, casi siempre un target mal puesto).
+	HintFirmwareDowngrade = "firmware-downgrade-target"
+	HintWanDown           = "wan-down"
+	HintWifiWeak          = "wifi-weak"
+	HintGhostPort         = "ghost-port"
+	HintDegradedLink      = "degraded-link"
+	HintAgentOutdated     = "agent-outdated"
+	HintWanSlow           = "wan-slow"
+	HintUplinkSwitch      = "uplink-switched"
+	HintSnmpFailing       = "snmp-failing"
 )
 
 // Additional stable alert-type slugs (issue #712): recovery/info/beacon/rearmer
@@ -155,34 +158,37 @@ const (
 // The canonical language is English (#1014): alertlang and the web feed swap
 // it for the catalog wording when the target language is Spanish.
 var Hints = map[string]string{
-	HintAgentDown:     "Check the router power and connection; if it does not recover, reinstall the agent from LuCI.",
-	HintAgentDownSSH:  "Check the router's power and connection; if it doesn't recover, reinstall the agent from LuCI.",
-	HintGatewayUnrch:  "Check the connection between the gateway and the rest of the network.",
-	HintHighTemp:      "Improve ventilation and keep the router away from heat sources.",
-	HintPortFlapping:  "Check the cable or switch port: an unstable link is usually the culprit.",
-	HintDeviceOffline: "Verify the device power and network cable.",
-	HintUnknownDevice: "If you do not recognize it, block it or mark it as trusted in Settings.",
-	HintSsidImpostor:  "An unknown radio is broadcasting your network name. Check the area around the hearing AP; if you do not recognize the BSSID, treat it as a rogue AP.",
-	HintNewNeighborSsid: "A new network name has been broadcasting nearby for hours. If it is not yours, find out what it is (a new router, an IoT device in pairing mode, a hotspot); if it is a permanent neighbor you do not care about, dismiss the alert - it will not repeat.",
-	HintNewClient:       "A device just joined the network for the first time. If you recognize it, name it or mark it as trusted in Settings; if not, check what it is.",
-	HintFirmware:      "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
-	HintWanDown:       "Check the modem/ONT and contact your ISP if the outage persists.",
-	HintWifiWeak:      "Move the device closer to an access point or relocate the AP.",
-	HintGhostPort:     "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
-	HintDegradedLink:  "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
-	HintAgentOutdated: "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
-	HintUplinkSwitch:  "Check the line that dropped: the router goes back to it on its own once it recovers.",
-	HintWanSlow:       "Restart the router and the modem/ONT and run the test again; if it stays low, contact your ISP (line degradation or congestion in your area).",
-	HintSnmpFailing:   "Check the SNMP community string and switch port: the device answers ping but not polling.",
+	HintAgentDown:         "Check the router power and connection; if it does not recover, reinstall the agent from LuCI.",
+	HintAgentDownSSH:      "Check the router's power and connection; if it doesn't recover, reinstall the agent from LuCI.",
+	HintGatewayUnrch:      "Check the connection between the gateway and the rest of the network.",
+	HintHighTemp:          "Improve ventilation and keep the router away from heat sources.",
+	HintPortFlapping:      "Check the cable or switch port: an unstable link is usually the culprit.",
+	HintDeviceOffline:     "Verify the device power and network cable.",
+	HintUnknownDevice:     "If you do not recognize it, block it or mark it as trusted in Settings.",
+	HintSsidImpostor:      "An unknown radio is broadcasting your network name. Check the area around the hearing AP; if you do not recognize the BSSID, treat it as a rogue AP.",
+	HintNewNeighborSsid:   "A new network name has been broadcasting nearby for hours. If it is not yours, find out what it is (a new router, an IoT device in pairing mode, a hotspot); if it is a permanent neighbor you do not care about, dismiss the alert - it will not repeat.",
+	HintNewClient:         "A device just joined the network for the first time. If you recognize it, name it or mark it as trusted in Settings; if not, check what it is.",
+	HintFirmware:          "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
+	HintFirmwareDowngrade: "The configured target is older than the installed firmware; fix the target version in the fleet unit settings.",
+	HintWanDown:           "Check the modem/ONT and contact your ISP if the outage persists.",
+	HintWifiWeak:          "Move the device closer to an access point or relocate the AP.",
+	HintGhostPort:         "Check the cable and the connected device: an active port that goes silent usually means a loose cable or a powered-off device.",
+	HintDegradedLink:      "Check the cable and connectors: a degraded link is often a sign of a damaged cable or a loose connector.",
+	HintAgentOutdated:     "Update the agent from Settings, Agents (Update button); if it's a NetGrip panel, update it from its own panel.",
+	HintUplinkSwitch:      "Check the line that dropped: the router goes back to it on its own once it recovers.",
+	HintWanSlow:           "Restart the router and the modem/ONT and run the test again; if it stays low, contact your ISP (line degradation or congestion in your area).",
+	HintSnmpFailing:       "Check the SNMP community string and switch port: the device answers ping but not polling.",
 }
 
 // HintFor returns the suggestion for a slug, or "" when it does not exist.
 func HintFor(slug string) string { return Hints[slug] }
 
 // Notifier es el hook de notificación externa (push/webhook/telegram/ntfy).
-// El engine dispara TODOS los eventos que pasan config (salvo suprimidos);
-// la decisión de urgencia es por canal (#874).
-// Se llama SOLO para eventos que pasan config Y son Urgent=true.
+// El engine lo dispara solo para eventos cuya categoría permite notificación
+// según el nivel configurado (#1413): none nunca, urgent solo Urgent, all
+// siempre. La decisión de urgencia fina por canal sigue en cada integración
+// (#874, urgencyGate). Los eventos suprimidos topológicamente se guardan con
+// SuppressedBy y nunca notifican.
 type Notifier interface {
 	Notify(ev AlertEvent)
 }
@@ -460,16 +466,19 @@ func (e *Engine) SetConfig(patch map[string]string) error {
 	return nil
 }
 
-// pasaLocked: ¿el evento supera la config de su categoría? (none descarta;
-// urgent solo deja urgentes; all deja todo). Requiere e.mu ya tomado.
-func (e *Engine) pasaLocked(ev AlertEvent) bool {
+// notificaLocked: ¿la config de la categoría permite NOTIFICAR este evento?
+// (issue #1413: los niveles son política de notificación, no de ingesta:
+// todo se guarda en el log y el feed; el nivel solo gobierna el Notifier).
+// none = nunca; urgent = solo eventos Urgent; all = siempre. Categoría
+// desconocida: notifica (la validación estricta es de SetConfig).
+// Requiere e.mu ya tomado.
+func (e *Engine) notificaLocked(ev AlertEvent) bool {
 	level, known := e.cfg[ev.Category]
 	if known {
 		if level == LevelNone || (level == LevelUrgent && !ev.Urgent) {
 			return false
 		}
 	}
-	// Categoría desconocida: pasa (la validación estricta es de SetConfig).
 	return true
 }
 
@@ -543,19 +552,15 @@ func (e *Engine) persistLocked(ev AlertEvent) {
 		   (SELECT id FROM alert_log ORDER BY ts DESC LIMIT ?)`, PersistMaxEvents)
 }
 
-// Emit aplica la semántica none/urgent/all EN CREACIÓN, el dedup de 5 min y
-// el cap de 100; devuelve true si el evento pasó (se guardó). Los eventos
-// que pasan disparan el Notifier (hook de Bloque C) con SU suppressión; el
-// filtro por URGENCIA vive en cada canal (#874): cada transporte decide si
-// lleva solo urgentes (default) o todo.
+// Emit aplica el dedup de 5 min y el cap de 100; devuelve true si el evento
+// se guardó. TODO evento se guarda (issue #1413): el nivel none/urgent/all de
+// su categoría ya no filtra la ingesta, solo gobierna si dispara el Notifier.
+// El filtro por URGENCIA fino vive en cada canal (#874): cada transporte
+// decide si lleva solo urgentes (default) o todo.
 // Supresión topológica (#332): si el router tiene un padre offline en el
 // grafo, la alerta se guarda con SuppressedBy y NO dispara el Notifier.
 func (e *Engine) Emit(ev AlertEvent) bool {
 	e.mu.Lock()
-	if !e.pasaLocked(ev) {
-		e.mu.Unlock()
-		return false
-	}
 	if e.suppression != nil && ev.RouterID != "" {
 		if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
 			ev.SuppressedBy = parent
@@ -574,15 +579,17 @@ func (e *Engine) Emit(ev AlertEvent) bool {
 	now := e.now()
 	ok := e.insertaLocked(ev, now, false)
 	n := e.notifier
+	notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
 	e.mu.Unlock()
-	if ok && n != nil && ev.SuppressedBy == "" {
+	if ok && notify {
 		n.Notify(ev)
 	}
 	return ok
 }
 
-// EmitNoDedup es Emit sin la ventana de dedup de 5 min (silencio, config y
-// cap SÍ aplican, y la supresión topológica marca SuppressedBy igual). Uso:
+// EmitNoDedup es Emit sin la ventana de dedup de 5 min (silencio, cap,
+// supresión y política de notificación por categoría SÍ aplican; issue #1413:
+// la config ya no filtra la ingesta, solo la notificación). Uso:
 // alertas cuya condición se trackea por estado fuera del engine (issue #846,
 // offline de router): al ABRIR incidente la alerta debe entrar siempre,
 // porque el cierre del incidente anterior ya retiró la suya del feed y el
@@ -590,10 +597,6 @@ func (e *Engine) Emit(ev AlertEvent) bool {
 // de incidente (offlineOpen), no la ventana.
 func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
 	e.mu.Lock()
-	if !e.pasaLocked(ev) {
-		e.mu.Unlock()
-		return false
-	}
 	if e.suppression != nil && ev.RouterID != "" {
 		if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
 			ev.SuppressedBy = parent
@@ -609,8 +612,9 @@ func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
 	now := e.now()
 	ok := e.insertaLocked(ev, now, true)
 	n := e.notifier
+	notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
 	e.mu.Unlock()
-	if ok && n != nil && ev.SuppressedBy == "" {
+	if ok && notify {
 		n.Notify(ev)
 	}
 	return ok
@@ -622,13 +626,10 @@ func (e *Engine) EmitNoDedup(ev AlertEvent) bool {
 // Diseñado para alertas "en curso" que se actualizan (p.ej. auto-rearme sin
 // recuperación: un incidente = una sola alerta, issue #271). El update NO
 // pasa por el dedup (consolida, no duplica); la inserción de un ID nuevo sí.
-// Devuelve true si el evento pasó la config (insertado o actualizado).
+// Devuelve true si se insertó o actualizó. La notificación obedece la
+// política de nivel de la categoría (#1413).
 func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 	e.mu.Lock()
-	if !e.pasaLocked(ev) {
-		e.mu.Unlock()
-		return false
-	}
 	// #1074: mismo default de Ts/Time que en Emit (#914) ANTES de insertar y
 	// notificar. La rama de inserción pasaba la `ev` original a Notify: si el
 	// emisor no fijaba Ts (p. ej. agent-outdated), el notifier recibía Ts=0
@@ -675,8 +676,9 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 			e.list = append([]AlertEvent{ev}, e.list...)
 			e.persistLocked(ev)
 			n := e.notifier
+			notify := n != nil && e.notificaLocked(ev)
 			e.mu.Unlock()
-			if n != nil {
+			if notify {
 				n.Notify(ev)
 			}
 			return true
@@ -684,8 +686,9 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 	}
 	ok := e.insertaLocked(ev, now, false)
 	n := e.notifier
+	notify := n != nil && e.notificaLocked(ev)
 	e.mu.Unlock()
-	if ok && n != nil {
+	if ok && notify {
 		n.Notify(ev)
 	}
 	return ok
@@ -695,17 +698,14 @@ func (e *Engine) EmitOrUpdate(ev AlertEvent) bool {
 // persiste en alert_log y, si ya existe una alerta con el mismo ID, se
 // actualiza en sitio y se mueve al frente (semántica "viva por router": un
 // incidente abierto = una alerta con ID estable). Si quedara una copia
-// persistida antigua con ese ID, se borra. Config, silencio y supresión
-// topológica aplican igual que en Emit; el dedup de 5 min NO aplica (el
-// tracking del incidente vive en el emisor, patrón #846). Devuelve true si
-// el evento pasó la config.
+// persistida antigua con ese ID, se borra. Silencio y supresión
+// topológica aplican como en Emit; la notificación obedece el nivel de la
+// categoría (#1413). El dedup de 5 min NO aplica (el tracking del incidente
+// vive en el emisor, patrón #846). Devuelve true siempre (la volátil nunca
+// se descarta por config).
 func (e *Engine) EmitVolatile(ev AlertEvent) bool {
 	ev.Volatile = true
 	e.mu.Lock()
-	if !e.pasaLocked(ev) {
-		e.mu.Unlock()
-		return false
-	}
 	if e.suppression != nil && ev.RouterID != "" {
 		if parent := e.suppression.SuppressedBy(ev.RouterID); parent != "" {
 			ev.SuppressedBy = parent
@@ -747,17 +747,16 @@ func (e *Engine) EmitVolatile(ev AlertEvent) bool {
 		_, _ = e.db.Exec("DELETE FROM alert_log WHERE id = ?", ev.ID)
 	}
 	n := e.notifier
+	notify := n != nil && ev.SuppressedBy == "" && e.notificaLocked(ev)
 	e.mu.Unlock()
-	if n != nil && ev.SuppressedBy == "" {
+	if notify {
 		n.Notify(ev)
 	}
 	return true
 }
 
-// Seed inserta un evento histórico (arranque del modo demo) SIN aplicar el
-// filtro de config — el SPEC §5 exige que las 5 canon sobrevivan con los
-// defaults aunque "vpn:none"/"clients:urgent" descartarían 2 en creación —.
-// Mantiene dedup, cap y Read=false; NO dispara el Notifier (son historia).
+// Seed inserta un evento histórico (arranque del modo demo) SIN disparar el
+// Notifier (son historia). Mantiene dedup, cap y Read=false.
 // Devuelve true si se guardó.
 func (e *Engine) Seed(ev AlertEvent) bool {
 	e.mu.Lock()

+ 36 - 19
server-go/internal/alerts/alerts_test.go

@@ -1,6 +1,7 @@
 // alerts_test.go — tests del motor (SPEC-ALERTAS §2-4): defaults, validación,
-// filtrado none/urgent/all en creación, dedup 5 min, cap 100, read-state
-// (FIFO 200, persistencia kv) y hook Notifier.
+// política de notificación none/urgent/all (#1413: la ingesta ya no se
+// filtra), dedup 5 min, cap 100, read-state (FIFO 200, persistencia kv) y
+// hook Notifier.
 package alerts
 
 import (
@@ -63,39 +64,55 @@ func TestSetConfigPartialAndValidation(t *testing.T) {
 	}
 }
 
+// TestEmitFiltering cubre la semántica #1413: la config de categoría NO filtra
+// la ingesta (todo se guarda en el log y el feed); solo gobierna el Notifier
+// (none = nunca, urgent = solo Urgent, all = siempre).
 func TestEmitFiltering(t *testing.T) {
 	e := New(nil, nil)
-	// none → descarta (signal por defecto)
-	if e.Emit(ev("s1", CatSignal, true)) {
-		t.Fatal("signal:none debía descartar")
+	spy := &spyNotifier{}
+	e.SetNotifier(spy)
+	// none → se guarda pero NO notifica (signal por defecto)
+	if !e.Emit(ev("s1", CatSignal, true)) {
+		t.Fatal("signal:none debía guardar (la ingesta ya no se filtra)")
+	}
+	if len(spy.got) != 0 {
+		t.Fatalf("signal:none no debía notificar, notificó %d", len(spy.got))
+	}
+	// urgent → se guarda el no-urgente pero solo notifica el urgente (router)
+	if !e.Emit(ev("r1", CatRouter, false)) {
+		t.Fatal("router:urgent debía guardar el no-urgente")
 	}
-	// urgent → solo urgentes (router por defecto)
-	if e.Emit(ev("r1", CatRouter, false)) {
-		t.Fatal("router:urgent debía descartar no-urgente")
+	if len(spy.got) != 0 {
+		t.Fatalf("router:urgent no debía notificar el no-urgente, notificó %d", len(spy.got))
 	}
 	if !e.Emit(ev("r2", CatRouter, true)) {
-		t.Fatal("router:urgent debía aceptar urgente")
+		t.Fatal("router:urgent debía guardar el urgente")
 	}
-	// all → pasa todo (clients=all desde #196)
-	if !e.Emit(ev("c1", CatClients, false)) {
-		t.Fatal("clients:all debía aceptar no-urgente")
+	if len(spy.got) != 1 || spy.got[0].ID != "r2" {
+		t.Fatalf("router:urgent debía notificar solo el urgente: %+v", spy.got)
 	}
-	if !e.Emit(ev("c2", CatClients, true)) {
-		t.Fatal("clients:all debía aceptar urgente")
+	// all → guarda y notifica todo (clients=all desde #196, system por defecto)
+	if !e.Emit(ev("c1", CatClients, false)) || !e.Emit(ev("c2", CatClients, true)) {
+		t.Fatal("clients:all debía guardar todo")
 	}
-	// all → pasa todo (system por defecto)
 	if !e.Emit(ev("y1", CatSystem, false)) {
 		t.Fatal("system:all debía aceptar no-urgente")
 	}
-	if got := len(e.List()); got != 4 {
-		t.Fatalf("lista: %d, esperaba 4", got)
+	if len(spy.got) != 4 {
+		t.Fatalf("notificados: %d, esperaba 4 (todo salvo signal:none y el no-urgente de router)", len(spy.got))
 	}
-	// Cambio de nivel reconfigura el filtrado
+	if got := len(e.List()); got != 6 {
+		t.Fatalf("lista: %d, esperaba 6 (nada se descarta)", got)
+	}
+	// Cambio de nivel reconfigura SOLO la notificación
 	if err := e.SetConfig(map[string]string{"signal": "all"}); err != nil {
 		t.Fatal(err)
 	}
 	if !e.Emit(ev("s2", CatSignal, false)) {
-		t.Fatal("signal:all debía aceptar")
+		t.Fatal("signal:all debía guardar")
+	}
+	if len(spy.got) != 5 {
+		t.Fatalf("signal:all debía notificar: %d notificados", len(spy.got))
 	}
 }
 

+ 63 - 0
server-go/internal/firmware/method.go

@@ -0,0 +1,63 @@
+// method.go — método de upgrade preferido por unidad (#1414). Persistido en
+// kv (firmware.method.<routerId>): el selector de la tarjeta decide qué
+// sección de la página se muestra y qué motor dispara "Upgrade now".
+package firmware
+
+import (
+	"database/sql"
+	"fmt"
+	"strings"
+)
+
+// Métodos del selector por unidad.
+const (
+	// MethodAuto: comportamiento actual (secciones owut y URL visibles a la
+	// vez). Es el default: no rompe a quien ya usa la página.
+	MethodAuto   = "auto"
+	MethodOwut   = "owut"
+	MethodURL    = "url"
+	MethodUpload = "upload"
+)
+
+const methodKeyPrefix = "firmware.method."
+
+// ValidMethod reporta si m es un método aceptable.
+func ValidMethod(m string) bool {
+	switch m {
+	case MethodAuto, MethodOwut, MethodURL, MethodUpload:
+		return true
+	}
+	return false
+}
+
+// LoadMethod devuelve el método persistido del router; MethodAuto si no hay
+// o hay valor inválido.
+func LoadMethod(db *sql.DB, routerID string) string {
+	if db == nil {
+		return MethodAuto
+	}
+	var v string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", methodKeyPrefix+routerID).Scan(&v); err != nil {
+		return MethodAuto
+	}
+	v = strings.TrimSpace(v)
+	if !ValidMethod(v) {
+		return MethodAuto
+	}
+	return v
+}
+
+// SaveMethod persiste el método del router. Valida antes de escribir.
+func SaveMethod(db *sql.DB, routerID, method string) error {
+	if db == nil {
+		return fmt.Errorf("no db")
+	}
+	method = strings.TrimSpace(method)
+	if !ValidMethod(method) {
+		return fmt.Errorf("invalid method %q", method)
+	}
+	_, err := db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+		methodKeyPrefix+routerID, method)
+	return err
+}

+ 31 - 0
server-go/internal/firmware/owut_flow.go

@@ -211,6 +211,37 @@ func RunOwutUpgrade(runner Runner, host, cmd string) (int, string, error) {
 	return exit, raw, err
 }
 
+// owutDownloadTimeout: build remoto ASU + descarga de la imagen al router.
+// `owut download` NO flashea: termina por sí solo y la sesión SSH sobrevive.
+const owutDownloadTimeout = 10 * time.Minute
+
+// OwutDownloadCmd construye `owut download` (paso intermedio del flujo por
+// pasos de #1414): construye la imagen en ASU y la descarga al router SIN
+// flashear, para que el admin la revise antes de `owut install`. Sin -q a
+// propósito: la salida completa es la revisión.
+func OwutDownloadCmd(target, current string) string {
+	cmd := "owut download"
+	if target != "" && current != "" && target != current {
+		cmd += " -V " + shQuote(target)
+	}
+	return cmd
+}
+
+// RunOwutDownload ejecuta `owut download` y devuelve salida + exit. El comando
+// termina normalmente (no flashea), así que la sesión SSH NO muere: un exit
+// distinto de 0 o un error de sesión es fallo real.
+func RunOwutDownload(runner Runner, host, cmd string) (int, string, error) {
+	wrapped := cmd + ` 2>&1; printf '\n__owut_exit__=%d\n' $?`
+	out, err := runner.Run(host, wrapped, owutDownloadTimeout)
+	exit, raw := extractExitCode(out)
+	return exit, raw, err
+}
+
+// OwutInstallCmd construye `owut install`: flashea la imagen que `owut
+// download` dejó en el router y reinicia (la sesión SSH muere como en el
+// upgrade; el resultado se confirma por el board info tras el reboot).
+func OwutInstallCmd() string { return "owut install" }
+
 // Platform es la foto de plataforma de un router: si tiene owut y si lleva
 // firmware de fabricante. Vendor != "" significa firmware compilado por el
 // vendor con su propia gestión de actualizaciones (GL.iNet): NetPulse NO

+ 7 - 0
server-go/internal/httpapi/firmware.go

@@ -20,6 +20,8 @@ type firmwareStatusResponse struct {
 	TargetVersion  string `json:"targetVersion"`
 	TargetURL      string `json:"targetUrl"`
 	Checksum       string `json:"checksum"`
+	// Method (#1414): método preferido de la tarjeta (auto/owut/url/upload).
+	Method string `json:"method"`
 	// Detección #477 P2: último board info reportado por el agente/SSH.
 	// detectedBoard es el board_name (perfil ASU) y detectedTarget el
 	// DISTRIB_TARGET; base para el prefill del formulario y el lookup ASU.
@@ -49,6 +51,10 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 
 	// Ciclo owut completo + recurrencia (#761).
 	s.registerFirmwareOwutRoutes(mux)
+	// Método por unidad + imagen subida desde local (#1414).
+	s.registerFirmwareUploadRoutes(mux)
+	// Backups de config en el server (#1414).
+	s.registerFirmwareBackupRoutes(mux)
 
 	mux.Handle("GET /api/firmware-upgrades", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		if s.db == nil {
@@ -85,6 +91,7 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 				RouterID: r.ID,
 				Name:     r.Name,
 				Model:    model,
+				Method:   firmware.LoadMethod(s.db.DB, r.ID),
 			}
 			if t := targetMap[r.ID]; t != nil {
 				item.CurrentVersion = t.CurrentVersion

+ 126 - 0
server-go/internal/httpapi/firmware_owut.go

@@ -176,6 +176,93 @@ func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
 		}
 	})))
 
+	// POST owut-download: construye y descarga la imagen en el router SIN
+	// flashear (paso intermedio del flujo por pasos, #1414). Síncrono: la
+	// salida completa es la revisión del admin antes de instalar.
+	mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-download", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		host := s.hostOfRouter(id)
+		if host == "" {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		if s.pool == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_ssh_pool")
+			return
+		}
+		plat := s.platform(id, host)
+		if plat.Vendor != "" {
+			writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
+				"El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
+			return
+		}
+		if !plat.Owut {
+			writeError(w, http.StatusPreconditionFailed, "owut_not_installed",
+				"owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
+			return
+		}
+		var body struct {
+			TargetVersion string `json:"targetVersion"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			return
+		}
+		cmd := firmware.OwutDownloadCmd(body.TargetVersion, s.detectedFirmwareVersion(id))
+		exit, out, err := firmware.RunOwutDownload(s.pool, host, cmd)
+		if err != nil || exit != 0 {
+			msg := owutTail(out, err)
+			if msg == "" {
+				msg = fmt.Sprintf("owut download falló (exit %d)", exit)
+			}
+			writeError(w, http.StatusBadGateway, "owut_download_failed", msg)
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "output": out})
+	})))
+
+	// POST owut-install-image: flashea la imagen que owut-download dejó en el
+	// router (#1414, paso final del flujo por pasos). Igual que owut-upgrade:
+	// 202 inmediata, la máquina de estados confirma tras el reboot.
+	mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-install-image", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		host := s.hostOfRouter(id)
+		if host == "" {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		if s.pool == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_ssh_pool")
+			return
+		}
+		plat := s.platform(id, host)
+		if plat.Vendor != "" {
+			writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
+				"El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
+			return
+		}
+		if !plat.Owut {
+			writeError(w, http.StatusPreconditionFailed, "owut_not_installed",
+				"owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
+			return
+		}
+		if up, _ := s.firmware.LatestUpgrade(id); up != nil && owutUpgradeActive(up.Status) {
+			writeError(w, http.StatusConflict, "upgrade_in_progress", "Ya hay un upgrade en curso")
+			return
+		}
+		target := ""
+		if t, _ := s.firmware.GetTarget(id); t != nil {
+			target = t.TargetVersion
+		}
+		uid, err := s.firmware.BeginUpgrade(id, target, "", "")
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		_ = s.firmware.SetEngine(uid, "owut")
+		go s.runOwutInstallImage(uid, id, host, target)
+		writeJSON(w, http.StatusAccepted, map[string]any{"upgradeId": uid, "engine": "owut"})
+	})))
+
 	// GET/PUT/DELETE recurrence: programación once/weekly/monthly.
 	mux.Handle("GET /api/firmware-upgrades/{routerId}/recurrence", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		id := r.PathValue("routerId")
@@ -276,6 +363,45 @@ func (s *server) runOwutUpgrade(id int64, routerID, host, target, origin string,
 	}
 }
 
+// runOwutInstallImage ejecuta `owut install` (flash de la imagen ya
+// descargada por owut-download, paso final de #1414). Igual semántica que
+// runOwutUpgrade: la muerte de la sesión SSH tras >owutSSHMinRun es el final
+// NORMAL del flash; el resultado se confirma mirando el board info.
+func (s *server) runOwutInstallImage(id int64, routerID, host, target string) {
+	from := ""
+	if s.boardVersionFn != nil {
+		from = s.boardVersionFn(routerID)
+	}
+	_ = s.firmware.SetStatus(id, "running", "", "")
+	if err := firmware.EnsureStackPreserved(s.pool, host); err != nil {
+		log.Printf("[firmware] preserve-stack %s falló (continuo): %v", routerID, err)
+	}
+	start := time.Now()
+	exit, out, err := firmware.RunOwutUpgrade(s.pool, host, firmware.OwutInstallCmd())
+	dur := time.Since(start)
+	switch {
+	case err == nil && exit == 0:
+		// owut install puede terminar sin reiniciar si no había imagen
+		// descargada: no es un éxito, es un no-op que hay que decir.
+		msg := strings.TrimSpace(out)
+		if msg == "" {
+			msg = "owut install terminó sin flashear (¿sin imagen descargada con owut download?)"
+		}
+		_ = s.firmware.SetStatus(id, "failed", msg, "")
+		s.emitFirmwareResult(routerID, from, target, "manual", false, msg)
+	case err != nil && dur >= owutSSHMinRun:
+		s.awaitReboot(id, routerID, target, "manual", from)
+	default:
+		msg := owutTail(out, err)
+		if strings.TrimSpace(msg) == "" {
+			msg = fmt.Sprintf("owut install falló (exit %d)", exit)
+		}
+		log.Printf("[firmware] owut install %s falló (exit %d): %s", routerID, exit, msg)
+		_ = s.firmware.SetStatus(id, "failed", msg, "")
+		s.emitFirmwareResult(routerID, from, target, "manual", false, msg)
+	}
+}
+
 // awaitReboot espera a que el router vuelva del sysupgrade y su board info
 // reporte la versión objetivo. Deadline: owutRebootGrace.
 func (s *server) awaitReboot(id int64, routerID, target, origin, from string) {

+ 284 - 0
server-go/internal/httpapi/firmware_upload.go

@@ -0,0 +1,284 @@
+// firmware_upload.go — selector de método por unidad e imagen subida desde
+// local (#1414). La imagen se guarda en el server y el flujo clásico la sirve
+// al agente para su descarga (el agente ya descarga por URL con sha256, sin
+// cambios de protocolo).
+package httpapi
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+	"path/filepath"
+	"sort"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/firmware"
+)
+
+// maxFirmwareUpload: tope de una imagen subida (las de OpenWrt rondan 8-25 MB;
+// 100 MB da margen para perfiles con muchos paquetes empaquetados).
+const maxFirmwareUpload = 100 << 20
+
+func (s *server) registerFirmwareUploadRoutes(mux *http.ServeMux) {
+	if s.firmware == nil {
+		return
+	}
+
+	// PUT method: método preferido de la tarjeta (auto/owut/url/upload).
+	mux.Handle("PUT /api/firmware-upgrades/{routerId}/method", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		var body struct {
+			Method string `json:"method"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			return
+		}
+		if !firmware.ValidMethod(body.Method) {
+			writeError(w, http.StatusBadRequest, "invalid_method", "method debe ser auto, owut, url o upload")
+			return
+		}
+		if err := firmware.SaveMethod(s.db.DB, id, body.Method); err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+	})))
+
+	// POST image: sube una imagen (multipart, campo "image") y la deja como
+	// target del flujo clásico: URL servida por este mismo server (alcanzable
+	// por el agente vía NETPULSE_AGENT_URL/PublicURL) + checksum calculado.
+	mux.Handle("POST /api/firmware-upgrades/{routerId}/image", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		if err := r.ParseMultipartForm(maxFirmwareUpload); err != nil {
+			writeError(w, http.StatusRequestEntityTooLarge, "image_too_large", fmt.Sprintf("imagen mayor de %d MB", maxFirmwareUpload>>20))
+			return
+		}
+		f, hdr, err := r.FormFile("image")
+		if err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_body", "campo multipart 'image' requerido")
+			return
+		}
+		defer f.Close()
+
+		dir := filepath.Join(filepath.Dir(s.db.Path), "firmware-uploads")
+		if err := os.MkdirAll(dir, 0o700); err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		dest := filepath.Join(dir, id+".bin")
+		tmp := dest + ".tmp"
+		df, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		h := sha256.New()
+		n, copyErr := io.Copy(io.MultiWriter(df, h), io.LimitReader(f, maxFirmwareUpload+1))
+		closeErr := df.Close()
+		if copyErr != nil || closeErr != nil {
+			os.Remove(tmp)
+			writeError(w, http.StatusInternalServerError, "firmware_error", "no se pudo guardar la imagen")
+			return
+		}
+		if n == 0 || n > maxFirmwareUpload {
+			os.Remove(tmp)
+			writeError(w, http.StatusRequestEntityTooLarge, "image_too_large", "imagen vacía o mayor del tope")
+			return
+		}
+		if err := os.Rename(tmp, dest); err != nil {
+			os.Remove(tmp)
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		sum := hex.EncodeToString(h.Sum(nil))
+
+		// La URL con la que los AGENTES deben alcanzar al server (#1335):
+		// la misma cadena de precedencia que el install line.
+		imgURL := s.agentBaseURL(r) + "/api/firmware-image/" + id
+		t, _ := s.firmware.GetTarget(id)
+		if t == nil {
+			t = &firmware.Target{RouterID: id}
+		}
+		t.TargetURL = imgURL
+		t.Checksum = sum
+		if err := s.firmware.SetTarget(*t); err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{
+			"ok": true, "checksum": sum, "size": n, "name": hdr.Filename, "url": imgURL,
+		})
+	})))
+
+	// GET image: sirve la imagen subida. Sin auth de admin a propósito: el
+	// AGENTE la descarga con su transporte pinned (mismo caso que
+	// GET /api/agents/{slug}/binary, #1367) y no puede añadir cabeceras.
+	// La imagen tampoco es secreta (es la que el admin subió para flashear).
+	mux.HandleFunc("GET /api/firmware-image/{routerId}", s.handleFirmwareImage)
+}
+
+// firmwareBackupDir resuelve el directorio de backups de config subidos por
+// los agentes (#1414), junto a la BD (misma política que los backups #741).
+func (s *server) firmwareBackupDir() string {
+	return filepath.Join(filepath.Dir(s.db.Path), "backups", "firmware")
+}
+
+// maxFirmwareBackupsPerRouter: retención de backups de config por unidad.
+const maxFirmwareBackupsPerRouter = 5
+
+// registerFirmwareBackupRoutes: el agente sube el backup de config hecho con
+// sysupgrade -b (persistencia real frente al /tmp local, que muere en el
+// reboot del flash) y el admin lista/descarga.
+func (s *server) registerFirmwareBackupRoutes(mux *http.ServeMux) {
+	if s.firmware == nil {
+		return
+	}
+
+	// POST: subida del agente (Bearer, misma auth que firmware-progress).
+	// Body crudo: el .tar.gz tal cual.
+	mux.HandleFunc("POST /api/agents/{slug}/firmware-backup", func(w http.ResponseWriter, r *http.Request) {
+		slug := r.PathValue("slug")
+		token := bearerToken(r)
+		if !s.checkAgentToken(slug, token) {
+			writeError(w, http.StatusUnauthorized, "unauthorized")
+			return
+		}
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		dir := s.firmwareBackupDir()
+		if err := os.MkdirAll(dir, 0o700); err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		name := fmt.Sprintf("%s-%d.tar.gz", slug, time.Now().Unix())
+		dest := filepath.Join(dir, name)
+		df, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
+		n, copyErr := io.Copy(df, io.LimitReader(r.Body, maxFirmwareUpload+1))
+		closeErr := df.Close()
+		if copyErr != nil || closeErr != nil {
+			os.Remove(dest)
+			writeError(w, http.StatusInternalServerError, "firmware_error", "no se pudo guardar el backup")
+			return
+		}
+		if n == 0 || n > maxFirmwareUpload {
+			os.Remove(dest)
+			writeError(w, http.StatusRequestEntityTooLarge, "backup_too_large", "backup vacío o mayor del tope")
+			return
+		}
+		pruneFirmwareBackups(dir, slug)
+		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name, "size": n})
+	})
+
+	// GET list: backups de config de una unidad (admin).
+	mux.Handle("GET /api/firmware-backups/{routerId}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		entries, err := os.ReadDir(s.firmwareBackupDir())
+		if err != nil {
+			writeJSON(w, http.StatusOK, []any{})
+			return
+		}
+		type info struct {
+			Name string `json:"name"`
+			Size int64  `json:"size"`
+			Ts   int64  `json:"ts"`
+		}
+		out := []info{}
+		for _, e := range entries {
+			if e.IsDir() || !strings.HasPrefix(e.Name(), id+"-") || !strings.HasSuffix(e.Name(), ".tar.gz") {
+				continue
+			}
+			if fi, err := e.Info(); err == nil {
+				// ts = parte numérica del nombre (<slug>-<ts>.tar.gz)
+				ts := int64(0)
+				if n, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimPrefix(e.Name(), id+"-"), ".tar.gz"), 10, 64); err == nil {
+					ts = n
+				}
+				out = append(out, info{Name: e.Name(), Size: fi.Size(), Ts: ts})
+			}
+		}
+		sort.Slice(out, func(i, j int) bool { return out[i].Ts > out[j].Ts })
+		writeJSON(w, http.StatusOK, out)
+	})))
+
+	// GET file: descarga de un backup (admin).
+	mux.Handle("GET /api/firmware-backups/{routerId}/file", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		name := filepath.Base(r.URL.Query().Get("name"))
+		if name == "." || name == "" || !strings.HasPrefix(name, id+"-") || !strings.HasSuffix(name, ".tar.gz") {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		path := filepath.Join(s.firmwareBackupDir(), name)
+		st, err := os.Stat(path)
+		if err != nil || st.IsDir() {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		w.Header().Set("Content-Type", "application/gzip")
+		w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", name))
+		http.ServeFile(w, r, path)
+	})))
+}
+
+// pruneFirmwareBackups deja los maxFirmwareBackupsPerRouter más recientes de
+// una unidad (el nombre lleva ts, ordenar por nombre = ordenar por ts).
+func pruneFirmwareBackups(dir, slug string) {
+	entries, err := os.ReadDir(dir)
+	if err != nil {
+		return
+	}
+	var mine []os.DirEntry
+	for _, e := range entries {
+		if !e.IsDir() && strings.HasPrefix(e.Name(), slug+"-") && strings.HasSuffix(e.Name(), ".tar.gz") {
+			mine = append(mine, e)
+		}
+	}
+	sort.Slice(mine, func(i, j int) bool { return mine[i].Name() > mine[j].Name() })
+	for i := maxFirmwareBackupsPerRouter; i < len(mine); i++ {
+		os.Remove(filepath.Join(dir, mine[i].Name()))
+	}
+}
+
+// handleFirmwareImage sirve la imagen subida de un router. El id se sanea:
+// solo nombre base (sin separadores ni puntos dobles) dentro del directorio
+// de uploads.
+func (s *server) handleFirmwareImage(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("routerId")
+	if id == "" || strings.ContainsAny(id, `/\`) || strings.Contains(id, "..") {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	if s.db == nil {
+		writeError(w, http.StatusServiceUnavailable, "no_db")
+		return
+	}
+	path := filepath.Join(filepath.Dir(s.db.Path), "firmware-uploads", id+".bin")
+	st, err := os.Stat(path)
+	if err != nil || st.IsDir() {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	w.Header().Set("Content-Type", "application/octet-stream")
+	w.Header().Set("Content-Length", fmt.Sprintf("%d", st.Size()))
+	http.ServeFile(w, r, path)
+}