Przeglądaj źródła

fix(agent): preserve user env vars on reinstall, document defaults, drop watchdog cron (#851) (#872)

The console reinstall and the hot token rotation rewrote /etc/netpulse-agent.env from scratch, dropping user settings like NETPULSE_SCAN_INTERVAL=0: both now preserve any NETPULSE_* lines they don't manage, and the generated env documents the available options as commented defaults. The watchdog cron is dropped from new installs (blind restarts don't fix a crash loop, the server's dead-man detection does; procd respawn still covers one-shot crashes and the binary self-heal moves into the standalone init). Upgrading cleans the cron entry and watchdog file from previous versions. Ref #851
Nacho 2 miesięcy temu
rodzic
commit
ac3d68438e

+ 37 - 0
agent/deploy/netpulse-agent.init

@@ -15,10 +15,47 @@ START=99
 STOP=10
 USE_PROCD=1
 
+ENV_FILE=/etc/netpulse-agent.env
 BIN=/usr/sbin/netpulse-agent
 [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
 
+# Self-heal: un sysupgrade solo conserva /etc, así que si el binario falta
+# al arrancar se descarga del server con el env (mismo criterio que el
+# reinstall del server; #851 retiró el watchdog cron, esto cubre el boot).
+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 ;;
+        mips)
+            case "$(head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12')" in
+                1) local ARCH=mipsle ;;
+                2) local ARCH=mips ;;
+                *) return 1 ;;
+            esac ;;
+        *) 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"
     # respawn: si muere, procd lo levanta (5 s entre intentos, 5 intentos/hora)

+ 8 - 29
deploy/openwrt/netpulse-agent/files/netpulse-agent.defaults

@@ -1,7 +1,7 @@
 #!/bin/sh
 # uci-defaults: ejecutado UNA vez tras instalar el .ipk.
 # Migra una instalación manual previa (si existe /etc/netpulse-agent.env)
-# al formato UCI, y programa el watchdog cron.
+# al formato UCI, y retira el watchdog cron de versiones anteriores (#851).
 
 AGENT_ENV=/etc/netpulse-agent.env
 AGENT_UCI=netpulse-agent
@@ -44,34 +44,13 @@ if [ -f "$AGENT_ENV" ]; then
 	uci commit "$AGENT_UCI"
 fi
 
-# Watchdog cron: cada 2 min, reiniciar si el agente no late
-WATCHDOG=/usr/sbin/netpulse-watchdog
-HEARTBEAT=/tmp/netpulse-agent.heartbeat
-
-cat > "$WATCHDOG" << 'WDOG'
-#!/bin/sh
-# netpulse-watchdog: si el agente no ha escrito el heartbeat en 300s, reiniciar
-HB=/tmp/netpulse-agent.heartbeat
-if ! pidof netpulse-agent > /dev/null; then
-	/etc/init.d/netpulse-agent restart
-	exit 0
-fi
-if [ -f "$HB" ]; then
-	now=$(date +%s)
-	last=$(cat "$HB" 2>/dev/null)
-	if [ -n "$last" ] && [ $((now - last)) -gt 300 ]; then
-		logger -t netpulse-agent "watchdog: heartbeat stalled ($((now - last))s), restarting"
-		/etc/init.d/netpulse-agent restart
-	fi
-fi
-WDOG
-
-chmod 755 "$WATCHDOG"
-
-# Instalar cron solo si no existe ya
-if ! crontab -l 2>/dev/null | grep -q netpulse-watchdog; then
-	(crontab -l 2>/dev/null; echo "*/2 * * * * $WATCHDOG") | crontab -
-fi
+# Watchdog cron (#851): YA NO se programa. Si venimos de una versión que lo
+# instalaba, limpiarlo aquí: el reinicio a ciegas de un agente en bucle de
+# crash no lo arregla (solo ensucia el log); la detección efectiva es el
+# dead-man del servidor (alerta) y el crash puntual lo cubre el respawn de
+# procd. El binario tras sysupgrade lo restaura el self-heal del init.
+rm -f /usr/sbin/netpulse-watchdog
+crontab -l 2>/dev/null | grep -v netpulse-watchdog | crontab - 2>/dev/null || true
 
 # Habilitar y arrancar el servicio
 /etc/init.d/netpulse-agent enable

+ 1 - 1
deploy/openwrt/netpulse-agent/files/netpulse-agent.init

@@ -72,7 +72,7 @@ start_service() {
 	procd_open_instance
 	procd_set_param command "$PROG"
 	procd_set_param stdout stderr  # logs vía procd a syslog
-	procd_set_param respawn 3600 3600 0  # respawn tras 1h como máximo (el watchdog cron lo gestiona)
+	procd_set_param respawn 3600 3600 0  # respawn con backoff de 1h (#851: ya sin watchdog cron)
 	procd_close_instance
 }
 

+ 63 - 58
install-agent.sh

@@ -324,22 +324,31 @@ FP_LINE=""
 if [ -n "$SERVER_FP" ]; then
     FP_LINE="NETPULSE_SERVER_FP=$SERVER_FP"
 fi
+# #851: conservar las NETPULSE_* del usuario que este script no gestiona
+# (p. ej. NETPULSE_SCAN_INTERVAL=0): el rewrite toca solo las gestionadas
+# (SERVER/SLUG/TOKEN/SERVER_FP/PAIRING_TOKEN).
+USER_VARS=$(ssh $SSH_IDENT_ARGS "$SSH" "grep -E '^NETPULSE_[A-Z0-9_]+=' $ENV_FILE 2>/dev/null | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)='") || USER_VARS=""
 ssh $SSH_IDENT_ARGS "$SSH" "cat > $ENV_FILE && chmod 600 $ENV_FILE" <<EOF
 # netpulse-agent — config (generado por install-agent.sh)
 NETPULSE_SERVER=$SERVER
 NETPULSE_SLUG=$SLUG
 $TOKEN_LINE
 $FP_LINE
-# NETPULSE_INTERVAL=15
-# NETPULSE_SCAN_INTERVAL=0          # min entre scans de vecinos; "0" = sin scans
-#                                   # periódicos (APs con clientes Intel: cada
-#                                   # off-channel gap puede costar un deauth)
-# NETPULSE_WAN_TARGET=1.1.1.1      # solo si este equipo es el gateway
-# NETPULSE_GW_TARGET=192.168.8.1   # ping al gateway (APs)
+# defaults (líneas comentadas; descomenta para cambiar):
+# NETPULSE_INTERVAL=30              # segundos entre pushes
+# NETPULSE_SCAN_INTERVAL=30m        # min entre scans de vecinos; "0" = sin
+#                                   # scans periódicos (APs con clientes Intel:
+#                                   # cada off-channel gap puede costar un deauth)
+# NETPULSE_WAN_TARGET=1.1.1.1       # solo si este equipo es el gateway
+# NETPULSE_GW_TARGET=192.168.8.1    # ping al gateway (APs)
+# NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat
 EOF
+if [ -n "$USER_VARS" ]; then
+    printf '%s\n' "$USER_VARS" | ssh $SSH_IDENT_ARGS "$SSH" "cat >> $ENV_FILE"
+fi
 ok "config escrita"
 
-# Servicio procd (respawn)
+# Servicio procd (respawn + self-heal del binario tras sysupgrade)
 info "instalando servicio procd"
 SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
 if [ -f "$SCRIPT_DIR/agent/deploy/$INIT_NAME.init" ]; then
@@ -354,10 +363,47 @@ START=99
 STOP=10
 USE_PROCD=1
 
+ENV_FILE=/etc/netpulse-agent.env
 BIN=/usr/sbin/netpulse-agent
 [ -x "$BIN" ] || BIN=/tmp/netpulse-agent
 
+# Self-heal: un sysupgrade solo conserva /etc, así que si el binario falta
+# al arrancar se descarga del server con el env (mismo criterio que el
+# reinstall del server; #851 retiró el watchdog cron, esto cubre el boot).
+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 ;;
+        mips)
+            case "$(head -c 6 /bin/sh | tail -c 1 | tr '\001\002' '12')" in
+                1) local ARCH=mipsle ;;
+                2) local ARCH=mips ;;
+                *) return 1 ;;
+            esac ;;
+        *) 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}"
@@ -371,59 +417,18 @@ fi
 ssh $SSH_IDENT_ARGS "$SSH" "chmod 0755 $INIT_DST && $INIT_DST enable && $INIT_DST restart"
 ok "servicio $INIT_NAME habilitado y arrancado"
 
-# ------------------------------------------------------------ watchdog cron --
-# Fase 5 (Plan A): cron cada 2 min relanza el agente si procd se rindió o
-# si está "vivo pero roto" (heartbeat viejo). Idempotente: reemplaza la
-# línea previa del crontab.
-info "instalando watchdog (cron, cada 2 min)"
-WATCHDOG_DST="/usr/sbin/netpulse-watchdog"
-if [ -f "$SCRIPT_DIR/agent/deploy/netpulse-watchdog.sh" ]; then
-    scp -Oq $SSH_IDENT_ARGS "$SCRIPT_DIR/agent/deploy/netpulse-watchdog.sh" "$SSH:$WATCHDOG_DST"
-else
-    ssh $SSH_IDENT_ARGS "$SSH" "cat > $WATCHDOG_DST" <<'WATCHDOGEOF'
-#!/bin/sh
-INIT=/etc/init.d/netpulse-agent
-HB=/tmp/netpulse-agent.heartbeat
-MAX_AGE=300
-[ -f /etc/netpulse-agent.env ] && . /etc/netpulse-agent.env 2>/dev/null
-[ -n "${NETPULSE_HEARTBEAT_FILE:-}" ] && HB="$NETPULSE_HEARTBEAT_FILE"
-log() { logger -t netpulse-watchdog "$*"; }
-if [ ! -x /usr/sbin/netpulse-agent ] && [ ! -x /tmp/netpulse-agent ]; then
-    exit 0
-fi
-# Nota: BusyBox pgrep -x compara contra la línea de comando completa,
-# no solo el nombre base; /usr/sbin/netpulse-agent no coincide con
-# netpulse-agent. Usamos pidof, que busca por comm/pidof y funciona
-# tanto en BusyBox como en procps-ng.
-if ! pidof netpulse-agent >/dev/null 2>&1; then
-    log "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 "$MAX_AGE" ]; then
-        log "proceso vivo pero sin latido en ${age}s — reiniciando servicio"
-        $INIT restart >/dev/null 2>&1
-    fi
-fi
-exit 0
-WATCHDOGEOF
-fi
+# Watchdog cron: NO se instala (#851). Si el agente crashea en bucle, un
+# reinicio a ciegas cada 2 min no lo arregla y ensucia el log; la detección
+# efectiva es el dead-man del servidor (alerta) y el crash puntual lo cubre
+# el respawn de procd. Además se limpia la entrada si venimos de una
+# instalación previa que sí lo programaba.
 ssh $SSH_IDENT_ARGS "$SSH" "
-    chmod 0755 $WATCHDOG_DST
-    mkdir -p /etc/crontabs
-    sed -i '/netpulse-watchdog/d' /etc/crontabs/root 2>/dev/null
-    echo '*/2 * * * * $WATCHDOG_DST' >> /etc/crontabs/root
-    /etc/init.d/cron enable
-    /etc/init.d/cron restart
+    rm -f /usr/sbin/netpulse-watchdog
+    if [ -f /etc/crontabs/root ]; then
+        sed -i '/netpulse-watchdog/d' /etc/crontabs/root
+    fi
 "
-ok "watchdog en cron (*/2 * * * *)"
+ok "watchdog cron no instalado (legacy limpiado)"
 
 sleep 2
 if ssh $SSH_IDENT_ARGS "$SSH" "logread -e $INIT_NAME" 2>/dev/null | tail -2 | grep -q .; then

+ 1 - 1
server-go/internal/firmware/owut_flow.go

@@ -261,7 +261,7 @@ const stackPreserveCmd = `P=/etc/sysupgrade.conf; touch $P; ensure() { grep -qxF
 	`ensure /usr/libexec/netgrip-restore-rules; ensure /etc/netgrip/; ` +
 	`for f in /etc/rc.d/*netgrip*; do [ -e "$f" ] && ensure "$f"; done; fi; ` +
 	`if [ -f /usr/sbin/netpulse-agent ]; then ensure /usr/sbin/netpulse-agent; ensure /etc/netpulse-agent.env; ` +
-	`ensure /usr/sbin/netpulse-watchdog; ensure /etc/init.d/netpulse-agent; ` +
+	`ensure /etc/init.d/netpulse-agent; ` +
 	`for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure "$f"; done; fi; true`
 
 // EnsureStackPreserved ejecuta la preservación en el router (tolerante: un

+ 41 - 37
server-go/internal/reinstall/reinstall.go

@@ -9,7 +9,11 @@ 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.
+// con self-heal) de forma idempotente. Ya NO instala el watchdog con cron
+// (#851): si el agente crashea en bucle, un reinicio a ciegas no lo arregla
+// y ensucia el log; la detección efectiva es el dead-man del servidor. La
+// caída puntual la cubre el respawn de procd; el binario tras sysupgrade lo
+// restaura el self-heal del init.
 // digests mapa arch→sha256 del binario embebido; un arch sin digest queda
 // sin verificación (build dev) en lugar de bloquear.
 // serverFP es el SPKI pin del server (#851): si serverURL es https y el
@@ -22,7 +26,6 @@ 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 + `"
@@ -63,18 +66,33 @@ fi
 chmod 0755 /tmp/netpulse-agent.new
 mv -f /tmp/netpulse-agent.new "$BIN"
 
-# Config (chmod 600)
+# Config (chmod 600). El rewrite toca SOLO las vars gestionadas (SERVER,
+# SLUG, TOKEN, SERVER_FP): las NETPULSE_* del usuario (p. ej.
+# NETPULSE_SCAN_INTERVAL=0) se conservan tal cual (#851).
+USER_VARS=""
+if [ -f "$ENV_FILE" ]; then
+	USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)=') || true
+fi
 cat > "$ENV_FILE" <<EOF
 # netpulse-agent — config (generado por reinstall)
 NETPULSE_SERVER=$SERVER
 NETPULSE_SLUG=$SLUG
 NETPULSE_TOKEN=$TOKEN
+# NETPULSE_SERVER_FP=<sha256>    # pin SPKI del server (https); lo rellena el instalador
+# NETPULSE_INTERVAL=30           # segundos entre pushes
+# NETPULSE_SCAN_INTERVAL=30m     # min entre scans de vecinos; "0" = sin scans periódicos
+# NETPULSE_WAN_TARGET=1.1.1.1    # solo si este equipo es el gateway
+# NETPULSE_GW_TARGET=192.168.8.1 # ping al gateway (APs)
+# NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat
 EOF
 # #851: con server https el agente exige el SPKI pin; vacío = http plano o
 # el server no pudo derivarlo (se comporta como antes).
 if [ -n "$SERVER_FP" ]; then
 	echo "NETPULSE_SERVER_FP=$SERVER_FP" >> "$ENV_FILE"
 fi
+if [ -n "$USER_VARS" ]; then
+	printf '%s\n' "$USER_VARS" >> "$ENV_FILE"
+fi
 chmod 600 "$ENV_FILE"
 
 # Init procd con self-heal (#457): un sysupgrade solo conserva /etc, así que
@@ -136,35 +154,13 @@ start_service() {
 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
+# #851: el watchdog cron YA NO se instala (un reinicio a ciegas de un crash
+# loop no arregla nada y ensucia el log; la detección es el dead-man del
+# servidor). Si el router viene de una instalación que sí lo tenía, limpiarlo.
+rm -f /usr/sbin/netpulse-watchdog
+if [ -f /etc/crontabs/root ]; then
+	sed -i '/netpulse-watchdog/d' /etc/crontabs/root
 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
@@ -172,10 +168,11 @@ chmod 0755 "$WATCHDOG"
 }
 
 // TokenPushScript construye el POSIX sh que rota el token en CALIENTE: solo
-// reescribe el token en /etc/netpulse-agent.env (conservando server y slug,
-// escritura atómica) y reinicia el servicio. No descarga binario, no toca
-// init/watchdog/cron: es la versión ligera de reinstall para cuando el token
-// cambia pero el binario y la config ya están bien (rotate "en caliente").
+// reescribe el token en /etc/netpulse-agent.env (conservando server, slug,
+// FP del pin SPKI y las NETPULSE_* del usuario) y reinicia el servicio. No
+// descarga binario ni toca el init: es la versión ligera de reinstall para
+// cuando el token cambia pero el binario y la config ya están bien (rotate
+// "en caliente").
 func TokenPushScript(slug, token string) string {
 	return `#!/bin/sh
 set -e
@@ -186,9 +183,13 @@ INIT=/etc/init.d/netpulse-agent
 # Conservar el server y el slug del env existente para no romper la config.
 SERVER=$(sed -n 's/^NETPULSE_SERVER=//p' "$ENV_FILE" | head -n1)
 SLUG=$(sed -n 's/^NETPULSE_SLUG=//p' "$ENV_FILE" | head -n1)
-# #851: el FP del pin SPKI también hay que conservarlo; si se pierde aquí el
-# agente cae en el bucle fatal "HTTPS requiere NETPULSE_SERVER_FP" al arrancar.
+# #851: conservar también el FP del pin SPKI y las NETPULSE_* no gestionadas
+# (p. ej. NETPULSE_SCAN_INTERVAL=0); si se pierden, el agente cae en bucle
+# fatal (https sin FP) o pierde la config del usuario. TOKEN y PAIRING_TOKEN
+# se descartan a propósito: el token rota y un pairing token residual ya no
+# aplica una vez emparejado.
 FP=$(sed -n 's/^NETPULSE_SERVER_FP=//p' "$ENV_FILE" | head -n1)
+USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE" | grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)=') || true
 [ -n "$SLUG" ] || { echo "netpulse-agent.env sin NETPULSE_SLUG"; exit 31; }
 umask 077
 cat > "$ENV_FILE.tmp" <<EOF
@@ -199,6 +200,9 @@ EOF
 if [ -n "$FP" ]; then
 	echo "NETPULSE_SERVER_FP=$FP" >> "$ENV_FILE.tmp"
 fi
+if [ -n "$USER_VARS" ]; then
+	printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"
+fi
 chmod 600 "$ENV_FILE.tmp"
 # Swap atómico: el proceso vivo sigue leyendo el archivo íntegro.
 mv -f "$ENV_FILE.tmp" "$ENV_FILE"

+ 53 - 13
server-go/internal/reinstall/script_test.go

@@ -41,6 +41,38 @@ func TestScriptConfig(t *testing.T) {
 	}
 }
 
+// #851: el env generado documenta las opciones disponibles como líneas
+// comentadas con sus defaults.
+func TestScriptEnvDocumentsDefaults(t *testing.T) {
+	s := scriptForTest()
+	for _, want := range []string{
+		"# NETPULSE_INTERVAL=30",
+		"# NETPULSE_SCAN_INTERVAL=30m",
+		"# NETPULSE_WAN_TARGET=1.1.1.1",
+		"# NETPULSE_GW_TARGET=192.168.8.1",
+		"# NETPULSE_HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat",
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("env generado sin %q", want)
+		}
+	}
+}
+
+// #851: el rewrite del env conserva las NETPULSE_* del usuario (p. ej.
+// NETPULSE_SCAN_INTERVAL=0) en vez de pisarlas.
+func TestScriptPreservesUserVars(t *testing.T) {
+	s := scriptForTest()
+	for _, want := range []string{
+		`USER_VARS=$(grep -E '^NETPULSE_[A-Z0-9_]+=' "$ENV_FILE"`,
+		`grep -vE '^NETPULSE_(SERVER|SLUG|TOKEN|SERVER_FP|PAIRING_TOKEN)='`,
+		`printf '%s\n' "$USER_VARS" >> "$ENV_FILE"`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("script sin preservación de vars de usuario: falta %q", want)
+		}
+	}
+}
+
 func TestScriptArchAndDigests(t *testing.T) {
 	s := scriptForTest()
 	for _, want := range []string{
@@ -97,22 +129,27 @@ func TestScriptSelfHealInit(t *testing.T) {
 	}
 }
 
-func TestScriptWatchdogAndCron(t *testing.T) {
+// #851: el watchdog cron YA NO se instala; el script limpia los restos de
+// instalaciones previas que sí lo tenían.
+func TestScriptNoWatchdogCron(t *testing.T) {
 	s := scriptForTest()
-	for _, want := range []string{
-		"pidof netpulse-agent",
-		`echo '*/2 * * * * /usr/sbin/netpulse-watchdog'`,
+	for _, notWant := range []string{
+		"*/2 * * * *",
+		"proceso vivo pero sin latido",
+		`echo '*/2`,
 		"/etc/init.d/cron restart",
 	} {
-		if !strings.Contains(s, want) {
-			t.Errorf("watchdog/cron incompleto: falta %q", want)
+		if strings.Contains(s, notWant) {
+			t.Errorf("script con watchdog/cron (%q) pese a #851", notWant)
 		}
 	}
-	if strings.Contains(s, "pgrep -x") {
-		t.Error("el watchdog no debe usar pgrep -x (bug BusyBox)")
-	}
-	if !strings.Contains(s, "grep -v netpulse-watchdog") {
-		t.Error("el cron no es idempotente")
+	for _, want := range []string{
+		`rm -f /usr/sbin/netpulse-watchdog`,
+		`sed -i '/netpulse-watchdog/d' /etc/crontabs/root`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("script sin limpieza legacy del watchdog: falta %q", want)
+		}
 	}
 }
 
@@ -130,6 +167,9 @@ func TestTokenPushScriptConfig(t *testing.T) {
 		"NETPULSE_TOKEN=" + strings.Repeat("c3", 32),
 		"sed -n 's/^NETPULSE_SERVER=//p' \"$ENV_FILE\"",
 		"sed -n 's/^NETPULSE_SLUG=//p' \"$ENV_FILE\"",
+		// #851: preservar FP y NETPULSE_* del usuario (p. ej. SCAN_INTERVAL).
+		"sed -n 's/^NETPULSE_SERVER_FP=//p' \"$ENV_FILE\"",
+		`printf '%s\n' "$USER_VARS" >> "$ENV_FILE.tmp"`,
 		"chmod 600 \"$ENV_FILE.tmp\"",
 		"mv -f \"$ENV_FILE.tmp\" \"$ENV_FILE\"",
 		"\"$INIT\" restart",
@@ -140,11 +180,11 @@ func TestTokenPushScriptConfig(t *testing.T) {
 			t.Errorf("TokenPushScript sin %q", want)
 		}
 	}
-	// No debe descargar binario ni tocar init/watchdog/cron (rotate ligero).
+	// No debe descargar binario ni tocar el init (rotate ligero).
 	if strings.Contains(s, "/binary?arch=") {
 		t.Error("TokenPushScript no debe descargar el binario")
 	}
-	for _, notWant := range []string{"watchdog", "crontab", "/etc/init.d/netpulse-agent >", "GOT=$(sha256sum"} {
+	for _, notWant := range []string{"*/2 * * * *", "GOT=$(sha256sum"} {
 		if strings.Contains(s, notWant) {
 			t.Errorf("TokenPushScript no debe contener %q (rotate ligero)", notWant)
 		}

+ 3 - 2
server-go/internal/uninstall/uninstall.go

@@ -1,8 +1,9 @@
 // Package uninstall: construcción del script que desinstala el agente
 // netpulse-agent de un router OpenWrt (#624). Es la operación inversa al
 // paquete reinstall: en lugar de instalar binario + env + init procd
-// (con self-heal y watchdog), se detiene y deshabilita el servicio, y se
-// eliminan todos los artefactos que reinstall deja en el router.
+// (con self-heal), desinstala el agente standalone: detiene y deshabilita el
+// servicio, y borra binario/env/init. El watchdog cron se sigue limpiando
+// porque las instalaciones previas a #851 lo dejaron en el router.
 //
 // Vive en su propio paquete (como reinstall) porque httpapi importa
 // rearmer/reinstall y ninguno de esos paquetes puede importar a httpapi.