Explorar o código

fix: issues #3/#4/#5 — idioma auto, demo desde UI, clientes GL.iNet y layout radial

- #3: idioma por defecto 'auto' (LanguageDetector sigue al navegador);
  selector de Ajustes muestra 'auto' sin elección previa (i18n.ts, Settings.tsx).
- #4: instalación con BD limpia por defecto (sin prompt interactivo);
  POST /api/demo/enable (admin) reescribe DEMO_MODE en .env y toca
  data/.restart-me para reinicio vía systemd.path; DemoCard en Ajustes;
  install.sh instala las units netpulse-restart.path/.service y las limpia
  en --uninstall.
- #5 bug1: clientes GL.iNet sin lease de dnsmasq recibían su IP desde
  'ubus call gl-clients list' (solo clientes online; nunca crea dispositivos
  nuevos). Parser ParseGlClients + GetGlClients + cableado en buildDevices.
- #5 bug2: nodos de distribución con >5 hijos usan anillos concéntricos
  (fan de 136° a radio fijo los solapaba); hueco hacia el router libre.
- install.sh: VERSION ya no queda pisada por /etc/os-release (Debian 13).
- docs: ROADMAP renumerado con fases consecutivas 1-11; tablas de ambos
  README sincronizadas.
- Bump a v2.4.2.
gnacho hai 4 meses
pai
achega
424408954a

+ 6 - 3
README.es.md

@@ -123,9 +123,12 @@ OpenWrt deberían funcionar, pero el tuyo sería el primero en contarlo.
 | **5 — Topología v5** | ✅ | Mapa semántico real: FDB + LLDP en vivo, backhaul, switches gestionados vs. inferidos, hipervisores con sus CTs anidados, collector de series temporales |
 | **6 — Alertas, Push y agente (piloto)** | ✅ | Alertas con 6 categorías y config por categoría (urgente/todo/nada), Web Push nativo (VAPID), refresco bajo demanda, auditoría switch/bridge con canon de datos reconciliado, agente OpenWrt piloto (ingesta con tokens, fallback SSH, procd) |
 | **6.5 — View-model versionado** | ✅ | API como view-model de presentación (`vm: 1`), canon demo single-source en Go → JSON, `Device.infra` sellado server-side, topología semántica en el snapshot, remodel de Preferencias (nombre de saludo, info de sistema real, AdGuard/usuarios/routers simplificados) |
-| **6 inc. 2 — Agente a fondo** | ⏳ | netlink/nl80211 nativo, eventos ubus en tiempo real, paquete `.ipk`, medición en hardware real |
-| **7 — Cliente en el router** | 🔮 | `luci-app-netpulse`: cliente ligero LuCI que consume el view-model versionado (la 6.5 deja la API lista para esto) |
-| **Backlog** | 📋 | Integrar las series del collector en server-go · verificación de push real (FCM) · piloto del agente en los APs reales |
+| **8 — Resiliencia del agente** | ✅ | Watchdog + heartbeat en el router (v2.3.0), rearme manual desde el servidor (v2.4.0), auto-rearme tras TTL (v2.4.0) y rutas de mutación solo-admin (v2.4.1) |
+| **7 — TLS y endurecimiento** | 🔮 | HTTPS en CT 226 (desbloquea Web Push real), HMAC-SHA256 en la ingesta del agente, servir el binario del agente desde el propio servidor |
+| **9 — Agente a fondo** | ⏳ | netlink/nl80211 nativo, eventos ubus en tiempo real, paquete `.ipk`, medición en hardware real |
+| **10 — Cliente en el router** | 🔮 | `luci-app-netpulse`: cliente ligero LuCI que consume el view-model versionado (la 6.5 deja la API lista para esto) |
+| **11 — Escritura/orquestación** | 🔮 | Plan → apply → state (patrón Terraform), `uci` transaccional, allowlist estricta; empieza por AdGuard Home |
+| **Backlog** | 📋 | Integrar las series del collector en server-go · verificación de push real (FCM) · retención de series + informe semanal |
 
 Detalle completo en [docs/ROADMAP.md](docs/ROADMAP.md).
 

+ 6 - 3
README.md

@@ -121,9 +121,12 @@ Other OpenWrt devices should work, but yours would be the first to tell.
 | **5 — Topology v5** | ✅ | Real semantic map: live FDB + LLDP, backhaul, managed vs. inferred switches, hypervisors with nested CTs, time-series collector |
 | **6 — Alerts, Push & agent (pilot)** | ✅ | Alerts with 6 categories and per-category config (urgent/all/none), native Web Push (VAPID), on-demand refresh, switch/bridge audit with reconciled data canon, OpenWrt agent pilot (token ingest, SSH fallback, procd) |
 | **6.5 — Versioned view-model** | ✅ | API as a presentation view-model (`vm: 1`), single-sourced demo canon in Go → JSON, server-stamped `Device.infra`, semantic topology in the snapshot, Settings revamp (greeting name, real system info, streamlined AdGuard/users/routers) |
-| **6 inc. 2 — Agent deep dive** | ⏳ | Native netlink/nl80211, real-time ubus events, `.ipk` package, real-hardware benchmarking |
-| **7 — On-router client** | 🔮 | `luci-app-netpulse`: lightweight LuCI client consuming the versioned view-model (6.5 makes the API ready for this) |
-| **Backlog** | 📋 | Integrate collector series into server-go · real push verification (FCM) · agent pilot on the real APs |
+| **8 — Agent resilience** | ✅ | Router-side watchdog + heartbeat (v2.3.0), server-side manual rearm (v2.4.0), TTL auto-rearm (v2.4.0) and admin-only mutation routes (v2.4.1) |
+| **7 — TLS & hardening** | 🔮 | HTTPS on CT 226 (unlocks real Web Push), HMAC-SHA256 on agent ingest, serve the agent binary from the server itself |
+| **9 — Agent deep dive** | ⏳ | Native netlink/nl80211, real-time ubus events, `.ipk` package, real-hardware benchmarking |
+| **10 — On-router client** | 🔮 | `luci-app-netpulse`: lightweight LuCI client consuming the versioned view-model (6.5 makes the API ready for this) |
+| **11 — Write/orchestration** | 🔮 | Plan → apply → state (Terraform pattern), transactional `uci`, strict allowlist; starts with AdGuard Home |
+| **Backlog** | 📋 | Integrate collector series into server-go · real push verification (FCM) · series retention + weekly availability report |
 
 Full detail in [docs/ROADMAP.md](docs/ROADMAP.md).
 

+ 47 - 0
agent/probe/probe.go

@@ -31,6 +31,10 @@ const (
 	CmdPingGateway = "ping -c 2 -W 2 %s 2>/dev/null | tail -1"
 	CmdDhcpUbus    = "ubus call dhcp ipv4leases"
 	CmdDhcpFile    = "cat /tmp/dhcp.leases 2>/dev/null || true"
+	// CmdGlClients (GL.iNet): base de clientes completa del firmware. Es un
+	// SUPERSET de dhcp.leases: incluye equipos con IP estática o sin lease
+	// DHCP que el dnsmasq del Flint2 no lista (issue #5 bug 1).
+	CmdGlClients = "ubus call gl-clients list 2>/dev/null || true"
 	// CmdIwinfoAssoc: "<mac> <sig> <freq>" por cliente wifi asociado.
 	CmdIwinfoAssoc = `for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do ` +
 		`freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); ` +
@@ -302,6 +306,49 @@ func ParseDhcpLeasesFile(out string) []DhcpLease {
 	return leases
 }
 
+// ParseGlClients parsea la respuesta de `ubus call gl-clients list`
+// (GL.iNet Flint2 y similares): {"clients": {"MAC": {mac, ip, name, online, ...}}}.
+// Error si no es JSON con esa forma. Solo devuelve entradas ONLINE con IP:
+// la base del firmware acumula historial (cientos de entradas) y las offline
+// solo servirían para inflar la lista de dispositivos; los equipos que
+// necesitan resolución de IP son los que están en la red ahora (issue #5
+// bug 1).
+func ParseGlClients(raw []byte) ([]DhcpLease, error) {
+	type clientJSON struct {
+		MAC      string `json:"mac"`
+		IP       string `json:"ip"`
+		Name     string `json:"name"`
+		Hostname string `json:"hostname"`
+		Online   bool   `json:"online"`
+	}
+	var data struct {
+		Clients map[string]clientJSON `json:"clients"`
+	}
+	if err := json.Unmarshal(raw, &data); err != nil {
+		return nil, err
+	}
+	if data.Clients == nil {
+		return nil, fmt.Errorf("gl-clients: sin clave clients")
+	}
+	out := make([]DhcpLease, 0, len(data.Clients))
+	for key, c := range data.Clients {
+		mac := c.MAC
+		if mac == "" {
+			mac = key
+		}
+		if mac == "" || c.IP == "" || !c.Online {
+			continue
+		}
+		hostname := c.Hostname
+		if hostname == "" {
+			hostname = c.Name
+		}
+		out = append(out, DhcpLease{MAC: strings.ToUpper(mac), IP: c.IP, Hostname: hostname})
+	}
+	sort.Slice(out, func(i, j int) bool { return out[i].MAC < out[j].MAC })
+	return out, nil
+}
+
 // ParseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
 func ParseWirelessClients(out string) map[string]WirelessClient {
 	m := map[string]WirelessClient{}

+ 31 - 0
agent/probe/probe_test.go

@@ -92,6 +92,37 @@ func TestParseDhcp(t *testing.T) {
 	}
 }
 
+func TestParseGlClients(t *testing.T) {
+	// Formato real del Flint2: map mac -> objeto con mac/ip/name/online.
+	raw := `{"clients":{
+		"AA:BB:CC:DD:EE:FF":{"mac":"aa:bb:cc:dd:ee:ff","ip":"192.168.8.21","name":"imac","online":true},
+		"11:22:33:44:55:66":{"mac":"11:22:33:44:55:66","ip":"192.168.8.34","name":"","online":true},
+		"22:33:44:55:66:77":{"mac":"22:33:44:55:66:77","ip":"192.168.8.40","name":"viejo","online":false},
+		"33:44:55:66:77:88":{"mac":"33:44:55:66:77:88","ip":"","name":"sinip","online":true}
+	}}`
+	leases, err := ParseGlClients([]byte(raw))
+	if err != nil {
+		t.Fatalf("parse: %v", err)
+	}
+	// Solo deben quedar los ONLINE con IP (2 de 4), ordenados por MAC.
+	if len(leases) != 2 {
+		t.Fatalf("esperadas 2, %d: %+v", len(leases), leases)
+	}
+	if leases[0].MAC != "11:22:33:44:55:66" || leases[0].IP != "192.168.8.34" {
+		t.Fatalf("primera %+v", leases[0])
+	}
+	if leases[1].MAC != "AA:BB:CC:DD:EE:FF" || leases[1].IP != "192.168.8.21" || leases[1].Hostname != "imac" {
+		t.Fatalf("segunda %+v", leases[1])
+	}
+	// Salida vacía / JSON roto no deben dar entradas.
+	if got, err := ParseGlClients([]byte("")); err == nil && len(got) != 0 {
+		t.Fatalf("vacío: %+v", got)
+	}
+	if _, err := ParseGlClients([]byte("not json")); err == nil {
+		t.Fatal("JSON roto debería dar error")
+	}
+}
+
 func TestParseWireless(t *testing.T) {
 	out := "A4:83:E7:21:0B:3C -48 5\nEC:71:DB:44:12:8A -72 2.4\n"
 	m := ParseWirelessClients(out)

+ 2 - 2
app/package-lock.json

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

+ 1 - 1
app/package.json

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

+ 58 - 49
app/public/locales/en/translation.json

@@ -560,6 +560,21 @@
     "accentCyan": "Cyan",
     "accentEmerald": "Emerald",
     "accentViolet": "Violet",
+    "adguard": {
+      "title": "AdGuard Home",
+      "caption": "Connection to the AdGuard API on the GL.iNet router (port 3000)",
+      "host": "Router IP",
+      "user": "GL UI username",
+      "pass": "GL UI password",
+      "passKeep": "Saved (type to change)",
+      "edit": "Edit",
+      "configured": "Configured",
+      "notConfigured": "Not configured",
+      "save": "Save",
+      "saving": "Saving…",
+      "errorGeneric": "Could not save.",
+      "hint": "Port 3000 (fixed on GL.iNet). The password is stored only on the server; NetPulse logs into the GL UI through the router itself (SSH) and queries the API with that session."
+    },
     "appearance": "Appearance",
     "appearanceCaption": "Applies instantly and is remembered on this device",
     "data": {
@@ -582,6 +597,15 @@
       "title": "Data & thresholds",
       "units": "Traffic units"
     },
+    "demo": {
+      "caption": "Explore NetPulse with a sample network without touching your routers",
+      "disable": "Back to live mode",
+      "disableDesc": "The server will restart in live mode, polling your real routers.",
+      "enable": "Load sample data",
+      "enableDesc": "The server will restart and show a sample network (60+ devices). Your routers are untouched.",
+      "restarting": "The server is restarting with the sample network…",
+      "title": "Demo mode"
+    },
     "density": "Density",
     "densityCaption": "Compact reduces paddings and heights ~15%",
     "densityComfy": "Comfortable",
@@ -641,32 +665,6 @@
     },
     "reduceMotion": "Reduce animations",
     "reduceMotionCaption": "Disables pulses, tweens and staggered entrances",
-    "saved": "Preferences saved",
-    "session": {
-      "active": "Active session on this device",
-      "activeCaption": "You will have to enter the password again to sign in.",
-      "logout": "Sign out",
-      "title": "My session",
-      "demoActive": "Demo mode active",
-      "demoCaption": "Local simulated data, no connection to your network.",
-      "exitDemo": "Exit demo mode",
-      "changePassword": "Change my password",
-      "name": "Name",
-      "nameHint": "This is how the Summary greets you; it's not your username",
-      "nameSaved": "Name saved",
-      "pwCurrent": "Current password",
-      "pwNew": "New password",
-      "pwConfirm": "Repeat password",
-      "pwMismatch": "Passwords do not match",
-      "pwSubmit": "Change password",
-      "pwSubmitting": "Changing…",
-      "pwChanged": "Password updated",
-      "pwError": "Could not change password"
-    },
-    "subtitle": "NetPulse local preferences — nothing here modifies your network",
-    "themeDark": "Dark",
-    "themeLight": "Light",
-    "themeSystem": "System",
     "routers": {
       "title": "Routers",
       "caption": "The gateway is auto-detected on boot; add the rest manually",
@@ -695,6 +693,40 @@
       "copy": "Copy",
       "copied": "Copied"
     },
+    "saved": "Preferences saved",
+    "services": {
+      "title": "Services",
+      "caption": "Which services are shown on the dashboard",
+      "adguardCaption": "Filtered DNS on the gateway",
+      "wireguardCaption": "WireGuard VPN tunnels",
+      "openvpnCaption": "OpenVPN tunnels (coming soon)",
+      "note": "Only checked cards are shown. More services coming soon."
+    },
+    "session": {
+      "active": "Active session on this device",
+      "activeCaption": "You will have to enter the password again to sign in.",
+      "logout": "Sign out",
+      "title": "My session",
+      "demoActive": "Demo mode active",
+      "demoCaption": "Local simulated data, no connection to your network.",
+      "exitDemo": "Exit demo mode",
+      "changePassword": "Change my password",
+      "name": "Name",
+      "nameHint": "This is how the Summary greets you; it's not your username",
+      "nameSaved": "Name saved",
+      "pwCurrent": "Current password",
+      "pwNew": "New password",
+      "pwConfirm": "Repeat password",
+      "pwMismatch": "Passwords do not match",
+      "pwSubmit": "Change password",
+      "pwSubmitting": "Changing…",
+      "pwChanged": "Password updated",
+      "pwError": "Could not change password"
+    },
+    "subtitle": "NetPulse local preferences — nothing here modifies your network",
+    "themeDark": "Dark",
+    "themeLight": "Light",
+    "themeSystem": "System",
     "users": {
       "title": "Users",
       "caption": "Who can sign in to NetPulse. Everything else works the same for everyone.",
@@ -715,29 +747,6 @@
       "cancel": "Cancel",
       "newPassword": "New password (min. 6)",
       "savePassword": "Save"
-    },
-    "adguard": {
-      "title": "AdGuard Home",
-      "caption": "Connection to the AdGuard API on the GL.iNet router (port 3000)",
-      "host": "Router IP",
-      "user": "GL UI username",
-      "pass": "GL UI password",
-      "passKeep": "Saved (type to change)",
-      "edit": "Edit",
-      "configured": "Configured",
-      "notConfigured": "Not configured",
-      "save": "Save",
-      "saving": "Saving…",
-      "errorGeneric": "Could not save.",
-      "hint": "Port 3000 (fixed on GL.iNet). The password is stored only on the server; NetPulse logs into the GL UI through the router itself (SSH) and queries the API with that session."
-    },
-    "services": {
-      "title": "Services",
-      "caption": "Which services are shown on the dashboard",
-      "adguardCaption": "Filtered DNS on the gateway",
-      "wireguardCaption": "WireGuard VPN tunnels",
-      "openvpnCaption": "OpenVPN tunnels (coming soon)",
-      "note": "Only checked cards are shown. More services coming soon."
     }
   },
   "statcard": {

+ 58 - 49
app/public/locales/es/translation.json

@@ -560,6 +560,21 @@
     "accentCyan": "Cian",
     "accentEmerald": "Esmeralda",
     "accentViolet": "Violeta",
+    "adguard": {
+      "title": "AdGuard Home",
+      "caption": "Conexión con la API de AdGuard en el router GL.iNet (puerto 3000)",
+      "host": "IP del router",
+      "user": "Usuario de la interfaz GL",
+      "pass": "Contraseña de la interfaz GL",
+      "passKeep": "Guardada (escribe para cambiar)",
+      "edit": "Editar",
+      "configured": "Configurado",
+      "notConfigured": "Sin configurar",
+      "save": "Guardar",
+      "saving": "Guardando…",
+      "errorGeneric": "No se pudo guardar.",
+      "hint": "Puerto 3000 (fijo en GL.iNet). La contraseña se guarda solo en el servidor; NetPulse inicia sesión en la UI GL a través del propio router (SSH) y consulta la API con esa sesión."
+    },
     "appearance": "Apariencia",
     "appearanceCaption": "Se aplica al instante y se recuerda en este dispositivo",
     "data": {
@@ -582,6 +597,15 @@
       "title": "Datos y umbrales",
       "units": "Unidades de tráfico"
     },
+    "demo": {
+      "caption": "Explora NetPulse con una red de ejemplo sin tocar tus routers",
+      "disable": "Volver al modo live",
+      "disableDesc": "El servidor se reiniciará en modo live, sondeando tus routers reales.",
+      "enable": "Cargar datos de ejemplo",
+      "enableDesc": "El servidor se reiniciará y mostrará una red de ejemplo (60+ dispositivos). Tus routers no se tocan.",
+      "restarting": "El servidor se está reiniciando con la red de ejemplo…",
+      "title": "Modo demo"
+    },
     "density": "Densidad",
     "densityCaption": "Compacta reduce paddings y alturas ~15 %",
     "densityComfy": "Cómoda",
@@ -641,32 +665,6 @@
     },
     "reduceMotion": "Reducir animaciones",
     "reduceMotionCaption": "Desactiva pulsos, tweens y entradas escalonadas",
-    "saved": "Preferencias guardadas",
-    "session": {
-      "active": "Sesión activa en este dispositivo",
-      "activeCaption": "Tendrás que volver a introducir la contraseña para entrar.",
-      "logout": "Cerrar sesión",
-      "title": "Mi sesión",
-      "demoActive": "Modo demo activo",
-      "demoCaption": "Datos simulados locales, sin conexión a tu red.",
-      "exitDemo": "Salir del modo demo",
-      "changePassword": "Cambiar mi contraseña",
-      "name": "Nombre",
-      "nameHint": "Así te saluda el Resumen; no es tu nombre de usuario",
-      "nameSaved": "Nombre guardado",
-      "pwCurrent": "Contraseña actual",
-      "pwNew": "Nueva contraseña",
-      "pwConfirm": "Repite la contraseña",
-      "pwMismatch": "Las contraseñas no coinciden",
-      "pwSubmit": "Cambiar contraseña",
-      "pwSubmitting": "Cambiando…",
-      "pwChanged": "Contraseña actualizada",
-      "pwError": "No se pudo cambiar la contraseña"
-    },
-    "subtitle": "Preferencias locales de NetPulse — nada aquí modifica tu red",
-    "themeDark": "Oscuro",
-    "themeLight": "Claro",
-    "themeSystem": "Sistema",
     "routers": {
       "title": "Routers",
       "caption": "La puerta de enlace se autodetecta en el arranque; añade el resto a mano",
@@ -695,6 +693,40 @@
       "copy": "Copiar",
       "copied": "Copiada"
     },
+    "saved": "Preferencias guardadas",
+    "services": {
+      "title": "Servicios",
+      "caption": "Qué servicios se muestran en el panel",
+      "adguardCaption": "DNS filtrado en el gateway",
+      "wireguardCaption": "Túneles VPN WireGuard",
+      "openvpnCaption": "Túneles VPN OpenVPN (próximamente)",
+      "note": "Solo se muestran las tarjetas marcadas. Más servicios próximamente."
+    },
+    "session": {
+      "active": "Sesión activa en este dispositivo",
+      "activeCaption": "Tendrás que volver a introducir la contraseña para entrar.",
+      "logout": "Cerrar sesión",
+      "title": "Mi sesión",
+      "demoActive": "Modo demo activo",
+      "demoCaption": "Datos simulados locales, sin conexión a tu red.",
+      "exitDemo": "Salir del modo demo",
+      "changePassword": "Cambiar mi contraseña",
+      "name": "Nombre",
+      "nameHint": "Así te saluda el Resumen; no es tu nombre de usuario",
+      "nameSaved": "Nombre guardado",
+      "pwCurrent": "Contraseña actual",
+      "pwNew": "Nueva contraseña",
+      "pwConfirm": "Repite la contraseña",
+      "pwMismatch": "Las contraseñas no coinciden",
+      "pwSubmit": "Cambiar contraseña",
+      "pwSubmitting": "Cambiando…",
+      "pwChanged": "Contraseña actualizada",
+      "pwError": "No se pudo cambiar la contraseña"
+    },
+    "subtitle": "Preferencias locales de NetPulse — nada aquí modifica tu red",
+    "themeDark": "Oscuro",
+    "themeLight": "Claro",
+    "themeSystem": "Sistema",
     "users": {
       "title": "Usuarios",
       "caption": "Quién puede entrar en NetPulse. El resto de funciones es igual para todos.",
@@ -715,29 +747,6 @@
       "cancel": "Cancelar",
       "newPassword": "Nueva contraseña (mín. 6)",
       "savePassword": "Guardar"
-    },
-    "adguard": {
-      "title": "AdGuard Home",
-      "caption": "Conexión con la API de AdGuard en el router GL.iNet (puerto 3000)",
-      "host": "IP del router",
-      "user": "Usuario de la interfaz GL",
-      "pass": "Contraseña de la interfaz GL",
-      "passKeep": "Guardada (escribe para cambiar)",
-      "edit": "Editar",
-      "configured": "Configurado",
-      "notConfigured": "Sin configurar",
-      "save": "Guardar",
-      "saving": "Guardando…",
-      "errorGeneric": "No se pudo guardar.",
-      "hint": "Puerto 3000 (fijo en GL.iNet). La contraseña se guarda solo en el servidor; NetPulse inicia sesión en la UI GL a través del propio router (SSH) y consulta la API con esa sesión."
-    },
-    "services": {
-      "title": "Servicios",
-      "caption": "Qué servicios se muestran en el panel",
-      "adguardCaption": "DNS filtrado en el gateway",
-      "wireguardCaption": "Túneles VPN WireGuard",
-      "openvpnCaption": "Túneles VPN OpenVPN (próximamente)",
-      "note": "Solo se muestran las tarjetas marcadas. Más servicios próximamente."
     }
   },
   "statcard": {

+ 26 - 2
app/src/components/topology/model.ts

@@ -241,6 +241,14 @@ const GW_EAST_FAN: [number, number] = [336, 24] // wrap (a1 < a0)
 const GW_WEST_FAN: [number, number] = [150, 210]
 const AP_WIRED_FAN: [number, number] = [50, 130]
 const DIST_FAN_RADIUS = 82
+/** distnodes: hasta DIST_FAN_MAX hijos en abanico de 136°; con más, el arco
+ *  de radio fijo los amontona (issue #5 bug 2: 8 bocas tras un switch en el
+ *  mismo puerto) → anillos concéntricos alrededor del círculo dashed. */
+const DIST_FAN_MAX = 5
+const DIST_RINGS = [
+  { r: 62, cap: 7 },
+  { r: 104, cap: 12 },
+]
 const HUB_FAN_RADIUS = 56
 const ROUTER_FAN_RADIUS = 134
 /** Hosts hipervisores del gateway: lejos (su grid de CTs necesita espacio) */
@@ -587,12 +595,28 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   }
   chips.push(...hubChips)
 
-  // hijos de distnodes inferidos: abanico alrededor del círculo dashed
+  // hijos de distnodes inferidos: hasta DIST_FAN_MAX en abanico de 136°; con
+  // más, anillos concéntricos (el arco único los solapa — issue #5 bug 2).
   for (const dv of distNodes) {
     const kids = childrenOf(dv.id).map((d) => mkChip(d, dv.id))
     const rn = routerById.get(dv.node.routerId)
     const center = rn ? angleTo(rn.x, rn.y, dv.x, dv.y) : 0
-    fanLayout(kids, dv, DIST_FAN_RADIUS, center - 68, center + 68)
+    if (kids.length > DIST_FAN_MAX) {
+      // anillos alrededor del círculo dashed: se excluye el sector hacia el
+      // router (por donde entra el enlace dist-*) para que las líneas no
+      // crucen los chips
+      const excludes = rn ? arcAround(angleTo(dv.x, dv.y, rn.x, rn.y), 20) : []
+      const rings = [...DIST_RINGS]
+      let cap = rings.reduce((a, r) => a + r.cap, 0)
+      while (cap < kids.length) {
+        const last = rings[rings.length - 1]
+        rings.push({ r: last.r + 34, cap: last.cap + 5 })
+        cap = rings.reduce((a, r) => a + r.cap, 0)
+      }
+      ringLayout(kids, dv, rings, excludes)
+    } else {
+      fanLayout(kids, dv, DIST_FAN_RADIUS, center - 68, center + 68)
+    }
     chips.push(...kids)
   }
 

+ 8 - 5
app/src/i18n.ts

@@ -3,8 +3,10 @@ import { initReactI18next } from 'react-i18next'
 import LanguageDetector from 'i18next-browser-languagedetector'
 import HttpBackend from 'i18next-http-backend'
 
-// 'auto' => seguir al navegador: no debe quedar idioma cacheado en localStorage
-if (localStorage.getItem('netpulse-lang') === 'auto') {
+// 'auto' (o sin elección previa) => seguir al navegador: no debe quedar
+// idioma cacheado en localStorage por el detector
+const savedLang = localStorage.getItem('netpulse-lang')
+if (!savedLang || savedLang === 'auto') {
   localStorage.removeItem('i18nextLng')
 }
 
@@ -13,9 +15,10 @@ i18n
   .use(LanguageDetector)
   .use(initReactI18next)
   .init({
-    // Inglés por defecto salvo elección previa (español opcional en Ajustes;
-    // la opción 'auto' sigue al navegador vía detector manual)
-    lng: localStorage.getItem('i18nextLng') ?? 'en',
+    // Sin elección previa NO se fija idioma: el LanguageDetector resuelve
+    // desde el navegador (orden localStorage → navigator). 'en' queda solo
+    // como fallback para locales no soportados. (issue #3)
+    lng: localStorage.getItem('i18nextLng') ?? undefined,
     fallbackLng: 'en',
     supportedLngs: ['es', 'en'],
     nonExplicitSupportedLngs: true,

+ 97 - 2
app/src/pages/Settings.tsx

@@ -10,6 +10,7 @@ import {
   Copy,
   Download,
   FileText,
+  FlaskConical,
   Github,
   Heart,
   KeyRound,
@@ -1420,6 +1421,92 @@ function PushNotificationsCard({ reduce, onSaved }: { reduce: boolean; onSaved:
   )
 }
 
+// ---------------------------------------------------------------------------
+// Modo demo (issue #4): activar/desactivar desde la UI sin reinstalar.
+// El instalador ya no pregunta por demo (default BD limpia); este card es la
+// vía de explorarla después. Solo visible para admin con backend real (en el
+// demo local sin backend no hay .env que tocar).
+// ---------------------------------------------------------------------------
+function DemoCard({ reduce, onSaved }: { reduce: boolean; onSaved: () => void }) {
+  const { t } = useTranslation()
+  const [serverMode, setServerMode] = useState<'demo' | 'live' | null>(null)
+  const [busy, setBusy] = useState(false)
+  const [error, setError] = useState<string | null>(null)
+
+  useEffect(() => {
+    void (async () => {
+      try {
+        const res = await fetch('/api/health', { signal: AbortSignal.timeout(3000) })
+        if (!res.ok) return
+        const json = (await res.json()) as { mode?: string }
+        if (json.mode === 'demo' || json.mode === 'live') setServerMode(json.mode)
+      } catch {
+        /* sin backend: el card no se muestra */
+      }
+    })()
+  }, [])
+
+  const switchMode = useCallback(
+    async (enable: boolean) => {
+      if (busy) return
+      setBusy(true)
+      setError(null)
+      try {
+        const res = await fetch('/api/demo/enable', {
+          method: 'POST',
+          headers: { 'Content-Type': 'application/json' },
+          body: JSON.stringify({ enable }),
+          signal: AbortSignal.timeout(15_000),
+        })
+        if (!res.ok) {
+          setError(`${t('settings.demo.title')} — HTTP ${res.status}`)
+          setBusy(false)
+          return
+        }
+        onSaved()
+        // El servidor se está reiniciando (flag .restart-me → systemd.path).
+        // Recargar en unos segundos para recoger el nuevo modo.
+        window.setTimeout(() => window.location.reload(), 6000)
+      } catch {
+        setError(`${t('settings.demo.title')} — fetch error`)
+        setBusy(false)
+      }
+    },
+    [busy, onSaved, t],
+  )
+
+  if (serverMode === null) return null
+
+  const enabling = serverMode === 'live'
+  return (
+    <Card title={t('settings.demo.title')} caption={t('settings.demo.caption')} index={5} reduce={reduce}>
+      <div className="flex flex-col gap-3">
+        <p className="text-caption leading-relaxed text-text-muted">
+          {enabling ? t('settings.demo.enableDesc') : t('settings.demo.disableDesc')}
+        </p>
+        {busy ? (
+          <div className="flex items-center gap-2 rounded-xl bg-elevated px-3.5 py-2.5 text-caption text-text-secondary">
+            <span className="relative flex h-2 w-2">
+              <span className="absolute inline-flex h-full w-full animate-ping-soft rounded-full bg-accent opacity-75" />
+              <span className="relative inline-flex h-2 w-2 rounded-full bg-accent" />
+            </span>
+            {t('settings.demo.restarting')}
+          </div>
+        ) : (
+          <button
+            onClick={() => void switchMode(enabling)}
+            className="inline-flex w-fit items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+          >
+            <FlaskConical className="h-4 w-4" strokeWidth={1.75} />
+            {enabling ? t('settings.demo.enable') : t('settings.demo.disable')}
+          </button>
+        )}
+        {error && <p className="text-caption text-red-500">{error}</p>}
+      </div>
+    </Card>
+  )
+}
+
 // ---------------------------------------------------------------------------
 // Página Ajustes `/settings` (settings.md)
 // ---------------------------------------------------------------------------
@@ -1432,10 +1519,10 @@ export default function Settings() {
   // SPEC-65 D65-7c: la tarjeta AdGuard entera desaparece si el servicio está oculto
   const [services] = useServicesVisibility()
 
-  // ——— Idioma ('en' por defecto; 'auto' sigue al navegador; persistido) ———
+  // ——— Idioma ('auto' por defecto sigue al navegador; elección explícita persistida) ———
   const [lang, setLang] = useState<'auto' | 'es' | 'en'>(() => {
     const raw = localStorage.getItem('netpulse-lang')
-    return raw === 'es' || raw === 'en' || raw === 'auto' ? raw : 'en'
+    return raw === 'es' || raw === 'en' || raw === 'auto' ? raw : 'auto'
   })
   const setLanguage = useCallback((v: 'auto' | 'es' | 'en') => {
     setLang(v)
@@ -2084,6 +2171,14 @@ export default function Settings() {
           </div>
         )}
 
+        {/* Modo demo (issue #4): activar/desactivar desde la UI. Solo admin;
+            el card se oculta solo si no hay backend real (demo local). */}
+        {!isDemo && auth?.role === 'admin' && (
+          <div className="lg:col-span-5">
+            <DemoCard reduce={reduce} onSaved={notify} />
+          </div>
+        )}
+
         {/* AdGuard Home (GL.iNet) — solo admin, modo live y servicio visible */}
         {!isDemo && auth?.role === 'admin' && services.adguard && (
           <div className="lg:col-span-12">

+ 23 - 15
docs/ROADMAP.md

@@ -1,12 +1,14 @@
 # NetPulse — Hoja de ruta
 
-> Actualizada: 2026-08-04 (v2.4.1: endurecimiento de permisos — rutas de
-> agentes/rearme/gestión de routers exigen rol admin; auditoría §2, issue #7).
-> Orden por dependencias: lo bloqueante primero.
+> Actualizada: 2026-08-04 (v2.4.2: issues #3/#4/#5 — idioma auto, BD limpia
+> por defecto con demo activable desde la UI, clientes GL.iNet sin lease y
+> layout radial en topología).
+> Fases consecutivas desde la 1; la numeración antigua (0, 6.1, 6, 7, 8) se
+> reasignó en orden de dependencias: lo bloqueante primero.
 > Referencias: `docs/AUDITORIA-FASE65.md` (riesgos R1-R8),
 > `docs/AGENTE-OPENWRT.md` (diseño del agente), ARCHITECTURE.md.
 
-## Estado actual (v2.2.0)
+## Estado actual (v2.4.2)
 
 Hecho y en producción (CT 226):
 - Fases 1-5: monitorización SSH agentless, AdGuard/WireGuard, topología,
@@ -16,7 +18,13 @@ Hecho y en producción (CT 226):
   categorías.
 - Fase 6.5: view-model semántico (`vm: 1`), `Device.infra`, displayName,
   `/api/system/info`.
-- Fixes recientes: pantalla negra tras update (cache + reload racing + guard),
+- Fase 8: resiliencia del agente (v2.3.0), rearme manual (v2.4.0),
+  auto-rearme (v2.4.0) y endurecimiento de permisos (v2.4.1).
+- Fixes v2.4.2: idioma por defecto "auto" (sigue al navegador, issue #3);
+  instalación con BD limpia y demo activable desde Ajustes (issue #4);
+  IPs de clientes GL.iNet vía `gl-clients` donde dnsmasq no tiene lease y
+  layout en anillos para nodos de distribución con muchos hijos (issue #5).
+- Fixes previos: pantalla negra tras update (cache + reload racing + guard),
   `-X main.Version` en el build del agente, `scp -O` para dropbear.
 
 Dormido en producción (implementado pero sin efecto real):
@@ -26,9 +34,9 @@ Dormido en producción (implementado pero sin efecto real):
   aportan tiempo real; y reportan versión 0.1.0 hasta reinstalarlos con la
   próxima release.
 
-## Fase 0 — TLS y endurecimiento (BLOQUEANTE, ~1 día)
+## Fase 7 — TLS y endurecimiento (BLOQUEANTE, ~1 día)
 
-Sin esto, ni push funciona ni la Fase 8 es segura.
+Sin esto, ni push funciona ni la Fase 11 es segura.
 
 1. **HTTPS en CT 226** (R1): Caddy delante con cert autofirmado + confianza
    manual, o Tailscale Serve (HTTPS automático). Desbloquea Web Push real y
@@ -36,14 +44,14 @@ Sin esto, ni push funciona ni la Fase 8 es segura.
    Decisión pendiente: Caddy vs Tailscale (afecta a cómo confiarán los
    routers en el cert cuando ellos también empujen con TLS).
 2. **HMAC-SHA256 en la ingesta del agente** (R4): firmar el payload con el
-   token. ~10 líneas. Barato ahora, carísimo después de la Fase 8.
+   token. ~10 líneas. Barato ahora, carísimo después de la Fase 11.
 3. **Reinstalar agentes con release nueva** para que reporten versión real
    (el fix `-X main.Version` ya está en goreleaser).
 4. **Servir el binario del agente desde el propio servidor** (R3):
    `GET /api/agents/{slug}/binary?arch=...` — elimina la dependencia de
    GitHub en LANs sin salida y el `curl | sh` con token en argv.
 
-## Fase 6.1 — resiliencia del agente (hecha, v2.3.0) + auto-rearme (v2.4.0)
+## Fase 8 — resiliencia del agente (hecha: v2.3.0, v2.4.0, v2.4.1)
 
 Cierre de los dos huecos de supervisión detectados en la auditoría del piloto:
 
@@ -58,7 +66,7 @@ Cierre de los dos huecos de supervisión detectados en la auditoría del piloto:
    botón «Rearmar» en la cabecera del router (solo agente caído).
 3. **Auto-rearme tras TTL (v2.4.0):** supervisor en el servidor (cada 30 s)
    que rearma automáticamente los agentes cuyo último push expiró (TTL 90 s).
-   Detrás de flag `NETPULSE_AUTO_REARM=1` (opt-in, regla Fase 8: nada
+   Detrás de flag `NETPULSE_AUTO_REARM=1` (opt-in, regla Fase 11: nada
    autónomo sobre red sin confirmación). Cooldown largo por slug
    (`NETPULSE_AUTO_REARM_COOLDOWN_S`, default 600 s); solo rearma slugs con
    token registrado y push previo (nunca un slug que no ha empujado jamás);
@@ -74,7 +82,7 @@ Cierre de los dos huecos de supervisión detectados en la auditoría del piloto:
    se ocultan a usuarios no admin. Cierra el punto §2 de la auditoría
    (issue #7); el resto de la auditoría vive en el issue #6.
 
-## Fase 6 — incremento 2: el agente de verdad (~1 semana)
+## Fase 9 — el agente de verdad (~1 semana)
 
 El piloto actual ahorra SSH pero no da tiempo real. El salto es:
 
@@ -86,14 +94,14 @@ El piloto actual ahorra SSH pero no da tiempo real. El salto es:
    instalador actual queda como fallback.
 4. Medición en hardware real (RAM/CPU/flash) y ajuste de intervalos.
 
-## Fase 7 — app embebida en routers (decisión de diseño primero)
+## Fase 10 — app embebida en routers (decisión de diseño primero)
 
 Convertir NetPulse en una app DEL router, no solo un panel externo:
 
 - **Arquitectura objetivo**: el Flint 2 (gateway, 8 GB) corre
   `netpulse-agent` + `netpulse-server` reducido (modo on-box); los APs solo
   agent. La URL de la app ES la IP del router.
-- **Bloqueantes previos**: decisión TLS de la Fase 0 (la app servida por el
+- **Bloqueantes previos**: decisión TLS de la Fase 7 (la app servida por el
   router necesita cert autofirmado + flujo "confiar") y DB fuera de NAND
   (SQLite WAL en flash = inviable; usar USB/eMMC/overlay).
 - **Pairing cero-fricción**: token de emparejamiento mostrado en LuCI
@@ -102,7 +110,7 @@ Convertir NetPulse en una app DEL router, no solo un panel externo:
 - Presupuesto: server-go hoy = 20 MB RSS / 14,4 MB binario → sobra en el
   gateway; en APs (512 MB) nunca debe correr el server.
 
-## Fase 8 — escritura/orquestación (riesgo alto, reglas estrictas)
+## Fase 11 — escritura/orquestación (riesgo alto, reglas estrictas)
 
 Pasar de leer a actuar. Reglas de diseño innegociables
 (detalle en AUDITORIA-FASE65.md §5):
@@ -112,7 +120,7 @@ Pasar de leer a actuar. Reglas de diseño innegociables
   rollback verificable obligatorio.
 - Idempotencia (estado declarado, no acumulado).
 - Ejecutor con allowlist estricta de comandos (nada de shell libre).
-- HMAC (Fase 0) firmado ANTES de que viaje ninguna orden.
+- HMAC (Fase 7) firmado ANTES de que viaje ninguna orden.
 
 Orden por riesgo/beneficio:
 1. **AdGuard Home** (fácil: binario + YAML + DNS en dnsmasq; el módulo de

+ 38 - 6
install.sh

@@ -112,6 +112,12 @@ if [ "$UNINSTALL" -eq 1 ]; then
         run $SUDO systemctl stop "$SERVICE_NAME" 2>/dev/null || true
         run $SUDO systemctl disable "$SERVICE_NAME" 2>/dev/null || true
         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 rm -f "/etc/systemd/system/$SERVICE_NAME-restart.path" \
+                "/etc/systemd/system/$SERVICE_NAME-restart.service"
+        fi
         run $SUDO systemctl daemon-reload
         ok "systemd unit removed"
     fi
@@ -132,7 +138,12 @@ if [ "$UNINSTALL" -eq 1 ]; then
 fi
 
 # --------------------------------------------------------------- detection --
+# /etc/os-release define su propia VERSION ("13 (trixie)" en Debian) y pisaría
+# la variable VERSION del script; guardar y restaurar alrededor del source.
+_saved_version="$VERSION"
 . /etc/os-release 2>/dev/null || true
+VERSION="$_saved_version"
+unset _saved_version
 OS_PRETTY="${PRETTY_NAME:-$(uname -s)}"
 
 ARCH=$(uname -m)
@@ -226,12 +237,9 @@ if [ ! -f "$STATE_DIR/.env" ]; then
     fi
 fi
 
-# Demo mode: --demo flag, or ask interactively on fresh installs.
-if [ ! -f "$STATE_DIR/.env" ] && [ "$DEMO" -eq 0 ]; then
-    if ask_yes_no "Install in DEMO mode first? (sample network with 60+ devices to explore; you can switch to your real routers later)" 0; then
-        DEMO=1
-    fi
-fi
+# Demo mode (issue #4): solo con --demo explícito. El default es BD limpia;
+# la demo se activa después desde Ajustes (el botón llama a
+# POST /api/demo/enable y reinicia el servicio vía .restart-me).
 
 # --------------------------------------------------------- resolve version --
 if [ -z "$VERSION" ]; then
@@ -349,11 +357,35 @@ UMask=007
 
 [Install]
 WantedBy=multi-user.target
+EOF
+
+    # Unidad de reinicio bajo demanda (issue #4 + updater): una unit .path
+    # vigila $STATE_DIR/data/.restart-me; cuando el servidor lo toca (p.ej.
+    # POST /api/demo/enable) este oneshot lo borra y reinicia el servicio.
+    $SUDO tee "/etc/systemd/system/$SERVICE_NAME-restart.path" >/dev/null <<EOF
+[Unit]
+Description=Reinicia $SERVICE_NAME cuando el servidor toca .restart-me
+
+[Path]
+PathChanged=$STATE_DIR/data/.restart-me
+
+[Install]
+WantedBy=multi-user.target
+EOF
+    $SUDO tee "/etc/systemd/system/$SERVICE_NAME-restart.service" >/dev/null <<EOF
+[Unit]
+Description=Reinicio de $SERVICE_NAME solicitado por el servidor
+
+[Service]
+Type=oneshot
+ExecStart=/bin/sh -c "rm -f $STATE_DIR/data/.restart-me; /bin/systemctl restart $SERVICE_NAME.service"
 EOF
 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)"
 
 if [ "$DRY_RUN" -eq 0 ]; then
     sleep 3

+ 26 - 1
server-go/internal/adapters/live.go

@@ -68,6 +68,10 @@ type routerPolled struct {
 	uptimeSec float64
 	net       *NetDevBps
 	leases    []DhcpLease
+	// glClients (GL.iNet): base de clientes del firmware, superset de las
+	// leases. Se usa SOLO para resolver IPs de dispositivos ya conocidos que
+	// salen sin IP (dnsmasq sin lease), nunca para crear dispositivos nuevos.
+	glClients []DhcpLease
 	wireless  map[string]WirelessClient
 	ports     []EthPort
 	radios    []Radio
@@ -461,6 +465,10 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		net = &NetDevBps{}
 	}
 	leases := client.GetDhcpLeases()
+	// gl-clients (GL.iNet): complementa la resolución de IP donde dnsmasq no
+	// tiene lease (issue #5 bug 1). En routers sin el objeto ubus sale vacío
+	// — coste: una llamada ubus local por poll.
+	glClients := client.GetGlClients()
 	wireless := client.GetWirelessClients()
 	ports := client.GetEthPorts(layout)
 	radios := client.GetRadios()
@@ -535,7 +543,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	return &routerPolled{
 		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
 		cpu: cpuV, ram: ramPct, temp: tempV,
-		uptimeSec: sysInfo.Uptime, net: net, leases: leases,
+		uptimeSec: sysInfo.Uptime, net: net, leases: leases, glClients: glClients,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp,
@@ -918,12 +926,21 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 // FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
 func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	leasesByMac := map[string]DhcpLease{}
+	glByMac := map[string]DhcpLease{}
 	for _, p := range polled {
 		for _, le := range p.leases {
 			if le.MAC != "" {
 				leasesByMac[le.MAC] = le
 			}
 		}
+		// gl-clients: fallback de IP para MACs sin lease (dnsmasq sin ese
+		// cliente). No crea dispositivos: solo enriquece los ya resueltos
+		// por wireless/FDB (issue #5 bug 1).
+		for _, le := range p.glClients {
+			if le.MAC != "" && le.IP != "" {
+				glByMac[le.MAC] = le
+			}
+		}
 	}
 	type knownInfo struct {
 		routerID string
@@ -1040,6 +1057,14 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			d.IP = lease.IP
 		} else {
 			d.Name = mac
+			// Fallback gl-clients (GL.iNet): el cliente no tiene lease pero el
+			// firmware sí conoce su IP (y a veces nombre). (issue #5 bug 1)
+			if gl, ok := glByMac[mac]; ok {
+				d.IP = gl.IP
+				if gl.Hostname != "" {
+					d.Name = gl.Hostname
+				}
+			}
 		}
 		// Tipo estimado por hostname (el DHCP/FDB no dice qué es el cliente).
 		// Con nombre-MAC (sin hostname) queda "desconocido".

+ 18 - 0
server-go/internal/adapters/openwrt.go

@@ -325,6 +325,24 @@ func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
 	return parseDhcpLeasesFile(out)
 }
 
+// GetGlClients: base de clientes del firmware GL.iNet (`ubus call gl-clients
+// list`). SUPERSET de dhcp.leases: incluye equipos con IP estática o sin
+// lease que el dnsmasq del Flint2 no lista. En routers sin el objeto ubus
+// gl-clients devuelve vacío (la salida del comando es vacía) — el caller lo
+// usa solo para enriquecer IPs de dispositivos ya conocidos, nunca para
+// crearlos (issue #5 bug 1).
+func (c *OpenWrtClient) GetGlClients() []DhcpLease {
+	out, err := c.pool.Run(c.Host, probe.CmdGlClients, 0)
+	if err != nil || strings.TrimSpace(out) == "" {
+		return []DhcpLease{}
+	}
+	leases, perr := probe.ParseGlClients([]byte(out))
+	if perr != nil {
+		return []DhcpLease{}
+	}
+	return leases
+}
+
 // parseDhcpLeasesFile parsea /tmp/dhcp.leases:
 // <expiry> <mac> <ip> <hostname> <clientid>
 func parseDhcpLeasesFile(out string) []DhcpLease {

+ 88 - 0
server-go/internal/httpapi/demo.go

@@ -0,0 +1,88 @@
+// demo.go — POST /api/demo/enable (issue #4): activa (o desactiva) el modo
+// demo desde la UI sin reinstalar. El instalador ya no pregunta por demo
+// (default BD limpia); este endpoint es la vía de activarla después.
+//
+// Body opcional: {"enable": true|false} (por defecto true).
+//
+// Mecanismo: reescribe DEMO_MODE en el .env del servidor y toca
+// <dataDir>/.restart-me; una unidad systemd.path (netpulse-go-restart.path)
+// vigila ese flag y reinicia el servicio como root. Al arrancar, main.go
+// vuelve a leer el .env y construye el adaptador demo o live. El flag
+// .restart-me es el mismo que usa el updater (deploy/update.sh), así que no
+// se introduce ningún mecanismo nuevo.
+package httpapi
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// setDemoModeInEnv reescribe el .env del serverRoot cambiando (o añadiendo)
+// la clave DEMO_MODE. Conserva las demás líneas.
+func setDemoModeInEnv(envPath string, on bool) error {
+	raw, err := os.ReadFile(envPath)
+	if err != nil {
+		raw = []byte{} // no existe: lo creamos
+	}
+	value := "0"
+	if on {
+		value = "1"
+	}
+	lines := strings.Split(string(raw), "\n")
+	found := false
+	for i, line := range lines {
+		t := strings.TrimSpace(line)
+		if strings.HasPrefix(t, "DEMO_MODE=") {
+			lines[i] = "DEMO_MODE=" + value
+			found = true
+			break
+		}
+	}
+	if !found {
+		lines = append(lines, "DEMO_MODE="+value)
+	}
+	out := strings.TrimRight(strings.Join(lines, "\n"), "\n") + "\n"
+	return os.WriteFile(envPath, []byte(out), 0o600)
+}
+
+// handleDemoEnable cambia el modo demo (solo admin). 200 {ok, restarting} si
+// se programó el reinicio; 409 si ya estábamos en el estado pedido.
+func (s *server) handleDemoEnable(w http.ResponseWriter, r *http.Request) {
+	on := true
+	if body, err := io.ReadAll(io.LimitReader(r.Body, 1024)); err == nil && len(body) > 0 {
+		var req struct {
+			Enable *bool `json:"enable"`
+		}
+		if json.Unmarshal(body, &req) == nil && req.Enable != nil {
+			on = *req.Enable
+		}
+	}
+	if s.cfg.DemoMode == on {
+		writeError(w, http.StatusConflict, map[bool]string{true: "already_demo", false: "already_live"}[on])
+		return
+	}
+	envPath := filepath.Join(s.cfg.ServerRoot, ".env")
+	if err := setDemoModeInEnv(envPath, on); err != nil {
+		writeError(w, http.StatusInternalServerError, "env_write_failed", err.Error())
+		return
+	}
+	// Flag de reinicio que vigila netpulse-go-restart.path (systemd).
+	flag := filepath.Join(s.cfg.DataDir, ".restart-me")
+	_ = os.WriteFile(flag, []byte("demo-switch\n"), 0o600)
+	writeJSON(w, http.StatusOK, map[string]any{
+		"ok":         true,
+		"restarting": true,
+		"mode":       map[bool]string{true: "demo", false: "live"}[on],
+	})
+}
+
+// registerDemoRoutes registra POST /api/demo/enable tras RequireAdmin.
+func (s *server) registerDemoRoutes(mux *http.ServeMux) {
+	mux.Handle("POST /api/demo/enable", auth.RequireAdmin(http.HandlerFunc(s.handleDemoEnable)))
+}

+ 53 - 0
server-go/internal/httpapi/demo_internal_test.go

@@ -0,0 +1,53 @@
+// demo_internal_test.go — prueba unitaria de setDemoModeInEnv (package httpapi).
+package httpapi
+
+import (
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+func TestSetDemoModeInEnv(t *testing.T) {
+	dir := t.TempDir()
+	env := filepath.Join(dir, ".env")
+
+	// Caso 1: DEMO_MODE=0 existente → se reescribe a 1 conservando el resto.
+	orig := "PORT=3000\nDEMO_MODE=0\nAUTH_USER=admin\n"
+	if err := os.WriteFile(env, []byte(orig), 0o600); err != nil {
+		t.Fatal(err)
+	}
+	if err := setDemoModeInEnv(env, true); err != nil {
+		t.Fatalf("setDemoModeInEnv(true): %v", err)
+	}
+	got, _ := os.ReadFile(env)
+	s := string(got)
+	if !strings.Contains(s, "DEMO_MODE=1") {
+		t.Errorf("esperaba DEMO_MODE=1, got:\n%s", s)
+	}
+	if strings.Contains(s, "DEMO_MODE=0") {
+		t.Errorf("no debería quedar DEMO_MODE=0, got:\n%s", s)
+	}
+	if !strings.Contains(s, "PORT=3000") || !strings.Contains(s, "AUTH_USER=admin") {
+		t.Errorf("se perdieron otras claves, got:\n%s", s)
+	}
+
+	// Caso 2: apagar (1 → 0).
+	if err := setDemoModeInEnv(env, false); err != nil {
+		t.Fatal(err)
+	}
+	got, _ = os.ReadFile(env)
+	if !strings.Contains(string(got), "DEMO_MODE=0") {
+		t.Errorf("esperaba DEMO_MODE=0, got:\n%s", got)
+	}
+
+	// Caso 3: sin .env previo → se crea con la clave.
+	env2 := filepath.Join(dir, ".env2")
+	if err := setDemoModeInEnv(env2, true); err != nil {
+		t.Fatal(err)
+	}
+	got, _ = os.ReadFile(env2)
+	if strings.TrimSpace(string(got)) != "DEMO_MODE=1" {
+		t.Errorf(".env nuevo inesperado: %q", got)
+	}
+}

+ 44 - 0
server-go/internal/httpapi/demo_test.go

@@ -0,0 +1,44 @@
+// demo_test.go — issue #4: POST /api/demo/enable (solo admin). El
+// testServer arranca con DEMO_MODE=1 (httpapi_test.go), así que el
+// endpoint responde 409 already_demo; la lógica de reescritura del .env
+// (setDemoModeInEnv) se cubre a nivel de unidad sobre un fichero temporal.
+package httpapi_test
+
+import (
+	"net/http"
+	"strings"
+	"testing"
+)
+
+func TestDemoEnable403ParaRolUser(t *testing.T) {
+	ts := makeTestServer(t)
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewerdemo", "clave1234", "user")
+
+	res := do(t, "POST", ts.URL, "/api/demo/enable", userCookie)
+	if res.StatusCode != http.StatusForbidden {
+		t.Fatalf("demo/enable rol user: got %d want 403", res.StatusCode)
+	}
+}
+
+func TestDemoEnable401SinSesion(t *testing.T) {
+	ts := makeTestServer(t)
+	req, _ := http.NewRequest("POST", ts.URL+"/api/demo/enable", strings.NewReader("{}"))
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("sin sesión: got %d want 401", res.StatusCode)
+	}
+}
+
+func TestDemoEnable409CuandoYaDemo(t *testing.T) {
+	ts := makeTestServer(t) // DEMO_MODE=1
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	res := do(t, "POST", ts.URL, "/api/demo/enable", adminCookie)
+	if res.StatusCode != http.StatusConflict {
+		t.Fatalf("ya en demo: got %d want 409", res.StatusCode)
+	}
+}

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

@@ -30,7 +30,7 @@ import (
 )
 
 // Version es la versión del backend (app.js:18).
-const Version = "2.4.1"
+const Version = "2.4.2"
 
 // Deps son las dependencias del servidor API (como createApp de app.js).
 type Deps struct {
@@ -171,6 +171,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Config (sesión; /api/config/adguard solo admin) ---
 	s.registerConfigRoutes(mux)
 
+	// --- Demo (issue #4): activar modo demo desde la UI; solo admin ---
+	s.registerDemoRoutes(mux)
+
 	// --- Update (solo admin; ausente si no hay updater, p.ej. en tests) ---
 	if d.Updater != nil {
 		s.registerUpdateRoutes(mux, d.Updater)