Browse Source

feat(firmware): full owut flow, recurring schedule and vendor firmware guard (#762)

* feat(firmware): owut full flow backend, recurring schedule and result alerts (#761)

* feat(firmware): redesign upgrades UI - detected readonly fields, target dropdown, owut install/check/upgrade, schedule dialog (#761)

* fix(firmware): exclude branch SNAPSHOT from versions, dropdown offers current and newer only

* fix(firmware): retry owut install from official repo, prefill target, monday-first week, exclude local packages from ASU build

* feat(firmware): block vendor firmware (GL.iNet) from owut flow, informative panel only

* fix(firmware): robust vendor detection (grep exit 2 on apk3), owut-required guard, clear vendor panel

* feat(firmware): parse missing packages from check, prefill exclusions, running banner, target version validation

* fix(firmware): target saves without image URL (owut builds it via ASU)

* fix(firmware): verbose owut check lists missing package names

* feat(firmware): preserve stack packages (netgrip/agent) across ASU upgrades via sysupgrade.conf

* feat(firmware): in-progress card view with phase, progress bar and console log

* feat(firmware): success celebration view after completed owut upgrade, stale check auto-clear

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 months ago
parent
commit
91d6ca5867

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

@@ -226,6 +226,14 @@
       "wireguard-handshake": {
       "wireguard-handshake": {
         "title": "WireGuard handshake",
         "title": "WireGuard handshake",
         "description": "{{peer}} connected"
         "description": "{{peer}} connected"
+      },
+      "firmware-upgrade-done": {
+        "title": "Firmware upgraded",
+        "description": "{{router}}: {{from}} → {{to}} (owut, {{origin}})"
+      },
+      "firmware-upgrade-failed": {
+        "title": "Firmware upgrade failed",
+        "description": "{{router}}: target {{to}} (owut, {{origin}}): {{detail}}"
       }
       }
     }
     }
   },
   },
@@ -1708,7 +1716,9 @@
       "flashing": "Flashing",
       "flashing": "Flashing",
       "done": "Done",
       "done": "Done",
       "failed": "Failed",
       "failed": "Failed",
-      "scheduled": "Scheduled"
+      "scheduled": "Scheduled",
+      "running": "running",
+      "rebooting": "rebooting"
     },
     },
     "schedule": "Schedule",
     "schedule": "Schedule",
     "scheduleAt": "Schedule for",
     "scheduleAt": "Schedule for",
@@ -1722,7 +1732,53 @@
     "owutUpToDate": "No pending changes; no upgrade needed.",
     "owutUpToDate": "No pending changes; no upgrade needed.",
     "owutNotBuildable": "The ASU server cannot build the image for this router right now.",
     "owutNotBuildable": "The ASU server cannot build the image for this router right now.",
     "owutCheckFailed": "The check could not run (router unreachable or not responding).",
     "owutCheckFailed": "The check could not run (router unreachable or not responding).",
-    "owutOutput": "owut output"
+    "owutOutput": "owut output",
+    "check": "Check",
+    "installOwut": "Install owut",
+    "installingOwut": "Installing owut...",
+    "notDetected": "Not detected",
+    "installedTag": "installed",
+    "latestTag": "latest",
+    "majorWarn": "Major version jump ({{from}} → {{to}}): review the release notes before upgrading",
+    "advanced": "Advanced (URL and checksum)",
+    "owutConfirmTitle": "Upgrade with owut (ASU)",
+    "owutConfirmBody": "The ASU server will build a stock OpenWrt image and the router will install it. The session drops when it reboots.",
+    "owutConfirmPackages": "The ASU image keeps the packages you installed on the router",
+    "scheduleTitle": "Schedule upgrade",
+    "scheduleBody": "Date/time and recurrence. It only flashes when the installed version differs from the target.",
+    "rec_once": "Once",
+    "rec_weekly": "Weekly",
+    "rec_monthly": "Monthly",
+    "recDate": "Date and time",
+    "recDay": "Day of the week",
+    "recDayOfMonth": "Day of the month",
+    "recTime": "Time",
+    "recNeedDate": "Pick a date and time for the one-shot schedule",
+    "recScheduled": "Scheduled ({{kind}}): {{when}}",
+    "recRemove": "Remove schedule",
+    "recIdempotentHint": "Every attempt reports its result (alert, push and Telegram when configured). If the router is already on the target version, nothing happens.",
+    "excludePkgs": "Packages to exclude from the ASU image",
+    "excludePkgsHint": "Only needed when the check complains about packages outside the official repos (they are lost on upgrade; reinstall them afterwards).",
+    "owutNotBuildableHint": "Usually a package installed outside the official repos: check the output and exclude it when upgrading.",
+    "vendorNote": "This router runs vendor firmware (GL.iNet): NetPulse does not manage its upgrades. Use the GL.iNet panel (Upgrade Firmware), which already offers the latest official release for the model.",
+    "missingPkgsBanner": "These packages are not in the official feeds: {{pkgs}}. They will be excluded from the image if you keep them while upgrading (they are lost; reinstall afterwards).",
+    "upgradeRunningOwut": "owut upgrade in progress {{step}} · {{elapsed}}. It can take several minutes and the router reboots at the end.",
+    "stepWorking": "(building the image on ASU and downloading)",
+    "stepRebooting": "(waiting for the router to come back from reboot)",
+    "emptyFailure": "no details: check the Comprobar output or retry",
+    "missingPkgsBannerStack": "These packages are not in the official feeds: {{pkgs}}. Own-stack ones (netgrip / agent) will be excluded from the image but their files survive the update; anything else is lost (reinstall it afterwards).",
+    "phaseBuild": "Building the image on ASU (usually takes 1-3 min)",
+    "phaseDownload": "Downloading and verifying the image",
+    "phaseFlash": "About to flash: the router reboots shortly",
+    "consoleContact": "contacting sysupgrade.openwrt.org...",
+    "consoleBuild": "requesting image build from ASU...",
+    "consoleDownload": "downloading image...",
+    "consoleVerify": "verifying sha256...",
+    "consoleWrite": "writing firmware...",
+    "consoleReboot": "router is rebooting; waiting for it to come back (up to 15 min)",
+    "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"
   },
   },
   "orchestration": {
   "orchestration": {
     "title": "Orchestration",
     "title": "Orchestration",

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

@@ -226,6 +226,14 @@
       "wireguard-handshake": {
       "wireguard-handshake": {
         "title": "Handshake WireGuard",
         "title": "Handshake WireGuard",
         "description": "{{peer}} conectado"
         "description": "{{peer}} conectado"
+      },
+      "firmware-upgrade-done": {
+        "title": "Firmware actualizado",
+        "description": "{{router}}: {{from}} → {{to}} (owut, {{origin}})"
+      },
+      "firmware-upgrade-failed": {
+        "title": "Actualización de firmware fallida",
+        "description": "{{router}}: objetivo {{to}} (owut, {{origin}}): {{detail}}"
       }
       }
     }
     }
   },
   },
@@ -1708,7 +1716,9 @@
       "flashing": "Flasheando",
       "flashing": "Flasheando",
       "done": "Completada",
       "done": "Completada",
       "failed": "Fallida",
       "failed": "Fallida",
-      "scheduled": "Programada"
+      "scheduled": "Programada",
+      "running": "ejecutando",
+      "rebooting": "reiniciando"
     },
     },
     "schedule": "Programar",
     "schedule": "Programar",
     "scheduleAt": "Programar para",
     "scheduleAt": "Programar para",
@@ -1722,7 +1732,53 @@
     "owutUpToDate": "Sin cambios pendientes; no es necesario actualizar.",
     "owutUpToDate": "Sin cambios pendientes; no es necesario actualizar.",
     "owutNotBuildable": "El servidor ASU no puede construir la imagen para este router en este momento.",
     "owutNotBuildable": "El servidor ASU no puede construir la imagen para este router en este momento.",
     "owutCheckFailed": "No se pudo ejecutar el check (router inalcanzable o sin respuesta).",
     "owutCheckFailed": "No se pudo ejecutar el check (router inalcanzable o sin respuesta).",
-    "owutOutput": "Salida de owut"
+    "owutOutput": "Salida de owut",
+    "check": "Comprobar",
+    "installOwut": "Instalar owut",
+    "installingOwut": "Instalando owut...",
+    "notDetected": "Sin detectar",
+    "installedTag": "instalada",
+    "latestTag": "última",
+    "majorWarn": "Salto de versión mayor ({{from}} → {{to}}): revisa los cambios de la rama antes de actualizar",
+    "advanced": "Avanzado (URL y checksum)",
+    "owutConfirmTitle": "Actualizar con owut (ASU)",
+    "owutConfirmBody": "El servidor ASU construirá una imagen OpenWrt estándar y el router la instalará. La sesión se cortará al reiniciar.",
+    "owutConfirmPackages": "La imagen ASU conserva los paquetes que instalaste en el router",
+    "scheduleTitle": "Programar actualización",
+    "scheduleBody": "Fecha/hora y recurrencia. Solo flashea si la versión instalada difiere del objetivo.",
+    "rec_once": "Una vez",
+    "rec_weekly": "Semanal",
+    "rec_monthly": "Mensual",
+    "recDate": "Fecha y hora",
+    "recDay": "Día de la semana",
+    "recDayOfMonth": "Día del mes",
+    "recTime": "Hora",
+    "recNeedDate": "Elige fecha y hora para la programación única",
+    "recScheduled": "Programado ({{kind}}): {{when}}",
+    "recRemove": "Quitar programación",
+    "recIdempotentHint": "Cada intento avisa del resultado (alerta, push y Telegram si está configurado). Si el router ya está en la versión objetivo, no hace nada.",
+    "excludePkgs": "Paquetes a excluir de la imagen ASU",
+    "excludePkgsHint": "Solo necesarios si el check objeta paquetes instalados fuera de los repos oficiales (se pierden al actualizar; reinstálalos después).",
+    "owutNotBuildableHint": "Suele ser un paquete instalado que no está en los repos oficiales: revisa la salida y exclúyelo al actualizar.",
+    "vendorNote": "Este router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones. Usa el panel de GL.iNet (Upgrade Firmware), que ya ofrece la última versión oficial del modelo.",
+    "missingPkgsBanner": "Estos paquetes no están en los feeds oficiales: {{pkgs}}. Se excluirán de la imagen si los añades al actualizar (se pierden; reinstálalos después).",
+    "upgradeRunningOwut": "Actualización owut en curso {{step}} · {{elapsed}}. Puede tardar varios minutos y el router se reiniciará al final.",
+    "stepWorking": "(construyendo la imagen en ASU y descargando)",
+    "stepRebooting": "(esperando a que el router vuelva del reinicio)",
+    "emptyFailure": "sin detalles: consulta la salida de Comprobar o reintenta",
+    "missingPkgsBannerStack": "Estos paquetes no están en los feeds oficiales: {{pkgs}}. Los del propio stack (netgrip / agente) se excluirán de la imagen pero sus ficheros se conservan tras el update; cualquier otro se pierde (reinstálalo después).",
+    "phaseBuild": "Construyendo la imagen en ASU (suele tardar 1-3 min)",
+    "phaseDownload": "Descargando y verificando la imagen",
+    "phaseFlash": "A punto de flashear: el router se reiniciará en breve",
+    "consoleContact": "contactando con sysupgrade.openwrt.org...",
+    "consoleBuild": "solicitando build de la imagen a ASU...",
+    "consoleDownload": "descargando imagen...",
+    "consoleVerify": "verificando sha256...",
+    "consoleWrite": "escribiendo firmware...",
+    "consoleReboot": "el router se está reiniciando; esperando a que vuelva (hasta 15 min)",
+    "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"
   },
   },
   "orchestration": {
   "orchestration": {
     "title": "Orquestación",
     "title": "Orquestación",

File diff suppressed because it is too large
+ 606 - 203
app/src/pages/FirmwareUpgrades.tsx


+ 1 - 0
server-go/cmd/netpulse/main.go

@@ -549,6 +549,7 @@ func run() error {
 		ConfigBackup:    cfgBackup,
 		ConfigBackup:    cfgBackup,
 		Firmware:        fwStore,
 		Firmware:        fwStore,
 		Speedtest:       stScheduler,
 		Speedtest:       stScheduler,
+		AlertEmitter:    adapter.AlertsEngine(),
 		ChannelPlan:     chPlan,
 		ChannelPlan:     chPlan,
 		LastOverview: func() *adapters.Overview {
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 			return p.LastOverview()

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

@@ -470,6 +470,8 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
 	migrate(sqldb, "routers", "temp_threshold", "ALTER TABLE routers ADD COLUMN temp_threshold INTEGER")
 	// issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
 	// issue #494: upgrades desatendidos programados (epoch ms UTC; NULL = manual).
 	migrate(sqldb, "firmware_upgrades", "scheduled_for", "ALTER TABLE firmware_upgrades ADD COLUMN scheduled_for INTEGER")
 	migrate(sqldb, "firmware_upgrades", "scheduled_for", "ALTER TABLE firmware_upgrades ADD COLUMN scheduled_for INTEGER")
+	// issue #761: motor del upgrade ("" = clásico URL+checksum, "owut" = ASU).
+	migrate(sqldb, "firmware_upgrades", "engine", "ALTER TABLE firmware_upgrades ADD COLUMN engine TEXT NOT NULL DEFAULT ''")
 
 
 	// Si no hubo migración Node (instalación fresca creada por Go), marca la
 	// Si no hubo migración Node (instalación fresca creada por Go), marca la
 	// DB para que el siguiente arranque no dispare una "migración" espuria
 	// DB para que el siguiente arranque no dispare una "migración" espuria

+ 33 - 6
server-go/internal/firmware/owut.go

@@ -29,12 +29,15 @@ const (
 // owutDetectCmd comprueba si el binario owut está en el PATH del router.
 // owutDetectCmd comprueba si el binario owut está en el PATH del router.
 const owutDetectCmd = "command -v owut"
 const owutDetectCmd = "command -v owut"
 
 
-// owutCheckCmd envuelve `owut check` fusionando stderr en stdout y añadiendo
-// una línea final con el exit code. SSHPool.Run descarta el stdout cuando el
-// comando sale con código distinto de cero (session.Output), así que sin este
-// wrapper un check fallido perdería su salida. La línea `__owut_exit__=N` se
-// parsea y se retira del rawOutput antes de exponerlo.
-const owutCheckCmd = "owut check 2>&1; printf '\\n__owut_exit__=%d\\n' $?"
+// owutCheckCmd envuelve `owut check -v` fusionando stderr en stdout y
+// añadiendo una línea final con el exit code. El verbose es necesario para
+// que la salida LISTE los paquetes "missing to-version" (sus nombres), que
+// el resumen sin -v solo cuenta; de ahí salen los MissingPkgs para sugerir
+// la exclusión. SSHPool.Run descarta el stdout cuando el comando sale con
+// código distinto de cero (session.Output), así que sin este wrapper un
+// check fallido perdería su salida. La línea `__owut_exit__=N` se parsea y
+// se retira del rawOutput antes de exponerlo.
+const owutCheckCmd = "owut check -v 2>&1; printf '\\n__owut_exit__=%d\\n' $?"
 
 
 // owutExitRe extrae el exit code embebido por el wrapper de owutCheckCmd.
 // owutExitRe extrae el exit code embebido por el wrapper de owutCheckCmd.
 var owutExitRe = regexp.MustCompile(`__owut_exit__=(\d+)`)
 var owutExitRe = regexp.MustCompile(`__owut_exit__=(\d+)`)
@@ -61,6 +64,10 @@ type OwutStatus struct {
 	// Buildable: la infraestructura ASU puede construir la imagen (owut salió
 	// Buildable: la infraestructura ASU puede construir la imagen (owut salió
 	// con código 0, es decir, sin paquetes missing ni build failures).
 	// con código 0, es decir, sin paquetes missing ni build failures).
 	Buildable bool `json:"buildable"`
 	Buildable bool `json:"buildable"`
+	// MissingPkgs (#761): paquetes instalados fuera de los feeds oficiales
+	// ("missing to-version") que bloquean la build de ASU. La UI los muestra
+	// y ofrece excluirlos del upgrade (-r): se pierden y hay que reinstalar.
+	MissingPkgs []string `json:"missingPkgs,omitempty"`
 	// RawOutput: salida completa de `owut check` (sin la línea de exit code).
 	// RawOutput: salida completa de `owut check` (sin la línea de exit code).
 	RawOutput string `json:"rawOutput,omitempty"`
 	RawOutput string `json:"rawOutput,omitempty"`
 	// Error: fallo de transporte (router inalcanzable, timeout SSH), no un
 	// Error: fallo de transporte (router inalcanzable, timeout SSH), no un
@@ -89,6 +96,7 @@ func CheckOwut(runner Runner, host string) OwutStatus {
 	status.CheckRan = raw != ""
 	status.CheckRan = raw != ""
 	status.RawOutput = raw
 	status.RawOutput = raw
 	status.UpgradeAvailable, status.Buildable = parseOwutCheck(raw, exitCode)
 	status.UpgradeAvailable, status.Buildable = parseOwutCheck(raw, exitCode)
+	status.MissingPkgs = ParseMissingPkgs(raw)
 	return status
 	return status
 }
 }
 
 
@@ -114,6 +122,25 @@ func extractExitCode(out string) (int, string) {
 	return code, strings.TrimRight(raw, "\n")
 	return code, strings.TrimRight(raw, "\n")
 }
 }
 
 
+// owutMissingRe caza las líneas de paquete del reporte de owut:
+//
+//	netgrip    0.71.0-r1    missing to-version
+var owutMissingRe = regexp.MustCompile(`(?m)^\s{2,}([a-zA-Z0-9][a-zA-Z0-9._+-]*)\s+\S+\s+missing to-version\s*$`)
+
+// ParseMissingPkgs extrae los paquetes instalados fuera de los feeds
+// oficiales (bloquean la build de ASU). Función pura.
+func ParseMissingPkgs(out string) []string {
+	var pkgs []string
+	seen := map[string]bool{}
+	for _, m := range owutMissingRe.FindAllStringSubmatch(out, -1) {
+		if !seen[m[1]] {
+			seen[m[1]] = true
+			pkgs = append(pkgs, m[1])
+		}
+	}
+	return pkgs
+}
+
 // parseOwutCheck interpreta la salida de `owut check` a dos señales claras:
 // parseOwutCheck interpreta la salida de `owut check` a dos señales claras:
 // si hay upgrade disponible y si ASU puede construir la imagen. El mapeo está
 // si hay upgrade disponible y si ASU puede construir la imagen. El mapeo está
 // tomado de la fuente oficial de owut (check_updates + el resumen final):
 // tomado de la fuente oficial de owut (check_updates + el resumen final):

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

@@ -0,0 +1,290 @@
+// owut_flow.go - ciclo owut completo (#761): lista de versiones disponibles,
+// instalación del paquete y comando de upgrade desatendido.
+//
+// `owut upgrade` es no interactivo por diseño (verificado sobre el fuente
+// ucode de owut 2026.07): aborta solo si los checks fallan, hace warn sin
+// preguntar cuando hay default packages perdidos, y si no hay cambios termina
+// con exit 0 sin tocar nada (idempotencia nativa). Sin -V reconstruye la
+// versión instalada con los paquetes al día; con -V VERSION salta de versión
+// conservando los paquetes instalados (attended sysupgrade vía ASU).
+package firmware
+
+import (
+	"fmt"
+	"regexp"
+	"strconv"
+	"strings"
+	"time"
+)
+
+const (
+	owutVersionsTimeout = 60 * time.Second
+	owutInstallTimeout  = 240 * time.Second
+	// OwutUpgradeTimeout: build ASU + descarga + verificación + flash. El
+	// build remoto puede tardar minutos; el flash final mata dropbear y la
+	// sesión SSH muere con el router reiniciándose (resultado esperado).
+	OwutUpgradeTimeout = 15 * time.Minute
+)
+
+// OwutVersion es una versión destino que ASU puede construir para el router.
+type OwutVersion struct {
+	Version string `json:"version"`
+	Branch  string `json:"branch"`
+	Latest  bool   `json:"latest,omitempty"`
+	Newer   bool   `json:"newer,omitempty"`
+}
+
+var (
+	owutBranchRe = regexp.MustCompile(`^\s{2}(\S+)\s+release branch\s*$`)
+	owutVerRe    = regexp.MustCompile(`^\s{4}(\S+)(\s+\(latest\))?\s*$`)
+)
+
+// ListOwutVersions parsea `owut versions` y devuelve las versiones estables
+// (se excluyen -rc* y *-SNAPSHOT) con la marca Latest y Newer respecto a la
+// versión instalada actual (vacía = todas sin comparar).
+func ListOwutVersions(runner Runner, host, current string) ([]OwutVersion, error) {
+	if runner == nil || host == "" {
+		return nil, fmt.Errorf("firmware: runner o host vacío")
+	}
+	out, err := runner.Run(host, "owut versions 2>&1", owutVersionsTimeout)
+	if err != nil {
+		return nil, err
+	}
+	return ParseOwutVersions(out, current), nil
+}
+
+// ParseOwutVersions interpreta la salida de `owut versions` (función pura,
+// testeada): ramas con dos espacios y versiones con cuatro.
+func ParseOwutVersions(out, current string) []OwutVersion {
+	var versions []OwutVersion
+	branch := ""
+	for _, line := range strings.Split(out, "\n") {
+		if m := owutBranchRe.FindStringSubmatch(line); m != nil {
+			branch = m[1]
+			continue
+		}
+		if m := owutVerRe.FindStringSubmatch(line); m != nil {
+			v := m[1]
+			if !stableVersion(v) {
+				continue
+			}
+			versions = append(versions, OwutVersion{
+				Version: v,
+				Branch:  branch,
+				Latest:  m[2] != "",
+				Newer:   current != "" && VersionCmp(v, current) > 0,
+			})
+		}
+	}
+	return versions
+}
+
+// stableVersion filtra release candidates y snapshots del desplegable
+// (incluido el "SNAPSHOT" literal con que cierra cada rama del server ASU).
+func stableVersion(v string) bool {
+	if v == "SNAPSHOT" || !strings.ContainsFunc(v, isDigitRune) {
+		return false
+	}
+	return !strings.Contains(v, "-rc") && !strings.HasSuffix(v, "-SNAPSHOT")
+}
+
+func isDigitRune(r rune) bool { return r >= '0' && r <= '9' }
+
+// VersionCmp compara dos versiones OpenWrt ("25.12.5") numéricamente por
+// componentes; devuelve -1/0/1. Componentes no numéricos valen 0.
+func VersionCmp(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++ {
+		av, bv := 0, 0
+		if i < len(as) {
+			av, _ = strconv.Atoi(as[i])
+		}
+		if i < len(bs) {
+			bv, _ = strconv.Atoi(bs[i])
+		}
+		if av != bv {
+			if av < bv {
+				return -1
+			}
+			return 1
+		}
+	}
+	return 0
+}
+
+// MajorJump informa de si pasar de current a target cambia de rama mayor
+// ("23.05.5" -> "24.10.0" es salto mayor; "23.05.5" -> "23.05.7" no).
+func MajorJump(current, target string) bool {
+	if current == "" || target == "" {
+		return false
+	}
+	cs := strings.Split(current, ".")
+	ts := strings.Split(target, ".")
+	if len(cs) == 0 || len(ts) == 0 {
+		return false
+	}
+	return cs[0] != ts[0]
+}
+
+// owutInstallCmd detecta el gestor de paquetes del router e instala owut con
+// los repositorios PROPIOS del router (los firmware vanilla lo empaquetan).
+// En releases sin paquete owut (23.05-) el comando falla con el error del
+// gestor; en firmware de fabricante (GL.iNet) el flujo va bloqueado antes
+// (cada vendor gestiona sus actualizaciones en su propio panel).
+const owutInstallCmd = `if command -v apk >/dev/null 2>&1; then ` +
+	`apk update >/dev/null 2>&1; ` +
+	`apk add owut; ` +
+	`elif command -v opkg >/dev/null 2>&1; then opkg update && opkg install owut; ` +
+	`else printf '__no_pm__\n'; fi 2>&1; printf '\n__owut_exit__=%d\n' $?`
+
+// InstallOwut instala el paquete owut en el router con el gestor disponible
+// (con reintento vía repo oficial para firmware de vendor). Devuelve la
+// salida del gestor; error si no hay gestor, falla la instalación o falla el
+// transporte SSH.
+func InstallOwut(runner Runner, host string) (string, error) {
+	if runner == nil || host == "" {
+		return "", fmt.Errorf("firmware: runner o host vacío")
+	}
+	out, err := runner.Run(host, owutInstallCmd, owutInstallTimeout)
+	if err != nil {
+		return out, err
+	}
+	exit, raw := extractExitCode(out)
+	if strings.Contains(raw, "__no_pm__") {
+		return raw, fmt.Errorf("firmware: el router no tiene apk ni opkg")
+	}
+	if exit != 0 {
+		tail := raw
+		if len(tail) > 300 {
+			tail = "..." + tail[len(tail)-300:]
+		}
+		return raw, fmt.Errorf("instalación de owut falló (exit %d): %s", exit, strings.TrimSpace(tail))
+	}
+	return raw, nil
+}
+
+// OwutUpgradeCmd construye el comando de upgrade desatendido. Con target
+// distinto de la versión actual añade -V TARGET (salto de versión); si son
+// iguales (o current desconocida) reconstruye la versión instalada con los
+// paquetes al día. removePkgs excluye paquetes locales que no están en los
+// feeds oficiales ( owut "-r"): sin ellos ASU se niega a construir la imagen.
+func OwutUpgradeCmd(target, current string, removePkgs []string) string {
+	cmd := "owut upgrade -q"
+	if target != "" && current != "" && target != current {
+		cmd += " -V " + shQuote(target)
+	}
+	if pkgs := sanitizeRemovePkgs(removePkgs); pkgs != "" {
+		cmd += " -r " + shQuote(pkgs)
+	}
+	return cmd
+}
+
+// pkgNameRe: nombre de paquete apk/opkg sano (defensa contra inyección en
+// el comando SSH; el shQuote ya protege, esto limita el abuso).
+var pkgNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._+-]*$`)
+
+// sanitizeRemovePkgs filtra y une la lista de exclusiones (máx 20).
+func sanitizeRemovePkgs(list []string) string {
+	var keep []string
+	for _, p := range list {
+		p = strings.TrimSpace(p)
+		if p != "" && pkgNameRe.MatchString(p) && len(keep) < 20 {
+			keep = append(keep, p)
+		}
+	}
+	return strings.Join(keep, " ")
+}
+
+// RunOwutUpgrade ejecuta el comando de upgrade con el wrapper de exit code y
+// devuelve (exit, salida, error de transporte). Un error de transporte al
+// final del flujo es NORMAL: el sysupgrade reinicia el router y la sesión SSH
+// muere sin llegar a escribir la línea de exit (el caller lo interpreta).
+func RunOwutUpgrade(runner Runner, host, cmd string) (int, string, error) {
+	wrapped := cmd + ` 2>&1; printf '\n__owut_exit__=%d\n' $?`
+	out, err := runner.Run(host, wrapped, OwutUpgradeTimeout)
+	exit, raw := extractExitCode(out)
+	return exit, raw, err
+}
+
+// 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
+// ofrece upgrades ASU ahí, el vendor ya resuelve los suyos en su panel.
+type Platform struct {
+	Owut   bool
+	Vendor string // "" | "gl-inet"
+}
+
+// platformDetectCmd: una sola ida SSH resuelve ambas señales. La marca de
+// vendor son los repositorios propios (fw.gl-inet.com en apk u opkg): el
+// /etc/openwrt_release de los GL op25 es idéntico al vanilla y NO sirve.
+// OJO: busybox grep sale con 2 si algún fichero listado no existe (aunque
+// haya matches), así que el match se decide por salida (grep -q .), no por
+// exit code del primer grep.
+const platformDetectCmd = `command -v owut >/dev/null 2>&1 && printf '__owut__\n'; ` +
+	`grep -hs fw.gl-inet.com /etc/apk/repositories /etc/apk/repositories.d/* /etc/opkg/distfeeds.conf 2>/dev/null | grep -q . && printf '__gl__\n'; true`
+
+// DetectPlatform sondea owut y vendor del router (tolerante: runner/host
+// vacíos → Platform vacía).
+func DetectPlatform(runner Runner, host string) Platform {
+	if runner == nil || host == "" {
+		return Platform{}
+	}
+	out, _ := runner.Run(host, platformDetectCmd, owutDetectTimeout)
+	return ParsePlatform(out)
+}
+
+// ParsePlatform interpreta las marcas de platformDetectCmd (función pura).
+func ParsePlatform(out string) Platform {
+	p := Platform{}
+	if strings.Contains(out, "__owut__") {
+		p.Owut = true
+	}
+	if strings.Contains(out, "__gl__") {
+		p.Vendor = "gl-inet"
+	}
+	return p
+}
+
+// stackPreserveCmd garantiza de forma idempotente que los ficheros del
+// stack propio presente en el router (netgrip y/o agente NetPulse) estén en
+// /etc/sysupgrade.conf: ASU no puede incluir paquetes sin feed en la imagen,
+// pero los ficheros listados SOBREVIVEN al flash (el servicio arranca en el
+// primer boot; el registro apk se recupera con una reinstalación posterior).
+const stackPreserveCmd = `P=/etc/sysupgrade.conf; touch $P; ensure() { grep -qxF "$1" $P || echo "$1" >> $P; }; ` +
+	`if [ -f /usr/sbin/netgrip ]; then ensure /usr/sbin/netgrip; ensure /etc/init.d/netgrip; ` +
+	`ensure /usr/libexec/netgrip-restore-rules; ensure /etc/netgrip/; ` +
+	`for f in /etc/rc.d/*netgrip*; do [ -e "$f" ] && ensure "$f"; done; fi; ` +
+	`if [ -f /usr/sbin/netpulse-agent ]; then ensure /usr/sbin/netpulse-agent; ensure /etc/netpulse-agent.env; ` +
+	`ensure /usr/sbin/netpulse-watchdog; ensure /etc/init.d/netpulse-agent; ` +
+	`for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure "$f"; done; fi; true`
+
+// EnsureStackPreserved ejecuta la preservación en el router (tolerante: un
+// runner nil es no-op; devuelve el error de transporte si falla y el caller
+// decide si continúa).
+func EnsureStackPreserved(runner Runner, host string) error {
+	if runner == nil || host == "" {
+		return nil
+	}
+	_, err := runner.Run(host, stackPreserveCmd, owutDetectTimeout)
+	return err
+}
+
+// OpenWrtVersionRe: versión destino válida para -V ("25.12.5", "24.10.2").
+// Evita que textos libres guardados como target disparen upgrades sin sentido.
+var OpenWrtVersionRe = regexp.MustCompile(`^\d+\.\d+(\.\d+)?(-[a-zA-Z0-9.]+)?$`)
+
+// ValidOpenWrtVersion informa de si target parece una versión OpenWrt.
+func ValidOpenWrtVersion(v string) bool {
+	return OpenWrtVersionRe.MatchString(strings.TrimSpace(v))
+}
+
+// shQuote entrecomilla un valor para shell POSIX (single-quote escaping).
+func shQuote(v string) string {
+	return "'" + strings.ReplaceAll(v, "'", `'\''`) + "'"
+}

+ 209 - 0
server-go/internal/firmware/owut_flow_test.go

@@ -0,0 +1,209 @@
+// owut_flow_test.go - tests del ciclo owut completo (#761): parse de
+// versiones, comparadores, construcción del comando de upgrade e instalación.
+package firmware
+
+import (
+	"errors"
+	"strings"
+	"testing"
+	"time"
+)
+
+type fakeSSHRunner struct {
+	out string
+	err error
+	got string
+}
+
+func (f *fakeSSHRunner) Run(host, cmd string, timeout time.Duration) (string, error) {
+	f.got = cmd
+	return f.out, f.err
+}
+
+// owutVersionsOut reproduce el formato real de `owut versions` (verificado en
+// un router OpenWrt 25.12 con owut 2026.07).
+const owutVersionsOut = `Available 'version-to' values from https://sysupgrade.openwrt.org:
+  22.03 release branch
+    22.03.0-rc1
+    22.03.7 (latest)
+    22.03-SNAPSHOT
+  23.05 release branch
+    23.05.4
+    23.05.5 (latest)
+  24.10 release branch
+    24.10.0
+    24.10.2 (latest)
+  25.12 release branch
+    25.12.4
+    25.12.5
+    25.12.7 (latest)
+`
+
+func TestParseOwutVersions(t *testing.T) {
+	vs := ParseOwutVersions(owutVersionsOut, "25.12.5")
+	if len(vs) != 8 {
+		t.Fatalf("esperaba 8 versiones estables (rc y SNAPSHOT fuera), got %d: %+v", len(vs), vs)
+	}
+	byVer := map[string]OwutVersion{}
+	for _, v := range vs {
+		byVer[v.Version] = v
+	}
+	if v := byVer["25.12.7"]; !v.Latest || !v.Newer || v.Branch != "25.12" {
+		t.Fatalf("25.12.7: %+v", v)
+	}
+	if v := byVer["25.12.5"]; v.Latest || v.Newer {
+		t.Fatalf("25.12.5 (instalada): %+v", v)
+	}
+	if v := byVer["23.05.5"]; v.Branch != "23.05" {
+		t.Fatalf("23.05.5: %+v", v)
+	}
+	if _, ok := byVer["22.03.0-rc1"]; ok {
+		t.Fatalf("un rc no debe aparecer: %+v", byVer["22.03.0-rc1"])
+	}
+	if _, ok := byVer["22.03-SNAPSHOT"]; ok {
+		t.Fatalf("un SNAPSHOT no debe aparecer")
+	}
+	if _, ok := byVer["SNAPSHOT"]; ok {
+		t.Fatalf("el SNAPSHOT literal de fin de rama no debe aparecer")
+	}
+}
+
+func TestParseOwutVersionsBranchSnapshot(t *testing.T) {
+	// El server ASU cierra cada rama con "SNAPSHOT" (sin versión): fuera.
+	vs := ParseOwutVersions("  25.12 release branch\n    25.12.4\n    SNAPSHOT (latest)\n", "25.12.4")
+	if len(vs) != 1 || vs[0].Version != "25.12.4" {
+		t.Fatalf("esperaba solo 25.12.4, got %+v", vs)
+	}
+}
+
+func TestVersionCmp(t *testing.T) {
+	cases := []struct {
+		a, b string
+		want int
+	}{
+		{"25.12.5", "25.12.5", 0},
+		{"25.12.7", "25.12.5", 1},
+		{"23.05.5", "24.10.0", -1},
+		{"25.12", "25.12.0", 0},
+		{"25.12.1", "25.12", 1},
+		{"", "", 0},
+	}
+	for _, c := range cases {
+		if got := VersionCmp(c.a, c.b); got != c.want {
+			t.Fatalf("VersionCmp(%q, %q) = %d, esperaba %d", c.a, c.b, got, c.want)
+		}
+	}
+}
+
+func TestMajorJump(t *testing.T) {
+	cases := []struct {
+		current, target string
+		want            bool
+	}{
+		{"23.05.5", "24.10.0", true},
+		{"23.05.5", "23.05.7", false},
+		{"25.12.5", "25.12.7", false},
+		{"", "24.10.0", false},
+		{"23.05.5", "", false},
+	}
+	for _, c := range cases {
+		if got := MajorJump(c.current, c.target); got != c.want {
+			t.Fatalf("MajorJump(%q, %q) = %v, esperaba %v", c.current, c.target, got, c.want)
+		}
+	}
+}
+
+func TestOwutUpgradeCmd(t *testing.T) {
+	if got := OwutUpgradeCmd("25.12.7", "25.12.5", nil); got != "owut upgrade -q -V '25.12.7'" {
+		t.Fatalf("salto de versión: %q", got)
+	}
+	if got := OwutUpgradeCmd("25.12.5", "25.12.5", nil); got != "owut upgrade -q" {
+		t.Fatalf("misma versión (rebuild de paquetes): %q", got)
+	}
+	if got := OwutUpgradeCmd("25.12.7", "", nil); got != "owut upgrade -q" {
+		t.Fatalf("current desconocida: %q", got)
+	}
+	if got := OwutUpgradeCmd("25.12.5", "25.12.5", []string{"netgrip", ""}); got != "owut upgrade -q -r 'netgrip'" {
+		t.Fatalf("exclusión de paquete local: %q", got)
+	}
+	if got := OwutUpgradeCmd("25.12.5", "25.12.5", []string{"a;rm -rf /", "b"}); got != "owut upgrade -q -r 'b'" {
+		t.Fatalf("nombres hostiles se filtran: %q", got)
+	}
+}
+
+func TestRunOwutUpgradeParsesExit(t *testing.T) {
+	f := &fakeSSHRunner{out: "There are no changes to upgrade\n__owut_exit__=0\n"}
+	exit, out, err := RunOwutUpgrade(f, "h", OwutUpgradeCmd("25.12.5", "25.12.5", nil))
+	if err != nil || exit != 0 || !strings.Contains(out, "no changes") {
+		t.Fatalf("exit=%d err=%v out=%q", exit, err, out)
+	}
+	if !strings.Contains(f.got, "__owut_exit__") {
+		t.Fatalf("el comando debe llevar el wrapper de exit: %q", f.got)
+	}
+}
+
+func TestRunOwutUpgradeTransportDeath(t *testing.T) {
+	// La sesión SSH muere con el reinicio del sysupgrade: err != nil, sin
+	// línea de exit (el caller decide con la duración).
+	f := &fakeSSHRunner{err: errors.New("ssh: connection reset")}
+	exit, _, err := RunOwutUpgrade(f, "h", "owut upgrade -q")
+	if err == nil {
+		t.Fatalf("debe propagar el error de transporte")
+	}
+	if exit != 0 {
+		t.Fatalf("sin línea de exit el código es 0 por defecto, got %d", exit)
+	}
+}
+
+func TestInstallOwutNoPackageManager(t *testing.T) {
+	f := &fakeSSHRunner{out: "__no_pm__\n__owut_exit__=0\n"}
+	if _, err := InstallOwut(f, "h"); err == nil {
+		t.Fatalf("sin apk ni opkg debe devolver error")
+	}
+}
+
+func TestInstallOwutFails(t *testing.T) {
+	f := &fakeSSHRunner{out: "ERROR: unable to select packages\n__owut_exit__=1\n"}
+	if _, err := InstallOwut(f, "h"); err == nil {
+		t.Fatalf("exit 1 del gestor debe ser error")
+	}
+}
+
+func TestParsePlatform(t *testing.T) {
+	cases := []struct {
+		name       string
+		out        string
+		wantOwut   bool
+		wantVendor string
+	}{
+		{"vanilla con owut", "__owut__\n", true, ""},
+		{"vanilla sin owut", "", false, ""},
+		{"GL sin owut", "__gl__\n", false, "gl-inet"},
+		{"GL con owut instalado", "__owut__\n__gl__\n", true, "gl-inet"},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			got := ParsePlatform(c.out)
+			if got.Owut != c.wantOwut || got.Vendor != c.wantVendor {
+				t.Fatalf("ParsePlatform(%q) = %+v", c.out, got)
+			}
+		})
+	}
+}
+
+func TestParseMissingPkgs(t *testing.T) {
+	// Salida real de owut check -v en un router con un paquete local sin feed.
+	out := `Collecting package data ...
+  netgrip                            0.71.0-r1                      missing to-version
+1 packages missing in target version, cannot upgrade
+46 packages are out-of-date
+It is safe to proceed with an upgrade (re-run with '--verbose' for details)
+`
+	pkgs := ParseMissingPkgs(out)
+	if len(pkgs) != 1 || pkgs[0] != "netgrip" {
+		t.Fatalf("ParseMissingPkgs = %v, esperaba [netgrip]", pkgs)
+	}
+	if got := ParseMissingPkgs("sin nada relevante"); got != nil {
+		t.Fatalf("sin matches debe devolver nil, got %v", got)
+	}
+}

+ 272 - 0
server-go/internal/firmware/recurrence.go

@@ -0,0 +1,272 @@
+// recurrence.go - programación recurrente de firmware por router (#761).
+//
+// Patrón de speedtest (#744) y backups (#741): ajustes en kv, vencimiento
+// derivado del last_run PERSISTIDO (reinicios/auto-update no resetean el
+// reloj) y decisión pura RecurrenceDue. La ejecución es idempotente por
+// contrato: el disparo solo flashea si la versión instalada difiere del
+// target guardado; un router al día es un no-op silencioso.
+package firmware
+
+import (
+	"database/sql"
+	"fmt"
+	"log"
+	"strconv"
+	"time"
+)
+
+// Kinds de recurrencia.
+const (
+	RecurrenceOnce    = "once"
+	RecurrenceWeekly  = "weekly"
+	RecurrenceMonthly = "monthly"
+)
+
+// Recurrence es la programación persistida de un router.
+type Recurrence struct {
+	Enabled bool `json:"enabled"`
+	// Kind: once (AtMs fijo, se desactiva tras disparar) | weekly
+	// (DayOfWeek a Time local) | monthly (DayOfMonth a Time local; clamp
+	// al último día si el mes no lo tiene).
+	Kind       string `json:"kind"`
+	AtMs       int64  `json:"atMs,omitempty"`       // once, epoch ms
+	DayOfWeek  *int   `json:"dayOfWeek,omitempty"`  // 0=domingo..6 (weekly)
+	DayOfMonth *int   `json:"dayOfMonth,omitempty"` // 1..31 (monthly)
+	Time       string `json:"time,omitempty"`       // "HH:MM" hora local
+	LastRunMs  int64  `json:"lastRunMs,omitempty"`  // último disparo (cualquier resultado)
+}
+
+// ValidateRecurrence comprueba la coherencia kind/campos (patrón speedtest).
+func ValidateRecurrence(rc Recurrence) error {
+	switch rc.Kind {
+	case RecurrenceOnce:
+		if rc.AtMs <= 0 {
+			return fmt.Errorf("once exige atMs (epoch ms)")
+		}
+	case RecurrenceWeekly:
+		if rc.DayOfWeek == nil || *rc.DayOfWeek < 0 || *rc.DayOfWeek > 6 {
+			return fmt.Errorf("weekly exige dayOfWeek 0-6 (0 = domingo)")
+		}
+		if !validRecTime(rc.Time) {
+			return fmt.Errorf("weekly exige time HH:MM")
+		}
+	case RecurrenceMonthly:
+		if rc.DayOfMonth == nil || *rc.DayOfMonth < 1 || *rc.DayOfMonth > 31 {
+			return fmt.Errorf("monthly exige dayOfMonth 1-31")
+		}
+		if !validRecTime(rc.Time) {
+			return fmt.Errorf("monthly exige time HH:MM")
+		}
+	default:
+		return fmt.Errorf("kind debe ser once, weekly o monthly")
+	}
+	return nil
+}
+
+// RecurrenceDue decide si toca disparar (función pura). El vencimiento
+// siempre deriva de LastRunMs: weekly exige día exacto de la semana y que el
+// slot de hoy sea posterior al último disparo; monthly aplica clamp de fin de
+// mes; once dispara una única vez (AtMs) aunque LastRunMs sea 0.
+func RecurrenceDue(rc Recurrence, now time.Time) bool {
+	if !rc.Enabled {
+		return false
+	}
+	switch rc.Kind {
+	case RecurrenceOnce:
+		return now.UnixMilli() >= rc.AtMs && rc.LastRunMs < rc.AtMs
+	case RecurrenceWeekly:
+		dow := 0
+		if rc.DayOfWeek != nil {
+			dow = *rc.DayOfWeek
+		}
+		if int(now.Weekday()) != dow {
+			return false
+		}
+		slot := recTodaySlot(rc.Time, now)
+		return !now.Before(slot) && rc.LastRunMs < slot.UnixMilli()
+	case RecurrenceMonthly:
+		dom := 1
+		if rc.DayOfMonth != nil {
+			dom = *rc.DayOfMonth
+		}
+		h, m := recParseTime(rc.Time)
+		slot := time.Date(now.Year(), now.Month(), recClampDay(dom, now), h, m, 0, 0, now.Location())
+		return !now.Before(slot) && rc.LastRunMs < slot.UnixMilli()
+	}
+	return false
+}
+
+// NextRecurrenceAt calcula el próximo disparo para la UI (Status).
+func NextRecurrenceAt(rc Recurrence, now time.Time) time.Time {
+	h, m := recParseTime(rc.Time)
+	switch rc.Kind {
+	case RecurrenceOnce:
+		return time.UnixMilli(rc.AtMs)
+	case RecurrenceWeekly:
+		dow := 0
+		if rc.DayOfWeek != nil {
+			dow = *rc.DayOfWeek
+		}
+		today := recTodaySlot(rc.Time, now)
+		if int(now.Weekday()) == dow && (now.Before(today) || rc.LastRunMs < today.UnixMilli()) {
+			return today
+		}
+		days := (dow - int(now.Weekday()) + 7) % 7
+		if days == 0 {
+			days = 7
+		}
+		d := now.AddDate(0, 0, days)
+		return time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, now.Location())
+	case RecurrenceMonthly:
+		dom := 1
+		if rc.DayOfMonth != nil {
+			dom = *rc.DayOfMonth
+		}
+		slot := time.Date(now.Year(), now.Month(), recClampDay(dom, now), h, m, 0, 0, now.Location())
+		if now.Before(slot) || rc.LastRunMs < slot.UnixMilli() {
+			return slot
+		}
+		next := now.AddDate(0, 1, 0)
+		return time.Date(next.Year(), next.Month(), recClampDay(dom, next), h, m, 0, 0, now.Location())
+	}
+	return time.Time{}
+}
+
+// --- Persistencia kv (claves firmware.recurrence.<router>.<campo>) ---
+
+func recKey(routerID, field string) string {
+	return "firmware.recurrence." + routerID + "." + field
+}
+
+// LoadRecurrence lee la programación del router (valores ausentes = default).
+func LoadRecurrence(db *sql.DB, routerID string) Recurrence {
+	rc := Recurrence{}
+	if db == nil || routerID == "" {
+		return rc
+	}
+	rc.Enabled = recKVGet(db, recKey(routerID, "enabled")) == "1"
+	rc.Kind = recKVGet(db, recKey(routerID, "kind"))
+	rc.AtMs = recKVParseInt(db, recKey(routerID, "at_ms"))
+	rc.LastRunMs = recKVParseInt(db, recKey(routerID, "last_run"))
+	if v, ok := recKVIntPtr(db, recKey(routerID, "dow")); ok {
+		rc.DayOfWeek = v
+	}
+	if v, ok := recKVIntPtr(db, recKey(routerID, "dom")); ok {
+		rc.DayOfMonth = v
+	}
+	rc.Time = recKVGet(db, recKey(routerID, "time"))
+	return rc
+}
+
+// SaveRecurrence persiste la programación completa (UPSERT por clave).
+func SaveRecurrence(db *sql.DB, routerID string, rc Recurrence) error {
+	if db == nil || routerID == "" {
+		return fmt.Errorf("firmware: db o router vacío")
+	}
+	if err := ValidateRecurrence(rc); err != nil {
+		return err
+	}
+	recKVSet(db, recKey(routerID, "enabled"), boolRecStr(rc.Enabled))
+	recKVSet(db, recKey(routerID, "kind"), rc.Kind)
+	recKVSet(db, recKey(routerID, "at_ms"), strconv.FormatInt(rc.AtMs, 10))
+	recKVSet(db, recKey(routerID, "last_run"), strconv.FormatInt(rc.LastRunMs, 10))
+	dow, dom := "", ""
+	if rc.DayOfWeek != nil {
+		dow = strconv.Itoa(*rc.DayOfWeek)
+	}
+	if rc.DayOfMonth != nil {
+		dom = strconv.Itoa(*rc.DayOfMonth)
+	}
+	recKVSet(db, recKey(routerID, "dow"), dow)
+	recKVSet(db, recKey(routerID, "dom"), dom)
+	recKVSet(db, recKey(routerID, "time"), rc.Time)
+	return nil
+}
+
+// SetRecurrenceLastRun actualiza solo el último disparo (lo toca el loop).
+func SetRecurrenceLastRun(db *sql.DB, routerID string, ms int64) {
+	recKVSet(db, recKey(routerID, "last_run"), strconv.FormatInt(ms, 10))
+}
+
+// DisableRecurrence apaga la programación (config inválida detectada en
+// runtime: sin target guardado, etc.).
+func DisableRecurrence(db *sql.DB, routerID string) {
+	recKVSet(db, recKey(routerID, "enabled"), "0")
+}
+
+// --- helpers (patrón speedtest, locales del paquete) ---
+
+func validRecTime(v string) bool {
+	if v == "" {
+		return false
+	}
+	_, err := time.Parse("15:04", v)
+	return err == nil
+}
+
+func recParseTime(v string) (int, int) {
+	t, err := time.Parse("15:04", v)
+	if err != nil {
+		return 0, 0
+	}
+	return t.Hour(), t.Minute()
+}
+
+func recDaysInMonth(t time.Time) int {
+	return time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()).Day()
+}
+
+func recClampDay(dom int, t time.Time) int {
+	if dom < 1 {
+		dom = 1
+	}
+	if max := recDaysInMonth(t); dom > max {
+		dom = max
+	}
+	return dom
+}
+
+func recTodaySlot(v string, now time.Time) time.Time {
+	h, m := recParseTime(v)
+	return time.Date(now.Year(), now.Month(), now.Day(), h, m, 0, 0, now.Location())
+}
+
+func boolRecStr(b bool) string {
+	if b {
+		return "1"
+	}
+	return "0"
+}
+
+func recKVGet(db *sql.DB, key string) string {
+	var v string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
+		return ""
+	}
+	return v
+}
+
+func recKVParseInt(db *sql.DB, key string) int64 {
+	n, _ := strconv.ParseInt(recKVGet(db, key), 10, 64)
+	return n
+}
+
+func recKVIntPtr(db *sql.DB, key string) (*int, bool) {
+	raw := recKVGet(db, key)
+	if raw == "" {
+		return nil, false
+	}
+	n, err := strconv.Atoi(raw)
+	if err != nil {
+		return nil, false
+	}
+	return &n, true
+}
+
+func recKVSet(db *sql.DB, key, val string) {
+	if _, err := db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		key, val); err != nil {
+		log.Printf("[firmware] kv set %s: %v", key, err)
+	}
+}

+ 125 - 0
server-go/internal/firmware/recurrence_test.go

@@ -0,0 +1,125 @@
+// recurrence_test.go - tests de la programación recurrente de firmware
+// (#761): vencimiento weekly/monthly/once (patrón de scheduler744_test) y
+// persistencia kv roundtrip.
+package firmware
+
+import (
+	"testing"
+	"time"
+)
+
+func intPtr(v int) *int { return &v }
+
+func TestRecurrenceDueWeekly(t *testing.T) {
+	// Domingo 2026-09-13 10:00 local (fecha del desarrollo de #761).
+	now := time.Date(2026, 9, 13, 10, 0, 0, 0, time.Local)
+	slot := time.Date(2026, 9, 13, 3, 30, 0, 0, time.Local)
+	cases := []struct {
+		name string
+		rc   Recurrence
+		now  time.Time
+		want bool
+	}{
+		{"domingo despues del slot sin lastRun", Recurrence{Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(0), Time: "03:30"}, now, true},
+		{"domingo antes del slot", Recurrence{Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(0), Time: "11:00"}, now, false},
+		{"otro dia", Recurrence{Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(3), Time: "03:30"}, now, false},
+		{"ya disparado hoy", Recurrence{Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(0), Time: "03:30", LastRunMs: slot.UnixMilli()}, now, false},
+		{"disparado ayer", Recurrence{Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(0), Time: "03:30", LastRunMs: slot.Add(-24 * time.Hour).UnixMilli()}, now, true},
+		{"disabled", Recurrence{Enabled: false, Kind: RecurrenceWeekly, DayOfWeek: intPtr(0), Time: "03:30"}, now, false},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			if got := RecurrenceDue(c.rc, c.now); got != c.want {
+				t.Fatalf("RecurrenceDue = %v, esperaba %v", got, c.want)
+			}
+		})
+	}
+}
+
+func TestRecurrenceDueMonthly(t *testing.T) {
+	now := time.Date(2026, 9, 12, 10, 0, 0, 0, time.Local)
+	slot := time.Date(2026, 9, 12, 4, 0, 0, 0, time.Local)
+	cases := []struct {
+		name string
+		rc   Recurrence
+		now  time.Time
+		want bool
+	}{
+		{"dia 12 a las 04", Recurrence{Enabled: true, Kind: RecurrenceMonthly, DayOfMonth: intPtr(12), Time: "04:00"}, now, true},
+		{"dia 13", Recurrence{Enabled: true, Kind: RecurrenceMonthly, DayOfMonth: intPtr(13), Time: "04:00"}, now, false},
+		{"ya disparado este mes", Recurrence{Enabled: true, Kind: RecurrenceMonthly, DayOfMonth: intPtr(12), Time: "04:00", LastRunMs: slot.UnixMilli()}, now, false},
+		{"clamp 31 en febrero", Recurrence{Enabled: true, Kind: RecurrenceMonthly, DayOfMonth: intPtr(31), Time: "04:00"}, time.Date(2026, 2, 28, 5, 0, 0, 0, time.Local), true},
+	}
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			if got := RecurrenceDue(c.rc, c.now); got != c.want {
+				t.Fatalf("RecurrenceDue = %v, esperaba %v", got, c.want)
+			}
+		})
+	}
+}
+
+func TestRecurrenceDueOnce(t *testing.T) {
+	now := time.Now()
+	past := now.Add(-time.Hour).UnixMilli()
+	future := now.Add(time.Hour).UnixMilli()
+	if !RecurrenceDue(Recurrence{Enabled: true, Kind: RecurrenceOnce, AtMs: past}, now) {
+		t.Fatalf("once vencido sin disparar debe disparar")
+	}
+	if RecurrenceDue(Recurrence{Enabled: true, Kind: RecurrenceOnce, AtMs: past, LastRunMs: past + 1}, now) {
+		t.Fatalf("once ya disparado no repite")
+	}
+	if RecurrenceDue(Recurrence{Enabled: true, Kind: RecurrenceOnce, AtMs: future}, now) {
+		t.Fatalf("once futuro no dispara")
+	}
+}
+
+func TestValidateRecurrence(t *testing.T) {
+	if err := ValidateRecurrence(Recurrence{Kind: RecurrenceWeekly}); err == nil {
+		t.Fatalf("weekly sin dayOfWeek/time debe fallar")
+	}
+	if err := ValidateRecurrence(Recurrence{Kind: RecurrenceMonthly, DayOfMonth: intPtr(12)}); err == nil {
+		t.Fatalf("monthly sin time debe fallar")
+	}
+	if err := ValidateRecurrence(Recurrence{Kind: RecurrenceOnce}); err == nil {
+		t.Fatalf("once sin atMs debe fallar")
+	}
+	if err := ValidateRecurrence(Recurrence{Kind: "hourly"}); err == nil {
+		t.Fatalf("kind desconocido debe fallar")
+	}
+	if err := ValidateRecurrence(Recurrence{Kind: RecurrenceWeekly, DayOfWeek: intPtr(5), Time: "23:59"}); err != nil {
+		t.Fatalf("weekly válida: %v", err)
+	}
+}
+
+func TestRecurrenceSaveLoadRoundtrip(t *testing.T) {
+	st := open(t)
+	rc := Recurrence{
+		Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(2), Time: "04:15",
+	}
+	if err := SaveRecurrence(st.db, "rt1", rc); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got := LoadRecurrence(st.db, "rt1")
+	if !got.Enabled || got.Kind != RecurrenceWeekly || got.DayOfWeek == nil || *got.DayOfWeek != 2 || got.Time != "04:15" {
+		t.Fatalf("roundtrip: %+v", got)
+	}
+	SetRecurrenceLastRun(st.db, "rt1", 12345)
+	if LoadRecurrence(st.db, "rt1").LastRunMs != 12345 {
+		t.Fatalf("lastRun no persistió")
+	}
+	DisableRecurrence(st.db, "rt1")
+	if LoadRecurrence(st.db, "rt1").Enabled {
+		t.Fatalf("disable no aplicó")
+	}
+}
+
+func TestNextRecurrenceAtWeekly(t *testing.T) {
+	// Domingo 10:00, programado martes 04:15 -> próximo martes.
+	now := time.Date(2026, 9, 13, 10, 0, 0, 0, time.Local)
+	rc := Recurrence{Enabled: true, Kind: RecurrenceWeekly, DayOfWeek: intPtr(2), Time: "04:15"}
+	next := NextRecurrenceAt(rc, now)
+	if next.Weekday() != time.Tuesday || next.Hour() != 4 || next.Minute() != 15 {
+		t.Fatalf("next = %v (%s), esperaba martes 04:15", next, next.Weekday())
+	}
+}

+ 17 - 4
server-go/internal/firmware/store.go

@@ -33,6 +33,9 @@ type Upgrade struct {
 	// upgrade es del flujo manual/inmediato. Nota: StartedAt/FinishedAt siguen
 	// upgrade es del flujo manual/inmediato. Nota: StartedAt/FinishedAt siguen
 	// en unix SEGUNDOS (convención previa), ScheduledFor en ms.
 	// en unix SEGUNDOS (convención previa), ScheduledFor en ms.
 	ScheduledFor *int64 `json:"scheduledFor,omitempty"`
 	ScheduledFor *int64 `json:"scheduledFor,omitempty"`
+	// Engine (#761): "owut" (attended sysupgrade vía ASU) o "" (motor
+	// clásico con imagen URL+checksum).
+	Engine string `json:"engine,omitempty"`
 }
 }
 
 
 // Store persiste targets y upgrades.
 // Store persiste targets y upgrades.
@@ -136,9 +139,10 @@ func scanUpgrade(sc rowScanner) (*Upgrade, error) {
 	var u Upgrade
 	var u Upgrade
 	var finished, scheduled sql.NullInt64
 	var finished, scheduled sql.NullInt64
 	var errStr, backup sql.NullString
 	var errStr, backup sql.NullString
+	var engine sql.NullString
 	if err := sc.Scan(
 	if err := sc.Scan(
 		&u.ID, &u.RouterID, &u.TargetVersion, &u.TargetURL, &u.Checksum,
 		&u.ID, &u.RouterID, &u.TargetVersion, &u.TargetURL, &u.Checksum,
-		&u.Status, &errStr, &backup, &u.StartedAt, &finished, &scheduled,
+		&u.Status, &errStr, &backup, &u.StartedAt, &finished, &scheduled, &engine,
 	); err != nil {
 	); err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
@@ -154,13 +158,22 @@ func scanUpgrade(sc rowScanner) (*Upgrade, error) {
 	if backup.Valid {
 	if backup.Valid {
 		u.BackupPath = backup.String
 		u.BackupPath = backup.String
 	}
 	}
+	if engine.Valid {
+		u.Engine = engine.String
+	}
 	return &u, nil
 	return &u, nil
 }
 }
 
 
+// SetEngine marca el motor que ejecuta el upgrade (#761: owut vs clásico).
+func (s *Store) SetEngine(id int64, engine string) error {
+	_, err := s.db.Exec(`UPDATE firmware_upgrades SET engine = ? WHERE id = ?`, engine, id)
+	return err
+}
+
 // LatestUpgrade devuelve el upgrade más reciente de un router.
 // LatestUpgrade devuelve el upgrade más reciente de un router.
 func (s *Store) LatestUpgrade(routerID string) (*Upgrade, error) {
 func (s *Store) LatestUpgrade(routerID string) (*Upgrade, error) {
 	u, err := scanUpgrade(s.db.QueryRow(`
 	u, err := scanUpgrade(s.db.QueryRow(`
-		SELECT id, router_id, target_version, target_url, checksum, status, error, backup_path, started_at, finished_at, scheduled_for
+		SELECT id, router_id, target_version, target_url, checksum, status, error, backup_path, started_at, finished_at, scheduled_for, engine
 		FROM firmware_upgrades
 		FROM firmware_upgrades
 		WHERE router_id = ?
 		WHERE router_id = ?
 		ORDER BY started_at DESC
 		ORDER BY started_at DESC
@@ -178,7 +191,7 @@ func (s *Store) LatestUpgrade(routerID string) (*Upgrade, error) {
 // GetUpgradeByID busca un upgrade por ID (para validar propiedad del agente).
 // GetUpgradeByID busca un upgrade por ID (para validar propiedad del agente).
 func (s *Store) GetUpgradeByID(id int64) (*Upgrade, error) {
 func (s *Store) GetUpgradeByID(id int64) (*Upgrade, error) {
 	u, err := scanUpgrade(s.db.QueryRow(`
 	u, err := scanUpgrade(s.db.QueryRow(`
-		SELECT id, router_id, target_version, target_url, checksum, status, error, backup_path, started_at, finished_at, scheduled_for
+		SELECT id, router_id, target_version, target_url, checksum, status, error, backup_path, started_at, finished_at, scheduled_for, engine
 		FROM firmware_upgrades WHERE id = ?
 		FROM firmware_upgrades WHERE id = ?
 	`, id))
 	`, id))
 	if err == sql.ErrNoRows {
 	if err == sql.ErrNoRows {
@@ -249,7 +262,7 @@ func (s *Store) CancelScheduled(routerID string) error {
 // scheduled_for <= nowMs), ordenadas por hora para lanzarlas en orden.
 // scheduled_for <= nowMs), ordenadas por hora para lanzarlas en orden.
 func (s *Store) DueScheduled(nowMs int64) ([]Upgrade, error) {
 func (s *Store) DueScheduled(nowMs int64) ([]Upgrade, error) {
 	rows, err := s.db.Query(`
 	rows, err := s.db.Query(`
-		SELECT id, router_id, target_version, target_url, checksum, status, error, backup_path, started_at, finished_at, scheduled_for
+		SELECT id, router_id, target_version, target_url, checksum, status, error, backup_path, started_at, finished_at, scheduled_for, engine
 		FROM firmware_upgrades
 		FROM firmware_upgrades
 		WHERE status = 'scheduled' AND scheduled_for <= ?
 		WHERE status = 'scheduled' AND scheduled_for <= ?
 		ORDER BY scheduled_for ASC
 		ORDER BY scheduled_for ASC

+ 8 - 2
server-go/internal/httpapi/firmware.go

@@ -47,6 +47,9 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 		return
 		return
 	}
 	}
 
 
+	// Ciclo owut completo + recurrencia (#761).
+	s.registerFirmwareOwutRoutes(mux)
+
 	mux.Handle("GET /api/firmware-upgrades", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 	mux.Handle("GET /api/firmware-upgrades", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		if s.db == nil {
 		if s.db == nil {
 			writeError(w, http.StatusServiceUnavailable, "no_db")
 			writeError(w, http.StatusServiceUnavailable, "no_db")
@@ -202,8 +205,11 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 		if st := readJSONBody(w, r, &body); st != 0 {
 		if st := readJSONBody(w, r, &body); st != 0 {
 			return
 			return
 		}
 		}
-		if body.Model == "" || body.TargetVersion == "" || body.TargetURL == "" {
-			writeError(w, http.StatusBadRequest, "invalid_body", "model, targetVersion y targetUrl son requeridos")
+		// #761: la URL de la imagen ya no es obligatoria al guardar el target;
+		// el flujo owut la construye ASU. El motor clásico (URL+checksum) la
+		// sigue exigiendo al disparar (ErrNoTarget en StartUpgrade).
+		if body.Model == "" || body.TargetVersion == "" {
+			writeError(w, http.StatusBadRequest, "invalid_body", "model y targetVersion son requeridos")
 			return
 			return
 		}
 		}
 		if err := s.firmware.SetTarget(firmware.Target{
 		if err := s.firmware.SetTarget(firmware.Target{

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

@@ -0,0 +1,522 @@
+// firmware_owut.go - ciclo owut completo y recurrencia de firmware (#761).
+//
+// Endpoints: lista de versiones (dropdown), instalación del paquete owut,
+// upgrade desatendido (máquina de estados running -> rebooting -> done) y
+// programación recurrente (once/weekly/monthly, idempotente). El resultado
+// de cada intento (éxito o fallo) se emite como alerta urgent, que llega al
+// feed, push, webhook y Telegram con la configuración existente.
+package httpapi
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"log"
+	"net/http"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/firmware"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// Estados no terminales de un upgrade (clásico + owut).
+func owutUpgradeActive(status string) bool {
+	return status != "" && status != "done" && status != "failed"
+}
+
+// Cinturones de plataforma (#761): firmware de fabricante fuera, y sin owut
+// instalado no se lanza nada.
+var (
+	errVendorFirmware   = errors.New("firmware de fabricante (GL.iNet) sin soporte")
+	ErrOwutNotInstalled = errors.New("owut no está instalado en el router")
+)
+
+// alertEmitter lo cumple *alerts.Engine (mismo patrón que speedtest).
+type alertEmitter interface {
+	Emit(ev alerts.AlertEvent) bool
+}
+
+// platformCacheEntry cachea la plataforma (owut + vendor) por router (1 h):
+// el loop de recurrencia y los endpoints la consultan y sondear por SSH en
+// cada operación sería ruido innecesario.
+type platformCacheEntry struct {
+	p  firmware.Platform
+	at time.Time
+}
+
+const (
+	owutDetectCacheTTL = time.Hour
+	// owutRebootGrace: margen para que el router reinicie, vuelva el sondeo
+	// y el board info reporte la versión nueva.
+	owutRebootGrace = 15 * time.Minute
+	// owutSSHMinRun: si la sesión SSH muere antes de este umbral, no fue el
+	// reinicio del sysupgrade: el comando ni arrancó.
+	owutSSHMinRun = 30 * time.Second
+	recTickEvery  = time.Minute
+)
+
+func (s *server) registerFirmwareOwutRoutes(mux *http.ServeMux) {
+	if s.firmware == nil {
+		return
+	}
+
+	// GET versions: candidatos del dropdown (requiere owut en el router).
+	mux.Handle("GET /api/firmware-upgrades/{routerId}/owut-versions", 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
+		}
+		resp := struct {
+			Current        string                 `json:"current"`
+			OwutAvailable  bool                   `json:"owutAvailable"`
+			VendorFirmware string                 `json:"vendorFirmware,omitempty"`
+			Versions       []firmware.OwutVersion `json:"versions"`
+			Error          string                 `json:"error,omitempty"`
+		}{Current: s.detectedFirmwareVersion(id)}
+		plat := s.platform(id, host)
+		if plat.Vendor != "" {
+			// Firmware de fabricante: sus updates los gestiona el vendor.
+			resp.VendorFirmware = plat.Vendor
+			resp.Versions = []firmware.OwutVersion{}
+			writeJSON(w, http.StatusOK, resp)
+			return
+		}
+		if !plat.Owut {
+			resp.Versions = []firmware.OwutVersion{}
+			writeJSON(w, http.StatusOK, resp)
+			return
+		}
+		resp.OwutAvailable = true
+		versions, err := firmware.ListOwutVersions(s.pool, host, resp.Current)
+		if err != nil {
+			resp.Error = err.Error()
+			resp.Versions = []firmware.OwutVersion{}
+		} else {
+			resp.Versions = versions
+		}
+		writeJSON(w, http.StatusOK, resp)
+	})))
+
+	// POST owut-install: instala el paquete owut con apk u opkg.
+	mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-install", 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
+		}
+		if s.platform(id, host).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
+		}
+		output, err := firmware.InstallOwut(s.pool, host)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "owut_install_failed", err.Error())
+			return
+		}
+		s.invalidatePlatformCache(id)
+		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "output": output})
+	})))
+
+	// POST owut-upgrade: lanza el attended upgrade desatendido (ASU).
+	mux.Handle("POST /api/firmware-upgrades/{routerId}/owut-upgrade", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		var body struct {
+			TargetVersion string   `json:"targetVersion"`
+			RemovePkgs    []string `json:"removePackages"`
+		}
+		if st := readJSONBody(w, r, &body); st != 0 {
+			return
+		}
+		if body.TargetVersion == "" {
+			writeError(w, http.StatusBadRequest, "invalid_body", "targetVersion es requerido")
+			return
+		}
+		if !firmware.ValidOpenWrtVersion(body.TargetVersion) {
+			writeError(w, http.StatusBadRequest, "invalid_target_version",
+				"targetVersion debe ser una versión OpenWrt (p. ej. 25.12.5), no un texto libre")
+			return
+		}
+		if host := s.hostOfRouter(id); host != "" && s.platform(id, host).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
+		}
+		upgradeID, err := s.startOwutUpgrade(id, body.TargetVersion, "manual", body.RemovePkgs)
+		switch {
+		case errors.Is(err, firmware.ErrUpgradeInProgress):
+			writeError(w, http.StatusConflict, "upgrade_in_progress", "Ya hay un upgrade en curso")
+		case errors.Is(err, errVendorFirmware):
+			writeError(w, http.StatusUnprocessableEntity, "vendor_firmware",
+				"El router lleva firmware del fabricante (GL.iNet): NetPulse no gestiona sus actualizaciones, usa su propio panel.")
+		case errors.Is(err, ErrOwutNotInstalled):
+			writeError(w, http.StatusPreconditionFailed, "owut_not_installed",
+				"owut no está instalado en el router: instálalo primero con el botón Instalar owut.")
+		case errors.Is(err, errRouterNotFound):
+			writeError(w, http.StatusNotFound, "not_found")
+		case err != nil:
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+		default:
+			writeJSON(w, http.StatusAccepted, map[string]any{"upgradeId": upgradeID, "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")
+		rc := firmware.LoadRecurrence(s.db.DB, id)
+		out := map[string]any{"recurrence": rc}
+		if rc.Enabled {
+			next := firmware.NextRecurrenceAt(rc, time.Now())
+			if !next.IsZero() {
+				out["nextRunMs"] = next.UnixMilli()
+			}
+		}
+		writeJSON(w, http.StatusOK, out)
+	})))
+
+	mux.Handle("PUT /api/firmware-upgrades/{routerId}/recurrence", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		var body firmware.Recurrence
+		if st := readJSONBody(w, r, &body); st != 0 {
+			return
+		}
+		prev := firmware.LoadRecurrence(s.db.DB, id)
+		body.LastRunMs = prev.LastRunMs
+		if err := firmware.SaveRecurrence(s.db.DB, id, body); err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_body", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+	})))
+
+	mux.Handle("DELETE /api/firmware-upgrades/{routerId}/recurrence", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		id := r.PathValue("routerId")
+		firmware.DisableRecurrence(s.db.DB, id)
+		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+	})))
+}
+
+// startOwutUpgrade crea la fila del upgrade y lanza la goroutine que lo
+// ejecuta por SSH. El POST responde 202 inmediatamente; el progreso se sigue
+// por GET /api/firmware-upgrades (item.upgrade).
+func (s *server) startOwutUpgrade(routerID, targetVersion, origin string, removePkgs []string) (int64, error) {
+	host := s.hostOfRouter(routerID)
+	if host == "" {
+		return 0, errRouterNotFound
+	}
+	if s.pool == nil {
+		return 0, errors.New("sin pool SSH")
+	}
+	// Cinturones de platform (#761): firmware de fabricante fuera, y sin
+	// owut instalado no se lanza nada (el comando moriría en 127).
+	if plat := s.platform(routerID, host); plat.Vendor != "" {
+		return 0, errVendorFirmware
+	} else if !plat.Owut {
+		return 0, ErrOwutNotInstalled
+	}
+	if up, _ := s.firmware.LatestUpgrade(routerID); up != nil && owutUpgradeActive(up.Status) {
+		return 0, firmware.ErrUpgradeInProgress
+	}
+	id, err := s.firmware.BeginUpgrade(routerID, targetVersion, "", "")
+	if err != nil {
+		return 0, err
+	}
+	_ = s.firmware.SetEngine(id, "owut")
+	go s.runOwutUpgrade(id, routerID, host, targetVersion, origin, removePkgs)
+	return id, nil
+}
+
+// runOwutUpgrade ejecuta `owut upgrade` y decide la transición. La muerte de
+// la sesión SSH tras >owutSSHMinRun es el final NORMAL del flash (el sysupgrade
+// reinicia el router); el resultado se confirma mirando el board info.
+func (s *server) runOwutUpgrade(id int64, routerID, host, target, origin string, removePkgs []string) {
+	from := ""
+	if s.boardVersionFn != nil {
+		from = s.boardVersionFn(routerID)
+	}
+	cmd := firmware.OwutUpgradeCmd(target, from, removePkgs)
+	_ = s.firmware.SetStatus(id, "running", "", "")
+	// #761: antes de flashear, asegurar que el stack presente (netgrip /
+	// agente) sobrevive al update (ASU no puede empaquetarlos: sin feed).
+	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, cmd)
+	dur := time.Since(start)
+	switch {
+	case err == nil && exit == 0 && strings.Contains(out, "no changes"):
+		_ = s.firmware.SetStatus(id, "done", "sin cambios: ya estaba al día", "")
+	case (err == nil && exit == 0) || (err != nil && dur >= owutSSHMinRun):
+		s.awaitReboot(id, routerID, target, origin, from)
+	default:
+		msg := owutTail(out, err)
+		if strings.TrimSpace(msg) == "" {
+			msg = fmt.Sprintf("owut terminó sin salida (exit %d)", exit)
+		}
+		log.Printf("[firmware] owut upgrade %s falló (exit %d): %s", routerID, exit, msg)
+		_ = s.firmware.SetStatus(id, "failed", msg, "")
+		s.emitFirmwareResult(routerID, from, target, origin, 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) {
+	_ = s.firmware.SetStatus(id, "rebooting", "", "")
+	deadline := time.Now().Add(owutRebootGrace)
+	for time.Now().Before(deadline) {
+		time.Sleep(20 * time.Second)
+		if v := s.detectedFirmwareVersion(routerID); v == target && target != "" {
+			_ = s.firmware.SetStatus(id, "done", "", "")
+			s.emitFirmwareResult(routerID, from, target, origin, true, "")
+			return
+		}
+	}
+	msg := "sin confirmación tras el reinicio (¿versión instalada distinta del objetivo?)"
+	_ = s.firmware.SetStatus(id, "failed", msg, "")
+	s.emitFirmwareResult(routerID, from, target, origin, false, msg)
+}
+
+// detectedFirmwareVersion: última versión reportada por el board info.
+func (s *server) detectedFirmwareVersion(routerID string) string {
+	if s.adapter == nil {
+		return ""
+	}
+	if bi := s.adapter.BoardInfoFor(routerID); bi != nil {
+		return bi.Release.Version
+	}
+	return ""
+}
+
+// boardInfoFor expone el board info completo (tests y debug).
+func (s *server) boardInfoFor(routerID string) *adapters.BoardInfo {
+	if s.adapter == nil {
+		return nil
+	}
+	return s.adapter.BoardInfoFor(routerID)
+}
+
+// owutTail recorta la salida de owut para el campo error (últimas líneas).
+func owutTail(out string, err error) string {
+	msg := strings.TrimSpace(out)
+	if err != nil {
+		if msg != "" {
+			msg += "; "
+		}
+		msg += err.Error()
+	}
+	if len(msg) > 400 {
+		msg = "..." + msg[len(msg)-400:]
+	}
+	return msg
+}
+
+// emitFirmwareResult notifica el resultado de un intento de upgrade (éxito o
+// fallo, manual o programado). Urgent para cruzar el Notifier (Telegram,
+// push, webhook); severity info/warn según resultado.
+func (s *server) emitFirmwareResult(routerID, from, to, origin string, ok bool, detail string) {
+	if s.alertEmitter == nil {
+		return
+	}
+	name := routerID
+	if rt := s.routerName(routerID); rt != "" {
+		name = rt
+	}
+	originTxt := "manual"
+	if origin == "scheduled" {
+		originTxt = "programado"
+	}
+	ev := alerts.AlertEvent{
+		ID:       fmt.Sprintf("alert-firmware-upgrade-%s-%d", routerID, time.Now().UnixMilli()),
+		Category: alerts.CatSystem,
+		Urgent:   true,
+		RouterID: routerID,
+		Time:     "ahora mismo",
+		Ts:       time.Now().Unix(),
+		Vars:     map[string]string{"router": name, "from": from, "to": to, "origin": originTxt},
+	}
+	if ok {
+		ev.Severity = "info"
+		ev.Type = "firmware-upgrade-done"
+		ev.Title = "Firmware actualizado"
+		ev.Description = fmt.Sprintf("%s: %s -> %s (owut, %s)", name, from, to, originTxt)
+	} else {
+		ev.Severity = "warn"
+		ev.Type = "firmware-upgrade-failed"
+		ev.Title = "Actualización de firmware fallida"
+		ev.Description = fmt.Sprintf("%s: objetivo %s (owut, %s): %s", name, to, originTxt, detail)
+		ev.Vars["detail"] = detail
+	}
+	s.alertEmitter.Emit(ev)
+}
+
+// emitFirmwareConfigAlert avisa de una recurrencia desactivada por config
+// inválida (sin target guardado, sin motor disponible).
+func (s *server) emitFirmwareConfigAlert(routerID, reason string) {
+	if s.alertEmitter == nil {
+		return
+	}
+	name := routerID
+	if rt := s.routerName(routerID); rt != "" {
+		name = rt
+	}
+	s.alertEmitter.Emit(alerts.AlertEvent{
+		ID:          fmt.Sprintf("alert-firmware-recurrence-%s-%d", routerID, time.Now().UnixMilli()),
+		Category:    alerts.CatSystem,
+		Urgent:      true,
+		Severity:    "warn",
+		RouterID:    routerID,
+		Title:       "Programación de firmware desactivada",
+		Description: fmt.Sprintf("%s: %s", name, reason),
+		Time:        "ahora mismo",
+		Ts:          time.Now().Unix(),
+	})
+}
+
+// routerName resuelve el nombre visible del router (fallback: su ID).
+func (s *server) routerName(routerID string) string {
+	if s.db == nil {
+		return ""
+	}
+	for _, rt := range routerstore.ListRouters(s.db.DB) {
+		if rt.ID == routerID {
+			return rt.Name
+		}
+	}
+	return ""
+}
+
+// --- Detección owut cacheada ---
+
+func (s *server) platform(routerID, host string) firmware.Platform {
+	s.owutMu.Lock()
+	defer s.owutMu.Unlock()
+	if s.owutCache == nil {
+		s.owutCache = map[string]platformCacheEntry{}
+	}
+	if e, ok := s.owutCache[routerID]; ok && time.Since(e.at) < owutDetectCacheTTL {
+		return e.p
+	}
+	p := firmware.DetectPlatform(s.pool, host)
+	s.owutCache[routerID] = platformCacheEntry{p: p, at: time.Now()}
+	return p
+}
+
+func (s *server) invalidatePlatformCache(routerID string) {
+	s.owutMu.Lock()
+	defer s.owutMu.Unlock()
+	delete(s.owutCache, routerID)
+}
+
+// --- Loop de recurrencia (#761) ---
+
+// firmwareRecurrenceLoop: tick corto; el vencimiento se deriva del last_run
+// persistido (reboot-safe). Solo en live (en demo no hay datos que actualizar).
+func (s *server) firmwareRecurrenceLoop(ctx context.Context, tickEvery time.Duration) {
+	ticker := time.NewTicker(tickEvery)
+	defer ticker.Stop()
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		case <-ticker.C:
+			s.recurrenceTick()
+		}
+	}
+}
+
+func (s *server) recurrenceTick() {
+	if s.db == nil || s.firmware == nil {
+		return
+	}
+	now := time.Now()
+	for _, rt := range routerstore.ListRouters(s.db.DB) {
+		if !agentUpgradeable(rt.Type) {
+			continue
+		}
+		rc := firmware.LoadRecurrence(s.db.DB, rt.ID)
+		if !firmware.RecurrenceDue(rc, now) {
+			continue
+		}
+		s.recMu.Lock()
+		if s.recInFlight[rt.ID] {
+			s.recMu.Unlock()
+			continue
+		}
+		if s.recInFlight == nil {
+			s.recInFlight = map[string]bool{}
+		}
+		s.recInFlight[rt.ID] = true
+		s.recMu.Unlock()
+		go func(id string) {
+			defer func() {
+				s.recMu.Lock()
+				delete(s.recInFlight, id)
+				s.recMu.Unlock()
+			}()
+			s.runRecurrenceShot(id)
+		}(rt.ID)
+	}
+}
+
+// runRecurrenceShot ejecuta un disparo vencido. Idempotente por contrato: si
+// la versión instalada ya coincide con el target, no-op silencioso; el
+// resultado real (éxito/fallo) se notifica desde la máquina de estados owut.
+func (s *server) runRecurrenceShot(routerID string) {
+	target, err := s.firmware.GetTarget(routerID)
+	if err != nil || target == nil || target.TargetVersion == "" {
+		firmware.DisableRecurrence(s.db.DB, routerID)
+		s.emitFirmwareConfigAlert(routerID, "sin target de firmware guardado")
+		return
+	}
+	current := ""
+	if s.boardVersionFn != nil {
+		current = s.boardVersionFn(routerID)
+	}
+	if current != "" && current == target.TargetVersion {
+		// Al día: el disparo consume el slot sin flashear nada (#761).
+		firmware.SetRecurrenceLastRun(s.db.DB, routerID, time.Now().UnixMilli())
+		return
+	}
+	firmware.SetRecurrenceLastRun(s.db.DB, routerID, time.Now().UnixMilli())
+	host := s.hostOfRouter(routerID)
+	if host != "" && s.pool != nil {
+		if plat := s.platform(routerID, host); plat.Vendor != "" {
+			firmware.DisableRecurrence(s.db.DB, routerID)
+			s.emitFirmwareConfigAlert(routerID, "router con firmware del fabricante (GL.iNet): sus actualizaciones las gestiona su propio panel")
+			return
+		}
+	}
+	if host != "" && s.pool != nil && s.platform(routerID, host).Owut {
+		if _, err := s.startOwutUpgrade(routerID, target.TargetVersion, "scheduled", nil); err != nil {
+			s.emitFirmwareResult(routerID, current, target.TargetVersion, "scheduled", false, err.Error())
+		}
+		return
+	}
+	// Sin owut: motor clásico si hay imagen URL+checksum configurada.
+	if target.TargetURL != "" && s.firmwareEngine != nil {
+		if _, err := s.firmwareEngine.StartUpgrade(routerID); err != nil {
+			s.emitFirmwareResult(routerID, current, target.TargetVersion, "scheduled", false, err.Error())
+		}
+		return
+	}
+	firmware.DisableRecurrence(s.db.DB, routerID)
+	s.emitFirmwareConfigAlert(routerID, "router sin owut y sin URL de imagen para el motor clásico")
+}

+ 160 - 0
server-go/internal/httpapi/firmware_owut_internal_test.go

@@ -0,0 +1,160 @@
+// firmware_owut_internal_test.go - tests internos (package httpapi) del
+// disparo recurrente: idempotencia cuando la versión instalada coincide con
+// el target, y autodesactivación con config inválida (#761).
+package httpapi
+
+import (
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/firmware"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// recFakeSSH registra comandos y responde owut instalado (para el camino
+// owut del disparo) sin tocar ningún router real.
+type recFakeSSH struct {
+	mu   sync.Mutex
+	cmds []string
+}
+
+func (f *recFakeSSH) Run(host, cmd string, _ time.Duration) (string, error) {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	f.cmds = append(f.cmds, cmd)
+	if strings.Contains(cmd, "command -v owut") {
+		return "__owut__\n", nil
+	}
+	if strings.Contains(cmd, "owut upgrade") {
+		return "There are no changes to upgrade\n__owut_exit__=0\n", nil
+	}
+	return "", nil
+}
+
+func (f *recFakeSSH) saw(substr string) bool {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	for _, c := range f.cmds {
+		if strings.Contains(c, substr) {
+			return true
+		}
+	}
+	return false
+}
+
+// makeRecServer monta un server mínimo (sin HTTP) con la BD, el store de
+// firmware, el pool fake y el hook de versión instalada.
+func makeRecServer(t *testing.T, installed string) (*server, string, *recFakeSSH) {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	r, err := routerstore.AddRouter(d.DB, routerstore.AddInput{
+		Name: "RecRouter", Host: "192.168.1.60", Type: "openwrt",
+	})
+	if err != nil {
+		t.Fatalf("add router: %v", err)
+	}
+	pool := &recFakeSSH{}
+	s := &server{
+		cfg: cfg, db: d, adapter: nil,
+		hub:    sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		secret: secret, pool: pool,
+		firmware:       firmware.NewStore(d.DB),
+		firmwareEngine: firmware.NewEngine(firmware.NewStore(d.DB), nil),
+	}
+	s.boardVersionFn = func(string) string { return installed }
+	return s, r.ID, pool
+}
+
+func TestRunRecurrenceShotNoOpWhenUpToDate(t *testing.T) {
+	s, rid, pool := makeRecServer(t, "25.12.5")
+	if err := s.firmware.SetTarget(firmware.Target{
+		RouterID: rid, Model: "x", CurrentVersion: "25.12.5",
+		TargetVersion: "25.12.5", TargetURL: "http://x/i.bin",
+	}); err != nil {
+		t.Fatalf("target: %v", err)
+	}
+	if err := firmware.SaveRecurrence(s.db.DB, rid, firmware.Recurrence{
+		Enabled: true, Kind: firmware.RecurrenceWeekly, DayOfWeek: func() *int { v := 0; return &v }(), Time: "00:00",
+	}); err != nil {
+		t.Fatalf("recurrence: %v", err)
+	}
+
+	s.runRecurrenceShot(rid)
+
+	if pool.saw("owut upgrade") {
+		t.Fatalf("al día no debe flashear: %v", pool.cmds)
+	}
+	if got := firmware.LoadRecurrence(s.db.DB, rid).LastRunMs; got == 0 {
+		t.Fatalf("lastRun debe quedar marcado tras el disparo")
+	}
+}
+
+func TestRunRecurrenceShotDisablesWithoutTarget(t *testing.T) {
+	s, rid, _ := makeRecServer(t, "25.12.5")
+	if err := firmware.SaveRecurrence(s.db.DB, rid, firmware.Recurrence{
+		Enabled: true, Kind: firmware.RecurrenceWeekly, DayOfWeek: func() *int { v := 1; return &v }(), Time: "00:00",
+	}); err != nil {
+		t.Fatalf("recurrence: %v", err)
+	}
+
+	s.runRecurrenceShot(rid)
+
+	if firmware.LoadRecurrence(s.db.DB, rid).Enabled {
+		t.Fatalf("sin target guardado la recurrencia debe autodesactivarse")
+	}
+}
+
+func TestRunRecurrenceShotLaunchesOwutWhenOutdated(t *testing.T) {
+	s, rid, pool := makeRecServer(t, "25.12.5")
+	if err := s.firmware.SetTarget(firmware.Target{
+		RouterID: rid, Model: "x", CurrentVersion: "25.12.5",
+		TargetVersion: "25.12.7", TargetURL: "",
+	}); err != nil {
+		t.Fatalf("target: %v", err)
+	}
+	if err := firmware.SaveRecurrence(s.db.DB, rid, firmware.Recurrence{
+		Enabled: true, Kind: firmware.RecurrenceWeekly, DayOfWeek: func() *int { v := 2; return &v }(), Time: "00:00",
+	}); err != nil {
+		t.Fatalf("recurrence: %v", err)
+	}
+
+	s.runRecurrenceShot(rid)
+
+	// El upgrade corre en goroutine: esperar a que el comando llegue al fake.
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) {
+		if pool.saw("owut upgrade -q -V '25.12.7'") {
+			if got := firmware.LoadRecurrence(s.db.DB, rid).LastRunMs; got == 0 {
+				t.Fatalf("lastRun debe quedar marcado tras el disparo")
+			}
+			return
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	t.Fatalf("desfasado debe lanzar owut upgrade -V 25.12.7: %v", pool.cmds)
+}

+ 313 - 0
server-go/internal/httpapi/firmware_owut_test.go

@@ -0,0 +1,313 @@
+// firmware_owut_test.go - contrato HTTP del ciclo owut completo (#761):
+// lista de versiones, instalación, upgrade desatendido y recurrencia.
+package httpapi_test
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+	"time"
+)
+
+// owutVersionsSample replica `owut versions` (salida real recortada).
+const owutVersionsSample = `Available 'version-to' values from https://sysupgrade.openwrt.org:
+  24.10 release branch
+    24.10.0
+    24.10.2 (latest)
+  25.12 release branch
+    25.12.5
+    25.12.7 (latest)
+`
+
+func reqJSON(t *testing.T, method, base, path, payload, cookie string) *http.Response {
+	t.Helper()
+	var body io.Reader
+	if payload != "" {
+		body = bytes.NewBufferString(payload)
+	}
+	req, err := http.NewRequest(method, base+path, body)
+	if err != nil {
+		t.Fatalf("new request: %v", err)
+	}
+	req.Header.Set("Content-Type", "application/json")
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("do: %v", err)
+	}
+	return res
+}
+
+func getJSONPath(t *testing.T, base, path, cookie string) *http.Response {
+	return reqJSON(t, http.MethodGet, base, path, "", cookie)
+}
+
+func putJSONPath(t *testing.T, base, path, payload, cookie string) *http.Response {
+	return reqJSON(t, http.MethodPut, base, path, payload, cookie)
+}
+
+func deleteJSONPath(t *testing.T, base, path, cookie string) *http.Response {
+	return reqJSON(t, http.MethodDelete, base, path, "", cookie)
+}
+
+func TestOwutVersionsEndpoint(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut versions", out: owutVersionsSample},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if body["owutAvailable"] != true {
+		t.Fatalf("owutAvailable: %v", body["owutAvailable"])
+	}
+	versions, _ := body["versions"].([]any)
+	if len(versions) != 4 {
+		t.Fatalf("esperaba 4 versiones, got %v", versions)
+	}
+}
+
+func TestOwutVersionsEndpointWithoutOwut(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "\n"}, // PATH sin owut
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if body["owutAvailable"] != false {
+		t.Fatalf("owutAvailable: %v", body["owutAvailable"])
+	}
+	if versions, _ := body["versions"].([]any); len(versions) != 0 {
+		t.Fatalf("sin owut no hay versiones: %v", versions)
+	}
+	if ssh.saw("owut versions") {
+		t.Fatalf("no debe lanzarse owut versions sin owut: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestOwutInstallEndpoint(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "apk add owut", out: "OK: 1 installed\n__owut_exit__=0\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if body["ok"] != true {
+		t.Fatalf("ok: %v", body)
+	}
+	if !ssh.saw("apk add owut") {
+		t.Fatalf("no se lanzó la instalación: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestOwutInstallEndpointNoPackageManager(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "apk update", out: "__no_pm__\n__owut_exit__=0\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
+	if res.StatusCode != 500 {
+		t.Fatalf("status %d, esperaba 500", res.StatusCode)
+	}
+}
+
+// waitForUpgradeStatus polea la lista hasta que el upgrade llegue al estado
+// terminal (la goroutine del server corre en background).
+func waitForUpgradeStatus(t *testing.T, ts *testServer, rid, want, cookie string) map[string]any {
+	t.Helper()
+	deadline := time.Now().Add(5 * time.Second)
+	for time.Now().Before(deadline) {
+		res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
+		for _, it := range readJSONArray(t, res) {
+			m, _ := it.(map[string]any)
+			if m["routerId"] != rid {
+				continue
+			}
+			if up, ok := m["upgrade"].(map[string]any); ok && up["status"] == want {
+				return up
+			}
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	t.Fatalf("el upgrade no llegó a %s", want)
+	return nil
+}
+
+func TestOwutUpgradeEndpointNoChanges(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut upgrade", out: "There are no changes to upgrade (see '--force')\n__owut_exit__=0\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 202 {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if body["engine"] != "owut" {
+		t.Fatalf("engine: %v", body["engine"])
+	}
+	up := waitForUpgradeStatus(t, ts, rid, "done", cookie)
+	if up["engine"] != "owut" {
+		t.Fatalf("engine del upgrade: %v", up["engine"])
+	}
+	if !ssh.saw("owut upgrade -q") {
+		t.Fatalf("comando lanzado: %v", ssh.cmdsSnapshot())
+	}
+	// #761: antes de flashear se preserva el stack en /etc/sysupgrade.conf.
+	if !ssh.saw("/etc/sysupgrade.conf") {
+		t.Fatalf("preserve-stack no se ejecutó: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestOwutUpgradeEndpointFailure(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut upgrade", out: "Update checks reveal errors, can't proceed\n__owut_exit__=1\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
+	if res.StatusCode != 202 {
+		t.Fatalf("status %d", res.StatusCode)
+	}
+	up := waitForUpgradeStatus(t, ts, rid, "failed", cookie)
+	if msg, _ := up["error"].(string); !strings.Contains(msg, "can't proceed") {
+		t.Fatalf("error del upgrade: %v", up["error"])
+	}
+}
+
+func TestOwutUpgradeRequiresTarget(t *testing.T) {
+	ts, rid := makeOwutTestServer(t, nil)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{}`, cookie)
+	if res.StatusCode != 400 {
+		t.Fatalf("status %d, esperaba 400 sin targetVersion", res.StatusCode)
+	}
+}
+
+func TestRecurrencePutGetDelete(t *testing.T) {
+	ts, rid := makeOwutTestServer(t, nil)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	// weekly válido.
+	res := putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
+		`{"enabled":true,"kind":"weekly","dayOfWeek":5,"time":"04:00"}`, cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT weekly: %d %v", res.StatusCode, readJSON(t, res))
+	}
+	res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
+	body := readJSON(t, res)
+	rc, _ := body["recurrence"].(map[string]any)
+	if rc["kind"] != "weekly" || rc["enabled"] != true {
+		t.Fatalf("GET recurrence: %v", body)
+	}
+	if _, ok := body["nextRunMs"]; !ok {
+		t.Fatalf("GET recurrence debe traer nextRunMs: %v", body)
+	}
+
+	// weekly sin time: 400.
+	res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
+		`{"enabled":true,"kind":"weekly","dayOfWeek":5}`, cookie)
+	if res.StatusCode != 400 {
+		t.Fatalf("PUT inválido: %d, esperaba 400", res.StatusCode)
+	}
+
+	// monthly y once válidos.
+	res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
+		`{"enabled":true,"kind":"monthly","dayOfMonth":1,"time":"05:30"}`, cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT monthly: %d", res.StatusCode)
+	}
+	future := time.Now().Add(48 * time.Hour).UnixMilli()
+	res = putJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence",
+		fmt.Sprintf(`{"enabled":true,"kind":"once","atMs":%d}`, future), cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT once: %d", res.StatusCode)
+	}
+
+	// DELETE desactiva.
+	res = deleteJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("DELETE: %d", res.StatusCode)
+	}
+	res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/recurrence", cookie)
+	body = readJSON(t, res)
+	rc, _ = body["recurrence"].(map[string]any)
+	if rc["enabled"] != false {
+		t.Fatalf("tras DELETE debe quedar disabled: %v", body)
+	}
+}
+
+func TestOwutEndpointsBlockedForVendorFirmware(t *testing.T) {
+	// GL.iNet: la plataforma devuelve __gl__ -> install y upgrade 422, y el
+	// listado de versiones llega con vendorFirmware y sin sondear ASU.
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "fw.gl-inet.com", out: "__gl__\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-install", "{}", cookie)
+	if res.StatusCode != 422 {
+		t.Fatalf("install status %d, esperaba 422 vendor_firmware", res.StatusCode)
+	}
+	res = postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie)
+	if res.StatusCode != 422 {
+		t.Fatalf("upgrade status %d, esperaba 422 vendor_firmware", res.StatusCode)
+	}
+	res = getJSONPath(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-versions", cookie)
+	body := readJSON(t, res)
+	if body["vendorFirmware"] != "gl-inet" {
+		t.Fatalf("vendorFirmware: %v", body["vendorFirmware"])
+	}
+	if versions, _ := body["versions"].([]any); len(versions) != 0 {
+		t.Fatalf("vendor no debe listar versiones: %v", versions)
+	}
+	if ssh.saw("owut versions") {
+		t.Fatalf("vendor no debe sondear versiones ASU: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestTargetSaveWithoutURL(t *testing.T) {
+	// #761: con owut la imagen la construye ASU; el target se guarda sin URL.
+	ts, rid := makeOwutTestServer(t, nil)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/target",
+		`{"model":"redmi_ax6","currentVersion":"25.12.5","targetVersion":"25.12.5"}`, cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("guardar sin targetUrl: %d %v", res.StatusCode, readJSON(t, res))
+	}
+	res = getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
+	for _, it := range readJSONArray(t, res) {
+		m, _ := it.(map[string]any)
+		if m["routerId"] == rid && m["targetVersion"] != "25.12.5" {
+			t.Fatalf("target no persistió: %v", m)
+		}
+	}
+}

+ 1 - 1
server-go/internal/httpapi/owut_test.go

@@ -80,7 +80,7 @@ func makeOwutTestServer(t *testing.T, ssh *scriptedSSH) (*testServer, string) {
 
 
 func TestOwutCheckUpgradeAvailable(t *testing.T) {
 func TestOwutCheckUpgradeAvailable(t *testing.T) {
 	ssh := &scriptedSSH{rules: []sshRule{
 	ssh := &scriptedSSH{rules: []sshRule{
-		{contains: "command -v owut", out: "/usr/bin/owut\n"},
+		{contains: "command -v owut", out: "__owut__\n"},
 		{contains: "owut check", out: owutCheckOKOut},
 		{contains: "owut check", out: owutCheckOKOut},
 	}}
 	}}
 	ts, rid := makeOwutTestServer(t, ssh)
 	ts, rid := makeOwutTestServer(t, ssh)

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

@@ -28,6 +28,7 @@ import (
 	"time"
 	"time"
 
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
 	"github.com/gnacho/netpulse/server-go/internal/apitoken"
 	"github.com/gnacho/netpulse/server-go/internal/apitoken"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/baselines"
 	"github.com/gnacho/netpulse/server-go/internal/baselines"
@@ -116,6 +117,11 @@ type Deps struct {
 	FirmwareImage *firmware.ImageResolver
 	FirmwareImage *firmware.ImageResolver
 	// Speedtest: scheduler del test periódico WAN (#511). nil → 503.
 	// Speedtest: scheduler del test periódico WAN (#511). nil → 503.
 	Speedtest *speedtest.Scheduler
 	Speedtest *speedtest.Scheduler
+	// AlertEmitter: motor de alertas para los resultados de firmware owut
+	// (#761). nil → sin alertas de resultado (p. ej. en tests).
+	AlertEmitter interface {
+		Emit(ev alerts.AlertEvent) bool
+	}
 }
 }
 
 
 type server struct {
 type server struct {
@@ -160,6 +166,17 @@ type server struct {
 	// (POST /api/backup/run) y el scheduler periódico.
 	// (POST /api/backup/run) y el scheduler periódico.
 	backupMu sync.Mutex
 	backupMu sync.Mutex
 
 
+	// Firmware owut (#761): emisor de alertas de resultado (lo inyecta main
+	// tras construir el adapter), cache de detección de owut por router y
+	// single-flight de los disparos recurrentes.
+	alertEmitter alertEmitter
+	owutMu       sync.Mutex
+	owutCache    map[string]platformCacheEntry
+	recMu        sync.Mutex
+	recInFlight  map[string]bool
+	// boardVersionFn: versión instalada según board info (hook de test).
+	boardVersionFn func(routerID string) string
+
 	// Avisos externos (announcements.json del repo): caché del último
 	// Avisos externos (announcements.json del repo): caché del último
 	// fetch; nil si el refresco no está activo.
 	// fetch; nil si el refresco no está activo.
 	announcements *announcementCache
 	announcements *announcementCache
@@ -232,10 +249,14 @@ func NewHandler(d Deps) http.Handler {
 		firmwareEngine:  firmware.NewEngine(d.Firmware, d.AgentHub),
 		firmwareEngine:  firmware.NewEngine(d.Firmware, d.AgentHub),
 		imageResolver:   d.FirmwareImage,
 		imageResolver:   d.FirmwareImage,
 		speedtest:       d.Speedtest,
 		speedtest:       d.Speedtest,
+		alertEmitter:    d.AlertEmitter,
 	}
 	}
 	if s.imageResolver == nil {
 	if s.imageResolver == nil {
 		s.imageResolver = firmware.NewImageResolver()
 		s.imageResolver = firmware.NewImageResolver()
 	}
 	}
+	if s.boardVersionFn == nil {
+		s.boardVersionFn = s.detectedFirmwareVersion
+	}
 	// Rearmer compartido entre el endpoint manual y el supervisor de
 	// Rearmer compartido entre el endpoint manual y el supervisor de
 	// auto-rearme (cmd/netpulse lo construye y lo pasa para que ambos
 	// auto-rearme (cmd/netpulse lo construye y lo pasa para que ambos
 	// compartan cooldowns; nil → se crea uno interno, p. ej. en tests).
 	// compartan cooldowns; nil → se crea uno interno, p. ej. en tests).
@@ -465,6 +486,9 @@ func NewHandler(d Deps) http.Handler {
 	// auto-updates no resetean el reloj. Solo en live (en demo no hay datos).
 	// auto-updates no resetean el reloj. Solo en live (en demo no hay datos).
 	if s.cfg == nil || !s.cfg.DemoMode {
 	if s.cfg == nil || !s.cfg.DemoMode {
 		go s.backupLoop(context.Background(), backupTickEvery)
 		go s.backupLoop(context.Background(), backupTickEvery)
+		// Recurrencia de firmware (#761): mismo contrato reboot-safe; el
+		// disparo es idempotente (al día = no-op) y notifica el resultado.
+		go s.firmwareRecurrenceLoop(context.Background(), recTickEvery)
 	}
 	}
 
 
 	// --- Overrides manuales de topología (issue #142; solo admin) ---
 	// --- Overrides manuales de topología (issue #142; solo admin) ---

Some files were not shown because too many files changed in this diff