فهرست منبع

chore: backlog sweep - 26 fixes across security, topology, frontend, demo and packaging (#262)

* fix(wan): gate simulated jitter to demo mode

* fix(orchestration): clean up applyPlan polling and handle rejections

* perf(orchestration): memoize visibleRouters to avoid effect churn

* fix(roaming): cancel stale fetches on tab and range changes

* fix(devices): guard NaN percentage when totals are zero

* fix(home): use stable keys for service cards

* fix(provider): keep server unread count in live mode

* fix(update): cap apply polling and clear it on unmount

* fix(ui): clear spin timers on unmount

* fix(roaming): redirect to login on dawn 401

* chore(tsconfig): enable noUncheckedIndexedAccess

* fix(alerts): fire unknown-device alert once per MAC

* fix(alerts): resolve router offline alert on recovery

* feat(topology): expose lldpd missing flag on router

* fix(topology): discover LLDP links by router identity

* fix(routers): distinguish no-SSH-access from offline

* ci: trigger openwrt packaging on tag push and wait for release assets (#235)

* ci: package luci-app-netpulse and attach it to releases (#236)

* fix(ui): make roaming and reports tabs WAI-ARIA compliant (#229)

* fix(config): enforce minimum length 10 on AUTH_PASS seed (#216)

* fix(demo): show friendly message when the static demo serves HTML for /api/*

* fix(demo): point exit demo to the app login instead of the landing

* feat(landing): highlight post-quantum TLS and fleet agent self-update

* fix(server): add ReadTimeout/WriteTimeout with SSE write-deadline exemption (#210)

* style(ci): use plain hyphen in packaging comments

* fix(auth): decay login_attempts when the lock has expired (#211)

* fix(topology): keep router detail popup open while traveling to it (#255)

* feat(i18n): localize demo alert texts in the active language (#239)

* fix(auth): reject cross-origin mutations via Origin/Host check (#213)

* fix(api): return 413 (not 400) for oversized JSON bodies via real ResponseWriter (#215)

* fix(config): log webhook host only, not the full URL (#217)

* fix(auth): stop logging the on-box pairing token in clear (#214)

* chore(backup): warn and audit the full-DB download that includes kv secrets (#218)

* fix(ui): satisfy noUncheckedIndexedAccess across topology, pull-to-refresh and performance

The integration of leaves C (#230 flag) with D (#229/#255/#239) surfaced
indexed accesses that only the full vite build catches (tsc -b on the
solution file skipped them). Non-null assertions where a size guard already
exists; fetchJson now distinguishes 401 (unauthorized) so #228 redirect still
works through the shared helper.

* chore(gitleaks): ignore test-only password in migrate e2e test

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 ماه پیش
والد
کامیت
c4cd4538a3
83فایلهای تغییر یافته به همراه2271 افزوده شده و 473 حذف شده
  1. 109 11
      .github/workflows/openwrt-package.yml
  2. 1 0
      .gitleaksignore
  3. 29 1
      README.md
  4. 5 2
      app/public/locales/en/translation.json
  5. 5 2
      app/public/locales/es/translation.json
  6. 14 3
      app/src/components/Layout.tsx
  7. 2 2
      app/src/components/PullToRefresh.tsx
  8. 20 5
      app/src/components/UpdateBanner.tsx
  9. 3 1
      app/src/components/routers/BackhaulPanel.tsx
  10. 1 1
      app/src/components/routers/RouterPerformance.tsx
  11. 11 9
      app/src/components/routers/routerExtras.ts
  12. 2 0
      app/src/components/topology/DawnPanel.tsx
  13. 106 12
      app/src/components/topology/TopologyMap.tsx
  14. 21 20
      app/src/components/topology/model.ts
  15. 9 3
      app/src/data/DataProvider.tsx
  16. 7 5
      app/src/data/alertFeed.ts
  17. 30 12
      app/src/data/mock.ts
  18. 32 4
      app/src/lib/utils.ts
  19. 15 10
      app/src/pages/Devices.tsx
  20. 11 8
      app/src/pages/Home.tsx
  21. 37 14
      app/src/pages/Orchestration.tsx
  22. 78 14
      app/src/pages/Reports.tsx
  23. 182 43
      app/src/pages/Roaming.tsx
  24. 1 0
      app/src/pages/Settings.tsx
  25. 12 2
      app/src/sections/RecentAlerts.tsx
  26. 8 5
      app/src/sections/WanTraffic.tsx
  27. 1 0
      app/tsconfig.app.json
  28. 5 3
      deploy/openwrt/luci-app-netpulse/Makefile
  29. 35 24
      deploy/openwrt/package-luci.sh
  30. 103 40
      deploy/openwrt/package.sh
  31. 54 6
      server-go/cmd/netpulse/main.go
  32. 79 0
      server-go/cmd/netpulse/main_test.go
  33. 130 6
      server-go/internal/adapters/alerts_live_test.go
  34. 92 15
      server-go/internal/adapters/demo_dataset.go
  35. 228 70
      server-go/internal/adapters/live.go
  36. 56 0
      server-go/internal/adapters/live_firmware_test.go
  37. 71 1
      server-go/internal/adapters/lldp_test.go
  38. 87 4
      server-go/internal/adapters/topology.go
  39. 46 0
      server-go/internal/adapters/topology_test.go
  40. 10 1
      server-go/internal/adapters/types.go
  41. 12 2
      server-go/internal/auth/auth.go
  42. 141 1
      server-go/internal/auth/auth_test.go
  43. 55 0
      server-go/internal/auth/middleware.go
  44. 8 1
      server-go/internal/config/config.go
  45. 16 2
      server-go/internal/config/config_test.go
  46. 1 1
      server-go/internal/httpapi/admin_gate_test.go
  47. 5 1
      server-go/internal/httpapi/agent.go
  48. 2 2
      server-go/internal/httpapi/agent_api_test.go
  49. 4 4
      server-go/internal/httpapi/alerts_api_test.go
  50. 5 1
      server-go/internal/httpapi/auth.go
  51. 1 1
      server-go/internal/httpapi/availability_test.go
  52. 15 2
      server-go/internal/httpapi/backup.go
  53. 38 0
      server-go/internal/httpapi/backup_test.go
  54. 6 6
      server-go/internal/httpapi/config.go
  55. 4 4
      server-go/internal/httpapi/config_test.go
  56. 7 3
      server-go/internal/httpapi/data.go
  57. 2 2
      server-go/internal/httpapi/demo_test.go
  58. 3 3
      server-go/internal/httpapi/demoreadonly_test.go
  59. 2 2
      server-go/internal/httpapi/device_events_test.go
  60. 2 2
      server-go/internal/httpapi/display_name_test.go
  61. 61 12
      server-go/internal/httpapi/httpapi_test.go
  62. 1 1
      server-go/internal/httpapi/migrate_e2e_test.go
  63. 11 2
      server-go/internal/httpapi/orchestr.go
  64. 8 3
      server-go/internal/httpapi/pairing.go
  65. 6 2
      server-go/internal/httpapi/pairing_test.go
  66. 7 3
      server-go/internal/httpapi/push.go
  67. 1 1
      server-go/internal/httpapi/push_api_test.go
  68. 2 2
      server-go/internal/httpapi/rearm_api_test.go
  69. 4 4
      server-go/internal/httpapi/refresh_test.go
  70. 1 1
      server-go/internal/httpapi/reports_test.go
  71. 39 8
      server-go/internal/httpapi/server.go
  72. 6 6
      server-go/internal/httpapi/settings.go
  73. 6 6
      server-go/internal/httpapi/settings_knownmacs_test.go
  74. 3 3
      server-go/internal/httpapi/settings_wanspeed_test.go
  75. 1 1
      server-go/internal/httpapi/system_api_test.go
  76. 4 4
      server-go/internal/httpapi/topology_override.go
  77. 2 2
      server-go/internal/httpapi/update_helpers_test.go
  78. 1 1
      server-go/internal/httpapi/update_pending_test.go
  79. 2 2
      server-go/internal/httpapi/upgrade.go
  80. 4 4
      server-go/internal/httpapi/upgrade_api_test.go
  81. 17 6
      server-go/internal/httpapi/users.go
  82. 2 0
      web/i18n.js
  83. 5 0
      web/index.html

+ 109 - 11
.github/workflows/openwrt-package.yml

@@ -1,10 +1,23 @@
 name: openwrt-package
 
-# Disparado cuando se publica un release de GitHub (tag v* → goreleaser).
-# Descarga el binario netpulse-agent arm64 de la release, lo empaqueta
-# en .ipk (SDK 24.10) y .apk (SDK 25.12), y los adjunta a la release.
+# Builds the OpenWrt packages for the released agent and attaches them to the
+# published release:
+#   - netpulse-agent as .ipk (24.10 SDK, mediatek/filogic) and .apk (25.12
+#     SDK, qualcommax/ipq807x).
+#   - luci-app-netpulse (arch all) as .ipk and .apk (#236).
+#
+# Triggered on v* tag pushes, the SAME event that runs release.yml. It does
+# not rely on the `release` event for goreleaser-published releases: goreleaser
+# creates releases with the workflow GITHUB_TOKEN, and events triggered by the
+# GITHUB_TOKEN do not start new workflow runs
+# (https://docs.github.com/en/actions/concepts/security/github_token). So this
+# workflow runs in parallel with release.yml and waits for the agent tarballs
+# before attaching packages. The `release: published` trigger stays for
+# manually published releases.
 
 on:
+  push:
+    tags: ['v*']
   release:
     types: [published]
   workflow_dispatch:
@@ -17,7 +30,7 @@ permissions:
   contents: write
 
 jobs:
-  package:
+  package-agent:
     runs-on: ubuntu-latest
     strategy:
       fail-fast: false
@@ -33,16 +46,34 @@ jobs:
     steps:
       - uses: actions/checkout@v4
 
-      - name: Determinar release tag
+      - name: Resolve release tag
         id: tag
         run: |
           if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
             echo "tag=${{ inputs.version }}" >> "$GITHUB_OUTPUT"
+          elif [ "${{ github.event_name }}" = "push" ]; then
+            echo "tag=${{ github.ref_name }}" >> "$GITHUB_OUTPUT"
           else
             echo "tag=${{ github.event.release.tag_name }}" >> "$GITHUB_OUTPUT"
           fi
 
-      - name: Descargar binario netpulse-agent arm64
+      - name: Wait for agent tarballs on the release
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          TAG: ${{ steps.tag.outputs.tag }}
+        run: |
+          for i in $(seq 1 80); do
+            if gh release view "$TAG" --json assets --jq '.assets[].name' 2>/dev/null | grep -q 'netpulse-agent_.*_linux_arm64.tar.gz'; then
+              echo "Agent tarballs present after $i attempts"
+              exit 0
+            fi
+            echo "Waiting for agent tarballs ($i/80)..."
+            sleep 15
+          done
+          echo "ERROR: agent tarballs not found on $TAG after 20 min" >&2
+          exit 1
+
+      - name: Download netpulse-agent arm64 binary
         env:
           GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
           TAG: ${{ steps.tag.outputs.tag }}
@@ -53,11 +84,13 @@ jobs:
           ls -la netpulse-agent
           file netpulse-agent
 
-      - name: Empaquetar ${{ matrix.format }} (SDK ${{ matrix.sdk-version }})
+      - name: Package ${{ matrix.format }} (SDK ${{ matrix.sdk-version }})
+        env:
+          TAG: ${{ steps.tag.outputs.tag }}
         run: |
           chmod +x deploy/openwrt/package.sh
-          PKG_VERSION=$(sed -n 's/^PKG_VERSION:=//p' deploy/openwrt/netpulse-agent/Makefile | head -1)
-          PKG_RELEASE=$(sed -n 's/^PKG_RELEASE:=//p' deploy/openwrt/netpulse-agent/Makefile | head -1)
+          export PKG_VERSION="${TAG#v}"
+          export PKG_RELEASE="1"
           deploy/openwrt/package.sh \
             "${{ matrix.sdk-version }}" \
             "${{ matrix.sdk-target }}" \
@@ -65,11 +98,76 @@ jobs:
             "${{ matrix.format }}" \
             /tmp/agent/netpulse-agent
 
-      - name: Subir a release
+      - name: Upload to release
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          TAG: ${{ steps.tag.outputs.tag }}
+        run: |
+          echo "Packages generated:"
+          ls -la dist/packages/
+          gh release upload "$TAG" dist/packages/*.${{ matrix.format }} --clobber
+
+  package-luci:
+    runs-on: ubuntu-latest
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - sdk-version: 24.10.5
+            sdk-target: mediatek/filogic
+            format: ipk
+          - sdk-version: 25.12.5
+            sdk-target: qualcommax/ipq807x
+            format: apk
+
+    steps:
+      - uses: actions/checkout@v4
+
+      - name: Resolve release tag
+        id: tag
+        run: |
+          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
+            echo "tag=${{ inputs.version }}" >> "$GITHUB_OUTPUT"
+          elif [ "${{ github.event_name }}" = "push" ]; then
+            echo "tag=${{ github.ref_name }}" >> "$GITHUB_OUTPUT"
+          else
+            echo "tag=${{ github.event.release.tag_name }}" >> "$GITHUB_OUTPUT"
+          fi
+
+      - name: Wait for agent tarballs on the release
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          TAG: ${{ steps.tag.outputs.tag }}
+        run: |
+          for i in $(seq 1 80); do
+            if gh release view "$TAG" --json assets --jq '.assets[].name' 2>/dev/null | grep -q 'netpulse-agent_.*_linux_arm64.tar.gz'; then
+              echo "Release ready after $i attempts"
+              exit 0
+            fi
+            echo "Waiting for release assets ($i/80)..."
+            sleep 15
+          done
+          echo "ERROR: agent tarballs not found on $TAG after 20 min" >&2
+          exit 1
+
+      - name: Package luci-app-netpulse ${{ matrix.format }} (SDK ${{ matrix.sdk-version }})
+        env:
+          TAG: ${{ steps.tag.outputs.tag }}
+        run: |
+          chmod +x deploy/openwrt/package-luci.sh
+          export PKG_VERSION="${TAG#v}"
+          export PKG_RELEASE="1"
+          deploy/openwrt/package-luci.sh \
+            "${{ matrix.sdk-version }}" \
+            "${{ matrix.sdk-target }}" \
+            "" \
+            "${{ matrix.format }}"
+
+      - name: Upload to release
         env:
           GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
           TAG: ${{ steps.tag.outputs.tag }}
         run: |
-          echo "Paquetes generados:"
+          echo "LuCI packages generated:"
           ls -la dist/packages/
           gh release upload "$TAG" dist/packages/*.${{ matrix.format }} --clobber

+ 1 - 0
.gitleaksignore

@@ -1,3 +1,4 @@
 c6ae504f95ae416450b2ca884db80c2112bdb614:server-go/internal/db/migrate_node_test.go:generic-api-key:37
 d699083e78374c3508a80a84487c59b4ff458390:server-go/internal/db/migrate_node_test.go:generic-api-key:37
 85ca49bc95c9dbc422d58d4bf7d5b29ee67397ba:server-go/internal/httpapi/push.go:generic-api-key:51
+39727b9dfc1773882a7f0388f9db21fedb6a4bc7:server-go/internal/httpapi/migrate_e2e_test.go:generic-api-key:34

+ 29 - 1
README.md

@@ -130,7 +130,7 @@ Other OpenWrt devices should work, but yours would be the first to tell.
 | **8 — Consolidation** | ✅ | `/api/health` metrics, persistent agent registry, retention ladder (raw 7d → 5min buckets 1y → daily ∞), recharts v3, outgoing alert webhooks |
 | **9 — On-box** | ✅ | UCI config, AUTH_PASS bootstrap, TLS self-signed + SPKI pinning, pairing token, OpenWrt server package |
 | **10 — Orchestration** | 🔄 | Plan→apply→state engine + sandboxed agent executor (10.1), AdGuard module (10.2). WireGuard/DAWN-write deferred to Phase 17 |
-| **11 — LuCI package** | ✅ | `luci-app-netpulse`: local agent status/view (procd, UCI, logs, restart/rearm) + bridge to the web app |
+| **11 — LuCI package** | ✅ | `luci-app-netpulse` shipped as `.ipk`/`.apk` on every release: local agent status/view (procd, UCI, logs, restart/rearm) + bridge to the web app |
 | **12 — Security audit** | ✅ | TRUST_PROXY, anti-replay on ingest, body cap, password min 10 |
 | **13 — Robustness audit** | ✅ | Single-flight GetOverview, SSE write deadline, sshpool dial race, error wrapping |
 | **14 — WiFi/roaming visibility** | ✅ | DAWN signal matrix, 802.11r status per SSID, channel utilization survey, persistent roaming events feed (30d) |
@@ -172,6 +172,34 @@ Settings. Authorize it on each router you want to monitor
 boot via LAN discovery (TCP :22 sweep, ubus/GL-UI fingerprint); the rest
 are added from Settings. Polling is strictly read-only.
 
+## OpenWrt packages
+
+Every `v*` release ships the agent and the LuCI app as installable OpenWrt
+packages alongside the tarballs:
+
+- `netpulse-agent` as `.ipk` (OpenWrt 24.10 SDK, mediatek/filogic) and `.apk`
+  (OpenWrt 25.12 SDK, qualcommax/ipq807x).
+- `luci-app-netpulse` as `.ipk` and `.apk` (`all` arch, any target): LuCI
+  pages that show the local agent status, let you restart it, edit its UCI
+  config and jump to the NetPulse web app.
+
+Grab the assets from the
+[latest release](https://github.com/gnacho/netpulse/releases) and install on
+the router (LuCI System > Software, or over SSH):
+
+```sh
+# OpenWrt 24.10 (ipk)
+opkg install ./netpulse-agent_*.ipk ./luci-app-netpulse_*.ipk
+
+# OpenWrt 25.12 (apk)
+apk add --allow-untrusted ./netpulse-agent_*.apk ./luci-app-netpulse_*.apk
+```
+
+`luci-app-netpulse` depends on `netpulse-agent` and `luci-base`; installing
+both packages together resolves the dependencies without extra feeds. After
+install, LuCI picks up the new pages automatically (the package restarts
+`rpcd` and clears the index cache).
+
 ## Development
 
 ```bash

+ 5 - 2
app/public/locales/en/translation.json

@@ -319,6 +319,7 @@
     "subtitle": "Roaming and WiFi mesh status",
     "loading": "Loading DAWN data…",
     "error": "Could not load DAWN status. Check that the service runs on your routers.",
+    "noApi": "Available only with a live backend.",
     "empty": "No router has DAWN enabled. Install it on OpenWrt to see the roaming mesh.",
     "tabMatrix": "Matrix",
     "tab11r": "802.11r",
@@ -401,7 +402,8 @@
       "disconnected": "Disconnected",
       "dawn": "DAWN",
       "other": "Other"
-    }
+    },
+    "tabsLabel": "Roaming views"
   },
   "notFound": {
     "construction": "This page is under construction. The mockup will complete it in the next iteration."
@@ -581,6 +583,7 @@
     "footnote": "Availability = minutes with data over the period total. The current period is shown as partial.",
     "latency": "Average latency",
     "loading": "Loading report…",
+    "noApi": "Available only with a live backend.",
     "rangeLabel": "Range to show",
     "subtitle": "Availability and performance per router.",
     "tabDay": "Daily",
@@ -1181,4 +1184,4 @@
       }
     }
   }
-}
+}

+ 5 - 2
app/public/locales/es/translation.json

@@ -319,6 +319,7 @@
     "subtitle": "Estado del roaming y la malla WiFi",
     "loading": "Cargando datos de DAWN…",
     "error": "No se pudo cargar el estado de DAWN. Comprueba que el servicio corre en tus routers.",
+    "noApi": "Disponible solo con backend en vivo.",
     "empty": "Ningún router tiene DAWN activo. Instálalo en OpenWrt para ver la malla de roaming.",
     "tabMatrix": "Matriz",
     "tab11r": "802.11r",
@@ -401,7 +402,8 @@
       "disconnected": "Desconectado",
       "dawn": "DAWN",
       "other": "Otro"
-    }
+    },
+    "tabsLabel": "Vistas de roaming"
   },
   "notFound": {
     "construction": "Esta página está en construcción. El mockup la completará en la siguiente iteración."
@@ -581,6 +583,7 @@
     "footnote": "Disponibilidad = minutos con datos sobre el total del período. El período en curso se muestra parcial.",
     "latency": "Latencia media",
     "loading": "Cargando informe…",
+    "noApi": "Disponible solo con backend en vivo.",
     "rangeLabel": "Rango a mostrar",
     "subtitle": "Disponibilidad y rendimiento por router.",
     "tabDay": "Diario",
@@ -1181,4 +1184,4 @@
       }
     }
   }
-}
+}

+ 14 - 3
app/src/components/Layout.tsx

@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router'
 import { AnimatePresence, motion } from 'framer-motion'
@@ -197,7 +197,9 @@ function Sidebar({ collapsed, onToggleCollapse }: { collapsed: boolean; onToggle
   const { t } = useTranslation()
   const items = useVisibleNavItems()
   const main = items.filter((i) => i.to !== '/settings')
-  const settings = items[items.length - 1]
+  // Settings siempre es el último ítem de NAV_ITEMS y los filtros de
+  // useVisibleNavItems nunca lo quitan → garantizado definido.
+  const settings = items[items.length - 1]!
 
   if (collapsed) {
     // Sidebar colapsado = raíl de iconos en lg (persiste en localStorage)
@@ -423,12 +425,21 @@ function Topbar() {
   const { refresh: refreshData } = useNetPulse()
   const [spinning, setSpinning] = useState(false)
   const location = useLocation()
+  // Timer del spin del botón de refresh (#227): limpiado en unmount.
+  const spinTimer = useRef<number | null>(null)
+  useEffect(() => () => {
+    if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+  }, [])
 
   const onRefresh = () => {
     setSpinning(true)
     refresh()
     refreshData()
-    window.setTimeout(() => setSpinning(false), 450)
+    if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+    spinTimer.current = window.setTimeout(() => {
+      spinTimer.current = null
+      setSpinning(false)
+    }, 450)
   }
 
   return (

+ 2 - 2
app/src/components/PullToRefresh.tsx

@@ -20,14 +20,14 @@ export default function PullToRefresh({ children }: { children: ReactNode }) {
   useEffect(() => {
     const onTouchStart = (e: TouchEvent) => {
       if (window.scrollY <= 0 && e.touches.length === 1) {
-        startY.current = e.touches[0].clientY
+        startY.current = e.touches[0]!.clientY
       } else {
         startY.current = null
       }
     }
     const onTouchMove = (e: TouchEvent) => {
       if (startY.current === null) return
-      const dy = e.touches[0].clientY - startY.current
+      const dy = e.touches[0]!.clientY - startY.current
       if (dy > 0) {
         const v = Math.min(dy * 0.5, 120)
         pullRef.current = v

+ 20 - 5
app/src/components/UpdateBanner.tsx

@@ -32,6 +32,7 @@ const POLL_MS = 60 * 60 * 1000
 const WEEK_MS = 7 * 24 * 60 * 60 * 1000
 const CHECK_KEY = 'netpulse-last-update-check'
 const APPLY_POLL_MS = 2500
+const APPLY_TIMEOUT_MS = 90_000
 
 export function UpdateBanner() {
   const { t } = useTranslation()
@@ -40,6 +41,16 @@ export function UpdateBanner() {
   const [status, setStatus] = useState<UpdateStatus | null>(null)
   const [dismissed, setDismissed] = useState<string | null>(null)
   const applyingRef = useRef(false)
+  // Id del poll de progreso del apply: en un ref para limpiarlo en unmount
+  // (#226).
+  const applyPollRef = useRef<number | null>(null)
+  const clearApplyPoll = () => {
+    if (applyPollRef.current !== null) {
+      window.clearInterval(applyPollRef.current)
+      applyPollRef.current = null
+    }
+  }
+  useEffect(() => clearApplyPoll, [])
 
   const fetchStatus = useCallback(async () => {
     try {
@@ -123,14 +134,18 @@ export function UpdateBanner() {
     }
     try {
       await fetch('/api/update/apply', { method: 'POST' })
-      // Seguimiento del progreso hasta que acabe
-      const id = window.setInterval(async () => {
+      // Seguimiento del progreso hasta que acabe. Tope de 90 s: si el backend
+      // se queda en 'updating' sin llegar a 'done', se abandona el poll en vez
+      // de seguir sondeando para siempre (#226). El id vive en un ref para
+      // limpiarlo si el banner se desmonta.
+      const deadline = Date.now() + APPLY_TIMEOUT_MS
+      applyPollRef.current = window.setInterval(async () => {
         const s = await fetchStatus()
         if (s && s.updating && s.updating.step === 'done') {
-          window.clearInterval(id)
+          clearApplyPoll()
           waitAndReload(uptimeBefore)
-        } else if (s && !s.updating) {
-          window.clearInterval(id)
+        } else if ((s && !s.updating) || Date.now() > deadline) {
+          clearApplyPoll()
           applyingRef.current = false
         }
       }, APPLY_POLL_MS)

+ 3 - 1
app/src/components/routers/BackhaulPanel.tsx

@@ -22,11 +22,13 @@ function SignalTooltip({
   wireless: boolean
 }) {
   if (!active || !payload?.length) return null
+  const value = payload[0]?.value
+  if (value === undefined) return null
   return (
     <div className="rounded-[10px] border border-border-strong bg-elevated px-3 py-2 shadow-lg">
       <div className="mb-0.5 font-mono text-caption text-text-muted">{label}</div>
       <div className="font-mono text-mono-sm text-text-primary">
-        {payload[0].value} {wireless ? 'dBm' : '% carga enlace'}
+        {value} {wireless ? 'dBm' : '% carga enlace'}
       </div>
     </div>
   )

+ 1 - 1
app/src/components/routers/RouterPerformance.tsx

@@ -45,7 +45,7 @@ function PerfTooltip({
 }) {
   const { t } = useTranslation()
   if (!active || !payload?.length) return null
-  const p = payload[0]
+  const p = payload[0]!
   const def = SERIES.find((s) => s.key === p.dataKey)
   return (
     <div className="rounded-[10px] border border-border-strong bg-elevated px-3 py-2 shadow-lg">

+ 11 - 9
app/src/components/routers/routerExtras.ts

@@ -207,7 +207,8 @@ export const routerExtras: Record<string, RouterExtras> = {
 }
 
 export function getRouterExtras(id: string): RouterExtras {
-  return routerExtras[id] ?? routerExtras.flint2
+  // flint2 es el default canónico y siempre está en el literal de arriba.
+  return routerExtras[id] ?? routerExtras.flint2!
 }
 
 // ---------------------------------------------------------------------------
@@ -268,17 +269,18 @@ export function perfSeries(router: Router, range: '1h' | '24h' | '7d'): PerfPoin
     let temp = Math.max(30, Math.round(router.temp - 5 + wob * 4 + dayShape * 4))
     if (i === peakIdx) cpu = cpuPeak
     if (i === peakIdx) temp = tempPeak
-    points.push({ t: labels[i], cpu, ram, temp })
+    points.push({ t: labels[i]!, cpu, ram, temp })
   }
   // La serie termina SIEMPRE en el valor canónico actual
-  points[n - 1] = { t: labels[n - 1], cpu: router.cpu, ram: router.ram, temp: router.temp }
+  points[n - 1] = { t: labels[n - 1]!, cpu: router.cpu, ram: router.ram, temp: router.temp }
   return points
 }
 
 export function perfCaptions(router: Router, data: PerfPoint[]): { cpu: string; ram: string; temp: string } {
   const extras = getRouterExtras(router.id)
-  const cpuMax = data.reduce((m, p) => (p.cpu > m.cpu ? p : m), data[0])
-  const tempMax = data.reduce((m, p) => (p.temp > m.temp ? p : m), data[0])
+  if (data.length === 0) throw new Error('perfCaptions: empty perf series')
+  const cpuMax = data.reduce((m, p) => (p.cpu > m.cpu ? p : m), data[0]!)
+  const tempMax = data.reduce((m, p) => (p.temp > m.temp ? p : m), data[0]!)
   const ramUsed = Math.round((router.ram / 100) * extras.ramMb)
   return {
     cpu: i18n.t('routerDetail.perf.peakCpu', { pct: cpuMax.cpu, t: cpuMax.t }),
@@ -324,15 +326,15 @@ function buildAdGuardSeriesFrom(stats: { queries24h: number; blocked24h: number
   const isCanon = totalQ === 84312 && totalB === 15687
   if (isCanon) q[21] = 5412
   const drift = totalQ - q.reduce((a, b) => a + b, 0)
-  q[20] += drift // absorber el redondeo en la hora anterior
+  q[20] = (q[20] ?? 0) + drift // absorber el redondeo en la hora anterior
   const b = q.map((v) => Math.round(v * (totalQ > 0 ? totalB / totalQ : 0)))
   if (isCanon) b[21] = 1031
   const driftB = totalB - b.reduce((a, c) => a + c, 0)
-  b[20] += driftB
+  b[20] = (b[20] ?? 0) + driftB
   return q.map((v, i) => ({
     t: `${String(i).padStart(2, '0')}:00`,
-    permitidas: v - b[i],
-    bloqueadas: b[i],
+    permitidas: v - (b[i] ?? 0),
+    bloqueadas: b[i] ?? 0,
   }))
 }
 

+ 2 - 0
app/src/components/topology/DawnPanel.tsx

@@ -6,6 +6,7 @@ import { useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Wifi } from 'lucide-react'
 import { SectionHeader } from '@/components/SectionHeader'
+import { redirectLogin } from '@/data/DataProvider'
 import { cn } from '@/lib/utils'
 
 interface DawnAp {
@@ -36,6 +37,7 @@ export function DawnPanel() {
     const load = async () => {
       try {
         const res = await fetch('/api/dawn')
+        if (res.status === 401) redirectLogin()
         if (!res.ok) return
         const json = (await res.json()) as { aps: DawnAp[]; mesh?: DawnMesh[] }
         if (!disposed) {

+ 106 - 12
app/src/components/topology/TopologyMap.tsx

@@ -99,22 +99,32 @@ function TooltipCard({
   touch,
   wan,
   routerName,
+  onPointerEnter,
+  onPointerLeave,
 }: {
   tip: TooltipState
   touch: boolean
   wan: WanInfo
   /** nombre visible del router del que cuelga un nodo (D8: tooltip dist) */
   routerName: (id: string) => string
+  /** puente de hover (issue #255): cancelar el cierre al entrar en el popup */
+  onPointerEnter?: () => void
+  onPointerLeave?: () => void
 }) {
   const { t } = useTranslation()
   return (
     <div
       className={cn(
-        'pointer-events-none absolute z-20 w-72 -translate-x-1/2 rounded-xl border border-border-strong bg-elevated p-3 shadow-lg',
+        // En puntero fino el popup participa del hover (puente para que no se
+        // cierre al viajar del nodo al popup); en táctil sigue transparente.
+        touch ? 'pointer-events-none' : 'pointer-events-auto',
+        'absolute z-20 w-72 -translate-x-1/2 rounded-xl border border-border-strong bg-elevated p-3 shadow-lg',
         tip.below ? 'translate-y-[14px]' : '-translate-y-[calc(100%+14px)]',
       )}
       style={{ left: tip.left, top: tip.top }}
       role="tooltip"
+      onPointerEnter={onPointerEnter}
+      onPointerLeave={onPointerLeave}
     >
       {tip.kind === 'router' && (
         <div>
@@ -426,6 +436,9 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
   const drag = useRef<{ px: number; py: number } | null>(null)
   const pinch = useRef<{ view0: View; mid0: { x: number; y: number }; dist0: number } | null>(null)
   const moved = useRef(false)
+  /** Retardo de cierre del tooltip (issue #255): el cursor debe poder viajar
+   *  desde el nodo hasta el popup sin que este desaparezca. */
+  const hoverCloseTimer = useRef<number | null>(null)
 
   const [hoverNode, setHoverNode] = useState<string | null>(null)
   const [tooltip, setTooltip] = useState<TooltipState | null>(null)
@@ -531,10 +544,10 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
       pinch.current = {
         view0: { ...viewRef.current },
         mid0: {
-          x: (pts[0].x + pts[1].x) / 2 - rect.left,
-          y: (pts[0].y + pts[1].y) / 2 - rect.top,
+          x: (pts[0]!.x + pts[1]!.x) / 2 - rect.left,
+          y: (pts[0]!.y + pts[1]!.y) / 2 - rect.top,
         },
-        dist0: Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1,
+        dist0: Math.hypot(pts[0]!.x - pts[1]!.x, pts[0]!.y - pts[1]!.y) || 1,
       }
     }
   }, [])
@@ -550,10 +563,10 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
       if (pinch.current && pointers.current.size >= 2) {
         const pts = [...pointers.current.values()]
         const mid = {
-          x: (pts[0].x + pts[1].x) / 2 - rect.left,
-          y: (pts[0].y + pts[1].y) / 2 - rect.top,
+          x: (pts[0]!.x + pts[1]!.x) / 2 - rect.left,
+          y: (pts[0]!.y + pts[1]!.y) / 2 - rect.top,
         }
-        const cur = Math.hypot(pts[0].x - pts[1].x, pts[0].y - pts[1].y) || 1
+        const cur = Math.hypot(pts[0]!.x - pts[1]!.x, pts[0]!.y - pts[1]!.y) || 1
         const { view0, mid0, dist0 } = pinch.current
         const factor = dist0 / cur
         const newW = clamp(view0.w * factor, MIN_W, MAX_W)
@@ -607,21 +620,57 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
     setTooltip({ ...data, left, top, below })
   }, [])
 
-  const closeHover = useCallback(() => {
-    if (hoverCapable) {
+  // El cierre no es inmediato: si el cursor deja el nodo rumbo al popup (que
+  // flota sobre él), un retardo corto evita que el popup desaparezca antes de
+  // poder clicarlo (issue #255). Entrar en otro nodo o en el propio popup lo
+  // cancela.
+  const scheduleClose = useCallback(() => {
+    if (!hoverCapable) return
+    if (hoverCloseTimer.current !== null) return
+    hoverCloseTimer.current = window.setTimeout(() => {
+      hoverCloseTimer.current = null
       setTooltip(null)
       setHoverNode(null)
-    }
+    }, 180)
   }, [hoverCapable])
 
+  const cancelClose = useCallback(() => {
+    if (hoverCloseTimer.current !== null) {
+      window.clearTimeout(hoverCloseTimer.current)
+      hoverCloseTimer.current = null
+    }
+  }, [])
+
+  // Limpieza del timer al desmontar (evita setState tras unmount).
+  useEffect(
+    () => () => {
+      if (hoverCloseTimer.current !== null) window.clearTimeout(hoverCloseTimer.current)
+    },
+    [],
+  )
+
+  const closeHover = scheduleClose
+
   // -- interacción con nodos ---------------------------------------------------
   const handleNodeHover = useCallback(
     (data: TooltipData, e: ReactPointerEvent) => {
       if (e.pointerType !== 'mouse') return
+      cancelClose()
       setHoverNode(data.id)
       openTooltip(data)
     },
-    [openTooltip],
+    [cancelClose, openTooltip],
+  )
+
+  /** Teclado (issue #255): el foco abre el popup igual que el hover. */
+  const handleNodeFocus = useCallback(
+    (data: TooltipData) => {
+      if (!hoverCapable) return
+      cancelClose()
+      setHoverNode(data.id)
+      openTooltip(data)
+    },
+    [hoverCapable, cancelClose, openTooltip],
   )
 
   const handleNodeClick = useCallback(
@@ -849,6 +898,8 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             handleNodeHover({ kind: 'internet', id: 'internet', x: internetNode.x, y: internetNode.y + 46 }, e)
           }
           onPointerLeave={closeHover}
+          onFocus={() => handleNodeFocus({ kind: 'internet', id: 'internet', x: internetNode.x, y: internetNode.y + 46 })}
+          onBlur={closeHover}
           onClick={(e) =>
             nodeClick(e, { kind: 'internet', id: 'internet', x: internetNode.x, y: internetNode.y + 46 })
           }
@@ -907,6 +958,10 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                 handleNodeHover({ kind: 'router', id: node.id, router: node.router, x: node.x, y: node.y - node.r - 10 }, e)
               }
               onPointerLeave={closeHover}
+              onFocus={() =>
+                handleNodeFocus({ kind: 'router', id: node.id, router: node.router, x: node.x, y: node.y - node.r - 10 })
+              }
+              onBlur={closeHover}
               onClick={(e) =>
                 nodeClick(
                   e,
@@ -989,6 +1044,8 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                     handleNodeHover({ kind: 'peer', id: node.id, peer: node.peer, x: node.x, y: node.y + 30 }, e)
                   }
                   onPointerLeave={closeHover}
+                  onFocus={() => handleNodeFocus({ kind: 'peer', id: node.id, peer: node.peer, x: node.x, y: node.y + 30 })}
+                  onBlur={closeHover}
                   onClick={(e) =>
                     nodeClick(e, { kind: 'peer', id: node.id, peer: node.peer, x: node.x, y: node.y + 30 })
                   }
@@ -1034,6 +1091,16 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                   )
                 }
                 onPointerLeave={closeHover}
+                onFocus={() =>
+                  handleNodeFocus({
+                    kind: 'peersOverflow',
+                    id: 'peers-overflow',
+                    peers: hiddenPeers,
+                    x: PEERS_OVERFLOW_COORD.x,
+                    y: PEERS_OVERFLOW_COORD.y + 30,
+                  })
+                }
+                onBlur={closeHover}
                 onClick={(e) =>
                   nodeClick(
                     e,
@@ -1088,6 +1155,8 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
                   aria-label={t('topology.ring.overflowAria', { count: chip.count, router: routerName })}
                   onPointerEnter={(e) => handleNodeHover(tip, e)}
                   onPointerLeave={closeHover}
+                  onFocus={() => handleNodeFocus(tip)}
+                  onBlur={closeHover}
                   onClick={(e) => nodeClick(e, tip)}
                   onKeyDown={(e) => {
                     if (e.key === 'Enter' || e.key === ' ') {
@@ -1116,6 +1185,8 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             opacity={nodeOpacity(dv.id)}
             onHover={(e) => handleNodeHover({ kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 }, e)}
             onLeave={closeHover}
+            onFocus={() => handleNodeFocus({ kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 })}
+            onBlur={closeHover}
             onClick={(e) => nodeClick(e, { kind: 'dist', id: dv.id, node: dv.node, x: dv.x, y: dv.y - dv.r - 12 })}
           />
         ))}
@@ -1131,6 +1202,8 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
             opacity={nodeOpacity(chip.id)}
             onHover={(e) => handleNodeHover(chipTip(chip), e)}
             onLeave={closeHover}
+            onFocus={() => handleNodeFocus(chipTip(chip))}
+            onBlur={closeHover}
             onClick={(e) => {
               if (onTagDevice) {
                 nodeClick(e, chipTip(chip))
@@ -1231,7 +1304,16 @@ export function TopologyMap({ model, apiRef, showLabels, flow, hoverLink, onHove
       </svg>
 
       {/* tooltip flotante */}
-      {tooltip && <TooltipCard tip={tooltip} touch={!hoverCapable} wan={wan} routerName={routerName} />}
+      {tooltip && (
+        <TooltipCard
+          tip={tooltip}
+          touch={!hoverCapable}
+          wan={wan}
+          routerName={routerName}
+          onPointerEnter={cancelClose}
+          onPointerLeave={scheduleClose}
+        />
+      )}
     </div>
   )
 }
@@ -1288,6 +1370,8 @@ const DistNodeGroup = memo(function DistNodeGroup({
   opacity,
   onHover,
   onLeave,
+  onFocus,
+  onBlur,
   onClick,
 }: {
   dv: DistNodeView
@@ -1296,6 +1380,8 @@ const DistNodeGroup = memo(function DistNodeGroup({
   opacity: number
   onHover: (e: ReactPointerEvent) => void
   onLeave: () => void
+  onFocus: () => void
+  onBlur: () => void
   onClick: (e: { stopPropagation: () => void }) => void
 }) {
   const { t } = useTranslation()
@@ -1316,6 +1402,8 @@ const DistNodeGroup = memo(function DistNodeGroup({
       transition={{ duration: 0.2 }}
       onPointerEnter={onHover}
       onPointerLeave={onLeave}
+      onFocus={onFocus}
+      onBlur={onBlur}
       onClick={onClick}
       onKeyDown={(e) => {
         if (e.key === 'Enter' || e.key === ' ') {
@@ -1374,6 +1462,8 @@ const ChipGroup = memo(function ChipGroup({
   opacity,
   onHover,
   onLeave,
+  onFocus,
+  onBlur,
   onClick,
 }: {
   chip: ChipNode
@@ -1383,6 +1473,8 @@ const ChipGroup = memo(function ChipGroup({
   opacity: number
   onHover: (e: ReactPointerEvent) => void
   onLeave: () => void
+  onFocus: () => void
+  onBlur: () => void
   onClick: (e: { stopPropagation: () => void }) => void
 }) {
   const d = chip.device
@@ -1403,6 +1495,8 @@ const ChipGroup = memo(function ChipGroup({
         style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
         onPointerEnter={onHover}
         onPointerLeave={onLeave}
+        onFocus={onFocus}
+        onBlur={onBlur}
         onClick={onClick}
         onKeyDown={(e) => {
           if (e.key === 'Enter' || e.key === ' ') {

+ 21 - 20
app/src/components/topology/model.ts

@@ -328,8 +328,9 @@ function widestGapCenterInView(
   const angles = points.map((p) => angleTo(origin.x, origin.y, p.x, p.y)).sort((a, b) => a - b)
   const gaps: { start: number; gap: number }[] = []
   for (let i = 0; i < angles.length; i++) {
-    const next = angles[(i + 1) % angles.length] + (i === angles.length - 1 ? 360 : 0)
-    gaps.push({ start: angles[i], gap: next - angles[i] })
+    const start = angles[i]!
+    const next = angles[(i + 1) % angles.length]! + (i === angles.length - 1 ? 360 : 0)
+    gaps.push({ start, gap: next - start })
   }
   gaps.sort((a, b) => b.gap - a.gap)
   const inView = (a: number) => {
@@ -382,7 +383,7 @@ function ringLayoutCount<T extends { x: number; y: number; size?: number }>(
     const minArcDeg = ((chipSize + CHIP_GAP) * 180) / (Math.PI * ring.r)
     let ringPlaced = 0
     for (let ai = 0; ai < free.length && ringPlaced < ring.cap && idx < items.length; ai++) {
-      const [s, e] = free[ai]
+      const [s, e] = free[ai]!
       const arcLen = e - s
       const maxFit = Math.max(1, Math.floor(arcLen / minArcDeg))
       const remaining = items.length - idx
@@ -390,7 +391,7 @@ function ringLayoutCount<T extends { x: number; y: number; size?: number }>(
       for (let i = 0; i < k; i++) {
         const a = s + (arcLen * (i + 0.5)) / k
         const p = pos(node.x, node.y, a, ring.r)
-        Object.assign(items[idx++], p)
+        Object.assign(items[idx++]!, p)
         ringPlaced++
       }
     }
@@ -410,8 +411,8 @@ function ringLayout<T extends { x: number; y: number; size?: number }>(
   const free = freeArcs(excludes)
   const outer = rings[rings.length - 1]
   const freeArr = free.filter(([s, e]) => e - s > 0)
-  if (freeArr.length === 0) return
-  const [s0, e0] = freeArr[0]
+  if (!outer || freeArr.length === 0) return
+  const [s0, e0] = freeArr[0]!
   let placed = 0
   for (const item of items) {
     if (item.x === 0 && item.y === 0) {
@@ -478,8 +479,8 @@ function resolveCollisions(
     let moved = false
     for (let i = 0; i < items.length; i++) {
       for (let j = i + 1; j < items.length; j++) {
-        const a = items[i]
-        const b = items[j]
+        const a = items[i]!
+        const b = items[j]!
         const dx = b.x - a.x
         const dy = b.y - a.y
         const dist = Math.sqrt(dx * dx + dy * dy) || 0.001
@@ -504,7 +505,7 @@ function resolveCollisions(
     }
     // repulsión de segmentos (cables ajenos): empuje perpendicular al cable
     for (let i = 0; i < items.length; i++) {
-      const it = items[i]
+      const it = items[i]!
       if (it.fixed || it.id === undefined) continue
       for (const seg of segments) {
         if (seg.ownerId === it.id) continue // el propio cable no se auto-repele
@@ -588,7 +589,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const switchAnchor = gatewayNode
     ? (() => {
         const others = [...apNodes, internetNode].map((p) => ({ x: p.x, y: p.y }))
-        const r = GATEWAY_RINGS[GATEWAY_RINGS.length - 1].r + 120
+        const r = GATEWAY_RINGS[GATEWAY_RINGS.length - 1]!.r + 120
         const a = widestGapCenterInView(gatewayNode, others, r)
         return { x: Math.round(gatewayNode.x + r * Math.cos(rad(a))), y: Math.round(gatewayNode.y + r * Math.sin(rad(a))), angle: a }
       })()
@@ -712,7 +713,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       // distnodes del gateway (switch inferido al ESTE): fuera del círculo
       // virtual wifi (radio base máximo + margen) para no invadir la zona de
       // clientes wifi del Flint.
-      fanLayout(eastItems, node, GATEWAY_RINGS[GATEWAY_RINGS.length - 1].r + 50, GW_EAST_FAN[0], GW_EAST_FAN[1])
+      fanLayout(eastItems, node, GATEWAY_RINGS[GATEWAY_RINGS.length - 1]!.r + 50, GW_EAST_FAN[0], GW_EAST_FAN[1])
       fanLayout(farWestItems, node, HYPERVISOR_FAN_RADIUS, 160, 200)
       if (westItems.length >= GW_GRID_MIN) {
         gridLayoutWest(westItems, node)
@@ -806,8 +807,8 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     const extraCap = (r: number) => Math.max(10, Math.floor(360 / ((20 + CHIP_GAP) * 180) * (Math.PI * r)))
     let placed = 0
     for (let guard = 0; guard < 8 && placed < wifi.length; guard++) {
-      const last = rings[rings.length - 1]
-      const cap = rings[rings.length - 1].cap + 2
+      const last = rings[rings.length - 1]!
+      const cap = rings[rings.length - 1]!.cap + 2
       rings.push({ r: last.r + 40, cap: Math.max(extraCap(last.r + 40), cap) })
       // re-colocar desde el principio (las posiciones parciales se recalcular)
       wifi.forEach((c) => { c.x = 0; c.y = 0 })
@@ -816,7 +817,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     ringRadii.set(node.id, rings.map((r) => r.r))
     ringLayout(wifi, node, rings, excludes)
     wifi.forEach((c, i) => {
-      if (i >= baseRings[0].cap) c.size = 20
+      if (i >= baseRings[0]!.cap) c.size = 20
     })
     chips.push(...wifi)
 
@@ -832,7 +833,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       // los APs. Así un AP/switch nunca invade la zona de clientes wifi sin
       // ser empujado absurdamente lejos.
       const ringRadiiGw = ringRadii.get(node.id)
-      const baseMax = GATEWAY_RINGS[GATEWAY_RINGS.length - 1].r
+      const baseMax = GATEWAY_RINGS[GATEWAY_RINGS.length - 1]!.r
       const gwRingRadius = ringRadiiGw?.[ringRadiiGw.length - 1] ?? baseMax
       const clearDist = Math.max(baseMax, Math.min(gwRingRadius, baseMax + 80)) + 36
       // Internet: sobre el gateway (misma x), empujado hacia arriba del viewport.
@@ -894,7 +895,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       const rings = [...HUB_RINGS]
       let cap = rings.reduce((a, r) => a + r.cap, 0)
       while (cap < kids.length) {
-        const last = rings[rings.length - 1]
+        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)
       }
@@ -920,7 +921,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       const rings = [...DIST_RINGS]
       let cap = rings.reduce((a, r) => a + r.cap, 0)
       while (cap < kids.length) {
-        const last = rings[rings.length - 1]
+        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)
       }
@@ -958,7 +959,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     if (!node) continue
     const radii = ringRadii.get(routerId)
     const isGw = routerId === gatewayNode?.id
-    const r = radii?.[radii.length - 1] ?? (isGw ? GATEWAY_RINGS : AP_RINGS)[(isGw ? GATEWAY_RINGS : AP_RINGS).length - 1].r
+    const r = radii?.[radii.length - 1] ?? (isGw ? GATEWAY_RINGS : AP_RINGS)[(isGw ? GATEWAY_RINGS : AP_RINGS).length - 1]!.r
     // Clientes ocultos = miembros del anillo que exceden el aforo visible
     // (issue #117: el chip "+N" los lista al hacer clic, como peers-overflow).
     const hidden = online.filter((d) => hubOf(d) === routerId && !isVisibleInRing(d))
@@ -973,7 +974,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     kind: 'peer',
     id: `peer-${peer.id}`,
     peer,
-    ...PEER_COORDS[i],
+    ...PEER_COORDS[i]!,
   }))
   const hiddenPeers = activePeers.slice(PEER_COORDS.length)
 
@@ -1400,7 +1401,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   resolveCollisions(collidables, 80, 14, repelSegments)
   // Escribir posiciones de vuelta (solo chips; routers y distnodes son fixed)
   let ci = routerNodes.length + 1 // +1 = Internet (añadido tras los routers)
-  for (const c of chips) { c.x = collidables[ci].x; c.y = collidables[ci].y; ci++ }
+  for (const c of chips) { const ref = collidables[ci]!; c.x = ref.x; c.y = ref.y; ci++ }
 
   return {
     gatewayNode,

+ 9 - 3
app/src/data/DataProvider.tsx

@@ -255,7 +255,9 @@ export const EMPTY_EXTRAS: RouterExtras = {
 // Utilidades de red / demo
 // ---------------------------------------------------------------------------
 
-function redirectLogin(): never {
+/** Redirect compartido 401 → /login (evento para AuthGate + assign). Lo usan
+ * el provider y las páginas que hacen fetch directo (Roaming, DawnPanel). */
+export function redirectLogin(): never {
   window.dispatchEvent(new Event('netpulse-unauthorized'))
   window.location.assign('/login')
   throw new Error('unauthorized')
@@ -299,7 +301,7 @@ function demoTick(prev: NetPulseData): NetPulseData {
     (Object.keys(prev.traffic) as TimeRange[]).map((range) => {
       const series = prev.traffic[range]
       if (series.length === 0) return [range, series]
-      const last = series[series.length - 1]
+      const last = series[series.length - 1]!
       const next = { ...last, down: walkPct(last.down, 5, 1), up: walkPct(last.up, 5, 0.5) }
       return [range, [...series.slice(0, -1), next]]
     }),
@@ -653,9 +655,13 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     const idSet = new Set(ids)
     setBundle((prev) => {
       const alerts = prev.alerts.map((a) => (idSet.has(a.id) ? { ...a, read: true } : a))
+      // En live NO se recalcula el contador localmente: el snapshot/SSE lo
+      // corrige con la config por categoría del servidor (#224). Un filtrado
+      // por `!read` a secas ignoraría categorías silenciadas y mostraría un
+      // badge inconsistente hasta el siguiente snapshot.
       const unreadAlerts =
         modeRef.current === 'live'
-          ? alerts.filter((a) => !a.read).length
+          ? prev.unreadAlerts
           : countUnreadAlerts(alerts, configRef.current)
       return { ...prev, alerts, unreadAlerts }
     })

+ 7 - 5
app/src/data/alertFeed.ts

@@ -91,6 +91,8 @@ export function buildAlertFeed(
   modelShort: (routerId: string) => string | undefined = (id) => getRouter(id)?.modelShort,
 ): FeedEvent[] {
   const byId = Object.fromEntries(canonAlerts.map((a) => [a.id, a]))
+  // El proxy SIEMPRE devuelve un AlertEvent (fallback a fallbackCanon); los
+  // accesos llevan `!` por noUncheckedIndexedAccess.
   const canon = new Proxy(byId as Record<string, AlertEvent>, {
     get: (target, id: string) => target[id] ?? fallbackCanon[id],
   })
@@ -102,7 +104,7 @@ export function buildAlertFeed(
   return [
   // ————— Hoy —————
   {
-    ...canon['alert-temp-patio'],
+    ...canon['alert-temp-patio']!,
     description: '71 °C, por encima del umbral de 65 °C — revisa la ventilación',
     day: 'hoy',
     kind: 'router',
@@ -120,7 +122,7 @@ export function buildAlertFeed(
     },
   },
   {
-    ...canon['alert-handshake-wg'],
+    ...canon['alert-handshake-wg']!,
     day: 'hoy',
     kind: 'wireguard',
     icon: KeyRound,
@@ -135,7 +137,7 @@ export function buildAlertFeed(
     },
   },
   {
-    ...canon['alert-nuevo-tab'],
+    ...canon['alert-nuevo-tab']!,
     day: 'hoy',
     kind: 'dispositivos',
     context: {
@@ -195,7 +197,7 @@ export function buildAlertFeed(
     },
   },
   {
-    ...canon['alert-firmware-estudio'],
+    ...canon['alert-firmware-estudio']!,
     day: 'hoy',
     kind: 'router',
     icon: DownloadCloud,
@@ -258,7 +260,7 @@ export function buildAlertFeed(
 
   // ————— Ayer —————
   {
-    ...canon['alert-backup-adguard'],
+    ...canon['alert-backup-adguard']!,
     title: 'Copia de seguridad de AdGuard completada',
     day: 'ayer',
     kind: 'adguard',

+ 30 - 12
app/src/data/mock.ts

@@ -15,7 +15,7 @@
 // aquí solo se re-exportan para no romper imports existentes.
 // ---------------------------------------------------------------------------
 
-import { numLocale } from '@/i18n'
+import i18n, { numLocale } from '@/i18n'
 import canon from '@/data/demo-canon.json'
 import type {
   AdGuardStats,
@@ -126,7 +126,7 @@ export const trafficByRange: Record<TimeRange, TrafficPoint[]> = {
 }
 
 // ---------------------------------------------------------------------------
-// Alertas (canon §11)
+// Alertas (canon §11) — bilingües ES/EN (issue #239)
 // ---------------------------------------------------------------------------
 
 // Ts unix SEGUNDOS escalonados en coherencia con el string legado
@@ -134,26 +134,44 @@ export const trafficByRange: Record<TimeRange, TrafficPoint[]> = {
 // (server-go/internal/adapters/demo_dataset.go canonAlerts, SPEC-ALERTAS §5).
 const alertNow = Math.floor(Date.now() / 1000)
 
+/** Texto bilingüe de alerta demo: es/en según el idioma activo (issue #239). */
+function demoText({ es, en }: { es: string; en: string }): string {
+  return i18n.language?.startsWith('es') ? es : en
+}
+
+// Los títulos/descripciones se resuelven con getters al leerlos: un cambio de
+// idioma re-renderiza (useTranslation) y las alertas se muestran en el idioma
+// activo sin recargar, aunque el bundle ya tenga la referencia al array.
 export const alerts: AlertEvent[] = [
   {
-    id: 'alert-temp-patio', category: 'router', urgent: true, severity: 'warn', title: 'High temperature on Patio',
-    description: '71 °C, above the threshold (65 °C)', time: '12 min ago', ts: alertNow - 12 * 60, read: false, routerId: 'patio',
+    id: 'alert-temp-patio', category: 'router', urgent: true, severity: 'warn',
+    get title() { return demoText({ es: 'Temperatura alta en Patio', en: 'High temperature on Patio' }) },
+    get description() { return demoText({ es: '71 °C, por encima del umbral (65 °C)', en: '71 °C, above the threshold (65 °C)' }) },
+    time: '12 min ago', ts: alertNow - 12 * 60, read: false, routerId: 'patio',
   },
   {
-    id: 'alert-firmware-estudio', category: 'system', urgent: false, severity: 'warn', title: 'Firmware available',
-    description: 'OpenWrt 24.10.1 for Study', time: '3h ago', ts: alertNow - 3 * 3600, read: false, routerId: 'estudio',
+    id: 'alert-firmware-estudio', category: 'system', urgent: false, severity: 'warn',
+    get title() { return demoText({ es: 'Firmware disponible', en: 'Firmware available' }) },
+    get description() { return demoText({ es: 'OpenWrt 24.10.1 para Estudio', en: 'OpenWrt 24.10.1 for Study' }) },
+    time: '3h ago', ts: alertNow - 3 * 3600, read: false, routerId: 'estudio',
   },
   {
-    id: 'alert-nuevo-tab', category: 'clients', urgent: false, severity: 'info', title: 'New device',
-    description: "'Galaxy Tab S9' joined Living Room", time: '26 min ago', ts: alertNow - 26 * 60, read: true, routerId: 'living',
+    id: 'alert-nuevo-tab', category: 'clients', urgent: false, severity: 'info',
+    get title() { return demoText({ es: 'Nuevo dispositivo', en: 'New device' }) },
+    get description() { return demoText({ es: "'Galaxy Tab S9' se ha unido a Salón", en: "'Galaxy Tab S9' joined Living Room" }) },
+    time: '26 min ago', ts: alertNow - 26 * 60, read: true, routerId: 'living',
   },
   {
-    id: 'alert-handshake-wg', category: 'vpn', urgent: false, severity: 'info', title: 'WireGuard handshake',
-    description: 'Pixel 8 Pro connected from 5.224.x.x', time: '38s ago', ts: alertNow - 38, read: true, routerId: 'flint2',
+    id: 'alert-handshake-wg', category: 'vpn', urgent: false, severity: 'info',
+    get title() { return demoText({ es: 'Handshake WireGuard', en: 'WireGuard handshake' }) },
+    get description() { return demoText({ es: 'Pixel 8 Pro conectado desde 5.224.x.x', en: 'Pixel 8 Pro connected from 5.224.x.x' }) },
+    time: '38s ago', ts: alertNow - 38, read: true, routerId: 'flint2',
   },
   {
-    id: 'alert-backup-adguard', category: 'system', urgent: false, severity: 'ok', title: 'AdGuard backup completed',
-    description: 'Configuration and lists backed up to the NAS', time: '1 day ago', ts: alertNow - 24 * 3600, read: true, routerId: 'flint2',
+    id: 'alert-backup-adguard', category: 'system', urgent: false, severity: 'ok',
+    get title() { return demoText({ es: 'Copia de AdGuard completada', en: 'AdGuard backup completed' }) },
+    get description() { return demoText({ es: 'Configuración y listas respaldadas en el NAS', en: 'Configuration and lists backed up to the NAS' }) },
+    time: '1 day ago', ts: alertNow - 24 * 3600, read: true, routerId: 'flint2',
   },
 ]
 

+ 32 - 4
app/src/lib/utils.ts

@@ -7,9 +7,11 @@ export function cn(...inputs: ClassValue[]) {
 
 /**
  * Salir del modo demo (frontend estático sin backend): aquí no hay sesión ni
- * login al que volver, así que se intenta cerrar la ventana; si el navegador
- * bloquea window.close() (pestañas no abiertas por script), se vuelve a la
- * landing pública de NetPulse.
+ * login al que volver. Se intenta cerrar la ventana (la demo se abre en una
+ * pestaña propia desde la landing); si el navegador bloquea window.close()
+ * (pestañas no abiertas por script), se vuelve a la pantalla de login de la
+ * propia app, que explica que la demo es de solo lectura y permite volver a
+ * entrar como demo.
  */
 export function exitDemo() {
   try {
@@ -19,6 +21,32 @@ export function exitDemo() {
   }
   window.close()
   window.setTimeout(() => {
-    window.location.href = 'https://netpulse.cloudless.club/'
+    window.location.assign('/login')
   }, 300)
 }
+
+export type JsonFetch<T> =
+  | { ok: true; data: T }
+  | { ok: false; kind: 'error' | 'no-api' | 'unauthorized' }
+
+/**
+ * Fetch de un endpoint que debe devolver JSON. Distingue el fallo de red/HTTP
+ * del caso "demo sin API": la demo estática (sin backend) sirve el HTML del
+ * SPA para /api/* vía fallback de nginx (200 con content-type text/html),
+ * así que un body que no es JSON se reporta como `kind: 'no-api'`. Los
+ * paneles que hacen fetch directo (Reports/Roaming) deciden qué mostrar.
+ */
+export async function fetchJson<T>(url: string, init?: RequestInit): Promise<JsonFetch<T>> {
+  try {
+    const res = await fetch(url, init)
+    if (res.status === 401) return { ok: false, kind: 'unauthorized' }
+    if (!res.ok) throw new Error(`status ${res.status}`)
+    const contentType = res.headers.get('content-type') ?? ''
+    if (!contentType.includes('application/json')) {
+      return { ok: false, kind: 'no-api' }
+    }
+    return { ok: true, data: (await res.json()) as T }
+  } catch {
+    return { ok: false, kind: 'error' }
+  }
+}

+ 15 - 10
app/src/pages/Devices.tsx

@@ -289,16 +289,21 @@ function StatsStrip({ allDevices }: { allDevices: ClientDevice[] }) {
       label: t('devices.stats.adguardProtected'),
       icon: ShieldCheck,
       iconClass: 'text-ok',
-      render: () => (
-        <>
-          <div className="font-mono text-stat text-text-primary">
-            <CountUp value={adguardProtected} nonce={refreshKey} />
-            <span className="text-sm font-medium text-text-secondary">/{deviceTotals.total}</span>
-          </div>
-          <MetricBar value={Math.round((adguardProtected / deviceTotals.total) * 100)} className="mt-2 max-w-[140px]" />
-          <div className="mt-1 text-caption text-text-muted">{t('devices.stats.pctClients', { pct: Math.round((adguardProtected / deviceTotals.total) * 100) })}</div>
-        </>
-      ),
+      render: () => {
+        // Guard NaN (#222): antes del primer snapshot live total es 0 y la
+        // división daría NaN en MetricBar y en el texto del porcentaje.
+        const pct = deviceTotals.total > 0 ? Math.round((adguardProtected / deviceTotals.total) * 100) : 0
+        return (
+          <>
+            <div className="font-mono text-stat text-text-primary">
+              <CountUp value={adguardProtected} nonce={refreshKey} />
+              <span className="text-sm font-medium text-text-secondary">/{deviceTotals.total}</span>
+            </div>
+            <MetricBar value={pct} className="mt-2 max-w-[140px]" />
+            <div className="mt-1 text-caption text-text-muted">{t('devices.stats.pctClients', { pct })}</div>
+          </>
+        )
+      },
     },
   ]
   return (

+ 11 - 8
app/src/pages/Home.tsx

@@ -1,3 +1,4 @@
+import type { ReactNode } from 'react'
 import { AdGuardCard, WireGuardCard } from '@/sections/GatewayServices'
 import { HeroStrip } from '@/sections/HeroStrip'
 import { RecentAlerts } from '@/sections/RecentAlerts'
@@ -11,11 +12,13 @@ import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 export default function Home() {
   const { isDemo } = useNetPulse()
   const [services] = useServicesVisibility()
-  const cards = [
-    services.adguard && <AdGuardCard key="adguard" />,
-    services.wireguard && <WireGuardCard key="wireguard" />,
-    <RecentAlerts key="alerts" />,
-  ].filter(Boolean)
+  // Clave ESTABLE por tarjeta (#223): si AdGuard/WireGuard se deshabilitan en
+  // Ajustes la lista se reordena y, con key={i}, React remontaría RecentAlerts
+  // y perdería su readIds. Cada id identifica al hijo, no su posición.
+  const cards: { id: string; node: ReactNode }[] = []
+  if (services.adguard) cards.push({ id: 'adguard', node: <AdGuardCard /> })
+  if (services.wireguard) cards.push({ id: 'wireguard', node: <WireGuardCard /> })
+  cards.push({ id: 'alerts', node: <RecentAlerts /> })
   const span = Math.max(4, Math.floor(12 / cards.length))
   const spanCls = {
     4: 'lg:col-span-4',
@@ -32,9 +35,9 @@ export default function Home() {
         <WanTraffic />
       </div>
       {/* ② Servicios marcados en Ajustes + Alertas en una fila */}
-      {cards.map((card, i) => (
-        <div key={i} className={spanCls}>
-          {card}
+      {cards.map((c) => (
+        <div key={c.id} className={spanCls}>
+          {c.node}
         </div>
       ))}
       {/* ③ Routers */}

+ 37 - 14
app/src/pages/Orchestration.tsx

@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion } from 'framer-motion'
@@ -86,11 +86,25 @@ export default function Orchestration() {
   const gatewayId = routers.find((r) => r.roleBadge === 'Principal')?.id
   // Routers del dropdown: solo el gateway por defecto; todos si el toggle
   // advanced está activo. Se listan los AGENTES conectados (el apply usa SSE).
-  const visibleRouters = allowNonGateway
-    ? agents
-    : agents.filter((a) => a.slug === gatewayId)
+  // useMemo: identidad estable para no re-disparar el efecto de auto-select en
+  // cada render (#225).
+  const visibleRouters = useMemo(
+    () => (allowNonGateway ? agents : agents.filter((a) => a.slug === gatewayId)),
+    [agents, allowNonGateway, gatewayId],
+  )
   const nonGatewaySelected = allowNonGateway && routerId !== gatewayId
 
+  // Poll de applyPlan: el id vive en un ref para limpiarlo en unmount y al
+  // generar un plan nuevo / cambiar de módulo (#220).
+  const applyPollRef = useRef<number | null>(null)
+  const stopApplyPoll = () => {
+    if (applyPollRef.current !== null) {
+      window.clearInterval(applyPollRef.current)
+      applyPollRef.current = null
+    }
+  }
+  useEffect(() => stopApplyPoll, [])
+
   // Auto-seleccionar: gateway por defecto (o el primer agente visible).
   useEffect(() => {
     if (!routerId || !visibleRouters.some((a) => a.slug === routerId)) {
@@ -118,6 +132,7 @@ export default function Orchestration() {
   }
 
   const createPlan = async () => {
+    stopApplyPoll()
     setBusy(true)
     setError('')
     setPlan(null)
@@ -159,21 +174,29 @@ export default function Orchestration() {
 
   const applyPlan = async () => {
     if (!plan) return
+    stopApplyPoll()
     setBusy(true)
     setError('')
     try {
       const res = await fetch(`/api/plans/${plan.id}/apply`, { method: 'POST' })
       if (!res.ok) throw new Error(await res.text())
       setPlan({ ...plan, status: 'applying' })
-      // Poll hasta que termine
-      const poll = setInterval(async () => {
-        const r = await fetch(`/api/plans/${plan.id}`)
-        if (!r.ok) return
-        const p: Plan = await r.json()
-        setPlan(p)
-        if (p.status !== 'applying') {
-          clearInterval(poll)
-          setBusy(false)
+      // Poll hasta que termine. El id vive en el ref para limpiarlo en unmount
+      // y al generar un plan nuevo / cambiar de módulo (#220). El cuerpo va en
+      // try/catch: un fetch que rechaza no debe quedar como promise rejection
+      // sin manejar.
+      applyPollRef.current = window.setInterval(async () => {
+        try {
+          const r = await fetch(`/api/plans/${plan.id}`)
+          if (!r.ok) return
+          const p: Plan = await r.json()
+          setPlan(p)
+          if (p.status !== 'applying') {
+            stopApplyPoll()
+            setBusy(false)
+          }
+        } catch {
+          /* el siguiente tick reintenta; no propaga */
         }
       }, 2000)
     } catch (e) {
@@ -208,7 +231,7 @@ export default function Orchestration() {
           <button
             key={m}
             type="button"
-            onClick={() => { setModule(m); setPlan(null); setError(''); setWarnCode('') }}
+            onClick={() => { stopApplyPoll(); setModule(m); setPlan(null); setBusy(false); setError(''); setWarnCode('') }}
             className={`rounded-full px-3.5 py-1.5 text-sm font-medium transition-colors ${
               module === m
                 ? 'bg-accent text-canvas'

+ 78 - 14
app/src/pages/Reports.tsx

@@ -1,9 +1,11 @@
-import { useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import type { KeyboardEvent as ReactKeyboardEvent } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
 import { CalendarDays, RefreshCw } from 'lucide-react'
-import { cn } from '@/lib/utils'
+import { cn, fetchJson } from '@/lib/utils'
+import { useNetPulse } from '@/data/DataProvider'
 
 // ---------------------------------------------------------------------------
 // Tipos del contrato GET /api/reports/availability (server-go/internal/httpapi/reports.go)
@@ -64,29 +66,48 @@ function AvailabilityBar({ pct }: { pct: number }) {
 export default function Reports() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
+  const { isDemo } = useNetPulse()
   const [range, setRange] = useState<Range>('week')
   const [n, setN] = useState<number>(DEFAULT_N.week)
   const [items, setItems] = useState<AvailabilityEntry[]>([])
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState(false)
+  const [noApi, setNoApi] = useState(false)
   const [spin, setSpin] = useState(false)
 
+  // AbortController del fetch actual (#221): un cambio rápido de rango/n o un
+  // Refresh doble aborta la carga anterior en vuelo y descarta la respuesta
+  // vieja. En unmount se aborta.
+  const loadAc = useRef<AbortController | null>(null)
+  // Timer del spin del botón Refresh (#227): limpiado en unmount.
+  const spinTimer = useRef<number | null>(null)
+
   async function load(r: Range, count: number) {
+    loadAc.current?.abort()
+    const ac = new AbortController()
+    loadAc.current = ac
     setLoading(true)
     setError(false)
-    try {
-      const res = await fetch(`/api/reports/availability?range=${r}&n=${count}`)
-      if (!res.ok) throw new Error(`status ${res.status}`)
-      const env = (await res.json()) as { items: AvailabilityEntry[] }
-      setItems(env.items)
-    } catch {
+    setNoApi(false)
+    const result = await fetchJson<{ items: AvailabilityEntry[] }>(`/api/reports/availability?range=${r}&n=${count}`, { signal: ac.signal })
+    if (ac.signal.aborted) return
+    if (result.ok) {
+      setItems(result.data.items)
+    } else if (result.kind === 'no-api' && isDemo) {
+      setNoApi(true)
+      setItems([])
+    } else {
       setError(true)
       setItems([])
-    } finally {
-      setLoading(false)
     }
+    setLoading(false)
   }
 
+  useEffect(() => () => {
+    loadAc.current?.abort()
+    if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+  }, [])
+
   useEffect(() => {
     void load(range, n)
   }, [range, n])
@@ -97,6 +118,27 @@ export default function Reports() {
     setN(DEFAULT_N[r])
   }
 
+  // -- pestañas WAI-ARIA (issue #229): roving tabindex + flechas + Home/End
+  const tabRefs = useRef<(HTMLButtonElement | null)[]>([])
+
+  const onTablistKeyDown = useCallback(
+    (e: ReactKeyboardEvent<HTMLDivElement>) => {
+      const idx = RANGE_TABS.indexOf(range)
+      let next = idx
+      if (e.key === 'ArrowRight') next = (idx + 1) % RANGE_TABS.length
+      else if (e.key === 'ArrowLeft') next = (idx - 1 + RANGE_TABS.length) % RANGE_TABS.length
+      else if (e.key === 'Home') next = 0
+      else if (e.key === 'End') next = RANGE_TABS.length - 1
+      else return
+      e.preventDefault()
+      const target = RANGE_TABS[next]!
+      setRange(target)
+      setN(DEFAULT_N[target])
+      tabRefs.current[next]?.focus()
+    },
+    [range],
+  )
+
   // Agrupa por router y coloca los buckets en columnas (fila = router).
   const routerIds = [...new Set(items.map((i) => i.routerId))].sort()
   const buckets = [...new Set(items.map((i) => i.bucket))].sort().reverse()
@@ -153,7 +195,11 @@ export default function Reports() {
                 void load(range, n)
                 if (reduce) return
                 setSpin(true)
-                window.setTimeout(() => setSpin(false), 650)
+                if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+                spinTimer.current = window.setTimeout(() => {
+                  spinTimer.current = null
+                  setSpin(false)
+                }, 650)
               }}
               className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-surface px-3 text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
             >
@@ -165,12 +211,23 @@ export default function Reports() {
       </header>
 
       {/* ② Pestañas de rango */}
-      <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-surface p-1" role="tablist">
-        {RANGE_TABS.map((r) => (
+      <div
+        role="tablist"
+        aria-label={t('reports.rangeLabel')}
+        onKeyDown={onTablistKeyDown}
+        className="inline-flex items-center gap-1 rounded-lg border border-border bg-surface p-1"
+      >
+        {RANGE_TABS.map((r, i) => (
           <button
             key={r}
+            ref={(el) => {
+              tabRefs.current[i] = el
+            }}
+            id={`tab-${r}`}
             role="tab"
             aria-selected={range === r}
+            aria-controls={`panel-${r}`}
+            tabIndex={range === r ? 0 : -1}
             onClick={() => changeRange(r)}
             className={cn(
               'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
@@ -183,17 +240,23 @@ export default function Reports() {
       </div>
 
       {/* ③ Contenido */}
+      <div role="tabpanel" id={`panel-${range}`} aria-labelledby={`tab-${range}`} tabIndex={0}>
       {loading && items.length === 0 && (
         <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
           {t('reports.loading')}
         </div>
       )}
+      {noApi && (
+        <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+          {t('reports.noApi')}
+        </div>
+      )}
       {error && items.length === 0 && (
         <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
           {t('reports.error')}
         </div>
       )}
-      {!loading && !error && items.length === 0 && (
+      {!loading && !error && !noApi && items.length === 0 && (
         <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
           {t('reports.empty')}
         </div>
@@ -274,6 +337,7 @@ export default function Reports() {
           <p className="mt-6 text-caption text-text-muted">{t('reports.footnote')}</p>
         </section>
       )}
+      </div>
     </div>
   )
 }

+ 182 - 43
app/src/pages/Roaming.tsx

@@ -1,10 +1,11 @@
-import { useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import type { KeyboardEvent as ReactKeyboardEvent } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import { motion, useReducedMotion } from 'framer-motion'
 import { AlertTriangle, ArrowDownToLine, ArrowUpFromLine, CheckCircle2, GitFork, History, RefreshCw, Wifi, XCircle } from 'lucide-react'
-import { cn } from '@/lib/utils'
-import { useNetPulse } from '@/data/DataProvider'
+import { cn, fetchJson } from '@/lib/utils'
+import { useNetPulse, redirectLogin } from '@/data/DataProvider'
 
 // ---------------------------------------------------------------------------
 // Tipos del contrato GET /api/dawn (server-go/internal/adapters/types.go).
@@ -135,6 +136,9 @@ interface RoamEvent {
 type Band = 'all' | '2.4 GHz' | '5 GHz'
 type Tab = 'matrix' | '11r' | 'survey' | 'events'
 
+/** Orden estable de pestañas (issue #229: navegación por teclado). */
+const TAB_IDS: Tab[] = ['matrix', '11r', 'survey', 'events']
+
 /** Clase de color por señal (-dBm): verde óptimo, ámbar aceptable, rojo límite. */
 function signalClass(s: number): string {
   if (s >= -65) return 'bg-ok/15 text-ok ring-ok/30'
@@ -145,7 +149,7 @@ function signalClass(s: number): string {
 export default function Roaming() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
-  const { devices } = useNetPulse()
+  const { devices, isDemo } = useNetPulse()
   const [tab, setTab] = useState<Tab>('matrix')
   const [band, setBand] = useState<Band>('all')
   const [weakOnly, setWeakOnly] = useState(false)
@@ -153,16 +157,20 @@ export default function Roaming() {
   const [dot11r, setDot11r] = useState<Dot11rOverview | null>(null)
   const [dot11rLoading, setDot11rLoading] = useState(false)
   const [dot11rError, setDot11rError] = useState(false)
+  const [dot11rNoApi, setDot11rNoApi] = useState(false)
   const [survey, setSurvey] = useState<SurveyOverview | null>(null)
   const [surveyLoading, setSurveyLoading] = useState(false)
   const [surveyError, setSurveyError] = useState(false)
+  const [surveyNoApi, setSurveyNoApi] = useState(false)
   const [surveyBand, setSurveyBand] = useState<'all' | '2.4 GHz' | '5 GHz'>('all')
   const [events, setEvents] = useState<RoamEvent[]>([])
   const [eventsLoading, setEventsLoading] = useState(false)
   const [eventsError, setEventsError] = useState(false)
+  const [eventsNoApi, setEventsNoApi] = useState(false)
   const [eventsTypeFilter, setEventsTypeFilter] = useState<'all' | 'connected' | 'disconnected' | 'dawn_decision'>('all')
   const [loading, setLoading] = useState(true)
   const [error, setError] = useState(false)
+  const [noApi, setNoApi] = useState(false)
   const [spin, setSpin] = useState(false)
 
   // MAC → nombre (resuelto desde la lista de dispositivos del overview).
@@ -174,37 +182,64 @@ export default function Roaming() {
     return m
   }, [devices])
 
+  // Un AbortController por fuente de datos (#221): cada carga aborta la
+  // anterior en vuelo para que una respuesta vieja y lenta nunca sobrescriba
+  // una más nueva (cambio de pestaña/rango o Refresh repetido). En unmount se
+  // abortan todos.
+  const dawnAc = useRef<AbortController | null>(null)
+  const dot11rAc = useRef<AbortController | null>(null)
+  const surveyAc = useRef<AbortController | null>(null)
+  const eventsAc = useRef<AbortController | null>(null)
+  // Timer del spin del botón Refresh (#227): limpiado en unmount.
+  const spinTimer = useRef<number | null>(null)
+
   async function load() {
+    dawnAc.current?.abort()
+    const ac = new AbortController()
+    dawnAc.current = ac
     setLoading(true)
     setError(false)
-    try {
-      const res = await fetch('/api/dawn')
-      if (!res.ok) throw new Error(`status ${res.status}`)
-      setDawn((await res.json()) as Dawn)
-    } catch {
+    setNoApi(false)
+    const result = await fetchJson<Dawn>('/api/dawn', { signal: ac.signal })
+    if (ac.signal.aborted) return
+    if (result.ok) {
+      setDawn(result.data)
+    } else if (result.kind === 'unauthorized') {
+      redirectLogin()
+    } else if (result.kind === 'no-api' && isDemo) {
+      setNoApi(true)
+      setDawn(null)
+    } else {
       setError(true)
       setDawn(null)
-    } finally {
-      setLoading(false)
     }
+    setLoading(false)
   }
 
   // Carga perezosa de /api/dot11r solo cuando se abre la pestaña 11r (es un
   // SSH a cada router con wifi, más caro que la matriz DAWN que ya está cache
   // en el primer router). Recarga también al pulsar Refresh con 11r abierta.
   async function loadDot11r() {
+    dot11rAc.current?.abort()
+    const ac = new AbortController()
+    dot11rAc.current = ac
     setDot11rLoading(true)
     setDot11rError(false)
-    try {
-      const res = await fetch('/api/dot11r')
-      if (!res.ok) throw new Error(`status ${res.status}`)
-      setDot11r((await res.json()) as Dot11rOverview)
-    } catch {
+    setDot11rNoApi(false)
+    const result = await fetchJson<Dot11rOverview>('/api/dot11r', { signal: ac.signal })
+    if (ac.signal.aborted) return
+    if (result.ok) {
+      setDot11r(result.data)
+    } else if (result.kind === 'unauthorized') {
+      redirectLogin()
+    } else if (result.kind === 'no-api' && isDemo) {
+      setDot11rNoApi(true)
+      setDot11r(null)
+    } else {
       setDot11rError(true)
       setDot11r(null)
-    } finally {
-      setDot11rLoading(false)
     }
+    setDot11rLoading(false)
   }
 
   useEffect(() => {
@@ -221,18 +256,26 @@ export default function Roaming() {
 
   // Carga perezosa de /api/survey: igual que dot11r, un SSH por router con wifi.
   async function loadSurvey() {
+    surveyAc.current?.abort()
+    const ac = new AbortController()
+    surveyAc.current = ac
     setSurveyLoading(true)
     setSurveyError(false)
-    try {
-      const res = await fetch('/api/survey')
-      if (!res.ok) throw new Error(`status ${res.status}`)
-      setSurvey((await res.json()) as SurveyOverview)
-    } catch {
+    setSurveyNoApi(false)
+    const result = await fetchJson<SurveyOverview>('/api/survey', { signal: ac.signal })
+    if (ac.signal.aborted) return
+    if (result.ok) {
+      setSurvey(result.data)
+    } else if (result.kind === 'unauthorized') {
+      redirectLogin()
+    } else if (result.kind === 'no-api' && isDemo) {
+      setSurveyNoApi(true)
+      setSurvey(null)
+    } else {
       setSurveyError(true)
       setSurvey(null)
-    } finally {
-      setSurveyLoading(false)
     }
+    setSurveyLoading(false)
   }
 
   useEffect(() => {
@@ -244,27 +287,44 @@ export default function Roaming() {
   // Carga perezosa de /api/roam-events. Polling cada 30s mientras la pestaña
   // está activa (los eventos llegan por ingest continua al SQLite).
   async function loadEvents() {
+    eventsAc.current?.abort()
+    const ac = new AbortController()
+    eventsAc.current = ac
     setEventsLoading(true)
     setEventsError(false)
-    try {
-      const res = await fetch('/api/roam-events?limit=100')
-      if (!res.ok) throw new Error(`status ${res.status}`)
-      const json = (await res.json()) as { events: RoamEvent[] }
-      setEvents(json.events ?? [])
-    } catch {
+    setEventsNoApi(false)
+    const result = await fetchJson<{ events: RoamEvent[] }>('/api/roam-events?limit=100', { signal: ac.signal })
+    if (ac.signal.aborted) return
+    if (result.ok) {
+      setEvents(result.data.events ?? [])
+    } else if (result.kind === 'unauthorized') {
+      redirectLogin()
+    } else if (result.kind === 'no-api' && isDemo) {
+      setEventsNoApi(true)
+      setEvents([])
+    } else {
       setEventsError(true)
       setEvents([])
-    } finally {
-      setEventsLoading(false)
     }
+    setEventsLoading(false)
   }
 
+  useEffect(() => () => {
+    dawnAc.current?.abort()
+    dot11rAc.current?.abort()
+    surveyAc.current?.abort()
+    eventsAc.current?.abort()
+    if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+  }, [])
+
   useEffect(() => {
     if (tab !== 'events') return
     void loadEvents()
     const id = window.setInterval(() => void loadEvents(), 30_000)
-    return () => window.clearInterval(id)
-    // eslint-disable-next-line react-hooks/exhaustive-deps
+    return () => {
+      window.clearInterval(id)
+      eventsAc.current?.abort()
+    }
   }, [tab])
 
   // APs visibles según el filtro de banda.
@@ -311,6 +371,26 @@ export default function Roaming() {
     { id: 'events', label: t('roaming.tabEvents'), soon: false },
   ]
 
+  // -- pestañas WAI-ARIA (issue #229): roving tabindex + flechas + Home/End
+  const tabRefs = useRef<(HTMLButtonElement | null)[]>([])
+
+  const onTablistKeyDown = useCallback(
+    (e: ReactKeyboardEvent<HTMLDivElement>) => {
+      const idx = TAB_IDS.indexOf(tab)
+      let next = idx
+      if (e.key === 'ArrowRight') next = (idx + 1) % TAB_IDS.length
+      else if (e.key === 'ArrowLeft') next = (idx - 1 + TAB_IDS.length) % TAB_IDS.length
+      else if (e.key === 'Home') next = 0
+      else if (e.key === 'End') next = TAB_IDS.length - 1
+      else return
+      e.preventDefault()
+      const target = TAB_IDS[next]!
+      setTab(target)
+      tabRefs.current[next]?.focus()
+    },
+    [tab],
+  )
+
   const initial = reduce ? false : { opacity: 0, y: 12 }
 
   return (
@@ -348,7 +428,11 @@ export default function Roaming() {
               if (tab === 'events') void loadEvents()
               if (reduce) return
               setSpin(true)
-              window.setTimeout(() => setSpin(false), 650)
+              if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+              spinTimer.current = window.setTimeout(() => {
+                spinTimer.current = null
+                setSpin(false)
+              }, 650)
             }}
             className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-surface px-3 text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
           >
@@ -359,12 +443,23 @@ export default function Roaming() {
       </header>
 
       {/* ② Pestañas */}
-      <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-surface p-1" role="tablist">
-        {tabs.map((tb) => (
+      <div
+        role="tablist"
+        aria-label={t('roaming.tabsLabel')}
+        onKeyDown={onTablistKeyDown}
+        className="inline-flex items-center gap-1 rounded-lg border border-border bg-surface p-1"
+      >
+        {tabs.map((tb, i) => (
           <button
             key={tb.id}
+            ref={(el) => {
+              tabRefs.current[i] = el
+            }}
+            id={`tab-${tb.id}`}
             role="tab"
             aria-selected={tab === tb.id}
+            aria-controls={`panel-${tb.id}`}
+            tabIndex={tab === tb.id ? 0 : -1}
             onClick={() => setTab(tb.id)}
             className={cn(
               'rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
@@ -383,19 +478,36 @@ export default function Roaming() {
         </div>
       )}
 
-      {tab === '11r' && <Dot11rPanel overview={dot11r} loading={dot11rLoading} error={dot11rError} />}
+      {tab === '11r' && (
+        <div role="tabpanel" id="panel-11r" aria-labelledby="tab-11r" tabIndex={0}>
+          <Dot11rPanel overview={dot11r} loading={dot11rLoading} error={dot11rError} noApi={dot11rNoApi} />
+        </div>
+      )}
 
-      {tab === 'survey' && <SurveyPanel overview={survey} loading={surveyLoading} error={surveyError} band={surveyBand} setBand={setSurveyBand} />}
+      {tab === 'survey' && (
+        <div role="tabpanel" id="panel-survey" aria-labelledby="tab-survey" tabIndex={0}>
+          <SurveyPanel overview={survey} loading={surveyLoading} error={surveyError} noApi={surveyNoApi} band={surveyBand} setBand={setSurveyBand} />
+        </div>
+      )}
 
-      {tab === 'events' && <EventsPanel events={events} loading={eventsLoading} error={eventsError} typeFilter={eventsTypeFilter} setTypeFilter={setEventsTypeFilter} nameByMac={nameByMac} />}
+      {tab === 'events' && (
+        <div role="tabpanel" id="panel-events" aria-labelledby="tab-events" tabIndex={0}>
+          <EventsPanel events={events} loading={eventsLoading} error={eventsError} noApi={eventsNoApi} typeFilter={eventsTypeFilter} setTypeFilter={setEventsTypeFilter} nameByMac={nameByMac} />
+        </div>
+      )}
 
       {tab === 'matrix' && (
-        <>
+        <div role="tabpanel" id="panel-matrix" aria-labelledby="tab-matrix" tabIndex={0}>
           {loading && (!dawn || aps.length === 0) && (
             <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
               {t('roaming.loading')}
             </div>
           )}
+          {noApi && (
+            <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+              {t('roaming.noApi')}
+            </div>
+          )}
           {error && (
             <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
               {t('roaming.error')}
@@ -532,7 +644,7 @@ export default function Roaming() {
               </div>
             </motion.section>
           )}
-        </>
+        </div>
       )}
     </div>
   )
@@ -546,10 +658,12 @@ function Dot11rPanel({
   overview,
   loading,
   error,
+  noApi,
 }: {
   overview: Dot11rOverview | null
   loading: boolean
   error: boolean
+  noApi: boolean
 }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
@@ -562,6 +676,13 @@ function Dot11rPanel({
       </div>
     )
   }
+  if (noApi) {
+    return (
+      <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+        {t('roaming.noApi')}
+      </div>
+    )
+  }
   if (error) {
     return (
       <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
@@ -811,12 +932,14 @@ function SurveyPanel({
   overview,
   loading,
   error,
+  noApi,
   band,
   setBand,
 }: {
   overview: SurveyOverview | null
   loading: boolean
   error: boolean
+  noApi: boolean
   band: SurveyBand
   setBand: (b: SurveyBand) => void
 }) {
@@ -831,6 +954,13 @@ function SurveyPanel({
       </div>
     )
   }
+  if (noApi) {
+    return (
+      <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+        {t('roaming.noApi')}
+      </div>
+    )
+  }
   if (error) {
     return (
       <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
@@ -1004,6 +1134,7 @@ function EventsPanel({
   events,
   loading,
   error,
+  noApi,
   typeFilter,
   setTypeFilter,
   nameByMac,
@@ -1011,6 +1142,7 @@ function EventsPanel({
   events: RoamEvent[]
   loading: boolean
   error: boolean
+  noApi: boolean
   typeFilter: EventTypeFilter
   setTypeFilter: (t: EventTypeFilter) => void
   nameByMac: Map<string, string>
@@ -1031,6 +1163,13 @@ function EventsPanel({
       </div>
     )
   }
+  if (noApi) {
+    return (
+      <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">
+        {t('roaming.noApi')}
+      </div>
+    )
+  }
   if (error) {
     return (
       <div className="rounded-2xl border border-border bg-surface p-8 text-center text-caption text-text-muted">

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

@@ -3233,6 +3233,7 @@ export default function Settings() {
                     step={1}
                     value={[s.value]}
                     onValueChange={([v]) => {
+                      if (v === undefined) return
                       s.set(v)
                       notify()
                     }}

+ 12 - 2
app/src/sections/RecentAlerts.tsx

@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useNavigate } from 'react-router'
 import { motion } from 'framer-motion'
@@ -15,6 +15,12 @@ export function RecentAlerts() {
   const { alerts, unreadAlerts } = useNetPulse()
   const [readIds, setReadIds] = useState<Set<string>>(new Set())
   const [spinning, setSpinning] = useState(false)
+  // Timer del spin del botón de recheck: en un ref para limpiarlo en unmount
+  // (#227).
+  const spinTimer = useRef<number | null>(null)
+  useEffect(() => () => {
+    if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+  }, [])
   const recent = alerts.slice(0, 4)
   // El badge muestra el total de no leídas (como la campana), no solo de las 4 visibles
   const unread = Math.max(0, unreadAlerts - readIds.size)
@@ -55,7 +61,11 @@ export function RecentAlerts() {
           aria-label={t('home.recentAlerts.recheck')}
           onClick={() => {
             setSpinning(true)
-            window.setTimeout(() => setSpinning(false), 450)
+            if (spinTimer.current !== null) window.clearTimeout(spinTimer.current)
+            spinTimer.current = window.setTimeout(() => {
+              spinTimer.current = null
+              setSpinning(false)
+            }, 450)
           }}
           className="flex h-7 w-7 items-center justify-center rounded-lg text-text-muted transition-colors hover:bg-hover hover:text-accent"
         >

+ 8 - 5
app/src/sections/WanTraffic.tsx

@@ -53,7 +53,7 @@ function makeLiveDot(dataLength: number, color: string) {
 /** ② Tráfico WAN — área doble serie (home.md §②) */
 export function WanTraffic() {
   const { t } = useTranslation()
-  const { traffic: trafficByRange, wan } = useNetPulse()
+  const { traffic: trafficByRange, wan, isDemo } = useNetPulse()
   const [range, setRange] = useState<TimeRange>('24h')
   const [liveData, setLiveData] = useState<TrafficPoint[]>(trafficByRange['24h'])
 
@@ -68,16 +68,19 @@ export function WanTraffic() {
     setLiveData(trafficByRange[range])
   }, [range, trafficByRange])
 
-  // Polling simulado 3s: en 1h la ventana hace scroll suave; en el resto "respira" el último punto
+  // Polling simulado 3s SOLO en demo (#219): en 1h la ventana hace scroll
+  // suave; en el resto "respira" el último punto. En live el chart muestra el
+  // snapshot real sin que un jitter simulado corrompa el último punto.
   useEffect(() => {
+    if (!isDemo) return
     const id = window.setInterval(() => {
       setLiveData((prev) => {
         if (prev.length === 0) return prev
-        const last = prev[prev.length - 1]
+        const last = prev[prev.length - 1]!
         const jitter = () => 0.9 + Math.random() * 0.2
         const next = { ...last, down: Math.max(1, last.down * jitter()), up: Math.max(0.5, last.up * jitter()) }
         if (range === '1h') {
-          const [hh, mm] = last.t.split(':').map(Number)
+          const [hh = 0, mm = 0] = last.t.split(':').map(Number)
           const d = new Date(2024, 0, 1, hh, mm + 3)
           const t = `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
           return [...prev.slice(1), { ...next, t }]
@@ -86,7 +89,7 @@ export function WanTraffic() {
       })
     }, 3000)
     return () => window.clearInterval(id)
-  }, [range])
+  }, [range, isDemo])
 
   const liveDotDown = useMemo(() => makeLiveDot(liveData.length, '#22D3EE'), [liveData.length])
   const liveDotUp = useMemo(() => makeLiveDot(liveData.length, '#A78BFA'), [liveData.length])

+ 1 - 0
app/tsconfig.app.json

@@ -22,6 +22,7 @@
 
     /* Linting */
     "strict": true,
+    "noUncheckedIndexedAccess": true,
     "resolveJsonModule": true,
     "noUnusedLocals": true,
     "noUnusedParameters": true,

+ 5 - 3
deploy/openwrt/luci-app-netpulse/Makefile

@@ -1,4 +1,4 @@
-# luci-app-netpulse — OpenWrt Makefile (Fase 11)
+# luci-app-netpulse OpenWrt Makefile (Fase 11)
 # Paquete LuCI de solo ficheros (JS/JSON/ucode, PKGARCH:=all): vista de nodo
 # del agente NetPulse. Makefile plano a propósito (no luci.mk): construye en
 # el SDK pelado igual que netpulse-agent, sin necesitar el feed luci en el
@@ -13,8 +13,10 @@
 include $(TOPDIR)/rules.mk
 
 PKG_NAME:=luci-app-netpulse
-PKG_VERSION:=2.7.2
-PKG_RELEASE:=1
+# ?= so the CI can override the version from the release tag via the env
+# (PKG_VERSION / PKG_RELEASE); falls back to these defaults for local builds.
+PKG_VERSION?=2.7.2
+PKG_RELEASE?=1
 
 PKG_LICENSE:=AGPL-3.0-only
 PKG_MAINTAINER:=Nacho <netpulse@cloudless.club>

+ 35 - 24
deploy/openwrt/package-luci.sh

@@ -1,26 +1,30 @@
 #!/bin/bash
-# package-luci.sh — empaqueta luci-app-netpulse en .ipk y .apk con el SDK.
-# Espejo de package.sh (agente) sin la parte de binario: el paquete es solo
-# ficheros (PKGARCH all), así que el MISMO artefacto vale para gateway y APs.
+# package-luci.sh builds luci-app-netpulse as .ipk or .apk with the SDK.
+# Mirror of package.sh (agent) without the binary: the package is files-only
+# (PKGARCH all), so the SAME artifact works for the gateway and the APs.
 #
-# Uso:
+# Usage:
 #   package-luci.sh <SDK_VERSION> <SDK_TARGET> <SDK_SUBTARGET> <FORMAT>
 #
-#   SDK_VERSION:  24.10.5  o  25.12.5
-#   SDK_TARGET:   mediatek/filogic  o  qualcommax/ipq807x
-#   SDK_SUBTARGET: (vacío, se detecta solo)
-#   FORMAT:       ipk  o  apk
+#   SDK_VERSION:   24.10.5 or 25.12.5
+#   SDK_TARGET:    mediatek/filogic or qualcommax/ipq807x
+#   SDK_SUBTARGET: (empty, detected automatically)
+#   FORMAT:        ipk or apk
 #
-# Ejemplo:
+# The package version defaults to the luci-app-netpulse Makefile and can be
+# overridden through the PKG_VERSION / PKG_RELEASE env vars (the CI matches
+# the release tag).
+#
+# Example:
 #   package-luci.sh 24.10.5 mediatek/filogic "" ipk
 #   package-luci.sh 25.12.5 qualcommax/ipq807x "" apk
 
 set -euo pipefail
 
-SDK_VERSION="${1:?falta SDK_VERSION}"
-SDK_TARGET="${2:?falta SDK_TARGET}"
+SDK_VERSION="${1:?missing SDK_VERSION}"
+SDK_TARGET="${2:?missing SDK_TARGET}"
 SDK_SUBTARGET="${3:-}"
-FORMAT="${4:?falta FORMAT (ipk|apk)}"
+FORMAT="${4:?missing FORMAT (ipk|apk)}"
 
 echo "=== package-luci.sh: $FORMAT SDK=$SDK_VERSION target=$SDK_TARGET ==="
 
@@ -30,25 +34,32 @@ APP_DIR="$SCRIPT_DIR/luci-app-netpulse"
 WORK_DIR="$(mktemp -d)"
 trap 'rm -rf "$WORK_DIR"' EXIT
 
-PKG_VERSION=$(sed -n 's/^PKG_VERSION:=//p' "$APP_DIR/Makefile" | head -1)
-PKG_RELEASE=$(sed -n 's/^PKG_RELEASE:=//p' "$APP_DIR/Makefile" | head -1)
+PKG_VERSION="${PKG_VERSION:-$(sed -n 's/^PKG_VERSION:=//p' "$APP_DIR/Makefile" | head -1)}"
+PKG_RELEASE="${PKG_RELEASE:-$(sed -n 's/^PKG_RELEASE:=//p' "$APP_DIR/Makefile" | head -1)}"
 
-# ── SDK URL (mismo esquema que package.sh) ───────────────────────────
-SDK_NAME="openwrt-sdk-${SDK_VERSION}-${SDK_TARGET//\//-}_gcc-13.3.0_musl.Linux-x86_64"
-SDK_URL="https://downloads.openwrt.org/releases/${SDK_VERSION}/targets/${SDK_TARGET}/${SDK_NAME}.tar.zst"
+# SDK URL. Resolve the real archive name from the download index (the
+# toolchain component differs across OpenWrt releases); same scheme as
+# package.sh.
+SDK_DIR_URL="https://downloads.openwrt.org/releases/${SDK_VERSION}/targets/${SDK_TARGET}/"
+SDK_NAME="$(curl -fsSL "$SDK_DIR_URL" 2>/dev/null | grep -o 'openwrt-sdk-[^"]*\.tar\.zst' | head -1 || true)"
+if [ -z "$SDK_NAME" ]; then
+  echo "ERROR: SDK not found under ${SDK_DIR_URL}" >&2
+  exit 1
+fi
+SDK_URL="${SDK_DIR_URL}${SDK_NAME}"
 
 echo "  SDK: $SDK_URL"
 
 cd "$WORK_DIR"
 curl -fsSL "$SDK_URL" -o sdk.tar.zst
 tar --zstd -xf sdk.tar.zst
-SDK_DIR="$WORK_DIR/$SDK_NAME"
+SDK_DIR="$WORK_DIR/${SDK_NAME%.tar.zst}"
 
 OUT_DIR="$REPO_ROOT/dist/packages"
 mkdir -p "$OUT_DIR"
 
 if [ "$FORMAT" = "ipk" ]; then
-  echo "  Construyendo .ipk (ipkg-build, arch all)..."
+  echo "  Building .ipk (ipkg-build, arch all)..."
   PKG_DIR="$WORK_DIR/luci-app-netpulse-pkg"
   mkdir -p "$PKG_DIR/CONTROL"
   cp -r "$APP_DIR/files/." "$PKG_DIR/"
@@ -90,22 +101,22 @@ POSTRM
   echo "  IPK: $(ls "$OUT_DIR"/luci-app-netpulse_*.ipk)"
 
 elif [ "$FORMAT" = "apk" ]; then
-  echo "  Construyendo .apk vía SDK..."
+  echo "  Building .apk via SDK..."
   cp -r "$APP_DIR" "$SDK_DIR/package/luci-app-netpulse"
 
   cd "$SDK_DIR"
-  # luci-base solo como dependencia de instalación; el feed luci se indexa
-  # para que el resolutor del SDK la conozca.
+  # luci-base is only an install dependency; index the luci feed so the SDK
+  # resolver knows about it.
   ./scripts/feeds update luci 2>/dev/null || true
   ./scripts/feeds install luci-base 2>/dev/null || true
   make defconfig >/dev/null 2>&1 || true
   make package/luci-app-netpulse/compile V=s 2>&1 | tail -20
 
   find bin/packages -name "luci-app-netpulse*.apk" -exec cp {} "$OUT_DIR/" \;
-  echo "  APK: $(ls "$OUT_DIR"/luci-app-netpulse*.apk 2>/dev/null || echo 'NO ENCONTRADO')"
+  echo "  APK: $(ls "$OUT_DIR"/luci-app-netpulse*.apk 2>/dev/null || echo 'NOT FOUND')"
 
 else
-  echo "ERROR: FORMAT debe ser ipk o apk" >&2
+  echo "ERROR: FORMAT must be ipk or apk" >&2
   exit 1
 fi
 

+ 103 - 40
deploy/openwrt/package.sh

@@ -1,66 +1,80 @@
 #!/bin/bash
-# package.sh — empaqueta netpulse-agent en .ipk y .apk usando el SDK de OpenWrt.
+# package.sh builds the netpulse-agent OpenWrt package as .ipk or .apk
+# using the OpenWrt SDK.
 #
-# Uso:
+# Usage:
 #   package.sh <SDK_VERSION> <SDK_TARGET> <SDK_SUBTARGET> <FORMAT> <BINARY_PATH>
 #
-#   SDK_VERSION:  24.10.5  o  25.12.5
-#   SDK_TARGET:   mediatek/filogic  o  qualcommax/ipq807x
-#   SDK_SUBTARGET: (vacío para 24.10, se detecta solo)
-#   FORMAT:       ipk  o  apk
-#   BINARY_PATH:  ruta al binario netpulse-agent precompilado (arm64)
+#   SDK_VERSION:   24.10.5 or 25.12.5
+#   SDK_TARGET:    mediatek/filogic or qualcommax/ipq807x
+#   SDK_SUBTARGET: (empty, detected automatically)
+#   FORMAT:        ipk or apk
+#   BINARY_PATH:   path to the prebuilt netpulse-agent binary (arm64)
 #
-# Ejemplo:
+# The package version defaults to the netpulse-agent Makefile (PKG_VERSION /
+# PKG_RELEASE) and can be overridden through the PKG_VERSION / PKG_RELEASE env
+# vars, which is what the CI does to match the release tag.
+#
+# Example:
 #   package.sh 24.10.5 mediatek/filogic "" ipk ./netpulse-agent-arm64
-#   package.sh 25.12.5 qualcommax/ipq807x "" apk  ./netpulse-agent-arm64
+#   package.sh 25.12.5 qualcommax/ipq807x "" apk ./netpulse-agent-arm64
 
 set -euo pipefail
 
-SDK_VERSION="${1:?falta SDK_VERSION}"
-SDK_TARGET="${2:?falta SDK_TARGET}"
+SDK_VERSION="${1:?missing SDK_VERSION}"
+SDK_TARGET="${2:?missing SDK_TARGET}"
 SDK_SUBTARGET="${3:-}"
-FORMAT="${4:?falta FORMAT (ipk|apk)}"
-BINARY="${5:?falta BINARY_PATH}"
+FORMAT="${4:?missing FORMAT (ipk|apk)}"
+BINARY="${5:?missing BINARY_PATH}"
 
 if [ ! -f "$BINARY" ]; then
-  echo "ERROR: binario no encontrado: $BINARY" >&2
+  echo "ERROR: binary not found: $BINARY" >&2
   exit 1
 fi
 
-echo "=== package.sh: $FORMAT SDK=$SDK_VERSION target=$SDK_TARGET ==="
-
 SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
 REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+
+PKG_VERSION="${PKG_VERSION:-$(sed -n 's/^PKG_VERSION:=//p' "$SCRIPT_DIR/netpulse-agent/Makefile" | head -1)}"
+PKG_RELEASE="${PKG_RELEASE:-$(sed -n 's/^PKG_RELEASE:=//p' "$SCRIPT_DIR/netpulse-agent/Makefile" | head -1)}"
+
+echo "=== package.sh: $FORMAT SDK=$SDK_VERSION target=$SDK_TARGET version=${PKG_VERSION:-0.0.0}-${PKG_RELEASE:-1} ==="
+
 WORK_DIR="$(mktemp -d)"
 trap 'rm -rf "$WORK_DIR"' EXIT
 
-# ── SDK URL ──────────────────────────────────────────────────────────
-SDK_NAME="openwrt-sdk-${SDK_VERSION}-${SDK_TARGET//\//-}_gcc-13.3.0_musl.Linux-x86_64"
-SDK_URL="https://downloads.openwrt.org/releases/${SDK_VERSION}/targets/${SDK_TARGET}/${SDK_NAME}.tar.zst"
+# SDK URL. The toolchain name in the archive differs across OpenWrt releases
+# (24.10 uses gcc-13.3.0, 25.12 uses gcc-14.3.0), so resolve the real name
+# from the download index instead of hardcoding it.
+SDK_DIR_URL="https://downloads.openwrt.org/releases/${SDK_VERSION}/targets/${SDK_TARGET}/"
+SDK_NAME="$(curl -fsSL "$SDK_DIR_URL" 2>/dev/null | grep -o 'openwrt-sdk-[^"]*\.tar\.zst' | head -1 || true)"
+if [ -z "$SDK_NAME" ]; then
+  echo "ERROR: SDK not found under ${SDK_DIR_URL}" >&2
+  exit 1
+fi
+SDK_URL="${SDK_DIR_URL}${SDK_NAME}"
 
 echo "  SDK: $SDK_URL"
 
-# ── Descargar y extraer SDK ──────────────────────────────────────────
+# Download and extract the SDK
 cd "$WORK_DIR"
 curl -fsSL "$SDK_URL" -o sdk.tar.zst
 tar --zstd -xf sdk.tar.zst
-SDK_DIR="$WORK_DIR/$SDK_NAME"
+SDK_DIR="$WORK_DIR/${SDK_NAME%.tar.zst}"
 
-# ── Preparar binario ─────────────────────────────────────────────────
-BIN_SIZE=$(stat -c%s "$BINARY" 2>/dev/null || stat -f%z "$BINARY")
+# Stage the binary and package files
 cp "$BINARY" "$WORK_DIR/netpulse-agent"
 chmod 755 "$WORK_DIR/netpulse-agent"
 
-# ── Crear estructura de paquete ──────────────────────────────────────
 PKG_DIR="$WORK_DIR/netpulse-agent-pkg"
 mkdir -p "$PKG_DIR/CONTROL" "$PKG_DIR/usr/sbin" "$PKG_DIR/etc/init.d" "$PKG_DIR/etc/config" "$PKG_DIR/etc/uci-defaults"
 
 cp "$WORK_DIR/netpulse-agent" "$PKG_DIR/usr/sbin/netpulse-agent"
-cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.init"   "$PKG_DIR/etc/init.d/netpulse-agent"
+cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.init" "$PKG_DIR/etc/init.d/netpulse-agent"
 cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.config" "$PKG_DIR/etc/config/netpulse-agent"
 cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/files/netpulse-agent.defaults" "$PKG_DIR/etc/uci-defaults/90-netpulse-agent"
 
-# ── CONTROL files ────────────────────────────────────────────────────
+# CONTROL files
 cat > "$PKG_DIR/CONTROL/control" << CTRL
 Package: netpulse-agent
 Version: ${PKG_VERSION:-0.0.0}-${PKG_RELEASE:-1}
@@ -98,38 +112,87 @@ chmod 755 "$PKG_DIR/CONTROL/prerm"
 
 echo "/etc/config/netpulse-agent" > "$PKG_DIR/CONTROL/conffiles"
 
-# ── Construir paquete ────────────────────────────────────────────────
+# Build the package
 OUT_DIR="$REPO_ROOT/dist/packages"
 mkdir -p "$OUT_DIR"
 
 if [ "$FORMAT" = "ipk" ]; then
-  echo "  Construyendo .ipk..."
+  echo "  Building .ipk..."
   "$SDK_DIR/scripts/ipkg-build" "$PKG_DIR" "$OUT_DIR"
   echo "  IPK: $(ls "$OUT_DIR"/netpulse-agent_*.ipk)"
 
 elif [ "$FORMAT" = "apk" ]; then
-  echo "  Construyendo .apk vía SDK..."
-  # El SDK 25.12+ produce .apk con make. Copiamos el Makefile existente
-  # pero le inyectamos el binario precompilado (sin compilar Go).
-  mkdir -p "$SDK_DIR/package/utils/netpulse-agent/files"
-  cp "$REPO_ROOT/deploy/openwrt/netpulse-agent/Makefile" "$SDK_DIR/package/utils/netpulse-agent/"
-  cp -r "$PKG_DIR/usr" "$PKG_DIR/etc" "$SDK_DIR/package/utils/netpulse-agent/files/" 2>/dev/null || true
+  echo "  Building .apk via SDK..."
+  # SDK 25.12+ builds .apk with make. Generate a source-less Makefile with a
+  # no-op Build/Compile: the prebuilt binary and its files are staged in
+  # files/, so the SDK neither clones the repo nor compiles Go.
+  PKG_DIR_SDK="$SDK_DIR/package/utils/netpulse-agent"
+  mkdir -p "$PKG_DIR_SDK/files"
+  cp -r "$PKG_DIR/usr" "$PKG_DIR/etc" "$PKG_DIR_SDK/files/"
+  cat > "$PKG_DIR_SDK/Makefile" << 'MAKE'
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=netpulse-agent
+PKG_VERSION:=@PKG_VERSION@
+PKG_RELEASE:=@PKG_RELEASE@
+
+PKG_LICENSE:=AGPL-3.0-only
+PKG_MAINTAINER:=Nacho <netpulse@cloudless.club>
+
+include $(INCLUDE_DIR)/package.mk
+
+define Package/netpulse-agent
+	SECTION:=utils
+	CATEGORY:=Utilities
+	TITLE:=NetPulse native agent for OpenWrt
+	URL:=https://github.com/gnacho/netpulse
+	DEPENDS:=+iw @(aarch64||arm||x86_64)
+endef
+
+define Package/netpulse-agent/description
+	Native OpenWrt agent for NetPulse network monitor. Probes the local
+	router (system, wireless, DHCP, FDB) and pushes data to a NetPulse
+	server. Stateless: no writes to flash.
+endef
+
+define Build/Compile
+endef
+
+define Package/netpulse-agent/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) ./files/usr/sbin/netpulse-agent $(1)/usr/sbin/netpulse-agent
+	$(INSTALL_DIR) $(1)/etc/init.d
+	$(INSTALL_BIN) ./files/etc/init.d/netpulse-agent $(1)/etc/init.d/netpulse-agent
+	$(INSTALL_DIR) $(1)/etc/config
+	$(INSTALL_CONF) ./files/etc/config/netpulse-agent $(1)/etc/config/netpulse-agent
+	$(INSTALL_DIR) $(1)/etc/uci-defaults
+	$(INSTALL_BIN) ./files/etc/uci-defaults/90-netpulse-agent $(1)/etc/uci-defaults/90-netpulse-agent
+endef
+
+define Package/netpulse-agent/postinst
+#!/bin/sh
+if [ -z "$${IPKG_INSTROOT}" ]; then
+	/etc/init.d/netpulse-agent stop 2>/dev/null || true
+	[ -f /etc/uci-defaults/90-netpulse-agent ] && sh /etc/uci-defaults/90-netpulse-agent
+fi
+exit 0
+endef
 
-  # Parche: saltar Build/Compile (el binario YA está en files/)
-  sed -i 's/^define Build\/Compile/define Build\/Compile_disabled/' "$SDK_DIR/package/utils/netpulse-agent/Makefile"
+$(eval $(call BuildPackage,netpulse-agent))
+MAKE
+  sed -i "s/@PKG_VERSION@/${PKG_VERSION:-0.0.0}/; s/@PKG_RELEASE@/${PKG_RELEASE:-1}/" "$PKG_DIR_SDK/Makefile"
 
   cd "$SDK_DIR"
-  # Feeds mínimos para resolver dependencias
+  # Minimal feeds so the package index resolves iw; best effort.
   ./scripts/feeds update packages 2>/dev/null || true
   ./scripts/feeds install iw 2>/dev/null || true
   make package/netpulse-agent/compile V=s 2>&1 | tail -20
 
-  # Recoger .apk
   find bin/packages -name "netpulse-agent*.apk" -exec cp {} "$OUT_DIR/" \;
-  echo "  APK: $(ls "$OUT_DIR"/netpulse-agent*.apk 2>/dev/null || echo 'NO ENCONTRADO')"
+  echo "  APK: $(ls "$OUT_DIR"/netpulse-agent*.apk 2>/dev/null || echo 'NOT FOUND')"
 
 else
-  echo "ERROR: FORMAT debe ser ipk o apk" >&2
+  echo "ERROR: FORMAT must be ipk or apk" >&2
   exit 1
 fi
 

+ 54 - 6
server-go/cmd/netpulse/main.go

@@ -20,11 +20,13 @@ import (
 	"fmt"
 	"log"
 	"net/http"
+	"net/url"
 	"os"
 	"os/signal"
 	"path/filepath"
 	"reflect"
 	"strconv"
+	"strings"
 	"syscall"
 	"time"
 
@@ -48,6 +50,49 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/webhook"
 )
 
+// Timeouts de http.Server (issue #210): ReadTimeout/WriteTimeout acotan una
+// conexión lenta (slowloris) sin cuerpo. Los endpoints SSE (/api/stream y
+// /api/agents/{slug}/stream) son conexiones largas que escriben de forma
+// continua: su write deadline se extiende vía http.ResponseController antes
+// de delegar en el handler (con WriteTimeout plano, la conexión moriría a los
+// 15 s aunque hubiera heartbeats).
+const (
+	serverReadTimeout  = 15 * time.Second
+	serverWriteTimeout = 15 * time.Second
+	sseWriteTimeout    = 24 * time.Hour
+)
+
+// isSSEStreamPath devuelve true para los endpoints SSE de larga duración.
+func isSSEStreamPath(p string) bool {
+	if p == "/api/stream" {
+		return true
+	}
+	return strings.HasPrefix(p, "/api/agents/") && strings.HasSuffix(p, "/stream")
+}
+
+// webhookHostForLog devuelve solo el host del webhook para el log de arranque:
+// la URL completa puede incrustar credenciales (https://user:pass@host) y
+// acabarían en el log (issue #217).
+func webhookHostForLog(rawURL string) string {
+	u, err := url.Parse(rawURL)
+	if err != nil || u.Host == "" {
+		return "(sin host)"
+	}
+	return u.Host
+}
+
+// withSSEWriteTimeout extiende el write deadline para los endpoints SSE: el
+// server lo fija a WriteTimeout al leer la petición y, sin este override, una
+// conexión SSE se cerraría a los 15 s.
+func withSSEWriteTimeout(next http.Handler, long time.Duration) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if isSSEStreamPath(r.URL.Path) {
+			_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(long))
+		}
+		next.ServeHTTP(w, r)
+	})
+}
+
 func main() {
 	if err := run(); err != nil {
 		log.Printf("[netpulse] error fatal en arranque: %v", err)
@@ -220,7 +265,7 @@ func run() error {
 	var webhookNotifier *webhook.Notifier
 	if cfg.Webhook != nil && cfg.Webhook.Enabled {
 		webhookNotifier = webhook.NewNotifier(*cfg.Webhook, dbHandle)
-		log.Printf("[netpulse] webhook saliente activo: %s", cfg.Webhook.URL)
+		log.Printf("[netpulse] webhook saliente activo: %s", webhookHostForLog(cfg.Webhook.URL))
 	}
 
 	// Notifier compuesto: push + webhook (SetNotifier solo admite UNO).
@@ -309,12 +354,13 @@ func run() error {
 		log.Printf("[netpulse] TLS autofirmado on-box: %s", certPath)
 		log.Printf("[netpulse] FINGERPRINT SPKI (sha256): %s", serverFP)
 
-		// Pairing token (generado en primer arranque, logueado).
-		pairTok, perr := httpapi.EnsurePairingToken(dbHandle)
-		if perr != nil {
+		// Pairing token (generado en el primer arranque). NO se loguea (issue
+		// #214): está disponible en la UI de Ajustes > Adopción (GET
+		// /api/pairing/token, admin) y un proceso cualquiera con acceso a los
+		// logs podría adoptar agentes con él.
+		if _, perr := httpapi.EnsurePairingToken(dbHandle); perr != nil {
 			return fmt.Errorf("pairing token: %w", perr)
 		}
-		log.Printf("[netpulse] PAIRING TOKEN: %s", pairTok)
 	}
 
 	handler := httpapi.NewHandler(httpapi.Deps{
@@ -352,8 +398,10 @@ func run() error {
 
 	srv := &http.Server{
 		Addr:              fmt.Sprintf(":%d", cfg.Port),
-		Handler:           handler,
+		Handler:           withSSEWriteTimeout(handler, sseWriteTimeout),
 		ReadHeaderTimeout: 10 * time.Second,
+		ReadTimeout:       serverReadTimeout,
+		WriteTimeout:      serverWriteTimeout,
 		IdleTimeout:       2 * time.Minute,
 	}
 

+ 79 - 0
server-go/cmd/netpulse/main_test.go

@@ -3,7 +3,11 @@
 package main
 
 import (
+	"net/http"
+	"net/http/httptest"
+	"strings"
 	"testing"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/alerts"
 )
@@ -36,3 +40,78 @@ func TestNotifierChainConNilPlano(t *testing.T) {
 	chain := notifierChain{real, nil}
 	chain.Notify(alerts.AlertEvent{ID: "test2"}) // no debe paniquear
 }
+
+func TestIsSSEStreamPath(t *testing.T) {
+	cases := map[string]bool{
+		"/api/stream":                true,
+		"/api/agents/gw/stream":      true,
+		"/api/agents/gateway/stream": true,
+		"/api/agents/gw/binary":      false,
+		"/api/agents/gw/refresh":     false,
+		"/api/agents/gw/stream/x":    false,
+		"/api/agents":                false,
+		"/api/overview":              false,
+		"/":                          false,
+	}
+	for p, want := range cases {
+		if got := isSSEStreamPath(p); got != want {
+			t.Errorf("isSSEStreamPath(%q) = %v, want %v", p, got, want)
+		}
+	}
+}
+
+// deadlineRecorder envuelve una ResponseWriter registrando si se llama a
+// SetWriteDeadline y con qué deadline (para verificar el override de SSE).
+type deadlineRecorder struct {
+	http.ResponseWriter
+	deadline time.Time
+	set      bool
+}
+
+func (d *deadlineRecorder) SetWriteDeadline(t time.Time) error {
+	d.deadline = t
+	d.set = true
+	return nil
+}
+
+func TestWithSSEWriteTimeoutExtiendeDeadlineSSE(t *testing.T) {
+	h := withSSEWriteTimeout(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), 24*time.Hour)
+	for _, p := range []string{"/api/stream", "/api/agents/gateway/stream"} {
+		rec := &deadlineRecorder{}
+		h.ServeHTTP(rec, httptest.NewRequest("GET", p, nil))
+		if !rec.set {
+			t.Fatalf("%s: debe extender el write deadline", p)
+		}
+		if rec.deadline.Before(time.Now().Add(23 * time.Hour)) {
+			t.Fatalf("%s: deadline %v no es el esperado (24 h)", p, rec.deadline)
+		}
+	}
+}
+
+func TestWithSSEWriteTimeoutNoTocaNoSSE(t *testing.T) {
+	h := withSSEWriteTimeout(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), 24*time.Hour)
+	rec := &deadlineRecorder{}
+	h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/overview", nil))
+	if rec.set {
+		t.Fatal("/api/overview no debe extender el write deadline")
+	}
+}
+
+func TestWebhookHostForLog(t *testing.T) {
+	// Issue #217: el log de arranque del webhook debe mostrar solo el host,
+	// sin userinfo ni path (posibles credenciales embebidas).
+	cases := map[string]string{
+		"https://user:pass@hooks.example.com/hook/abc": "hooks.example.com",
+		"https://hooks.example.com/path":               "hooks.example.com",
+		"http://192.168.1.50:8080/h":                   "192.168.1.50:8080",
+		"no-es-una-url":                                "(sin host)",
+	}
+	for raw, want := range cases {
+		if got := webhookHostForLog(raw); got != want {
+			t.Errorf("webhookHostForLog(%q) = %q, want %q", raw, got, want)
+		}
+	}
+	if s := webhookHostForLog("https://user:pass@hooks.example.com/x"); strings.Contains(s, "pass") {
+		t.Fatalf("el host no debe contener credenciales: %q", s)
+	}
+}

+ 130 - 6
server-go/internal/adapters/alerts_live_test.go

@@ -69,10 +69,13 @@ func TestDemoCanonAlertsThroughEngine(t *testing.T) {
 // liveTestLive: Live mínimo con motor en memoria para probar las emisiones.
 func liveTestLive() *Live {
 	return &Live{
-		engine:     alerts.New(nil, nil),
-		lastStatus: map[string]string{},
-		wanDown:    map[string]int{},
-		onlineMacs: map[string]bool{},
+		engine:          alerts.New(nil, nil),
+		lastStatus:      map[string]string{},
+		wanDown:         map[string]int{},
+		onlineMacs:      map[string]bool{},
+		unknownGrace:    map[string]int{},
+		unknownAlerted:  map[string]bool{},
+		unknownGraceNum: 3,
 	}
 }
 
@@ -106,6 +109,42 @@ func TestLiveRouterRecoveredTaxonomy(t *testing.T) {
 	}
 }
 
+// Issue #256: la alerta crítica de offline de un router se RESUELVE (marca
+// leída) cuando el router vuelve a responder; con APs que flapean no quedan
+// caídas fantasma "no leídas para siempre".
+func TestLiveRouterOfflineAlertResolvedOnRecovery(t *testing.T) {
+	l := liveTestLive()
+	offlineID := "alert-offline-patio-1"
+	l.engine.Emit(AlertEvent{
+		ID: offlineID, Category: alerts.CatRouter, Urgent: true,
+		Severity: "critical", Title: "Patio offline", RouterID: "patio", Time: "ahora mismo",
+	})
+	if len(l.engine.List()) != 1 {
+		t.Fatalf("alerta de caída: %d", len(l.engine.List()))
+	}
+	// El router vuelve online → las caídas pendientes se resuelven.
+	l.mu.Lock()
+	l.resolveOfflineAlerts("patio")
+	l.mu.Unlock()
+	list := l.engine.List()
+	if len(list) != 1 || !list[0].Read {
+		t.Fatalf("la caída debería quedar leída tras la recuperación: %+v", list)
+	}
+	// Las caídas de OTROS routers no se tocan.
+	l.engine.Emit(AlertEvent{
+		ID: "alert-offline-living-1", Category: alerts.CatRouter, Urgent: true,
+		Severity: "critical", Title: "Living offline", RouterID: "living", Time: "ahora mismo",
+	})
+	l.mu.Lock()
+	l.resolveOfflineAlerts("patio")
+	l.mu.Unlock()
+	for _, ev := range l.engine.List() {
+		if ev.ID == "alert-offline-living-1" && ev.Read {
+			t.Fatal("la caída de living no debía resolverse")
+		}
+	}
+}
+
 func TestLiveWanDownTaxonomyAndDebounce(t *testing.T) {
 	l := liveTestLive()
 	cfg := &RouterConfig{ID: "flint2", Name: "Flint 2", Host: "192.168.8.1"}
@@ -176,16 +215,34 @@ func TestLiveTrackUnknownDevices(t *testing.T) {
 	if len(l.engine.List()) != 0 {
 		t.Fatal("reconexión sin caída no debía alertar")
 	}
-	// Se desconecta y vuelve: AHORA sí alerta (sin nombre → desconocido)
+	// Se desconecta y vuelve: la gracia de N ticks (issue #234) evita alertar
+	// mientras el lease aún no se resuelve tras reconectar.
 	l.trackUnknownDevices([]Device{named})
 	l.trackUnknownDevices([]Device{unknown, named})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("1 tick nameless no debía alertar (gracia)")
+	}
+	l.trackUnknownDevices([]Device{unknown, named})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("2 ticks nameless no debían alertar (gracia)")
+	}
+	// Al tercer tick consecutivo online+sin nombre, el desconocido real alerta
+	l.trackUnknownDevices([]Device{unknown, named})
 	list := l.engine.List()
 	if len(list) != 1 {
-		t.Fatalf("reconexión de desconocido: %d alertas", len(list))
+		t.Fatalf("desconocido tras gracia: %d alertas", len(list))
 	}
 	if list[0].Category != alerts.CatClients || list[0].Urgent {
 		t.Fatalf("taxonomía: %+v", list[0])
 	}
+	// Issue #248: la reconexión posterior de la MISMA MAC ya no alerta
+	l.trackUnknownDevices([]Device{named})
+	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown, named})
+	l.trackUnknownDevices([]Device{unknown, named})
+	if len(l.engine.List()) != 1 {
+		t.Fatal("memoria per-MAC (#248): no debía re-alertar")
+	}
 	// El dispositivo CON nombre nunca alerta aunque se reconecte
 	l.trackUnknownDevices([]Device{unknown})
 	l.trackUnknownDevices([]Device{unknown, named})
@@ -194,6 +251,73 @@ func TestLiveTrackUnknownDevices(t *testing.T) {
 	}
 }
 
+// Issue #234: un dispositivo conocido cuyo lease DHCP tarda un par de ticks
+// en resolverse tras reconectar NO dispara la alerta de desconocido.
+func TestLiveTrackUnknownDevicesGraciaConocido(t *testing.T) {
+	l := liveTestLive()
+	d := Device{MAC: "77:88:99:AA:BB:CC", Name: "77:88:99:AA:BB:CC", RouterID: "living", Online: true}
+	// Siembra; desconexión; reconexión SIN lease resuelto durante 2 ticks…
+	l.trackUnknownDevices([]Device{d})
+	l.trackUnknownDevices([]Device{})
+	l.trackUnknownDevices([]Device{d}) // tick 1 sin nombre
+	l.trackUnknownDevices([]Device{d}) // tick 2 sin nombre
+	if len(l.engine.List()) != 0 {
+		t.Fatal("no debía alertar antes de resolver el lease")
+	}
+	// …y al tercer tick el lease ya está (Name != MAC) → nunca llega al umbral
+	d.Name = "Galaxy Tab"
+	l.trackUnknownDevices([]Device{d})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("con hostname resuelto no debía alertar")
+	}
+	// La gracia se reseteó al ver el nombre: una reconexión futura sin nombre
+	// parte de cero y vuelve a necesitar los N ticks completos (no 1).
+	l.trackUnknownDevices([]Device{})
+	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("tras reset, tick 1 no debía alertar")
+	}
+	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}})
+	if len(l.engine.List()) != 0 {
+		t.Fatal("tras reset, tick 2 no debía alertar")
+	}
+	l.trackUnknownDevices([]Device{{Name: d.MAC, MAC: d.MAC, RouterID: "living", Online: true}})
+	if len(l.engine.List()) != 1 {
+		t.Fatalf("tras reset y gracia completa: %d alertas", len(l.engine.List()))
+	}
+}
+
+// Issue #248: la memoria per-MAC es PERSISTENTE (kv) y sobrevive a un reinicio
+// del servidor: una MAC que ya alertó no vuelve a alertar en un proceso nuevo.
+func TestLiveUnknownDeviceMemoryPersisted(t *testing.T) {
+	d := openLiveTestDB(t)
+	l := NewLive(nil, d, nil, nil)
+	mac := "AA:BB:CC:DD:EE:0F"
+	unknown := Device{MAC: mac, Name: mac, RouterID: "living", Online: true}
+	// Reconexión simulada: siembra, caída, vuelve → tras la gracia alerta.
+	l.trackUnknownDevices([]Device{unknown})
+	l.trackUnknownDevices([]Device{})
+	l.trackUnknownDevices([]Device{unknown})
+	l.trackUnknownDevices([]Device{unknown})
+	l.trackUnknownDevices([]Device{unknown})
+	if len(l.engine.List()) != 1 {
+		t.Fatalf("primera alerta: %d", len(l.engine.List()))
+	}
+	// "Reinicio": un Live nuevo sobre la MISMA BD carga la memoria persistida.
+	l2 := NewLive(nil, d, nil, nil)
+	if !l2.unknownAlerted[mac] {
+		t.Fatal("la memoria per-MAC no se cargó desde kv")
+	}
+	l2.trackUnknownDevices([]Device{unknown})
+	l2.trackUnknownDevices([]Device{})
+	l2.trackUnknownDevices([]Device{unknown})
+	l2.trackUnknownDevices([]Device{unknown})
+	l2.trackUnknownDevices([]Device{unknown})
+	if len(l2.engine.List()) != 0 {
+		t.Fatal("tras reinicio no debía re-alertar (memoria persistida)")
+	}
+}
+
 func TestLiveTrackUnknownDevicesTrustedAllowlist(t *testing.T) {
 	l := liveTestLive()
 	l.db = openLiveTestDB(t) // allowlist en BD real

+ 92 - 15
server-go/internal/adapters/demo_dataset.go

@@ -10,6 +10,10 @@
 // DERIVADOS del dataset (deviceTotalsOf / onlineClientsOf), no literales.
 // SPEC-65 D65-2: Device.Infra sellado en el canon (pve=hypervisor, sus
 // CTs/VMs=ct, switch-netgear=managed-switch).
+// ALERTAS BILINGÜES (issue #239): el canon de alertas guarda title/description
+// en es/en (canonAlertSpecs). El seed de NewDemo sirve ES (sin contexto de
+// petición); localizedCanonAlerts(lang) permite servir la lengua activa cuando
+// el handler la propague.
 //
 //go:generate go run ../../cmd/gen-demo-canon
 package adapters
@@ -142,23 +146,96 @@ func canonWireguard() WireGuardStats {
 	}
 }
 
-// canonAlerts: las 5 alertas canónicas con Category/Urgent/Ts (SPEC-ALERTAS
-// §1 y §5). Los Ts son unix SEGUNDOS escalonados en coherencia con el string
-// legado ("hace 38 s" → now-38, "hace 12 min" → now-720, ...).
-func canonAlerts() []AlertEvent {
+// alertText: pareja de textos de una alerta demo en es/en (issue #239). El
+// canon de alertas es bilingüe; la lengua se elige al construir el evento.
+type alertText struct {
+	Es string
+	En string
+}
+
+// alertSpec describe una alerta canónica con textos bilingües. tsOffset es el
+// escalonado hacia atrás desde now ("hace 12 min" → now-720, ...).
+type alertSpec struct {
+	id, category, severity, routerID string
+	urgent, read                     bool
+	tsOffset                         int64
+	title, description               alertText
+	time                             string
+}
+
+// canonAlertSpecs: las 5 alertas canónicas (SPEC-ALERTAS §1 y §5), con title/
+// description en es/en. Time es el string legado de display.
+var canonAlertSpecs = []alertSpec{
+	{
+		id: "alert-temp-patio", category: alerts.CatRouter, severity: "warn", routerID: "patio",
+		urgent: true, tsOffset: 12 * 60, time: "hace 12 min",
+		title:       alertText{Es: "Temperatura alta en Patio", En: "High temperature on Patio"},
+		description: alertText{Es: "71 °C, por encima del umbral (65 °C)", En: "71 °C, above the threshold (65 °C)"},
+	},
+	{
+		id: "alert-firmware-estudio", category: alerts.CatSystem, severity: "warn", routerID: "estudio",
+		tsOffset: 3 * 3600, time: "hace 3 h",
+		title:       alertText{Es: "Firmware disponible", En: "Firmware available"},
+		description: alertText{Es: "OpenWrt 24.10.1 para Estudio", En: "OpenWrt 24.10.1 for Study"},
+	},
+	{
+		id: "alert-nuevo-tab", category: alerts.CatClients, severity: "info", routerID: "living",
+		read: true, tsOffset: 26 * 60, time: "hace 26 min",
+		title:       alertText{Es: "Nuevo dispositivo", En: "New device"},
+		description: alertText{Es: "'Galaxy Tab S9' se ha unido a Salón", En: "'Galaxy Tab S9' joined Living Room"},
+	},
+	{
+		id: "alert-handshake-wg", category: alerts.CatVPN, severity: "info", routerID: "flint2",
+		read: true, tsOffset: 38, time: "hace 38 s",
+		title:       alertText{Es: "Handshake WireGuard", En: "WireGuard handshake"},
+		description: alertText{Es: "Pixel 8 Pro conectado desde 5.224.x.x", En: "Pixel 8 Pro connected from 5.224.x.x"},
+	},
+	{
+		id: "alert-backup-adguard", category: alerts.CatSystem, severity: "ok", routerID: "flint2",
+		read: true, tsOffset: 24 * 3600, time: "hace 1 día",
+		title:       alertText{Es: "Copia de AdGuard completada", En: "AdGuard backup completed"},
+		description: alertText{Es: "Configuración y listas respaldadas en el NAS", En: "Configuration and lists backed up to the NAS"},
+	},
+}
+
+// pickText selecciona el texto de una alerta por lengua ("es" → español,
+// cualquier otra → inglés).
+func pickText(t alertText, lang string) string {
+	if lang == "es" {
+		return t.Es
+	}
+	return t.En
+}
+
+// buildCanonAlerts construye las 5 alertas canónicas en la lengua dada. Los
+// Ts son unix SEGUNDOS escalonados en coherencia con el string legado
+// ("hace 38 s" → now-38, "hace 12 min" → now-720, ...).
+func buildCanonAlerts(lang string) []AlertEvent {
 	now := time.Now().Unix()
-	return []AlertEvent{
-		{ID: "alert-temp-patio", Category: alerts.CatRouter, Urgent: true, Severity: "warn", Title: "Temperatura alta en Patio",
-			Description: "71 °C, por encima del umbral (65 °C)", Time: "hace 12 min", Ts: now - 12*60, Read: false, RouterID: "patio"},
-		{ID: "alert-firmware-estudio", Category: alerts.CatSystem, Urgent: false, Severity: "warn", Title: "Firmware disponible",
-			Description: "OpenWrt 24.10.1 para Estudio", Time: "hace 3 h", Ts: now - 3*3600, Read: false, RouterID: "estudio"},
-		{ID: "alert-nuevo-tab", Category: alerts.CatClients, Urgent: false, Severity: "info", Title: "Nuevo dispositivo",
-			Description: "'Galaxy Tab S9' se ha unido a Salón", Time: "hace 26 min", Ts: now - 26*60, Read: true, RouterID: "living"},
-		{ID: "alert-handshake-wg", Category: alerts.CatVPN, Urgent: false, Severity: "info", Title: "Handshake WireGuard",
-			Description: "Pixel 8 Pro conectado desde 5.224.x.x", Time: "hace 38 s", Ts: now - 38, Read: true, RouterID: "flint2"},
-		{ID: "alert-backup-adguard", Category: alerts.CatSystem, Urgent: false, Severity: "ok", Title: "Copia de AdGuard completada",
-			Description: "Configuración y listas respaldadas en el NAS", Time: "hace 1 día", Ts: now - 24*3600, Read: true, RouterID: "flint2"},
+	out := make([]AlertEvent, 0, len(canonAlertSpecs))
+	for _, s := range canonAlertSpecs {
+		out = append(out, AlertEvent{
+			ID: s.id, Category: s.category, Urgent: s.urgent, Severity: s.severity,
+			Title: pickText(s.title, lang), Description: pickText(s.description, lang),
+			Time: s.time, Ts: now - s.tsOffset, Read: s.read, RouterID: s.routerID,
+		})
 	}
+	return out
+}
+
+// canonAlerts: las 5 alertas canónicas (SPEC-ALERTAS §1 y §5) en español. El
+// seed corre en NewDemo sin contexto de petición, por eso el canon sirve ES;
+// la localización por lengua de la petición se puede conectar pasando la
+// lengua a localizedCanonAlerts desde el handler (issue #239).
+func canonAlerts() []AlertEvent {
+	return buildCanonAlerts("es")
+}
+
+// localizedCanonAlerts: alertas canónicas en la lengua de la petición ("es" →
+// español, resto → inglés). Punto de entrada para localizar el dataset demo
+// server-side cuando el handler propague la lengua (issue #239).
+func localizedCanonAlerts(lang string) []AlertEvent {
+	return buildCanonAlerts(lang)
 }
 
 // ---------------------------------------------------------------------------

+ 228 - 70
server-go/internal/adapters/live.go

@@ -33,6 +33,10 @@ func fmtUptime(sec float64) string {
 	return fmt.Sprintf("%dd %dh", d, h)
 }
 
+// bptr: puntero a bool (el view-model usa *bool para distinguir "ausente" de
+// "false" explícito, p.ej. Router.LldpAvailable).
+func bptr(v bool) *bool { return &v }
+
 // mbps: bps → Mbps 1 decimal (null → 0).
 func mbps(bps *float64) float64 {
 	if bps == nil {
@@ -109,6 +113,9 @@ type routerPolled struct {
 	backhaul string
 	// lldp: vecinos LLDP del tier lento (nil = sin lldpd o sonda fallida).
 	lldp []LldpNeighbor
+	// lldpUnavailable: lldpd no está instalado en este router (issue #247) →
+	// el view-model expone `lldpAvailable:false` para el hint de instalación.
+	lldpUnavailable bool
 }
 
 // extrasSnapshot es la caché anti-parpadeo por router.
@@ -133,9 +140,12 @@ type backhaulCacheEntry struct {
 const lldpCacheTTL = 45 * time.Second
 
 // lldpCacheEntry: vecinos LLDP cacheados por router (nil = sin datos).
+// unavailable=true cuando lldpd NO está instalado en el router (ErrLldpUnavailable);
+// la UI lo usa para el hint "instala lldpd" (issue #247).
 type lldpCacheEntry struct {
-	neighbors []LldpNeighbor
-	at        time.Time
+	neighbors   []LldpNeighbor
+	unavailable bool
+	at          time.Time
 }
 
 // Live es el Snapshotter del modo live.
@@ -149,30 +159,37 @@ type Live struct {
 	gatewayCfg *RouterConfig
 	clients    map[string]*OpenWrtClient
 
-	lastGood       map[string]*Router
-	lastStatus     map[string]string
-	boardCache     map[string]*BoardInfo
-	layoutCache    map[string][]PortLayout
-	extrasCache    map[string]*extrasSnapshot
-	lastPolled     map[string]*routerPolled
-	failCount      map[string]int
-	engine         *alerts.Engine
-	wgActive       map[string]bool
-	weakAlerted    map[string]int64
-	onlineMacs     map[string]bool
+	lastGood    map[string]*Router
+	lastStatus  map[string]string
+	boardCache  map[string]*BoardInfo
+	layoutCache map[string][]PortLayout
+	extrasCache map[string]*extrasSnapshot
+	lastPolled  map[string]*routerPolled
+	failCount   map[string]int
+	lastErr     map[string]error // último error del sondeo (issue #257: distinguir sin-acceso de caído)
+	engine      *alerts.Engine
+	wgActive    map[string]bool
+	weakAlerted map[string]int64
+	onlineMacs  map[string]bool
+	// unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
+	// MAC. unknownAlerted: MACs que ya dispararon la alerta de desconocido
+	// (issue #248, persistido en kv: cada MAC alerta UNA sola vez).
+	unknownGrace    map[string]int
+	unknownAlerted  map[string]bool
+	unknownGraceNum int // ticks antes de declarar desconocido (default 3, #234)
 	// Presencia wireless (issue #184): devicePresence = MAC → online del
 	// último ciclo evaluado; presenceMisses = ticks seguidos sin verse.
 	// presenceSeen evita la avalancha del primer ciclo (anti-arranque).
-	presenceSeen        bool
-	devicePresence      map[string]bool
-	presenceMisses      map[string]int
+	presenceSeen         bool
+	devicePresence       map[string]bool
+	presenceMisses       map[string]int
 	presenceOfflineAfter int // ticks sin verse antes de declarar offline (default 3)
 	// dawnAvailable: cache de "¿hay DAWN en algún router?" para el flag del
 	// overview (entrada /roaming). Refrescado asíncronamente (TTL 30s, 1 SSH
 	// al gateway) por dawnAvailableCached para no bloquear buildOverview.
-	dawnAvailable bool
-	dawnCheckedAt time.Time
-	dawnChecking  bool
+	dawnAvailable  bool
+	dawnCheckedAt  time.Time
+	dawnChecking   bool
 	seenOnlineMacs bool
 	wanDown        map[string]int
 	backhaulCache  map[string]backhaulCacheEntry
@@ -205,28 +222,32 @@ type sfCall struct {
 // NewLive crea el adapter live (db puede ser nil en tests).
 func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool) *Live {
 	l := &Live{
-		cfg:           cfg,
-		db:            d,
-		pool:          pool,
-		lastGood:      map[string]*Router{},
-		lastStatus:    map[string]string{},
-		boardCache:    map[string]*BoardInfo{},
-		layoutCache:   map[string][]PortLayout{},
-		extrasCache:   map[string]*extrasSnapshot{},
-		lastPolled:    map[string]*routerPolled{},
-		failCount:     map[string]int{},
-		engine:        alerts.New(d, nil),
-		wgActive:      map[string]bool{},
-		weakAlerted:   map[string]int64{},
-		onlineMacs:    map[string]bool{},
-		devicePresence: map[string]bool{},
-		presenceMisses: map[string]int{},
+		cfg:                  cfg,
+		db:                   d,
+		pool:                 pool,
+		lastGood:             map[string]*Router{},
+		lastStatus:           map[string]string{},
+		boardCache:           map[string]*BoardInfo{},
+		layoutCache:          map[string][]PortLayout{},
+		extrasCache:          map[string]*extrasSnapshot{},
+		lastPolled:           map[string]*routerPolled{},
+		failCount:            map[string]int{},
+		lastErr:              map[string]error{},
+		engine:               alerts.New(d, nil),
+		wgActive:             map[string]bool{},
+		weakAlerted:          map[string]int64{},
+		onlineMacs:           map[string]bool{},
+		unknownGrace:         map[string]int{},
+		unknownAlerted:       map[string]bool{},
+		unknownGraceNum:      3, // default de #234; el engine/demo puede afinarlo
+		devicePresence:       map[string]bool{},
+		presenceMisses:       map[string]int{},
 		presenceOfflineAfter: 3,
-		wanDown:       map[string]int{},
-		backhaulCache: map[string]backhaulCacheEntry{},
-		lldpCache:     map[string]lldpCacheEntry{},
-		agentDown:        map[string]bool{},
-		agentDownConfirm: 3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
+		wanDown:              map[string]int{},
+		backhaulCache:        map[string]backhaulCacheEntry{},
+		lldpCache:            map[string]lldpCacheEntry{},
+		agentDown:            map[string]bool{},
+		agentDownConfirm:     3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
 	}
 	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
 	if d != nil {
@@ -236,6 +257,18 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 			_, _ = d.Exec("INSERT INTO kv (key, value) VALUES ('attrib_v2', '1')")
 			log.Printf("[netpulse] device_attrib limpiada (attrib_v2: solo wireless persiste)")
 		}
+		// issue #248: memoria per-MAC de "desconocido ya alertado", persistida
+		// en kv para que un reinicio del servidor no vuelva a alertar las
+		// MACs ya conocidas (clave `unknown_alerted:<mac>`).
+		if rows, err := d.Query("SELECT key FROM kv WHERE key LIKE 'unknown_alerted:%'"); err == nil {
+			for rows.Next() {
+				var key string
+				if rows.Scan(&key) == nil {
+					l.unknownAlerted[strings.TrimPrefix(key, "unknown_alerted:")] = true
+				}
+			}
+			rows.Close()
+		}
 	}
 	l.SetRouters(initial)
 	return l
@@ -304,6 +337,17 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.failCount, id)
 		}
 	}
+	for id := range l.lastErr {
+		if !ids[id] {
+			delete(l.lastErr, id)
+		}
+	}
+	// unknownGrace es per-MAC (no por router): se poda por ausencia en
+	// trackUnknownDevices; aquí solo se limpia la lista completa si no queda
+	// ningún router (config vacía tras un reset).
+	if len(l.routers) == 0 {
+		l.unknownGrace = map[string]int{}
+	}
 	for id := range l.backhaulCache {
 		if !ids[id] {
 			delete(l.backhaulCache, id)
@@ -342,25 +386,30 @@ func (l *Live) probeBackhaul(routerID string, client *OpenWrtClient) string {
 
 // probeLldp: vecinos LLDP del router con caché de 45 s (tier lento, como los
 // extras anti-parpadeo). Error o lldpd ausente → nil (sin datos; el FDB solo
-// sigue mandando, comportamiento actual intacto).
-func (l *Live) probeLldp(ctx context.Context, routerID string, client *OpenWrtClient) []LldpNeighbor {
+// sigue mandando, comportamiento actual intacto). Devuelve además si lldpd
+// NO está instalado (ErrLldpUnavailable) para que el view-model lo exponga
+// (issue #247): hint "instala lldpd" en la UI.
+func (l *Live) probeLldp(ctx context.Context, routerID string, client *OpenWrtClient) ([]LldpNeighbor, bool) {
 	l.mu.Lock()
 	e, ok := l.lldpCache[routerID]
 	l.mu.Unlock()
 	if ok && time.Since(e.at) < lldpCacheTTL {
-		return e.neighbors
+		return e.neighbors, e.unavailable
 	}
 	neighbors, err := client.LldpNeighbors(ctx)
+	unavailable := false
 	if err != nil {
-		if !errors.Is(err, ErrLldpUnavailable) {
+		if errors.Is(err, ErrLldpUnavailable) {
+			unavailable = true
+		} else {
 			log.Printf("[netpulse] LLDP %s: %v", routerID, err)
 		}
 		neighbors = nil
 	}
 	l.mu.Lock()
-	l.lldpCache[routerID] = lldpCacheEntry{neighbors: neighbors, at: time.Now()}
+	l.lldpCache[routerID] = lldpCacheEntry{neighbors: neighbors, unavailable: unavailable, at: time.Now()}
 	l.mu.Unlock()
-	return neighbors
+	return neighbors, unavailable
 }
 
 // getAdguardClient: kv (GL.iNet) con fallback a .env (AGH estándar).
@@ -632,7 +681,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	// Tier lento: backhaul (5 min) y vecinos LLDP (45 s), ambos cacheados y
 	// tolerantes a error (router sin wifi/lldpd → campo ausente, sin romper).
 	backhaul := l.probeBackhaul(cfg.ID, client)
-	lldp := l.probeLldp(ctx, cfg.ID, client)
+	lldp, lldpUnavailable := l.probeLldp(ctx, cfg.ID, client)
 	if !hasBoard {
 		if b, err := client.GetBoard(); err == nil {
 			board = b
@@ -701,7 +750,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		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,
+		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
 	}, nil
 }
 
@@ -792,6 +841,9 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if uplink := l.uplinkLldp(p); uplink != nil {
 		r.Lldp = uplink
 	}
+	if p.lldpUnavailable {
+		r.LldpAvailable = bptr(false)
+	}
 	if p.board != nil {
 		r.Firmware = p.board.Release.Description
 	}
@@ -822,11 +874,13 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	return r
 }
 
-// uplinkLldp: vecino LLDP del router que es OTRO router conocido (su
-// chassis-MAC es la bridge MAC de otro router de la config) → el uplink
-// está identificado por LLDP y la app muestra el sufijo "· LLDP". Si el FDB
-// dice dónde se aprendió esa MAC, el anuncio debe llegar por ese puerto
-// (uplink); sin FDB, la MAC ya es evidencia suficiente. nil si no hay dato.
+// uplinkLldp: vecino LLDP del router que es OTRO router conocido → el uplink
+// está identificado por LLDP y la app muestra el sufijo "· LLDP". El vecino se
+// casa por chassis-MAC = bridge MAC de otro router (matching original) o, si
+// el chassis-ID que anuncia lldpd difiere de la br-lan (habitual en OpenWrt,
+// issue #252), por su mgmt-IP o nombre del chasis. Si el FDB dice dónde se
+// aprendió esa MAC, el anuncio debe llegar por ese puerto (uplink); sin FDB,
+// la MAC ya es evidencia suficiente. nil si no hay dato.
 func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
 	if len(p.lldp) == 0 {
 		return nil
@@ -834,15 +888,10 @@ func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
 	l.mu.Lock()
 	polled := l.lastPolled
 	l.mu.Unlock()
-	routerMacs := map[string]bool{}
-	for id, other := range polled {
-		if id != p.cfg.ID && other.brMac != "" {
-			routerMacs[other.brMac] = true
-		}
-	}
+	routers := routerIdentities(polled)
 	for i := range p.lldp {
 		nb := &p.lldp[i]
-		if nb.ChassisMac == "" || !routerMacs[nb.ChassisMac] {
+		if neighborIsRouter(nb, routers, p.cfg.ID) == nil {
 			continue
 		}
 		if port, ok := p.fdb[nb.ChassisMac]; ok && port != nb.Port {
@@ -854,6 +903,9 @@ func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
 }
 
 // offlineRouter: último bueno marcado offline o placeholder (index.js:251-272).
+// issue #257: si el último fallo fue de ACCESO (el router responde pero la
+// clave SSH no está autorizada), el estado es "unreachable" + accessMissing,
+// no un "offline" de apagado/inalcanzable (config issue, no power issue).
 func (l *Live) offlineRouter(cfg RouterConfig) Router {
 	l.mu.Lock()
 	prev := l.lastGood[cfg.ID]
@@ -884,9 +936,45 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 		}
 	}
 	r.Status = "offline"
+	if l.accessMissing(cfg.ID) {
+		r.Status = "unreachable"
+		r.AccessMissing = true
+	}
 	return r
 }
 
+// accessMissing: el último fallo de sondeo de este router fue de ACCESO
+// (SSH responde pero la clave no está autorizada / ubus rechaza), es decir
+// el router está vivo pero el servidor no puede entrar (issue #257).
+func (l *Live) accessMissing(routerID string) bool {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	return isAccessError(l.lastErr[routerID])
+}
+
+// isAccessError: ¿el error indica que el router RESPONDE pero el acceso
+// SSH/ubus no está configurado? (handshake SSH que rechaza la clave del
+// servidor). Un fallo de conexión (refused/timeout/red) NO es un fallo de
+// acceso: ahí el router puede estar apagado o inalcanzable (issue #257).
+func isAccessError(err error) bool {
+	if err == nil {
+		return false
+	}
+	msg := strings.ToLower(err.Error())
+	for _, hint := range []string{
+		"unable to authenticate",
+		"no supported methods",
+		"permission denied",
+		"authentication failed",
+		"not authorized",
+	} {
+		if strings.Contains(msg, hint) {
+			return true
+		}
+	}
+	return false
+}
+
 // pollAll sondea todos los routers en paralelo (Promise.allSettled).
 func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 	l.mu.Lock()
@@ -917,6 +1005,7 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 		if res.err == nil {
 			polled[res.cfg.ID] = res.p
 			l.failCount[res.cfg.ID] = 0
+			delete(l.lastErr, res.cfg.ID)
 			// Persiste la bridgeMAC del router (issue #196): la exclusión de
 			// "dispositivo desconocido" no debe depender de que este router se
 			// sondee bien en el tick actual.
@@ -929,6 +1018,10 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 				if name == "" {
 					name = res.cfg.Host
 				}
+				// issue #256: la alerta crítica de offline pendiente se resuelve
+				// (marca leída) al volver online; sin esto queda "no leída" para
+				// siempre y con APs que flapean se acumulan caídas fantasma.
+				l.resolveOfflineAlerts(res.cfg.ID)
 				l.emitRouterRecovered(res.cfg.ID, name)
 			}
 			l.lastStatus[res.cfg.ID] = "online"
@@ -941,9 +1034,14 @@ func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
 		}
 		fails := l.failCount[res.cfg.ID] + 1
 		l.failCount[res.cfg.ID] = fails
+		l.lastErr[res.cfg.ID] = res.err
 		log.Printf("[netpulse] router %s inalcanzable (%d): %v", res.cfg.ID, fails, res.err)
-		// Alerta solo tras 2 fallos seguidos (un fallo suelto no es una caída)
-		if fails >= 2 && l.lastStatus[res.cfg.ID] != "offline" {
+		// Alerta solo tras 2 fallos seguidos (un fallo suelto no es una caída).
+		// issue #257: un fallo de ACCESO (SSH responde pero la clave no está
+		// autorizada) no es una caída — el router está vivo; la UI lo marca
+		// como "sin acceso" y no merece una alerta crítica de offline.
+		accessErr := isAccessError(res.err)
+		if fails >= 2 && l.lastStatus[res.cfg.ID] != "offline" && !accessErr {
 			name := res.cfg.Name
 			if name == "" {
 				name = res.cfg.Host
@@ -979,6 +1077,23 @@ func (l *Live) emitRouterRecovered(routerID, name string) {
 	})
 }
 
+// resolveOfflineAlerts resuelve las alertas de offline pendientes del router
+// (issue #256): al volver online se marcan como leídas, de modo que la caída
+// crítica no queda "no leída para siempre" y un AP que flapea no acumula
+// caídas fantasma. El evento "recuperado" (emitRouterRecovered) es el relevo
+// positivo que sustituye la caída en el feed. Debe llamarse con l.mu tomado.
+func (l *Live) resolveOfflineAlerts(routerID string) {
+	ids := []string{}
+	for _, ev := range l.engine.List() {
+		if ev.RouterID == routerID && strings.HasPrefix(ev.ID, "alert-offline-") {
+			ids = append(ids, ev.ID)
+		}
+	}
+	if len(ids) > 0 {
+		l.engine.MarkRead(ids...)
+	}
+}
+
 // trackWanDown detecta "WAN/Internet caído" (category internet, urgent true,
 // critical — SPEC-ALERTAS §1): el gateway responde por SSH pero su ping a
 // internet da 100 % de pérdida en 2 sondeos seguidos (debounce como offline).
@@ -1011,10 +1126,15 @@ func (l *Live) trackWanDown(cfg *RouterConfig, p *routerPolled) {
 
 // trackUnknownDevices emite "dispositivo desconocido se conecta" cuando un
 // cliente SIN nombre (Name == MAC, sin hostname DHCP ni alias — device_attrib
-// no guarda alias) pasa de no-online a online. El primer ciclo de sondeo del
-// proceso NO alerta (evita la avalancha de arranque: todo lo ya conectado
-// sería "nuevo"). Las MAC de la allowlist known_macs (issue #196) nunca
-// alertan, haya alias o no. Toma l.mu internamente.
+// no guarda alias) pasa de no-online a online y PERMANECE nameless durante
+// `unknownGraceNum` ticks seguidos (issue #234): un dispositivo conocido que
+// reconecta resuelve su lease DHCP en 1-2 ticks y nunca alcanza el umbral.
+// La memoria per-MAC persistida (issue #248) garantiza que cada MAC desconocida
+// alerta UNA sola vez en la vida del servidor, hasta que se confíe en
+// Settings (known_macs) o se resete. El primer ciclo de sondeo del proceso
+// NO alerta (evita la avalancha de arranque: todo lo ya conectado sería
+// "nuevo"). Las MAC de la allowlist known_macs (issue #196) nunca alertan,
+// haya alias o no. Toma l.mu internamente.
 func (l *Live) trackUnknownDevices(devices []Device) {
 	l.mu.Lock()
 	defer l.mu.Unlock()
@@ -1038,16 +1158,54 @@ func (l *Live) trackUnknownDevices(devices []Device) {
 		}
 		nowOnline[d.MAC] = true
 		if trusted[d.MAC] {
+			delete(l.unknownGrace, d.MAC)
+			continue
+		}
+		// issue #234: con hostname (lease resuelto) el dispositivo es
+		// conocido; se resetea su gracia y nunca alerta.
+		if d.Name != d.MAC {
+			delete(l.unknownGrace, d.MAC)
+			continue
+		}
+		// issue #248: esta MAC ya alertó alguna vez → no vuelve a hacerlo.
+		if l.unknownAlerted[d.MAC] {
+			delete(l.unknownGrace, d.MAC)
 			continue
 		}
-		if l.seenOnlineMacs && !l.onlineMacs[d.MAC] && d.Name == d.MAC {
-			l.emitUnknownDevice(d)
+		// Solo los dispositivos que ACABAN de conectarse (o que ya estaban en
+		// gracia) acumulan ticks; los conectados antes del arranque no entran.
+		_, counting := l.unknownGrace[d.MAC]
+		if l.seenOnlineMacs && (counting || !l.onlineMacs[d.MAC]) {
+			l.unknownGrace[d.MAC]++
+			if l.unknownGrace[d.MAC] >= l.unknownGraceNum {
+				l.emitUnknownDevice(d)
+				l.unknownAlerted[d.MAC] = true
+				l.persistUnknownAlerted(d.MAC)
+				delete(l.unknownGrace, d.MAC)
+			}
+		}
+	}
+	// La gracia solo acumula en estado "online + sin nombre": cualquier otra
+	// transición la resetea (una reconexión futura parte de cero).
+	for mac := range l.unknownGrace {
+		if !nowOnline[mac] {
+			delete(l.unknownGrace, mac)
 		}
 	}
 	l.onlineMacs = nowOnline
 	l.seenOnlineMacs = true
 }
 
+// persistUnknownAlerted guarda en kv la memoria per-MAC (issue #248) para que
+// sobreviva a reinicios del servidor. Con db nil (demo/tests) es no-op.
+// Debe llamarse con l.mu tomado.
+func (l *Live) persistUnknownAlerted(mac string) {
+	if l.db == nil {
+		return
+	}
+	_, _ = l.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "unknown_alerted:"+mac)
+}
+
 // emitUnknownDevice: evento "dispositivo desconocido se conecta" (category
 // clients, warn, NO urgente — issue #196). "Desconocido" = sin nombre/alias:
 // device_attrib no guarda alias, así que la señal práctica es un cliente sin
@@ -1651,7 +1809,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes), // SPEC-65 D65-3
 		Devices:           devices,
 		Dawn:              &DawnOverview{Available: l.dawnAvailableCached()},
-		VM:                ViewModelVersion,                                            // SPEC-65 D65-4
+		VM:                ViewModelVersion, // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),
 	}, nil
 }
@@ -2372,7 +2530,7 @@ func freqToChannel(freq int) int {
 		return (freq - 5000) / 5
 	case freq >= 5940 && freq <= 7115:
 		// 6 GHz (Wi-Fi 6E): 5950=ch1 ... 7115=ch233. Mismo (freq-5000)/5, con offset.
-		return (freq - 5950) / 5 + 1
+		return (freq-5950)/5 + 1
 	case freq == 56160:
 		return 1
 	case freq >= 56160:

+ 56 - 0
server-go/internal/adapters/live_firmware_test.go

@@ -1,6 +1,7 @@
 package adapters
 
 import (
+	"errors"
 	"strings"
 	"testing"
 )
@@ -131,3 +132,58 @@ func TestBuildRouterFirmwareSinBoard(t *testing.T) {
 		t.Fatalf("alertas=%d, esperaba 0", n)
 	}
 }
+
+// Issue #257: un gateway detectado pero SIN acceso SSH (la clave del server
+// no está autorizada) NO se muestra como "offline": status "unreachable" +
+// accessMissing true (config issue, no power issue). Un fallo de conexión
+// real (refused/timeout) sigue siendo "offline".
+func TestBuildRouterAccessMissing(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "gw", Host: "192.168.8.1", IsGateway: true}}, nil)
+	cfg := RouterConfig{ID: "gw", Host: "192.168.8.1", IsGateway: true}
+	l.mu.Lock()
+	l.lastErr["gw"] = errors.New("ssh 192.168.8.1: handshake failed: ssh: unable to authenticate, attempted methods [none publickey]")
+	l.mu.Unlock()
+	r := l.offlineRouter(cfg)
+	if r.Status != "unreachable" || !r.AccessMissing {
+		t.Fatalf("sin acceso: status=%q accessMissing=%v", r.Status, r.AccessMissing)
+	}
+	l.mu.Lock()
+	l.lastErr["gw"] = errors.New("ssh 192.168.8.1: dial tcp 192.168.8.1:22: connect: connection refused")
+	l.mu.Unlock()
+	r = l.offlineRouter(cfg)
+	if r.Status != "offline" || r.AccessMissing {
+		t.Fatalf("caído real: status=%q accessMissing=%v", r.Status, r.AccessMissing)
+	}
+	l.mu.Lock()
+	delete(l.lastErr, "gw")
+	l.mu.Unlock()
+	r = l.offlineRouter(cfg)
+	if r.Status != "offline" {
+		t.Fatalf("sin dato previo: status=%q", r.Status)
+	}
+}
+
+func TestIsAccessError(t *testing.T) {
+	for _, m := range []string{
+		"ssh h: handshake failed: ssh: unable to authenticate, attempted methods [none publickey]",
+		"ssh h: handshake failed: ssh: no supported methods remain",
+		"ssh h: permission denied (publickey)",
+	} {
+		if !isAccessError(errors.New(m)) {
+			t.Fatalf("debería ser access error: %q", m)
+		}
+	}
+	for _, m := range []string{
+		"ssh h: dial tcp h:22: connect: connection refused",
+		"ssh h: timeout (5s)",
+		"ssh h: Process exited with status 127",
+		"",
+	} {
+		if isAccessError(errors.New(m)) {
+			t.Fatalf("no debería ser access error: %q", m)
+		}
+	}
+	if isAccessError(nil) {
+		t.Fatal("nil no es access error")
+	}
+}

+ 71 - 1
server-go/internal/adapters/lldp_test.go

@@ -208,6 +208,30 @@ func TestIsLldpUnavailable(t *testing.T) {
 // Router.Lldp live (ítem 4 de C2): si los vecinos LLDP de un router incluyen
 // en su puerto de uplink a OTRO router conocido (chassis-MAC = bridge MAC de
 // otro router de la config), la tarjeta lleva Lldp; si no, se omite.
+// Issue #247: cuando lldpd NO está instalado (ErrLldpUnavailable), el
+// view-model expone `lldpAvailable:false` para que la UI muestre el hint
+// "instala lldpd". Con lldpd presente (aunque no haya vecinos) el campo se
+// omite (nil → ausente en el JSON).
+func TestBuildRouterLldpUnavailable(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "r1", Host: "192.168.8.2"}}, nil)
+	p := &routerPolled{
+		cfg:             RouterConfig{ID: "r1", Name: "Switch", Host: "192.168.8.2"},
+		lldp:            nil,
+		lldpUnavailable: true,
+	}
+	r := l.buildRouter(p, nil)
+	if r.LldpAvailable == nil || *r.LldpAvailable {
+		t.Fatalf("lldpAvailable debería ser false explícito: %+v", r.LldpAvailable)
+	}
+	p2 := &routerPolled{
+		cfg:  RouterConfig{ID: "r1", Name: "Switch", Host: "192.168.8.2"},
+		lldp: []LldpNeighbor{},
+	}
+	if r2 := l.buildRouter(p2, nil); r2.LldpAvailable != nil {
+		t.Fatalf("con lldpd presente el campo debería omitirse: %+v", r2.LldpAvailable)
+	}
+}
+
 func TestBuildRouterLldpUplink(t *testing.T) {
 	l := NewLive(nil, nil, []RouterConfig{
 		{ID: "flint2", Host: "192.168.8.1", IsGateway: true},
@@ -242,9 +266,12 @@ func TestBuildRouterLldpUplink(t *testing.T) {
 	if r := l.buildRouter(ap, nil); r.Lldp != nil {
 		t.Fatalf("anuncio por puerto distinto al del FDB: %+v", r.Lldp)
 	}
-	// Vecino LLDP que NO es un router de la config → sin campo
+	// Vecino LLDP que NO es un router de la config (ni MAC, ni IP, ni nombre)
+	// → sin campo
 	ap.fdb["94:83:C4:00:00:01"] = "lan1"
 	ap.lldp[0].ChassisMac = "28:C6:8E:1D:90:44"
+	ap.lldp[0].Chassis = "GS308E"
+	ap.lldp[0].Mgmt = "192.168.8.13"
 	if r := l.buildRouter(ap, nil); r.Lldp != nil {
 		t.Fatalf("vecino no-router: %+v", r.Lldp)
 	}
@@ -254,3 +281,46 @@ func TestBuildRouterLldpUplink(t *testing.T) {
 		t.Fatalf("sin LLDP: %+v", r.Lldp)
 	}
 }
+
+// Issue #252: en OpenWrt/GLuON lldpd suele anunciar como chassis-ID la MAC de
+// la primera interfaz (eth0/WAN), distinta de la br-lan que aprende el FDB del
+// vecino. El matching por identidad (mgmt-IP = Host del router, o nombre del
+// chasis) descubre el uplink aunque la chassis-MAC no esté entre las bridge
+// MACs de la config.
+func TestUplinkLldpIdentityFallback(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{
+		{ID: "flint2", Host: "192.168.8.1", IsGateway: true},
+		{ID: "living", Host: "192.168.8.2"},
+	}, nil)
+	gw := &routerPolled{cfg: RouterConfig{ID: "flint2", Name: "Flint 2", Host: "192.168.8.1", IsGateway: true},
+		brMac: "94:83:C4:00:00:01", fdb: map[string]string{}, lldp: []LldpNeighbor{}}
+	// El AP anuncia el gateway con chassis-ID = MAC de eth0 (NO la br-lan),
+	// pero su mgmt-IP coincide con el Host del gateway → uplink identificado.
+	ap := &routerPolled{cfg: RouterConfig{ID: "living", Name: "Living", Host: "192.168.8.2"},
+		brMac: "94:83:C4:00:00:02",
+		fdb:   map[string]string{},
+		lldp: []LldpNeighbor{{
+			Port: "lan1", Chassis: "Flint 2", ChassisMac: "94:83:C4:99:99:99",
+			Mgmt: "192.168.8.1", Caps: []string{"Bridge", "Router"}, PortDesc: "lan3",
+		}}}
+	l.lastPolled = map[string]*routerPolled{"flint2": gw, "living": ap}
+	r := l.buildRouter(ap, nil)
+	if r.Lldp == nil {
+		t.Fatal("uplink por mgmt-IP debería identificarse (fallback #252)")
+	}
+	if r.Lldp.Chassis != "Flint 2" || r.Lldp.Mgmt != "192.168.8.1" {
+		t.Fatalf("Router.Lldp: %+v", r.Lldp)
+	}
+	// Fallback por nombre del chasis (sin mgmt-IP anunciada).
+	ap.lldp[0].Mgmt = ""
+	ap.lldp[0].Chassis = "living-2" // hostname del router, no su Name config
+	ap.lldp[0].ChassisMac = "94:83:C4:99:99:98"
+	if r := l.buildRouter(ap, nil); r.Lldp != nil {
+		t.Fatalf("nombre sin coincidir no debe casar: %+v", r.Lldp)
+	}
+	ap.lldp[0].Chassis = "Flint 2"
+	ap.lldp[0].ChassisMac = "94:83:C4:99:99:98"
+	if r := l.buildRouter(ap, nil); r.Lldp == nil {
+		t.Fatal("uplink por nombre del chasis debería identificarse (fallback #252)")
+	}
+}

+ 87 - 4
server-go/internal/adapters/topology.go

@@ -86,6 +86,10 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 	if gw := pickGatewayCfg(polled); gw != nil {
 		gatewayID = gw.ID
 	}
+	// Identidades de routers para el matching LLDP tolerante (issue #252):
+	// un vecino cuya mgmt-IP/nombre coincide con un router conocido identifica
+	// el switch/AP aunque su chassis-ID no esté entre las MACs aprendidas.
+	routers := routerIdentities(polled)
 
 	for _, routerID := range routerIDs {
 		p := polled[routerID]
@@ -171,7 +175,7 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 			// entre las aprendidas identifica el switch/AP gestionado que
 			// multiplexa → nodo "managed" (evidencia positiva, válida también
 			// tras un AP; ver cabecera).
-			if nb := findManagedNeighbor(p.lldp, port, kept); nb != nil {
+			if nb := findManagedNeighbor(p.lldp, port, kept, routers, routerID); nb != nil {
 				setPort()
 				dists = append(dists, DistributionNode{
 					ID: id, Kind: "managed", RouterID: routerID, Port: port,
@@ -258,9 +262,79 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 	return devices, dists
 }
 
-// findManagedNeighbor: vecino LLDP anunciado en `port` cuya chassis-MAC está
-// entre las MACs aprendidas (nil si no hay evidencia).
-func findManagedNeighbor(neighbors []LldpNeighbor, port string, kept []string) *LldpNeighbor {
+// routerIdentity: datos de un router de la config para casar un vecino LLDP
+// aunque su chassis-ID no coincida con la bridge MAC. En OpenWrt/GLuON lldpd
+// suele anunciar como chassis la MAC de la primera interfaz (p.ej. eth0/WAN),
+// que NO es la br-lan que aprende el FDB del vecino: el matching exclusivo por
+// chassis-MAC dejaba links sin descubrir con lldpd instalado en todo (issue #252).
+type routerIdentity struct {
+	ID, Name, Host string
+	BrMac          string
+}
+
+// routerIdentities: identidades de todos los routers sondeados, en orden
+// determinista (el mapa polled no lo es).
+func routerIdentities(polled map[string]*routerPolled) []routerIdentity {
+	ids := make([]string, 0, len(polled))
+	for id := range polled {
+		ids = append(ids, id)
+	}
+	sort.Strings(ids)
+	out := make([]routerIdentity, 0, len(ids))
+	for _, id := range ids {
+		p := polled[id]
+		out = append(out, routerIdentity{ID: id, Name: p.cfg.Name, Host: p.cfg.Host, BrMac: p.brMac})
+	}
+	return out
+}
+
+// neighborIsRouter: el vecino LLDP identifica a un router conocido de la
+// config. Coincide por cualquiera de (prioridad): chassis-MAC = bridge MAC
+// (matching original, SPEC C2), mgmt-IP = Host, o nombre del chasis ≈ nombre
+// del router (case-insensitive). Los dos últimos son el fix tolerante al
+// chassis-ID distinto de la br-lan (issue #252). selfID se excluye (un router
+// no es su propio vecino). nil si no hay coincidencia.
+func neighborIsRouter(nb *LldpNeighbor, routers []routerIdentity, selfID string) *routerIdentity {
+	if nb == nil {
+		return nil
+	}
+	for i := range routers {
+		r := &routers[i]
+		if r.ID == selfID {
+			continue
+		}
+		if nb.ChassisMac != "" && r.BrMac != "" && strings.EqualFold(nb.ChassisMac, r.BrMac) {
+			return r
+		}
+	}
+	for i := range routers {
+		r := &routers[i]
+		if r.ID == selfID {
+			continue
+		}
+		if nb.Mgmt != "" && r.Host != "" && nb.Mgmt == r.Host {
+			return r
+		}
+	}
+	for i := range routers {
+		r := &routers[i]
+		if r.ID == selfID {
+			continue
+		}
+		if nb.Chassis != "" && r.Name != "" && strings.EqualFold(nb.Chassis, r.Name) {
+			return r
+		}
+	}
+	return nil
+}
+
+// findManagedNeighbor: vecino LLDP anunciado en `port` que identifica el
+// equipo que multiplexa ese puerto multi-MAC (nil si no hay evidencia).
+//  1. matching estricto: chassis-MAC entre las MACs aprendidas del puerto.
+//  2. fallback #252: la identidad del vecino (mgmt-IP o nombre del chasis)
+//     coincide con un router conocido de la config → ese router ES el switch/AP
+//     que multiplexa, aunque su chassis-ID no esté en el FDB.
+func findManagedNeighbor(neighbors []LldpNeighbor, port string, kept []string, routers []routerIdentity, selfID string) *LldpNeighbor {
 	for i := range neighbors {
 		nb := &neighbors[i]
 		if nb.Port != port || nb.ChassisMac == "" {
@@ -272,5 +346,14 @@ func findManagedNeighbor(neighbors []LldpNeighbor, port string, kept []string) *
 			}
 		}
 	}
+	for i := range neighbors {
+		nb := &neighbors[i]
+		if nb.Port != port {
+			continue
+		}
+		if r := neighborIsRouter(nb, routers, selfID); r != nil {
+			return nb
+		}
+	}
 	return nil
 }

+ 46 - 0
server-go/internal/adapters/topology_test.go

@@ -330,6 +330,52 @@ func TestInferTopologyManagedTrasAP(t *testing.T) {
 	}
 }
 
+// Issue #252: switch gestionado que es un router de la config cuyo chassis-ID
+// anunciado NO está entre las MACs aprendidas (lldpd anuncia la MAC de la 1ª
+// interfaz, no la br-lan), pero su mgmt-IP coincide con su Host → el puerto
+// multi-MAC se promueve a "managed" igualmente.
+func TestInferTopologyManagedPorIdentidad(t *testing.T) {
+	polled := map[string]*routerPolled{
+		"flint2": {cfg: RouterConfig{ID: "flint2", IsGateway: true}, brMac: "94:83:C4:00:00:01",
+			fdb: map[string]string{
+				"04:D4:C4:8B:30:A7": "lan3", // PC tras el switch
+				"DC:A6:32:4F:77:02": "lan3", // Raspberry tras el switch
+			}},
+		"switch1": {cfg: RouterConfig{ID: "switch1", Name: "LGS352C", Host: "192.168.8.20", Type: "managed-switch", AgentOnly: true},
+			brMac: "94:83:C4:00:00:0A", fdb: map[string]string{}},
+	}
+	// El gateway recibe el anuncio del switch en lan3 con chassis-MAC que NO
+	// está en su FDB, pero con mgmt-IP = Host del switch.
+	polled["flint2"].lldp = []LldpNeighbor{{
+		Port: "lan3", Chassis: "lgs352c", ChassisMac: "AA:BB:CC:DD:EE:0A",
+		Mgmt: "192.168.8.20", Caps: []string{"Bridge"}, PortDesc: "lan3",
+	}}
+	devices := []Device{
+		dev("04:D4:C4:8B:30:A7", "flint2", "cable"),
+		dev("DC:A6:32:4F:77:02", "flint2", "cable"),
+	}
+	devices, dists := inferTopology(polled, devices)
+	if len(dists) != 1 {
+		t.Fatalf("distnodes: %+v", dists)
+	}
+	dn := dists[0]
+	if dn.Kind != "managed" || dn.ID != "dist-flint2-lan3" || dn.Name != "lgs352c" || dn.Ip != "192.168.8.20" {
+		t.Fatalf("managed por identidad: %+v", dn)
+	}
+	for _, d := range devices {
+		if d.AttachTo != "dist-flint2-lan3" {
+			t.Fatalf("%s debería colgar del nodo managed: %q", d.MAC, d.AttachTo)
+		}
+	}
+	// Sin coincidencia de identidad → vuelve a "inferred" (no se afirma nada).
+	polled["flint2"].lldp[0].Mgmt = "192.168.8.99"
+	polled["flint2"].lldp[0].Chassis = "otro-equipo"
+	_, dists = inferTopology(polled, devices)
+	if len(dists) != 1 || dists[0].Kind != "inferred" {
+		t.Fatalf("sin identidad debería seguir inferred: %+v", dists)
+	}
+}
+
 // Vecino LLDP cuya chassis-MAC es un Device conocido en puerto de UNA sola
 // MAC (cableado directo): no hay nodo, pero el Device queda identificado.
 func TestInferTopologyLldpIdentificaDeviceDirecto(t *testing.T) {

+ 10 - 1
server-go/internal/adapters/types.go

@@ -143,8 +143,12 @@ type Router struct {
 	// para NO ofrecer reinstall/upgrade de agentes en dispositivos que no usan
 	// el agente nativo (scrapers de switches, etc.).
 	Type string `json:"type,omitempty"`
-	Status     string    `json:"status"`             // "online"|"warn"|"offline"
+	Status     string    `json:"status"`             // "online"|"warn"|"offline"|"unreachable"
 	Health     int       `json:"health"`
+	// AccessMissing: el router responde pero el acceso SSH/ubus no está
+	// configurado (clave del servidor no autorizada) — issue #257. La UI lo
+	// pinta como "sin acceso" en vez de "offline" (config issue, no power).
+	AccessMissing bool `json:"accessMissing,omitempty"`
 	CPU        *int      `json:"cpu"`
 	RAM        *int      `json:"ram"`
 	Temp       *int      `json:"temp"`
@@ -159,6 +163,11 @@ type Router struct {
 	// (uplink identificado por LLDP). Ausente si no hay dato — la app lo usa
 	// para el sufijo "· LLDP" en la etiqueta del uplink.
 	Lldp *LldpInfo `json:"lldp,omitempty"`
+	// LldpAvailable: nil = sin dato (lldpd presente o sonda aún no ejecutada);
+	// false = lldpd NO está instalado en el router (ErrLldpUnavailable) — la
+	// UI muestra el hint "instala lldpd" para identificar switches gestionados
+	// (issue #247). Nunca emite true (ausente = OK).
+	LldpAvailable *bool `json:"lldpAvailable,omitempty"`
 }
 
 // DeviceTotals del overview (quirk: NewToday=0 en live).

+ 12 - 2
server-go/internal/auth/auth.go

@@ -393,18 +393,28 @@ func LoginRateLimited(d *db.DB, r *http.Request) (limited bool, retryAfterSec in
 
 // RegisterLoginFail registra un fallo: bloquea 5 min cuando el valor ANTERIOR
 // de attempts >= 4 (el bloqueo se arma en el 5º fallo — UPSERT literal).
+// Decay (issue #211): si el bloqueo previo ya expiró (locked_until en el
+// pasado), la cuenta se resetea a 1 y el marcador se limpia — un fallo suelto
+// (o un typo) tras el lockout ya no lo rearma al instante, evitando el
+// lockout casi permanente por IP. Una ráfaga nueva de 5 fallos tras la
+// expiración vuelve a armar el bloqueo.
 func RegisterLoginFail(d *db.DB, r *http.Request) {
 	ip := ClientIP(r)
+	now := db.NowMS()
 	_, _ = d.Exec(`
 		INSERT INTO login_attempts (ip, attempts, locked_until)
 		VALUES (?, 1, 0)
 		ON CONFLICT(ip) DO UPDATE SET
-		  attempts = attempts + 1,
+		  attempts = CASE
+		    WHEN locked_until > 0 AND locked_until <= ? THEN 1
+		    ELSE attempts + 1
+		  END,
 		  locked_until = CASE
+		    WHEN locked_until > 0 AND locked_until <= ? THEN 0
 		    WHEN attempts >= 4 THEN ?
 		    ELSE locked_until
 		  END
-	`, ip, db.NowMS()+LockMS)
+	`, ip, now, now, now+LockMS)
 }
 
 // LoginOk borra la fila de login_attempts de la IP.

+ 141 - 1
server-go/internal/auth/auth_test.go

@@ -21,7 +21,7 @@ func testDB(t *testing.T) *db.DB {
 }
 
 func testCfg() *config.Config {
-	return &config.Config{AuthUser: "admin", AuthPass: "test1234", CookieSecure: "auto"}
+	return &config.Config{AuthUser: "admin", AuthPass: "test123456", CookieSecure: "auto"}
 }
 
 func TestSignVerifyRoundtrip(t *testing.T) {
@@ -179,6 +179,146 @@ func TestRateLimitFifthFailArmsLock(t *testing.T) {
 	}
 }
 
+func TestLoginAttemptsDecayTrasLockExpired(t *testing.T) {
+	// Issue #211: tras expirar el lockout (5 min), un fallo suelto ya NO
+	// rearma el bloqueo — la cuenta decae a 1.
+	SetTrustProxy(true)
+	t.Cleanup(func() { SetTrustProxy(false) })
+	d := testDB(t)
+	newReq := func() *http.Request {
+		r := httptest.NewRequest("POST", "/api/auth/login", nil)
+		r.Header.Set("X-Forwarded-For", "10.9.9.9, 10.0.0.1")
+		return r
+	}
+	for i := 0; i < 5; i++ {
+		RegisterLoginFail(d, newReq())
+	}
+	if limited, _ := LoginRateLimited(d, newReq()); !limited {
+		t.Fatal("tras 5 fallos debe estar bloqueado")
+	}
+	// El lockout expira.
+	_, _ = d.Exec("UPDATE login_attempts SET locked_until = ? WHERE ip = '10.9.9.9'", db.NowMS()-1)
+	// Un fallo suelto tras la expiración no rearma el lockout.
+	RegisterLoginFail(d, newReq())
+	if limited, _ := LoginRateLimited(d, newReq()); limited {
+		t.Fatal("un fallo tras expirar el lockout no debe rearmarlo")
+	}
+	var attempts int
+	var lockedUntil int64
+	if err := d.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
+		Scan(&attempts, &lockedUntil); err != nil {
+		t.Fatal(err)
+	}
+	if attempts != 1 || lockedUntil != 0 {
+		t.Fatalf("tras el decay esperaba attempts=1 locked_until=0, got %d %d", attempts, lockedUntil)
+	}
+}
+
+func TestLoginAttemptsRearmanTrasBurstNuevo(t *testing.T) {
+	// Issue #211: tras el decay, una ráfaga nueva de 5 fallos vuelve a
+	// armar el bloqueo (no se queda desarmado para siempre).
+	SetTrustProxy(true)
+	t.Cleanup(func() { SetTrustProxy(false) })
+	d := testDB(t)
+	newReq := func() *http.Request {
+		r := httptest.NewRequest("POST", "/api/auth/login", nil)
+		r.Header.Set("X-Forwarded-For", "10.9.9.9, 10.0.0.1")
+		return r
+	}
+	for i := 0; i < 5; i++ {
+		RegisterLoginFail(d, newReq())
+	}
+	_, _ = d.Exec("UPDATE login_attempts SET locked_until = ? WHERE ip = '10.9.9.9'", db.NowMS()-1)
+	// Decay: primer fallo tras la expiración resetea a 1.
+	RegisterLoginFail(d, newReq())
+	if limited, _ := LoginRateLimited(d, newReq()); limited {
+		t.Fatal("el primer fallo tras expirar no debe rearmar")
+	}
+	// Ráfaga nueva completa: 5 fallos seguidos vuelven a armar el lockout.
+	for i := 0; i < 5; i++ {
+		RegisterLoginFail(d, newReq())
+	}
+	if limited, _ := LoginRateLimited(d, newReq()); !limited {
+		t.Fatal("una ráfaga nueva de 5 fallos debe rearmar el lockout")
+	}
+}
+
+func TestRequireSameOrigin(t *testing.T) {
+	// Issue #213: mutaciones (POST/PUT/DELETE) validan Origin contra el host.
+	SetTrustProxy(true)
+	t.Cleanup(func() { SetTrustProxy(false) })
+	next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
+	h := RequireSameOrigin(next)
+
+	// POST sin Origin (cliente no-navegador) → pasa.
+	rec := httptest.NewRecorder()
+	h.ServeHTTP(rec, httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil))
+	if rec.Code != http.StatusNoContent {
+		t.Fatalf("POST sin Origin debe pasar, got %d", rec.Code)
+	}
+
+	// POST con Origin == Host → pasa.
+	req := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
+	req.Header.Set("Origin", "http://192.168.1.226:3000")
+	rec2 := httptest.NewRecorder()
+	h.ServeHTTP(rec2, req)
+	if rec2.Code != http.StatusNoContent {
+		t.Fatalf("POST Origin==Host debe pasar, got %d", rec2.Code)
+	}
+
+	// POST con Origin distinto → 403 cross_origin.
+	req2 := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
+	req2.Header.Set("Origin", "https://evil.example")
+	rec3 := httptest.NewRecorder()
+	h.ServeHTTP(rec3, req2)
+	if rec3.Code != http.StatusForbidden {
+		t.Fatalf("POST Origin distinto debe dar 403, got %d", rec3.Code)
+	}
+
+	// POST con Origin null (iframe sandbox) → 403.
+	req3 := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
+	req3.Header.Set("Origin", "null")
+	rec4 := httptest.NewRecorder()
+	h.ServeHTTP(rec4, req3)
+	if rec4.Code != http.StatusForbidden {
+		t.Fatalf("POST Origin null debe dar 403, got %d", rec4.Code)
+	}
+
+	// GET no se valida (no es mutación).
+	req4 := httptest.NewRequest("GET", "http://192.168.1.226:3000/api/x", nil)
+	req4.Header.Set("Origin", "https://evil.example")
+	rec5 := httptest.NewRecorder()
+	h.ServeHTTP(rec5, req4)
+	if rec5.Code != http.StatusNoContent {
+		t.Fatalf("GET con Origin distinto no debe validarse, got %d", rec5.Code)
+	}
+
+	// Sec-Fetch-Site: cross-site sin Origin → 403.
+	req5 := httptest.NewRequest("POST", "http://192.168.1.226:3000/api/x", nil)
+	req5.Header.Set("Sec-Fetch-Site", "cross-site")
+	rec6 := httptest.NewRecorder()
+	h.ServeHTTP(rec6, req5)
+	if rec6.Code != http.StatusForbidden {
+		t.Fatalf("POST Sec-Fetch-Site=cross-site debe dar 403, got %d", rec6.Code)
+	}
+}
+
+func TestEffectiveHostConfiaEnXFH(t *testing.T) {
+	// Con TRUST_PROXY, X-Forwarded-Host (primer valor) es el host efectivo.
+	SetTrustProxy(true)
+	t.Cleanup(func() { SetTrustProxy(false) })
+	r := httptest.NewRequest("POST", "http://internal:3000/api/x", nil)
+	r.Header.Set("X-Forwarded-Host", "netpulse.example.com, internal:3000")
+	if got := effectiveHost(r); got != "netpulse.example.com" {
+		t.Fatalf("effectiveHost con XFH: %q", got)
+	}
+	// Sin TRUST_PROXY, XFH se ignora.
+	SetTrustProxy(false)
+	if got := effectiveHost(r); got != "internal:3000" {
+		t.Fatalf("effectiveHost sin TRUST_PROXY: %q", got)
+	}
+}
+
 func TestBuildSessionCookieFlags(t *testing.T) {
 	// El caso X-Forwarded-Proto=https requiere TRUST_PROXY (auditoría #1).
 	SetTrustProxy(true)

+ 55 - 0
server-go/internal/auth/middleware.go

@@ -5,6 +5,7 @@ import (
 	"context"
 	"encoding/json"
 	"net/http"
+	"net/url"
 	"strings"
 
 	"github.com/gnacho/netpulse/server-go/internal/db"
@@ -82,3 +83,57 @@ func RequireAdmin(next http.Handler) http.Handler {
 		next.ServeHTTP(w, r)
 	})
 }
+
+// RequireSameOrigin es la defensa CSRF (issue #213). SameSite=Lax cubre el
+// envío de cookies cross-site de fetch/XHR, pero no hay defensa en
+// profundidad si la app se sirve desde otro origen o un navegador sin
+// SameSite. En mutaciones (POST/PUT/DELETE) se valida el header Origin contra
+// el host efectivo de la petición (X-Forwarded-Host si TRUST_PROXY, si no
+// r.Host). Un Origin ausente (cliente no-navegador: agente, curl, CLI) se
+// deja pasar; si el navegador envía Sec-Fetch-Site: cross-site sin Origin, se
+// rechaza igualmente. Un Origin que no casa → 403 {error:'cross_origin'}.
+func RequireSameOrigin(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete {
+			if !originAllowed(r) {
+				WriteError(w, http.StatusForbidden, "cross_origin")
+				return
+			}
+		}
+		next.ServeHTTP(w, r)
+	})
+}
+
+// originAllowed valida el header Origin (si viene) contra el host efectivo.
+func originAllowed(r *http.Request) bool {
+	origin := r.Header.Get("Origin")
+	if origin == "" {
+		if sf := r.Header.Get("Sec-Fetch-Site"); sf != "" {
+			return sf != "cross-site"
+		}
+		return true
+	}
+	u, err := url.Parse(origin)
+	if err != nil {
+		return false
+	}
+	// Origin "null" (iframe sandbox / redirect) no tiene host → no casa.
+	if u.Host == "" {
+		return false
+	}
+	return strings.EqualFold(u.Host, effectiveHost(r))
+}
+
+// effectiveHost devuelve el host al que el cliente cree estar llamando:
+// X-Forwarded-Host (si TRUST_PROXY) o r.Host. Sin TRUST_PROXY, un header
+// falseado no puede eludir la comprobación.
+func effectiveHost(r *http.Request) string {
+	if trustProxy {
+		if xfh := r.Header.Get("X-Forwarded-Host"); xfh != "" {
+			if first := strings.TrimSpace(strings.Split(xfh, ",")[0]); first != "" {
+				return first
+			}
+		}
+	}
+	return r.Host
+}

+ 8 - 1
server-go/internal/config/config.go

@@ -184,9 +184,16 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 
 	// AUTH_PASS: obligatoria (fail-fast) aunque ya existan usuarios — salvo
 	// en on-box, donde el bootstrap R4 genera una si falta (cmd/netpulse).
+	// Longitud mínima 10, igual que la policy de los endpoints de cambio
+	// (issue #216): un seed corto crearía un admin con contraseña trivial sin
+	// que nadie lo valide después.
 	authPass := ""
 	if v, ok := env["AUTH_PASS"]; ok && v != "" {
-		authPass = v
+		if len(v) < 10 {
+			errs.issues = append(errs.issues, issue{"AUTH_PASS", "String must contain at least 10 character(s)"})
+		} else {
+			authPass = v
+		}
 	} else if !onbox {
 		errs.issues = append(errs.issues, issue{"AUTH_PASS", "Required"})
 	}

+ 16 - 2
server-go/internal/config/config_test.go

@@ -41,15 +41,29 @@ func TestLoadOnboxConAuthPass(t *testing.T) {
 	}
 }
 
+func TestLoadAuthPassMinLength(t *testing.T) {
+	_, err := Load(map[string]string{"AUTH_PASS": "corta"}, t.TempDir())
+	if err == nil || !strings.Contains(err.Error(), "AUTH_PASS") {
+		t.Fatalf("AUTH_PASS corto debe fallar señalando la variable: %v", err)
+	}
+	cfg, err := Load(map[string]string{"AUTH_PASS": "diez-carac-"}, t.TempDir())
+	if err != nil {
+		t.Fatalf("AUTH_PASS de 10 caracteres no debe fallar: %v", err)
+	}
+	if cfg.AuthPass != "diez-carac-" {
+		t.Fatalf("AuthPass = %q, esperaba diez-carac-", cfg.AuthPass)
+	}
+}
+
 func TestLoadOnboxEnumInvalido(t *testing.T) {
-	_, err := Load(map[string]string{"NETPULSE_ONBOX": "2", "AUTH_PASS": "x"}, t.TempDir())
+	_, err := Load(map[string]string{"NETPULSE_ONBOX": "2", "AUTH_PASS": "segura-y-larga"}, t.TempDir())
 	if err == nil || !strings.Contains(err.Error(), "NETPULSE_ONBOX") {
 		t.Fatalf("NETPULSE_ONBOX=2 debe fallar señalando la variable: %v", err)
 	}
 }
 
 func TestLoadOnboxCeroEquivaleAHoy(t *testing.T) {
-	cfg, err := Load(map[string]string{"NETPULSE_ONBOX": "0", "AUTH_PASS": "x"}, t.TempDir())
+	cfg, err := Load(map[string]string{"NETPULSE_ONBOX": "0", "AUTH_PASS": "segura-y-larga"}, t.TempDir())
 	if err != nil {
 		t.Fatalf("Load: %v", err)
 	}

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

@@ -50,7 +50,7 @@ func do(t *testing.T, method, base, path, cookie string) *http.Response {
 
 func TestRutasAdminDevuelven403ParaRolUser(t *testing.T) {
 	ts := makeTestServer(t)
-	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewer", "clave12345", "user")
 
 	adminOnly := []struct{ method, path string }{

+ 5 - 1
server-go/internal/httpapi/agent.go

@@ -289,7 +289,11 @@ func (s *server) handleAgentsCreate(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		Slug string `json:"slug"`
 	}
-	if !readJSONBody(r, &body) || !agentSlugRe.MatchString(body.Slug) {
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", `Se esperaba { "slug": "<equipo>" } (a-z, 0-9, guiones)`)
+		return
+	}
+	if !agentSlugRe.MatchString(body.Slug) {
 		writeError(w, http.StatusBadRequest, "invalid_body",
 			`Se esperaba { "slug": "<equipo>" } (a-z, 0-9, guiones)`)
 		return

+ 2 - 2
server-go/internal/httpapi/agent_api_test.go

@@ -42,7 +42,7 @@ func makeAgentTestServer(t *testing.T) *agentTestServer {
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -66,7 +66,7 @@ func makeAgentTestServer(t *testing.T) *agentTestServer {
 		Agents: reg, Started: time.Now(),
 	})
 	srv := httptest.NewServer(handler)
-	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if status != 204 {
 		t.Fatalf("login: %d", status)
 	}

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

@@ -46,7 +46,7 @@ func alertItems(t *testing.T, res *http.Response) []map[string]any {
 
 func TestAlertsContractFields(t *testing.T) {
 	ts := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 
 	res := get(t, ts.URL, "/api/alerts", cookie)
 	items := alertItems(t, res)
@@ -94,7 +94,7 @@ func TestAlertsContractFields(t *testing.T) {
 
 func TestAlertsConfigEndpoints(t *testing.T) {
 	ts := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 
 	res := get(t, ts.URL, "/api/alerts/config", cookie)
 	cfg := readJSON(t, res)
@@ -144,7 +144,7 @@ func TestAlertsConfigEndpoints(t *testing.T) {
 
 func TestAlertsReadEndpoints(t *testing.T) {
 	ts := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 
 	unreadOf := func() float64 {
 		res := get(t, ts.URL, "/api/overview", cookie)
@@ -187,7 +187,7 @@ func TestAlertsReadEndpoints(t *testing.T) {
 // writeJSON sin '\n' final (paridad D5, SPEC-ALERTAS §4).
 func TestAlertsNoTrailingNewline(t *testing.T) {
 	ts := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	res := get(t, ts.URL, "/api/alerts/config", cookie)
 	defer res.Body.Close()
 	raw, _ := io.ReadAll(res.Body)

+ 5 - 1
server-go/internal/httpapi/auth.go

@@ -22,7 +22,11 @@ func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
 		Username *string `json:"username"`
 		Password *string `json:"password"`
 	}
-	if !readJSONBody(r, &body) || body.Username == nil || body.Password == nil ||
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", `Se esperaba { "username": string, "password": string }`)
+		return
+	}
+	if body.Username == nil || body.Password == nil ||
 		len(*body.Username) < 1 || len(*body.Username) > 64 || len(*body.Password) < 1 {
 		writeError(w, http.StatusBadRequest, "invalid_body",
 			`Se esperaba { "username": string, "password": string }`)

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

@@ -23,7 +23,7 @@ type availabilityEntry struct {
 
 func getAvailability(t *testing.T, ts *testServer, query string) (int, []availabilityEntry) {
 	t.Helper()
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	url := ts.URL + "/api/reports/availability" + query
 	req, _ := http.NewRequest("GET", url, nil)
 	req.Header.Set("Cookie", "session="+cookie)

+ 15 - 2
server-go/internal/httpapi/backup.go

@@ -3,6 +3,7 @@ package httpapi
 import (
 	"database/sql"
 	"fmt"
+	"log"
 	"net/http"
 	"os"
 	"path/filepath"
@@ -58,8 +59,8 @@ func (s *server) registerBackupRoutes(mux *http.ServeMux) {
 			FrequencyH    *int  `json:"frequency_h"`
 			RetentionDays *int  `json:"retention_days"`
 		}
-		if !readJSONBody(r, &body) {
-			writeError(w, http.StatusBadRequest, "invalid_body")
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "")
 			return
 		}
 
@@ -124,6 +125,14 @@ func (s *server) registerBackupRoutes(mux *http.ServeMux) {
 		})
 	})))
 
+	// GET /api/backup/download (admin) — descarga la BD COMPLETA, incluidos
+	// los secrets del kv en claro (session_secret, adguard_pass, tokens de
+	// agente/pairing) y webhook_events. Es un backup fiel para restaurar en
+	// otro host: NO se redacta nada (una redacción rompería la restauración).
+	// El riesgo queda acotado a (issue #218): RequireAdmin; el admin ya puede
+	// leer la DB en disco (el mismo acceso); aviso explícito en el header
+	// X-Netpulse-Backup-Contains-Credentials; y una línea de auditoría en el
+	// log on-box con el admin que descargó.
 	mux.Handle("GET /api/backup/download", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		backupDir := filepath.Join(filepath.Dir(s.db.Path), "backups")
 		os.MkdirAll(backupDir, 0755)
@@ -134,6 +143,10 @@ func (s *server) registerBackupRoutes(mux *http.ServeMux) {
 		}
 		defer os.Remove(tmpFile)
 
+		if u := auth.UserFromContext(r.Context()); u != nil {
+			log.Printf("[netpulse] backup: descarga completa de la BD (incluye secrets kv) por admin %s", u.Username)
+		}
+		w.Header().Set("X-Netpulse-Backup-Contains-Credentials", "true")
 		w.Header().Set("Content-Type", "application/octet-stream")
 		w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-%s.db"`, time.Now().UTC().Format("20060102-150405")))
 		http.ServeFile(w, r, tmpFile)

+ 38 - 0
server-go/internal/httpapi/backup_test.go

@@ -0,0 +1,38 @@
+// backup_test.go — issue #218: el download de la BD completa queda
+// restringido a admin y avisa explícitamente de que contiene secrets kv.
+package httpapi_test
+
+import (
+	"net/http"
+	"testing"
+)
+
+func TestBackupDownloadAdminHeaderYGate(t *testing.T) {
+	srv := makeTestServer(t)
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// Admin: 200 + aviso explícito de que la descarga lleva secrets.
+	req, _ := http.NewRequest("GET", srv.URL+"/api/backup/download", nil)
+	req.AddCookie(&http.Cookie{Name: "session", Value: adminCookie})
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("download: %v", err)
+	}
+	res.Body.Close()
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("download admin: got %d want 200", res.StatusCode)
+	}
+	if res.Header.Get("X-Netpulse-Backup-Contains-Credentials") != "true" {
+		t.Fatal("la descarga debe avisar de que contiene credenciales")
+	}
+
+	// Sin sesión: no debe servir el backup.
+	res2, err := http.Get(srv.URL + "/api/backup/download")
+	if err != nil {
+		t.Fatalf("download sin sesión: %v", err)
+	}
+	res2.Body.Close()
+	if res2.StatusCode == http.StatusOK {
+		t.Fatal("el download sin sesión debe rechazarse")
+	}
+}

+ 6 - 6
server-go/internal/httpapi/config.go

@@ -110,8 +110,8 @@ func validateHost(host string) (string, string) {
 // POST /api/config/routers — añadir router manualmente desde Ajustes.
 func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 	var in routerInput
-	if !readJSONBody(r, &in) {
-		writeError(w, http.StatusBadRequest, "invalid_json")
+	if st := readJSONBody(w, r, &in); st != 0 {
+		writeBodyError(w, st, "invalid_json", "")
 		return
 	}
 	// Orden de validación del schema zod: name, host, type
@@ -181,8 +181,8 @@ func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request
 func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
 	id := r.PathValue("id")
 	var in routerInput
-	if !readJSONBody(r, &in) {
-		writeError(w, http.StatusBadRequest, "invalid_json")
+	if st := readJSONBody(w, r, &in); st != 0 {
+		writeBodyError(w, st, "invalid_json", "")
 		return
 	}
 	var name *string
@@ -275,8 +275,8 @@ type adguardInput struct {
 // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
 func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
 	var in adguardInput
-	if !readJSONBody(r, &in) {
-		writeError(w, http.StatusBadRequest, "invalid_json")
+	if st := readJSONBody(w, r, &in); st != 0 {
+		writeBodyError(w, st, "invalid_json", "")
 		return
 	}
 	if in.Host == nil {

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

@@ -35,7 +35,7 @@ func doReq(t *testing.T, method, url, cookie, body string) *http.Response {
 // TestConfigRoutersCRUD replica routers.test.js.
 func TestConfigRoutersCRUD(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// GET inicial: lista vacía (200)
 	res := doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
@@ -147,7 +147,7 @@ func TestConfigRoutersCRUD(t *testing.T) {
 //   - la respuesta incluye publicKey + fingerprint
 func TestRotateSSHKey(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// Sin admin → 403.
 	res := doReq(t, "POST", srv.URL+"/api/config/sshkey/rotate", "", "")
@@ -189,7 +189,7 @@ func TestRotateSSHKey(t *testing.T) {
 //   - PUT no-admin → 401/403 (lo cubre admin_gate_test.go)
 func TestConfigRoutersUpdate(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// Setup: dos routers (rt1 no-gateway, gw gateway).
 	res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
@@ -276,7 +276,7 @@ func TestConfigRoutersUpdate(t *testing.T) {
 // alta con target, PUT que lo actualiza y persistencia en la lista.
 func TestConfigRoutersFirmwareTarget(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// POST con firmware_target → 201 y el router devuelto lo lleva.
 	res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,

+ 7 - 3
server-go/internal/httpapi/data.go

@@ -259,7 +259,11 @@ func (s *server) handleAlertsConfigGet(w http.ResponseWriter, _ *http.Request) {
 // categorías y niveles (400 en inválido, SPEC-ALERTAS §4).
 func (s *server) handleAlertsConfigPut(w http.ResponseWriter, r *http.Request) {
 	var patch map[string]string
-	if !readJSONBody(r, &patch) || patch == nil {
+	if st := readJSONBody(w, r, &patch); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	if patch == nil {
 		writeError(w, http.StatusBadRequest, "invalid_body", "body JSON inválido")
 		return
 	}
@@ -275,8 +279,8 @@ func (s *server) handleAlertsRead(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		IDs []string `json:"ids"`
 	}
-	if !readJSONBody(r, &body) {
-		writeError(w, http.StatusBadRequest, "invalid_body", "body JSON inválido")
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
 		return
 	}
 	s.adapter.AlertsEngine().MarkRead(body.IDs...)

+ 2 - 2
server-go/internal/httpapi/demo_test.go

@@ -12,7 +12,7 @@ import (
 
 func TestDemoEnable403ParaRolUser(t *testing.T) {
 	ts := makeTestServer(t)
-	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	userCookie := createUserAndLogin(t, ts.URL, adminCookie, "viewerdemo", "clave12345", "user")
 
 	res := do(t, "POST", ts.URL, "/api/demo/enable", userCookie)
@@ -36,7 +36,7 @@ func TestDemoEnable401SinSesion(t *testing.T) {
 
 func TestDemoEnable409CuandoYaDemo(t *testing.T) {
 	ts := makeDemoTestServer(t) // DEMO_MODE=1
-	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, adminCookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	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)

+ 3 - 3
server-go/internal/httpapi/demoreadonly_test.go

@@ -24,7 +24,7 @@ import (
 // refresh, push, users/me) sigue funcionando.
 func TestDemoReadOnly(t *testing.T) {
 	ts := makeDemoTestServer(t)
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	if cookie == "" {
 		t.Fatal("login no devolvió cookie")
 	}
@@ -98,7 +98,7 @@ func makeDemoAgentTestServer(t *testing.T) *agentTestServer {
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -122,7 +122,7 @@ func makeDemoAgentTestServer(t *testing.T) *agentTestServer {
 		Agents: reg, Started: time.Now(),
 	})
 	srv := httptest.NewServer(handler)
-	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if status != 204 {
 		t.Fatalf("login: %d", status)
 	}

+ 2 - 2
server-go/internal/httpapi/device_events_test.go

@@ -21,7 +21,7 @@ func TestDeviceEventsProtegido(t *testing.T) {
 	}
 
 	// Login y siembra de 2 eventos (la tabla la crea el schema al arrancar).
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if _, err := srv.db.Exec(
 		"INSERT INTO device_events (ts_ms, mac, router_id, state, signal_dbm) VALUES (?,?,?,?,?), (?,?,?,?,?)",
 		1000, "AA:BB:CC:DD:EE:01", "rt1", "offline", nil,
@@ -57,7 +57,7 @@ func TestDeviceEventsFiltros(t *testing.T) {
 	); err != nil {
 		t.Fatalf("seed: %v", err)
 	}
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// Filtro state=online → 1.
 	res := get(t, srv.URL, "/api/device-events?state=online", cookie)

+ 2 - 2
server-go/internal/httpapi/display_name_test.go

@@ -10,7 +10,7 @@ import (
 // SPEC-65 D65-5: display name por usuario — roundtrip completo.
 func TestDisplayNameRoundtrip(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// Al inicio: displayName "" (no puesto)
 	res := get(t, srv.URL, "/api/auth/me", cookie)
@@ -92,7 +92,7 @@ func TestDisplayNameRoundtrip(t *testing.T) {
 // GET /api/users incluye displayName por usuario (admin).
 func TestListUsersIncluyeDisplayName(t *testing.T) {
 	srv := makeTestServer(t)
-	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// Alta de una usuaria no-admin y display name propio (fuera del gate admin)
 	req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"clave-ana-1","role":"user"}`))

+ 61 - 12
server-go/internal/httpapi/httpapi_test.go

@@ -8,6 +8,7 @@ import (
 	"io"
 	"net/http"
 	"net/http/httptest"
+	"net/url"
 	"strings"
 	"testing"
 	"time"
@@ -55,7 +56,7 @@ func makeTestServerWithMode(t *testing.T, demoMode bool) *testServer {
 		demo = "1"
 	}
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": demo, "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -154,7 +155,7 @@ func TestLoginIncorrecto401(t *testing.T) {
 
 func TestLoginCorrectoYMe(t *testing.T) {
 	srv := makeTestServer(t)
-	status, cookie, setCookie := loginCookie(t, srv.URL, "admin", "test1234")
+	status, cookie, setCookie := loginCookie(t, srv.URL, "admin", "test123456")
 	if status != 204 {
 		t.Fatalf("status: got %d want 204", status)
 	}
@@ -190,7 +191,7 @@ func TestOverviewProtegido(t *testing.T) {
 	if body["error"] != "unauthorized" {
 		t.Fatalf("error: %v", body)
 	}
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	res2 := get(t, srv.URL, "/api/overview", cookie)
 	if res2.StatusCode != 200 {
 		t.Fatalf("con cookie: got %d want 200", res2.StatusCode)
@@ -216,7 +217,7 @@ func TestOverviewProtegido(t *testing.T) {
 
 func TestLogoutRevocaSesion(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	req, _ := http.NewRequest("POST", srv.URL+"/api/auth/logout", nil)
 	req.Header.Set("Cookie", "session="+cookie)
 	res, err := http.DefaultClient.Do(req)
@@ -237,6 +238,32 @@ func TestLogoutRevocaSesion(t *testing.T) {
 	}
 }
 
+func TestMutationsCrossOriginRejected(t *testing.T) {
+	// Issue #213: una mutación con Origin cruzado → 403 cross_origin antes
+	// incluso de la autenticación; el login legítimo con Origin propio pasa.
+	srv := makeTestServer(t)
+
+	req, _ := http.NewRequest("POST", srv.URL+"/api/refresh", strings.NewReader(`{}`))
+	req.Header.Set("Origin", "https://evil.example")
+	res, _ := http.DefaultClient.Do(req)
+	if res.StatusCode != http.StatusForbidden {
+		t.Fatalf("POST cross-origin: got %d want 403", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	if body["error"] != "cross_origin" {
+		t.Fatalf("error: %v", body)
+	}
+
+	u, _ := url.Parse(srv.URL)
+	req2, _ := http.NewRequest("POST", srv.URL+"/api/auth/login",
+		strings.NewReader(`{"username":"admin","password":"test123456"}`))
+	req2.Header.Set("Origin", u.Scheme+"://"+u.Host)
+	res2, _ := http.DefaultClient.Do(req2)
+	if res2.StatusCode != http.StatusNoContent {
+		t.Fatalf("login con Origin propio: got %d want 204", res2.StatusCode)
+	}
+}
+
 func TestRateLimitQuintoFallo(t *testing.T) {
 	srv := makeTestServer(t)
 	hdr := []string{"X-Forwarded-For", "10.9.9.9"}
@@ -262,7 +289,7 @@ func TestRateLimitQuintoFallo(t *testing.T) {
 		t.Fatalf("retryAfterSec: %v", body)
 	}
 	// Incluso con la password correcta sigue bloqueado.
-	status, _, _ := loginCookie(t, srv.URL, "admin", "test1234", hdr...)
+	status, _, _ := loginCookie(t, srv.URL, "admin", "test123456", hdr...)
 	if status != 429 {
 		t.Fatalf("bloqueado con password correcta: got %d want 429", status)
 	}
@@ -278,6 +305,28 @@ func TestRateLimitQuintoFallo(t *testing.T) {
 	}
 }
 
+func TestOversizedBodyReturns413(t *testing.T) {
+	// Issue #215: un body mayor que maxBodyBytes responde 413 payload_too_large
+	// (no 400 invalid_body) con el writer real en MaxBytesReader.
+	srv := makeTestServer(t)
+	big := `{"username":"admin","password":"` + strings.Repeat("a", (64<<10)+100) + `"}`
+	req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(big))
+	res, _ := http.DefaultClient.Do(req)
+	if res.StatusCode != http.StatusRequestEntityTooLarge {
+		t.Fatalf("body > maxBodyBytes: got %d want 413", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	if body["error"] != "payload_too_large" {
+		t.Fatalf("error: %v", body)
+	}
+	// Un JSON mal formado pero pequeño sigue siendo 400 invalid_body.
+	req2, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`not-json`))
+	res2, _ := http.DefaultClient.Do(req2)
+	if res2.StatusCode != http.StatusBadRequest || readJSON(t, res2)["error"] != "invalid_body" {
+		t.Fatalf("JSON inválido: got %d want 400 invalid_body", res2.StatusCode)
+	}
+}
+
 func TestLoginInvalidBody400(t *testing.T) {
 	srv := makeTestServer(t)
 	for _, payload := range []string{`not-json`, `{}`, `{"username":"admin"}`, `{"username":1,"password":"x"}`} {
@@ -308,7 +357,7 @@ func TestUsersCRUD(t *testing.T) {
 	}
 
 	// Admin: lista con 1 usuario
-	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	res = get(t, srv.URL, "/api/users", adminCookie)
 	body := readJSON(t, res)
 	users := body["users"].([]any)
@@ -485,7 +534,7 @@ func TestUsersCRUD(t *testing.T) {
 
 func TestCacheControl(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	cases := []struct {
 		path    string
@@ -514,7 +563,7 @@ func TestCacheControl(t *testing.T) {
 
 func TestDevicesPaginacionYFiltros(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	// Paginación: 65 dispositivos del dataset canónico reconciliado
 	// (SPEC-CANON D1/D3/D5: GS308E de vuelta como Device, sin IDs duplicadas)
@@ -612,7 +661,7 @@ func TestDevicesPaginacionYFiltros(t *testing.T) {
 
 func TestAlertsEndpoint(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	res := get(t, srv.URL, "/api/alerts", cookie)
 	body := readJSON(t, res)
@@ -633,7 +682,7 @@ func TestAlertsEndpoint(t *testing.T) {
 
 func TestRoutersYDetalle(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	res := get(t, srv.URL, "/api/routers", cookie)
 	body := readJSON(t, res)
@@ -671,7 +720,7 @@ func TestRoutersYDetalle(t *testing.T) {
 
 func TestAPI404JSON(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	for _, path := range []string{"/api/no-existe", "/api/routers/"} {
 		res := get(t, srv.URL, path, cookie)
 		body := readJSON(t, res)
@@ -769,7 +818,7 @@ func TestWriteJSONSinSaltoFinal(t *testing.T) {
 
 func TestWebhookDLQEndpoint(t *testing.T) {
 	srv := makeTestServer(t)
-	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if status != 204 {
 		t.Fatalf("login: %d", status)
 	}

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

@@ -31,7 +31,7 @@ func TestMigrationEndToEndHTTP(t *testing.T) {
 		t.Fatal(err)
 	}
 	secret := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
-	password := "n0de-p4ss"
+	password := "n0de-p4ss-larga"
 	hash, err := auth.HashPassword(password)
 	if err != nil {
 		t.Fatal(err)

+ 11 - 2
server-go/internal/httpapi/orchestr.go

@@ -32,7 +32,12 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 			Diff     []executor.Op   `json:"diff"`
 			Desired  json.RawMessage `json:"desired"`
 		}
-		if !readJSONBody(r, &body) || body.RouterID == "" || body.Resource == "" {
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body",
+				`Se esperaba { "routerId": "...", "resource": "adguard", "desired": {...} }`)
+			return
+		}
+		if body.RouterID == "" || body.Resource == "" {
 			writeError(w, http.StatusBadRequest, "invalid_body",
 				`Se esperaba { "routerId": "...", "resource": "adguard", "desired": {...} }`)
 			return
@@ -169,7 +174,11 @@ func (s *server) registerOrchestrRoutes(mux *http.ServeMux, mgr *orchestr.Manage
 			PlanID string               `json:"planId"`
 			Result executor.ApplyResult `json:"result"`
 		}
-		if !readJSONBody(r, &body) || body.PlanID == "" {
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "")
+			return
+		}
+		if body.PlanID == "" {
 			writeError(w, http.StatusBadRequest, "invalid_body")
 			return
 		}

+ 8 - 3
server-go/internal/httpapi/pairing.go

@@ -94,8 +94,8 @@ type pairRequest struct {
 
 // pairResponse es lo que recibe el agente tras un pairing exitoso.
 type pairResponse struct {
-	Slug    string `json:"slug"`
-	Token   string `json:"token"`
+	Slug     string `json:"slug"`
+	Token    string `json:"token"`
 	ServerFP string `json:"server_fp"`
 }
 
@@ -109,7 +109,12 @@ func (s *server) handleAgentPair(w http.ResponseWriter, r *http.Request) {
 	}
 
 	var body pairRequest
-	if !readJSONBody(r, &body) || !agentSlugRe.MatchString(body.Slug) || body.PairingToken == "" {
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body",
+			`Se esperaba { "pairing_token": "...", "slug": "<equipo>" }`)
+		return
+	}
+	if !agentSlugRe.MatchString(body.Slug) || body.PairingToken == "" {
 		writeError(w, http.StatusBadRequest, "invalid_body",
 			`Se esperaba { "pairing_token": "...", "slug": "<equipo>" }`)
 		return

+ 6 - 2
server-go/internal/httpapi/pairing_test.go

@@ -28,7 +28,9 @@ func getPairingToken(t *testing.T, ts *agentTestServer) string {
 	if res.StatusCode != 200 {
 		t.Fatalf("pairing token status: %d", res.StatusCode)
 	}
-	var body struct{ Token string `json:"token"` }
+	var body struct {
+		Token string `json:"token"`
+	}
 	json.NewDecoder(res.Body).Decode(&body)
 	if body.Token == "" {
 		t.Fatal("pairing token vacío")
@@ -115,7 +117,9 @@ func TestPairingRotateChangesToken(t *testing.T) {
 	if res.StatusCode != 200 {
 		t.Fatalf("rotate status: %d", res.StatusCode)
 	}
-	var body struct{ Token string `json:"token"` }
+	var body struct {
+		Token string `json:"token"`
+	}
 	json.NewDecoder(res.Body).Decode(&body)
 	if body.Token == "" || body.Token == old {
 		t.Fatalf("rotate should generate a new token: old=%s new=%s", old, body.Token)

+ 7 - 3
server-go/internal/httpapi/push.go

@@ -42,8 +42,8 @@ type pushSubscribeBody struct {
 // actualizó una existente (la app solo exige res.ok).
 func (s *server) handlePushSubscribe(w http.ResponseWriter, r *http.Request) {
 	var body pushSubscribeBody
-	if !readJSONBody(r, &body) {
-		writeError(w, http.StatusBadRequest, "invalid_body", "JSON esperado: {endpoint, keys:{auth, p256dh}}")
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "JSON esperado: {endpoint, keys:{auth, p256dh}}")
 		return
 	}
 	body.Endpoint = strings.TrimSpace(body.Endpoint)
@@ -77,7 +77,11 @@ func (s *server) handlePushUnsubscribe(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		Endpoint string `json:"endpoint"`
 	}
-	if !readJSONBody(r, &body) || strings.TrimSpace(body.Endpoint) == "" {
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "endpoint es obligatorio")
+		return
+	}
+	if strings.TrimSpace(body.Endpoint) == "" {
 		writeError(w, http.StatusBadRequest, "invalid_body", "endpoint es obligatorio")
 		return
 	}

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

@@ -26,7 +26,7 @@ func TestPushAuthRequired(t *testing.T) {
 
 func TestPushEndpointsContract(t *testing.T) {
 	ts := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 
 	// GET vapid-key: {"key":...} no vacía y ESTABLE entre llamadas; sin '\n'.
 	res := get(t, ts.URL, "/api/push/vapid-key", cookie)

+ 2 - 2
server-go/internal/httpapi/rearm_api_test.go

@@ -73,7 +73,7 @@ func makeRearmTestServer(t *testing.T, pool *fakeSSH, pollWait time.Duration) *r
 	t.Helper()
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -107,7 +107,7 @@ func makeRearmTestServer(t *testing.T, pool *fakeSSH, pollWait time.Duration) *r
 		Agents: reg, Pool: runner, RearmPollWait: pollWait, Started: time.Now(),
 	})
 	srv := httptest.NewServer(handler)
-	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if status != 204 {
 		t.Fatalf("login: %d", status)
 	}

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

@@ -23,7 +23,7 @@ func makeRefreshServer(t *testing.T) (*testServer, *atomic.Int32) {
 	t.Helper()
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -84,7 +84,7 @@ func TestRefreshSinSesion401(t *testing.T) {
 
 func TestRefreshAutenticado202(t *testing.T) {
 	srv, polls := makeRefreshServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	res := postRefresh(t, srv.URL, cookie)
 	body := readJSON(t, res)
 	if res.StatusCode != 202 || body["ok"] != true {
@@ -104,7 +104,7 @@ func TestRefreshAutenticado202(t *testing.T) {
 
 func TestRefreshRafaga429(t *testing.T) {
 	srv, polls := makeRefreshServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	res := postRefresh(t, srv.URL, cookie)
 	res.Body.Close()
 	if res.StatusCode != 202 {
@@ -131,7 +131,7 @@ func TestRefreshRafaga429(t *testing.T) {
 func TestRefreshSinPollerNoRompe(t *testing.T) {
 	// Deps sin PollNow (modo demo mínimo): 202 igualmente, nunca 500.
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	res := postRefresh(t, srv.URL, cookie)
 	body := readJSON(t, res)
 	if res.StatusCode != 202 || body["ok"] != true {

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

@@ -43,7 +43,7 @@ type weeklyReportEntry struct {
 
 func getWeekly(t *testing.T, ts *testServer, weeks string) (int, []weeklyReportEntry) {
 	t.Helper()
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	url := ts.URL + "/api/reports/weekly"
 	if weeks != "" {
 		url += "?weeks=" + weeks

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

@@ -15,6 +15,7 @@ import (
 	"database/sql"
 	"encoding/hex"
 	"encoding/json"
+	"errors"
 	"net/http"
 	"strings"
 	"sync"
@@ -24,10 +25,10 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/config"
 	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/security"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
-	"github.com/gnacho/netpulse/server-go/internal/orchestr"
 	"github.com/gnacho/netpulse/server-go/internal/staticspa"
 	"github.com/gnacho/netpulse/server-go/internal/updater"
 )
@@ -271,7 +272,7 @@ func NewHandler(d Deps) http.Handler {
 		mux.Handle("/", static)
 	}
 
-	return requestID(security.Middleware(auth.RequireAuth(s.db, s.secret, s.demoReadOnly(noStoreMux(mux)))))
+	return requestID(security.Middleware(auth.RequireSameOrigin(auth.RequireAuth(s.db, s.secret, s.demoReadOnly(noStoreMux(mux))))))
 }
 
 // requestID lee o genera un x-request-id para cada petición y lo expone en
@@ -336,13 +337,43 @@ func writeError(w http.ResponseWriter, status int, code string, message ...strin
 // el cap evita abuso de memoria con bodies gigantes (auditoría #3).
 const maxBodyBytes = 64 << 10
 
-// readJSONBody parsea el body JSON; devuelve false si no es JSON válido o
-// supera maxBodyBytes (equivalente a c.req.json().catch(() => null)).
-func readJSONBody(r *http.Request, dst any) bool {
-	r.Body = http.MaxBytesReader(nil, r.Body, maxBodyBytes)
+// readJSONBody parsea el body JSON. Devuelve 0 si OK o, si falla, el status
+// HTTP a responder: 400 (JSON inválido) o 413 (body > maxBodyBytes, issue
+// #215). Con el writer real, http.MaxBytesReader además marca la conexión
+// para cerrarla tras el 413 (el nil anterior devolvía 400 invalid_body).
+func readJSONBody(w http.ResponseWriter, r *http.Request, dst any) int {
+	r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
 	dec := json.NewDecoder(r.Body)
 	if err := dec.Decode(dst); err != nil {
-		return false
+		var tooLarge *http.MaxBytesError
+		if errors.As(err, &tooLarge) {
+			return http.StatusRequestEntityTooLarge
+		}
+		return http.StatusBadRequest
+	}
+	return 0
+}
+
+// bodyError mapea el status devuelto por readJSONBody al código del envelope:
+// 413 → payload_too_large (paridad con la ingesta); cualquier otro fallo →
+// el código que usaba el caller (invalid_body/invalid_json/invalid_input).
+func bodyError(status int, fallback string) string {
+	if status == http.StatusRequestEntityTooLarge {
+		return "payload_too_large"
+	}
+	return fallback
+}
+
+// writeBodyError responde el fallo de readJSONBody: 413 sin mensaje extra
+// (el body no se pudo leer), 400 con el código y mensaje del caller.
+func writeBodyError(w http.ResponseWriter, status int, fallback, message string) {
+	if status == http.StatusRequestEntityTooLarge {
+		writeError(w, status, "payload_too_large")
+		return
+	}
+	if message != "" {
+		writeError(w, status, fallback, message)
+		return
 	}
-	return true
+	writeError(w, status, fallback)
 }

+ 6 - 6
server-go/internal/httpapi/settings.go

@@ -89,8 +89,8 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 		var body struct {
 			Enabled bool `json:"enabled"`
 		}
-		if !readJSONBody(r, &body) {
-			writeError(w, http.StatusBadRequest, "invalid_body")
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "")
 			return
 		}
 		if err := kvSetBool(s.db.DB, orchestrationKey, body.Enabled); err != nil {
@@ -115,8 +115,8 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 	// PUT /api/settings/wanspeed — guarda ambas velocidades (down y up).
 	mux.Handle("PUT /api/settings/wanspeed", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		var body wanSpeedResponse
-		if !readJSONBody(r, &body) {
-			writeError(w, http.StatusBadRequest, "invalid_body")
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "")
 			return
 		}
 		if body.DownMbps == nil || body.UpMbps == nil {
@@ -191,8 +191,8 @@ func (s *server) registerKnownMacsRoutes(mux *http.ServeMux) {
 	// PUT /api/settings/known-macs — alta o actualización de una MAC.
 	mux.Handle("PUT /api/settings/known-macs", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		var body knownMacItem
-		if !readJSONBody(r, &body) {
-			writeError(w, http.StatusBadRequest, "invalid_body")
+		if st := readJSONBody(w, r, &body); st != 0 {
+			writeBodyError(w, st, "invalid_body", "")
 			return
 		}
 		mac, ok := validMAC(body.MAC)

+ 6 - 6
server-go/internal/httpapi/settings_knownmacs_test.go

@@ -11,7 +11,7 @@ import (
 // TestKnownMacsRoundtrip: GET vacío → PUT → GET lo devuelve → DELETE.
 func TestKnownMacsRoundtrip(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if cookie == "" {
 		t.Fatal("login no devolvió cookie")
 	}
@@ -58,13 +58,13 @@ func TestKnownMacsRoundtrip(t *testing.T) {
 // TestKnownMacsInvalidInput: MAC mal formada → 400; PUT sin admin → 401.
 func TestKnownMacsInvalidInput(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 
 	for _, body := range []string{
-		`{"mac":"A4:7E:FA:65:0C","name":"x"}`,       // corta
-		`{"mac":"A4:7E-FA:65:0C:AA","name":"x"}`,    // separador mal
-		`{"mac":"G4:7E:FA:65:0C:AA","name":"x"}`,    // hex inválido
-		`not-json`,                                  // body roto
+		`{"mac":"A4:7E:FA:65:0C","name":"x"}`,    // corta
+		`{"mac":"A4:7E-FA:65:0C:AA","name":"x"}`, // separador mal
+		`{"mac":"G4:7E:FA:65:0C:AA","name":"x"}`, // hex inválido
+		`not-json`,                               // body roto
 	} {
 		res, _ := wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/known-macs", cookie, body)
 		if res.StatusCode != http.StatusBadRequest {

+ 3 - 3
server-go/internal/httpapi/settings_wanspeed_test.go

@@ -39,7 +39,7 @@ func wanSpeedRequest(t *testing.T, method, base, path, cookie, body string) (*ht
 // TestWanSpeedDefaultEmpty: sin configurar, GET devuelve null en ambos campos.
 func TestWanSpeedDefaultEmpty(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if cookie == "" {
 		t.Fatal("login no devolvió cookie")
 	}
@@ -58,7 +58,7 @@ func TestWanSpeedDefaultEmpty(t *testing.T) {
 // TestWanSpeedRoundtrip: PUT válido guarda y GET lo devuelve.
 func TestWanSpeedRoundtrip(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if cookie == "" {
 		t.Fatal("login no devolvió cookie")
 	}
@@ -81,7 +81,7 @@ func TestWanSpeedRoundtrip(t *testing.T) {
 // TestWanSpeedInvalidInput: PUT inválido → 400 sin guardar nada.
 func TestWanSpeedInvalidInput(t *testing.T) {
 	srv := makeTestServer(t)
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if cookie == "" {
 		t.Fatal("login no devolvió cookie")
 	}

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

@@ -19,7 +19,7 @@ func TestSystemInfo(t *testing.T) {
 	}
 	res.Body.Close()
 
-	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	res = get(t, srv.URL, "/api/system/info", cookie)
 	if res.StatusCode != 200 {
 		t.Fatalf("con cookie: got %d want 200", res.StatusCode)

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

@@ -33,8 +33,8 @@ func (s *server) handleTopologyOverrideCreate(w http.ResponseWriter, r *http.Req
 		Name   string `json:"name"`
 		Parent string `json:"parent"`
 	}
-	if !readJSONBody(r, &body) {
-		writeError(w, http.StatusBadRequest, "invalid_body")
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "")
 		return
 	}
 	body.MAC = adapters.NormalizeMAC(body.MAC)
@@ -71,8 +71,8 @@ func (s *server) handleTopologyOverrideUpdate(w http.ResponseWriter, r *http.Req
 		Parent  *string `json:"parent"`
 		Enabled *bool   `json:"enabled"`
 	}
-	if !readJSONBody(r, &body) {
-		writeError(w, http.StatusBadRequest, "invalid_body")
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "")
 		return
 	}
 	if body.Kind != nil && *body.Kind != "hypervisor" && *body.Kind != "switch" && *body.Kind != "attach" {

+ 2 - 2
server-go/internal/httpapi/update_helpers_test.go

@@ -91,7 +91,7 @@ func makeTestServerWithUpdater(t *testing.T, repoRoot string) *testServer {
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -126,7 +126,7 @@ func makeTestServerWithUpdater(t *testing.T, repoRoot string) *testServer {
 
 func adminCookie(t *testing.T, ts *testServer) string {
 	t.Helper()
-	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test1234")
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
 	if cookie == "" {
 		t.Fatal("login admin falló")
 	}

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

@@ -33,7 +33,7 @@ func TestPendingConfirmEndpoint(t *testing.T) {
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {

+ 2 - 2
server-go/internal/httpapi/upgrade.go

@@ -70,8 +70,8 @@ func (s *server) handleAgentUpgradeResult(w http.ResponseWriter, r *http.Request
 		return
 	}
 	var body upgradeResult
-	if !readJSONBody(r, &body) {
-		writeError(w, http.StatusBadRequest, "invalid_body")
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "")
 		return
 	}
 	if body.OK {

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

@@ -43,7 +43,7 @@ func makeUpgradeTestServer(t *testing.T) *upgradeTestServer {
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
 	dataDir := t.TempDir()
 	cfg, err := config.Load(map[string]string{
-		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
 		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
 	}, dataDir)
 	if err != nil {
@@ -74,11 +74,11 @@ func makeUpgradeTestServer(t *testing.T) *upgradeTestServer {
 	})
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(),
-		Hub:     sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
-		Secret:  secret, Agents: reg, AgentHub: hub, Started: time.Now(),
+		Hub:    sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Secret: secret, Agents: reg, AgentHub: hub, Started: time.Now(),
 	})
 	srv := httptest.NewServer(handler)
-	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
 	if status != 204 {
 		t.Fatalf("login: %d", status)
 	}

+ 17 - 6
server-go/internal/httpapi/users.go

@@ -62,7 +62,11 @@ func (s *server) handleMyDisplayName(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		DisplayName *string `json:"displayName"`
 	}
-	if !readJSONBody(r, &body) || body.DisplayName == nil {
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_input", `Se esperaba { "displayName": string }`)
+		return
+	}
+	if body.DisplayName == nil {
 		writeError(w, http.StatusBadRequest, "invalid_input", `Se esperaba { "displayName": string }`)
 		return
 	}
@@ -85,8 +89,11 @@ func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		Language string `json:"language"`
 	}
-	if !readJSONBody(r, &body) ||
-		(body.Language != "auto" && body.Language != "es" && body.Language != "en") {
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_input", "language debe ser auto|es|en")
+		return
+	}
+	if body.Language != "auto" && body.Language != "es" && body.Language != "en" {
 		writeError(w, http.StatusBadRequest, "invalid_input", "language debe ser auto|es|en")
 		return
 	}
@@ -136,8 +143,8 @@ func (s *server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
 		Role     *string `json:"role"`
 		Language *string `json:"language"`
 	}
-	if !readJSONBody(r, &body) {
-		writeError(w, http.StatusBadRequest, "invalid_input", "Required")
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_input", "Required")
 		return
 	}
 	// Validación (orden zod: username → password → role → language)
@@ -230,7 +237,11 @@ func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
 	var body struct {
 		Password *string `json:"password"`
 	}
-	if !readJSONBody(r, &body) || body.Password == nil || len(*body.Password) < 10 || len(*body.Password) > 128 {
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_input", "password mínimo 10 caracteres")
+		return
+	}
+	if body.Password == nil || len(*body.Password) < 10 || len(*body.Password) > 128 {
 		writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 10 caracteres")
 		return
 	}

+ 2 - 0
web/i18n.js

@@ -106,6 +106,7 @@ const I18N = {
       f7t: 'Demo mode', f7p: 'DEMO_MODE=1 gives you a full sample network of 65 devices, no routers required. Try before you install.',
       f8t: 'Latency collector', f8p: 'Optional sidecar that polls TCP latency per router, with its own long-term time series.',
       f9t: 'Native OpenWrt package', f9p: 'The agent ships as a .ipk package installed with opkg. procd init, UCI configuration, a watchdog and iw events: a first-class OpenWrt citizen running on your routers at ~12 MB RSS.',
+      f10t: 'Post-quantum TLS, fleet always current', f10p: 'Hybrid post-quantum TLS (X25519MLKEM768, Go 1.24+) on by default on the transport; fleet agents self-update from the server and the SSH key rotates without touching the routers.',
     },
     install: {
       title: 'One line to install',
@@ -222,6 +223,7 @@ const I18N = {
       f7t: 'Modo demo', f7p: 'DEMO_MODE=1 te da una red de muestra completa con 65 dispositivos, sin routers. Pruébalo antes de instalar.',
       f8t: 'Collector de latencia', f8p: 'Sidecar opcional que sondea latencia TCP por router, con sus propias series temporales de largo plazo.',
       f9t: 'Paquete nativo OpenWrt', f9p: 'El agente se distribuye como paquete .ipk para instalar con opkg. Init procd, configuración UCI, watchdog y eventos iw: un ciudadano OpenWrt de primera clase, corriendo en tus routers a ~12 MB RSS.',
+      f10t: 'TLS post-quantum y flota al día', f10p: 'TLS híbrido post-quantum (X25519MLKEM768, Go 1.24+) activado por defecto en el transporte; los agentes de tu flota se auto-actualizan desde el servidor y la llave SSH rota sin tocar los routers.',
     },
     install: {
       title: 'Una línea para instalar',

+ 5 - 0
web/index.html

@@ -463,6 +463,11 @@
           <h3 data-i18n="features.f9t">Paquete nativo OpenWrt</h3>
           <p data-i18n="features.f9p">El agente se distribuye como paquete .ipk para instalar con opkg. Init procd, configuración UCI, watchdog y eventos iw: un ciudadano OpenWrt de primera clase, corriendo en tus routers a ~12 MB RSS.</p>
         </div>
+        <div class="card feature reveal">
+          <svg viewBox="0 0 24 24" fill="none" stroke="rgb(var(--ok))" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>
+          <h3 data-i18n="features.f10t">TLS post-quantum y flota al día</h3>
+          <p data-i18n="features.f10p">TLS híbrido post-quantum (X25519MLKEM768, Go 1.24+) activado por defecto en el transporte; los agentes de tu flota se auto-actualizan desde el servidor y la llave SSH rota sin tocar los routers.</p>
+        </div>
       </div>
     </div>
   </section>