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

Adaptación al skill webapp-stack v2 (reglas a fuego)

- R5: fuera prompt()/confirm() — formularios inline para cambiar contraseña
  y confirmación en dos pasos para borrar (usuarios y routers)
- R2: users.language en BD (migración); admin lo asigna al crear; PUT
  /api/users/me/language; /me lo devuelve y el front lo aplica tras login;
  el selector de Ajustes persiste en BD (localStorage solo caché)
- R4: contrato de eventos de sesión netpulse-authed/netpulse-unauthorized
  (login, 401, logout, AuthGate)
- R3: botón 'Entrar como demo' en Login (flag local, dataset simulado sin
  backend, salida desde Ajustes)
- Perf: single-flight en getOverview (los sondeos SSH concurrentes se
  comparten entre poller, /api/overview y SSE)
gnacho 4 месяцев назад
Родитель
Сommit
66a78bfdfb

+ 11 - 3
app/public/locales/en/translation.json

@@ -246,7 +246,8 @@
     "tooManyAttempts": "Too many attempts — wait",
     "tooManyAttempts": "Too many attempts — wait",
     "wrongPassword": "Wrong username or password",
     "wrongPassword": "Wrong username or password",
     "username": "Username",
     "username": "Username",
-    "usernamePlaceholder": "your username"
+    "usernamePlaceholder": "your username",
+    "demoEnter": "Enter as demo"
   },
   },
   "nav": {
   "nav": {
     "alerts": "Alerts",
     "alerts": "Alerts",
@@ -521,7 +522,10 @@
       "active": "Active session on this device",
       "active": "Active session on this device",
       "activeCaption": "You will have to enter the password again to sign in.",
       "activeCaption": "You will have to enter the password again to sign in.",
       "logout": "Sign out",
       "logout": "Sign out",
-      "title": "Session"
+      "title": "Session",
+      "demoActive": "Demo mode active",
+      "demoCaption": "Local simulated data, no connection to your network.",
+      "exitDemo": "Exit demo mode"
     },
     },
     "subtitle": "NetPulse local preferences — nothing here modifies your network",
     "subtitle": "NetPulse local preferences — nothing here modifies your network",
     "themeDark": "Dark",
     "themeDark": "Dark",
@@ -568,7 +572,11 @@
       "changePassword": "Change password",
       "changePassword": "Change password",
       "passwordPrompt": "New password for {name} (min. 6 chars):",
       "passwordPrompt": "New password for {name} (min. 6 chars):",
       "errorDuplicate": "That username already exists",
       "errorDuplicate": "That username already exists",
-      "errorGeneric": "Could not complete the operation."
+      "errorGeneric": "Could not complete the operation.",
+      "confirmDelete": "Confirm",
+      "cancel": "Cancel",
+      "newPassword": "New password (min. 6)",
+      "savePassword": "Save"
     },
     },
     "adguard": {
     "adguard": {
       "title": "AdGuard Home",
       "title": "AdGuard Home",

+ 11 - 3
app/public/locales/es/translation.json

@@ -246,7 +246,8 @@
     "tooManyAttempts": "Demasiados intentos — espera",
     "tooManyAttempts": "Demasiados intentos — espera",
     "wrongPassword": "Usuario o contraseña incorrectos",
     "wrongPassword": "Usuario o contraseña incorrectos",
     "username": "Usuario",
     "username": "Usuario",
-    "usernamePlaceholder": "tu usuario"
+    "usernamePlaceholder": "tu usuario",
+    "demoEnter": "Entrar como demo"
   },
   },
   "nav": {
   "nav": {
     "alerts": "Alertas",
     "alerts": "Alertas",
@@ -521,7 +522,10 @@
       "active": "Sesión activa en este dispositivo",
       "active": "Sesión activa en este dispositivo",
       "activeCaption": "Tendrás que volver a introducir la contraseña para entrar.",
       "activeCaption": "Tendrás que volver a introducir la contraseña para entrar.",
       "logout": "Cerrar sesión",
       "logout": "Cerrar sesión",
-      "title": "Sesión"
+      "title": "Sesión",
+      "demoActive": "Modo demo activo",
+      "demoCaption": "Datos simulados locales, sin conexión a tu red.",
+      "exitDemo": "Salir del modo demo"
     },
     },
     "subtitle": "Preferencias locales de NetPulse — nada aquí modifica tu red",
     "subtitle": "Preferencias locales de NetPulse — nada aquí modifica tu red",
     "themeDark": "Oscuro",
     "themeDark": "Oscuro",
@@ -568,7 +572,11 @@
       "changePassword": "Cambiar contraseña",
       "changePassword": "Cambiar contraseña",
       "passwordPrompt": "Nueva contraseña para {name} (mín. 6 caracteres):",
       "passwordPrompt": "Nueva contraseña para {name} (mín. 6 caracteres):",
       "errorDuplicate": "Ese usuario ya existe",
       "errorDuplicate": "Ese usuario ya existe",
-      "errorGeneric": "No se pudo completar la operación."
+      "errorGeneric": "No se pudo completar la operación.",
+      "confirmDelete": "Confirmar",
+      "cancel": "Cancelar",
+      "newPassword": "Nueva contraseña (mín. 6)",
+      "savePassword": "Guardar"
     },
     },
     "adguard": {
     "adguard": {
       "title": "AdGuard Home",
       "title": "AdGuard Home",

+ 12 - 2
app/src/components/AuthGate.tsx

@@ -9,6 +9,7 @@
  */
  */
 import { useEffect, useState } from 'react'
 import { useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useTranslation } from 'react-i18next'
+import i18n from '@/i18n'
 import { Navigate } from 'react-router-dom'
 import { Navigate } from 'react-router-dom'
 import { motion } from 'framer-motion'
 import { motion } from 'framer-motion'
 import { AuthProvider } from '@/data/AuthContext'
 import { AuthProvider } from '@/data/AuthContext'
@@ -17,15 +18,17 @@ import type { AuthUser } from '@/data/AuthContext'
 type GateState = 'loading' | 'authed' | 'login' | 'demo'
 type GateState = 'loading' | 'authed' | 'login' | 'demo'
 
 
 async function checkSession(): Promise<{ state: GateState; auth: AuthUser | null }> {
 async function checkSession(): Promise<{ state: GateState; auth: AuthUser | null }> {
+  // Modo demo local (botón "Entrar como demo" del login): sin backend ni sesión
+  if (sessionStorage.getItem('netpulse-demo') === '1') return { state: 'demo', auth: null }
   try {
   try {
     const res = await fetch('/api/auth/me', { signal: AbortSignal.timeout(2500) })
     const res = await fetch('/api/auth/me', { signal: AbortSignal.timeout(2500) })
     if (res.status === 401) return { state: 'login', auth: null }
     if (res.status === 401) return { state: 'login', auth: null }
     if (!res.ok) return { state: 'demo', auth: null }
     if (!res.ok) return { state: 'demo', auth: null }
     // La preview estática responde HTML con 200 (SPA fallback): no es sesión
     // La preview estática responde HTML con 200 (SPA fallback): no es sesión
     if (!(res.headers.get('content-type') ?? '').includes('application/json')) return { state: 'demo', auth: null }
     if (!(res.headers.get('content-type') ?? '').includes('application/json')) return { state: 'demo', auth: null }
-    const data = (await res.json()) as { user?: string; role?: 'admin' | 'user' }
+    const data = (await res.json()) as { user?: string; role?: 'admin' | 'user'; language?: 'auto' | 'es' | 'en' }
     if (!data?.user) return { state: 'demo', auth: null }
     if (!data?.user) return { state: 'demo', auth: null }
-    return { state: 'authed', auth: { user: data.user, role: data.role ?? 'user' } }
+    return { state: 'authed', auth: { user: data.user, role: data.role ?? 'user', language: data.language ?? 'auto' } }
   } catch {
   } catch {
     return { state: 'demo', auth: null }
     return { state: 'demo', auth: null }
   }
   }
@@ -66,10 +69,17 @@ export function AuthGate({ children }: { children: React.ReactNode }) {
       if (cancelled) return
       if (cancelled) return
       setState(s)
       setState(s)
       setAuth(a)
       setAuth(a)
+      if (s === 'authed') window.dispatchEvent(new Event('netpulse-authed'))
+      // Idioma por usuario (BD) sobre la autodetección del navegador
+      if (a?.language && a.language !== 'auto') {
+        void i18n.changeLanguage(a.language)
+        localStorage.setItem('i18nextLng', a.language)
+      }
     })
     })
     return () => {
     return () => {
       cancelled = true
       cancelled = true
     }
     }
+    // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [])
   }, [])
 
 
   if (state === 'loading') return <GateSkeleton />
   if (state === 'loading') return <GateSkeleton />

+ 30 - 3
app/src/components/topology/DawnPanel.tsx

@@ -19,9 +19,17 @@ interface DawnAp {
   iface: string
   iface: string
 }
 }
 
 
+interface DawnMesh {
+  routerId: string
+  name: string
+  dawn: boolean
+  apsSeen: number
+}
+
 export function DawnPanel() {
 export function DawnPanel() {
   const { t } = useTranslation()
   const { t } = useTranslation()
   const [aps, setAps] = useState<DawnAp[] | null>(null)
   const [aps, setAps] = useState<DawnAp[] | null>(null)
+  const [mesh, setMesh] = useState<DawnMesh[] | null>(null)
 
 
   useEffect(() => {
   useEffect(() => {
     let disposed = false
     let disposed = false
@@ -29,8 +37,11 @@ export function DawnPanel() {
       try {
       try {
         const res = await fetch('/api/dawn')
         const res = await fetch('/api/dawn')
         if (!res.ok) return
         if (!res.ok) return
-        const json = (await res.json()) as { aps: DawnAp[] }
-        if (!disposed) setAps(json.aps)
+        const json = (await res.json()) as { aps: DawnAp[]; mesh?: DawnMesh[] }
+        if (!disposed) {
+          setAps(json.aps)
+          setMesh(json.mesh ?? null)
+        }
       } catch {
       } catch {
         /* sin DAWN */
         /* sin DAWN */
       }
       }
@@ -44,11 +55,27 @@ export function DawnPanel() {
   }, [])
   }, [])
 
 
   if (!aps || aps.length === 0) return null
   if (!aps || aps.length === 0) return null
+  const active = mesh?.filter((m) => m.dawn).length ?? 0
+  const total = mesh?.length ?? 0
 
 
   return (
   return (
     <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
     <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
       <SectionHeader title={t('topology.dawn.title')} />
       <SectionHeader title={t('topology.dawn.title')} />
-      <p className="mt-1 text-caption text-text-muted">{t('topology.dawn.caption')}</p>
+      <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-caption text-text-muted">
+        <span>{t('topology.dawn.caption')}</span>
+        {mesh && (
+          <span className="inline-flex items-center gap-1.5">
+            <span className={cn('h-1.5 w-1.5 rounded-full', active === total ? 'bg-ok' : 'bg-warn')} />
+            DAWN {active}/{total}
+          </span>
+        )}
+        {mesh?.map((m) => (
+          <span key={m.routerId} className="inline-flex items-center gap-1 rounded-full bg-elevated px-2 py-0.5 font-mono text-[10px]">
+            <span className={cn('h-1.5 w-1.5 rounded-full', m.dawn ? 'bg-ok' : 'bg-danger')} />
+            {m.name} · {m.apsSeen} APs
+          </span>
+        ))}
+      </div>
       <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
       <div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-4">
         {aps.map((ap) => (
         {aps.map((ap) => (
           <div
           <div

+ 2 - 0
app/src/data/AuthContext.tsx

@@ -7,6 +7,8 @@ import { createContext, useContext } from 'react'
 export interface AuthUser {
 export interface AuthUser {
   user: string
   user: string
   role: 'admin' | 'user'
   role: 'admin' | 'user'
+  /** 'auto' (navegador) | 'es' | 'en' — fuente de verdad: users.language */
+  language?: 'auto' | 'es' | 'en'
 }
 }
 
 
 const AuthContext = createContext<AuthUser | null>(null)
 const AuthContext = createContext<AuthUser | null>(null)

+ 6 - 0
app/src/data/DataProvider.tsx

@@ -173,6 +173,7 @@ export const EMPTY_EXTRAS: RouterExtras = {
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 
 
 function redirectLogin(): never {
 function redirectLogin(): never {
+  window.dispatchEvent(new Event('netpulse-unauthorized'))
   window.location.assign('/login')
   window.location.assign('/login')
   throw new Error('unauthorized')
   throw new Error('unauthorized')
 }
 }
@@ -401,6 +402,11 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
     }
 
 
     void (async () => {
     void (async () => {
+      // Modo demo local (flag del login): dataset simulado sin backend
+      if (sessionStorage.getItem('netpulse-demo') === '1') {
+        startDemo()
+        return
+      }
       const hasBackend = await probeBackend()
       const hasBackend = await probeBackend()
       if (disposed) return
       if (disposed) return
       if (hasBackend) await startLive()
       if (hasBackend) await startLive()

+ 13 - 0
app/src/pages/Login.tsx

@@ -67,6 +67,7 @@ export default function Login() {
         body: JSON.stringify({ username, password }),
         body: JSON.stringify({ username, password }),
       })
       })
       if (res.status === 204) {
       if (res.status === 204) {
+        window.dispatchEvent(new Event('netpulse-authed'))
         window.location.assign('/')
         window.location.assign('/')
         return
         return
       }
       }
@@ -240,6 +241,18 @@ export default function Login() {
             <ShieldCheck className="h-3.5 w-3.5 text-ok" strokeWidth={1.75} />
             <ShieldCheck className="h-3.5 w-3.5 text-ok" strokeWidth={1.75} />
             {t('login.localSession')}
             {t('login.localSession')}
           </p>
           </p>
+
+          {/* Entrar como demo: dataset simulado local, sin contraseña */}
+          <button
+            type="button"
+            onClick={() => {
+              sessionStorage.setItem('netpulse-demo', '1')
+              navigate('/', { replace: true })
+            }}
+            className="mt-3 flex w-full items-center justify-center gap-2 rounded-lg border border-border py-2.5 text-sm font-medium text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+          >
+            {t('login.demoEnter')}
+          </button>
         </div>
         </div>
       </motion.main>
       </motion.main>
     </div>
     </div>

+ 165 - 48
app/src/pages/Settings.tsx

@@ -282,6 +282,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [type, setType] = useState<'glinet' | 'openwrt'>('openwrt')
   const [type, setType] = useState<'glinet' | 'openwrt'>('openwrt')
   const [gateway, setGateway] = useState(false)
   const [gateway, setGateway] = useState(false)
   const [submitting, setSubmitting] = useState(false)
   const [submitting, setSubmitting] = useState(false)
+  const [confirmDeleteFor, setConfirmDeleteFor] = useState<string | null>(null)
   const [pubkey, setPubkey] = useState<{ publicKey: string; fingerprint: string } | null>(null)
   const [pubkey, setPubkey] = useState<{ publicKey: string; fingerprint: string } | null>(null)
   const [copied, setCopied] = useState(false)
   const [copied, setCopied] = useState(false)
   const [scanning, setScanning] = useState(false)
   const [scanning, setScanning] = useState(false)
@@ -433,10 +434,10 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   }
   }
 
 
   const remove = async (r: ConfigRouter) => {
   const remove = async (r: ConfigRouter) => {
-    if (!window.confirm(t('settings.routers.deleteConfirm', { name: r.name || r.host }))) return
     try {
     try {
       const res = await fetch(`/api/config/routers/${encodeURIComponent(r.id)}`, { method: 'DELETE' })
       const res = await fetch(`/api/config/routers/${encodeURIComponent(r.id)}`, { method: 'DELETE' })
       if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
       if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
+      setConfirmDeleteFor(null)
       await load()
       await load()
       refresh()
       refresh()
     } catch {
     } catch {
@@ -474,14 +475,33 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   {r.host} · {r.type === 'glinet' ? 'GL.iNet' : 'OpenWrt'}
                   {r.host} · {r.type === 'glinet' ? 'GL.iNet' : 'OpenWrt'}
                 </div>
                 </div>
               </div>
               </div>
-              <button
-                type="button"
-                onClick={() => void remove(r)}
-                aria-label={t('settings.routers.delete')}
-                className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-danger/40 hover:text-danger"
-              >
-                <Trash2 className="h-4 w-4" strokeWidth={1.75} />
-              </button>
+              {confirmDeleteFor === r.id ? (
+                <span className="flex shrink-0 items-center gap-1.5">
+                  <button
+                    type="button"
+                    onClick={() => void remove(r)}
+                    className="rounded-lg bg-danger px-2.5 py-1.5 text-[11px] font-semibold text-canvas transition-opacity hover:opacity-90"
+                  >
+                    {t('settings.users.confirmDelete')}
+                  </button>
+                  <button
+                    type="button"
+                    onClick={() => setConfirmDeleteFor(null)}
+                    className="rounded-lg border border-border px-2.5 py-1.5 text-[11px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+                  >
+                    {t('settings.users.cancel')}
+                  </button>
+                </span>
+              ) : (
+                <button
+                  type="button"
+                  onClick={() => setConfirmDeleteFor(r.id)}
+                  aria-label={t('settings.routers.delete')}
+                  className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-danger/40 hover:text-danger"
+                >
+                  <Trash2 className="h-4 w-4" strokeWidth={1.75} />
+                </button>
+              )}
             </li>
             </li>
           ))}
           ))}
         </ul>
         </ul>
@@ -641,6 +661,9 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
   const auth = useAuth()
   const auth = useAuth()
   const [list, setList] = useState<ManagedUser[]>([])
   const [list, setList] = useState<ManagedUser[]>([])
   const [error, setError] = useState<string | null>(null)
   const [error, setError] = useState<string | null>(null)
+  const [editingPassFor, setEditingPassFor] = useState<number | null>(null)
+  const [passDraft, setPassDraft] = useState('')
+  const [confirmDeleteFor, setConfirmDeleteFor] = useState<number | null>(null)
   const [newUser, setNewUser] = useState('')
   const [newUser, setNewUser] = useState('')
   const [newPass, setNewPass] = useState('')
   const [newPass, setNewPass] = useState('')
   const [newAdmin, setNewAdmin] = useState(false)
   const [newAdmin, setNewAdmin] = useState(false)
@@ -704,7 +727,6 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
   }
   }
 
 
   const remove = async (u: ManagedUser) => {
   const remove = async (u: ManagedUser) => {
-    if (!window.confirm(t('settings.users.deleteConfirm', { name: u.username }))) return
     try {
     try {
       const res = await fetch(`/api/users/${u.id}`, { method: 'DELETE' })
       const res = await fetch(`/api/users/${u.id}`, { method: 'DELETE' })
       if (!res.ok && res.status !== 204) {
       if (!res.ok && res.status !== 204) {
@@ -732,18 +754,19 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
   }
   }
 
 
   const changePassword = async (u: ManagedUser) => {
   const changePassword = async (u: ManagedUser) => {
-    const pass = window.prompt(t('settings.users.passwordPrompt', { name: u.username }))
-    if (!pass) return
+    if (passDraft.length < 6) return
     try {
     try {
       const res = await fetch(`/api/users/${u.id}/password`, {
       const res = await fetch(`/api/users/${u.id}/password`, {
         method: 'PUT',
         method: 'PUT',
         headers: { 'Content-Type': 'application/json' },
         headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify({ password: pass }),
+        body: JSON.stringify({ password: passDraft }),
       })
       })
       if (!res.ok && res.status !== 204) {
       if (!res.ok && res.status !== 204) {
         const body = (await res.json().catch(() => null)) as { message?: string } | null
         const body = (await res.json().catch(() => null)) as { message?: string } | null
         throw new Error(body?.message ?? `HTTP ${res.status}`)
         throw new Error(body?.message ?? `HTTP ${res.status}`)
       }
       }
+      setEditingPassFor(null)
+      setPassDraft('')
       onSaved()
       onSaved()
     } catch (err) {
     } catch (err) {
       setError(err instanceof Error ? err.message : t('settings.users.errorGeneric'))
       setError(err instanceof Error ? err.message : t('settings.users.errorGeneric'))
@@ -754,44 +777,102 @@ function UsersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => voi
     <Card title={t('settings.users.title')} caption={t('settings.users.caption')} index={5} reduce={reduce}>
     <Card title={t('settings.users.title')} caption={t('settings.users.caption')} index={5} reduce={reduce}>
       <ul className="flex flex-col gap-2">
       <ul className="flex flex-col gap-2">
         {list.map((u) => (
         {list.map((u) => (
-          <li key={u.id} className="flex items-center gap-3 rounded-xl border border-border bg-elevated px-3.5 py-2.5">
-            <UserCog className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
-            <div className="min-w-0 flex-1">
-              <div className="flex items-center gap-2">
-                <span className="truncate text-sm font-medium text-text-primary">{u.username}</span>
-                {auth?.user === u.username && (
-                  <span className="rounded-full bg-ok/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-ok">
-                    {t('settings.users.you')}
-                  </span>
-                )}
+          <li key={u.id} className="rounded-xl border border-border bg-elevated px-3.5 py-2.5">
+            <div className="flex items-center gap-3">
+              <UserCog className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
+              <div className="min-w-0 flex-1">
+                <div className="flex items-center gap-2">
+                  <span className="truncate text-sm font-medium text-text-primary">{u.username}</span>
+                  {auth?.user === u.username && (
+                    <span className="rounded-full bg-ok/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-ok">
+                      {t('settings.users.you')}
+                    </span>
+                  )}
+                </div>
               </div>
               </div>
-            </div>
-            <label className="flex shrink-0 cursor-pointer items-center gap-2 text-caption text-text-secondary" title={t('settings.users.roleAdmin')}>
-              {t('settings.users.roleAdmin')}
-              <Switch
-                checked={u.role === 'admin'}
-                onCheckedChange={(v) => void changeRole(u, v)}
-                disabled={auth?.user === u.username}
-              />
-            </label>
-            <button
-              type="button"
-              onClick={() => void changePassword(u)}
-              aria-label={t('settings.users.changePassword')}
-              title={t('settings.users.changePassword')}
-              className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent"
-            >
-              <KeyRound className="h-4 w-4" strokeWidth={1.75} />
-            </button>
-            {auth?.user !== u.username && (
+              <label className="flex shrink-0 cursor-pointer items-center gap-2 text-caption text-text-secondary" title={t('settings.users.roleAdmin')}>
+                {t('settings.users.roleAdmin')}
+                <Switch
+                  checked={u.role === 'admin'}
+                  onCheckedChange={(v) => void changeRole(u, v)}
+                  disabled={auth?.user === u.username}
+                />
+              </label>
               <button
               <button
                 type="button"
                 type="button"
-                onClick={() => void remove(u)}
-                aria-label={t('settings.users.delete')}
-                className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-danger/40 hover:text-danger"
+                onClick={() => {
+                  setEditingPassFor(editingPassFor === u.id ? null : u.id)
+                  setPassDraft('')
+                  setConfirmDeleteFor(null)
+                }}
+                aria-label={t('settings.users.changePassword')}
+                title={t('settings.users.changePassword')}
+                className={cn(
+                  'flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border transition-colors duration-150',
+                  editingPassFor === u.id ? 'border-accent/50 text-accent' : 'border-border text-text-muted hover:border-accent/40 hover:text-accent',
+                )}
               >
               >
-                <Trash2 className="h-4 w-4" strokeWidth={1.75} />
+                <KeyRound className="h-4 w-4" strokeWidth={1.75} />
               </button>
               </button>
+              {auth?.user !== u.username &&
+                (confirmDeleteFor === u.id ? (
+                  <span className="flex shrink-0 items-center gap-1.5">
+                    <button
+                      type="button"
+                      onClick={() => void remove(u)}
+                      className="rounded-lg bg-danger px-2.5 py-1.5 text-[11px] font-semibold text-canvas transition-opacity hover:opacity-90"
+                    >
+                      {t('settings.users.confirmDelete')}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => setConfirmDeleteFor(null)}
+                      className="rounded-lg border border-border px-2.5 py-1.5 text-[11px] font-medium text-text-secondary transition-colors hover:text-text-primary"
+                    >
+                      {t('settings.users.cancel')}
+                    </button>
+                  </span>
+                ) : (
+                  <button
+                    type="button"
+                    onClick={() => {
+                      setConfirmDeleteFor(u.id)
+                      setEditingPassFor(null)
+                    }}
+                    aria-label={t('settings.users.delete')}
+                    className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-danger/40 hover:text-danger"
+                  >
+                    <Trash2 className="h-4 w-4" strokeWidth={1.75} />
+                  </button>
+                ))}
+            </div>
+            {editingPassFor === u.id && (
+              <form
+                className="mt-2.5 flex items-center gap-2 border-t border-border pt-2.5"
+                onSubmit={(e) => {
+                  e.preventDefault()
+                  void changePassword(u)
+                }}
+              >
+                <input
+                  type="password"
+                  required
+                  minLength={6}
+                  value={passDraft}
+                  onChange={(e) => setPassDraft(e.target.value)}
+                  placeholder={t('settings.users.newPassword')}
+                  aria-label={t('settings.users.newPassword')}
+                  autoComplete="new-password"
+                  className="min-w-0 flex-1 rounded-lg border border-border bg-canvas px-3 py-1.5 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+                />
+                <button
+                  type="submit"
+                  disabled={passDraft.length < 6}
+                  className="shrink-0 rounded-lg bg-accent px-3 py-1.5 text-xs font-semibold text-canvas transition-opacity hover:opacity-90 disabled:opacity-40"
+                >
+                  {t('settings.users.savePassword')}
+                </button>
+              </form>
             )}
             )}
           </li>
           </li>
         ))}
         ))}
@@ -1011,7 +1092,15 @@ export default function Settings() {
     } else {
     } else {
       void i18n.changeLanguage(v)
       void i18n.changeLanguage(v)
     }
     }
-  }, [i18n])
+    // Fuente de verdad: users.language en el backend (modo live)
+    if (!isDemo) {
+      void fetch('/api/users/me/language', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ language: v }),
+      }).catch(() => undefined)
+    }
+  }, [i18n, isDemo])
 
 
   // ——— Toast "Preferencias guardadas" ———
   // ——— Toast "Preferencias guardadas" ———
   const [toastKey, setToastKey] = useState<number | null>(null)
   const [toastKey, setToastKey] = useState<number | null>(null)
@@ -1549,6 +1638,31 @@ export default function Settings() {
           </div>
           </div>
         )}
         )}
 
 
+        {/* Salir del modo demo (flag local, sin sesión) */}
+        {isDemo && (
+          <div className="lg:col-span-12">
+            <Card title={t('settings.session.title')} index={5} reduce={reduce}>
+              <div className="flex flex-wrap items-center justify-between gap-4">
+                <div>
+                  <p className="text-sm font-medium text-text-primary">{t('settings.session.demoActive')}</p>
+                  <p className="mt-0.5 text-caption text-text-muted">{t('settings.session.demoCaption')}</p>
+                </div>
+                <button
+                  type="button"
+                  onClick={() => {
+                    sessionStorage.removeItem('netpulse-demo')
+                    window.location.assign('/login')
+                  }}
+                  className="flex items-center gap-2 rounded-lg border border-danger/30 bg-danger/10 px-4 py-2 text-sm font-medium text-danger transition-colors duration-150 hover:bg-danger/15"
+                >
+                  <LogOut className="h-4 w-4" strokeWidth={1.75} />
+                  {t('settings.session.exitDemo')}
+                </button>
+              </div>
+            </Card>
+          </div>
+        )}
+
         {/* Cerrar sesión — solo con backend (modo live), webapp-stack §Logout */}
         {/* Cerrar sesión — solo con backend (modo live), webapp-stack §Logout */}
         {!isDemo && (
         {!isDemo && (
           <div className="lg:col-span-12">
           <div className="lg:col-span-12">
@@ -1565,7 +1679,10 @@ export default function Settings() {
                   onClick={() => {
                   onClick={() => {
                     void fetch('/api/auth/logout', { method: 'POST' })
                     void fetch('/api/auth/logout', { method: 'POST' })
                       .catch(() => undefined)
                       .catch(() => undefined)
-                      .finally(() => window.location.assign('/login'))
+                      .finally(() => {
+                        window.dispatchEvent(new Event('netpulse-unauthorized'))
+                        window.location.assign('/login')
+                      })
                   }}
                   }}
                   className="flex items-center gap-2 rounded-lg border border-danger/30 bg-danger/10 px-4 py-2 text-sm font-medium text-danger transition-colors duration-150 hover:bg-danger/15"
                   className="flex items-center gap-2 rounded-lg border border-danger/30 bg-danger/10 px-4 py-2 text-sm font-medium text-danger transition-colors duration-150 hover:bg-danger/15"
                 >
                 >

+ 22 - 7
server/src/adapters/adguard-glinet.js

@@ -13,6 +13,7 @@ import { sshBaseArgs } from '../sshkey.js'
 
 
 const SSH_TIMEOUT_MS = 8000
 const SSH_TIMEOUT_MS = 8000
 const HTTP_TIMEOUT_MS = 4000
 const HTTP_TIMEOUT_MS = 4000
+const LOGIN_COOLDOWN_MS = 5 * 60 * 1000 // el GL bloquea logins tras N fallos
 
 
 export class AdGuardGlinetClient {
 export class AdGuardGlinetClient {
   /**
   /**
@@ -32,8 +33,9 @@ export class AdGuardGlinetClient {
         'ssh',
         'ssh',
         [...sshBaseArgs(this.sshKeyPath), '-o', 'ControlMaster=no', `root@${this.host}`, cmd],
         [...sshBaseArgs(this.sshKeyPath), '-o', 'ControlMaster=no', `root@${this.host}`, cmd],
         { timeout: timeoutMs, maxBuffer: 1024 * 1024 },
         { timeout: timeoutMs, maxBuffer: 1024 * 1024 },
-        (err, stdout, stderr) => {
-          if (err) return reject(new Error(`ssh ${this.host}: ${err.message} ${stderr || ''}`.trim()))
+        (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)
           resolve(stdout)
         },
         },
       )
       )
@@ -42,22 +44,35 @@ export class AdGuardGlinetClient {
 
 
   /** Login GL completo en el router → sid (cookie Admin-Token). */
   /** Login GL completo en el router → sid (cookie Admin-Token). */
   async login() {
   async login() {
-    const passB64 = Buffer.from(this.pass, 'utf8').toString('base64')
+    // Cooldown tras fallo: el GL bloquea logins tras N intentos (303 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 = [
     const script = [
-      `PASS=$(echo ${passB64} | base64 -d)`,
+      `PASS='${esc}'`,
       `RESP=$(curl -s -m 5 -X POST http://127.0.0.1/rpc -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"challenge","params":{"username":"${this.user}"}}')`,
       `RESP=$(curl -s -m 5 -X POST http://127.0.0.1/rpc -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"challenge","params":{"username":"${this.user}"}}')`,
       'SALT=$(echo "$RESP" | jsonfilter -e @.result.salt)',
       'SALT=$(echo "$RESP" | jsonfilter -e @.result.salt)',
       'NONCE=$(echo "$RESP" | jsonfilter -e @.result.nonce)',
       'NONCE=$(echo "$RESP" | jsonfilter -e @.result.nonce)',
       'ALG=$(echo "$RESP" | jsonfilter -e @.result.alg)',
       'ALG=$(echo "$RESP" | jsonfilter -e @.result.alg)',
-      'CIPHER=$(openssl passwd -$ALG -salt "$SALT" "$PASS" 2>/dev/null || echo -n "$PASS" | openssl passwd -$ALG -salt "$SALT" -stdin)',
+      'CIPHER=$(openssl passwd -$ALG -salt "$SALT" "$PASS")',
       'HASH=$(echo -n "$CIPHER:$NONCE" | md5sum | cut -d" " -f1)',
       'HASH=$(echo -n "$CIPHER:$NONCE" | md5sum | cut -d" " -f1)',
       `RESP2=$(curl -s -m 5 -X POST http://127.0.0.1/rpc -H 'Content-Type: application/json' -d "{\\"jsonrpc\\":\\"2.0\\",\\"id\\":1,\\"method\\":\\"login\\",\\"params\\":{\\"username\\":\\"${this.user}\\",\\"hash\\":\\"$HASH\\"}}")`,
       `RESP2=$(curl -s -m 5 -X POST http://127.0.0.1/rpc -H 'Content-Type: application/json' -d "{\\"jsonrpc\\":\\"2.0\\",\\"id\\":1,\\"method\\":\\"login\\",\\"params\\":{\\"username\\":\\"${this.user}\\",\\"hash\\":\\"$HASH\\"}}")`,
       'SID=$(echo "$RESP2" | jsonfilter -e @.result.sid 2>/dev/null)',
       'SID=$(echo "$RESP2" | jsonfilter -e @.result.sid 2>/dev/null)',
       'echo "SID:$SID"',
       'echo "SID:$SID"',
     ].join(' && ')
     ].join(' && ')
-    const out = await this.ssh(script)
+    const out = await this.ssh(script).catch((err) => {
+      this.loginFailUntil = Date.now() + LOGIN_COOLDOWN_MS
+      throw err
+    })
     const m = /^SID:(\S+)$/m.exec(out)
     const m = /^SID:(\S+)$/m.exec(out)
-    if (!m) throw new Error('login GL falló (revisa usuario/contraseña de la UI)')
+    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]
     this.sid = m[1]
     return this.sid
     return this.sid
   }
   }

+ 46 - 21
server/src/adapters/index.js

@@ -502,7 +502,18 @@ function createLiveAdapter(config, dbHandle, initialRouters) {
     }
     }
   }
   }
 
 
+  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() {
   async function getOverview() {
+    if (overviewInFlight) return overviewInFlight
+    overviewInFlight = buildOverview().finally(() => {
+      overviewInFlight = null
+    })
+    return overviewInFlight
+  }
+
+  async function buildOverview() {
     const polled = await pollAll()
     const polled = await pollAll()
     const routerList = routers.map((cfg) => {
     const routerList = routers.map((cfg) => {
       const p = polled.get(cfg.id)
       const p = polled.get(cfg.id)
@@ -691,6 +702,14 @@ function createLiveAdapter(config, dbHandle, initialRouters) {
     if (id === gatewayCfg?.id) {
     if (id === gatewayCfg?.id) {
       detail.adguard = await pollAdGuard()
       detail.adguard = await pollAdGuard()
       detail.wireguard = await pollWireGuard(detail.clients)
       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
     return detail
   }
   }
@@ -723,34 +742,40 @@ function createLiveAdapter(config, dbHandle, initialRouters) {
     return null // el poller usa el último overview (adguard del snapshot)
     return null // el poller usa el último overview (adguard del snapshot)
   }
   }
 
 
-  /** Red DAWN (roaming/band-steering): la malla completa la tiene cualquier nodo. */
+  /** Red DAWN (roaming/band-steering): APs de la malla + salud por router. */
   async function getDawn() {
   async function getDawn() {
+    let firstData = null
+    const mesh = []
     for (const [routerId, p] of lastPolled) {
     for (const [routerId, p] of lastPolled) {
       try {
       try {
         const data = await p.client.sshJson('ubus call dawn get_network')
         const data = await p.client.sshJson('ubus call dawn get_network')
-        const aps = []
-        for (const [ssid, bssids] of Object.entries(data ?? {})) {
-          for (const [bssid, ap] of Object.entries(bssids)) {
-            aps.push({
-              ssid,
-              bssid,
-              hostname: ap.hostname ?? routerId,
-              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, from: routerId }
+        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 {
       } catch {
-        // prueba el siguiente router de la malla
+        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 ?? '',
+        })
       }
       }
     }
     }
-    return null
+    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). */
   /** Clientes AdGuard (solo si está configurado y responde). */

+ 1 - 0
server/src/db.js

@@ -87,6 +87,7 @@ export function openDb(dataDir) {
   // Migraciones tolerantes (añadir columnas si faltan en DBs antiguas)
   // Migraciones tolerantes (añadir columnas si faltan en DBs antiguas)
   migrate(db, 'sessions', 'ua', 'ALTER TABLE sessions ADD COLUMN ua TEXT')
   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, '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 = {
   const stmts = {
     insertMetric: db.prepare(
     insertMetric: db.prepare(

+ 2 - 1
server/src/routes/auth.js

@@ -53,6 +53,7 @@ export function registerAuthRoutes(app, { db, config, secret, mode }) {
 
 
   app.get('/api/auth/me', (c) => {
   app.get('/api/auth/me', (c) => {
     const user = c.get('user')
     const user = c.get('user')
-    return c.json({ user: user.username, role: user.role, mode })
+    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 })
   })
   })
 }
 }

+ 22 - 5
server/src/routes/users.js

@@ -20,19 +20,36 @@ const createSchema = z.object({
   username: usernameSchema,
   username: usernameSchema,
   password: z.string().min(6).max(128),
   password: z.string().min(6).max(128),
   role: z.enum(['admin', 'user']).default('user'),
   role: z.enum(['admin', 'user']).default('user'),
+  language: z.enum(['auto', 'es', 'en']).default('auto'),
 })
 })
 
 
 const passwordSchema = z.object({
 const passwordSchema = z.object({
   password: z.string().min(6).max(128),
   password: z.string().min(6).max(128),
 })
 })
 
 
+const languageSchema = z.object({
+  language: z.enum(['auto', 'es', 'en']),
+})
+
 export function registerUserRoutes(app, { db }) {
 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.use('/api/users/*', requireAdmin())
   app.use('/api/users/*', requireAdmin())
 
 
   app.get('/api/users', (c) => {
   app.get('/api/users', (c) => {
     const users = db
     const users = db
-      .prepare('SELECT id, username, role, created_at FROM users ORDER BY username')
+      .prepare('SELECT id, username, role, language, created_at FROM users ORDER BY username')
       .all()
       .all()
     return c.json({ users })
     return c.json({ users })
   })
   })
@@ -43,15 +60,15 @@ export function registerUserRoutes(app, { db }) {
     if (!parsed.success) {
     if (!parsed.success) {
       return c.json({ error: 'invalid_input', message: parsed.error.issues[0]?.message }, 400)
       return c.json({ error: 'invalid_input', message: parsed.error.issues[0]?.message }, 400)
     }
     }
-    const { username, password, role } = parsed.data
+    const { username, password, role, language } = parsed.data
     if (db.prepare('SELECT 1 FROM users WHERE username = ?').get(username)) {
     if (db.prepare('SELECT 1 FROM users WHERE username = ?').get(username)) {
       return c.json({ error: 'duplicate_user', message: `Ya existe el usuario ${username}` }, 409)
       return c.json({ error: 'duplicate_user', message: `Ya existe el usuario ${username}` }, 409)
     }
     }
     const hash = await bcrypt.hash(password, 10)
     const hash = await bcrypt.hash(password, 10)
     const info = db
     const info = db
-      .prepare('INSERT INTO users (username, pass_hash, role, created_at) VALUES (?, ?, ?, ?)')
-      .run(username, hash, role, Date.now())
-    return c.json({ user: { id: info.lastInsertRowid, username, role } }, 201)
+      .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) => {
   app.put('/api/users/:id/password', async (c) => {

+ 1 - 1
server/tests/auth.test.js

@@ -35,7 +35,7 @@ describe('auth', () => {
     const me = await fetch(`${srv.base}/api/auth/me`, { headers: { cookie: `session=${cookie}` } })
     const me = await fetch(`${srv.base}/api/auth/me`, { headers: { cookie: `session=${cookie}` } })
     assert.equal(me.status, 200)
     assert.equal(me.status, 200)
     const body = await me.json()
     const body = await me.json()
-    assert.deepEqual(body, { user: 'admin', role: 'admin', mode: 'demo' })
+    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 () => {
   it('protege /api/overview sin cookie (401) y la sirve con cookie (200)', async () => {