浏览代码

fix(agent): reject privileged commands over plain HTTP (#1599)

Require HTTPS for apply, upgrade, firmware and config backup on both
sides of the SSE channel. The server now refuses to enqueue privileged
commands to HTTP agents with 409 insecure_agent_transport, and the
native agent drops them unless the explicit transition flag is set.

Make X-Checksum-Sha256 mandatory for upgrades and verify it before the
swap. The self-heal script now checks the digest of the downloaded
binary in its three copies instead of installing it blindly.

Add NETPULSE_ALLOW_INSECURE_COMMANDS and
NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS as temporary migration valves,
documented in the EN and ES manuals.

Closes #1598
Nacho 1 月之前
父节点
当前提交
1a2cb21ae1

+ 19 - 3
agent/deploy/netpulse-agent.init

@@ -41,14 +41,30 @@ selfheal_binary() {
             esac ;;
         *) return 1 ;;
     esac
-    local url tmp
+    local url tmp hdr digest sum
     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.$$
+    hdr=/tmp/netpulse-agent.hdr.$$
     if command -v curl >/dev/null 2>&1; then
-        curl -fsSL -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
+        curl -fsSL -m 120 -D "$hdr" -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || { rm -f "$tmp" "$hdr"; return 1; }
     else
-        wget -q -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
+        wget -S -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" 2>"$hdr" || { rm -f "$tmp" "$hdr"; return 1; }
+    fi
+    digest=$(grep -i '^[[:space:]]*x-checksum-sha256:' "$hdr" 2>/dev/null | tail -n 1 | tr -d '\r' | awk '{print $2}')
+    rm -f "$hdr"
+    case "$digest" in
+        ""|*[!0123456789abcdefABCDEF]*)
+            logger -t netpulse-agent "self-heal: sin X-Checksum-Sha256 válido, binario descartado"
+            rm -f "$tmp"
+            return 1 ;;
+    esac
+    [ "${#digest}" -eq 64 ] || { logger -t netpulse-agent "self-heal: digest con longitud inválida, binario descartado"; rm -f "$tmp"; return 1; }
+    sum=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
+    if [ -z "$sum" ] || [ "$(printf '%s' "$sum" | tr 'A-F' 'a-f')" != "$(printf '%s' "$digest" | tr 'A-F' 'a-f')" ]; then
+        logger -t netpulse-agent "self-heal: SHA-256 no coincide, binario descartado"
+        rm -f "$tmp"
+        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"

+ 8 - 0
agent/runtime/config.go

@@ -53,6 +53,14 @@ func LoadConfigFromEnv(envFile string) (Options, error) {
 		HeartbeatFile: get("NETPULSE_HEARTBEAT_FILE"),
 		EnvFile:       envFile,
 	}
+	switch strings.ToLower(strings.TrimSpace(get("NETPULSE_ALLOW_INSECURE_COMMANDS"))) {
+	case "1", "true", "yes", "on":
+		opts.AllowInsecureCommands = true
+	case "", "0", "false", "no", "off":
+	default:
+		slog.Warn("[netpulse-agent] NETPULSE_ALLOW_INSECURE_COMMANDS inválido, se ignora",
+			"value", get("NETPULSE_ALLOW_INSECURE_COMMANDS"))
+	}
 	if v := get("NETPULSE_INTERVAL"); v != "" {
 		if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
 			opts.Interval = time.Duration(sec) * time.Second

+ 21 - 5
agent/runtime/runtime.go

@@ -40,7 +40,11 @@ type Options struct {
 	Slug         string // slug del equipo (agent.token.<slug> en el servidor)
 	ServerFP     string // SHA-256 del SPKI del servidor en hex (https obligatorio)
 	PairingToken string // modo bootstrap: pairing una vez y salir
-	Interval     time.Duration
+	// AllowInsecureCommands permite aceptar comandos privilegiados por HTTP
+	// (NETPULSE_ALLOW_INSECURE_COMMANDS=1). Solo para la transicion a HTTPS:
+	// el valor por defecto los rechaza y deja el agente reportando.
+	AllowInsecureCommands bool
+	Interval              time.Duration
 	// ScanInterval: mínimo entre scans de vecinos del prober (#699). 0 =
 	// probe.DefaultScanInterval; probe.ScanDisabled = sin scans periódicos
 	// (env NETPULSE_SCAN_INTERVAL, "0" lo desactiva).
@@ -226,6 +230,18 @@ func Run(ctx context.Context, opts Options) error {
 		case <-ctx.Done():
 		}
 	}
+	privilegedErr := privilegedEventAllowed(opts.Server, opts.AllowInsecureCommands)
+	if privilegedErr != nil {
+		log.Warn("[netpulse-agent] comandos privilegiados deshabilitados", "err", privilegedErr)
+	}
+	enqueuePrivileged := func(event string, fn func()) {
+		if privilegedErr != nil {
+			log.Warn("[netpulse-agent] comando privilegiado rechazado",
+				"event", event, "err", privilegedErr)
+			return
+		}
+		enqueue(fn)
+	}
 	go func() {
 		sse := sseclient.New(opts.Server, opts.Slug, opts.Token,
 			&http.Client{Timeout: 0, Transport: transport},
@@ -238,11 +254,11 @@ func Run(ctx context.Context, opts Options) error {
 				}
 				if ev.Name == "apply" && ev.Data != "" {
 					data := ev.Data
-					enqueue(func() { a.handleApply(ex, transport, data) })
+					enqueuePrivileged("apply", func() { a.handleApply(ex, transport, data) })
 				}
 				if ev.Name == "upgrade" {
 					data := ev.Data
-					enqueue(func() {
+					enqueuePrivileged("upgrade", func() {
 						if opts.OnUpgrade != nil {
 							opts.OnUpgrade(data)
 						} else {
@@ -252,11 +268,11 @@ func Run(ctx context.Context, opts Options) error {
 				}
 				if ev.Name == "firmware_upgrade" && ev.Data != "" {
 					data := ev.Data
-					enqueue(func() { handleFirmwareUpgrade(opts, transport, data) })
+					enqueuePrivileged("firmware_upgrade", func() { handleFirmwareUpgrade(opts, transport, data) })
 				}
 				if ev.Name == "config_backup" {
 					data := ev.Data
-					enqueue(func() {
+					enqueuePrivileged("config_backup", func() {
 						if opts.OnConfigBackup != nil {
 							opts.OnConfigBackup(data)
 						} else {

+ 7 - 6
agent/runtime/runtime_command_queue_test.go

@@ -50,12 +50,13 @@ func TestRunSerializesPrivilegedCommands(t *testing.T) {
 	done := make(chan error, 1)
 	go func() {
 		done <- Run(ctx, Options{
-			Server:        srv.URL,
-			Token:         "tok",
-			Slug:          "patio",
-			Interval:      20 * time.Millisecond,
-			HeartbeatFile: filepath.Join(t.TempDir(), "hb"),
-			Version:       "test",
+			Server:                srv.URL,
+			Token:                 "tok",
+			Slug:                  "patio",
+			AllowInsecureCommands: true,
+			Interval:              20 * time.Millisecond,
+			HeartbeatFile:         filepath.Join(t.TempDir(), "hb"),
+			Version:               "test",
 			OnUpgrade: func(data string) {
 				started <- data
 				<-release

+ 24 - 0
agent/runtime/runtime_test.go

@@ -62,6 +62,30 @@ NETPULSE_HEARTBEAT_FILE=/tmp/hb
 	}
 }
 
+func TestLoadConfigAllowInsecureCommands(t *testing.T) {
+	dir := t.TempDir()
+	env := filepath.Join(dir, "agent.env")
+	base := "NETPULSE_SERVER=http://example.com:3000\nNETPULSE_TOKEN=abc123\nNETPULSE_SLUG=patio\n"
+
+	writeFile(t, env, base+"NETPULSE_ALLOW_INSECURE_COMMANDS=1\n")
+	opts, err := LoadConfigFromEnv(env)
+	if err != nil {
+		t.Fatalf("LoadConfigFromEnv: %v", err)
+	}
+	if !opts.AllowInsecureCommands {
+		t.Fatal("NETPULSE_ALLOW_INSECURE_COMMANDS=1 debe activar la válvula")
+	}
+
+	writeFile(t, env, base+"NETPULSE_ALLOW_INSECURE_COMMANDS=0\n")
+	opts, err = LoadConfigFromEnv(env)
+	if err != nil {
+		t.Fatalf("LoadConfigFromEnv: %v", err)
+	}
+	if opts.AllowInsecureCommands {
+		t.Fatal("NETPULSE_ALLOW_INSECURE_COMMANDS=0 debe mantener la válvula cerrada")
+	}
+}
+
 // #883: los comentarios inline (" #" tras el valor) no deben formar parte
 // del valor; en concreto NETPULSE_SCAN_INTERVAL=0 con comentario debe
 // aplicar "sin scans periódicos", no caer en el default.

+ 32 - 0
agent/runtime/transport_policy.go

@@ -0,0 +1,32 @@
+package runtime
+
+import (
+	"fmt"
+	"net/url"
+	"strings"
+)
+
+// privilegedEventAllowed decide si el agente puede aceptar comandos que
+// acaban en root (apply, upgrade, firmware_upgrade, config_backup). HTTPS es
+// el unico transporte valido. HTTP solo se permite durante la transicion con
+// NETPULSE_ALLOW_INSECURE_COMMANDS=1.
+func privilegedEventAllowed(server string, allowInsecure bool) error {
+	u, err := url.Parse(strings.TrimSpace(server))
+	if err != nil {
+		return fmt.Errorf("URL de servidor invalida: %w", err)
+	}
+	if u.Scheme == "" || u.Host == "" {
+		return fmt.Errorf("URL de servidor sin esquema o host: %q", server)
+	}
+	switch strings.ToLower(u.Scheme) {
+	case "https":
+		return nil
+	case "http":
+		if allowInsecure {
+			return nil
+		}
+		return fmt.Errorf("comandos privilegiados rechazados sobre HTTP; usa HTTPS o NETPULSE_ALLOW_INSECURE_COMMANDS=1")
+	default:
+		return fmt.Errorf("esquema %q no soportado para comandos privilegiados", u.Scheme)
+	}
+}

+ 30 - 0
agent/runtime/transport_policy_test.go

@@ -0,0 +1,30 @@
+package runtime
+
+import "testing"
+
+func TestPrivilegedEventAllowed(t *testing.T) {
+	for _, tc := range []struct {
+		name      string
+		server    string
+		allow     bool
+		wantError bool
+	}{
+		{"https", "https://netpulse.local:8443", false, false},
+		{"https con path", "https://netpulse.local/netpulse", false, false},
+		{"http denegado", "http://192.168.1.226:3000", false, true},
+		{"http con valvula", "http://192.168.1.226:3000", true, false},
+		{"sin esquema", "192.168.1.226:3000", false, true},
+		{"esquema desconocido", "ftp://192.168.1.226", true, true},
+		{"vacio", "   ", false, true},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			err := privilegedEventAllowed(tc.server, tc.allow)
+			if tc.wantError && err == nil {
+				t.Fatal("se esperaba error")
+			}
+			if !tc.wantError && err != nil {
+				t.Fatalf("error inesperado: %v", err)
+			}
+		})
+	}
+}

+ 17 - 11
agent/runtime/upgrade.go

@@ -28,10 +28,11 @@ import (
 const (
 	defaultBinPath  = "/usr/sbin/netpulse-agent"
 	agentInitScript = "/etc/init.d/netpulse-agent"
-	// tmpBinPath: descarga temporal del binario nuevo antes del swap atómico.
-	tmpBinPath = "/tmp/netpulse-agent.new"
 )
 
+// tmpBinPath es la descarga temporal del binario nuevo antes del swap atómico.
+var tmpBinPath = "/tmp/netpulse-agent.new"
+
 // netpulseArch traduce runtime.GOARCH al nombre de binario que sirve el
 // servidor (agentbin: amd64/arm64/armv7). GOARCH "arm" (armv7) no casa con
 // el sufijo del fichero embebido, así que se normaliza.
@@ -85,7 +86,7 @@ func (p *progressReader) Read(buf []byte) (int, error) {
 // en dest con permisos 0755. Error si la petición no es 200 o el cuerpo está
 // vacío. onPct (opcional) recibe el progreso 0-100 de la descarga (#284).
 // Devuelve el valor de la cabecera X-Checksum-Sha256 (vacía si el server no
-// la manda) para que el llamante verifique la integridad.
+// la manda). El llamante exige que no esté vacía antes de instalar.
 func downloadBinary(ctx context.Context, hc *http.Client, url, token, dest string, onPct func(pct int)) (string, error) {
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 	if err != nil {
@@ -234,14 +235,19 @@ func handleUpgrade(opts Options, transport http.RoundTripper, data string) {
 		return
 	}
 
-	// Integridad (#284): sha256 contra la cabecera del servidor, ANTES del swap.
-	if digest != "" {
-		reportUpgradeProgress(opts, transport, "verifying", 0)
-		if err := verifySha256(tmpBinPath, digest); err != nil {
-			log.Error("[netpulse-agent] upgrade: verificación falló", "err", err)
-			reportUpgradeResult(opts, transport, false, err.Error())
-			return
-		}
+	// Integridad (#284): sha256 obligatorio contra la cabecera del servidor,
+	// ANTES del swap. Sin digest no se instala nada.
+	if digest == "" {
+		err := errors.New("el servidor no envió X-Checksum-Sha256; upgrade rechazado")
+		log.Error("[netpulse-agent] upgrade: falta el digest", "err", err)
+		reportUpgradeResult(opts, transport, false, err.Error())
+		return
+	}
+	reportUpgradeProgress(opts, transport, "verifying", 0)
+	if err := verifySha256(tmpBinPath, digest); err != nil {
+		log.Error("[netpulse-agent] upgrade: verificación falló", "err", err)
+		reportUpgradeResult(opts, transport, false, err.Error())
+		return
 	}
 
 	dst := currentBinPath()

+ 72 - 0
agent/runtime/upgrade_test.go

@@ -4,11 +4,14 @@
 package runtime
 
 import (
+	"crypto/sha256"
+	"encoding/hex"
 	"encoding/json"
 	"net/http"
 	"net/http/httptest"
 	"os"
 	"path/filepath"
+	"strings"
 	"sync"
 	"testing"
 )
@@ -176,7 +179,9 @@ func TestReportUpgradeProgressSteps(t *testing.T) {
 			w.WriteHeader(http.StatusOK)
 		case "/api/agents/patio/binary":
 			data := make([]byte, 64)
+			sum := sha256.Sum256(data)
 			w.Header().Set("Content-Length", "64")
+			w.Header().Set("X-Checksum-Sha256", hex.EncodeToString(sum[:]))
 			_, _ = w.Write(data)
 		case "/api/agents/patio/upgrade-result":
 			w.WriteHeader(http.StatusOK)
@@ -220,3 +225,70 @@ func TestReportUpgradeProgressSteps(t *testing.T) {
 		t.Fatalf("pasos incompletos: %v", steps)
 	}
 }
+
+func TestUpgradeRejectsMissingOrMismatchedDigest(t *testing.T) {
+	for _, tc := range []struct {
+		name   string
+		digest string
+	}{
+		{"sin digest", ""},
+		{"digest que no coincide", strings.Repeat("0", 64)},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			var mu sync.Mutex
+			var steps []string
+			var result map[string]any
+			srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+				switch r.URL.Path {
+				case "/api/agents/patio/upgrade-progress":
+					var body struct {
+						Step string `json:"step"`
+					}
+					_ = json.NewDecoder(r.Body).Decode(&body)
+					mu.Lock()
+					steps = append(steps, body.Step)
+					mu.Unlock()
+					w.WriteHeader(http.StatusOK)
+				case "/api/agents/patio/binary":
+					data := make([]byte, 64)
+					if tc.digest != "" {
+						w.Header().Set("X-Checksum-Sha256", tc.digest)
+					}
+					_, _ = w.Write(data)
+				case "/api/agents/patio/upgrade-result":
+					mu.Lock()
+					result = nil
+					_ = json.NewDecoder(r.Body).Decode(&result)
+					mu.Unlock()
+					w.WriteHeader(http.StatusOK)
+				default:
+					w.WriteHeader(http.StatusNotFound)
+				}
+			}))
+			defer srv.Close()
+
+			oldTmp := tmpBinPath
+			tmpBinPath = filepath.Join(t.TempDir(), "netpulse-agent.new")
+			defer func() { tmpBinPath = oldTmp }()
+			oldPath := currentBinPath
+			currentBinPath = func() string { return filepath.Join(t.TempDir(), "netpulse-agent") }
+			defer func() { currentBinPath = oldPath }()
+
+			handleUpgrade(Options{Server: srv.URL, Slug: "patio", Token: "tok"}, nil, "")
+
+			mu.Lock()
+			defer mu.Unlock()
+			for _, step := range steps {
+				if step == "swapping" || step == "restarting" {
+					t.Fatalf("no debía instalar nada, pasos: %v", steps)
+				}
+			}
+			if result == nil {
+				t.Fatal("no se reportó el resultado del upgrade")
+			}
+			if ok, _ := result["ok"].(bool); ok {
+				t.Fatalf("el upgrade debía fallar, resultado: %v", result)
+			}
+		})
+	}
+}

+ 11 - 0
docs/manual.en.md

@@ -136,6 +136,17 @@ For routers the server cannot reach over SSH, use the **pairing token** (Setting
 2. Click **Update agents** and confirm.
 3. Follow the progress panel: per agent you will see the status (waiting, downloading, installing, updated, or no response). An agent that does not respond within a few seconds requires manual reinstall.
 
+### Agent transport security
+
+Privileged agent commands (apply, upgrade, firmware upgrade and config backup) require the agent to reach the server over HTTPS. If the agent reports over plain HTTP, the server rejects the command with `insecure_agent_transport` and leaves it queued or pending instead of sending it in clear.
+
+The agent also refuses privileged SSE events when `NETPULSE_SERVER` is not HTTPS. During a migration to HTTPS, two environment variables open a temporary exception:
+
+- `NETPULSE_ALLOW_INSECURE_COMMANDS=1` on the agent.
+- `NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS=1` on the server.
+
+Use them only while moving the fleet to HTTPS, then remove them. Binary upgrades always require the `X-Checksum-Sha256` header: both the agent upgrade and the self-heal discard the binary when the header is missing or the digest does not match.
+
 ---
 
 ## Device detail

+ 11 - 0
docs/manual.es.md

@@ -136,6 +136,17 @@ Para routers a los que el servidor no puede acceder por SSH, usa el **token de e
 2. Pulsa **Actualizar agentes** y confirma.
 3. Sigue el panel de progreso: por cada agente verás el estado (esperando, descargando, instalando, actualizado o sin respuesta). Un agente que no responde en unos segundos requiere reinstalación manual.
 
+### Seguridad del transporte del agente
+
+Los comandos privilegiados del agente (aplicar, actualizar, actualizar firmware y copia de configuración) exigen que el agente llegue al servidor por HTTPS. Si el agente reporta por HTTP en claro, el servidor rechaza el comando con `insecure_agent_transport` y lo deja en cola o pendiente en lugar de enviarlo sin cifrar.
+
+El agente también rechaza los eventos SSE privilegiados cuando `NETPULSE_SERVER` no es HTTPS. Durante una migración a HTTPS, dos variables de entorno abren una excepción temporal:
+
+- `NETPULSE_ALLOW_INSECURE_COMMANDS=1` en el agente.
+- `NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS=1` en el servidor.
+
+Úsalas solo mientras mueves la flota a HTTPS y retíralas después. Las actualizaciones de binario exigen siempre la cabecera `X-Checksum-Sha256`: tanto la actualización del agente como el self-heal descartan el binario si falta la cabecera o el digest no coincide.
+
 ---
 
 ## Detalle del dispositivo

+ 19 - 3
install-agent.sh

@@ -447,14 +447,30 @@ selfheal_binary() {
             esac ;;
         *) return 1 ;;
     esac
-    local url tmp
+    local url tmp hdr digest sum
     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.$$
+    hdr=/tmp/netpulse-agent.hdr.$$
     if command -v curl >/dev/null 2>&1; then
-        curl -fsSL -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
+        curl -fsSL -m 120 -D "$hdr" -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || { rm -f "$tmp" "$hdr"; return 1; }
     else
-        wget -q -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
+        wget -S -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" 2>"$hdr" || { rm -f "$tmp" "$hdr"; return 1; }
+    fi
+    digest=$(grep -i '^[[:space:]]*x-checksum-sha256:' "$hdr" 2>/dev/null | tail -n 1 | tr -d '\r' | awk '{print $2}')
+    rm -f "$hdr"
+    case "$digest" in
+        ""|*[!0123456789abcdefABCDEF]*)
+            logger -t netpulse-agent "self-heal: sin X-Checksum-Sha256 válido, binario descartado"
+            rm -f "$tmp"
+            return 1 ;;
+    esac
+    [ "${#digest}" -eq 64 ] || { logger -t netpulse-agent "self-heal: digest con longitud inválida, binario descartado"; rm -f "$tmp"; return 1; }
+    sum=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
+    if [ -z "$sum" ] || [ "$(printf '%s' "$sum" | tr 'A-F' 'a-f')" != "$(printf '%s' "$digest" | tr 'A-F' 'a-f')" ]; then
+        logger -t netpulse-agent "self-heal: SHA-256 no coincide, binario descartado"
+        rm -f "$tmp"
+        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"

+ 27 - 26
server-go/cmd/netpulse/main.go

@@ -492,6 +492,7 @@ func run() error {
 	agentHub := sse.NewAgentHub(func(slug, token string) bool {
 		return checkAgentToken(dbHandle, slug, token)
 	})
+	agentHub.SetAllowInsecureCommands(cfg.AllowInsecureAgentCommands)
 
 	// Scheduler de upgrades programados (#494): tick 30 s, reutiliza el motor
 	// compartido (firmware.Engine) del flujo manual vía el AgentHub.
@@ -750,33 +751,33 @@ func run() error {
 	}
 
 	handler := httpapi.NewHandler(httpapi.Deps{
-		Config:          cfg,
-		DB:              dbHandle,
-		Adapter:         adapter,
-		Hub:             hub,
-		Secret:          secret,
-		Static:          static,
-		Updater:         upd,
-		Agents:          agentReg,
-		Pool:            sshPool,
-		Rearmer:         arm,
-		AgentHub:        agentHub,
-		ServerFP:        serverFP,
-		ServerFPFunc:    serverFPFunc,
-		TLS:             tlsMgr,
-		Orchestr:        orchMgr,
-		MQTT:            mqttMgr,
-		TokenStore:      tokenStore,
-		CollectorReader: collReader,
-		WiFiSLE:         wifiSLE,
-		PathAnalysis:    pathStore,
-		ConfigBackup:    cfgBackup,
-		Firmware:        fwStore,
+		Config:           cfg,
+		DB:               dbHandle,
+		Adapter:          adapter,
+		Hub:              hub,
+		Secret:           secret,
+		Static:           static,
+		Updater:          upd,
+		Agents:           agentReg,
+		Pool:             sshPool,
+		Rearmer:          arm,
+		AgentHub:         agentHub,
+		ServerFP:         serverFP,
+		ServerFPFunc:     serverFPFunc,
+		TLS:              tlsMgr,
+		Orchestr:         orchMgr,
+		MQTT:             mqttMgr,
+		TokenStore:       tokenStore,
+		CollectorReader:  collReader,
+		WiFiSLE:          wifiSLE,
+		PathAnalysis:     pathStore,
+		ConfigBackup:     cfgBackup,
+		Firmware:         fwStore,
 		FirmwareReleases: fwReleases,
-		Speedtest:       stScheduler,
-		AlertEmitter:    adapter.AlertsEngine(),
-		ChannelPlan:     chPlan,
-		MCP:             mcpSrv,
+		Speedtest:        stScheduler,
+		AlertEmitter:     adapter.AlertsEngine(),
+		ChannelPlan:      chPlan,
+		MCP:              mcpSrv,
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},

+ 87 - 69
server-go/internal/config/config.go

@@ -42,35 +42,38 @@ type Webhook struct {
 
 // Config es la config normalizada (equivalente al objeto de loadConfig).
 type Config struct {
-	Port             int
-	NodeEnv          string
-	StaticDir        string // resuelta (absoluta)
-	DataDir          string // resuelta (absoluta)
-	SessionSecret    string // "" si falta (autogenerado en kv)
-	AuthUser         string
-	AuthPass         string
-	DemoMode         bool
-	MaxSSEClients    int
-	Routers          []RouterSeed
-	SSHKeyPath       string
-	Adguard          *AdGuard
-	Webhook          *Webhook
-	WGInterface      string
-	CookieSecure     string // "auto" | "always" | "never"
-	TrustProxy       bool   // confiar en X-Forwarded-For/-Proto (detrás de proxy)
-	MaxTsDriftSec    int    // ventana frescura ts agente en s (0 → default 5 min)
-	GithubRepo       string
-	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)
-	AgentURL         string // NETPULSE_AGENT_URL: URL base preferente SOLO para agentes (install line, reinstall, reemit, auto-reinstall); manda sobre PublicURL (#1335)
-	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)
-	GhostPortEnabled bool   // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
-	MCPEnabled       bool   // NETPULSE_MCP_ENABLED=1: servidor MCP embebido en /mcp (#1114); default false
+	Port            int
+	NodeEnv         string
+	StaticDir       string // resuelta (absoluta)
+	DataDir         string // resuelta (absoluta)
+	SessionSecret   string // "" si falta (autogenerado en kv)
+	AuthUser        string
+	AuthPass        string
+	DemoMode        bool
+	MaxSSEClients   int
+	Routers         []RouterSeed
+	SSHKeyPath      string
+	Adguard         *AdGuard
+	Webhook         *Webhook
+	WGInterface     string
+	CookieSecure    string // "auto" | "always" | "never"
+	TrustProxy      bool   // confiar en X-Forwarded-For/-Proto (detrás de proxy)
+	MaxTsDriftSec   int    // ventana frescura ts agente en s (0 → default 5 min)
+	GithubRepo      string
+	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)
+	AgentURL        string // NETPULSE_AGENT_URL: URL base preferente SOLO para agentes (install line, reinstall, reemit, auto-reinstall); manda sobre PublicURL (#1335)
+	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)
+	// NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS=1: envía comandos privilegiados
+	// a agentes conectados por HTTP. Solo para la transición a HTTPS.
+	AllowInsecureAgentCommands bool
+	Onbox                      bool // NETPULSE_ONBOX=1: modo on-box (Fase 9: config UCI, bootstrap AUTH_PASS)
+	GhostPortEnabled           bool // GHOST_PORT_ENABLED=1: activa alertas de ghost port (#419); default false
+	MCPEnabled                 bool // NETPULSE_MCP_ENABLED=1: servidor MCP embebido en /mcp (#1114); default false
 	// NETPULSE_TLS_ENABLED=1: listener HTTPS adicional (puerto NETPULSE_TLS_PORT,
 	// default 443) junto al HTTP de PORT. Opt-in: sin la variable, arranque
 	// idéntico al actual. El modo on-box ya sirve HTTPS en PORT (Fase 9) y no
@@ -406,6 +409,20 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		}
 	}
 
+	// NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS: '0'|'1', opcional. Permite
+	// enviar comandos privilegiados a agentes que siguen en HTTP. Solo para
+	// la transición a HTTPS; el default los rechaza con 409.
+	allowInsecureAgentCommands := false
+	if v, ok := env["NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			allowInsecureAgentCommands = true
+		default:
+			errs.issues = append(errs.issues, issue{"NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
 	// ADGUARD_*: cliente estándar solo si hay URL válida
 	var adguard *AdGuard
 	if v, ok := env["ADGUARD_URL"]; ok && v != "" {
@@ -627,46 +644,47 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 	}
 
 	return &Config{
-		Port:              port,
-		NodeEnv:           nodeEnv,
-		StaticDir:         resolve(staticDir),
-		DataDir:           resolve(dataDir),
-		SessionSecret:     sessionSecret,
-		AuthUser:          authUser,
-		AuthPass:          authPass,
-		DemoMode:          demoMode,
-		MaxSSEClients:     maxSSE,
-		Routers:           routers,
-		SSHKeyPath:        sshKeyPath,
-		Adguard:           adguard,
-		Webhook:           webhook,
-		WGInterface:       wgInterface,
-		CookieSecure:      cookieSecure,
-		TrustProxy:        trustProxy,
-		MaxTsDriftSec:     maxTsDriftSec,
-		GithubRepo:        githubRepo,
-		GithubToken:       githubToken,
-		ServerRoot:        serverRoot,
-		AutoRearm:         autoRearm,
-		AutoReinstall:     autoReinstall,
-		PublicURL:         publicURL,
-		AgentURL:          agentURL,
-		BeaconListen:      beaconListen,
-		AgentAutoenroll:   agentAutoenroll,
-		Onbox:             onbox,
-		GhostPortEnabled:  ghostPortEnabled,
-		MCPEnabled:        mcpEnabled,
-		RTLConsolePass:    rtlPass,
-		RTLConsolePollSec: rtlPollSec,
-		PollIntervalSec:   pollIntervalSec,
-		TLSEnabled:        tlsEnabled,
-		TLSPort:           tlsPort,
-		TLSPortSet:        tlsPortSet,
-		TLSCert:           tlsCert,
-		TLSKey:            tlsKey,
-		TLSCA:             tlsCA,
-		TLSNames:          tlsNames,
-		HTTPMode:          httpMode,
+		Port:                       port,
+		NodeEnv:                    nodeEnv,
+		StaticDir:                  resolve(staticDir),
+		DataDir:                    resolve(dataDir),
+		SessionSecret:              sessionSecret,
+		AuthUser:                   authUser,
+		AuthPass:                   authPass,
+		DemoMode:                   demoMode,
+		MaxSSEClients:              maxSSE,
+		Routers:                    routers,
+		SSHKeyPath:                 sshKeyPath,
+		Adguard:                    adguard,
+		Webhook:                    webhook,
+		WGInterface:                wgInterface,
+		CookieSecure:               cookieSecure,
+		TrustProxy:                 trustProxy,
+		MaxTsDriftSec:              maxTsDriftSec,
+		GithubRepo:                 githubRepo,
+		GithubToken:                githubToken,
+		ServerRoot:                 serverRoot,
+		AutoRearm:                  autoRearm,
+		AutoReinstall:              autoReinstall,
+		PublicURL:                  publicURL,
+		AgentURL:                   agentURL,
+		BeaconListen:               beaconListen,
+		AgentAutoenroll:            agentAutoenroll,
+		AllowInsecureAgentCommands: allowInsecureAgentCommands,
+		Onbox:                      onbox,
+		GhostPortEnabled:           ghostPortEnabled,
+		MCPEnabled:                 mcpEnabled,
+		RTLConsolePass:             rtlPass,
+		RTLConsolePollSec:          rtlPollSec,
+		PollIntervalSec:            pollIntervalSec,
+		TLSEnabled:                 tlsEnabled,
+		TLSPort:                    tlsPort,
+		TLSPortSet:                 tlsPortSet,
+		TLSCert:                    tlsCert,
+		TLSKey:                     tlsKey,
+		TLSCA:                      tlsCA,
+		TLSNames:                   tlsNames,
+		HTTPMode:                   httpMode,
 	}, nil
 }
 

+ 27 - 0
server-go/internal/config/config_test.go

@@ -133,6 +133,33 @@ func TestLoadTLSEnumInvalido(t *testing.T) {
 	}
 }
 
+func TestLoadAllowInsecureAgentCommands(t *testing.T) {
+	cfg, err := Load(map[string]string{"AUTH_PASS": "segura-y-larga"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if cfg.AllowInsecureAgentCommands {
+		t.Fatal("la válvula debe estar cerrada por defecto")
+	}
+
+	cfg, err = Load(map[string]string{
+		"AUTH_PASS": "segura-y-larga", "NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS": "1",
+	}, t.TempDir())
+	if err != nil {
+		t.Fatalf("Load: %v", err)
+	}
+	if !cfg.AllowInsecureAgentCommands {
+		t.Fatal("NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS=1 debe activar la válvula")
+	}
+
+	_, err = Load(map[string]string{
+		"AUTH_PASS": "segura-y-larga", "NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS": "2",
+	}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "NETPULSE_ALLOW_INSECURE_AGENT_COMMANDS") {
+		t.Fatalf("un valor inválido debe fallar señalando la variable: %v", err)
+	}
+}
+
 func TestLoadTLSCertKeyPareja(t *testing.T) {
 	cfg, err := Load(map[string]string{
 		"AUTH_PASS": "segura-y-larga", "NETPULSE_TLS_ENABLED": "1",

+ 13 - 4
server-go/internal/firmware/engine.go

@@ -8,20 +8,25 @@
 // transición a failed si el agente no está disponible.
 package firmware
 
-import "errors"
+import (
+	"errors"
+
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
 
 // Errores centinela del motor, mapeados por httpapi a los códigos HTTP que el
 // flujo manual ya devolvía (no_target 400, upgrade_in_progress 409,
-// agent_not_connected 503).
+// agent_not_connected 503, insecure_agent_transport 409).
 var (
 	ErrNoTarget          = errors.New("firmware: no target configurado")
 	ErrUpgradeInProgress = errors.New("firmware: upgrade en curso")
 	ErrAgentNotConnected = errors.New("firmware: agente no conectado")
+	ErrInsecureTransport = errors.New("firmware: el agente no usa HTTPS")
 )
 
 // Sender envía comandos al agente vía SSE. Lo implementa *sse.AgentHub.
 type Sender interface {
-	Send(slug, event string, data any) bool
+	SendPrivileged(slug, event string, data any) error
 }
 
 // Engine ejecuta upgrades con el motor compartido (store + sender).
@@ -83,7 +88,11 @@ func (e *Engine) dispatch(id int64, routerID, targetURL, checksum string) error
 		"checksum":   checksum,
 		"keepConfig": true,
 	}
-	if !e.send.Send(routerID, "firmware_upgrade", cmd) {
+	if err := e.send.SendPrivileged(routerID, "firmware_upgrade", cmd); err != nil {
+		if errors.Is(err, sse.ErrInsecureAgentTransport) {
+			_ = e.store.SetStatus(id, "failed", "insecure agent transport", "")
+			return ErrInsecureTransport
+		}
 		_ = e.store.SetStatus(id, "failed", "agent not connected", "")
 		return ErrAgentNotConnected
 	}

+ 2 - 2
server-go/internal/firmware/engine_concurrency_test.go

@@ -8,9 +8,9 @@ import (
 
 type auditConcurrentSender struct{ calls atomic.Int64 }
 
-func (s *auditConcurrentSender) Send(string, string, any) bool {
+func (s *auditConcurrentSender) SendPrivileged(string, string, any) error {
 	s.calls.Add(1)
-	return true
+	return nil
 }
 
 func TestAuditConcurrentStartUpgradeIsSingleFlight(t *testing.T) {

+ 29 - 4
server-go/internal/firmware/engine_test.go

@@ -5,26 +5,36 @@ package firmware
 import (
 	"errors"
 	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/sse"
 )
 
 // fakeSender implementa Sender registrando los comandos enviados. `ok` fija el
-// resultado de Send (false = agente no conectado).
+// resultado de SendPrivileged (false = agente no conectado) y `err` permite
+// simular un transporte inseguro.
 type fakeSender struct {
 	sent []struct {
 		slug  string
 		event string
 		data  any
 	}
-	ok bool
+	ok  bool
+	err error
 }
 
-func (f *fakeSender) Send(slug, event string, data any) bool {
+func (f *fakeSender) SendPrivileged(slug, event string, data any) error {
 	f.sent = append(f.sent, struct {
 		slug  string
 		event string
 		data  any
 	}{slug, event, data})
-	return f.ok
+	if f.err != nil {
+		return f.err
+	}
+	if !f.ok {
+		return errors.New("agent not connected")
+	}
+	return nil
 }
 
 func (f *fakeSender) count() int { return len(f.sent) }
@@ -101,6 +111,21 @@ func TestEngineStartUpgradeAgentOffline(t *testing.T) {
 	}
 }
 
+// TestEngineStartUpgradeInsecureTransport: un agente que sigue en HTTP deja la
+// fila failed y devuelve ErrInsecureTransport, sin confundirlo con offline.
+func TestEngineStartUpgradeInsecureTransport(t *testing.T) {
+	s := open(t)
+	setTarget(t, s, "rt1")
+	e := NewEngine(s, &fakeSender{err: sse.ErrInsecureAgentTransport})
+	if _, err := e.StartUpgrade("rt1"); !errors.Is(err, ErrInsecureTransport) {
+		t.Fatalf("esperaba ErrInsecureTransport, got %v", err)
+	}
+	up, _ := s.LatestUpgrade("rt1")
+	if up == nil || up.Status != "failed" || up.Error != "insecure agent transport" {
+		t.Fatalf("esperaba failed con insecure agent transport, got %+v", up)
+	}
+}
+
 // TestEngineLaunchScheduled: una programación vencida se lanza por el motor
 // (transición requested + comando enviado).
 func TestEngineLaunchScheduled(t *testing.T) {

+ 1 - 0
server-go/internal/httpapi/agent_api_test.go

@@ -71,6 +71,7 @@ func makeAgentTestServer(t *testing.T) *agentTestServer {
 		sum := sha256.Sum256([]byte(token))
 		return hex.EncodeToString(sum[:]) == stored
 	})
+	agentHub.SetAllowInsecureCommands(true)
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
 		Agents: reg, Started: time.Now(), AgentHub: agentHub,

+ 1 - 0
server-go/internal/httpapi/agent_url_test.go

@@ -52,6 +52,7 @@ func makeURLTestServer(t *testing.T, extraEnv map[string]string) *agentTestServe
 	reg := adapters.NewAgentRegistry(90 * time.Second)
 	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
 	agentHub := sse.NewAgentHub(func(_, _ string) bool { return false })
+	agentHub.SetAllowInsecureCommands(true)
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
 		Agents: reg, Started: time.Now(), AgentHub: agentHub,

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

@@ -250,6 +250,9 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 			writeError(w, http.StatusBadRequest, "no_target", "Configura el target de firmware antes de actualizar")
 		case errors.Is(err, firmware.ErrUpgradeInProgress):
 			writeError(w, http.StatusConflict, "upgrade_in_progress", "Ya hay un upgrade en curso")
+		case errors.Is(err, firmware.ErrInsecureTransport):
+			writeError(w, http.StatusConflict, "insecure_agent_transport",
+				"el agente sigue en HTTP; los comandos privilegiados exigen HTTPS")
 		case errors.Is(err, firmware.ErrAgentNotConnected):
 			writeError(w, http.StatusServiceUnavailable, "agent_not_connected", "El agente no está conectado vía SSE")
 		case err != nil:

+ 1 - 0
server-go/internal/httpapi/firmware_test.go

@@ -69,6 +69,7 @@ func firmwareTestServerWithAdapter(t *testing.T, adapter adapters.Snapshotter, r
 	orchestrMgr := orchestr.New(d)
 	agents := adapters.NewAgentRegistry(0)
 	agentHub := sse.NewAgentHub(func(_, _ string) bool { return true })
+	agentHub.SetAllowInsecureCommands(true)
 	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
 	chPlan := channelplan.NewStore(d.DB)
 	handler := httpapi.NewHandler(httpapi.Deps{

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

@@ -5,6 +5,7 @@ package httpapi
 
 import (
 	"encoding/json"
+	"errors"
 	"log"
 	"net/http"
 	"strconv"
@@ -14,6 +15,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/mqttpub"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
 )
 
 // mqttRedactedPass sustituye la contraseña del broker en la copia del plan que
@@ -225,10 +227,14 @@ func (s *server) registerMQTTRoutes(mux *http.ServeMux, mgr *mqttpub.Manager, or
 				continue
 			}
 			data, _ := json.Marshal(map[string]any{"plan_id": plan.ID, "ops": []executor.Op{op}})
-			if !s.agentHub.Send(rt.ID, "apply", json.RawMessage(data)) {
+			if err := s.agentHub.SendPrivileged(rt.ID, "apply", json.RawMessage(data)); err != nil {
 				// No se entregó: el plan vuelve a pending (no se simula éxito).
 				s.restorePlan(orchMgr, plan.ID, "applying", "pending", actor, "sse delivery failed")
-				res["error"] = "agent_not_connected"
+				if errors.Is(err, sse.ErrInsecureAgentTransport) {
+					res["error"] = "insecure_agent_transport"
+				} else {
+					res["error"] = "agent_not_connected"
+				}
 				results = append(results, res)
 				continue
 			}

+ 13 - 2
server-go/internal/httpapi/orchestr.go

@@ -18,6 +18,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
 )
 
 // registerOrchestrRoutes registra las rutas de orquestación (solo admin).
@@ -196,8 +197,13 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 			return
 		}
 		cmdData, _ := json.Marshal(map[string]any{"plan_id": id, "ops": diff})
-		if !s.agentHub.Send(plan.RouterID, "apply", json.RawMessage(cmdData)) {
+		if err := s.agentHub.SendPrivileged(plan.RouterID, "apply", json.RawMessage(cmdData)); err != nil {
 			s.restorePlan(mgr, id, "rolling_back", "applied", actor, "sse delivery failed")
+			if errors.Is(err, sse.ErrInsecureAgentTransport) {
+				writeError(w, http.StatusConflict, "insecure_agent_transport",
+					"el agente sigue en HTTP; los comandos privilegiados exigen HTTPS")
+				return
+			}
 			writeError(w, http.StatusServiceUnavailable, "agent_not_connected",
 				"El agente no está conectado vía SSE")
 			return
@@ -292,8 +298,13 @@ func (s *server) applyPlanHandler(w http.ResponseWriter, r *http.Request, mgr *o
 		return
 	}
 	applyData, _ := json.Marshal(map[string]any{"plan_id": id, "ops": plan.Diff})
-	if !s.agentHub.Send(plan.RouterID, "apply", json.RawMessage(applyData)) {
+	if err := s.agentHub.SendPrivileged(plan.RouterID, "apply", json.RawMessage(applyData)); err != nil {
 		s.restorePlan(mgr, id, "applying", "pending", actor, "sse delivery failed")
+		if errors.Is(err, sse.ErrInsecureAgentTransport) {
+			writeError(w, http.StatusConflict, "insecure_agent_transport",
+				"el agente sigue en HTTP; los comandos privilegiados exigen HTTPS")
+			return
+		}
 		writeError(w, http.StatusServiceUnavailable, "agent_not_connected",
 			"El agente no está conectado vía SSE")
 		return

+ 1 - 0
server-go/internal/httpapi/orchestr_netgrip_test.go

@@ -78,6 +78,7 @@ func newSSEPlanServer(t *testing.T, ov *adapters.Overview, opts ...serverOption)
 	reg := adapters.NewAgentRegistry(0)
 	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
 	agentHub := sse.NewAgentHub(func(_, _ string) bool { return true })
+	agentHub.SetAllowInsecureCommands(true)
 	mqttMgr := mqttpub.NewManager(mqttpub.Config{
 		Enabled: true, Host: "broker.test", Port: 1883,
 		User: "netpulse", Pass: "broker-pass", Instance: "netpulse",

+ 33 - 11
server-go/internal/httpapi/upgrade.go

@@ -18,6 +18,7 @@
 package httpapi
 
 import (
+	"errors"
 	"fmt"
 	"log"
 	"net/http"
@@ -26,6 +27,7 @@ import (
 	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
 	"github.com/gnacho/netpulse/server-go/internal/vercmp"
 )
 
@@ -219,8 +221,8 @@ type upgradeProgress struct {
 // handleAgentUpgrade (admin): ordena a un agente conectado que se actualice
 // descargando el binario embebido del propio servidor.
 //
-//	Códigos: 404 slug desconocido (sin token), 409 agente no conectado por SSE,
-//	         202 comando enviado, 503 sin AgentHub.
+//	Códigos: 404 slug desconocido (sin token), 409 agente en HTTP o no conectado,
+//	         202 comando enviado o encolado, 503 sin AgentHub.
 func (s *server) handleAgentUpgrade(w http.ResponseWriter, r *http.Request) {
 	slug := r.PathValue("slug")
 	if !agentSlugRe.MatchString(slug) {
@@ -242,7 +244,12 @@ func (s *server) handleAgentUpgrade(w http.ResponseWriter, r *http.Request) {
 	// El agente conoce su propia arquitectura (runtime.GOARCH); no hace falta
 	// pasársela. Data vacía {}. Si no está conectado por SSE, el upgrade se
 	// ENCOLA y se enviará en cuanto vuelva a conectar (#284).
-	status := s.sendOrQueueUpgrade(slug)
+	status, err := s.sendOrQueueUpgrade(slug)
+	if errors.Is(err, sse.ErrInsecureAgentTransport) {
+		writeError(w, http.StatusConflict, "insecure_agent_transport",
+			"el agente sigue en HTTP; los comandos privilegiados exigen HTTPS")
+		return
+	}
 	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "status": status})
 }
 
@@ -252,18 +259,22 @@ func (s *server) handleAgentUpgrade(w http.ResponseWriter, r *http.Request) {
 // agente la empuje (#401): nativos → binario embebido; netgrip → su última
 // release pública; external → nunca llega aquí (upgrade-all los filtra y el
 // comando individual no tiene sentido para un scraper).
-func (s *server) sendOrQueueUpgrade(slug string) string {
+func (s *server) sendOrQueueUpgrade(slug string) (string, error) {
 	target := agentbin.EmbeddedAgentVersion
 	if s.agentKindOf(slug) == "netgrip" {
 		target = netgripLatest()
 	}
-	if s.agentHub.Send(slug, "upgrade", map[string]any{}) {
+	err := s.agentHub.SendPrivileged(slug, "upgrade", map[string]any{})
+	if err == nil {
 		// Paso inicial del progreso en vivo (#284): el comando salió.
 		s.upgrades.begin(slug, target)
-		return "sent"
+		return "sent", nil
+	}
+	if errors.Is(err, sse.ErrInsecureAgentTransport) {
+		return "insecure_transport", err
 	}
 	s.upgrades.queue(slug)
-	return "queued"
+	return "queued", nil
 }
 
 // FlushQueuedUpgrade envía el upgrade pendiente de un agente que acaba de
@@ -280,7 +291,7 @@ func (s *server) FlushQueuedUpgrade(slug string) {
 	if s.agentKindOf(slug) == "netgrip" {
 		target = netgripLatest()
 	}
-	if s.agentHub.Send(slug, "upgrade", map[string]any{}) {
+	if err := s.agentHub.SendPrivileged(slug, "upgrade", map[string]any{}); err == nil {
 		s.upgrades.begin(slug, target)
 	} else {
 		s.upgrades.queue(slug)
@@ -309,7 +320,12 @@ func (s *server) handleAgentBackup(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	if !s.agentHub.Send(slug, "config_backup", map[string]any{}) {
+	if err := s.agentHub.SendPrivileged(slug, "config_backup", map[string]any{}); err != nil {
+		if errors.Is(err, sse.ErrInsecureAgentTransport) {
+			writeError(w, http.StatusConflict, "insecure_agent_transport",
+				"el agente sigue en HTTP; los comandos privilegiados exigen HTTPS")
+			return
+		}
 		writeError(w, http.StatusConflict, "not_connected", "agente no conectado por SSE")
 		return
 	}
@@ -423,8 +439,11 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 					// comando SSE dispara el self-update del propio
 					// NetGrip, no el del agente nativo.
 					if version != "" && cmpSemver(netgripLatest(), version) > 0 {
-						item.Status = s.sendOrQueueUpgrade(slug)
+						item.Status, err = s.sendOrQueueUpgrade(slug)
 						item.Upgraded = item.Status == "sent"
+						if errors.Is(err, sse.ErrInsecureAgentTransport) {
+							item.Status = "insecure_transport"
+						}
 						if item.Status == "sent" {
 							sent++
 						}
@@ -439,8 +458,11 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 				// binario embebido (build incluido); un agente más nuevo no
 				// está desactualizado y el botón ofrecería un downgrade.
 				case !agentbin.EmbeddedMismatch() && version != "" && vercmp.CmpBuild(version, agentbin.EmbeddedAgentVersion) < 0:
-					item.Status = s.sendOrQueueUpgrade(slug)
+					item.Status, err = s.sendOrQueueUpgrade(slug)
 					item.Upgraded = item.Status == "sent"
+					if errors.Is(err, sse.ErrInsecureAgentTransport) {
+						item.Status = "insecure_transport"
+					}
 					if item.Status == "sent" {
 						sent++
 					}

+ 22 - 0
server-go/internal/httpapi/upgrade_api_test.go

@@ -39,6 +39,11 @@ type upgradeTestServer struct {
 // makeUpgradeTestServer: app real con registry + AgentHub (checkToken contra
 // kv, como producción). El AgentHub habilita stream/refresh/upgrade.
 func makeUpgradeTestServer(t *testing.T) *upgradeTestServer {
+	t.Helper()
+	return makeUpgradeTestServerWithOptions(t, true)
+}
+
+func makeUpgradeTestServerWithOptions(t *testing.T, allowInsecure bool) *upgradeTestServer {
 	t.Helper()
 	auth.SetTrustProxy(true)
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
@@ -73,6 +78,7 @@ func makeUpgradeTestServer(t *testing.T) *upgradeTestServer {
 		sum := sha256.Sum256([]byte(token))
 		return subtle.ConstantTimeCompare([]byte(hex.EncodeToString(sum[:])), []byte(stored)) == 1
 	})
+	hub.SetAllowInsecureCommands(allowInsecure)
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(),
 		Hub:    sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
@@ -269,6 +275,22 @@ func TestUpgradeConectado202(t *testing.T) {
 	<-done
 }
 
+func TestUpgradeRejectsHTTPTransportWithoutOptIn(t *testing.T) {
+	ts := makeUpgradeTestServerWithOptions(t, false)
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 || tok == "" {
+		t.Fatalf("create: %d", st)
+	}
+	cancel, done := openStream(t, ts, "patio", tok)
+
+	status, body := postUpgrade(t, ts, "patio", ts.cookie)
+	if status != 409 || body["error"] != "insecure_agent_transport" {
+		t.Fatalf("http sin opt-in: got %d %v", status, body)
+	}
+	cancel()
+	<-done
+}
+
 func TestUpgradeResultBearer(t *testing.T) {
 	ts := makeUpgradeTestServer(t)
 	st, tok := createUpgradeToken(t, ts, "patio")

+ 19 - 3
server-go/internal/reinstall/reinstall.go

@@ -309,16 +309,32 @@ selfheal_binary() {
 			esac ;;
 		*) return 1 ;;
 	esac
-	local url tmp
+	local url tmp hdr digest sum
 	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.$$
+	hdr=/tmp/netpulse-agent.hdr.$$
 	local ctls="" wtls=""
 	if [ -f /etc/netpulse-ca.pem ]; then ctls="--cacert /etc/netpulse-ca.pem"; wtls="--ca-certificate=/etc/netpulse-ca.pem"; fi
 	if command -v curl >/dev/null 2>&1; then
-		curl -fsSL $ctls -m 120 -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || return 1
+		curl -fsSL $ctls -m 120 -D "$hdr" -H "Authorization: Bearer $NETPULSE_TOKEN" -o "$tmp" "$url" || { rm -f "$tmp" "$hdr"; return 1; }
 	else
-		wget -q $wtls -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" || return 1
+		wget -S $wtls -T 60 -O "$tmp" --header="Authorization: Bearer $NETPULSE_TOKEN" "$url" 2>"$hdr" || { rm -f "$tmp" "$hdr"; return 1; }
+	fi
+	digest=$(grep -i '^[[:space:]]*x-checksum-sha256:' "$hdr" 2>/dev/null | tail -n 1 | tr -d '\r' | awk '{print $2}')
+	rm -f "$hdr"
+	case "$digest" in
+		""|*[!0123456789abcdefABCDEF]*)
+			logger -t netpulse-agent "self-heal: sin X-Checksum-Sha256 válido, binario descartado"
+			rm -f "$tmp"
+			return 1 ;;
+	esac
+	[ "${#digest}" -eq 64 ] || { logger -t netpulse-agent "self-heal: digest con longitud inválida, binario descartado"; rm -f "$tmp"; return 1; }
+	sum=$(sha256sum "$tmp" 2>/dev/null | awk '{print $1}')
+	if [ -z "$sum" ] || [ "$(printf '%s' "$sum" | tr 'A-F' 'a-f')" != "$(printf '%s' "$digest" | tr 'A-F' 'a-f')" ]; then
+		logger -t netpulse-agent "self-heal: SHA-256 no coincide, binario descartado"
+		rm -f "$tmp"
+		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"

+ 17 - 0
server-go/internal/reinstall/script_test.go

@@ -255,6 +255,23 @@ func TestScriptEmptyDigestSkipsVerify(t *testing.T) {
 	}
 }
 
+func TestScriptSelfHealVerifiesDigest(t *testing.T) {
+	s := reinstall.Script(
+		"r", strings.Repeat("b2", 32), "https://np.example.org", strings.Repeat("c1", 32),
+		map[string]string{"arm64": "x", "arm": "x", "amd64": "x"},
+	)
+	for _, want := range []string{
+		"x-checksum-sha256:",
+		`sha256sum "$tmp"`,
+		"self-heal: sin X-Checksum-Sha256 válido, binario descartado",
+		"self-heal: SHA-256 no coincide, binario descartado",
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("init embebido sin %q en el self-heal", want)
+		}
+	}
+}
+
 // #851: con server https y FP derivado, el .env generado debe llevar
 // NETPULSE_SERVER_FP o el agente entra en bucle fatal al arrancar.
 func TestScriptIncludesServerFP(t *testing.T) {

+ 50 - 3
server-go/internal/sse/agenthub.go

@@ -5,11 +5,22 @@ package sse
 
 import (
 	"encoding/json"
+	"errors"
 	"fmt"
 	"net/http"
 	"strings"
 	"sync"
 	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+var (
+	// ErrAgentNotConnected indica que el agente no tiene stream SSE abierto.
+	ErrAgentNotConnected = errors.New("agent not connected")
+	// ErrInsecureAgentTransport indica que el agente habla HTTP y los
+	// comandos privilegiados exigen HTTPS salvo transición explícita.
+	ErrInsecureAgentTransport = errors.New("agent transport is not secure")
 )
 
 // AgentHub gestiona conexiones SSE por slug de agente.
@@ -17,8 +28,9 @@ type AgentHub struct {
 	// checkToken(slug, token) → true si el token es válido
 	checkToken func(slug, token string) bool
 
-	mu    sync.Mutex
-	conns map[string]*agentConn // slug → conexión activa
+	mu            sync.Mutex
+	conns         map[string]*agentConn // slug → conexión activa
+	allowInsecure bool                  // transición: aceptar comandos sobre HTTP
 	// onConnect se llama (en su propia goroutine) cuando un agente conecta
 	// su stream; lo usa httpapi para enviar upgrades encolados (#284).
 	onConnectMu sync.Mutex
@@ -27,6 +39,7 @@ type AgentHub struct {
 
 type agentConn struct {
 	slug    string
+	secure  bool // la conexión llegó por TLS
 	w       http.ResponseWriter
 	flusher http.Flusher
 	wmu     sync.Mutex
@@ -43,6 +56,14 @@ func NewAgentHub(checkToken func(string, string) bool) *AgentHub {
 	return &AgentHub{checkToken: checkToken, conns: map[string]*agentConn{}}
 }
 
+// SetAllowInsecureCommands permite enviar comandos privilegiados a agentes
+// conectados por HTTP. Solo para la transición a HTTPS.
+func (h *AgentHub) SetAllowInsecureCommands(allow bool) {
+	h.mu.Lock()
+	h.allowInsecure = allow
+	h.mu.Unlock()
+}
+
 // SetOnConnect registra el callback de conexión de agente (#284).
 func (h *AgentHub) SetOnConnect(f func(slug string)) {
 	h.onConnectMu.Lock()
@@ -91,6 +112,32 @@ func (h *AgentHub) Send(slug, event string, data any) bool {
 	return true
 }
 
+// SendPrivileged envía un comando que acaba en root (apply, upgrade,
+// firmware, config_backup). Exige que la conexión del agente sea TLS, salvo
+// que el operador haya habilitado la transición insegura.
+func (h *AgentHub) SendPrivileged(slug, event string, data any) error {
+	h.mu.Lock()
+	c, ok := h.conns[slug]
+	allowInsecure := h.allowInsecure
+	h.mu.Unlock()
+	if !ok {
+		return ErrAgentNotConnected
+	}
+	if !c.secure && !allowInsecure {
+		return ErrInsecureAgentTransport
+	}
+	raw, err := json.Marshal(data)
+	if err != nil {
+		return err
+	}
+	payload := fmt.Sprintf("event: %s\ndata: %s\n\n", event, raw)
+	if err := c.write(payload); err != nil {
+		h.removeConn(c)
+		return err
+	}
+	return nil
+}
+
 func (h *AgentHub) removeConn(c *agentConn) {
 	h.mu.Lock()
 	if h.conns[c.slug] == c {
@@ -171,7 +218,7 @@ func (h *AgentHub) HandleStream(w http.ResponseWriter, r *http.Request) {
 	w.Header().Set("Cache-Control", "no-cache")
 	w.WriteHeader(http.StatusOK)
 
-	c := &agentConn{slug: slug, w: w, flusher: flusher, done: make(chan struct{})}
+	c := &agentConn{slug: slug, secure: auth.IsSecureRequest(r), w: w, flusher: flusher, done: make(chan struct{})}
 	h.mu.Lock()
 	h.conns[slug] = c
 	h.mu.Unlock()

+ 38 - 0
server-go/internal/sse/agenthub_test.go

@@ -1,7 +1,9 @@
 package sse
 
 import (
+	"errors"
 	"net/http/httptest"
+	"strings"
 	"sync"
 	"testing"
 )
@@ -45,3 +47,39 @@ func TestAgentConnWriteConcurrentNoRace(t *testing.T) {
 		t.Fatalf("body length = %d, want %d (interleaved/corrupted writes)", got, want)
 	}
 }
+
+func TestSendPrivilegedRequiresTLSTransport(t *testing.T) {
+	h := NewAgentHub(func(string, string) bool { return true })
+	rec := httptest.NewRecorder()
+	c := &agentConn{slug: "router", w: rec, flusher: rec, done: make(chan struct{})}
+	h.conns["router"] = c
+
+	if err := h.SendPrivileged("router", "upgrade", map[string]int{"n": 1}); !errors.Is(err, ErrInsecureAgentTransport) {
+		t.Fatalf("HTTP debía rechazarse, got %v", err)
+	}
+	if rec.Body.Len() != 0 {
+		t.Fatalf("no debía escribir nada, body: %q", rec.Body.String())
+	}
+
+	h.SetAllowInsecureCommands(true)
+	if err := h.SendPrivileged("router", "upgrade", map[string]int{"n": 1}); err != nil {
+		t.Fatalf("con la válvula debía permitirse, got %v", err)
+	}
+	if !strings.Contains(rec.Body.String(), "event: upgrade") {
+		t.Fatalf("no llegó el evento: %q", rec.Body.String())
+	}
+}
+
+func TestSendPrivilegedAllowsTLSAndRejectsDisconnected(t *testing.T) {
+	h := NewAgentHub(func(string, string) bool { return true })
+	rec := httptest.NewRecorder()
+	c := &agentConn{slug: "router", secure: true, w: rec, flusher: rec, done: make(chan struct{})}
+	h.conns["router"] = c
+
+	if err := h.SendPrivileged("router", "apply", map[string]string{"plan": "x"}); err != nil {
+		t.Fatalf("TLS debía permitirse, got %v", err)
+	}
+	if err := h.SendPrivileged("otro", "apply", nil); !errors.Is(err, ErrAgentNotConnected) {
+		t.Fatalf("desconectado debía dar ErrAgentNotConnected, got %v", err)
+	}
+}