Jelajahi Sumber

feat(updater): scheduled self-update - daily/weekly/monthly, opt-in, verified apply with rollback (#759) (#763)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 bulan lalu
induk
melakukan
675ba03e94

+ 7 - 0
CHANGELOG.md

@@ -5,6 +5,13 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
+## [Unreleased]
+
+### Added
+
+- **Flujo completo de actualizaciones de firmware con owut/ASU (#761)**: la pantalla de actualizaciones se rediseña en torno al attended sysupgrade. Modelo y versión actuales pasan a solo lectura con lo detectado del board info; la versión objetivo es un desplegable con las versiones estables que ASU puede construir para el router (aviso inline en saltos de rama mayor); URL y checksum quedan como vía avanzada. owut se puede instalar desde la UI, "Comprobar" pasa a la fila de acciones junto a Guardar / Actualizar ahora / Programar, y Actualizar ahora lanza el upgrade desatendido (conserva los paquetes instalados) con confirmación clara: el estado sigue la secuencia construcción → descarga → reinicio, con vista de proceso (fase, barra de progreso y consola) y vista de éxito al terminar. Programación con recurrencia una vez / semanal (empezando en lunes) / mensual, idempotente (un router al día no hace nada) y con aviso del resultado por alerta (feed, push, webhook, Telegram). Los routers con firmware de fabricante (GL.iNet, detectado por sus repositorios) quedan fuera del flujo con un panel informativo: sus actualizaciones las gestiona el fabricante. Los paquetes del propio stack (netgrip, agente) sobreviven al flasheo: NetPulse asegura sus ficheros en /etc/sysupgrade.conf antes de actualizar, y los paquetes locales sin feed se detectan en el check y se ofrecen para excluir con sus nombres.
+- **Auto-actualización programada del servidor (#759)**: nueva programación en Ajustes → Administración con modo desactivado (por defecto) / diaria / semanal / mensual y hora. El disparo comprueba novedades y aplica solo el binario cuando el readiness lo permite (nunca en modo demo ni con el check fallido), con la verificación de salud y el rollback automático del helper root; el reloj deriva del último disparo persistido, así que reinicios y la propia actualización no re disparan la ventana. Cada intento (aplicada, sin novedades, comprobación fallida, no aplicable) queda en Ajustes y avisa por alerta.
+
 ## [2.28.24] - 2026-09-12
 
 ### Added

+ 23 - 1
app/public/locales/en/translation.json

@@ -234,6 +234,10 @@
       "firmware-upgrade-failed": {
         "title": "Firmware upgrade failed",
         "description": "{{router}}: target {{to}} (owut, {{origin}}): {{detail}}"
+      },
+      "autoupdate": {
+        "title": "Scheduled auto-update",
+        "description": "{{detail}}"
       }
     }
   },
@@ -1565,7 +1569,25 @@
       "about": "About",
       "label": "Settings sections"
     },
-    "theme": "Theme"
+    "theme": "Theme",
+    "autoupdate": {
+      "button": "Auto-update",
+      "mode": "Mode",
+      "off": "Off",
+      "daily": "Daily",
+      "weekly": "Weekly",
+      "monthly": "Monthly",
+      "dayOfWeek": "Day of the week",
+      "dayOfMonth": "Day of the month",
+      "time": "Time",
+      "hint": "Applies the NetPulse binary only when a new release is out, with health verification and automatic rollback if the service does not come back. Never in demo mode or when readiness fails. Every attempt reports through an alert.",
+      "next": "Next run",
+      "last": "Last attempt",
+      "resultApplied": "update applied",
+      "resultUpToDate": "up to date",
+      "resultCheckFailed": "check failed",
+      "resultCannotApply": "could not apply (readiness or layout)"
+    }
   },
   "statcard": {
     "vsPrevious": "vs previous"

+ 23 - 1
app/public/locales/es/translation.json

@@ -234,6 +234,10 @@
       "firmware-upgrade-failed": {
         "title": "Actualización de firmware fallida",
         "description": "{{router}}: objetivo {{to}} (owut, {{origin}}): {{detail}}"
+      },
+      "autoupdate": {
+        "title": "Auto-actualización programada",
+        "description": "{{detail}}"
       }
     }
   },
@@ -1565,7 +1569,25 @@
       "about": "Acerca de",
       "label": "Secciones de Ajustes"
     },
-    "theme": "Tema"
+    "theme": "Tema",
+    "autoupdate": {
+      "button": "Auto-actualización",
+      "mode": "Modo",
+      "off": "Desactivada",
+      "daily": "Diaria",
+      "weekly": "Semanal",
+      "monthly": "Mensual",
+      "dayOfWeek": "Día de la semana",
+      "dayOfMonth": "Día del mes",
+      "time": "Hora",
+      "hint": "Aplica solo el binario de NetPulse cuando hay una versión nueva, con verificación de salud y rollback automático si el servicio no vuelve. Nunca en modo demo ni si el readiness falla. Cada intento avisa por alerta.",
+      "next": "Próximo disparo",
+      "last": "Último intento",
+      "resultApplied": "actualización aplicada",
+      "resultUpToDate": "sin novedades",
+      "resultCheckFailed": "comprobación fallida",
+      "resultCannotApply": "no se pudo aplicar (readiness o layout)"
+    }
   },
   "statcard": {
     "vsPrevious": "vs anterior"

+ 193 - 1
app/src/pages/Settings.tsx

@@ -45,6 +45,7 @@ import {
    Wifi,
    X,
    ChevronUp,
+  CalendarClock,
 } from 'lucide-react'
 import type { LucideIcon } from 'lucide-react'
 import { HealthRing } from '@/components/HealthRing'
@@ -3271,6 +3272,172 @@ function checkErrText(err: string | undefined, t: (k: string) => string): string
   }
 }
 
+// AutoUpdatePanel (#759): programación del auto-update del propio server.
+function AutoUpdatePanel() {
+  const { t, i18n } = useTranslation()
+  const [enabled, setEnabled] = useState(false)
+  const [kind, setKind] = useState<'daily' | 'weekly' | 'monthly'>('daily')
+  const [time, setTime] = useState('04:00')
+  const [dow, setDow] = useState(1)
+  const [dom, setDom] = useState(1)
+  const [info, setInfo] = useState<{ lastRunMs?: number; lastResult?: string; nextRunMs?: number }>({})
+  const [busy, setBusy] = useState(false)
+  const [err, setErr] = useState('')
+
+  const load = async () => {
+    try {
+      const res = await fetch('/api/settings/autoupdate')
+      if (!res.ok) return
+      const body = (await res.json()) as {
+        settings: { enabled: boolean; kind: string; time: string; dayOfWeek?: number; dayOfMonth?: number }
+        lastRunMs?: number
+        lastResult?: string
+        nextRunMs?: number
+      }
+      setEnabled(body.settings.enabled)
+      if (body.settings.kind === 'weekly' || body.settings.kind === 'monthly') setKind(body.settings.kind)
+      if (body.settings.time) setTime(body.settings.time)
+      if (typeof body.settings.dayOfWeek === 'number') setDow(body.settings.dayOfWeek)
+      if (typeof body.settings.dayOfMonth === 'number') setDom(body.settings.dayOfMonth)
+      setInfo({ lastRunMs: body.lastRunMs, lastResult: body.lastResult, nextRunMs: body.nextRunMs })
+    } catch {
+      // fail-silent
+    }
+  }
+  useEffect(() => {
+    void load()
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [])
+
+  const save = async () => {
+    setBusy(true)
+    setErr('')
+    try {
+      const res = await fetch('/api/settings/autoupdate', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          enabled,
+          kind,
+          time,
+          dayOfWeek: kind === 'weekly' ? dow : undefined,
+          dayOfMonth: kind === 'monthly' ? dom : undefined,
+        }),
+      })
+      const body = (await res.json().catch(() => ({}))) as { error?: { message?: string } }
+      if (!res.ok) throw new Error(body?.error?.message ?? `HTTP ${res.status}`)
+      await load()
+    } catch (e) {
+      setErr(String(e))
+    } finally {
+      setBusy(false)
+    }
+  }
+
+  const dowLabel = (d: number) => new Date(2026, 8, 13 + d).toLocaleDateString(i18n.language, { weekday: 'long' })
+  const resultText = (r?: string) =>
+    r === 'applied'
+      ? t('settings.autoupdate.resultApplied')
+      : r === 'up-to-date'
+        ? t('settings.autoupdate.resultUpToDate')
+        : r === 'check-failed'
+          ? t('settings.autoupdate.resultCheckFailed')
+          : r === 'cannot-apply'
+            ? t('settings.autoupdate.resultCannotApply')
+            : ''
+
+  return (
+    <div className="space-y-3">
+      <div className="flex flex-wrap items-end gap-3">
+        <label className="flex flex-col gap-1">
+          <span className="text-caption text-text-muted">{t('settings.autoupdate.mode')}</span>
+          <select
+            value={enabled ? kind : 'off'}
+            onChange={(ev) => {
+              const v = ev.target.value
+              setEnabled(v !== 'off')
+              if (v === 'daily' || v === 'weekly' || v === 'monthly') setKind(v)
+            }}
+            className="h-9 rounded-lg border border-border bg-canvas px-3 text-sm text-text-primary"
+          >
+            <option value="off">{t('settings.autoupdate.off')}</option>
+            <option value="daily">{t('settings.autoupdate.daily')}</option>
+            <option value="weekly">{t('settings.autoupdate.weekly')}</option>
+            <option value="monthly">{t('settings.autoupdate.monthly')}</option>
+          </select>
+        </label>
+        {enabled && kind === 'weekly' && (
+          <label className="flex flex-col gap-1">
+            <span className="text-caption text-text-muted">{t('settings.autoupdate.dayOfWeek')}</span>
+            <select
+              value={dow}
+              onChange={(ev) => setDow(Number(ev.target.value))}
+              className="h-9 rounded-lg border border-border bg-canvas px-3 text-sm text-text-primary"
+            >
+              {[1, 2, 3, 4, 5, 6, 0].map((d) => (
+                <option key={d} value={d}>
+                  {dowLabel(d)}
+                </option>
+              ))}
+            </select>
+          </label>
+        )}
+        {enabled && kind === 'monthly' && (
+          <label className="flex flex-col gap-1">
+            <span className="text-caption text-text-muted">{t('settings.autoupdate.dayOfMonth')}</span>
+            <select
+              value={dom}
+              onChange={(ev) => setDom(Number(ev.target.value))}
+              className="h-9 rounded-lg border border-border bg-canvas px-3 text-sm text-text-primary"
+            >
+              {Array.from({ length: 31 }, (_, i) => i + 1).map((d) => (
+                <option key={d} value={d}>
+                  {d}
+                </option>
+              ))}
+            </select>
+          </label>
+        )}
+        {enabled && (
+          <label className="flex flex-col gap-1">
+            <span className="text-caption text-text-muted">{t('settings.autoupdate.time')}</span>
+            <input
+              type="time"
+              value={time}
+              onChange={(ev) => setTime(ev.target.value)}
+              className="h-9 rounded-lg border border-border bg-canvas px-3 text-sm text-text-primary"
+            />
+          </label>
+        )}
+        <button
+          type="button"
+          onClick={() => void save()}
+          disabled={busy}
+          className="inline-flex h-9 items-center gap-2 rounded-lg bg-accent px-4 text-sm font-medium text-canvas transition-colors hover:bg-accent/90 disabled:opacity-50"
+        >
+          {busy ? t('common.loading') : t('common.save')}
+        </button>
+      </div>
+
+      {err && <p className="text-sm text-danger">{err}</p>}
+
+      <p className="text-xs text-text-muted">{t('settings.autoupdate.hint')}</p>
+
+      {enabled && info.nextRunMs != null && (
+        <p className="text-sm text-text-secondary">
+          {t('settings.autoupdate.next')}: {new Date(info.nextRunMs).toLocaleString()}
+        </p>
+      )}
+      {info.lastResult && (
+        <p className="text-sm text-text-secondary">
+          {t('settings.autoupdate.last')}: {resultText(info.lastResult)}
+          {info.lastRunMs ? ` (${new Date(info.lastRunMs).toLocaleString()})` : ''}
+        </p>
+      )}
+    </div>
+  )
+}
+
 function UpdateCheckInline() {
   const { t } = useTranslation()
   const [status, setStatus] = useState<NetPulseUpdateStatus | null>(null)
@@ -3704,7 +3871,7 @@ export default function Settings() {
   const auth = useAuth()
   // SPEC-65 D65-7c: la tarjeta AdGuard entera desaparece si el servicio está oculto
   const [services] = useServicesVisibility()
-  const [adminPanel, setAdminPanel] = useState<'users' | 'backups' | null>(null)
+  const [adminPanel, setAdminPanel] = useState<'users' | 'backups' | 'autoupdate' | null>(null)
 
   // ——— Orquestación (issue #121): toggle opt-in en la AdminBar ———
   const [orchOn, setOrchOn] = useState(false)
@@ -4526,6 +4693,26 @@ export default function Settings() {
                 {/* 1. Comprobar actualizaciones (widget inline) */}
                 <UpdateCheckInline />
 
+                {/* 1b. Auto-actualización programada (desplegable, #759) */}
+                <button
+                  type="button"
+                  aria-expanded={adminPanel === 'autoupdate'}
+                  onClick={() => setAdminPanel(adminPanel === 'autoupdate' ? null : 'autoupdate')}
+                  className={[
+                    'inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl border px-3 text-[13px] font-medium transition-colors',
+                    adminPanel === 'autoupdate'
+                      ? 'border-accent bg-accent-soft text-accent'
+                      : 'border-border bg-elevated text-text-secondary hover:bg-hover hover:text-text-primary',
+                  ].join(' ')}
+                >
+                  <CalendarClock className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
+                  <span className="hidden sm:inline">{t('settings.autoupdate.button')}</span>
+                  <ChevronDown
+                    className={`h-3.5 w-3.5 shrink-0 transition-transform ${adminPanel === 'autoupdate' ? 'rotate-180' : ''}`}
+                    aria-hidden="true"
+                  />
+                </button>
+
                 {/* 2. Respaldos (desplegable) */}
                 <button
                   type="button"
@@ -4572,6 +4759,11 @@ export default function Settings() {
                 </div>
               </div>
 
+              {adminPanel === 'autoupdate' && (
+                <div className="mt-4 border-t border-border pt-4">
+                  <AutoUpdatePanel />
+                </div>
+              )}
               {adminPanel === 'backups' && (
                 <div className="mt-4 border-t border-border pt-4">
                   <BackupsPanel />

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

@@ -528,6 +528,17 @@ func run() error {
 		go stScheduler.Start()
 	}
 
+	// Auto-update programado (#759): opt-in del admin, nunca en demo. El
+	// disparo deriva del last_run persistido (reboot-safe: el propio update
+	// reinicia el proceso y no debe re-disparar el mismo slot).
+	if !cfg.DemoMode {
+		autoSched := updater.NewScheduler(dbHandle.DB, upd)
+		if adapter != nil {
+			autoSched.SetAlertEmitter(adapter.AlertsEngine())
+		}
+		go autoSched.Start()
+	}
+
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config:          cfg,
 		DB:              dbHandle,

+ 40 - 0
server-go/internal/httpapi/owut_test.go

@@ -148,3 +148,43 @@ func TestOwutCheckNoSSHPool(t *testing.T) {
 		t.Fatalf("error: %v", body["error"])
 	}
 }
+
+// TestAutoUpdateSettingsContract (#759): GET/PUT de la programación.
+func TestAutoUpdateSettingsContract(t *testing.T) {
+	ts, _ := makeOwutTestServer(t, nil)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	// GET inicial: desactivado.
+	res := getJSONPath(t, ts.URL, "/api/settings/autoupdate", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("GET: %d %v", res.StatusCode, body)
+	}
+	if st, _ := body["settings"].(map[string]any); st["enabled"] != false {
+		t.Fatalf("default debe ser off: %v", body)
+	}
+
+	// PUT válido weekly.
+	res = putJSONPath(t, ts.URL, "/api/settings/autoupdate",
+		`{"enabled":true,"kind":"weekly","time":"04:00","dayOfWeek":1}`, cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT weekly: %d %v", res.StatusCode, readJSON(t, res))
+	}
+
+	// GET: settings + nextRunMs presentes.
+	res = getJSONPath(t, ts.URL, "/api/settings/autoupdate", cookie)
+	body = readJSON(t, res)
+	if st, _ := body["settings"].(map[string]any); st["kind"] != "weekly" || st["enabled"] != true {
+		t.Fatalf("tras PUT: %v", body)
+	}
+	if _, ok := body["nextRunMs"]; !ok {
+		t.Fatalf("GET debe traer nextRunMs habilitado: %v", body)
+	}
+
+	// PUT inválido (weekly sin dayOfWeek): 400.
+	res = putJSONPath(t, ts.URL, "/api/settings/autoupdate",
+		`{"enabled":true,"kind":"weekly","time":"04:00"}`, cookie)
+	if res.StatusCode != 400 {
+		t.Fatalf("PUT inválido: %d, esperaba 400", res.StatusCode)
+	}
+}

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

@@ -466,6 +466,10 @@ func NewHandler(d Deps) http.Handler {
 	if d.Updater != nil {
 		s.registerUpdateRoutes(mux, d.Updater)
 	}
+	// Auto-update programado (#759): ajustes siempre disponibles en live.
+	if s.db != nil {
+		s.registerAutoUpdateSettings(mux)
+	}
 
 	// --- Orquestación (Fase 10; solo admin) ---
 	s.registerOrchestrRoutes(mux, d.Orchestr)

+ 37 - 0
server-go/internal/httpapi/update.go

@@ -100,3 +100,40 @@ func (s *server) registerUpdateRoutes(mux *http.ServeMux, u *updater.Updater) {
 		w.WriteHeader(http.StatusNoContent)
 	})))
 }
+
+// registerAutoUpdateSettings (#759): ajustes del auto-update programado.
+// Funcionan aunque el updater no esté montado (el loop simplemente no corre).
+func (s *server) registerAutoUpdateSettings(mux *http.ServeMux) {
+	mux.Handle("GET /api/settings/autoupdate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		st := updater.LoadAutoUpdateSettings(s.db.DB)
+		lastRun, lastResult := updater.AutoRunState(s.db.DB)
+		out := map[string]any{
+			"settings":   st,
+			"lastRunMs":  lastRun,
+			"lastResult": lastResult,
+		}
+		if st.Enabled {
+			next := updater.NextAutoUpdateAt(st, lastRun, time.Now())
+			if !next.IsZero() {
+				out["nextRunMs"] = next.UnixMilli()
+			}
+		}
+		writeJSON(w, http.StatusOK, out)
+	})))
+
+	mux.Handle("PUT /api/settings/autoupdate", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		var body updater.AutoUpdateSettings
+		if st := readJSONBody(w, r, &body); st != 0 {
+			return
+		}
+		if body.Kind == "" {
+			writeError(w, http.StatusBadRequest, "invalid_body", "kind es requerido")
+			return
+		}
+		if err := updater.SaveAutoUpdateSettings(s.db.DB, body); err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_body", err.Error())
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
+	})))
+}

+ 419 - 0
server-go/internal/updater/autosched.go

@@ -0,0 +1,419 @@
+// autosched.go - auto-actualización programada del propio server (#759).
+//
+// Off por defecto (opt-in explícito del admin). Patrón de backups (#741),
+// speedtest (#744) y firmware (#761): ajustes en kv, vencimiento derivado
+// del last_run PERSISTIDO (reinicios y el propio update no resetean el
+// reloj) y single-flight. El disparo: Check y, solo si hay novedad fresca y
+// el layout puede aplicar, ApplyBy("scheduled"): binario únicamente, con la
+// verificación de salud y el rollback del helper root de #480. El last_run
+// se persiste ANTES de actuar: el apply reinicia el proceso y el arranque
+// posterior no debe volver a disparar el mismo slot.
+package updater
+
+import (
+	"context"
+	"database/sql"
+	"fmt"
+	"log"
+	"strconv"
+	"sync/atomic"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// Kinds de programación del auto-update.
+const (
+	AutoDaily   = "daily"
+	AutoWeekly  = "weekly"
+	AutoMonthly = "monthly"
+)
+
+// AutoUpdateSettings persistidas en kv (claves settings.autoupdate.*).
+type AutoUpdateSettings struct {
+	Enabled bool   `json:"enabled"`
+	Kind    string `json:"kind"` // daily | weekly | monthly
+	Time    string `json:"time"` // "HH:MM" hora local
+	// DayOfWeek 0=domingo..6 (weekly); DayOfMonth 1..31 con clamp (monthly).
+	DayOfWeek  *int `json:"dayOfWeek,omitempty"`
+	DayOfMonth *int `json:"dayOfMonth,omitempty"`
+}
+
+// LastRunMs / LastResult viajan aparte (no los escribe el PUT).
+type autoRunState struct {
+	LastRunMs  int64  `json:"lastRunMs,omitempty"`
+	LastResult string `json:"lastResult,omitempty"` // "" | applied | up-to-date | check-failed | cannot-apply
+}
+
+// CheckerApplier es lo que el scheduler necesita del updater (lo satisface
+// *Updater; fakes en tests).
+type CheckerApplier interface {
+	Check(ctx context.Context) Status
+	CanApply() bool
+	ApplyBy(initiatedBy string) bool
+}
+
+// AlertEmitter lo cumple *alerts.Engine (nil = sin alertas, p. ej. tests).
+type AlertEmitter interface {
+	Emit(ev alerts.AlertEvent) bool
+}
+
+// Scheduler ejecuta el auto-update programado.
+type Scheduler struct {
+	db   *sql.DB
+	ua   CheckerApplier
+	emit AlertEmitter
+
+	now  func() time.Time
+	logf func(format string, args ...any)
+
+	running atomic.Bool
+}
+
+// NewScheduler construye el scheduler (Start lo arranca como daemon).
+func NewScheduler(db *sql.DB, ua CheckerApplier) *Scheduler {
+	return &Scheduler{
+		db:  db,
+		ua:  ua,
+		now: time.Now,
+		logf: func(f string, a ...any) {
+			log.Printf("[autoupdate] "+f, a...)
+		},
+	}
+}
+
+// SetAlertEmitter fija el motor de alertas (llamado tras construir el
+// adapter live en main).
+func (s *Scheduler) SetAlertEmitter(e AlertEmitter) { s.emit = e }
+
+// Start lanza el bucle periódico (daemon; no retorna).
+func (s *Scheduler) Start() {
+	ticker := time.NewTicker(time.Minute)
+	defer ticker.Stop()
+	for range ticker.C {
+		s.tick()
+	}
+}
+
+func (s *Scheduler) tick() {
+	if s.db == nil || s.ua == nil {
+		return
+	}
+	st := LoadAutoUpdateSettings(s.db)
+	state := loadAutoRunState(s.db)
+	if !AutoUpdateDue(st, state.LastRunMs, s.now()) {
+		return
+	}
+	if !s.running.CompareAndSwap(false, true) {
+		return
+	}
+	go func() {
+		defer s.running.Store(false)
+		s.shot(st, state)
+	}()
+}
+
+// shot ejecuta un disparo vencido: marca el slot, comprueba y aplica si
+// procede. El resultado queda en kv (UI) y en el historial del updater.
+func (s *Scheduler) shot(st AutoUpdateSettings, prev autoRunState) {
+	nowMs := s.now().UnixMilli()
+	setAutoKv(s.db, "last_run", strconv.FormatInt(nowMs, 10))
+
+	status := s.ua.Check(context.Background())
+	switch {
+	case status.CheckFailed:
+		saveAutoResult(s.db, "check-failed")
+		s.alert(false, fmt.Sprintf("No se pudo comprobar (razón: %s); se reintentará en el próximo disparo", status.CheckErr), status.CheckErr)
+	case !status.UpdateAvailable:
+		saveAutoResult(s.db, "up-to-date")
+	case !status.CanApply:
+		// Readiness o layout sin apply: se avisa (hay novedad esperando y no
+		// se podrá aplicar hasta que el admin lo resuelva).
+		saveAutoResult(s.db, "cannot-apply")
+		s.alert(false, "Hay una actualización disponible pero este layout no puede aplicarla ahora (revisa readiness en Ajustes)", "cannot-apply")
+	default:
+		saveAutoResult(s.db, "applied")
+		if s.ua.ApplyBy("scheduled") {
+			s.alert(true, fmt.Sprintf("Actualización programada iniciada: %s (solo binario, con verificación y rollback automático)", statusLatestDeref(status)), "")
+		} else {
+			s.alert(false, "La actualización programada no pudo arrancar (¿otra actualización en curso?)", "apply-busy")
+		}
+	}
+}
+
+// alert emite la notificación del disparo (info en éxito, warn en aviso).
+func (s *Scheduler) alert(ok bool, desc, code string) {
+	s.logf("%s", desc)
+	if s.emit == nil {
+		return
+	}
+	sev := "warn"
+	if ok {
+		sev = "info"
+	}
+	s.emit.Emit(alerts.AlertEvent{
+		ID:          fmt.Sprintf("alert-autoupdate-%d", s.now().UnixMilli()),
+		Category:    alerts.CatSystem,
+		Urgent:      true,
+		Severity:    sev,
+		Title:       "Auto-actualización programada",
+		Description: desc,
+		Time:        "ahora mismo",
+		Ts:          s.now().Unix(),
+		Type:        "autoupdate",
+		Vars:        map[string]string{"result": code, "detail": desc},
+	})
+}
+
+// --- Validación y due (funciones puras) ---
+
+// ValidateAutoUpdate comprueba la coherencia kind/campos.
+func ValidateAutoUpdate(st AutoUpdateSettings) error {
+	switch st.Kind {
+	case AutoDaily:
+		if !validAutoTime(st.Time) {
+			return fmt.Errorf("daily exige time HH:MM")
+		}
+	case AutoWeekly:
+		if st.DayOfWeek == nil || *st.DayOfWeek < 0 || *st.DayOfWeek > 6 {
+			return fmt.Errorf("weekly exige dayOfWeek 0-6 (0 = domingo)")
+		}
+		if !validAutoTime(st.Time) {
+			return fmt.Errorf("weekly exige time HH:MM")
+		}
+	case AutoMonthly:
+		if st.DayOfMonth == nil || *st.DayOfMonth < 1 || *st.DayOfMonth > 31 {
+			return fmt.Errorf("monthly exige dayOfMonth 1-31")
+		}
+		if !validAutoTime(st.Time) {
+			return fmt.Errorf("monthly exige time HH:MM")
+		}
+	default:
+		return fmt.Errorf("kind debe ser daily, weekly o monthly")
+	}
+	return nil
+}
+
+// AutoUpdateDue decide si toca disparar (función pura, patrón #761).
+func AutoUpdateDue(st AutoUpdateSettings, lastRunMs int64, now time.Time) bool {
+	if !st.Enabled {
+		return false
+	}
+	switch st.Kind {
+	case AutoDaily:
+		slot := autoTodaySlot(st.Time, now)
+		return !now.Before(slot) && lastRunMs < slot.UnixMilli()
+	case AutoWeekly:
+		dow := 0
+		if st.DayOfWeek != nil {
+			dow = *st.DayOfWeek
+		}
+		if int(now.Weekday()) != dow {
+			return false
+		}
+		slot := autoTodaySlot(st.Time, now)
+		return !now.Before(slot) && lastRunMs < slot.UnixMilli()
+	case AutoMonthly:
+		dom := 1
+		if st.DayOfMonth != nil {
+			dom = *st.DayOfMonth
+		}
+		h, m := autoParseTime(st.Time)
+		slot := time.Date(now.Year(), now.Month(), autoClampDay(dom, now), h, m, 0, 0, now.Location())
+		return !now.Before(slot) && lastRunMs < slot.UnixMilli()
+	}
+	return false
+}
+
+// NextAutoUpdateAt calcula el próximo disparo para la UI.
+func NextAutoUpdateAt(st AutoUpdateSettings, lastRunMs int64, now time.Time) time.Time {
+	h, m := autoParseTime(st.Time)
+	switch st.Kind {
+	case AutoDaily:
+		slot := autoTodaySlot(st.Time, now)
+		if now.Before(slot) || lastRunMs < slot.UnixMilli() {
+			return slot
+		}
+		return slot.AddDate(0, 0, 1)
+	case AutoWeekly:
+		dow := 0
+		if st.DayOfWeek != nil {
+			dow = *st.DayOfWeek
+		}
+		today := autoTodaySlot(st.Time, now)
+		if int(now.Weekday()) == dow && (now.Before(today) || lastRunMs < today.UnixMilli()) {
+			return today
+		}
+		days := (dow - int(now.Weekday()) + 7) % 7
+		if days == 0 {
+			days = 7
+		}
+		d := now.AddDate(0, 0, days)
+		return time.Date(d.Year(), d.Month(), d.Day(), h, m, 0, 0, now.Location())
+	case AutoMonthly:
+		dom := 1
+		if st.DayOfMonth != nil {
+			dom = *st.DayOfMonth
+		}
+		slot := time.Date(now.Year(), now.Month(), autoClampDay(dom, now), h, m, 0, 0, now.Location())
+		if now.Before(slot) || lastRunMs < slot.UnixMilli() {
+			return slot
+		}
+		next := now.AddDate(0, 1, 0)
+		return time.Date(next.Year(), next.Month(), autoClampDay(dom, next), h, m, 0, 0, now.Location())
+	}
+	return time.Time{}
+}
+
+// --- Persistencia kv ---
+
+const autoKvPrefix = "settings.autoupdate."
+
+// LoadAutoUpdateSettings lee los ajustes (defaults sanos).
+func LoadAutoUpdateSettings(db *sql.DB) AutoUpdateSettings {
+	st := AutoUpdateSettings{}
+	if db == nil {
+		return st
+	}
+	st.Enabled = autoKVGet(db, "enabled") == "1"
+	if k := autoKVGet(db, "kind"); validAutoKind(k) {
+		st.Kind = k
+	}
+	st.Time = autoKVGet(db, "time")
+	if v, ok := autoKVIntPtr(db, "dow"); ok {
+		st.DayOfWeek = v
+	}
+	if v, ok := autoKVIntPtr(db, "dom"); ok {
+		st.DayOfMonth = v
+	}
+	return st
+}
+
+// SaveAutoUpdateSettings valida y persiste los ajustes (sin tocar last_run).
+func SaveAutoUpdateSettings(db *sql.DB, st AutoUpdateSettings) error {
+	if db == nil {
+		return fmt.Errorf("autoupdate: sin base de datos")
+	}
+	if err := ValidateAutoUpdate(st); err != nil {
+		return err
+	}
+	setAutoKv(db, "enabled", autoBoolStr(st.Enabled))
+	setAutoKv(db, "kind", st.Kind)
+	setAutoKv(db, "time", st.Time)
+	dow, dom := "", ""
+	if st.DayOfWeek != nil {
+		dow = strconv.Itoa(*st.DayOfWeek)
+	}
+	if st.DayOfMonth != nil {
+		dom = strconv.Itoa(*st.DayOfMonth)
+	}
+	setAutoKv(db, "dow", dow)
+	setAutoKv(db, "dom", dom)
+	return nil
+}
+
+func loadAutoRunState(db *sql.DB) autoRunState {
+	return autoRunState{
+		LastRunMs:  autoKVParseInt(db, "last_run"),
+		LastResult: autoKVGet(db, "last_result"),
+	}
+}
+
+// AutoRunState expone el estado del último disparo (para la UI).
+func AutoRunState(db *sql.DB) (int64, string) {
+	st := loadAutoRunState(db)
+	return st.LastRunMs, st.LastResult
+}
+
+func saveAutoResult(db *sql.DB, result string) {
+	setAutoKv(db, "last_result", result)
+}
+
+// --- helpers locales (patrón speedtest/firmware) ---
+
+func validAutoKind(v string) bool {
+	return v == AutoDaily || v == AutoWeekly || v == AutoMonthly
+}
+
+func validAutoTime(v string) bool {
+	if v == "" {
+		return false
+	}
+	_, err := time.Parse("15:04", v)
+	return err == nil
+}
+
+func autoParseTime(v string) (int, int) {
+	t, err := time.Parse("15:04", v)
+	if err != nil {
+		return 0, 0
+	}
+	return t.Hour(), t.Minute()
+}
+
+func autoTodaySlot(v string, now time.Time) time.Time {
+	h, m := autoParseTime(v)
+	return time.Date(now.Year(), now.Month(), now.Day(), h, m, 0, 0, now.Location())
+}
+
+func autoDaysInMonth(t time.Time) int {
+	return time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, t.Location()).Day()
+}
+
+func autoClampDay(dom int, t time.Time) int {
+	if dom < 1 {
+		dom = 1
+	}
+	if max := autoDaysInMonth(t); dom > max {
+		dom = max
+	}
+	return dom
+}
+
+func autoBoolStr(b bool) string {
+	if b {
+		return "1"
+	}
+	return "0"
+}
+
+func autoKVGet(db *sql.DB, key string) string {
+	var v string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", autoKvPrefix+key).Scan(&v); err != nil {
+		return ""
+	}
+	return v
+}
+
+func autoKVParseInt(db *sql.DB, key string) int64 {
+	n, _ := strconv.ParseInt(autoKVGet(db, key), 10, 64)
+	return n
+}
+
+func autoKVIntPtr(db *sql.DB, key string) (*int, bool) {
+	raw := autoKVGet(db, key)
+	if raw == "" {
+		return nil, false
+	}
+	n, err := strconv.Atoi(raw)
+	if err != nil {
+		return nil, false
+	}
+	return &n, true
+}
+
+func setAutoKv(db *sql.DB, key, val string) {
+	if _, err := db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		autoKvPrefix+key, val); err != nil {
+		log.Printf("[autoupdate] kv set %s: %v", key, err)
+	}
+}
+
+// LatestDeref devuelve status.Latest sin nil-panic (para mensajes).
+func statusLatestDeref(s Status) string {
+	if s.Latest != nil {
+		return *s.Latest
+	}
+	return "?"
+}

+ 182 - 0
server-go/internal/updater/autosched_test.go

@@ -0,0 +1,182 @@
+// autosched_test.go - tests del auto-update programado (#759): vencimiento
+// daily/weekly/monthly, validación, roundtrip kv y disparo con fakes.
+package updater
+
+import (
+	"context"
+	"testing"
+	"time"
+)
+
+func autoIntPtr(v int) *int { return &v }
+
+func TestAutoUpdateDueDaily(t *testing.T) {
+	now := time.Date(2026, 9, 13, 10, 0, 0, 0, time.Local) // domingo
+	slot := time.Date(2026, 9, 13, 3, 30, 0, 0, time.Local)
+	st := AutoUpdateSettings{Enabled: true, Kind: AutoDaily, Time: "03:30"}
+	if !AutoUpdateDue(st, 0, now) {
+		t.Fatalf("slot pasado sin lastRun debe disparar")
+	}
+	if AutoUpdateDue(st, slot.UnixMilli(), now) {
+		t.Fatalf("ya disparado hoy no repite")
+	}
+	if AutoUpdateDue(st, 0, slot.Add(-time.Minute)) {
+		t.Fatalf("antes del slot no dispara")
+	}
+	if AutoUpdateDue(AutoUpdateSettings{Kind: AutoDaily, Time: "03:30"}, 0, now) {
+		t.Fatalf("disabled no dispara")
+	}
+}
+
+func TestAutoUpdateDueWeeklyMonthly(t *testing.T) {
+	now := time.Date(2026, 9, 13, 10, 0, 0, 0, time.Local) // domingo 10:00
+	weekly := AutoUpdateSettings{Enabled: true, Kind: AutoWeekly, DayOfWeek: autoIntPtr(0), Time: "04:00"}
+	if !AutoUpdateDue(weekly, 0, now) {
+		t.Fatalf("domingo despues del slot debe disparar")
+	}
+	weeklyTue := AutoUpdateSettings{Enabled: true, Kind: AutoWeekly, DayOfWeek: autoIntPtr(2), Time: "04:00"}
+	if AutoUpdateDue(weeklyTue, 0, now) {
+		t.Fatalf("otro dia no dispara")
+	}
+	monthly := AutoUpdateSettings{Enabled: true, Kind: AutoMonthly, DayOfMonth: autoIntPtr(13), Time: "04:00"}
+	if !AutoUpdateDue(monthly, 0, now) {
+		t.Fatalf("dia 13 despues del slot debe disparar")
+	}
+	clampFeb := AutoUpdateSettings{Enabled: true, Kind: AutoMonthly, DayOfMonth: autoIntPtr(31), Time: "04:00"}
+	if !AutoUpdateDue(clampFeb, 0, time.Date(2026, 2, 28, 5, 0, 0, 0, time.Local)) {
+		t.Fatalf("clamp 31->28 en febrero dispara")
+	}
+}
+
+func TestValidateAutoUpdate(t *testing.T) {
+	if err := ValidateAutoUpdate(AutoUpdateSettings{Kind: AutoDaily}); err == nil {
+		t.Fatalf("daily sin time falla")
+	}
+	if err := ValidateAutoUpdate(AutoUpdateSettings{Kind: AutoWeekly, DayOfWeek: autoIntPtr(1)}); err == nil {
+		t.Fatalf("weekly sin time falla")
+	}
+	if err := ValidateAutoUpdate(AutoUpdateSettings{Kind: "hourly"}); err == nil {
+		t.Fatalf("kind desconocido falla")
+	}
+	if err := ValidateAutoUpdate(AutoUpdateSettings{Kind: AutoMonthly, DayOfMonth: autoIntPtr(1), Time: "04:00"}); err != nil {
+		t.Fatalf("monthly valido: %v", err)
+	}
+}
+
+func TestAutoUpdateSettingsRoundtrip(t *testing.T) {
+	db := openDB(t)
+	st := AutoUpdateSettings{Enabled: true, Kind: AutoWeekly, DayOfWeek: autoIntPtr(4), Time: "02:15"}
+	if err := SaveAutoUpdateSettings(db, st); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got := LoadAutoUpdateSettings(db)
+	if !got.Enabled || got.Kind != AutoWeekly || got.DayOfWeek == nil || *got.DayOfWeek != 4 || got.Time != "02:15" {
+		t.Fatalf("roundtrip: %+v", got)
+	}
+	if err := SaveAutoUpdateSettings(db, AutoUpdateSettings{Enabled: true, Kind: "nope"}); err == nil {
+		t.Fatalf("guardar basura debe fallar")
+	}
+	if _, r := AutoRunState(db); r != "" {
+		t.Fatalf("sin disparos lastResult vacío, got %q", r)
+	}
+}
+
+// fakeUA: CheckerApplier scripted.
+type fakeUA struct {
+	status    Status
+	applied   int
+	applyRet  bool
+	applyHook func()
+}
+
+func (f *fakeUA) Check(ctx context.Context) Status { return f.status }
+func (f *fakeUA) CanApply() bool                   { return f.status.CanApply }
+func (f *fakeUA) ApplyBy(by string) bool {
+	f.applied++
+	if f.applyHook != nil {
+		f.applyHook()
+	}
+	return f.applyRet
+}
+
+func TestSchedulerShotAppliesWhenDue(t *testing.T) {
+	db := openDB(t)
+	latest := "v9.9.9"
+	ua := &fakeUA{
+		status:   Status{UpdateAvailable: true, CanApply: true, Latest: &latest},
+		applyRet: true,
+	}
+	s := NewScheduler(db, ua)
+	s.now = func() time.Time { return time.Date(2026, 9, 13, 10, 0, 0, 0, time.Local) }
+	_ = AutoUpdateSettings{Enabled: true, Kind: AutoDaily, Time: "03:30"}
+	s.shot(AutoUpdateSettings{}, autoRunState{})
+	if ua.applied != 1 {
+		t.Fatalf("debe aplicar: %d", ua.applied)
+	}
+	if _, res := AutoRunState(db); res != "applied" {
+		t.Fatalf("lastResult: %q", res)
+	}
+	lr, _ := AutoRunState(db)
+	if lr == 0 {
+		t.Fatalf("lastRun debe quedar marcado")
+	}
+}
+
+func TestSchedulerShotCheckFailed(t *testing.T) {
+	// #743: estado rancio tras fetch fallido: NUNCA aplicar sobre él.
+	db := openDB(t)
+	ua := &fakeUA{status: Status{CheckFailed: true, UpdateAvailable: true, CanApply: true}}
+	s := NewScheduler(db, ua)
+	s.shot(AutoUpdateSettings{}, autoRunState{})
+	if ua.applied != 0 {
+		t.Fatalf("check fallido no debe aplicar")
+	}
+	if _, res := AutoRunState(db); res != "check-failed" {
+		t.Fatalf("lastResult: %q", res)
+	}
+}
+
+func TestSchedulerShotUpToDate(t *testing.T) {
+	db := openDB(t)
+	ua := &fakeUA{status: Status{UpdateAvailable: false, CanApply: true}}
+	s := NewScheduler(db, ua)
+	s.shot(AutoUpdateSettings{}, autoRunState{})
+	if ua.applied != 0 {
+		t.Fatalf("sin novedad no aplica")
+	}
+	if _, res := AutoRunState(db); res != "up-to-date" {
+		t.Fatalf("lastResult: %q", res)
+	}
+}
+
+func TestSchedulerTickMarksBeforeApply(t *testing.T) {
+	// El last_run se persiste ANTES del apply: si el proceso muere en el
+	// restart, el arranque posterior no re-dispara el mismo slot.
+	db := openDB(t)
+	latest := "v9.9.9"
+	ua := &fakeUA{
+		status:   Status{UpdateAvailable: true, CanApply: true, Latest: &latest},
+		applyRet: true,
+	}
+	if err := SaveAutoUpdateSettings(db, AutoUpdateSettings{Enabled: true, Kind: AutoDaily, Time: "00:00"}); err != nil {
+		t.Fatal(err)
+	}
+	now := time.Date(2026, 9, 13, 10, 0, 0, 0, time.Local)
+	s := NewScheduler(db, ua)
+	s.now = func() time.Time { return now }
+	// El apply "mata" el proceso: last_run ya debe estar persistido.
+	ua.applyHook = func() {
+		lr, _ := AutoRunState(db)
+		if lr == 0 {
+			t.Errorf("last_run debe persistir ANTES del apply")
+		}
+	}
+	s.tick()
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) && ua.applied == 0 {
+		time.Sleep(10 * time.Millisecond)
+	}
+	if ua.applied != 1 {
+		t.Fatalf("tick con settings vencidos debe aplicar: %d", ua.applied)
+	}
+}