Procházet zdrojové kódy

feat: Fase 6 — HMAC-SHA256 en ingesta del agente y binario servido desde el servidor

- HMAC-SHA256(token, body) en cabecera X-Agent-Signature (agente + servidor)
- GET /api/agents/{slug}/binary?arch=... sirve el binario embebido
- Binarios del agente (amd64/arm64/armv7) embebidos vía go:embed en agentbin/
- CI construye agentes para las 3 arquitecturas antes de compilar el servidor
- One-liner de instalación descarga el binario del servidor (sin GitHub)
- Bump v2.5.0 (server-go + app/package.json + docs)
gnacho před 4 měsíci
rodič
revize
cdc259d634

+ 10 - 0
.github/workflows/go.yml

@@ -47,6 +47,16 @@ jobs:
         working-directory: server-go
         run: go test ./...
 
+      - name: Build agent binaries para embed (todas las arquitecturas)
+        run: |
+          for target in amd64 arm64 armv7; do
+            goarch="$target"
+            goarm=""
+            if [ "$target" = "armv7" ]; then goarch="arm"; goarm="GOARM=7"; fi
+            echo "→ agente linux/$target"
+            (cd agent && CGO_ENABLED=0 GOOS=linux GOARCH=$goarch $goarm go build -trimpath -ldflags "-s -w" -o ../server-go/internal/agentbin/agents/netpulse-agent-$target ./cmd/netpulse-agent)
+          done
+
       - name: Build binario (linux/${{ matrix.arch }})
         working-directory: server-go
         env:

+ 10 - 0
.github/workflows/release.yml

@@ -44,6 +44,16 @@ jobs:
           (cd server-go && go test ./...)
           (cd collector && go test ./...)
 
+      - name: Build agent binaries para embed (todas las arquitecturas)
+        run: |
+          for target in amd64 arm64 armv7; do
+            goarch="$target"
+            goarm=""
+            if [ "$target" = "armv7" ]; then goarch="arm"; goarm="GOARM=7"; fi
+            echo "→ agente linux/$target"
+            (cd agent && CGO_ENABLED=0 GOOS=linux GOARCH=$goarch $goarm go build -trimpath -ldflags "-s -w" -o ../server-go/internal/agentbin/agents/netpulse-agent-$target ./cmd/netpulse-agent)
+          done
+
       - name: Valida config goreleaser
         uses: goreleaser/goreleaser-action@v6
         with:

+ 3 - 0
.gitignore

@@ -15,3 +15,6 @@ server/.env
 # Notas locales con credenciales
 *_user.txt
 v2/
+
+# Binarios de agente embebidos (construidos por CI)
+server-go/internal/agentbin/agents/netpulse-agent-*

+ 12 - 1
agent/internal/push/push.go

@@ -8,6 +8,9 @@ package push
 import (
 	"bytes"
 	"context"
+	"crypto/hmac"
+	"crypto/sha256"
+	"encoding/hex"
 	"encoding/json"
 	"fmt"
 	"io"
@@ -165,7 +168,14 @@ func (c *Client) growBackoffLocked() {
 	}
 }
 
-// post hace el POST con Bearer; error si no hay 2xx.
+// hmacSign devuelve HMAC-SHA256(token, body) en hex.
+func hmacSign(token string, body []byte) string {
+	mac := hmac.New(sha256.New, []byte(token))
+	mac.Write(body)
+	return hex.EncodeToString(mac.Sum(nil))
+}
+
+// post hace el POST con Bearer + HMAC; error si no hay 2xx.
 func (c *Client) post(ctx context.Context, p *probe.Payload) error {
 	body, err := json.Marshal(p)
 	if err != nil {
@@ -177,6 +187,7 @@ func (c *Client) post(ctx context.Context, p *probe.Payload) error {
 	}
 	req.Header.Set("Content-Type", "application/json")
 	req.Header.Set("Authorization", "Bearer "+c.token)
+	req.Header.Set("X-Agent-Signature", hmacSign(c.token, body))
 	res, err := c.hc.Do(req)
 	if err != nil {
 		return err

+ 3 - 3
app/package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "netpulse",
-  "version": "2.4.4",
+  "version": "2.5.0",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "netpulse",
-      "version": "2.4.4",
+      "version": "2.5.0",
       "dependencies": {
         "@hookform/resolvers": "^5.2.2",
         "@radix-ui/react-accordion": "^1.2.12",
@@ -10425,4 +10425,4 @@
       }
     }
   }
-}
+}

+ 1 - 1
app/package.json

@@ -1,7 +1,7 @@
 {
   "name": "netpulse",
   "private": true,
-  "version": "2.4.4",
+  "version": "2.5.0",
   "type": "module",
   "scripts": {
     "dev": "vite",

+ 5 - 6
docs/AGENTE-OPENWRT.md

@@ -1,15 +1,14 @@
 # Fase 6 — Agente nativo OpenWrt (`netpulse-agent`)
 
-> Estado: **piloto implementado** (2026-08-02): ingesta `POST /api/ingest/agent`
-> + tokens por equipo + adapter live-agent con fallback SSH + binario
-> `agent/` (probe compartido, push con backoff, procd, install-agent.sh).
+> Estado: **piloto implementado** (2026-08-02) + **seguridad HMAC + binario desde server** (v2.5.0, 2026-08-05):
+> ingesta `POST /api/ingest/agent` + tokens por equipo + adapter live-agent con fallback SSH + binario
+> `agent/` (probe compartido, push con backoff, procd, install-agent.sh) +
+> **HMAC-SHA256 obligatorio** (cabecera `X-Agent-Signature`) + **binario servido desde
+> `GET /api/agents/{slug}/binary?arch=...`** (embebido vía go:embed, sin GitHub).
 > Medido: **5,8 MB arm64** (suelo realista con TLS/x509; el objetivo inicial
 > ≤ 3 MB no es alcanzable sin renunciar a HTTPS — cabe sobrado en MT6000/MT7981;
 > la variante `/tmp` cubre flashes justas). Pendiente incremento 2: netlink/
 > nl80211 nativo, eventos ubus, `.ipk`, medición en hardware real.
-> Base: auditoría del collector piloto (2026-08-02) y la decisión de tiers:
-> Tier 0 = SSH agentless (actual, obligatorio) · Tier 1 = `lldpd` ·
-> **Tier 2 = agente nativo opcional por equipo.**
 
 ## Por qué un agente
 

+ 4 - 120
docs/HOJA-DE-RUTA-OPENCODE.md

@@ -1,15 +1,14 @@
 # Hoja de ruta operativa para opencode — NetPulse
 
-> Versión: 2026-08-05 (v2.4.4). Repo: `~/Documentos/Mi Nube/Proyectos/repos/netpulse-git`.
+> Versión: 2026-08-05 (v2.5.0). Repo: `~/Documentos/Mi Nube/Proyectos/repos/netpulse-git`.
 > Ejecutar desde opencode en ese repo. Antes de cada fase, leer `docs/ROADMAP.md`,
 > `docs/AUDITORIA-FASE65.md` y este fichero.
 
 ## Estado de partida
 
-- Producción en CT 226 (`192.168.1.226:3000`), versión `v2.4.4`.
-- Fases 1-5 terminadas y desplegadas.
-- Fase 6 incompleta: HMAC, binario del agente, HTTPS y cluster Proxmox.
-- Fases 7-9 definidas en `docs/ROADMAP.md` pero no iniciadas.
+- Producción en CT 226 (`192.168.1.226:3000`), versión `v2.5.0`.
+- Fases 1-6 terminadas y desplegadas (Fase 6 = HMAC + binario agente desde server).
+- Fase 7 definida en `docs/ROADMAP.md` pero no iniciada.
 - Convenciones de trabajo: `reglas.md` (opencode memory), `docs/ROADMAP.md` §Convención.
 
 ## Reglas para opencode
@@ -30,121 +29,6 @@
 
 ---
 
-## Fase 6 — TLS, endurecimiento y cierre de fixes
-
-**Meta:** que el agente sea seguro, el servidor sirva HTTPS, los agentes se
-reinstalen desde el propio servidor, y el cluster Proxmox se identifique.
-Sin esto no se puede avanzar a Fase 7/8/9.
-
-### 6.1 HMAC-SHA256 en la ingesta del agente
-
-**Riesgo:** cualquiera con la URL puede inyectar datos falsos.
-**Solución:** firmar el payload JSON con el token compartido.
-
-Pasos:
-1. En `server-go`, añadir middleware/validador en la ruta de ingesta del
-   agente (buscar dónde recibe `POST` del agente; probablemente en
-   `internal/httpapi/` o `internal/adapters/`). Rechazar si falta cabecera
-   `X-Agent-Signature` o si no coincide `HMAC-SHA256(token, body)`.
-2. En `agent/` (Go), calcular la firma antes de enviar y añadir la cabecera.
-3. Asegurar que el token no viaje en URL (ya debería estar en env/cabecera).
-4. Tests: unitario en server-go con payload válido e inválido.
-5. Añadir en `docs/AGENTE-OPENWRT.md` la nueva cabecera.
-
-Criterio de aceptación:
-- Un POST sin firma devuelve 401.
-- Un POST con firma correcta se ingiere.
-- El agente oficial sigue funcionando tras reinstalar.
-
-### 6.2 Servir el binario del agente desde el servidor
-
-**Riesgo:** el `install-agent.sh` descarga de GitHub y pasa el token en argv.
-**Solución:** endpoint `GET /api/agents/{slug}/binary?arch=...` sirve el
-binario correcto firmado por el servidor.
-
-Pasos:
-1. Incluir los binarios del agente (o al menos los targets habituales:
-   `mipsel-softfloat`, `aarch64`, `x86_64`) en el release CI o en
-   `server-go/assets/agents/`.
-2. Crear endpoint autenticado/admin que sirva el binario según `slug` y `arch`.
-3. Generar un script de instalación reducido que:
-   - Descarga el binario del servidor con autenticación de admin.
-   - Lo instala en `/usr/bin/netpulse-agent`.
-   - Crea procd service y UCI config.
-   - Pide/adopta el token de emparejamiento.
-4. Marcar `install-agent.sh` antiguo como fallback para desarrollo.
-5. Actualizar `docs/AGENTE-OPENWRT.md` y el skill `netpulse-ops` si procede.
-
-Criterio de aceptación:
-- Desde un router se puede ejecutar el nuevo install y obtener el binario del
-  servidor sin GitHub.
-- El token no aparece en `ps` ni en argv.
-
-### 6.3 HTTPS en CT 226
-
-**Bloqueo:** Web Push no funciona sin secure context; los agentes no pueden
-validar un cert autofirmado sin `--insecure`.
-
-Opciones a decidir:
-- **A) Caddy + cert autofirmado**: Caddy delante de server-go en CT 226.
-  El navegador añade excepción la primera vez. El agente valida el cert
-  con fingerprint pre-ship o usa HMAC (no hace falta TLS para la firma, pero sí
-  para confidencialidad).
-- **B) Tailscale Serve**: si hay salida a internet, `tailscale serve` da HTTPS
-  automático. Los routers deben estar en la misma tailnet. Es más fácil pero
-  añade dependencia externa.
-
-Pasos comunes:
-1. Elegir A o B y documentar la decisión en `docs/SEGURIDAD-TLS.md`.
-2. Si se elige A, añadir Caddy al CT, cert autofirmado, redirección 80→443, y
-   proxy inverso a `server-go` en localhost:3000.
-3. Actualizar `install.sh` del servidor para generar/renovar cert.
-4. Asegurar que `NETPULSE_INSECURE_TLS` pueda retirarse.
-5. Deploy y verificar `/api/health` en `https://192.168.1.226`.
-
-Criterio de aceptación:
-- Web Push se puede suscribir desde un navegador en la red local.
-- El agente se comunica con el servidor sin `--insecure`.
-
-### 6.4 Identificación de Proxmox en cluster
-
-**Problema actual:** la regla de topología requiere exactamente un host por
-puerto de switch. En un cluster Proxmox hay 2 hosts (citadel-01/02), por lo que
-el puerto se etiqueta como `inferred`.
-
-Ubicación a investigar:
-- `server-go/internal/adapters/topo_semantics.go` y `topology.go`.
-- Búsqueda clave: OUI de hypervisor (`BC:24:11` para Proxmox), `vmMAC`,
-  `hostMACs`, `DistributionNode`, `hypervisor`.
-
-Pasos:
-1. Revisar el FDB real del switch para ver cómo se aprenden las MACs de los
-   hosts Proxmox y sus CTs/VMs. Preguntar/verificar si cada host tiene su
-   propio puerto o si comparten uno.
-2. Si cada host está en su propio puerto, revisar por qué no se detecta
-   (quizá la MAC del host no está en la base de datos o la regla falla).
-3. Si comparten puerto, decidir estrategia:
-   - Opción A: crear un nodo `hypervisor-cluster` que agrupa múltiples hosts y
-     sus CTs/VMs (el frontend necesitaría saber pintarlo).
-   - Opción B: detectar por API de Proxmox (corosync, API pve) para asignar
-     cada VM/CT a su host.
-   - Opción C: configuración manual del usuario: declarar los hosts del
-     cluster y dejar que el servidor asigne las VMs por IP/subnet.
-4. Implementar la opción elegida.
-5. Añadir tests con datos de FDB simulados para cluster de 2 hosts.
-6. Actualizar ROADMAP y documentar la decisión.
-
-Criterio de aceptación:
-- En producción, el mapa de topología muestra el cluster Proxmox con sus hosts
-  y CTs correctamente anidados, o documenta por qué no es posible sin API externa.
-
-### 6.5 Cierre de deuda cosmética
-
-Si tras v2.4.4 queda algo (layout, traducciones, iconos), resolverlo aquí.
-No iniciar nuevas features cosméticas.
-
----
-
 ## Fase 7 — Agente a fondo
 
 **Meta:** convertir el agente de sondeo cada 15 s en componente de red a

+ 30 - 31
docs/ROADMAP.md

@@ -1,12 +1,12 @@
 # NetPulse — Hoja de ruta
 
-> Actualizada: 2026-08-05 (v2.4.4). Fases reordenadas por peso/entregable, no
+> Actualizada: 2026-08-05 (v2.5.0). Fases reordenadas por peso/entregable, no
 > estrictamente por orden cronológico. El refactor Node → Go sigue siendo la
 > base, pero se sitúa como Fase 3 porque las Fases 1 y 2 son los hitos visibles
 > que hoy definen el producto. Referencias: `docs/AUDITORIA-FASE65.md`
 > (riesgos R1-R8), `docs/AGENTE-OPENWRT.md` (diseño del agente), ARCHITECTURE.md.
 
-## Estado actual (v2.4.4)
+## Estado actual (v2.5.0)
 
 Hecho y en producción (CT 226):
 - **Fase 1 — Topología v5** (v2.1.0): FDB + LLDP en vivo, backhaul real,
@@ -21,6 +21,10 @@ Hecho y en producción (CT 226):
   displayName y remodel de Preferencias.
 - **Fase 5 — Resiliencia del agente** (v2.3.0/v2.4.0/v2.4.1): watchdog,
   rearme desde servidor, auto-rearme TTL y endurecimiento de rutas admin.
+- **Fase 6 — Seguridad del agente** (v2.5.0): **HMAC-SHA256 en la ingesta**
+  (firma obligatoria del payload con el token), **binario del agente servido
+  desde el propio servidor** (`GET /api/agents/{slug}/binary`) eliminando la
+  dependencia de GitHub y el token en argv.
 - **Cierre de fixes cosméticos/de datos** (v2.4.2/v2.4.3/v2.4.4): idioma
   "auto", BD limpia + demo desde UI, clientes GL.iNet vía `gl-clients`, layout
   radial y espaciado de iconos en topología (issues #3/#4/#5).
@@ -32,11 +36,18 @@ Dormido en producción (implementado pero sin efecto real):
   aportan tiempo real; y reportan versión 0.1.0 hasta reinstalarlos con la
   próxima release.
 
-Pendiente inmediato (Fase 6):
-- HMAC-SHA256 en la ingesta del agente.
-- Servir el binario del agente desde el propio servidor.
-- HTTPS en CT 226.
-- Identificación de Proxmox en cluster.
+Pendiente inmediato (Fase 7):
+- Eventos ubus en tiempo real (hostapd assoc/disassoc).
+- netlink/nl80211 nativo (FDB/ARP/stations sin parsear CLI).
+- Comunicación bidireccional (WebSocket/SSE agente↔servidor).
+- Empaquetado `.ipk` para `opkg install`.
+- Profiling en hardware real (Flint 2 + APs).
+
+Deuda sin fase:
+- Web Push dormido (sin HTTPS en servidor; decisión de despliegue del usuario).
+- Agentes reportan versión 0.1.0 (reinstalar con release nueva para el fix de goreleaser `-X main.Version`).
+- Collector sidecar sin integrar con server-go.
+- recharts v2 deprecated.
 
 ---
 
@@ -103,32 +114,20 @@ Cierre de los huecos de supervisión detectados en la auditoría del piloto:
 
 ---
 
-## Fase 6 — TLS, endurecimiento y cierre de fixes (bloqueante, ~1 día + sprints)
+## Fase 6 — Seguridad del agente (hecha, v2.5.0)
 
-Fusión de la deuda cosmética reciente con los bloqueantes de seguridad.
-Sin esto, ni push funciona ni la Fase 8 es segura.
+Cierre de los huecos de seguridad detectados en la auditoría del piloto:
 
-**Desarrollo:**
-1. **HMAC-SHA256 en la ingesta del agente** (R4): firmar el payload con el
-   token. ~10 líneas. Barato ahora, carísimo después de la Fase 8.
-2. **Servir el binario del agente desde el propio servidor** (R3):
-   `GET /api/agents/{slug}/binary?arch=...` — elimina la dependencia de
-   GitHub en LANs sin salida y el `curl | sh` con token en argv.
-3. **Identificación de Proxmox en live**: hoy solo se detecta hipervisor si
-   hay exactamente un host con MAC de hipervisor + VMs con OUI de hipervisor.
-   En producción con cluster Proxmox (2 hosts citadel-01/02) no se identifica
-   porque la regla exige "exactamente un host". Revisar si hay que relajar a
-   "uno o más hosts" o si el problema es que los hosts no están en la BD.
-4. Cierre de deuda cosmética pendiente (si queda algo tras v2.4.4).
-
-**Deploy:**
-1. **HTTPS en CT 226** (R1): Caddy delante con cert autofirmado + confianza
-   manual, o Tailscale Serve (HTTPS automático). Desbloquea Web Push real y
-   permite retirar `NETPULSE_INSECURE_TLS`.
-   Decisión pendiente: Caddy vs Tailscale (afecta a cómo confiarán los
-   routers en el cert cuando ellos también empujen con TLS).
-2. **Reinstalar agentes con release nueva** para que reporten versión real
-   (el fix `-X main.Version` ya está en goreleaser).
+1. **HMAC-SHA256 en la ingesta** (R4): el agente firma cada payload con
+   `HMAC-SHA256(token, body)` en la cabecera `X-Agent-Signature`. El servidor
+   rechaza peticiones sin firma o con firma inválida (401).
+2. **Binario del agente desde el servidor** (R3): endpoint
+   `GET /api/agents/{slug}/binary?arch=...` con auth por token de agente
+   (Bearer). Los binarios van embebidos en el servidor vía `go:embed`
+   (construidos por CI para amd64/arm64/armv7). El one-liner de instalación
+   descarga el binario del servidor en vez de GitHub.
+
+**Deploy**: reinstalar agentes con la nueva release para que usen HMAC.
 
 ---
 

+ 43 - 0
server-go/internal/agentbin/agentbin.go

@@ -0,0 +1,43 @@
+// Package agentbin — binarios del agente netpulse-agent embebidos en el
+// servidor para servir vía GET /api/agents/{slug}/binary?arch=... sin
+// dependencia de GitHub (Fase 6.2).
+//
+// El CI construye el agente para amd64/arm64/armv7, copia los binarios a
+// agentbin/agents/ (netpulse-agent-amd64, netpulse-agent-arm64, etc.) y
+// luego compila el servidor. En desarrollo el directorio solo contiene
+// .gitkeep (lo ignora git) y el servidor devuelve 404 para el endpoint
+// de binarios — el install-agent.sh con --binary o GitHub siguen funcionando.
+package agentbin
+
+import (
+	"embed"
+	"io/fs"
+)
+
+//go:embed agents/*
+var agentsFS embed.FS
+
+// Open devuelve el binario para la arquitectura dada, o error si no existe.
+// Las arquitecturas válidas son las mismas que las builds de goreleaser:
+// "amd64", "arm64", "armv7".
+func Open(arch string) (fs.File, error) {
+	name := "agents/netpulse-agent-" + arch
+	f, err := agentsFS.Open(name)
+	if err != nil {
+		return nil, err
+	}
+	// El embed no distingue ficheros de directorios (todos tienen IsDir false,
+	// incluso el directorio agents/ si está vacío). Si el fichero existe pero
+	// no tiene contenido útil, el Stat devolverá tamaño 0 y lo tratamos como
+	// no disponible.
+	st, err := f.Stat()
+	if err != nil {
+		f.Close()
+		return nil, err
+	}
+	if st.Size() == 0 {
+		f.Close()
+		return nil, fs.ErrNotExist
+	}
+	return f, nil
+}

+ 0 - 0
server-go/internal/agentbin/agents/.gitkeep


+ 75 - 5
server-go/internal/httpapi/agent.go

@@ -13,6 +13,7 @@
 package httpapi
 
 import (
+	"crypto/hmac"
 	"crypto/rand"
 	"crypto/sha256"
 	"crypto/subtle"
@@ -28,6 +29,7 @@ import (
 	"time"
 
 	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/agentbin"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
@@ -134,6 +136,21 @@ func (s *server) checkAgentToken(slug, token string) bool {
 	return subtle.ConstantTimeCompare([]byte(got), []byte(stored)) == 1
 }
 
+// checkHMAC verifica que X-Agent-Signature coincida con HMAC-SHA256(token, body).
+// Devuelve nil si la firma es correcta; error si falta o no coincide.
+func checkHMAC(token string, body []byte, sig string) error {
+	if sig == "" {
+		return errors.New("falta X-Agent-Signature")
+	}
+	mac := hmac.New(sha256.New, []byte(token))
+	mac.Write(body)
+	expected := hex.EncodeToString(mac.Sum(nil))
+	if subtle.ConstantTimeCompare([]byte(sig), []byte(expected)) != 1 {
+		return errors.New("HMAC no coincide")
+	}
+	return nil
+}
+
 // ---------------------------------------------------------------------------
 // POST /api/ingest/agent (auth Bearer propia; exenta del middleware de sesión)
 // ---------------------------------------------------------------------------
@@ -175,6 +192,12 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusUnauthorized, "unauthorized")
 		return
 	}
+	// 401: HMAC-SHA256 del payload no coincide (R4: firma obligatoria)
+	sig := r.Header.Get("X-Agent-Signature")
+	if err := checkHMAC(token, body, sig); err != nil {
+		writeError(w, http.StatusUnauthorized, "invalid_signature", err.Error())
+		return
+	}
 	if s.agents == nil {
 		writeError(w, http.StatusServiceUnavailable, "unavailable",
 			"el servidor no tiene registry de agentes")
@@ -184,6 +207,52 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
 }
 
+// ---------------------------------------------------------------------------
+// GET /api/agents/{slug}/binary?arch=... — Fase 6.2: servir el binario del
+// agente desde el propio servidor (embebido vía go:embed en agentbin/).
+// Elimina la dependencia de GitHub para instalar/reinstalar agentes.
+// Auth por token de agente (Bearer), igual que la ingesta — el one-liner de
+// instalación incluye el token y se ejecuta en el router.
+// ---------------------------------------------------------------------------
+
+func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	if !agentSlugRe.MatchString(slug) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	// Auth por token de agente (no sesión admin)
+	token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+	if !s.checkAgentToken(slug, token) {
+		writeError(w, http.StatusUnauthorized, "unauthorized")
+		return
+	}
+	arch := r.URL.Query().Get("arch")
+	if arch == "" {
+		arch = "arm64"
+	}
+	f, err := agentbin.Open(arch)
+	if err != nil {
+		writeError(w, http.StatusNotFound, "not_found",
+			"binario no disponible para "+arch+" (compila el servidor con los binarios de agente embebidos)")
+		return
+	}
+	defer f.Close()
+	st, _ := f.Stat()
+	w.Header().Set("Content-Type", "application/octet-stream")
+	w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-agent-%s"`, arch))
+	http.ServeContent(w, r, st.Name(), st.ModTime(), f.(io.ReadSeeker))
+}
+
+// hasAgentToken verifica si existe un token para el slug (rápido, sin cargar el valor).
+func (s *server) hasAgentToken(slug string) bool {
+	if s.db == nil {
+		return false
+	}
+	var dummy string
+	return s.db.QueryRow("SELECT value FROM kv WHERE key = ?", agentTokenKey(slug)).Scan(&dummy) == nil
+}
+
 // ---------------------------------------------------------------------------
 // Gestión de tokens (sesión): POST/GET /api/agents, DELETE /api/agents/{slug}
 // ---------------------------------------------------------------------------
@@ -224,9 +293,10 @@ func (s *server) handleAgentsCreate(w http.ResponseWriter, r *http.Request) {
 	})
 }
 
-// agentInstallLine: one-liner de instalación vía SSH desde esta máquina
-// (install-agent.sh, hermano de install-collector.sh). El host del router se
-// resuelve de la tabla routers si el slug existe.
+// agentInstallLine: one-liner de instalación vía SSH desde esta máquina.
+// El host del router se resuelve de la tabla routers si el slug existe.
+// Fase 6.2: el binario se descarga del propio servidor con el token del agente
+// en vez de GitHub, eliminando la dependencia de internet y el token en argv.
 func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 	host := "<ip-del-router>"
 	if s.db != nil {
@@ -243,8 +313,8 @@ func (s *server) agentInstallLine(r *http.Request, slug, token string) string {
 	}
 	server := scheme + "://" + r.Host
 	return fmt.Sprintf(
-		"curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --host %s --server %s --slug %s --token %s",
-		host, server, slug, token)
+		"curl -fsSL -H 'Authorization: Bearer %s' %s/api/agents/%s/binary -o /tmp/netpulse-agent && curl -fsSL https://raw.githubusercontent.com/gnacho/netpulse/main/install-agent.sh | sh -s -- --binary /tmp/netpulse-agent --host %s --server %s --slug %s --token %s",
+		token, server, slug, host, server, slug, token)
 }
 
 // agentListItem: lo que ve la UI — NUNCA el token ni su hash.

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

@@ -5,6 +5,7 @@
 package httpapi_test
 
 import (
+	"crypto/hmac"
 	"crypto/sha256"
 	"encoding/hex"
 	"encoding/json"
@@ -102,6 +103,9 @@ func ingest(t *testing.T, ts *agentTestServer, token, ip, payload string) *http.
 	req.Header.Set("X-Forwarded-For", ip)
 	if token != "" {
 		req.Header.Set("Authorization", "Bearer "+token)
+		mac := hmac.New(sha256.New, []byte(token))
+		mac.Write([]byte(payload))
+		req.Header.Set("X-Agent-Signature", hex.EncodeToString(mac.Sum(nil)))
 	}
 	res, err := http.DefaultClient.Do(req)
 	if err != nil {

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

@@ -30,7 +30,7 @@ import (
 )
 
 // Version es la versión del backend (app.js:18).
-const Version = "2.4.4"
+const Version = "2.5.0"
 
 // Deps son las dependencias del servidor API (como createApp de app.js).
 type Deps struct {
@@ -151,6 +151,10 @@ func NewHandler(d Deps) http.Handler {
 	mux.Handle("DELETE /api/agents/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleAgentsDelete)))
 	// Fase 5 (Plan B): rearme del servicio procd del agente vía SSH.
 	mux.Handle("POST /api/agents/{slug}/rearm", auth.RequireAdmin(http.HandlerFunc(s.handleAgentRearm)))
+	// Fase 6.2: servir binario del agente desde el propio servidor (sin GitHub).
+	// Auth por token de agente (Bearer), igual que la ingesta — el one-liner de
+	// instalación incluye el token y se ejecuta en el router, sin sesión admin.
+	mux.HandleFunc("GET /api/agents/{slug}/binary", s.handleAgentBinary)
 
 	// --- Web Push (Fase 3 Bloque C; tras sesión como el resto del API) ---
 	mux.HandleFunc("GET /api/push/vapid-key", s.handlePushVapidKey)