فهرست منبع

chore: remove legacy Node backend (dead code, closes stale hono alerts) (#189)

* fix(app): bump transitive nanoid to 3.3.18 (CVE custom generators loop)

* chore: remove legacy Node backend (dead code, closes stale hono alerts)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 ماه پیش
والد
کامیت
3567030971
40فایلهای تغییر یافته به همراه11 افزوده شده و 5935 حذف شده
  1. 3 3
      ARCHITECTURE.md
  2. 3 3
      README.es.md
  3. 3 3
      README.md
  4. 0 49
      deploy/netpulse.service
  5. 2 2
      deploy/update.sh
  6. 0 21
      legacy/server-node/.env.example
  7. 0 27
      legacy/server-node/README.md
  8. 0 510
      legacy/server-node/package-lock.json
  9. 0 25
      legacy/server-node/package.json
  10. 0 163
      legacy/server-node/src/adapters/adguard-glinet.js
  11. 0 75
      legacy/server-node/src/adapters/adguard.js
  12. 0 224
      legacy/server-node/src/adapters/demo.js
  13. 0 803
      legacy/server-node/src/adapters/index.js
  14. 0 451
      legacy/server-node/src/adapters/openwrt.js
  15. 0 112
      legacy/server-node/src/adapters/wireguard.js
  16. 0 70
      legacy/server-node/src/app.js
  17. 0 278
      legacy/server-node/src/auth.js
  18. 0 111
      legacy/server-node/src/config.js
  19. 0 150
      legacy/server-node/src/db.js
  20. 0 913
      legacy/server-node/src/demo/dataset.js
  21. 0 214
      legacy/server-node/src/discover.js
  22. 0 28
      legacy/server-node/src/health.js
  23. 0 89
      legacy/server-node/src/index.js
  24. 0 78
      legacy/server-node/src/poller.js
  25. 0 158
      legacy/server-node/src/routerstore.js
  26. 0 85
      legacy/server-node/src/routes/auth.js
  27. 0 117
      legacy/server-node/src/routes/config.js
  28. 0 125
      legacy/server-node/src/routes/data.js
  29. 0 25
      legacy/server-node/src/routes/update.js
  30. 0 130
      legacy/server-node/src/routes/users.js
  31. 0 19
      legacy/server-node/src/security.js
  32. 0 90
      legacy/server-node/src/sse.js
  33. 0 57
      legacy/server-node/src/sshkey.js
  34. 0 151
      legacy/server-node/src/updater.js
  35. 0 95
      legacy/server-node/tests/auth.test.js
  36. 0 74
      legacy/server-node/tests/devices.test.js
  37. 0 59
      legacy/server-node/tests/helpers.js
  38. 0 115
      legacy/server-node/tests/routers.test.js
  39. 0 119
      legacy/server-node/tests/snapshot.test.js
  40. 0 114
      legacy/server-node/tests/users.test.js

+ 3 - 3
ARCHITECTURE.md

@@ -1,8 +1,8 @@
 # NetPulse — Arquitectura
 
-> v2.0.0 (era Go). El backend Node legado vive en `legacy/server-node/` como
-> histórico (decisión 5-Ago-2026: no se despliega ni se actualiza; ver README).
-> El backend activo es `server-go/`.
+> v2.0.0 (era Go). El backend Node legado fue eliminado (decisión 5-Ago-2026: no
+> se despliega ni se actualiza; su historial git se conserva). El backend activo
+> es `server-go/`.
 
 ## Vista de capas
 

+ 3 - 3
README.es.md

@@ -190,9 +190,9 @@ npm install
 npm run dev
 ```
 
-El backend Node legado se conserva en `legacy/server-node/` solo como histórico
-(decisión 5-Ago-2026: no se despliega ni se actualiza); la migración desde su
-base de datos ocurre automáticamente en el primer arranque Go.
+El backend Node legado fue eliminado (decisión 5-Ago-2026: no se despliega ni se
+actualiza); su historial git se conserva. La migración desde su base de datos
+ocurre automáticamente en el primer arranque Go.
 
 ## Tests
 

+ 3 - 3
README.md

@@ -186,9 +186,9 @@ npm install
 npm run dev
 ```
 
-The legacy Node backend is kept under `legacy/server-node/` as history only
-(decision 5-Ago-2026: it is not deployed or updated anymore); migration from
-its database happens automatically on the first Go boot.
+The legacy Node backend was removed (it is not deployed or updated anymore,
+decision 5-Ago-2026); its git history is preserved. Migration from its
+database happens automatically on the first Go boot.
 
 ## Tests
 

+ 0 - 49
deploy/netpulse.service

@@ -1,49 +0,0 @@
-# NetPulse — unit systemd (BACKEND NODE LEGACY, SOLO HISTÓRICO)
-# ⚠️ DECISIÓN 5-Ago-2026: el backend Go (deploy/netpulse-go.service) es el
-# único desplegable. Esta unidad se conserva como referencia del fallback Node
-# antiguo (legacy/server-node/) pero NO se usa en nuevos deploys.
-# NOTA: la skill 'infraestructura' del usuario refinará este fichero en el
-# despliegue real (puerto 80 con CAP_NET_BIND_SERVICE, reverse proxy HTTPS, etc).
-# Esta unidad es el punto de partida razonable: usuario dedicado, hardening
-# básico y arranque tras la red.
-#
-# Instalación (NO usar; solo histórico):
-#   sudo useradd --system --home /opt/netpulse --shell /usr/sbin/nologin netpulse
-#   sudo cp deploy/netpulse.service /etc/systemd/system/
-#   sudo systemctl daemon-reload && sudo systemctl enable --now netpulse
-
-[Unit]
-Description=NetPulse — 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/legacy/server-node
-EnvironmentFile=/opt/netpulse/legacy/server-node/.env
-# NODE_ENV ya viene en .env; descomentar para forzar:
-#Environment=NODE_ENV=production
-ExecStart=/usr/bin/node src/index.js
-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 /opt/netpulse/server/data/.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

+ 2 - 2
deploy/update.sh

@@ -3,8 +3,8 @@
 # como netpulse). Único flujo soportado: Go.
 #   - Go   (/opt/netpulse/server-go/netpulse): git pull → binario precompilado
 #          de CI (go-latest) → swap atómico → reinicio diferido.
-# El backend Node (legacy/server-node/) se conserva solo como histórico; NO se
-# despliega ni actualiza (decisión 5-Ago-2026).
+# El backend Node legado fue eliminado; solo existe el flujo Go (decisión
+# 5-Ago-2026).
 set -e
 cd /opt/netpulse
 

+ 0 - 21
legacy/server-node/.env.example

@@ -1,21 +0,0 @@
-PORT=3000
-NODE_ENV=production
-STATIC_DIR=../app/dist
-DATA_DIR=./data
-SESSION_SECRET=            # opcional; autogenerado y persistido en kv si falta
-AUTH_USER=admin
-AUTH_PASS=cambia-esto      # hash bcryptjs en kv tras primer login
-DEMO_MODE=0                # 1 = dataset de demostración (sin escribir en la BD)
-MAX_SSE_CLIENTS=10
-
-# --- Modo live ---
-# Routers: la tabla `routers` de SQLite es la fuente de verdad y nace VACÍA.
-# En el primer arranque se autodetecta la puerta de enlace (ip route + sondeo
-# SSH) y el resto se añade desde Ajustes. ROUTERS_JSON solo se usa como
-# semilla opcional si la tabla está vacía.
-# ROUTERS_JSON=[{"id":"flint2","name":"Gateway","host":"192.168.1.1","type":"glinet"},{"id":"living","host":"192.168.1.2","type":"openwrt"}]
-SSH_KEY_PATH=~/.ssh/id_ed25519
-ADGUARD_URL=http://192.168.1.1
-ADGUARD_USER=admin
-ADGUARD_PASS=
-WG_INTERFACE=wg0

+ 0 - 27
legacy/server-node/README.md

@@ -1,27 +0,0 @@
-# legacy/server-node — backend Node (HISTÓRICO)
-
-**Estado: histórico desde el 5-Ago-2026.** El backend activo es
-[`server-go/`](../../server-go/) (reescritura en Go con paridad funcional
-verificada). Este backend Node se conserva **solo como histórico/referencia** —
-no se despliega ni se actualiza (decisión del usuario 5-Ago-2026: Go estable,
-fuera de los nuevos deploys).
-
-No recibe features nuevas ni fixes.
-
-## Referencia (lo que fue el flujo de rollback)
-
-```bash
-systemctl disable --now netpulse-go.service
-systemctl enable --now netpulse.service
-```
-
-- El Node arrancaba sobre el mismo `DATA_DIR` (`/opt/netpulse/server/data`) — la
-  BD compartida era compatible en ambos sentidos (verificado el 1-Ago-2026:
-  Node arrancando contra la BD ya migrada por Go: `/api/health` OK, login OK).
-- Si la BD estuviera corrupta o incompatible: restaurar
-  `/opt/netpulse/server/data/netpulse.db.bak-<timestamp>` (backup automático
-  de la migración Node→Go).
-- El updater en modo Node usa el flujo legacy de `deploy/update.sh`
-  (dist precompilado de la prerelease `dist-latest`); el flag de reinicio
-  vuelve a ser `/opt/netpulse/server/data/.restart-me` (unidad
-  `netpulse-restart.path`, que se conserva activa en el CT).

+ 0 - 510
legacy/server-node/package-lock.json

@@ -1,510 +0,0 @@
-{
-  "name": "netpulse-server",
-  "version": "1.0.0",
-  "lockfileVersion": 3,
-  "requires": true,
-  "packages": {
-    "": {
-      "name": "netpulse-server",
-      "version": "1.0.0",
-      "dependencies": {
-        "@hono/node-server": "^1.13.7",
-        "bcryptjs": "^2.4.3",
-        "better-sqlite3": "^12.2.0",
-        "hono": "^4.6.14",
-        "zod": "^3.23.8"
-      },
-      "engines": {
-        "node": ">=22"
-      }
-    },
-    "node_modules/@hono/node-server": {
-      "version": "1.19.17",
-      "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",
-      "integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",
-      "license": "MIT",
-      "engines": {
-        "node": ">=18.14.1"
-      },
-      "peerDependencies": {
-        "hono": "^4"
-      }
-    },
-    "node_modules/base64-js": {
-      "version": "1.5.1",
-      "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
-      "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
-      "funding": [
-        {
-          "type": "github",
-          "url": "https://github.com/sponsors/feross"
-        },
-        {
-          "type": "patreon",
-          "url": "https://www.patreon.com/feross"
-        },
-        {
-          "type": "consulting",
-          "url": "https://feross.org/support"
-        }
-      ],
-      "license": "MIT"
-    },
-    "node_modules/bcryptjs": {
-      "version": "2.4.3",
-      "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
-      "integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==",
-      "license": "MIT"
-    },
-    "node_modules/better-sqlite3": {
-      "version": "12.11.1",
-      "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz",
-      "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==",
-      "hasInstallScript": true,
-      "license": "MIT",
-      "dependencies": {
-        "bindings": "^1.5.0",
-        "prebuild-install": "^7.1.1"
-      },
-      "engines": {
-        "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x"
-      }
-    },
-    "node_modules/bindings": {
-      "version": "1.5.0",
-      "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
-      "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
-      "license": "MIT",
-      "dependencies": {
-        "file-uri-to-path": "1.0.0"
-      }
-    },
-    "node_modules/bl": {
-      "version": "4.1.0",
-      "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
-      "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
-      "license": "MIT",
-      "dependencies": {
-        "buffer": "^5.5.0",
-        "inherits": "^2.0.4",
-        "readable-stream": "^3.4.0"
-      }
-    },
-    "node_modules/buffer": {
-      "version": "5.7.1",
-      "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
-      "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
-      "funding": [
-        {
-          "type": "github",
-          "url": "https://github.com/sponsors/feross"
-        },
-        {
-          "type": "patreon",
-          "url": "https://www.patreon.com/feross"
-        },
-        {
-          "type": "consulting",
-          "url": "https://feross.org/support"
-        }
-      ],
-      "license": "MIT",
-      "dependencies": {
-        "base64-js": "^1.3.1",
-        "ieee754": "^1.1.13"
-      }
-    },
-    "node_modules/chownr": {
-      "version": "1.1.4",
-      "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
-      "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
-      "license": "ISC"
-    },
-    "node_modules/decompress-response": {
-      "version": "6.0.0",
-      "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
-      "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
-      "license": "MIT",
-      "dependencies": {
-        "mimic-response": "^3.1.0"
-      },
-      "engines": {
-        "node": ">=10"
-      },
-      "funding": {
-        "url": "https://github.com/sponsors/sindresorhus"
-      }
-    },
-    "node_modules/deep-extend": {
-      "version": "0.6.0",
-      "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
-      "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
-      "license": "MIT",
-      "engines": {
-        "node": ">=4.0.0"
-      }
-    },
-    "node_modules/detect-libc": {
-      "version": "2.1.2",
-      "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
-      "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
-      "license": "Apache-2.0",
-      "engines": {
-        "node": ">=8"
-      }
-    },
-    "node_modules/end-of-stream": {
-      "version": "1.4.5",
-      "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
-      "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
-      "license": "MIT",
-      "dependencies": {
-        "once": "^1.4.0"
-      }
-    },
-    "node_modules/expand-template": {
-      "version": "2.0.3",
-      "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
-      "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
-      "license": "(MIT OR WTFPL)",
-      "engines": {
-        "node": ">=6"
-      }
-    },
-    "node_modules/file-uri-to-path": {
-      "version": "1.0.0",
-      "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
-      "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
-      "license": "MIT"
-    },
-    "node_modules/fs-constants": {
-      "version": "1.0.0",
-      "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
-      "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
-      "license": "MIT"
-    },
-    "node_modules/github-from-package": {
-      "version": "0.0.0",
-      "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
-      "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
-      "license": "MIT"
-    },
-    "node_modules/hono": {
-      "version": "4.12.33",
-      "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.33.tgz",
-      "integrity": "sha512-+SwvkaiJtxsiPjhy9LivY/1m7UsNqCJetM1BrZl9A5DkQhlbHQDU730mMiDPWjnoCYOM8Chf3WrCJw27kNTPFQ==",
-      "license": "MIT",
-      "engines": {
-        "node": ">=16.9.0"
-      }
-    },
-    "node_modules/ieee754": {
-      "version": "1.2.1",
-      "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
-      "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
-      "funding": [
-        {
-          "type": "github",
-          "url": "https://github.com/sponsors/feross"
-        },
-        {
-          "type": "patreon",
-          "url": "https://www.patreon.com/feross"
-        },
-        {
-          "type": "consulting",
-          "url": "https://feross.org/support"
-        }
-      ],
-      "license": "BSD-3-Clause"
-    },
-    "node_modules/inherits": {
-      "version": "2.0.4",
-      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
-      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
-      "license": "ISC"
-    },
-    "node_modules/ini": {
-      "version": "1.3.8",
-      "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
-      "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
-      "license": "ISC"
-    },
-    "node_modules/mimic-response": {
-      "version": "3.1.0",
-      "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
-      "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
-      "license": "MIT",
-      "engines": {
-        "node": ">=10"
-      },
-      "funding": {
-        "url": "https://github.com/sponsors/sindresorhus"
-      }
-    },
-    "node_modules/minimist": {
-      "version": "1.2.8",
-      "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
-      "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
-      "license": "MIT",
-      "funding": {
-        "url": "https://github.com/sponsors/ljharb"
-      }
-    },
-    "node_modules/mkdirp-classic": {
-      "version": "0.5.3",
-      "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
-      "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
-      "license": "MIT"
-    },
-    "node_modules/napi-build-utils": {
-      "version": "2.0.0",
-      "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
-      "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
-      "license": "MIT"
-    },
-    "node_modules/node-abi": {
-      "version": "3.94.0",
-      "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz",
-      "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==",
-      "license": "MIT",
-      "dependencies": {
-        "semver": "^7.3.5"
-      },
-      "engines": {
-        "node": ">=10"
-      }
-    },
-    "node_modules/once": {
-      "version": "1.4.0",
-      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
-      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
-      "license": "ISC",
-      "dependencies": {
-        "wrappy": "1"
-      }
-    },
-    "node_modules/prebuild-install": {
-      "version": "7.1.3",
-      "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
-      "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
-      "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
-      "license": "MIT",
-      "dependencies": {
-        "detect-libc": "^2.0.0",
-        "expand-template": "^2.0.3",
-        "github-from-package": "0.0.0",
-        "minimist": "^1.2.3",
-        "mkdirp-classic": "^0.5.3",
-        "napi-build-utils": "^2.0.0",
-        "node-abi": "^3.3.0",
-        "pump": "^3.0.0",
-        "rc": "^1.2.7",
-        "simple-get": "^4.0.0",
-        "tar-fs": "^2.0.0",
-        "tunnel-agent": "^0.6.0"
-      },
-      "bin": {
-        "prebuild-install": "bin.js"
-      },
-      "engines": {
-        "node": ">=10"
-      }
-    },
-    "node_modules/pump": {
-      "version": "3.0.4",
-      "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
-      "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
-      "license": "MIT",
-      "dependencies": {
-        "end-of-stream": "^1.1.0",
-        "once": "^1.3.1"
-      }
-    },
-    "node_modules/rc": {
-      "version": "1.2.8",
-      "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
-      "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
-      "license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
-      "dependencies": {
-        "deep-extend": "^0.6.0",
-        "ini": "~1.3.0",
-        "minimist": "^1.2.0",
-        "strip-json-comments": "~2.0.1"
-      },
-      "bin": {
-        "rc": "cli.js"
-      }
-    },
-    "node_modules/readable-stream": {
-      "version": "3.6.2",
-      "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
-      "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
-      "license": "MIT",
-      "dependencies": {
-        "inherits": "^2.0.3",
-        "string_decoder": "^1.1.1",
-        "util-deprecate": "^1.0.1"
-      },
-      "engines": {
-        "node": ">= 6"
-      }
-    },
-    "node_modules/safe-buffer": {
-      "version": "5.2.1",
-      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
-      "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
-      "funding": [
-        {
-          "type": "github",
-          "url": "https://github.com/sponsors/feross"
-        },
-        {
-          "type": "patreon",
-          "url": "https://www.patreon.com/feross"
-        },
-        {
-          "type": "consulting",
-          "url": "https://feross.org/support"
-        }
-      ],
-      "license": "MIT"
-    },
-    "node_modules/semver": {
-      "version": "7.8.5",
-      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
-      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
-      "license": "ISC",
-      "bin": {
-        "semver": "bin/semver.js"
-      },
-      "engines": {
-        "node": ">=10"
-      }
-    },
-    "node_modules/simple-concat": {
-      "version": "1.0.1",
-      "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
-      "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
-      "funding": [
-        {
-          "type": "github",
-          "url": "https://github.com/sponsors/feross"
-        },
-        {
-          "type": "patreon",
-          "url": "https://www.patreon.com/feross"
-        },
-        {
-          "type": "consulting",
-          "url": "https://feross.org/support"
-        }
-      ],
-      "license": "MIT"
-    },
-    "node_modules/simple-get": {
-      "version": "4.0.1",
-      "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz",
-      "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
-      "funding": [
-        {
-          "type": "github",
-          "url": "https://github.com/sponsors/feross"
-        },
-        {
-          "type": "patreon",
-          "url": "https://www.patreon.com/feross"
-        },
-        {
-          "type": "consulting",
-          "url": "https://feross.org/support"
-        }
-      ],
-      "license": "MIT",
-      "dependencies": {
-        "decompress-response": "^6.0.0",
-        "once": "^1.3.1",
-        "simple-concat": "^1.0.0"
-      }
-    },
-    "node_modules/string_decoder": {
-      "version": "1.3.0",
-      "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
-      "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
-      "license": "MIT",
-      "dependencies": {
-        "safe-buffer": "~5.2.0"
-      }
-    },
-    "node_modules/strip-json-comments": {
-      "version": "2.0.1",
-      "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
-      "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
-      "license": "MIT",
-      "engines": {
-        "node": ">=0.10.0"
-      }
-    },
-    "node_modules/tar-fs": {
-      "version": "2.1.5",
-      "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz",
-      "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==",
-      "license": "MIT",
-      "dependencies": {
-        "chownr": "^1.1.1",
-        "mkdirp-classic": "^0.5.2",
-        "pump": "^3.0.0",
-        "tar-stream": "^2.1.4"
-      }
-    },
-    "node_modules/tar-stream": {
-      "version": "2.2.0",
-      "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
-      "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
-      "license": "MIT",
-      "dependencies": {
-        "bl": "^4.0.3",
-        "end-of-stream": "^1.4.1",
-        "fs-constants": "^1.0.0",
-        "inherits": "^2.0.3",
-        "readable-stream": "^3.1.1"
-      },
-      "engines": {
-        "node": ">=6"
-      }
-    },
-    "node_modules/tunnel-agent": {
-      "version": "0.6.0",
-      "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
-      "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
-      "license": "Apache-2.0",
-      "dependencies": {
-        "safe-buffer": "^5.0.1"
-      },
-      "engines": {
-        "node": "*"
-      }
-    },
-    "node_modules/util-deprecate": {
-      "version": "1.0.2",
-      "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
-      "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
-      "license": "MIT"
-    },
-    "node_modules/wrappy": {
-      "version": "1.0.2",
-      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
-      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
-      "license": "ISC"
-    },
-    "node_modules/zod": {
-      "version": "3.25.76",
-      "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
-      "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
-      "license": "MIT",
-      "funding": {
-        "url": "https://github.com/sponsors/colinhacks"
-      }
-    }
-  }
-}

+ 0 - 25
legacy/server-node/package.json

@@ -1,25 +0,0 @@
-{
-  "name": "netpulse-server",
-  "version": "1.0.0",
-  "private": true,
-  "description": "NetPulse backend — Hono + SQLite (auth single-user, SSE, adapters demo/live)",
-  "type": "module",
-  "engines": {
-    "node": ">=22"
-  },
-  "scripts": {
-    "dev": "node --watch src/index.js",
-    "start": "node src/index.js",
-    "test": "node --test tests/*.test.js"
-  },
-  "dependencies": {
-    "@hono/node-server": "^1.13.7",
-    "bcryptjs": "^2.4.3",
-    "better-sqlite3": "^12.2.0",
-    "hono": "^4.6.14",
-    "zod": "^3.23.8"
-  },
-  "allowScripts": {
-    "better-sqlite3@12.11.1": true
-  }
-}

+ 0 - 163
legacy/server-node/src/adapters/adguard-glinet.js

@@ -1,163 +0,0 @@
-/**
- * Cliente AdGuard Home en firmware GL.iNet:
- *
- * - La API (puerto 3000) exige cookie `Admin-Token` = sesión de la UI GL.
- * - Login GL (/rpc): challenge → salt+nonce+alg → crypt local → login → sid.
- *   Todo se calcula EN el router vía SSH root (openssl passwd), sin
- *   implementar crypt en Node. La contraseña viaja base64 por el canal SSH.
- * - Credenciales: Ajustes → AdGuard (kv en el servidor; nunca vuelven al navegador).
- * - El sid se cachea y se renueva al primer 401.
- */
-import { execFile } from 'node:child_process'
-import { sshBaseArgs } from '../sshkey.js'
-
-const SSH_TIMEOUT_MS = 8000
-const HTTP_TIMEOUT_MS = 4000
-const LOGIN_COOLDOWN_MS = 15 * 60 * 1000 // el GL bloquea logins tras N fallos; no alimentar el lockout
-
-export class AdGuardGlinetClient {
-  /**
-   * @param {{ host: string, user: string, pass: string, sshKeyPath: string }} cfg
-   */
-  constructor(cfg) {
-    this.host = cfg.host
-    this.user = cfg.user
-    this.pass = cfg.pass
-    this.sshKeyPath = cfg.sshKeyPath
-    this.sid = null
-  }
-
-  ssh(cmd, timeoutMs = SSH_TIMEOUT_MS) {
-    return new Promise((resolve, reject) => {
-      execFile(
-        'ssh',
-        [...sshBaseArgs(this.sshKeyPath), '-o', 'ControlMaster=no', `root@${this.host}`, cmd],
-        { timeout: timeoutMs, maxBuffer: 1024 * 1024 },
-        (err, stdout) => {
-          // NUNCA incluir el comando (lleva la contraseña embebida)
-          if (err) return reject(new Error(`ssh ${this.host}: exit ${err.code ?? err.message}`))
-          resolve(stdout)
-        },
-      )
-    })
-  }
-
-  /** Login GL completo en el router → sid (cookie Admin-Token).
-   *  Flujo (del propio binario gl-ngx-session):
-   *    challenge → nonce+salt+alg → pw=openssl passwd -alg -salt salt pass
-   *    → hash=sha256("<user>:<pw>:<nonce>") → login → sid */
-  async login() {
-    // Cooldown tras fallo: el GL bloquea logins tras N intentos (600 s)
-    if (this.loginFailUntil && Date.now() < this.loginFailUntil) {
-      throw new Error(`login GL en cooldown (${Math.ceil((this.loginFailUntil - Date.now()) / 1000)} s)`)
-    }
-    // Contraseña embebida con escaping de comillas simples (BusyBox del GL
-    // NO tiene base64). El resto del flujo va entre comillas dobles seguro.
-    const esc = this.pass.replace(/'/g, `'\\''`)
-    const script = [
-      `PASS='${esc}'`,
-      `RESP=$(ubus call gl-session challenge '{"username":"${this.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 "${this.user}:$PW:$NONCE" | sha256sum | cut -d' ' -f1)`,
-      `RESP2=$(ubus call gl-session login '{"username":"${this.user}","hash":"'$HASH'"}')`,
-      'SID=$(jsonfilter -s "$RESP2" -e \'@.data.sid\')',
-      'echo "SID:$SID"',
-    ].join(' && ')
-    const out = await this.ssh(script).catch((err) => {
-      this.loginFailUntil = Date.now() + LOGIN_COOLDOWN_MS
-      throw err
-    })
-    const m = /^SID:(\S+)$/m.exec(out)
-    if (!m) {
-      this.loginFailUntil = Date.now() + LOGIN_COOLDOWN_MS
-      throw new Error('login GL falló (revisa usuario/contraseña de la UI)')
-    }
-    this.loginFailUntil = 0
-    this.sid = m[1]
-    return this.sid
-  }
-
-  async queryStats() {
-    const ctrl = new AbortController()
-    const timer = setTimeout(() => ctrl.abort(), HTTP_TIMEOUT_MS)
-    try {
-      const res = await fetch(`http://${this.host}:3000/control/stats`, {
-        headers: { Cookie: `Admin-Token=${this.sid}` },
-        signal: ctrl.signal,
-      })
-      if (res.status === 401) throw new Error('401 no autorizado')
-      if (!res.ok) throw new Error(`HTTP ${res.status}`)
-      const data = await res.json()
-      const total = data.num_dns_queries ?? 0
-      const blocked = data.num_blocked_filtering ?? 0
-      const topBlocked = Array.isArray(data.top_blocked_domains)
-        ? data.top_blocked_domains.slice(0, 5).map((d) => {
-            const domain = Object.keys(d)[0] ?? ''
-            return { domain, count: d[domain] ?? 0 }
-          })
-        : []
-      return {
-        host: this.host,
-        port: 3000,
-        status: 'active',
-        queries24h: total,
-        blocked24h: blocked,
-        blockedPct: total > 0 ? +((blocked / total) * 100).toFixed(1) : 0,
-        trackersBlocked: 0,
-        dnsLatencyMs: Math.round((data.avg_processing_time ?? 0) * 1000),
-        clientsUsing: Array.isArray(data.top_clients) ? data.top_clients.length : 0,
-        clientsTotal: Array.isArray(data.top_clients) ? data.top_clients.length : 0,
-        topBlocked,
-        filterLists: 0,
-        rules: 0,
-      }
-    } finally {
-      clearTimeout(timer)
-    }
-  }
-
-  /** Stats con login/relogin automático. */
-  async getStats() {
-    if (!this.sid) await this.login()
-    try {
-      return await this.queryStats()
-    } catch (err) {
-      if (!/401/.test(err.message)) throw err
-      this.sid = null
-      await this.login()
-      return this.queryStats()
-    }
-  }
-
-  /** Lista de clientes que usan AdGuard (/control/clients). */
-  async queryClients() {
-    if (!this.sid) await this.login()
-    const ctrl = new AbortController()
-    const timer = setTimeout(() => ctrl.abort(), HTTP_TIMEOUT_MS)
-    try {
-      const res = await fetch(`http://${this.host}:3000/control/clients`, {
-        headers: { Cookie: `Admin-Token=${this.sid}` },
-        signal: ctrl.signal,
-      })
-      if (res.status === 401) {
-        this.sid = null
-        await this.login()
-        return this.queryClients()
-      }
-      if (!res.ok) throw new Error(`HTTP ${res.status}`)
-      const data = await res.json()
-      const clients = Array.isArray(data.clients) ? data.clients : []
-      return clients.map((cl) => ({
-        name: cl.name || cl.ids?.[0] || '',
-        ip: cl.ids?.[0] ?? '',
-        useGlobalSettings: Boolean(cl.use_global_settings),
-        blockedServices: (cl.blocked_services ?? []).length,
-      }))
-    } finally {
-      clearTimeout(timer)
-    }
-  }
-}

+ 0 - 75
legacy/server-node/src/adapters/adguard.js

@@ -1,75 +0,0 @@
-/**
- * Adapter live para AdGuard Home (API HTTP /control).
- * Basic auth con ADGUARD_USER/ADGUARD_PASS. Timeout corto y errores controlados:
- * si AdGuard no responde, devolvemos status 'inactive' y el poller sigue.
- *
- * NOTA SANDBOX: sin AdGuard real aquí; código defensivo no probado en vivo.
- */
-const HTTP_TIMEOUT_MS = 4000
-
-export class AdGuardClient {
-  /** @param {{ url: string, user: string, pass: string }} cfg url sin barra final */
-  constructor(cfg) {
-    this.url = cfg.url
-    this.auth = 'Basic ' + Buffer.from(`${cfg.user}:${cfg.pass}`).toString('base64')
-  }
-
-  async _get(path) {
-    const ctrl = new AbortController()
-    const timer = setTimeout(() => ctrl.abort(), HTTP_TIMEOUT_MS)
-    try {
-      const res = await fetch(`${this.url}${path}`, {
-        headers: { Authorization: this.auth, Accept: 'application/json' },
-        signal: ctrl.signal,
-      })
-      if (!res.ok) throw new Error(`AdGuard ${path} → HTTP ${res.status}`)
-      return await res.json()
-    } finally {
-      clearTimeout(timer)
-    }
-  }
-
-  /**
-   * Devuelve AdGuardStats (shape del contrato). Lanza si AdGuard está caído;
-   * el caller decide degradar.
-   */
-  async getStats() {
-    const [status, stats, filtering] = await Promise.all([
-      this._get('/control/status'),
-      this._get('/control/stats'),
-      this._get('/control/filtering/status').catch(() => null),
-    ])
-
-    const queries = stats.num_dns_queries ?? 0
-    const blocked = stats.num_blocked_filtering ?? 0
-    const host = new URL(this.url).hostname
-    const port = Number(new URL(this.url).port || 80)
-
-    const filters = filtering?.filters ?? []
-    return {
-      host,
-      port,
-      status: status.protection_enabled && status.running ? 'active' : 'inactive',
-      queries24h: queries,
-      blocked24h: blocked,
-      blockedPct: queries > 0 ? +((blocked / queries) * 100).toFixed(1) : 0,
-      // AdGuard no separa trackers en /control/stats; aproximación: bloqueos
-      // por safebrowsing/parental no incluidos. Mejor esfuerzo.
-      trackersBlocked: stats.num_replaced_safebrowsing != null
-        ? blocked - (stats.num_replaced_safebrowsing + (stats.num_replaced_parental || 0))
-        : blocked,
-      // avg_processing_time viene en segundos (float) → ms
-      dnsLatencyMs: Math.round((stats.avg_processing_time ?? 0) * 1000),
-      clientsUsing: stats.num_clients ?? 0,
-      clientsTotal: stats.num_clients ?? 0,
-      topBlocked: (stats.top_blocked_domains ?? []).slice(0, 5).map((d) =>
-        // versiones nuevas: {domain: count}; viejas: ["domain", count]
-        Array.isArray(d)
-          ? { domain: d[0], count: d[1] }
-          : { domain: Object.keys(d)[0], count: Object.values(d)[0] },
-      ),
-      filterLists: filters.filter((f) => f.enabled).length,
-      rules: filters.reduce((acc, f) => acc + (f.enabled ? f.rules_count || 0 : 0), 0),
-    }
-  }
-}

+ 0 - 224
legacy/server-node/src/adapters/demo.js

@@ -1,224 +0,0 @@
-/**
- * Adapter demo: sirve el dataset canónico (port de mock.ts + routerExtras.ts +
- * devices-data.ts) con un random walk suave en cada tick:
- *   - cpu/ram/temp ±2 máx
- *   - tráfico ±5 %
- *   - latencia WAN acotada 6–11 ms
- *   - bytes WireGuard crecientes (peers activos)
- * El PRIMER snapshot (antes del primer tick) es exactamente el canon.
- */
-import {
-  routers as canonRouters,
-  wan as canonWan,
-  trafficByRange,
-  healthScore,
-  deviceTotals,
-  allDevices,
-  adguard as canonAdguard,
-  wireguard as canonWireguard,
-  alerts as canonAlerts,
-  routerExtras as canonExtras,
-  perfSeries,
-  WAN_LATENCY_24H,
-  WAN_LATENCY_STATS,
-  adguardSeries24h,
-  wgPeerExtras,
-  WG_TOTALS_30D,
-} from '../demo/dataset.js'
-
-const GATEWAY_ID = 'flint2'
-
-// ---------------------------------------------------------------------------
-// Bytes WireGuard: parseo/formato ES ("1,2 GB" ⇄ 1.2e9) para el random walk
-// ---------------------------------------------------------------------------
-
-const UNIT_MULT = { B: 1, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12 }
-
-function parseBytes(str) {
-  const m = /^([\d.,]+)\s*(B|KB|MB|GB|TB)$/.exec(str.trim())
-  if (!m) return 0
-  return Math.round(parseFloat(m[1].replace(/\./g, '').replace(',', '.')) * (UNIT_MULT[m[2]] ?? 1))
-}
-
-function fmtBytes(bytes) {
-  if (bytes >= 1e9) {
-    const v = bytes / 1e9
-    return Number.isInteger(v) ? `${v} GB` : `${v.toFixed(1).replace('.', ',')} GB`
-  }
-  if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`
-  if (bytes >= 1e3) return `${Math.round(bytes / 1e3)} KB`
-  return `${Math.round(bytes)} B`
-}
-
-// ---------------------------------------------------------------------------
-// Random walk helpers
-// ---------------------------------------------------------------------------
-
-const rnd = (min, max) => min + Math.random() * (max - min)
-const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
-/** Entero en ±step del valor anterior, acotado. */
-function walkInt(prev, step, lo, hi) {
-  return clamp(Math.round(prev + rnd(-step, step)), lo, hi)
-}
-/** ±pct % del valor anterior (1 decimal), acotado. */
-function walkPct(prev, pct, lo, hi) {
-  return clamp(+(prev * (1 + rnd(-pct, pct))).toFixed(1), lo, hi)
-}
-
-// ---------------------------------------------------------------------------
-// Adapter
-// ---------------------------------------------------------------------------
-
-export function createDemoAdapter() {
-  // Estado mutable: clon profundo del canon (el canon exportado no se toca)
-  const state = structuredClone({
-    routers: canonRouters,
-    wan: canonWan,
-    adguard: canonAdguard,
-    wireguard: canonWireguard,
-    alerts: canonAlerts,
-    devices: allDevices,
-    extras: canonExtras,
-  })
-  // Peers WG con contadores numéricos internos (rx/tx se formatean al servir)
-  const wgBytes = new Map(
-    state.wireguard.peers.map((p) => [p.id, { rx: parseBytes(p.rx), tx: parseBytes(p.tx), active: p.active }]),
-  )
-
-  /** Random walk suave de un tick (5 s). */
-  function tick() {
-    for (const r of state.routers) {
-      r.cpu = walkInt(r.cpu, 2, 2, 95)
-      r.ram = walkInt(r.ram, 2, 10, 92)
-      r.temp = walkInt(r.temp, 2, 30, 82)
-      const ex = state.extras[r.id]
-      if (ex) ex.trafficNow = walkPct(ex.trafficNow || 0.1, 0.05, 0.05, 950)
-    }
-    state.wan.downMbps = walkPct(state.wan.downMbps, 0.05, 5, 580)
-    state.wan.upMbps = walkPct(state.wan.upMbps, 0.05, 2, 120)
-    state.wan.latencyMs = clamp(walkInt(state.wan.latencyMs, 1, 6, 11), 6, 11)
-    for (const d of state.devices) {
-      if (d.online && d.trafficMbps > 0) {
-        d.trafficMbps = +walkPct(d.trafficMbps, 0.05, 0.001, 950).toFixed(2)
-      }
-    }
-    // AdGuard: contadores siempre crecientes
-    state.adguard.queries24h += Math.round(rnd(2, 10))
-    const newBlocked = Math.round(rnd(0, 2))
-    state.adguard.blocked24h += newBlocked
-    state.adguard.trackersBlocked += Math.round(rnd(0, newBlocked))
-    state.adguard.blockedPct = +((state.adguard.blocked24h / state.adguard.queries24h) * 100).toFixed(1)
-    // WireGuard: bytes crecientes solo en peers activos
-    for (const [id, b] of wgBytes) {
-      if (!b.active) continue
-      b.rx += Math.round(rnd(0.2, 1.7) * 1e6)
-      b.tx += Math.round(rnd(0.04, 0.4) * 1e6)
-      const peer = state.wireguard.peers.find((p) => p.id === id)
-      if (peer) {
-        peer.rx = fmtBytes(b.rx)
-        peer.tx = fmtBytes(b.tx)
-      }
-    }
-  }
-
-  function wireguardSnapshot() {
-    return { ...state.wireguard, peers: state.wireguard.peers.map((p) => ({ ...p })) }
-  }
-
-  function topDevices(n = 5) {
-    return [...state.devices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, n)
-  }
-
-  function getOverview() {
-    return {
-      health: structuredClone(healthScore),
-      wan: { ...state.wan },
-      traffic: trafficByRange,
-      adguard: { ...state.adguard },
-      wireguard: wireguardSnapshot(),
-      routers: state.routers.map((r) => ({ ...r })),
-      deviceTotals: { ...deviceTotals },
-      topDevices: topDevices(5),
-      alerts: state.alerts.map((a) => ({ ...a })),
-      unreadAlerts: state.alerts.filter((a) => !a.read).length,
-      ts: Math.floor(Date.now() / 1000),
-    }
-  }
-
-  function getRouters() {
-    return state.routers.map((r) => ({ ...r }))
-  }
-
-  function getRouterDetail(id) {
-    const router = state.routers.find((r) => r.id === id)
-    if (!router) return null
-    const extras = state.extras[id] ?? state.extras[GATEWAY_ID]
-    const detail = {
-      router: { ...router },
-      ports: extras.ethPorts,
-      radios: extras.radios.length ? extras.radios : null,
-      backhaul: extras.backhaul ?? null,
-      series: {
-        '1h': perfSeries(router, '1h'),
-        '24h': perfSeries(router, '24h'),
-        '7d': perfSeries(router, '7d'),
-      },
-      clients: state.devices.filter((d) => d.routerId === id).map((d) => ({ ...d })),
-      extras,
-    }
-    if (id === GATEWAY_ID) {
-      detail.adguard = { ...state.adguard }
-      detail.wireguard = wireguardSnapshot()
-      detail.adguardSeries24h = adguardSeries24h
-      detail.wanLatency = { last24h: WAN_LATENCY_24H, stats: WAN_LATENCY_STATS }
-      detail.wgPeerExtras = wgPeerExtras
-      detail.wgTotals30d = WG_TOTALS_30D
-    }
-    return detail
-  }
-
-  function getDevices() {
-    return state.devices.map((d) => ({ ...d }))
-  }
-
-  function getAlerts() {
-    return state.alerts.map((a) => ({ ...a }))
-  }
-
-  /** Filas para la tabla metrics del poller. */
-  function getMetricsRows() {
-    return state.routers.map((r) => {
-      const ex = state.extras[r.id] ?? {}
-      const rx = (ex.trafficNow ?? 0) * 1e6
-      return {
-        router_id: r.id,
-        cpu: r.cpu,
-        ram: r.ram,
-        temp: r.temp,
-        latency_ms: r.id === GATEWAY_ID ? state.wan.latencyMs : (ex.gatewayLatencyMs ?? null),
-        rx_bps: Math.round(rx),
-        tx_bps: Math.round(rx * 0.15),
-      }
-    })
-  }
-
-  function getAdguardRow() {
-    return { queries: state.adguard.queries24h, blocked: state.adguard.blocked24h }
-  }
-
-  return {
-    mode: 'demo',
-    tick,
-    setRouters() {}, // la demo ignora la configuración de routers
-    getOverview,
-    getRouters,
-    getRouterDetail,
-    getDevices,
-    getAlerts,
-    getMetricsRows,
-    getAdguardRow,
-    getDawn: async () => null,
-    getAdguardClients: async () => null,
-    async close() {},
-  }
-}

+ 0 - 803
legacy/server-node/src/adapters/index.js

@@ -1,803 +0,0 @@
-/**
- * Factoría de adapters + adapter live.
- *
- * - DEMO_MODE=1 → adapter demo (dataset canónico). NO escribe en la BD.
- * - Resto → adapter live: OpenWrtClient por router (ubus HTTP + fallback SSH),
- *   AdGuardClient (HTTP API) y WireGuard vía SSH en el gateway.
- *   La lista de routers vive en SQLite (tabla `routers`) y puede cambiar en
- *   caliente desde Ajustes vía `setRouters()`. Con 0 routers configurados el
- *   overview sale vacío (la UI muestra estados vacíos), nunca demo implícito.
- *
- * Degradación elegante: si un router falla, se marca status 'offline' (con el
- * último dato bueno conocido), se genera una alerta y el resto sigue. El
- * poller NUNCA se cae por un fallo de sondeo.
- */
-import { createDemoAdapter } from './demo.js'
-import { OpenWrtClient } from './openwrt.js'
-import { AdGuardClient } from './adguard.js'
-import { AdGuardGlinetClient } from './adguard-glinet.js'
-import { getWireGuardStats } from './wireguard.js'
-
-export function createAdapter(config, dbHandle, routers = []) {
-  if (config.demoMode) {
-    return createDemoAdapter()
-  }
-  return createLiveAdapter(config, dbHandle, routers)
-}
-
-// ---------------------------------------------------------------------------
-// Adapter live
-// ---------------------------------------------------------------------------
-
-function fmtUptime(sec) {
-  const d = Math.floor(sec / 86400)
-  const h = Math.floor((sec % 86400) / 3600)
-  return `${d}d ${h}h`
-}
-
-function mbps(bps) {
-  return bps == null ? 0 : +(bps / 1e6).toFixed(1)
-}
-
-function pickGateway(routers) {
-  return routers.find((r) => r.is_gateway) ?? routers.find((r) => r.type === 'glinet') ?? routers[0] ?? null
-}
-
-function createLiveAdapter(config, dbHandle, initialRouters) {
-  let routers = [...initialRouters]
-  let gatewayCfg = pickGateway(routers)
-  let clients = new Map()
-
-  function rebuildClients() {
-    clients = new Map(
-      routers.map((cfg) => [
-        cfg.id,
-        new OpenWrtClient(cfg, { sshKeyPath: config.sshKeyPath }),
-      ]),
-    )
-  }
-  rebuildClients()
-
-  /** Actualiza la lista de routers en caliente (CRUD de Ajustes). */
-  function setRouters(list) {
-    routers = [...list]
-    gatewayCfg = pickGateway(routers)
-    rebuildClients()
-    // Limpia cachés de routers que ya no existen
-    const ids = new Set(routers.map((r) => r.id))
-    for (const id of [...lastGood.keys()]) if (!ids.has(id)) lastGood.delete(id)
-    for (const id of [...lastStatus.keys()]) if (!ids.has(id)) lastStatus.delete(id)
-    for (const id of [...boardCache.keys()]) if (!ids.has(id)) boardCache.delete(id)
-    for (const id of [...layoutCache.keys()]) if (!ids.has(id)) layoutCache.delete(id)
-    for (const id of [...extrasCache.keys()]) if (!ids.has(id)) extrasCache.delete(id)
-    for (const id of [...lastPolled.keys()]) if (!ids.has(id)) lastPolled.delete(id)
-    for (const id of [...failCount.keys()]) if (!ids.has(id)) failCount.delete(id)
-  }
-
-  // AdGuard: config desde kv (Ajustes, GL.iNet) con fallback a .env (AGH estándar)
-  let adguardClient = null
-  let adguardClientKey = ''
-  function getAdguardClient() {
-    let client = null
-    let key = ''
-    if (dbHandle) {
-      const host = dbHandle.db.prepare("SELECT value FROM kv WHERE key='adguard_host'").get()?.value
-      if (host) {
-        const user = dbHandle.db.prepare("SELECT value FROM kv WHERE key='adguard_user'").get()?.value ?? 'root'
-        const pass = dbHandle.db.prepare("SELECT value FROM kv WHERE key='adguard_pass'").get()?.value ?? ''
-        if (pass) {
-          key = `gl|${host}|${user}`
-          if (adguardClientKey !== key) client = new AdGuardGlinetClient({ host, user, pass, sshKeyPath: config.sshKeyPath })
-        }
-      }
-    }
-    if (!client && !key && config.adguard?.pass) {
-      key = `std|${config.adguard.url}`
-      if (adguardClientKey !== key) client = new AdGuardClient(config.adguard)
-    }
-    if (!key) return null
-    if (adguardClientKey !== key) {
-      adguardClient = client
-      adguardClientKey = key
-    }
-    return adguardClient
-  }
-
-  // Estado entre ticks
-  const lastGood = new Map() // routerId → último Router online
-  const lastStatus = new Map() // routerId → 'online' | 'offline'
-  const boardCache = new Map() // routerId → system board
-  const layoutCache = new Map() // routerId → layout de puertos (board.json, estático)
-  const extrasCache = new Map() // routerId → { ports, radios, wireless, fdb } último bueno
-  let alerts = [] // AlertEvent[], más recientes primero (máx 100)
-  let lastWgPeersActive = new Set()
-  const weakAlerted = new Map() // mac → ts última alerta de señal débil
-
-  function pushAlert(alert) {
-    alerts = [alert, ...alerts].slice(0, 100)
-    return alert
-  }
-
-  /** Consulta métricas históricas del router para sparkline/series. */
-  function metricsHistory(routerId, range) {
-    if (!dbHandle || !routerId) return []
-    const now = Date.now()
-    const ranges = {
-      '1h': { span: 3600e3, bucket: 180e3, fmt: (d) => `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}` },
-      '24h': { span: 86400e3, bucket: 3600e3, fmt: (d) => `${String(d.getHours()).padStart(2, '0')}` },
-      '7d': { span: 7 * 86400e3, bucket: 86400e3, fmt: (d) => ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'][d.getDay()] },
-      '30d': { span: 30 * 86400e3, bucket: 86400e3, fmt: (d) => String(d.getDate()) },
-    }
-    const r = ranges[range]
-    if (!r) return []
-    const rows = dbHandle.db
-      .prepare(
-        `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`,
-      )
-      .all(r.bucket, routerId, now - r.span)
-    return rows.map((row) => ({
-      t: r.fmt(new Date(row.t0)),
-      down: mbps(row.rx),
-      up: mbps(row.tx),
-      cpu: Math.round(row.cpu ?? 0),
-      ram: Math.round(row.ram ?? 0),
-      temp: Math.round(row.temp ?? 0),
-    }))
-  }
-
-  /** Sondea un router; lanza si está inalcanzable. */
-  async function pollRouter(cfg) {
-    const client = clients.get(cfg.id)
-    // Calienta el ControlMaster SSH en serie: las 7 llamadas en paralelo de
-    // abajo multiplexan sobre la conexión ya establecida (en frío, todas
-    // compiten por crear el socket y algunas mueren → falso "offline").
-    await client.ssh('true')
-    // Layout de puertos desde la CONFIG (board.json): se lee una vez y se
-    // cachea; solo se reintenta mientras no se haya conseguido ninguno
-    let layout = layoutCache.get(cfg.id)
-    if (!layout) {
-      layout = await client.getPortLayout().catch(() => null)
-      if (layout?.length) layoutCache.set(cfg.id, layout)
-    }
-    const [sysInfo, cpu, temp, net, leases, wireless, ports, radios, fdb, brMac] = await Promise.all([
-      client.getSystemInfo(),
-      client.getCpuPercent().catch(() => null),
-      client.getTempC().catch(() => null),
-      client.getNetDevBps().catch(() => ({ rxBps: null, txBps: null })),
-      client.getDhcpLeases().catch(() => []),
-      client.getWirelessClients().catch(() => null),
-      client.getEthPorts(layout ?? undefined).catch(() => []),
-      client.getRadios().catch(() => []),
-      client.getBridgeFdb().catch(() => null),
-      client.getBridgeMac().catch(() => null),
-    ])
-    if (!boardCache.has(cfg.id)) {
-      boardCache.set(cfg.id, await client.getBoard().catch(() => null))
-    }
-    const board = boardCache.get(cfg.id)
-    // Anti-parpadeo: si una sonda puntual falla (tick parcial), conserva la
-    // última lista buena en vez de devolver vacío. null = sonda fallida;
-    // colección vacía = resultado real (p.ej. 0 clientes wifi)
-    const cached = extrasCache.get(cfg.id) ?? { ports: [], radios: [], wireless: new Map(), fdb: new Map() }
-    const portsGood = ports.length > 0 ? ports : cached.ports
-    const radiosGood = radios.length > 0 ? radios : cached.radios
-    const wirelessGood = wireless ?? cached.wireless
-    const fdbGood = fdb ?? cached.fdb
-    extrasCache.set(cfg.id, { ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood })
-    const mem = sysInfo?.memory ?? {}
-    // Uso real de RAM como en la UI del router: used = total − available
-    // (MemAvailable ya descuenta caché recuperable; total−free−buffered infla)
-    const ramPct =
-      mem.total > 0
-        ? Math.round(((mem.total - (mem.available ?? (mem.free || 0) + (mem.buffered || 0))) / mem.total) * 100)
-        : null
-    const isGw = cfg.id === gatewayCfg?.id
-    const latency = isGw
-      ? await client.getWanLatency().catch(() => ({ latencyMs: null, lossPct: null }))
-      : { latencyMs: await client.getGatewayLatency(gatewayCfg?.host).catch(() => null), lossPct: null }
-
-    return {
-      cfg,
-      client,
-      sysInfo,
-      board,
-      cpu: cpu ?? 0,
-      ram: ramPct ?? 0,
-      temp: temp ?? 0,
-      uptimeSec: sysInfo?.uptime ?? 0,
-      net,
-      leases,
-      wireless: wirelessGood,
-      ports: portsGood,
-      radios: radiosGood,
-      fdb: fdbGood,
-      brMac,
-      latency,
-    }
-  }
-
-  /** Construye el objeto Router del contrato a partir del sondeo. */
-  function buildRouter(polled, history) {
-    const { cfg } = polled
-    const model = polled.board?.model || cfg.name || cfg.host
-    const temp = polled.temp
-    const health = Math.max(
-      0,
-      100 - (polled.cpu > 85 ? 20 : polled.cpu > 70 ? 10 : 0) - (temp > 75 ? 25 : temp > 65 ? 12 : 0) - (polled.ram > 90 ? 15 : 0),
-    )
-    return {
-      id: cfg.id,
-      name: polled.board?.hostname || cfg.name || cfg.host,
-      model,
-      modelShort: model,
-      role: cfg.id === gatewayCfg?.id ? 'Gateway principal' : 'Punto de acceso',
-      roleBadge: cfg.id === gatewayCfg?.id ? 'Principal' : 'AP',
-      ip: cfg.host,
-      mac: polled.brMac ?? undefined,
-      firmware: polled.board?.release?.description ?? undefined,
-      status: temp > 65 || polled.cpu > 85 ? 'warn' : 'online',
-      health,
-      cpu: polled.cpu,
-      ram: polled.ram,
-      temp,
-      uptime: fmtUptime(polled.uptimeSec),
-      clients: polled.leases.length,
-      ...(temp > 65 ? { hotMetric: 'temp' } : {}),
-      sparkline: history.map((p) => p.down),
-    }
-  }
-
-  function offlineRouter(cfg) {
-    const prev = lastGood.get(cfg.id)
-    return {
-      ...(prev ?? {
-        id: cfg.id,
-        name: cfg.name || cfg.host,
-        model: cfg.type === 'glinet' ? 'GL.iNet' : 'OpenWrt',
-        modelShort: cfg.type === 'glinet' ? 'GL.iNet' : 'OpenWrt',
-        role: cfg.id === gatewayCfg?.id ? 'Gateway principal' : 'Punto de acceso',
-        roleBadge: cfg.id === gatewayCfg?.id ? 'Principal' : 'AP',
-        ip: cfg.host,
-        health: 0,
-        cpu: 0,
-        ram: 0,
-        temp: 0,
-        uptime: '—',
-        clients: 0,
-        sparkline: [],
-      }),
-      status: 'offline',
-    }
-  }
-
-  /** Cache de sondeos del último tick (para detalle/persistencia). */
-  let lastPolled = new Map()
-  const failCount = new Map() // routerId → fallos consecutivos
-
-  async function pollAll() {
-    const results = await Promise.allSettled(routers.map((cfg) => pollRouter(cfg)))
-    const polled = new Map()
-    results.forEach((res, i) => {
-      const cfg = routers[i]
-      if (res.status === 'fulfilled') {
-        polled.set(cfg.id, res.value)
-        failCount.set(cfg.id, 0)
-        lastStatus.set(cfg.id, 'online')
-      } else {
-        const fails = (failCount.get(cfg.id) ?? 0) + 1
-        failCount.set(cfg.id, fails)
-        console.warn(`[netpulse] router ${cfg.id} inalcanzable (${fails}): ${res.reason?.message}`)
-        // Alerta solo tras 2 fallos seguidos: un fallo suelto (SSH frío,
-        // red ocupada) no es una caída real del router
-        if (fails >= 2 && lastStatus.get(cfg.id) !== 'offline') {
-          pushAlert({
-            id: `alert-offline-${cfg.id}-${Date.now()}`,
-            severity: 'critical',
-            title: `${cfg.name || cfg.host} offline`,
-            description: `Sin respuesta de ${cfg.host}: ${res.reason?.message ?? 'error desconocido'}`,
-            time: 'ahora mismo',
-            read: false,
-            routerId: cfg.id,
-          })
-        }
-        if (fails >= 2) lastStatus.set(cfg.id, 'offline')
-      }
-    })
-    lastPolled = polled
-    return polled
-  }
-
-  async function pollAdGuard() {
-    const client = getAdguardClient()
-    if (!client) return null
-    try {
-      return await client.getStats()
-    } catch (err) {
-      console.warn(`[netpulse] AdGuard inalcanzable: ${err.message}`)
-      return {
-        host: client.host ?? '',
-        port: 3000,
-        status: 'inactive',
-        queries24h: 0, blocked24h: 0, blockedPct: 0, trackersBlocked: 0,
-        dnsLatencyMs: 0, clientsUsing: 0, clientsTotal: 0,
-        topBlocked: [], filterLists: 0, rules: 0,
-      }
-    }
-  }
-
-  async function pollWireGuard(devices) {
-    if (!gatewayCfg) return null
-    try {
-      const stats = await getWireGuardStats({
-        host: gatewayCfg?.host,
-        sshKeyPath: config.sshKeyPath,
-        iface: config.wgInterface,
-        subnet: '',
-        peerNames: Object.fromEntries(
-          devices.filter((d) => d.ip).map((d) => [d.ip, { id: d.id, name: d.name, type: d.type }]),
-        ),
-      })
-      // Alerta en handshake nuevo (peer pasa a activo)
-      const activeNow = new Set(stats.peers.filter((p) => p.active).map((p) => p.id))
-      for (const id of activeNow) {
-        if (!lastWgPeersActive.has(id) && lastWgPeersActive.size > 0) {
-          const peer = stats.peers.find((p) => p.id === id)
-          pushAlert({
-            id: `alert-wg-${id}-${Date.now()}`,
-            severity: 'info',
-            title: 'Handshake WireGuard',
-            description: `${peer?.name ?? id} conectado`,
-            time: 'ahora mismo',
-            read: false,
-            routerId: gatewayCfg?.id,
-          })
-        }
-      }
-      lastWgPeersActive = activeNow
-      return stats
-    } catch (err) {
-      console.warn(`[netpulse] WireGuard no disponible: ${err.message}`)
-      return { interface: config.wgInterface, subnet: '', status: 'inactive', peers: [] }
-    }
-  }
-  /**
-   * Dispositivos = unión de leases DHCP (nombre/IP) y MACs VISTAS por cada
-   * router (assoclist WiFi + FDB del bridge). El routerId es el router que
-   * realmente tiene asociado/conectado el dispositivo; si nadie lo ve pero
-   * tiene lease, se atribuye al gateway.
-   *
-   * Persistencia (tabla device_attrib): el FDB del gateway aprende TODAS las
-   * MACs (tráfico hacia internet), así que ver una MAC ahí no dice cómo
-   * conecta. Guardamos la última atribución buena (wireless o FDB de
-   * satélite) y la usamos cuando el dispositivo no está asociado ahora.
-   */
-  const attribStmt = dbHandle
-    ? {
-        upsert: dbHandle.db.prepare(
-          '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',
-        ),
-        all: dbHandle.db.prepare('SELECT mac, router_id, band, signal_dbm FROM device_attrib'),
-      }
-    : null
-
-  // Migración una vez (attrib_v2): las primeras versiones guardaban banda
-  // desde el FDB (incluidas MACs wifi de paso, p.ej. shelly) → tabla limpia
-  if (dbHandle && attribStmt) {
-    const flag = dbHandle.db.prepare("SELECT value FROM kv WHERE key = 'attrib_v2'").get()
-    if (!flag) {
-      dbHandle.db.prepare('DELETE FROM device_attrib').run()
-      dbHandle.db.prepare("INSERT INTO kv (key, value) VALUES ('attrib_v2', '1')").run()
-      console.log('[netpulse] device_attrib limpiada (attrib_v2: solo wireless persiste)')
-    }
-  }
-
-  function buildDevices(polled) {
-    const leasesByMac = new Map()
-    for (const [, p] of polled) {
-      for (const l of p.leases ?? []) if (l.mac) leasesByMac.set(l.mac, l)
-    }
-    const known = new Map((attribStmt?.all.all() ?? []).map((r) => [r.mac, r]))
-    const now = Date.now()
-
-    const seen = new Map() // mac → { routerId, band, signalDbm }
-    // (1) wireless de cualquier router: la mejor pista y la ÚNICA que se
-    // persiste. El FDB (de satélites o gateway) también ve MACs de paso
-    // (wifi de otro AP atravesando el bridge) → no sirve para recordar banda.
-    for (const [routerId, p] of polled) {
-      for (const [mac, w] of p.wireless ?? new Map()) {
-        seen.set(mac, { routerId, band: w.band, signalDbm: w.signalDbm })
-        attribStmt?.upsert.run(mac, routerId, w.band, w.signalDbm, now)
-      }
-    }
-    // (2) FDB de satélites: pista solo de ESTE tick (no se guarda)
-    const gwId = gatewayCfg?.id
-    for (const [routerId, p] of polled) {
-      if (routerId === gwId) continue
-      for (const [mac] of p.fdb ?? new Map()) {
-        if (!seen.has(mac)) {
-          seen.set(mac, { routerId, band: 'cable', signalDbm: null })
-        }
-      }
-    }
-    // (3) FDB del gateway: solo si no hay memoria (puede ser wifi de cualquier
-    // AP que pasa por el backhaul). No se guarda: es mala pista.
-    const gwPolled = gwId ? polled.get(gwId) : null
-    for (const [mac] of gwPolled?.fdb ?? new Map()) {
-      if (!seen.has(mac) && !known.has(mac)) {
-        seen.set(mac, { routerId: gwId, band: 'cable', signalDbm: null })
-      }
-    }
-
-    const allMacs = new Set([...leasesByMac.keys(), ...seen.keys(), ...known.keys()])
-    const routerMacs = new Set()
-    for (const [, p] of polled) if (p.brMac) routerMacs.add(p.brMac)
-    const devices = []
-    for (const mac of allMacs) {
-      if (routerMacs.has(mac)) continue // los routers no son clientes
-      const lease = leasesByMac.get(mac)
-      const s = seen.get(mac) // visto ESTE tick (assoc/FDB)
-      const k = s ? null : known.get(mac) // última atribución buena
-      devices.push({
-        id: mac.toLowerCase().replace(/:/g, '-'),
-        name: lease?.hostname || mac,
-        type: 'desconocido',
-        manufacturer: 'Desconocido',
-        ip: lease?.ip ?? '',
-        mac,
-        routerId: s?.routerId ?? k?.router_id ?? gwId,
-        band: s?.band ?? k?.band ?? '—',
-        signalDbm: s?.signalDbm ?? k?.signal_dbm ?? null,
-        trafficMbps: 0,
-        // Lease NO es estar online (las reservas son 'infinite'): online =
-        // visto asociado/conectado en este tick
-        online: Boolean(s),
-        sparkline: [],
-      })
-    }
-    return devices
-  }
-
-  function computeHealth(routers, adguard) {
-    let score = 100
-    const breakdown = []
-    for (const r of routers) {
-      if (r.status === 'offline') {
-        score -= 30
-        breakdown.push({ label: `${r.name} offline`, delta: -30 })
-      } else if (r.temp > 65) {
-        score -= 8
-        breakdown.push({ label: `temp. ${r.name}`, delta: -8 })
-      }
-    }
-    if (adguard && adguard.status !== 'active') {
-      score -= 5
-      breakdown.push({ label: 'AdGuard inactivo', delta: -5 })
-    }
-    score = Math.max(0, score)
-    return {
-      score,
-      label: score >= 85 ? 'Excelente' : score >= 65 ? 'Bueno' : 'Atención',
-      caption: 'Puntuación de salud de la red',
-      note: breakdown.length ? `Penalizado por: ${breakdown.map((b) => b.label).join(', ')}.` : 'Sin penalizaciones.',
-      breakdown,
-    }
-  }
-
-  function defaultWan(gw) {
-    const p = gw ? lastPolled.get(gw.id) : null
-    return {
-      plan: '—',
-      downMbps: mbps(p?.net?.rxBps),
-      upMbps: mbps(p?.net?.txBps),
-      latencyMs: p?.latency?.latencyMs ?? 0,
-      lossPct: p?.latency?.lossPct ?? 0,
-      publicIp: '—',
-      isp: '—',
-      peakTodayMbps: 0,
-      peakTodayTime: '—',
-      avgDownMbps: 0,
-      total24h: '—',
-    }
-  }
-
-  let overviewInFlight = null
-  /** Single-flight: los llamantes concurrentes (poller + /api/overview + SSE)
-   *  comparten el mismo sondeo en curso (los SSH son lo caro). */
-  async function getOverview() {
-    if (overviewInFlight) return overviewInFlight
-    overviewInFlight = buildOverview().finally(() => {
-      overviewInFlight = null
-    })
-    return overviewInFlight
-  }
-
-  async function buildOverview() {
-    const polled = await pollAll()
-    const routerList = routers.map((cfg) => {
-      const p = polled.get(cfg.id)
-      if (!p) {
-        // Fallo transitorio (1 tick): muestra el último dato bueno tal cual
-        const prev = lastGood.get(cfg.id)
-        if (prev && (failCount.get(cfg.id) ?? 0) < 2) return prev
-        return offlineRouter(cfg)
-      }
-      const router = buildRouter(p, metricsHistory(cfg.id, '24h'))
-      lastGood.set(cfg.id, router)
-      if (router.temp > 65 && lastStatus.get(`${cfg.id}:temp`) !== 'warn') {
-        lastStatus.set(`${cfg.id}:temp`, 'warn')
-        pushAlert({
-          id: `alert-temp-${cfg.id}-${Date.now()}`,
-          severity: 'warn',
-          title: `Temperatura alta en ${router.name}`,
-          description: `${router.temp} °C, por encima del umbral (65 °C)`,
-          time: 'ahora mismo',
-          read: false,
-          routerId: cfg.id,
-        })
-      }
-      return router
-    })
-    const devices = buildDevices(polled)
-    // Aviso de señal débil (< -70 dBm): una alerta por dispositivo y día
-    for (const d of devices) {
-      if (d.online && d.signalDbm != null && d.signalDbm < -70) {
-        const last = weakAlerted.get(d.mac) ?? 0
-        if (Date.now() - last > 24 * 3600e3) {
-          weakAlerted.set(d.mac, Date.now())
-          pushAlert({
-            id: `alert-weak-${d.mac}-${Date.now()}`,
-            severity: 'warn',
-            title: `Señal débil en ${d.name}`,
-            description: `${d.signalDbm} dBm en ${d.routerId} — revisa cobertura o acerca un AP`,
-            time: 'ahora mismo',
-            read: false,
-            routerId: d.routerId,
-          })
-        }
-      }
-    }
-    // Clientes reales por router (atribución wireless/FDB, no leases)
-    for (const r of routerList) {
-      r.clients = devices.filter((d) => d.routerId === r.id && d.online).length
-    }
-    const [adguard, wireguard] = await Promise.all([pollAdGuard(), pollWireGuard(devices)])
-    const gw = routerList.find((r) => r.id === gatewayCfg?.id)
-    const wan = defaultWan(gatewayCfg)
-    if (gw?.status === 'offline') {
-      wan.publicIp = '—'
-    }
-    return {
-      health: computeHealth(routerList, adguard),
-      wan,
-      traffic: {
-        '1h': metricsHistory(gatewayCfg?.id, '1h').map(({ t, down, up }) => ({ t, down, up })),
-        '24h': metricsHistory(gatewayCfg?.id, '24h').map(({ t, down, up }) => ({ t, down, up })),
-        '7d': metricsHistory(gatewayCfg?.id, '7d').map(({ t, down, up }) => ({ t, down, up })),
-        '30d': metricsHistory(gatewayCfg?.id, '30d').map(({ t, down, up }) => ({ t, down, up })),
-      },
-      adguard: adguard ?? {
-        host: '', port: 0, status: 'inactive', queries24h: 0, blocked24h: 0, blockedPct: 0,
-        trackersBlocked: 0, dnsLatencyMs: 0, clientsUsing: 0, clientsTotal: 0,
-        topBlocked: [], filterLists: 0, rules: 0,
-      },
-      wireguard: wireguard ?? { interface: config.wgInterface, subnet: '', status: 'inactive', peers: [] },
-      routers: routerList,
-      deviceTotals: {
-        total: devices.length,
-        online: devices.filter((d) => d.online).length,
-        knownOffline: devices.filter((d) => !d.online).length,
-        newToday: 0,
-      },
-      topDevices: [...devices].sort((a, b) => b.trafficMbps - a.trafficMbps).slice(0, 5),
-      alerts: [...alerts],
-      unreadAlerts: alerts.filter((a) => !a.read).length,
-      ts: Math.floor(Date.now() / 1000),
-    }
-  }
-
-  function getRouters() {
-    return routers.map((cfg) => {
-      const p = lastPolled.get(cfg.id)
-      if (!p) {
-        const prev = lastGood.get(cfg.id)
-        if (prev && (failCount.get(cfg.id) ?? 0) < 2) return prev
-        return offlineRouter(cfg)
-      }
-      return buildRouter(p, metricsHistory(cfg.id, '24h'))
-    })
-  }
-
-  async function getRouterDetail(id) {
-    const cfg = routers.find((r) => r.id === id)
-    if (!cfg) return null
-    const p = lastPolled.get(id)
-    const router = p ? buildRouter(p, metricsHistory(id, '24h')) : offlineRouter(cfg)
-    // Mapa global MAC → lease (los satélites no tienen DHCP: hay que mirar
-    // la tabla del gateway para nombrar lo que cuelga de sus bocas)
-    const leaseMap = new Map()
-    const routerByMac = new Map() // br-lan MAC → nombre del router
-    for (const [, polled] of lastPolled) {
-      for (const l of polled.leases ?? []) if (l.mac) leaseMap.set(l.mac, l)
-      if (polled.brMac) routerByMac.set(polled.brMac, polled.cfg.name || polled.cfg.host)
-    }
-    // Boca → MACs aprendidas. Lo importante es el VECINO inmediato (lo que
-    // hay al otro lado del cable), no cuántos equipos cuelgan detrás.
-    const portMacs = new Map()
-    for (const [mac, portName] of p?.fdb ?? new Map()) {
-      if (!portMacs.has(portName)) portMacs.set(portName, [])
-      portMacs.get(portName).push(mac)
-    }
-    const ports = (p?.ports ?? []).map((port) => {
-      if (!port.up) return port
-      const all = portMacs.get(port.id) ?? []
-      // 1) ¿Hay otro router al otro lado? (uplink router↔router)
-      const neighbor = all.find((mac) => routerByMac.has(mac))
-      if (neighbor) {
-        return { ...port, connectedTo: routerByMac.get(neighbor), detail: 'enlace entre routers' }
-      }
-      // 2) Un solo dispositivo final
-      const endDevices = all
-      if (endDevices.length === 1) {
-        const mac = endDevices[0]
-        const lease = leaseMap.get(mac)
-        return {
-          ...port,
-          connectedTo: lease?.hostname || lease?.ip || mac,
-          deviceMac: mac,
-          detail: lease?.ip ? `${lease.ip} · full duplex` : undefined,
-        }
-      }
-      // 3) Varios: el vecino es un switch/hub — si tiene nombre (lease), ese es
-      if (endDevices.length > 1) {
-        const infraMac = endDevices.find((mac) => leaseMap.get(mac)?.hostname)
-        const infra = infraMac ? leaseMap.get(infraMac) : null
-        return {
-          ...port,
-          connectedTo: infra?.hostname || 'Switch',
-          deviceMac: infraMac || undefined,
-          detail: infra?.ip ?? undefined,
-        }
-      }
-      return port
-    })
-    const radios = p?.radios ?? []
-    const detail = {
-      router,
-      ports,
-      radios,
-      backhaul: null,
-      series: {
-        '1h': metricsHistory(id, '1h').map(({ t, cpu, ram, temp }) => ({ t, cpu, ram, temp })),
-        '24h': metricsHistory(id, '24h').map(({ t, cpu, ram, temp }) => ({ t, cpu, ram, temp })),
-        '7d': metricsHistory(id, '7d').map(({ t, cpu, ram, temp }) => ({ t, cpu, ram, temp })),
-      },
-      clients: buildDevices(lastPolled).filter((d) => d.routerId === id),
-      extras: {
-        mac: p?.brMac ?? '—',
-        firmware: p?.board?.release?.description ?? '—',
-        firmwareUpdated: true,
-        lastReboot: p?.uptimeSec
-          ? new Date(Date.now() - p.uptimeSec * 1000).toLocaleString('es-ES', {
-              day: '2-digit',
-              month: '2-digit',
-              year: 'numeric',
-              hour: '2-digit',
-              minute: '2-digit',
-            })
-          : '—',
-        soc: p?.board?.system ?? '—',
-        flash: '—',
-        ramMb: p?.sysInfo?.memory?.total ? Math.round(p.sysInfo.memory.total / 1e6) : 0,
-        bandSplit: { band24: 0, band5: 0, cable: 0 },
-        trafficNow: mbps(p?.net?.rxBps),
-        gatewayLatencySpark: [],
-        backhaulSignal: [],
-        radios,
-        ports,
-        ethPorts: ports,
-      },
-    }
-    if (id === gatewayCfg?.id) {
-      detail.adguard = await pollAdGuard()
-      detail.wireguard = await pollWireGuard(detail.clients)
-    } else {
-      // Backhaul real del AP: boca que enlaza con otro router + latencia al gateway
-      const uplink = ports.find((p) => p.detail === 'enlace entre routers') ?? ports.find((p) => p.up)
-      detail.backhaul = {
-        kind: 'cable',
-        headline: `Cable · ${uplink?.speed ?? '—'} · full duplex`,
-        latencyMs: p?.latency?.latencyMs ?? 0,
-      }
-    }
-    return detail
-  }
-
-  function getDevices() {
-    return buildDevices(lastPolled)
-  }
-
-  function getAlerts() {
-    return [...alerts]
-  }
-
-  function getMetricsRows() {
-    const rows = []
-    for (const [id, p] of lastPolled) {
-      rows.push({
-        router_id: id,
-        cpu: p.cpu,
-        ram: p.ram,
-        temp: p.temp,
-        latency_ms: p.latency?.latencyMs ?? null,
-        rx_bps: p.net?.rxBps ?? null,
-        tx_bps: p.net?.txBps ?? null,
-      })
-    }
-    return rows
-  }
-
-  function getAdguardRow() {
-    return null // el poller usa el último overview (adguard del snapshot)
-  }
-
-  /** Red DAWN (roaming/band-steering): APs de la malla + salud por router. */
-  async function getDawn() {
-    let firstData = null
-    const mesh = []
-    for (const [routerId, p] of lastPolled) {
-      try {
-        const data = await p.client.sshJson('ubus call dawn get_network')
-        if (!firstData) firstData = data
-        let seen = 0
-        for (const bssids of Object.values(data ?? {})) seen += Object.keys(bssids).length
-        mesh.push({ routerId, name: p.cfg.name || routerId, dawn: true, apsSeen: seen })
-      } catch {
-        mesh.push({ routerId, name: p.cfg.name || routerId, dawn: false, apsSeen: 0 })
-      }
-    }
-    if (!firstData) return null
-    const aps = []
-    for (const [ssid, bssids] of Object.entries(firstData)) {
-      for (const [bssid, ap] of Object.entries(bssids)) {
-        aps.push({
-          ssid,
-          bssid,
-          hostname: ap.hostname ?? '',
-          band: (ap.freq ?? 0) >= 5000 ? '5 GHz' : '2.4 GHz',
-          channel: ap.channel ?? 0,
-          utilizationPct: ap.channel_utilization ?? 0,
-          clients: ap.num_sta ?? 0,
-          local: Boolean(ap.local),
-          iface: ap.iface ?? '',
-        })
-      }
-    }
-    aps.sort((a, b) => a.hostname.localeCompare(b.hostname) || a.band.localeCompare(b.band))
-    return { aps, mesh }
-  }
-
-  /** Clientes AdGuard (solo si está configurado y responde). */
-  async function getAdguardClients() {
-    const client = getAdguardClient()
-    if (!client || typeof client.queryClients !== 'function') return null
-    return client.queryClients()
-  }
-
-  return {
-    mode: 'live',
-    tick() {}, // el sondeo real ocurre en getOverview() (async)
-    setRouters,
-    getOverview,
-    getRouters,
-    getRouterDetail,
-    getDevices,
-    getAlerts,
-    getMetricsRows,
-    getAdguardRow,
-    getDawn,
-    getAdguardClients,
-    async close() {},
-  }
-}

+ 0 - 451
legacy/server-node/src/adapters/openwrt.js

@@ -1,451 +0,0 @@
-/**
- * Adapter live para routers OpenWrt / GL.iNet (Flint 2 usa firmware basado en
- * OpenWrt con ubus expuesto igualmente).
- *
- * Estrategia por consulta:
- *   1. ubus JSON-RPC sobre HTTP: POST http://<host>/ubus
- *      (login: method "call", ["00000000000000000000000000000000","session","login",
- *       {username, password}] → ubus_rpc_session).
- *   2. Fallback SSH (clave, sin passphrase interactiva):
- *      ssh -i $SSH_KEY_PATH -o BatchMode=yes -o ConnectTimeout=4 root@<host> <cmd>
- *
- * NOTA SANDBOX: este código no se puede probar contra routers reales aquí.
- * Todas las llamadas tienen timeout y degradan con excepción controlada:
- * el caller (live adapter) marca el router offline y sigue con el resto.
- */
-import { execFile } from 'node:child_process'
-import { sshBaseArgs } from '../sshkey.js'
-
-const SSH_TIMEOUT_MS = 5000
-const HTTP_TIMEOUT_MS = 4000
-
-export class OpenWrtClient {
-  /**
-   * @param {{ id: string, host: string, name?: string, type?: string }} routerCfg
-   * @param {{ sshKeyPath: string, user?: string, password?: string }} opts
-   *   user/password son opcionales: solo necesarios para ubus HTTP (session login).
-   */
-  constructor(routerCfg, opts) {
-    this.cfg = routerCfg
-    this.host = routerCfg.host
-    this.sshKeyPath = opts.sshKeyPath
-    this.user = opts.user || 'root'
-    this.password = opts.password || ''
-    this._sid = null // sesión ubus HTTP cacheada
-    this._lastStat = null // /proc/stat previo para cpu%
-    this._lastNetDev = null // /proc/net/dev previo para bps
-  }
-
-  // -------------------------------------------------------------------------
-  // Transporte SSH
-  // -------------------------------------------------------------------------
-
-  ssh(cmd, timeoutMs = SSH_TIMEOUT_MS) {
-    return new Promise((resolve, reject) => {
-      execFile(
-        'ssh',
-        [
-          ...sshBaseArgs(this.sshKeyPath),
-          // Multiplexación: reutiliza la conexión SSH entre ticks del poller
-          '-o', 'ControlMaster=auto',
-          '-o', `ControlPath=/tmp/netpulse-ssh-%r@%h:%p`,
-          '-o', 'ControlPersist=60',
-          `root@${this.host}`,
-          cmd,
-        ],
-        { timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 },
-        (err, stdout, stderr) => {
-          if (err) return reject(new Error(`ssh ${this.host}: ${err.message} ${stderr || ''}`.trim()))
-          resolve(stdout)
-        },
-      )
-    })
-  }
-
-  async sshJson(cmd) {
-    const out = await this.ssh(cmd)
-    return JSON.parse(out)
-  }
-
-  // -------------------------------------------------------------------------
-  // Transporte ubus HTTP (JSON-RPC)
-  // -------------------------------------------------------------------------
-
-  async _ubusHttpRpc(sid, object, method, params = {}) {
-    const ctrl = new AbortController()
-    const timer = setTimeout(() => ctrl.abort(), HTTP_TIMEOUT_MS)
-    try {
-      const res = await fetch(`http://${this.host}/ubus`, {
-        method: 'POST',
-        headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify({
-          jsonrpc: '2.0',
-          id: 1,
-          method: 'call',
-          params: [sid, object, method, params],
-        }),
-        signal: ctrl.signal,
-      })
-      if (!res.ok) throw new Error(`ubus HTTP ${res.status}`)
-      const data = await res.json()
-      if (data.error) throw new Error(`ubus RPC error: ${JSON.stringify(data.error)}`)
-      const result = data.result
-      // ubus devuelve [exitCode, payload]
-      if (Array.isArray(result) && result[0] === 0) return result[1]
-      throw new Error(`ubus call falló: ${JSON.stringify(result)}`)
-    } finally {
-      clearTimeout(timer)
-    }
-  }
-
-  async _ubusLogin() {
-    const result = await this._ubusHttpRpc(
-      '00000000000000000000000000000000',
-      'session',
-      'login',
-      { username: this.user, password: this.password },
-    )
-    this._sid = result.ubus_rpc_session
-    return this._sid
-  }
-
-  /**
-   * ubus call con HTTP + login cacheado; reintenta login una vez si la sesión
-   * expiró; fallback a SSH si HTTP no está disponible.
-   */
-  async ubusCall(object, method, params = {}) {
-    try {
-      if (!this._sid) await this._ubusLogin()
-      try {
-        return await this._ubusHttpRpc(this._sid, object, method, params)
-      } catch (err) {
-        // Sesión caducada → un solo re-login
-        this._sid = null
-        await this._ubusLogin()
-        return await this._ubusHttpRpc(this._sid, object, method, params)
-      }
-    } catch (httpErr) {
-      // Fallback SSH: ubus call <object> <method> '<json>'
-      const paramsJson = JSON.stringify(params).replace(/'/g, "'\\''")
-      return this.sshJson(`ubus call ${object} ${method} '${paramsJson}'`)
-    }
-  }
-
-  // -------------------------------------------------------------------------
-  // Sonda de sistema
-  // -------------------------------------------------------------------------
-
-  /** Modelo, release, kernel → metadatos estáticos del router. */
-  async getBoard() {
-    return this.ubusCall('system', 'board')
-  }
-
-  /** uptime, memoria, load. */
-  async getSystemInfo() {
-    return this.ubusCall('system', 'info')
-  }
-
-  /**
-   * CPU % real por delta de /proc/stat (vía SSH; ubus no lo expone).
-   * Primera muestra: null (no hay delta aún).
-   */
-  async getCpuPercent() {
-    const out = await this.ssh("grep '^cpu ' /proc/stat")
-    const parts = out.trim().split(/\s+/).slice(1).map(Number)
-    const [user, nice, system, idle, iowait, irq, softirq] = parts
-    const idleAll = idle + (iowait || 0)
-    const nonIdle = user + nice + system + (irq || 0) + (softirq || 0)
-    const total = idleAll + nonIdle
-    const prev = this._lastStat
-    this._lastStat = { total, idleAll }
-    if (!prev) return null
-    const dTotal = total - prev.total
-    const dIdle = idleAll - prev.idleAll
-    if (dTotal <= 0) return null
-    return Math.round(((dTotal - dIdle) / dTotal) * 100)
-  }
-
-  /** Temperatura °C del primer thermal zone disponible (vía SSH). */
-  async getTempC() {
-    const out = await this.ssh(
-      'for f in /sys/class/thermal/thermal_zone*/temp; do [ -r "$f" ] && cat "$f" && break; done',
-    )
-    const milli = parseInt(out.trim(), 10)
-    return Number.isFinite(milli) ? Math.round(milli / 1000) : null
-  }
-
-  /**
-   * Tráfico agregado (bps) por delta de /proc/net/dev en interfaces físicas
-   * (excluye lo, bridges, ifb, wg, tun/tap para no duplicar contadores).
-   */
-  async getNetDevBps() {
-    const out = await this.ssh("cat /proc/net/dev | tail -n +3")
-    let rx = 0
-    let tx = 0
-    for (const line of out.trim().split('\n')) {
-      const m = /^\s*([\w.-]+):\s*(.*)$/.exec(line)
-      if (!m) continue
-      const iface = m[1]
-      if (/^(lo|br-|ifb|wg|tun|tap)/.test(iface)) continue
-      const fields = m[2].trim().split(/\s+/).map(Number)
-      rx += fields[0] || 0
-      tx += fields[8] || 0
-    }
-    const now = Date.now()
-    const prev = this._lastNetDev
-    this._lastNetDev = { rx, tx, at: now }
-    if (!prev) return { rxBps: null, txBps: null }
-    const dt = (now - prev.at) / 1000
-    if (dt <= 0) return { rxBps: null, txBps: null }
-    return {
-      rxBps: Math.max(0, Math.round(((rx - prev.rx) * 8) / dt)),
-      txBps: Math.max(0, Math.round(((tx - prev.tx) * 8) / dt)),
-    }
-  }
-
-  /** Latencia/pérdida WAN (ping a internet) — solo tiene sentido en el gateway. */
-  async getWanLatency(target = '1.1.1.1') {
-    const out = await this.ssh(`ping -c 3 -W 2 ${target} 2>/dev/null | tail -2`)
-    const loss = /(\d+(?:\.\d+)?)% packet loss/.exec(out)
-    const rtt = /= [\d.]+\/([\d.]+)\/[\d.]+\/[\d.]+ ms/.exec(out)
-    return {
-      latencyMs: rtt ? Math.round(parseFloat(rtt[1])) : null,
-      lossPct: loss ? parseFloat(loss[1]) : null,
-    }
-  }
-
-  /** Latencia al gateway desde un AP (ping corto). */
-  async getGatewayLatency(gatewayHost) {
-    const out = await this.ssh(`ping -c 2 -W 2 ${gatewayHost} 2>/dev/null | tail -1`)
-    const rtt = /= [\d.]+\/([\d.]+)\/[\d.]+ ms/.exec(out)
-    return rtt ? Math.round(parseFloat(rtt[1])) : null
-  }
-
-  // -------------------------------------------------------------------------
-  // Clientes (DHCP + wireless)
-  // -------------------------------------------------------------------------
-
-  /** Leases DHCP: ubus dhcp ipv4leases; fallback /tmp/dhcp.leases. */
-  async getDhcpLeases() {
-    try {
-      const data = await this.ubusCall('dhcp', 'ipv4leases')
-      const leases = data?.lease ?? data?.leases ?? []
-      return leases.map((l) => ({
-        mac: (l.mac || '').toUpperCase(),
-        ip: l['ip-address'] || l.ip || '',
-        hostname: l.hostname || '',
-      }))
-    } catch {
-      const out = await this.ssh('cat /tmp/dhcp.leases 2>/dev/null || true')
-      // Formato: <expiry> <mac> <ip> <hostname> <clientid>
-      return out
-        .trim()
-        .split('\n')
-        .filter(Boolean)
-        .map((line) => {
-          const p = line.split(/\s+/)
-          return { mac: (p[1] || '').toUpperCase(), ip: p[2] || '', hostname: p[3] === '*' ? '' : p[3] || '' }
-        })
-    }
-  }
-
-  /**
-   * Clientes wireless asociados: iwinfo <iface> assoclist por cada radio.
-   * Compatible BusyBox (sin grep -P): awk para listar ifaces, sed BRE para parsear.
-   * Devuelve mapa mac → { signalDbm, band }.
-   */
-  async getWirelessClients() {
-    const out = await this.ssh(
-      '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',
-      8000,
-    )
-    const map = new Map()
-    for (const line of out.trim().split('\n').filter(Boolean)) {
-      const [mac, sig, freq] = line.split(/\s+/)
-      const ghz = parseFloat(freq || '0')
-      map.set(mac.toUpperCase(), {
-        signalDbm: parseInt(sig, 10),
-        band: ghz >= 5 ? '5 GHz' : '2.4 GHz',
-      })
-    }
-    return map
-  }
-
-  // -------------------------------------------------------------------------
-  // Puertos
-  // -------------------------------------------------------------------------
-
-  /** Estado de interfaces: operstate + speed desde /sys (vía SSH). */
-  async getPortStates() {
-    const out = await this.ssh(
-      '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',
-    )
-    return out
-      .trim()
-      .split('\n')
-      .filter(Boolean)
-      .map((line) => {
-        const [name, oper, speed] = line.split(/\s+/)
-        const mbps = parseInt(speed, 10)
-        return {
-          name,
-          up: oper === 'up',
-          speed: mbps > 0 ? (mbps >= 1000 ? `${mbps / 1000} Gbps` : `${mbps} Mbps`) : '—',
-        }
-      })
-  }
-
-  /**
-   * Layout canónico de puertos desde /etc/board.json (la CONFIG del router).
-   * Es estático por hardware: el adapter lo cachea y no se re-lee cada tick.
-   * Devuelve [{ id, name, label, role }] — WAN normalizado a id 'wan'.
-   */
-  async getPortLayout() {
-    const out = await this.ssh('cat /etc/board.json 2>/dev/null')
-    const net = JSON.parse(out)?.network ?? {}
-    const ports = []
-    for (const name of net.lan?.ports ?? []) {
-      ports.push({ id: name, name, label: name.replace('lan', 'LAN '), role: 'lan' })
-    }
-    const wanDev = net.wan?.device
-    if (wanDev) {
-      ports.unshift({ id: 'wan', name: wanDev, label: 'WAN', role: 'wan' })
-    }
-    return ports
-  }
-
-  /**
-   * Bocas Ethernet = layout (config) + estado /sys por nombre de interfaz.
-   * En APs en modo bridge el puerto físico "wan" está metido en br-lan (es
-   * una boca LAN más, no WAN): se detecta por brif y se re-etiqueta.
-   * Si el layout no está disponible, heurística: lanN + wan/pppoe-wan/eth1.
-   * Devuelve [{ id, label, up, speed }] listo para EthPort.
-   */
-  async getEthPorts(layout = null) {
-    const states = await this.getPortStates()
-    const byName = new Map(states.map((p) => [p.name, p]))
-    if (layout?.length) {
-      // Miembros del bridge: si "wan" está en br-lan, este router es un AP
-      const brif = await this.ssh('ls /sys/class/net/br-lan/brif/ 2>/dev/null').catch(() => '')
-      const members = new Set(brif.trim().split('\n').filter(Boolean))
-      const lanCount = layout.filter((p) => p.role === 'lan').length
-      return layout.map((p) => {
-        const st = byName.get(p.name)
-        const up = st?.up ?? false
-        const isWanInBridge = p.role === 'wan' && members.has(p.name)
-        return {
-          id: p.id,
-          label: isWanInBridge ? `LAN ${lanCount + 1}` : p.label,
-          up,
-          speed: up ? st?.speed : undefined,
-        }
-      })
-    }
-    // Fallback sin config
-    const lan = states
-      .filter((p) => /^lan\d+$/.test(p.name))
-      .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))
-      .map((p) => ({ id: p.name, label: p.name.replace('lan', 'LAN '), up: p.up, speed: p.up ? p.speed : undefined }))
-    let wanName = byName.has('wan') ? 'wan' : byName.has('pppoe-wan') ? 'eth1' : byName.has('eth1') ? 'eth1' : null
-    if (wanName) {
-      const st = byName.get(wanName)
-      lan.unshift({ id: 'wan', label: 'WAN', up: st.up, speed: st.up ? st.speed : undefined })
-    }
-    return lan
-  }
-
-  /**
-   * Tabla de reenvío del bridge: MAC aprendida → puerto (lanN/wan).
-   * Usa brctl (BusyBox lo trae; `bridge` no existe en estos routers) +
-   * /sys/class/net/br-lan/brif/<iface>/port_no para mapear nº de puerto → nombre.
-   * Devuelve Map mac → port.
-   */
-  async getBridgeFdb() {
-    const out = await this.ssh(
-      '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}\'',
-    )
-    const map = new Map()
-    const portNames = new Map()
-    let section = ''
-    for (const line of out.split('\n')) {
-      const t = line.trim()
-      if (t.startsWith('==PORTS==')) {
-        section = 'p'
-        continue
-      }
-      if (t.startsWith('==MACS==')) {
-        section = 'm'
-        continue
-      }
-      if (section === 'p') {
-        const [no, name] = t.split(/\s+/)
-        // port_no puede venir en hex (0x2) o decimal; brctl lo muestra decimal
-        const dec = no?.startsWith('0x') ? String(parseInt(no, 16)) : no
-        if (dec && name) portNames.set(dec, name)
-      } else if (section === 'm') {
-        const [no, mac] = t.split(/\s+/)
-        const port = portNames.get(no)
-        if (mac && port && /^(lan\d+|wan)$/.test(port)) map.set(mac.toUpperCase(), port)
-      }
-    }
-    return map
-  }
-
-  /** MAC del bridge br-lan (para reconocer uplinks entre routers en el FDB). */
-  async getBridgeMac() {
-    const out = await this.ssh('cat /sys/class/net/br-lan/address 2>/dev/null')
-    return out.trim().toUpperCase() || null
-  }
-
-  // -------------------------------------------------------------------------
-  // Radios WiFi
-  // -------------------------------------------------------------------------
-
-  /**
-   * Radios activas: por cada interfaz AP con ESSID, canal/ancho/potencia
-   * (iwinfo info) y nº de clientes (iwinfo assoclist). Agregado por banda.
-   * Compatible BusyBox (awk/sed, sin grep -P).
-   * Devuelve [{ name, channel, widthMhz, powerDbm, clients }].
-   */
-  async getRadios() {
-    const out = await this.ssh(
-      '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',
-      8000,
-    )
-    const byBand = new Map()
-    for (const line of out.trim().split('\n').filter(Boolean)) {
-      const [freqS, chS, ht, txS, nS] = line.split('|')
-      const freq = parseFloat(freqS || '0')
-      if (!freq) continue
-      const band = freq >= 5 ? '5 GHz' : '2.4 GHz'
-      const widthMhz = parseInt((ht || '').replace(/\D/g, ''), 10) || 20
-      const clients = parseInt(nS || '0', 10) || 0
-      const cur = byBand.get(band)
-      if (!cur) {
-        byBand.set(band, {
-          name: band,
-          channel: parseInt(chS || '0', 10) || 0,
-          widthMhz,
-          powerDbm: parseInt(txS || '0', 10) || 0,
-          clients,
-        })
-      } else {
-        cur.clients += clients // SSID extra en la misma banda (suma clientes)
-      }
-    }
-    return [...byBand.values()]
-  }
-}

+ 0 - 112
legacy/server-node/src/adapters/wireguard.js

@@ -1,112 +0,0 @@
-/**
- * Adapter live para WireGuard: parsea `wg show <iface> dump` vía SSH en el
- * gateway. Formato dump (TSV):
- *   línea 1 (interfaz): private-key  public-key  listen-port  fwmark
- *   peers:              public-key  preshared-key  endpoint  allowed-ips
- *                       latest-handshake  transfer-rx  transfer-tx  persistent-keepalive
- *
- * NOTA SANDBOX: sin servidor WG real aquí; el parseo está cubierto por tests
- * unitarios con salidas de ejemplo.
- */
-import { execFile } from 'node:child_process'
-import { sshBaseArgs } from '../sshkey.js'
-
-const SSH_TIMEOUT_MS = 5000
-
-function ssh(host, keyPath, cmd) {
-  return new Promise((resolve, reject) => {
-    execFile(
-      'ssh',
-      [
-        ...sshBaseArgs(keyPath),
-        '-o', 'ControlMaster=auto',
-        '-o', 'ControlPath=/tmp/netpulse-ssh-%r@%h:%p',
-        '-o', 'ControlPersist=60',
-        `root@${host}`,
-        cmd,
-      ],
-      { timeout: SSH_TIMEOUT_MS, maxBuffer: 1024 * 1024 },
-      (err, stdout, stderr) => {
-        if (err) return reject(new Error(`ssh ${host}: ${err.message} ${stderr || ''}`.trim()))
-        resolve(stdout)
-      },
-    )
-  })
-}
-
-/** bytes → formato ES ("1,2 GB" / "214 MB") coherente con el contrato. */
-export function fmtBytes(bytes) {
-  if (bytes >= 1e9) {
-    const v = bytes / 1e9
-    return Number.isInteger(v) ? `${v} GB` : `${v.toFixed(1).replace('.', ',')} GB`
-  }
-  if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`
-  if (bytes >= 1e3) return `${Math.round(bytes / 1e3)} KB`
-  return `${bytes} B`
-}
-
-/** Epoch seg → texto relativo ES ("hace 38 s", "hace 2 días"). */
-export function relTime(epochSec, nowSec = Math.floor(Date.now() / 1000)) {
-  const diff = Math.max(0, nowSec - epochSec)
-  if (diff < 60) return `hace ${diff} s`
-  if (diff < 3600) return `hace ${Math.floor(diff / 60)} min`
-  if (diff < 86400) return `hace ${Math.floor(diff / 3600)} h`
-  return `hace ${Math.floor(diff / 86400)} días`
-}
-
-/**
- * Parsea la salida de `wg show <iface> dump`.
- * @returns {{ peers: Array<{pubkey, endpoint, allowedIps, handshakeSec, rxBytes, txBytes}> }}
- */
-export function parseWgDump(dump) {
-  const lines = dump.trim().split('\n')
-  const peers = []
-  for (const line of lines.slice(1)) {
-    const f = line.split('\t')
-    if (f.length < 8) continue
-    peers.push({
-      pubkey: f[0],
-      endpoint: f[2] === '(none)' ? null : f[2],
-      allowedIps: f[3],
-      handshakeSec: parseInt(f[4], 10) || 0,
-      rxBytes: parseInt(f[5], 10) || 0,
-      txBytes: parseInt(f[6], 10) || 0,
-    })
-  }
-  return { peers }
-}
-
-/**
- * Obtiene WireGuardStats del gateway.
- * @param {object} opts { host, sshKeyPath, iface, subnet, peerNames }
- *   peerNames: mapa opcional allowedIp/tunnelIp → { name, type } para etiquetar.
- */
-export async function getWireGuardStats({ host, sshKeyPath, iface = 'wg0', subnet = '', peerNames = {} }) {
-  const dump = await ssh(host, sshKeyPath, `wg show ${iface} dump`)
-  const { peers } = parseWgDump(dump)
-  const nowSec = Math.floor(Date.now() / 1000)
-  const HANDSHAKE_ACTIVE_SEC = 180 // handshake < 3 min ⇒ peer activo
-
-  return {
-    interface: iface,
-    subnet,
-    status: peers.length >= 0 ? 'active' : 'inactive',
-    peers: peers.map((p, i) => {
-      const tunnelIp = (p.allowedIps.split(',')[0] || '').replace('/32', '')
-      const named = peerNames[tunnelIp] || peerNames[p.pubkey] || {}
-      const active = p.handshakeSec > 0 && nowSec - p.handshakeSec < HANDSHAKE_ACTIVE_SEC
-      return {
-        id: named.id || `peer-${i + 1}`,
-        name: named.name || tunnelIp || `Peer ${p.pubkey.slice(0, 8)}`,
-        type: named.type || 'desconocido',
-        tunnelIp,
-        active,
-        lastHandshake: p.handshakeSec > 0 ? relTime(p.handshakeSec, nowSec) : 'nunca',
-        rx: fmtBytes(p.rxBytes),
-        tx: fmtBytes(p.txBytes),
-        endpoint: p.endpoint,
-        allowedIps: p.allowedIps,
-      }
-    }),
-  }
-}

+ 0 - 70
legacy/server-node/src/app.js

@@ -1,70 +0,0 @@
-/**
- * Ensamblado de la app Hono: seguridad → auth → rutas API → estáticos + SPA.
- * Exportado para tests (createApp con deps inyectadas).
- */
-import fs from 'node:fs'
-import path from 'node:path'
-import { Hono } from 'hono'
-import { serveStatic } from '@hono/node-server/serve-static'
-import { securityHeaders } from './security.js'
-import { requireAuth } from './auth.js'
-import { registerHealthRoutes } from './health.js'
-import { registerAuthRoutes } from './routes/auth.js'
-import { registerDataRoutes } from './routes/data.js'
-import { registerConfigRoutes } from './routes/config.js'
-import { registerUserRoutes } from './routes/users.js'
-import { registerUpdateRoutes } from './routes/update.js'
-
-const VERSION = '1.0.0'
-
-export function createApp({ config, dbHandle, adapter, sse, poller, secret, updater }) {
-  const app = new Hono()
-  const mode = adapter.mode
-
-  const getOverview = () => poller?.lastOverview ?? null
-
-  // 1. Headers de seguridad (global)
-  app.use('*', securityHeaders())
-
-  // 2. Auth: todo /api/* salvo /api/health y /api/auth/login
-  app.use('*', requireAuth(dbHandle.db, secret))
-
-  // 3. Rutas API
-  registerHealthRoutes(app, { dbHandle, mode, version: VERSION })
-  registerAuthRoutes(app, { db: dbHandle.db, config, secret, mode })
-  registerDataRoutes(app, { adapter, getOverview })
-  registerConfigRoutes(app, { dbHandle, adapter, config })
-  registerUserRoutes(app, { db: dbHandle.db })
-  if (updater) registerUpdateRoutes(app, { updater })
-  app.get('/api/stream', (c) => sse.handleStream(c))
-
-  // 4. 404 JSON para /api/* desconocido
-  app.all('/api/*', (c) => c.json({ error: 'not_found' }, 404))
-
-  // 5. Estáticos + SPA fallback (excluye /api/* y /assets/*)
-  const staticDir = config.staticDir
-  const indexPath = path.join(staticDir, 'index.html')
-  let indexHtml = null
-  try {
-    indexHtml = fs.readFileSync(indexPath, 'utf8')
-  } catch {
-    console.warn(`[netpulse] STATIC_DIR=${staticDir} sin index.html (¿falta "npm run build" en app/?)`)
-  }
-
-  app.use('/*', serveStatic({ root: staticDir }))
-  app.get('*', (c) => {
-    if (c.req.path.startsWith('/api/')) return c.json({ error: 'not_found' }, 404)
-    if (c.req.path.startsWith('/assets/')) return c.notFound()
-    if (!indexHtml) return c.text('NetPulse: frontend no compilado (cd app && npm run build)', 503)
-    return c.html(indexHtml)
-  })
-
-  app.onError((err, c) => {
-    console.error('[netpulse] error no controlado:', err)
-    return c.json({ error: 'internal_error' }, 500)
-  })
-
-  return app
-}
-
-export { VERSION }

+ 0 - 278
legacy/server-node/src/auth.js

@@ -1,278 +0,0 @@
-/**
- * Auth single-user (decisión tomada: AUTH_USER/AUTH_PASS en .env).
- * - Cookie `session` = `id.hmac` (HMAC-SHA256), httpOnly, SameSite=Lax, 30d.
- *   Secure: siempre que la petición sea HTTPS (auto) o según COOKIE_SECURE.
- * - Secret HMAC: SESSION_SECRET o autogenerado persistido en kv.
- * - Password: hash bcryptjs en kv tras primer login — NUNCA texto plano
- *   persistido. Se guarda también sha256(AUTH_PASS) para detectar cambios de
- *   la password en .env y re-hashear (el hash viejo no se reutiliza).
- * - Rate-limit en SQLite (login_attempts): bloqueo 5 min tras 5 fallos
- *   (bloquea cuando attempts >= 4, ver registerLoginFail).
- * - Rotación de sesión tras login: se invalida la sesión anterior si existía.
- */
-import crypto from 'node:crypto'
-import bcrypt from 'bcryptjs'
-
-export const SESSION_COOKIE = 'session'
-export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000 // 30 días
-const LOCK_MS = 5 * 60 * 1000 // 5 minutos
-
-// ---------------------------------------------------------------------------
-// Usuarios (multiusuario): seed admin desde .env si la tabla está vacía
-// ---------------------------------------------------------------------------
-
-/** Crea el admin inicial (AUTH_USER/AUTH_PASS) cuando no hay ningún usuario. */
-export async function ensureUsers(db, config) {
-  const count = db.prepare('SELECT COUNT(*) AS c FROM users').get().c
-  if (count > 0) return
-  const hash = await bcrypt.hash(config.authPass, 10)
-  db.prepare('INSERT INTO users (username, pass_hash, role, created_at) VALUES (?, ?, ?, ?)').run(
-    config.authUser,
-    hash,
-    'admin',
-    Date.now(),
-  )
-  console.log(`[netpulse] usuario admin inicial creado: ${config.authUser}`)
-}
-
-export function getUserByName(db, username) {
-  return db.prepare('SELECT id, username, pass_hash, role FROM users WHERE username = ?').get(username)
-}
-
-export function getUserById(db, id) {
-  return db.prepare('SELECT id, username, role FROM users WHERE id = ?').get(id)
-}
-
-// ---------------------------------------------------------------------------
-// Secret HMAC y hash de password
-// ---------------------------------------------------------------------------
-
-export function ensureSessionSecret(db, config) {
-  if (config.sessionSecret) return config.sessionSecret
-  const row = db.prepare('SELECT value FROM kv WHERE key = ?').get('session_secret')
-  if (row?.value) return row.value
-  const secret = crypto.randomBytes(32).toString('hex')
-  db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(
-    'session_secret',
-    secret,
-  )
-  return secret
-}
-
-/**
- * Devuelve el hash bcrypt de AUTH_PASS, generándolo y persistiéndolo en kv la
- * primera vez (o cuando AUTH_PASS cambia en .env).
- */
-export async function ensurePasswordHash(db, config) {
-  const envFingerprint = crypto.createHash('sha256').update(config.authPass).digest('hex')
-  const storedHash = db.prepare('SELECT value FROM kv WHERE key = ?').get('auth_pass_hash')?.value
-  const storedFp = db.prepare('SELECT value FROM kv WHERE key = ?').get('auth_pass_fp')?.value
-  if (storedHash?.startsWith('$2') && storedFp === envFingerprint) return storedHash
-  const hash = await bcrypt.hash(config.authPass, 10)
-  const upsert = db.prepare(
-    'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
-  )
-  upsert.run('auth_pass_hash', hash)
-  upsert.run('auth_pass_fp', envFingerprint)
-  return hash
-}
-
-// ---------------------------------------------------------------------------
-// Cookie id.hmac
-// ---------------------------------------------------------------------------
-
-function hmac(secret, id) {
-  return crypto.createHmac('sha256', secret).update(id).digest('hex')
-}
-
-function safeEqual(a, b) {
-  const ba = Buffer.from(String(a))
-  const bb = Buffer.from(String(b))
-  return ba.length === bb.length && crypto.timingSafeEqual(ba, bb)
-}
-
-export function signSessionId(secret, id) {
-  return `${id}.${hmac(secret, id)}`
-}
-
-export function verifySessionCookie(secret, value) {
-  if (!value || typeof value !== 'string') return null
-  const dot = value.lastIndexOf('.')
-  if (dot <= 0) return null
-  const id = value.slice(0, dot)
-  const sig = value.slice(dot + 1)
-  if (!safeEqual(sig, hmac(secret, id))) return null
-  return id
-}
-
-export function isSecureRequest(c) {
-  if (c.req.url.startsWith('https://')) return true
-  return c.req.header('x-forwarded-proto')?.split(',')[0].trim() === 'https'
-}
-
-export function cookieSecureFlag(config, c) {
-  if (config.cookieSecure === 'always') return true
-  if (config.cookieSecure === 'never') return false
-  return isSecureRequest(c) // auto
-}
-
-export function buildSessionCookie(config, c, signedId, maxAgeSec) {
-  const parts = [
-    `${SESSION_COOKIE}=${signedId}`,
-    'Path=/',
-    'HttpOnly',
-    'SameSite=Lax',
-    `Max-Age=${maxAgeSec}`,
-  ]
-  if (cookieSecureFlag(config, c)) parts.push('Secure')
-  return parts.join('; ')
-}
-
-// ---------------------------------------------------------------------------
-// Sesiones en SQLite
-// ---------------------------------------------------------------------------
-
-export function createSession(db, ua, userId = null) {
-  const id = crypto.randomUUID()
-  const now = Date.now()
-  db.prepare('INSERT INTO sessions (id, created_at, expires_at, ua, user_id) VALUES (?, ?, ?, ?, ?)').run(
-    id,
-    now,
-    now + SESSION_TTL_MS,
-    (ua || '').slice(0, 255),
-    userId,
-  )
-  return id
-}
-
-export function destroySession(db, id) {
-  if (id) db.prepare('DELETE FROM sessions WHERE id = ?').run(id)
-}
-
-export function destroyUserSessions(db, userId) {
-  db.prepare('DELETE FROM sessions WHERE user_id = ?').run(userId)
-}
-
-export function getSession(db, id) {
-  if (!id) return null
-  const row = db.prepare('SELECT id, expires_at, user_id FROM sessions WHERE id = ?').get(id)
-  if (!row) return null
-  if (row.expires_at < Date.now()) {
-    destroySession(db, id)
-    return null
-  }
-  return row
-}
-
-/** Sesión válida + usuario asociado (null si la sesión es antigua sin user). */
-export function sessionUserFromRequest(db, secret, c) {
-  const header = c.req.header('cookie') || ''
-  const match = /(?:^|;\s*)session=([^;]+)/.exec(header)
-  const id = verifySessionCookie(secret, match?.[1])
-  const session = id && getSession(db, id)
-  if (!session || !session.user_id) return null
-  const user = getUserById(db, session.user_id)
-  return user ? { sessionId: id, user } : null
-}
-
-export function sessionIdFromRequest(db, secret, c) {
-  const header = c.req.header('cookie') || ''
-  const match = /(?:^|;\s*)session=([^;]+)/.exec(header)
-  const id = verifySessionCookie(secret, match?.[1])
-  return id && getSession(db, id) ? id : null
-}
-
-// ---------------------------------------------------------------------------
-// Rate-limit en SQLite (persiste tras reinicios)
-// ---------------------------------------------------------------------------
-
-export function clientIp(c) {
-  return (
-    c.req.header('x-forwarded-for')?.split(',')[0].trim() ||
-    c.env?.incoming?.socket?.remoteAddress ||
-    'unknown'
-  )
-}
-
-/** true si la IP está bloqueada; devuelve también segundos restantes. */
-export function loginRateLimited(db, c) {
-  const ip = clientIp(c)
-  const row = db.prepare('SELECT locked_until FROM login_attempts WHERE ip = ?').get(ip)
-  if (!row) return { limited: false, retryAfterSec: 0 }
-  const remaining = row.locked_until - Date.now()
-  if (remaining > 0) return { limited: true, retryAfterSec: Math.ceil(remaining / 1000) }
-  return { limited: false, retryAfterSec: 0 }
-}
-
-/** Registra un fallo: bloquea 5 min cuando se alcanza el 5º fallo (attempts >= 4). */
-export function registerLoginFail(db, c) {
-  const ip = clientIp(c)
-  db.prepare(`
-    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
-  `).run(ip, Date.now() + LOCK_MS)
-}
-
-export function loginOk(db, c) {
-  db.prepare('DELETE FROM login_attempts WHERE ip = ?').run(clientIp(c))
-}
-
-// ---------------------------------------------------------------------------
-// Login / logout
-// ---------------------------------------------------------------------------
-
-/**
- * Valida credenciales contra la tabla users y crea sesión nueva
- * (rotación: invalida la anterior).
- * @returns { id, user } o null si credenciales inválidas.
- */
-export async function handleLogin(db, config, secret, c, body) {
-  const { username, password } = body || {}
-  if (!username || !password) return null
-  const user = getUserByName(db, username)
-  if (!user) return null
-  const valid = await bcrypt.compare(password, user.pass_hash)
-  if (!valid) return null
-  // Rotación de sesión: invalida la cookie previa si existía
-  const prevId = sessionIdFromRequest(db, secret, c)
-  if (prevId) destroySession(db, prevId)
-  const id = createSession(db, c.req.header('user-agent'), user.id)
-  return { id, user: { id: user.id, username: user.username, role: user.role } }
-}
-
-export function handleLogout(db, secret, c) {
-  const id = sessionIdFromRequest(db, secret, c)
-  if (id) destroySession(db, id)
-}
-
-// ---------------------------------------------------------------------------
-// Middleware requireAuth: todo /api/* salvo login y health
-// ---------------------------------------------------------------------------
-
-export function requireAuth(db, secret) {
-  return async (c, next) => {
-    const path = c.req.path
-    if (!path.startsWith('/api/')) return next()
-    if (path === '/api/health' || path === '/api/auth/login') return next()
-    const sess = sessionUserFromRequest(db, secret, c)
-    if (!sess) return c.json({ error: 'unauthorized' }, 401)
-    c.set('sessionId', sess.sessionId)
-    c.set('user', sess.user)
-    return next()
-  }
-}
-
-/** Middleware admin: tras requireAuth, exige role === 'admin'. */
-export function requireAdmin() {
-  return async (c, next) => {
-    const user = c.get('user')
-    if (!user || user.role !== 'admin') return c.json({ error: 'forbidden' }, 403)
-    return next()
-  }
-}

+ 0 - 111
legacy/server-node/src/config.js

@@ -1,111 +0,0 @@
-/**
- * Configuración por entorno, validada con zod (fail-fast).
- * Lee server/.env manualmente (sin dependencia dotenv) y luego valida.
- */
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-import { z } from 'zod'
-
-const SERVER_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
-
-/** Parser .env mínimo: KEY=VALUE, # comentarios, comillas simples/dobles opcionales. */
-export function loadDotEnv(envPath = path.join(SERVER_ROOT, '.env')) {
-  if (!fs.existsSync(envPath)) return
-  for (const rawLine of fs.readFileSync(envPath, 'utf8').split('\n')) {
-    const line = rawLine.trim()
-    if (!line || line.startsWith('#')) continue
-    const eq = line.indexOf('=')
-    if (eq === -1) continue
-    const key = line.slice(0, eq).trim()
-    let value = line.slice(eq + 1).trim()
-    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
-      value = value.slice(1, -1)
-    }
-    if (!(key in process.env)) process.env[key] = value
-  }
-}
-
-const routerSchema = z.object({
-  id: z.string().min(1),
-  name: z.string().optional(),
-  host: z.string().min(1),
-  type: z.enum(['glinet', 'openwrt']).default('openwrt'),
-})
-
-const envSchema = z.object({
-  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
-  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
-  STATIC_DIR: z.string().default('../app/dist'),
-  DATA_DIR: z.string().default('./data'),
-  SESSION_SECRET: z.string().min(32).optional(), // autogenerado (kv) si falta
-  AUTH_USER: z.string().min(1).default('admin'),
-  AUTH_PASS: z.string().min(1), // obligatoria: fail-fast si falta
-  DEMO_MODE: z.enum(['0', '1']).optional(), // si falta: demo cuando no hay ROUTERS_JSON
-  MAX_SSE_CLIENTS: z.coerce.number().int().min(1).max(100).default(10),
-  // --- Modo live ---
-  ROUTERS_JSON: z.string().optional(),
-  // Si no se define, la app genera y usa su propia clave en DATA_DIR/.ssh
-  SSH_KEY_PATH: z.string().optional(),
-  ADGUARD_URL: z.string().url().optional(),
-  ADGUARD_USER: z.string().default('admin'),
-  ADGUARD_PASS: z.string().optional(),
-  WG_INTERFACE: z.string().default('wg0'),
-  // Cookie Secure: 'auto' = solo si la petición llega por HTTPS (o X-Forwarded-Proto)
-  COOKIE_SECURE: z.enum(['auto', 'always', 'never']).default('auto'),
-  // Actualizador (repo GitHub privado → token fine-grained Contents:read)
-  GITHUB_REPO: z.string().default('gnacho/netpulse'),
-  GITHUB_TOKEN: z.string().optional(),
-})
-
-/**
- * Valida process.env y devuelve la config normalizada.
- * Lanza (fail-fast) si falta algo crítico o ROUTERS_JSON está mal formado.
- */
-export function loadConfig(env = process.env) {
-  const parsed = envSchema.safeParse(env)
-  if (!parsed.success) {
-    const issues = parsed.error.issues.map((i) => `  - ${i.path.join('.')}: ${i.message}`).join('\n')
-    throw new Error(`[netpulse] Configuración inválida (revisa server/.env):\n${issues}`)
-  }
-  const e = parsed.data
-
-  let routers = []
-  if (e.ROUTERS_JSON) {
-    try {
-      const raw = JSON.parse(e.ROUTERS_JSON)
-      routers = z.array(routerSchema).parse(raw)
-    } catch (err) {
-      throw new Error(`[netpulse] ROUTERS_JSON inválido: ${err.message}`)
-    }
-  }
-
-  // Demo SOLO si se fuerza con DEMO_MODE=1. Con 0 routers configurados el
-  // adapter live arranca vacío (overview sin routers) a la espera de la
-  // autodetección del gateway o del alta manual desde Ajustes.
-  const demoMode = e.DEMO_MODE === '1'
-
-  return {
-    port: e.PORT,
-    nodeEnv: e.NODE_ENV,
-    staticDir: path.resolve(SERVER_ROOT, e.STATIC_DIR),
-    dataDir: path.resolve(SERVER_ROOT, e.DATA_DIR),
-    sessionSecret: e.SESSION_SECRET,
-    authUser: e.AUTH_USER,
-    authPass: e.AUTH_PASS,
-    demoMode,
-    maxSseClients: e.MAX_SSE_CLIENTS,
-    routers,
-    sshKeyPath: e.SSH_KEY_PATH
-      ? e.SSH_KEY_PATH.replace(/^~/, process.env.HOME || '~')
-      : path.join(path.resolve(SERVER_ROOT, e.DATA_DIR), '.ssh', 'id_ed25519'),
-    adguard: e.ADGUARD_URL
-      ? { url: e.ADGUARD_URL.replace(/\/$/, ''), user: e.ADGUARD_USER, pass: e.ADGUARD_PASS || '' }
-      : null,
-    wgInterface: e.WG_INTERFACE,
-    cookieSecure: e.COOKIE_SECURE,
-    githubRepo: e.GITHUB_REPO,
-    githubToken: e.GITHUB_TOKEN,
-    serverRoot: SERVER_ROOT,
-  }
-}

+ 0 - 150
legacy/server-node/src/db.js

@@ -1,150 +0,0 @@
-/**
- * SQLite (better-sqlite3, síncrono): schema + helpers + jobs de mantenimiento.
- * WAL + synchronous NORMAL, checkpoint TRUNCATE periódico, retención 7 días.
- */
-import fs from 'node:fs'
-import path from 'node:path'
-import Database from 'better-sqlite3'
-
-const RETENTION_MS = 7 * 24 * 60 * 60 * 1000 // 7 días
-const MAINTENANCE_MS = 60 * 60 * 1000 // 1 h
-
-export function openDb(dataDir) {
-  fs.mkdirSync(dataDir, { recursive: true })
-  const dbPath = path.join(dataDir, 'netpulse.db')
-  const db = new Database(dbPath)
-  db.pragma('journal_mode = WAL')
-  db.pragma('synchronous = NORMAL')
-  db.pragma('foreign_keys = ON')
-
-  db.exec(`
-    -- 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 (banda/router donde se vio asociado;
-    -- el FDB del gateway ve todo y no sirve para saber cómo conecta un equipo)
-    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 (vacía al importar; se rellena por autodetección
-    -- del gateway, ROUTERS_JSON o el CRUD de Ajustes)
-    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
-    );
-  `)
-
-  // Migraciones tolerantes (añadir columnas si faltan en DBs antiguas)
-  migrate(db, 'sessions', 'ua', 'ALTER TABLE sessions ADD COLUMN ua TEXT')
-  migrate(db, 'sessions', 'user_id', 'ALTER TABLE sessions ADD COLUMN user_id INTEGER')
-  migrate(db, 'users', 'language', "ALTER TABLE users ADD COLUMN language TEXT DEFAULT 'auto'")
-
-  const stmts = {
-    insertMetric: db.prepare(
-      'INSERT INTO metrics (router_id, ts, cpu, ram, temp, latency_ms, rx_bps, tx_bps) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
-    ),
-    insertAdguard: db.prepare('INSERT INTO adguard_stats (ts, queries, blocked) VALUES (?, ?, ?)'),
-    deleteOldMetrics: db.prepare('DELETE FROM metrics WHERE ts < ?'),
-    deleteOldAdguard: db.prepare('DELETE FROM adguard_stats WHERE ts < ?'),
-    deleteExpiredSessions: db.prepare('DELETE FROM sessions WHERE expires_at < ?'),
-    listRouters: db.prepare('SELECT id, name, host, type, is_gateway, created_at FROM routers ORDER BY is_gateway DESC, created_at ASC'),
-    insertRouter: db.prepare('INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES (?, ?, ?, ?, ?, ?)'),
-    deleteRouter: db.prepare('DELETE FROM routers WHERE id = ?'),
-    clearGateways: db.prepare('UPDATE routers SET is_gateway = 0'),
-    health: db.prepare('SELECT 1 AS ok'),
-  }
-
-  function maintenance() {
-    const cutoff = Date.now() - RETENTION_MS
-    try {
-      stmts.deleteOldMetrics.run(cutoff)
-      stmts.deleteOldAdguard.run(cutoff)
-      stmts.deleteExpiredSessions.run(Date.now())
-      db.pragma('wal_checkpoint(TRUNCATE)')
-    } catch (err) {
-      console.error('[netpulse] error en mantenimiento DB:', err.message)
-    }
-  }
-
-  const maintenanceTimer = setInterval(maintenance, MAINTENANCE_MS)
-  maintenanceTimer.unref()
-
-  return {
-    db,
-    stmts,
-    checkHealth() {
-      try {
-        return stmts.health.get().ok === 1
-      } catch {
-        return false
-      }
-    },
-    maintenance,
-    close() {
-      clearInterval(maintenanceTimer)
-      try {
-        db.pragma('wal_checkpoint(TRUNCATE)')
-      } catch {}
-      db.close()
-    },
-  }
-}
-
-function migrate(db, table, column, ddl) {
-  const cols = db.prepare(`PRAGMA table_info(${table})`).all()
-  if (!cols.some((c) => c.name === column)) {
-    try {
-      db.exec(ddl)
-    } catch {}
-  }
-}

+ 0 - 913
legacy/server-node/src/demo/dataset.js

@@ -1,913 +0,0 @@
-/**
- * NetPulse — Dataset demo canónico.
- * Port ESM (JS puro) de:
- *   - app/src/data/mock.ts                      (valores canónicos §11 design.md)
- *   - app/src/components/routers/routerExtras.ts (extras por router + series)
- *   - app/src/pages/devices-data.ts              (lista completa de 47 clientes)
- * Los valores deben coincidir EXACTAMENTE con el frontend (camelCase idéntico).
- * `iconOverride` (componente Lucide) se porta como string con el nombre del icono.
- */
-
-// ---------------------------------------------------------------------------
-// Routers (canon §11)
-// ---------------------------------------------------------------------------
-
-export const routers = [
-  {
-    id: 'flint2',
-    name: 'Gateway',
-    model: 'GL.iNet Flint 2 (GL-MT6000)',
-    modelShort: 'GL.iNet Flint 2',
-    role: 'Main gateway',
-    roleBadge: 'Main',
-    ip: '192.168.8.1',
-    status: 'online',
-    health: 98,
-    cpu: 23,
-    ram: 41,
-    temp: 54,
-    uptime: '32d 14h',
-    clients: 14,
-    sparkline: [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: 'Living Room',
-    model: 'OpenWrt AP (Xiaomi AX3000T)',
-    modelShort: 'Xiaomi AX3000T',
-    role: 'Access point',
-    roleBadge: 'AP',
-    ip: '192.168.8.2',
-    status: 'online',
-    health: 95,
-    cpu: 12,
-    ram: 38,
-    temp: 47,
-    uptime: '32d 14h',
-    clients: 18,
-    sparkline: [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: 'Study',
-    model: 'OpenWrt (NanoPi R4S)',
-    modelShort: 'NanoPi R4S',
-    role: 'AP + switch',
-    roleBadge: 'AP',
-    ip: '192.168.8.3',
-    status: 'online',
-    health: 92,
-    cpu: 18,
-    ram: 44,
-    temp: 51,
-    uptime: '11d 3h',
-    clients: 9,
-    sparkline: [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: 'Outdoor AP',
-    roleBadge: 'AP',
-    ip: '192.168.8.4',
-    status: 'warn',
-    health: 68,
-    cpu: 31,
-    ram: 57,
-    temp: 71,
-    uptime: '4d 2h',
-    clients: 6,
-    hotMetric: 'temp',
-    sparkline: [1, 1, 1, 1, 1, 2, 3, 5, 7, 8, 8, 9, 10, 9, 8, 9, 11, 12, 13, 12, 9, 6, 4, 2],
-  },
-]
-
-// ---------------------------------------------------------------------------
-// WAN (vía Flint 2)
-// ---------------------------------------------------------------------------
-
-export const 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',
-}
-
-// ---------------------------------------------------------------------------
-// Tráfico WAN — series por rango
-// ---------------------------------------------------------------------------
-
-export const trafficByRange = {
-  '1h': [
-    { t: '21:30', down: 68, up: 9 }, { t: '21:33', down: 74, up: 10 },
-    { t: '21:36', down: 81, up: 11 }, { t: '21:39', down: 92, up: 12 },
-    { t: '21:42', down: 88, up: 10 }, { t: '21:45', down: 96, up: 13 },
-    { t: '21:48', down: 104, up: 14 }, { t: '21:51', down: 98, up: 12 },
-    { t: '21:54', down: 90, up: 11 }, { t: '21:57', down: 86, up: 10 },
-    { t: '22:00', down: 82, up: 11 }, { t: '22:03', down: 78, up: 12 },
-    { t: '22:06', down: 84, up: 13 }, { t: '22:09', down: 91, up: 14 },
-    { t: '22:12', down: 88, up: 12 }, { t: '22:15', down: 84, up: 11 },
-    { t: '22:18', down: 80, up: 10 }, { t: '22:21', down: 83, up: 12 },
-    { t: '22:24', down: 86, up: 13 }, { t: '22:27', down: 84, up: 12.6 },
-  ],
-  '24h': [
-    { t: '00', down: 42, up: 8 }, { t: '01', down: 28, up: 6 },
-    { t: '02', down: 15, up: 5 }, { t: '03', down: 9, up: 4 },
-    { t: '04', down: 7, up: 4 }, { t: '05', down: 8, up: 5 },
-    { t: '06', down: 14, up: 6 }, { t: '07', down: 32, up: 9 },
-    { t: '08', down: 58, up: 14 }, { t: '09', down: 74, up: 18 },
-    { t: '10', down: 88, up: 21 }, { t: '11', down: 96, up: 24 },
-    { t: '12', down: 112, up: 26 }, { t: '13', down: 124, up: 28 },
-    { t: '14', down: 118, up: 25 }, { t: '15', down: 132, up: 27 },
-    { t: '16', down: 148, up: 30 }, { t: '17', down: 176, up: 34 },
-    { t: '18', down: 224, up: 42 }, { t: '19', down: 298, up: 55 },
-    { t: '20', down: 356, up: 71 }, { t: '21', down: 412, up: 96 },
-    { t: '22', down: 284, up: 48 }, { t: '23', down: 122, up: 21 },
-  ],
-  '7d': [
-    { t: 'Mon', down: 61, up: 12 }, { t: 'Tue', down: 58, up: 11 },
-    { t: 'Wed', down: 64, up: 13 }, { t: 'Thu', down: 71, up: 15 },
-    { t: 'Fri', down: 88, up: 19 }, { t: 'Sat', down: 96, up: 22 },
-    { t: 'Sun', down: 84, up: 18 },
-  ],
-  '30d': [
-    { t: '1', down: 54, up: 10 }, { t: '4', down: 58, up: 11 },
-    { t: '7', down: 62, up: 12 }, { t: '10', down: 57, up: 11 },
-    { t: '13', down: 66, up: 13 }, { t: '16', down: 72, up: 15 },
-    { t: '19', down: 68, up: 14 }, { t: '22', down: 75, up: 16 },
-    { t: '25', down: 81, up: 18 }, { t: '28', down: 78, up: 17 },
-    { t: '30', down: 84, up: 19 },
-  ],
-}
-
-// ---------------------------------------------------------------------------
-// Health Score global
-// ---------------------------------------------------------------------------
-
-export const healthScore = {
-  score: 92,
-  label: 'Excellent',
-  caption: 'Network health score',
-  note: 'Penalized by the Patio temperature.',
-  breakdown: [
-    { label: 'Patio temp.', delta: -4 },
-    { label: 'Patio coverage', delta: -2 },
-    { label: 'congested 2.4 GHz channel', delta: -2 },
-  ],
-}
-
-// ---------------------------------------------------------------------------
-// Dispositivos (totales del canon)
-// ---------------------------------------------------------------------------
-
-export const deviceTotals = {
-  total: 47,
-  online: 39,
-  knownOffline: 8,
-  newToday: 3,
-}
-
-// ---------------------------------------------------------------------------
-// Dispositivos canónicos destacados (mock.ts §Dispositivos)
-// ---------------------------------------------------------------------------
-
-const canonDevices = [
-  {
-    id: 'imac-salon', name: 'iMac Living Room', type: 'ordenador', manufacturer: 'Apple',
-    ip: '192.168.8.21', mac: 'A4:83:E7:21:0B:3C', routerId: 'living', band: '5 GHz',
-    signalDbm: -48, trafficMbps: 32.4, online: true,
-    sparkline: [12, 15, 18, 22, 26, 30, 34, 32, 28, 30, 32, 31],
-  },
-  {
-    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: -52, trafficMbps: 18.1, online: true,
-    sparkline: [8, 10, 14, 16, 18, 20, 19, 18, 17, 18, 18, 18],
-  },
-  {
-    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: -41, trafficMbps: 6.2, online: true,
-    sparkline: [3, 4, 5, 7, 6, 8, 6, 5, 7, 6, 6, 6],
-  },
-  {
-    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: -45, trafficMbps: 4.8, online: true,
-    sparkline: [2, 3, 4, 5, 5, 6, 5, 4, 5, 5, 5, 5],
-  },
-  {
-    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: null, trafficMbps: 12.7, online: true,
-    sparkline: [4, 6, 8, 10, 12, 14, 13, 12, 13, 12, 13, 13],
-  },
-  {
-    id: 'robot-aspirador', name: 'Robot vacuum', type: 'iot', manufacturer: 'Roborock',
-    ip: '192.168.8.61', mac: 'B0:4A:39:2E:77:10', routerId: 'patio', band: '2.4 GHz',
-    signalDbm: -67, trafficMbps: 0.02, online: true,
-    sparkline: [0.01, 0.02, 0.02, 0.03, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02],
-  },
-  {
-    id: 'camara-porche', name: 'Porch camera', type: 'camara', manufacturer: 'Reolink',
-    ip: '192.168.8.71', mac: 'EC:71:DB:44:12:8A', routerId: 'patio', band: '2.4 GHz',
-    signalDbm: -72, trafficMbps: 1.1, online: true,
-    sparkline: [1, 1.1, 1.1, 1.2, 1.1, 1, 1.1, 1.1, 1.2, 1.1, 1.1, 1.1],
-  },
-  {
-    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: -55, trafficMbps: 0.4, online: true,
-    sparkline: [0.3, 0.4, 0.4, 0.5, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4],
-  },
-  {
-    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: null, trafficMbps: 2.3, online: true,
-    sparkline: [1, 1.5, 2, 2.5, 3, 2.8, 2.4, 2.2, 2.3, 2.3, 2.3, 2.3],
-  },
-  {
-    id: 'bombillas-ikea', name: 'Ikea bulbs ×6', type: 'iot', manufacturer: 'Ikea',
-    ip: '192.168.8.8x', mac: '—', routerId: 'living', band: '2.4 GHz',
-    signalDbm: -60, trafficMbps: 0, online: true,
-    sparkline: [0, 0, 0.01, 0, 0, 0.01, 0, 0, 0, 0.01, 0, 0],
-  },
-  {
-    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: -50, trafficMbps: 1.8, online: true, isNew: true,
-    sparkline: [0, 0, 0, 0, 0, 0, 0, 0, 0.5, 1.2, 1.6, 1.8],
-  },
-]
-
-// ---------------------------------------------------------------------------
-// AdGuard Home (en Flint 2, :3000)
-// ---------------------------------------------------------------------------
-
-export const adguard = {
-  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: [
-    { 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,
-}
-
-// ---------------------------------------------------------------------------
-// WireGuard (servidor en Flint 2, wg0 · 10.0.0.1/24)
-// ---------------------------------------------------------------------------
-
-export const wireguard = {
-  interface: 'wg0',
-  subnet: '10.0.0.1/24',
-  status: 'active',
-  peers: [
-    { id: 'pixel-8-pro', name: 'Pixel 8 Pro', type: 'movil', tunnelIp: '10.0.0.2', active: true, lastHandshake: '38s ago', rx: '1.2 GB', tx: '214 MB' },
-    { id: 'macbook-air', name: 'MacBook Air', type: 'portatil', tunnelIp: '10.0.0.3', active: true, lastHandshake: '1 min ago', rx: '640 MB', tx: '88 MB' },
-    { id: 'ipad-air', name: 'iPad Air', type: 'tablet', tunnelIp: '10.0.0.4', active: false, lastHandshake: '2 days ago', rx: '3.1 GB', tx: '402 MB' },
-    { id: 'portatil-trabajo', name: 'Work laptop', type: 'portatil', tunnelIp: '10.0.0.5', active: false, lastHandshake: '6h ago', rx: '812 MB', tx: '121 MB' },
-    { id: 'casa-familia', name: 'Family home', type: 'sitio', tunnelIp: '10.0.0.6', active: false, lastHandshake: '9 days ago', rx: '12 GB', tx: '4.2 GB' },
-  ],
-}
-
-// ---------------------------------------------------------------------------
-// Alertas (canon §11)
-// ---------------------------------------------------------------------------
-
-export const alerts = [
-  {
-    id: 'alert-temp-patio', severity: 'warn', title: 'High temperature on Patio',
-    description: '71 °C, above the threshold (65 °C)', time: '12 min ago', read: false, routerId: 'patio',
-  },
-  {
-    id: 'alert-firmware-estudio', severity: 'warn', title: 'Firmware available',
-    description: 'OpenWrt 24.10.1 for Study', time: '3h ago', read: false, routerId: 'estudio',
-  },
-  {
-    id: 'alert-nuevo-tab', severity: 'info', title: 'New device',
-    description: "'Galaxy Tab S9' joined Living Room", time: '26 min ago', read: true, routerId: 'living',
-  },
-  {
-    id: 'alert-handshake-wg', severity: 'info', title: 'WireGuard handshake',
-    description: 'Pixel 8 Pro connected from 5.224.x.x', time: '38s ago', read: true, routerId: 'flint2',
-  },
-  {
-    id: 'alert-backup-adguard', severity: 'ok', title: 'AdGuard backup completed',
-    description: 'Configuration and lists backed up to the NAS', time: '1 day ago', read: true, routerId: 'flint2',
-  },
-]
-
-export const unreadAlerts = alerts.filter((a) => !a.read).length
-
-// ---------------------------------------------------------------------------
-// Lista completa de clientes (port de app/src/pages/devices-data.ts):
-// 10 canónicos (el agregado "Bombillas Ikea ×6" se expande en 6 bombillas)
-// + 37 adicionales = 47 · 39 online · 8 offline
-// (Gateway 14, Salón 18, Estudio 9, Patio 6)
-// ---------------------------------------------------------------------------
-
-const CANON_DETAILS = {
-  'imac-salon': {
-    hostname: 'imac-de-marc', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
-    traffic24hRx: '38 GB', traffic24hTx: '2.1 GB', adguard: true, group: 'ordenadores',
-  },
-  'tv-samsung': {
-    hostname: 'samsung-tv-salon', dhcpLease: 'renews in 7h 48min', firstSeen: '290 days ago',
-    traffic24hRx: '54 GB', traffic24hTx: '1.2 GB', adguard: true, group: 'tv',
-  },
-  'pixel-8-pro': {
-    hostname: 'pixel-8-pro', dhcpLease: 'renews in 9h 12min', firstSeen: '214 days ago',
-    traffic24hRx: '4.2 GB', traffic24hTx: '310 MB', adguard: true, group: 'moviles',
-  },
-  'macbook-air': {
-    hostname: 'macbook-air-de-ana', dhcpLease: 'renews in 5h 31min', firstSeen: '260 days ago',
-    traffic24hRx: '18 GB', traffic24hTx: '2.2 GB', adguard: true, group: 'ordenadores',
-  },
-  'ps5': {
-    hostname: 'ps5-salon', dhcpLease: 'Static IP (reservation)', firstSeen: '300 days ago',
-    traffic24hRx: '92 GB', traffic24hTx: '4.8 GB', adguard: true, group: 'tv',
-  },
-  'robot-aspirador': {
-    hostname: 'roborock-s8', dhcpLease: 'renews in 10h 2min', firstSeen: '180 days ago',
-    traffic24hRx: '340 MB', traffic24hTx: '28 MB', adguard: true, group: 'iot',
-  },
-  'camara-porche': {
-    hostname: 'reolink-porche', dhcpLease: 'renews in 3h 57min', firstSeen: '150 days ago',
-    traffic24hRx: '11 GB', traffic24hTx: '640 MB', adguard: true, group: 'iot',
-  },
-  'nest-mini': {
-    hostname: 'nest-mini-estudio', dhcpLease: 'renews in 8h 20min', firstSeen: '240 days ago',
-    traffic24hRx: '1.4 GB', traffic24hTx: '88 MB', adguard: true, group: 'iot',
-  },
-  'nas-synology': {
-    hostname: 'diskstation', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
-    traffic24hRx: '96 GB', traffic24hTx: '1.1 TB', adguard: true, group: 'red',
-  },
-  'galaxy-tab-s9': {
-    hostname: 'galaxy-tab-s9', dhcpLease: 'renews in 11h 5min', firstSeen: 'today',
-    traffic24hRx: '640 MB', traffic24hTx: '48 MB', adguard: true, group: 'moviles', newThisWeek: true,
-  },
-}
-
-/** Sparkline determinista (mismo PRNG que devices-data.ts) */
-function spark(seed, base, spread) {
-  let s = seed
-  const out = []
-  for (let i = 0; i < 12; i++) {
-    s = (s * 9301 + 49297) % 233280
-    const r = s / 233280
-    out.push(Math.max(0, +(base + (r - 0.45) * spread).toFixed(2)))
-  }
-  out[out.length - 1] = base
-  return out
-}
-
-function extra(spec) {
-  const { seed = 1, spread, ...d } = spec
-  return { ...d, sparkline: d.online ? spark(seed, d.trafficMbps, spread ?? d.trafficMbps * 0.8) : [] }
-}
-
-function bulb(n, name, ip, mac, dbm) {
-  return {
-    id: `bombilla-${n}`, name, type: 'iot', manufacturer: 'Ikea Trådfri',
-    ip, mac, routerId: 'living', band: '2.4 GHz', signalDbm: dbm,
-    trafficMbps: 0, online: true, sparkline: spark(40 + n, 0.005, 0.02),
-    hostname: `tradfri-${n}`, dhcpLease: 'renews in 12h 0min', firstSeen: '280 days ago',
-    traffic24hRx: '4 MB', traffic24hTx: '1 MB', adguard: true, group: 'iot',
-  }
-}
-
-const ADDITIONAL = [
-  // —— Gateway (flint2): 14 totales (canon: pixel-8-pro, nas-synology) ——
-  {
-    ...extra({ id: 'iphone-ana', name: "Ana's iPhone", type: 'movil', manufacturer: 'Apple',
-      ip: '192.168.8.44', mac: 'F4:D4:88:19:C2:71', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -46, trafficMbps: 2.1, online: true, seed: 11 }),
-    hostname: 'iphone-de-ana', dhcpLease: 'renews in 6h 40min', firstSeen: '190 days ago',
-    traffic24hRx: '2.8 GB', traffic24hTx: '240 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'macbook-pro', name: "Marc's MacBook Pro", type: 'portatil', manufacturer: 'Apple',
-      ip: '192.168.8.26', mac: 'F0:18:98:5A:11:E9', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -44, trafficMbps: 8.6, online: true, seed: 12 }),
-    hostname: 'macbook-pro-marc', dhcpLease: 'renews in 4h 16min', firstSeen: '230 days ago',
-    traffic24hRx: '12.4 GB', traffic24hTx: '1.9 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'pc-sobremesa', name: 'Desktop PC', type: 'ordenador', manufacturer: 'ASUSTeK',
-      ip: '192.168.8.11', mac: '04:D4:C4:8B:30:A7', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 21.3, online: true, seed: 13 }),
-    hostname: 'desktop-8f2k1', dhcpLease: 'Static IP (reservation)', firstSeen: '310 days ago',
-    traffic24hRx: '84 GB', traffic24hTx: '6.2 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ 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: null, trafficMbps: 0.8, online: true, seed: 14 }),
-    hostname: 'raspberrypi', dhcpLease: 'Static IP (reservation)', firstSeen: '320 days ago',
-    traffic24hRx: '3.4 GB', traffic24hTx: '890 MB', adguard: true, group: 'red',
-  },
-  {
-    ...extra({ id: 'switch-netgear', name: 'Netgear 8-port switch', type: 'servidor', manufacturer: 'Netgear',
-      ip: '192.168.8.13', mac: '28:C6:8E:1D:90:44', routerId: 'flint2', band: 'cable',
-      signalDbm: null, trafficMbps: 0.02, online: true, seed: 15, spread: 0.04 }),
-    hostname: 'gs308e', dhcpLease: 'Static IP (reservation)', firstSeen: '300 days ago',
-    traffic24hRx: '64 MB', traffic24hTx: '12 MB', adguard: false, group: 'red',
-    iconOverride: 'Network',
-  },
-  {
-    ...extra({ id: 'timbre-nest', name: 'Nest doorbell', type: 'camara', manufacturer: 'Google',
-      ip: '192.168.8.72', mac: 'F4:F5:D8:66:01:B8', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -58, trafficMbps: 0.6, online: true, seed: 16 }),
-    hostname: 'nest-doorbell', dhcpLease: 'renews in 9h 44min', firstSeen: '170 days ago',
-    traffic24hRx: '1.2 GB', traffic24hTx: '140 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'enchufe-lavadora', name: 'Washing machine plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.81', mac: '50:C7:BF:22:E1:9C', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -62, trafficMbps: 0.01, online: true, seed: 17, spread: 0.02 }),
-    hostname: 'tapo-p110-lavadora', dhcpLease: 'renews in 12h 0min', firstSeen: '140 days ago',
-    traffic24hRx: '8 MB', traffic24hTx: '2 MB', adguard: false, group: 'iot',
-  },
-  {
-    ...extra({ 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: -49, trafficMbps: 1.4, online: true, seed: 18 }),
-    hostname: 'pixel-7', dhcpLease: 'renews in 7h 3min', firstSeen: '205 days ago',
-    traffic24hRx: '1.9 GB', traffic24hTx: '180 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'impresora-hp', name: 'HP Printer', type: 'desconocido', manufacturer: 'HP',
-      ip: '192.168.8.14', mac: '3C:52:82:AB:19:60', routerId: 'flint2', band: '2.4 GHz',
-      signalDbm: -60, trafficMbps: 0, online: false }),
-    hostname: 'hp-laserjet-m209', dhcpLease: 'Expired', firstSeen: '250 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'otros',
-    iconOverride: 'Printer',
-  },
-  {
-    ...extra({ 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: -54, trafficMbps: 0, online: false }),
-    hostname: 'ipad-air', dhcpLease: 'Expired', firstSeen: '260 days ago',
-    traffic24hRx: '6.4 GB', traffic24hTx: '520 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ id: 'portatil-trabajo', name: 'Work laptop', type: 'portatil', manufacturer: 'Lenovo',
-      ip: '192.168.8.27', mac: '54:EE:75:9A:03:F1', routerId: 'flint2', band: '5 GHz',
-      signalDbm: -50, trafficMbps: 0, online: false }),
-    hostname: 'thinkpad-t14', dhcpLease: 'Expired', firstSeen: '160 days ago',
-    traffic24hRx: '812 MB', traffic24hTx: '121 MB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ 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: -58, trafficMbps: 0, online: false }),
-    hostname: 'kindle-paperwhite', dhcpLease: 'Expired', firstSeen: '220 days ago',
-    traffic24hRx: '220 MB', traffic24hTx: '8 MB', adguard: true, group: 'otros',
-    iconOverride: 'BookOpen',
-  },
-]
-
-const LIVING = [
-  // —— Salón (living): 18 totales (canon: imac, tv-samsung, ps5, galaxy-tab-s9) ——
-  bulb(1, 'Living room bulb 1', '192.168.8.90', 'CC:86:EC:10:04:21', -58),
-  bulb(2, 'Living room bulb 2', '192.168.8.91', 'CC:86:EC:10:04:22', -59),
-  bulb(3, 'Floor lamp bulb', '192.168.8.92', 'CC:86:EC:10:04:23', -61),
-  bulb(4, 'Entryway bulb', '192.168.8.93', 'CC:86:EC:10:04:24', -64),
-  bulb(5, 'Hallway bulb', '192.168.8.94', 'CC:86:EC:10:04:25', -66),
-  bulb(6, 'Kitchen bulb', '192.168.8.95', 'CC:86:EC:10:04:26', -60),
-  {
-    ...extra({ 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: -54, trafficMbps: 3.9, online: true, seed: 21 }),
-    hostname: 'chromecast-hd', dhcpLease: 'renews in 6h 12min', firstSeen: '200 days ago',
-    traffic24hRx: '21 GB', traffic24hTx: '380 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ 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: -47, trafficMbps: 0.3, online: true, seed: 22 }),
-    hostname: 'homepod-mini', dhcpLease: 'renews in 10h 41min', firstSeen: '190 days ago',
-    traffic24hRx: '2.2 GB', traffic24hTx: '96 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ 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: -51, trafficMbps: 0.9, online: true, seed: 23 }),
-    hostname: 'galaxy-s23', dhcpLease: 'renews in 8h 55min', firstSeen: '175 days ago',
-    traffic24hRx: '3.2 GB', traffic24hTx: '290 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ 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: -56, trafficMbps: 0.2, online: true, seed: 24 }),
-    hostname: 'echo-dot-cocina', dhcpLease: 'renews in 11h 18min', firstSeen: '210 days ago',
-    traffic24hRx: '1.1 GB', traffic24hTx: '74 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ 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: -53, trafficMbps: 0.1, online: true, seed: 25, spread: 0.3 }),
-    hostname: 'switch-oled', dhcpLease: 'renews in 5h 47min', firstSeen: '240 days ago',
-    traffic24hRx: '8.6 GB', traffic24hTx: '310 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'portatil-invitado', name: 'Guest laptop', type: 'portatil', manufacturer: 'Desconocido',
-      ip: '192.168.8.29', mac: 'A2:7E:9C:41:0B:6D', routerId: 'living', band: '5 GHz',
-      signalDbm: -58, trafficMbps: 0.7, online: true, isNew: true, seed: 26 }),
-    hostname: 'unknown-7f2a', dhcpLease: 'renews in 2h 9min', firstSeen: 'today',
-    traffic24hRx: '480 MB', traffic24hTx: '62 MB', adguard: false, group: 'ordenadores',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ 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: -55, trafficMbps: 0, online: false }),
-    hostname: 'xbox-series-s', dhcpLease: 'Expired', firstSeen: '230 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'tv',
-  },
-  {
-    ...extra({ id: 'portatil-antiguo', name: 'Old laptop', type: 'portatil', manufacturer: 'HP',
-      ip: '192.168.8.28', mac: '3C:52:82:5D:90:17', routerId: 'living', band: '2.4 GHz',
-      signalDbm: -62, trafficMbps: 0, online: false }),
-    hostname: 'hp-pavilion-15', dhcpLease: 'Expired', firstSeen: '300 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'ordenadores',
-  },
-]
-
-const ESTUDIO = [
-  // —— Estudio: 9 totales (canon: macbook-air, nest-mini) ——
-  {
-    ...extra({ 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: null, trafficMbps: 1.9, online: true, seed: 31 }),
-    hostname: 'mac-mini', dhcpLease: 'Static IP (reservation)', firstSeen: '280 days ago',
-    traffic24hRx: '44 GB', traffic24hTx: '5.6 GB', adguard: true, group: 'ordenadores',
-  },
-  {
-    ...extra({ id: 'enchufe-ventilador', name: 'Fan plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.82', mac: '9C:53:22:B1:4E:70', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -59, trafficMbps: 0.01, online: true, seed: 32, spread: 0.02 }),
-    hostname: 'tapo-p110-ventilador', dhcpLease: 'renews in 12h 0min', firstSeen: '120 days ago',
-    traffic24hRx: '7 MB', traffic24hTx: '2 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ 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: -49, trafficMbps: 0.8, online: true, seed: 33 }),
-    hostname: 'ipad-pro', dhcpLease: 'renews in 9h 26min', firstSeen: '160 days ago',
-    traffic24hRx: '5.1 GB', traffic24hTx: '390 MB', adguard: true, group: 'moviles',
-  },
-  {
-    ...extra({ 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: null, trafficMbps: 0.02, online: true, seed: 34, spread: 0.04 }),
-    hostname: 'philips-hue-bridge', dhcpLease: 'Static IP (reservation)', firstSeen: '280 days ago',
-    traffic24hRx: '96 MB', traffic24hTx: '22 MB', adguard: false, group: 'iot',
-  },
-  {
-    ...extra({ 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: -57, trafficMbps: 0.5, online: true, seed: 35 }),
-    hostname: 'sonos-one-estudio', dhcpLease: 'renews in 10h 4min', firstSeen: '195 days ago',
-    traffic24hRx: '3.8 GB', traffic24hTx: '110 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'iphone-trabajo', name: 'Work iPhone', type: 'movil', manufacturer: 'Apple',
-      ip: '192.168.8.50', mac: '8C:85:90:47:C1:93', routerId: 'estudio', band: '5 GHz',
-      signalDbm: -47, trafficMbps: 0.3, online: true, isNew: true, seed: 36 }),
-    hostname: 'iphone-15-pro-work', dhcpLease: 'renews in 3h 38min', firstSeen: 'today',
-    traffic24hRx: '320 MB', traffic24hTx: '41 MB', adguard: true, group: 'moviles',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'macbook-viejo', name: 'Old MacBook', type: 'portatil', manufacturer: 'Apple',
-      ip: '192.168.8.25', mac: '3C:22:FB:0E:66:A1', routerId: 'estudio', band: '2.4 GHz',
-      signalDbm: -60, trafficMbps: 0, online: false }),
-    hostname: 'macbook-pro-2015', dhcpLease: 'Expired', firstSeen: '320 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: true, group: 'ordenadores',
-  },
-]
-
-const PATIO = [
-  // —— Patio: 6 totales (canon: robot-aspirador, camara-porche) ——
-  {
-    ...extra({ id: 'camara-jardin', name: 'Garden camera', type: 'camara', manufacturer: 'Reolink',
-      ip: '192.168.8.73', mac: 'EC:71:DB:44:12:9B', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -74, trafficMbps: 1.4, online: true, seed: 41 }),
-    hostname: 'reolink-jardin', dhcpLease: 'renews in 8h 49min', firstSeen: '4 days ago',
-    traffic24hRx: '14 GB', traffic24hTx: '820 MB', adguard: true, group: 'iot',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'sensor-riego', name: 'Irrigation sensor', type: 'iot', manufacturer: 'Tuya',
-      ip: '192.168.8.89', mac: 'D8:1F:12:5B:08:44', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -71, trafficMbps: 0.01, online: true, seed: 42, spread: 0.02 }),
-    hostname: 'tuya-riego-01', dhcpLease: 'renews in 12h 0min', firstSeen: '5 days ago',
-    traffic24hRx: '2 MB', traffic24hTx: '1 MB', adguard: false, group: 'iot',
-    newThisWeek: true,
-  },
-  {
-    ...extra({ id: 'enchufe-calefactor', name: 'Heater plug', type: 'iot', manufacturer: 'TP-Link',
-      ip: '192.168.8.80', mac: '50:C7:BF:31:7A:05', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -75, trafficMbps: 0.02, online: true, seed: 43, spread: 0.03 }),
-    hostname: 'tapo-p110-calefactor', dhcpLease: 'renews in 12h 0min', firstSeen: '96 days ago',
-    traffic24hRx: '6 MB', traffic24hTx: '2 MB', adguard: true, group: 'iot',
-  },
-  {
-    ...extra({ id: 'camara-garaje', name: 'Garage camera', type: 'camara', manufacturer: 'Reolink',
-      ip: '192.168.8.74', mac: 'EC:71:DB:44:13:02', routerId: 'patio', band: '2.4 GHz',
-      signalDbm: -78, trafficMbps: 0, online: false }),
-    hostname: 'reolink-garaje', dhcpLease: 'Expired', firstSeen: '130 days ago',
-    traffic24hRx: '0 MB', traffic24hTx: '0 MB', adguard: false, group: 'iot',
-  },
-]
-
-// Lista completa: 47 clientes (los 10 del canon — salvo el agregado de
-// bombillas, que se expande — + 37 adicionales)
-const canonExpanded = canonDevices
-  .filter((d) => d.id !== 'bombillas-ikea')
-  .map((d) => ({ ...d, ...CANON_DETAILS[d.id] }))
-
-export const allDevices = [...canonExpanded, ...ADDITIONAL, ...LIVING, ...ESTUDIO, ...PATIO]
-
-// ---------------------------------------------------------------------------
-// Extras por router (port de routerExtras.ts). Toda serie termina en el valor
-// actual canónico del router.
-// ---------------------------------------------------------------------------
-
-export const routerExtras = {
-  flint2: {
-    mac: '94:83:C4:2A:7F:10',
-    firmware: 'GL 4.7.0',
-    firmwareBase: 'OpenWrt 21.02',
-    firmwareUpdated: true,
-    lastReboot: 'Nov 12, 03:12 (maintenance)',
-    soc: 'MediaTek MT7986A',
-    flash: '8 GB eMMC',
-    ramMb: 512,
-    bandSplit: { band24: 4, band5: 10, cable: 3 },
-    trafficNow: 84.2,
-    gatewayLatencySpark: [],
-    backhaulSignal: [],
-    radios: [],
-    ports: [],
-    // GL-MT6000: 1× WAN 2.5G + 4× LAN 1G
-    ethPorts: [
-      { id: 'wan', label: 'WAN', up: true, speed: '2.5 Gbps', connectedTo: 'Fiber ONT · Digi', detail: '84.122.x.x · full duplex' },
-      { id: 'lan1', label: 'LAN 1', up: true, speed: '1 Gbps', connectedTo: 'Living Room · AX3000T', detail: 'Living Room AP uplink (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: 'Study · NanoPi R4S', detail: 'Study AP uplink (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: 'Nov 12, 03:12 (maintenance)',
-    soc: 'MediaTek MT7981B',
-    flash: '128 MB NAND',
-    ramMb: 256,
-    bandSplit: { band24: 6, band5: 10, cable: 2 },
-    trafficNow: 51.7,
-    gatewayLatencyMs: 1,
-    gatewayLatencySpark: [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: { kind: 'cable', headline: 'Cable · 1 Gbps · full duplex', latencyMs: 1 },
-    backhaulSignal: [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: [
-      { name: '2.4 GHz', channel: 6, widthMhz: 20, powerDbm: 20, clients: 6 },
-      { name: '5 GHz', channel: 36, widthMhz: 80, powerDbm: 23, clients: 10 },
-    ],
-    ports: [
-      { name: 'br-lan', up: true, speed: '—', role: 'Bridge LAN' },
-      { name: 'eth0', up: true, speed: '1 Gbps', role: 'Uplink to 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: [
-      { 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: 'Dec 2, 21:40 (update)',
-    soc: 'Rockchip RK3399',
-    flash: '32 GB microSD',
-    ramMb: 1024,
-    bandSplit: { band24: 4, band5: 4, cable: 1 },
-    trafficNow: 9.4,
-    gatewayLatencyMs: 1,
-    gatewayLatencySpark: [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: { kind: 'cable', headline: 'Cable · 1 Gbps · full duplex', latencyMs: 1 },
-    backhaulSignal: [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: [
-      { name: '2.4 GHz', channel: 11, widthMhz: 20, powerDbm: 18, clients: 4 },
-      { name: '5 GHz', channel: 44, widthMhz: 80, powerDbm: 21, clients: 4 },
-    ],
-    ports: [
-      { name: 'br-lan', up: true, speed: '—', role: 'Bridge LAN' },
-      { name: 'eth0', up: true, speed: '1 Gbps', role: 'Uplink to Gateway' },
-      { name: 'eth1', up: true, speed: '1 Gbps', role: 'Study switch' },
-      { 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: [
-      { 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: 'Study switch', detail: '8-port switch · 4 in use' },
-    ],
-  },
-  patio: {
-    mac: 'C0:4A:00:9B:51:8D',
-    firmware: 'OpenWrt 23.05.5',
-    firmwareUpdated: false,
-    firmwareAvailable: '24.10.1',
-    lastReboot: 'Dec 9, 14:05 (power outage)',
-    soc: 'Qualcomm QCA9563',
-    flash: '16 MB SPI',
-    ramMb: 128,
-    bandSplit: { band24: 5, band5: 1, cable: 0 },
-    trafficNow: 1.8,
-    gatewayLatencyMs: 2,
-    gatewayLatencySpark: [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: { kind: 'wireless', headline: '−58 dBm · 866 Mbps PHY', latencyMs: 2 },
-    backhaulSignal: [-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: [
-      { 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: [
-      { name: 'br-lan', up: true, speed: '—', role: 'Bridge LAN' },
-      { name: 'eth0', up: false, speed: '—', role: 'LAN port (unused)' },
-      { name: 'phy0-ap0', up: true, speed: '—', role: 'Radio 2.4 GHz' },
-      { name: 'phy1-sta0', up: true, speed: '866 Mbps', role: 'Wireless uplink to Gateway' },
-    ],
-    // EAP225: 1× 1G — sin uso (uplink inalámbrico mesh, ver backhaul)
-    ethPorts: [
-      { id: 'lan1', label: 'LAN', up: false, detail: 'Uplink over WiFi mesh' },
-    ],
-  },
-}
-
-export function getRouterExtras(id) {
-  return routerExtras[id] ?? routerExtras.flint2
-}
-
-// ---------------------------------------------------------------------------
-// Series de rendimiento (CPU / RAM / Temp) — deterministas, terminan en el
-// valor actual canónico. Picos documentados: Gateway CPU 61 % (21:10), temp
-// máx 58 °C.
-// ---------------------------------------------------------------------------
-
-/** Ruido determinista 0..1 a partir del índice y una semilla por router. */
-function noise(i, seed) {
-  const x = Math.sin(i * 127.1 + seed * 311.7) * 43758.5453
-  return x - Math.floor(x)
-}
-
-function hourLabels() {
-  return Array.from({ length: 24 }, (_, i) => `${String(i).padStart(2, '0')}:00`)
-}
-
-/** Etiquetas para 1h: puntos cada 3 minutos terminando "ahora". */
-function hourRangeLabels(n = 20) {
-  const labels = []
-  const now = new Date()
-  for (let i = n - 1; i >= 0; i--) {
-    const d = new Date(now.getTime() - i * 3 * 60_000)
-    labels.push(`${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`)
-  }
-  return labels
-}
-
-const DAY_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
-
-export function perfSeries(router, range) {
-  const seed = routers.findIndex((r) => r.id === router.id) + 1
-  const isGateway = router.id === 'flint2'
-  const n = range === '1h' ? 20 : range === '24h' ? 24 : 7
-  const labels = range === '1h' ? hourRangeLabels(n) : range === '24h' ? hourLabels() : DAY_LABELS
-
-  // Índice del pico: 21:00 en 24h, penúltimo tramo en 1h, viernes en 7d
-  const peakIdx = range === '24h' ? 21 : range === '1h' ? 15 : 4
-  const cpuPeak = isGateway ? 61 : Math.min(88, router.cpu + 34)
-  const tempPeak = isGateway ? 58 : router.temp + 4
-
-  const points = []
-  for (let i = 0; i < n; i++) {
-    // Forma diaria: valle de madrugada, subida por la tarde
-    const dayShape =
-      range === '7d'
-        ? 0.7 + 0.3 * (i / (n - 1))
-        : 0.55 + 0.45 * Math.sin(((i - 6) / n) * Math.PI * 2 - Math.PI / 2) ** 2
-    const wob = noise(i, seed)
-    let cpu = Math.max(2, Math.round(router.cpu * dayShape + wob * 6))
-    const ram = Math.max(10, Math.round(router.ram - 6 + wob * 10 + (i / n) * 4))
-    let temp = Math.max(30, Math.round(router.temp - 5 + wob * 4 + dayShape * 4))
-    if (i === peakIdx) cpu = cpuPeak
-    if (i === peakIdx) temp = tempPeak
-    points.push({ t: labels[i], cpu, ram, temp })
-  }
-  // La serie termina SIEMPRE en el valor canónico actual
-  points[n - 1] = { t: labels[n - 1], cpu: router.cpu, ram: router.ram, temp: router.temp }
-  return points
-}
-
-// ---------------------------------------------------------------------------
-// Latencia WAN 24h (Flint 2): base 8-12 ms, pico 34 ms a las 21:00 (canon).
-// ---------------------------------------------------------------------------
-
-export const WAN_LATENCY_24H = [
-  9, 8, 8, 7, 7, 8, 9, 10, 11, 12, 11, 12, 13, 12, 11, 12, 14, 16, 19, 24, 29, 34, 14, 8,
-]
-
-export const WAN_LATENCY_STATS = { avgMs: 11, jitterMs: 2.1, lossPct: 0 }
-
-// ---------------------------------------------------------------------------
-// AdGuard — serie horaria 24h: suma exacta del canon (84 312 / 15 687) con el
-// punto documentado 21:00 → 5 412 consultas · 1 031 bloqueadas.
-// ---------------------------------------------------------------------------
-
-function buildAdGuardSeries() {
-  // Pesos de actividad por hora (valle nocturno, pico 21h)
-  const weights = [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 = adguard.queries24h
-  const totalB = adguard.blocked24h
-  const sumW = weights.reduce((a, b) => a + b, 0)
-  const q = weights.map((w) => Math.round((w / sumW) * totalQ))
-  // Fijar el punto canónico de las 21:00 y repartir el ajuste
-  q[21] = 5412
-  const drift = totalQ - q.reduce((a, b) => a + b, 0)
-  q[20] += drift // absorber el redondeo en la hora anterior
-  const b = q.map((v) => Math.round(v * (totalB / totalQ)))
-  b[21] = 1031
-  const driftB = totalB - b.reduce((a, c) => a + c, 0)
-  b[20] += driftB
-  return q.map((v, i) => ({
-    t: `${String(i).padStart(2, '0')}:00`,
-    permitidas: v - b[i],
-    bloqueadas: b[i],
-  }))
-}
-
-export const adguardSeries24h = buildAdGuardSeries()
-
-// ---------------------------------------------------------------------------
-// WireGuard — extras de peers (endpoint, allowed IPs, última IP de conexión)
-// ---------------------------------------------------------------------------
-
-export const wgPeerExtras = {
-  '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' },
-}
-
-export const WG_TOTALS_30D = { rx: '17.9 GB', tx: '5.0 GB' }
-
-// ---------------------------------------------------------------------------
-// Utilidades
-// ---------------------------------------------------------------------------
-
-export function getRouter(id) {
-  return routers.find((r) => r.id === id)
-}
-
-/** "32d 14h" → horas (para ordenar la tabla comparativa) */
-export function uptimeHours(uptime) {
-  const d = /([0-9]+)d/.exec(uptime)?.[1] ?? '0'
-  const h = /([0-9]+)h/.exec(uptime)?.[1] ?? '0'
-  return Number(d) * 24 + Number(h)
-}

+ 0 - 214
legacy/server-node/src/discover.js

@@ -1,214 +0,0 @@
-/**
- * Descubrimiento de routers candidatos en la LAN:
- *
- *  1. Subred: se deriva de la puerta de enlace por defecto (`ip route`),
- *     asumiendo /24 (LAN doméstica).
- *  2. Barrido TCP del puerto 22 en los 254 hosts con concurrencia limitada
- *     (NO se usa ping: necesita cap_net_raw, no disponible en LXC ni con el
- *     hardening del servicio).
- *  3. A los vivos se les prueba la firma OpenWrt: POST http://<ip>/ubus
- *     (cualquier respuesta JSON-RPC, incluso "access denied", delata uhttpd
- *     con ubus ⇒ router OpenWrt/GL.iNet).
- *  4. A los candidatos se les prueba SSH con la clave propia (BatchMode):
- *       - OK → `authorized: true` + modelo (ubus system board)
- *       - Permission denied → `authorized: false` (falta autorizar la clave)
- *
- * El resultado se cachea 60 s (el barrido tarda varios segundos).
- */
-import net from 'node:net'
-import http from 'node:http'
-import https from 'node:https'
-import { execFile } from 'node:child_process'
-import { detectGatewayIp, listRouters } from './routerstore.js'
-import { sshBaseArgs } from './sshkey.js'
-
-const CACHE_MS = 60_000
-const TCP_TIMEOUT_MS = 800
-const HTTP_TIMEOUT_MS = 1500
-const SSH_TIMEOUT_MS = 4000
-
-let cache = { at: 0, subnet: null, results: [] }
-
-function exec(cmd, args, timeoutMs) {
-  return new Promise((resolve) => {
-    execFile(cmd, args, { timeout: timeoutMs }, (err, stdout) => {
-      resolve({ ok: !err, stdout: stdout || '' })
-    })
-  })
-}
-
-/** true si el puerto TCP responde (SYN/ACK) antes del timeout. */
-function tcpOpen(host, port, timeoutMs = TCP_TIMEOUT_MS) {
-  return new Promise((resolve) => {
-    const sock = net.connect({ host, port, timeout: timeoutMs })
-    sock.once('connect', () => {
-      sock.destroy()
-      resolve(true)
-    })
-    sock.once('timeout', () => {
-      sock.destroy()
-      resolve(false)
-    })
-    sock.once('error', () => resolve(false))
-  })
-}
-
-/** Ejecuta tareas con concurrencia limitada. */
-async function pool(items, size, fn) {
-  const out = new Array(items.length)
-  let i = 0
-  await Promise.all(
-    Array.from({ length: Math.min(size, items.length) }, async () => {
-      while (i < items.length) {
-        const idx = i++
-        out[idx] = await fn(items[idx])
-      }
-    }),
-  )
-  return out
-}
-
-/** POST /ubus crudo (http u https con cert ignorado) — devuelve {status, body} o null. */
-function postUbus(host, useHttps) {
-  return new Promise((resolve) => {
-    const body = JSON.stringify({
-      jsonrpc: '2.0',
-      id: 1,
-      method: 'call',
-      params: ['0'.repeat(32), 'session', 'login', { username: 'netpulse-probe', password: '' }],
-    })
-    const mod = useHttps ? https : http
-    const req = mod.request(
-      {
-        host,
-        port: useHttps ? 443 : 80,
-        path: '/ubus',
-        method: 'POST',
-        headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
-        timeout: HTTP_TIMEOUT_MS,
-        rejectUnauthorized: false,
-      },
-      (res) => {
-        let data = ''
-        res.on('data', (chunk) => {
-          data += chunk
-          if (data.length > 8192) req.destroy()
-        })
-        res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data }))
-      },
-    )
-    req.on('timeout', () => {
-      req.destroy()
-      resolve(null)
-    })
-    req.on('error', () => resolve(null))
-    req.write(body)
-    req.end()
-  })
-}
-
-/**
- * true si el host huele a OpenWrt/GL.iNet:
- *  1. POST /ubus (http, luego https si hay redirect) con firma JSON-RPC.
- *  2. El firmware GL.iNet NO expone /ubus (nginx lo redirige a su UI) →
- *     firma alternativa: el HTML raíz contiene "gl-ui"/"GL.iNet".
- */
-async function probeUbus(host) {
-  const isUbus = (r) => r && (r.body.includes('jsonrpc') || r.body.includes('ubus_rpc_session'))
-  const httpRes = await postUbus(host, false)
-  if (isUbus(httpRes)) return true
-  if (httpRes && [301, 302, 307, 308].includes(httpRes.status)) {
-    if (isUbus(await postUbus(host, true))) return true
-    const root = await getRoot(host, true)
-    if (root && /gl-ui|GL\.iNet|glinet/i.test(root.body)) return true
-  }
-  return false
-}
-
-/** GET / (http/https, cert ignorado) — devuelve {status, body} o null. */
-function getRoot(host, useHttps) {
-  return new Promise((resolve) => {
-    const mod = useHttps ? https : http
-    const req = mod.request(
-      { host, port: useHttps ? 443 : 80, path: '/', method: 'GET', timeout: HTTP_TIMEOUT_MS, rejectUnauthorized: false },
-      (res) => {
-        let data = ''
-        res.on('data', (chunk) => {
-          data += chunk
-          if (data.length > 16384) req.destroy()
-        })
-        res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data }))
-        res.on('error', () => resolve(null))
-      },
-    )
-    req.on('timeout', () => {
-      req.destroy()
-      resolve(null)
-    })
-    req.on('error', () => resolve(null))
-    req.end()
-  })
-}
-
-/** Prueba SSH con la clave propia; devuelve { authorized, model }. */
-async function probeSsh(host, sshKeyPath) {
-  const { ok, stdout } = await exec(
-    'ssh',
-    [
-      ...sshBaseArgs(sshKeyPath),
-      '-o', 'ConnectTimeout=2',
-      '-o', 'ControlMaster=no',
-      `root@${host}`,
-      'ubus call system board | jsonfilter -e @.model',
-    ],
-    SSH_TIMEOUT_MS,
-  )
-  if (!ok) return { authorized: false, model: null }
-  return { authorized: true, model: stdout.trim() || null }
-}
-
-/**
- * Escanea la LAN y devuelve candidatos a router OpenWrt.
- * @param {object} db - handle better-sqlite3 (para marcar los ya configurados)
- * @param {string} sshKeyPath
- * @param {boolean} force - ignora la caché
- */
-export async function discoverRouters(db, sshKeyPath, force = false) {
-  if (!force && Date.now() - cache.at < CACHE_MS) return { ...cache, cached: true }
-
-  const gwIp = await detectGatewayIp()
-  if (!gwIp) return { subnet: null, results: [], cached: false, error: 'no_gateway' }
-  const prefix = gwIp.split('.').slice(0, 3).join('.')
-  const subnet = `${prefix}.0/24`
-
-  // Hosts con SSH a la vista (barrido TCP :22) — se excluye la propia IP
-  const selfIps = new Set(
-    (await exec('sh', ['-c', 'ip -o -4 addr show | grep -oP "inet \\K[0-9.]+"'], 3000)).stdout
-      .split('\n')
-      .filter(Boolean),
-  )
-  const hosts = Array.from({ length: 254 }, (_, i) => `${prefix}.${i + 1}`).filter((h) => !selfIps.has(h))
-  const alive = (
-    await pool(hosts, 100, async (h) => ((await tcpOpen(h, 22)) ? h : null))
-  ).filter(Boolean)
-
-  // De los vivos, los que huelen a OpenWrt (ubus HTTP)
-  const configured = new Set(listRouters(db).map((r) => r.host))
-  const candidates = (
-    await pool(alive, 16, async (h) => {
-      if (!(await probeUbus(h))) return null
-      const { authorized, model } = await probeSsh(h, sshKeyPath)
-      return {
-        host: h,
-        isGateway: h === gwIp,
-        authorized,
-        model,
-        configured: configured.has(h),
-      }
-    })
-  ).filter(Boolean)
-
-  candidates.sort((a, b) => Number(b.isGateway) - Number(a.isGateway) || a.host.localeCompare(b.host))
-  cache = { at: Date.now(), subnet, results: candidates }
-  return { ...cache, cached: false }
-}

+ 0 - 28
legacy/server-node/src/health.js

@@ -1,28 +0,0 @@
-/**
- * Health endpoints:
- *   GET /api/health (público, contrato): { ok, version, mode, uptimeSec, db }
- *   GET /health (skill): { status, uptime, memory, db }
- */
-export function registerHealthRoutes(app, { dbHandle, mode, version }) {
-  app.get('/api/health', (c) => {
-    const dbOk = dbHandle.checkHealth()
-    return c.json({
-      ok: dbOk,
-      version,
-      mode,
-      uptimeSec: Math.floor(process.uptime()),
-      db: dbOk ? 'ok' : 'error',
-    })
-  })
-
-  app.get('/health', (c) => {
-    const dbOk = dbHandle.checkHealth()
-    const mem = process.memoryUsage()
-    return c.json({
-      status: dbOk ? 'ok' : 'degraded',
-      uptime: process.uptime(),
-      memory: { rss: mem.rss, heap: mem.heapUsed },
-      db: dbOk ? 'connected' : 'error',
-    })
-  })
-}

+ 0 - 89
legacy/server-node/src/index.js

@@ -1,89 +0,0 @@
-/**
- * Entry: valida .env (fail-fast), abre SQLite, crea adapter (demo/live),
- * hub SSE, poller (5 s), app Hono y arranca el servidor.
- * Graceful shutdown en SIGTERM/SIGINT.
- */
-import { serve } from '@hono/node-server'
-import path from 'node:path'
-import { loadDotEnv, loadConfig } from './config.js'
-import { openDb } from './db.js'
-import { ensureSessionSecret, ensureUsers } from './auth.js'
-import { ensureSshKeypair } from './sshkey.js'
-import { ensureInitialRouters } from './routerstore.js'
-import { createAdapter } from './adapters/index.js'
-import { createSseHub } from './sse.js'
-import { createPoller } from './poller.js'
-import { createUpdater } from './updater.js'
-import { createApp, VERSION } from './app.js'
-
-async function main() {
-  loadDotEnv()
-  let config
-  try {
-    config = loadConfig()
-  } catch (err) {
-    console.error(err.message)
-    process.exit(1)
-  }
-
-  const dbHandle = openDb(config.dataDir)
-  const secret = ensureSessionSecret(dbHandle.db, config)
-  // Multiusuario: seed del admin desde .env si la tabla users está vacía
-  await ensureUsers(dbHandle.db, config)
-  // Clave SSH propia para sondear routers (se genera la primera vez)
-  await ensureSshKeypair(config.sshKeyPath)
-  // Bootstrap de routers: tabla vacía → ROUTERS_JSON o autodetección del gateway
-  const routers = await ensureInitialRouters(dbHandle.db, config)
-  const adapter = createAdapter(config, dbHandle, routers)
-
-  // Dependencia circular sse↔poller resuelta con un holder
-  const holder = { poller: null }
-  const sse = createSseHub({
-    db: dbHandle.db,
-    maxClients: config.maxSseClients,
-    getOverview: () => holder.poller?.lastOverview ?? null,
-  })
-  const poller = createPoller({ adapter, dbHandle, sse })
-  holder.poller = poller
-
-  // Actualizador: repoRoot = /opt/netpulse (padre de server/)
-  const updater = createUpdater({
-    repoRoot: path.resolve(config.serverRoot, '..'),
-    repo: config.githubRepo,
-    token: config.githubToken,
-  })
-
-  const app = createApp({ config, dbHandle, adapter, sse, poller, secret, updater })
-
-  const server = serve({ fetch: app.fetch, port: config.port }, (info) => {
-    console.log(`[netpulse] v${VERSION} · modo ${adapter.mode} · http://localhost:${info.port}`)
-    console.log(`[netpulse] datos: ${config.dataDir} · estáticos: ${config.staticDir}`)
-    poller.start()
-    updater.start()
-  })
-
-  function shutdown(signal) {
-    console.log(`[netpulse] ${signal} recibido, cerrando...`)
-    poller.stop()
-    updater.stop()
-    sse.notifyShutdown()
-    adapter.close?.()
-    server.close(() => {
-      dbHandle.close()
-      process.exit(0)
-    })
-    // Salvavidas: si el server no cierra en 3 s, salir igualmente
-    setTimeout(() => {
-      dbHandle.close()
-      process.exit(0)
-    }, 3000).unref()
-  }
-
-  process.on('SIGTERM', () => shutdown('SIGTERM'))
-  process.on('SIGINT', () => shutdown('SIGINT'))
-}
-
-main().catch((err) => {
-  console.error('[netpulse] error fatal en arranque:', err)
-  process.exit(1)
-})

+ 0 - 78
legacy/server-node/src/poller.js

@@ -1,78 +0,0 @@
-/**
- * Poller: snapshot cada 5 s del adapter activo.
- *   - Primer snapshot inmediato al arrancar.
- *   - Broadcast SSE `snapshot` (overview) a los clientes conectados.
- *   - Alertas nuevas → evento SSE `alert`.
- *   - Persistencia: metrics(router_id, ts, ...) + adguard_stats(ts, ...).
- *   - Nunca se cae por un fallo del adapter (try/catch + log).
- */
-const TICK_MS = 5000
-
-export function createPoller({ adapter, dbHandle, sse }) {
-  let timer = null
-  let lastOverview = null
-  let lastAdguard = null
-  const knownAlertIds = new Set()
-  let alertsPrimed = false
-
-  async function tick() {
-    try {
-      await adapter.tick?.()
-      const overview = await adapter.getOverview()
-      lastOverview = overview
-      lastAdguard = overview.adguard ?? null
-
-      // Persistencia (solo live: en demo la BD se mantiene 100% vacía)
-      if (adapter.mode !== 'demo') {
-        const ts = Date.now()
-        for (const row of adapter.getMetricsRows()) {
-          dbHandle.stmts.insertMetric.run(
-            row.router_id,
-            ts,
-            row.cpu,
-            row.ram,
-            row.temp,
-            row.latency_ms,
-            row.rx_bps,
-            row.tx_bps,
-          )
-        }
-        if (lastAdguard) {
-          dbHandle.stmts.insertAdguard.run(ts, lastAdguard.queries24h, lastAdguard.blocked24h)
-        }
-      }
-
-      // SSE: snapshot + alertas nuevas
-      sse.broadcast('snapshot', overview)
-      if (alertsPrimed) {
-        for (const alert of overview.alerts ?? []) {
-          if (!knownAlertIds.has(alert.id)) {
-            knownAlertIds.add(alert.id)
-            sse.broadcast('alert', alert)
-          }
-        }
-      } else {
-        // Primer tick: no re-notificar alertas preexistentes
-        for (const alert of overview.alerts ?? []) knownAlertIds.add(alert.id)
-        alertsPrimed = true
-      }
-    } catch (err) {
-      console.error('[netpulse] error en tick del poller:', err)
-    }
-  }
-
-  return {
-    start() {
-      tick() // primer snapshot inmediato
-      timer = setInterval(tick, TICK_MS)
-      timer.unref()
-    },
-    stop() {
-      if (timer) clearInterval(timer)
-      timer = null
-    },
-    get lastOverview() {
-      return lastOverview
-    },
-  }
-}

+ 0 - 158
legacy/server-node/src/routerstore.js

@@ -1,158 +0,0 @@
-/**
- * Almacén de routers configurados (tabla `routers` de SQLite) + bootstrap:
- *
- *  1. Si la tabla tiene filas → es la fuente de verdad.
- *  2. Si está vacía y hay ROUTERS_JSON en el entorno → se siembra desde ahí.
- *  3. Si sigue vacía y NO estamos en demo forzado → autodetección de la
- *     puerta de enlace: `ip route show default` en el propio servidor y
- *     sondeo SSH (`ubus call system board`) para averiguar modelo y tipo
- *     (GL.iNet vs OpenWrt genérico). El resto de routers se añaden a mano
- *     desde Ajustes (CRUD /api/config/routers).
- *
- * La tabla NACE VACÍA al importar el código: no hay datos de semilla.
- */
-import { execFile } from 'node:child_process'
-import { sshBaseArgs } from './sshkey.js'
-
-const PROBE_TIMEOUT_MS = 4000
-
-export function listRouters(db) {
-  return db
-    .prepare('SELECT id, name, host, type, is_gateway, created_at FROM routers ORDER BY is_gateway DESC, created_at ASC')
-    .all()
-    .map((r) => ({ ...r, is_gateway: r.is_gateway === 1 }))
-}
-
-function slugify(text) {
-  return String(text)
-    .toLowerCase()
-    .normalize('NFD')
-    .replace(/[̀-ͯ]/g, '')
-    .replace(/[^a-z0-9]+/g, '-')
-    .replace(/^-+|-+$/g, '')
-    .slice(0, 32)
-}
-
-/** Genera un id único a partir del nombre o del host. */
-function uniqueId(db, name, host) {
-  const base = slugify(name || '') || `router-${String(host).split('.').pop()}`
-  let id = base || 'router'
-  let n = 2
-  while (db.prepare('SELECT 1 FROM routers WHERE id = ?').get(id)) {
-    id = `${base}-${n++}`
-  }
-  return id
-}
-
-/**
- * Inserta un router y devuelve la fila creada.
- * Si `isGateway`, el resto pierde el flag (solo un gateway).
- */
-export function addRouter(db, { name, host, type = 'openwrt', isGateway = false }) {
-  const id = uniqueId(db, name, host)
-  const now = Date.now()
-  const tx = db.transaction(() => {
-    if (isGateway) db.prepare('UPDATE routers SET is_gateway = 0').run()
-    db.prepare('INSERT INTO routers (id, name, host, type, is_gateway, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(
-      id,
-      name || host,
-      host,
-      type,
-      isGateway ? 1 : 0,
-      now,
-    )
-  })
-  tx()
-  return listRouters(db).find((r) => r.id === id)
-}
-
-export function removeRouter(db, id) {
-  return db.prepare('DELETE FROM routers WHERE id = ?').run(id).changes > 0
-}
-
-// ---------------------------------------------------------------------------
-// Autodetección de la puerta de enlace
-// ---------------------------------------------------------------------------
-
-function exec(cmd, args, timeoutMs = PROBE_TIMEOUT_MS) {
-  return new Promise((resolve, reject) => {
-    execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
-      if (err) return reject(new Error(`${cmd}: ${err.message} ${stderr || ''}`.trim()))
-      resolve(stdout)
-    })
-  })
-}
-
-/** IP de la puerta de enlace por defecto del servidor (null si no se sabe). */
-export async function detectGatewayIp() {
-  try {
-    const out = await exec('ip', ['route', 'show', 'default'])
-    const m = /default via (\d+\.\d+\.\d+\.\d+)/.exec(out)
-    return m ? m[1] : null
-  } catch {
-    return null
-  }
-}
-
-/** Sondea el modelo del gateway por SSH (ubus system board). */
-async function probeGatewayModel(host, sshKeyPath) {
-  try {
-    const out = await exec(
-      'ssh',
-      [
-        ...sshBaseArgs(sshKeyPath),
-        '-o', 'ConnectTimeout=3',
-        '-o', 'ControlMaster=no',
-        `root@${host}`,
-        'ubus call system board',
-      ],
-      PROBE_TIMEOUT_MS + 1000,
-    )
-    const board = JSON.parse(out)
-    const model = board?.model || ''
-    const isGlinet = /GL[.-]?iNet|GL-[A-Z]/i.test(model) || /glinet/i.test(board?.release?.distribution || '')
-    return { model, type: isGlinet ? 'glinet' : 'openwrt' }
-  } catch {
-    return { model: '', type: 'openwrt' }
-  }
-}
-
-/**
- * Bootstrap de la tabla routers. Devuelve la lista final configurada.
- * @param {object} db - handle better-sqlite3
- * @param {object} config - config cargada (routers de ROUTERS_JSON, sshKeyPath, demoMode)
- * @param {(msg: string) => void} log
- */
-export async function ensureInitialRouters(db, config, log = console.log) {
-  const existing = listRouters(db)
-  if (existing.length > 0) return existing
-
-  // 1. Semilla desde ROUTERS_JSON (primer arranque)
-  if (config.routers.length > 0) {
-    for (const [i, r] of config.routers.entries()) {
-      addRouter(db, { name: r.name, host: r.host, type: r.type, isGateway: r.type === 'glinet' || i === 0 })
-    }
-    log(`[netpulse] routers sembrados desde ROUTERS_JSON (${config.routers.length})`)
-    return listRouters(db)
-  }
-
-  // 2. Autodetección de la puerta de enlace (nunca en demo forzado)
-  if (config.demoMode) return []
-
-  const gwIp = await detectGatewayIp()
-  if (!gwIp) {
-    log('[netpulse] sin puerta de enlace detectada; añade routers desde Ajustes')
-    return []
-  }
-  const probe = await probeGatewayModel(gwIp, config.sshKeyPath)
-  const created = addRouter(db, {
-    name: probe.model || 'Gateway',
-    host: gwIp,
-    type: probe.type,
-    isGateway: true,
-  })
-  log(
-    `[netpulse] gateway autodetectado: ${created.host} (${probe.model || 'modelo desconocido'}, tipo ${created.type}). El resto se añade desde Ajustes.`,
-  )
-  return listRouters(db)
-}

+ 0 - 85
legacy/server-node/src/routes/auth.js

@@ -1,85 +0,0 @@
-/**
- * Rutas de autenticación (contrato):
- *   POST /api/auth/login   {username, password} → 204 + Set-Cookie · 401 · 429
- *   POST /api/auth/logout  → 204 (borra cookie)
- *   GET  /api/auth/me      → 200 {user, role, mode} · 401 (requireAuth)
- */
-import { z } from 'zod'
-import bcrypt from 'bcryptjs'
-import {
-  SESSION_COOKIE,
-  SESSION_TTL_MS,
-  buildSessionCookie,
-  handleLogin,
-  handleLogout,
-  loginOk,
-  loginRateLimited,
-  registerLoginFail,
-  sessionIdFromRequest,
-  signSessionId,
-} from '../auth.js'
-
-const loginSchema = z.object({
-  username: z.string().min(1).max(64),
-  password: z.string().min(1),
-})
-
-const ownPasswordSchema = z.object({
-  current: z.string().min(1),
-  password: z.string().min(6).max(128),
-})
-
-export function registerAuthRoutes(app, { db, config, secret, mode }) {
-  app.post('/api/auth/login', async (c) => {
-    const { limited, retryAfterSec } = loginRateLimited(db, c)
-    if (limited) {
-      return c.json({ error: 'rate_limited', retryAfterSec }, 429)
-    }
-    const body = await c.req.json().catch(() => null)
-    const parsed = loginSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_body', message: 'Se esperaba { "username": string, "password": string }' }, 400)
-    }
-    const result = await handleLogin(db, config, secret, c, parsed.data)
-    if (!result) {
-      registerLoginFail(db, c)
-      return c.json({ error: 'invalid_credentials' }, 401)
-    }
-    loginOk(db, c)
-    const signed = signSessionId(secret, result.id)
-    c.header('Set-Cookie', buildSessionCookie(config, c, signed, Math.floor(SESSION_TTL_MS / 1000)))
-    return c.body(null, 204)
-  })
-
-  app.post('/api/auth/logout', (c) => {
-    handleLogout(db, secret, c)
-    // Borra la cookie (mismos atributos para que el navegador la reemplace)
-    c.header('Set-Cookie', `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`)
-    return c.body(null, 204)
-  })
-
-  // Cambio de la propia contraseña (verifica la actual, cierra las demás sesiones)
-  app.put('/api/auth/password', async (c) => {
-    const user = c.get('user')
-    const body = await c.req.json().catch(() => null)
-    const parsed = ownPasswordSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_input', message: 'password mínimo 6 caracteres' }, 400)
-    }
-    const row = db.prepare('SELECT id, pass_hash FROM users WHERE id = ?').get(user.id)
-    if (!row) return c.json({ error: 'not_found' }, 404)
-    const ok = await bcrypt.compare(parsed.data.current, row.pass_hash)
-    if (!ok) return c.json({ error: 'invalid_current', message: 'La contraseña actual no es correcta' }, 403)
-    const hash = await bcrypt.hash(parsed.data.password, 10)
-    db.prepare('UPDATE users SET pass_hash = ? WHERE id = ?').run(hash, user.id)
-    const sid = sessionIdFromRequest(db, secret, c)
-    db.prepare('DELETE FROM sessions WHERE user_id = ? AND id != ?').run(user.id, sid ?? '')
-    return c.body(null, 204)
-  })
-
-  app.get('/api/auth/me', (c) => {
-    const user = c.get('user')
-    const row = db.prepare('SELECT language FROM users WHERE id = ?').get(user.id)
-    return c.json({ user: user.username, role: user.role, language: row?.language ?? 'auto', mode })
-  })
-}

+ 0 - 117
legacy/server-node/src/routes/config.js

@@ -1,117 +0,0 @@
-/**
- * Rutas de configuración en caliente: CRUD de routers (tabla `routers`),
- * clave SSH propia del servidor y descubrimiento de routers en la LAN.
- * Tras cada mutación se sincroniza el adapter live (setRouters) sin reiniciar.
- */
-import { z } from 'zod'
-import { listRouters, addRouter, removeRouter } from '../routerstore.js'
-import { getPublicKey } from '../sshkey.js'
-import { discoverRouters } from '../discover.js'
-import { requireAdmin } from '../auth.js'
-
-const hostSchema = z
-  .string()
-  .trim()
-  .min(1)
-  .max(253)
-  .regex(/^[a-zA-Z0-9._-]+$/, 'host debe ser una IP o hostname válido')
-
-const routerInputSchema = z.object({
-  name: z.string().trim().min(1).max(60).optional(),
-  host: hostSchema,
-  type: z.enum(['glinet', 'openwrt']).default('openwrt'),
-  gateway: z.boolean().default(false),
-})
-
-export function registerConfigRoutes(app, { dbHandle, adapter, config }) {
-  const sync = () => adapter.setRouters?.(listRouters(dbHandle.db))
-
-  // GET /api/config/sshkey — clave pública propia para autorizar en routers
-  app.get('/api/config/sshkey', async (c) => {
-    const key = await getPublicKey(config.sshKeyPath)
-    if (!key) return c.json({ error: 'no_key' }, 500)
-    return c.json(key)
-  })
-
-  // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s)
-  app.get('/api/config/discover', async (c) => {
-    try {
-      const result = await discoverRouters(dbHandle.db, config.sshKeyPath, c.req.query('force') === '1')
-      return c.json(result)
-    } catch (err) {
-      return c.json({ error: 'discover_failed', message: err.message }, 500)
-    }
-  })
-
-
-  // GET /api/config/routers — lista configurada (no el estado sondeado)
-  app.get('/api/config/routers', (c) => {
-    return c.json({ routers: listRouters(dbHandle.db) })
-  })
-
-  // POST /api/config/routers — añadir router manualmente desde Ajustes
-  app.post('/api/config/routers', async (c) => {
-    let body
-    try {
-      body = await c.req.json()
-    } catch {
-      return c.json({ error: 'invalid_json' }, 400)
-    }
-    const parsed = routerInputSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_input', message: parsed.error.issues[0]?.message }, 400)
-    }
-    const { name, host, type, gateway } = parsed.data
-    if (listRouters(dbHandle.db).some((r) => r.host === host)) {
-      return c.json({ error: 'duplicate_host', message: `Ya hay un router con ${host}` }, 409)
-    }
-    const created = addRouter(dbHandle.db, { name, host, type, isGateway: gateway })
-    sync()
-    return c.json({ router: created }, 201)
-  })
-
-  // DELETE /api/config/routers/:id
-  app.delete('/api/config/routers/:id', (c) => {
-    const ok = removeRouter(dbHandle.db, c.req.param('id'))
-    if (!ok) return c.json({ error: 'not_found' }, 404)
-    sync()
-    return c.body(null, 204)
-  })
-
-  // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
-
-  app.get('/api/config/adguard', requireAdmin(), (c) => {
-    const get = (k) => dbHandle.db.prepare(`SELECT value FROM kv WHERE key = ?`).get(k)?.value ?? ''
-    return c.json({
-      host: get('adguard_host'),
-      user: get('adguard_user') || 'root',
-      passSet: Boolean(get('adguard_pass')),
-    })
-  })
-
-  const adguardSchema = z.object({
-    host: hostSchema,
-    user: z.string().trim().min(1).max(64).default('root'),
-    password: z.string().max(128).optional(),
-  })
-
-  app.put('/api/config/adguard', requireAdmin(), async (c) => {
-    let body
-    try {
-      body = await c.req.json()
-    } catch {
-      return c.json({ error: 'invalid_json' }, 400)
-    }
-    const parsed = adguardSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_input', message: parsed.error.issues[0]?.message }, 400)
-    }
-    const upsert = dbHandle.db.prepare(
-      'INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value',
-    )
-    upsert.run('adguard_host', parsed.data.host)
-    upsert.run('adguard_user', parsed.data.user)
-    if (parsed.data.password) upsert.run('adguard_pass', parsed.data.password)
-    return c.body(null, 204)
-  })
-}

+ 0 - 125
legacy/server-node/src/routes/data.js

@@ -1,125 +0,0 @@
-/**
- * Rutas de datos (contrato API v1). Todas bajo requireAuth, Cache-Control:
- * no-store, errores { error, message? }. Paginación obligatoria (skill).
- */
-import { z } from 'zod'
-
-const BANDS = ['5 GHz', '2.4 GHz', 'cable']
-const SEVERITIES = ['warn', 'critical', 'info', 'ok']
-
-const pageSchema = z.object({
-  page: z.coerce.number().int().min(1).default(1),
-  pageSize: z.coerce.number().int().min(1).max(1000).default(50),
-})
-
-function paginate(items, page, pageSize) {
-  const total = items.length
-  const start = (page - 1) * pageSize
-  return { items: items.slice(start, start + pageSize), total, page, pageSize }
-}
-
-/** Middleware: Cache-Control: no-store en todas las respuestas de datos. */
-function noStore() {
-  return async (c, next) => {
-    c.header('Cache-Control', 'no-store')
-    await next()
-  }
-}
-
-export function registerDataRoutes(app, { adapter, getOverview }) {
-  app.use('/api/*', noStore())
-
-  // GET /api/overview — bundle Home + Layout + stream SSE
-  app.get('/api/overview', async (c) => {
-    const overview = getOverview() ?? (await adapter.getOverview())
-    return c.json(overview)
-  })
-
-  // GET /api/routers
-  app.get('/api/routers', (c) => {
-    return c.json({ routers: adapter.getRouters() })
-  })
-
-  // GET /api/routers/:id
-  app.get('/api/routers/:id', async (c) => {
-    const detail = await adapter.getRouterDetail(c.req.param('id'))
-    if (!detail) return c.json({ error: 'not_found' }, 404)
-    return c.json(detail)
-  })
-
-  // GET /api/devices?q=&routerId=&band=&type=&status=&page=1&pageSize=50
-  app.get('/api/devices', (c) => {
-    const parsed = pageSchema.safeParse({
-      page: c.req.query('page'),
-      pageSize: c.req.query('pageSize'),
-    })
-    if (!parsed.success) return c.json({ error: 'invalid_query', message: 'page/pageSize inválidos' }, 400)
-    const { page, pageSize } = parsed.data
-    const q = (c.req.query('q') || '').trim().toLowerCase().slice(0, 100)
-    const routerId = c.req.query('routerId') || ''
-    const band = c.req.query('band') || ''
-    const type = c.req.query('type') || ''
-    const status = c.req.query('status') || ''
-
-    if (band && !BANDS.includes(band)) {
-      return c.json({ error: 'invalid_query', message: `band debe ser una de: ${BANDS.join(', ')}` }, 400)
-    }
-    if (status && !['online', 'offline'].includes(status)) {
-      return c.json({ error: 'invalid_query', message: 'status debe ser online|offline' }, 400)
-    }
-
-    let items = adapter.getDevices()
-    if (routerId) items = items.filter((d) => d.routerId === routerId)
-    if (band) items = items.filter((d) => d.band === band)
-    if (type) items = items.filter((d) => d.type === type || d.group === type)
-    if (status) items = items.filter((d) => (status === 'online' ? d.online : !d.online))
-    if (q) {
-      items = items.filter((d) =>
-        [d.name, d.hostname, d.ip, d.mac, d.manufacturer]
-          .filter(Boolean)
-          .some((v) => String(v).toLowerCase().includes(q)),
-      )
-    }
-    return c.json(paginate(items, page, pageSize))
-  })
-
-  // GET /api/alerts?severity=&page=1&pageSize=20
-  app.get('/api/alerts', (c) => {
-    const parsed = pageSchema.safeParse({
-      page: c.req.query('page'),
-      pageSize: c.req.query('pageSize') ?? 20,
-    })
-    if (!parsed.success) return c.json({ error: 'invalid_query', message: 'page/pageSize inválidos' }, 400)
-    const { page, pageSize } = parsed.data
-    const severity = c.req.query('severity') || ''
-    if (severity && !SEVERITIES.includes(severity)) {
-      return c.json({ error: 'invalid_query', message: `severity debe ser una de: ${SEVERITIES.join(', ')}` }, 400)
-    }
-    let items = adapter.getAlerts()
-    if (severity) items = items.filter((a) => a.severity === severity)
-    return c.json(paginate(items, page, pageSize))
-  })
-
-  // GET /api/topology
-  app.get('/api/topology', (c) => {
-    return c.json({ routers: adapter.getRouters(), devices: adapter.getDevices() })
-  })
-
-  // GET /api/dawn — malla DAWN (roaming): APs, canales, utilización, clientes
-  app.get('/api/dawn', async (c) => {
-    const dawn = await adapter.getDawn()
-    if (!dawn) return c.json({ error: 'unavailable' }, 503)
-    return c.json(dawn)
-  })
-
-  // GET /api/adguard/clients — clientes que usa AdGuard (si está configurado)
-  app.get('/api/adguard/clients', async (c) => {
-    try {
-      const clients = await adapter.getAdguardClients()
-      if (!clients) return c.json({ error: 'not_configured' }, 404)
-      return c.json({ clients })
-    } catch (err) {
-      return c.json({ error: 'adguard_error', message: err.message }, 502)
-    }
-  })
-}

+ 0 - 25
legacy/server-node/src/routes/update.js

@@ -1,25 +0,0 @@
-/**
- * Rutas del actualizador (solo admin):
- *   GET  /api/update/status → estado actual (versión, última, disponible, progreso)
- *   POST /api/update/check  → fuerza un chequeo contra GitHub
- *   POST /api/update/apply  → aplica la actualización (git pull + build + restart)
- */
-import { requireAdmin } from '../auth.js'
-
-export function registerUpdateRoutes(app, { updater }) {
-  app.use('/api/update', requireAdmin())
-  app.use('/api/update/*', requireAdmin())
-
-  app.get('/api/update/status', (c) => c.json(updater.status))
-
-  app.post('/api/update/check', async (c) => {
-    await updater.check()
-    return c.json(updater.status)
-  })
-
-  app.post('/api/update/apply', (c) => {
-    const started = updater.apply()
-    if (!started) return c.json({ error: 'already_updating' }, 409)
-    return c.json(updater.status, 202)
-  })
-}

+ 0 - 130
legacy/server-node/src/routes/users.js

@@ -1,130 +0,0 @@
-/**
- * Rutas de gestión de usuarios (solo admin):
- *   GET    /api/users                 → lista [{id, username, role, created_at}]
- *   POST   /api/users                 {username, password, role?} → 201
- *   PUT    /api/users/:id/password    {password} → 204 (invalida sus sesiones)
- *   DELETE /api/users/:id             → 204 (no self, no último admin)
- */
-import { z } from 'zod'
-import bcrypt from 'bcryptjs'
-import { requireAdmin, destroyUserSessions } from '../auth.js'
-
-const usernameSchema = z
-  .string()
-  .trim()
-  .min(2)
-  .max(32)
-  .regex(/^[a-zA-Z0-9_.-]+$/, 'usuario debe ser alfanumérico (.-_ permitidos)')
-
-const createSchema = z.object({
-  username: usernameSchema,
-  password: z.string().min(6).max(128),
-  role: z.enum(['admin', 'user']).default('user'),
-  language: z.enum(['auto', 'es', 'en']).default('auto'),
-})
-
-const passwordSchema = z.object({
-  password: z.string().min(6).max(128),
-})
-
-const languageSchema = z.object({
-  language: z.enum(['auto', 'es', 'en']),
-})
-
-export function registerUserRoutes(app, { db }) {
-  // Idioma propio (cualquier usuario logueado; fuente de verdad del idioma UI)
-  app.put('/api/users/me/language', async (c) => {
-    const me = c.get('user')
-    const body = await c.req.json().catch(() => null)
-    const parsed = languageSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_input', message: 'language debe ser auto|es|en' }, 400)
-    }
-    db.prepare('UPDATE users SET language = ? WHERE id = ?').run(parsed.data.language, me.id)
-    return c.body(null, 204)
-  })
-
-  app.use('/api/users', requireAdmin())
-  app.use('/api/users/*', requireAdmin())
-
-  app.get('/api/users', (c) => {
-    const users = db
-      .prepare('SELECT id, username, role, language, created_at FROM users ORDER BY username')
-      .all()
-    return c.json({ users })
-  })
-
-  app.post('/api/users', async (c) => {
-    const body = await c.req.json().catch(() => null)
-    const parsed = createSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_input', message: parsed.error.issues[0]?.message }, 400)
-    }
-    const { username, password, role, language } = parsed.data
-    if (db.prepare('SELECT 1 FROM users WHERE username = ?').get(username)) {
-      return c.json({ error: 'duplicate_user', message: `Ya existe el usuario ${username}` }, 409)
-    }
-    const hash = await bcrypt.hash(password, 10)
-    const info = db
-      .prepare('INSERT INTO users (username, pass_hash, role, language, created_at) VALUES (?, ?, ?, ?, ?)')
-      .run(username, hash, role, language, Date.now())
-    return c.json({ user: { id: info.lastInsertRowid, username, role, language } }, 201)
-  })
-
-  app.put('/api/users/:id/password', async (c) => {
-    const id = Number(c.req.param('id'))
-    const target = db.prepare('SELECT id, username FROM users WHERE id = ?').get(id)
-    if (!target) return c.json({ error: 'not_found' }, 404)
-    const body = await c.req.json().catch(() => null)
-    const parsed = passwordSchema.safeParse(body)
-    if (!parsed.success) {
-      return c.json({ error: 'invalid_input', message: 'password mínimo 6 caracteres' }, 400)
-    }
-    const hash = await bcrypt.hash(parsed.data.password, 10)
-    db.prepare('UPDATE users SET pass_hash = ? WHERE id = ?').run(hash, id)
-    destroyUserSessions(db, id) // fuerza re-login con la nueva contraseña
-    return c.body(null, 204)
-  })
-
-  app.put('/api/users/:id/role', (c) => {
-    const id = Number(c.req.param('id'))
-    const me = c.get('user')
-    const target = db.prepare('SELECT id, username, role FROM users WHERE id = ?').get(id)
-    if (!target) return c.json({ error: 'not_found' }, 404)
-    const role = c.req.query('role') ?? ''
-    if (!['admin', 'user'].includes(role)) {
-      return c.json({ error: 'invalid_input', message: 'role debe ser admin|user' }, 400)
-    }
-    if (target.id === me.id) {
-      return c.json({ error: 'cannot_change_self', message: 'No puedes cambiar tu propio rol' }, 400)
-    }
-    if (target.role === 'admin' && role === 'user') {
-      const admins = db.prepare("SELECT COUNT(*) AS c FROM users WHERE role = 'admin'").get().c
-      if (admins <= 1) {
-        return c.json({ error: 'last_admin', message: 'Debe quedar al menos un admin' }, 400)
-      }
-    }
-    db.prepare('UPDATE users SET role = ? WHERE id = ?').run(role, id)
-    destroyUserSessions(db, id) // fuerza re-login con el nuevo rol
-    return c.body(null, 204)
-  })
-
-  app.delete('/api/users/:id', (c) => {
-    const id = Number(c.req.param('id'))
-    const me = c.get('user')
-    const target = db.prepare('SELECT id, username, role FROM users WHERE id = ?').get(id)
-    if (!target) return c.json({ error: 'not_found' }, 404)
-    if (target.id === me.id) {
-      return c.json({ error: 'cannot_delete_self', message: 'No puedes borrar tu propio usuario' }, 400)
-    }
-    if (target.role === 'admin') {
-      const admins = db.prepare("SELECT COUNT(*) AS c FROM users WHERE role = 'admin'").get().c
-      if (admins <= 1) {
-        return c.json({ error: 'last_admin', message: 'Debe quedar al menos un admin' }, 400)
-      }
-    }
-    destroyUserSessions(db, id)
-    db.prepare('DELETE FROM users WHERE id = ?').run(id)
-    return c.body(null, 204)
-  })
-}

+ 0 - 19
legacy/server-node/src/security.js

@@ -1,19 +0,0 @@
-/**
- * Headers de seguridad obligatorios (middleware global).
- * CSP: SPA con inline script de tema (ver app/index.html) → 'unsafe-inline'
- * en script-src/style-src, resto 'self'.
- */
-export function securityHeaders() {
-  return async (c, next) => {
-    c.header('X-Content-Type-Options', 'nosniff')
-    c.header('X-Frame-Options', 'DENY')
-    c.header('Referrer-Policy', 'strict-origin-when-cross-origin')
-    c.header('Permissions-Policy', 'geolocation=(), microphone=(), camera=()')
-    c.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
-    c.header(
-      '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'",
-    )
-    await next()
-  }
-}

+ 0 - 90
legacy/server-node/src/sse.js

@@ -1,90 +0,0 @@
-/**
- * SSE (Server-Sent Events) — /api/stream
- * Reglas del skill/contrato:
- *   - NUNCA Content-Encoding: gzip manual (SSE es texto chunked; nginx ya
- *     comprime transparente si procede).
- *   - X-Accel-Buffering: no + Cache-Control: no-cache.
- *   - Primer evento `snapshot` inmediato; luego uno por tick del poller (5 s).
- *   - Evento `alert` cuando se genera una alerta nueva.
- *   - Heartbeat `:hb` cada 30 s.
- *   - MAX_SSE_CLIENTS (429/503 al superarlo) → contrato: 503 too_many_clients.
- *   - En pérdida de sesión → evento `bye` y cierre.
- */
-import { streamSSE } from 'hono/streaming'
-import { getSession } from './auth.js'
-
-const HEARTBEAT_MS = 30_000
-
-export function createSseHub({ db, maxClients, getOverview }) {
-  /** @type {Set<{id: number, sessionId: string, stream: any}>} */
-  const clients = new Set()
-  let nextId = 1
-
-  function broadcast(event, data) {
-    const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
-    for (const client of clients) {
-      // Sesión revocada/expirada → evento bye y cierre
-      if (!getSession(db, client.sessionId)) {
-        try {
-          client.stream.writeSSE({ event: 'bye', data: '{}' }).then(() => client.stream.close()).catch(() => {})
-        } catch {}
-        clients.delete(client)
-        continue
-      }
-      client.stream.write(payload).catch(() => clients.delete(client))
-    }
-  }
-
-  function notifyShutdown() {
-    for (const client of clients) {
-      try {
-        client.stream.write('event: shutdown\ndata: {}\n\n').catch(() => {})
-      } catch {}
-    }
-  }
-
-  /** Handler Hono para GET /api/stream (requiere sesión → requireAuth antes). */
-  function handleStream(c) {
-    if (clients.size >= maxClients) {
-      return c.json({ error: 'too_many_clients' }, 503)
-    }
-    const sessionId = c.get('sessionId')
-    const overview = getOverview?.()
-
-    c.header('X-Accel-Buffering', 'no')
-    c.header('Cache-Control', 'no-cache')
-    // Deliberadamente SIN Content-Encoding (ver cabecera del fichero)
-
-    return streamSSE(c, async (stream) => {
-      const client = { id: nextId++, sessionId, stream }
-      clients.add(client)
-
-      // Primer snapshot inmediato al conectar
-      if (overview) {
-        await stream.writeSSE({ event: 'snapshot', data: JSON.stringify(overview) })
-      }
-
-      const heartbeat = setInterval(() => {
-        stream.write(':hb\n\n').catch(() => {})
-      }, HEARTBEAT_MS)
-
-      // Mantener la conexión abierta hasta que el cliente cierre
-      await new Promise((resolve) => {
-        stream.onAbort(() => {
-          clearInterval(heartbeat)
-          clients.delete(client)
-          resolve()
-        })
-      })
-    })
-  }
-
-  return {
-    handleStream,
-    broadcast,
-    notifyShutdown,
-    get size() {
-      return clients.size
-    },
-  }
-}

+ 0 - 57
legacy/server-node/src/sshkey.js

@@ -1,57 +0,0 @@
-/**
- * Clave SSH propia de NetPulse para sondear routers (solo lectura).
- * La app genera su par ed25519 en DATA_DIR/.ssh la primera vez y expone la
- * pública vía /api/config/sshkey para que el usuario la autorice a mano en
- * cada router (/etc/dropbear/authorized_keys).
- */
-import fs from 'node:fs'
-import path from 'node:path'
-import { execFile } from 'node:child_process'
-
-/**
- * Args SSH comunes: known_hosts JUNTO a la clave (dentro de DATA_DIR).
- * Imprescindible con systemd ProtectSystem=strict: el HOME del usuario del
- * servicio es de solo lectura y ssh no podría escribir ~/.ssh/known_hosts.
- */
-export function sshBaseArgs(keyPath) {
-  return [
-    '-i', keyPath,
-    '-o', 'BatchMode=yes',
-    '-o', 'ConnectTimeout=4',
-    '-o', 'StrictHostKeyChecking=accept-new',
-    '-o', `UserKnownHostsFile=${path.join(path.dirname(keyPath), 'known_hosts')}`,
-  ]
-}
-
-/** Garantiza que existe un par de claves en keyPath; devuelve la ruta. */
-export async function ensureSshKeypair(keyPath) {
-  if (fs.existsSync(keyPath) && fs.existsSync(`${keyPath}.pub`)) return keyPath
-  fs.mkdirSync(path.dirname(keyPath), { recursive: true, mode: 0o700 })
-  await new Promise((resolve, reject) => {
-    execFile('ssh-keygen', ['-t', 'ed25519', '-f', keyPath, '-N', '', '-C', 'netpulse', '-q'], (err) =>
-      err ? reject(err) : resolve(),
-    )
-  })
-  try {
-    fs.chmodSync(path.dirname(keyPath), 0o700)
-    fs.chmodSync(keyPath, 0o600)
-  } catch {}
-  return keyPath
-}
-
-/** Lee la clave pública y su fingerprint (null si no existe). */
-export async function getPublicKey(keyPath) {
-  try {
-    const publicKey = fs.readFileSync(`${keyPath}.pub`, 'utf8').trim()
-    const fingerprint = await new Promise((resolve) => {
-      execFile('ssh-keygen', ['-lf', `${keyPath}.pub`], (err, stdout) => {
-        if (err) return resolve('')
-        const m = /^\d+\s+(\S+)/.exec(stdout.trim())
-        resolve(m ? m[1] : '')
-      })
-    })
-    return { publicKey, fingerprint }
-  } catch {
-    return null
-  }
-}

+ 0 - 151
legacy/server-node/src/updater.js

@@ -1,151 +0,0 @@
-/**
- * Actualizador: comprueba periódicamente si hay versión nueva en GitHub
- * (rama main del repo) y aplica la actualización ejecutando deploy/update.sh
- * (git pull + deps + build frontend + reinicio diferido del servicio).
- *
- * - Repo privado: necesita GITHUB_TOKEN (fine-grained, Contents: read).
- * - El chequeo corre al arrancar y cada CHECK_INTERVAL_MS, bajo demanda
- *   con POST /api/update/check.
- * - El estado se expone en GET /api/update/status (admin).
- */
-import { execFile, spawn } from 'node:child_process'
-import fs from 'node:fs'
-
-const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000 // 6 h
-const HTTP_TIMEOUT_MS = 8000
-
-const state = {
-  current: 'desconocido',
-  latest: null,
-  latestMsg: null,
-  updateAvailable: false,
-  lastCheck: null,
-  updating: false, // { step } mientras corre update.sh
-  error: null,
-}
-
-let timer = null
-
-function git(args, cwd) {
-  return new Promise((resolve) => {
-    execFile('git', args, { cwd, timeout: 10000 }, (err, stdout) => {
-      resolve(err ? '' : stdout.trim())
-    })
-  })
-}
-
-async function currentCommit(repoRoot) {
-  const sha = await git(['rev-parse', '--short', 'HEAD'], repoRoot)
-  return sha || 'desconocido'
-}
-
-/** Consulta el último commit de main en la API de GitHub. */
-async function fetchLatest(repo, token) {
-  const ctrl = new AbortController()
-  const t = setTimeout(() => ctrl.abort(), HTTP_TIMEOUT_MS)
-  try {
-    const headers = {
-      Accept: 'application/vnd.github+json',
-      'User-Agent': 'netpulse-updater',
-      'X-GitHub-Api-Version': '2022-11-28',
-    }
-    if (token) headers.Authorization = `Bearer ${token}`
-    const res = await fetch(`https://api.github.com/repos/${repo}/commits/main`, { headers, signal: ctrl.signal })
-    if (res.status === 401 || res.status === 403 || res.status === 404) {
-      return { error: token ? `github_${res.status}` : 'no_token' }
-    }
-    if (!res.ok) return { error: `github_${res.status}` }
-    const data = await res.json()
-    return { sha: (data.sha || '').slice(0, 7), msg: (data.commit?.message || '').split('\n')[0].slice(0, 80) }
-  } catch (err) {
-    return { error: err.name === 'AbortError' ? 'timeout' : 'network' }
-  } finally {
-    clearTimeout(t)
-  }
-}
-
-export function createUpdater({ repoRoot, repo, token }) {
-  async function check() {
-    state.current = await currentCommit(repoRoot)
-    const latest = await fetchLatest(repo, token)
-    state.lastCheck = Date.now()
-    if (latest.error) {
-      state.error = latest.error
-      // no_token no es un error visible: el banner simplemente no aparece
-      return state
-    }
-    state.error = null
-    state.latest = latest.sha
-    state.latestMsg = latest.msg
-    state.updateAvailable = Boolean(latest.sha && state.current !== 'desconocido' && latest.sha !== state.current)
-    if (state.updateAvailable) {
-      console.log(`[netpulse] nueva versión disponible: ${state.current} → ${state.latest} (${latest.msg})`)
-    }
-    return state
-  }
-
-  function apply() {
-    if (state.updating) return false
-    state.updating = { step: 'start', log: '' }
-    // Copia el script a /tmp antes de ejecutarlo: el propio update hace
-    // `git reset --hard`, que reescribiría el script mientras bash lo lee
-    const tmpScript = `${process.env.TMPDIR || '/tmp'}/netpulse-update-${Date.now()}.sh`
-    try {
-      fs.copyFileSync(`${repoRoot}/deploy/update.sh`, tmpScript)
-      fs.chmodSync(tmpScript, 0o755)
-    } catch (err) {
-      state.updating = false
-      state.error = `update_copy_failed`
-      console.error('[netpulse] no se pudo copiar update.sh:', err.message)
-      return false
-    }
-    const child = spawn('bash', [tmpScript], {
-      cwd: repoRoot,
-      env: { ...process.env, NODE_OPTIONS: '--max-old-space-size=400' },
-    })
-    child.stdout.on('data', (chunk) => {
-      const text = chunk.toString()
-      state.updating.log = (state.updating.log + text).slice(-4000)
-      const m = /STEP:(\w+)/.exec(text)
-      if (m) state.updating.step = m[1]
-      console.log('[netpulse:update]', text.trim())
-    })
-    child.stderr.on('data', (chunk) => {
-      state.updating.log = (state.updating.log + chunk.toString()).slice(-4000)
-    })
-    child.on('close', (code) => {
-      if (code === 0) {
-        state.updating = { step: 'done', log: state.updating.log }
-        state.lastLog = state.updating.log
-        state.updateAvailable = false
-      } else {
-        state.lastLog = state.updating?.log ?? null
-        state.updating = false
-        state.error = `update_exit_${code}`
-      }
-    })
-    return true
-  }
-
-  return {
-    start() {
-      void check()
-      timer = setInterval(() => void check(), CHECK_INTERVAL_MS)
-      timer.unref()
-    },
-    stop() {
-      if (timer) clearInterval(timer)
-    },
-    check,
-    apply,
-    get status() {
-      return {
-        ...state,
-        updating: state.updating ? { step: state.updating.step } : false,
-        lastLog: state.updating?.log?.slice(-800) ?? state.lastLog ?? null,
-        repo,
-        hasToken: Boolean(token),
-      }
-    },
-  }
-}

+ 0 - 95
legacy/server-node/tests/auth.test.js

@@ -1,95 +0,0 @@
-/**
- * Tests de auth (contrato + skill):
- *  - login incorrecto → 401 invalid_credentials
- *  - login correcto → 204 + Set-Cookie httpOnly; /api/auth/me con cookie → 200
- *  - overview sin cookie → 401
- *  - rate-limit SQLite: 5º fallo bloquea 5 min → siguiente intento 429 rate_limited
- *  - logout → 204 y la sesión queda revocada
- */
-import { describe, it, before, after } from 'node:test'
-import assert from 'node:assert/strict'
-import { makeTestServer, loginCookie } from './helpers.js'
-
-describe('auth', () => {
-  let srv
-  before(async () => {
-    srv = await makeTestServer()
-  })
-  after(async () => {
-    await srv.close()
-  })
-
-  it('rechaza login incorrecto con 401 invalid_credentials', async () => {
-    const { status, cookie } = await loginCookie(srv.base, 'wrong-pass')
-    assert.equal(status, 401)
-    assert.equal(cookie, null)
-  })
-
-  it('acepta login correcto: 204 + Set-Cookie httpOnly, y me devuelve user/mode', async () => {
-    const { status, cookie, setCookie } = await loginCookie(srv.base)
-    assert.equal(status, 204)
-    assert.ok(cookie, 'debe devolver cookie de sesión')
-    assert.match(setCookie, /HttpOnly/)
-    assert.match(setCookie, /SameSite=Lax/)
-
-    const me = await fetch(`${srv.base}/api/auth/me`, { headers: { cookie: `session=${cookie}` } })
-    assert.equal(me.status, 200)
-    const body = await me.json()
-    assert.deepEqual(body, { user: 'admin', role: 'admin', language: 'auto', mode: 'demo' })
-  })
-
-  it('protege /api/overview sin cookie (401) y la sirve con cookie (200)', async () => {
-    const unauth = await fetch(`${srv.base}/api/overview`)
-    assert.equal(unauth.status, 401)
-
-    const { cookie } = await loginCookie(srv.base)
-    const auth = await fetch(`${srv.base}/api/overview`, { headers: { cookie: `session=${cookie}` } })
-    assert.equal(auth.status, 200)
-  })
-
-  it('logout: 204 y la sesión queda revocada', async () => {
-    const { cookie } = await loginCookie(srv.base)
-    const out = await fetch(`${srv.base}/api/auth/logout`, {
-      method: 'POST',
-      headers: { cookie: `session=${cookie}` },
-    })
-    assert.equal(out.status, 204)
-    const after_ = await fetch(`${srv.base}/api/overview`, { headers: { cookie: `session=${cookie}` } })
-    assert.equal(after_.status, 401)
-  })
-
-  it('rate-limit: bloquea tras el 5º fallo (429 rate_limited con retryAfterSec)', async () => {
-    const ip = '10.9.9.9'
-    const headers = { 'Content-Type': 'application/json', 'x-forwarded-for': ip }
-    const bad = () =>
-      fetch(`${srv.base}/api/auth/login`, {
-        method: 'POST',
-        headers,
-        body: JSON.stringify({ username: 'admin', password: 'nope' }),
-      })
-    for (let i = 1; i <= 5; i++) {
-      const res = await bad()
-      assert.equal(res.status, 401, `fallo ${i} debe ser 401`)
-    }
-    // 6º intento: ya bloqueado (5 min)
-    const blocked = await bad()
-    assert.equal(blocked.status, 429)
-    const body = await blocked.json()
-    assert.equal(body.error, 'rate_limited')
-    assert.ok(body.retryAfterSec > 0 && body.retryAfterSec <= 300)
-    // Incluso con la password correcta sigue bloqueado
-    const goodWhileLocked = await fetch(`${srv.base}/api/auth/login`, {
-      method: 'POST',
-      headers,
-      body: JSON.stringify({ username: 'admin', password: 'test1234' }),
-    })
-    assert.equal(goodWhileLocked.status, 429)
-  })
-
-  it('el rate-limit persiste en SQLite (no solo memoria)', async () => {
-    const row = srv.dbHandle.db.prepare('SELECT * FROM login_attempts WHERE ip = ?').get('10.9.9.9')
-    assert.ok(row, 'debe existir fila en login_attempts')
-    assert.ok(row.attempts >= 5)
-    assert.ok(row.locked_until > Date.now())
-  })
-})

+ 0 - 74
legacy/server-node/tests/devices.test.js

@@ -1,74 +0,0 @@
-/**
- * Tests de paginación y filtros de /api/devices (paginación obligatoria, skill).
- */
-import { describe, it, before, after } from 'node:test'
-import assert from 'node:assert/strict'
-import { makeTestServer, loginCookie } from './helpers.js'
-
-describe('GET /api/devices', () => {
-  let srv
-  let cookie
-  before(async () => {
-    srv = await makeTestServer()
-    ;({ cookie } = await loginCookie(srv.base))
-  })
-  after(async () => {
-    await srv.close()
-  })
-
-  const get = (qs) =>
-    fetch(`${srv.base}/api/devices?${qs}`, { headers: { cookie: `session=${cookie}` } }).then((r) => r.json())
-
-  it('devuelve los 47 clientes paginados (page 1 de 10)', async () => {
-    const body = await get('page=1&pageSize=10')
-    assert.equal(body.total, 47)
-    assert.equal(body.items.length, 10)
-    assert.equal(body.page, 1)
-    assert.equal(body.pageSize, 10)
-  })
-
-  it('última página con resto (page 5 de 10 → 7 items)', async () => {
-    const body = await get('page=5&pageSize=10')
-    assert.equal(body.total, 47)
-    assert.equal(body.items.length, 7)
-    // Sin solape con la página anterior
-    const prev = await get('page=4&pageSize=10')
-    const prevIds = new Set(prev.items.map((d) => d.id))
-    assert.ok(body.items.every((d) => !prevIds.has(d.id)))
-  })
-
-  it('filtros: routerId, band, status, type y búsqueda q', async () => {
-    const living = await get('routerId=living&pageSize=200')
-    assert.equal(living.total, 18)
-    assert.ok(living.items.every((d) => d.routerId === 'living'))
-
-    const cable = await get('band=cable&pageSize=200')
-    assert.ok(cable.items.every((d) => d.band === 'cable'))
-
-    const offline = await get('status=offline&pageSize=200')
-    assert.equal(offline.total, 8)
-    assert.ok(offline.items.every((d) => !d.online))
-
-    const moviles = await get('type=movil&pageSize=200')
-    assert.ok(moviles.items.every((d) => d.type === 'movil' || d.group === 'moviles'))
-
-    const q = await get('q=pixel&pageSize=200')
-    assert.ok(q.total >= 2, 'pixel-8-pro y pixel-7')
-    assert.ok(q.items.some((d) => d.id === 'pixel-8-pro'))
-  })
-
-  it('valida parámetros (band inválida → 400)', async () => {
-    const res = await fetch(`${srv.base}/api/devices?band=wifi6`, { headers: { cookie: `session=${cookie}` } })
-    assert.equal(res.status, 400)
-    const body = await res.json()
-    assert.equal(body.error, 'invalid_query')
-  })
-
-  it('los items llevan el shape Device (camelCase del contrato)', async () => {
-    const body = await get('page=1&pageSize=1')
-    const d = body.items[0]
-    for (const key of ['id', 'name', 'type', 'manufacturer', 'ip', 'mac', 'routerId', 'band', 'signalDbm', 'trafficMbps', 'online', 'sparkline']) {
-      assert.ok(key in d, `device sin ${key}`)
-    }
-  })
-})

+ 0 - 59
legacy/server-node/tests/helpers.js

@@ -1,59 +0,0 @@
-/**
- * Helpers de test: app real sobre puerto efímero con adapter demo y DB temporal.
- */
-import fs from 'node:fs'
-import os from 'node:os'
-import path from 'node:path'
-import { serve } from '@hono/node-server'
-import { loadConfig } from '../src/config.js'
-import { openDb } from '../src/db.js'
-import { ensureSessionSecret, ensureUsers } from '../src/auth.js'
-import { createDemoAdapter } from '../src/adapters/demo.js'
-import { createSseHub } from '../src/sse.js'
-import { createApp } from '../src/app.js'
-
-export async function makeTestServer(env = {}) {
-  const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'netpulse-test-'))
-  const config = loadConfig({
-    AUTH_USER: 'admin',
-    AUTH_PASS: 'test1234',
-    DEMO_MODE: '1',
-    DATA_DIR: dataDir,
-    NODE_ENV: 'test',
-    ...env,
-  })
-  const dbHandle = openDb(dataDir)
-  const secret = ensureSessionSecret(dbHandle.db, config)
-  await ensureUsers(dbHandle.db, config)
-  const adapter = createDemoAdapter()
-  const sse = createSseHub({ db: dbHandle.db, maxClients: config.maxSseClients, getOverview: () => null })
-  const app = createApp({ config, dbHandle, adapter, sse, poller: null, secret })
-
-  const server = serve({ fetch: app.fetch, port: 0 })
-  const address = server.address()
-  const base = `http://127.0.0.1:${address.port}`
-
-  return {
-    base,
-    config,
-    dbHandle,
-    adapter,
-    async close() {
-      await new Promise((resolve) => server.close(resolve))
-      dbHandle.close()
-      fs.rmSync(dataDir, { recursive: true, force: true })
-    },
-  }
-}
-
-/** Login y devuelve el valor de la cookie de sesión (id.hmac). */
-export async function loginCookie(base, password = 'test1234', username = 'admin') {
-  const res = await fetch(`${base}/api/auth/login`, {
-    method: 'POST',
-    headers: { 'Content-Type': 'application/json' },
-    body: JSON.stringify({ username, password }),
-  })
-  const setCookie = res.headers.get('set-cookie') || ''
-  const match = /session=([^;]+)/.exec(setCookie)
-  return { status: res.status, cookie: match?.[1] ?? null, setCookie }
-}

+ 0 - 115
legacy/server-node/tests/routers.test.js

@@ -1,115 +0,0 @@
-/**
- * Tests del CRUD de routers (/api/config/routers):
- *  - Auth obligatoria (401 sin cookie).
- *  - Alta, listado, duplicados (409), validación (400) y borrado (204/404).
- *  - La tabla nace VACÍA (regla de la skill: BD sin datos al importar).
- */
-import { describe, it, before, after } from 'node:test'
-import assert from 'node:assert/strict'
-import { makeTestServer, loginCookie } from './helpers.js'
-
-describe('config routers', () => {
-  let srv
-  let cookie
-
-  before(async () => {
-    srv = await makeTestServer()
-    const login = await loginCookie(srv.base)
-    assert.equal(login.status, 204)
-    cookie = login.cookie
-  })
-
-  after(async () => {
-    await srv.close()
-  })
-
-  it('requiere auth', async () => {
-    const res = await fetch(`${srv.base}/api/config/routers`)
-    assert.equal(res.status, 401)
-  })
-
-  it('la tabla nace vacía y admite alta', async () => {
-    let res = await fetch(`${srv.base}/api/config/routers`, {
-      headers: { cookie: `session=${cookie}` },
-    })
-    assert.equal(res.status, 200)
-    assert.deepEqual((await res.json()).routers, [])
-
-    res = await fetch(`${srv.base}/api/config/routers`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ name: 'Gateway', host: '192.168.1.1', type: 'glinet', gateway: true }),
-    })
-    assert.equal(res.status, 201)
-    const { router } = await res.json()
-    assert.equal(router.host, '192.168.1.1')
-    assert.equal(router.is_gateway, true)
-
-    res = await fetch(`${srv.base}/api/config/routers`, {
-      headers: { cookie: `session=${cookie}` },
-    })
-    const { routers } = await res.json()
-    assert.equal(routers.length, 1)
-    assert.equal(routers[0].id, 'gateway')
-  })
-
-  it('rechaza duplicados y entradas inválidas', async () => {
-    let res = await fetch(`${srv.base}/api/config/routers`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ host: '192.168.1.1' }),
-    })
-    assert.equal(res.status, 409)
-
-    res = await fetch(`${srv.base}/api/config/routers`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ host: '192.168.1.2; rm -rf /' }),
-    })
-    assert.equal(res.status, 400)
-
-    res = await fetch(`${srv.base}/api/config/routers`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ host: '192.168.1.2', type: 'cisco' }),
-    })
-    assert.equal(res.status, 400)
-  })
-
-  it('solo un gateway: el nuevo desbanca al anterior', async () => {
-    const res = await fetch(`${srv.base}/api/config/routers`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ name: 'Patio', host: '192.168.1.3', gateway: true }),
-    })
-    assert.equal(res.status, 201)
-    const list = await (
-      await fetch(`${srv.base}/api/config/routers`, { headers: { cookie: `session=${cookie}` } })
-    ).json()
-    const gateways = list.routers.filter((r) => r.is_gateway)
-    assert.equal(gateways.length, 1)
-    assert.equal(gateways[0].host, '192.168.1.3')
-  })
-
-  it('borra y devuelve 404 si no existe', async () => {
-    const list = await (
-      await fetch(`${srv.base}/api/config/routers`, { headers: { cookie: `session=${cookie}` } })
-    ).json()
-    for (const r of list.routers) {
-      const res = await fetch(`${srv.base}/api/config/routers/${r.id}`, {
-        method: 'DELETE',
-        headers: { cookie: `session=${cookie}` },
-      })
-      assert.equal(res.status, 204)
-    }
-    const res = await fetch(`${srv.base}/api/config/routers/no-existe`, {
-      method: 'DELETE',
-      headers: { cookie: `session=${cookie}` },
-    })
-    assert.equal(res.status, 404)
-    const after = await (
-      await fetch(`${srv.base}/api/config/routers`, { headers: { cookie: `session=${cookie}` } })
-    ).json()
-    assert.deepEqual(after.routers, [])
-  })
-})

+ 0 - 119
legacy/server-node/tests/snapshot.test.js

@@ -1,119 +0,0 @@
-/**
- * Tests del snapshot demo (contrato):
- *  - El overview contiene todas las claves del contrato con los shapes del mock.
- *  - El primer snapshot es EXACTAMENTE el canon (antes del random walk).
- *  - El random walk respeta los límites (cpu/ram/temp ±2, latencia 6–11 ms,
- *    bytes WG crecientes).
- */
-import { describe, it } from 'node:test'
-import assert from 'node:assert/strict'
-import { createDemoAdapter } from '../src/adapters/demo.js'
-import { routers as canonRouters, wan as canonWan, adguard as canonAdguard } from '../src/demo/dataset.js'
-
-describe('snapshot demo', () => {
-  it('contiene todas las claves del contrato', () => {
-    const adapter = createDemoAdapter()
-    const snap = adapter.getOverview()
-    for (const key of [
-      'health', 'wan', 'traffic', 'adguard', 'wireguard',
-      'routers', 'deviceTotals', 'topDevices', 'alerts', 'unreadAlerts', 'ts',
-    ]) {
-      assert.ok(key in snap, `falta ${key} en el snapshot`)
-    }
-    assert.equal(snap.routers.length, 4)
-    assert.equal(snap.topDevices.length, 5)
-    assert.ok(Array.isArray(snap.alerts))
-    for (const range of ['1h', '24h', '7d', '30d']) {
-      assert.ok(Array.isArray(snap.traffic[range]), `falta traffic.${range}`)
-    }
-    // Shapes clave (camelCase del mock)
-    const r0 = snap.routers[0]
-    for (const key of ['id', 'name', 'model', 'modelShort', 'roleBadge', 'ip', 'status', 'health', 'cpu', 'ram', 'temp', 'uptime', 'clients', 'sparkline']) {
-      assert.ok(key in r0, `router sin ${key}`)
-    }
-    for (const key of ['queries24h', 'blocked24h', 'blockedPct', 'topBlocked', 'filterLists', 'rules']) {
-      assert.ok(key in snap.adguard, `adguard sin ${key}`)
-    }
-    for (const key of ['interface', 'subnet', 'status', 'peers']) {
-      assert.ok(key in snap.wireguard, `wireguard sin ${key}`)
-    }
-    for (const key of ['id', 'name', 'type', 'tunnelIp', 'active', 'lastHandshake', 'rx', 'tx']) {
-      assert.ok(key in snap.wireguard.peers[0], `peer sin ${key}`)
-    }
-    assert.equal(typeof snap.deviceTotals.total, 'number')
-    assert.equal(typeof snap.unreadAlerts, 'number')
-    assert.equal(typeof snap.ts, 'number')
-  })
-
-  it('el primer snapshot es exactamente el canon', () => {
-    const adapter = createDemoAdapter()
-    const snap = adapter.getOverview()
-    const flint = snap.routers.find((r) => r.id === 'flint2')
-    assert.equal(flint.cpu, canonRouters[0].cpu)
-    assert.equal(flint.ram, canonRouters[0].ram)
-    assert.equal(flint.temp, canonRouters[0].temp)
-    assert.equal(snap.wan.downMbps, canonWan.downMbps)
-    assert.equal(snap.wan.latencyMs, canonWan.latencyMs)
-    assert.equal(snap.adguard.queries24h, canonAdguard.queries24h)
-    const pixel = snap.wireguard.peers.find((p) => p.id === 'pixel-8-pro')
-    assert.equal(pixel.rx, '1,2 GB')
-    assert.equal(pixel.tx, '214 MB')
-    const inactivo = snap.wireguard.peers.find((p) => p.id === 'casa-familia')
-    assert.equal(inactivo.rx, '12 GB')
-    assert.equal(snap.deviceTotals.total, 47)
-  })
-
-  it('random walk: cpu/ram/temp ±2 máx, latencia 6–11 ms, bytes WG crecen', () => {
-    const adapter = createDemoAdapter()
-    const before = adapter.getOverview()
-    adapter.tick()
-    const after = adapter.getOverview()
-    for (let i = 0; i < 4; i++) {
-      for (const key of ['cpu', 'ram', 'temp']) {
-        const delta = Math.abs(after.routers[i][key] - before.routers[i][key])
-        assert.ok(delta <= 2, `${key} de ${after.routers[i].id} saltó ${delta} (>2)`)
-      }
-    }
-    assert.ok(after.wan.latencyMs >= 6 && after.wan.latencyMs <= 11, `latencia ${after.wan.latencyMs} fuera de 6–11`)
-    // AdGuard crece
-    assert.ok(after.adguard.queries24h >= before.adguard.queries24h)
-    // WG: parseo de formato ES y comparación numérica
-    const parse = (s) => {
-      const m = /^([\d,]+) (GB|MB|KB)$/.exec(s)
-      const mult = { GB: 1e9, MB: 1e6, KB: 1e3 }[m[2]]
-      return parseFloat(m[1].replace(',', '.')) * mult
-    }
-    for (const id of ['pixel-8-pro', 'macbook-air']) {
-      const b = before.wireguard.peers.find((p) => p.id === id)
-      const a = after.wireguard.peers.find((p) => p.id === id)
-      assert.ok(parse(a.rx) >= parse(b.rx), `rx de ${id} debe crecer`)
-      assert.ok(parse(a.tx) >= parse(b.tx), `tx de ${id} debe crecer`)
-    }
-    // Peers inactivos: no cambian
-    const bIn = before.wireguard.peers.find((p) => p.id === 'ipad-air')
-    const aIn = after.wireguard.peers.find((p) => p.id === 'ipad-air')
-    assert.equal(aIn.rx, bIn.rx)
-  })
-
-  it('detalle de router: extras, series y 404 en id desconocido', async () => {
-    const adapter = createDemoAdapter()
-    const detail = await adapter.getRouterDetail('flint2')
-    assert.ok(detail.ports.length >= 5, 'flint2 tiene 5 bocas RJ45')
-    assert.equal(detail.radios, null, 'flint2 no define radios en el canon')
-    assert.equal(detail.backhaul, null)
-    for (const range of ['1h', '24h', '7d']) {
-      assert.ok(Array.isArray(detail.series[range]), `falta series.${range}`)
-      const last = detail.series[range].at(-1)
-      // La serie termina SIEMPRE en el valor actual del router
-      assert.equal(last.cpu, detail.router.cpu)
-      assert.equal(last.temp, detail.router.temp)
-    }
-    assert.ok(detail.adguard, 'gateway incluye adguard')
-    assert.ok(detail.wireguard, 'gateway incluye wireguard')
-    assert.ok(Array.isArray(detail.clients))
-    const living = await adapter.getRouterDetail('living')
-    assert.ok(Array.isArray(living.radios) && living.radios.length === 2)
-    assert.equal(living.adguard, undefined, 'AP no incluye adguard')
-    assert.equal(await adapter.getRouterDetail('no-existe'), null)
-  })
-})

+ 0 - 114
legacy/server-node/tests/users.test.js

@@ -1,114 +0,0 @@
-/**
- * Tests del CRUD de usuarios (/api/users, solo admin):
- *  - 403 para no-admin y 401 sin sesión.
- *  - Alta (201), duplicado (409), validación (400).
- *  - Cambio de password (204, invalida sesiones), borrado (204),
- *    protección self/último admin (400).
- */
-import { describe, it, before, after } from 'node:test'
-import assert from 'node:assert/strict'
-import { makeTestServer, loginCookie } from './helpers.js'
-
-describe('users CRUD', () => {
-  let srv
-  let cookie
-
-  before(async () => {
-    srv = await makeTestServer()
-    const login = await loginCookie(srv.base)
-    assert.equal(login.status, 204)
-    cookie = login.cookie
-  })
-
-  after(async () => {
-    await srv.close()
-  })
-
-  it('requiere auth y rol admin', async () => {
-    let res = await fetch(`${srv.base}/api/users`)
-    assert.equal(res.status, 401)
-    // admin sí
-    res = await fetch(`${srv.base}/api/users`, { headers: { cookie: `session=${cookie}` } })
-    assert.equal(res.status, 200)
-    const { users } = await res.json()
-    assert.equal(users.length, 1)
-    assert.equal(users[0].username, 'admin')
-    assert.equal(users[0].role, 'admin')
-  })
-
-  it('alta, duplicado y validación', async () => {
-    let res = await fetch(`${srv.base}/api/users`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ username: 'ana', password: 'secreto1' }),
-    })
-    assert.equal(res.status, 201)
-
-    res = await fetch(`${srv.base}/api/users`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ username: 'ana', password: 'otra1234' }),
-    })
-    assert.equal(res.status, 409)
-
-    res = await fetch(`${srv.base}/api/users`, {
-      method: 'POST',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ username: 'mal usuario', password: 'x'.repeat(10) }),
-    })
-    assert.equal(res.status, 400)
-  })
-
-  it('el usuario creado puede hacer login; cambio de password invalida su sesión', async () => {
-    let login = await loginCookie(srv.base, 'secreto1', 'ana')
-    assert.equal(login.status, 204)
-
-    const list = await (
-      await fetch(`${srv.base}/api/users`, { headers: { cookie: `session=${cookie}` } })
-    ).json()
-    const ana = list.users.find((u) => u.username === 'ana')
-
-    const res = await fetch(`${srv.base}/api/users/${ana.id}/password`, {
-      method: 'PUT',
-      headers: { 'Content-Type': 'application/json', cookie: `session=${cookie}` },
-      body: JSON.stringify({ password: 'nueva-clave-9' }),
-    })
-    assert.equal(res.status, 204)
-
-    // La sesión vieja de ana quedó invalidada
-    const me = await fetch(`${srv.base}/api/auth/me`, { headers: { cookie: `session=${login.cookie}` } })
-    assert.equal(me.status, 401)
-    // Y entra con la nueva
-    login = await loginCookie(srv.base, 'nueva-clave-9', 'ana')
-    assert.equal(login.status, 204)
-    // Un no-admin no puede listar usuarios
-    const forbidden = await fetch(`${srv.base}/api/users`, { headers: { cookie: `session=${login.cookie}` } })
-    assert.equal(forbidden.status, 403)
-  })
-
-  it('no borra self ni el último admin; borra usuarios normales', async () => {
-    const list = await (
-      await fetch(`${srv.base}/api/users`, { headers: { cookie: `session=${cookie}` } })
-    ).json()
-    const admin = list.users.find((u) => u.username === 'admin')
-    const ana = list.users.find((u) => u.username === 'ana')
-
-    let res = await fetch(`${srv.base}/api/users/${admin.id}`, {
-      method: 'DELETE',
-      headers: { cookie: `session=${cookie}` },
-    })
-    assert.equal(res.status, 400) // self
-
-    res = await fetch(`${srv.base}/api/users/${ana.id}`, {
-      method: 'DELETE',
-      headers: { cookie: `session=${cookie}` },
-    })
-    assert.equal(res.status, 204)
-
-    res = await fetch(`${srv.base}/api/users/${ana.id}`, {
-      method: 'DELETE',
-      headers: { cookie: `session=${cookie}` },
-    })
-    assert.equal(res.status, 404)
-  })
-})