Просмотр исходного кода

feat: dry-run command preview for device writes and an external announcements channel (#756)

* feat(devices): dry-run command preview before applying reservations and blocks (#754)

* feat(announcements): external announcement banner fed from the repo, first notice the netgrip beta program

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
e8363cc4c7

+ 10 - 0
CHANGELOG.md

@@ -7,6 +7,16 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- **Avisos externos para todas las instancias**: el servidor consulta `announcements.json` del repositorio (raw de GitHub, refresco cada 6 h, fail-silent) y expone el aviso vigente en `/api/announcement`; la UI lo pinta con el mismo estilo que el aviso de actualización, con enlace opcional y descarte persistente por identificador. Primer aviso publicado: el programa de beta testers de NetGrip está abierto. Fuente configurable con `NETPULSE_ANNOUNCEMENTS_URL`.
+
+
+### Added
+
+- **Previsualización de los comandos antes de escribir en el router (#754)**: reservar una IP o bloquear un dispositivo ya no aplica directo. Al confirmar la acción, NetPulse pide primero el plan al servidor (`?dry_run=1`: construye los mismos comandos uci sin ejecutarlos) y lo muestra en la ficha del dispositivo -comandos que se ejecutarán y, plegables, los de rollback-, con el router identificado. Nada se aplica hasta pulsar "Ejecutar y aplicar"; desbloquear y eliminar reserva siguen siendo directos. Estilo LuCI "Unsaved Changes", pedido por la comunidad.
+
+
 ### Fixed
 
 - **Fuera las afirmaciones de "solo lectura" aplicadas al producto entero (#751)**: ya no son ciertas (reservas DHCP, bloqueo de dispositivos, orquestación, actualizaciones de firmware escriben en los routers). README, web (metas, JSON-LD, hero, FAQ, tour de funciones, footer, 10 idiomas) y manuales pasan a decir la verdad con el matiz correcto: el sondeo es de solo lectura; lo que escribe es siempre explícito, lo lanza un admin y va con snapshot y rollback. La alerta "firmware disponible" también mentía ("NetPulse es de solo lectura: usa LuCI") y ahora señala a Actualizaciones de firmware.

+ 23 - 0
announcements.json

@@ -0,0 +1,23 @@
+{
+  "announcements": [
+    {
+      "id": "netgrip-beta-2026-09",
+      "urgency": "info",
+      "title": {
+        "es": "Programa de beta testers de NetGrip abierto",
+        "en": "NetGrip beta tester program is open"
+      },
+      "body": {
+        "es": "Buscamos testers para NetGrip, el panel compañero que corre en tu router OpenWrt: toggles de servicios con rollback, clientes, tráfico por aplicación. Estrena sus funciones antes que nadie y ayúdanos a pulirlas.",
+        "en": "We are looking for testers for NetGrip, the companion panel that runs on your OpenWrt router: service toggles with rollback, clients, per-app traffic. Try its features first and help us polish them."
+      },
+      "url": "https://netgrip.cloudless.club",
+      "urlLabel": {
+        "es": "Ver NetGrip",
+        "en": "See NetGrip"
+      },
+      "starts": "2026-09-12",
+      "expires": "2026-11-01"
+    }
+  ]
+}

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

@@ -380,7 +380,11 @@
       "blocked": "Blocked",
       "allowed": "Allowed",
       "block": "Block",
-      "unblock": "Unblock"
+      "unblock": "Unblock",
+      "planTitle": "These commands will run on {{host}}:",
+      "planRollback": "Rollback commands (if anything fails)",
+      "planRun": "Run and apply",
+      "planNone": "Nothing to apply"
     },
     "new": "New",
     "onlyOnline": "Only online",
@@ -2005,5 +2009,9 @@
         "tip": "After a flash only /etc survives: the agent's self-heal restores the binary at boot, and ⟦Reinstall⟧ puts everything fresh if needed."
       }
     }
+  },
+  "announcement": {
+    "link": "See more",
+    "dismiss": "Dismiss announcement"
   }
 }

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

@@ -380,7 +380,11 @@
       "blocked": "Bloqueado",
       "allowed": "Permitido",
       "block": "Bloquear",
-      "unblock": "Desbloquear"
+      "unblock": "Desbloquear",
+      "planTitle": "Estos comandos se ejecutarán en {{host}}:",
+      "planRollback": "Comandos de rollback (si algo falla)",
+      "planRun": "Ejecutar y aplicar",
+      "planNone": "Sin cambios que aplicar"
     },
     "new": "Nuevo",
     "onlyOnline": "Solo online",
@@ -2005,5 +2009,9 @@
         "tip": "Tras un flash solo sobrevive lo de /etc: el self-heal del agente restaura el binario al arrancar, y ⟦Reinstalar⟧ lo deja todo fresco si hiciera falta."
       }
     }
+  },
+  "announcement": {
+    "link": "Ver más",
+    "dismiss": "Descartar aviso"
   }
 }

+ 115 - 0
app/src/components/AnnouncementBanner.tsx

@@ -0,0 +1,115 @@
+/**
+ * AnnouncementBanner — franja de avisos externos (announcements.json del
+ * repo, servida por /api/announcement): mismo estilo que el ribbon de
+ * actualizar. Visible para cualquier sesión; se descarta por id y el
+ * descarte persiste en localStorage.
+ */
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
+import { ExternalLink, Megaphone, X } from 'lucide-react'
+
+const DISMISS_KEY = 'netpulse.announcement.dismissed'
+const POLL_MS = 6 * 60 * 60 * 1000
+
+interface Announcement {
+  id: string
+  urgency?: string
+  title: Record<string, string>
+  body?: Record<string, string>
+  url?: string
+  urlLabel?: Record<string, string>
+}
+
+const pick = (m: Record<string, string> | undefined, lang: string) =>
+  (m && (m[lang] || m.en || m.es || '')) || ''
+
+export function AnnouncementBanner() {
+  const { t, i18n } = useTranslation()
+  const reduce = useReducedMotion()
+  const [a, setA] = useState<Announcement | null>(null)
+  const [dismissed, setDismissed] = useState<string | null>(null)
+
+  const fetchA = useCallback(async () => {
+    try {
+      const res = await fetch('/api/announcement')
+      if (!res.ok) return
+      const json = (await res.json()) as { active: boolean; announcement?: Announcement }
+      setA(json.active && json.announcement ? json.announcement : null)
+    } catch {
+      /* sin aviso */
+    }
+  }, [])
+
+  useEffect(() => {
+    try {
+      setDismissed(localStorage.getItem(DISMISS_KEY))
+    } catch {
+      /* sin localStorage: siempre visible */
+    }
+    void fetchA()
+    const id = window.setInterval(() => void fetchA(), POLL_MS)
+    return () => window.clearInterval(id)
+  }, [fetchA])
+
+  if (!a || a.id === dismissed) return null
+
+  const lang = i18n.language?.startsWith('en') ? 'en' : 'es'
+  const title = pick(a.title, lang)
+  const body = pick(a.body, lang)
+  const urlLabel = pick(a.urlLabel, lang) || t('announcement.link')
+  const warn = a.urgency === 'warn'
+
+  const dismiss = () => {
+    setDismissed(a.id)
+    try {
+      localStorage.setItem(DISMISS_KEY, a.id)
+    } catch {
+      /* sin localStorage: se descarta hasta el refresco */
+    }
+  }
+
+  return (
+    <AnimatePresence>
+      <motion.div
+        initial={reduce ? false : { opacity: 0, y: -8 }}
+        animate={{ opacity: 1, y: 0 }}
+        exit={{ opacity: 0, y: -8 }}
+        transition={{ duration: 0.25, ease: 'easeOut' }}
+        role="status"
+        className="mb-2"
+      >
+        <div
+          className={`flex items-center gap-3 rounded-xl border px-4 py-2.5 ${
+            warn ? 'border-warn/40 bg-warn/10' : 'border-accent/40 bg-accent-soft'
+          }`}
+        >
+          <Megaphone className={`h-4 w-4 shrink-0 ${warn ? 'text-warn' : 'text-accent'}`} strokeWidth={1.75} />
+          <div className="min-w-0 flex-1">
+            {title && <p className="truncate text-sm font-medium text-text-primary">{title}</p>}
+            {body && <p className="text-xs text-text-muted">{body}</p>}
+          </div>
+          {a.url && (
+            <a
+              href={a.url}
+              target="_blank"
+              rel="noreferrer"
+              className="flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs font-semibold text-text-primary transition-colors hover:bg-surface-2"
+            >
+              <ExternalLink className="h-3.5 w-3.5" strokeWidth={2} />
+              <span className="hidden sm:inline">{urlLabel}</span>
+            </a>
+          )}
+          <button
+            type="button"
+            onClick={dismiss}
+            aria-label={t('announcement.dismiss')}
+            className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg text-text-muted transition-colors hover:text-text-primary"
+          >
+            <X className="h-4 w-4" strokeWidth={1.75} />
+          </button>
+        </div>
+      </motion.div>
+    </AnimatePresence>
+  )
+}

+ 115 - 15
app/src/components/DeviceEditSheet.tsx

@@ -39,6 +39,30 @@ export function DeviceEditSheet({
   const [reservation, setReservation] = useState<{ reserved: boolean; ip: string; loading: boolean }>({ reserved: false, ip: '', loading: false })
   const [reserveDraft, setReserveDraft] = useState(device?.ip ?? '')
   const [block, setBlock] = useState<{ blocked: boolean; loading: boolean }>({ blocked: false, loading: false })
+  // #754: dry-run de comandos. Antes de escribir en el router (reservar o
+  // bloquear) se pide el plan al server y se muestra; nada se aplica hasta
+  // la confirmación explícita sobre esos comandos.
+  const [plan, setPlan] = useState<{ host: string; apply: string[]; rollback: string[] } | null>(null)
+  const [planRun, setPlanRun] = useState<null | (() => Promise<void>)>(null)
+  const [planBusy, setPlanBusy] = useState(false)
+
+  const closePlan = () => {
+    setPlan(null)
+    setPlanRun(null)
+  }
+
+  const openPlan = async (path: string, body: unknown, run: () => Promise<void>) => {
+    const sep = path.includes('?') ? '&' : '?'
+    const res = await fetchJson<{ host?: string; apply?: string[]; rollback?: string[] }>(path + sep + 'dry_run=1', {
+      method: 'PUT',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify(body),
+    })
+    if (!res.ok || !res.data) return false
+    setPlan({ host: res.data.host ?? '', apply: res.data.apply ?? [], rollback: res.data.rollback ?? [] })
+    setPlanRun(() => run)
+    return true
+  }
 
   useEffect(() => {
     setIcon(device?.iconOverride ?? '')
@@ -199,13 +223,24 @@ export function DeviceEditSheet({
                   onClick={async () => {
                     if (!device) return
                     setReservation((p) => ({ ...p, loading: true }))
-                    const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/reservation`, {
-                      method: 'PUT',
-                      headers: { 'Content-Type': 'application/json' },
-                      body: JSON.stringify({ ip: reserveDraft, hostname: asDhcpHostname(device.name) }),
-                    })
-                    if (res.ok) {
-                      setReservation({ reserved: true, ip: reserveDraft, loading: false })
+                    const path = `/api/devices/${encodeURIComponent(device.mac)}/reservation`
+                    const body = { ip: reserveDraft, hostname: asDhcpHostname(device.name) }
+                    const applyReserve = async () => {
+                      const res = await fetchJson(path, {
+                        method: 'PUT',
+                        headers: { 'Content-Type': 'application/json' },
+                        body: JSON.stringify(body),
+                      })
+                      if (res.ok) {
+                        setReservation({ reserved: true, ip: reserveDraft, loading: false })
+                      } else {
+                        setReservation((p) => ({ ...p, loading: false }))
+                      }
+                    }
+                    // #754: primero el plan de comandos; se aplica al confirmar.
+                    const planned = await openPlan(path, body, applyReserve)
+                    if (!planned) {
+                      await applyReserve()
                     } else {
                       setReservation((p) => ({ ...p, loading: false }))
                     }
@@ -233,15 +268,40 @@ export function DeviceEditSheet({
                   disabled={block.loading}
                   onClick={async () => {
                     if (!device) return
-                    setBlock((p) => ({ ...p, loading: true }))
                     const url = `/api/devices/${encodeURIComponent(device.mac)}/block`
-                    const res = await fetchJson(url, {
-                      method: block.blocked ? 'DELETE' : 'PUT',
-                      headers: { 'Content-Type': 'application/json' },
-                      body: JSON.stringify({ router: device.routerId }),
-                    })
-                    if (res.ok) {
-                      setBlock({ blocked: !block.blocked, loading: false })
+                    const body = { router: device.routerId }
+                    if (block.blocked) {
+                      // Desbloquear (DELETE): quitar la regla no necesita plan.
+                      setBlock((p) => ({ ...p, loading: true }))
+                      const res = await fetchJson(url, {
+                        method: 'DELETE',
+                        headers: { 'Content-Type': 'application/json' },
+                        body: JSON.stringify(body),
+                      })
+                      if (res.ok) {
+                        setBlock({ blocked: false, loading: false })
+                      } else {
+                        setBlock((p) => ({ ...p, loading: false }))
+                      }
+                      return
+                    }
+                    // Bloquear (#754): plan de comandos primero, aplicar al confirmar.
+                    setBlock((p) => ({ ...p, loading: true }))
+                    const applyBlock = async () => {
+                      const res = await fetchJson(url, {
+                        method: 'PUT',
+                        headers: { 'Content-Type': 'application/json' },
+                        body: JSON.stringify(body),
+                      })
+                      if (res.ok) {
+                        setBlock({ blocked: true, loading: false })
+                      } else {
+                        setBlock((p) => ({ ...p, loading: false }))
+                      }
+                    }
+                    const planned = await openPlan(url, body, applyBlock)
+                    if (!planned) {
+                      await applyBlock()
                     } else {
                       setBlock((p) => ({ ...p, loading: false }))
                     }
@@ -252,6 +312,46 @@ export function DeviceEditSheet({
               </div>
             </div>
 
+            {/* Plan de comandos (#754): nada se aplica hasta confirmar aquí */}
+            {plan && (
+              <div className="space-y-2 rounded-xl border border-warn/40 bg-warn/5 p-3" role="dialog" aria-label={t('devices.edit.planTitle', { host: plan.host })}>
+                <div className="text-label uppercase tracking-wide text-warn">
+                  {t('devices.edit.planTitle', { host: plan.host || device?.routerId || '' })}
+                </div>
+                <pre className="overflow-x-auto rounded-lg border border-border bg-canvas p-2 font-mono text-caption leading-relaxed text-text-primary">
+                  {plan.apply.length ? plan.apply.join('\n') : t('devices.edit.planNone')}
+                </pre>
+                {plan.rollback.length > 0 && (
+                  <details className="text-caption text-text-muted">
+                    <summary className="cursor-pointer select-none">{t('devices.edit.planRollback')}</summary>
+                    <pre className="mt-1 overflow-x-auto rounded-lg border border-border bg-canvas p-2 font-mono text-caption leading-relaxed">
+                      {plan.rollback.join('\n')}
+                    </pre>
+                  </details>
+                )}
+                <div className="flex items-center gap-2">
+                  <Button
+                    size="sm"
+                    disabled={planBusy}
+                    onClick={async () => {
+                      setPlanBusy(true)
+                      try {
+                        await planRun?.()
+                      } finally {
+                        setPlanBusy(false)
+                        closePlan()
+                      }
+                    }}
+                  >
+                    {planBusy ? t('common.loading') : t('devices.edit.planRun')}
+                  </Button>
+                  <Button size="sm" variant="outline" disabled={planBusy} onClick={closePlan}>
+                    {t('common.cancel')}
+                  </Button>
+                </div>
+              </div>
+            )}
+
             {isDemo && (
               <p className="rounded-lg border border-warn/30 bg-warn/10 p-3 text-caption text-warn">
                 {t('devices.edit.demoNotice')}

+ 2 - 0
app/src/components/Layout.tsx

@@ -33,6 +33,7 @@ import { HealthRing } from '@/components/HealthRing'
 import InstallPrompt from '@/components/InstallPrompt'
 import { ThemeToggle } from '@/components/ThemeToggle'
 import { UpdateBanner } from '@/components/UpdateBanner'
+import { AnnouncementBanner } from '@/components/AnnouncementBanner'
 import { UpdateConfirmToast } from '@/components/UpdateConfirmToast'
 import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet'
 import { useIsMobile } from '@/hooks/use-mobile'
@@ -759,6 +760,7 @@ function Shell() {
         <MobileHeader />
         <main className="[view-transition-name:netpulse-content] mx-auto w-full max-w-[1400px] px-4 pb-24 pt-4 md:px-6 md:pb-10 md:pt-6">
           {isDemo && <DemoBanner />}
+          <AnnouncementBanner />
           <UpdateBanner />
           {/* Confirmación post-update (issue #161): toast al cargar si el
               último apply llegó a arrancar con el commit nuevo. */}

+ 148 - 0
server-go/internal/httpapi/announcements.go

@@ -0,0 +1,148 @@
+// announcements.go — avisos externos para todas las instancias: el server
+// consulta announcements.json del repo (raw de GitHub, como hace el updater)
+// y expone el aviso activo en /api/announcement. La UI lo pinta con el
+// estilo del ribbon de actualizar. Override de la fuente con
+// NETPULSE_ANNOUNCEMENTS_URL (pruebas); fail-silent: sin red, sin aviso.
+package httpapi
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"log"
+	"net/http"
+	"os"
+	"sync"
+	"time"
+)
+
+const (
+	defaultAnnouncementsURL = "https://raw.githubusercontent.com/gnacho/netpulse/main/announcements.json"
+	announcementsRefresh    = 6 * time.Hour
+	announcementsTimeout    = 5 * time.Second
+	announcementsMaxBytes   = 64 << 10
+)
+
+// Announcement es un aviso publicado en announcements.json. Title/Body van
+// por idioma (es/en; el cliente cae a en). Starts/Expires ("YYYY-MM-DD",
+// opcionales) delimitan la ventana de vigencia.
+type Announcement struct {
+	ID       string            `json:"id"`
+	Urgency  string            `json:"urgency"` // "info" | "warn"
+	Title    map[string]string `json:"title"`
+	Body     map[string]string `json:"body,omitempty"`
+	URL      string            `json:"url,omitempty"`
+	URLLabel map[string]string `json:"urlLabel,omitempty"`
+	Starts   string            `json:"starts,omitempty"`
+	Expires  string            `json:"expires,omitempty"`
+}
+
+type announcementsFile struct {
+	Announcements []Announcement `json:"announcements"`
+}
+
+type announcementCache struct {
+	mu  sync.Mutex
+	now func() time.Time
+	url string
+	cur *Announcement
+}
+
+func (c *announcementCache) set(a *Announcement) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	c.cur = a
+}
+
+func (c *announcementCache) get() *Announcement {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	return c.cur
+}
+
+// activeAnnouncement elige el primer aviso vigente (starts <= hoy < expires).
+func activeAnnouncement(list []Announcement, now time.Time) *Announcement {
+	today := now.Format("2006-01-02")
+	for i := range list {
+		a := list[i]
+		if a.ID == "" {
+			continue
+		}
+		if a.Starts != "" && today < a.Starts {
+			continue
+		}
+		if a.Expires != "" && today >= a.Expires {
+			continue
+		}
+		return &a
+	}
+	return nil
+}
+
+func fetchAnnouncements(ctx context.Context, url string) (*Announcement, error) {
+	ctx, cancel := context.WithTimeout(ctx, announcementsTimeout)
+	defer cancel()
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+	if err != nil {
+		return nil, err
+	}
+	req.Header.Set("User-Agent", "netpulse-announcements")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("announcements: HTTP %d", res.StatusCode)
+	}
+	var file announcementsFile
+	if err := json.NewDecoder(io.LimitReader(res.Body, announcementsMaxBytes)).Decode(&file); err != nil {
+		return nil, err
+	}
+	return activeAnnouncement(file.Announcements, time.Now()), nil
+}
+
+// startAnnouncements lanza el bucle de refresco (daemon; vive con el server).
+func (s *server) startAnnouncements() {
+	url := defaultAnnouncementsURL
+	if v := os.Getenv("NETPULSE_ANNOUNCEMENTS_URL"); v != "" {
+		url = v
+	}
+	c := &announcementCache{now: time.Now, url: url}
+	s.announcements = c
+	refresh := func() {
+		a, err := fetchAnnouncements(context.Background(), c.url)
+		if err != nil {
+			log.Printf("[netpulse] announcements: fetch falló: %v", err)
+			return
+		}
+		c.set(a)
+	}
+	go func() {
+		refresh()
+		t := time.NewTicker(announcementsRefresh)
+		defer t.Stop()
+		for range t.C {
+			refresh()
+		}
+	}()
+}
+
+func (s *server) registerAnnouncementRoutes(mux *http.ServeMux) {
+	// Sin sesión no hay aviso (igual que el overview); en demo la sesión
+	// pública de la demo lo recibe igual: el aviso va a todas las instancias.
+	mux.HandleFunc("GET /api/announcement", func(w http.ResponseWriter, r *http.Request) {
+		c := s.announcements
+		if c == nil {
+			writeJSON(w, http.StatusOK, map[string]any{"active": false})
+			return
+		}
+		a := c.get()
+		if a == nil {
+			writeJSON(w, http.StatusOK, map[string]any{"active": false})
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"active": true, "announcement": a})
+	})
+}

+ 57 - 0
server-go/internal/httpapi/announcements_test.go

@@ -0,0 +1,57 @@
+// announcements_test.go — avisos externos: selección del aviso vigente
+// (starts/expires) y fetch con servidor de prueba (fail-silent fuera).
+package httpapi
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+	"time"
+)
+
+func TestActiveAnnouncementWindow(t *testing.T) {
+	now := time.Date(2026, 9, 12, 10, 0, 0, 0, time.UTC)
+	list := []Announcement{
+		{ID: "futuro", Starts: "2026-10-01"},
+		{ID: "caducado", Expires: "2026-09-01"},
+		{ID: "sin-ventana", Title: map[string]string{"en": "always"}},
+		{ID: "vigente-con-fin", Starts: "2026-09-01", Expires: "2026-11-01"},
+	}
+	got := activeAnnouncement(list, now)
+	if got == nil || got.ID != "sin-ventana" {
+		t.Fatalf("debe elegir el primero vigente sin ventana: %+v", got)
+	}
+	solo := []Announcement{{ID: "vigente-con-fin", Starts: "2026-09-01", Expires: "2026-11-01"}}
+	if got := activeAnnouncement(solo, now); got == nil || got.ID != "vigente-con-fin" {
+		t.Fatalf("ventana válida debe activarse: %+v", got)
+	}
+	if got := activeAnnouncement(nil, now); got != nil {
+		t.Fatalf("lista vacía: sin aviso, got %+v", got)
+	}
+}
+
+func TestFetchAnnouncementsPicksActive(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		w.Write([]byte(`{"announcements":[{"id":"caducado","expires":"2020-01-01"},{"id":"vivo","title":{"es":"hola","en":"hello"}}]}`))
+	}))
+	defer srv.Close()
+	a, err := fetchAnnouncements(context.Background(), srv.URL)
+	if err != nil {
+		t.Fatalf("fetch: %v", err)
+	}
+	if a == nil || a.ID != "vivo" || a.Title["en"] != "hello" {
+		t.Fatalf("aviso activo incorrecto: %+v", a)
+	}
+}
+
+func TestFetchAnnouncementsFailsSilent(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusInternalServerError)
+	}))
+	defer srv.Close()
+	if _, err := fetchAnnouncements(context.Background(), srv.URL); err == nil {
+		t.Fatal("un 500 debe devolver error (el caller lo traga con log)")
+	}
+}

+ 25 - 0
server-go/internal/httpapi/device_actions.go

@@ -339,6 +339,12 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 		rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
 	}
 
+	// Dry-run (#754): devolver el plan sin ejecutar nada en el router.
+	if r.URL.Query().Get("dry_run") == "1" {
+		writeDevicePlan(w, mac, host, apply, rollback)
+		return
+	}
+
 	if err := s.runUCICommands(host, "dhcp", apply); err != nil {
 		writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
 		return
@@ -353,6 +359,19 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 	writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "ip": body.IP})
 }
 
+// writeDevicePlan responde un dry-run (#754): comandos que SE EJECUTARÍAN
+// (apply) y su plan de vuelta (rollback), sin tocar el router.
+func writeDevicePlan(w http.ResponseWriter, mac, host string, apply, rollback []string) {
+	writeJSON(w, http.StatusOK, map[string]any{
+		"ok":       true,
+		"dryRun":   true,
+		"mac":      mac,
+		"host":     host,
+		"apply":    apply,
+		"rollback": rollback,
+	})
+}
+
 // handleDeviceReservationDelete elimina la reserva DHCP estática.
 func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Request) {
 	mac := normalizeMAC(r.PathValue("mac"))
@@ -563,6 +582,12 @@ func (s *server) handleDeviceBlockPut(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	section := blockRuleSection(mac)
+	// Dry-run (#754): plan sin ejecutar (el check de "ya bloqueado" sí corre:
+	// es lectura uci show, no escribe nada).
+	if r.URL.Query().Get("dry_run") == "1" {
+		writeDevicePlan(w, mac, host, blockRuleApply(section, mac), blockRuleRollback(section))
+		return
+	}
 	if err := s.runUCICommands(host, "firewall", blockRuleApply(section, mac)); err != nil {
 		writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
 		return

+ 86 - 0
server-go/internal/httpapi/device_actions_dryrun_test.go

@@ -0,0 +1,86 @@
+// device_actions_dryrun_test.go — #754: los PUT de reserva y bloqueo con
+// ?dry_run=1 devuelven el plan de comandos SIN ejecutar nada en el router.
+package httpapi_test
+
+import (
+	"strings"
+	"testing"
+)
+
+func TestReservationDryRunPlansWithoutExecuting(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation?dry_run=1", ts.cookie,
+		`{"ip":"192.168.1.60","hostname":"tv-salon"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT dry_run: %d (body %v)", res.StatusCode, decodeBody(t, res))
+	}
+	body := decodeBody(t, res)
+	res.Body.Close()
+
+	if body["dryRun"] != true {
+		t.Fatalf("la respuesta debe ser dryRun: %v", body)
+	}
+	apply, _ := body["apply"].([]any)
+	if len(apply) < 4 {
+		t.Fatalf("plan apply incompleto: %v", apply)
+	}
+	joined := ""
+	for _, c := range apply {
+		if s, ok := c.(string); ok {
+			joined += s + "\n"
+		}
+	}
+	if !strings.Contains(joined, "uci set dhcp.np_host_aabbccddeeff=host") ||
+		!strings.Contains(joined, "uci set dhcp.np_host_aabbccddeeff.ip='192.168.1.60'") {
+		t.Fatalf("apply no contiene la reserva: %v", apply)
+	}
+	rb, _ := body["rollback"].([]any)
+	if len(rb) == 0 || !strings.Contains(rb[0].(string), "uci delete dhcp.np_host_aabbccddeeff") {
+		t.Fatalf("rollback esperado (borrar sección): %v", rb)
+	}
+
+	// NADA se ejecutó: solo la lectura uci show del sondeo de conflictos.
+	for _, forbidden := range []string{"uci set", "uci commit", "uci delete", "/etc/init.d"} {
+		if ssh.saw(forbidden) {
+			t.Fatalf("dry-run ejecutó comandos (%q): %v", forbidden, ssh.cmdsSnapshot())
+		}
+	}
+}
+
+func TestBlockDryRunPlansWithoutExecuting(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/block?dry_run=1", ts.cookie,
+		`{"router":"gateway"}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT block dry_run: %d (body %v)", res.StatusCode, decodeBody(t, res))
+	}
+	body := decodeBody(t, res)
+	res.Body.Close()
+
+	if body["dryRun"] != true {
+		t.Fatalf("la respuesta debe ser dryRun: %v", body)
+	}
+	apply, _ := body["apply"].([]any)
+	if len(apply) == 0 {
+		t.Fatalf("plan apply vacío: %v", apply)
+	}
+	joined := ""
+	for _, c := range apply {
+		if s, ok := c.(string); ok {
+			joined += s + "\n"
+		}
+	}
+	if !strings.Contains(joined, "uci set firewall.np_block_aabbccddeeff=rule") {
+		t.Fatalf("apply no contiene la regla de bloqueo: %v", apply)
+	}
+
+	for _, forbidden := range []string{"uci set", "uci commit", "uci delete", "/etc/init.d"} {
+		if ssh.saw(forbidden) {
+			t.Fatalf("dry-run ejecutó comandos (%q): %v", forbidden, ssh.cmdsSnapshot())
+		}
+	}
+}

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

@@ -160,6 +160,10 @@ type server struct {
 	// (POST /api/backup/run) y el scheduler periódico.
 	backupMu sync.Mutex
 
+	// Avisos externos (announcements.json del repo): caché del último
+	// fetch; nil si el refresco no está activo.
+	announcements *announcementCache
+
 	// rtlConsole (#639): sondeo HTTP de la consola de switches RTLPlayground
 	// (firmware + uptime) para agentes external/beacon. nil si desactivado.
 	rtlConsole *rtlConsoleCache
@@ -452,6 +456,10 @@ func NewHandler(d Deps) http.Handler {
 	// --- Copias de seguridad (issue #158) ---
 	s.registerBackupRoutes(mux)
 
+	// Avisos externos para todas las instancias (siempre: también en demo).
+	s.startAnnouncements()
+	s.registerAnnouncementRoutes(mux)
+
 	// Backups automáticos (#741): el scheduler vive con el handler; el
 	// vencimiento se deriva del last_run persistido, así que reinicios y
 	// auto-updates no resetean el reloj. Solo en live (en demo no hay datos).