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

feat(rearmer): supervisor escalates rearm to full agent reinstall (#476)

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

+ 6 - 0
server-go/.env.example

@@ -27,6 +27,12 @@ WG_INTERFACE=wg0
 # confirmación explícita. Cooldown entre intentos automáticos por slug.
 NETPULSE_AUTO_REARM=0
 NETPULSE_AUTO_REARM_COOLDOWN_S=600
+# Escalado del supervisor (#457): reinstalar el agente completo cuando un
+# rearme no lo recupera (p. ej. binario perdido tras un sysupgrade).
+# Requiere NETPULSE_PUBLIC_URL (URL con la que los routers alcanzan al server).
+NETPULSE_AUTO_REINSTALL=0
+#NETPULSE_AUTO_REINSTALL_COOLDOWN_S=3600
+#NETPULSE_PUBLIC_URL=http://192.168.1.226:3000
 
 # --- Alertas de ghost port (#419) ---
 # 1 = activa alertas "Ghost port: X went silent". Default 0 (deshabilitado)

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

@@ -388,6 +388,18 @@ func run() error {
 			}
 		}
 		rearmSup = rearmer.NewSupervisor(arm, agentReg, dbHandle.DB, rearmEngine, 0, cooldown)
+		// #457: escalado rearm→reinstall (opt-in doble: AUTO_REINSTALL=1 y
+		// PUBLIC_URL configurada; la config ya lo valida como par).
+		if cfg.AutoReinstall && cfg.PublicURL != "" {
+			var rcool time.Duration
+			if v := os.Getenv("NETPULSE_AUTO_REINSTALL_COOLDOWN_S"); v != "" {
+				if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
+					rcool = time.Duration(sec) * time.Second
+				}
+			}
+			rearmSup.EnableReinstall(cfg.PublicURL, rcool)
+			log.Printf("[netpulse] escalado auto-reinstall activo (PUBLIC_URL %s)", cfg.PublicURL)
+		}
 		rearmSup.Start()
 		if cooldown <= 0 {
 			cooldown = rearmer.AutoCooldownDefault

+ 34 - 0
server-go/internal/config/config.go

@@ -63,6 +63,8 @@ type Config struct {
 	GithubToken     string
 	ServerRoot      string
 	AutoRearm       bool   // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
+	AutoReinstall   bool   // NETPULSE_AUTO_REINSTALL=1: el supervisor escala rearm→reinstall (#457); exige PUBLIC_URL
+	PublicURL       string // NETPULSE_PUBLIC_URL: URL base con la que los routers alcanzan al server (reinstall/self-heal)
 	BeaconListen    string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140"
 	AgentAutoenroll bool   // AGENT_AUTOENROLL=1: el responder UDP entrega token de alta y /pair lo acepta (#367)
 	Onbox           bool   // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
@@ -243,6 +245,36 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// NETPULSE_AUTO_REINSTALL: '0'|'1', opcional (#457). El supervisor
+	// escala rearm→reinstall cuando el reinicio no recupera el agente.
+	// Exige NETPULSE_PUBLIC_URL: sin ella no hay forma fiable de decirle al
+	// router desde dónde descargar el binario.
+	autoReinstall := false
+	if v, ok := env["NETPULSE_AUTO_REINSTALL"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			autoReinstall = true
+		default:
+			errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
+	// NETPULSE_PUBLIC_URL: URL base (http(s)://host[:port]) con la que los
+	// ROUTERS alcanzan al servidor. Opcional; la usan el reinstall (manual y
+	// del supervisor) como fuente preferente.
+	publicURL := strings.TrimSpace(env["NETPULSE_PUBLIC_URL"])
+	if publicURL != "" {
+		if !strings.HasPrefix(publicURL, "http://") && !strings.HasPrefix(publicURL, "https://") {
+			errs.issues = append(errs.issues, issue{"NETPULSE_PUBLIC_URL", "String must contain a http:// or https:// prefix"})
+		} else {
+			publicURL = strings.TrimRight(publicURL, "/")
+		}
+	}
+	if autoReinstall && publicURL == "" {
+		errs.issues = append(errs.issues, issue{"NETPULSE_AUTO_REINSTALL", "NETPULSE_PUBLIC_URL is required when auto-reinstall is enabled"})
+	}
+
 	// MAX_SSE_CLIENTS: int 1..100, default 10
 	maxSSE := 10
 	if v, ok := env["MAX_SSE_CLIENTS"]; ok && v != "" {
@@ -452,6 +484,8 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		GithubToken:     githubToken,
 		ServerRoot:      serverRoot,
 		AutoRearm:       autoRearm,
+		AutoReinstall:   autoReinstall,
+		PublicURL:       publicURL,
 		BeaconListen:    beaconListen,
 		AgentAutoenroll: agentAutoenroll,
 		Onbox:           onbox,

+ 8 - 152
server-go/internal/httpapi/agent.go

@@ -31,6 +31,7 @@ import (
 
 	"github.com/gnacho/netpulse/agent/probe"
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
@@ -695,25 +696,20 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	// URL base del server (para que el router descargue el binario). Mismo
-	// esquema que agentInstallLine: http en LAN, https si la request es segura.
+	// URL base del server (para que el router descargue el binario).
+	// NETPULSE_PUBLIC_URL manda si está configurada (#457): sin ella, llamar
+	// al endpoint vía localhost haría que el router descargue de localhost.
 	scheme := "http"
 	if auth.IsSecureRequest(r) {
 		scheme = "https"
 	}
 	serverURL := scheme + "://" + r.Host
-
-	// Digests sha256 de los binarios embebidos (#463): el router verifica la
-	// descarga antes del swap. Arch sin binario (build dev sin agentes) queda
-	// sin verificar en lugar de bloquear la instalación.
-	digests := map[string]string{
-		"arm64": agentbin.Digest("arm64"),
-		"arm":   agentbin.Digest("arm"),
-		"amd64": agentbin.Digest("amd64"),
+	if s.cfg != nil && s.cfg.PublicURL != "" {
+		serverURL = s.cfg.PublicURL
 	}
 
-	// Script de instalación (replica install-agent.sh vía SSH, sin scp).
-	script := reinstallScript(slug, token, serverURL, digests)
+	// Script de instalación canónico (compartido con el supervisor, #457).
+	script := reinstall.Script(slug, token, serverURL, reinstall.Digests())
 
 	before := time.Now()
 	var prevSeen time.Time
@@ -749,146 +745,6 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 	})
 }
 
-// reinstallScript construye el script POSIX sh que se ejecuta en el router
-// (#463): instala el agente completo —binario verificado por sha256, config
-// .env, init procd con self-heal y watchdog con su cron— de forma idempotente.
-// digests mapa arch→sha256 del binario embebido; un arch sin digest queda sin
-// verificación (build dev) en lugar de bloquear.
-func reinstallScript(slug, token, serverURL string, digests map[string]string) string {
-	return `#!/bin/sh
-set -e
-INIT=/etc/init.d/netpulse-agent
-BIN=/usr/sbin/netpulse-agent
-ENV_FILE=/etc/netpulse-agent.env
-WATCHDOG=/usr/sbin/netpulse-watchdog
-SERVER="` + serverURL + `"
-SLUG="` + slug + `"
-TOKEN="` + token + `"
-
-# Detectar arquitectura del router y el digest esperado del binario embebido
-ARCH=$(uname -m)
-case "$ARCH" in
-	aarch64|arm64)  GOARCH=arm64; SHA256="` + digests["arm64"] + `" ;;
-	armv7l|armv7|armhf|arm) GOARCH=arm; SHA256="` + digests["arm"] + `" ;;
-	x86_64|amd64)   GOARCH=amd64; SHA256="` + digests["amd64"] + `" ;;
-	*) echo "arch no soportado: $ARCH"; exit 20 ;;
-esac
-
-# Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
-[ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
-
-# Descargar el binario del propio server (auth por token)
-if command -v curl >/dev/null 2>&1; then
-	curl -fsSL --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
-else
-	wget -q -T 60 -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
-fi
-
-# Verificación sha256 contra el digest embebido (#463); vacío = sin verificar
-if [ -n "$SHA256" ]; then
-	GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')
-	[ "$GOT" = "$SHA256" ] || { echo "sha256 no coincide (esperado $SHA256, obtenido $GOT)"; exit 21; }
-fi
-chmod 0755 /tmp/netpulse-agent.new
-mv -f /tmp/netpulse-agent.new "$BIN"
-
-# Config (chmod 600)
-cat > "$ENV_FILE" <<EOF
-# netpulse-agent — config (generado por reinstall)
-NETPULSE_SERVER=$SERVER
-NETPULSE_SLUG=$SLUG
-NETPULSE_TOKEN=$TOKEN
-EOF
-chmod 600 "$ENV_FILE"
-
-# Init procd con self-heal (#457): un sysupgrade solo conserva /etc, así que
-# si el binario falta al arrancar se descarga del server con este env.
-cat > "$INIT" <<'INITEOF'
-#!/bin/sh /etc/rc.common
-# netpulse-agent — agente nativo NetPulse para OpenWrt, con self-heal.
-# Config en /etc/netpulse-agent.env (chmod 600); procd reinicia si cambia.
-START=99
-STOP=10
-USE_PROCD=1
-
-ENV_FILE=/etc/netpulse-agent.env
-BIN=/usr/sbin/netpulse-agent
-[ -x "$BIN" ] || BIN=/tmp/netpulse-agent
-
-selfheal_binary() {
-	[ -x "$BIN" ] && return 0
-	[ -f "$ENV_FILE" ] || return 1
-	. "$ENV_FILE" 2>/dev/null
-	[ -n "${NETPULSE_SERVER:-}" ] && [ -n "${NETPULSE_TOKEN:-}" ] && [ -n "${NETPULSE_SLUG:-}" ] || return 1
-	case "$(uname -m)" in
-		aarch64|arm64) local ARCH=arm64 ;;
-		armv7l|armv7|armhf|arm) local ARCH=arm ;;
-		x86_64|amd64) local ARCH=amd64 ;;
-		*) return 1 ;;
-	esac
-	local url tmp
-	url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"
-	logger -t netpulse-agent "self-heal: binario ausente, descargando de $NETPULSE_SERVER"
-	tmp=/tmp/netpulse-agent.$$
-	if command -v curl >/dev/null 2>&1; then
-		curl -fsSL -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
-	else
-		wget -q -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
-	fi
-	chmod 0755 "$tmp" && mv "$tmp" /usr/sbin/netpulse-agent || { rm -f "$tmp"; return 1; }
-	logger -t netpulse-agent "self-heal: binario restaurado"
-	BIN=/usr/sbin/netpulse-agent
-	return 0
-}
-
-start_service() {
-	selfheal_binary || logger -t netpulse-agent "self-heal: no se pudo restaurar el binario"
-	procd_open_instance netpulse-agent
-	procd_set_param command "$BIN"
-	procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
-	procd_set_param stdout 1
-	procd_set_param stderr 1
-	procd_set_param file /etc/netpulse-agent.env
-	procd_close_instance
-}
-INITEOF
-chmod 0755 "$INIT"
-
-# Watchdog + cron (mismo criterio que el paquete; detección por pidof,
-# compatible con BusyBox)
-cat > "$WATCHDOG" <<'WGEOF'
-#!/bin/sh
-# netpulse-watchdog — relanza el agente si el proceso murió o el heartbeat
-# lleva >300s sin latir. Cron cada 2 min.
-INIT=/etc/init.d/netpulse-agent
-HB=/tmp/netpulse-agent.heartbeat
-[ -x "$INIT" ] || exit 0
-if ! pidof netpulse-agent >/dev/null 2>&1; then
-	logger -t netpulse-watchdog "agente no está en marcha, reiniciando servicio"
-	"$INIT" restart >/dev/null 2>&1
-	exit 0
-fi
-if [ -f "$HB" ]; then
-	now=$(date +%s)
-	hb=$(cat "$HB" 2>/dev/null)
-	case "$hb" in ''|*[!0-9]*) exit 0 ;; esac
-	age=$((now - hb))
-	if [ "$age" -gt 300 ]; then
-		logger -t netpulse-watchdog "proceso vivo pero sin latido en ${age}s, reiniciando servicio"
-		"$INIT" restart >/dev/null 2>&1
-	fi
-fi
-exit 0
-WGEOF
-chmod 0755 "$WATCHDOG"
-( crontab -l 2>/dev/null | grep -v netpulse-watchdog ; echo '*/2 * * * * /usr/sbin/netpulse-watchdog' ) | crontab -
-/etc/init.d/cron restart >/dev/null 2>&1 || true
-
-"$INIT" enable
-"$INIT" restart
-`
-}
-
 // ---------------------------------------------------------------------------
 // POST /api/agents/{slug}/refresh — Fase 7.3: enviar comando refresh al
 // agente vía SSE para que haga un sondeo inmediato. Admin solo.

+ 183 - 21
server-go/internal/rearmer/rearmer.go

@@ -10,13 +10,18 @@
 package rearmer
 
 import (
+	"crypto/rand"
+	"crypto/sha256"
 	"database/sql"
+	"encoding/hex"
+	"errors"
 	"fmt"
 	"sync"
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 )
 
@@ -34,6 +39,12 @@ const (
 	AutoCooldownDefault = 600 * time.Second
 	// SupervisorIntervalDefault: cadencia del supervisor.
 	SupervisorIntervalDefault = 30 * time.Second
+
+	// ReinstallSSHWait: margen del script de instalación (descarga incluida).
+	ReinstallSSHWait = 300 * time.Second
+	// ReinstallCooldownDefault: anti-martilleo del escalado reinstall del
+	// supervisor (#457): 1 h por slug.
+	ReinstallCooldownDefault = 3600 * time.Second
 )
 
 // TokenPrefix: prefijo de las claves kv que marcan un slug con agente
@@ -81,8 +92,8 @@ var (
 	// ErrNetgripAgent (#363): el agente de este slug es el NetGrip embebido;
 	// no se rearma ni se reinstala desde el servidor.
 	ErrNetgripAgent = fmt.Errorf("agente embebido en NetGrip: gestionarlo desde el panel NetGrip")
-	ErrNoSSH    = fmt.Errorf("el servidor no tiene pool SSH (modo demo o clave ausente)")
-	ErrNoDB     = fmt.Errorf("db no disponible")
+	ErrNoSSH        = fmt.Errorf("el servidor no tiene pool SSH (modo demo o clave ausente)")
+	ErrNoDB         = fmt.Errorf("db no disponible")
 )
 
 // Rearmer ejecuta rearmes (compartido entre el handler manual y el
@@ -195,23 +206,7 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 		return Result{}, fmt.Errorf("no pude reiniciar el servicio en %s: %w", host, err)
 	}
 
-	// Esperar a que el agente vuelva a empujar (poll cada 2 s hasta pollWait).
-	recovered := false
-	deadline := time.Now().Add(r.pollWait)
-	pollInterval := 2 * time.Second
-	if r.pollWait < pollInterval {
-		pollInterval = 50 * time.Millisecond
-	}
-	for time.Now().Before(deadline) {
-		time.Sleep(pollInterval)
-		if r.agents == nil {
-			break
-		}
-		if seen, _, _, _, ok := r.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
-			recovered = true
-			break
-		}
-	}
+	recovered := r.waitForPush(slug, prevSeen, before)
 
 	res := Result{Slug: slug, Restarted: true, Recovered: recovered}
 	if recovered {
@@ -231,6 +226,112 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 	return res, nil
 }
 
+// Reinstall reinstala el agente completo en el router vía SSH (#457):
+// rota el token, ejecuta el script canónico (binario verificado + config +
+// init self-heal + watchdog) y espera el push de vuelta. Es el escalado
+// cuando un rearme no recupera el agente (proceso muerto o binario perdido
+// por un sysupgrade).
+func (r *Rearmer) Reinstall(slug, publicURL string) (Result, error) {
+	if r.db == nil {
+		return Result{}, ErrNoDB
+	}
+	if publicURL == "" {
+		return Result{}, fmt.Errorf("reinstall automático sin NETPULSE_PUBLIC_URL")
+	}
+	if r.agents != nil {
+		if _, _, kind, _, ok := r.agents.Info(slug); ok && kind == "netgrip" {
+			return Result{}, ErrNetgripAgent
+		}
+	}
+	var exists int
+	if err := r.db.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", TokenPrefix+slug).Scan(&exists); err != nil || exists == 0 {
+		return Result{}, ErrNoToken
+	}
+	host := ""
+	for _, rc := range routerstore.ListRouters(r.db) {
+		if rc.ID == slug {
+			if !nativeAgentType(rc.Type) {
+				return Result{}, ErrExternalAgent
+			}
+			host = rc.Host
+			break
+		}
+	}
+	if host == "" {
+		return Result{}, ErrNoRouter
+	}
+	if r.pool == nil {
+		return Result{}, ErrNoSSH
+	}
+
+	// Rotar el token: el script lo instala en el router y el hash nuevo
+	// sustituye al viejo en kv.
+	buf := make([]byte, 32)
+	if _, err := rand.Read(buf); err != nil {
+		return Result{}, fmt.Errorf("token: %w", err)
+	}
+	token := hex.EncodeToString(buf)
+	sum := sha256.Sum256([]byte(token))
+	if _, err := r.db.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",
+		TokenPrefix+slug, hex.EncodeToString(sum[:])); err != nil {
+		return Result{}, fmt.Errorf("token kv: %w", err)
+	}
+
+	script := reinstall.Script(slug, token, publicURL, reinstall.Digests())
+
+	before := time.Now()
+	var prevSeen time.Time
+	if r.agents != nil {
+		if seen, _, _, _, ok := r.agents.Info(slug); ok {
+			prevSeen = seen
+		}
+	}
+
+	if _, err := r.pool.Run(host, script, ReinstallSSHWait); err != nil {
+		return Result{}, fmt.Errorf("no se pudo instalar el agente en %s: %w", host, err)
+	}
+
+	recovered := r.waitForPush(slug, prevSeen, before)
+
+	res := Result{Slug: slug, Restarted: true, Recovered: recovered}
+	if recovered {
+		res.Message = "agente reinstalado y empujando"
+		if r.engine != nil {
+			r.engine.Emit(alerts.AlertEvent{
+				ID:       fmt.Sprintf("alert-agent-reinstall-%s-%d", slug, time.Now().UnixMilli()),
+				Category: alerts.CatSystem, Urgent: false, Severity: "info",
+				Title:       fmt.Sprintf("Agente reinstalado en %s", slug),
+				Description: "Reinstalación completa desde el servidor (binario, config, init y watchdog) — el agente vuelve a empujar",
+				Time:        "ahora mismo", RouterID: slug,
+			})
+		}
+	} else {
+		res.Message = fmt.Sprintf("agente reinstalado, pero aún no ha empujado en %d s", int(r.pollWait.Seconds()))
+	}
+	return res, nil
+}
+
+// waitForPush: poll del registry hasta pollWait esperando un push NUEVO.
+// Extraído del cuerpo de Rearm para compartirlo con Reinstall.
+func (r *Rearmer) waitForPush(slug string, prevSeen, before time.Time) bool {
+	deadline := time.Now().Add(r.pollWait)
+	pollInterval := 2 * time.Second
+	if r.pollWait < pollInterval {
+		pollInterval = 50 * time.Millisecond
+	}
+	for time.Now().Before(deadline) {
+		time.Sleep(pollInterval)
+		if r.agents == nil {
+			return false
+		}
+		if seen, _, _, _, ok := r.agents.Info(slug); ok && seen.After(prevSeen) && seen.After(before.Add(-5*time.Second)) {
+			return true
+		}
+	}
+	return false
+}
+
 // ---------------------------------------------------------------------------
 // Supervisor: auto-rearme tras expiración del TTL (NETPULSE_AUTO_REARM=1)
 // ---------------------------------------------------------------------------
@@ -247,6 +348,14 @@ type Supervisor struct {
 	interval time.Duration
 	cooldown time.Duration
 
+	// Escalado rearm→reinstall (#457): opt-in (NETPULSE_AUTO_REINSTALL=1 y
+	// NETPULSE_PUBLIC_URL). Cuando un rearme ejecutado NO recupera el push,
+	// se reinstala el agente completo con cooldown propio (1 h por slug).
+	autoReinstall     bool
+	publicURL         string
+	reinstallSlots    map[string]time.Time
+	reinstallCooldown time.Duration
+
 	mu    sync.Mutex
 	slots map[string]time.Time
 
@@ -273,10 +382,23 @@ func NewSupervisor(r *Rearmer, registry *adapters.AgentRegistry, db *sql.DB, eng
 		rearmer: r, registry: registry, db: db, engine: engine,
 		interval: interval, cooldown: cooldown,
 		slots: map[string]time.Time{}, failIDs: map[string]string{},
+		reinstallSlots: map[string]time.Time{}, reinstallCooldown: ReinstallCooldownDefault,
 		stop: make(chan struct{}), done: make(chan struct{}),
 	}
 }
 
+// EnableReinstall activa el escalado rearm→reinstall del supervisor (#457).
+// Requiere publicURL (NETPULSE_PUBLIC_URL): es la URL con la que el router
+// descarga el binario del servidor. cooldown <= 0 → 1 h.
+func (s *Supervisor) EnableReinstall(publicURL string, cooldown time.Duration) {
+	if cooldown <= 0 {
+		cooldown = ReinstallCooldownDefault
+	}
+	s.autoReinstall = true
+	s.publicURL = publicURL
+	s.reinstallCooldown = cooldown
+}
+
 // Start lanza el loop en una goroutine (no bloquea).
 func (s *Supervisor) Start() {
 	go s.run()
@@ -352,12 +474,36 @@ func (s *Supervisor) CheckOnce() {
 			s.closeFailID(slug)
 			continue
 		}
+		// #457: el rearme no recuperó el agente (proceso muerto o binario
+		// perdido). Si el escalado está activo, reinstalación completa con
+		// cooldown propio; solo para slugs con preconditions válidas.
+		if s.autoReinstall && s.publicURL != "" && s.reinstallSlotFree(slug) {
+			if r2, err := s.rearmer.Reinstall(slug, s.publicURL); err == nil {
+				s.markReinstallSlot(slug)
+				if r2.Recovered {
+					s.closeFailID(slug)
+					continue
+				}
+			} else if !isPreconditionError(err) {
+				// El intento llegó al SSH y falló (router apagado, red
+				// caída): también consume el slot de reinstall.
+				s.markReinstallSlot(slug)
+			}
+		}
 		if s.engine != nil {
 			s.emitFail(slug)
 		}
 	}
 }
 
+// isPreconditionError: true para errores de guard (sin token, router
+// desconocido, externo, netgrip, sin SSH/DB): no consumen el slot.
+func isPreconditionError(err error) bool {
+	return errors.Is(err, ErrNoToken) || errors.Is(err, ErrNoRouter) ||
+		errors.Is(err, ErrExternalAgent) || errors.Is(err, ErrNetgripAgent) ||
+		errors.Is(err, ErrNoSSH) || errors.Is(err, ErrNoDB)
+}
+
 // emitFail: alerta consolidada de fallo (issue #271). La primera vez del
 // incidente crea la alerta con ID = slug + timestamp del primer fallo; cada
 // reintento del MISMO incidente la actualiza (EmitOrUpdate) en vez de
@@ -372,8 +518,8 @@ func (s *Supervisor) emitFail(slug string) {
 	}
 	s.mu.Unlock()
 	s.engine.EmitOrUpdate(alerts.AlertEvent{
-		ID:          id,
-		Category:    alerts.CatSystem, Urgent: false, Severity: "warn",
+		ID:       id,
+		Category: alerts.CatSystem, Urgent: false, Severity: "warn",
 		Title:       fmt.Sprintf("Auto-rearme sin recuperación en %s", slug),
 		Description: fmt.Sprintf("El supervisor reinició netpulse-agent en %s pero el agente no ha vuelto a empujar; próximo intento en %d s", slug, int(s.cooldown.Seconds())),
 		Time:        "ahora mismo", RouterID: slug,
@@ -418,3 +564,19 @@ func (s *Supervisor) markSlot(slug string) {
 	defer s.mu.Unlock()
 	s.slots[slug] = time.Now()
 }
+
+// reinstallSlotFree: ¿pasó el cooldown de reinstall desde el último
+// intento del slug? (#457)
+func (s *Supervisor) reinstallSlotFree(slug string) bool {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	last, ok := s.reinstallSlots[slug]
+	return !ok || time.Since(last) >= s.reinstallCooldown
+}
+
+// markReinstallSlot registra un intento de reinstalación del slug.
+func (s *Supervisor) markReinstallSlot(slug string) {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	s.reinstallSlots[slug] = time.Now()
+}

+ 84 - 0
server-go/internal/rearmer/rearmer_test.go

@@ -6,6 +6,7 @@ package rearmer_test
 
 import (
 	"errors"
+	"strings"
 	"sync"
 	"testing"
 	"time"
@@ -352,3 +353,86 @@ func TestRearmExternalAgentRejected(t *testing.T) {
 		t.Fatalf("patio (openwrt) no debe rechazarse como externo")
 	}
 }
+
+// #457: Reinstall directo — rota el token, ejecuta el script canónico con
+// la PUBLIC_URL y espera el push de vuelta.
+func TestReinstallInstalaYRecupera(t *testing.T) {
+	env := makeRearmEnv(t, "patio")
+	env.pushViejo("patio")
+	env.expira(time.Minute)
+	env.arm.SetPollWait(200 * time.Millisecond)
+
+	// Push nuevo poco después de "instalar" para que waitForPush lo vea.
+	go func() {
+		time.Sleep(60 * time.Millisecond)
+		env.setNow(env.now.Add(2 * time.Second))
+		env.pushViejo("patio")
+	}()
+
+	res, err := env.arm.Reinstall("patio", "http://192.168.1.226:3000")
+	if err != nil {
+		t.Fatalf("Reinstall: %v", err)
+	}
+	if !res.Restarted || !res.Recovered {
+		t.Fatalf("esperaba reinstalado+recuperado: %+v", res)
+	}
+	if env.ssh.count() != 1 {
+		t.Fatalf("quiero 1 comando SSH, tuve %d", env.ssh.count())
+	}
+	cmd := env.ssh.cmds[0]
+	if !strings.Contains(cmd, `SERVER="http://192.168.1.226:3000"`) || !strings.Contains(cmd, "api/agents/$SLUG/binary") {
+		t.Error("el script no descarga de la PUBLIC_URL indicada")
+	}
+	if !strings.Contains(cmd, "selfheal_binary") {
+		t.Error("el script no instala el init con self-heal")
+	}
+	// El token rotó: el hash en kv ya no es el fakehash original.
+	var stored string
+	if err := env.d.QueryRow("SELECT value FROM kv WHERE key = ?", rearmer.TokenPrefix+"patio").Scan(&stored); err != nil {
+		t.Fatal(err)
+	}
+	if stored == "fakehash" || len(stored) != 64 {
+		t.Fatalf("token no rotado: %q", stored)
+	}
+}
+
+// #457: el supervisor escala a reinstall cuando el rearme no recupera, y el
+// slot de 1 h evita martillear en pasadas consecutivas.
+func TestSupervisorEscalaAReinstall(t *testing.T) {
+	env := makeRearmEnv(t, "patio")
+	env.pushViejo("patio")
+	env.expira(time.Minute)
+	env.arm.SetPollWait(100 * time.Millisecond)
+
+	sup := rearmer.NewSupervisor(env.arm, env.reg, env.d.DB, env.engine, time.Hour, time.Hour)
+	sup.EnableReinstall("http://192.168.1.226:3000", time.Hour)
+	sup.CheckOnce()
+
+	if env.ssh.count() != 2 {
+		t.Fatalf("quiero 2 comandos SSH (rearm + reinstall), tuve %d", env.ssh.count())
+	}
+	if !strings.Contains(env.ssh.cmds[1], "selfheal_binary") {
+		t.Error("el segundo comando debería ser la reinstalación completa")
+	}
+
+	// Segunda pasada inmediata: slots ocupados → sin más comandos.
+	sup.CheckOnce()
+	if env.ssh.count() != 2 {
+		t.Fatalf("los slots deberían frenar la segunda pasada: %d comandos", env.ssh.count())
+	}
+}
+
+// Sin escalado activo, el rearme fallido se queda en rearm (comportamiento
+// histórico preservado).
+func TestSupervisorSinEscaladoQuedaEnRearm(t *testing.T) {
+	env := makeRearmEnv(t, "patio")
+	env.pushViejo("patio")
+	env.expira(time.Minute)
+	env.arm.SetPollWait(100 * time.Millisecond)
+
+	sup := rearmer.NewSupervisor(env.arm, env.reg, env.d.DB, env.engine, time.Hour, time.Hour)
+	sup.CheckOnce()
+	if env.ssh.count() != 1 {
+		t.Fatalf("sin escalado quiero solo el rearm, tuve %d", env.ssh.count())
+	}
+}

+ 158 - 0
server-go/internal/reinstall/reinstall.go

@@ -0,0 +1,158 @@
+// Package reinstall: construcción del script de instalación del agente
+// netpulse-agent en un router OpenWrt (#246, #457, #463). Lo comparten el
+// handler manual (POST /api/agents/{slug}/reinstall) y el supervisor del
+// rearmer (escalado restart → reinstall), de ahí su propio paquete: httpapi
+// importa rearmer y ninguno de los dos puede importar al otro.
+package reinstall
+
+import "github.com/gnacho/netpulse/server-go/internal/agentbin"
+
+// Script construye el POSIX sh que se ejecuta en el router: instala el
+// agente completo (binario verificado por sha256, config .env, init procd
+// con self-heal y watchdog con su cron) de forma idempotente.
+// digests mapa arch→sha256 del binario embebido; un arch sin digest queda
+// sin verificación (build dev) en lugar de bloquear.
+func Script(slug, token, serverURL string, digests map[string]string) string {
+	return `#!/bin/sh
+set -e
+INIT=/etc/init.d/netpulse-agent
+BIN=/usr/sbin/netpulse-agent
+ENV_FILE=/etc/netpulse-agent.env
+WATCHDOG=/usr/sbin/netpulse-watchdog
+SERVER="` + serverURL + `"
+SLUG="` + slug + `"
+TOKEN="` + token + `"
+
+# Detectar arquitectura del router y el digest esperado del binario embebido
+ARCH=$(uname -m)
+case "$ARCH" in
+	aarch64|arm64)  GOARCH=arm64; SHA256="` + digests["arm64"] + `" ;;
+	armv7l|armv7|armhf|arm) GOARCH=arm; SHA256="` + digests["arm"] + `" ;;
+	x86_64|amd64)   GOARCH=amd64; SHA256="` + digests["amd64"] + `" ;;
+	*) echo "arch no soportado: $ARCH"; exit 20 ;;
+esac
+
+# Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
+[ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
+
+# Descargar el binario del propio server (auth por token)
+if command -v curl >/dev/null 2>&1; then
+	curl -fsSL --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
+else
+	wget -q -T 60 -O /tmp/netpulse-agent.new --header="Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"
+fi
+
+# Verificación sha256 contra el digest embebido (#463); vacío = sin verificar
+if [ -n "$SHA256" ]; then
+	GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')
+	[ "$GOT" = "$SHA256" ] || { echo "sha256 no coincide (esperado $SHA256, obtenido $GOT)"; exit 21; }
+fi
+chmod 0755 /tmp/netpulse-agent.new
+mv -f /tmp/netpulse-agent.new "$BIN"
+
+# Config (chmod 600)
+cat > "$ENV_FILE" <<EOF
+# netpulse-agent — config (generado por reinstall)
+NETPULSE_SERVER=$SERVER
+NETPULSE_SLUG=$SLUG
+NETPULSE_TOKEN=$TOKEN
+EOF
+chmod 600 "$ENV_FILE"
+
+# Init procd con self-heal (#457): un sysupgrade solo conserva /etc, así que
+# si el binario falta al arrancar se descarga del server con este env.
+cat > "$INIT" <<'INITEOF'
+#!/bin/sh /etc/rc.common
+# netpulse-agent — agente nativo NetPulse para OpenWrt, con self-heal.
+# Config en /etc/netpulse-agent.env (chmod 600); procd reinicia si cambia.
+START=99
+STOP=10
+USE_PROCD=1
+
+ENV_FILE=/etc/netpulse-agent.env
+BIN=/usr/sbin/netpulse-agent
+[ -x "$BIN" ] || BIN=/tmp/netpulse-agent
+
+selfheal_binary() {
+	[ -x "$BIN" ] && return 0
+	[ -f "$ENV_FILE" ] || return 1
+	. "$ENV_FILE" 2>/dev/null
+	[ -n "${NETPULSE_SERVER:-}" ] && [ -n "${NETPULSE_TOKEN:-}" ] && [ -n "${NETPULSE_SLUG:-}" ] || return 1
+	case "$(uname -m)" in
+		aarch64|arm64) local ARCH=arm64 ;;
+		armv7l|armv7|armhf|arm) local ARCH=arm ;;
+		x86_64|amd64) local ARCH=amd64 ;;
+		*) return 1 ;;
+	esac
+	local url tmp
+	url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"
+	logger -t netpulse-agent "self-heal: binario ausente, descargando de $NETPULSE_SERVER"
+	tmp=/tmp/netpulse-agent.$$
+	if command -v curl >/dev/null 2>&1; then
+		curl -fsSL -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
+	else
+		wget -q -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
+	fi
+	chmod 0755 "$tmp" && mv "$tmp" /usr/sbin/netpulse-agent || { rm -f "$tmp"; return 1; }
+	logger -t netpulse-agent "self-heal: binario restaurado"
+	BIN=/usr/sbin/netpulse-agent
+	return 0
+}
+
+start_service() {
+	selfheal_binary || logger -t netpulse-agent "self-heal: no se pudo restaurar el binario"
+	procd_open_instance netpulse-agent
+	procd_set_param command "$BIN"
+	procd_set_param respawn "${respawn_threshold:-3600}" "${respawn_timeout:-5}" "${respawn_retry:-5}"
+	procd_set_param stdout 1
+	procd_set_param stderr 1
+	procd_set_param file /etc/netpulse-agent.env
+	procd_close_instance
+}
+INITEOF
+chmod 0755 "$INIT"
+
+# Watchdog + cron (mismo criterio que el paquete; detección por pidof,
+# compatible con BusyBox)
+cat > "$WATCHDOG" <<'WGEOF'
+#!/bin/sh
+# netpulse-watchdog — relanza el agente si el proceso murió o el heartbeat
+# lleva >300s sin latir. Cron cada 2 min.
+INIT=/etc/init.d/netpulse-agent
+HB=/tmp/netpulse-agent.heartbeat
+[ -x "$INIT" ] || exit 0
+if ! pidof netpulse-agent >/dev/null 2>&1; then
+	logger -t netpulse-watchdog "agente no está en marcha, reiniciando servicio"
+	"$INIT" restart >/dev/null 2>&1
+	exit 0
+fi
+if [ -f "$HB" ]; then
+	now=$(date +%s)
+	hb=$(cat "$HB" 2>/dev/null)
+	case "$hb" in ''|*[!0-9]*) exit 0 ;; esac
+	age=$((now - hb))
+	if [ "$age" -gt 300 ]; then
+		logger -t netpulse-watchdog "proceso vivo pero sin latido en ${age}s, reiniciando servicio"
+		"$INIT" restart >/dev/null 2>&1
+	fi
+fi
+exit 0
+WGEOF
+chmod 0755 "$WATCHDOG"
+( crontab -l 2>/dev/null | grep -v netpulse-watchdog ; echo '*/2 * * * * /usr/sbin/netpulse-watchdog' ) | crontab -
+/etc/init.d/cron restart >/dev/null 2>&1 || true
+
+"$INIT" enable
+"$INIT" restart
+`
+}
+
+// Digests devuelve los sha256 de los binarios de agente embebidos para las
+// tres arquitecturas (cadena vacía si el arch no tiene binario).
+func Digests() map[string]string {
+	return map[string]string{
+		"arm64": agentbin.Digest("arm64"),
+		"arm":   agentbin.Digest("arm"),
+		"amd64": agentbin.Digest("amd64"),
+	}
+}

+ 20 - 25
server-go/internal/httpapi/reinstall_script_test.go → server-go/internal/reinstall/script_test.go

@@ -1,15 +1,16 @@
-// reinstall_script_test.go — contrato de reinstallScript (#463): instalación
+// script_test.go — contrato de reinstall.Script (#463/#457): instalación
 // completa del agente (binario verificado, init self-heal, watchdog, cron).
-package httpapi
+package reinstall_test
 
 import (
 	"strings"
 	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
 )
 
-func reinstallScriptForTest(t *testing.T) string {
-	t.Helper()
-	return reinstallScript(
+func scriptForTest() string {
+	return reinstall.Script(
 		"test-router",
 		strings.Repeat("a1", 32), // 64 hex como un token real
 		"http://192.168.1.226:3000",
@@ -21,8 +22,8 @@ func reinstallScriptForTest(t *testing.T) string {
 	)
 }
 
-func TestReinstallScriptConfig(t *testing.T) {
-	s := reinstallScriptForTest(t)
+func TestScriptConfig(t *testing.T) {
+	s := scriptForTest()
 	for _, want := range []string{
 		`SERVER="http://192.168.1.226:3000"`,
 		`SLUG="test-router"`,
@@ -37,9 +38,8 @@ func TestReinstallScriptConfig(t *testing.T) {
 	}
 }
 
-func TestReinstallScriptArchAndDigests(t *testing.T) {
-	s := reinstallScriptForTest(t)
-	// Mapeo uname → goarch con alias arm completos.
+func TestScriptArchAndDigests(t *testing.T) {
+	s := scriptForTest()
 	for _, want := range []string{
 		"aarch64|arm64)  GOARCH=arm64; SHA256=\"cafebabe\"",
 		"armv7l|armv7|armhf|arm) GOARCH=arm; SHA256=\"deadbeef\"",
@@ -50,11 +50,9 @@ func TestReinstallScriptArchAndDigests(t *testing.T) {
 			t.Errorf("script sin %q", want)
 		}
 	}
-	// El armv7 legacy (que el endpoint normaliza a arm) ya no se pide.
 	if strings.Contains(s, "arch=armv7\"") {
 		t.Error("el script no debe pedir arch=armv7 (normalizeArch espera arm)")
 	}
-	// Verificación sha256 presente y aborta con exit 21 si no coincide.
 	if !strings.Contains(s, `GOT=$(sha256sum /tmp/netpulse-agent.new | awk '{print $1}')`) {
 		t.Error("sin verificación sha256sum")
 	}
@@ -63,8 +61,8 @@ func TestReinstallScriptArchAndDigests(t *testing.T) {
 	}
 }
 
-func TestReinstallScriptSelfHealInit(t *testing.T) {
-	s := reinstallScriptForTest(t)
+func TestScriptSelfHealInit(t *testing.T) {
+	s := scriptForTest()
 	for _, want := range []string{
 		"selfheal_binary()",
 		`url="${NETPULSE_SERVER%/}/api/agents/${NETPULSE_SLUG}/binary?arch=${ARCH}"`,
@@ -75,17 +73,16 @@ func TestReinstallScriptSelfHealInit(t *testing.T) {
 			t.Errorf("init sin self-heal: falta %q", want)
 		}
 	}
-	// El self-heal debe conocer los tres archs (mismo case que el exterior).
 	if strings.Count(s, "armv7l|armv7|armhf|arm") != 2 {
-		t.Errorf("case de arch incompleto en el script (apariciones: %d, esperadas 2)",
+		t.Errorf("case de arch incompleto (apariciones: %d, esperadas 2)",
 			strings.Count(s, "armv7l|armv7|armhf|arm"))
 	}
 }
 
-func TestReinstallScriptWatchdogAndCron(t *testing.T) {
-	s := reinstallScriptForTest(t)
+func TestScriptWatchdogAndCron(t *testing.T) {
+	s := scriptForTest()
 	for _, want := range []string{
-		"pidof netpulse-agent", // pidof, nunca pgrep -x (BusyBox)
+		"pidof netpulse-agent",
 		`echo '*/2 * * * * /usr/sbin/netpulse-watchdog'`,
 		"/etc/init.d/cron restart",
 	} {
@@ -96,25 +93,23 @@ func TestReinstallScriptWatchdogAndCron(t *testing.T) {
 	if strings.Contains(s, "pgrep -x") {
 		t.Error("el watchdog no debe usar pgrep -x (bug BusyBox)")
 	}
-	// Idempotencia del cron: reemplaza la línea previa en vez de duplicarla.
 	if !strings.Contains(s, "grep -v netpulse-watchdog") {
 		t.Error("el cron no es idempotente")
 	}
 }
 
-func TestReinstallScriptFinishesWithStart(t *testing.T) {
-	s := reinstallScriptForTest(t)
+func TestScriptFinishesWithStart(t *testing.T) {
+	s := scriptForTest()
 	if !strings.HasSuffix(strings.TrimSpace(s), "\"$INIT\" enable\n\"$INIT\" restart") {
 		t.Error("el script debe terminar con enable + restart")
 	}
 }
 
-func TestReinstallScriptEmptyDigestSkipsVerify(t *testing.T) {
-	s := reinstallScript(
+func TestScriptEmptyDigestSkipsVerify(t *testing.T) {
+	s := reinstall.Script(
 		"r", strings.Repeat("b2", 32), "http://s:3000",
 		map[string]string{"arm64": "", "arm": "", "amd64": ""},
 	)
-	// Sin digests: el case asigna SHA256 vacío y el guard salta la verificación.
 	if !strings.Contains(s, `GOARCH=arm64; SHA256=""`) {
 		t.Error("sin digest, SHA256 debe quedar vacío")
 	}