Преглед на файлове

fix(security): CSP inline styles + in-app help walkthroughs (#499)

* fix(security): allow inline styles in the CSP for Radix and framer-motion (#485)

* feat(app): in-app help section with guided walkthroughs in ES/EN (#484)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho преди 3 месеца
родител
ревизия
032f982690

+ 69 - 1
app/public/locales/en/translation.json

@@ -368,7 +368,8 @@
     "expand": "Expand menu",
     "orchestration": "Orchestration",
     "channelPlan": "Channel plan",
-    "firmwareUpgrades": "Firmware upgrades"
+    "firmwareUpgrades": "Firmware upgrades",
+    "help": "Help"
   },
   "roaming": {
     "subtitle": "Roaming and WiFi mesh status",
@@ -1623,5 +1624,72 @@
     "connectTime": "Connect",
     "dhcpSuccess": "DHCP",
     "dnsLatency": "DNS"
+  },
+  "help": {
+    "title": "Quick guide",
+    "subtitle": "Walkthroughs for the tasks a first-day admin actually needs, quoting the buttons exactly as they appear in the app.",
+    "flowsAria": "Guided walkthroughs",
+    "docsFooter": "This guide lives inside the app and quotes the real interface labels, so it always matches the version you are running.",
+    "docsLink": "Full documentation on GitHub",
+    "flows": {
+      "firstLogin": {
+        "title": "First run and password",
+        "subtitle": "Sign in for the first time and secure the admin account",
+        "intro": "The first admin user is created at server startup from the AUTH_PASS variable in .env; from then on the hash stored in the database is what counts.",
+        "steps": [
+          "Open the app and sign in with the admin user and the bootstrap password.",
+          "Go to ⟦Settings⟧ → ⟦Change my password⟧: it asks for your current password and the new one (10 to 128 characters). Your other sessions are signed out when it changes.",
+          "If you like, install NetPulse as an app from ⟦Settings⟧ → ⟦Install app⟧."
+        ],
+        "tip": "Create read-only users for anyone who just needs to look, from the users section in ⟦Settings⟧."
+      },
+      "addRouter": {
+        "title": "Onboard a router or switch",
+        "subtitle": "Add a device to the fleet",
+        "intro": "Devices are managed from Settings, not from the devices page: onboarding, editing and network discovery live there.",
+        "steps": [
+          "Go to ⟦Settings⟧ → the ⟦Devices⟧ section and click ⟦Add device⟧.",
+          "Fill in IP or hostname, name and type. Tick ⟦Is the gateway⟧ for the gateway; pick the matching type for managed switches.",
+          "For the server to poll over SSH, authorize its key: copy it from ⟦Server SSH key⟧ and install it on the router.",
+          "You can also click ⟦Discover on the network⟧ to detect candidates automatically."
+        ],
+        "tip": "A switch or AP without SSH can run in ⟦Agent only (no SSH)⟧ mode: all data will arrive through the agent."
+      },
+      "installAgent": {
+        "title": "Install the agent on a router",
+        "subtitle": "The recommended path for complete data",
+        "intro": "The agent probes the router locally (WiFi, DHCP, FDB, LLDP) and pushes the data to the server; without it the client list stays empty.",
+        "steps": [
+          "Go to ⟦Devices⟧ and scroll to the ⟦Agents⟧ section: every OpenWrt router has a row, agent or not.",
+          "Click ⟦Install agent⟧ on the router's row: it registers the token and deploys over SSH (binary, config, service and watchdog) in one click if the SSH key is already authorized.",
+          "Within seconds the router shows as online in that same table. ⟦Reinstall⟧ repeats the whole process and is what keeps the agent alive across firmware upgrades.",
+          "Manual path, or a version without the button? ⟦Settings⟧ → ⟦Agent adoption⟧ → ⟦Show token⟧, then run install-agent.sh with --pairing-token from a machine with SSH access to the router."
+        ],
+        "tip": "The pairing token is reusable for several routers until you rotate it with ⟦Rotate token⟧; each agent trades it for its own token on first contact."
+      },
+      "channelPlan": {
+        "title": "Read the channel plan",
+        "subtitle": "Pick the WiFi channel with the least interference",
+        "intro": "The page collects the passive neighbour scans pushed by the agents and scores each channel; the recommendation balances your current channel against the candidates.",
+        "steps": [
+          "Open ⟦Channel plan⟧ in the menu (marked as labs).",
+          "Pick the router: each radio shows its current channel, the neighbours it hears and the score of every candidate channel.",
+          "The highlighted recommendation is the channel with the least overlap; compare it with the current channel before touching anything."
+        ],
+        "tip": "Scans arrive with the agent pushes: if a router reports no neighbours, check that its agent is online."
+      },
+      "firmware": {
+        "title": "Upgrade a router's firmware",
+        "subtitle": "Controlled flash with verification and backup",
+        "intro": "The server tells the agent which image to flash; the agent downloads it, verifies the sha256, backs up the config and flashes with sysupgrade.",
+        "steps": [
+          "Open ⟦Firmware upgrades⟧ in the menu (labs, admin only).",
+          "Pick the router: the form preloads the detected system (model and current version). Paste the image URL and its sha256.",
+          "Click ⟦Upgrade now⟧: the confirmation summarises router, target version, URL and checksum, and warns about the downtime while it reboots.",
+          "Follow the progress on the same page; the final result lands when the router finishes booting."
+        ],
+        "tip": "After a flash only /etc survives: the agent's self-heal restores the binary at boot, and ⟦Reinstall⟧ puts everything fresh if needed."
+      }
+    }
   }
 }

+ 69 - 1
app/public/locales/es/translation.json

@@ -368,7 +368,8 @@
     "expand": "Desplegar menú",
     "orchestration": "Orquestación",
     "channelPlan": "Plan de canales",
-    "firmwareUpgrades": "Actualizaciones de firmware"
+    "firmwareUpgrades": "Actualizaciones de firmware",
+    "help": "Ayuda"
   },
   "roaming": {
     "subtitle": "Estado de la itinerancia WiFi y la malla WiFi",
@@ -1623,5 +1624,72 @@
     "connectTime": "Conexion",
     "dhcpSuccess": "DHCP",
     "dnsLatency": "DNS"
+  },
+  "help": {
+    "title": "Guía rápida",
+    "subtitle": "Los recorridos de las tareas que necesita un admin el primer día, citando los botones tal y como están en la app.",
+    "flowsAria": "Recorridos guiados",
+    "docsFooter": "Esta guía vive dentro de la app y cita las etiquetas reales de la interfaz, así que siempre está al día con la versión que estás usando.",
+    "docsLink": "Documentación completa en GitHub",
+    "flows": {
+      "firstLogin": {
+        "title": "Primer arranque y contraseña",
+        "subtitle": "Entrar por primera vez y asegurar la cuenta admin",
+        "intro": "El primer usuario admin se crea en el arranque del servidor a partir de la variable AUTH_PASS del .env; a partir de ahí manda el hash guardado en la base de datos.",
+        "steps": [
+          "Abre la app e inicia sesión con el usuario admin y la contraseña de arranque.",
+          "Ve a ⟦Ajustes⟧ → ⟦Cambiar mi contraseña⟧: pide la actual y la nueva (entre 10 y 128 caracteres). El resto de tus sesiones se cierran al cambiarla.",
+          "Si quieres, instala NetPulse como aplicación desde ⟦Ajustes⟧ → ⟦Instalar app⟧."
+        ],
+        "tip": "Crea usuarios de solo lectura para quien solo necesite mirar la red desde la sección de usuarios de ⟦Ajustes⟧."
+      },
+      "addRouter": {
+        "title": "Dar de alta un router o switch",
+        "subtitle": "Añadir un equipo a la flota",
+        "intro": "Los equipos se gestionan desde Ajustes, no desde la página de dispositivos: ahí viven el alta, la edición y el descubrimiento de la red.",
+        "steps": [
+          "Ve a ⟦Ajustes⟧ → sección ⟦Dispositivos⟧ y pulsa ⟦Añadir dispositivo⟧.",
+          "Rellena IP o hostname, nombre y tipo. Marca ⟦Es la puerta de enlace⟧ si es el gateway; para switches gestionados elige el tipo correspondiente.",
+          "Para que el server pueda sondear por SSH, autoriza su clave: cópiala desde ⟦Clave SSH del servidor⟧ e instálala en el router.",
+          "También puedes pulsar ⟦Descubrir en la red⟧ para detectar candidatos automáticamente."
+        ],
+        "tip": "Un switch o AP sin SSH puede funcionar en modo ⟦Solo agente (sin SSH)⟧: todos los datos llegarán por el agente."
+      },
+      "installAgent": {
+        "title": "Instalar el agente en un router",
+        "subtitle": "El camino recomendado para tener datos completos",
+        "intro": "El agente sondea el router en local (WiFi, DHCP, FDB, LLDP) y empuja los datos al servidor; sin él, la lista de clientes sale vacía.",
+        "steps": [
+          "Ve a ⟦Dispositivos⟧ y baja hasta la sección ⟦Agentes⟧: todo router OpenWrt tiene fila, tenga agente o no.",
+          "Pulsa ⟦Instalar agente⟧ en la fila del router: se registra el token y se despliega por SSH (binario, config, servicio y watchdog), en un solo clic si la clave SSH ya está autorizada.",
+          "En unos segundos el router pasa a estar en línea en esa misma tabla. ⟦Reinstalar⟧ repite el proceso completo y es lo que mantiene el agente vivo tras upgrades de firmware.",
+          "¿Vía manual o versión sin botón? ⟦Ajustes⟧ → ⟦Adopción de agentes⟧ → ⟦Mostrar token⟧, y desde una máquina con SSH al router ejecuta install-agent.sh con --pairing-token."
+        ],
+        "tip": "El token de pairing es reutilizable para varios routers hasta que lo rotes con ⟦Rotar token⟧; cada agente lo canjea por su token propio al primer contacto."
+      },
+      "channelPlan": {
+        "title": "Leer el plan de canales",
+        "subtitle": "Elegir canal WiFi con la menor interferencia",
+        "intro": "La página recoge los escaneos pasivos de vecinos que mandan los agentes y puntúa cada canal; la recomendación es el mejor balance entre tu canal actual y los candidatos.",
+        "steps": [
+          "Abre ⟦Plan de canales⟧ en el menú (marcado como labs).",
+          "Elige el router: verás cada radio con su canal actual, los vecinos que se oyen y la puntuación de cada canal candidato.",
+          "La recomendación destacada es el canal con menos solapamiento; compárala con el canal actual antes de tocar nada."
+        ],
+        "tip": "Los escaneos llegan con los pushes del agente: si un router no aporta vecinos, revisa que su agente esté en línea."
+      },
+      "firmware": {
+        "title": "Actualizar el firmware de un router",
+        "subtitle": "Flash controlado con verificación y respaldo",
+        "intro": "El servidor le dice al agente qué imagen flashear; el agente descarga, verifica el sha256, respalda la configuración y flashea con sysupgrade.",
+        "steps": [
+          "Abre ⟦Actualizaciones de firmware⟧ en el menú (labs, solo admin).",
+          "Elige el router: el formulario precarga el sistema detectado (modelo y versión actual). Pega la URL de la imagen y su sha256.",
+          "Pulsa ⟦Actualizar ahora⟧: la confirmación resume router, versión objetivo, URL y checksum, y avisa de la caída mientras reinicia.",
+          "Sigue el progreso desde la misma página; el resultado definitivo llega cuando el router termina de arrancar."
+        ],
+        "tip": "Tras un flash solo sobrevive lo de /etc: el self-heal del agente restaura el binario al arrancar, y ⟦Reinstalar⟧ lo deja todo fresco si hiciera falta."
+      }
+    }
   }
 }

+ 2 - 0
app/src/App.tsx

@@ -16,6 +16,7 @@ import Reports from '@/pages/Reports'
 import Orchestration from '@/pages/Orchestration'
 import FirmwareUpgrades from '@/pages/FirmwareUpgrades'
 import Settings from '@/pages/Settings'
+import Help from '@/pages/Help'
 import Placeholder from '@/pages/Placeholder'
 
 /**
@@ -50,6 +51,7 @@ export default function App() {
         <Route path="firmware-upgrades" element={<FirmwareUpgrades />} />
         <Route path="reports" element={<Reports />} />
         <Route path="orchestration" element={<Orchestration />} />
+        <Route path="help" element={<Help />} />
         <Route path="settings" element={<Settings />} />
         <Route path="*" element={<Placeholder title="Página no encontrada" />} />
       </Route>

+ 2 - 1
app/src/components/CommandPalette.tsx

@@ -1,7 +1,7 @@
 import { useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { useNavigate } from 'react-router'
-import { Bell, LayoutDashboard, MonitorSmartphone, Router as RouterIcon, Settings, Waypoints } from 'lucide-react'
+import { Bell, CircleHelp, LayoutDashboard, MonitorSmartphone, Router as RouterIcon, Settings, Waypoints } from 'lucide-react'
 import {
   CommandDialog,
   CommandEmpty,
@@ -19,6 +19,7 @@ const PAGES = [
   { to: '/devices', labelKey: 'nav.devices', icon: MonitorSmartphone },
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
+  { to: '/help', labelKey: 'nav.help', icon: CircleHelp },
   { to: '/settings', labelKey: 'nav.settings', icon: Settings },
 ] as const
 

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

@@ -6,6 +6,7 @@ import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router'
 import { AnimatePresence, motion } from 'framer-motion'
 import PullToRefresh from '@/components/PullToRefresh'
 import {
+  CircleHelp,
   ArrowLeft,
   BarChart3,
   Bell,
@@ -62,6 +63,7 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
   { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true, badge: 'labs' },
+  { to: '/help', labelKey: 'nav.help', icon: CircleHelp },
   { to: '/settings', labelKey: 'nav.settings', icon: Settings },
 ]
 
@@ -83,6 +85,7 @@ const PAGE_TITLE_KEYS: [RegExp, string][] = [
   [/^\/alerts/, 'nav.alerts'],
   [/^\/reports/, 'nav.reports'],
   [/^\/orchestration/, 'nav.orchestration'],
+  [/^\/help/, 'nav.help'],
   [/^\/settings/, 'nav.settings'],
 ]
 

+ 154 - 0
app/src/pages/Help.tsx

@@ -0,0 +1,154 @@
+/**
+ * Help — sección de ayuda in-app con walkthroughs guiados (issue #484).
+ * Nació del feedback del foro: un admin nuevo se atascaba en "¿dónde doy de
+ * alta un agente?" y la única referencia era el README, que ya había drift
+ * de la UI al menos una vez.
+ *
+ * Los pasos citan las etiquetas REALES de la UI (mismo i18n que los
+ * componentes) renderizadas como chips ⟦así⟧, de modo que la ayuda deriva
+ * junto con la interfaz: si un botón cambia de nombre, la búsqueda del chip
+ * en los locales lo delata. Sin capturas bitmap a propósito: envejecen mal
+ * y nadie quiere mantenerlas.
+ */
+import { useTranslation } from 'react-i18next'
+import {
+  BookOpen,
+  CircleHelp,
+  Cpu,
+  KeyRound,
+  ListChecks,
+  Router as RouterIcon,
+  Wifi,
+} from 'lucide-react'
+import {
+  Accordion,
+  AccordionContent,
+  AccordionItem,
+  AccordionTrigger,
+} from '@/components/ui/accordion'
+
+/** Chip de etiqueta de UI dentro de un paso (botón, sección, página). */
+function UiChip({ children }: { children: string }) {
+  return (
+    <span className="mx-0.5 inline-flex items-center rounded-md border border-border bg-surface-2 px-1.5 py-px align-middle text-[0.85em] font-medium text-text-primary">
+      {children}
+    </span>
+  )
+}
+
+/**
+ * RichText: renderiza un string i18n marcando ⟦etiqueta de UI⟧ como chip.
+ * Sin marcadores, texto plano. Un solo delimitador a propósito: mantener la
+ * ayuda escaneable y no convertir esto en un mini-lenguaje.
+ */
+function RichText({ text }: { text: string }) {
+  const parts = text.split(/⟦([^⟧]+)⟧/g)
+  return (
+    <>
+      {parts.map((p, i) => (i % 2 === 1 ? <UiChip key={i}>{p}</UiChip> : p))}
+    </>
+  )
+}
+
+const FLOWS = [
+  { key: 'firstLogin', icon: KeyRound },
+  { key: 'addRouter', icon: RouterIcon },
+  { key: 'installAgent', icon: CircleHelp },
+  { key: 'channelPlan', icon: Wifi },
+  { key: 'firmware', icon: Cpu },
+] as const
+
+export default function Help() {
+  const { t } = useTranslation()
+
+  return (
+    <div className="mx-auto flex w-full max-w-3xl flex-col gap-6 px-4 py-6 sm:px-6">
+      <header className="flex flex-col gap-2">
+        <h1 className="flex items-center gap-2.5 text-xl font-semibold text-text-primary">
+          <CircleHelp className="h-5 w-5 text-accent" strokeWidth={1.75} aria-hidden="true" />
+          {t('help.title')}
+        </h1>
+        <p className="text-sm text-text-secondary">{t('help.subtitle')}</p>
+      </header>
+
+      <section
+        aria-label={t('help.flowsAria')}
+        className="rounded-xl border border-border bg-surface"
+      >
+        <Accordion type="multiple" defaultValue={['firstLogin']}>
+          {FLOWS.map(({ key, icon: Icon }) => {
+            const steps = t(`help.flows.${key}.steps`, { returnObjects: true }) as string[]
+            return (
+              <AccordionItem key={key} value={key}>
+                <AccordionTrigger className="px-4 py-3.5 hover:no-underline">
+                  <span className="flex items-center gap-2.5 text-left">
+                    <Icon
+                      className="h-4 w-4 shrink-0 text-accent"
+                      strokeWidth={1.75}
+                      aria-hidden="true"
+                    />
+                    <span className="flex flex-col">
+                      <span className="text-sm font-medium text-text-primary">
+                        {t(`help.flows.${key}.title`)}
+                      </span>
+                      <span className="text-caption text-text-muted">
+                        {t(`help.flows.${key}.subtitle`)}
+                      </span>
+                    </span>
+                  </span>
+                </AccordionTrigger>
+                <AccordionContent className="px-4 pb-4">
+                  <p className="mb-3 text-caption leading-relaxed text-text-secondary">
+                    <RichText text={t(`help.flows.${key}.intro`)} />
+                  </p>
+                  <ol className="flex flex-col gap-2.5">
+                    {Array.isArray(steps)
+                      ? steps.map((s, i) => (
+                          <li key={i} className="flex items-start gap-2.5">
+                            <span
+                              className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-accent/40 bg-accent-soft text-[11px] font-semibold text-accent"
+                              aria-hidden="true"
+                            >
+                              {i + 1}
+                            </span>
+                            <span className="text-caption leading-relaxed text-text-secondary">
+                              <RichText text={s} />
+                            </span>
+                          </li>
+                        ))
+                      : null}
+                  </ol>
+                  {t(`help.flows.${key}.tip`, { defaultValue: '' }) && (
+                    <p className="mt-3 flex items-start gap-2 rounded-lg border border-border bg-surface-2 px-3 py-2 text-caption leading-relaxed text-text-secondary">
+                      <ListChecks
+                        className="mt-0.5 h-3.5 w-3.5 shrink-0 text-text-muted"
+                        strokeWidth={1.75}
+                        aria-hidden="true"
+                      />
+                      <RichText text={t(`help.flows.${key}.tip`)} />
+                    </p>
+                  )}
+                </AccordionContent>
+              </AccordionItem>
+            )
+          })}
+        </Accordion>
+      </section>
+
+      <footer className="flex items-start gap-2.5 rounded-xl border border-border bg-surface px-4 py-3 text-caption text-text-secondary">
+        <BookOpen className="mt-0.5 h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+        <span>
+          <RichText text={t('help.docsFooter')} />{' '}
+          <a
+            href="https://github.com/gnacho/netpulse#readme"
+            target="_blank"
+            rel="noreferrer"
+            className="text-accent hover:underline"
+          >
+            {t('help.docsLink')}
+          </a>
+        </span>
+      </footer>
+    </div>
+  )
+}

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

@@ -888,7 +888,7 @@ func TestSecurityHeaders(t *testing.T) {
 		"Referrer-Policy":           "strict-origin-when-cross-origin",
 		"Permissions-Policy":        "geolocation=(), microphone=(), camera=()",
 		"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
-		"Content-Security-Policy":   "default-src 'self'; script-src 'self'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'",
+		"Content-Security-Policy":   "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'",
 	}
 	for k, v := range want {
 		if got := res.Header.Get(k); got != v {

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

@@ -11,7 +11,14 @@ var Headers = []struct{ K, V string }{
 	{"Referrer-Policy", "strict-origin-when-cross-origin"},
 	{"Permissions-Policy", "geolocation=(), microphone=(), camera=()"},
 	{"Strict-Transport-Security", "max-age=31536000; includeSubDomains"},
-	{"Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'"},
+	// style-src lleva 'unsafe-inline' a propósito (#485): Radix (posicionado
+	// popper) y framer-motion (transform/opacity) escriben atributos style
+	// CON VALORES DINÁMICOS (píxeles calculados), imposibles de hashear con
+	// 'unsafe-hashes'. Sin 'unsafe-inline' cada apertura de diálogo loguea
+	// una violación CSP y las transiciones no corren. El riesgo de CSS
+	// inline es muy inferior al de script inline (la app no renderiza HTML
+	// controlado por el usuario), y script-src sigue sin 'unsafe-inline'.
+	{"Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; connect-src 'self'"},
 }
 
 // Middleware aplica los headers a todas las respuestas (HSTS también por