4
0
Эх сурвалжийг харах

feat(updater): stable self-update with root helper swap+restart (#482)

* feat(updater): stable self-update with root helper swap+restart (#480)

Stable layouts (install.sh single-binary) can now auto-apply releases:
the updater downloads the release tarball, verifies sha256, stages the
new binary in DATA_DIR/updates and drops a marker for the root helper
(systemd path unit) that swaps the binary and restarts the service.
Success is confirmed on the next boot via the helper's .update-applied
marker (same pattern as #444), re-marking the interrupted history entry
as success. Without the unit installed, canApply stays false (previous
behavior).

* feat(install): root helper + systemd units for stable self-update (#480)

install.sh now ships netpulse-stable-apply (verify sha256, atomic swap,
restart, healthcheck with rollback to .bak-selfupdate) plus
<svc>-stable-update.{path,service} watching DATA_DIR/.stable-update.
Cleanup added to --uninstall; summary notes updated.

* fix(install): raise stable-apply healthcheck budget to 210s (#480)

The service stop phase can take up to TimeoutStopSec (90s) when a poller
tick is stuck on slow SNMP (#481), so 90s of healthcheck could trigger a
bogus rollback after a good update. 70 tries x 3s gives enough headroom.

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 сар өмнө
parent
commit
a01cee3c67

+ 122 - 3
install.sh

@@ -114,10 +114,19 @@ if [ "$UNINSTALL" -eq 1 ]; then
         run $SUDO rm -f "/etc/systemd/system/$SERVICE_NAME.service"
         # Units de reinicio bajo demanda (issue #4): si existen, quitarlas
         if [ -f "/etc/systemd/system/$SERVICE_NAME-restart.path" ]; then
-            run $SUDO systemctl disable --now "$SERVICE_NAME-restart.path" 2>/dev/null || true
+            run $SUDO systemctl disable --now "$SERVICE_NAME-restart.path" 2>/dev/null
             run $SUDO rm -f "/etc/systemd/system/$SERVICE_NAME-restart.path" \
                 "/etc/systemd/system/$SERVICE_NAME-restart.service"
         fi
+        # Auto-update estable (#480): unidades + helper + marcadores residuales
+        if [ -f "/etc/systemd/system/$SERVICE_NAME-stable-update.path" ]; then
+            run $SUDO systemctl disable --now "$SERVICE_NAME-stable-update.path" 2>/dev/null
+            run $SUDO rm -f "/etc/systemd/system/$SERVICE_NAME-stable-update.path" \
+                "/etc/systemd/system/$SERVICE_NAME-stable-update.service" \
+                "$INSTALL_DIR/$APP_NAME-stable-apply"
+            run $SUDO rm -f "$STATE_DIR/data/.stable-update" \
+                "$STATE_DIR/data/.update-applied" "$STATE_DIR/data/.stable-update.error"
+        fi
         run $SUDO systemctl daemon-reload
         ok "systemd unit removed"
     fi
@@ -393,12 +402,121 @@ Description=Reinicio de $SERVICE_NAME solicitado por el servidor
 Type=oneshot
 ExecStart=/bin/sh -c "rm -f $STATE_DIR/data/.restart-me; /bin/systemctl restart $SERVICE_NAME.service"
 EOF
+
+    # Auto-update estable (#480): el servidor deja el binario nuevo en
+    # escena + marcador .stable-update; esta unit .path dispara el helper
+    # root que verifica, hace swap y reinicia con rollback.
+    $SUDO tee "/etc/systemd/system/$SERVICE_NAME-stable-update.path" >/dev/null <<EOF
+[Unit]
+Description=Vigila el marcador de auto-update estable de $SERVICE_NAME
+
+[Path]
+PathChanged=$STATE_DIR/data/.stable-update
+
+[Install]
+WantedBy=multi-user.target
+EOF
+    $SUDO tee "/etc/systemd/system/$SERVICE_NAME-stable-update.service" >/dev/null <<EOF
+[Unit]
+Description=Aplica el update estable de $SERVICE_NAME (swap+restart)
+
+[Service]
+Type=oneshot
+Environment=STATE_DIR=$STATE_DIR
+Environment=SERVER_BIN=$INSTALL_DIR/$BIN_NAME
+Environment=SERVICE=$SERVICE_NAME
+ExecStart=$INSTALL_DIR/$APP_NAME-stable-apply
+EOF
+    $SUDO tee "$INSTALL_DIR/$APP_NAME-stable-apply" >/dev/null <<'EOF_HELPER'
+#!/bin/sh
+# netpulse-stable-apply — helper root del auto-update estable (#480).
+# Lo dispara netpulse-stable-update.path cuando el servidor deja el binario
+# nuevo en escena con el marcador .stable-update (target/sha256/staged).
+# Reverifica el sha256, swap atómico, reinicio y healthcheck; rollback si
+# el servicio no vuelve a levantar. Sin curl, acepta sin verificar salud.
+set -u
+
+STATE_DIR="${STATE_DIR:-/var/lib/netpulse}"
+SERVER_BIN="${SERVER_BIN:-/usr/local/bin/netpulse}"
+SERVICE="${SERVICE:-netpulse}"
+DATA_DIR="$STATE_DIR/data"
+MARKER="$DATA_DIR/.stable-update"
+APPLIED="$DATA_DIR/.update-applied"
+ERRFILE="$DATA_DIR/.stable-update.error"
+BACKUP="$SERVER_BIN.bak-selfupdate"
+LOG_TAG="netpulse-stable-apply"
+
+log() { logger -t "$LOG_TAG" "$*" 2>/dev/null || echo "$LOG_TAG: $*"; }
+fail() {
+    log "ERROR: $*"
+    rm -f "$MARKER"
+    echo "$*" > "$ERRFILE" 2>/dev/null || true
+    exit 1
+}
+
+[ -f "$MARKER" ] || exit 0
+
+target=""; sha=""; staged=""
+while IFS='=' read -r k v; do
+    case "$k" in
+        target) target="$v" ;;
+        sha256) sha="$v" ;;
+        staged) staged="$v" ;;
+    esac
+done < "$MARKER"
+[ -n "$target" ] && [ -n "$sha" ] && [ -n "$staged" ] || fail "stable_marker_invalid"
+case "$target" in v[0-9]*) ;; *) fail "stable_marker_invalid" ;; esac
+[ -f "$staged" ] || fail "stable_marker_invalid"
+
+echo "$sha  $staged" | sha256sum -c - >/dev/null 2>&1 || fail "stable_checksum_mismatch"
+
+cp -a "$SERVER_BIN" "$BACKUP" 2>/dev/null || true
+install -T -m 0755 "$staged" "$SERVER_BIN" || fail "stable_install_failed"
+
+# Marcador de éxito ANTES del reinicio (patrón #444): el arranque nuevo lo
+# usa para confirmar el apply en el historial.
+printf '%s\n' "$target" > "$APPLIED"
+rm -f "$MARKER" "$staged"
+log "swap a $target hecho; reiniciando $SERVICE"
+systemctl restart "$SERVICE.service" || fail "stable_install_failed"
+
+if ! command -v curl >/dev/null 2>&1; then
+    log "curl no disponible; healthcheck omitido"
+    rm -f "$ERRFILE"
+    exit 0
+fi
+PORT=""
+[ -f "$STATE_DIR/.env" ] && PORT=$(sed -n 's/^PORT=//p' "$STATE_DIR/.env" | head -1)
+PORT="${PORT:-3000}"
+# Budget generoso: el stop del servicio puede tardar hasta TimeoutStopSec
+# (90 s) si un tick del poller queda atascado en SNMP lentos (#481), más el
+# arranque con primer poll en curso.
+i=0
+while [ "$i" -lt 70 ]; do
+    if curl -fsS --max-time 3 "http://127.0.0.1:$PORT/api/health" >/dev/null 2>&1; then
+        log "healthcheck OK tras actualizar a $target"
+        rm -f "$ERRFILE"
+        exit 0
+    fi
+    i=$((i + 1))
+    sleep 3
+done
+
+log "healthcheck falló tras 210s; rollback a $BACKUP"
+cp -a "$BACKUP" "$SERVER_BIN" 2>/dev/null || true
+systemctl restart "$SERVICE.service" 2>/dev/null || true
+rm -f "$APPLIED"
+fail "stable_healthcheck_failed"
+EOF_HELPER
+    $SUDO chmod 0755 "$INSTALL_DIR/$APP_NAME-stable-apply"
 fi
 run $SUDO systemctl daemon-reload
 if [ "$UPGRADING" -eq 1 ]; then run $SUDO systemctl restart "$SERVICE_NAME"
 else run $SUDO systemctl enable --now "$SERVICE_NAME"; fi
 run $SUDO systemctl enable --now "$SERVICE_NAME-restart.path" 2>/dev/null \
     || warn "could not enable $SERVICE_NAME-restart.path (demo/update auto-restart)"
+run $SUDO systemctl enable --now "$SERVICE_NAME-stable-update.path" 2>/dev/null \
+    || warn "could not enable $SERVICE_NAME-stable-update.path (stable self-update)"
 
 if [ "$DRY_RUN" -eq 0 ]; then
     sleep 3
@@ -443,6 +561,7 @@ printf '      firewall-cmd --permanent --add-port=%s/tcp && firewall-cmd --reloa
 printf '      ufw allow %s/tcp\n' "$PORT"
 printf '  - Live mode: authorize the server SSH public key on each router\n'
 printf '    (Settings shows it; append to /etc/dropbear/authorized_keys).\n'
-printf '  - The in-app updater follows rolling builds from main; for stable\n'
-printf '    updates re-run this script.\n'
+printf '  - Auto-update: the app downloads, verifies (sha256) and applies new\n'
+printf '    stable versions by itself (root helper %s-stable-apply; rollback\n' "$APP_NAME"
+printf '    if the health check fails). Re-run this script for manual updates.\n'
 printf '%s================================================%s\n\n' "$C_G" "$C_0"

+ 4 - 2
server-go/cmd/netpulse/main.go

@@ -367,8 +367,10 @@ func run() error {
 
 	// Actualizador: repoRoot = padre de serverRoot (paridad index.js:49-53).
 	// La versión embebida (httpapi.Version) se usa para comparar contra el
-	// último release tag en modo estable (layout install.sh).
-	upd := updater.New(filepath.Clean(filepath.Join(cfg.ServerRoot, "..")), cfg.GithubRepo, cfg.GithubToken, httpapi.Version, dbHandle.DB)
+	// último release tag en modo estable (layout install.sh). ConDataDir
+	// habilita el auto-apply estable (#480): staging y marcadores en DATA_DIR.
+	upd := updater.New(filepath.Clean(filepath.Join(cfg.ServerRoot, "..")), cfg.GithubRepo, cfg.GithubToken, httpapi.Version, dbHandle.DB).
+		WithDataDir(cfg.DataDir)
 
 	// Fase 10: motor de orquestación (plan→apply→state).
 	orchMgr := orchestr.New(dbHandle)

+ 24 - 0
server-go/internal/updater/history.go

@@ -87,6 +87,30 @@ func (u *Updater) finalizeInterrupted() {
 	}
 }
 
+// markInterruptedAsSuccess (#480): en estable el apply tiene éxito MATANDO
+// el proceso (swap+restart por la unidad root), así que su entrada queda
+// como failed/interrupted_by_restart hasta el arranque siguiente. Si el
+// marcador del helper confirmó el objetivo (ver loadPendingApply), esa
+// última entrada es el camino de éxito y se re-marca como tal.
+func (u *Updater) markInterruptedAsSuccess(to string) {
+	if u.db == nil || to == "" {
+		return
+	}
+	res, err := u.db.Exec(
+		`UPDATE update_history SET status = 'success', error = 'restarted_by_update'
+		 WHERE id = (SELECT id FROM update_history
+		              WHERE status = 'failed' AND error = 'interrupted_by_restart'
+		                AND version_to = ?
+		              ORDER BY ts DESC LIMIT 1)`, to)
+	if err != nil {
+		fmt.Printf("[netpulse] no se pudo re-marcar el historial de update: %v\n", err)
+		return
+	}
+	if n, _ := res.RowsAffected(); n > 0 {
+		fmt.Printf("[netpulse] historial: apply estable a %s registrado como éxito\n", to)
+	}
+}
+
 // ListHistory devuelve los últimos `limit` registros de update_history
 // (issue #159), más reciente primero. Cota de 200 por petición.
 func ListHistory(db *sql.DB, limit int) ([]HistoryEntry, error) {

+ 39 - 3
server-go/internal/updater/pending.go

@@ -9,6 +9,8 @@ import (
 	"database/sql"
 	"encoding/json"
 	"fmt"
+	"os"
+	"strings"
 )
 
 // pendingApplyKey es la clave kv del marcador pre-update.
@@ -70,14 +72,16 @@ func (u *Updater) loadPendingApply() {
 		return
 	}
 	u.finalizeInterrupted()
+	if u.mode != "rolling" {
+		// #480: en estable el marcador de éxito vive en el dataDir, que
+		// llega DESPUÉS de New (WithDataDir) → la confirmación va allí.
+		return
+	}
 	p, ok := readPendingApply(u.db)
 	if !ok {
 		return
 	}
 	defer u.clearPendingApply()
-	if u.mode != "rolling" {
-		return // layout estable: sin auto-apply, no hay nada que confirmar
-	}
 	now := gitShort(u.repoRoot)
 	if now == "" || now == p.From {
 		return // sin cambio o commit desconocido → silencioso
@@ -88,6 +92,38 @@ func (u *Updater) loadPendingApply() {
 	fmt.Printf("[netpulse] update confirmado: %s → %s\n", p.From, now)
 }
 
+// loadStablePending confirma (o descarta en silencio) el apply estable
+// pendiente una vez el dataDir está disponible (#480). Idempotente: sin
+// marcador en kv no hace nada. El apply estable mata el proceso con el
+// restart, así que este es el único sitio donde el éxito se puede registrar:
+// exige el marcador de éxito del helper con el objetivo esperado (patrón
+// #444) y re-marca el historial que finalizeInterrupted dejó como fallido.
+func (u *Updater) loadStablePending() {
+	if u.db == nil || u.dataDir == "" {
+		return
+	}
+	p, ok := readPendingApply(u.db)
+	if !ok {
+		return
+	}
+	defer u.clearPendingApply()
+	now := u.version
+	if now == "" || now == "desconocido" || now == p.From {
+		return // sin cambio o versión desconocida → silencioso
+	}
+	marker := readAppliedMarker(u.appliedMarkerPath())
+	if marker == "" || (p.To != "" && marker != strings.TrimSpace(p.To)) {
+		fmt.Printf("[netpulse] apply estable sin marcador de éxito (marker=%q, target=%q); no se confirma\n", marker, p.To)
+		return
+	}
+	_ = os.Remove(u.appliedMarkerPath())
+	u.markInterruptedAsSuccess(strings.TrimSpace(p.To))
+	u.mu.Lock()
+	u.pendingApply = &PendingApply{From: p.From, To: now}
+	u.mu.Unlock()
+	fmt.Printf("[netpulse] update confirmado: %s → %s\n", p.From, now)
+}
+
 // AckPending confirma y descarta el pendingApply en memoria (una sola vez:
 // el frontend lo muestra y llama a POST /api/update/pending-confirm).
 func (u *Updater) AckPending() {

+ 307 - 0
server-go/internal/updater/stable.go

@@ -0,0 +1,307 @@
+// stable.go — auto-apply en layout estable (single-binary de install.sh,
+// issue #480). El server corre como usuario netpulse con sandbox
+// ProtectSystem=strict: NO puede reemplazar /usr/local/bin/netpulse. Flujo:
+//
+//  1. El updater descarga el asset de la release estable (tarball +
+//     checksums.txt) a <dataDir>/updates/ y verifica el sha256 del tarball
+//     contra checksums.txt (mismo formato que usa install.sh).
+//  2. Extrae el binario a <dataDir>/updates/netpulse.new, le calcula su
+//     sha256 y escribe el marcador <dataDir>/.stable-update (atómico, vía
+//     rename) con target/sha256/ruta del binario en escena.
+//  3. La unidad root netpulse-stable-update.path (instalada por install.sh,
+//     detectada por stableUnitInstalled) reacciona al marcador y lanza el
+//     helper netpulse-stable-apply, que RE-VERIFICA el sha256, respalda el
+//     binario actual, hace swap, escribe el marcador de éxito
+//     .update-applied con el objetivo (patrón #444), reinicia el servicio y
+//     comprueba health; ante cualquier fallo restaura el binario anterior.
+//  4. El restart mata este proceso, así que el éxito se confirma en el
+//     arranque siguiente: loadPendingApply compara la versión embebida con
+//     el marcador persistido (#161) y marca el historial (patrón #444
+//     extendido a boot-time).
+package updater
+
+import (
+	"archive/tar"
+	"compress/gzip"
+	"crypto/sha256"
+	"encoding/hex"
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+	"path/filepath"
+	"runtime"
+	"strings"
+	"time"
+)
+
+const (
+	// stableMarkerName dispara la unidad root (PathChanged). Se escribe de
+	// forma atómica (tmp + rename) para que el helper nunca lea a medias.
+	stableMarkerName = ".stable-update"
+	// stableAppliedName: objetivo escrito por el helper justo antes de
+	// reiniciar (mismo papel que el .update-applied de update.sh en rolling,
+	// issue #444).
+	stableAppliedName = ".update-applied"
+	// stableErrorName: código de fallo del helper (verificación, swap o
+	// healthcheck con rollback). Informativo; el historial manda.
+	stableErrorName = ".stable-update.error"
+	// stableBinName: nombre del binario dentro del tarball de release y
+	// base del nombre de asset (netpulse_<ver>_linux_<GOARCH>.tar.gz).
+	stableBinName = "netpulse"
+	// stableMaxBinSize cota el tamaño del binario extraído (defensa).
+	stableMaxBinSize = 256 << 20
+	// stableRestartWait: espera máxima al swap+restart. En producción el
+	// proceso muere en segundos; si vence, el apply se marca fallido y se
+	// retira el marcador para que no dispare un swap tardío.
+	stableRestartWait = 3 * time.Minute
+)
+
+// downloadBase es la base de los assets de release (inyectable en tests).
+var downloadBase = "https://github.com"
+
+// downloadClient: el tarball ronda los 20 MB; el timeout de la API (8 s)
+// no aplica aquí.
+var downloadClient = &http.Client{Timeout: 10 * time.Minute}
+
+// stableUnitInstalled detecta la unidad root que hace el swap: busca
+// /etc/systemd/system/<binario>-stable-update.path (install.sh la nombra a
+// partir del binario, igual que las unidades -restart). Var de paquete para
+// poder sobreescribirla en tests.
+var stableUnitInstalled = func() bool {
+	exe, err := os.Executable()
+	if err != nil {
+		return false
+	}
+	unit := filepath.Join("/etc/systemd/system", filepath.Base(exe)+"-stable-update.path")
+	_, err = os.Stat(unit)
+	return err == nil
+}
+
+// WithDataDir fija el dataDir real (ruta resuelta de DATA_DIR). Necesario
+// para el auto-apply estable (#480): staging y marcadores viven ahí. Sin
+// dataDir el apply estable falla con stable_no_datadir. Encadenable tras
+// New(); debe llamarse antes de servir tráfico. Como New() ya lanzó
+// loadPendingApply sin dataDir, aquí corre la confirmación estable
+// pendiente (loadStablePending): es el "arranque siguiente" de un apply
+// que murió con el restart.
+func (u *Updater) WithDataDir(path string) *Updater {
+	// Sin u.mu a propósito: dataDir es boot-time e inmutable tras la
+	// construcción (paridad repoRoot/version en New), y loadStablePending
+	// toma u.mu al confirmar (mutex no reentrante).
+	u.dataDir = path
+	if path != "" {
+		u.loadStablePending()
+	}
+	return u
+}
+
+// applyStable ejecuta el flujo completo de staging (download → verify →
+// install → restart) emitiendo los mismos pasos del contrato #280. Al final
+// espera la muerte del proceso (el restart de la unidad root); si no llega,
+// aborta limpio.
+func (u *Updater) applyStable(historyID int64, tag string, startedAt time.Time) {
+	fail := func(code string) {
+		u.mu.Lock()
+		u.updatingStep = nil
+		u.err = &code
+		u.broadcastLocked()
+		u.mu.Unlock()
+		u.finishHistory(historyID, "failed", code, time.Since(startedAt))
+		u.clearPendingApply()
+		fmt.Printf("[netpulse:update] apply estable fallido: %s\n", code)
+	}
+
+	if u.dataDir == "" {
+		fail("stable_no_datadir")
+		return
+	}
+	ver := strings.TrimPrefix(tag, "v")
+	asset := fmt.Sprintf("%s_%s_linux_%s.tar.gz", stableBinName, ver, runtime.GOARCH)
+
+	u.mu.Lock()
+	u.setStepLocked("download")
+	u.broadcastLocked()
+	u.mu.Unlock()
+	fmt.Printf("[netpulse:update] estable: descargando %s (%s)\n", asset, tag)
+
+	staging := filepath.Join(u.dataDir, "updates")
+	_ = os.RemoveAll(staging) // restos de intentos previos
+	_ = os.Remove(filepath.Join(u.dataDir, stableErrorName))
+	if err := os.MkdirAll(staging, 0o755); err != nil {
+		fail("stable_staging_failed")
+		return
+	}
+	tgz := filepath.Join(staging, asset)
+	base := fmt.Sprintf("%s/%s/releases/download/%s", downloadBase, u.repo, tag)
+	if err := downloadToFile(base+"/"+asset, tgz); err != nil {
+		fmt.Printf("[netpulse:update] descarga de %s falló: %v\n", asset, err)
+		fail("stable_download_failed")
+		return
+	}
+	if err := downloadToFile(base+"/checksums.txt", filepath.Join(staging, "checksums.txt")); err != nil {
+		fmt.Printf("[netpulse:update] descarga de checksums.txt falló: %v\n", err)
+		fail("stable_download_failed")
+		return
+	}
+
+	u.mu.Lock()
+	u.setStepLocked("verify")
+	u.broadcastLocked()
+	u.mu.Unlock()
+
+	want, err := checksumFor(filepath.Join(staging, "checksums.txt"), asset)
+	if err != nil {
+		fail("stable_checksum_missing")
+		return
+	}
+	got, err := fileSHA256(tgz)
+	if err != nil {
+		fail("stable_checksum_missing")
+		return
+	}
+	if !strings.EqualFold(want, got) {
+		fmt.Printf("[netpulse:update] sha256 mismatch del tarball: want %s got %s\n", want, got)
+		fail("stable_checksum_mismatch")
+		return
+	}
+
+	binNew, err := extractBinary(tgz, staging)
+	if err != nil {
+		fail("stable_extract_failed")
+		return
+	}
+	// sha256 del binario YA extraído: el helper lo re-verifica antes del
+	// swap (defensa en profundidad: el marcador vive en disco).
+	binSHA, err := fileSHA256(binNew)
+	if err != nil {
+		fail("stable_extract_failed")
+		return
+	}
+
+	u.mu.Lock()
+	u.setStepLocked("install")
+	u.broadcastLocked()
+	u.mu.Unlock()
+
+	marker := filepath.Join(u.dataDir, stableMarkerName)
+	tmp := marker + ".tmp"
+	content := fmt.Sprintf("target=%s\nsha256=%s\nstaged=%s\n", tag, binSHA, binNew)
+	if err := os.WriteFile(tmp, []byte(content), 0o644); err != nil {
+		fail("stable_marker_failed")
+		return
+	}
+	if err := os.Rename(tmp, marker); err != nil {
+		fail("stable_marker_failed")
+		return
+	}
+
+	u.mu.Lock()
+	u.setStepLocked("restart")
+	u.broadcastLocked()
+	u.mu.Unlock()
+	fmt.Printf("[netpulse:update] estable %s en escena; esperando swap+restart (unidad root)\n", tag)
+
+	// En producción el helper reinicia el servicio y el proceso muere aquí
+	// con el binario nuevo. En tests, Stop() desbloquea sin marcar nada
+	// (el éxito se confirma en el "arranque siguiente", ver loadPendingApply).
+	select {
+	case <-u.stopCh:
+		return
+	case <-time.After(stableRestartWait):
+		_ = os.Remove(marker)
+		fail("stable_restart_timeout")
+	}
+}
+
+func downloadToFile(url, dst string) error {
+	resp, err := downloadClient.Get(url)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return fmt.Errorf("http %d para %s", resp.StatusCode, url)
+	}
+	f, err := os.Create(dst)
+	if err != nil {
+		return err
+	}
+	defer f.Close()
+	_, err = io.Copy(f, io.LimitReader(resp.Body, stableMaxBinSize))
+	return err
+}
+
+func fileSHA256(path string) (string, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+	h := sha256.New()
+	if _, err := io.Copy(h, f); err != nil {
+		return "", err
+	}
+	return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+// checksumFor extrae de checksums.txt el sha256 del asset dado (líneas
+// "<hex>  <nombre>", mismo formato que grepea install.sh).
+func checksumFor(sumsFile, asset string) (string, error) {
+	data, err := os.ReadFile(sumsFile)
+	if err != nil {
+		return "", err
+	}
+	for _, line := range strings.Split(string(data), "\n") {
+		fields := strings.Fields(line)
+		if len(fields) == 2 && fields[1] == asset {
+			return fields[0], nil
+		}
+	}
+	return "", fmt.Errorf("%s no está en %s", asset, sumsFile)
+}
+
+// extractBinary extrae la entrada "netpulse" (posible prefijo ./) del
+// tarball a staging como netpulse.new con 0755. Rechaza entradas raras.
+func extractBinary(tgz, staging string) (string, error) {
+	f, err := os.Open(tgz)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+	gz, err := gzip.NewReader(f)
+	if err != nil {
+		return "", err
+	}
+	defer gz.Close()
+	tr := tar.NewReader(gz)
+	for {
+		hdr, err := tr.Next()
+		if err == io.EOF {
+			return "", fmt.Errorf("tarball sin entrada %s", stableBinName)
+		}
+		if err != nil {
+			return "", err
+		}
+		name := strings.TrimPrefix(hdr.Name, "./")
+		if name != stableBinName || hdr.Typeflag != tar.TypeReg {
+			continue
+		}
+		if hdr.Size > stableMaxBinSize {
+			return "", fmt.Errorf("entrada %s demasiado grande (%d)", name, hdr.Size)
+		}
+		dst := filepath.Join(staging, "netpulse.new")
+		out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
+		if err != nil {
+			return "", err
+		}
+		if _, err := io.Copy(out, io.LimitReader(tr, stableMaxBinSize)); err != nil {
+			out.Close()
+			return "", err
+		}
+		if err := out.Close(); err != nil {
+			return "", err
+		}
+		return dst, nil
+	}
+}

+ 307 - 0
server-go/internal/updater/stable_test.go

@@ -0,0 +1,307 @@
+// stable_test.go — auto-apply en layout estable (#480): capacidad (unidad
+// root instalada), flujo de staging feliz (download+verify+marcador),
+// confirmación en el arranque siguiente (patrón #444) y fallos (checksum).
+package updater
+
+import (
+	"archive/tar"
+	"compress/gzip"
+	"context"
+	"crypto/sha256"
+	"encoding/hex"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"runtime"
+	"strings"
+	"testing"
+	"time"
+)
+
+// overrideStableUnit fuerza el resultado de la detección de la unidad root
+// durante el test.
+func overrideStableUnit(t *testing.T, installed bool) {
+	t.Helper()
+	old := stableUnitInstalled
+	stableUnitInstalled = func() bool { return installed }
+	t.Cleanup(func() { stableUnitInstalled = old })
+}
+
+// fakeReleaseAsset construye un tarball con un binario "netpulse" dentro y
+// devuelve (bytes del tarball, sha256 hex del tarball).
+func fakeReleaseAsset(t *testing.T, binContent string) ([]byte, string) {
+	t.Helper()
+	var buf strings.Builder
+	gz := gzip.NewWriter(&bufWriter{&buf})
+	tw := tar.NewWriter(gz)
+	if err := tw.WriteHeader(&tar.Header{Name: "netpulse", Mode: 0o755, Size: int64(len(binContent))}); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := tw.Write([]byte(binContent)); err != nil {
+		t.Fatal(err)
+	}
+	if err := tw.Close(); err != nil {
+		t.Fatal(err)
+	}
+	if err := gz.Close(); err != nil {
+		t.Fatal(err)
+	}
+	raw := []byte(buf.String())
+	sum := sha256.Sum256(raw)
+	return raw, hex.EncodeToString(sum[:])
+}
+
+// bufWriter adapta strings.Builder a io.Writer sin copiar el contenido dos
+// veces (Write recibe la porción, no el builder entero).
+type bufWriter struct{ b *strings.Builder }
+
+func (w *bufWriter) Write(p []byte) (int, error) { return w.b.Write(p) }
+
+// serveStableRelease monta un httptest que hace de GitHub: APIBase para
+// /releases/latest y downloadBase para los assets del tag dado.
+func serveStableRelease(t *testing.T, tag, asset, tgzSum string, tgzBytes []byte, sumLine string) {
+	t.Helper()
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path == "/" {
+			return // probe de readiness: solo comprueba conectividad
+		}
+		if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
+			t.Errorf("API path inesperado: %s", r.URL.Path)
+			w.WriteHeader(404)
+			return
+		}
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprintf(w, `{"tag_name":%q,"name":%q,"body":"notas de %s"}`, tag, tag, tag)
+	})
+	dl := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		want := "/owner/netpulse/releases/download/" + tag
+		if !strings.HasPrefix(r.URL.Path, want+"/") {
+			t.Errorf("download path inesperado: %s", r.URL.Path)
+			w.WriteHeader(404)
+			return
+		}
+		switch filepath.Base(r.URL.Path) {
+		case asset:
+			w.Header().Set("Content-Type", "application/gzip")
+			_, _ = w.Write(tgzBytes)
+		case "checksums.txt":
+			fmt.Fprintf(w, "%s  %s\n", sumLine, asset)
+		default:
+			w.WriteHeader(404)
+		}
+	}))
+	t.Cleanup(dl.Close)
+	old := downloadBase
+	downloadBase = dl.URL
+	t.Cleanup(func() { downloadBase = old })
+}
+
+func waitStableMarker(t *testing.T, dataDir string) string {
+	t.Helper()
+	marker := filepath.Join(dataDir, stableMarkerName)
+	deadline := time.Now().Add(15 * time.Second)
+	for {
+		if _, err := os.Stat(marker); err == nil {
+			b, err := os.ReadFile(marker)
+			if err != nil {
+				t.Fatal(err)
+			}
+			return string(b)
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("timeout esperando el marcador %s (status: %+v)", marker, func() any {
+				u := marker
+				return u
+			}())
+		}
+		time.Sleep(25 * time.Millisecond)
+	}
+}
+
+// Camino feliz: capacidad estable → Check (updateAvailable) → Apply →
+// marcador con sha256 y binario en escena → "arranque siguiente" con la
+// versión nueva y el marcador de éxito del helper → pendingApply + historial
+// success (patrón #444 extendido a boot-time).
+func TestStableApplyHappyPath(t *testing.T) {
+	overrideStableUnit(t, true)
+	bin := "#!/bin/sh\necho netpulse-9.9.9\n"
+	tgz, tgzSum := fakeReleaseAsset(t, bin)
+	asset := fmt.Sprintf("%s_9.9.9_linux_%s.tar.gz", stableBinName, runtime.GOARCH)
+	serveStableRelease(t, "v9.9.9", asset, tgzSum, tgz, tgzSum)
+
+	dataDir := t.TempDir()
+	dbh := openDB(t)
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", dbh).WithDataDir(dataDir)
+
+	st := u.Check(context.Background())
+	if st.Error != nil || !st.UpdateAvailable || !st.CanApply {
+		t.Fatalf("check: %+v", st)
+	}
+	if st.Mode != "stable" {
+		t.Fatalf("mode: %s", st.Mode)
+	}
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+
+	marker := waitStableMarker(t, dataDir)
+	if !strings.Contains(marker, "target=v9.9.9") {
+		t.Fatalf("marcador sin target: %q", marker)
+	}
+	stagedPath := fieldOf(marker, "staged")
+	wantSHA := fieldOf(marker, "sha256")
+	gotSHA, err := fileSHA256(stagedPath)
+	if err != nil {
+		t.Fatalf("binario en escena no accesible: %v", err)
+	}
+	if gotSHA != wantSHA {
+		t.Fatalf("sha del binario en escena: got %s want %s", gotSHA, wantSHA)
+	}
+
+	// Simular al helper: swap OK → marcador de éxito con el objetivo y
+	// limpieza del marcador disparador (el proceso muere con el restart).
+	if err := os.WriteFile(filepath.Join(dataDir, stableAppliedName), []byte("v9.9.9\n"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	_ = os.Remove(filepath.Join(dataDir, stableMarkerName))
+
+	// "Arranque siguiente": updater nuevo con la versión ya actualizada.
+	u.Stop() // libera la goroutine del apply (sigue esperando el restart)
+	u2 := New(t.TempDir(), "owner/netpulse", "", "9.9.9", dbh).WithDataDir(dataDir)
+	st2 := u2.Status()
+	if st2.PendingApply == nil {
+		t.Fatal("pendingApply debería confirmarse en el arranque con marcador de éxito")
+	}
+	if st2.PendingApply.From != "2.0.0" || st2.PendingApply.To != "9.9.9" {
+		t.Fatalf("pendingApply: %+v", st2.PendingApply)
+	}
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 || hist[0].Status != "success" {
+		t.Fatalf("historial: esperaba success re-marcado, got %+v", hist)
+	}
+}
+
+// Sin el marcador de éxito del helper (apply murió a medias): el arranque
+// NO confirma y el historial queda fallido.
+func TestStableApplyWithoutHelperMarkerIsSilent(t *testing.T) {
+	overrideStableUnit(t, true)
+	bin := "x"
+	tgz, tgzSum := fakeReleaseAsset(t, bin)
+	asset := fmt.Sprintf("%s_9.9.9_linux_%s.tar.gz", stableBinName, runtime.GOARCH)
+	serveStableRelease(t, "v9.9.9", asset, tgzSum, tgz, tgzSum)
+
+	dataDir := t.TempDir()
+	dbh := openDB(t)
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", dbh).WithDataDir(dataDir)
+	if st := u.Check(context.Background()); !st.UpdateAvailable {
+		t.Fatalf("check: %+v", st)
+	}
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	_ = waitStableMarker(t, dataDir)
+	// El helper NO llega a escribir .update-applied (p.ej. sha mismatch).
+	u.Stop()
+
+	u2 := New(t.TempDir(), "owner/netpulse", "", "9.9.9", dbh).WithDataDir(dataDir)
+	if u2.Status().PendingApply != nil {
+		t.Fatal("sin marcador del helper no debería confirmarse")
+	}
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 || hist[0].Status != "failed" {
+		t.Fatalf("historial: esperaba failed, got %+v", hist)
+	}
+}
+
+// Checksum del tarball incorrecto: el apply falla, no hay marcador y el
+// pending se limpia (#161).
+func TestStableApplyChecksumMismatch(t *testing.T) {
+	overrideStableUnit(t, true)
+	bin := "x"
+	tgz, _ := fakeReleaseAsset(t, bin)
+	asset := fmt.Sprintf("%s_9.9.9_linux_%s.tar.gz", stableBinName, runtime.GOARCH)
+	serveStableRelease(t, "v9.9.9", asset, "deadbeef", tgz, strings.Repeat("0", 64))
+
+	dataDir := t.TempDir()
+	dbh := openDB(t)
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", dbh).WithDataDir(dataDir)
+	if st := u.Check(context.Background()); !st.UpdateAvailable {
+		t.Fatalf("check: %+v", st)
+	}
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	deadline := time.Now().Add(15 * time.Second)
+	for {
+		if st := u.Status(); st.Error != nil && *st.Error == "stable_checksum_mismatch" {
+			break
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("timeout esperando stable_checksum_mismatch: %+v", u.Status())
+		}
+		time.Sleep(25 * time.Millisecond)
+	}
+	if _, err := os.Stat(filepath.Join(dataDir, stableMarkerName)); !os.IsNotExist(err) {
+		t.Fatal("no debería quedar marcador tras un mismatch")
+	}
+	if _, ok := readPendingApply(dbh); ok {
+		t.Fatal("pendingApply debe limpiarse en un fallo (#161)")
+	}
+	hist, err := ListHistory(dbh, 10)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(hist) == 0 || hist[0].Status != "failed" || hist[0].Error == nil || *hist[0].Error != "stable_checksum_mismatch" {
+		t.Fatalf("historial: %+v", hist[0])
+	}
+}
+
+// Con la unidad root instalada, el layout estable pasa a canApply (#480);
+// sin ella, sigue !canApply (comportamiento previo intacto).
+func TestStableCapabilityWithUnit(t *testing.T) {
+	overrideStableUnit(t, true)
+	u := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil).WithDataDir(t.TempDir())
+	if !u.CanApply() || u.mode != "stable" {
+		t.Fatalf("estable+unidad debería ser stable/canApply: %+v", u.Status())
+	}
+
+	overrideStableUnit(t, false)
+	u2 := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil).WithDataDir(t.TempDir())
+	if u2.CanApply() || u2.mode != "stable" {
+		t.Fatalf("estable sin unidad debería ser stable/!canApply")
+	}
+}
+
+// El marcador .update-applied vive en el dataDir en estable y en el
+// repoRoot en rolling.
+func TestAppliedMarkerPathByMode(t *testing.T) {
+	uRolling := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil)
+	writeDeployScript(t, uRolling.repoRoot)
+	// recrear para que la detección pille el update.sh
+	uRolling = New(uRolling.repoRoot, "owner/netpulse", "", "1.0.0", nil)
+	if !strings.HasSuffix(uRolling.appliedMarkerPath(), filepath.Join(uRolling.repoRoot, ".update-applied")) {
+		t.Fatalf("rolling: %s", uRolling.appliedMarkerPath())
+	}
+	dataDir := t.TempDir()
+	uStable := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil).WithDataDir(dataDir)
+	if uStable.appliedMarkerPath() != filepath.Join(dataDir, stableAppliedName) {
+		t.Fatalf("estable: %s", uStable.appliedMarkerPath())
+	}
+}
+
+func fieldOf(marker, key string) string {
+	for _, line := range strings.Split(marker, "\n") {
+		if strings.HasPrefix(line, key+"=") {
+			return strings.TrimPrefix(line, key+"=")
+		}
+	}
+	return ""
+}

+ 45 - 8
server-go/internal/updater/updater.go

@@ -93,8 +93,11 @@ type Updater struct {
 	repo     string
 	token    string
 	version  string // semver embebido (httpapi.Version) para comparar en estable
-	canApply bool   // true si existe deploy/update.sh (layout git)
+	canApply bool   // rolling: deploy/update.sh; estable: unidad root de swap (#480)
 	mode     string // "rolling" (git layout) | "stable" (install.sh)
+	// dataDir: ruta real resuelta de DATA_DIR (WithDataDir). En estable es
+	// donde el auto-apply (#480) deja el staging y los marcadores.
+	dataDir string
 	// db: SQLite para historial (#159) y marcador pendingApply (#161). nil →
 	// persistencia deshabilitada (tests sin BD).
 	db *sql.DB
@@ -129,16 +132,19 @@ type Updater struct {
 }
 
 // New crea el updater. version es el semver embebido (httpapi.Version) usado
-// para comparar contra el último release tag en modo estable. La detección de
-// layout es automática: si existe deploy/update.sh junto a repoRoot, el modo
-// es "rolling" (compara contra main HEAD y puede auto-aplicar); si no, es
-// "stable" (compara contra release tags y NO puede auto-aplicar — el usuario
-// debe re-ejecutar install.sh). db puede ser nil (persistencia deshabilitada).
+// para comparar contra el último release tag en modo estable. La detección
+// de layout es automática: si existe deploy/update.sh junto a repoRoot, el
+// modo es "rolling" (compara contra main HEAD y aplica vía update.sh); si
+// no, es "stable" (compara contra release tags). En estable, con la unidad
+// root de swap instalada por install.sh, el auto-apply también está
+// disponible (#480). db puede ser nil (persistencia deshabilitada).
 func New(repoRoot, repo, token, version string, db *sql.DB) *Updater {
 	canApply := fileExists(filepath.Join(repoRoot, "deploy", "update.sh"))
 	mode := "stable"
 	if canApply {
 		mode = "rolling"
+	} else if stableUnitInstalled() {
+		canApply = true
 	}
 	u := &Updater{
 		repoRoot: repoRoot,
@@ -498,6 +504,32 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 	u.persistPendingApply(from, to)
 	startedAt := time.Now()
 
+	if u.mode == "stable" {
+		// Issue #480: layout single-binary con unidad root de swap. Nada
+		// de update.sh: descargar release estable, verificar y dejar el
+		// binario en escena para el helper root (applyStable). El éxito se
+		// confirma en el arranque siguiente (#444 vía loadPendingApply).
+		if to == nil || strings.TrimSpace(*to) == "" {
+			u.mu.Lock()
+			u.updatingStep = nil
+			code := "stable_no_target"
+			u.err = &code
+			u.broadcastLocked()
+			u.mu.Unlock()
+			u.finishHistory(historyID, "failed", code, time.Since(startedAt))
+			u.clearPendingApply()
+			return false
+		}
+		// Marcador de un apply previo: fuera antes de empezar (#444).
+		_ = os.Remove(u.appliedMarkerPath())
+		u.wg.Add(1)
+		go func() {
+			defer u.wg.Done()
+			u.applyStable(historyID, strings.TrimSpace(*to), startedAt)
+		}()
+		return true
+	}
+
 	tmpScript := filepath.Join(os.TempDir(), fmt.Sprintf("netpulse-update-%d.sh", time.Now().UnixMilli()))
 	src, err := os.ReadFile(filepath.Join(u.repoRoot, "deploy", "update.sh"))
 	if err == nil {
@@ -726,9 +758,14 @@ func (u *Updater) Stop() {
 	u.wg.Wait()
 }
 
-// appliedMarkerPath: fichero que update.sh escribe justo antes de tocar el
-// flag de reinicio diferido (#444). Vive en la raíz del repo (gitignored).
+// appliedMarkerPath: fichero que update.sh (rolling) o el helper root
+// (estable, #480) escriben justo antes de tocar el flag de reinicio (#444).
 func (u *Updater) appliedMarkerPath() string {
+	if u.mode == "stable" && u.dataDir != "" {
+		// En estable el repoRoot (padre del working dir, p.ej. /var/lib)
+		// no es escribible por el servicio: el marcador vive en el dataDir.
+		return filepath.Join(u.dataDir, stableAppliedName)
+	}
 	return filepath.Join(u.repoRoot, ".update-applied")
 }
 

+ 4 - 3
server-go/internal/updater/updater_pending_test.go

@@ -73,12 +73,13 @@ func TestPendingApplyClearedSilentlyWhenUnchanged(t *testing.T) {
 }
 
 func TestPendingApplyIgnoredOnStableLayout(t *testing.T) {
-	// Layout estable (sin deploy/update.sh): el marcador se limpia sin
-	// confirmación (no hay auto-apply en este layout).
+	// Layout estable SIN marcador de éxito del helper (#480): el arranque
+	// con dataDir (vía WithDataDir) limpia el marcador sin confirmar, como
+	// un apply que murió a medias.
 	root := t.TempDir()
 	dbh := openDB(t)
 	seedPending(t, dbh, "oldsha", "newsha")
-	u := New(root, "owner/netpulse", "", "2.0.0", dbh)
+	u := New(root, "owner/netpulse", "", "2.0.0", dbh).WithDataDir(t.TempDir())
 	if u.Status().PendingApply != nil {
 		t.Fatal("en layout estable no debería confirmar")
 	}