Jelajahi Sumber

feat: backend Go completo (server-go) con paridad verificada y migración Node→Go

Reescritura del backend Node/Hono en Go 1.26: net/http ServeMux,
modernc.org/sqlite (binario estático sin CGO), x/crypto (bcrypt+ssh),
go:embed del app/dist. Misma API (25 endpoints), mismas variables de
entorno y .env. Migración automática desde la BD Node al primer arranque
(backup .bak, bcrypt cruzado, sesiones vivas preservadas).

Paridad verificada en vivo Node vs Go (~130 comprobaciones, DEMO_MODE):
5 discrepancias encontradas y corregidas (D1-D5). go test 5/5 paquetes.

Incluye: workflow go.yml (build linux/amd64+arm64 → prerelease go-latest),
deploy/netpulse-go.service y update.sh dual (detecta backend instalado).
gnacho 4 bulan lalu
induk
melakukan
c6ae504f95
45 mengubah file dengan 10882 tambahan dan 39 penghapusan
  1. 75 0
      .github/workflows/go.yml
  2. 50 0
      deploy/netpulse-go.service
  3. 83 39
      deploy/update.sh
  4. 81 0
      server-go/README.md
  5. 175 0
      server-go/cmd/netpulse/main.go
  6. 21 0
      server-go/go.mod
  7. 56 0
      server-go/go.sum
  8. 395 0
      server-go/internal/adapters/adapters_test.go
  9. 175 0
      server-go/internal/adapters/adguard.go
  10. 253 0
      server-go/internal/adapters/adguard_glinet.go
  11. 340 0
      server-go/internal/adapters/demo.go
  12. 417 0
      server-go/internal/adapters/demo_dataset.go
  13. 329 0
      server-go/internal/adapters/demo_extras.go
  14. 68 0
      server-go/internal/adapters/fmtutil.go
  15. 1412 0
      server-go/internal/adapters/live.go
  16. 812 0
      server-go/internal/adapters/openwrt.go
  17. 241 0
      server-go/internal/adapters/sshpool.go
  18. 401 0
      server-go/internal/adapters/types.go
  19. 119 0
      server-go/internal/adapters/wireguard.go
  20. 418 0
      server-go/internal/auth/auth.go
  21. 202 0
      server-go/internal/auth/auth_test.go
  22. 76 0
      server-go/internal/auth/middleware.go
  23. 292 0
      server-go/internal/config/config.go
  24. 254 0
      server-go/internal/db/db.go
  25. 180 0
      server-go/internal/db/migrate_node.go
  26. 208 0
      server-go/internal/db/migrate_node_test.go
  27. 323 0
      server-go/internal/discover/discover.go
  28. 70 0
      server-go/internal/httpapi/auth.go
  29. 221 0
      server-go/internal/httpapi/config.go
  30. 142 0
      server-go/internal/httpapi/config_test.go
  31. 257 0
      server-go/internal/httpapi/data.go
  32. 49 0
      server-go/internal/httpapi/health.go
  33. 713 0
      server-go/internal/httpapi/httpapi_test.go
  34. 134 0
      server-go/internal/httpapi/migrate_e2e_test.go
  35. 159 0
      server-go/internal/httpapi/server.go
  36. 36 0
      server-go/internal/httpapi/update.go
  37. 272 0
      server-go/internal/httpapi/users.go
  38. 157 0
      server-go/internal/poller/poller.go
  39. 288 0
      server-go/internal/routerstore/routerstore.go
  40. 26 0
      server-go/internal/security/security.go
  41. 173 0
      server-go/internal/sse/hub.go
  42. 86 0
      server-go/internal/sshkey/sshkey.go
  43. 133 0
      server-go/internal/staticspa/staticspa.go
  44. 362 0
      server-go/internal/updater/updater.go
  45. 148 0
      server-go/internal/updater/updater_test.go

+ 75 - 0
.github/workflows/go.yml

@@ -0,0 +1,75 @@
+name: go-server
+
+# Compila el backend Go (con app/dist embebido en el binario) y lo publica como
+# asset de la prerelease "go-latest" (el CT 226 tiene 512MB y no tiene Go; el
+# updater descarga el binario exacto de su commit:
+# netpulse-server-<sha>-linux-<arch>.tar.gz).
+
+on:
+  push:
+    branches: [main]
+    paths:
+      - 'server-go/**'
+      - 'app/**' # el dist va embebido en el binario
+      - '.github/workflows/go.yml'
+  workflow_dispatch:
+
+jobs:
+  build:
+    runs-on: ubuntu-latest
+    permissions:
+      contents: write # publicar assets en la prerelease go-latest
+    strategy:
+      matrix:
+        arch: [amd64, arm64]
+    steps:
+      - uses: actions/checkout@v4
+
+      - uses: actions/setup-node@v4
+        with:
+          node-version: 22
+          cache: npm
+          cache-dependency-path: app/package-lock.json
+
+      - uses: actions/setup-go@v5
+        with:
+          go-version: '1.26'
+          cache-dependency-path: server-go/go.sum
+
+      - name: Build frontend
+        working-directory: app
+        run: npm ci --no-audit --no-fund && npm run build
+
+      - name: Copia dist al embed del binario
+        run: rm -rf server-go/internal/staticspa/dist && cp -r app/dist server-go/internal/staticspa/dist
+
+      - name: Tests Go
+        working-directory: server-go
+        run: go test ./...
+
+      - name: Build binario (linux/${{ matrix.arch }})
+        working-directory: server-go
+        env:
+          CGO_ENABLED: 0
+          GOOS: linux
+          GOARCH: ${{ matrix.arch }}
+        run: go build -trimpath -ldflags "-s -w" -o netpulse ./cmd/netpulse
+
+      - name: Empaqueta binario + despliegue
+        run: tar czf netpulse-server-${{ github.sha }}-linux-${{ matrix.arch }}.tar.gz -C server-go netpulse .env.example -C .. deploy
+
+      - name: Publica en prerelease go-latest
+        uses: softprops/action-gh-release@v2
+        with:
+          tag_name: go-latest
+          name: go-latest
+          prerelease: true
+          files: netpulse-server-${{ github.sha }}-linux-${{ matrix.arch }}.tar.gz
+
+      - name: Limpia assets antiguos (conserva los 10 más recientes por fecha)
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+        run: |
+          gh api repos/${{ github.repository }}/releases/tags/go-latest \
+            --jq '.assets | sort_by(.created_at) | reverse | .[10:] | .[].name' \
+            | while read -r a; do gh release delete-asset go-latest "$a" -y; done

+ 50 - 0
deploy/netpulse-go.service

@@ -0,0 +1,50 @@
+# NetPulse (backend Go) — unit systemd
+# NOTA: la skill 'infraestructura' del usuario refinará este fichero en el
+# despliegue real (puerto 80 con CAP_NET_BIND_SERVICE, reverse proxy HTTPS, etc).
+#
+# Instalación (migrando desde la versión Node):
+#   1. Descarga el binario de CI (release go-latest) o compílalo (ver server-go/README.md)
+#      y colócalo en /opt/netpulse/server-go/netpulse (con .env junto a él).
+#   2. DATA_DIR: apunta al MISMO directorio de datos que usaba la versión Node
+#      (p. ej. /opt/netpulse/server/data): el primer arranque migra la DB
+#      automáticamente (backup netpulse.db.bak-<timestamp> incluido; usuarios,
+#      sesiones vivas, routers y métricas se conservan).
+#   3. sudo cp deploy/netpulse-go.service /etc/systemd/system/
+#      sudo systemctl daemon-reload && sudo systemctl enable --now netpulse-go
+#   4. El flag de reinicio del updater pasa a ser
+#      /opt/netpulse/server-go/data/.restart-me — añádelo a netpulse-restart.path
+#      (o crea una unidad path equivalente que haga `systemctl restart netpulse-go`).
+
+[Unit]
+Description=NetPulse (Go) — dashboard de monitorización de red doméstica
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=netpulse
+Group=netpulse
+WorkingDirectory=/opt/netpulse/server-go
+EnvironmentFile=/opt/netpulse/server-go/.env
+ExecStart=/opt/netpulse/server-go/netpulse
+Restart=on-failure
+RestartSec=3
+
+# Hardening
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectSystem=strict
+# La DB vive en DATA_DIR; el auto-actualizador escribe en todo /opt/netpulse
+ReadWritePaths=/opt/netpulse
+# NOTA modo live: ProtectHome=true impide leer claves SSH bajo /home o /root.
+# Coloca la clave de los routers en DATA_DIR/.ssh (o ajusta SSH_KEY_PATH +
+# ReadWritePaths/ProtectHome en consecuencia).
+ProtectHome=true
+ProtectKernelTunables=true
+ProtectKernelModules=true
+ProtectControlGroups=true
+RestrictSUIDSGID=true
+LockPersonality=true
+
+[Install]
+WantedBy=multi-user.target

+ 83 - 39
deploy/update.sh

@@ -1,55 +1,99 @@
 #!/bin/bash
-# NetPulse — script de actualización (lo lanza el servicio, corre como netpulse)
-# git pull → deps server si cambia el lock → build frontend → reinicio diferido.
+# NetPulse — script de actualización (lo lanza el updater del backend, corre
+# como netpulse). Flujo dual según el backend instalado:
+#   - Go   (/opt/netpulse/server-go/netpulse existe): git pull → binario
+#          precompilado de CI (go-latest) → swap atómico → reinicio diferido.
+#   - Node (legacy): git pull → deps → dist precompilado (dist-latest) →
+#          swap atómico del dist → reinicio diferido.
 set -e
 cd /opt/netpulse
 
 echo "STEP:fetch"
 git fetch origin main
 git reset --hard origin/main
+SHA=$(git rev-parse HEAD)
 
-echo "STEP:server-deps"
-if git diff --name-only 'HEAD@{1}' HEAD 2>/dev/null | grep -q 'server/package-lock.json'; then
-  cd /opt/netpulse/server
-  npm ci --omit=dev --no-audit --no-fund
-fi
+if [ -f /opt/netpulse/server-go/netpulse ]; then
+  # ---------------- Flujo Go ----------------
+  echo "STEP:binary"
+  ARCH=$(uname -m)
+  case "$ARCH" in
+    x86_64)  ARCH=amd64 ;;
+    aarch64) ARCH=arm64 ;;
+    *) echo "arquitectura no soportada: $ARCH"; exit 1 ;;
+  esac
+  URL="https://github.com/gnacho/netpulse/releases/download/go-latest/netpulse-server-$SHA-linux-$ARCH.tar.gz"
+  rm -rf /opt/netpulse/server-go/pkg.new
+  mkdir -p /opt/netpulse/server-go/pkg.new
+  # 1) asset exacto del commit; 2) si no existe (commit sin cambios en
+  #    server-go/ ni app/), el asset más reciente de esta arquitectura.
+  if curl -fsSL -m 300 "$URL" -o /tmp/netpulse-go.tgz && tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new; then
+    echo "binario precompilado descargado de CI ($SHA)"
+  else
+    ASSET=$(curl -fsSL -m 30 https://api.github.com/repos/gnacho/netpulse/releases/tags/go-latest \
+      | grep -oP '"name":\s*"\Knetpulse-server-[0-9a-f]+-linux-'"$ARCH"'\.tar\.gz' | head -1)
+    if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz \
+      && tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new; then
+      echo "binario de CI más reciente disponible ($ASSET)"
+    else
+      echo "ERROR: sin binario en CI para $ARCH (el CT no puede compilar Go)"
+      exit 1
+    fi
+  fi
+  # Swap atómico del binario: si algo falló antes, el anterior queda intacto
+  chmod +x /opt/netpulse/server-go/pkg.new/netpulse
+  mv /opt/netpulse/server-go/netpulse /opt/netpulse/server-go/netpulse.old
+  mv /opt/netpulse/server-go/pkg.new/netpulse /opt/netpulse/server-go/netpulse
+  rm -rf /opt/netpulse/server-go/pkg.new /opt/netpulse/server-go/netpulse.old /tmp/netpulse-go.tgz
 
-echo "STEP:frontend-build"
-cd /opt/netpulse
-SHA=$(git rev-parse HEAD)
-URL="https://github.com/gnacho/netpulse/releases/download/dist-latest/app-dist-$SHA.tar.gz"
-rm -rf /opt/netpulse/app/dist.new
-mkdir -p /opt/netpulse/app/dist.new
-# Vía preferida: dist precompilado por CI (el CT no tiene RAM para compilar).
-# 1) asset exacto del commit; 2) si no existe (commit sin cambios en app/),
-#    el asset más reciente disponible (el dist no ha cambiado entonces).
-if curl -fsSL -m 300 "$URL" -o /tmp/app-dist.tgz && tar xzf /tmp/app-dist.tgz -C /opt/netpulse/app/dist.new; then
-  echo "dist precompilado descargado de CI ($SHA)"
+  echo "STEP:restart"
+  # Reinicio vía unidad systemd.path del CT (netpulse-restart.path vigila este
+  # flag y ejecuta systemctl restart netpulse-go.service como root)
+  touch /opt/netpulse/server-go/data/.restart-me
 else
-  ASSET=$(curl -fsSL -m 30 https://api.github.com/repos/gnacho/netpulse/releases/tags/dist-latest \
-    | grep -oP '"name":\s*"\Kapp-dist-[0-9a-f]+\.tar\.gz' | head -1)
-  if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/dist-latest/$ASSET" -o /tmp/app-dist.tgz \
-    && tar xzf /tmp/app-dist.tgz -C /opt/netpulse/app/dist.new; then
-    echo "dist de CI más reciente disponible ($ASSET)"
+  # ---------------- Flujo Node (legacy) ----------------
+  echo "STEP:server-deps"
+  if git diff --name-only 'HEAD@{1}' HEAD 2>/dev/null | grep -q 'server/package-lock.json'; then
+    cd /opt/netpulse/server
+    npm ci --omit=dev --no-audit --no-fund
+  fi
+
+  echo "STEP:frontend-build"
+  cd /opt/netpulse
+  URL="https://github.com/gnacho/netpulse/releases/download/dist-latest/app-dist-$SHA.tar.gz"
+  rm -rf /opt/netpulse/app/dist.new
+  mkdir -p /opt/netpulse/app/dist.new
+  # Vía preferida: dist precompilado por CI (el CT no tiene RAM para compilar).
+  # 1) asset exacto del commit; 2) si no existe (commit sin cambios en app/),
+  #    el asset más reciente disponible (el dist no ha cambiado entonces).
+  if curl -fsSL -m 300 "$URL" -o /tmp/app-dist.tgz && tar xzf /tmp/app-dist.tgz -C /opt/netpulse/app/dist.new; then
+    echo "dist precompilado descargado de CI ($SHA)"
   else
-    echo "sin dist en CI; build local (riesgo OOM en 512MB)"
-    cd /opt/netpulse/app
-    # npm ci SOLO si cambió el lockfile (656 paquetes: OOM seguro en el CT)
-    if git diff --name-only 'HEAD@{1}' HEAD 2>/dev/null | grep -q 'app/package-lock.json'; then
-      npm ci --no-audit --no-fund
+    ASSET=$(curl -fsSL -m 30 https://api.github.com/repos/gnacho/netpulse/releases/tags/dist-latest \
+      | grep -oP '"name":\s*"\Kapp-dist-[0-9a-f]+\.tar\.gz' | head -1)
+    if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/dist-latest/$ASSET" -o /tmp/app-dist.tgz \
+      && tar xzf /tmp/app-dist.tgz -C /opt/netpulse/app/dist.new; then
+      echo "dist de CI más reciente disponible ($ASSET)"
+    else
+      echo "sin dist en CI; build local (riesgo OOM en 512MB)"
+      cd /opt/netpulse/app
+      # npm ci SOLO si cambió el lockfile (656 paquetes: OOM seguro en el CT)
+      if git diff --name-only 'HEAD@{1}' HEAD 2>/dev/null | grep -q 'app/package-lock.json'; then
+        npm ci --no-audit --no-fund
+      fi
+      npm run build -- --outDir dist.new
     fi
-    npm run build -- --outDir dist.new
   fi
-fi
-# Swap atómico: si algo falló antes, el dist anterior queda intacto
-rm -rf /opt/netpulse/app/dist.old
-[ -d /opt/netpulse/app/dist ] && mv /opt/netpulse/app/dist /opt/netpulse/app/dist.old
-mv /opt/netpulse/app/dist.new /opt/netpulse/app/dist
-rm -rf /opt/netpulse/app/dist.old /tmp/app-dist.tgz
+  # Swap atómico: si algo falló antes, el dist anterior queda intacto
+  rm -rf /opt/netpulse/app/dist.old
+  [ -d /opt/netpulse/app/dist ] && mv /opt/netpulse/app/dist /opt/netpulse/app/dist.old
+  mv /opt/netpulse/app/dist.new /opt/netpulse/app/dist
+  rm -rf /opt/netpulse/app/dist.old /tmp/app-dist.tgz
 
-echo "STEP:restart"
-# Reinicio vía unidad systemd.path del CT (netpulse-restart.path vigila este
-# flag y ejecuta systemctl restart netpulse.service como root)
-touch /opt/netpulse/server/data/.restart-me
+  echo "STEP:restart"
+  # Reinicio vía unidad systemd.path del CT (netpulse-restart.path vigila este
+  # flag y ejecuta systemctl restart netpulse.service como root)
+  touch /opt/netpulse/server/data/.restart-me
+fi
 
 echo "STEP:done"

+ 81 - 0
server-go/README.md

@@ -0,0 +1,81 @@
+# NetPulse — backend Go
+
+Reescritura en Go del backend original de Node (`server/`), con **paridad total
+de API** (mismos endpoints, envelopes y auth) y **migración automática** desde
+la instalación anterior. Binario estático único (sin CGO) con el frontend
+embebido — ideal para el CT de 512MB: sin `node_modules`, sin runtime.
+
+## Stack
+
+- Go ≥1.25, std `net/http` (ServeMux de patrones, sin framework)
+- `modernc.org/sqlite` (SQLite puro, sin CGO) — mismo esquema y fichero de DB que la versión Node
+- `golang.org/x/crypto` — bcrypt (auth) + ssh (adapters OpenWrt/WireGuard)
+
+## Build
+
+```bash
+cd server-go
+go build -trimpath -ldflags "-s -w" -o netpulse ./cmd/netpulse
+```
+
+El binario embebe `internal/staticspa/dist` (en el repo hay un placeholder;
+**la CI copia `app/dist` ahí antes de compilar** — ver `.github/workflows/go.yml`).
+Para desarrollo, `STATIC_DIR=../app/dist` tiene prioridad sobre el embed.
+
+## Run
+
+Mismo `.env` que la versión Node (mismas variables, mismo formato — ver
+`.env.example`):
+
+```bash
+cp .env.example .env   # edita AUTH_USER/AUTH_PASS, DEMO_MODE=1 para empezar
+./netpulse             # http://localhost:3000
+```
+
+## Migración desde la versión Node
+
+Automática en el primer arranque si `DATA_DIR` contiene la DB de la versión
+Node:
+
+1. `wal_checkpoint(TRUNCATE)` + **backup** a `netpulse.db.bak-<timestamp>`.
+2. Se conservan: usuarios (hashes bcrypt portables), `kv` completo (incl.
+   `session_secret` → **las sesiones vivas siguen válidas, no hay re-login**),
+   sesiones, routers configurados, `device_attrib`, `metrics` y `adguard_stats`.
+3. `login_attempts` se resetea (rate-limit limpio) y se marca `go_migration`
+   en `kv` (idempotente).
+
+Para migrar: para el servicio Node, configura el mismo `DATA_DIR` en el `.env`
+del Go (o copia el directorio de datos) y arranca. El frontend no cambia.
+
+## Actualizaciones
+
+La CI publica `netpulse-server-<sha>-linux-<arch>.tar.gz` en la prerelease
+`go-latest` (con tests ejecutados antes del build). `deploy/update.sh` detecta
+el backend instalado y, para Go, descarga el binario y hace swap atómico —
+`/api/update/*` y el UpdateBanner del frontend funcionan igual que en Node.
+
+## Tests
+
+```bash
+go test ./...   # auth, db (+migración con fixture Node), httpapi, adapters, updater
+```
+
+## Estructura
+
+```
+cmd/netpulse/        entrypoint (config → db+migración → SSE → poller → HTTP → shutdown)
+internal/config/     .env + validación fail-fast
+internal/db/         schema, WAL, jobs, migrate_node.go
+internal/auth/       cookie id.hmac, sesiones, rate-limit, bcrypt, middleware
+internal/httpapi/    handlers (auth, users, data, config, update, health)
+internal/sse/        hub (MAX_SSE_CLIENTS=10, heartbeat, sin gzip)
+internal/poller/     tick 5s, persistencia, alertas
+internal/adapters/   contrato Snapshotter + demo (dataset canónico) + live
+                     (openwrt ubus/SSH, adguard, adguard-glinet, wireguard, dawn)
+internal/routerstore/  CRUD de routers + bootstrap (ROUTERS_JSON/autodetección)
+internal/sshkey/     generación/gestión de claves en DATA_DIR/.ssh
+internal/discover/   descubrimiento de routers en la LAN
+internal/updater/    check/status/apply contra GitHub releases
+internal/security/   headers (CSP, HSTS, X-Frame-Options…)
+internal/staticspa/  estáticos embebidos + SPA fallback
+```

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

@@ -0,0 +1,175 @@
+// NetPulse backend (Go) — entry point (paridad src/index.js):
+//
+//	loadDotEnv → loadConfig (fail-fast) → openDb (+ migración Node→Go) →
+//	ensureSessionSecret → ensureUsers (seed admin) → adapter (stub demo;
+//	el live llega con el agente B) → hub SSE → poller → HTTP → graceful
+//	shutdown SIGTERM/SIGINT (salvavidas 3 s).
+//
+// Base de rutas relativas (STATIC_DIR/DATA_DIR/.env): el WORKING DIRECTORY
+// del proceso (equivalente al SERVER_ROOT de Node; systemd usa
+// WorkingDirectory=/opt/netpulse/server).
+package main
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"log"
+	"net/http"
+	"os"
+	"os/signal"
+	"path/filepath"
+	"syscall"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"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/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/poller"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+	"github.com/gnacho/netpulse/server-go/internal/staticspa"
+	"github.com/gnacho/netpulse/server-go/internal/updater"
+)
+
+func main() {
+	if err := run(); err != nil {
+		log.Printf("[netpulse] error fatal en arranque: %v", err)
+		os.Exit(1)
+	}
+}
+
+func run() error {
+	serverRoot, err := os.Getwd()
+	if err != nil {
+		return err
+	}
+	config.LoadDotEnv(serverRoot + "/.env")
+	envMap := config.FromEnviron()
+	cfg, err := config.Load(envMap, serverRoot)
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err.Error())
+		os.Exit(1)
+	}
+
+	dbHandle, err := db.Open(cfg.DataDir)
+	if err != nil {
+		return err
+	}
+
+	secret, err := auth.EnsureSessionSecret(dbHandle, cfg)
+	if err != nil {
+		return err
+	}
+	if err := auth.EnsureUsers(dbHandle, cfg); err != nil {
+		return err
+	}
+
+	// Clave SSH propia para sondear routers (se genera la primera vez)
+	if err := sshkey.EnsureKeypair(cfg.SSHKeyPath); err != nil {
+		log.Printf("[netpulse] aviso: no se pudo generar la clave SSH: %v", err)
+	}
+	// Bootstrap de routers: tabla vacía → ROUTERS_JSON o autodetección
+	routers := routerstore.EnsureInitialRouters(dbHandle.DB, cfg)
+
+	// Adapter: DEMO_MODE=1 → demo (dataset canónico + random walk);
+	// live → sondeo real (SSH/ubus) de los routers configurados.
+	var adapter adapters.Snapshotter
+	if cfg.DemoMode {
+		adapter = adapters.NewDemo()
+	} else {
+		pool, err := adapters.NewSSHPool(cfg.SSHKeyPath)
+		if err != nil {
+			log.Printf("[netpulse] aviso: pool SSH no disponible (%v); sirviendo dataset demo", err)
+			adapter = adapters.NewDemo()
+		} else {
+			adapter = adapters.NewLive(cfg, dbHandle, routers, pool)
+		}
+	}
+
+	// Dependencia sse↔poller resuelta con un holder (como index.js:40-45).
+	var p *poller.Poller
+	hub := sse.NewHub(dbHandle, cfg.MaxSSEClients, func() any {
+		if p == nil {
+			return nil
+		}
+		return p.LastOverview()
+	})
+	p = poller.New(adapter, dbHandle, hub)
+
+	// Estáticos: STATIC_DIR explícito → disco; si no → dist embebido.
+	staticDir := ""
+	if _, set := envMap["STATIC_DIR"]; set {
+		staticDir = cfg.StaticDir
+	}
+	static := staticspa.New(staticDir)
+
+	// Actualizador: repoRoot = padre de serverRoot (paridad index.js:49-53)
+	upd := updater.New(filepath.Clean(filepath.Join(cfg.ServerRoot, "..")), cfg.GithubRepo, cfg.GithubToken)
+
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config:  cfg,
+		DB:      dbHandle,
+		Adapter: adapter,
+		Hub:     hub,
+		Secret:  secret,
+		Static:  static,
+		Updater: upd,
+		LastOverview: func() *adapters.Overview {
+			return p.LastOverview()
+		},
+		Started: time.Now(),
+	})
+
+	srv := &http.Server{
+		Addr:    fmt.Sprintf(":%d", cfg.Port),
+		Handler: handler,
+	}
+
+	errCh := make(chan error, 1)
+	go func() {
+		log.Printf("[netpulse] v%s · modo %s · http://localhost:%d", httpapi.Version, adapter.Mode(), cfg.Port)
+		staticDesc := staticDir
+		if staticDesc == "" {
+			staticDesc = "(embed)"
+		}
+		log.Printf("[netpulse] datos: %s · estáticos: %s", cfg.DataDir, staticDesc)
+		p.Start()
+		upd.Start()
+		errCh <- srv.ListenAndServe()
+	}()
+
+	sigCh := make(chan os.Signal, 1)
+	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
+
+	select {
+	case err := <-errCh:
+		if err != nil && !errors.Is(err, http.ErrServerClosed) {
+			return err
+		}
+	case sig := <-sigCh:
+		name := "SIGINT"
+		if sig == syscall.SIGTERM {
+			name = "SIGTERM"
+		}
+		log.Printf("[netpulse] %s recibido, cerrando...", name)
+		p.Stop()
+		upd.Stop()
+		hub.NotifyShutdown()
+		_ = adapter.Close()
+		// Salvavidas de 3 s: salir igualmente aunque el server no cierre.
+		lifeline := time.AfterFunc(3*time.Second, func() {
+			_ = dbHandle.Close()
+			os.Exit(0)
+		})
+		defer lifeline.Stop()
+		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+		defer cancel()
+		_ = srv.Shutdown(ctx)
+		_ = dbHandle.Close()
+	}
+	return nil
+}

+ 21 - 0
server-go/go.mod

@@ -0,0 +1,21 @@
+module github.com/gnacho/netpulse/server-go
+
+go 1.25.0
+
+require (
+	golang.org/x/crypto v0.54.0
+	golang.org/x/text v0.40.0
+	modernc.org/sqlite v1.55.0
+)
+
+require (
+	github.com/dustin/go-humanize v1.0.1 // indirect
+	github.com/google/uuid v1.6.0 // indirect
+	github.com/mattn/go-isatty v0.0.20 // indirect
+	github.com/ncruces/go-strftime v1.0.0 // indirect
+	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+	golang.org/x/sys v0.47.0 // indirect
+	modernc.org/libc v1.74.1 // indirect
+	modernc.org/mathutil v1.7.1 // indirect
+	modernc.org/memory v1.11.0 // indirect
+)

+ 56 - 0
server-go/go.sum

@@ -0,0 +1,56 @@
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
+golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
+golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
+modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
+modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
+modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
+modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
+modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
+modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
+modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
+modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
+modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=

+ 395 - 0
server-go/internal/adapters/adapters_test.go

@@ -0,0 +1,395 @@
+// adapters_test.go — port de snapshot.test.js (canon demo) + tests de
+// parseo con fixtures literales (wg dump, iwinfo, leases, netdev, /proc/stat,
+// puertos, radios, FDB, board.json, top_blocked, parseBytes/fmtBytes).
+package adapters
+
+import (
+	"context"
+	"testing"
+)
+
+// --- snapshot.test.js: el PRIMER snapshot del demo es el canon EXACTO ---
+
+func TestDemoPrimerSnapshotEsCanon(t *testing.T) {
+	d := NewDemo()
+	ov, err := d.GetOverview(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	// Escalares canónicos del flint2
+	var flint *Router
+	for i := range ov.Routers {
+		if ov.Routers[i].ID == "flint2" {
+			flint = &ov.Routers[i]
+		}
+	}
+	if flint == nil {
+		t.Fatal("flint2 ausente")
+	}
+	if *flint.CPU != 23 || *flint.RAM != 41 || *flint.Temp != 54 {
+		t.Fatalf("flint2 cpu/ram/temp: %v/%v/%v", *flint.CPU, *flint.RAM, *flint.Temp)
+	}
+	if flint.Clients != 14 || flint.Health != 98 {
+		t.Fatalf("flint2 clients/health: %v/%v", flint.Clients, flint.Health)
+	}
+	// WAN
+	if ov.WAN.DownMbps != 84.2 || ov.WAN.UpMbps != 12.6 || ov.WAN.LatencyMs != 8 {
+		t.Fatalf("wan: %+v", ov.WAN)
+	}
+	// AdGuard
+	if ov.Adguard.Queries24h != 84312 || ov.Adguard.Blocked24h != 15687 || ov.Adguard.BlockedPct != 18.6 {
+		t.Fatalf("adguard: %+v", ov.Adguard)
+	}
+	if len(ov.Adguard.TopBlocked) != 5 || ov.Adguard.TopBlocked[0].Domain != "graph.facebook.com" {
+		t.Fatalf("topBlocked: %+v", ov.Adguard.TopBlocked)
+	}
+	// WireGuard
+	if ov.Wireguard.Status != "active" || len(ov.Wireguard.Peers) != 5 {
+		t.Fatalf("wireguard: %+v", ov.Wireguard)
+	}
+	p0 := ov.Wireguard.Peers[0]
+	if p0.ID != "pixel-8-pro" || !p0.Active || p0.Rx != "1,2 GB" || p0.Tx != "214 MB" || p0.LastHandshake != "hace 38 s" {
+		t.Fatalf("peer0: %+v", p0)
+	}
+	// DeviceTotals
+	if ov.DeviceTotals != (DeviceTotals{Total: 47, Online: 39, KnownOffline: 8, NewToday: 3}) {
+		t.Fatalf("deviceTotals: %+v", ov.DeviceTotals)
+	}
+	// Health
+	if ov.Health.Score != 92 || ov.Health.Label != "Excelente" || len(ov.Health.Breakdown) != 3 {
+		t.Fatalf("health: %+v", ov.Health)
+	}
+	// ts en segundos (no ms)
+	if ov.Ts > 1e12 {
+		t.Fatalf("ts debería ser epoch segundos: %v", ov.Ts)
+	}
+	// Alertas canónicas
+	if len(ov.Alerts) != 5 || ov.UnreadAlerts != 2 {
+		t.Fatalf("alerts: %d unread %d", len(ov.Alerts), ov.UnreadAlerts)
+	}
+}
+
+func TestDemoDevices47YTop(t *testing.T) {
+	d := NewDemo()
+	devs := d.GetDevices(context.Background())
+	if len(devs) != 47 {
+		t.Fatalf("devices: %d", len(devs))
+	}
+	offline := 0
+	for _, dev := range devs {
+		if !dev.Online {
+			offline++
+		}
+		if !dev.Online && dev.Sparkline == nil {
+			t.Fatalf("sparkline offline debe ser [] no null: %s", dev.ID)
+		}
+	}
+	if offline != 8 {
+		t.Fatalf("offline: %d", offline)
+	}
+	ov, _ := d.GetOverview(context.Background())
+	if len(ov.TopDevices) != 5 {
+		t.Fatalf("topDevices: %d", len(ov.TopDevices))
+	}
+	for i := 1; i < len(ov.TopDevices); i++ {
+		if ov.TopDevices[i-1].TrafficMbps < ov.TopDevices[i].TrafficMbps {
+			t.Fatal("topDevices no ordenado desc")
+		}
+	}
+	if ov.TopDevices[0].ID != "imac-salon" {
+		t.Fatalf("top1: %s", ov.TopDevices[0].ID)
+	}
+}
+
+func TestDemoDetallePatioYFlint(t *testing.T) {
+	d := NewDemo()
+	det, err := d.GetRouterDetail(context.Background(), "patio")
+	if err != nil || det == nil {
+		t.Fatalf("patio: %v %v", det, err)
+	}
+	// Extras completos del patio
+	ex, ok := det.Extras.(*demoExtras)
+	if !ok {
+		t.Fatalf("extras tipo: %T", det.Extras)
+	}
+	if ex.MAC != "C0:4A:00:9B:51:8D" || ex.RamMb != 128 || ex.Backhaul == nil || ex.Backhaul.Kind != "wireless" {
+		t.Fatalf("extras patio: %+v", ex)
+	}
+	if len(det.Radios) != 2 || !det.Radios[0].Congested {
+		t.Fatalf("radios patio: %+v", det.Radios)
+	}
+	if len(det.Clients) != 6 {
+		t.Fatalf("clients patio: %d", len(det.Clients))
+	}
+	// flint2: radios null + adguard/wireguard + series + wgPeerExtras
+	fdet, _ := d.GetRouterDetail(context.Background(), "flint2")
+	if fdet.Radios != nil {
+		t.Fatalf("radios flint2 debe ser null: %+v", fdet.Radios)
+	}
+	if fdet.Backhaul != nil {
+		t.Fatalf("backhaul flint2 debe ser null: %+v", fdet.Backhaul)
+	}
+	if fdet.Adguard == nil || fdet.Wireguard == nil || fdet.AdguardSeries24h == nil ||
+		fdet.WANLatency == nil || fdet.WGPeerExtras == nil || fdet.WGTotals30d == nil {
+		t.Fatal("flint2 sin secciones de gateway")
+	}
+	if len(fdet.AdguardSeries24h) != 24 {
+		t.Fatalf("adguardSeries24h: %d", len(fdet.AdguardSeries24h))
+	}
+	// Suma exacta del canon (84312 = permitidas + bloqueadas)
+	var sumP, sumB int64
+	for _, h := range fdet.AdguardSeries24h {
+		sumP += h.Permitidas
+		sumB += h.Bloqueadas
+	}
+	if sumP+sumB != 84312 || sumB != 15687 {
+		t.Fatalf("series adguard: %d+%d", sumP, sumB)
+	}
+	// Series de rendimiento terminan en el valor actual del router
+	if got := fdet.Series.H24[len(fdet.Series.H24)-1]; got.CPU != 23 || got.RAM != 41 || got.Temp != 54 {
+		t.Fatalf("último punto 24h: %+v", got)
+	}
+	// Id desconocido → (nil, nil)
+	none, err := d.GetRouterDetail(context.Background(), "nope")
+	if none != nil || err != nil {
+		t.Fatalf("id desconocido: %v %v", none, err)
+	}
+	// Dawn/AdguardClients → (nil, nil) en demo
+	if dawn, err := d.GetDawn(context.Background()); dawn != nil || err != nil {
+		t.Fatalf("dawn demo: %v %v", dawn, err)
+	}
+	if cl, err := d.GetAdguardClients(context.Background()); cl != nil || err != nil {
+		t.Fatalf("adguardClients demo: %v %v", cl, err)
+	}
+}
+
+func TestDemoRandomWalkEnRangos(t *testing.T) {
+	d := NewDemo()
+	for i := 0; i < 20; i++ {
+		if err := d.Tick(context.Background()); err != nil {
+			t.Fatal(err)
+		}
+	}
+	ov, _ := d.GetOverview(context.Background())
+	for _, r := range ov.Routers {
+		if *r.CPU < 2 || *r.CPU > 95 || *r.RAM < 10 || *r.RAM > 92 || *r.Temp < 30 || *r.Temp > 82 {
+			t.Fatalf("%s fuera de rango: %+v", r.ID, r)
+		}
+	}
+	if ov.WAN.LatencyMs < 6 || ov.WAN.LatencyMs > 11 {
+		t.Fatalf("latencia: %v", ov.WAN.LatencyMs)
+	}
+	if ov.Adguard.Queries24h < 84312 || ov.Adguard.Blocked24h < 15687 {
+		t.Fatal("adguard debe ser creciente")
+	}
+}
+
+// --- Parseo WG dump (fixture literal) ---
+
+func TestParseWGDump(t *testing.T) {
+	dump := "wg0\tAB private =\t(none)\t51820\n" +
+		"PEERKEY1=\t(none)\t5.224.10.20:51820\t10.0.0.2/32\t1700000060\t1200000000\t214000000\t0\n" +
+		"PEERKEY2=\t(none)\t(none)\t10.0.0.4/32\t0\t3100000000\t402000000\t0\n"
+	peers := ParseWGDump(dump)
+	if len(peers) != 2 {
+		t.Fatalf("peers: %d", len(peers))
+	}
+	if peers[0].Endpoint == nil || *peers[0].Endpoint != "5.224.10.20:51820" {
+		t.Fatalf("endpoint: %+v", peers[0])
+	}
+	if peers[1].Endpoint != nil || peers[1].HandshakeSec != 0 {
+		t.Fatalf("peer2: %+v", peers[1])
+	}
+	if peers[0].RxBytes != 1200000000 || peers[0].TxBytes != 214000000 {
+		t.Fatalf("bytes: %+v", peers[0])
+	}
+}
+
+// --- fmtBytes / parseBytes roundtrip del canon ---
+
+func TestFmtParseBytes(t *testing.T) {
+	cases := []struct {
+		in   float64
+		want string
+	}{
+		{1.2e9, "1,2 GB"}, {214e6, "214 MB"}, {3.1e9, "3,1 GB"}, {12e9, "12 GB"},
+		{402e6, "402 MB"}, {500, "500 B"}, {2500, "3 KB"}, {0, "0 B"},
+	}
+	for _, c := range cases {
+		if got := fmtBytes(c.in); got != c.want {
+			t.Fatalf("fmtBytes(%v) = %q, want %q", c.in, got, c.want)
+		}
+	}
+	if got := parseBytes("1,2 GB"); got != 1.2e9 {
+		t.Fatalf("parseBytes: %v", got)
+	}
+	if got := parseBytes("1,1 TB"); got != 1.1e12 {
+		t.Fatalf("parseBytes TB: %v", got)
+	}
+	if got := parseBytes("214 MB"); got != 214e6 {
+		t.Fatalf("parseBytes MB: %v", got)
+	}
+	if got := parseBytes("basura"); got != 0 {
+		t.Fatalf("parseBytes inválido: %v", got)
+	}
+}
+
+// --- /proc/stat ---
+
+func TestParseProcStat(t *testing.T) {
+	s, err := parseProcStat("cpu  4705 356 584 3699 23 0 23 0 0 0\n")
+	if err != nil {
+		t.Fatal(err)
+	}
+	idle := float64(3699 + 23)
+	total := idle + float64(4705+356+584+0+23)
+	if s.total != total || s.idleAll != idle {
+		t.Fatalf("procstat: %+v", s)
+	}
+}
+
+// --- /proc/net/dev ---
+
+func TestParseNetDev(t *testing.T) {
+	out := "  eth0: 1000000    0    0    0    0     0          0         0   500000    0\n" +
+		"    lo: 9999999    0    0    0    0     0          0         0  8888888    0\n" +
+		"br-lan: 7000000    0    0    0    0     0          0         0  6000000    0\n" +
+		"  lan1: 2000000    0    0    0    0     0          0         0  1000000    0\n"
+	rx, tx := parseNetDev(out)
+	if rx != 3000000 || tx != 1500000 { // lo, br-lan excluidos
+		t.Fatalf("netdev: %v/%v", rx, tx)
+	}
+}
+
+// --- dhcp.leases ---
+
+func TestParseDhcpLeasesFile(t *testing.T) {
+	out := "1700000000 aa:bb:cc:dd:ee:ff 192.168.8.21 imac-de-marc 01:aa:bb:cc:dd:ee:ff\n" +
+		"1700000001 11:22:33:44:55:66 192.168.8.34 * *\n"
+	leases := parseDhcpLeasesFile(out)
+	if len(leases) != 2 {
+		t.Fatalf("leases: %d", len(leases))
+	}
+	if leases[0].MAC != "AA:BB:CC:DD:EE:FF" || leases[0].Hostname != "imac-de-marc" {
+		t.Fatalf("lease0: %+v", leases[0])
+	}
+	if leases[1].Hostname != "" {
+		t.Fatalf("lease1 hostname: %+v", leases[1])
+	}
+}
+
+// --- wireless (iwinfo loop) ---
+
+func TestParseWirelessClients(t *testing.T) {
+	out := "A4:83:E7:21:0B:3C -48 5\nEC:71:DB:44:12:8A -72 2.4\n"
+	m := parseWirelessClients(out)
+	if len(m) != 2 {
+		t.Fatalf("clients: %d", len(m))
+	}
+	if m["A4:83:E7:21:0B:3C"].Band != "5 GHz" || m["A4:83:E7:21:0B:3C"].SignalDbm != -48 {
+		t.Fatalf("c0: %+v", m["A4:83:E7:21:0B:3C"])
+	}
+	if m["EC:71:DB:44:12:8A"].Band != "2.4 GHz" {
+		t.Fatalf("c1: %+v", m["EC:71:DB:44:12:8A"])
+	}
+}
+
+// --- puertos /sys ---
+
+func TestParsePortStates(t *testing.T) {
+	out := "eth0 up 2500\nlan1 up 1000\nlan2 down -1\nwlan0 up 0\n"
+	ports := parsePortStates(out)
+	if len(ports) != 4 {
+		t.Fatalf("ports: %d", len(ports))
+	}
+	if ports[0].Speed != "2 Gbps" || !ports[0].Up {
+		t.Fatalf("p0: %+v", ports[0])
+	}
+	if ports[1].Speed != "1 Gbps" {
+		t.Fatalf("p1: %+v", ports[1])
+	}
+	if ports[2].Up || ports[2].Speed != "—" {
+		t.Fatalf("p2: %+v", ports[2])
+	}
+}
+
+// --- board.json ---
+
+func TestParsePortLayout(t *testing.T) {
+	board := `{"network":{"lan":{"ports":["lan1","lan2","lan3","lan4"],"device":"br-lan"},"wan":{"device":"wan","protocol":"dhcp"}}}`
+	layout, err := parsePortLayout(board)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(layout) != 5 || layout[0].ID != "wan" || layout[0].Name != "wan" || layout[0].Role != "wan" {
+		t.Fatalf("layout: %+v", layout)
+	}
+	if layout[1].Label != "LAN 1" {
+		t.Fatalf("label: %+v", layout[1])
+	}
+}
+
+// --- bridge FDB ---
+
+func TestParseBridgeFdb(t *testing.T) {
+	out := "==PORTS==\n0x1 lan1\n0x2 lan2\n==MACS==\n1 aa:bb:cc:dd:ee:ff\n2 11:22:33:44:55:66\n"
+	m := parseBridgeFdb(out)
+	if len(m) != 2 || m["AA:BB:CC:DD:EE:FF"] != "lan1" || m["11:22:33:44:55:66"] != "lan2" {
+		t.Fatalf("fdb: %+v", m)
+	}
+}
+
+// --- radios iwinfo ---
+
+func TestParseRadios(t *testing.T) {
+	out := "2.4|6|HT20|20|3\n5|36|HT80|23|7\n"
+	radios := parseRadios(out)
+	if len(radios) != 2 {
+		t.Fatalf("radios: %d", len(radios))
+	}
+	if radios[0].Name != "2.4 GHz" || radios[0].Channel != 6 || radios[0].WidthMhz != 20 || radios[0].Clients != 3 {
+		t.Fatalf("r0: %+v", radios[0])
+	}
+	if radios[1].Name != "5 GHz" || radios[1].WidthMhz != 80 || radios[1].PowerDbm != 23 {
+		t.Fatalf("r1: %+v", radios[1])
+	}
+}
+
+// --- top_blocked_domains: ambos formatos ---
+
+func TestParseTopBlocked(t *testing.T) {
+	nuevo := parseTopBlocked([]byte(`[{"graph.facebook.com":1204},{"adservice.google.com":986}]`), 5)
+	if len(nuevo) != 2 || nuevo[0].Domain != "graph.facebook.com" || nuevo[0].Count != 1204 {
+		t.Fatalf("nuevo: %+v", nuevo)
+	}
+	viejo := parseTopBlocked([]byte(`[["graph.facebook.com",1204],["ads.tiktok.com",448]]`), 5)
+	if len(viejo) != 2 || viejo[1].Domain != "ads.tiktok.com" || viejo[1].Count != 448 {
+		t.Fatalf("viejo: %+v", viejo)
+	}
+	if vacio := parseTopBlocked([]byte(`null`), 5); len(vacio) != 0 {
+		t.Fatalf("vacio: %+v", vacio)
+	}
+}
+
+// --- spark determinista (LCG del dataset) ---
+
+func TestSparkDeterminista(t *testing.T) {
+	a := spark(11, 2.1, 1.68)
+	b := spark(11, 2.1, 1.68)
+	if len(a) != 12 {
+		t.Fatalf("len: %d", len(a))
+	}
+	for i := range a {
+		if a[i] != b[i] {
+			t.Fatal("spark no determinista")
+		}
+	}
+	if a[11] != 2.1 { // último punto = base
+		t.Fatalf("último: %v", a[11])
+	}
+	for _, v := range a {
+		if v < 0 {
+			t.Fatal("spark negativo")
+		}
+	}
+}

+ 175 - 0
server-go/internal/adapters/adguard.go

@@ -0,0 +1,175 @@
+// adguard.go — Cliente AdGuard Home estándar (API HTTP /control con Basic
+// auth; port de src/adapters/adguard.js, SPEC §7.3). Timeout corto y errores
+// controlados: si AdGuard no responde, el caller degrada y el poller sigue.
+package adapters
+
+import (
+	"context"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"io"
+	"math"
+	"net/http"
+	"net/url"
+	"strconv"
+	"time"
+)
+
+const adguardHTTPTimeout = 4 * time.Second
+
+// AdGuardClient es el cliente estándar (ADGUARD_URL/USER/PASS).
+type AdGuardClient struct {
+	url  string // sin barra final
+	auth string // "Basic …"
+	hc   *http.Client
+}
+
+// NewAdGuardClient crea el cliente estándar.
+func NewAdGuardClient(rawURL, user, pass string) *AdGuardClient {
+	return &AdGuardClient{
+		url:  rawURL,
+		auth: "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass)),
+		hc:   &http.Client{Timeout: adguardHTTPTimeout},
+	}
+}
+
+func (c *AdGuardClient) get(ctx context.Context, path string, dst any) error {
+	req, err := http.NewRequestWithContext(ctx, "GET", c.url+path, nil)
+	if err != nil {
+		return err
+	}
+	req.Header.Set("Authorization", c.auth)
+	req.Header.Set("Accept", "application/json")
+	res, err := c.hc.Do(req)
+	if err != nil {
+		return err
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 200 {
+		return fmt.Errorf("AdGuard %s → HTTP %d", path, res.StatusCode)
+	}
+	return json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(dst)
+}
+
+// adGuardStatus: /control/status
+type adGuardStatus struct {
+	ProtectionEnabled bool `json:"protection_enabled"`
+	Running           bool `json:"running"`
+}
+
+// adGuardStatsRaw: /control/stats (top_blocked_domains acepta los dos
+// formatos: [{domain:count}] o [["domain",count]]).
+type adGuardStatsRaw struct {
+	NumDNSQueries        int64           `json:"num_dns_queries"`
+	NumBlockedFiltering  int64           `json:"num_blocked_filtering"`
+	NumReplacedSafebrows *int64          `json:"num_replaced_safebrowsing"`
+	NumReplacedParental  int64           `json:"num_replaced_parental"`
+	AvgProcessingTime    float64         `json:"avg_processing_time"`
+	NumClients           int64           `json:"num_clients"`
+	TopBlockedDomains    json.RawMessage `json:"top_blocked_domains"`
+}
+
+// GetStats devuelve AdGuardStats (shape del contrato). Error si caído.
+func (c *AdGuardClient) GetStats(ctx context.Context) (*AdGuardStats, error) {
+	ctx, cancel := context.WithTimeout(ctx, adguardHTTPTimeout)
+	defer cancel()
+
+	var status adGuardStatus
+	if err := c.get(ctx, "/control/status", &status); err != nil {
+		return nil, err
+	}
+	var stats adGuardStatsRaw
+	if err := c.get(ctx, "/control/stats", &stats); err != nil {
+		return nil, err
+	}
+	var filtering struct {
+		Filters []struct {
+			Enabled    bool `json:"enabled"`
+			RulesCount int  `json:"rules_count"`
+		} `json:"filters"`
+	}
+	_ = c.get(ctx, "/control/filtering/status", &filtering) // best-effort (null en JS)
+
+	queries := stats.NumDNSQueries
+	blocked := stats.NumBlockedFiltering
+
+	u, _ := url.Parse(c.url)
+	host := u.Hostname()
+	port := 80
+	if p := u.Port(); p != "" {
+		if n, err := strconv.Atoi(p); err == nil {
+			port = n
+		}
+	}
+
+	blockedPct := 0.0
+	if queries > 0 {
+		blockedPct = math.Round(float64(blocked)/float64(queries)*100*10) / 10
+	}
+
+	trackers := blocked
+	if stats.NumReplacedSafebrows != nil {
+		trackers = blocked - (*stats.NumReplacedSafebrows + stats.NumReplacedParental)
+	}
+
+	status2 := "inactive"
+	if status.ProtectionEnabled && status.Running {
+		status2 = "active"
+	}
+
+	filterLists := 0
+	rules := 0
+	for _, f := range filtering.Filters {
+		if f.Enabled {
+			filterLists++
+			rules += f.RulesCount
+		}
+	}
+
+	return &AdGuardStats{
+		Host: host, Port: port, Status: status2,
+		Queries24h: queries, Blocked24h: blocked, BlockedPct: blockedPct,
+		TrackersBlocked: trackers,
+		DNSLatencyMs:    int(math.Round(stats.AvgProcessingTime * 1000)),
+		ClientsUsing:    int(stats.NumClients), ClientsTotal: int(stats.NumClients),
+		TopBlocked:      parseTopBlocked(stats.TopBlockedDomains, 5),
+		FilterLists:     filterLists, Rules: rules,
+	}, nil
+}
+
+// parseTopBlocked: top 5; acepta [{domain: count}] y [["domain", count]].
+func parseTopBlocked(raw json.RawMessage, limit int) []TopBlocked {
+	out := []TopBlocked{}
+	if len(raw) == 0 {
+		return out
+	}
+	var arr []json.RawMessage
+	if err := json.Unmarshal(raw, &arr); err != nil {
+		return out
+	}
+	for i, item := range arr {
+		if i >= limit {
+			break
+		}
+		// Formato viejo: ["domain", count]
+		var pair []json.RawMessage
+		if err := json.Unmarshal(item, &pair); err == nil && len(pair) == 2 {
+			var domain string
+			var count int64
+			if json.Unmarshal(pair[0], &domain) == nil && json.Unmarshal(pair[1], &count) == nil {
+				out = append(out, TopBlocked{Domain: domain, Count: count})
+				continue
+			}
+		}
+		// Formato nuevo: {domain: count}
+		var m map[string]int64
+		if err := json.Unmarshal(item, &m); err == nil {
+			for k, v := range m { // una sola clave por objeto
+				out = append(out, TopBlocked{Domain: k, Count: v})
+				break
+			}
+		}
+	}
+	return out
+}

+ 253 - 0
server-go/internal/adapters/adguard_glinet.go

@@ -0,0 +1,253 @@
+// adguard_glinet.go — Cliente AdGuard Home en firmware GL.iNet (port EXACTO
+// de src/adapters/adguard-glinet.js, SPEC §7.4 — algoritmo gl-ngx-session):
+//
+//   - La API (puerto 3000) exige cookie `Admin-Token` = sesión de la UI GL.
+//   - Login GL: challenge (nonce+salt+alg) → hash calculado EN el router vía
+//     SSH root (`openssl passwd -<alg> -salt <salt> <pass>` →
+//     sha256("<user>:<pw>:<nonce>") → ubus gl-session login) → sid.
+//   - La contraseña viaja embebida con escaping de comillas simples (BusyBox
+//     del GL NO tiene base64); NUNCA se incluye el comando en los errores.
+//   - Cooldown de 15 min tras fallo de login (el GL bloquea tras N intentos).
+//   - El sid se cachea y se renueva al primer 401.
+package adapters
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"math"
+	"net/http"
+	"regexp"
+	"strings"
+	"sync"
+	"time"
+)
+
+const (
+	glSSHTimeout    = 8 * time.Second
+	glHTTPTimeout   = 4 * time.Second
+	glLoginCooldown = 15 * time.Minute // el GL bloquea logins tras N fallos
+)
+
+// AdGuardGlinetClient es el cliente GL.iNet (host, user, pass + pool SSH).
+type AdGuardGlinetClient struct {
+	Host string
+	User string
+	Pass string
+	pool *SSHPool
+
+	mu             sync.Mutex
+	sid            string
+	loginFailUntil time.Time
+	hc             *http.Client
+}
+
+// NewAdGuardGlinetClient crea el cliente GL (host, user/pass de la UI GL).
+func NewAdGuardGlinetClient(host, user, pass string, pool *SSHPool) *AdGuardGlinetClient {
+	return &AdGuardGlinetClient{
+		Host: host, User: user, Pass: pass, pool: pool,
+		hc: &http.Client{Timeout: glHTTPTimeout},
+	}
+}
+
+// Login ejecuta el flujo gl-ngx-session completo EN el router → sid.
+// Literal del JS (adguard-glinet.js:49-81).
+func (c *AdGuardGlinetClient) Login() (string, error) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	// Cooldown tras fallo: el GL bloquea logins tras N intentos (600 s)
+	if time.Now().Before(c.loginFailUntil) {
+		return "", fmt.Errorf("login GL en cooldown (%d s)",
+			int(math.Ceil(time.Until(c.loginFailUntil).Seconds())))
+	}
+	// Contraseña embebida con escaping de comillas simples (BusyBox del GL
+	// NO tiene base64). El resto del flujo va entre comillas dobles seguro.
+	esc := strings.ReplaceAll(c.Pass, `'`, `'\''`)
+	script := strings.Join([]string{
+		`PASS='` + esc + `'`,
+		`RESP=$(ubus call gl-session challenge '{"username":"` + c.User + `"}')`,
+		`NONCE=$(jsonfilter -s "$RESP" -e '@.data.nonce')`,
+		`SALT=$(jsonfilter -s "$RESP" -e '@.data.salt')`,
+		`ALG=$(jsonfilter -s "$RESP" -e '@.data.alg')`,
+		`PW=$(openssl passwd -$ALG -salt "$SALT" "$PASS")`,
+		`HASH=$(echo -n "` + c.User + `:$PW:$NONCE" | sha256sum | cut -d' ' -f1)`,
+		`RESP2=$(ubus call gl-session login '{"username":"` + c.User + `","hash":"'$HASH'"}')`,
+		`SID=$(jsonfilter -s "$RESP2" -e '@.data.sid')`,
+		`echo "SID:$SID"`,
+	}, " && ")
+	out, err := c.pool.Run(c.Host, script, glSSHTimeout)
+	if err != nil {
+		// NUNCA incluir el comando (lleva la contraseña embebida)
+		c.loginFailUntil = time.Now().Add(glLoginCooldown)
+		return "", err
+	}
+	m := regexp.MustCompile(`(?m)^SID:(\S+)$`).FindStringSubmatch(out)
+	if m == nil {
+		c.loginFailUntil = time.Now().Add(glLoginCooldown)
+		return "", fmt.Errorf("login GL falló (revisa usuario/contraseña de la UI)")
+	}
+	c.loginFailUntil = time.Time{}
+	c.sid = m[1]
+	return c.sid, nil
+}
+
+var errGL401 = fmt.Errorf("401 no autorizado")
+
+// glGet: GET http://<host>:3000/control/<path> con cookie Admin-Token.
+func (c *AdGuardGlinetClient) glGet(ctx context.Context, path string, dst any) error {
+	req, err := http.NewRequestWithContext(ctx, "GET", "http://"+c.Host+":3000/control/"+path, nil)
+	if err != nil {
+		return err
+	}
+	c.mu.Lock()
+	sid := c.sid
+	c.mu.Unlock()
+	req.Header.Set("Cookie", "Admin-Token="+sid)
+	res, err := c.hc.Do(req)
+	if err != nil {
+		return err
+	}
+	defer res.Body.Close()
+	if res.StatusCode == 401 {
+		return errGL401
+	}
+	if res.StatusCode != 200 {
+		return fmt.Errorf("HTTP %d", res.StatusCode)
+	}
+	return json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(dst)
+}
+
+// queryStats: /control/stats con el sid actual.
+func (c *AdGuardGlinetClient) queryStats(ctx context.Context) (*AdGuardStats, error) {
+	var data struct {
+		NumDNSQueries       int64           `json:"num_dns_queries"`
+		NumBlockedFiltering int64           `json:"num_blocked_filtering"`
+		AvgProcessingTime   float64         `json:"avg_processing_time"`
+		TopBlockedDomains   json.RawMessage `json:"top_blocked_domains"`
+		TopClients          json.RawMessage `json:"top_clients"`
+	}
+	if err := c.glGet(ctx, "stats", &data); err != nil {
+		return nil, err
+	}
+	total := data.NumDNSQueries
+	blocked := data.NumBlockedFiltering
+	blockedPct := 0.0
+	if total > 0 {
+		blockedPct = math.Round(float64(blocked)/float64(total)*100*10) / 10
+	}
+	clients := 0
+	if len(data.TopClients) > 0 {
+		var tc []any
+		if json.Unmarshal(data.TopClients, &tc) == nil {
+			clients = len(tc)
+		}
+	}
+	// GL: top_blocked_domains siempre [{domain: count}] (como el JS)
+	top := []TopBlocked{}
+	var arr []json.RawMessage
+	if json.Unmarshal(data.TopBlockedDomains, &arr) == nil {
+		for i, item := range arr {
+			if i >= 5 {
+				break
+			}
+			var m map[string]int64
+			if json.Unmarshal(item, &m) == nil {
+				for k, v := range m {
+					top = append(top, TopBlocked{Domain: k, Count: v})
+					break
+				}
+			}
+		}
+	}
+	return &AdGuardStats{
+		Host: c.Host, Port: 3000, Status: "active",
+		Queries24h: total, Blocked24h: blocked, BlockedPct: blockedPct,
+		TrackersBlocked: 0,
+		DNSLatencyMs:    int(math.Round(data.AvgProcessingTime * 1000)),
+		ClientsUsing:    clients, ClientsTotal: clients,
+		TopBlocked:      top,
+		FilterLists:     0, Rules: 0,
+	}, nil
+}
+
+// GetStats: stats con login/relogin automático (401 → re-login una vez).
+func (c *AdGuardGlinetClient) GetStats(ctx context.Context) (*AdGuardStats, error) {
+	ctx, cancel := context.WithTimeout(ctx, glHTTPTimeout+glSSHTimeout)
+	defer cancel()
+	c.mu.Lock()
+	hasSid := c.sid != ""
+	c.mu.Unlock()
+	if !hasSid {
+		if _, err := c.Login(); err != nil {
+			return nil, err
+		}
+	}
+	stats, err := c.queryStats(ctx)
+	if err == nil {
+		return stats, nil
+	}
+	if err != errGL401 {
+		return nil, err
+	}
+	c.mu.Lock()
+	c.sid = ""
+	c.mu.Unlock()
+	if _, lerr := c.Login(); lerr != nil {
+		return nil, lerr
+	}
+	return c.queryStats(ctx)
+}
+
+// QueryClients: /control/clients con login automático (paridad del JS:
+// ante 401 re-login y reintento).
+func (c *AdGuardGlinetClient) QueryClients(ctx context.Context) ([]AdguardClient, error) {
+	ctx, cancel := context.WithTimeout(ctx, glHTTPTimeout+glSSHTimeout)
+	defer cancel()
+	c.mu.Lock()
+	hasSid := c.sid != ""
+	c.mu.Unlock()
+	if !hasSid {
+		if _, err := c.Login(); err != nil {
+			return nil, err
+		}
+	}
+	var data struct {
+		Clients []struct {
+			Name              string   `json:"name"`
+			IDs               []string `json:"ids"`
+			UseGlobalSettings bool     `json:"use_global_settings"`
+			BlockedServices   []string `json:"blocked_services"`
+		} `json:"clients"`
+	}
+	err := c.glGet(ctx, "clients", &data)
+	if err == errGL401 {
+		c.mu.Lock()
+		c.sid = ""
+		c.mu.Unlock()
+		if _, lerr := c.Login(); lerr != nil {
+			return nil, lerr
+		}
+		err = c.glGet(ctx, "clients", &data)
+	}
+	if err != nil {
+		return nil, err
+	}
+	out := make([]AdguardClient, 0, len(data.Clients))
+	for _, cl := range data.Clients {
+		name := cl.Name
+		ip := ""
+		if len(cl.IDs) > 0 {
+			if name == "" {
+				name = cl.IDs[0]
+			}
+			ip = cl.IDs[0]
+		}
+		out = append(out, AdguardClient{
+			Name: name, IP: ip,
+			UseGlobalSettings: cl.UseGlobalSettings,
+			BlockedServices:   len(cl.BlockedServices),
+		})
+	}
+	return out, nil
+}

+ 340 - 0
server-go/internal/adapters/demo.go

@@ -0,0 +1,340 @@
+// demo.go — Adapter demo COMPLETO (port de src/adapters/demo.js, SPEC §7.1):
+// dataset canónico + random walk por tick:
+//   - cpu/ram/temp ±2 máx (acotados 2-95 / 10-92 / 30-82)
+//   - tráfico ±5 %, latencia WAN acotada 6–11 ms
+//   - AdGuard siempre creciente, bytes WG crecientes solo en peers activos
+// El PRIMER snapshot (antes del primer Tick) es exactamente el canon.
+package adapters
+
+import (
+	"context"
+	"math"
+	"math/rand"
+	"sort"
+	"sync"
+	"time"
+)
+
+const demoGatewayID = "flint2"
+
+// wgByteCounter lleva los contadores numéricos internos de un peer WG
+// (rx/tx se formatean ES al servir).
+type wgByteCounter struct {
+	rx, tx float64
+	active bool
+}
+
+// Demo es el Snapshotter del modo demo.
+type Demo struct {
+	mu        sync.Mutex
+	rng       *rand.Rand
+	routers   []Router
+	wan       WAN
+	adguard   AdGuardStats
+	wireguard WireGuardStats
+	alerts    []AlertEvent
+	devices   []Device
+	extras    map[string]*demoExtras
+	wgBytes   map[string]*wgByteCounter
+	// Señuelos inmutables construidos una vez (series y extras del gateway).
+	adguardSeries []AdGuardHour
+	wanLatency    *WANLatency
+	wgPeerExtras  map[string]wgPeerExtra
+	wgTotals30d   *WGTotals
+}
+
+// NewDemo crea el adapter demo con una copia fresca del dataset canónico.
+func NewDemo() *Demo {
+	wg := canonWireguard()
+	d := &Demo{
+		rng:       rand.New(rand.NewSource(time.Now().UnixNano())),
+		routers:   canonRouters(),
+		wan:       canonWAN(),
+		adguard:   canonAdguard(),
+		wireguard: wg,
+		alerts:    canonAlerts(),
+		devices:   canonAllDevices(),
+		extras:    canonRouterExtras(),
+		wgBytes:   map[string]*wgByteCounter{},
+		adguardSeries: buildAdGuardSeries(),
+		wanLatency: &WANLatency{
+			Last24h: canonWANLatency24h(),
+			Stats:   canonWANLatencyStats(),
+		},
+		wgPeerExtras: canonWGPeerExtras(),
+		wgTotals30d:  canonWGTotals30d(),
+	}
+	for _, p := range wg.Peers {
+		d.wgBytes[p.ID] = &wgByteCounter{rx: parseBytes(p.Rx), tx: parseBytes(p.Tx), active: p.Active}
+	}
+	return d
+}
+
+// ---------------------------------------------------------------------------
+// Random walk (demo.js:57-66, 89-122)
+// ---------------------------------------------------------------------------
+
+func (d *Demo) rnd(min, max float64) float64 { return min + d.rng.Float64()*(max-min) }
+
+func clampF(v, lo, hi float64) float64 { return math.Min(hi, math.Max(lo, v)) }
+
+// walkInt: entero en ±step del valor anterior, acotado.
+func (d *Demo) walkInt(prev int, step, lo, hi int) int {
+	v := int(math.Round(float64(prev) + d.rnd(-float64(step), float64(step))))
+	if v < lo {
+		v = lo
+	}
+	if v > hi {
+		v = hi
+	}
+	return v
+}
+
+// walkPct: ±pct % del valor anterior (1 decimal), acotado.
+func (d *Demo) walkPct(prev, pct, lo, hi float64) float64 {
+	v := math.Round(prev*(1+d.rnd(-pct, pct))*10) / 10 // toFixed(1)
+	return clampF(v, lo, hi)
+}
+
+// Tick avanza el random walk (5 s). Paridad demo.js:89-122.
+func (d *Demo) Tick(context.Context) error {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	for i := range d.routers {
+		r := &d.routers[i]
+		*r.CPU = d.walkInt(*r.CPU, 2, 2, 95)
+		*r.RAM = d.walkInt(*r.RAM, 2, 10, 92)
+		*r.Temp = d.walkInt(*r.Temp, 2, 30, 82)
+		if ex := d.extras[r.ID]; ex != nil {
+			tn := ex.TrafficNow
+			if tn == 0 {
+				tn = 0.1
+			}
+			ex.TrafficNow = d.walkPct(tn, 0.05, 0.05, 950)
+		}
+	}
+	d.wan.DownMbps = d.walkPct(d.wan.DownMbps, 0.05, 5, 580)
+	d.wan.UpMbps = d.walkPct(d.wan.UpMbps, 0.05, 2, 120)
+	d.wan.LatencyMs = clampF(float64(d.walkInt(int(d.wan.LatencyMs), 1, 6, 11)), 6, 11)
+	for i := range d.devices {
+		dev := &d.devices[i]
+		if dev.Online && dev.TrafficMbps > 0 {
+			dev.TrafficMbps = math.Round(d.walkPct(dev.TrafficMbps, 0.05, 0.001, 950)*100) / 100
+		}
+	}
+	// AdGuard: contadores siempre crecientes
+	d.adguard.Queries24h += int64(math.Round(d.rnd(2, 10)))
+	newBlocked := int64(math.Round(d.rnd(0, 2)))
+	d.adguard.Blocked24h += newBlocked
+	d.adguard.TrackersBlocked += int64(math.Round(d.rnd(0, float64(newBlocked))))
+	d.adguard.BlockedPct = math.Round(float64(d.adguard.Blocked24h)/float64(d.adguard.Queries24h)*1000) / 10
+	// WireGuard: bytes crecientes solo en peers activos
+	for id, b := range d.wgBytes {
+		if !b.active {
+			continue
+		}
+		b.rx += math.Round(d.rnd(0.2, 1.7) * 1e6)
+		b.tx += math.Round(d.rnd(0.04, 0.4) * 1e6)
+		for i := range d.wireguard.Peers {
+			if d.wireguard.Peers[i].ID == id {
+				d.wireguard.Peers[i].Rx = fmtBytes(b.rx)
+				d.wireguard.Peers[i].Tx = fmtBytes(b.tx)
+			}
+		}
+	}
+	return nil
+}
+
+// ---------------------------------------------------------------------------
+// Snapshotter
+// ---------------------------------------------------------------------------
+
+func (d *Demo) Mode() string              { return "demo" }
+func (d *Demo) SetRouters([]RouterConfig) {} // la demo ignora la configuración
+func (d *Demo) Close() error              { return nil }
+
+func (d *Demo) GetDawn(context.Context) (*Dawn, error) { return nil, nil }
+
+func (d *Demo) GetAdguardClients(context.Context) ([]AdguardClient, error) { return nil, nil }
+
+// GetOverview: overview completo (ts en SEGUNDOS). Paridad demo.js:132-146.
+func (d *Demo) GetOverview(context.Context) (*Overview, error) {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	return d.buildOverview(), nil
+}
+
+func (d *Demo) buildOverview() *Overview {
+	unread := 0
+	for _, a := range d.alerts {
+		if !a.Read {
+			unread++
+		}
+	}
+	return &Overview{
+		Health:       canonHealthScore(),
+		WAN:          d.wan,
+		Traffic:      canonTraffic(),
+		Adguard:      d.adguard,
+		Wireguard:    d.wireguardSnapshot(),
+		Routers:      d.routersCopy(),
+		DeviceTotals: DeviceTotals{Total: 47, Online: 39, KnownOffline: 8, NewToday: 3},
+		TopDevices:   d.topDevices(5),
+		Alerts:       d.alertsCopy(),
+		UnreadAlerts: unread,
+		Ts:           time.Now().Unix(),
+	}
+}
+
+func (d *Demo) wireguardSnapshot() WireGuardStats {
+	peers := make([]WGPeer, len(d.wireguard.Peers))
+	copy(peers, d.wireguard.Peers)
+	return WireGuardStats{
+		Interface: d.wireguard.Interface, Subnet: d.wireguard.Subnet,
+		Status: d.wireguard.Status, Peers: peers,
+	}
+}
+
+func (d *Demo) routersCopy() []Router {
+	out := make([]Router, len(d.routers))
+	copy(out, d.routers)
+	return out
+}
+
+func (d *Demo) alertsCopy() []AlertEvent {
+	out := make([]AlertEvent, len(d.alerts))
+	copy(out, d.alerts)
+	return out
+}
+
+func (d *Demo) devicesCopy() []Device {
+	out := make([]Device, len(d.devices))
+	copy(out, d.devices)
+	return out
+}
+
+// topDevices: 5 por trafficMbps desc (orden estable, como el sort de V8).
+func (d *Demo) topDevices(n int) []Device {
+	devs := d.devicesCopy()
+	sort.SliceStable(devs, func(i, j int) bool { return devs[i].TrafficMbps > devs[j].TrafficMbps })
+	if len(devs) > n {
+		devs = devs[:n]
+	}
+	return devs
+}
+
+// GetRouters devuelve copia de las 4 tarjetas.
+func (d *Demo) GetRouters(context.Context) []Router {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	return d.routersCopy()
+}
+
+// GetRouterDetail (demo.js:152-178): extras canónicos, series deterministas,
+// y solo para flint2 adguard/wireguard/adguardSeries24h/wanLatency/
+// wgPeerExtras/wgTotals30d. Id desconocido → (nil, nil).
+func (d *Demo) GetRouterDetail(_ context.Context, id string) (*RouterDetail, error) {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	var router *Router
+	for i := range d.routers {
+		if d.routers[i].ID == id {
+			router = &d.routers[i]
+			break
+		}
+	}
+	if router == nil {
+		return nil, nil
+	}
+	extras := d.extras[id]
+	if extras == nil {
+		extras = d.extras[demoGatewayID]
+	}
+	var radios []Radio // nil → null si no hay (quirk del contrato)
+	if len(extras.Radios) > 0 {
+		radios = extras.Radios
+	}
+	var backhaul any
+	if extras.Backhaul != nil {
+		backhaul = extras.Backhaul
+	}
+	var clients []Device
+	for _, dev := range d.devices {
+		if dev.RouterID == id {
+			clients = append(clients, dev)
+		}
+	}
+	cpu, ram, temp := *router.CPU, *router.RAM, *router.Temp
+	detail := &RouterDetail{
+		Router:   *router,
+		Ports:    extras.EthPorts,
+		Radios:   radios,
+		Backhaul: backhaul,
+		Series: PerfSeries{
+			H1:  perfSeries(id, cpu, ram, temp, "1h"),
+			H24: perfSeries(id, cpu, ram, temp, "24h"),
+			D7:  perfSeries(id, cpu, ram, temp, "7d"),
+		},
+		Clients: clients,
+		Extras:  extras,
+	}
+	if id == demoGatewayID {
+		ag := d.adguard
+		wg := d.wireguardSnapshot()
+		detail.Adguard = &ag
+		detail.Wireguard = &wg
+		detail.AdguardSeries24h = d.adguardSeries
+		detail.WANLatency = d.wanLatency
+		detail.WGPeerExtras = d.wgPeerExtras
+		detail.WGTotals30d = d.wgTotals30d
+	}
+	return detail, nil
+}
+
+// GetDevices devuelve copia de los 47 dispositivos.
+func (d *Demo) GetDevices(context.Context) []Device {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	return d.devicesCopy()
+}
+
+// GetAlerts devuelve las 5 alertas canónicas.
+func (d *Demo) GetAlerts(context.Context) []AlertEvent {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	return d.alertsCopy()
+}
+
+// GetMetricsRows (demo.js:189-203). El poller no persiste en demo, pero la
+// interfaz lo exige.
+func (d *Demo) GetMetricsRows(context.Context) []MetricsRow {
+	d.mu.Lock()
+	defer d.mu.Unlock()
+	rows := make([]MetricsRow, 0, len(d.routers))
+	for _, r := range d.routers {
+		ex := d.extras[r.ID]
+		var trafficNow, gwLatency float64
+		if ex != nil {
+			trafficNow = ex.TrafficNow
+			if ex.GatewayLatencyMs != nil {
+				gwLatency = *ex.GatewayLatencyMs
+			}
+		}
+		rx := trafficNow * 1e6
+		row := MetricsRow{
+			RouterID: r.ID,
+			CPU:      fptr(float64(*r.CPU)),
+			RAM:      fptr(float64(*r.RAM)),
+			Temp:     fptr(float64(*r.Temp)),
+			RxBps:    fptr(math.Round(rx)),
+			TxBps:    fptr(math.Round(rx * 0.15)),
+		}
+		if r.ID == demoGatewayID {
+			row.LatencyMs = fptr(d.wan.LatencyMs)
+		} else if ex != nil && ex.GatewayLatencyMs != nil {
+			row.LatencyMs = fptr(gwLatency)
+		}
+		rows = append(rows, row)
+	}
+	return rows
+}

+ 417 - 0
server-go/internal/adapters/demo_dataset.go

@@ -0,0 +1,417 @@
+// demo_dataset.go — Dataset demo canónico COMPLETO (port literal de
+// server/src/demo/dataset.js, SPEC §7.1): 4 routers, WAN, trafficByRange,
+// health score, AdGuard, WireGuard, alertas, los 47 dispositivos (10
+// canónicos + 37 adicionales, sparklines deterministas con el mismo LCG),
+// routerExtras, perfSeries, WAN_LATENCY_24H, adguardSeries24h, wgPeerExtras
+// y WG_TOTALS_30D. Cada llamada a los builders devuelve estructuras NUEVAS
+// (el adapter muta su copia con el random walk; el canon no se toca).
+package adapters
+
+import (
+	"fmt"
+	"math"
+)
+
+func iptr(v int) *int { return &v }
+
+// ---------------------------------------------------------------------------
+// Routers / WAN / tráfico / health / AdGuard / WireGuard / alertas (canon)
+// ---------------------------------------------------------------------------
+
+func canonRouters() []Router {
+	return []Router{
+		{ID: "flint2", Name: "Gateway", Model: "GL.iNet Flint 2 (GL-MT6000)", ModelShort: "GL.iNet Flint 2",
+			Role: "Gateway principal", RoleBadge: "Principal", IP: "192.168.8.1", Status: "online",
+			Health: 98, CPU: iptr(23), RAM: iptr(41), Temp: iptr(54), Uptime: "32d 14h", Clients: 14,
+			Sparkline: []float64{8, 6, 5, 5, 6, 9, 18, 32, 41, 38, 35, 44, 52, 48, 45, 55, 68, 84, 96, 120, 150, 110, 84, 40}},
+		{ID: "living", Name: "Salón", Model: "OpenWrt AP (Xiaomi AX3000T)", ModelShort: "Xiaomi AX3000T",
+			Role: "Punto de acceso", RoleBadge: "AP", IP: "192.168.8.2", Status: "online",
+			Health: 95, CPU: iptr(12), RAM: iptr(38), Temp: iptr(47), Uptime: "32d 14h", Clients: 18,
+			Sparkline: []float64{4, 3, 3, 2, 3, 5, 10, 22, 28, 26, 24, 30, 38, 35, 33, 42, 55, 72, 88, 105, 132, 92, 61, 28}},
+		{ID: "estudio", Name: "Estudio", Model: "OpenWrt (NanoPi R4S)", ModelShort: "NanoPi R4S",
+			Role: "AP + switch", RoleBadge: "AP", IP: "192.168.8.3", Status: "online",
+			Health: 92, CPU: iptr(18), RAM: iptr(44), Temp: iptr(51), Uptime: "11d 3h", Clients: 9,
+			Sparkline: []float64{2, 2, 1, 1, 2, 4, 8, 15, 22, 25, 24, 22, 26, 24, 21, 24, 28, 31, 29, 24, 18, 12, 8, 4}},
+		{ID: "patio", Name: "Patio", Model: "OpenWrt (TP-Link EAP225)", ModelShort: "TP-Link EAP225",
+			Role: "AP exterior", RoleBadge: "AP", IP: "192.168.8.4", Status: "warn",
+			Health: 68, CPU: iptr(31), RAM: iptr(57), Temp: iptr(71), Uptime: "4d 2h", Clients: 6, HotMetric: "temp",
+			Sparkline: []float64{1, 1, 1, 1, 1, 2, 3, 5, 7, 8, 8, 9, 10, 9, 8, 9, 11, 12, 13, 12, 9, 6, 4, 2}},
+	}
+}
+
+func canonWAN() WAN {
+	return WAN{
+		Plan: "600/600 Mbps", DownMbps: 84.2, UpMbps: 12.6, LatencyMs: 8, LossPct: 0,
+		PublicIP: "84.122.x.x", Isp: "Digi", PeakTodayMbps: 412, PeakTodayTime: "21:14",
+		AvgDownMbps: 61, Total24h: "1,32 TB",
+	}
+}
+
+func tp(t string, down, up float64) TrafficPoint { return TrafficPoint{T: t, Down: down, Up: up} }
+
+func canonTraffic() TrafficByRange {
+	return TrafficByRange{
+		H1: []TrafficPoint{
+			tp("21:30", 68, 9), tp("21:33", 74, 10), tp("21:36", 81, 11), tp("21:39", 92, 12),
+			tp("21:42", 88, 10), tp("21:45", 96, 13), tp("21:48", 104, 14), tp("21:51", 98, 12),
+			tp("21:54", 90, 11), tp("21:57", 86, 10), tp("22:00", 82, 11), tp("22:03", 78, 12),
+			tp("22:06", 84, 13), tp("22:09", 91, 14), tp("22:12", 88, 12), tp("22:15", 84, 11),
+			tp("22:18", 80, 10), tp("22:21", 83, 12), tp("22:24", 86, 13), tp("22:27", 84, 12.6),
+		},
+		H24: []TrafficPoint{
+			tp("00", 42, 8), tp("01", 28, 6), tp("02", 15, 5), tp("03", 9, 4),
+			tp("04", 7, 4), tp("05", 8, 5), tp("06", 14, 6), tp("07", 32, 9),
+			tp("08", 58, 14), tp("09", 74, 18), tp("10", 88, 21), tp("11", 96, 24),
+			tp("12", 112, 26), tp("13", 124, 28), tp("14", 118, 25), tp("15", 132, 27),
+			tp("16", 148, 30), tp("17", 176, 34), tp("18", 224, 42), tp("19", 298, 55),
+			tp("20", 356, 71), tp("21", 412, 96), tp("22", 284, 48), tp("23", 122, 21),
+		},
+		D7: []TrafficPoint{
+			tp("Lun", 61, 12), tp("Mar", 58, 11), tp("Mié", 64, 13), tp("Jue", 71, 15),
+			tp("Vie", 88, 19), tp("Sáb", 96, 22), tp("Dom", 84, 18),
+		},
+		D30: []TrafficPoint{
+			tp("1", 54, 10), tp("4", 58, 11), tp("7", 62, 12), tp("10", 57, 11),
+			tp("13", 66, 13), tp("16", 72, 15), tp("19", 68, 14), tp("22", 75, 16),
+			tp("25", 81, 18), tp("28", 78, 17), tp("30", 84, 19),
+		},
+	}
+}
+
+func canonHealthScore() HealthScore {
+	return HealthScore{
+		Score: 92, Label: "Excelente", Caption: "Puntuación de salud de la red",
+		Note: "Penalizado por la temperatura del Patio.",
+		Breakdown: []HealthDelta{
+			{Label: "temp. Patio", Delta: -4},
+			{Label: "cobertura Patio", Delta: -2},
+			{Label: "canal 2.4 GHz congestionado", Delta: -2},
+		},
+	}
+}
+
+func canonAdguard() AdGuardStats {
+	return AdGuardStats{
+		Host: "192.168.8.1", Port: 3000, Status: "active",
+		Queries24h: 84312, Blocked24h: 15687, BlockedPct: 18.6, TrackersBlocked: 9204,
+		DNSLatencyMs: 14, ClientsUsing: 41, ClientsTotal: 47,
+		TopBlocked: []TopBlocked{
+			{Domain: "graph.facebook.com", Count: 1204},
+			{Domain: "adservice.google.com", Count: 986},
+			{Domain: "metrics.icloud.com", Count: 731},
+			{Domain: "telemetry.nvidia.com", Count: 512},
+			{Domain: "ads.tiktok.com", Count: 448},
+		},
+		FilterLists: 6, Rules: 218442,
+	}
+}
+
+func canonWireguard() WireGuardStats {
+	return WireGuardStats{
+		Interface: "wg0", Subnet: "10.0.0.1/24", Status: "active",
+		Peers: []WGPeer{
+			{ID: "pixel-8-pro", Name: "Pixel 8 Pro", Type: "movil", TunnelIP: "10.0.0.2", Active: true, LastHandshake: "hace 38 s", Rx: "1,2 GB", Tx: "214 MB"},
+			{ID: "macbook-air", Name: "MacBook Air", Type: "portatil", TunnelIP: "10.0.0.3", Active: true, LastHandshake: "hace 1 min", Rx: "640 MB", Tx: "88 MB"},
+			{ID: "ipad-air", Name: "iPad Air", Type: "tablet", TunnelIP: "10.0.0.4", Active: false, LastHandshake: "hace 2 días", Rx: "3,1 GB", Tx: "402 MB"},
+			{ID: "portatil-trabajo", Name: "Portátil trabajo", Type: "portatil", TunnelIP: "10.0.0.5", Active: false, LastHandshake: "hace 6 h", Rx: "812 MB", Tx: "121 MB"},
+			{ID: "casa-familia", Name: "Casa familia", Type: "sitio", TunnelIP: "10.0.0.6", Active: false, LastHandshake: "hace 9 días", Rx: "12 GB", Tx: "4,2 GB"},
+		},
+	}
+}
+
+func canonAlerts() []AlertEvent {
+	return []AlertEvent{
+		{ID: "alert-temp-patio", Severity: "warn", Title: "Temperatura alta en Patio",
+			Description: "71 °C, por encima del umbral (65 °C)", Time: "hace 12 min", Read: false, RouterID: "patio"},
+		{ID: "alert-firmware-estudio", Severity: "warn", Title: "Firmware disponible",
+			Description: "OpenWrt 24.10.1 para Estudio", Time: "hace 3 h", Read: false, RouterID: "estudio"},
+		{ID: "alert-nuevo-tab", Severity: "info", Title: "Nuevo dispositivo",
+			Description: "'Galaxy Tab S9' se ha unido a Salón", Time: "hace 26 min", Read: true, RouterID: "living"},
+		{ID: "alert-handshake-wg", Severity: "info", Title: "Handshake WireGuard",
+			Description: "Pixel 8 Pro conectado desde 5.224.x.x", Time: "hace 38 s", Read: true, RouterID: "flint2"},
+		{ID: "alert-backup-adguard", Severity: "ok", Title: "Copia de AdGuard completada",
+			Description: "Configuración y listas respaldadas en el NAS", Time: "hace 1 día", Read: true, RouterID: "flint2"},
+	}
+}
+
+// ---------------------------------------------------------------------------
+// Dispositivos: sparkline determinista (mismo LCG que devices-data.ts) y
+// helpers extra()/bulb() del dataset.js
+// ---------------------------------------------------------------------------
+
+// spark replica spark(seed, base, spread) de dataset.js: LCG
+// s = (s*9301 + 49297) % 233280, 12 puntos, el último es `base`.
+func spark(seed int, base, spread float64) []float64 {
+	s := seed
+	out := make([]float64, 0, 12)
+	for i := 0; i < 12; i++ {
+		s = (s*9301 + 49297) % 233280
+		r := float64(s) / 233280
+		v := base + (r-0.45)*spread
+		v = math.Round(v*100) / 100 // toFixed(2)
+		if v < 0 {
+			v = 0
+		}
+		out = append(out, v)
+	}
+	out[len(out)-1] = base
+	return out
+}
+
+// devExtra replica extra(spec): sparkline vacío ([]) si offline.
+func devExtra(d Device, seed int, spread float64) Device {
+	if d.Online {
+		if spread == 0 {
+			spread = d.TrafficMbps * 0.8
+		}
+		d.Sparkline = spark(seed, d.TrafficMbps, spread)
+	} else {
+		d.Sparkline = []float64{}
+	}
+	return d
+}
+
+// bulb replica bulb(n, name, ip, mac, dbm) del dataset.js.
+func bulb(n int, name, ip, mac string, dbm int) Device {
+	return Device{
+		ID: fmt.Sprintf("bombilla-%d", n), Name: name, Type: "iot", Manufacturer: "Ikea Trådfri",
+		IP: ip, MAC: mac, RouterID: "living", Band: "2.4 GHz", SignalDbm: iptr(dbm),
+		TrafficMbps: 0, Online: true, Sparkline: spark(40+n, 0.005, 0.02),
+		Hostname: fmt.Sprintf("tradfri-%d", n), DHCPLease: "renueva en 12 h 0 min", FirstSeen: "hace 280 días",
+		Traffic24hRx: "4 MB", Traffic24hTx: "1 MB", Adguard: boolp(true), Group: "iot",
+	}
+}
+
+// canonDevices son los 10 destacados (el agregado bombillas-ikea NO está:
+// se expande en 6 bulb()), ya fusionados con CANON_DETAILS.
+func canonDevices() []Device {
+	return []Device{
+		{ID: "imac-salon", Name: "iMac Salón", Type: "ordenador", Manufacturer: "Apple",
+			IP: "192.168.8.21", MAC: "A4:83:E7:21:0B:3C", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-48), TrafficMbps: 32.4, Online: true,
+			Sparkline: []float64{12, 15, 18, 22, 26, 30, 34, 32, 28, 30, 32, 31},
+			Hostname:  "imac-de-marc", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 320 días",
+			Traffic24hRx: "38 GB", Traffic24hTx: "2,1 GB", Adguard: boolp(true), Group: "ordenadores"},
+		{ID: "tv-samsung", Name: "TV Samsung", Type: "tv", Manufacturer: "Samsung",
+			IP: "192.168.8.34", MAC: "8C:EA:48:5D:2F:91", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-52), TrafficMbps: 18.1, Online: true,
+			Sparkline: []float64{8, 10, 14, 16, 18, 20, 19, 18, 17, 18, 18, 18},
+			Hostname:  "samsung-tv-salon", DHCPLease: "renueva en 7 h 48 min", FirstSeen: "hace 290 días",
+			Traffic24hRx: "54 GB", Traffic24hTx: "1,2 GB", Adguard: boolp(true), Group: "tv"},
+		{ID: "pixel-8-pro", Name: "Pixel 8 Pro", Type: "movil", Manufacturer: "Google",
+			IP: "192.168.8.45", MAC: "F2:6D:19:A8:44:C2", RouterID: "flint2", Band: "5 GHz",
+			SignalDbm: iptr(-41), TrafficMbps: 6.2, Online: true,
+			Sparkline: []float64{3, 4, 5, 7, 6, 8, 6, 5, 7, 6, 6, 6},
+			Hostname:  "pixel-8-pro", DHCPLease: "renueva en 9 h 12 min", FirstSeen: "hace 214 días",
+			Traffic24hRx: "4,2 GB", Traffic24hTx: "310 MB", Adguard: boolp(true), Group: "moviles"},
+		{ID: "macbook-air", Name: "MacBook Air", Type: "portatil", Manufacturer: "Apple",
+			IP: "192.168.8.23", MAC: "3C:22:FB:71:9E:05", RouterID: "estudio", Band: "5 GHz",
+			SignalDbm: iptr(-45), TrafficMbps: 4.8, Online: true,
+			Sparkline: []float64{2, 3, 4, 5, 5, 6, 5, 4, 5, 5, 5, 5},
+			Hostname:  "macbook-air-de-ana", DHCPLease: "renueva en 5 h 31 min", FirstSeen: "hace 260 días",
+			Traffic24hRx: "18 GB", Traffic24hTx: "2,2 GB", Adguard: boolp(true), Group: "ordenadores"},
+		{ID: "ps5", Name: "PS5", Type: "consola", Manufacturer: "Sony",
+			IP: "192.168.8.31", MAC: "78:C8:81:0A:6B:D4", RouterID: "living", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 12.7, Online: true,
+			Sparkline: []float64{4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13},
+			Hostname:  "ps5-salon", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 300 días",
+			Traffic24hRx: "92 GB", Traffic24hTx: "4,8 GB", Adguard: boolp(true), Group: "tv"},
+		{ID: "robot-aspirador", Name: "Robot aspirador", Type: "iot", Manufacturer: "Roborock",
+			IP: "192.168.8.61", MAC: "B0:4A:39:2E:77:10", RouterID: "patio", Band: "2.4 GHz",
+			SignalDbm: iptr(-67), TrafficMbps: 0.02, Online: true,
+			Sparkline: []float64{0.01, 0.02, 0.02, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02},
+			Hostname:  "roborock-s8", DHCPLease: "renueva en 10 h 2 min", FirstSeen: "hace 180 días",
+			Traffic24hRx: "340 MB", Traffic24hTx: "28 MB", Adguard: boolp(true), Group: "iot"},
+		{ID: "camara-porche", Name: "Cámara porche", Type: "camara", Manufacturer: "Reolink",
+			IP: "192.168.8.71", MAC: "EC:71:DB:44:12:8A", RouterID: "patio", Band: "2.4 GHz",
+			SignalDbm: iptr(-72), TrafficMbps: 1.1, Online: true,
+			Sparkline: []float64{1, 1.1, 1.1, 1.2, 1.1, 1, 1.1, 1.1, 1.2, 1.1, 1.1, 1.1},
+			Hostname:  "reolink-porche", DHCPLease: "renueva en 3 h 57 min", FirstSeen: "hace 150 días",
+			Traffic24hRx: "11 GB", Traffic24hTx: "640 MB", Adguard: boolp(true), Group: "iot"},
+		{ID: "nest-mini", Name: "Nest Mini", Type: "altavoz", Manufacturer: "Google",
+			IP: "192.168.8.52", MAC: "1A:2B:3C:4D:5E:6F", RouterID: "estudio", Band: "2.4 GHz",
+			SignalDbm: iptr(-55), TrafficMbps: 0.4, Online: true,
+			Sparkline: []float64{0.3, 0.4, 0.4, 0.5, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4},
+			Hostname:  "nest-mini-estudio", DHCPLease: "renueva en 8 h 20 min", FirstSeen: "hace 240 días",
+			Traffic24hRx: "1,4 GB", Traffic24hTx: "88 MB", Adguard: boolp(true), Group: "iot"},
+		{ID: "nas-synology", Name: "NAS Synology", Type: "servidor", Manufacturer: "Synology",
+			IP: "192.168.8.10", MAC: "00:11:32:9C:51:B7", RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 2.3, Online: true,
+			Sparkline: []float64{1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3},
+			Hostname:  "diskstation", DHCPLease: "IP fija (reserva)", FirstSeen: "hace 320 días",
+			Traffic24hRx: "96 GB", Traffic24hTx: "1,1 TB", Adguard: boolp(true), Group: "red"},
+		{ID: "galaxy-tab-s9", Name: "Galaxy Tab S9", Type: "tablet", Manufacturer: "Samsung",
+			IP: "192.168.8.48", MAC: "D6:91:2F:07:B3:55", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-50), TrafficMbps: 1.8, Online: true, IsNew: true,
+			Sparkline: []float64{0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1.2, 1.6, 1.8},
+			Hostname:  "galaxy-tab-s9", DHCPLease: "renueva en 11 h 5 min", FirstSeen: "hoy",
+			Traffic24hRx: "640 MB", Traffic24hTx: "48 MB", Adguard: boolp(true), Group: "moviles", NewThisWeek: true},
+	}
+}
+
+// additionalDevices: ADDITIONAL (flint2) + LIVING + ESTUDIO + PATIO.
+func additionalDevices() []Device {
+	out := []Device{
+		// —— Gateway (flint2) ——
+		withDetails(devExtra(Device{ID: "iphone-ana", Name: "iPhone de Ana", Type: "movil", Manufacturer: "Apple",
+			IP: "192.168.8.44", MAC: "F4:D4:88:19:C2:71", RouterID: "flint2", Band: "5 GHz",
+			SignalDbm: iptr(-46), TrafficMbps: 2.1, Online: true}, 11, 0),
+			"iphone-de-ana", "renueva en 6 h 40 min", "hace 190 días", "2,8 GB", "240 MB", true, "moviles", ""),
+		withDetails(devExtra(Device{ID: "macbook-pro", Name: "MacBook Pro de Marc", Type: "portatil", Manufacturer: "Apple",
+			IP: "192.168.8.26", MAC: "F0:18:98:5A:11:E9", RouterID: "flint2", Band: "5 GHz",
+			SignalDbm: iptr(-44), TrafficMbps: 8.6, Online: true}, 12, 0),
+			"macbook-pro-marc", "renueva en 4 h 16 min", "hace 230 días", "12,4 GB", "1,9 GB", true, "ordenadores", ""),
+		withDetails(devExtra(Device{ID: "pc-sobremesa", Name: "PC de sobremesa", Type: "ordenador", Manufacturer: "ASUSTeK",
+			IP: "192.168.8.11", MAC: "04:D4:C4:8B:30:A7", RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 21.3, Online: true}, 13, 0),
+			"desktop-8f2k1", "IP fija (reserva)", "hace 310 días", "84 GB", "6,2 GB", true, "ordenadores", ""),
+		withDetails(devExtra(Device{ID: "raspberry-pi", Name: "Raspberry Pi 4", Type: "servidor", Manufacturer: "Raspberry Pi",
+			IP: "192.168.8.12", MAC: "DC:A6:32:4F:77:02", RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 0.8, Online: true}, 14, 0),
+			"raspberrypi", "IP fija (reserva)", "hace 320 días", "3,4 GB", "890 MB", true, "red", ""),
+		withDetails(devExtra(Device{ID: "switch-netgear", Name: "Switch Netgear 8p", Type: "servidor", Manufacturer: "Netgear",
+			IP: "192.168.8.13", MAC: "28:C6:8E:1D:90:44", RouterID: "flint2", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 0.02, Online: true}, 15, 0.04),
+			"gs308e", "IP fija (reserva)", "hace 300 días", "64 MB", "12 MB", false, "red", "Network"),
+		withDetails(devExtra(Device{ID: "timbre-nest", Name: "Timbre Nest", Type: "camara", Manufacturer: "Google",
+			IP: "192.168.8.72", MAC: "F4:F5:D8:66:01:B8", RouterID: "flint2", Band: "2.4 GHz",
+			SignalDbm: iptr(-58), TrafficMbps: 0.6, Online: true}, 16, 0),
+			"nest-doorbell", "renueva en 9 h 44 min", "hace 170 días", "1,2 GB", "140 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "enchufe-lavadora", Name: "Enchufe lavadora", Type: "iot", Manufacturer: "TP-Link",
+			IP: "192.168.8.81", MAC: "50:C7:BF:22:E1:9C", RouterID: "flint2", Band: "2.4 GHz",
+			SignalDbm: iptr(-62), TrafficMbps: 0.01, Online: true}, 17, 0.02),
+			"tapo-p110-lavadora", "renueva en 12 h 0 min", "hace 140 días", "8 MB", "2 MB", false, "iot", ""),
+		withDetails(devExtra(Device{ID: "pixel-7", Name: "Pixel 7", Type: "movil", Manufacturer: "Google",
+			IP: "192.168.8.46", MAC: "3C:5A:B4:08:D7:5E", RouterID: "flint2", Band: "5 GHz",
+			SignalDbm: iptr(-49), TrafficMbps: 1.4, Online: true}, 18, 0),
+			"pixel-7", "renueva en 7 h 3 min", "hace 205 días", "1,9 GB", "180 MB", true, "moviles", ""),
+		withDetails(devExtra(Device{ID: "impresora-hp", Name: "Impresora HP", Type: "desconocido", Manufacturer: "HP",
+			IP: "192.168.8.14", MAC: "3C:52:82:AB:19:60", RouterID: "flint2", Band: "2.4 GHz",
+			SignalDbm: iptr(-60), TrafficMbps: 0, Online: false}, 1, 0),
+			"hp-laserjet-m209", "Expirado", "hace 250 días", "0 MB", "0 MB", true, "otros", "Printer"),
+		withDetails(devExtra(Device{ID: "ipad-air", Name: "iPad Air", Type: "tablet", Manufacturer: "Apple",
+			IP: "192.168.8.47", MAC: "8C:85:90:2F:B4:11", RouterID: "flint2", Band: "5 GHz",
+			SignalDbm: iptr(-54), TrafficMbps: 0, Online: false}, 1, 0),
+			"ipad-air", "Expirado", "hace 260 días", "6,4 GB", "520 MB", true, "moviles", ""),
+		withDetails(devExtra(Device{ID: "portatil-trabajo", Name: "Portátil trabajo", Type: "portatil", Manufacturer: "Lenovo",
+			IP: "192.168.8.27", MAC: "54:EE:75:9A:03:F1", RouterID: "flint2", Band: "5 GHz",
+			SignalDbm: iptr(-50), TrafficMbps: 0, Online: false}, 1, 0),
+			"thinkpad-t14", "Expirado", "hace 160 días", "812 MB", "121 MB", true, "ordenadores", ""),
+		withDetails(devExtra(Device{ID: "kindle", Name: "Kindle Paperwhite", Type: "desconocido", Manufacturer: "Amazon",
+			IP: "192.168.8.49", MAC: "44:65:0D:71:28:C3", RouterID: "flint2", Band: "2.4 GHz",
+			SignalDbm: iptr(-58), TrafficMbps: 0, Online: false}, 1, 0),
+			"kindle-paperwhite", "Expirado", "hace 220 días", "220 MB", "8 MB", true, "otros", "BookOpen"),
+		// —— Salón (living) ——
+		bulb(1, "Bombilla salón 1", "192.168.8.90", "CC:86:EC:10:04:21", -58),
+		bulb(2, "Bombilla salón 2", "192.168.8.91", "CC:86:EC:10:04:22", -59),
+		bulb(3, "Bombilla lámpara pie", "192.168.8.92", "CC:86:EC:10:04:23", -61),
+		bulb(4, "Bombilla entrada", "192.168.8.93", "CC:86:EC:10:04:24", -64),
+		bulb(5, "Bombilla pasillo", "192.168.8.94", "CC:86:EC:10:04:25", -66),
+		bulb(6, "Bombilla cocina", "192.168.8.95", "CC:86:EC:10:04:26", -60),
+		withDetails(devExtra(Device{ID: "chromecast", Name: "Chromecast HD", Type: "tv", Manufacturer: "Google",
+			IP: "192.168.8.36", MAC: "54:60:09:E3:5B:0A", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-54), TrafficMbps: 3.9, Online: true}, 21, 0),
+			"chromecast-hd", "renueva en 6 h 12 min", "hace 200 días", "21 GB", "380 MB", true, "tv", ""),
+		withDetails(devExtra(Device{ID: "homepod-mini", Name: "HomePod mini", Type: "altavoz", Manufacturer: "Apple",
+			IP: "192.168.8.53", MAC: "F0:D1:A9:3E:77:5C", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-47), TrafficMbps: 0.3, Online: true}, 22, 0),
+			"homepod-mini", "renueva en 10 h 41 min", "hace 190 días", "2,2 GB", "96 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "galaxy-s23", Name: "Galaxy S23", Type: "movil", Manufacturer: "Samsung",
+			IP: "192.168.8.42", MAC: "5C:0A:5B:88:1D:E4", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-51), TrafficMbps: 0.9, Online: true}, 23, 0),
+			"galaxy-s23", "renueva en 8 h 55 min", "hace 175 días", "3,2 GB", "290 MB", true, "moviles", ""),
+		withDetails(devExtra(Device{ID: "echo-dot", Name: "Echo Dot", Type: "altavoz", Manufacturer: "Amazon",
+			IP: "192.168.8.54", MAC: "74:C2:46:19:F0:6B", RouterID: "living", Band: "2.4 GHz",
+			SignalDbm: iptr(-56), TrafficMbps: 0.2, Online: true}, 24, 0),
+			"echo-dot-cocina", "renueva en 11 h 18 min", "hace 210 días", "1,1 GB", "74 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "nintendo-switch", Name: "Nintendo Switch", Type: "consola", Manufacturer: "Nintendo",
+			IP: "192.168.8.33", MAC: "58:BD:A3:4C:E2:09", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-53), TrafficMbps: 0.1, Online: true}, 25, 0.3),
+			"switch-oled", "renueva en 5 h 47 min", "hace 240 días", "8,6 GB", "310 MB", true, "tv", ""),
+		withDetails(devExtra(Device{ID: "portatil-invitado", Name: "Portátil invitado", Type: "portatil", Manufacturer: "Desconocido",
+			IP: "192.168.8.29", MAC: "A2:7E:9C:41:0B:6D", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-58), TrafficMbps: 0.7, Online: true, IsNew: true}, 26, 0),
+			"unknown-7f2a", "renueva en 2 h 9 min", "hoy", "480 MB", "62 MB", false, "ordenadores", ""),
+		withDetails(devExtra(Device{ID: "xbox-series-s", Name: "Xbox Series S", Type: "consola", Manufacturer: "Microsoft",
+			IP: "192.168.8.32", MAC: "7C:1E:52:06:AA:3F", RouterID: "living", Band: "5 GHz",
+			SignalDbm: iptr(-55), TrafficMbps: 0, Online: false}, 1, 0),
+			"xbox-series-s", "Expirado", "hace 230 días", "0 MB", "0 MB", true, "tv", ""),
+		withDetails(devExtra(Device{ID: "portatil-antiguo", Name: "Portátil antiguo", Type: "portatil", Manufacturer: "HP",
+			IP: "192.168.8.28", MAC: "3C:52:82:5D:90:17", RouterID: "living", Band: "2.4 GHz",
+			SignalDbm: iptr(-62), TrafficMbps: 0, Online: false}, 1, 0),
+			"hp-pavilion-15", "Expirado", "hace 300 días", "0 MB", "0 MB", true, "ordenadores", ""),
+		// —— Estudio ——
+		withDetails(devExtra(Device{ID: "mac-mini", Name: "Mac mini", Type: "ordenador", Manufacturer: "Apple",
+			IP: "192.168.8.22", MAC: "A4:83:E7:66:2C:98", RouterID: "estudio", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 1.9, Online: true}, 31, 0),
+			"mac-mini", "IP fija (reserva)", "hace 280 días", "44 GB", "5,6 GB", true, "ordenadores", ""),
+		withDetails(devExtra(Device{ID: "enchufe-ventilador", Name: "Enchufe ventilador", Type: "iot", Manufacturer: "TP-Link",
+			IP: "192.168.8.82", MAC: "9C:53:22:B1:4E:70", RouterID: "estudio", Band: "2.4 GHz",
+			SignalDbm: iptr(-59), TrafficMbps: 0.01, Online: true}, 32, 0.02),
+			"tapo-p110-ventilador", "renueva en 12 h 0 min", "hace 120 días", "7 MB", "2 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "ipad-pro", Name: "iPad Pro", Type: "tablet", Manufacturer: "Apple",
+			IP: "192.168.8.51", MAC: "F0:18:98:91:5A:2B", RouterID: "estudio", Band: "5 GHz",
+			SignalDbm: iptr(-49), TrafficMbps: 0.8, Online: true}, 33, 0),
+			"ipad-pro", "renueva en 9 h 26 min", "hace 160 días", "5,1 GB", "390 MB", true, "moviles", ""),
+		withDetails(devExtra(Device{ID: "hue-hub", Name: "Hub Philips Hue", Type: "iot", Manufacturer: "Signify",
+			IP: "192.168.8.15", MAC: "00:17:88:2A:91:CE", RouterID: "estudio", Band: "cable",
+			SignalDbm: nil, TrafficMbps: 0.02, Online: true}, 34, 0.04),
+			"philips-hue-bridge", "IP fija (reserva)", "hace 280 días", "96 MB", "22 MB", false, "iot", ""),
+		withDetails(devExtra(Device{ID: "sonos-one", Name: "Sonos One", Type: "altavoz", Manufacturer: "Sonos",
+			IP: "192.168.8.55", MAC: "48:A6:B8:14:72:E0", RouterID: "estudio", Band: "2.4 GHz",
+			SignalDbm: iptr(-57), TrafficMbps: 0.5, Online: true}, 35, 0),
+			"sonos-one-estudio", "renueva en 10 h 4 min", "hace 195 días", "3,8 GB", "110 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "iphone-trabajo", Name: "iPhone de trabajo", Type: "movil", Manufacturer: "Apple",
+			IP: "192.168.8.50", MAC: "8C:85:90:47:C1:93", RouterID: "estudio", Band: "5 GHz",
+			SignalDbm: iptr(-47), TrafficMbps: 0.3, Online: true, IsNew: true}, 36, 0),
+			"iphone-15-pro-work", "renueva en 3 h 38 min", "hoy", "320 MB", "41 MB", true, "moviles", ""),
+		withDetails(devExtra(Device{ID: "macbook-viejo", Name: "MacBook viejo", Type: "portatil", Manufacturer: "Apple",
+			IP: "192.168.8.25", MAC: "3C:22:FB:0E:66:A1", RouterID: "estudio", Band: "2.4 GHz",
+			SignalDbm: iptr(-60), TrafficMbps: 0, Online: false}, 1, 0),
+			"macbook-pro-2015", "Expirado", "hace 320 días", "0 MB", "0 MB", true, "ordenadores", ""),
+		// —— Patio ——
+		withDetails(devExtra(Device{ID: "camara-jardin", Name: "Cámara jardín", Type: "camara", Manufacturer: "Reolink",
+			IP: "192.168.8.73", MAC: "EC:71:DB:44:12:9B", RouterID: "patio", Band: "2.4 GHz",
+			SignalDbm: iptr(-74), TrafficMbps: 1.4, Online: true}, 41, 0),
+			"reolink-jardin", "renueva en 8 h 49 min", "hace 4 días", "14 GB", "820 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "sensor-riego", Name: "Sensor de riego", Type: "iot", Manufacturer: "Tuya",
+			IP: "192.168.8.89", MAC: "D8:1F:12:5B:08:44", RouterID: "patio", Band: "2.4 GHz",
+			SignalDbm: iptr(-71), TrafficMbps: 0.01, Online: true}, 42, 0.02),
+			"tuya-riego-01", "renueva en 12 h 0 min", "hace 5 días", "2 MB", "1 MB", false, "iot", ""),
+		withDetails(devExtra(Device{ID: "enchufe-calefactor", Name: "Enchufe calefactor", Type: "iot", Manufacturer: "TP-Link",
+			IP: "192.168.8.80", MAC: "50:C7:BF:31:7A:05", RouterID: "patio", Band: "2.4 GHz",
+			SignalDbm: iptr(-75), TrafficMbps: 0.02, Online: true}, 43, 0.03),
+			"tapo-p110-calefactor", "renueva en 12 h 0 min", "hace 96 días", "6 MB", "2 MB", true, "iot", ""),
+		withDetails(devExtra(Device{ID: "camara-garaje", Name: "Cámara garaje", Type: "camara", Manufacturer: "Reolink",
+			IP: "192.168.8.74", MAC: "EC:71:DB:44:13:02", RouterID: "patio", Band: "2.4 GHz",
+			SignalDbm: iptr(-78), TrafficMbps: 0, Online: false}, 1, 0),
+			"reolink-garaje", "Expirado", "hace 130 días", "0 MB", "0 MB", false, "iot", ""),
+	}
+	// newThisWeek (queda fuera de CANON_DETAILS en el JS)
+	for i := range out {
+		switch out[i].ID {
+		case "portatil-invitado", "iphone-trabajo", "camara-jardin", "sensor-riego":
+			out[i].NewThisWeek = true
+		}
+	}
+	return out
+}
+
+// withDetails fusiona los literales de detalle (segundo objeto del spread JS).
+func withDetails(d Device, hostname, lease, firstSeen, rx, tx string, adguard bool, group, icon string) Device {
+	d.Hostname, d.DHCPLease, d.FirstSeen = hostname, lease, firstSeen
+	d.Traffic24hRx, d.Traffic24hTx = rx, tx
+	d.Adguard, d.Group, d.IconOverride = &adguard, group, icon
+	return d
+}
+
+// canonAllDevices: los 47 clientes (canon expandido + adicionales).
+func canonAllDevices() []Device {
+	out := canonDevices()
+	out = append(out, additionalDevices()...)
+	return out
+}
+
+// boolp: los literales demo fijan adguard explícito (true/false) como en el
+// dataset JS; live lo deja nil para omitir el campo.
+func boolp(b bool) *bool { return &b }

+ 329 - 0
server-go/internal/adapters/demo_extras.go

@@ -0,0 +1,329 @@
+// demo_extras.go — routerExtras canónicos + series sintéticas deterministas
+// (port de routerExtras.ts vía dataset.js, SPEC §7.1).
+package adapters
+
+import (
+	"fmt"
+	"math"
+	"time"
+)
+
+// demoBandSplit es el {band24, band5, cable} de los extras demo.
+type demoBandSplit struct {
+	Band24 int `json:"band24"`
+	Band5  int `json:"band5"`
+	Cable  int `json:"cable"`
+}
+
+// demoBackhaul es el objeto backhaul de los extras demo ({kind, headline, latencyMs}).
+type demoBackhaul struct {
+	Kind      string  `json:"kind"`
+	Headline  string  `json:"headline"`
+	LatencyMs float64 `json:"latencyMs"`
+}
+
+// demoPortState es una entrada de extras.ports ({name, up, speed, role}).
+type demoPortState struct {
+	Name  string `json:"name"`
+	Up    bool   `json:"up"`
+	Speed string `json:"speed"`
+	Role  string `json:"role"`
+}
+
+// demoExtras es el objeto routerExtras por router (shape JSON exacto de
+// routerExtras.ts). Claves opcionales ausentes con omitempty (paridad
+// `undefined`): firmwareBase, firmwareAvailable, gatewayLatencyMs, backhaul.
+type demoExtras struct {
+	MAC                 string          `json:"mac"`
+	Firmware            string          `json:"firmware"`
+	FirmwareBase        string          `json:"firmwareBase,omitempty"`
+	FirmwareUpdated     bool            `json:"firmwareUpdated"`
+	FirmwareAvailable   string          `json:"firmwareAvailable,omitempty"`
+	LastReboot          string          `json:"lastReboot"`
+	Soc                 string          `json:"soc"`
+	Flash               string          `json:"flash"`
+	RamMb               int             `json:"ramMb"`
+	BandSplit           demoBandSplit   `json:"bandSplit"`
+	TrafficNow          float64         `json:"trafficNow"`
+	GatewayLatencyMs    *float64        `json:"gatewayLatencyMs,omitempty"`
+	GatewayLatencySpark []float64       `json:"gatewayLatencySpark"`
+	Backhaul            *demoBackhaul   `json:"backhaul,omitempty"`
+	BackhaulSignal      []float64       `json:"backhaulSignal"`
+	Radios              []Radio         `json:"radios"`
+	Ports               []demoPortState `json:"ports"`
+	EthPorts            []EthPort       `json:"ethPorts"`
+}
+
+func fptr(v float64) *float64 { return &v }
+
+// canonRouterExtras: port literal de routerExtras (dataset.js:661-781).
+func canonRouterExtras() map[string]*demoExtras {
+	return map[string]*demoExtras{
+		"flint2": {
+			MAC: "94:83:C4:2A:7F:10", Firmware: "GL 4.7.0", FirmwareBase: "OpenWrt 21.02",
+			FirmwareUpdated: true, LastReboot: "12 nov, 03:12 (mantenimiento)",
+			Soc: "MediaTek MT7986A", Flash: "8 GB eMMC", RamMb: 512,
+			BandSplit: demoBandSplit{Band24: 4, Band5: 10, Cable: 3},
+			TrafficNow: 84.2,
+			// GL-MT6000: 1× WAN 2.5G + 4× LAN 1G
+			GatewayLatencySpark: []float64{},
+			BackhaulSignal:      []float64{},
+			Radios:              []Radio{},
+			Ports:               []demoPortState{},
+			EthPorts: []EthPort{
+				{ID: "wan", Label: "WAN", Up: true, Speed: "2.5 Gbps", ConnectedTo: "ONT fibra · Digi", Detail: "84.122.x.x · full duplex"},
+				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "Salón · AX3000T", Detail: "Uplink AP Salón (192.168.8.2)"},
+				{ID: "lan2", Label: "LAN 2", Up: true, Speed: "1 Gbps", ConnectedTo: "NAS Synology", Detail: "192.168.8.10 · cable"},
+				{ID: "lan3", Label: "LAN 3", Up: true, Speed: "1 Gbps", ConnectedTo: "Estudio · NanoPi R4S", Detail: "Uplink AP Estudio (192.168.8.3)"},
+				{ID: "lan4", Label: "LAN 4", Up: false},
+			},
+		},
+		"living": {
+			MAC: "50:D2:F5:11:8C:2E", Firmware: "OpenWrt 23.05.5",
+			FirmwareUpdated: true, LastReboot: "12 nov, 03:12 (mantenimiento)",
+			Soc: "MediaTek MT7981B", Flash: "128 MB NAND", RamMb: 256,
+			BandSplit:  demoBandSplit{Band24: 6, Band5: 10, Cable: 2},
+			TrafficNow: 51.7, GatewayLatencyMs: fptr(1),
+			GatewayLatencySpark: []float64{1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1},
+			Backhaul:            &demoBackhaul{Kind: "cable", Headline: "Cable · 1 Gbps · full duplex", LatencyMs: 1},
+			BackhaulSignal:      []float64{58, 59, 60, 59, 58, 58, 60, 61, 60, 59, 60, 60, 61, 60, 59, 60, 61, 62, 61, 60, 60, 59, 60, 60},
+			Radios: []Radio{
+				{Name: "2.4 GHz", Channel: 6, WidthMhz: 20, PowerDbm: 20, Clients: 6},
+				{Name: "5 GHz", Channel: 36, WidthMhz: 80, PowerDbm: 23, Clients: 10},
+			},
+			Ports: []demoPortState{
+				{Name: "br-lan", Up: true, Speed: "—", Role: "Bridge LAN"},
+				{Name: "eth0", Up: true, Speed: "1 Gbps", Role: "Uplink al Gateway"},
+				{Name: "lan1", Up: true, Speed: "1 Gbps", Role: "PS5"},
+				{Name: "phy0-ap0", Up: true, Speed: "—", Role: "Radio 2.4 GHz"},
+				{Name: "phy1-ap0", Up: true, Speed: "—", Role: "Radio 5 GHz"},
+			},
+			// AX3000T: 1× WAN + 3× LAN
+			EthPorts: []EthPort{
+				{ID: "wan", Label: "WAN", Up: true, Speed: "1 Gbps", ConnectedTo: "Uplink → Gateway", Detail: "Gateway · LAN 1 (192.168.8.1)"},
+				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "PS5", Detail: "192.168.8.31 · cable"},
+				{ID: "lan2", Label: "LAN 2", Up: false},
+				{ID: "lan3", Label: "LAN 3", Up: false},
+			},
+		},
+		"estudio": {
+			MAC: "7A:1B:9C:03:F4:62", Firmware: "OpenWrt 23.05.5",
+			FirmwareUpdated: false, FirmwareAvailable: "24.10.1", LastReboot: "2 dic, 21:40 (actualización)",
+			Soc: "Rockchip RK3399", Flash: "32 GB microSD", RamMb: 1024,
+			BandSplit:  demoBandSplit{Band24: 4, Band5: 4, Cable: 1},
+			TrafficNow: 9.4, GatewayLatencyMs: fptr(1),
+			GatewayLatencySpark: []float64{1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1},
+			Backhaul:            &demoBackhaul{Kind: "cable", Headline: "Cable · 1 Gbps · full duplex", LatencyMs: 1},
+			BackhaulSignal:      []float64{55, 56, 56, 55, 55, 56, 57, 56, 55, 56, 56, 57, 56, 56, 55, 56, 57, 57, 56, 56, 56, 55, 56, 56},
+			Radios: []Radio{
+				{Name: "2.4 GHz", Channel: 11, WidthMhz: 20, PowerDbm: 18, Clients: 4},
+				{Name: "5 GHz", Channel: 44, WidthMhz: 80, PowerDbm: 21, Clients: 4},
+			},
+			Ports: []demoPortState{
+				{Name: "br-lan", Up: true, Speed: "—", Role: "Bridge LAN"},
+				{Name: "eth0", Up: true, Speed: "1 Gbps", Role: "Uplink al Gateway"},
+				{Name: "eth1", Up: true, Speed: "1 Gbps", Role: "Switch estudio"},
+				{Name: "phy0-ap0", Up: true, Speed: "—", Role: "Radio 2.4 GHz"},
+				{Name: "phy1-ap0", Up: true, Speed: "—", Role: "Radio 5 GHz"},
+			},
+			// NanoPi R4S: 2× 1G (WAN + LAN)
+			EthPorts: []EthPort{
+				{ID: "wan", Label: "WAN", Up: true, Speed: "1 Gbps", ConnectedTo: "Uplink → Gateway", Detail: "Gateway · LAN 3 (192.168.8.1)"},
+				{ID: "lan1", Label: "LAN 1", Up: true, Speed: "1 Gbps", ConnectedTo: "Switch estudio", Detail: "Switch 8 puertos · 4 en uso"},
+			},
+		},
+		"patio": {
+			MAC: "C0:4A:00:9B:51:8D", Firmware: "OpenWrt 23.05.5",
+			FirmwareUpdated: false, FirmwareAvailable: "24.10.1", LastReboot: "9 dic, 14:05 (corte eléctrico)",
+			Soc: "Qualcomm QCA9563", Flash: "16 MB SPI", RamMb: 128,
+			BandSplit:  demoBandSplit{Band24: 5, Band5: 1, Cable: 0},
+			TrafficNow: 1.8, GatewayLatencyMs: fptr(2),
+			GatewayLatencySpark: []float64{2, 2, 3, 2, 2, 2, 3, 2, 2, 3, 2, 2, 3, 3, 2, 2, 3, 4, 3, 2, 2, 2, 2, 2},
+			Backhaul:            &demoBackhaul{Kind: "wireless", Headline: "−58 dBm · 866 Mbps PHY", LatencyMs: 2},
+			BackhaulSignal:      []float64{-60, -61, -61, -62, -61, -60, -59, -60, -61, -60, -59, -58, -59, -60, -60, -59, -58, -57, -58, -59, -60, -59, -58, -58},
+			Radios: []Radio{
+				{Name: "2.4 GHz", Channel: 1, WidthMhz: 20, PowerDbm: 20, Clients: 5, Congested: true},
+				{Name: "5 GHz", Channel: 149, WidthMhz: 80, PowerDbm: 22, Clients: 1},
+			},
+			Ports: []demoPortState{
+				{Name: "br-lan", Up: true, Speed: "—", Role: "Bridge LAN"},
+				{Name: "eth0", Up: false, Speed: "—", Role: "Puerto LAN (sin uso)"},
+				{Name: "phy0-ap0", Up: true, Speed: "—", Role: "Radio 2.4 GHz"},
+				{Name: "phy1-sta0", Up: true, Speed: "866 Mbps", Role: "Uplink wireless al Gateway"},
+			},
+			// EAP225: 1× 1G — sin uso (uplink inalámbrico mesh, ver backhaul)
+			EthPorts: []EthPort{
+				{ID: "lan1", Label: "LAN", Up: false, Detail: "Uplink por WiFi mesh"},
+			},
+		},
+	}
+}
+
+// ---------------------------------------------------------------------------
+// perfSeries (dataset.js:816-845) — deterministas, terminan en el valor actual
+// ---------------------------------------------------------------------------
+
+// noise replica el ruido determinista 0..1 del JS.
+func noise(i int, seed int) float64 {
+	x := math.Sin(float64(i)*127.1+float64(seed)*311.7) * 43758.5453
+	return x - math.Floor(x)
+}
+
+// hourRangeLabels: etiquetas 1h — puntos cada 3 minutos terminando "ahora".
+func hourRangeLabels(n int) []string {
+	labels := make([]string, 0, n)
+	now := time.Now()
+	for i := n - 1; i >= 0; i-- {
+		d := now.Add(-time.Duration(i) * 3 * time.Minute)
+		labels = append(labels, fmt.Sprintf("%02d:%02d", d.Hour(), d.Minute()))
+	}
+	return labels
+}
+
+var dayLabels = []string{"Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"}
+
+// canonRouterIDs es el orden canónico (seed = índice + 1).
+var canonRouterIDs = []string{"flint2", "living", "estudio", "patio"}
+
+// perfSeries replica perfSeries(router, range): range ∈ "1h"|"24h"|"7d".
+// cpu/ram/temp son los valores ACTUALES del router (canon o caminados).
+func perfSeries(routerID string, cpu, ram, temp int, rang string) []PerfPoint {
+	seed := 1
+	for i, id := range canonRouterIDs {
+		if id == routerID {
+			seed = i + 1
+		}
+	}
+	isGateway := routerID == "flint2"
+	var n int
+	var labels []string
+	switch rang {
+	case "1h":
+		n = 20
+		labels = hourRangeLabels(n)
+	case "24h":
+		n = 24
+		labels = make([]string, n)
+		for i := range labels {
+			labels[i] = fmt.Sprintf("%02d:00", i)
+		}
+	default: // "7d"
+		n = 7
+		labels = dayLabels
+	}
+
+	peakIdx := 4 // 7d
+	if rang == "24h" {
+		peakIdx = 21
+	} else if rang == "1h" {
+		peakIdx = 15
+	}
+	cpuPeak := cpu + 34
+	if cpuPeak > 88 {
+		cpuPeak = 88
+	}
+	if isGateway {
+		cpuPeak = 61
+	}
+	tempPeak := temp + 4
+	if isGateway {
+		tempPeak = 58
+	}
+
+	points := make([]PerfPoint, 0, n)
+	for i := 0; i < n; i++ {
+		var dayShape float64
+		if rang == "7d" {
+			dayShape = 0.7 + 0.3*(float64(i)/float64(n-1))
+		} else {
+			s := math.Sin((float64(i)-6)/float64(n)*math.Pi*2 - math.Pi/2)
+			dayShape = 0.55 + 0.45*s*s
+		}
+		wob := noise(i, seed)
+		c := math.Max(2, math.Round(float64(cpu)*dayShape+wob*6))
+		r := math.Max(10, math.Round(float64(ram)-6+wob*10+(float64(i)/float64(n))*4))
+		t := math.Max(30, math.Round(float64(temp)-5+wob*4+dayShape*4))
+		if i == peakIdx {
+			c = float64(cpuPeak)
+			t = float64(tempPeak)
+		}
+		points = append(points, PerfPoint{T: labels[i], CPU: c, RAM: r, Temp: t})
+	}
+	// La serie termina SIEMPRE en el valor actual del router.
+	points[n-1] = PerfPoint{T: labels[n-1], CPU: float64(cpu), RAM: float64(ram), Temp: float64(temp)}
+	return points
+}
+
+// ---------------------------------------------------------------------------
+// Latencia WAN 24h (canon: pico 34 ms a las 21:00)
+// ---------------------------------------------------------------------------
+
+func canonWANLatency24h() []float64 {
+	return []float64{9, 8, 8, 7, 7, 8, 9, 10, 11, 12, 11, 12, 13, 12, 11, 12, 14, 16, 19, 24, 29, 34, 14, 8}
+}
+
+func canonWANLatencyStats() WANLatencyStats {
+	return WANLatencyStats{AvgMs: 11, JitterMs: 2.1, LossPct: 0}
+}
+
+// ---------------------------------------------------------------------------
+// adguardSeries24h (buildAdGuardSeries, dataset.js:862-884): suma exacta del
+// canon (84312 / 15687), punto 21:00 fijado a 5412/1031, drift en la hora 20.
+// ---------------------------------------------------------------------------
+
+func buildAdGuardSeries() []AdGuardHour {
+	weights := []float64{0.35, 0.22, 0.15, 0.12, 0.12, 0.18, 0.35, 0.6, 0.8, 0.9, 1, 1.05, 1.1, 1.05, 1, 1.05, 1.15, 1.3, 1.5, 1.7, 1.9, 2.1, 1.4, 0.7}
+	const totalQ, totalB = 84312, 15687
+	sumW := 0.0
+	for _, w := range weights {
+		sumW += w
+	}
+	q := make([]int64, len(weights))
+	for i, w := range weights {
+		q[i] = int64(math.Round(w / sumW * totalQ))
+	}
+	q[21] = 5412
+	var sumQ int64
+	for _, v := range q {
+		sumQ += v
+	}
+	q[20] += totalQ - sumQ // drift absorbido en la hora 20
+	b := make([]int64, len(weights))
+	for i, v := range q {
+		b[i] = int64(math.Round(float64(v) * (float64(totalB) / float64(totalQ))))
+	}
+	b[21] = 1031
+	var sumB int64
+	for _, v := range b {
+		sumB += v
+	}
+	b[20] += totalB - sumB
+	out := make([]AdGuardHour, len(weights))
+	for i := range weights {
+		out[i] = AdGuardHour{T: fmt.Sprintf("%02d:00", i), Permitidas: q[i] - b[i], Bloqueadas: b[i]}
+	}
+	return out
+}
+
+// ---------------------------------------------------------------------------
+// WireGuard extras (wgPeerExtras + WG_TOTALS_30D)
+// ---------------------------------------------------------------------------
+
+// wgPeerExtra es {endpoint, allowedIps, lastIp} por peer (shape routerExtras.ts).
+type wgPeerExtra struct {
+	Endpoint   string `json:"endpoint"`
+	AllowedIPs string `json:"allowedIps"`
+	LastIP     string `json:"lastIp"`
+}
+
+func canonWGPeerExtras() map[string]wgPeerExtra {
+	return map[string]wgPeerExtra{
+		"pixel-8-pro":      {Endpoint: "5.224.x.x:51820", AllowedIPs: "10.0.0.2/32", LastIP: "5.224.x.x"},
+		"macbook-air":      {Endpoint: "92.58.x.x:51820", AllowedIPs: "10.0.0.3/32", LastIP: "92.58.x.x"},
+		"ipad-air":         {Endpoint: "—", AllowedIPs: "10.0.0.4/32", LastIP: "81.34.x.x"},
+		"portatil-trabajo": {Endpoint: "—", AllowedIPs: "10.0.0.5/32", LastIP: "80.102.x.x"},
+		"casa-familia":     {Endpoint: "—", AllowedIPs: "10.0.0.6/32", LastIP: "95.60.x.x"},
+	}
+}
+
+func canonWGTotals30d() *WGTotals { return &WGTotals{Rx: "17,9 GB", Tx: "5,0 GB"} }

+ 68 - 0
server-go/internal/adapters/fmtutil.go

@@ -0,0 +1,68 @@
+// fmtutil.go — utilidades de formato ES compartidas (demo random walk y
+// WireGuard live): parseBytes/fmtBytes ("1,2 GB" ⇄ 1.2e9) y relTime
+// ("hace 38 s"). Port literal de demo.js:35-51 y wireguard.js:38-55.
+package adapters
+
+import (
+	"fmt"
+	"math"
+	"regexp"
+	"strconv"
+	"strings"
+)
+
+var byteStrRe = regexp.MustCompile(`^([\d.,]+)\s*(B|KB|MB|GB|TB)$`)
+
+var unitMult = map[string]float64{"B": 1, "KB": 1e3, "MB": 1e6, "GB": 1e9, "TB": 1e12}
+
+// parseBytes parsea formato ES ("1,2 GB", "214 MB", "1,1 TB") a bytes.
+// Quita puntos de miles y convierte la coma decimal (demo.js:37-41).
+func parseBytes(str string) float64 {
+	m := byteStrRe.FindStringSubmatch(strings.TrimSpace(str))
+	if m == nil {
+		return 0
+	}
+	num := strings.NewReplacer(".", "", ",", ".").Replace(m[1])
+	v, err := strconv.ParseFloat(num, 64)
+	if err != nil {
+		return 0
+	}
+	return math.Round(v * unitMult[m[2]])
+}
+
+// fmtBytes formatea bytes al estilo ES del contrato (wireguard.js:38-46):
+// ≥1e9 → entero "N GB" o 1 decimal con coma; ≥1e6 → "N MB"; ≥1e3 → "N KB".
+func fmtBytes(bytes float64) string {
+	if bytes >= 1e9 {
+		v := bytes / 1e9
+		if v == math.Trunc(v) {
+			return fmt.Sprintf("%d GB", int64(v))
+		}
+		return strings.Replace(strconv.FormatFloat(v, 'f', 1, 64), ".", ",", 1) + " GB"
+	}
+	if bytes >= 1e6 {
+		return fmt.Sprintf("%d MB", int64(math.Round(bytes/1e6)))
+	}
+	if bytes >= 1e3 {
+		return fmt.Sprintf("%d KB", int64(math.Round(bytes/1e3)))
+	}
+	return fmt.Sprintf("%d B", int64(math.Round(bytes)))
+}
+
+// relTime: epoch seg → texto relativo ES (wireguard.js:49-55).
+func relTime(epochSec, nowSec int64) string {
+	diff := nowSec - epochSec
+	if diff < 0 {
+		diff = 0
+	}
+	switch {
+	case diff < 60:
+		return fmt.Sprintf("hace %d s", diff)
+	case diff < 3600:
+		return fmt.Sprintf("hace %d min", diff/60)
+	case diff < 86400:
+		return fmt.Sprintf("hace %d h", diff/3600)
+	default:
+		return fmt.Sprintf("hace %d días", diff/86400)
+	}
+}

+ 1412 - 0
server-go/internal/adapters/live.go

@@ -0,0 +1,1412 @@
+// live.go — Adapter live (port de src/adapters/index.js, SPEC §7.2-§7.8):
+// compone el snapshot por router con degradación elegante (router caído →
+// offline + alerta tras 2 fallos seguidos; el resto sigue), single-flight en
+// GetOverview (los SSH son lo caro), persistencia de atribución en
+// device_attrib (solo wireless) y alertas en memoria (máx 100).
+package adapters
+
+import (
+	"context"
+	"database/sql"
+	"encoding/json"
+	"fmt"
+	"log"
+	"math"
+	"sort"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// fmtUptime: "<d>d <h>h" (index.js:32-36).
+func fmtUptime(sec float64) string {
+	d := int(sec) / 86400
+	h := (int(sec) % 86400) / 3600
+	return fmt.Sprintf("%dd %dh", d, h)
+}
+
+// mbps: bps → Mbps 1 decimal (null → 0).
+func mbps(bps *float64) float64 {
+	if bps == nil {
+		return 0
+	}
+	return math.Round(*bps/1e6*10) / 10
+}
+
+// pickGateway: is_gateway → glinet → primero.
+func pickGateway(routers []RouterConfig) *RouterConfig {
+	for i := range routers {
+		if routers[i].IsGateway {
+			return &routers[i]
+		}
+	}
+	for i := range routers {
+		if routers[i].Type == "glinet" {
+			return &routers[i]
+		}
+	}
+	if len(routers) > 0 {
+		return &routers[0]
+	}
+	return nil
+}
+
+// routerPolled es el sondeo de un tick de un router.
+type routerPolled struct {
+	cfg       RouterConfig
+	client    *OpenWrtClient
+	sysInfo   *SysInfo
+	board     *BoardInfo
+	cpu       int
+	ram       int
+	temp      int
+	uptimeSec float64
+	net       *NetDevBps
+	leases    []DhcpLease
+	wireless  map[string]WirelessClient
+	ports     []EthPort
+	radios    []Radio
+	fdb       map[string]string
+	brMac     string
+	latencyMs *float64
+	lossPct   *float64
+}
+
+// extrasSnapshot es la caché anti-parpadeo por router.
+type extrasSnapshot struct {
+	ports    []EthPort
+	radios   []Radio
+	wireless map[string]WirelessClient
+	fdb      map[string]string
+}
+
+// Live es el Snapshotter del modo live.
+type Live struct {
+	cfg  *config.Config
+	db   *db.DB
+	pool *SSHPool
+
+	mu         sync.Mutex
+	routers    []RouterConfig
+	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
+	alerts      []AlertEvent
+	wgActive    map[string]bool
+	weakAlerted map[string]int64
+
+	agStd *AdGuardClient
+	agGL  *AdGuardGlinetClient
+	agKey string
+
+	sfMu       sync.Mutex
+	sfInFlight chan sfResult
+}
+
+type sfResult struct {
+	ov  *Overview
+	err error
+}
+
+// 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{},
+		wgActive:    map[string]bool{},
+		weakAlerted: map[string]int64{},
+	}
+	// Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
+	if d != nil {
+		var flag string
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = 'attrib_v2'").Scan(&flag); err == sql.ErrNoRows {
+			_, _ = d.Exec("DELETE FROM device_attrib")
+			_, _ = d.Exec("INSERT INTO kv (key, value) VALUES ('attrib_v2', '1')")
+			log.Printf("[netpulse] device_attrib limpiada (attrib_v2: solo wireless persiste)")
+		}
+	}
+	l.SetRouters(initial)
+	return l
+}
+
+// Mode: "live".
+func (l *Live) Mode() string { return "live" }
+
+// Tick: no-op (el sondeo real ocurre en GetOverview, como el JS).
+func (l *Live) Tick(context.Context) error { return nil }
+
+// Close cierra el pool SSH.
+func (l *Live) Close() error {
+	l.pool.Close()
+	return nil
+}
+
+// SetRouters actualiza la lista en caliente y limpia cachés de bajas.
+func (l *Live) SetRouters(list []RouterConfig) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	l.routers = append([]RouterConfig(nil), list...)
+	l.gatewayCfg = pickGateway(l.routers)
+	l.clients = map[string]*OpenWrtClient{}
+	for _, c := range l.routers {
+		l.clients[c.ID] = NewOpenWrtClient(c, l.pool, "root", "")
+	}
+	ids := map[string]bool{}
+	for _, r := range l.routers {
+		ids[r.ID] = true
+	}
+	for id := range l.lastGood {
+		if !ids[id] {
+			delete(l.lastGood, id)
+		}
+	}
+	for id := range l.lastStatus {
+		if !ids[id] {
+			delete(l.lastStatus, id)
+		}
+	}
+	for id := range l.boardCache {
+		if !ids[id] {
+			delete(l.boardCache, id)
+		}
+	}
+	for id := range l.layoutCache {
+		if !ids[id] {
+			delete(l.layoutCache, id)
+		}
+	}
+	for id := range l.extrasCache {
+		if !ids[id] {
+			delete(l.extrasCache, id)
+		}
+	}
+	for id := range l.lastPolled {
+		if !ids[id] {
+			delete(l.lastPolled, id)
+		}
+	}
+	for id := range l.failCount {
+		if !ids[id] {
+			delete(l.failCount, id)
+		}
+	}
+}
+
+// getAdguardClient: kv (GL.iNet) con fallback a .env (AGH estándar).
+func (l *Live) getAdguardClient() (std *AdGuardClient, gl *AdGuardGlinetClient) {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	key := ""
+	if l.db != nil {
+		var host string
+		if err := l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_host'").Scan(&host); err == nil && host != "" {
+			user := "root"
+			_ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_user'").Scan(&user)
+			pass := ""
+			_ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_pass'").Scan(&pass)
+			if pass != "" {
+				key = "gl|" + host + "|" + user
+				if l.agKey != key {
+					l.agGL = NewAdGuardGlinetClient(host, user, pass, l.pool)
+				}
+			}
+		}
+	}
+	if key == "" && l.cfg.Adguard != nil && l.cfg.Adguard.Pass != "" {
+		key = "std|" + l.cfg.Adguard.URL
+		if l.agKey != key {
+			l.agStd = NewAdGuardClient(l.cfg.Adguard.URL, l.cfg.Adguard.User, l.cfg.Adguard.Pass)
+		}
+	}
+	if key == "" {
+		return nil, nil
+	}
+	if l.agKey != key {
+		l.agKey = key
+		if strings.HasPrefix(key, "gl|") {
+			l.agStd = nil
+		} else {
+			l.agGL = nil
+		}
+	}
+	return l.agStd, l.agGL
+}
+
+// histPoint es un punto de metricsHistory {t, down, up, cpu, ram, temp}.
+type histPoint struct {
+	t              string
+	down, up       float64
+	cpu, ram, temp int
+}
+
+var weekdayES = []string{"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"}
+
+// metricsHistory consulta las métricas históricas (index.js:122-147).
+func (l *Live) metricsHistory(routerID, rang string) []histPoint {
+	if l.db == nil || routerID == "" {
+		return []histPoint{}
+	}
+	now := time.Now().UnixMilli()
+	var span, bucket int64
+	var fmtLabel func(time.Time) string
+	switch rang {
+	case "1h":
+		span, bucket = 3600e3, 180e3
+		fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d:%02d", d.Hour(), d.Minute()) }
+	case "24h":
+		span, bucket = 86400e3, 3600e3
+		fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d", d.Hour()) }
+	case "7d":
+		span, bucket = 7*86400e3, 86400e3
+		fmtLabel = func(d time.Time) string { return weekdayES[d.Weekday()] }
+	case "30d":
+		span, bucket = 30*86400e3, 86400e3
+		fmtLabel = func(d time.Time) string { return fmt.Sprintf("%d", d.Day()) }
+	default:
+		return []histPoint{}
+	}
+	rows, err := l.db.Query(
+		`SELECT (ts / ?) AS bucket, AVG(rx_bps) AS rx, AVG(tx_bps) AS tx, AVG(cpu) AS cpu, AVG(ram) AS ram, AVG(temp) AS temp, MIN(ts) AS t0
+		 FROM metrics WHERE router_id = ? AND ts >= ? GROUP BY bucket ORDER BY bucket`,
+		bucket, routerID, now-span)
+	if err != nil {
+		return []histPoint{}
+	}
+	defer rows.Close()
+	out := []histPoint{}
+	for rows.Next() {
+		var b, t0 int64
+		var rx, tx, cpu, ram, temp sql.NullFloat64
+		if err := rows.Scan(&b, &rx, &tx, &cpu, &ram, &temp, &t0); err != nil {
+			continue
+		}
+		hp := histPoint{t: fmtLabel(time.UnixMilli(t0).Local())}
+		if rx.Valid {
+			hp.down = math.Round(rx.Float64/1e6*10) / 10
+		}
+		if tx.Valid {
+			hp.up = math.Round(tx.Float64/1e6*10) / 10
+		}
+		if cpu.Valid {
+			hp.cpu = int(math.Round(cpu.Float64))
+		}
+		if ram.Valid {
+			hp.ram = int(math.Round(ram.Float64))
+		}
+		if temp.Valid {
+			hp.temp = int(math.Round(temp.Float64))
+		}
+		out = append(out, hp)
+	}
+	return out
+}
+
+// pollRouter sondea un router; error si está inalcanzable.
+func (l *Live) pollRouter(cfg RouterConfig) (*routerPolled, error) {
+	l.mu.Lock()
+	client := l.clients[cfg.ID]
+	gw := l.gatewayCfg
+	layout, hasLayout := l.layoutCache[cfg.ID]
+	board, hasBoard := l.boardCache[cfg.ID]
+	cached := l.extrasCache[cfg.ID]
+	l.mu.Unlock()
+	if client == nil {
+		return nil, fmt.Errorf("router %s sin cliente", cfg.ID)
+	}
+
+	// Calienta la conexión SSH en serie (equivalente al `ssh true` del JS:
+	// las llamadas de abajo multiplexan sobre la conexión ya establecida).
+	if _, err := l.pool.Run(cfg.Host, "true", 0); err != nil {
+		return nil, err
+	}
+	// Layout de puertos (board.json): se lee una vez y se cachea
+	if !hasLayout {
+		if lay, err := client.GetPortLayout(); err == nil && len(lay) > 0 {
+			layout = lay
+			l.mu.Lock()
+			l.layoutCache[cfg.ID] = lay
+			l.mu.Unlock()
+		}
+	}
+	// sysInfo es la única sonda obligatoria (sin catch en el JS)
+	sysInfo, err := client.GetSysInfo()
+	if err != nil {
+		return nil, err
+	}
+	cpu, _ := client.GetCPUPercent()
+	temp, _ := client.GetTempC()
+	net, nerr := client.GetNetDevBps()
+	if nerr != nil || net == nil {
+		net = &NetDevBps{}
+	}
+	leases := client.GetDhcpLeases()
+	wireless := client.GetWirelessClients()
+	ports := client.GetEthPorts(layout)
+	radios := client.GetRadios()
+	fdb := client.GetBridgeFdb()
+	brMac := client.GetBridgeMac()
+	if !hasBoard {
+		if b, err := client.GetBoard(); err == nil {
+			board = b
+			l.mu.Lock()
+			l.boardCache[cfg.ID] = b
+			l.mu.Unlock()
+		}
+	}
+
+	// Anti-parpadeo: conserva la última lista buena en sondas puntuales
+	// (null = sonda fallida; colección vacía = resultado real).
+	if cached == nil {
+		cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
+			wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
+	}
+	portsGood := cached.ports
+	if len(ports) > 0 {
+		portsGood = ports
+	}
+	radiosGood := cached.radios
+	if len(radios) > 0 {
+		radiosGood = radios
+	}
+	wirelessGood := cached.wireless
+	if wireless != nil {
+		wirelessGood = wireless
+	}
+	fdbGood := cached.fdb
+	if fdb != nil {
+		fdbGood = fdb
+	}
+	l.mu.Lock()
+	l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood}
+	l.mu.Unlock()
+
+	// Uso real de RAM como en la UI del router: used = total − available
+	mem := sysInfo.Memory
+	ramPct := 0
+	if mem.Total > 0 {
+		avail := mem.Available
+		if avail == 0 {
+			avail = mem.Free + mem.Buffered
+		}
+		ramPct = int(math.Round((mem.Total - avail) / mem.Total * 100))
+	}
+
+	isGw := gw != nil && cfg.ID == gw.ID
+	var latencyMs, lossPct *float64
+	if isGw {
+		latencyMs, lossPct, _ = client.GetWanLatency("")
+	} else if gw != nil {
+		latencyMs, _ = client.GetGatewayLatency(gw.Host)
+	}
+
+	cpuV := 0
+	if cpu != nil {
+		cpuV = *cpu
+	}
+	tempV := 0
+	if temp != nil {
+		tempV = *temp
+	}
+	return &routerPolled{
+		cfg: cfg, client: client, sysInfo: sysInfo, board: board,
+		cpu: cpuV, ram: ramPct, temp: tempV,
+		uptimeSec: sysInfo.Uptime, net: net, leases: leases,
+		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
+		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
+	}, nil
+}
+
+// buildRouter construye el Router del contrato (index.js:221-249).
+func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
+	l.mu.Lock()
+	gw := l.gatewayCfg
+	l.mu.Unlock()
+	model := p.cfg.Name
+	if model == "" {
+		model = p.cfg.Host
+	}
+	if p.board != nil && p.board.Model != "" {
+		model = p.board.Model
+	}
+	name := p.cfg.Name
+	if name == "" {
+		name = p.cfg.Host
+	}
+	if p.board != nil && p.board.Hostname != "" {
+		name = p.board.Hostname
+	}
+	health := 100
+	if p.cpu > 85 {
+		health -= 20
+	} else if p.cpu > 70 {
+		health -= 10
+	}
+	if p.temp > 75 {
+		health -= 25
+	} else if p.temp > 65 {
+		health -= 12
+	}
+	if p.ram > 90 {
+		health -= 15
+	}
+	if health < 0 {
+		health = 0
+	}
+	isGw := gw != nil && p.cfg.ID == gw.ID
+	status := "online"
+	if p.temp > 65 || p.cpu > 85 {
+		status = "warn"
+	}
+	sparkline := make([]float64, 0, len(history))
+	for _, h := range history {
+		sparkline = append(sparkline, h.down)
+	}
+	r := Router{
+		ID: p.cfg.ID, Name: name, Model: model, ModelShort: model,
+		IP: p.cfg.Host, Status: status, Health: health,
+		CPU: iptr(p.cpu), RAM: iptr(p.ram), Temp: iptr(p.temp),
+		Uptime: fmtUptime(p.uptimeSec), Clients: len(p.leases),
+		Sparkline: sparkline,
+	}
+	if isGw {
+		r.Role, r.RoleBadge = "Gateway principal", "Principal"
+	} else {
+		r.Role, r.RoleBadge = "Punto de acceso", "AP"
+	}
+	if p.brMac != "" {
+		r.MAC = p.brMac
+	}
+	if p.board != nil {
+		r.Firmware = p.board.Release.Description
+	}
+	if p.temp > 65 {
+		r.HotMetric = "temp"
+	}
+	return r
+}
+
+// offlineRouter: último bueno marcado offline o placeholder (index.js:251-272).
+func (l *Live) offlineRouter(cfg RouterConfig) Router {
+	l.mu.Lock()
+	prev := l.lastGood[cfg.ID]
+	gw := l.gatewayCfg
+	l.mu.Unlock()
+	var r Router
+	if prev != nil {
+		r = *prev
+	} else {
+		model := "OpenWrt"
+		if cfg.Type == "glinet" {
+			model = "GL.iNet"
+		}
+		name := cfg.Name
+		if name == "" {
+			name = cfg.Host
+		}
+		r = Router{
+			ID: cfg.ID, Name: name, Model: model, ModelShort: model,
+			IP: cfg.Host, Health: 0,
+			CPU: iptr(0), RAM: iptr(0), Temp: iptr(0),
+			Uptime: "—", Clients: 0, Sparkline: []float64{},
+		}
+		if gw != nil && cfg.ID == gw.ID {
+			r.Role, r.RoleBadge = "Gateway principal", "Principal"
+		} else {
+			r.Role, r.RoleBadge = "Punto de acceso", "AP"
+		}
+	}
+	r.Status = "offline"
+	return r
+}
+
+// pollAll sondea todos los routers en paralelo (Promise.allSettled).
+func (l *Live) pollAll() map[string]*routerPolled {
+	l.mu.Lock()
+	routers := append([]RouterConfig(nil), l.routers...)
+	l.mu.Unlock()
+
+	type result struct {
+		cfg RouterConfig
+		p   *routerPolled
+		err error
+	}
+	results := make([]result, len(routers))
+	var wg sync.WaitGroup
+	for i, cfg := range routers {
+		wg.Add(1)
+		go func(i int, cfg RouterConfig) {
+			defer wg.Done()
+			p, err := l.pollRouter(cfg)
+			results[i] = result{cfg, p, err}
+		}(i, cfg)
+	}
+	wg.Wait()
+
+	polled := map[string]*routerPolled{}
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	for _, res := range results {
+		if res.err == nil {
+			polled[res.cfg.ID] = res.p
+			l.failCount[res.cfg.ID] = 0
+			l.lastStatus[res.cfg.ID] = "online"
+			continue
+		}
+		fails := l.failCount[res.cfg.ID] + 1
+		l.failCount[res.cfg.ID] = fails
+		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" {
+			name := res.cfg.Name
+			if name == "" {
+				name = res.cfg.Host
+			}
+			l.alerts = append([]AlertEvent{{
+				ID:       fmt.Sprintf("alert-offline-%s-%d", res.cfg.ID, time.Now().UnixMilli()),
+				Severity: "critical",
+				Title:    name + " offline",
+				Description: fmt.Sprintf("Sin respuesta de %s: %v", res.cfg.Host, res.err),
+				Time:     "ahora mismo", Read: false, RouterID: res.cfg.ID,
+			}}, l.alerts...)
+			if len(l.alerts) > 100 {
+				l.alerts = l.alerts[:100]
+			}
+		}
+		if fails >= 2 {
+			l.lastStatus[res.cfg.ID] = "offline"
+		}
+	}
+	l.lastPolled = polled
+	return polled
+}
+
+// pollAdGuard: stats del cliente configurado; fallback inactivo si falla.
+func (l *Live) pollAdGuard(ctx context.Context) *AdGuardStats {
+	std, gl := l.getAdguardClient()
+	if std == nil && gl == nil {
+		return nil
+	}
+	var stats *AdGuardStats
+	var err error
+	host := ""
+	if std != nil {
+		u := std.url
+		if i := strings.Index(u, "://"); i >= 0 {
+			u = u[i+3:]
+		}
+		host = strings.SplitN(u, ":", 2)[0]
+		stats, err = std.GetStats(ctx)
+	} else {
+		host = gl.Host
+		stats, err = gl.GetStats(ctx)
+	}
+	if err != nil {
+		log.Printf("[netpulse] AdGuard inalcanzable: %v", err)
+		return &AdGuardStats{
+			Host: host, Port: 3000, Status: "inactive",
+			TopBlocked: []TopBlocked{},
+		}
+	}
+	return stats
+}
+
+// pollWireGuard: stats WG del gateway + alerta de handshake nuevo.
+func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
+	l.mu.Lock()
+	gw := l.gatewayCfg
+	l.mu.Unlock()
+	if gw == nil {
+		return nil
+	}
+	peerNames := map[string]WGPeerName{}
+	for _, d := range devices {
+		if d.IP != "" {
+			peerNames[d.IP] = WGPeerName{ID: d.ID, Name: d.Name, Type: d.Type}
+		}
+	}
+	stats, err := GetWireGuardStats(l.pool, gw.Host, l.cfg.WGInterface, "", peerNames)
+	if err != nil {
+		log.Printf("[netpulse] WireGuard no disponible: %v", err)
+		return &WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
+	}
+	// Alerta en handshake nuevo (peer pasa a activo)
+	activeNow := map[string]bool{}
+	for _, p := range stats.Peers {
+		if p.Active {
+			activeNow[p.ID] = true
+		}
+	}
+	l.mu.Lock()
+	for id := range activeNow {
+		if !l.wgActive[id] && len(l.wgActive) > 0 {
+			name := id
+			for _, p := range stats.Peers {
+				if p.ID == id {
+					name = p.Name
+				}
+			}
+			l.alerts = append([]AlertEvent{{
+				ID: fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
+				Severity: "info", Title: "Handshake WireGuard",
+				Description: name + " conectado",
+				Time:        "ahora mismo", Read: false, RouterID: gw.ID,
+			}}, l.alerts...)
+			if len(l.alerts) > 100 {
+				l.alerts = l.alerts[:100]
+			}
+		}
+	}
+	l.wgActive = activeNow
+	l.mu.Unlock()
+	return stats
+}
+
+// buildDevices: unión de leases + MACs vistas (wireless > FDB satélites >
+// FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
+func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
+	leasesByMac := map[string]DhcpLease{}
+	for _, p := range polled {
+		for _, le := range p.leases {
+			if le.MAC != "" {
+				leasesByMac[le.MAC] = le
+			}
+		}
+	}
+	type knownInfo struct {
+		routerID string
+		band     string
+		signal   *int
+	}
+	known := map[string]knownInfo{}
+	if l.db != nil {
+		rows, err := l.db.Query("SELECT mac, router_id, band, signal_dbm FROM device_attrib")
+		if err == nil {
+			defer rows.Close()
+			for rows.Next() {
+				var mac, routerID, band string
+				var signal sql.NullInt64
+				if rows.Scan(&mac, &routerID, &band, &signal) == nil {
+					k := knownInfo{routerID: routerID, band: band}
+					if signal.Valid {
+						v := int(signal.Int64)
+						k.signal = &v
+					}
+					known[mac] = k
+				}
+			}
+		}
+	}
+	now := time.Now().UnixMilli()
+
+	type seenInfo struct {
+		routerID string
+		band     string
+		signal   *int
+	}
+	seen := map[string]seenInfo{}
+	// (1) wireless de cualquier router: la ÚNICA que se persiste
+	for routerID, p := range polled {
+		for mac, w := range p.wireless {
+			sig := w.SignalDbm
+			seen[mac] = seenInfo{routerID, w.Band, &sig}
+			if l.db != nil {
+				_, _ = l.db.Exec(
+					`INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?, ?, ?, ?, ?)
+					 ON CONFLICT(mac) DO UPDATE SET router_id=excluded.router_id, band=excluded.band, signal_dbm=excluded.signal_dbm, last_seen=excluded.last_seen`,
+					mac, routerID, w.Band, w.SignalDbm, now)
+			}
+		}
+	}
+	l.mu.Lock()
+	gw := l.gatewayCfg
+	l.mu.Unlock()
+	gwID := ""
+	if gw != nil {
+		gwID = gw.ID
+	}
+	// (2) FDB de satélites: pista solo de ESTE tick (no se guarda)
+	for routerID, p := range polled {
+		if routerID == gwID {
+			continue
+		}
+		for mac := range p.fdb {
+			if _, ok := seen[mac]; !ok {
+				seen[mac] = seenInfo{routerID, "cable", nil}
+			}
+		}
+	}
+	// (3) FDB del gateway: solo si no hay memoria (mala pista; no se guarda)
+	if gwID != "" {
+		if gwPolled := polled[gwID]; gwPolled != nil {
+			for mac := range gwPolled.fdb {
+				if _, ok := seen[mac]; !ok {
+					if _, ok := known[mac]; !ok {
+						seen[mac] = seenInfo{gwID, "cable", nil}
+					}
+				}
+			}
+		}
+	}
+
+	allMacs := map[string]bool{}
+	for mac := range leasesByMac {
+		allMacs[mac] = true
+	}
+	for mac := range seen {
+		allMacs[mac] = true
+	}
+	for mac := range known {
+		allMacs[mac] = true
+	}
+	routerMacs := map[string]bool{}
+	for _, p := range polled {
+		if p.brMac != "" {
+			routerMacs[p.brMac] = true
+		}
+	}
+	devices := []Device{}
+	for mac := range allMacs {
+		if routerMacs[mac] {
+			continue // los routers no son clientes
+		}
+		lease, hasLease := leasesByMac[mac]
+		s, isSeen := seen[mac]
+		d := Device{
+			ID: strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
+			MAC: mac, Type: "desconocido", Manufacturer: "Desconocido",
+			TrafficMbps: 0, Sparkline: []float64{},
+			RouterID: gwID, Band: "—",
+			Online: isSeen,
+		}
+		if hasLease {
+			if lease.Hostname != "" {
+				d.Name = lease.Hostname
+			} else {
+				d.Name = mac
+			}
+			d.IP = lease.IP
+		} else {
+			d.Name = mac
+		}
+		if isSeen {
+			d.RouterID = s.routerID
+			d.Band = s.band
+			d.SignalDbm = s.signal
+		} else if k, ok := known[mac]; ok {
+			d.RouterID = k.routerID
+			d.Band = k.band
+			d.SignalDbm = k.signal
+		}
+		devices = append(devices, d)
+	}
+	return devices
+}
+
+// computeHealth (index.js:462-486).
+func computeHealth(routers []Router, adguard *AdGuardStats) HealthScore {
+	score := 100
+	breakdown := []HealthDelta{}
+	for _, r := range routers {
+		if r.Status == "offline" {
+			score -= 30
+			breakdown = append(breakdown, HealthDelta{Label: r.Name + " offline", Delta: -30})
+		} else if r.Temp != nil && *r.Temp > 65 {
+			score -= 8
+			breakdown = append(breakdown, HealthDelta{Label: "temp. " + r.Name, Delta: -8})
+		}
+	}
+	if adguard != nil && adguard.Status != "active" {
+		score -= 5
+		breakdown = append(breakdown, HealthDelta{Label: "AdGuard inactivo", Delta: -5})
+	}
+	if score < 0 {
+		score = 0
+	}
+	label := "Atención"
+	if score >= 85 {
+		label = "Excelente"
+	} else if score >= 65 {
+		label = "Bueno"
+	}
+	note := "Sin penalizaciones."
+	if len(breakdown) > 0 {
+		labels := make([]string, len(breakdown))
+		for i, b := range breakdown {
+			labels[i] = b.Label
+		}
+		note = "Penalizado por: " + strings.Join(labels, ", ") + "."
+	}
+	return HealthScore{
+		Score: score, Label: label, Caption: "Puntuación de salud de la red",
+		Note: note, Breakdown: breakdown,
+	}
+}
+
+// defaultWan (index.js:488-503).
+func (l *Live) defaultWan(gw *RouterConfig) WAN {
+	l.mu.Lock()
+	var p *routerPolled
+	if gw != nil {
+		p = l.lastPolled[gw.ID]
+	}
+	l.mu.Unlock()
+	wan := WAN{
+		Plan: "—", PublicIP: "—", Isp: "—", PeakTodayTime: "—", Total24h: "—",
+	}
+	if p != nil {
+		if p.net != nil {
+			wan.DownMbps = mbps(p.net.RxBps)
+			wan.UpMbps = mbps(p.net.TxBps)
+		}
+		if p.latencyMs != nil {
+			wan.LatencyMs = *p.latencyMs
+		}
+		if p.lossPct != nil {
+			wan.LossPct = *p.lossPct
+		}
+	}
+	return wan
+}
+
+// GetOverview: single-flight (los llamantes concurrentes comparten sondeo).
+func (l *Live) GetOverview(ctx context.Context) (*Overview, error) {
+	l.sfMu.Lock()
+	if l.sfInFlight != nil {
+		ch := l.sfInFlight
+		l.sfMu.Unlock()
+		r := <-ch
+		return r.ov, r.err
+	}
+	ch := make(chan sfResult, 1)
+	l.sfInFlight = ch
+	l.sfMu.Unlock()
+
+	ov, err := l.buildOverview(ctx)
+	ch <- sfResult{ov, err}
+	close(ch)
+
+	l.sfMu.Lock()
+	l.sfInFlight = nil
+	l.sfMu.Unlock()
+	return ov, err
+}
+
+func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
+	polled := l.pollAll()
+	l.mu.Lock()
+	routers := append([]RouterConfig(nil), l.routers...)
+	gw := l.gatewayCfg
+	l.mu.Unlock()
+
+	routerList := make([]Router, 0, len(routers))
+	for _, cfg := range routers {
+		p := polled[cfg.ID]
+		if p == nil {
+			l.mu.Lock()
+			prev := l.lastGood[cfg.ID]
+			fails := l.failCount[cfg.ID]
+			l.mu.Unlock()
+			if prev != nil && fails < 2 {
+				routerList = append(routerList, *prev)
+			} else {
+				routerList = append(routerList, l.offlineRouter(cfg))
+			}
+			continue
+		}
+		router := l.buildRouter(p, l.metricsHistory(cfg.ID, "24h"))
+		l.mu.Lock()
+		l.lastGood[cfg.ID] = &router
+		// Alerta de temperatura UNA vez por proceso (flag, como el JS)
+		if router.Temp != nil && *router.Temp > 65 && l.lastStatus[cfg.ID+":temp"] != "warn" {
+			l.lastStatus[cfg.ID+":temp"] = "warn"
+			l.alerts = append([]AlertEvent{{
+				ID: fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
+				Severity: "warn", Title: "Temperatura alta en " + router.Name,
+				Description: fmt.Sprintf("%d °C, por encima del umbral (65 °C)", *router.Temp),
+				Time:        "ahora mismo", Read: false, RouterID: cfg.ID,
+			}}, l.alerts...)
+			if len(l.alerts) > 100 {
+				l.alerts = l.alerts[:100]
+			}
+		}
+		l.mu.Unlock()
+		routerList = append(routerList, router)
+	}
+	devices := l.buildDevices(polled)
+	// Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
+	for _, d := range devices {
+		if d.Online && d.SignalDbm != nil && *d.SignalDbm < -70 {
+			l.mu.Lock()
+			last := l.weakAlerted[d.MAC]
+			if time.Now().UnixMilli()-last > 24*3600e3 {
+				l.weakAlerted[d.MAC] = time.Now().UnixMilli()
+				l.alerts = append([]AlertEvent{{
+					ID: fmt.Sprintf("alert-weak-%s-%d", d.MAC, time.Now().UnixMilli()),
+					Severity: "warn", Title: "Señal débil en " + d.Name,
+					Description: fmt.Sprintf("%d dBm en %s — revisa cobertura o acerca un AP", *d.SignalDbm, d.RouterID),
+					Time:        "ahora mismo", Read: false, RouterID: d.RouterID,
+				}}, l.alerts...)
+				if len(l.alerts) > 100 {
+					l.alerts = l.alerts[:100]
+				}
+			}
+			l.mu.Unlock()
+		}
+	}
+	// Clientes reales por router (atribución wireless/FDB, no leases)
+	for i := range routerList {
+		n := 0
+		for _, d := range devices {
+			if d.RouterID == routerList[i].ID && d.Online {
+				n++
+			}
+		}
+		routerList[i].Clients = n
+	}
+	adguard := l.pollAdGuard(ctx)
+	wireguard := l.pollWireGuard(devices)
+	gwID := ""
+	if gw != nil {
+		gwID = gw.ID
+	}
+	wan := l.defaultWan(gw)
+	for _, r := range routerList {
+		if r.ID == gwID && r.Status == "offline" {
+			wan.PublicIP = "—"
+		}
+	}
+	trafficOf := func(rang string) []TrafficPoint {
+		h := l.metricsHistory(gwID, rang)
+		out := make([]TrafficPoint, 0, len(h))
+		for _, p := range h {
+			out = append(out, TrafficPoint{T: p.t, Down: p.down, Up: p.up})
+		}
+		return out
+	}
+	ag := AdGuardStats{Status: "inactive", TopBlocked: []TopBlocked{}}
+	if adguard != nil {
+		ag = *adguard
+	}
+	wgStats := WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
+	if wireguard != nil {
+		wgStats = *wireguard
+	}
+	online := 0
+	for _, d := range devices {
+		if d.Online {
+			online++
+		}
+	}
+	top := append([]Device(nil), devices...)
+	sort.SliceStable(top, func(i, j int) bool { return top[i].TrafficMbps > top[j].TrafficMbps })
+	if len(top) > 5 {
+		top = top[:5]
+	}
+	l.mu.Lock()
+	alertsCopy := append([]AlertEvent(nil), l.alerts...)
+	l.mu.Unlock()
+	unread := 0
+	for _, a := range alertsCopy {
+		if !a.Read {
+			unread++
+		}
+	}
+	return &Overview{
+		Health:  computeHealth(routerList, adguard),
+		WAN:     wan,
+		Traffic: TrafficByRange{H1: trafficOf("1h"), H24: trafficOf("24h"), D7: trafficOf("7d"), D30: trafficOf("30d")},
+		Adguard: ag, Wireguard: wgStats, Routers: routerList,
+		DeviceTotals: DeviceTotals{
+			Total: len(devices), Online: online, KnownOffline: len(devices) - online, NewToday: 0,
+		},
+		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
+		Ts: time.Now().Unix(),
+	}, nil
+}
+
+// GetRouters: tarjetas desde la caché del último tick (index.js:600-610).
+func (l *Live) GetRouters(context.Context) []Router {
+	l.mu.Lock()
+	routers := append([]RouterConfig(nil), l.routers...)
+	polled := l.lastPolled
+	l.mu.Unlock()
+	out := make([]Router, 0, len(routers))
+	for _, cfg := range routers {
+		p := polled[cfg.ID]
+		if p == nil {
+			l.mu.Lock()
+			prev := l.lastGood[cfg.ID]
+			fails := l.failCount[cfg.ID]
+			l.mu.Unlock()
+			if prev != nil && fails < 2 {
+				out = append(out, *prev)
+			} else {
+				out = append(out, l.offlineRouter(cfg))
+			}
+			continue
+		}
+		out = append(out, l.buildRouter(p, l.metricsHistory(cfg.ID, "24h")))
+	}
+	return out
+}
+
+// liveExtras es el objeto extras del detalle live (index.js:677-700).
+type liveExtras struct {
+	MAC                 string        `json:"mac"`
+	Firmware            string        `json:"firmware"`
+	FirmwareUpdated     bool          `json:"firmwareUpdated"`
+	LastReboot          string        `json:"lastReboot"`
+	Soc                 string        `json:"soc"`
+	Flash               string        `json:"flash"`
+	RamMb               int           `json:"ramMb"`
+	BandSplit           demoBandSplit `json:"bandSplit"`
+	TrafficNow          float64       `json:"trafficNow"`
+	GatewayLatencySpark []float64     `json:"gatewayLatencySpark"`
+	BackhaulSignal      []float64     `json:"backhaulSignal"`
+	Radios              []Radio       `json:"radios"`
+	Ports               []EthPort     `json:"ports"`
+	EthPorts            []EthPort     `json:"ethPorts"`
+}
+
+// GetRouterDetail (index.js:612-715). Id desconocido → (nil, nil).
+func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, error) {
+	l.mu.Lock()
+	var cfg *RouterConfig
+	for i := range l.routers {
+		if l.routers[i].ID == id {
+			cfg = &l.routers[i]
+			break
+		}
+	}
+	p := l.lastPolled[id]
+	gw := l.gatewayCfg
+	polledAll := l.lastPolled
+	l.mu.Unlock()
+	if cfg == nil {
+		return nil, nil
+	}
+	var router Router
+	if p != nil {
+		router = l.buildRouter(p, l.metricsHistory(id, "24h"))
+	} else {
+		router = l.offlineRouter(*cfg)
+	}
+	// Mapa global MAC → lease + MAC de bridge → nombre de router
+	leaseMap := map[string]DhcpLease{}
+	routerByMac := map[string]string{}
+	for _, polled := range polledAll {
+		for _, le := range polled.leases {
+			if le.MAC != "" {
+				leaseMap[le.MAC] = le
+			}
+		}
+		if polled.brMac != "" {
+			name := polled.cfg.Name
+			if name == "" {
+				name = polled.cfg.Host
+			}
+			routerByMac[polled.brMac] = name
+		}
+	}
+	// Boca → MACs aprendidas (vecino inmediato)
+	portMacs := map[string][]string{}
+	if p != nil {
+		for mac, portName := range p.fdb {
+			portMacs[portName] = append(portMacs[portName], mac)
+		}
+	}
+	ports := []EthPort{}
+	if p != nil {
+		ports = p.ports
+	}
+	enriched := make([]EthPort, 0, len(ports))
+	for _, port := range ports {
+		if !port.Up {
+			enriched = append(enriched, port)
+			continue
+		}
+		all := portMacs[port.ID]
+		// 1) ¿Otro router al otro lado? (uplink router↔router)
+		neighbor := ""
+		for _, mac := range all {
+			if _, ok := routerByMac[mac]; ok {
+				neighbor = mac
+				break
+			}
+		}
+		if neighbor != "" {
+			port.ConnectedTo = routerByMac[neighbor]
+			port.Detail = "enlace entre routers"
+			enriched = append(enriched, port)
+			continue
+		}
+		// 2) Un solo dispositivo final
+		if len(all) == 1 {
+			mac := all[0]
+			lease, ok := leaseMap[mac]
+			switch {
+			case ok && lease.Hostname != "":
+				port.ConnectedTo = lease.Hostname
+			case ok && lease.IP != "":
+				port.ConnectedTo = lease.IP
+			default:
+				port.ConnectedTo = mac
+			}
+			port.DeviceMac = mac
+			if ok && lease.IP != "" {
+				port.Detail = lease.IP + " · full duplex"
+			}
+			enriched = append(enriched, port)
+			continue
+		}
+		// 3) Varios: el vecino es un switch/hub
+		if len(all) > 1 {
+			infraMac := ""
+			for _, mac := range all {
+				if le, ok := leaseMap[mac]; ok && le.Hostname != "" {
+					infraMac = mac
+					break
+				}
+			}
+			if infraMac != "" {
+				lease := leaseMap[infraMac]
+				port.ConnectedTo = lease.Hostname
+				port.DeviceMac = infraMac
+				if lease.IP != "" {
+					port.Detail = lease.IP
+				}
+			} else {
+				port.ConnectedTo = "Switch"
+			}
+			enriched = append(enriched, port)
+			continue
+		}
+		enriched = append(enriched, port)
+	}
+	radios := []Radio{}
+	if p != nil && p.radios != nil {
+		radios = p.radios
+	}
+	seriesOf := func(rang string) []PerfPoint {
+		h := l.metricsHistory(id, rang)
+		out := make([]PerfPoint, 0, len(h))
+		for _, hp := range h {
+			out = append(out, PerfPoint{T: hp.t, CPU: float64(hp.cpu), RAM: float64(hp.ram), Temp: float64(hp.temp)})
+		}
+		return out
+	}
+	clients := []Device{}
+	for _, d := range l.buildDevices(polledAll) {
+		if d.RouterID == id {
+			clients = append(clients, d)
+		}
+	}
+	extras := liveExtras{
+		MAC: "—", Firmware: "—", FirmwareUpdated: true, LastReboot: "—",
+		Soc: "—", Flash: "—", RamMb: 0,
+		BandSplit:           demoBandSplit{},
+		GatewayLatencySpark: []float64{},
+		BackhaulSignal:      []float64{},
+		Radios:              radios,
+		Ports:               enriched,
+		EthPorts:            enriched,
+	}
+	if p != nil {
+		if p.brMac != "" {
+			extras.MAC = p.brMac
+		}
+		if p.board != nil {
+			extras.Firmware = p.board.Release.Description
+			extras.Soc = p.board.System
+			if extras.Soc == "" {
+				extras.Soc = "—"
+			}
+		}
+		if p.uptimeSec > 0 {
+			rb := time.Now().Add(-time.Duration(p.uptimeSec) * time.Second)
+			extras.LastReboot = fmt.Sprintf("%02d/%02d/%d, %02d:%02d", rb.Day(), int(rb.Month()), rb.Year(), rb.Hour(), rb.Minute())
+		}
+		if p.sysInfo != nil && p.sysInfo.Memory.Total > 0 {
+			extras.RamMb = int(math.Round(p.sysInfo.Memory.Total / 1e6))
+		}
+		if p.net != nil {
+			extras.TrafficNow = mbps(p.net.RxBps)
+		}
+	}
+	detail := &RouterDetail{
+		Router: router, Ports: enriched, Radios: radios, Backhaul: nil,
+		Series: PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
+		Clients: clients, Extras: extras,
+	}
+	if gw != nil && id == gw.ID {
+		detail.Adguard = l.pollAdGuard(ctx)
+		detail.Wireguard = l.pollWireGuard(clients)
+	} else {
+		// Backhaul real del AP: boca que enlaza con otro router + latencia
+		var uplink *EthPort
+		for i := range enriched {
+			if enriched[i].Detail == "enlace entre routers" {
+				uplink = &enriched[i]
+				break
+			}
+		}
+		if uplink == nil {
+			for i := range enriched {
+				if enriched[i].Up {
+					uplink = &enriched[i]
+					break
+				}
+			}
+		}
+		speed := "—"
+		if uplink != nil && uplink.Speed != "" {
+			speed = uplink.Speed
+		}
+		latency := 0.0
+		if p != nil && p.latencyMs != nil {
+			latency = *p.latencyMs
+		}
+		detail.Backhaul = demoBackhaul{
+			Kind: "cable", Headline: "Cable · " + speed + " · full duplex", LatencyMs: latency,
+		}
+	}
+	return detail, nil
+}
+
+// GetDevices: buildDevices sobre el último sondeo.
+func (l *Live) GetDevices(context.Context) []Device {
+	l.mu.Lock()
+	polled := l.lastPolled
+	l.mu.Unlock()
+	return l.buildDevices(polled)
+}
+
+// GetAlerts: copia de las alertas en memoria.
+func (l *Live) GetAlerts(context.Context) []AlertEvent {
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	return append([]AlertEvent(nil), l.alerts...)
+}
+
+// GetMetricsRows: filas para el poller (index.js:725-739).
+func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
+	l.mu.Lock()
+	polled := l.lastPolled
+	l.mu.Unlock()
+	rows := []MetricsRow{}
+	for id, p := range polled {
+		row := MetricsRow{
+			RouterID:  id,
+			CPU:       fptr(float64(p.cpu)),
+			RAM:       fptr(float64(p.ram)),
+			Temp:      fptr(float64(p.temp)),
+			LatencyMs: p.latencyMs,
+		}
+		if p.net != nil {
+			row.RxBps = p.net.RxBps
+			row.TxBps = p.net.TxBps
+		}
+		rows = append(rows, row)
+	}
+	return rows
+}
+
+// GetAdguardClients: solo GL tiene /control/clients (nil si no configurado).
+func (l *Live) GetAdguardClients(ctx context.Context) ([]AdguardClient, error) {
+	_, gl := l.getAdguardClient()
+	if gl == nil {
+		return nil, nil
+	}
+	return gl.QueryClients(ctx)
+}
+
+// dawnNetwork es la respuesta de `ubus call dawn get_network`.
+type dawnNetwork map[string]map[string]struct {
+	Hostname           string  `json:"hostname"`
+	Freq               float64 `json:"freq"`
+	Channel            int     `json:"channel"`
+	ChannelUtilization float64 `json:"channel_utilization"`
+	NumSta             int     `json:"num_sta"`
+	Local              bool    `json:"local"`
+	Iface              string  `json:"iface"`
+}
+
+// GetDawn: red DAWN (roaming/band-steering). nil si ningún router responde.
+func (l *Live) GetDawn(context.Context) (*Dawn, error) {
+	l.mu.Lock()
+	routers := append([]RouterConfig(nil), l.routers...)
+	polled := l.lastPolled
+	l.mu.Unlock()
+	var firstData dawnNetwork
+	mesh := []DawnMesh{}
+	for _, cfg := range routers {
+		p := polled[cfg.ID]
+		if p == nil {
+			continue
+		}
+		name := cfg.Name
+		if name == "" {
+			name = cfg.ID
+		}
+		out, err := l.pool.Run(cfg.Host, "ubus call dawn get_network", 0)
+		if err != nil {
+			mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: false, ApsSeen: 0})
+			continue
+		}
+		var data dawnNetwork
+		if json.Unmarshal([]byte(out), &data) != nil {
+			mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: false, ApsSeen: 0})
+			continue
+		}
+		if firstData == nil {
+			firstData = data
+		}
+		seen := 0
+		for _, bssids := range data {
+			seen += len(bssids)
+		}
+		mesh = append(mesh, DawnMesh{RouterID: cfg.ID, Name: name, Dawn: true, ApsSeen: seen})
+	}
+	if firstData == nil {
+		return nil, nil
+	}
+	aps := []DawnAP{}
+	for ssid, bssids := range firstData {
+		for bssid, ap := range bssids {
+			band := "2.4 GHz"
+			if ap.Freq >= 5000 {
+				band = "5 GHz"
+			}
+			aps = append(aps, DawnAP{
+				SSID: ssid, BSSID: bssid, Hostname: ap.Hostname, Band: band,
+				Channel: ap.Channel, UtilizationPct: ap.ChannelUtilization,
+				Clients: ap.NumSta, Local: ap.Local, Iface: ap.Iface,
+			})
+		}
+	}
+	sort.Slice(aps, func(i, j int) bool {
+		if aps[i].Hostname != aps[j].Hostname {
+			return aps[i].Hostname < aps[j].Hostname
+		}
+		return aps[i].Band < aps[j].Band
+	})
+	return &Dawn{APs: aps, Mesh: mesh}, nil
+}

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

@@ -0,0 +1,812 @@
+// openwrt.go — Cliente live para routers OpenWrt / GL.iNet (port de
+// src/adapters/openwrt.js, SPEC §7.2):
+//
+//   1. ubus JSON-RPC sobre HTTP (POST http://<host>/ubus, session login con
+//      token cacheado y un solo re-login ante sesión caducada).
+//   2. Fallback SSH con pool persistente (sshpool.go; equivalente al
+//      ControlMaster del JS).
+//
+// Comandos y parseo literales del JS; timeouts cortos y errores controlados:
+// el caller (live) marca el router offline y sigue con el resto.
+package adapters
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"regexp"
+	"sort"
+	"strconv"
+	"strings"
+	"time"
+)
+
+const (
+	ubusHTTPTimeout = 4 * time.Second
+	iwinfoTimeout   = 8 * time.Second
+)
+
+// OpenWrtClient es el cliente de un router (uno por router del config).
+type OpenWrtClient struct {
+	Host     string
+	User     string // para ubus HTTP (default root)
+	Password string
+
+	pool *SSHPool
+
+	sid        string     // sesión ubus HTTP cacheada
+	lastStat   *cpuSample // /proc/stat previo
+	lastNetDev *netSample // /proc/net/dev previo
+}
+
+type cpuSample struct{ total, idleAll float64 }
+type netSample struct {
+	rx, tx float64
+	at     time.Time
+}
+
+// NewOpenWrtClient crea el cliente de un router.
+func NewOpenWrtClient(cfg RouterConfig, pool *SSHPool, user, password string) *OpenWrtClient {
+	if user == "" {
+		user = "root"
+	}
+	return &OpenWrtClient{Host: cfg.Host, User: user, Password: password, pool: pool}
+}
+
+// ---------------------------------------------------------------------------
+// Transporte ubus HTTP (JSON-RPC)
+// ---------------------------------------------------------------------------
+
+type ubusRPCError struct{ msg string }
+
+func (e *ubusRPCError) Error() string { return e.msg }
+
+// ubusHTTPRpc: POST /ubus; devuelve result[1] si result[0] == 0.
+func (c *OpenWrtClient) ubusHTTPRpc(sid, object, method string, params any) (json.RawMessage, error) {
+	if params == nil {
+		params = map[string]any{}
+	}
+	body, _ := json.Marshal(map[string]any{
+		"jsonrpc": "2.0", "id": 1, "method": "call",
+		"params": []any{sid, object, method, params},
+	})
+	ctx, cancel := context.WithTimeout(context.Background(), ubusHTTPTimeout)
+	defer cancel()
+	req, err := http.NewRequestWithContext(ctx, "POST", "http://"+c.Host+"/ubus", bytes.NewReader(body))
+	if err != nil {
+		return nil, err
+	}
+	req.Header.Set("Content-Type", "application/json")
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer res.Body.Close()
+	data, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
+	if err != nil {
+		return nil, err
+	}
+	if res.StatusCode != 200 {
+		return nil, &ubusRPCError{fmt.Sprintf("ubus HTTP %d", res.StatusCode)}
+	}
+	var rpc struct {
+		Error  json.RawMessage `json:"error"`
+		Result json.RawMessage `json:"result"`
+	}
+	if err := json.Unmarshal(data, &rpc); err != nil {
+		return nil, &ubusRPCError{"ubus: respuesta no JSON"}
+	}
+	if len(rpc.Error) > 0 && string(rpc.Error) != "null" {
+		return nil, &ubusRPCError{"ubus RPC error: " + string(rpc.Error)}
+	}
+	// ubus devuelve [exitCode, payload]
+	var result []json.RawMessage
+	if err := json.Unmarshal(rpc.Result, &result); err != nil || len(result) != 2 {
+		return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
+	}
+	var code int
+	if err := json.Unmarshal(result[0], &code); err != nil || code != 0 {
+		return nil, &ubusRPCError{"ubus call falló: " + string(rpc.Result)}
+	}
+	return result[1], nil
+}
+
+// ubusLogin: session login con sid '0'×32 → ubus_rpc_session.
+func (c *OpenWrtClient) ubusLogin() error {
+	payload, err := c.ubusHTTPRpc("00000000000000000000000000000000", "session", "login",
+		map[string]any{"username": c.User, "password": c.Password})
+	if err != nil {
+		return err
+	}
+	var res struct {
+		Session string `json:"ubus_rpc_session"`
+	}
+	if err := json.Unmarshal(payload, &res); err != nil || res.Session == "" {
+		return &ubusRPCError{"ubus login: sin ubus_rpc_session"}
+	}
+	c.sid = res.Session
+	return nil
+}
+
+// UbusCall: ubus call con HTTP + login cacheado; un solo re-login si la
+// sesión caducó; fallback a SSH si HTTP no está disponible.
+func (c *OpenWrtClient) UbusCall(object, method string, params any) (json.RawMessage, error) {
+	if params == nil {
+		params = map[string]any{}
+	}
+	payload, err := func() (json.RawMessage, error) {
+		if c.sid == "" {
+			if err := c.ubusLogin(); err != nil {
+				return nil, err
+			}
+		}
+		payload, err := c.ubusHTTPRpc(c.sid, object, method, params)
+		if err != nil {
+			// Sesión caducada → un solo re-login
+			c.sid = ""
+			if lerr := c.ubusLogin(); lerr != nil {
+				return nil, lerr
+			}
+			return c.ubusHTTPRpc(c.sid, object, method, params)
+		}
+		return payload, nil
+	}()
+	if err == nil {
+		return payload, nil
+	}
+	// Fallback SSH: ubus call <object> <method> '<json>'
+	paramsJSON, _ := json.Marshal(params)
+	esc := strings.ReplaceAll(string(paramsJSON), `'`, `'\''`)
+	out, serr := c.pool.Run(c.Host, fmt.Sprintf("ubus call %s %s '%s'", object, method, esc), 0)
+	if serr != nil {
+		return nil, serr
+	}
+	if !json.Valid([]byte(out)) {
+		return nil, &ubusRPCError{"ubus ssh: respuesta no JSON"}
+	}
+	return json.RawMessage(out), nil
+}
+
+// ---------------------------------------------------------------------------
+// Sonda de sistema
+// ---------------------------------------------------------------------------
+
+// BoardInfo: ubus system board (metadatos estáticos; lo cachea el live).
+type BoardInfo struct {
+	Model    string `json:"model"`
+	Hostname string `json:"hostname"`
+	System   string `json:"system"`
+	Release  struct {
+		Version     string `json:"version"`
+		Description string `json:"description"`
+	} `json:"release"`
+}
+
+// GetBoard: modelo, release, kernel → metadatos estáticos del router.
+func (c *OpenWrtClient) GetBoard() (*BoardInfo, error) {
+	raw, err := c.UbusCall("system", "board", nil)
+	if err != nil {
+		return nil, err
+	}
+	var b BoardInfo
+	if err := json.Unmarshal(raw, &b); err != nil {
+		return nil, err
+	}
+	return &b, nil
+}
+
+// SysInfo: ubus system info (uptime, memoria, load).
+type SysInfo struct {
+	Uptime float64   `json:"uptime"`
+	Load   []float64 `json:"load"`
+	Memory struct {
+		Total     float64 `json:"total"`
+		Free      float64 `json:"free"`
+		Buffered  float64 `json:"buffered"`
+		Available float64 `json:"available"`
+	} `json:"memory"`
+}
+
+// GetSysInfo: uptime, memoria, load.
+func (c *OpenWrtClient) GetSysInfo() (*SysInfo, error) {
+	raw, err := c.UbusCall("system", "info", nil)
+	if err != nil {
+		return nil, err
+	}
+	var s SysInfo
+	if err := json.Unmarshal(raw, &s); err != nil {
+		return nil, err
+	}
+	return &s, nil
+}
+
+// ---------------------------------------------------------------------------
+// CPU / temperatura / netdev / ping (SSH; parseo literal del JS)
+// ---------------------------------------------------------------------------
+
+// GetCPUPercent: CPU % por delta de /proc/stat. Primera muestra: nil.
+func (c *OpenWrtClient) GetCPUPercent() (*int, error) {
+	out, err := c.pool.Run(c.Host, "grep '^cpu ' /proc/stat", 0)
+	if err != nil {
+		return nil, err
+	}
+	cur, err := parseProcStat(out)
+	if err != nil {
+		return nil, err
+	}
+	prev := c.lastStat
+	c.lastStat = &cur
+	if prev == nil {
+		return nil, nil
+	}
+	dTotal := cur.total - prev.total
+	dIdle := cur.idleAll - prev.idleAll
+	if dTotal <= 0 {
+		return nil, nil
+	}
+	v := int(float64(dTotal-dIdle)/float64(dTotal)*100 + 0.5)
+	return &v, nil
+}
+
+// parseProcStat parsea "cpu  user nice system idle iowait irq softirq ...".
+func parseProcStat(out string) (cpuSample, error) {
+	fields := strings.Fields(strings.TrimSpace(out))
+	if len(fields) < 5 || fields[0] != "cpu" {
+		return cpuSample{}, fmt.Errorf("/proc/stat inesperado: %q", out)
+	}
+	nums := make([]float64, 0, len(fields)-1)
+	for _, f := range fields[1:] {
+		n, err := strconv.ParseFloat(f, 64)
+		if err != nil {
+			n = 0
+		}
+		nums = append(nums, n)
+	}
+	get := func(i int) float64 {
+		if i < len(nums) {
+			return nums[i]
+		}
+		return 0
+	}
+	idleAll := get(3) + get(4)                          // idle + iowait
+	nonIdle := get(0) + get(1) + get(2) + get(5) + get(6) // user+nice+system+irq+softirq
+	return cpuSample{total: idleAll + nonIdle, idleAll: idleAll}, nil
+}
+
+// GetTempC: °C del primer thermal zone disponible (nil si no hay).
+func (c *OpenWrtClient) GetTempC() (*int, error) {
+	out, err := c.pool.Run(c.Host,
+		`for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && cat "$f" && break; done`, 0)
+	if err != nil {
+		return nil, err
+	}
+	milli, err := strconv.Atoi(strings.TrimSpace(out))
+	if err != nil {
+		return nil, nil
+	}
+	v := milli / 1000
+	if milli%1000 >= 500 {
+		v++
+	}
+	return &v, nil
+}
+
+// NetDevBps es el resultado del delta de /proc/net/dev.
+type NetDevBps struct {
+	RxBps *float64
+	TxBps *float64
+}
+
+var netdevSkipRe = regexp.MustCompile(`^(lo|br-|ifb|wg|tun|tap)`)
+
+// GetNetDevBps: tráfico agregado por delta (excluye lo, bridges, ifb, wg,
+// tun/tap para no duplicar contadores). Primera muestra: null/null.
+func (c *OpenWrtClient) GetNetDevBps() (*NetDevBps, error) {
+	out, err := c.pool.Run(c.Host, "cat /proc/net/dev | tail -n +3", 0)
+	if err != nil {
+		return nil, err
+	}
+	rx, tx := parseNetDev(out)
+	now := time.Now()
+	prev := c.lastNetDev
+	c.lastNetDev = &netSample{rx: rx, tx: tx, at: now}
+	res := &NetDevBps{}
+	if prev == nil {
+		return res, nil
+	}
+	dt := now.Sub(prev.at).Seconds()
+	if dt <= 0 {
+		return res, nil
+	}
+	rxBps := round0(max0((rx - prev.rx) * 8 / dt))
+	txBps := round0(max0((tx - prev.tx) * 8 / dt))
+	res.RxBps = &rxBps
+	res.TxBps = &txBps
+	return res, nil
+}
+
+// parseNetDev suma rx/tx de las interfaces físicas.
+func parseNetDev(out string) (rx, tx float64) {
+	lineRe := regexp.MustCompile(`^\s*([\w.-]+):\s*(.*)$`)
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		m := lineRe.FindStringSubmatch(line)
+		if m == nil || netdevSkipRe.MatchString(m[1]) {
+			continue
+		}
+		fields := strings.Fields(strings.TrimSpace(m[2]))
+		num := func(i int) float64 {
+			if i < len(fields) {
+				n, _ := strconv.ParseFloat(fields[i], 64)
+				return n
+			}
+			return 0
+		}
+		rx += num(0)
+		tx += num(8)
+	}
+	return rx, tx
+}
+
+var pingLossRe = regexp.MustCompile(`(\d+(?:\.\d+)?)% packet loss`)
+var pingRTTRe = regexp.MustCompile(`= [\d.]+/([\d.]+)/[\d.]+/[\d.]+ ms`)
+
+// GetWanLatency: ping a internet (solo gateway) → latencia avg + pérdida.
+func (c *OpenWrtClient) GetWanLatency(target string) (latency *float64, loss *float64, err error) {
+	if target == "" {
+		target = "1.1.1.1"
+	}
+	out, err := c.pool.Run(c.Host, fmt.Sprintf("ping -c 3 -W 2 %s 2>/dev/null | tail -2", target), 0)
+	if err != nil {
+		return nil, nil, err
+	}
+	if m := pingRTTRe.FindStringSubmatch(out); m != nil {
+		v, _ := strconv.ParseFloat(m[1], 64)
+		v = float64(int(v + 0.5))
+		latency = &v
+	}
+	if m := pingLossRe.FindStringSubmatch(out); m != nil {
+		v, _ := strconv.ParseFloat(m[1], 64)
+		loss = &v
+	}
+	return latency, loss, nil
+}
+
+// GetGatewayLatency: ping corto al gateway desde un AP (avg, redondeado).
+func (c *OpenWrtClient) GetGatewayLatency(gatewayHost string) (*float64, error) {
+	out, err := c.pool.Run(c.Host, fmt.Sprintf("ping -c 2 -W 2 %s 2>/dev/null | tail -1", gatewayHost), 0)
+	if err != nil {
+		return nil, err
+	}
+	if m := pingRTTRe.FindStringSubmatch(out); m != nil {
+		v, _ := strconv.ParseFloat(m[1], 64)
+		v = float64(int(v + 0.5))
+		return &v, nil
+	}
+	return nil, nil
+}
+
+// ---------------------------------------------------------------------------
+// Clientes (DHCP + wireless)
+// ---------------------------------------------------------------------------
+
+// DhcpLease es {mac, ip, hostname} (mac en mayúsculas).
+type DhcpLease struct {
+	MAC      string
+	IP       string
+	Hostname string
+}
+
+// GetDhcpLeases: ubus dhcp ipv4leases; fallback /tmp/dhcp.leases.
+func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
+	type leaseJSON struct {
+		MAC      string `json:"mac"`
+		IPAddr   string `json:"ip-address"`
+		IP       string `json:"ip"`
+		Hostname string `json:"hostname"`
+	}
+	raw, err := c.UbusCall("dhcp", "ipv4leases", nil)
+	if err == nil {
+		var data struct {
+			Lease  []leaseJSON `json:"lease"`
+			Leases []leaseJSON `json:"leases"`
+		}
+		if json.Unmarshal(raw, &data) == nil {
+			leases := data.Lease
+			if leases == nil {
+				leases = data.Leases
+			}
+			out := make([]DhcpLease, 0, len(leases))
+			for _, l := range leases {
+				ip := l.IPAddr
+				if ip == "" {
+					ip = l.IP
+				}
+				out = append(out, DhcpLease{MAC: strings.ToUpper(l.MAC), IP: ip, Hostname: l.Hostname})
+			}
+			return out
+		}
+	}
+	out, serr := c.pool.Run(c.Host, "cat /tmp/dhcp.leases 2>/dev/null || true", 0)
+	if serr != nil {
+		return []DhcpLease{}
+	}
+	return parseDhcpLeasesFile(out)
+}
+
+// parseDhcpLeasesFile parsea /tmp/dhcp.leases:
+// <expiry> <mac> <ip> <hostname> <clientid>
+func parseDhcpLeasesFile(out string) []DhcpLease {
+	leases := []DhcpLease{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Fields(line)
+		if len(p) < 3 {
+			continue
+		}
+		hostname := ""
+		if len(p) > 3 && p[3] != "*" {
+			hostname = p[3]
+		}
+		leases = append(leases, DhcpLease{MAC: strings.ToUpper(p[1]), IP: p[2], Hostname: hostname})
+	}
+	return leases
+}
+
+// WirelessClient es {signalDbm, band} por MAC.
+type WirelessClient struct {
+	SignalDbm int
+	Band      string
+}
+
+// GetWirelessClients: iwinfo assoclist por radio → mapa MAC → cliente.
+func (c *OpenWrtClient) GetWirelessClients() map[string]WirelessClient {
+	out, err := c.pool.Run(c.Host,
+		`for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do `+
+			`freq=$(iwinfo "$i" info 2>/dev/null | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); `+
+			`iwinfo "$i" assoclist 2>/dev/null | sed -n 's/^\([0-9A-Fa-f:]\{17\}\) *\(-[0-9]*\).*/\1 \2/p' | while read mac sig; do `+
+			`echo "$mac $sig $freq"; done; done`, iwinfoTimeout)
+	if err != nil {
+		return map[string]WirelessClient{}
+	}
+	return parseWirelessClients(out)
+}
+
+// parseWirelessClients parsea líneas "<mac> <sig> <freq>" del bucle iwinfo.
+func parseWirelessClients(out string) map[string]WirelessClient {
+	m := map[string]WirelessClient{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Fields(line)
+		if len(p) < 2 {
+			continue
+		}
+		freq := 0.0
+		if len(p) > 2 {
+			freq, _ = strconv.ParseFloat(p[2], 64)
+		}
+		sig, _ := strconv.Atoi(p[1])
+		band := "2.4 GHz"
+		if freq >= 5 {
+			band = "5 GHz"
+		}
+		m[strings.ToUpper(p[0])] = WirelessClient{SignalDbm: sig, Band: band}
+	}
+	return m
+}
+
+// ---------------------------------------------------------------------------
+// Puertos
+// ---------------------------------------------------------------------------
+
+// PortState es {name, up, speed} de una interfaz (/sys operstate+speed).
+type PortState struct {
+	Name  string
+	Up    bool
+	Speed string // "1 Gbps" | "100 Mbps" | "—"
+}
+
+// GetPortStates: estado de interfaces desde /sys (SSH).
+func (c *OpenWrtClient) GetPortStates() []PortState {
+	out, err := c.pool.Run(c.Host,
+		`for d in /sys/class/net/*; do i=$(basename "$d"); `+
+			`echo "$i $(cat $d/operstate 2>/dev/null) $(cat $d/speed 2>/dev/null || echo -1)"; done`, 0)
+	if err != nil {
+		return []PortState{}
+	}
+	return parsePortStates(out)
+}
+
+// parsePortStates parsea líneas "<name> <operstate> <speed>".
+func parsePortStates(out string) []PortState {
+	ports := []PortState{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Fields(line)
+		if len(p) < 3 {
+			continue
+		}
+		mbps, _ := strconv.Atoi(p[2])
+		speed := "—"
+		if mbps > 0 {
+			if mbps >= 1000 {
+				speed = strconv.Itoa(mbps/1000) + " Gbps"
+			} else {
+				speed = strconv.Itoa(mbps) + " Mbps"
+			}
+		}
+		ports = append(ports, PortState{Name: p[0], Up: p[1] == "up", Speed: speed})
+	}
+	return ports
+}
+
+// PortLayout es una boca del layout canónico (/etc/board.json).
+type PortLayout struct {
+	ID    string
+	Name  string
+	Label string
+	Role  string // "lan" | "wan"
+}
+
+// GetPortLayout: layout canónico desde /etc/board.json (estático; lo cachea
+// el live). WAN normalizado a id 'wan'.
+func (c *OpenWrtClient) GetPortLayout() ([]PortLayout, error) {
+	out, err := c.pool.Run(c.Host, "cat /etc/board.json 2>/dev/null", 0)
+	if err != nil {
+		return nil, err
+	}
+	return parsePortLayout(out)
+}
+
+// parsePortLayout parsea board.json → [{id, name, label, role}].
+func parsePortLayout(out string) ([]PortLayout, error) {
+	var board struct {
+		Network struct {
+			Lan struct {
+				Ports []string `json:"ports"`
+			} `json:"lan"`
+			Wan struct {
+				Device string `json:"device"`
+			} `json:"wan"`
+		} `json:"network"`
+	}
+	if err := json.Unmarshal([]byte(out), &board); err != nil {
+		return nil, err
+	}
+	ports := []PortLayout{}
+	for _, name := range board.Network.Lan.Ports {
+		ports = append(ports, PortLayout{ID: name, Name: name, Label: strings.Replace(name, "lan", "LAN ", 1), Role: "lan"})
+	}
+	if wanDev := board.Network.Wan.Device; wanDev != "" {
+		ports = append([]PortLayout{{ID: "wan", Name: wanDev, Label: "WAN", Role: "wan"}}, ports...)
+	}
+	return ports, nil
+}
+
+// GetEthPorts: layout + estado /sys; AP en bridge re-etiqueta wan→LAN N+1;
+// fallback heurístico sin config. Devuelve []EthPort listo para el detalle.
+func (c *OpenWrtClient) GetEthPorts(layout []PortLayout) []EthPort {
+	states := c.GetPortStates()
+	byName := map[string]PortState{}
+	for _, p := range states {
+		byName[p.Name] = p
+	}
+	if len(layout) > 0 {
+		// Miembros del bridge: si "wan" está en br-lan, este router es un AP
+		brif, _ := c.pool.Run(c.Host, "ls /sys/class/net/br-lan/brif/ 2>/dev/null", 0)
+		members := map[string]bool{}
+		for _, l := range strings.Split(strings.TrimSpace(brif), "\n") {
+			if l != "" {
+				members[l] = true
+			}
+		}
+		lanCount := 0
+		for _, p := range layout {
+			if p.Role == "lan" {
+				lanCount++
+			}
+		}
+		ports := make([]EthPort, 0, len(layout))
+		for _, p := range layout {
+			st, ok := byName[p.Name]
+			up := ok && st.Up
+			label := p.Label
+			if p.Role == "wan" && members[p.Name] {
+				label = "LAN " + strconv.Itoa(lanCount+1)
+			}
+			ep := EthPort{ID: p.ID, Label: label, Up: up}
+			if up {
+				ep.Speed = st.Speed
+			}
+			ports = append(ports, ep)
+		}
+		return ports
+	}
+	// Fallback sin config
+	lanRe := regexp.MustCompile(`^lan\d+$`)
+	lans := []PortState{}
+	for _, p := range states {
+		if lanRe.MatchString(p.Name) {
+			lans = append(lans, p)
+		}
+	}
+	sort.Slice(lans, func(i, j int) bool { return naturalLess(lans[i].Name, lans[j].Name) })
+	ports := make([]EthPort, 0, len(lans)+1)
+	for _, p := range lans {
+		ep := EthPort{ID: p.Name, Label: strings.Replace(p.Name, "lan", "LAN ", 1), Up: p.Up}
+		if p.Up {
+			ep.Speed = p.Speed
+		}
+		ports = append(ports, ep)
+	}
+	wanName := ""
+	if _, ok := byName["wan"]; ok {
+		wanName = "wan"
+	} else if _, ok := byName["pppoe-wan"]; ok {
+		wanName = "eth1"
+	} else if _, ok := byName["eth1"]; ok {
+		wanName = "eth1"
+	}
+	if wanName != "" {
+		st := byName[wanName]
+		ep := EthPort{ID: "wan", Label: "WAN", Up: st.Up}
+		if st.Up {
+			ep.Speed = st.Speed
+		}
+		ports = append([]EthPort{ep}, ports...)
+	}
+	return ports
+}
+
+// naturalLess ordena lan2 < lan10 (localeCompare numeric del JS).
+func naturalLess(a, b string) bool {
+	re := regexp.MustCompile(`^(.*?)(\d+)$`)
+	ma, mb := re.FindStringSubmatch(a), re.FindStringSubmatch(b)
+	if ma != nil && mb != nil && ma[1] == mb[1] {
+		na, _ := strconv.Atoi(ma[2])
+		nb, _ := strconv.Atoi(mb[2])
+		return na < nb
+	}
+	return a < b
+}
+
+// GetBridgeFdb: MAC aprendida → puerto (brctl showmacs + port_no).
+func (c *OpenWrtClient) GetBridgeFdb() map[string]string {
+	out, err := c.pool.Run(c.Host,
+		`echo "==PORTS=="; for d in /sys/class/net/br-lan/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; `+
+			`echo "==MACS=="; brctl showmacs br-lan 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}'`, 0)
+	if err != nil {
+		return map[string]string{}
+	}
+	return parseBridgeFdb(out)
+}
+
+var fdbPortRe = regexp.MustCompile(`^(lan\d+|wan)$`)
+
+// parseBridgeFdb parsea la salida ==PORTS==/==MACS== del JS.
+func parseBridgeFdb(out string) map[string]string {
+	m := map[string]string{}
+	portNames := map[string]string{}
+	section := byte(0)
+	for _, line := range strings.Split(out, "\n") {
+		t := strings.TrimSpace(line)
+		if strings.HasPrefix(t, "==PORTS==") {
+			section = 'p'
+			continue
+		}
+		if strings.HasPrefix(t, "==MACS==") {
+			section = 'm'
+			continue
+		}
+		p := strings.Fields(t)
+		if len(p) < 2 {
+			continue
+		}
+		switch section {
+		case 'p':
+			no, name := p[0], p[1]
+			if strings.HasPrefix(no, "0x") {
+				if n, err := strconv.ParseInt(no[2:], 16, 64); err == nil {
+					no = strconv.FormatInt(n, 10)
+				}
+			}
+			portNames[no] = name
+		case 'm':
+			no, mac := p[0], p[1]
+			if port, ok := portNames[no]; ok && mac != "" && fdbPortRe.MatchString(port) {
+				m[strings.ToUpper(mac)] = port
+			}
+		}
+	}
+	return m
+}
+
+// GetBridgeMac: MAC del bridge br-lan (para reconocer uplinks).
+func (c *OpenWrtClient) GetBridgeMac() string {
+	out, err := c.pool.Run(c.Host, "cat /sys/class/net/br-lan/address 2>/dev/null", 0)
+	if err != nil {
+		return ""
+	}
+	return strings.ToUpper(strings.TrimSpace(out))
+}
+
+// ---------------------------------------------------------------------------
+// Radios WiFi
+// ---------------------------------------------------------------------------
+
+// GetRadios: radios activas agregadas por banda (iwinfo info + assoclist).
+func (c *OpenWrtClient) GetRadios() []Radio {
+	out, err := c.pool.Run(c.Host,
+		`for i in $(iwinfo 2>/dev/null | awk '/^[a-z]/ {print $1}'); do `+
+			`info=$(iwinfo "$i" info 2>/dev/null) || continue; `+
+			`echo "$info" | grep -q ESSID || continue; `+
+			`freq=$(echo "$info" | sed -n 's/.*Channel: [0-9]* (\([0-9.]*\) GHz).*/\1/p' | head -1); `+
+			`ch=$(echo "$info" | sed -n 's/.*Channel: \([0-9][0-9]*\).*/\1/p' | head -1); `+
+			`ht=$(echo "$info" | sed -n 's/.*HT [Mm]ode: \([A-Za-z0-9]*\).*/\1/p' | head -1); `+
+			`tx=$(echo "$info" | sed -n 's/.*Tx-Power: \([0-9]*\).*/\1/p' | head -1); `+
+			`n=$(iwinfo "$i" assoclist 2>/dev/null | grep -c '^[0-9A-Fa-f:]'); `+
+			`echo "$freq|$ch|$ht|$tx|$n"; done`, iwinfoTimeout)
+	if err != nil {
+		return []Radio{}
+	}
+	return parseRadios(out)
+}
+
+var nonDigitRe = regexp.MustCompile(`\D`)
+
+// parseRadios: líneas "freq|ch|ht|tx|n" agregadas por banda (suma clientes).
+func parseRadios(out string) []Radio {
+	byBand := map[string]*Radio{}
+	order := []string{}
+	for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
+		if line == "" {
+			continue
+		}
+		p := strings.Split(line, "|")
+		if len(p) < 5 {
+			continue
+		}
+		freq, _ := strconv.ParseFloat(p[0], 64)
+		if freq == 0 {
+			continue
+		}
+		band := "2.4 GHz"
+		if freq >= 5 {
+			band = "5 GHz"
+		}
+		width, _ := strconv.Atoi(nonDigitRe.ReplaceAllString(p[2], ""))
+		if width == 0 {
+			width = 20
+		}
+		ch, _ := strconv.Atoi(p[1])
+		tx, _ := strconv.Atoi(p[3])
+		n, _ := strconv.Atoi(p[4])
+		if cur, ok := byBand[band]; ok {
+			cur.Clients += n
+		} else {
+			byBand[band] = &Radio{Name: band, Channel: ch, WidthMhz: width, PowerDbm: float64(tx), Clients: n}
+			order = append(order, band)
+		}
+	}
+	radios := []Radio{}
+	for _, b := range order {
+		radios = append(radios, *byBand[b])
+	}
+	return radios
+}
+
+func round0(v float64) float64 { return float64(int64(v + 0.5)) }
+func max0(v float64) float64 {
+	if v < 0 {
+		return 0
+	}
+	return v
+}

+ 241 - 0
server-go/internal/adapters/sshpool.go

@@ -0,0 +1,241 @@
+// sshpool.go — Pool de conexiones SSH persistentes (equivalente Go del
+// ControlMaster/ControlPersist del JS, SPEC §7.2): UNA conexión por router,
+// reutilizada entre ticks del poller, con reconexión automática y backoff
+// exponencial (30 s base, máx 5 min) para no martillear un router caído.
+//
+// known_hosts con semántica accept-new junto a la clave (como el JS):
+// host desconocido → se acepta y se anota; host conocido con clave distinta
+// → se rechaza (posible MITM).
+package adapters
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"net"
+	"os"
+	"path/filepath"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+	"golang.org/x/crypto/ssh"
+	"golang.org/x/crypto/ssh/knownhosts"
+)
+
+const (
+	sshDialTimeout    = 4 * time.Second // ConnectTimeout=4 del JS
+	sshDefaultTimeout = 5 * time.Second // SSH_TIMEOUT_MS del JS
+	sshBackoffBase    = 30 * time.Second
+	sshBackoffMax     = 5 * time.Minute
+)
+
+// SSHPool gestiona conexiones persistentes a los routers.
+type SSHPool struct {
+	keyPath string
+	signer  ssh.Signer
+	khPath  string
+
+	mu     sync.Mutex
+	conns  map[string]*sshConn
+	closed bool
+}
+
+type sshConn struct {
+	client   *ssh.Client
+	failures int
+	notUntil time.Time
+}
+
+// NewSSHPool crea el pool cargando la clave privada (ed25519 sin passphrase).
+func NewSSHPool(keyPath string) (*SSHPool, error) {
+	pem, err := os.ReadFile(keyPath)
+	if err != nil {
+		return nil, fmt.Errorf("leer clave SSH: %w", err)
+	}
+	signer, err := ssh.ParsePrivateKey(pem)
+	if err != nil {
+		return nil, fmt.Errorf("parsear clave SSH: %w", err)
+	}
+	return &SSHPool{
+		keyPath: keyPath,
+		signer:  signer,
+		khPath:  sshkey.KnownHostsPath(keyPath),
+		conns:   map[string]*sshConn{},
+	}, nil
+}
+
+// hostKeyCallback implementa accept-new sobre el known_hosts propio.
+func (p *SSHPool) hostKeyCallback() (ssh.HostKeyCallback, error) {
+	if _, err := os.Stat(p.khPath); os.IsNotExist(err) {
+		if err := os.MkdirAll(filepath.Dir(p.khPath), 0o700); err == nil {
+			_ = os.WriteFile(p.khPath, nil, 0o600)
+		}
+	}
+	checker, err := knownhosts.New(p.khPath)
+	if err != nil {
+		return nil, err
+	}
+	return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
+		err := checker(hostname, remote, key)
+		if err == nil {
+			return nil
+		}
+		var keyErr *knownhosts.KeyError
+		if errors.As(err, &keyErr) && len(keyErr.Want) > 0 {
+			return err // clave CAMBIADA → rechazar
+		}
+		// Host desconocido → accept-new
+		line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
+		f, ferr := os.OpenFile(p.khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
+		if ferr != nil {
+			return ferr
+		}
+		defer f.Close()
+		_, ferr = f.WriteString(line + "\n")
+		return ferr
+	}, nil
+}
+
+// dial abre (o reabre) la conexión a un host respetando el backoff.
+func (p *SSHPool) dial(host string) (*ssh.Client, error) {
+	p.mu.Lock()
+	entry := p.conns[host]
+	if entry == nil {
+		entry = &sshConn{}
+		p.conns[host] = entry
+	}
+	if entry.client != nil {
+		c := entry.client
+		p.mu.Unlock()
+		return c, nil
+	}
+	if time.Now().Before(entry.notUntil) {
+		p.mu.Unlock()
+		return nil, fmt.Errorf("ssh %s: en backoff tras %d fallos", host, entry.failures)
+	}
+	p.mu.Unlock()
+
+	cb, err := p.hostKeyCallback()
+	if err != nil {
+		return nil, err
+	}
+	cfg := &ssh.ClientConfig{
+		User:            "root",
+		Auth:            []ssh.AuthMethod{ssh.PublicKeys(p.signer)},
+		HostKeyCallback: cb,
+		Timeout:         sshDialTimeout,
+	}
+	client, err := ssh.Dial("tcp", net.JoinHostPort(host, "22"), cfg)
+
+	p.mu.Lock()
+	defer p.mu.Unlock()
+	if err != nil {
+		entry.failures++
+		backoff := sshBackoffBase << min(entry.failures-1, 4)
+		if backoff > sshBackoffMax {
+			backoff = sshBackoffMax
+		}
+		entry.notUntil = time.Now().Add(backoff)
+		return nil, fmt.Errorf("ssh %s: %w", host, err)
+	}
+	entry.client = client
+	entry.failures = 0
+	entry.notUntil = time.Time{}
+	return client, nil
+}
+
+// drop invalida la conexión de un host (la próxima llamada rediala).
+func (p *SSHPool) drop(host string) {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+	if e := p.conns[host]; e != nil && e.client != nil {
+		_ = e.client.Close()
+		e.client = nil
+	}
+}
+
+// Run ejecuta cmd en host con timeout (por defecto 5 s, como el JS).
+// Una sesión fallida por canal roto invalida la conexión (reconexión).
+func (p *SSHPool) Run(host, cmd string, timeout time.Duration) (string, error) {
+	if timeout <= 0 {
+		timeout = sshDefaultTimeout
+	}
+	client, err := p.dial(host)
+	if err != nil {
+		return "", err
+	}
+	session, err := client.NewSession()
+	if err != nil {
+		p.drop(host)
+		return "", fmt.Errorf("ssh %s: session: %w", host, err)
+	}
+	defer session.Close()
+
+	type result struct {
+		out []byte
+		err error
+	}
+	ch := make(chan result, 1)
+	go func() {
+		out, err := session.Output(cmd)
+		ch <- result{out, err}
+	}()
+	select {
+	case res := <-ch:
+		if res.err != nil {
+			var ee *ssh.ExitError
+			if !errors.As(res.err, &ee) {
+				p.drop(host) // canal roto, no exit status
+			}
+			return "", fmt.Errorf("ssh %s: %w", host, res.err)
+		}
+		return string(res.out), nil
+	case <-time.After(timeout):
+		_ = session.Close()
+		p.drop(host)
+		return "", fmt.Errorf("ssh %s: timeout (%s)", host, timeout)
+	}
+}
+
+// RunCtx es Run con cancelación por contexto.
+func (p *SSHPool) RunCtx(ctx context.Context, host, cmd string, timeout time.Duration) (string, error) {
+	type res struct {
+		out string
+		err error
+	}
+	ch := make(chan res, 1)
+	go func() {
+		out, err := p.Run(host, cmd, timeout)
+		ch <- res{out, err}
+	}()
+	select {
+	case r := <-ch:
+		return r.out, r.err
+	case <-ctx.Done():
+		return "", ctx.Err()
+	}
+}
+
+// Close cierra todas las conexiones del pool.
+func (p *SSHPool) Close() {
+	p.mu.Lock()
+	defer p.mu.Unlock()
+	if p.closed {
+		return
+	}
+	p.closed = true
+	for _, e := range p.conns {
+		if e.client != nil {
+			_ = e.client.Close()
+			e.client = nil
+		}
+	}
+}
+
+func min(a, b int) int {
+	if a < b {
+		return a
+	}
+	return b
+}

+ 401 - 0
server-go/internal/adapters/types.go

@@ -0,0 +1,401 @@
+// Package adapters — contrato entre el núcleo (handlers, poller, SSE) y los
+// adapters de datos (demo / live OpenWrt).
+//
+// El tipo central es Snapshotter (SPEC §7): los handlers NUNCA hablan con
+// routers directamente, solo con esta interfaz. Las formas JSON de este
+// fichero son CONTRATO EXACTO con el frontend (camelCase, null vs ausente):
+//   - Campos con omitempty = ausentes cuando no aplican (paridad `undefined`).
+//   - Slices nil serializan como null; slices vacíos no-nil como [].
+//     En RouterDetail.Radios la demo devuelve null si no hay radios y el live
+//     devuelve [] (quirk del SPEC §7.8) — se expresa con nil vs no-nil.
+//   - Epochs: ms en DB, SEGUNDOS en Overview.Ts.
+package adapters
+
+import "context"
+
+// ---------------------------------------------------------------------------
+// Bloques del Overview (SPEC §7.8)
+// ---------------------------------------------------------------------------
+
+// HealthDelta es una penalización del health score.
+type HealthDelta struct {
+	Label string `json:"label"`
+	Delta int    `json:"delta"`
+}
+
+// HealthScore global (demo: canon; live: computeHealth).
+type HealthScore struct {
+	Score     int           `json:"score"`
+	Label     string        `json:"label"` // "Excelente"|"Bueno"|"Atención"
+	Caption   string        `json:"caption"`
+	Note      string        `json:"note"`
+	Breakdown []HealthDelta `json:"breakdown"`
+}
+
+// WAN stats (vía gateway).
+type WAN struct {
+	Plan          string  `json:"plan"`
+	DownMbps      float64 `json:"downMbps"`
+	UpMbps        float64 `json:"upMbps"`
+	LatencyMs     float64 `json:"latencyMs"`
+	LossPct       float64 `json:"lossPct"`
+	PublicIP      string  `json:"publicIp"`
+	Isp           string  `json:"isp"`
+	PeakTodayMbps float64 `json:"peakTodayMbps"`
+	PeakTodayTime string  `json:"peakTodayTime"`
+	AvgDownMbps   float64 `json:"avgDownMbps"`
+	Total24h      string  `json:"total24h"`
+}
+
+// TrafficPoint es un punto {t, down, up} de las series de tráfico WAN.
+type TrafficPoint struct {
+	T    string  `json:"t"`
+	Down float64 `json:"down"`
+	Up   float64 `json:"up"`
+}
+
+// TrafficByRange son las 4 series del gateway (claves fijas del contrato).
+type TrafficByRange struct {
+	H1  []TrafficPoint `json:"1h"`
+	H24 []TrafficPoint `json:"24h"`
+	D7  []TrafficPoint `json:"7d"`
+	D30 []TrafficPoint `json:"30d"`
+}
+
+// TopBlocked es un dominio bloqueado por AdGuard.
+type TopBlocked struct {
+	Domain string `json:"domain"`
+	Count  int64  `json:"count"`
+}
+
+// AdGuardStats (SPEC §7.3/§7.4). El fallback inactivo es el valor cero con
+// Status "inactive" (host "" y port 0 si no configurado).
+type AdGuardStats struct {
+	Host            string       `json:"host"`
+	Port            int          `json:"port"`
+	Status          string       `json:"status"` // "active"|"inactive"
+	Queries24h      int64        `json:"queries24h"`
+	Blocked24h      int64        `json:"blocked24h"`
+	BlockedPct      float64      `json:"blockedPct"`
+	TrackersBlocked int64        `json:"trackersBlocked"`
+	DNSLatencyMs    int          `json:"dnsLatencyMs"`
+	ClientsUsing    int          `json:"clientsUsing"`
+	ClientsTotal    int          `json:"clientsTotal"`
+	TopBlocked      []TopBlocked `json:"topBlocked"`
+	FilterLists     int          `json:"filterLists"`
+	Rules           int          `json:"rules"`
+}
+
+// WGPeer es un peer WireGuard (bytes formateados ES: "1,2 GB").
+type WGPeer struct {
+	ID            string `json:"id"`
+	Name          string `json:"name"`
+	Type          string `json:"type"`
+	TunnelIP      string `json:"tunnelIp"`
+	Active        bool   `json:"active"`
+	LastHandshake string `json:"lastHandshake"`
+	Rx            string `json:"rx"`
+	Tx            string `json:"tx"`
+}
+
+// WireGuardStats (quirk: Status siempre "active" si `wg show` respondió).
+type WireGuardStats struct {
+	Interface string   `json:"interface"`
+	Subnet    string   `json:"subnet"`
+	Status    string   `json:"status"` // "active"|"inactive"
+	Peers     []WGPeer `json:"peers"`
+}
+
+// Router es la tarjeta de router (demo canon + live buildRouter).
+// CPU/RAM/Temp son *int porque el live puede emitir null en el primer tick
+// (primera muestra de /proc/stat; SPEC §7.2 getCpuPercent).
+type Router struct {
+	ID         string    `json:"id"`
+	Name       string    `json:"name"`
+	Model      string    `json:"model"`
+	ModelShort string    `json:"modelShort"`
+	Role       string    `json:"role"`
+	RoleBadge  string    `json:"roleBadge"`
+	IP         string    `json:"ip"`
+	MAC        string    `json:"mac,omitempty"`      // ausente si no se conoce (undefined)
+	Firmware   string    `json:"firmware,omitempty"` // ausente si no se conoce
+	Status     string    `json:"status"`             // "online"|"warn"|"offline"
+	Health     int       `json:"health"`
+	CPU        *int      `json:"cpu"`
+	RAM        *int      `json:"ram"`
+	Temp       *int      `json:"temp"`
+	Uptime     string    `json:"uptime"` // "<d>d <h>h" | "—"
+	Clients    int       `json:"clients"`
+	HotMetric  string    `json:"hotMetric,omitempty"` // "temp" solo si temp>65
+	Sparkline  []float64 `json:"sparkline"`
+}
+
+// DeviceTotals del overview (quirk: NewToday=0 en live).
+type DeviceTotals struct {
+	Total        int `json:"total"`
+	Online       int `json:"online"`
+	KnownOffline int `json:"knownOffline"`
+	NewToday     int `json:"newToday"`
+}
+
+// Device es un cliente de red. Las 12 primeras claves son el contrato base
+// (SPEC §2.9); el resto solo existe en demo (ausentes en live).
+// SignalDbm es null cuando no hay medida (nunca ausente).
+type Device struct {
+	ID           string    `json:"id"`
+	Name         string    `json:"name"`
+	Type         string    `json:"type"`
+	Manufacturer string    `json:"manufacturer"`
+	IP           string    `json:"ip"`
+	MAC          string    `json:"mac"`
+	RouterID     string    `json:"routerId"`
+	Band         string    `json:"band"` // "5 GHz"|"2.4 GHz"|"cable"|"—"
+	SignalDbm    *int      `json:"signalDbm"`
+	TrafficMbps  float64   `json:"trafficMbps"`
+	Online       bool      `json:"online"`
+	Sparkline    []float64 `json:"sparkline"`
+	// --- extras demo (omitempty = ausentes en live) ---
+	Hostname     string `json:"hostname,omitempty"`
+	DHCPLease    string `json:"dhcpLease,omitempty"`
+	FirstSeen    string `json:"firstSeen,omitempty"`
+	Traffic24hRx string `json:"traffic24hRx,omitempty"`
+	Traffic24hTx string `json:"traffic24hTx,omitempty"`
+	Adguard      *bool  `json:"adguard,omitempty"` // puntero: demo emite true/false explícito; live lo omite (paridad Node)
+	Group        string `json:"group,omitempty"`
+	IsNew        bool   `json:"isNew,omitempty"`
+	NewThisWeek  bool   `json:"newThisWeek,omitempty"`
+	IconOverride string `json:"iconOverride,omitempty"`
+}
+
+// AlertEvent (máx 100 en memoria, más recientes primero).
+type AlertEvent struct {
+	ID          string `json:"id"`
+	Severity    string `json:"severity"` // "warn"|"critical"|"info"|"ok"
+	Title       string `json:"title"`
+	Description string `json:"description"`
+	Time        string `json:"time"` // relativo ES ("hace 12 min") — el frontend lo muestra tal cual
+	Read        bool   `json:"read"`
+	RouterID    string `json:"routerId"`
+}
+
+// Overview es el bundle completo (SPEC §7.8). Ts en SEGUNDOS.
+type Overview struct {
+	Health       HealthScore    `json:"health"`
+	WAN          WAN            `json:"wan"`
+	Traffic      TrafficByRange `json:"traffic"`
+	Adguard      AdGuardStats   `json:"adguard"`   // fallback inactivo si no configurado (nunca null en live)
+	Wireguard    WireGuardStats `json:"wireguard"` // fallback inactivo si error SSH
+	Routers      []Router       `json:"routers"`
+	DeviceTotals DeviceTotals   `json:"deviceTotals"`
+	TopDevices   []Device       `json:"topDevices"` // 5 por trafficMbps desc
+	Alerts       []AlertEvent   `json:"alerts"`
+	UnreadAlerts int            `json:"unreadAlerts"`
+	Ts           int64          `json:"ts"` // floor(now/1000) — SEGUNDOS
+}
+
+// ---------------------------------------------------------------------------
+// RouterDetail (GET /api/routers/:id; SPEC §7.8 y demo §7.1)
+// ---------------------------------------------------------------------------
+
+// PerfPoint es un punto de las series de rendimiento {t, cpu, ram, temp}.
+type PerfPoint struct {
+	T    string  `json:"t"`
+	CPU  float64 `json:"cpu"`
+	RAM  float64 `json:"ram"`
+	Temp float64 `json:"temp"`
+}
+
+// PerfSeries son las 3 series del detalle (claves fijas).
+type PerfSeries struct {
+	H1  []PerfPoint `json:"1h"`
+	H24 []PerfPoint `json:"24h"`
+	D7  []PerfPoint `json:"7d"`
+}
+
+// EthPort es una boca ethernet ({id, label, up, speed?} + enriquecimiento de
+// vecino en el detalle: connectedTo/deviceMac/detail, SPEC §7.8).
+type EthPort struct {
+	ID          string `json:"id"`
+	Label       string `json:"label"`
+	Up          bool   `json:"up"`
+	Speed       string `json:"speed,omitempty"` // solo si up ("1 Gbps"|"100 Mbps")
+	ConnectedTo string `json:"connectedTo,omitempty"`
+	DeviceMac   string `json:"deviceMac,omitempty"`
+	Detail      string `json:"detail,omitempty"`
+}
+
+// Radio agrega una banda wifi ({name, channel, widthMhz, powerDbm, clients}).
+type Radio struct {
+	Name      string  `json:"name"` // "5 GHz"|"2.4 GHz"
+	Channel   int     `json:"channel"`
+	WidthMhz  int     `json:"widthMhz"`
+	PowerDbm  float64 `json:"powerDbm"`
+	Clients   int     `json:"clients"`
+	Congested bool    `json:"congested,omitempty"` // solo demo
+}
+
+// Backhaul del AP (null en gateway): {kind:'cable', headline, latencyMs} o el
+// objeto wireless de la demo (routerExtras.backhaul). Por eso es `any`.
+// El detalle de gateway emite null (nil).
+
+// RouterDetail es la respuesta de GET /api/routers/:id.
+// Radios: nil → null (demo sin radios), no-nil vacío → [] (live). Quirk SPEC.
+// Backhaul y Extras son `any`: la demo tiene objetos ricos canónicos
+// (routerExtras, dataset.js) y el live construye los suyos (SPEC §7.8).
+type RouterDetail struct {
+	Router   Router     `json:"router"`
+	Ports    []EthPort  `json:"ports"`
+	Radios   []Radio    `json:"radios"` // nil → null (demo), [] (live)
+	Backhaul any        `json:"backhaul"`
+	Series   PerfSeries `json:"series"`
+	Clients  []Device   `json:"clients"`
+	Extras   any        `json:"extras"`
+	// --- solo gateway (demo: solo flint2; live: solo el gateway) ---
+	Adguard          *AdGuardStats  `json:"adguard,omitempty"`
+	Wireguard        *WireGuardStats `json:"wireguard,omitempty"`
+	AdguardSeries24h []AdGuardHour  `json:"adguardSeries24h,omitempty"`
+	WANLatency       *WANLatency    `json:"wanLatency,omitempty"`
+	WGPeerExtras     any            `json:"wgPeerExtras,omitempty"`
+	WGTotals30d      *WGTotals      `json:"wgTotals30d,omitempty"`
+}
+
+// AdGuardHour es un punto de la serie horaria AdGuard del detalle del gateway
+// (demo; shape literal de dataset.js buildAdGuardSeries: {t,permitidas,bloqueadas}).
+type AdGuardHour struct {
+	T          string `json:"t"`
+	Permitidas int64  `json:"permitidas"`
+	Bloqueadas int64  `json:"bloqueadas"`
+}
+
+// WANLatency (solo detalle del gateway, demo).
+type WANLatency struct {
+	Last24h []float64       `json:"last24h"`
+	Stats   WANLatencyStats `json:"stats"`
+}
+
+// WANLatencyStats {avgMs, jitterMs, lossPct}.
+type WANLatencyStats struct {
+	AvgMs    float64 `json:"avgMs"`
+	JitterMs float64 `json:"jitterMs"`
+	LossPct  float64 `json:"lossPct"`
+}
+
+// WGTotals {rx, tx} formateados ES.
+type WGTotals struct {
+	Rx string `json:"rx"`
+	Tx string `json:"tx"`
+}
+
+// ---------------------------------------------------------------------------
+// DAWN (GET /api/dawn; SPEC §7.6) y AdGuard clients (§2.13)
+// ---------------------------------------------------------------------------
+
+// DawnAP es un punto de acceso visto por DAWN.
+type DawnAP struct {
+	SSID           string  `json:"ssid"`
+	BSSID          string  `json:"bssid"`
+	Hostname       string  `json:"hostname"`
+	Band           string  `json:"band"` // freq >= 5000 ? "5 GHz" : "2.4 GHz"
+	Channel        int     `json:"channel"`
+	UtilizationPct float64 `json:"utilizationPct"`
+	Clients        int     `json:"clients"`
+	Local          bool    `json:"local"`
+	Iface          string  `json:"iface"`
+}
+
+// DawnMesh marca por router si tiene DAWN y cuántos APs ve.
+type DawnMesh struct {
+	RouterID string `json:"routerId"`
+	Name     string `json:"name"`
+	Dawn     bool   `json:"dawn"`
+	ApsSeen  int    `json:"apsSeen"`
+}
+
+// Dawn es la respuesta de /api/dawn (503 si ningún router tiene DAWN).
+type Dawn struct {
+	APs  []DawnAP   `json:"aps"`
+	Mesh []DawnMesh `json:"mesh"`
+}
+
+// AdguardClient es un cliente configurado en AdGuard GL.iNet (§2.13).
+type AdguardClient struct {
+	Name              string `json:"name"`
+	IP                string `json:"ip"`
+	UseGlobalSettings bool   `json:"useGlobalSettings"`
+	BlockedServices   int    `json:"blockedServices"`
+}
+
+// ---------------------------------------------------------------------------
+// Filas de persistencia (poller → DB; NO es JSON de API)
+// ---------------------------------------------------------------------------
+
+// MetricsRow es una fila de la tabla metrics (ts lo pone el poller, epoch ms).
+// Los *float64 admiten null (primera muestra de cpu/bps, SPEC §7.2).
+type MetricsRow struct {
+	RouterID  string
+	CPU       *float64
+	RAM       *float64
+	Temp      *float64
+	LatencyMs *float64
+	RxBps     *float64
+	TxBps     *float64
+}
+
+// RouterConfig es una fila de la tabla routers (fuente de verdad; is_gateway
+// como booleano, orden is_gateway DESC, created_at ASC — SPEC §8.2).
+type RouterConfig struct {
+	ID        string `json:"id"`
+	Name      string `json:"name"`
+	Host      string `json:"host"`
+	Type      string `json:"type"` // "glinet"|"openwrt"
+	IsGateway bool   `json:"is_gateway"`
+	CreatedAt int64  `json:"created_at"` // epoch ms
+}
+
+// ---------------------------------------------------------------------------
+// Snapshotter — la interfaz que consumen handlers, poller y SSE
+// ---------------------------------------------------------------------------
+
+// Snapshotter es el contrato del adapter de datos (paridad con la interfaz JS
+// de SPEC §7: mode/tick/setRouters/getOverview/getRouters/getRouterDetail/
+// getDevices/getAlerts/getMetricsRows/getDawn/getAdguardClients/close;
+// getAdguardRow() está muerto en Node y NO se porta).
+//
+// Convenciones de retorno (consumidas por internal/httpapi):
+//   - GetRouterDetail: (nil, nil) → 404 {"error":"not_found"}.
+//   - GetDawn: (nil, nil) → 503 {"error":"unavailable"}.
+//   - GetAdguardClients: (nil, nil) → 404 {"error":"not_configured"};
+//     (x, err) → 502 {"error":"adguard_error","message":err}.
+//   - GetOverview nunca devuelve nil sin error; el handler lo serializa tal
+//     cual (shape Overview exacto).
+type Snapshotter interface {
+	// Mode es "demo" | "live" (lo reportan /api/health y /api/auth/me).
+	Mode() string
+	// Tick avanza el estado interno (demo: random walk; live: no-op, el
+	// sondeo ocurre en GetOverview). Lo llama el poller cada 5 s.
+	Tick(ctx context.Context) error
+	// SetRouters resincroniza la configuración de routers en caliente (CRUD
+	// de /api/config/routers). En demo es no-op.
+	SetRouters(list []RouterConfig)
+	// GetOverview construye el snapshot completo (single-flight en live).
+	GetOverview(ctx context.Context) (*Overview, error)
+	// GetRouters lista las tarjetas de router actuales.
+	GetRouters(ctx context.Context) []Router
+	// GetRouterDetail devuelve el detalle o (nil, nil) si el id no existe.
+	GetRouterDetail(ctx context.Context, id string) (*RouterDetail, error)
+	// GetDevices lista todos los dispositivos (sin paginar; la paginación y
+	// filtros los aplica el handler de /api/devices).
+	GetDevices(ctx context.Context) []Device
+	// GetAlerts lista las alertas (más recientes primero, máx 100).
+	GetAlerts(ctx context.Context) []AlertEvent
+	// GetMetricsRows devuelve las filas para la tabla metrics del tick
+	// actual (el poller solo persiste si Mode() != "demo").
+	GetMetricsRows(ctx context.Context) []MetricsRow
+	// GetDawn devuelve la malla DAWN o (nil, nil) si no hay DAWN.
+	GetDawn(ctx context.Context) (*Dawn, error)
+	// GetAdguardClients devuelve los clientes AdGuard, (nil, nil) si no hay
+	// cliente configurado o no soporta queryClients, o error → 502.
+	GetAdguardClients(ctx context.Context) ([]AdguardClient, error)
+	// Close libera recursos (conexiones SSH, clientes HTTP).
+	Close() error
+}

+ 119 - 0
server-go/internal/adapters/wireguard.go

@@ -0,0 +1,119 @@
+// wireguard.go — Adapter live para WireGuard (port de
+// src/adapters/wireguard.js, SPEC §7.5): parsea `wg show <iface> dump` vía
+// SSH en el gateway. Quirk preservado: status 'active' siempre que el
+// comando responda (peers.length >= 0 ⇒ true).
+package adapters
+
+import (
+	"strconv"
+	"strings"
+	"time"
+)
+
+const handshakeActiveSec = 180 // handshake < 3 min ⇒ peer activo
+
+// WGDumpPeer es un peer parseado del dump (campos numéricos crudos).
+type WGDumpPeer struct {
+	Pubkey       string
+	Endpoint     *string // nil si "(none)"
+	AllowedIPs   string
+	HandshakeSec int64
+	RxBytes      int64
+	TxBytes      int64
+}
+
+// ParseWGDump parsea la salida TSV de `wg show <iface> dump` (literal del
+// JS: se ignora la línea 1 — interfaz — y las líneas con < 8 campos).
+func ParseWGDump(dump string) []WGDumpPeer {
+	lines := strings.Split(strings.TrimSpace(dump), "\n")
+	peers := []WGDumpPeer{}
+	for _, line := range lines[1:] {
+		f := strings.Split(line, "\t")
+		if len(f) < 8 {
+			continue
+		}
+		var endpoint *string
+		if f[2] != "(none)" {
+			ep := f[2]
+			endpoint = &ep
+		}
+		peers = append(peers, WGDumpPeer{
+			Pubkey:       f[0],
+			Endpoint:     endpoint,
+			AllowedIPs:   f[3],
+			HandshakeSec: atoiOr(f[4], 0),
+			RxBytes:      atoiOr(f[5], 0),
+			TxBytes:      atoiOr(f[6], 0),
+		})
+	}
+	return peers
+}
+
+func atoiOr(s string, def int64) int64 {
+	n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
+	if err != nil {
+		return def
+	}
+	return n
+}
+
+// WGPeerName etiqueta un peer por tunnelIp o pubkey (peerNames del config).
+type WGPeerName struct {
+	ID   string
+	Name string
+	Type string
+}
+
+// GetWireGuardStats obtiene WireGuardStats del gateway vía SSH.
+// peerNames: mapa tunnelIp/pubkey → etiqueta opcional.
+func GetWireGuardStats(pool *SSHPool, host, iface, subnet string, peerNames map[string]WGPeerName) (*WireGuardStats, error) {
+	dump, err := pool.Run(host, "wg show "+iface+" dump", 0)
+	if err != nil {
+		return nil, err
+	}
+	peers := ParseWGDump(dump)
+	nowSec := time.Now().Unix()
+
+	out := &WireGuardStats{
+		Interface: iface,
+		Subnet:    subnet,
+		Status:    "active", // quirk: siempre que el comando responda
+		Peers:     []WGPeer{},
+	}
+	for i, p := range peers {
+		tunnelIP := ""
+		if parts := strings.Split(p.AllowedIPs, ","); len(parts) > 0 {
+			tunnelIP = strings.Replace(parts[0], "/32", "", 1)
+		}
+		named, ok := peerNames[tunnelIP]
+		if !ok {
+			named = peerNames[p.Pubkey]
+		}
+		id := named.ID
+		if id == "" {
+			id = "peer-" + strconv.Itoa(i+1)
+		}
+		name := named.Name
+		if name == "" {
+			name = tunnelIP
+			if name == "" {
+				name = "Peer " + p.Pubkey[:min(len(p.Pubkey), 8)]
+			}
+		}
+		typ := named.Type
+		if typ == "" {
+			typ = "desconocido"
+		}
+		active := p.HandshakeSec > 0 && nowSec-p.HandshakeSec < handshakeActiveSec
+		lastHandshake := "nunca"
+		if p.HandshakeSec > 0 {
+			lastHandshake = relTime(p.HandshakeSec, nowSec)
+		}
+		out.Peers = append(out.Peers, WGPeer{
+			ID: id, Name: name, Type: typ, TunnelIP: tunnelIP,
+			Active: active, LastHandshake: lastHandshake,
+			Rx: fmtBytes(float64(p.RxBytes)), Tx: fmtBytes(float64(p.TxBytes)),
+		})
+	}
+	return out, nil
+}

+ 418 - 0
server-go/internal/auth/auth.go

@@ -0,0 +1,418 @@
+// Package auth — autenticación multiusuario (paridad con server/src/auth.js):
+//   - Cookie `session` = `id.hmac` (UUID v4 . hex(HMAC-SHA256)), httpOnly,
+//     SameSite=Lax, 30 días; Secure según COOKIE_SECURE / X-Forwarded-Proto.
+//   - Verificación: split por el ÚLTIMO punto, comparación timing-safe.
+//   - Secret HMAC: SESSION_SECRET o autogenerado persistido en kv.
+//   - Sesiones en SQLite (30 d), rotación tras login.
+//   - Rate-limit persistente (login_attempts): bloqueo 5 min armado cuando
+//     attempts previos >= 4 (5º fallo), 429 con retryAfterSec.
+//   - bcrypt cost 10 (hashes bcryptjs $2a/$2b verificables con x/crypto).
+package auth
+
+import (
+	"crypto/hmac"
+	"crypto/rand"
+	"crypto/sha256"
+	"database/sql"
+	"encoding/hex"
+	"fmt"
+	"log"
+	"net"
+	"net/http"
+	"regexp"
+	"strings"
+
+	"golang.org/x/crypto/bcrypt"
+
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+const (
+	// SessionCookie es el nombre de la cookie de sesión.
+	SessionCookie = "session"
+	// SessionTTLMS = 30 días en ms (Max-Age=2592000).
+	SessionTTLMS = 30 * 24 * 60 * 60 * 1000
+	// LockMS = 5 minutos en ms.
+	LockMS = 5 * 60 * 1000
+)
+
+// ---------------------------------------------------------------------------
+// Usuarios
+// ---------------------------------------------------------------------------
+
+// User fila pública de users (sin pass_hash).
+type User struct {
+	ID       int64
+	Username string
+	Role     string
+}
+
+// EnsureUsers crea el admin inicial (AUTH_USER/AUTH_PASS) si users está vacía.
+func EnsureUsers(d *db.DB, cfg *config.Config) error {
+	var count int
+	if err := d.QueryRow("SELECT COUNT(*) FROM users").Scan(&count); err != nil {
+		return err
+	}
+	if count > 0 {
+		return nil
+	}
+	hash, err := bcrypt.GenerateFromPassword([]byte(cfg.AuthPass), 10)
+	if err != nil {
+		return err
+	}
+	if _, err := d.Exec(
+		"INSERT INTO users (username, pass_hash, role, created_at) VALUES (?, ?, 'admin', ?)",
+		cfg.AuthUser, string(hash), db.NowMS(),
+	); err != nil {
+		return err
+	}
+	log.Printf("[netpulse] usuario admin inicial creado: %s", cfg.AuthUser)
+	return nil
+}
+
+type userRow struct {
+	ID       int64
+	Username string
+	PassHash string
+	Role     string
+}
+
+// GetUserByName devuelve la fila de login (con pass_hash) o nil.
+func GetUserByName(d *db.DB, username string) *userRow {
+	var u userRow
+	err := d.QueryRow("SELECT id, username, pass_hash, role FROM users WHERE username = ?", username).
+		Scan(&u.ID, &u.Username, &u.PassHash, &u.Role)
+	if err != nil {
+		return nil
+	}
+	return &u
+}
+
+// GetUserByID devuelve {id, username, role} o nil.
+func GetUserByID(d *db.DB, id int64) *User {
+	var u User
+	err := d.QueryRow("SELECT id, username, role FROM users WHERE id = ?", id).
+		Scan(&u.ID, &u.Username, &u.Role)
+	if err != nil {
+		return nil
+	}
+	return &u
+}
+
+// CheckPassword verifica bcrypt (cost 10; hashes bcryptjs $2a/$2b portables).
+func CheckPassword(password, hash string) bool {
+	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil
+}
+
+// HashPassword genera un hash bcrypt cost 10.
+func HashPassword(password string) (string, error) {
+	h, err := bcrypt.GenerateFromPassword([]byte(password), 10)
+	return string(h), err
+}
+
+// ---------------------------------------------------------------------------
+// Secret HMAC
+// ---------------------------------------------------------------------------
+
+// EnsureSessionSecret: SESSION_SECRET del env si existe; si no, kv
+// `session_secret`; si no existe, se genera (64 chars hex) y se persiste.
+func EnsureSessionSecret(d *db.DB, cfg *config.Config) (string, error) {
+	if cfg.SessionSecret != "" {
+		return cfg.SessionSecret, nil
+	}
+	var value string
+	err := d.QueryRow("SELECT value FROM kv WHERE key = 'session_secret'").Scan(&value)
+	if err == nil && value != "" {
+		return value, nil
+	}
+	buf := make([]byte, 32)
+	if _, err := rand.Read(buf); err != nil {
+		return "", err
+	}
+	secret := hex.EncodeToString(buf)
+	if _, err := d.Exec(
+		"INSERT INTO kv (key, value) VALUES ('session_secret', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+		secret,
+	); err != nil {
+		return "", err
+	}
+	return secret, nil
+}
+
+// ---------------------------------------------------------------------------
+// Cookie id.hmac
+// ---------------------------------------------------------------------------
+
+func hmacHex(secret, id string) string {
+	m := hmac.New(sha256.New, []byte(secret))
+	m.Write([]byte(id))
+	return hex.EncodeToString(m.Sum(nil))
+}
+
+// SignSessionID devuelve `${id}.${hmac}`.
+func SignSessionID(secret, id string) string {
+	return id + "." + hmacHex(secret, id)
+}
+
+// VerifySessionCookie valida `id.hmac`: split por el ÚLTIMO punto y
+// comparación timing-safe. Devuelve el id o "".
+func VerifySessionCookie(secret, value string) string {
+	if value == "" {
+		return ""
+	}
+	dot := strings.LastIndex(value, ".")
+	if dot <= 0 {
+		return ""
+	}
+	id := value[:dot]
+	sig := value[dot+1:]
+	expected := hmacHex(secret, id)
+	// hmac.Equal es constant-time para entradas de la misma longitud
+	// (paridad con safeEqual de auth.js:88-92).
+	if !hmac.Equal([]byte(sig), []byte(expected)) {
+		return ""
+	}
+	return id
+}
+
+// cookieRe replica /(?:^|;\s*)session=([^;]+)/ (primera ocurrencia).
+var cookieRe = regexp.MustCompile(`(?:^|;\s*)session=([^;]+)`)
+
+func sessionCookieValue(r *http.Request) string {
+	m := cookieRe.FindStringSubmatch(r.Header.Get("Cookie"))
+	if m == nil {
+		return ""
+	}
+	return m[1]
+}
+
+// IsSecureRequest: URL https o primer X-Forwarded-Proto == "https".
+func IsSecureRequest(r *http.Request) bool {
+	if r.TLS != nil || r.URL.Scheme == "https" {
+		return true
+	}
+	proto := r.Header.Get("X-Forwarded-Proto")
+	if proto == "" {
+		return false
+	}
+	first := strings.TrimSpace(strings.Split(proto, ",")[0])
+	return first == "https"
+}
+
+// CookieSecureFlag: always→true, never→false, auto→IsSecureRequest.
+func CookieSecureFlag(cfg *config.Config, r *http.Request) bool {
+	switch cfg.CookieSecure {
+	case "always":
+		return true
+	case "never":
+		return false
+	default:
+		return IsSecureRequest(r)
+	}
+}
+
+// BuildSessionCookie compone el header Set-Cookie (literal de auth.js:119-129).
+func BuildSessionCookie(cfg *config.Config, r *http.Request, signedID string, maxAgeSec int64) string {
+	parts := []string{
+		fmt.Sprintf("%s=%s", SessionCookie, signedID),
+		"Path=/",
+		"HttpOnly",
+		"SameSite=Lax",
+		fmt.Sprintf("Max-Age=%d", maxAgeSec),
+	}
+	if CookieSecureFlag(cfg, r) {
+		parts = append(parts, "Secure")
+	}
+	return strings.Join(parts, "; ")
+}
+
+// ClearSessionCookie borra la cookie (literal, SIN Secure aunque sea HTTPS).
+const ClearSessionCookie = "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"
+
+// ---------------------------------------------------------------------------
+// Sesiones en SQLite
+// ---------------------------------------------------------------------------
+
+// newUUIDv4 genera un UUID v4 canónico (8-4-4-4-12 hex) con crypto/rand.
+func newUUIDv4() string {
+	var b [16]byte
+	if _, err := rand.Read(b[:]); err != nil {
+		panic(err)
+	}
+	b[6] = (b[6] & 0x0f) | 0x40 // versión 4
+	b[8] = (b[8] & 0x3f) | 0x80 // variante RFC 4122
+	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
+}
+
+// CreateSession crea una sesión (UUID v4, TTL 30 d, ua truncado a 255).
+func CreateSession(d *db.DB, ua string, userID int64) string {
+	id := newUUIDv4()
+	now := db.NowMS()
+	if len(ua) > 255 {
+		ua = ua[:255]
+	}
+	_, _ = d.Exec(
+		"INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES (?, ?, ?, ?, ?)",
+		id, now, now+SessionTTLMS, ua, userID,
+	)
+	return id
+}
+
+// DestroySession borra una sesión por id.
+func DestroySession(d *db.DB, id string) {
+	if id != "" {
+		_, _ = d.Exec("DELETE FROM sessions WHERE id = ?", id)
+	}
+}
+
+// DestroyUserSessions borra todas las sesiones de un usuario (re-login forzado).
+func DestroyUserSessions(d *db.DB, userID int64) {
+	_, _ = d.Exec("DELETE FROM sessions WHERE user_id = ?", userID)
+}
+
+// Session es la fila viva de sessions.
+type Session struct {
+	ID        string
+	ExpiresAt int64
+	UserID    sql.NullInt64
+}
+
+// GetSession devuelve la sesión si existe y no expiró (si expiró, la borra).
+func GetSession(d *db.DB, id string) *Session {
+	if id == "" {
+		return nil
+	}
+	var s Session
+	err := d.QueryRow("SELECT id, expires_at, user_id FROM sessions WHERE id = ?", id).
+		Scan(&s.ID, &s.ExpiresAt, &s.UserID)
+	if err != nil {
+		return nil
+	}
+	if s.ExpiresAt < db.NowMS() {
+		DestroySession(d, id)
+		return nil
+	}
+	return &s
+}
+
+// SessionUser es el resultado de sessionUserFromRequest.
+type SessionUser struct {
+	SessionID string
+	User      *User
+}
+
+// SessionUserFromRequest: cookie válida + sesión en DB con user_id NO nulo +
+// usuario existente (una sesión legacy sin user_id NO autentica).
+func SessionUserFromRequest(d *db.DB, secret string, r *http.Request) *SessionUser {
+	id := VerifySessionCookie(secret, sessionCookieValue(r))
+	sess := GetSession(d, id)
+	if sess == nil || !sess.UserID.Valid {
+		return nil
+	}
+	user := GetUserByID(d, sess.UserID.Int64)
+	if user == nil {
+		return nil
+	}
+	return &SessionUser{SessionID: id, User: user}
+}
+
+// SessionIDFromRequest devuelve el id de sesión válida (sin exigir user_id).
+func SessionIDFromRequest(d *db.DB, secret string, r *http.Request) string {
+	id := VerifySessionCookie(secret, sessionCookieValue(r))
+	if GetSession(d, id) == nil {
+		return ""
+	}
+	return id
+}
+
+// ---------------------------------------------------------------------------
+// Rate-limit en SQLite (persiste tras reinicios)
+// ---------------------------------------------------------------------------
+
+// ClientIP: primer X-Forwarded-For o la IP remota o 'unknown'.
+func ClientIP(r *http.Request) string {
+	if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
+		if first := strings.TrimSpace(strings.Split(xff, ",")[0]); first != "" {
+			return first
+		}
+	}
+	if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && host != "" {
+		return host
+	}
+	if r.RemoteAddr != "" {
+		return r.RemoteAddr
+	}
+	return "unknown"
+}
+
+// LoginRateLimited: si la IP está bloqueada → retryAfterSec = ceil(rest/1000).
+func LoginRateLimited(d *db.DB, r *http.Request) (limited bool, retryAfterSec int64) {
+	ip := ClientIP(r)
+	var lockedUntil int64
+	err := d.QueryRow("SELECT locked_until FROM login_attempts WHERE ip = ?", ip).Scan(&lockedUntil)
+	if err != nil {
+		return false, 0
+	}
+	remaining := lockedUntil - db.NowMS()
+	if remaining > 0 {
+		return true, (remaining + 999) / 1000
+	}
+	return false, 0
+}
+
+// RegisterLoginFail registra un fallo: bloquea 5 min cuando el valor ANTERIOR
+// de attempts >= 4 (el bloqueo se arma en el 5º fallo — UPSERT literal).
+func RegisterLoginFail(d *db.DB, r *http.Request) {
+	ip := ClientIP(r)
+	_, _ = d.Exec(`
+		INSERT INTO login_attempts (ip, attempts, locked_until)
+		VALUES (?, 1, 0)
+		ON CONFLICT(ip) DO UPDATE SET
+		  attempts = attempts + 1,
+		  locked_until = CASE
+		    WHEN attempts >= 4 THEN ?
+		    ELSE locked_until
+		  END
+	`, ip, db.NowMS()+LockMS)
+}
+
+// LoginOk borra la fila de login_attempts de la IP.
+func LoginOk(d *db.DB, r *http.Request) {
+	_, _ = d.Exec("DELETE FROM login_attempts WHERE ip = ?", ClientIP(r))
+}
+
+// ---------------------------------------------------------------------------
+// Login / logout
+// ---------------------------------------------------------------------------
+
+// LoginResult es el resultado de HandleLogin.
+type LoginResult struct {
+	SessionID string
+	User      *User
+}
+
+// HandleLogin valida credenciales y crea sesión nueva (rotación: invalida la
+// sesión previa de la cookie si existía). Nil si credenciales inválidas.
+func HandleLogin(d *db.DB, secret string, r *http.Request, username, password string) *LoginResult {
+	if username == "" || password == "" {
+		return nil
+	}
+	u := GetUserByName(d, username)
+	if u == nil || !CheckPassword(password, u.PassHash) {
+		return nil
+	}
+	// Rotación de sesión
+	if prevID := SessionIDFromRequest(d, secret, r); prevID != "" {
+		DestroySession(d, prevID)
+	}
+	id := CreateSession(d, r.Header.Get("User-Agent"), u.ID)
+	return &LoginResult{SessionID: id, User: &User{ID: u.ID, Username: u.Username, Role: u.Role}}
+}
+
+// HandleLogout destruye la sesión de la cookie (si existe y es válida).
+func HandleLogout(d *db.DB, secret string, r *http.Request) {
+	if id := SessionIDFromRequest(d, secret, r); id != "" {
+		DestroySession(d, id)
+	}
+}

+ 202 - 0
server-go/internal/auth/auth_test.go

@@ -0,0 +1,202 @@
+package auth
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func testDB(t *testing.T) *db.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("open db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d
+}
+
+func testCfg() *config.Config {
+	return &config.Config{AuthUser: "admin", AuthPass: "test1234", CookieSecure: "auto"}
+}
+
+func TestSignVerifyRoundtrip(t *testing.T) {
+	secret := strings.Repeat("ab", 32)
+	id := "f47ac10b-58cc-4372-a567-0e02b2c3d479"
+	signed := SignSessionID(secret, id)
+	if got := VerifySessionCookie(secret, signed); got != id {
+		t.Fatalf("roundtrip: got %q, want %q", got, id)
+	}
+	// El id puede contener puntos: el split es por el ÚLTIMO punto.
+	weird := "id.con.puntos"
+	if got := VerifySessionCookie(secret, SignSessionID(secret, weird)); got != weird {
+		t.Fatalf("split último punto: got %q", got)
+	}
+}
+
+func TestVerifyRejects(t *testing.T) {
+	secret := strings.Repeat("ab", 32)
+	id := "f47ac10b-58cc-4372-a567-0e02b2c3d479"
+	signed := SignSessionID(secret, id)
+	cases := map[string]string{
+		"vacío":                          "",
+		"sin punto":                      "abcdef",
+		"punto al inicio":                ".abcdef",
+		"firma alterada":                 signed[:len(signed)-2] + "00",
+		"otro secret":                    SignSessionID(strings.Repeat("cd", 32), id),
+		"misma longitud, distinta firma": tamperedSignature(secret, id),
+	}
+	for name, v := range cases {
+		if got := VerifySessionCookie(secret, v); got != "" {
+			t.Errorf("%s: esperaba rechazo, got %q", name, got)
+		}
+	}
+}
+
+// tamperedSignature cambia el último carácter hex de la firma (misma longitud).
+func tamperedSignature(secret, id string) string {
+	signed := SignSessionID(secret, id)
+	last := signed[len(signed)-1]
+	repl := byte('0')
+	if last == '0' {
+		repl = '1'
+	}
+	return signed[:len(signed)-1] + string(repl)
+}
+
+func TestCookieExtraction(t *testing.T) {
+	d := testDB(t)
+	secret, err := EnsureSessionSecret(d, testCfg())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(secret) != 64 {
+		t.Fatalf("secret autogenerado debe ser 64 hex, got %d", len(secret))
+	}
+	// Persistido en kv: segunda llamada devuelve el mismo.
+	again, _ := EnsureSessionSecret(d, testCfg())
+	if again != secret {
+		t.Fatal("el secret debe persistirse en kv")
+	}
+
+	if err := EnsureUsers(d, testCfg()); err != nil {
+		t.Fatal(err)
+	}
+	admin := GetUserByName(d, "admin")
+	if admin == nil {
+		t.Fatal("seed admin")
+	}
+	id := CreateSession(d, "TestAgent/1.0", admin.ID)
+	signed := SignSessionID(secret, id)
+	r := httptest.NewRequest("GET", "/api/auth/me", nil)
+	r.Header.Set("Cookie", "other=1; session="+signed+"; theme=dark")
+	su := SessionUserFromRequest(d, secret, r)
+	if su == nil {
+		t.Fatal("cookie válida debe autenticar")
+	}
+	if su.SessionID != id {
+		t.Fatalf("sessionId: got %q want %q", su.SessionID, id)
+	}
+	// Primera ocurrencia gana (regex del JS).
+	r2 := httptest.NewRequest("GET", "/x", nil)
+	r2.Header.Set("Cookie", "session="+signed+"; session=garbage.garbage")
+	if SessionIDFromRequest(d, secret, r2) != id {
+		t.Fatal("debe usar la primera ocurrencia de session=")
+	}
+}
+
+func TestSessionExpiry(t *testing.T) {
+	d := testDB(t)
+	id := CreateSession(d, "", 1)
+	// Expira la sesión manualmente.
+	_, _ = d.Exec("UPDATE sessions SET expires_at = ? WHERE id = ?", db.NowMS()-1000, id)
+	if GetSession(d, id) != nil {
+		t.Fatal("sesión expirada debe ser inválida")
+	}
+	// Y se borra de la tabla.
+	var n int
+	_ = d.QueryRow("SELECT COUNT(*) FROM sessions WHERE id = ?", id).Scan(&n)
+	if n != 0 {
+		t.Fatal("sesión expirada debe borrarse al leerla")
+	}
+}
+
+func TestSessionWithoutUserIDDoesNotAuthenticate(t *testing.T) {
+	d := testDB(t)
+	secret, _ := EnsureSessionSecret(d, testCfg())
+	// Sesión legacy sin user_id.
+	_, _ = d.Exec("INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES ('legacy', ?, ?, '', NULL)",
+		db.NowMS(), db.NowMS()+SessionTTLMS)
+	r := httptest.NewRequest("GET", "/api/overview", nil)
+	r.Header.Set("Cookie", "session="+SignSessionID(secret, "legacy"))
+	if SessionUserFromRequest(d, secret, r) != nil {
+		t.Fatal("sesión sin user_id NO debe autenticar")
+	}
+}
+
+func TestRateLimitFifthFailArmsLock(t *testing.T) {
+	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 := 1; i <= 5; i++ {
+		if limited, _ := LoginRateLimited(d, newReq()); limited {
+			t.Fatalf("fallo %d: no debe estar limitado aún", i)
+		}
+		RegisterLoginFail(d, newReq())
+	}
+	limited, retry := LoginRateLimited(d, newReq())
+	if !limited {
+		t.Fatal("tras el 5º fallo la IP debe estar bloqueada")
+	}
+	if retry <= 0 || retry > 300 {
+		t.Fatalf("retryAfterSec debe estar en (0, 300], got %d", retry)
+	}
+	// Persistencia en SQLite.
+	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 < 5 || lockedUntil <= db.NowMS() {
+		t.Fatalf("fila esperada attempts>=5 y locked_until futuro: %d %d", attempts, lockedUntil)
+	}
+	// LoginOk limpia la fila.
+	LoginOk(d, newReq())
+	if limited, _ := LoginRateLimited(d, newReq()); limited {
+		t.Fatal("LoginOk debe limpiar el bloqueo")
+	}
+}
+
+func TestBuildSessionCookieFlags(t *testing.T) {
+	cfg := &config.Config{CookieSecure: "auto"}
+	r := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
+	c := BuildSessionCookie(cfg, r, "id.sig", 2592000)
+	want := "session=id.sig; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000"
+	if c != want {
+		t.Fatalf("cookie http:\n got %q\nwant %q", c, want)
+	}
+	// X-Forwarded-Proto https → Secure (auto).
+	r2 := httptest.NewRequest("POST", "http://x/api/auth/login", nil)
+	r2.Header.Set("X-Forwarded-Proto", "https, http")
+	if got := BuildSessionCookie(cfg, r2, "id.sig", 2592000); !strings.HasSuffix(got, "; Secure") {
+		t.Fatalf("auto + X-Forwarded-Proto=https debe añadir Secure: %q", got)
+	}
+	// always / never.
+	cfgAlways := &config.Config{CookieSecure: "always"}
+	if got := BuildSessionCookie(cfgAlways, r, "i.s", 1); !strings.HasSuffix(got, "; Secure") {
+		t.Fatal("always debe forzar Secure")
+	}
+	cfgNever := &config.Config{CookieSecure: "never"}
+	r3 := httptest.NewRequest("POST", "https://x/", nil)
+	if got := BuildSessionCookie(cfgNever, r3, "i.s", 1); strings.Contains(got, "Secure") {
+		t.Fatal("never debe omitir Secure incluso en https")
+	}
+}

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

@@ -0,0 +1,76 @@
+// middleware.go — requireAuth / requireAdmin (paridad auth.js:258-278).
+package auth
+
+import (
+	"context"
+	"encoding/json"
+	"net/http"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+type ctxKey int
+
+const (
+	ctxUser ctxKey = iota
+	ctxSessionID
+)
+
+// UserFromContext devuelve el usuario autenticado (nil si no hay).
+func UserFromContext(ctx context.Context) *User {
+	u, _ := ctx.Value(ctxUser).(*User)
+	return u
+}
+
+// SessionIDFromContext devuelve el sessionId autenticado ("" si no hay).
+func SessionIDFromContext(ctx context.Context) string {
+	s, _ := ctx.Value(ctxSessionID).(string)
+	return s
+}
+
+// WriteError escribe el envelope de error {error, message?} con el status dado.
+func WriteError(w http.ResponseWriter, status int, code string, message ...string) {
+	w.Header().Set("Content-Type", "application/json")
+	w.WriteHeader(status)
+	body := map[string]any{"error": code}
+	if len(message) > 0 {
+		body["message"] = message[0]
+	}
+	// json.Marshal (no Encoder): el cuerpo debe ser literal como Hono, SIN
+	// el '\n' final que añade Encode.
+	data, _ := json.Marshal(body)
+	_, _ = w.Write(data)
+}
+
+// RequireAuth es middleware global: todo /api/* exige sesión salvo
+// /api/health y /api/auth/login. Fallo → 401 {error:'unauthorized'}.
+func RequireAuth(d *db.DB, secret string, next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		path := r.URL.Path
+		if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" {
+			next.ServeHTTP(w, r)
+			return
+		}
+		sess := SessionUserFromRequest(d, secret, r)
+		if sess == nil {
+			WriteError(w, http.StatusUnauthorized, "unauthorized")
+			return
+		}
+		ctx := context.WithValue(r.Context(), ctxUser, sess.User)
+		ctx = context.WithValue(ctx, ctxSessionID, sess.SessionID)
+		next.ServeHTTP(w, r.WithContext(ctx))
+	})
+}
+
+// RequireAdmin exige role === 'admin' (tras RequireAuth) → 403 {error:'forbidden'}.
+func RequireAdmin(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		user := UserFromContext(r.Context())
+		if user == nil || user.Role != "admin" {
+			WriteError(w, http.StatusForbidden, "forbidden")
+			return
+		}
+		next.ServeHTTP(w, r)
+	})
+}

+ 292 - 0
server-go/internal/config/config.go

@@ -0,0 +1,292 @@
+// Package config — configuración por entorno, validada (fail-fast).
+// Paridad con server/src/config.js: parser .env propio (no pisa el entorno),
+// mismas variables, defaults y validaciones (SPEC §8.1).
+package config
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/url"
+	"os"
+	"path/filepath"
+	"strconv"
+	"strings"
+)
+
+// RouterSeed es una entrada de ROUTERS_JSON (semilla opcional de la tabla routers).
+type RouterSeed struct {
+	ID   string `json:"id"`
+	Name string `json:"name"`
+	Host string `json:"host"`
+	Type string `json:"type"` // "glinet" | "openwrt" (default "openwrt")
+}
+
+// AdGuard configura el cliente estándar (env). Nil si no hay ADGUARD_URL.
+type AdGuard struct {
+	URL  string
+	User string
+	Pass string
+}
+
+// Config es la config normalizada (equivalente al objeto de loadConfig).
+type Config struct {
+	Port          int
+	NodeEnv       string
+	StaticDir     string // resuelta (absoluta)
+	DataDir       string // resuelta (absoluta)
+	SessionSecret string // "" si falta (autogenerado en kv)
+	AuthUser      string
+	AuthPass      string
+	DemoMode      bool
+	MaxSSEClients int
+	Routers       []RouterSeed
+	SSHKeyPath    string
+	Adguard       *AdGuard
+	WGInterface   string
+	CookieSecure  string // "auto" | "always" | "never"
+	GithubRepo    string
+	GithubToken   string
+	ServerRoot    string
+}
+
+// LoadDotEnv parsea un .env: KEY=VALUE por línea, '#' comentarios (línea
+// completa), comillas simples/dobles opcionales. NO pisa variables ya
+// presentes en el entorno (paridad con config.js:13-27).
+func LoadDotEnv(envPath string) {
+	data, err := os.ReadFile(envPath)
+	if err != nil {
+		return
+	}
+	for _, rawLine := range strings.Split(string(data), "\n") {
+		line := strings.TrimSpace(rawLine)
+		if line == "" || strings.HasPrefix(line, "#") {
+			continue
+		}
+		eq := strings.Index(line, "=")
+		if eq == -1 {
+			continue
+		}
+		key := strings.TrimSpace(line[:eq])
+		value := strings.TrimSpace(line[eq+1:])
+		if len(value) >= 2 {
+			if (value[0] == '"' && value[len(value)-1] == '"') || (value[0] == '\'' && value[len(value)-1] == '\'') {
+				value = value[1 : len(value)-1]
+			}
+		}
+		if _, exists := os.LookupEnv(key); !exists {
+			os.Setenv(key, value)
+		}
+	}
+}
+
+type issue struct {
+	path, message string
+}
+
+// ValidationError es el error fail-fast de configuración (mismo formato que
+// config.js:67-70).
+type ValidationError struct{ issues []issue }
+
+func (e *ValidationError) Error() string {
+	var b strings.Builder
+	b.WriteString("[netpulse] Configuración inválida (revisa server/.env):")
+	for _, i := range e.issues {
+		fmt.Fprintf(&b, "\n  - %s: %s", i.path, i.message)
+	}
+	return b.String()
+}
+
+// Load valida el entorno y devuelve la config normalizada.
+// env es un mapa key→value (normalmente leído de os.Environ); serverRoot es
+// el directorio base para resolver STATIC_DIR/DATA_DIR relativos (en Node es
+// server/; en Go el working directory del proceso — ver cmd/netpulse).
+// Fail-fast: devuelve error si falta algo crítico o ROUTERS_JSON es inválido.
+func Load(env map[string]string, serverRoot string) (*Config, error) {
+	var errs ValidationError
+
+	// PORT: int 1..65535, default 3000
+	port := 3000
+	if v, ok := env["PORT"]; ok && v != "" {
+		n, err := strconv.Atoi(strings.TrimSpace(v))
+		if err != nil || n < 1 || n > 65535 {
+			errs.issues = append(errs.issues, issue{"PORT", "Expected int 1..65535"})
+		} else {
+			port = n
+		}
+	}
+
+	// NODE_ENV: development|production|test, default development
+	nodeEnv := "development"
+	if v, ok := env["NODE_ENV"]; ok && v != "" {
+		switch v {
+		case "development", "production", "test":
+			nodeEnv = v
+		default:
+			errs.issues = append(errs.issues, issue{"NODE_ENV", "Invalid enum value. Expected 'development' | 'production' | 'test'"})
+		}
+	}
+
+	staticDir := "../app/dist"
+	if v, ok := env["STATIC_DIR"]; ok && v != "" {
+		staticDir = v
+	}
+	dataDir := "./data"
+	if v, ok := env["DATA_DIR"]; ok && v != "" {
+		dataDir = v
+	}
+
+	// SESSION_SECRET: min 32, opcional
+	sessionSecret := ""
+	if v, ok := env["SESSION_SECRET"]; ok && v != "" {
+		if len(v) < 32 {
+			errs.issues = append(errs.issues, issue{"SESSION_SECRET", "String must contain at least 32 character(s)"})
+		} else {
+			sessionSecret = v
+		}
+	}
+
+	authUser := "admin"
+	if v, ok := env["AUTH_USER"]; ok && v != "" {
+		authUser = v
+	}
+
+	// AUTH_PASS: obligatoria (fail-fast) aunque ya existan usuarios
+	authPass := ""
+	if v, ok := env["AUTH_PASS"]; ok && v != "" {
+		authPass = v
+	} else {
+		errs.issues = append(errs.issues, issue{"AUTH_PASS", "Required"})
+	}
+
+	// DEMO_MODE: '0'|'1', opcional (demo solo si === '1')
+	demoMode := false
+	if v, ok := env["DEMO_MODE"]; ok && v != "" {
+		switch v {
+		case "0":
+		case "1":
+			demoMode = true
+		default:
+			errs.issues = append(errs.issues, issue{"DEMO_MODE", "Invalid enum value. Expected '0' | '1'"})
+		}
+	}
+
+	// MAX_SSE_CLIENTS: int 1..100, default 10
+	maxSSE := 10
+	if v, ok := env["MAX_SSE_CLIENTS"]; ok && v != "" {
+		n, err := strconv.Atoi(strings.TrimSpace(v))
+		if err != nil || n < 1 || n > 100 {
+			errs.issues = append(errs.issues, issue{"MAX_SSE_CLIENTS", "Expected int 1..100"})
+		} else {
+			maxSSE = n
+		}
+	}
+
+	// COOKIE_SECURE: auto|always|never, default auto
+	cookieSecure := "auto"
+	if v, ok := env["COOKIE_SECURE"]; ok && v != "" {
+		switch v {
+		case "auto", "always", "never":
+			cookieSecure = v
+		default:
+			errs.issues = append(errs.issues, issue{"COOKIE_SECURE", "Invalid enum value. Expected 'auto' | 'always' | 'never'"})
+		}
+	}
+
+	wgInterface := "wg0"
+	if v, ok := env["WG_INTERFACE"]; ok && v != "" {
+		wgInterface = v
+	}
+
+	githubRepo := "gnacho/netpulse"
+	if v, ok := env["GITHUB_REPO"]; ok && v != "" {
+		githubRepo = v
+	}
+	githubToken := env["GITHUB_TOKEN"]
+
+	// ADGUARD_*: cliente estándar solo si hay URL válida
+	var adguard *AdGuard
+	if v, ok := env["ADGUARD_URL"]; ok && v != "" {
+		if u, err := url.Parse(v); err != nil || u.Scheme == "" || u.Host == "" {
+			errs.issues = append(errs.issues, issue{"ADGUARD_URL", "Invalid url"})
+		} else {
+			user := "admin"
+			if w, ok := env["ADGUARD_USER"]; ok && w != "" {
+				user = w
+			}
+			adguard = &AdGuard{URL: strings.TrimSuffix(v, "/"), User: user, Pass: env["ADGUARD_PASS"]}
+		}
+	}
+
+	if len(errs.issues) > 0 {
+		return nil, &errs
+	}
+
+	// ROUTERS_JSON: array de {id, name?, host, type?}; inválido → fail-fast
+	var routers []RouterSeed
+	if v, ok := env["ROUTERS_JSON"]; ok && v != "" {
+		var raw []RouterSeed
+		if err := json.Unmarshal([]byte(v), &raw); err != nil {
+			return nil, fmt.Errorf("[netpulse] ROUTERS_JSON inválido: %v", err)
+		}
+		for i, r := range raw {
+			if r.ID == "" || r.Host == "" {
+				return nil, fmt.Errorf("[netpulse] ROUTERS_JSON inválido: entrada %d requiere id y host", i)
+			}
+			if r.Type == "" {
+				raw[i].Type = "openwrt"
+			} else if r.Type != "glinet" && r.Type != "openwrt" {
+				return nil, fmt.Errorf("[netpulse] ROUTERS_JSON inválido: type debe ser glinet|openwrt")
+			}
+		}
+		routers = raw
+	}
+
+	resolve := func(p string) string {
+		if filepath.IsAbs(p) {
+			return filepath.Clean(p)
+		}
+		return filepath.Join(serverRoot, p)
+	}
+
+	sshKeyPath := ""
+	if v, ok := env["SSH_KEY_PATH"]; ok && v != "" {
+		home, _ := os.UserHomeDir()
+		if strings.HasPrefix(v, "~") {
+			v = home + v[1:]
+		}
+		sshKeyPath = v
+	} else {
+		sshKeyPath = filepath.Join(resolve(dataDir), ".ssh", "id_ed25519")
+	}
+
+	return &Config{
+		Port:          port,
+		NodeEnv:       nodeEnv,
+		StaticDir:     resolve(staticDir),
+		DataDir:       resolve(dataDir),
+		SessionSecret: sessionSecret,
+		AuthUser:      authUser,
+		AuthPass:      authPass,
+		DemoMode:      demoMode,
+		MaxSSEClients: maxSSE,
+		Routers:       routers,
+		SSHKeyPath:    sshKeyPath,
+		Adguard:       adguard,
+		WGInterface:   wgInterface,
+		CookieSecure:  cookieSecure,
+		GithubRepo:    githubRepo,
+		GithubToken:   githubToken,
+		ServerRoot:    serverRoot,
+	}, nil
+}
+
+// FromEnviron construye el mapa de entorno del proceso.
+func FromEnviron() map[string]string {
+	env := map[string]string{}
+	for _, kv := range os.Environ() {
+		if eq := strings.Index(kv, "="); eq > 0 {
+			env[kv[:eq]] = kv[eq+1:]
+		}
+	}
+	return env
+}

+ 254 - 0
server-go/internal/db/db.go

@@ -0,0 +1,254 @@
+// Package db — SQLite (modernc.org/sqlite, sin CGO): schema literal de Node,
+// pragmas (WAL, synchronous NORMAL, foreign_keys ON), migraciones tolerantes
+// y jobs de mantenimiento (retención 7 días + wal_checkpoint(TRUNCATE) 1 h).
+// Paridad con server/src/db.js (SPEC §4).
+//
+// Epochs: TODOS los timestamps de la DB son milisegundos (created_at,
+// expires_at, metrics.ts, locked_until). Segundos solo en overview.ts.
+package db
+
+import (
+	"context"
+	"database/sql"
+	"fmt"
+	"log"
+	"os"
+	"path/filepath"
+	"sync"
+	"time"
+
+	_ "modernc.org/sqlite"
+)
+
+const (
+	RetentionMS  = 7 * 24 * 60 * 60 * 1000 // 7 días
+	Maintenance  = time.Hour
+	databaseFile = "netpulse.db"
+)
+
+// schemaSQL es el SQL literal de src/db.js:20-85.
+const schemaSQL = `
+-- Sesiones (cookie id.hmac)
+CREATE TABLE IF NOT EXISTS sessions (
+  id TEXT PRIMARY KEY,
+  created_at INTEGER NOT NULL,
+  expires_at INTEGER NOT NULL,
+  ua TEXT
+);
+-- Rate-limit de login por IP
+CREATE TABLE IF NOT EXISTS login_attempts (
+  ip TEXT PRIMARY KEY,
+  attempts INTEGER DEFAULT 0,
+  locked_until INTEGER DEFAULT 0
+);
+-- Clave-valor (session_secret, auth_pass_hash, ...)
+CREATE TABLE IF NOT EXISTS kv (
+  key TEXT PRIMARY KEY,
+  value TEXT
+);
+-- Métricas por router y tick del poller
+CREATE TABLE IF NOT EXISTS metrics (
+  router_id TEXT NOT NULL,
+  ts INTEGER NOT NULL,
+  cpu REAL, ram REAL, temp REAL,
+  latency_ms REAL, rx_bps REAL, tx_bps REAL
+);
+CREATE INDEX IF NOT EXISTS idx_metrics_router_ts ON metrics(router_id, ts);
+-- Estadísticas AdGuard por tick
+CREATE TABLE IF NOT EXISTS adguard_stats (
+  ts INTEGER NOT NULL,
+  queries INTEGER, blocked INTEGER
+);
+CREATE INDEX IF NOT EXISTS idx_adguard_ts ON adguard_stats(ts);
+-- Usuarios (multiusuario: el admin gestiona altas/bajas/passwords)
+CREATE TABLE IF NOT EXISTS users (
+  id INTEGER PRIMARY KEY AUTOINCREMENT,
+  username TEXT UNIQUE NOT NULL,
+  pass_hash TEXT NOT NULL,
+  role TEXT NOT NULL DEFAULT 'user',
+  created_at INTEGER NOT NULL
+);
+-- Última atribución conocida por MAC
+CREATE TABLE IF NOT EXISTS device_attrib (
+  mac TEXT PRIMARY KEY,
+  router_id TEXT,
+  band TEXT,
+  signal_dbm INTEGER,
+  last_seen INTEGER NOT NULL
+);
+-- Routers configurados
+CREATE TABLE IF NOT EXISTS routers (
+  id TEXT PRIMARY KEY,
+  name TEXT,
+  host TEXT NOT NULL,
+  type TEXT NOT NULL DEFAULT 'openwrt',
+  is_gateway INTEGER NOT NULL DEFAULT 0,
+  created_at INTEGER NOT NULL
+);
+`
+
+// DB envuelve *sql.DB con los jobs y helpers de paridad.
+type DB struct {
+	*sql.DB
+	Path  string
+	stop  chan struct{}
+	wg    sync.WaitGroup
+	close sync.Once
+}
+
+// NowMS devuelve el epoch actual en milisegundos (como Date.now()).
+func NowMS() int64 { return time.Now().UnixMilli() }
+
+// Open abre (o crea) DATA_DIR/netpulse.db, ejecuta la migración Node→Go si la
+// DB ya existía con esquema Node (backup atómico antes de tocar nada),
+// aplica pragmas, crea el schema y arranca el mantenimiento horario.
+func Open(dataDir string) (*DB, error) {
+	if err := os.MkdirAll(dataDir, 0o755); err != nil {
+		return nil, err
+	}
+	dbPath := filepath.Join(dataDir, databaseFile)
+
+	// Migración Node→Go (§12 del SPEC): si el fichero ya existe con esquema
+	// Node, backup + importación (preserva users/kv/sessions/routers/metrics).
+	rep, err := MigrateNodeDB(dbPath)
+	if err != nil {
+		return nil, fmt.Errorf("migración Node→Go: %w", err)
+	}
+	if rep != nil {
+		rep.Log()
+	}
+
+	// Una sola conexión: better-sqlite3 es síncrono/serial; con maxOpenConns=1
+	// Go serializa igual y evita SQLITE_BUSY en WAL.
+	sqldb, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)")
+	if err != nil {
+		return nil, err
+	}
+	sqldb.SetMaxOpenConns(1)
+
+	for _, p := range []string{
+		"PRAGMA journal_mode = WAL",
+		"PRAGMA synchronous = NORMAL",
+		"PRAGMA foreign_keys = ON",
+	} {
+		if _, err := sqldb.Exec(p); err != nil {
+			sqldb.Close()
+			return nil, fmt.Errorf("pragma %q: %w", p, err)
+		}
+	}
+	if _, err := sqldb.Exec(schemaSQL); err != nil {
+		sqldb.Close()
+		return nil, fmt.Errorf("schema: %w", err)
+	}
+
+	// Migraciones tolerantes (ALTER solo si falta la columna; errores tragados)
+	migrate(sqldb, "sessions", "ua", "ALTER TABLE sessions ADD COLUMN ua TEXT")
+	migrate(sqldb, "sessions", "user_id", "ALTER TABLE sessions ADD COLUMN user_id INTEGER")
+	migrate(sqldb, "users", "language", "ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'")
+
+	// Si no hubo migración Node (instalación fresca creada por Go), marca la
+	// DB para que el siguiente arranque no dispare una "migración" espuria
+	// (backup + reset de login_attempts) sobre una DB ya Go.
+	if rep == nil {
+		_, _ = sqldb.Exec(
+			"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
+			migrationMarkerKey, time.Now().Format(time.RFC3339),
+		)
+	}
+
+	d := &DB{DB: sqldb, Path: dbPath, stop: make(chan struct{})}
+	d.wg.Add(1)
+	go d.maintenanceLoop()
+	return d, nil
+}
+
+// migrate replica src/db.js:143-150: introspección PRAGMA table_info y DDL
+// tragándose errores.
+func migrate(db *sql.DB, table, column, ddl string) {
+	rows, err := db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table))
+	if err != nil {
+		return
+	}
+	defer rows.Close()
+	found := false
+	for rows.Next() {
+		var cid int
+		var name, ctype string
+		var notnull, pk int
+		var dflt sql.NullString
+		if err := rows.Scan(&cid, &name, &ctype, &notnull, &dflt, &pk); err == nil && name == column {
+			found = true
+		}
+	}
+	if !found {
+		_, _ = db.Exec(ddl) // errores tragados (paridad)
+	}
+}
+
+// Maintenance ejecuta una pasada de limpieza (paridad src/db.js:107-120):
+// retención 7 días en metrics/adguard_stats, sesiones expiradas y checkpoint.
+func (d *DB) Maintenance() {
+	cutoff := NowMS() - RetentionMS
+	steps := []string{
+		"DELETE FROM metrics WHERE ts < ?",
+		"DELETE FROM adguard_stats WHERE ts < ?",
+	}
+	for _, q := range steps {
+		if _, err := d.Exec(q, cutoff); err != nil {
+			log.Printf("[netpulse] error en mantenimiento DB: %v", err)
+		}
+	}
+	if _, err := d.Exec("DELETE FROM sessions WHERE expires_at < ?", NowMS()); err != nil {
+		log.Printf("[netpulse] error en mantenimiento DB: %v", err)
+	}
+	if _, err := d.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
+		log.Printf("[netpulse] error en mantenimiento DB: %v", err)
+	}
+}
+
+func (d *DB) maintenanceLoop() {
+	defer d.wg.Done()
+	t := time.NewTicker(Maintenance)
+	defer t.Stop()
+	for {
+		select {
+		case <-d.stop:
+			return
+		case <-t.C:
+			d.Maintenance()
+		}
+	}
+}
+
+// CheckHealth replica dbHandle.checkHealth(): SELECT 1.
+func (d *DB) CheckHealth() bool {
+	var ok int
+	if err := d.QueryRow("SELECT 1").Scan(&ok); err != nil {
+		return false
+	}
+	return ok == 1
+}
+
+// Close para el timer, checkpoint TRUNCATE (best-effort) y cierra.
+func (d *DB) Close() error {
+	var err error
+	d.close.Do(func() {
+		close(d.stop)
+		d.wg.Wait()
+		_, _ = d.Exec("PRAGMA wal_checkpoint(TRUNCATE)")
+		err = d.DB.Close()
+	})
+	return err
+}
+
+// ShutdownContext cierra el pool con contexto (para el salvavidas de 3 s).
+func (d *DB) ShutdownContext(ctx context.Context) error {
+	done := make(chan error, 1)
+	go func() { done <- d.Close() }()
+	select {
+	case err := <-done:
+		return err
+	case <-ctx.Done():
+		return ctx.Err()
+	}
+}

+ 180 - 0
server-go/internal/db/migrate_node.go

@@ -0,0 +1,180 @@
+// migrate_node.go — MIGRACIÓN desde el backend Node (SPEC §12, corazón del
+// refactor). El esquema Go es idéntico al de Node (mismo SQL literal), así
+// que la "importación" es preservación in situ:
+//
+//  1. Detección: el fichero existe y tiene las tablas firma de Node
+//     (users, sessions, kv) sin el marcador de migración ya aplicada.
+//  2. Backup atómico (checkpoint TRUNCATE + copia a fichero temporal +
+//     rename) ANTES de tocar nada: netpulse.db.bak-<timestamp>.
+//  3. Importación preservando: users (hashes bcrypt $2a/$2b portables),
+//     kv COMPLETO (session_secret incluido → las sesiones vivas siguen
+//     válidas, SIN forzar re-login), sessions vivas, routers (routerstore
+//     persiste en la propia tabla routers de SQLite — nada externo que
+//     importar), device_attrib, metrics/adguard_stats (epochs en MS, no se
+//     tocan), y login_attempts RESETEADO (efímero).
+//  4. Log claro de qué se importó y cuántas filas.
+//
+// El marcador kv `go_migration` evita re-migrar en cada arranque (repetir el
+// reset de login_attempts rompería la persistencia del rate-limit, que en
+// Node sobrevive a reinicios). Es un detalle interno no observable por la API.
+package db
+
+import (
+	"database/sql"
+	"fmt"
+	"io"
+	"log"
+	"os"
+	"time"
+)
+
+// migrationMarkerKey es la clave kv que marca la migración ya hecha.
+const migrationMarkerKey = "go_migration"
+
+// MigrationReport resume lo importado (para el log de arranque).
+type MigrationReport struct {
+	BackupPath         string
+	Users              int
+	Sessions           int // vivas (expires_at > ahora)
+	KV                 int
+	Routers            int
+	DeviceAttrib       int
+	Metrics            int
+	AdguardStats       int
+	LoginAttemptsReset int
+}
+
+// Log emite el resumen de migración (formato [netpulse] …).
+func (r *MigrationReport) Log() {
+	log.Printf("[netpulse] migración Node→Go: backup en %s", r.BackupPath)
+	log.Printf("[netpulse] migración Node→Go: importados users=%d sessions_vivas=%d kv=%d routers=%d device_attrib=%d metrics=%d adguard_stats=%d · login_attempts reseteado (%d filas)",
+		r.Users, r.Sessions, r.KV, r.Routers, r.DeviceAttrib, r.Metrics, r.AdguardStats, r.LoginAttemptsReset)
+}
+
+// MigrateNodeDB inspecciona dbPath y, si es una DB Node sin migrar, hace
+// backup y la importa. Devuelve nil si no hay nada que migrar (instalación
+// nueva o migración ya aplicada).
+func MigrateNodeDB(dbPath string) (*MigrationReport, error) {
+	st, err := os.Stat(dbPath)
+	if err != nil || st.Size() == 0 {
+		return nil, nil // instalación nueva
+	}
+
+	sqldb, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)")
+	if err != nil {
+		return nil, err
+	}
+	defer sqldb.Close()
+	sqldb.SetMaxOpenConns(1)
+
+	// Detección del esquema Node: tablas firma presentes.
+	if !hasTable(sqldb, "users") || !hasTable(sqldb, "sessions") || !hasTable(sqldb, "kv") {
+		log.Printf("[netpulse] aviso: %s existe pero no parece una DB de NetPulse; se continúa sin migración", dbPath)
+		return nil, nil
+	}
+	// ¿Ya migrada?
+	var marker string
+	if err := sqldb.QueryRow("SELECT value FROM kv WHERE key = ?", migrationMarkerKey).Scan(&marker); err == nil && marker != "" {
+		return nil, nil
+	}
+
+	// 1) Consolida el WAL en el fichero principal y cierra antes de copiar.
+	if _, err := sqldb.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
+		return nil, fmt.Errorf("checkpoint pre-backup: %w", err)
+	}
+
+	// 2) Backup atómico: copia a temporal + rename, ANTES de modificar la DB.
+	ts := time.Now().Format("20060102-150405")
+	backupPath := fmt.Sprintf("%s.bak-%s", dbPath, ts)
+	if err := atomicCopy(dbPath, backupPath); err != nil {
+		return nil, fmt.Errorf("backup: %w", err)
+	}
+
+	rep := &MigrationReport{BackupPath: backupPath}
+
+	// 3) Conteos para el log (qué se importa y cuántas filas).
+	rep.Users = countRows(sqldb, "users")
+	rep.Sessions = countWhere(sqldb, "sessions", "expires_at > ?", NowMS())
+	rep.KV = countRows(sqldb, "kv")
+	rep.Routers = countRows(sqldb, "routers")
+	rep.DeviceAttrib = countRows(sqldb, "device_attrib")
+	rep.Metrics = countRows(sqldb, "metrics")
+	rep.AdguardStats = countRows(sqldb, "adguard_stats")
+
+	// 4) login_attempts es efímero: se resetea.
+	res, err := sqldb.Exec("DELETE FROM login_attempts")
+	if err == nil {
+		n, _ := res.RowsAffected()
+		rep.LoginAttemptsReset = int(n)
+	}
+
+	// 5) Marcador de migración aplicada (interno, no observable por la API).
+	if _, err := sqldb.Exec(
+		"INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+		migrationMarkerKey, time.Now().Format(time.RFC3339),
+	); err != nil {
+		return nil, fmt.Errorf("marcador de migración: %w", err)
+	}
+
+	return rep, nil
+}
+
+// hasTable comprueba existencia en sqlite_master.
+func hasTable(db *sql.DB, name string) bool {
+	var n int
+	if err := db.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?", name).Scan(&n); err != nil {
+		return false
+	}
+	return n > 0
+}
+
+func countRows(db *sql.DB, table string) int {
+	if !hasTable(db, table) {
+		return 0
+	}
+	var n int
+	if err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", table)).Scan(&n); err != nil {
+		return 0
+	}
+	return n
+}
+
+func countWhere(db *sql.DB, table, where string, args ...any) int {
+	if !hasTable(db, table) {
+		return 0
+	}
+	var n int
+	if err := db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE %s", table, where), args...).Scan(&n); err != nil {
+		return 0
+	}
+	return n
+}
+
+// atomicCopy copia src→dst vía fichero temporal + rename (misma partición).
+func atomicCopy(src, dst string) error {
+	in, err := os.Open(src)
+	if err != nil {
+		return err
+	}
+	defer in.Close()
+	tmp := dst + ".tmp"
+	out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
+	if err != nil {
+		return err
+	}
+	if _, err := io.Copy(out, in); err != nil {
+		out.Close()
+		os.Remove(tmp)
+		return err
+	}
+	if err := out.Sync(); err != nil {
+		out.Close()
+		os.Remove(tmp)
+		return err
+	}
+	if err := out.Close(); err != nil {
+		os.Remove(tmp)
+		return err
+	}
+	return os.Rename(tmp, dst)
+}

+ 208 - 0
server-go/internal/db/migrate_node_test.go

@@ -0,0 +1,208 @@
+// migrate_node_test.go — migración Node→Go con fixture: DB creada con el SQL
+// literal del db.js de Node (esquema + columnas migradas) y datos de verdad.
+package db_test
+
+import (
+	"database/sql"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	_ "modernc.org/sqlite"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// nodeSchemaDDL es el DDL literal de src/db.js:20-85 + las 3 migraciones
+// (columnas ua, user_id, language) que una DB Node real ya tiene aplicadas.
+const nodeSchemaDDL = `
+CREATE TABLE sessions (id TEXT PRIMARY KEY, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, ua TEXT);
+CREATE TABLE login_attempts (ip TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, locked_until INTEGER DEFAULT 0);
+CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT);
+CREATE TABLE metrics (router_id TEXT NOT NULL, ts INTEGER NOT NULL, cpu REAL, ram REAL, temp REAL, latency_ms REAL, rx_bps REAL, tx_bps REAL);
+CREATE INDEX idx_metrics_router_ts ON metrics(router_id, ts);
+CREATE TABLE adguard_stats (ts INTEGER NOT NULL, queries INTEGER, blocked INTEGER);
+CREATE INDEX idx_adguard_ts ON adguard_stats(ts);
+CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, pass_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', created_at INTEGER NOT NULL);
+CREATE TABLE device_attrib (mac TEXT PRIMARY KEY, router_id TEXT, band TEXT, signal_dbm INTEGER, last_seen INTEGER NOT NULL);
+CREATE TABLE routers (id TEXT PRIMARY KEY, name TEXT, host TEXT NOT NULL, type TEXT NOT NULL DEFAULT 'openwrt', is_gateway INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL);
+ALTER TABLE sessions ADD COLUMN user_id INTEGER;
+ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto';
+`
+
+const fixtureSecret = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+const fixturePassword = "n0de-p4ss"
+const fixtureSessionID = "11111111-2222-4333-8444-555555555555"
+
+// buildNodeFixture crea una DB Node en dir con: admin bcrypt, kv completo,
+// sesión viva, routers, device_attrib, metrics, adguard_stats y login_attempts.
+func buildNodeFixture(t *testing.T, dir string) string {
+	t.Helper()
+	dbPath := filepath.Join(dir, "netpulse.db")
+	sqldb, err := sql.Open("sqlite", dbPath)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer sqldb.Close()
+	if _, err := sqldb.Exec("PRAGMA journal_mode = WAL"); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := sqldb.Exec(nodeSchemaDDL); err != nil {
+		t.Fatalf("schema fixture: %v", err)
+	}
+	hash, err := auth.HashPassword(fixturePassword)
+	if err != nil {
+		t.Fatal(err)
+	}
+	now := db.NowMS()
+	stmts := []struct {
+		q    string
+		args []any
+	}{
+		{"INSERT INTO users (username, pass_hash, role, created_at, language) VALUES ('admin', ?, 'admin', ?, 'es')", []any{hash, now}},
+		{"INSERT INTO kv (key, value) VALUES ('session_secret', ?)", []any{fixtureSecret}},
+		{"INSERT INTO kv (key, value) VALUES ('attrib_v2', '1')", nil},
+		{"INSERT INTO kv (key, value) VALUES ('adguard_host', '192.168.8.1')", nil},
+		{"INSERT INTO kv (key, value) VALUES ('auth_pass_hash', '$2a$10$legacydeadbeef')", nil}, // legacy muerto: no debe romper
+		// Sesión viva (30 d) del admin — debe seguir válida tras la migración.
+		{"INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES (?, ?, ?, 'NodeAgent/1.0', 1)", []any{fixtureSessionID, now, now + 30*24*3600*1000}},
+		{"INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES ('flint2', 'Gateway', '192.168.8.1', 'glinet', 1, ?)", []any{now}},
+		{"INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES ('AA:BB:CC:DD:EE:FF', 'flint2', '5 GHz', -50, ?)", []any{now}},
+		{"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES ('flint2', ?, 23, 41, 54, 8, 84000000, 12600000)", []any{now}},
+		{"INSERT INTO adguard_stats (ts, queries, blocked) VALUES (?, 84312, 15687)", []any{now}},
+		{"INSERT INTO login_attempts (ip, attempts, locked_until) VALUES ('1.2.3.4', 7, ?)", []any{now + 300000}},
+	}
+	for _, s := range stmts {
+		if _, err := sqldb.Exec(s.q, s.args...); err != nil {
+			t.Fatalf("fixture %q: %v", s.q, err)
+		}
+	}
+	if _, err := sqldb.Exec("PRAGMA wal_checkpoint(TRUNCATE)"); err != nil {
+		t.Fatal(err)
+	}
+	return dbPath
+}
+
+func TestMigrateNodeDB(t *testing.T) {
+	dir := t.TempDir()
+	dbPath := buildNodeFixture(t, dir)
+
+	rep, err := db.MigrateNodeDB(dbPath)
+	if err != nil {
+		t.Fatalf("migración: %v", err)
+	}
+	if rep == nil {
+		t.Fatal("debe detectar la DB Node y migrar")
+	}
+	// Conteos del informe
+	if rep.Users != 1 || rep.Sessions != 1 || rep.Routers != 1 || rep.DeviceAttrib != 1 ||
+		rep.Metrics != 1 || rep.AdguardStats != 1 || rep.LoginAttemptsReset != 1 {
+		t.Fatalf("reporte: %+v", rep)
+	}
+	if rep.KV != 4 {
+		t.Fatalf("kv: %+v", rep)
+	}
+	// Backup existe y es una SQLite válida con los datos
+	if _, err := os.Stat(rep.BackupPath); err != nil {
+		t.Fatalf("backup: %v", err)
+	}
+	if !strings.Contains(filepath.Base(rep.BackupPath), "netpulse.db.bak-") {
+		t.Fatalf("nombre de backup: %s", rep.BackupPath)
+	}
+	bak, err := sql.Open("sqlite", rep.BackupPath+"?mode=ro")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer bak.Close()
+	var n int
+	if err := bak.QueryRow("SELECT COUNT(*) FROM users").Scan(&n); err != nil || n != 1 {
+		t.Fatalf("backup users: %v n=%d", err, n)
+	}
+	// El backup conserva la fila de login_attempts (copia previa al reset).
+	if err := bak.QueryRow("SELECT COUNT(*) FROM login_attempts").Scan(&n); err != nil || n != 1 {
+		t.Fatalf("backup login_attempts: %v n=%d", err, n)
+	}
+
+	// La DB migrada: login_attempts reseteada, datos preservados, marcador puesto.
+	d, err := db.Open(dir)
+	if err != nil {
+		t.Fatalf("open migrada: %v", err)
+	}
+	defer d.Close()
+	if err := d.QueryRow("SELECT COUNT(*) FROM login_attempts").Scan(&n); err != nil || n != 0 {
+		t.Fatalf("login_attempts debe quedar reseteada: %v n=%d", err, n)
+	}
+	var secret string
+	if err := d.QueryRow("SELECT value FROM kv WHERE key = 'session_secret'").Scan(&secret); err != nil || secret != fixtureSecret {
+		t.Fatalf("session_secret preservado: %v %q", err, secret)
+	}
+	if err := d.QueryRow("SELECT COUNT(*) FROM sessions WHERE id = ?", fixtureSessionID).Scan(&n); err != nil || n != 1 {
+		t.Fatalf("sesión viva preservada: %v n=%d", err, n)
+	}
+	if err := d.QueryRow("SELECT COUNT(*) FROM routers WHERE id = 'flint2' AND is_gateway = 1").Scan(&n); err != nil || n != 1 {
+		t.Fatalf("routers preservados: %v n=%d", err, n)
+	}
+	var lang string
+	if err := d.QueryRow("SELECT language FROM users WHERE username = 'admin'").Scan(&lang); err != nil || lang != "es" {
+		t.Fatalf("language preservado: %v %q", err, lang)
+	}
+
+	// Idempotencia: una segunda migración no hace nada (el rate-limit
+	// persistente de Node no se borra en cada arranque).
+	rep2, err := db.MigrateNodeDB(dbPath)
+	if err != nil || rep2 != nil {
+		t.Fatalf("segunda migración debe ser no-op: %v %+v", err, rep2)
+	}
+}
+
+// TestMigrationLoginAndSession: el usuario importado hace login con su
+// password y la sesión importada sigue válida (SIN re-login forzado).
+func TestMigrationLoginAndSession(t *testing.T) {
+	dir := t.TempDir()
+	buildNodeFixture(t, dir)
+
+	d, err := db.Open(dir) // dispara la migración
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer d.Close()
+
+	cfg := &config.Config{AuthUser: "admin", AuthPass: fixturePassword, CookieSecure: "auto"}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if secret != fixtureSecret {
+		t.Fatal("el secret debe ser el importado de kv (no regenerado)")
+	}
+	// EnsureUsers NO re-siembra (ya hay usuarios).
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatal(err)
+	}
+	var n int
+	_ = d.QueryRow("SELECT COUNT(*) FROM users").Scan(&n)
+	if n != 1 {
+		t.Fatalf("users: %d (no debe duplicar el admin)", n)
+	}
+
+	// 1) Login con la password de la época Node (hash bcrypt $2a portable).
+	login := auth.HandleLogin(d, secret, httptest.NewRequest("POST", "/api/auth/login", nil), "admin", fixturePassword)
+	if login == nil {
+		t.Fatal("el usuario importado debe poder hacer login con su password")
+	}
+	if auth.HandleLogin(d, secret, httptest.NewRequest("POST", "/api/auth/login", nil), "admin", "otra-cosa") != nil {
+		t.Fatal("password incorrecta debe fallar")
+	}
+
+	// 2) La sesión importada sigue válida: cookie firmada con el secret
+	// importado autentica como el admin (sin re-login).
+	signed := auth.SignSessionID(secret, fixtureSessionID)
+	sess := auth.GetSession(d, auth.VerifySessionCookie(secret, signed))
+	if sess == nil || !sess.UserID.Valid || sess.UserID.Int64 != 1 {
+		t.Fatalf("sesión importada inválida: %+v", sess)
+	}
+}

+ 323 - 0
server-go/internal/discover/discover.go

@@ -0,0 +1,323 @@
+// Package discover — descubrimiento de routers candidatos en la LAN
+// (paridad src/discover.js, SPEC §7.7):
+//  1. Subred /24 derivada del gateway por defecto (`ip route`).
+//  2. Barrido TCP del puerto 22 en los 254 hosts (concurrencia 100; NO ping).
+//  3. Firma OpenWrt: POST http://<ip>/ubus (cualquier JSON-RPC, incluso
+//     "access denied", delata uhttpd+ubus; GL.iNet redirige a su UI → firma
+//     gl-ui por https).
+//  4. Probe SSH con la clave propia → {authorized, model}.
+// Caché de 60 s (force=1 la ignora).
+package discover
+
+import (
+	"bytes"
+	"crypto/tls"
+	"database/sql"
+	"io"
+	"net"
+	"net/http"
+	"os/exec"
+	"regexp"
+	"sort"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+)
+
+const (
+	cacheMS      = 60_000
+	tcpTimeout   = 800 * time.Millisecond
+	httpTimeout  = 1500 * time.Millisecond
+	sshTimeout   = 4 * time.Second
+	scanWorkers  = 100
+	probeWorkers = 16
+)
+
+// Result es un candidato a router.
+type Result struct {
+	Host       string  `json:"host"`
+	IsGateway  bool    `json:"isGateway"`
+	Authorized bool    `json:"authorized"`
+	Model      *string `json:"model"`
+	Configured bool    `json:"configured"`
+}
+
+// Response es la respuesta de /api/config/discover.
+type Response struct {
+	At      int64    `json:"at,omitempty"` // la respuesta no_gateway de Node NO incluye `at`
+	Subnet  *string  `json:"subnet"`
+	Results []Result `json:"results"`
+	Cached  bool     `json:"cached"`
+	Error   string   `json:"error,omitempty"`
+}
+
+var (
+	cacheMu sync.Mutex
+	cache   Response
+)
+
+// tcpOpen: true si el puerto TCP responde antes del timeout.
+func tcpOpen(host string, port int, timeout time.Duration) bool {
+	conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, itoa(port)), timeout)
+	if err != nil {
+		return false
+	}
+	_ = conn.Close()
+	return true
+}
+
+func itoa(n int) string {
+	var buf [4]byte
+	i := len(buf)
+	for n > 0 {
+		i--
+		buf[i] = byte('0' + n%10)
+		n /= 10
+	}
+	return string(buf[i:])
+}
+
+// pool ejecuta fn sobre items con concurrencia limitada.
+func pool[T any](items []T, size int, fn func(T) *T) []*T {
+	out := make([]*T, len(items))
+	var idx int64
+	var mu sync.Mutex
+	var wg sync.WaitGroup
+	workers := size
+	if len(items) < workers {
+		workers = len(items)
+	}
+	for w := 0; w < workers; w++ {
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			for {
+				mu.Lock()
+				if idx >= int64(len(items)) {
+					mu.Unlock()
+					return
+				}
+				i := idx
+				idx++
+				mu.Unlock()
+				out[i] = fn(items[i])
+			}
+		}()
+	}
+	wg.Wait()
+	res := make([]*T, 0, len(out))
+	for _, r := range out {
+		if r != nil {
+			res = append(res, r)
+		}
+	}
+	return res
+}
+
+func httpClient() *http.Client {
+	return &http.Client{
+		Timeout: httpTimeout,
+		Transport: &http.Transport{
+			TLSClientConfig:     &tls.Config{InsecureSkipVerify: true}, // firma, no confianza
+			DisableKeepAlives:   true,
+			MaxConnsPerHost:     1,
+			TLSHandshakeTimeout: httpTimeout,
+		},
+		CheckRedirect: func(req *http.Request, via []*http.Request) error {
+			return http.ErrUseLastResponse // necesitamos el status crudo (301/302)
+		},
+	}
+}
+
+type probeResp struct {
+	status int
+	body   string
+}
+
+var ubusProbeBody = `{"jsonrpc":"2.0","id":1,"method":"call","params":["00000000000000000000000000000000","session","login",{"username":"netpulse-probe","password":""}]}`
+
+// postUbus: POST /ubus crudo (http u https) — {status, body} o nil.
+func postUbus(host string, useHTTPS bool) *probeResp {
+	scheme := "http"
+	port := "80"
+	if useHTTPS {
+		scheme = "https"
+		port = "443"
+	}
+	req, err := http.NewRequest("POST", scheme+"://"+host+":"+port+"/ubus", bytes.NewReader([]byte(ubusProbeBody)))
+	if err != nil {
+		return nil
+	}
+	req.Header.Set("Content-Type", "application/json")
+	res, err := httpClient().Do(req)
+	if err != nil {
+		return nil
+	}
+	defer res.Body.Close()
+	body, _ := io.ReadAll(io.LimitReader(res.Body, 8192))
+	return &probeResp{status: res.StatusCode, body: string(body)}
+}
+
+// getRoot: GET / (http/https) — {status, body} o nil.
+func getRoot(host string, useHTTPS bool) *probeResp {
+	scheme := "http"
+	port := "80"
+	if useHTTPS {
+		scheme = "https"
+		port = "443"
+	}
+	res, err := httpClient().Get(scheme + "://" + host + ":" + port + "/")
+	if err != nil {
+		return nil
+	}
+	defer res.Body.Close()
+	body, _ := io.ReadAll(io.LimitReader(res.Body, 16384))
+	return &probeResp{status: res.StatusCode, body: string(body)}
+}
+
+var glUIRe = regexp.MustCompile(`(?i)gl-ui|GL\.iNet|glinet`)
+
+// probeUbus: true si el host huele a OpenWrt/GL.iNet.
+func probeUbus(host string) bool {
+	isUbus := func(r *probeResp) bool {
+		return r != nil && (strings.Contains(r.body, "jsonrpc") || strings.Contains(r.body, "ubus_rpc_session"))
+	}
+	httpRes := postUbus(host, false)
+	if isUbus(httpRes) {
+		return true
+	}
+	if httpRes != nil && (httpRes.status == 301 || httpRes.status == 302 || httpRes.status == 307 || httpRes.status == 308) {
+		if isUbus(postUbus(host, true)) {
+			return true
+		}
+		if root := getRoot(host, true); root != nil && glUIRe.MatchString(root.body) {
+			return true
+		}
+	}
+	return false
+}
+
+// probeSsh prueba SSH con la clave propia; devuelve (authorized, model).
+func probeSsh(host, keyPath string) (bool, *string) {
+	args := append(sshkey.BaseArgs(keyPath),
+		"-o", "ConnectTimeout=2",
+		"-o", "ControlMaster=no",
+		"root@"+host,
+		"ubus call system board | jsonfilter -e @.model",
+	)
+	cmd := exec.Command("ssh", args...)
+	type result struct {
+		out []byte
+		err error
+	}
+	ch := make(chan result, 1)
+	go func() {
+		out, err := cmd.Output()
+		ch <- result{out, err}
+	}()
+	select {
+	case <-time.After(sshTimeout):
+		_ = cmd.Process.Kill()
+		return false, nil
+	case res := <-ch:
+		if res.err != nil {
+			return false, nil
+		}
+		model := strings.TrimSpace(string(res.out))
+		if model == "" {
+			return true, nil
+		}
+		return true, &model
+	}
+}
+
+// selfIPs: IPs propias del servidor (para excluirlas del barrido).
+func selfIPs() map[string]bool {
+	out, err := exec.Command("sh", "-c", `ip -o -4 addr show | grep -oP "inet \K[0-9.]+"`).Output()
+	ips := map[string]bool{}
+	if err != nil {
+		return ips
+	}
+	for _, l := range strings.Split(string(out), "\n") {
+		if l = strings.TrimSpace(l); l != "" {
+			ips[l] = true
+		}
+	}
+	return ips
+}
+
+// Routers escanea la LAN y devuelve candidatos (paridad discoverRouters).
+// db se usa solo para marcar los ya configurados.
+func Routers(db *sql.DB, keyPath string, force bool) Response {
+	cacheMu.Lock()
+	defer cacheMu.Unlock()
+	now := time.Now().UnixMilli()
+	if !force && now-cache.At < cacheMS {
+		c := cache
+		c.Cached = true
+		return c
+	}
+
+	gwIP := routerstore.DetectGatewayIP()
+	if gwIP == "" {
+		return Response{Subnet: nil, Results: []Result{}, Cached: false, Error: "no_gateway"}
+	}
+	parts := strings.Split(gwIP, ".")
+	prefix := strings.Join(parts[:3], ".")
+	subnet := prefix + ".0/24"
+
+	own := selfIPs()
+	hosts := make([]string, 0, 254)
+	for i := 1; i <= 254; i++ {
+		h := prefix + "." + itoa(i)
+		if !own[h] {
+			hosts = append(hosts, h)
+		}
+	}
+	alive := pool(hosts, scanWorkers, func(h string) *string {
+		if tcpOpen(h, 22, tcpTimeout) {
+			return &h
+		}
+		return nil
+	})
+
+	configured := map[string]bool{}
+	for _, r := range routerstore.ListRouters(db) {
+		configured[r.Host] = true
+	}
+	type candidate struct{ h string }
+	cands := make([]candidate, 0, len(alive))
+	for _, h := range alive {
+		cands = append(cands, candidate{*h})
+	}
+	found := pool(cands, probeWorkers, func(c candidate) *candidate {
+		if !probeUbus(c.h) {
+			return nil
+		}
+		return &c
+	})
+
+	results := make([]Result, 0, len(found))
+	for _, c := range found {
+		authorized, model := probeSsh(c.h, keyPath)
+		results = append(results, Result{
+			Host:       c.h,
+			IsGateway:  c.h == gwIP,
+			Authorized: authorized,
+			Model:      model,
+			Configured: configured[c.h],
+		})
+	}
+	sort.Slice(results, func(i, j int) bool {
+		if results[i].IsGateway != results[j].IsGateway {
+			return results[i].IsGateway
+		}
+		return results[i].Host < results[j].Host
+	})
+
+	cache = Response{At: now, Subnet: &subnet, Results: results, Cached: false}
+	return cache
+}

+ 70 - 0
server-go/internal/httpapi/auth.go

@@ -0,0 +1,70 @@
+// auth.go — POST /api/auth/login · POST /api/auth/logout · GET /api/auth/me
+// (paridad routes/auth.js).
+package httpapi
+
+import (
+	"net/http"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// handleLogin: 429 rate_limited (antes de validar nada) → 400 invalid_body →
+// 401 invalid_credentials → 204 + Set-Cookie (rotación de sesión).
+func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) {
+	if limited, retryAfterSec := auth.LoginRateLimited(s.db, r); limited {
+		writeJSON(w, http.StatusTooManyRequests, map[string]any{
+			"error":         "rate_limited",
+			"retryAfterSec": retryAfterSec,
+		})
+		return
+	}
+	var body struct {
+		Username *string `json:"username"`
+		Password *string `json:"password"`
+	}
+	if !readJSONBody(r, &body) || 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 }`)
+		return
+	}
+	result := auth.HandleLogin(s.db, s.secret, r, *body.Username, *body.Password)
+	if result == nil {
+		auth.RegisterLoginFail(s.db, r)
+		writeError(w, http.StatusUnauthorized, "invalid_credentials")
+		return
+	}
+	auth.LoginOk(s.db, r)
+	signed := auth.SignSessionID(s.secret, result.SessionID)
+	w.Header().Set("Set-Cookie", auth.BuildSessionCookie(s.cfg, r, signed, auth.SessionTTLMS/1000))
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// handleLogout: destruye la sesión y borra la cookie (204; SIN Secure).
+func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) {
+	auth.HandleLogout(s.db, s.secret, r)
+	w.Header().Set("Set-Cookie", auth.ClearSessionCookie)
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// handleMe: {user, role, language, mode} (language releído de users).
+func (s *server) handleMe(mode string) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		user := auth.UserFromContext(r.Context())
+		if user == nil {
+			writeError(w, http.StatusUnauthorized, "unauthorized")
+			return
+		}
+		language := "auto"
+		var lang *string
+		if err := s.db.QueryRow("SELECT language FROM users WHERE id = ?", user.ID).Scan(&lang); err == nil && lang != nil {
+			language = *lang
+		}
+		writeJSON(w, http.StatusOK, map[string]any{
+			"user":     user.Username,
+			"role":     user.Role,
+			"language": language,
+			"mode":     mode,
+		})
+	}
+}

+ 221 - 0
server-go/internal/httpapi/config.go

@@ -0,0 +1,221 @@
+// config.go — rutas /api/config/* (paridad src/routes/config.js, SPEC §2.17):
+// CRUD de routers (tabla `routers`), clave SSH propia del servidor,
+// descubrimiento de la LAN y credenciales AdGuard GL.iNet (kv; la contraseña
+// NUNCA se devuelve). Tras cada mutación se sincroniza el adapter
+// (SetRouters) sin reiniciar.
+package httpapi
+
+import (
+	"database/sql"
+	"net/http"
+	"regexp"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/discover"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+)
+
+var hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
+
+// registerConfigRoutes registra las rutas /api/config/* en el mux.
+func (s *server) registerConfigRoutes(mux *http.ServeMux) {
+	mux.HandleFunc("GET /api/config/sshkey", s.handleGetSSHKey)
+	mux.HandleFunc("GET /api/config/discover", s.handleDiscover)
+	mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
+	mux.HandleFunc("POST /api/config/routers", s.handleAddConfigRouter)
+	mux.HandleFunc("DELETE /api/config/routers/{id}", s.handleDeleteConfigRouter)
+	mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
+	mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
+}
+
+// syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
+func (s *server) syncRouters() {
+	if s.adapter != nil {
+		s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
+	}
+}
+
+// GET /api/config/sshkey — clave pública propia para autorizar en routers.
+func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
+	key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
+	if key == nil {
+		writeError(w, http.StatusInternalServerError, "no_key")
+		return
+	}
+	writeJSON(w, http.StatusOK, key)
+}
+
+// GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
+func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
+	result := discover.Routers(s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
+	writeJSON(w, http.StatusOK, result)
+}
+
+// GET /api/config/routers — lista configurada (no el estado sondeado).
+func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
+	writeJSON(w, http.StatusOK, map[string]any{"routers": routerstore.ListRouters(s.db.DB)})
+}
+
+type routerInput struct {
+	Name    *string `json:"name"`
+	Host    *string `json:"host"`
+	Type    string  `json:"type"`
+	Gateway bool    `json:"gateway"`
+}
+
+// validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
+// trimmeado o "" + mensaje de error.
+func validateHost(host string) (string, string) {
+	h := strings.TrimSpace(host)
+	if len(h) < 1 {
+		return "", "String must contain at least 1 character(s)"
+	}
+	if len(h) > 253 {
+		return "", "String must contain at most 253 character(s)"
+	}
+	if !hostRe.MatchString(h) {
+		return "", "host debe ser una IP o hostname válido"
+	}
+	return h, ""
+}
+
+// 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")
+		return
+	}
+	// Orden de validación del schema zod: name, host, type
+	name := ""
+	if in.Name != nil {
+		name = strings.TrimSpace(*in.Name)
+		if len(name) < 1 {
+			writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
+			return
+		}
+		if len(name) > 60 {
+			writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
+			return
+		}
+	}
+	if in.Host == nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Required")
+		return
+	}
+	host, msg := validateHost(*in.Host)
+	if msg != "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", msg)
+		return
+	}
+	typ := in.Type
+	if typ == "" {
+		typ = "openwrt"
+	}
+	if typ != "glinet" && typ != "openwrt" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt'")
+		return
+	}
+	for _, rt := range routerstore.ListRouters(s.db.DB) {
+		if rt.Host == host {
+			writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
+			return
+		}
+	}
+	created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
+		Name: name, Host: host, Type: typ, IsGateway: in.Gateway,
+	})
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	s.syncRouters()
+	writeJSON(w, http.StatusCreated, map[string]any{"router": created})
+}
+
+// DELETE /api/config/routers/:id — 204 o 404.
+func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
+	if !routerstore.RemoveRouter(s.db.DB, r.PathValue("id")) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	s.syncRouters()
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
+
+func kvGet(db *sql.DB, key string) string {
+	var v string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
+		return ""
+	}
+	return v
+}
+
+// GET /api/config/adguard — {host, user ('root' por defecto), passSet}.
+func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
+	user := kvGet(s.db.DB, "adguard_user")
+	if user == "" {
+		user = "root"
+	}
+	writeJSON(w, http.StatusOK, map[string]any{
+		"host":    kvGet(s.db.DB, "adguard_host"),
+		"user":    user,
+		"passSet": kvGet(s.db.DB, "adguard_pass") != "",
+	})
+}
+
+type adguardInput struct {
+	Host     *string `json:"host"`
+	User     string  `json:"user"`
+	Password string  `json:"password"`
+}
+
+// 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")
+		return
+	}
+	if in.Host == nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Required")
+		return
+	}
+	host, msg := validateHost(*in.Host)
+	if msg != "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", msg)
+		return
+	}
+	user := strings.TrimSpace(in.User)
+	if user == "" {
+		user = "root"
+	}
+	if len(user) > 64 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
+		return
+	}
+	if len(in.Password) > 128 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
+		return
+	}
+	upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+	if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	if in.Password != "" {
+		if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 142 - 0
server-go/internal/httpapi/config_test.go

@@ -0,0 +1,142 @@
+// config_test.go — port de tests/routers.test.js: CRUD de /api/config/routers
+// (lista, alta, duplicado 409, validación 400, borrado 204/404) + sshkey.
+package httpapi_test
+
+import (
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+func doReq(t *testing.T, method, url, cookie, body string) *http.Response {
+	t.Helper()
+	var rdr io.Reader
+	if body != "" {
+		rdr = strings.NewReader(body)
+	}
+	req, err := http.NewRequest(method, url, rdr)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if body != "" {
+		req.Header.Set("Content-Type", "application/json")
+	}
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return res
+}
+
+// TestConfigRoutersCRUD replica routers.test.js.
+func TestConfigRoutersCRUD(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	// GET inicial: lista vacía (200)
+	res := doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("GET routers: %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	if _, ok := body["routers"].([]any); !ok {
+		t.Fatalf("routers no es lista: %v", body)
+	}
+
+	// POST: crea un router (201, {router})
+	res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"name":"Salón","host":"192.168.8.2","type":"openwrt"}`)
+	if res.StatusCode != 201 {
+		t.Fatalf("POST router: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	router := body["router"].(map[string]any)
+	if router["id"] != "salon" || router["name"] != "Salón" || router["is_gateway"] != false {
+		t.Fatalf("router creado: %v", router)
+	}
+
+	// POST gateway: is_gateway exclusivo
+	res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"host":"192.168.8.1","type":"glinet","gateway":true}`)
+	if res.StatusCode != 201 {
+		t.Fatalf("POST gateway: %d", res.StatusCode)
+	}
+	res = doReq(t, "GET", srv.URL+"/api/config/routers", cookie, "")
+	body = readJSON(t, res)
+	routers := body["routers"].([]any)
+	if len(routers) != 2 {
+		t.Fatalf("routers: %d", len(routers))
+	}
+	gwCount := 0
+	for _, r := range routers {
+		if r.(map[string]any)["is_gateway"] == true {
+			gwCount++
+		}
+	}
+	if gwCount != 1 {
+		t.Fatalf("gateways: %d", gwCount)
+	}
+
+	// POST duplicado → 409 duplicate_host
+	res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"host":"192.168.8.2"}`)
+	if res.StatusCode != 409 {
+		t.Fatalf("duplicado: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	if body["error"] != "duplicate_host" {
+		t.Fatalf("error: %v", body)
+	}
+
+	// POST host inválido → 400 invalid_input
+	res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"host":"no es un host"}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("host inválido: %d", res.StatusCode)
+	}
+
+	// POST type inválido → 400
+	res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"host":"192.168.8.9","type":"cisco"}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("type inválido: %d", res.StatusCode)
+	}
+
+	// POST JSON inválido → 400 invalid_json
+	res = doReq(t, "POST", srv.URL+"/api/config/routers", cookie, `{`)
+	if res.StatusCode != 400 {
+		t.Fatalf("json inválido: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	if body["error"] != "invalid_json" {
+		t.Fatalf("error: %v", body)
+	}
+
+	// DELETE existente → 204; repetir → 404
+	res = doReq(t, "DELETE", srv.URL+"/api/config/routers/salon", cookie, "")
+	if res.StatusCode != 204 {
+		t.Fatalf("DELETE: %d", res.StatusCode)
+	}
+	res = doReq(t, "DELETE", srv.URL+"/api/config/routers/salon", cookie, "")
+	if res.StatusCode != 404 {
+		t.Fatalf("DELETE 404: %d", res.StatusCode)
+	}
+
+	// GET sshkey → 200 {publicKey, fingerprint} (la clave se genera al vuelo)
+	res = doReq(t, "GET", srv.URL+"/api/config/sshkey", cookie, "")
+	// Sin clave generada en el DATA_DIR de test → 500 no_key; si existe
+	// ssh-keygen en el sistema la ruta la habría creado el arranque (no en
+	// tests) — aceptamos ambos y validamos el shape cuando hay clave.
+	if res.StatusCode == 200 {
+		body = readJSON(t, res)
+		if _, ok := body["publicKey"].(string); !ok {
+			t.Fatalf("sshkey: %v", body)
+		}
+	} else if res.StatusCode != 500 {
+		t.Fatalf("sshkey: %d", res.StatusCode)
+	}
+}

+ 257 - 0
server-go/internal/httpapi/data.go

@@ -0,0 +1,257 @@
+// data.go — rutas de datos (paridad routes/data.js). Paginación zod-coerce,
+// filtros literales y envelopes exactos.
+package httpapi
+
+import (
+	"math"
+	"net/http"
+	"strconv"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+)
+
+var bands = []string{"5 GHz", "2.4 GHz", "cable"}
+var severities = []string{"warn", "critical", "info", "ok"}
+
+func contains(list []string, v string) bool {
+	for _, x := range list {
+		if x == v {
+			return true
+		}
+	}
+	return false
+}
+
+// coercePage replica z.coerce.number().int().min(min).max(max): el valor debe
+// ser numérico y entero ("" → 0, "abc" → NaN → inválido).
+func coerceInt(raw string, def, min, max int64, hasDefault bool) (int64, bool) {
+	if raw == "" && hasDefault {
+		// zod: undefined → default; "" → Number("")=0 → inválido si min>0.
+		// La query de Go no distingue "?page=" de ausencia; r.URL.Query()
+		// devuelve [""] en ambos casos, tratado aquí por el llamador.
+		return def, true
+	}
+	f, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
+	if err != nil || math.IsNaN(f) || f != math.Trunc(f) {
+		return 0, false
+	}
+	n := int64(f)
+	if n < min || n > max {
+		return 0, false
+	}
+	return n, true
+}
+
+// parsePagination lee page/pageSize con semántica zod-coerce. hasParam
+// distingue ausencia (default) de "?page=" (→ 0 → inválido).
+func parsePagination(r *http.Request, defaultPageSize int64) (page, pageSize int64, ok bool) {
+	q := r.URL.Query()
+	page, pageSize = 1, defaultPageSize
+	if _, present := q["page"]; present {
+		raw := q.Get("page")
+		if raw == "" {
+			return 0, 0, false // Number("") = 0 < min
+		}
+		n, valid := coerceInt(raw, 1, 1, math.MaxInt64, false)
+		if !valid {
+			return 0, 0, false
+		}
+		page = n
+	}
+	if _, present := q["pageSize"]; present {
+		raw := q.Get("pageSize")
+		if raw == "" {
+			return 0, 0, false
+		}
+		n, valid := coerceInt(raw, defaultPageSize, 1, 1000, false)
+		if !valid {
+			return 0, 0, false
+		}
+		pageSize = n
+	}
+	return page, pageSize, true
+}
+
+// paginate: slice (page-1)*pageSize; items nunca null ([] si vacío).
+func paginate[T any](items []T, page, pageSize int64) map[string]any {
+	total := len(items)
+	start := (page - 1) * pageSize
+	var out []T
+	if start < int64(total) {
+		end := start + pageSize
+		if end > int64(total) {
+			end = int64(total)
+		}
+		out = items[start:end]
+	}
+	if out == nil {
+		out = []T{}
+	}
+	return map[string]any{"items": out, "total": total, "page": page, "pageSize": pageSize}
+}
+
+// handleOverview: último overview del poller o GetOverview en caliente.
+func (s *server) handleOverview(w http.ResponseWriter, r *http.Request) {
+	if s.lastOv != nil {
+		if ov := s.lastOv(); ov != nil {
+			writeJSON(w, http.StatusOK, ov)
+			return
+		}
+	}
+	ov, err := s.adapter.GetOverview(r.Context())
+	if err != nil || ov == nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	writeJSON(w, http.StatusOK, ov)
+}
+
+// handleRouters: {routers: [Router…]}.
+func (s *server) handleRouters(w http.ResponseWriter, r *http.Request) {
+	routers := s.adapter.GetRouters(r.Context())
+	if routers == nil {
+		routers = []adapters.Router{}
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"routers": routers})
+}
+
+// handleRouterDetail: RouterDetail o 404 {error:'not_found'}.
+func (s *server) handleRouterDetail(w http.ResponseWriter, r *http.Request) {
+	detail, err := s.adapter.GetRouterDetail(r.Context(), r.PathValue("id"))
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	if detail == nil {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	writeJSON(w, http.StatusOK, detail)
+}
+
+// handleDevices: filtros q/routerId/band/type/status + paginación.
+func (s *server) handleDevices(w http.ResponseWriter, r *http.Request) {
+	page, pageSize, ok := parsePagination(r, 50)
+	if !ok {
+		writeError(w, http.StatusBadRequest, "invalid_query", "page/pageSize inválidos")
+		return
+	}
+	q := r.URL.Query()
+	query := strings.ToLower(strings.TrimSpace(q.Get("q")))
+	if len([]rune(query)) > 100 {
+		query = string([]rune(query)[:100])
+	}
+	routerID := q.Get("routerId")
+	band := q.Get("band")
+	typ := q.Get("type")
+	status := q.Get("status")
+
+	if band != "" && !contains(bands, band) {
+		writeError(w, http.StatusBadRequest, "invalid_query", "band debe ser una de: "+strings.Join(bands, ", "))
+		return
+	}
+	if status != "" && status != "online" && status != "offline" {
+		writeError(w, http.StatusBadRequest, "invalid_query", "status debe ser online|offline")
+		return
+	}
+
+	items := s.adapter.GetDevices(r.Context())
+	filtered := make([]adapters.Device, 0, len(items))
+	for _, d := range items {
+		if routerID != "" && d.RouterID != routerID {
+			continue
+		}
+		if band != "" && d.Band != band {
+			continue
+		}
+		if typ != "" && d.Type != typ && d.Group != typ {
+			continue
+		}
+		if status == "online" && !d.Online {
+			continue
+		}
+		if status == "offline" && d.Online {
+			continue
+		}
+		if query != "" && !deviceMatches(d, query) {
+			continue
+		}
+		filtered = append(filtered, d)
+	}
+	writeJSON(w, http.StatusOK, paginate(filtered, page, pageSize))
+}
+
+// deviceMatches: substring (minúsculas) sobre name|hostname|ip|mac|manufacturer.
+func deviceMatches(d adapters.Device, query string) bool {
+	for _, v := range []string{d.Name, d.Hostname, d.IP, d.MAC, d.Manufacturer} {
+		if v != "" && strings.Contains(strings.ToLower(v), query) {
+			return true
+		}
+	}
+	return false
+}
+
+// handleAlerts: severity + paginación (default pageSize=20).
+func (s *server) handleAlerts(w http.ResponseWriter, r *http.Request) {
+	page, pageSize, ok := parsePagination(r, 20)
+	if !ok {
+		writeError(w, http.StatusBadRequest, "invalid_query", "page/pageSize inválidos")
+		return
+	}
+	severity := r.URL.Query().Get("severity")
+	if severity != "" && !contains(severities, severity) {
+		writeError(w, http.StatusBadRequest, "invalid_query", "severity debe ser una de: "+strings.Join(severities, ", "))
+		return
+	}
+	items := s.adapter.GetAlerts(r.Context())
+	filtered := make([]adapters.AlertEvent, 0, len(items))
+	for _, a := range items {
+		if severity != "" && a.Severity != severity {
+			continue
+		}
+		filtered = append(filtered, a)
+	}
+	writeJSON(w, http.StatusOK, paginate(filtered, page, pageSize))
+}
+
+// handleTopology: {routers, devices} sin paginar.
+func (s *server) handleTopology(w http.ResponseWriter, r *http.Request) {
+	routers := s.adapter.GetRouters(r.Context())
+	if routers == nil {
+		routers = []adapters.Router{}
+	}
+	devices := s.adapter.GetDevices(r.Context())
+	if devices == nil {
+		devices = []adapters.Device{}
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"routers": routers, "devices": devices})
+}
+
+// handleDawn: 503 {error:'unavailable'} si ningún router tiene DAWN.
+func (s *server) handleDawn(w http.ResponseWriter, r *http.Request) {
+	dawn, err := s.adapter.GetDawn(r.Context())
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	if dawn == nil {
+		writeError(w, http.StatusServiceUnavailable, "unavailable")
+		return
+	}
+	writeJSON(w, http.StatusOK, dawn)
+}
+
+// handleAdguardClients: 404 not_configured · 502 adguard_error.
+func (s *server) handleAdguardClients(w http.ResponseWriter, r *http.Request) {
+	clients, err := s.adapter.GetAdguardClients(r.Context())
+	if err != nil {
+		writeError(w, http.StatusBadGateway, "adguard_error", err.Error())
+		return
+	}
+	if clients == nil {
+		writeError(w, http.StatusNotFound, "not_configured")
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"clients": clients})
+}

+ 49 - 0
server-go/internal/httpapi/health.go

@@ -0,0 +1,49 @@
+// health.go — GET /api/health (público, contrato) y GET /health (SPEC §2.1/§2.2).
+package httpapi
+
+import (
+	"net/http"
+	"runtime"
+	"time"
+)
+
+// handleAPIHealth: {ok, version, mode, uptimeSec, db}.
+func (s *server) handleAPIHealth(mode string) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		dbOk := s.db.CheckHealth()
+		dbStatus := "ok"
+		if !dbOk {
+			dbStatus = "error"
+		}
+		writeJSON(w, http.StatusOK, map[string]any{
+			"ok":        dbOk,
+			"version":   Version,
+			"mode":      mode,
+			"uptimeSec": int64(time.Since(s.started).Seconds()),
+			"db":        dbStatus,
+		})
+	}
+}
+
+// handleHealth: {status, uptime (float segundos), memory:{rss, heap}, db}.
+// En Go los bytes salen de runtime.ReadMemStats: rss ≈ Sys (memoria obtenida
+// del SO) y heap ≈ HeapAlloc. Los valores absolutos cambian de lenguaje —
+// solo el shape es contrato (SPEC §2.2).
+func (s *server) handleHealth(w http.ResponseWriter, r *http.Request) {
+	dbOk := s.db.CheckHealth()
+	status, dbStatus := "ok", "connected"
+	if !dbOk {
+		status, dbStatus = "degraded", "error"
+	}
+	var mem runtime.MemStats
+	runtime.ReadMemStats(&mem)
+	writeJSON(w, http.StatusOK, map[string]any{
+		"status": status,
+		"uptime": time.Since(s.started).Seconds(),
+		"memory": map[string]any{
+			"rss":  mem.Sys,
+			"heap": mem.HeapAlloc,
+		},
+		"db": dbStatus,
+	})
+}

+ 713 - 0
server-go/internal/httpapi/httpapi_test.go

@@ -0,0 +1,713 @@
+// httpapi_test.go — tests de contrato de endpoints (port de tests/auth.test.js
+// y tests/users.test.js de Node + quirks de cache-control y SPA).
+package httpapi_test
+
+import (
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"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/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+type testServer struct {
+	*httptest.Server
+	db     *db.DB
+	secret string
+}
+
+// makeTestServer replica tests/helpers.js: app real con adapter demo stub y
+// DB temporal, config AUTH_USER=admin AUTH_PASS=test1234 DEMO_MODE=1.
+func makeTestServer(t *testing.T) *testServer {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test1234",
+		"DEMO_MODE": "1", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	secret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatalf("secret: %v", err)
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatalf("users: %v", err)
+	}
+	adapter := adapters.NewDemo()
+	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapter, Hub: hub, Secret: secret,
+		Started: time.Now(),
+	})
+	srv := httptest.NewServer(handler)
+	ts := &testServer{Server: srv, db: d, secret: secret}
+	t.Cleanup(func() {
+		srv.Close()
+		d.Close()
+	})
+	return ts
+}
+
+// loginCookie hace login y devuelve status + valor de la cookie (id.hmac) +
+// header Set-Cookie completo.
+func loginCookie(t *testing.T, base, username, password string, headers ...string) (int, string, string) {
+	t.Helper()
+	req, _ := http.NewRequest("POST", base+"/api/auth/login",
+		strings.NewReader(fmt.Sprintf(`{"username":%q,"password":%q}`, username, password)))
+	req.Header.Set("Content-Type", "application/json")
+	for i := 0; i+1 < len(headers); i += 2 {
+		req.Header.Set(headers[i], headers[i+1])
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("login: %v", err)
+	}
+	defer res.Body.Close()
+	io.Copy(io.Discard, res.Body)
+	setCookie := res.Header.Get("Set-Cookie")
+	cookie := ""
+	if m := strings.Index(setCookie, "session="); m >= 0 {
+		rest := setCookie[m+len("session="):]
+		if end := strings.Index(rest, ";"); end >= 0 {
+			cookie = rest[:end]
+		}
+	}
+	return res.StatusCode, cookie, setCookie
+}
+
+func get(t *testing.T, base, path, cookie string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest("GET", base+path, nil)
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("GET %s: %v", path, err)
+	}
+	return res
+}
+
+func readJSON(t *testing.T, res *http.Response) map[string]any {
+	t.Helper()
+	defer res.Body.Close()
+	var body map[string]any
+	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
+		t.Fatalf("json: %v", err)
+	}
+	return body
+}
+
+// ---------------------------------------------------------------------------
+// Port de tests/auth.test.js
+// ---------------------------------------------------------------------------
+
+func TestLoginIncorrecto401(t *testing.T) {
+	srv := makeTestServer(t)
+	status, cookie, _ := loginCookie(t, srv.URL, "admin", "wrong-pass")
+	if status != 401 {
+		t.Fatalf("status: got %d want 401", status)
+	}
+	if cookie != "" {
+		t.Fatal("login incorrecto no debe devolver cookie")
+	}
+}
+
+func TestLoginCorrectoYMe(t *testing.T) {
+	srv := makeTestServer(t)
+	status, cookie, setCookie := loginCookie(t, srv.URL, "admin", "test1234")
+	if status != 204 {
+		t.Fatalf("status: got %d want 204", status)
+	}
+	if cookie == "" {
+		t.Fatal("debe devolver cookie de sesión")
+	}
+	if !strings.Contains(setCookie, "HttpOnly") || !strings.Contains(setCookie, "SameSite=Lax") {
+		t.Fatalf("Set-Cookie sin HttpOnly/SameSite=Lax: %q", setCookie)
+	}
+	res := get(t, srv.URL, "/api/auth/me", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("me: got %d want 200", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "mode": "demo"}
+	for k, v := range want {
+		if body[k] != v {
+			t.Fatalf("me[%s]: got %v want %v (body=%v)", k, body[k], v, body)
+		}
+	}
+	if len(body) != len(want) {
+		t.Fatalf("me con claves extra: %v", body)
+	}
+}
+
+func TestOverviewProtegido(t *testing.T) {
+	srv := makeTestServer(t)
+	res := get(t, srv.URL, "/api/overview", "")
+	if res.StatusCode != 401 {
+		t.Fatalf("sin cookie: got %d want 401", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	if body["error"] != "unauthorized" {
+		t.Fatalf("error: %v", body)
+	}
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res2 := get(t, srv.URL, "/api/overview", cookie)
+	if res2.StatusCode != 200 {
+		t.Fatalf("con cookie: got %d want 200", res2.StatusCode)
+	}
+	ov := readJSON(t, res2)
+	// Shape del overview (claves del contrato)
+	for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "ts"} {
+		if _, ok := ov[k]; !ok {
+			t.Fatalf("overview sin clave %q", k)
+		}
+	}
+	if routers, ok := ov["routers"].([]any); !ok || len(routers) != 4 {
+		t.Fatalf("routers: %v", ov["routers"])
+	}
+	// ts en SEGUNDOS (no ms)
+	if ts, ok := ov["ts"].(float64); !ok || ts > 1e11 {
+		t.Fatalf("ts debe ser epoch en segundos: %v", ov["ts"])
+	}
+}
+
+func TestLogoutRevocaSesion(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	req, _ := http.NewRequest("POST", srv.URL+"/api/auth/logout", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("logout: got %d want 204", res.StatusCode)
+	}
+	if sc := res.Header.Get("Set-Cookie"); sc != "session=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" {
+		t.Fatalf("Set-Cookie de borrado literal: %q", sc)
+	}
+	res2 := get(t, srv.URL, "/api/overview", cookie)
+	res2.Body.Close()
+	if res2.StatusCode != 401 {
+		t.Fatalf("sesión revocada: got %d want 401", res2.StatusCode)
+	}
+}
+
+func TestRateLimitQuintoFallo(t *testing.T) {
+	srv := makeTestServer(t)
+	hdr := []string{"X-Forwarded-For", "10.9.9.9"}
+	for i := 1; i <= 5; i++ {
+		status, _, _ := loginCookie(t, srv.URL, "admin", "nope", hdr...)
+		if status != 401 {
+			t.Fatalf("fallo %d: got %d want 401", i, status)
+		}
+	}
+	// 6º intento: bloqueado (5 min)
+	req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(`{"username":"admin","password":"nope"}`))
+	req.Header.Set("X-Forwarded-For", "10.9.9.9")
+	res, _ := http.DefaultClient.Do(req)
+	if res.StatusCode != 429 {
+		t.Fatalf("6º intento: got %d want 429", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	if body["error"] != "rate_limited" {
+		t.Fatalf("error: %v", body)
+	}
+	retry, ok := body["retryAfterSec"].(float64)
+	if !ok || retry <= 0 || retry > 300 {
+		t.Fatalf("retryAfterSec: %v", body)
+	}
+	// Incluso con la password correcta sigue bloqueado.
+	status, _, _ := loginCookie(t, srv.URL, "admin", "test1234", hdr...)
+	if status != 429 {
+		t.Fatalf("bloqueado con password correcta: got %d want 429", status)
+	}
+	// Persistencia en SQLite.
+	var attempts int
+	var lockedUntil int64
+	if err := srv.db.QueryRow("SELECT attempts, locked_until FROM login_attempts WHERE ip = '10.9.9.9'").
+		Scan(&attempts, &lockedUntil); err != nil {
+		t.Fatal(err)
+	}
+	if attempts < 5 || lockedUntil <= db.NowMS() {
+		t.Fatalf("login_attempts: attempts=%d locked_until=%d", attempts, lockedUntil)
+	}
+}
+
+func TestLoginInvalidBody400(t *testing.T) {
+	srv := makeTestServer(t)
+	for _, payload := range []string{`not-json`, `{}`, `{"username":"admin"}`, `{"username":1,"password":"x"}`} {
+		req, _ := http.NewRequest("POST", srv.URL+"/api/auth/login", strings.NewReader(payload))
+		res, _ := http.DefaultClient.Do(req)
+		body := readJSON(t, res)
+		if res.StatusCode != 400 || body["error"] != "invalid_body" {
+			t.Fatalf("payload %s: got %d %v", payload, res.StatusCode, body)
+		}
+		if body["message"] != `Se esperaba { "username": string, "password": string }` {
+			t.Fatalf("message: %v", body["message"])
+		}
+	}
+}
+
+// ---------------------------------------------------------------------------
+// Port de tests/users.test.js
+// ---------------------------------------------------------------------------
+
+func TestUsersCRUD(t *testing.T) {
+	srv := makeTestServer(t)
+
+	// 401 sin sesión
+	res := get(t, srv.URL, "/api/users", "")
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("sin sesión: got %d want 401", res.StatusCode)
+	}
+
+	// Admin: lista con 1 usuario
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res = get(t, srv.URL, "/api/users", adminCookie)
+	body := readJSON(t, res)
+	users := body["users"].([]any)
+	if len(users) != 1 || users[0].(map[string]any)["username"] != "admin" {
+		t.Fatalf("users: %v", users)
+	}
+
+	// Alta 201
+	req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"secreto1"}`))
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	if res.StatusCode != 201 {
+		b, _ := io.ReadAll(res.Body)
+		res.Body.Close()
+		t.Fatalf("alta: got %d want 201 (%s)", res.StatusCode, b)
+	}
+	res.Body.Close()
+
+	// Duplicado 409
+	req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"otra1234"}`))
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 409 || body["error"] != "duplicate_user" {
+		t.Fatalf("duplicado: got %d %v", res.StatusCode, body)
+	}
+
+	// Username inválido 400
+	req, _ = http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"mal usuario","password":"xxxxxxxxxx"}`))
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 400 || body["error"] != "invalid_input" {
+		t.Fatalf("username inválido: got %d %v", res.StatusCode, body)
+	}
+	if body["message"] != "usuario debe ser alfanumérico (.-_ permitidos)" {
+		t.Fatalf("message: %v", body["message"])
+	}
+
+	// El usuario creado puede loguear
+	status, anaCookie, _ := loginCookie(t, srv.URL, "ana", "secreto1")
+	if status != 204 {
+		t.Fatalf("login ana: got %d", status)
+	}
+
+	// ID de ana
+	res = get(t, srv.URL, "/api/users", adminCookie)
+	body = readJSON(t, res)
+	var anaID, adminID float64
+	for _, u := range body["users"].([]any) {
+		m := u.(map[string]any)
+		if m["username"] == "ana" {
+			anaID = m["id"].(float64)
+		}
+		if m["username"] == "admin" {
+			adminID = m["id"].(float64)
+		}
+	}
+
+	// Cambio de password → 204 e invalida la sesión de ana
+	req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/password", srv.URL, anaID), strings.NewReader(`{"password":"nueva-clave-9"}`))
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("set password: got %d want 204", res.StatusCode)
+	}
+	res = get(t, srv.URL, "/api/auth/me", anaCookie)
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("sesión vieja de ana: got %d want 401", res.StatusCode)
+	}
+	status, anaCookie, _ = loginCookie(t, srv.URL, "ana", "nueva-clave-9")
+	if status != 204 {
+		t.Fatalf("re-login ana: got %d", status)
+	}
+
+	// No-admin → 403 en /api/users
+	res = get(t, srv.URL, "/api/users", anaCookie)
+	body = readJSON(t, res)
+	if res.StatusCode != 403 || body["error"] != "forbidden" {
+		t.Fatalf("no-admin: got %d %v", res.StatusCode, body)
+	}
+
+	// Pero SÍ puede cambiar su idioma (fuera del gate admin)
+	req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"es"}`))
+	req.Header.Set("Cookie", "session="+anaCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("me/language no-admin: got %d want 204", res.StatusCode)
+	}
+	res = get(t, srv.URL, "/api/auth/me", anaCookie)
+	body = readJSON(t, res)
+	if body["language"] != "es" {
+		t.Fatalf("language: %v", body)
+	}
+	// Idioma inválido → 400 literal
+	req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/language", strings.NewReader(`{"language":"fr"}`))
+	req.Header.Set("Cookie", "session="+anaCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 400 || body["message"] != "language debe ser auto|es|en" {
+		t.Fatalf("language inválido: got %d %v", res.StatusCode, body)
+	}
+
+	// Rol via QUERY STRING (quirk): ana pasa a admin
+	req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=admin", srv.URL, anaID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("set role: got %d want 204", res.StatusCode)
+	}
+	// La sesión de ana quedó invalidada por el cambio de rol
+	res = get(t, srv.URL, "/api/auth/me", anaCookie)
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("sesión ana tras cambio de rol: got %d want 401", res.StatusCode)
+	}
+	// Rol inválido → 400
+	req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=super", srv.URL, anaID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 400 || body["message"] != "role debe ser admin|user" {
+		t.Fatalf("role inválido: got %d %v", res.StatusCode, body)
+	}
+	// No puedes cambiar tu propio rol
+	req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, adminID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 400 || body["error"] != "cannot_change_self" {
+		t.Fatalf("self role: got %d %v", res.StatusCode, body)
+	}
+	// Degradar a la otra admin (ana) dejando 1 admin: OK; degradar de nuevo → last_admin
+	req, _ = http.NewRequest("PUT", fmt.Sprintf("%s/api/users/%v/role?role=user", srv.URL, anaID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("degradar ana: got %d want 204", res.StatusCode)
+	}
+
+	// No se puede borrar a sí mismo
+	req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, adminID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 400 || body["error"] != "cannot_delete_self" {
+		t.Fatalf("self delete: got %d %v", res.StatusCode, body)
+	}
+	// Borrado 204 y luego 404
+	req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("delete: got %d want 204", res.StatusCode)
+	}
+	req, _ = http.NewRequest("DELETE", fmt.Sprintf("%s/api/users/%v", srv.URL, anaID), nil)
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ = http.DefaultClient.Do(req)
+	body = readJSON(t, res)
+	if res.StatusCode != 404 || body["error"] != "not_found" {
+		t.Fatalf("delete 2: got %d %v", res.StatusCode, body)
+	}
+}
+
+// ---------------------------------------------------------------------------
+// Quirks de cache-control y datos
+// ---------------------------------------------------------------------------
+
+func TestCacheControl(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	cases := []struct {
+		path    string
+		noStore bool
+	}{
+		{"/api/health", false},
+		{"/api/auth/me", false},
+		{"/api/overview", true},
+		{"/api/users", true},
+		{"/api/devices", true},
+		{"/api/alerts", true},
+		{"/api/topology", true},
+	}
+	for _, c := range cases {
+		res := get(t, srv.URL, c.path, cookie)
+		res.Body.Close()
+		got := res.Header.Get("Cache-Control")
+		if c.noStore && got != "no-store" {
+			t.Errorf("%s: Cache-Control=%q, want no-store", c.path, got)
+		}
+		if !c.noStore && got == "no-store" {
+			t.Errorf("%s: NO debe llevar no-store", c.path)
+		}
+	}
+}
+
+func TestDevicesPaginacionYFiltros(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	// Paginación: 47 dispositivos del dataset canónico (port devices.test.js)
+	res := get(t, srv.URL, "/api/devices?page=1&pageSize=10", cookie)
+	body := readJSON(t, res)
+	if body["total"].(float64) != 47 || len(body["items"].([]any)) != 10 {
+		t.Fatalf("page1: %v items, total %v", len(body["items"].([]any)), body["total"])
+	}
+	if body["page"].(float64) != 1 || body["pageSize"].(float64) != 10 {
+		t.Fatalf("page/pageSize: %v", body)
+	}
+	res = get(t, srv.URL, "/api/devices?page=5&pageSize=10", cookie)
+	body = readJSON(t, res)
+	if len(body["items"].([]any)) != 7 {
+		t.Fatalf("page5 (resto): %v", len(body["items"].([]any)))
+	}
+	// Sin solape con la página anterior
+	res = get(t, srv.URL, "/api/devices?page=4&pageSize=10", cookie)
+	prev := readJSON(t, res)
+	prevIDs := map[string]bool{}
+	for _, it := range prev["items"].([]any) {
+		prevIDs[it.(map[string]any)["id"].(string)] = true
+	}
+	for _, it := range body["items"].([]any) {
+		if prevIDs[it.(map[string]any)["id"].(string)] {
+			t.Fatalf("solape entre page4 y page5: %v", it)
+		}
+	}
+	// Defaults: pageSize=50
+	res = get(t, srv.URL, "/api/devices", cookie)
+	body = readJSON(t, res)
+	if body["pageSize"].(float64) != 50 || body["page"].(float64) != 1 {
+		t.Fatalf("defaults: %v", body)
+	}
+	// Filtros
+	res = get(t, srv.URL, "/api/devices?routerId=living", cookie)
+	body = readJSON(t, res)
+	if body["total"].(float64) != 18 {
+		t.Fatalf("routerId=living: %v", body["total"])
+	}
+	res = get(t, srv.URL, "/api/devices?band=cable", cookie)
+	body = readJSON(t, res)
+	for _, it := range body["items"].([]any) {
+		if it.(map[string]any)["band"] != "cable" {
+			t.Fatalf("band=cable con item de otra banda: %v", it)
+		}
+	}
+	if body["total"].(float64) != 7 { // ps5, nas, pc-sobremesa, raspberry, switch, mac-mini, hue-hub
+		t.Fatalf("band=cable: %v", body["total"])
+	}
+	res = get(t, srv.URL, "/api/devices?status=offline", cookie)
+	body = readJSON(t, res)
+	if body["total"].(float64) != 8 {
+		t.Fatalf("status=offline: %v", body["total"])
+	}
+	res = get(t, srv.URL, "/api/devices?type=movil", cookie)
+	body = readJSON(t, res)
+	for _, it := range body["items"].([]any) {
+		m := it.(map[string]any)
+		if m["type"] != "movil" && m["group"] != "moviles" {
+			t.Fatalf("type=movil con item que no casa: %v", m)
+		}
+	}
+	if body["total"].(float64) != 5 { // pixel-8-pro, iphone-ana, pixel-7, galaxy-s23, iphone-trabajo
+		t.Fatalf("type=movil: %v", body["total"])
+	}
+	res = get(t, srv.URL, "/api/devices?q=PIXEL", cookie)
+	body = readJSON(t, res)
+	if body["total"].(float64) != 2 { // pixel-8-pro y pixel-7
+		t.Fatalf("q=PIXEL: %v", body["total"])
+	}
+	// Inválidos → 400
+	for _, u := range []string{
+		"/api/devices?band=wifi6",
+		"/api/devices?status=weird",
+		"/api/devices?page=abc",
+		"/api/devices?pageSize=1001",
+	} {
+		res = get(t, srv.URL, u, cookie)
+		body = readJSON(t, res)
+		if res.StatusCode != 400 || body["error"] != "invalid_query" {
+			t.Fatalf("%s: got %d %v", u, res.StatusCode, body)
+		}
+	}
+	// Shape Device (12 claves del contrato)
+	res = get(t, srv.URL, "/api/devices?pageSize=1", cookie)
+	body = readJSON(t, res)
+	dev := body["items"].([]any)[0].(map[string]any)
+	for _, k := range []string{"id", "name", "type", "manufacturer", "ip", "mac", "routerId", "band", "signalDbm", "trafficMbps", "online", "sparkline"} {
+		if _, ok := dev[k]; !ok {
+			t.Fatalf("device sin clave %q: %v", k, dev)
+		}
+	}
+}
+
+func TestAlertsEndpoint(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	res := get(t, srv.URL, "/api/alerts", cookie)
+	body := readJSON(t, res)
+	if body["total"].(float64) != 5 || body["pageSize"].(float64) != 20 {
+		t.Fatalf("alerts default: %v", body)
+	}
+	res = get(t, srv.URL, "/api/alerts?severity=warn", cookie)
+	body = readJSON(t, res)
+	if body["total"].(float64) != 2 {
+		t.Fatalf("severity=warn: %v", body["total"])
+	}
+	res = get(t, srv.URL, "/api/alerts?severity=fatal", cookie)
+	body = readJSON(t, res)
+	if res.StatusCode != 400 || body["message"] != "severity debe ser una de: warn, critical, info, ok" {
+		t.Fatalf("severity inválido: %d %v", res.StatusCode, body)
+	}
+}
+
+func TestRoutersYDetalle(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	res := get(t, srv.URL, "/api/routers", cookie)
+	body := readJSON(t, res)
+	if len(body["routers"].([]any)) != 4 {
+		t.Fatalf("routers: %v", body)
+	}
+	res = get(t, srv.URL, "/api/routers/flint2", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("detalle flint2: %d", res.StatusCode)
+	}
+	detail := readJSON(t, res)
+	for _, k := range []string{"router", "ports", "radios", "backhaul", "series", "clients", "extras", "adguard", "wireguard"} {
+		if _, ok := detail[k]; !ok {
+			t.Fatalf("detalle sin clave %q", k)
+		}
+	}
+	res = get(t, srv.URL, "/api/routers/no-existe", cookie)
+	body = readJSON(t, res)
+	if res.StatusCode != 404 || body["error"] != "not_found" {
+		t.Fatalf("detalle desconocido: %d %v", res.StatusCode, body)
+	}
+	// DAWN: el stub devuelve null → 503
+	res = get(t, srv.URL, "/api/dawn", cookie)
+	body = readJSON(t, res)
+	if res.StatusCode != 503 || body["error"] != "unavailable" {
+		t.Fatalf("dawn: %d %v", res.StatusCode, body)
+	}
+	// AdGuard clients: stub null → 404 not_configured
+	res = get(t, srv.URL, "/api/adguard/clients", cookie)
+	body = readJSON(t, res)
+	if res.StatusCode != 404 || body["error"] != "not_configured" {
+		t.Fatalf("adguard/clients: %d %v", res.StatusCode, body)
+	}
+}
+
+func TestAPI404JSON(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	for _, path := range []string{"/api/no-existe", "/api/routers/"} {
+		res := get(t, srv.URL, path, cookie)
+		body := readJSON(t, res)
+		if res.StatusCode != 404 || body["error"] != "not_found" {
+			t.Fatalf("%s: got %d %v", path, res.StatusCode, body)
+		}
+	}
+	// Cualquier método → 404 JSON (no 405)
+	req, _ := http.NewRequest("DELETE", srv.URL+"/api/overview", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, _ := http.DefaultClient.Do(req)
+	body := readJSON(t, res)
+	if res.StatusCode != 404 || body["error"] != "not_found" {
+		t.Fatalf("DELETE /api/overview: got %d %v", res.StatusCode, body)
+	}
+}
+
+func TestHealthEndpoints(t *testing.T) {
+	srv := makeTestServer(t)
+	res := get(t, srv.URL, "/api/health", "") // pública, sin cookie
+	body := readJSON(t, res)
+	if res.StatusCode != 200 {
+		t.Fatalf("/api/health: %d", res.StatusCode)
+	}
+	if body["ok"] != true || body["version"] != "1.0.0" || body["mode"] != "demo" || body["db"] != "ok" {
+		t.Fatalf("/api/health: %v", body)
+	}
+	if _, ok := body["uptimeSec"].(float64); !ok {
+		t.Fatalf("uptimeSec: %v", body)
+	}
+	res = get(t, srv.URL, "/health", "")
+	body = readJSON(t, res)
+	if body["status"] != "ok" || body["db"] != "connected" {
+		t.Fatalf("/health: %v", body)
+	}
+	mem := body["memory"].(map[string]any)
+	if mem["rss"].(float64) <= 0 || mem["heap"].(float64) <= 0 {
+		t.Fatalf("memory: %v", mem)
+	}
+}
+
+func TestSecurityHeaders(t *testing.T) {
+	srv := makeTestServer(t)
+	res := get(t, srv.URL, "/api/health", "")
+	res.Body.Close()
+	want := map[string]string{
+		"X-Content-Type-Options":    "nosniff",
+		"X-Frame-Options":           "DENY",
+		"Referrer-Policy":           "strict-origin-when-cross-origin",
+		"Permissions-Policy":        "geolocation=(), microphone=(), camera=()",
+		"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
+		"Content-Security-Policy":   "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'",
+	}
+	for k, v := range want {
+		if got := res.Header.Get(k); got != v {
+			t.Errorf("header %s:\n got %q\nwant %q", k, got, v)
+		}
+	}
+}
+
+func TestSPAFallback(t *testing.T) {
+	srv := makeTestServer(t) // Static nil → sin handler estático? No: ver abajo
+	// Nota: en makeTestServer no hay Static; el fallback / lo prueba el smoke
+	// con STATIC_DIR. Aquí solo verificamos que /api/* no cae al SPA.
+	_ = srv
+}

+ 134 - 0
server-go/internal/httpapi/migrate_e2e_test.go

@@ -0,0 +1,134 @@
+// migrate_e2e_test.go — migración Node→Go END-TO-END sobre HTTP:
+// fixture con esquema Node → db.Open (migra) → el usuario importado hace
+// login con su password y la sesión importada vale en /api/auth/me.
+package httpapi_test
+
+import (
+	"database/sql"
+	"net/http/httptest"
+	"path/filepath"
+	"testing"
+	"time"
+
+	_ "modernc.org/sqlite"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"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/httpapi"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+func TestMigrationEndToEndHTTP(t *testing.T) {
+	dir := t.TempDir()
+	dbPath := filepath.Join(dir, "netpulse.db")
+
+	// Fixture Node: esquema literal + admin bcrypt + kv(session_secret) +
+	// sesión viva + login_attempts con bloqueo (se resetea en la migración).
+	raw, err := sql.Open("sqlite", dbPath)
+	if err != nil {
+		t.Fatal(err)
+	}
+	secret := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+	password := "n0de-p4ss"
+	hash, err := auth.HashPassword(password)
+	if err != nil {
+		t.Fatal(err)
+	}
+	now := db.NowMS()
+	ddl := []string{
+		`CREATE TABLE sessions (id TEXT PRIMARY KEY, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, ua TEXT)`,
+		`CREATE TABLE login_attempts (ip TEXT PRIMARY KEY, attempts INTEGER DEFAULT 0, locked_until INTEGER DEFAULT 0)`,
+		`CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT)`,
+		`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, pass_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', created_at INTEGER NOT NULL)`,
+		`ALTER TABLE sessions ADD COLUMN user_id INTEGER`,
+		`ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'`,
+	}
+	for _, q := range ddl {
+		if _, err := raw.Exec(q); err != nil {
+			t.Fatalf("ddl: %v", err)
+		}
+	}
+	if _, err := raw.Exec("INSERT INTO users (username, pass_hash, role, created_at) VALUES ('admin', ?, 'admin', ?)", hash, now); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := raw.Exec("INSERT INTO kv (key, value) VALUES ('session_secret', ?)", secret); err != nil {
+		t.Fatal(err)
+	}
+	nodeSessionID := "99999999-8888-4777-8666-555555555555"
+	if _, err := raw.Exec("INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES (?, ?, ?, 'Node/1.0', 1)",
+		nodeSessionID, now, now+30*24*3600*1000); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := raw.Exec("INSERT INTO login_attempts (ip, attempts, locked_until) VALUES ('5.6.7.8', 9, ?)", now+60000); err != nil {
+		t.Fatal(err)
+	}
+	raw.Close()
+
+	// db.Open dispara la migración (backup + reset login_attempts + marcador).
+	d, err := db.Open(dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer d.Close()
+
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": password, "DEMO_MODE": "1",
+		"DATA_DIR": dir, "NODE_ENV": "test",
+	}, dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	gotSecret, err := auth.EnsureSessionSecret(d, cfg)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if gotSecret != secret {
+		t.Fatal("session_secret debe ser el importado (las sesiones Node sobreviven)")
+	}
+	if err := auth.EnsureUsers(d, cfg); err != nil {
+		t.Fatal(err)
+	}
+	// El bloqueo de login_attempts de la época Node se reseteó.
+	var attempts int
+	if err := d.QueryRow("SELECT COUNT(*) FROM login_attempts").Scan(&attempts); err != nil || attempts != 0 {
+		t.Fatalf("login_attempts reseteado: %v n=%d", err, attempts)
+	}
+
+	handler := httpapi.NewHandler(httpapi.Deps{
+		Config: cfg, DB: d, Adapter: adapters.NewDemo(),
+		Hub:    sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil }),
+		Secret: gotSecret, Started: time.Now(),
+	})
+	srv := httptest.NewServer(handler)
+	defer srv.Close()
+
+	// 1) El usuario importado hace login con su password → 204 + cookie.
+	status, _, _ := loginCookie(t, srv.URL, "admin", password)
+	if status != 204 {
+		t.Fatalf("login tras migración: got %d want 204", status)
+	}
+
+	// 2) La sesión importada es válida en /api/auth/me (SIN re-login).
+	cookie := auth.SignSessionID(secret, nodeSessionID)
+	res := get(t, srv.URL, "/api/auth/me", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != 200 || body["user"] != "admin" || body["role"] != "admin" || body["language"] != "auto" || body["mode"] != "demo" {
+		t.Fatalf("me con sesión importada: %d %v", res.StatusCode, body)
+	}
+
+	// 3) Una cookie firmada con OTRO secret no vale (el secret manda).
+	forged := auth.SignSessionID("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", nodeSessionID)
+	res = get(t, srv.URL, "/api/auth/me", forged)
+	res.Body.Close()
+	if res.StatusCode != 401 {
+		t.Fatalf("cookie con secret ajeno: got %d want 401", res.StatusCode)
+	}
+
+	// 4) El backup existe.
+	matches, _ := filepath.Glob(dbPath + ".bak-*")
+	if len(matches) != 1 {
+		t.Fatalf("backup: %v", matches)
+	}
+}

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

@@ -0,0 +1,159 @@
+// Package httpapi — handlers de la API (paridad con server/src/routes/* +
+// app.js + health.js). Ensamblado equivalente a createApp:
+//
+//	security headers (global) → requireAuth (global) → rutas API →
+//	404 JSON /api/* → estáticos + SPA fallback → onError 500.
+//
+// El middleware noStore (Cache-Control: no-store) se aplica a /api/* salvo
+// /api/health, /health y /api/auth/* (paridad con el orden de registro de
+// Hono, SPEC §1); /api/stream lo sobrescribe con no-cache.
+package httpapi
+
+import (
+	"encoding/json"
+	"net/http"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"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/security"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+	"github.com/gnacho/netpulse/server-go/internal/staticspa"
+	"github.com/gnacho/netpulse/server-go/internal/updater"
+)
+
+// Version es la versión del backend (app.js:18).
+const Version = "1.0.0"
+
+// Deps son las dependencias del servidor API (como createApp de app.js).
+type Deps struct {
+	Config  *config.Config
+	DB      *db.DB
+	Adapter adapters.Snapshotter
+	Hub     *sse.Hub
+	Secret  string
+	Static  *staticspa.Handler
+	Updater *updater.Updater // nil → sin rutas /api/update/*
+	// LastOverview devuelve el último overview del poller (nil si aún no hay).
+	LastOverview func() *adapters.Overview
+	Started      time.Time
+}
+
+type server struct {
+	cfg     *config.Config
+	db      *db.DB
+	adapter adapters.Snapshotter
+	hub     *sse.Hub
+	secret  string
+	lastOv  func() *adapters.Overview
+	started time.Time
+}
+
+// NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
+func NewHandler(d Deps) http.Handler {
+	s := &server{
+		cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
+		secret: d.Secret, lastOv: d.LastOverview, started: d.Started,
+	}
+	mode := d.Adapter.Mode()
+
+	mux := http.NewServeMux()
+
+	// --- Health (público; SIN no-store) ---
+	mux.HandleFunc("GET /api/health", s.handleAPIHealth(mode))
+	mux.HandleFunc("GET /health", s.handleHealth)
+
+	// --- Auth (público login; SIN no-store) ---
+	mux.HandleFunc("POST /api/auth/login", s.handleLogin)
+	mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
+	mux.HandleFunc("GET /api/auth/me", s.handleMe(mode))
+
+	// --- Datos (sesión; con no-store) ---
+	mux.HandleFunc("GET /api/overview", s.handleOverview)
+	mux.HandleFunc("GET /api/routers", s.handleRouters)
+	mux.HandleFunc("GET /api/routers/{id}", s.handleRouterDetail)
+	mux.HandleFunc("GET /api/devices", s.handleDevices)
+	mux.HandleFunc("GET /api/alerts", s.handleAlerts)
+	mux.HandleFunc("GET /api/topology", s.handleTopology)
+	mux.HandleFunc("GET /api/dawn", s.handleDawn)
+	mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
+
+	// --- Users ---
+	// Idioma propio: FUERA del gate admin (se registra antes en Node).
+	mux.HandleFunc("PUT /api/users/me/language", s.handleMyLanguage)
+	// Resto: solo admin.
+	mux.Handle("GET /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleListUsers)))
+	mux.Handle("POST /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleCreateUser)))
+	mux.Handle("PUT /api/users/{id}/password", auth.RequireAdmin(http.HandlerFunc(s.handleSetPassword)))
+	mux.Handle("PUT /api/users/{id}/role", auth.RequireAdmin(http.HandlerFunc(s.handleSetRole)))
+	mux.Handle("DELETE /api/users/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteUser)))
+
+	// --- Config (sesión; /api/config/adguard solo admin) ---
+	s.registerConfigRoutes(mux)
+
+	// --- Update (solo admin; ausente si no hay updater, p.ej. en tests) ---
+	if d.Updater != nil {
+		s.registerUpdateRoutes(mux, d.Updater)
+	}
+
+	// --- SSE ---
+	mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
+
+	// --- 404 JSON para cualquier /api/* no registrado (cualquier método) ---
+	mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
+		writeError(w, http.StatusNotFound, "not_found")
+	})
+
+	// --- Estáticos + SPA fallback ---
+	static := d.Static
+	if static != nil {
+		mux.Handle("/", static)
+	}
+
+	return security.Middleware(auth.RequireAuth(s.db, s.secret, noStoreMux(mux)))
+}
+
+// noStoreMux replica el middleware noStore() de routes/data.js: aplica
+// Cache-Control: no-store a /api/* EXCEPTO /api/health y /api/auth/*
+// (/health no es /api/*). /api/stream sobrescribe con no-cache después.
+func noStoreMux(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		p := r.URL.Path
+		if strings.HasPrefix(p, "/api/") && p != "/api/health" && !strings.HasPrefix(p, "/api/auth/") {
+			w.Header().Set("Cache-Control", "no-store")
+		}
+		next.ServeHTTP(w, r)
+	})
+}
+
+// writeJSON serializa como JSON.stringify: compacto y SIN escapar HTML
+// (SetEscapeHTML(false)).
+func writeJSON(w http.ResponseWriter, status int, v any) {
+	w.Header().Set("Content-Type", "application/json")
+	w.WriteHeader(status)
+	enc := json.NewEncoder(w)
+	enc.SetEscapeHTML(false)
+	_ = enc.Encode(v)
+}
+
+// writeError escribe el envelope {error, message?}.
+func writeError(w http.ResponseWriter, status int, code string, message ...string) {
+	if len(message) > 0 {
+		writeJSON(w, status, map[string]any{"error": code, "message": message[0]})
+		return
+	}
+	writeJSON(w, status, map[string]any{"error": code})
+}
+
+// readJSONBody parsea el body JSON; devuelve false si no es JSON válido
+// (equivalente a c.req.json().catch(() => null)).
+func readJSONBody(r *http.Request, dst any) bool {
+	dec := json.NewDecoder(r.Body)
+	if err := dec.Decode(dst); err != nil {
+		return false
+	}
+	return true
+}

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

@@ -0,0 +1,36 @@
+// update.go — rutas /api/update/* (paridad src/routes/update.js, SPEC §2.18,
+// solo admin):
+//   GET  /api/update/status → estado actual
+//   POST /api/update/check  → fuerza un chequeo contra GitHub
+//   POST /api/update/apply  → aplica la actualización (202 | 409)
+package httpapi
+
+import (
+	"context"
+	"net/http"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/updater"
+)
+
+// registerUpdateRoutes registra las rutas /api/update/* (solo si hay updater).
+func (s *server) registerUpdateRoutes(mux *http.ServeMux, u *updater.Updater) {
+	mux.Handle("GET /api/update/status", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		writeJSON(w, http.StatusOK, u.Status())
+	})))
+	mux.Handle("POST /api/update/check", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
+		defer cancel()
+		writeJSON(w, http.StatusOK, u.Check(ctx))
+	})))
+	mux.Handle("POST /api/update/apply", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if !u.Apply() {
+			// already_updating (o update_copy_failed: mismo 409 que el JS,
+			// que solo devuelve false en ambos casos)
+			writeError(w, http.StatusConflict, "already_updating")
+			return
+		}
+		writeJSON(w, http.StatusAccepted, u.Status())
+	})))
+}

+ 272 - 0
server-go/internal/httpapi/users.go

@@ -0,0 +1,272 @@
+// users.go — CRUD de usuarios (paridad routes/users.js).
+//
+//	PUT  /api/users/me/language   (cualquier rol — fuera del gate admin)
+//	GET  /api/users               (admin)
+//	POST /api/users               (admin) → 201 · 400 · 409
+//	PUT  /api/users/:id/password  (admin) → 204 (invalida sus sesiones)
+//	PUT  /api/users/:id/role?role= (admin) → rol nuevo en QUERY STRING (quirk)
+//	DELETE /api/users/:id         (admin) → 204 (no self, no último admin)
+package httpapi
+
+import (
+	"database/sql"
+	"net/http"
+	"regexp"
+	"strconv"
+	"strings"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
+
+// parseUserID replica Number(:id): no numérico → NaN → no encontrado (404).
+func parseUserID(s string) (float64, bool) {
+	n, err := strconv.ParseFloat(strings.TrimSpace(s), 64)
+	if err != nil {
+		return 0, false
+	}
+	return n, true
+}
+
+type userTarget struct {
+	ID       int64
+	Username string
+	Role     string
+}
+
+func (s *server) findUser(id float64) *userTarget {
+	var t userTarget
+	err := s.db.QueryRow("SELECT id, username, role FROM users WHERE id = ?", id).
+		Scan(&t.ID, &t.Username, &t.Role)
+	if err != nil {
+		return nil
+	}
+	return &t
+}
+
+func (s *server) adminCount() int {
+	var n int
+	_ = s.db.QueryRow("SELECT COUNT(*) FROM users WHERE role = 'admin'").Scan(&n)
+	return n
+}
+
+// handleMyLanguage: {language: auto|es|en} → 204 (fuera del gate admin).
+func (s *server) handleMyLanguage(w http.ResponseWriter, r *http.Request) {
+	me := auth.UserFromContext(r.Context())
+	var body struct {
+		Language string `json:"language"`
+	}
+	if !readJSONBody(r, &body) ||
+		(body.Language != "auto" && body.Language != "es" && body.Language != "en") {
+		writeError(w, http.StatusBadRequest, "invalid_input", "language debe ser auto|es|en")
+		return
+	}
+	_, _ = s.db.Exec("UPDATE users SET language = ? WHERE id = ?", body.Language, me.ID)
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// handleListUsers: {users:[{id, username, role, language, created_at}]} por username.
+func (s *server) handleListUsers(w http.ResponseWriter, r *http.Request) {
+	rows, err := s.db.Query("SELECT id, username, role, language, created_at FROM users ORDER BY username")
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	defer rows.Close()
+	users := []map[string]any{}
+	for rows.Next() {
+		var (
+			id        int64
+			username  string
+			role      string
+			language  sql.NullString
+			createdAt int64
+		)
+		if err := rows.Scan(&id, &username, &role, &language, &createdAt); err != nil {
+			continue
+		}
+		var lang any
+		if language.Valid {
+			lang = language.String
+		}
+		users = append(users, map[string]any{
+			"id": id, "username": username, "role": role, "language": lang, "created_at": createdAt,
+		})
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"users": users})
+}
+
+// handleCreateUser: alta (admin). bcrypt cost 10.
+func (s *server) handleCreateUser(w http.ResponseWriter, r *http.Request) {
+	var body struct {
+		Username *string `json:"username"`
+		Password *string `json:"password"`
+		Role     *string `json:"role"`
+		Language *string `json:"language"`
+	}
+	if !readJSONBody(r, &body) {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Required")
+		return
+	}
+	// Validación (orden zod: username → password → role → language)
+	if body.Username == nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Required")
+		return
+	}
+	username := strings.TrimSpace(*body.Username)
+	if len(username) < 2 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 2 character(s)")
+		return
+	}
+	if len(username) > 32 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 32 character(s)")
+		return
+	}
+	if !usernameRe.MatchString(username) {
+		writeError(w, http.StatusBadRequest, "invalid_input", "usuario debe ser alfanumérico (.-_ permitidos)")
+		return
+	}
+	if body.Password == nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Required")
+		return
+	}
+	password := *body.Password
+	if len(password) < 6 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 6 character(s)")
+		return
+	}
+	if len(password) > 128 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
+		return
+	}
+	role := "user"
+	if body.Role != nil {
+		if *body.Role != "admin" && *body.Role != "user" {
+			writeError(w, http.StatusBadRequest, "invalid_input",
+				"Invalid enum value. Expected 'admin' | 'user'")
+			return
+		}
+		role = *body.Role
+	}
+	language := "auto"
+	if body.Language != nil {
+		if *body.Language != "auto" && *body.Language != "es" && *body.Language != "en" {
+			writeError(w, http.StatusBadRequest, "invalid_input",
+				"Invalid enum value. Expected 'auto' | 'es' | 'en'")
+			return
+		}
+		language = *body.Language
+	}
+
+	var exists int
+	_ = s.db.QueryRow("SELECT 1 FROM users WHERE username = ?", username).Scan(&exists)
+	if exists == 1 {
+		writeError(w, http.StatusConflict, "duplicate_user", "Ya existe el usuario "+username)
+		return
+	}
+	hash, err := auth.HashPassword(password)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	res, err := s.db.Exec(
+		"INSERT INTO users (username, pass_hash, role, language, created_at) VALUES (?, ?, ?, ?, ?)",
+		username, hash, role, language, db.NowMS(),
+	)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	id, _ := res.LastInsertId()
+	writeJSON(w, http.StatusCreated, map[string]any{
+		"user": map[string]any{"id": id, "username": username, "role": role, "language": language},
+	})
+}
+
+// handleSetPassword: {password 6..128} → 204 + destroyUserSessions.
+func (s *server) handleSetPassword(w http.ResponseWriter, r *http.Request) {
+	id, ok := parseUserID(r.PathValue("id"))
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	target := s.findUser(id)
+	if target == nil {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	var body struct {
+		Password *string `json:"password"`
+	}
+	if !readJSONBody(r, &body) || body.Password == nil || len(*body.Password) < 6 || len(*body.Password) > 128 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "password mínimo 6 caracteres")
+		return
+	}
+	hash, err := auth.HashPassword(*body.Password)
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	_, _ = s.db.Exec("UPDATE users SET pass_hash = ? WHERE id = ?", hash, target.ID)
+	auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// handleSetRole: rol nuevo en QUERY STRING (quirk del contrato) → 204.
+func (s *server) handleSetRole(w http.ResponseWriter, r *http.Request) {
+	id, ok := parseUserID(r.PathValue("id"))
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	me := auth.UserFromContext(r.Context())
+	target := s.findUser(id)
+	if target == nil {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	role := r.URL.Query().Get("role")
+	if role != "admin" && role != "user" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "role debe ser admin|user")
+		return
+	}
+	if target.ID == me.ID {
+		writeError(w, http.StatusBadRequest, "cannot_change_self", "No puedes cambiar tu propio rol")
+		return
+	}
+	if target.Role == "admin" && role == "user" && s.adminCount() <= 1 {
+		writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
+		return
+	}
+	_, _ = s.db.Exec("UPDATE users SET role = ? WHERE id = ?", role, target.ID)
+	auth.DestroyUserSessions(s.db, target.ID) // fuerza re-login con el nuevo rol
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// handleDeleteUser: 204 (no self, no último admin); borra sesiones y la fila.
+func (s *server) handleDeleteUser(w http.ResponseWriter, r *http.Request) {
+	id, ok := parseUserID(r.PathValue("id"))
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	me := auth.UserFromContext(r.Context())
+	target := s.findUser(id)
+	if target == nil {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	if target.ID == me.ID {
+		writeError(w, http.StatusBadRequest, "cannot_delete_self", "No puedes borrar tu propio usuario")
+		return
+	}
+	if target.Role == "admin" && s.adminCount() <= 1 {
+		writeError(w, http.StatusBadRequest, "last_admin", "Debe quedar al menos un admin")
+		return
+	}
+	auth.DestroyUserSessions(s.db, target.ID)
+	_, _ = s.db.Exec("DELETE FROM users WHERE id = ?", target.ID)
+	w.WriteHeader(http.StatusNoContent)
+}

+ 157 - 0
server-go/internal/poller/poller.go

@@ -0,0 +1,157 @@
+// Package poller — sondeo cada 5 s (paridad src/poller.js, SPEC §6):
+// tick inmediato + intervalo; adapter.tick → getOverview → persiste (solo
+// live) → broadcast SSE snapshot → alertas nuevas (cebado en el 1er tick).
+// Robustez: un fallo del adapter nunca mata el poller.
+//
+// NOTA (núcleo Go): con el adapter STUB demo esto ya es funcional; el agente
+// B enchufa aquí el adapter live sin tocar este bucle.
+package poller
+
+import (
+	"context"
+	"log"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+// TickMS es el intervalo del poller (5 s).
+const TickMS = 5 * time.Second
+
+// Poller ejecuta el bucle de sondeo.
+type Poller struct {
+	adapter adapters.Snapshotter
+	db      *db.DB
+	hub     *sse.Hub
+
+	mu           sync.RWMutex
+	lastOverview *adapters.Overview
+	lastAdguard  *adapters.AdGuardStats
+	knownAlerts  map[string]struct{}
+	primed       bool
+
+	stopCh chan struct{}
+	doneCh chan struct{}
+	once   sync.Once
+}
+
+// New crea el poller.
+func New(adapter adapters.Snapshotter, d *db.DB, hub *sse.Hub) *Poller {
+	return &Poller{
+		adapter: adapter, db: d, hub: hub,
+		knownAlerts: map[string]struct{}{},
+		stopCh:      make(chan struct{}), doneCh: make(chan struct{}),
+	}
+}
+
+// LastOverview devuelve el último overview (para SSE y /api/overview).
+func (p *Poller) LastOverview() *adapters.Overview {
+	p.mu.RLock()
+	defer p.mu.RUnlock()
+	return p.lastOverview
+}
+
+// Start lanza el bucle: primer tick inmediato + ticker de 5 s.
+func (p *Poller) Start() {
+	go func() {
+		defer close(p.doneCh)
+		p.tick()
+		t := time.NewTicker(TickMS)
+		defer t.Stop()
+		for {
+			select {
+			case <-p.stopCh:
+				return
+			case <-t.C:
+				p.tick()
+			}
+		}
+	}()
+}
+
+// Stop detiene el bucle y espera a que termine el tick en curso.
+func (p *Poller) Stop() {
+	p.once.Do(func() {
+		close(p.stopCh)
+		<-p.doneCh
+	})
+}
+
+// tick ejecuta un ciclo completo (nunca propaga errores).
+func (p *Poller) tick() {
+	defer func() {
+		if rec := recover(); rec != nil {
+			log.Printf("[netpulse] error en tick del poller: %v", rec)
+		}
+	}()
+	ctx := context.Background()
+
+	_ = p.adapter.Tick(ctx) // demo: random walk; live: no-op
+
+	overview, err := p.adapter.GetOverview(ctx)
+	if err != nil || overview == nil {
+		if err != nil {
+			log.Printf("[netpulse] error en tick del poller: %v", err)
+		}
+		return
+	}
+
+	p.mu.Lock()
+	p.lastOverview = overview
+	ag := overview.Adguard
+	p.lastAdguard = &ag
+	p.mu.Unlock()
+
+	// Persistencia SOLO en live (en demo la BD se mantiene vacía de métricas).
+	if p.adapter.Mode() != "demo" {
+		p.persist(overview)
+	}
+
+	p.hub.Broadcast("snapshot", overview)
+
+	// Alertas: el 1er tick solo ceba knownAlertIds (no re-notifica).
+	alerts := p.adapter.GetAlerts(ctx)
+	if !p.primed {
+		for _, a := range alerts {
+			p.knownAlerts[a.ID] = struct{}{}
+		}
+		p.primed = true
+		return
+	}
+	for _, a := range alerts {
+		if _, known := p.knownAlerts[a.ID]; known {
+			continue
+		}
+		p.knownAlerts[a.ID] = struct{}{}
+		p.hub.Broadcast("alert", a)
+	}
+}
+
+// persist guarda métricas del tick (ts común, epoch ms). Quirk preservado:
+// en live se inserta una fila adguard_stats (0,0) cada tick aunque AdGuard
+// no esté configurado, porque overview.adguard siempre va presente (SPEC §6).
+func (p *Poller) persist(overview *adapters.Overview) {
+	ts := db.NowMS()
+	for _, row := range p.adapter.GetMetricsRows(context.Background()) {
+		if _, err := p.db.Exec(
+			"INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
+			row.RouterID, ts, row.CPU, row.RAM, row.Temp, row.LatencyMs, row.RxBps, row.TxBps,
+		); err != nil {
+			log.Printf("[netpulse] error en tick del poller (metrics): %v", err)
+		}
+	}
+	p.mu.RLock()
+	ag := p.lastAdguard
+	p.mu.RUnlock()
+	if ag != nil {
+		if _, err := p.db.Exec(
+			"INSERT INTO adguard_stats (ts, queries, blocked) VALUES (?, ?, ?)",
+			ts, ag.Queries24h, ag.Blocked24h,
+		); err != nil {
+			log.Printf("[netpulse] error en tick del poller (adguard_stats): %v", err)
+		}
+	}
+}

+ 288 - 0
server-go/internal/routerstore/routerstore.go

@@ -0,0 +1,288 @@
+// Package routerstore — almacén de routers configurados (tabla `routers` de
+// SQLite) + bootstrap (paridad src/routerstore.js, SPEC §8.2):
+//  1. Si la tabla tiene filas → es la fuente de verdad.
+//  2. Si está vacía y hay ROUTERS_JSON → se siembra.
+//  3. Si sigue vacía y NO es demo → autodetección del gateway (ip route +
+//     sondeo SSH `ubus call system board`).
+package routerstore
+
+import (
+	"database/sql"
+	"encoding/json"
+	"log"
+	"os/exec"
+	"regexp"
+	"strings"
+	"time"
+	"unicode"
+
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/sshkey"
+	"golang.org/x/text/unicode/norm"
+)
+
+const probeTimeout = 4 * time.Second
+
+// ListRouters devuelve la tabla routers ordenada is_gateway DESC,
+// created_at ASC, con is_gateway como booleano.
+func ListRouters(db *sql.DB) []adapters.RouterConfig {
+	rows, err := db.Query("SELECT id, name, host, type, is_gateway, created_at FROM routers ORDER BY is_gateway DESC, created_at ASC")
+	if err != nil {
+		return []adapters.RouterConfig{}
+	}
+	defer rows.Close()
+	out := []adapters.RouterConfig{}
+	for rows.Next() {
+		var r adapters.RouterConfig
+		var gw int
+		var name sql.NullString
+		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &r.CreatedAt); err != nil {
+			continue
+		}
+		r.Name = name.String
+		r.IsGateway = gw == 1
+		out = append(out, r)
+	}
+	return out
+}
+
+var slugNonAlnum = regexp.MustCompile(`[^a-z0-9]+`)
+
+// slugify replica el slug JS: minúsculas, NFD sin diacríticos,
+// [^a-z0-9]+ → '-', trim guiones, máx 32.
+func slugify(text string) string {
+	s := strings.ToLower(text)
+	// NFD + eliminar marcas combinantes (U+0300–U+036F)
+	var b strings.Builder
+	for _, r := range norm.NFD.String(s) {
+		if r >= 0x0300 && r <= 0x036F {
+			continue
+		}
+		if !unicode.Is(unicode.Mn, r) {
+			b.WriteRune(r)
+		}
+	}
+	s = slugNonAlnum.ReplaceAllString(b.String(), "-")
+	s = strings.Trim(s, "-")
+	if len(s) > 32 {
+		s = s[:32]
+	}
+	return s
+}
+
+// uniqueId genera un id único a partir del nombre o del host.
+func uniqueId(db *sql.DB, name, host string) string {
+	base := slugify(name)
+	if base == "" {
+		parts := strings.Split(host, ".")
+		base = "router-" + parts[len(parts)-1]
+	}
+	if base == "" {
+		base = "router"
+	}
+	id := base
+	n := 2
+	for {
+		var one int
+		err := db.QueryRow("SELECT 1 FROM routers WHERE id = ?", id).Scan(&one)
+		if err == sql.ErrNoRows {
+			return id
+		}
+		if err != nil {
+			return id
+		}
+		id = base + "-" + itoa(n)
+		n++
+	}
+}
+
+func itoa(n int) string {
+	if n == 0 {
+		return "0"
+	}
+	var buf [8]byte
+	i := len(buf)
+	for n > 0 {
+		i--
+		buf[i] = byte('0' + n%10)
+		n /= 10
+	}
+	return string(buf[i:])
+}
+
+// AddInput son los datos de alta de un router.
+type AddInput struct {
+	Name      string
+	Host      string
+	Type      string // default "openwrt"
+	IsGateway bool
+}
+
+// AddRouter inserta un router (si IsGateway, el resto pierde el flag —
+// transacción, un solo gateway) y devuelve la fila creada.
+func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
+	if in.Type == "" {
+		in.Type = "openwrt"
+	}
+	id := uniqueId(db, in.Name, in.Host)
+	now := time.Now().UnixMilli()
+	name := in.Name
+	if name == "" {
+		name = in.Host
+	}
+	tx, err := db.Begin()
+	if err != nil {
+		return adapters.RouterConfig{}, err
+	}
+	defer tx.Rollback()
+	if in.IsGateway {
+		if _, err := tx.Exec("UPDATE routers SET is_gateway = 0"); err != nil {
+			return adapters.RouterConfig{}, err
+		}
+	}
+	gw := 0
+	if in.IsGateway {
+		gw = 1
+	}
+	if _, err := tx.Exec(
+		"INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES (?, ?, ?, ?, ?, ?)",
+		id, name, in.Host, in.Type, gw, now,
+	); err != nil {
+		return adapters.RouterConfig{}, err
+	}
+	if err := tx.Commit(); err != nil {
+		return adapters.RouterConfig{}, err
+	}
+	for _, r := range ListRouters(db) {
+		if r.ID == id {
+			return r, nil
+		}
+	}
+	return adapters.RouterConfig{}, sql.ErrNoRows
+}
+
+// RemoveRouter borra por id; true si borró (changes > 0).
+func RemoveRouter(db *sql.DB, id string) bool {
+	res, err := db.Exec("DELETE FROM routers WHERE id = ?", id)
+	if err != nil {
+		return false
+	}
+	n, _ := res.RowsAffected()
+	return n > 0
+}
+
+// ---------------------------------------------------------------------------
+// Autodetección de la puerta de enlace
+// ---------------------------------------------------------------------------
+
+var defaultViaRe = regexp.MustCompile(`default via (\d+\.\d+\.\d+\.\d+)`)
+
+// DetectGatewayIP devuelve la IP de la puerta de enlace por defecto del
+// servidor ("" si no se sabe).
+func DetectGatewayIP() string {
+	out, err := exec.Command("ip", "route", "show", "default").Output()
+	if err != nil {
+		return ""
+	}
+	if m := defaultViaRe.FindSubmatch(out); m != nil {
+		return string(m[1])
+	}
+	return ""
+}
+
+var glinetModelRe = regexp.MustCompile(`(?i)GL[.-]?iNet|GL-[A-Z]`)
+var glinetDistRe = regexp.MustCompile(`(?i)glinet`)
+
+// probeGatewayModel sondea el modelo del gateway por SSH (ubus system board).
+func probeGatewayModel(host, keyPath string) (model, typ string) {
+	args := append(sshkey.BaseArgs(keyPath),
+		"-o", "ConnectTimeout=3",
+		"-o", "ControlMaster=no",
+		"root@"+host,
+		"ubus call system board",
+	)
+	cmd := exec.Command("ssh", args...)
+	type result struct {
+		out []byte
+		err error
+	}
+	ch := make(chan result, 1)
+	go func() {
+		out, err := cmd.Output()
+		ch <- result{out, err}
+	}()
+	select {
+	case <-time.After(probeTimeout + time.Second):
+		_ = cmd.Process.Kill()
+		return "", "openwrt"
+	case res := <-ch:
+		if res.err != nil {
+			return "", "openwrt"
+		}
+		var board struct {
+			Model   string `json:"model"`
+			Release struct {
+				Distribution string `json:"distribution"`
+			} `json:"release"`
+		}
+		if err := json.Unmarshal(res.out, &board); err != nil {
+			return "", "openwrt"
+		}
+		typ = "openwrt"
+		if glinetModelRe.MatchString(board.Model) || glinetDistRe.MatchString(board.Release.Distribution) {
+			typ = "glinet"
+		}
+		return board.Model, typ
+	}
+}
+
+// EnsureInitialRouters es el bootstrap de la tabla routers
+// (routerstore.js:126-158). Devuelve la lista final configurada.
+func EnsureInitialRouters(db *sql.DB, cfg *config.Config) []adapters.RouterConfig {
+	existing := ListRouters(db)
+	if len(existing) > 0 {
+		return existing
+	}
+
+	// 1. Semilla desde ROUTERS_JSON (primer arranque)
+	if len(cfg.Routers) > 0 {
+		for i, r := range cfg.Routers {
+			_, err := AddRouter(db, AddInput{
+				Name: r.Name, Host: r.Host, Type: r.Type,
+				IsGateway: r.Type == "glinet" || i == 0,
+			})
+			if err != nil {
+				log.Printf("[netpulse] error sembrando router %s: %v", r.Host, err)
+			}
+		}
+		log.Printf("[netpulse] routers sembrados desde ROUTERS_JSON (%d)", len(cfg.Routers))
+		return ListRouters(db)
+	}
+
+	// 2. Autodetección de la puerta de enlace (nunca en demo forzado)
+	if cfg.DemoMode {
+		return []adapters.RouterConfig{}
+	}
+	gwIP := DetectGatewayIP()
+	if gwIP == "" {
+		log.Printf("[netpulse] sin puerta de enlace detectada; añade routers desde Ajustes")
+		return []adapters.RouterConfig{}
+	}
+	model, typ := probeGatewayModel(gwIP, cfg.SSHKeyPath)
+	name := model
+	if name == "" {
+		name = "Gateway"
+	}
+	created, err := AddRouter(db, AddInput{Name: name, Host: gwIP, Type: typ, IsGateway: true})
+	if err != nil {
+		log.Printf("[netpulse] error creando gateway autodetectado: %v", err)
+		return ListRouters(db)
+	}
+	if model == "" {
+		model = "modelo desconocido"
+	}
+	log.Printf("[netpulse] gateway autodetectado: %s (%s, tipo %s). El resto se añade desde Ajustes.",
+		created.Host, model, created.Type)
+	return ListRouters(db)
+}

+ 26 - 0
server-go/internal/security/security.go

@@ -0,0 +1,26 @@
+// Package security — headers de seguridad obligatorios (middleware global).
+// Literales de src/security.js:6-19 (SPEC §10.1), en TODAS las respuestas.
+package security
+
+import "net/http"
+
+// Headers es la lista literal de headers (orden de security.js).
+var Headers = []struct{ K, V string }{
+	{"X-Content-Type-Options", "nosniff"},
+	{"X-Frame-Options", "DENY"},
+	{"Referrer-Policy", "strict-origin-when-cross-origin"},
+	{"Permissions-Policy", "geolocation=(), microphone=(), camera=()"},
+	{"Strict-Transport-Security", "max-age=31536000; includeSubDomains"},
+	{"Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'"},
+}
+
+// Middleware aplica los headers a todas las respuestas (HSTS también por
+// HTTP plano — comportamiento del JS, preservado).
+func Middleware(next http.Handler) http.Handler {
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		for _, h := range Headers {
+			w.Header().Set(h.K, h.V)
+		}
+		next.ServeHTTP(w, r)
+	})
+}

+ 173 - 0
server-go/internal/sse/hub.go

@@ -0,0 +1,173 @@
+// Package sse — hub Server-Sent Events para /api/stream (paridad src/sse.js).
+//   - X-Accel-Buffering: no + Cache-Control: no-cache (sobrescribe no-store).
+//   - NUNCA Content-Encoding manual.
+//   - Primer evento `snapshot` inmediato; heartbeat `:hb` cada 30 s.
+//   - MAX_SSE_CLIENTS → 503 {error:'too_many_clients'}.
+//   - Sesión revocada (detectado en broadcast) → evento `bye` y cierre.
+//   - Formato de evento: `event: <nombre>\ndata: <JSON>\n\n`.
+package sse
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"sync"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// Heartbeat = 30 s (HEARTBEAT_MS de sse.js:16).
+const Heartbeat = 30 * time.Second
+
+type client struct {
+	id        int
+	sessionID string
+	w         http.ResponseWriter
+	flusher   http.Flusher
+	wmu       sync.Mutex
+	done      chan struct{}
+	once      sync.Once
+}
+
+func (c *client) write(payload string) error {
+	c.wmu.Lock()
+	defer c.wmu.Unlock()
+	if _, err := fmt.Fprint(c.w, payload); err != nil {
+		return err
+	}
+	c.flusher.Flush()
+	return nil
+}
+
+func (c *client) close() { c.once.Do(func() { close(c.done) }) }
+
+// Hub gestiona los clientes SSE conectados.
+type Hub struct {
+	db          *db.DB
+	maxClients  int
+	getOverview func() any
+
+	mu      sync.Mutex
+	clients map[int]*client
+	nextID  int
+}
+
+// NewHub crea el hub. getOverview devuelve el último overview del poller
+// (o nil si aún no hay) para el snapshot inicial.
+func NewHub(d *db.DB, maxClients int, getOverview func() any) *Hub {
+	return &Hub{db: d, maxClients: maxClients, getOverview: getOverview, clients: map[int]*client{}, nextID: 1}
+}
+
+// Size es el número de clientes conectados.
+func (h *Hub) Size() int {
+	h.mu.Lock()
+	defer h.mu.Unlock()
+	return len(h.clients)
+}
+
+func (h *Hub) remove(c *client) {
+	h.mu.Lock()
+	delete(h.clients, c.id)
+	h.mu.Unlock()
+	c.close()
+}
+
+// Broadcast envía `event` con `data` (JSON) a todos los clientes. Si la
+// sesión de un cliente ya no existe/expiró → evento `bye` y cierre (la
+// comprobación solo ocurre durante un broadcast, como en Node).
+func (h *Hub) Broadcast(event string, data any) {
+	raw, err := json.Marshal(data)
+	if err != nil {
+		return
+	}
+	payload := fmt.Sprintf("event: %s\ndata: %s\n\n", event, raw)
+
+	h.mu.Lock()
+	list := make([]*client, 0, len(h.clients))
+	for _, c := range h.clients {
+		list = append(list, c)
+	}
+	h.mu.Unlock()
+
+	for _, c := range list {
+		if auth.GetSession(h.db, c.sessionID) == nil {
+			_ = c.write("event: bye\ndata: {}\n\n")
+			h.remove(c)
+			continue
+		}
+		if err := c.write(payload); err != nil {
+			h.remove(c)
+		}
+	}
+}
+
+// NotifyShutdown envía el evento `shutdown` a todos los clientes.
+func (h *Hub) NotifyShutdown() {
+	h.mu.Lock()
+	list := make([]*client, 0, len(h.clients))
+	for _, c := range h.clients {
+		list = append(list, c)
+	}
+	h.mu.Unlock()
+	for _, c := range list {
+		_ = c.write("event: shutdown\ndata: {}\n\n")
+	}
+}
+
+// HandleStream sirve GET /api/stream (requiere sesión: RequireAuth antes).
+func (h *Hub) HandleStream(w http.ResponseWriter, r *http.Request) {
+	h.mu.Lock()
+	full := len(h.clients) >= h.maxClients
+	h.mu.Unlock()
+	if full {
+		auth.WriteError(w, http.StatusServiceUnavailable, "too_many_clients")
+		return
+	}
+	flusher, ok := w.(http.Flusher)
+	if !ok {
+		auth.WriteError(w, http.StatusInternalServerError, "internal_error")
+		return
+	}
+	sessionID := auth.SessionIDFromContext(r.Context())
+
+	w.Header().Set("Content-Type", "text/event-stream")
+	w.Header().Set("X-Accel-Buffering", "no")
+	w.Header().Set("Cache-Control", "no-cache") // sobrescribe el no-store
+	// Deliberadamente SIN Content-Encoding (ver sse.js:3-6).
+	w.WriteHeader(http.StatusOK)
+
+	h.mu.Lock()
+	c := &client{id: h.nextID, sessionID: sessionID, w: w, flusher: flusher, done: make(chan struct{})}
+	h.nextID++
+	h.clients[c.id] = c
+	h.mu.Unlock()
+	defer h.remove(c)
+
+	// Primer snapshot inmediato al conectar
+	if h.getOverview != nil {
+		if ov := h.getOverview(); ov != nil {
+			if raw, err := json.Marshal(ov); err == nil {
+				if err := c.write(fmt.Sprintf("event: snapshot\ndata: %s\n\n", raw)); err != nil {
+					return
+				}
+			}
+		}
+	}
+
+	heartbeat := time.NewTicker(Heartbeat)
+	defer heartbeat.Stop()
+	for {
+		select {
+		case <-r.Context().Done():
+			return
+		case <-c.done:
+			return
+		case <-heartbeat.C:
+			if err := c.write(":hb\n\n"); err != nil {
+				return
+			}
+		}
+	}
+}

+ 86 - 0
server-go/internal/sshkey/sshkey.go

@@ -0,0 +1,86 @@
+// Package sshkey — clave SSH propia de NetPulse (paridad src/sshkey.js):
+// par ed25519 en DATA_DIR/.ssh generado la primera vez, pública expuesta vía
+// /api/config/sshkey para autorizarla a mano en cada router. known_hosts
+// JUNTO a la clave (imprescindible con systemd ProtectSystem=strict).
+package sshkey
+
+import (
+	"os"
+	"os/exec"
+	"path/filepath"
+	"regexp"
+	"strings"
+)
+
+// BaseArgs replica sshBaseArgs (src/sshkey.js:16-24): los args SSH comunes.
+// known_hosts junto a la clave (dentro de DATA_DIR).
+func BaseArgs(keyPath string) []string {
+	return []string{
+		"-i", keyPath,
+		"-o", "BatchMode=yes",
+		"-o", "ConnectTimeout=4",
+		"-o", "StrictHostKeyChecking=accept-new",
+		"-o", "UserKnownHostsFile=" + filepath.Join(filepath.Dir(keyPath), "known_hosts"),
+	}
+}
+
+// KnownHostsPath devuelve la ruta del known_hosts propio (junto a la clave).
+func KnownHostsPath(keyPath string) string {
+	return filepath.Join(filepath.Dir(keyPath), "known_hosts")
+}
+
+// EnsureKeypair garantiza que existe el par de claves en keyPath
+// (ssh-keygen -t ed25519 -N '' -C netpulse); best-effort en permisos.
+func EnsureKeypair(keyPath string) error {
+	if _, err := os.Stat(keyPath); err == nil {
+		if _, err := os.Stat(keyPath + ".pub"); err == nil {
+			return nil
+		}
+	}
+	if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
+		return err
+	}
+	cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "", "-C", "netpulse", "-q")
+	if out, err := cmd.CombinedOutput(); err != nil {
+		return &ExecError{What: "ssh-keygen", Err: err, Out: string(out)}
+	}
+	_ = os.Chmod(filepath.Dir(keyPath), 0o700)
+	_ = os.Chmod(keyPath, 0o600)
+	return nil
+}
+
+// ExecError envuelve un fallo de proceso externo.
+type ExecError struct {
+	What string
+	Err  error
+	Out  string
+}
+
+func (e *ExecError) Error() string { return e.What + ": " + e.Err.Error() + " " + strings.TrimSpace(e.Out) }
+func (e *ExecError) Unwrap() error { return e.Err }
+
+// PublicKey es la respuesta de /api/config/sshkey.
+type PublicKey struct {
+	PublicKey   string `json:"publicKey"`
+	Fingerprint string `json:"fingerprint"`
+}
+
+var fpRe = regexp.MustCompile(`^\d+\s+(\S+)`)
+
+// GetPublicKey lee la clave pública y su fingerprint (ssh-keygen -lf, 2º
+// campo). Devuelve (nil, nil) si no se puede leer (→ 500 no_key).
+func GetPublicKey(keyPath string) *PublicKey {
+	data, err := os.ReadFile(keyPath + ".pub")
+	if err != nil {
+		return nil
+	}
+	pub := strings.TrimSpace(string(data))
+	out, err := exec.Command("ssh-keygen", "-lf", keyPath+".pub").Output()
+	fp := ""
+	if err == nil {
+		if m := fpRe.FindStringSubmatch(strings.TrimSpace(string(out))); m != nil {
+			fp = m[1]
+		}
+	}
+	return &PublicKey{PublicKey: pub, Fingerprint: fp}
+}

+ 133 - 0
server-go/internal/staticspa/staticspa.go

@@ -0,0 +1,133 @@
+// Package staticspa — estáticos + SPA fallback (paridad app.js:44-60).
+//
+//   - Sirve ficheros existentes del root (STATIC_DIR del env si se define;
+//     si no, el dist EMBEBIDO — ver abajo).
+//   - index.html se cachea en memoria al arranque; si falta → warning y el
+//     fallback devuelve 503 texto.
+//   - Fallback GET: /api/* → 404 JSON {error:'not_found'}; /assets/* → 404
+//     plano; resto → 200 HTML con el index.html cacheado (SPA fallback).
+//
+// EMBED: go:embed no puede referenciar ../../app/dist (fuera del módulo), así
+// que el binario embebe internal/staticspa/dist. CI debe copiar app/dist a
+// server-go/internal/staticspa/dist antes de `go build` (hasta entonces hay
+// un index.html placeholder). STATIC_DIR siempre tiene prioridad sobre el
+// embed (override para desarrollo/despliegue clásico).
+package staticspa
+
+import (
+	"embed"
+	"io"
+	"io/fs"
+	"log"
+	"net/http"
+	"os"
+	"path"
+	"strings"
+)
+
+//go:embed dist
+var embeddedDist embed.FS
+
+// Handler sirve los estáticos y el SPA fallback.
+type Handler struct {
+	files     fs.FS
+	indexHTML []byte // nil si no hay index.html
+}
+
+// New crea el handler. Si staticDir != "" sirve ese directorio del disco
+// (override STATIC_DIR); si no, usa el dist embebido en el binario.
+// Lee index.html en memoria al arranque (warning si falta, como app.js:51).
+func New(staticDir string) *Handler {
+	h := &Handler{}
+	desc := staticDir
+	if staticDir != "" {
+		h.files = os.DirFS(staticDir)
+	} else {
+		sub, err := fs.Sub(embeddedDist, "dist")
+		if err != nil {
+			sub = embeddedDist
+		}
+		h.files = sub
+		desc = "(embed)"
+	}
+	if data, err := fs.ReadFile(h.files, "index.html"); err == nil {
+		h.indexHTML = data
+	} else {
+		log.Printf("[netpulse] STATIC_DIR=%s sin index.html (¿falta \"npm run build\" en app/?)", desc)
+	}
+	return h
+}
+
+// serveFile sirve el fichero `name` si existe y no es directorio.
+func (h *Handler) serveFile(w http.ResponseWriter, r *http.Request, name string) bool {
+	if !fs.ValidPath(name) {
+		return false
+	}
+	f, err := h.files.Open(name)
+	if err != nil {
+		return false
+	}
+	defer f.Close()
+	st, err := f.Stat()
+	if err != nil || st.IsDir() {
+		return false
+	}
+	rs, ok := f.(io.ReadSeeker)
+	if !ok {
+		return false
+	}
+	http.ServeContent(w, r, st.Name(), st.ModTime(), rs)
+	return true
+}
+
+// notFoundPlain replica el 404 por defecto de Hono (c.notFound()): cuerpo de
+// texto "404 Not Found", no el "404 page not found\n" de net/http.
+func notFoundPlain(w http.ResponseWriter) {
+	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+	w.WriteHeader(http.StatusNotFound)
+	_, _ = w.Write([]byte("404 Not Found"))
+}
+
+// ServeHTTP implementa http.Handler: estático si existe; si no, fallback.
+func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+	p := r.URL.Path
+
+	// /api/* nunca llega aquí (el mux lo enruta antes), pero por seguridad:
+	if strings.HasPrefix(p, "/api/") {
+		w.Header().Set("Content-Type", "application/json")
+		w.WriteHeader(http.StatusNotFound)
+		_, _ = w.Write([]byte(`{"error":"not_found"}`))
+		return
+	}
+	if r.Method != http.MethodGet && r.Method != http.MethodHead {
+		notFoundPlain(w)
+		return
+	}
+
+	// Estático: sirve el fichero si existe (raíz → index.html).
+	name := strings.TrimPrefix(path.Clean("/"+p), "/")
+	if name == "" {
+		name = "index.html"
+	}
+	if h.serveFile(w, r, name) {
+		return
+	}
+	if h.serveFile(w, r, path.Join(name, "index.html")) {
+		return
+	}
+
+	// Fallback (GET *):
+	if strings.HasPrefix(p, "/assets/") {
+		notFoundPlain(w) // 404 plano, sin JSON (cuerpo "404 Not Found" como Hono)
+		return
+	}
+	if h.indexHTML == nil {
+		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+		w.WriteHeader(http.StatusServiceUnavailable)
+		_, _ = w.Write([]byte("NetPulse: frontend no compilado (cd app && npm run build)"))
+		return
+	}
+	w.Header().Set("Content-Type", "text/html; charset=utf-8")
+	w.WriteHeader(http.StatusOK)
+	_, _ = w.Write(h.indexHTML)
+}

+ 362 - 0
server-go/internal/updater/updater.go

@@ -0,0 +1,362 @@
+// Package updater — actualizador (paridad src/updater.js, SPEC §9): chequea
+// el último commit de main en la API de GitHub al arrancar y cada 6 h, y
+// aplica la actualización lanzando deploy/update.sh (copiado antes a /tmp:
+// el propio update hace git reset --hard y reescribiría el script). El
+// binario Go se actualiza por el mismo mecanismo de script externo.
+package updater
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"regexp"
+	"strings"
+	"sync"
+	"time"
+)
+
+const (
+	checkInterval = 6 * time.Hour
+	httpTimeout   = 8 * time.Second
+	logTail       = 4000
+	statusLogTail = 800
+)
+
+// APIBase es la base de la API de GitHub (inyectable en tests).
+var APIBase = "https://api.github.com"
+
+type progress struct {
+	Step string `json:"step"`
+}
+
+// Status es la respuesta de /api/update/status (shape literal de updater.js:
+// updating es false | {step}; lastLog son los últimos 800 chars).
+type Status struct {
+	Current         string  `json:"current"`
+	Latest          *string `json:"latest"`
+	LatestMsg       *string `json:"latestMsg"`
+	UpdateAvailable bool    `json:"updateAvailable"`
+	LastCheck       *int64  `json:"lastCheck"`
+	Updating        any     `json:"updating"` // false | {"step": ...}
+	Error           *string `json:"error"`
+	LastLog         *string `json:"lastLog"`
+	Repo            string  `json:"repo"`
+	HasToken        bool    `json:"hasToken"`
+}
+
+// Updater mantiene el estado y los timers (como createUpdater).
+type Updater struct {
+	repoRoot string
+	repo     string
+	token    string
+
+	mu           sync.Mutex
+	current      string
+	latest       *string
+	latestMsg    *string
+	updateAvail  bool
+	lastCheck    *int64
+	updatingStep *string // nil = no actualizando
+	updatingLog  string
+	lastLog      *string
+	err          *string
+
+	stopCh chan struct{}
+	wg     sync.WaitGroup
+}
+
+// New crea el updater (repoRoot = padre de serverRoot, como index.js).
+func New(repoRoot, repo, token string) *Updater {
+	return &Updater{
+		repoRoot: repoRoot,
+		repo:     repo,
+		token:    token,
+		current:  "desconocido",
+		stopCh:   make(chan struct{}),
+	}
+}
+
+func gitShort(repoRoot string) string {
+	out, err := exec.Command("git", "-C", repoRoot, "rev-parse", "--short", "HEAD").Output()
+	if err != nil {
+		return ""
+	}
+	return strings.TrimSpace(string(out))
+}
+
+// fetchLatest consulta el último commit de main (errores → {error: ...}).
+func (u *Updater) fetchLatest(ctx context.Context) (sha, msg string, errCode string) {
+	req, err := http.NewRequestWithContext(ctx, "GET",
+		fmt.Sprintf("%s/repos/%s/commits/main", APIBase, u.repo), nil)
+	if err != nil {
+		return "", "", "network"
+	}
+	req.Header.Set("Accept", "application/vnd.github+json")
+	req.Header.Set("User-Agent", "netpulse-updater")
+	req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+	if u.token != "" {
+		req.Header.Set("Authorization", "Bearer "+u.token)
+	}
+	client := &http.Client{Timeout: httpTimeout}
+	res, err := client.Do(req)
+	if err != nil {
+		if ctx.Err() != nil {
+			return "", "", "timeout"
+		}
+		return "", "", "network"
+	}
+	defer res.Body.Close()
+	if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
+		if u.token != "" {
+			return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+		}
+		return "", "", "no_token"
+	}
+	if res.StatusCode != 200 {
+		return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+	}
+	var data struct {
+		SHA    string `json:"sha"`
+		Commit struct {
+			Message string `json:"message"`
+		} `json:"commit"`
+	}
+	if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
+		return "", "", "network"
+	}
+	sha = data.SHA
+	if len(sha) > 7 {
+		sha = sha[:7]
+	}
+	msg = strings.Split(data.Commit.Message, "\n")[0]
+	// JS slice(0, 80) corta por UNIDADES UTF-16 (un astral = 2 unidades),
+	// no por bytes: replicar ese cómputo (sin dejar surrogates partidos).
+	units, cut := 0, len(msg)
+	for i, r := range msg {
+		w := 1
+		if r > 0xFFFF {
+			w = 2
+		}
+		if units+w > 80 {
+			cut = i
+			break
+		}
+		units += w
+	}
+	msg = msg[:cut]
+	return sha, msg, ""
+}
+
+// Check fuerza un chequeo contra GitHub y devuelve el estado.
+func (u *Updater) Check(ctx context.Context) Status {
+	current := gitShort(u.repoRoot)
+	if current == "" {
+		current = "desconocido"
+	}
+	sha, msg, errCode := u.fetchLatest(ctx)
+	now := time.Now().UnixMilli()
+
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	u.current = current
+	u.lastCheck = &now
+	if errCode != "" {
+		u.err = &errCode // no_token no es un error visible: el banner no aparece
+		return u.statusLocked()
+	}
+	u.err = nil
+	u.latest = &sha
+	u.latestMsg = &msg
+	u.updateAvail = sha != "" && current != "desconocido" && sha != current
+	if u.updateAvail {
+		fmt.Printf("[netpulse] nueva versión disponible: %s → %s (%s)\n", current, sha, msg)
+	}
+	return u.statusLocked()
+}
+
+var stepRe = regexp.MustCompile(`STEP:(\w+)`)
+
+// Apply lanza update.sh en segundo plano. Devuelve false si ya hay una
+// actualización en curso (→ 409 already_updating) o si no se pudo copiar.
+func (u *Updater) Apply() bool {
+	u.mu.Lock()
+	if u.updatingStep != nil {
+		u.mu.Unlock()
+		return false
+	}
+	startStep := "start"
+	u.updatingStep = &startStep
+	u.updatingLog = ""
+	u.mu.Unlock()
+
+	tmpScript := filepath.Join(os.TempDir(), fmt.Sprintf("netpulse-update-%d.sh", time.Now().UnixMilli()))
+	src, err := os.ReadFile(filepath.Join(u.repoRoot, "deploy", "update.sh"))
+	if err == nil {
+		err = os.WriteFile(tmpScript, src, 0o755)
+	}
+	if err != nil {
+		u.mu.Lock()
+		u.updatingStep = nil
+		code := "update_copy_failed"
+		u.err = &code
+		u.mu.Unlock()
+		fmt.Printf("[netpulse] no se pudo copiar update.sh: %v\n", err)
+		return false
+	}
+
+	cmd := exec.Command("bash", tmpScript)
+	cmd.Dir = u.repoRoot
+	cmd.Env = append(os.Environ(), "NODE_OPTIONS=--max-old-space-size=400")
+	stdout, err := cmd.StdoutPipe()
+	if err != nil {
+		u.mu.Lock()
+		u.updatingStep = nil
+		u.mu.Unlock()
+		return false
+	}
+	cmd.Stderr = &tailWriter{u: u}
+	if err := cmd.Start(); err != nil {
+		u.mu.Lock()
+		u.updatingStep = nil
+		u.mu.Unlock()
+		return false
+	}
+	u.wg.Add(1)
+	go func() {
+		defer u.wg.Done()
+		buf := make([]byte, 4096)
+		for {
+			n, err := stdout.Read(buf)
+			if n > 0 {
+				u.appendLog(string(buf[:n]), true)
+			}
+			if err != nil {
+				break
+			}
+		}
+		waitErr := cmd.Wait()
+		u.mu.Lock()
+		defer u.mu.Unlock()
+		if waitErr == nil {
+			step := "done"
+			u.updatingStep = &step
+			log := u.updatingLog
+			u.lastLog = &log
+			u.updateAvail = false
+		} else {
+			if ee, ok := waitErr.(*exec.ExitError); ok {
+				log := u.updatingLog
+				u.lastLog = &log
+				u.updatingStep = nil
+				code := fmt.Sprintf("update_exit_%d", ee.ExitCode())
+				u.err = &code
+			} else {
+				u.updatingStep = nil
+				code := "update_exit_-1"
+				u.err = &code
+			}
+		}
+	}()
+	return true
+}
+
+// appendLog acumula el log (tail 4000) y extrae STEP:xxx del stdout.
+func (u *Updater) appendLog(text string, parseStep bool) {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	u.updatingLog = tail(u.updatingLog+text, logTail)
+	if parseStep {
+		if m := stepRe.FindStringSubmatch(text); m != nil {
+			step := m[1]
+			u.updatingStep = &step
+		}
+		fmt.Printf("[netpulse:update] %s\n", strings.TrimSpace(text))
+	}
+}
+
+func tail(s string, n int) string {
+	if len(s) > n {
+		return s[len(s)-n:]
+	}
+	return s
+}
+
+// tailWriter captura stderr al log.
+type tailWriter struct{ u *Updater }
+
+func (w *tailWriter) Write(p []byte) (int, error) {
+	w.u.appendLog(string(p), false)
+	return len(p), nil
+}
+
+// Status devuelve el estado actual (shape de la API).
+func (u *Updater) Status() Status {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	return u.statusLocked()
+}
+
+func (u *Updater) statusLocked() Status {
+	var updating any = false
+	if u.updatingStep != nil {
+		updating = progress{Step: *u.updatingStep}
+	}
+	var lastLog *string
+	if u.updatingStep != nil {
+		// JS: state.updating?.log?.slice(-800) ?? state.lastLog ?? null
+		l := tail(u.updatingLog, statusLogTail)
+		lastLog = &l
+	} else {
+		lastLog = u.lastLog
+	}
+	return Status{
+		Current:         u.current,
+		Latest:          u.latest,
+		LatestMsg:       u.latestMsg,
+		UpdateAvailable: u.updateAvail,
+		LastCheck:       u.lastCheck,
+		Updating:        updating,
+		Error:           u.err,
+		LastLog:         lastLog,
+		Repo:            u.repo,
+		HasToken:        u.token != "",
+	}
+}
+
+// Start lanza el chequeo inicial y el timer de 6 h (paridad start()).
+func (u *Updater) Start() {
+	u.wg.Add(1)
+	go func() {
+		defer u.wg.Done()
+		ctx, cancel := context.WithTimeout(context.Background(), httpTimeout+2*time.Second)
+		u.Check(ctx)
+		cancel()
+		t := time.NewTicker(checkInterval)
+		defer t.Stop()
+		for {
+			select {
+			case <-u.stopCh:
+				return
+			case <-t.C:
+				ctx, cancel := context.WithTimeout(context.Background(), httpTimeout+2*time.Second)
+				u.Check(ctx)
+				cancel()
+			}
+		}
+	}()
+}
+
+// Stop para el timer y espera a los procesos en curso (paridad stop()).
+func (u *Updater) Stop() {
+	select {
+	case <-u.stopCh:
+	default:
+		close(u.stopCh)
+	}
+	u.wg.Wait()
+}

+ 148 - 0
server-go/internal/updater/updater_test.go

@@ -0,0 +1,148 @@
+// updater_test.go — check contra API GitHub simulada (httptest) y shape del
+// estado; apply con script sintético (STEP:*/exit).
+package updater
+
+import (
+	"context"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+)
+
+func gitAvailable() bool { _, err := exec.LookPath("git"); return err == nil }
+
+func withAPI(t *testing.T, h http.HandlerFunc) {
+	t.Helper()
+	srv := httptest.NewServer(h)
+	t.Cleanup(srv.Close)
+	old := APIBase
+	APIBase = srv.URL
+	t.Cleanup(func() { APIBase = old })
+}
+
+func TestCheckUpdateAvailable(t *testing.T) {
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/repos/owner/netpulse/commits/main" {
+			t.Errorf("path: %s", r.URL.Path)
+		}
+		w.Header().Set("Content-Type", "application/json")
+		fmt.Fprint(w, `{"sha":"abc1234deadbeef","commit":{"message":"feat: algo\n\nbody"}}`)
+	})
+	// repoRoot con git válido (commit distinto) para updateAvailable
+	root := t.TempDir()
+	writeGitHead(t, root)
+	u := New(root, "owner/netpulse", "")
+	st := u.Check(context.Background())
+	if st.Error != nil {
+		t.Fatalf("error: %v", *st.Error)
+	}
+	if st.Latest == nil || *st.Latest != "abc1234" {
+		t.Fatalf("latest: %v", st.Latest)
+	}
+	if st.LatestMsg == nil || *st.LatestMsg != "feat: algo" {
+		t.Fatalf("latestMsg: %v", st.LatestMsg)
+	}
+	if !st.UpdateAvailable {
+		t.Fatalf("debería haber update: %+v", st)
+	}
+	if st.Updating != false || st.HasToken || st.Repo != "owner/netpulse" {
+		t.Fatalf("shape: %+v", st)
+	}
+	if st.LastCheck == nil {
+		t.Fatal("lastCheck nil")
+	}
+}
+
+func TestCheckNoToken(t *testing.T) {
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusNotFound)
+	})
+	u := New(t.TempDir(), "owner/netpulse", "")
+	st := u.Check(context.Background())
+	if st.Error == nil || *st.Error != "no_token" {
+		t.Fatalf("error: %v", st.Error)
+	}
+}
+
+func TestCheckMismaVersion(t *testing.T) {
+	root := t.TempDir()
+	short := writeGitHead(t, root)
+	withAPI(t, func(w http.ResponseWriter, r *http.Request) {
+		fmt.Fprintf(w, `{"sha":"%sffffffffff","commit":{"message":"x"}}`, short)
+	})
+	u := New(root, "owner/netpulse", "")
+	st := u.Check(context.Background())
+	if st.UpdateAvailable {
+		t.Fatal("no debería haber update")
+	}
+}
+
+// writeGitHead crea un repo git mínimo con un commit y devuelve su short SHA.
+func writeGitHead(t *testing.T, root string) string {
+	t.Helper()
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	run := func(args ...string) {
+		cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
+		if out, err := cmd.CombinedOutput(); err != nil {
+			t.Fatalf("git %v: %v %s", args, err, out)
+		}
+	}
+	run("init", "-q")
+	run("config", "user.email", "t@t")
+	run("config", "user.name", "t")
+	if err := os.WriteFile(filepath.Join(root, "f"), []byte("x"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	run("add", ".")
+	run("commit", "-qm", "init")
+	out, err := exec.Command("git", "-C", root, "rev-parse", "--short", "HEAD").Output()
+	if err != nil {
+		t.Fatal(err)
+	}
+	return strings.TrimSpace(string(out))
+}
+
+func TestApplyYaEnCursoYScript(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	script := "#!/bin/bash\necho STEP:backend\nsleep 0.1\necho STEP:done-steps\ntrue\n"
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	u := New(root, "owner/netpulse", "")
+	if !u.Apply() {
+		t.Fatal("apply debería arrancar")
+	}
+	// Segundo apply concurrente → 409 already_updating
+	if u.Apply() {
+		t.Fatal("apply duplicado debería ser false")
+	}
+	deadline := time.Now().Add(5 * time.Second)
+	for {
+		st := u.Status()
+		if m, ok := st.Updating.(progress); ok && m.Step == "done" {
+			break
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("timeout esperando done: %+v", st)
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	st := u.Status()
+	if st.LastLog == nil || *st.LastLog == "" {
+		t.Fatalf("lastLog: %+v", st)
+	}
+}