Răsfoiți Sursa

feat(beacon): UDP beacon agents for RTL8372/8373 switches (#294)

* feat(beacon): UDP ingest on a configurable port for embedded pushers

- NETPULSE_BEACON_LISTEN (default off; ':5140' on the CT) opens a UDP
  listener that accepts spec-v1 beacons from embedded devices: one JSON
  line with schema version, wrap-around seq, slug, agent token and the
  full port list (link code + good-frame counters)
- token validated against the same sha256 kv as the HTTP ingest; server
  stamps arrival time (the emitter has no RTC); rate limited per source
  IP like the HTTP path; seq jumps logged for loss/reorder diagnosis
- mapped onto the agent registry as kind=external interval=30 so the
  freshness window scales (3x) and the fleet badges it; MAC table is
  intentionally absent so the scraper FDB survives beacon-only periods
- port labels from scraper v2.1 are re-injected server-side (the beacon
  travels without labels to keep datagrams small)

Closes #291

* feat(switch): MAC-to-name matching on port detail and no wifi sections for wired switches

- polledFromAgent normalizes external pusher FDB port keys ("1" to
  "lan1") so the router detail enrichment (connected device per port)
  matches the declared port ids; wired-neighbor resolution now also falls
  back to known_macs aliases for static devices without DHCP leases
- RadiosPorts hides the empty wifi section when the device has no radios
  (managed switches like the RTLPlayground KP-9000) and lets the port
  panel span full width

* fix(ports): keep all jacks on a single horizontal row with overflow scroll

The chassis wrapped ports into several rows on narrow panels and phones;
a wired switch reads as one physical front panel, so the row is now
never broken and scrolls horizontally when it does not fit

* fix(detail): ports with many learned MACs show an aggregate instead of an arbitrary virtual NIC

A hypervisor port learns the virtual NICs of its containers; picking the
first DHCP-named one displayed a CT name (ngxpm) as if it were the
plugged device. Ports with more than 3 MACs and no LLDP now read
"N dispositivos" with an aggregation hint, leaving the physical
identification to the curated port label

* feat(beacon): auto-discovery of unpaired embedded switches

- spec-v1 beacons carrying dev/fw with an empty token are discovery
  announces: the listener records them as candidates keyed by source IP
  (10 min TTL, refreshed on each announce)
- GET /api/agents/discovered (admin) lists live candidates; a validated
  beacon from the same IP clears its candidate
- the fleet section shows a discovery strip for admins: pick a slug,
  create the agent token and get the exact beacon command to paste in
  the switch advanced settings
- createAgentInstall now surfaces the one-time token alongside the
  install one-liner

* docs: beacon protocol spec v1.1 (beacon, announce, events, loop guard)

* feat(beacon): immediate firmware events and link-change fallback alerts

- spec v1.1 event datagrams (loop, port_up, port_down, port_disabled,
  port_recovered) authenticated like beacons; they feed the alerts
  engine without touching the registry payload (no ports to wipe)
- loop is urgent; disabled/recovered carry the auto-guard lifecycle
- delta fallback: link changes between consecutive beacons emit the same
  titles so the engine dedup collapses duplicates when both paths fire
- port labels from the last scraper push are used in alert titles

* feat(beacon): dedicated FDB datagram (5 min) replacing the scraper path

- spec v1.2: one datagram carries the whole MAC table (~600 B); ports as
  bare numbers are aligned with the port ids server-side; an empty map
  is a real empty table while an absent field leaves it untouched
- the listener keeps the ports from the last periodic beacon so the FDB
  datagram never wipes them; link-delta fallback only runs on datagrams
  that carry ports
- loop guard section in the spec marked deferred with the roaming
  objection: alert-only if ever, never auto-disable, AP and uplink
  ports excluded

* fix(beacon): normalize bare MACs in FDB datagrams and detect switch reboots

- the firmware emits MACs uppercase without separators; the listener
  normalizes them to the canonical colon format so leases, wireless
  associations and port enrichment keep matching (invalid keys dropped)
- seq dropping to <=1 from a higher value is the firmware boot
  signature: emits an info alert ("Switch reiniciado") for free

* feat(detail): infrastructure-aware port attribution for managed switches

- a port whose learned MACs are all wifi clients of one AP attributes to
  the AP itself (the plugged device), with the client noted as behind it
- virtualization OUI prefixes (QEMU/KVM, Proxmox, Hyper-V, VMware,
  VirtualBox) mark the port as a hypervisor with the VM/CT behind
- a curated port label that does not match the learned device names the
  infrastructure and shows the device as behind it (custom-MAC CTs)
- fixes shelly-lavadora reading as directly wired to the switch instead
  of behind its Redmi AX6 AP, and ngxpm instead of behind citadel-02

* fix(detail): guard empty MAC list before wifi attribution

A port marked up with no learned MACs reached all[0] and panicked the
detail handler

* fix(detail): curated label names the device when nothing better is known

An unnamed learned MAC (no lease, no alias) plus a curated port label
means the label baptizes the device itself (hikvision camera), not the
infrastructure in front of it

* fix(ports): show the MAC instead of duplicating the label as connected device

* feat(i18n): device detail title instead of router detail

* fix(beacon): carry the last known MAC table in periodic beacons

The beacon payload traveled with nil MACs, wiping the persisted state 30 s
after every FDB datagram; after a server restart the restored state had
no MACs and port attribution stayed empty until the next 5 min datagram.
Beacons now carry the last known table (a real empty table still arrives
as {} from the FDB datagram), so restarts restore attribution instantly

* fix(topology): satellites never adopt devices learned on uplink ports

A satellite port that learns another router's bridge MAC is an uplink:
what it learns there is the rest of the LAN in transit. The agent-only
exception made managed switches adopt the whole network seen through
their uplink (TV, marantz and friends hanging off the switch's lan1);
uplink ports are now excluded from client attribution

* fix(detail): compact one-row backhaul panel with the real gateway IP

- drops the 160px signal area chart and the latency gauge/sparkline:
  backhaul and gateway latency now render as a single slim full-width
  row (icon + headline + kind + latency + target)
- the latency caption hardcodED the demo canon IP 192.168.8.1 (the
  mystery sighting); it now uses the live gateway IP from the fleet

* fix(detail): spread the backhaul row across the card width

Backhaul, gateway latency (with live IP), current traffic and last
reboot in a balanced 4-column grid instead of a cramped left-aligned
row

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 luni în urmă
părinte
comite
16882ce688

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

@@ -307,7 +307,7 @@
     "overview": "Overview",
     "reports": "Reports",
     "roaming": "WiFi roaming",
-    "routerDetail": "Router detail",
+    "routerDetail": "Device detail",
     "routers": "Devices",
     "settings": "Settings",
     "settingsDesc": "Theme, units and installation",
@@ -616,7 +616,13 @@
       "cmdFail": "Could not generate the command",
       "title": "Agents",
       "external": "External",
-      "externalTip": "External pusher (scraper): pushes every {{interval}} s, no installable agent or upgrades"
+      "externalTip": "External pusher (scraper): pushes every {{interval}} s, no installable agent or upgrades",
+      "discoveredTitle_one": "Embedded switch found on the network",
+      "discoveredTitle_other": "{{count}} embedded switches found on the network",
+      "discoveredSlug": "slug (e.g. switch16)",
+      "discoveredPair": "Pair",
+      "discoveredFail": "Could not create the token",
+      "discoveredHint": "Paste the command in the switch Advanced Settings"
     },
     "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s"
   },

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

@@ -307,7 +307,7 @@
     "overview": "Resumen",
     "reports": "Informes",
     "roaming": "Roaming WiFi",
-    "routerDetail": "Detalle de router",
+    "routerDetail": "Detalle del dispositivo",
     "routers": "Dispositivos",
     "settings": "Ajustes",
     "settingsDesc": "Tema, unidades e instalación",
@@ -616,7 +616,13 @@
       "cmdFail": "No se pudo generar el comando",
       "title": "Agentes",
       "external": "Externo",
-      "externalTip": "Pusher externo (scraper): empuja cada {{interval}} s, sin agente instalable ni actualizaciones"
+      "externalTip": "Pusher externo (scraper): empuja cada {{interval}} s, sin agente instalable ni actualizaciones",
+      "discoveredTitle_one": "Switch embebido encontrado en la red",
+      "discoveredTitle_other": "{{count}} switches embebidos encontrados en la red",
+      "discoveredSlug": "slug (p. ej. switch16)",
+      "discoveredPair": "Parear",
+      "discoveredFail": "No se pudo crear el token",
+      "discoveredHint": "Pega el comando en Advanced Settings del switch"
     },
     "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s"
   },

+ 100 - 1
app/src/components/routers/AgentsSection.tsx

@@ -1,7 +1,7 @@
 import { useEffect, useMemo, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
-import { Check, Clipboard, Clock, Loader2, RotateCcw } from 'lucide-react'
+import { Check, Clipboard, Clock, Loader2, Radar, RotateCcw } from 'lucide-react'
 import { motion } from 'framer-motion'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
@@ -282,6 +282,104 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
   )
 }
 
+/** Switch embebido anunciándose por broadcast sin parar (#291). */
+interface DiscoveredAgent {
+  ip: string
+  dev: string
+  fw?: string
+  ports?: number
+  lastSeen: number
+}
+
+/** Franja de descubrimiento: switches RTLPlayground encontrados en la LAN
+ * esperando pareado (slug + token + comando beacon). Solo admin (#291). */
+function DiscoveredStrip() {
+  const { t } = useTranslation()
+  const auth = useAuth()
+  const { createAgentInstall } = useNetPulse()
+  const [found, setFound] = useState<DiscoveredAgent[]>([])
+  const [slugByIp, setSlugByIp] = useState<Record<string, string>>({})
+  const [pairByIp, setPairByIp] = useState<Record<string, { token?: string; error?: string; busy?: boolean }>>({})
+
+  useEffect(() => {
+    if (auth?.role !== 'admin') return
+    let disposed = false
+    const load = async () => {
+      try {
+        const res = await fetch('/api/agents/discovered', { signal: AbortSignal.timeout(4000) })
+        if (!res.ok) return
+        const j = (await res.json()) as { discovered?: DiscoveredAgent[] }
+        if (!disposed) setFound(j.discovered ?? [])
+      } catch {
+        /* sin candidatos o sin sesión */
+      }
+    }
+    void load()
+    const id = window.setInterval(load, 30_000)
+    return () => {
+      disposed = true
+      window.clearInterval(id)
+    }
+  }, [auth?.role])
+
+  if (auth?.role !== 'admin' || found.length === 0) return null
+
+  const pair = async (ip: string) => {
+    const slug = (slugByIp[ip] ?? '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '')
+    if (!slug) return
+    setPairByIp((m) => ({ ...m, [ip]: { busy: true } }))
+    const res = await createAgentInstall(slug)
+    setPairByIp((m) => ({
+      ...m,
+      [ip]: res && res.token ? { token: res.token } : { error: 'fail' },
+    }))
+  }
+
+  return (
+    <div className="mb-4 flex flex-col gap-2 rounded-2xl border border-accent/30 bg-accent/5 p-4" role="status">
+      <p className="flex items-center gap-2 text-caption font-semibold text-accent">
+        <Radar className="h-4 w-4 animate-pulse" strokeWidth={1.75} aria-hidden="true" />
+        {t('routers.agents.discoveredTitle', { count: found.length })}
+      </p>
+      {found.map((c) => {
+        const pairState = pairByIp[c.ip] ?? {}
+        return (
+          <div key={c.ip} className="flex flex-wrap items-center gap-2 rounded-xl bg-surface px-3.5 py-2.5">
+            <span className="font-mono text-caption text-text-secondary">{c.ip}</span>
+            <span className="text-caption font-medium text-text-primary">{c.dev}</span>
+            {c.fw && <span className="rounded-full border border-border px-2 py-0.5 font-mono text-[10px] text-text-muted">{c.fw}</span>}
+            {pairState.token ? (
+              <code className="min-w-0 flex-1 truncate rounded-lg bg-canvas px-2 py-1 font-mono text-caption text-ok" title={`beacon <ip-netpulse> <slug> <token>`}>
+                beacon &lt;ip-netpulse&gt; &lt;slug&gt; {pairState.token.slice(0, 12)}…
+              </code>
+            ) : (
+              <>
+                <input
+                  value={slugByIp[c.ip] ?? ''}
+                  onChange={(e) => setSlugByIp((m) => ({ ...m, [c.ip]: e.target.value }))}
+                  placeholder={t('routers.agents.discoveredSlug')}
+                  aria-label={t('routers.agents.discoveredSlug')}
+                  className="h-8 w-36 rounded-lg border border-border bg-canvas px-2.5 font-mono text-caption text-text-primary outline-none focus:border-accent/50"
+                />
+                <button
+                  type="button"
+                  onClick={() => void pair(c.ip)}
+                  disabled={pairState.busy}
+                  className="inline-flex h-8 items-center rounded-lg bg-accent px-3 text-caption font-semibold text-canvas transition-opacity hover:opacity-90 disabled:opacity-50"
+                >
+                  {pairState.busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={2} aria-hidden="true" /> : t('routers.agents.discoveredPair')}
+                </button>
+                {pairState.error && <span className="text-caption text-danger">{t('routers.agents.discoveredFail')}</span>}
+              </>
+            )}
+            <span className="ml-auto text-caption text-text-muted">{t('routers.agents.discoveredHint')}</span>
+          </div>
+        )
+      })}
+    </div>
+  )
+}
+
 /** Sección de flota de agentes (issue #245): registrados + routers agent-only
  * sin agente. Vive al final de la página /routers (#284). */
 export function AgentsSection() {
@@ -313,6 +411,7 @@ export function AgentsSection() {
         <h2 id="agents-section-title" className="font-display text-h2 text-text-primary">{t('routers.agents.title')}</h2>
         <p className="text-caption text-text-muted">{t('routers.agents.subtitle', { total, down })}</p>
       </div>
+      <DiscoveredStrip />
       {rows.length === 0 ? (
         <p className="py-8 text-center text-sm text-text-secondary">{t('routers.agents.empty')}</p>
       ) : (

+ 46 - 105
app/src/components/routers/BackhaulPanel.tsx

@@ -1,123 +1,64 @@
-import { Cable, Wifi } from 'lucide-react'
-import { motion, useReducedMotion } from 'framer-motion'
-import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis } from 'recharts'
+import { Activity, Cable, Wifi } from 'lucide-react'
 import { useTranslation } from 'react-i18next'
 import type { Router } from '@/data/mock'
-import { SectionHeader } from '@/components/SectionHeader'
-import { Sparkline } from '@/components/Sparkline'
-import { LatencyGauge } from '@/components/routers/LatencyGauge'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import type { RouterExtras } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
 
-function SignalTooltip({
-  active,
-  payload,
-  label,
-  wireless,
-}: {
-  active?: boolean
-  payload?: { value?: number | string }[]
-  label?: string
-  wireless: boolean
-}) {
-  if (!active || !payload?.length) return null
-  const value = payload[0]?.value
-  if (value === undefined) return null
-  return (
-    <div className="rounded-[10px] border border-border-strong bg-elevated px-3 py-2 shadow-lg">
-      <div className="mb-0.5 font-mono text-caption text-text-muted">{label}</div>
-      <div className="font-mono text-mono-sm text-text-primary">
-        {value} {wireless ? 'dBm' : '% carga enlace'}
-      </div>
-    </div>
-  )
-}
-
-/** ④ variante OpenWrt — Backhaul + latencia al gateway (router-detail.md §Variante). */
+/** ④ variante OpenWrt — fila compacta a ancho completo: backhaul, latencia al
+ * gateway (con su IP REAL, no el literal del canon demo), tráfico y último
+ * reinicio repartidos en columnas (decisión 28-Ago-2026). */
 export function BackhaulPanel({ router, extras }: { router: Router; extras?: RouterExtras }) {
   const { t } = useTranslation()
-  const { isDemo } = useNetPulse()
+  const { isDemo, routers } = useNetPulse()
   const ex = extras ?? (isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS)
   const backhaul = ex.backhaul
-  const reduce = useReducedMotion()
   if (!backhaul) return null
 
   const wireless = backhaul.kind === 'wireless'
-  const data = ex.backhaulSignal.map((v, i) => ({
-    t: `${String(i).padStart(2, '0')}:00`,
-    v,
-  }))
   const Icon = wireless ? Wifi : Cable
+  const gwIp = routers.find((r) => r.roleBadge === 'Principal')?.ip
+  const latency = backhaul.latencyMs != null ? `${Math.round(backhaul.latencyMs)} ms` : '—'
 
-  return (
-    <div className="grid grid-cols-1 gap-4 md:gap-5 lg:col-span-12 lg:grid-cols-12">
-      {/* Backhaul */}
-      <section className="rounded-2xl border border-border bg-surface p-5 md:p-6 lg:col-span-7">
-        <SectionHeader title="Backhaul" />
-        <div className="mt-3 flex items-center gap-2.5 rounded-xl bg-elevated/60 px-3.5 py-3">
-          <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-accent-soft text-accent">
-            <Icon className="h-[18px] w-[18px]" strokeWidth={1.75} />
-          </span>
-          <div>
-            <div className="font-mono text-mono-sm font-semibold text-text-primary">{backhaul.headline}</div>
-            <div className="text-caption text-text-muted">
-              {wireless ? t('routerDetail.backhaul.wirelessLink') : t('routerDetail.backhaul.wiredLink')}
-            </div>
-          </div>
-        </div>
-        <motion.div
-          initial={reduce ? false : { opacity: 0 }}
-          animate={{ opacity: 1 }}
-          transition={{ duration: 0.3 }}
-          className="mt-4 h-[160px]"
-          role="img"
-          aria-label={wireless ? t('routerDetail.backhaul.signalAria') : t('routerDetail.backhaul.loadAria')}
-        >
-          <ResponsiveContainer width="100%" height="100%">
-            <AreaChart data={data} margin={{ top: 8, right: 4, bottom: 0, left: 4 }}>
-              <defs>
-                <linearGradient id="backhaul-grad" x1="0" y1="0" x2="0" y2="1">
-                  <stop offset="0%" stopColor="#22D3EE" stopOpacity={0.25} />
-                  <stop offset="100%" stopColor="#22D3EE" stopOpacity={0} />
-                </linearGradient>
-              </defs>
-              <CartesianGrid vertical={false} stroke="rgb(var(--border) / 0.5)" strokeDasharray="3 6" />
-              <XAxis
-                dataKey="t"
-                tickLine={false}
-                axisLine={false}
-                tick={{ fill: 'rgb(var(--text-muted))', fontSize: 10, fontFamily: '"JetBrains Mono", monospace' }}
-                interval="preserveStartEnd"
-                minTickGap={40}
-              />
-              <Tooltip content={<SignalTooltip wireless={wireless} />} cursor={{ stroke: 'rgb(var(--border-strong))', strokeWidth: 1 }} />
-              <Area
-                type="monotone"
-                dataKey="v"
-                stroke="#22D3EE"
-                strokeWidth={2}
-                fill="url(#backhaul-grad)"
-                dot={false}
-                animationDuration={900}
-                animationEasing="ease-out"
-              />
-            </AreaChart>
-          </ResponsiveContainer>
-        </motion.div>
-      </section>
+  const cell = 'flex min-w-0 flex-col gap-0.5'
+  const label = 'text-[10px] font-medium uppercase tracking-[0.06em] text-text-muted'
+  const value = 'truncate font-mono text-mono-sm font-semibold text-text-primary'
 
-      {/* Latencia al gateway */}
-      <section className="flex flex-col rounded-2xl border border-border bg-surface p-5 md:p-6 lg:col-span-5">
-        <SectionHeader title={t('routers.gatewayLatency')} />
-        <div className="mt-4 flex flex-1 flex-col items-center justify-center gap-4">
-          <LatencyGauge valueMs={backhaul.latencyMs} caption={t('routerDetail.latency.toHost', { host: '192.168.8.1' })} />
-          <div className="w-full">
-            <div className="mb-1 text-[10px] font-medium uppercase tracking-[0.06em] text-text-muted">{t('routerDetail.latency.24h')}</div>
-            <Sparkline data={ex.gatewayLatencySpark} width={560} height={48} color="#34D399" area className="w-full" />
-          </div>
-        </div>
-      </section>
-    </div>
+  return (
+    <section
+      className="grid grid-cols-2 items-center gap-x-6 gap-y-3 rounded-2xl border border-border bg-surface px-4 py-3.5 md:grid-cols-4 md:px-5 lg:col-span-12"
+      aria-label="Backhaul y latencia al gateway"
+    >
+      <div className={cell}>
+        <span className={`${label} flex items-center gap-1.5`}>
+          <Icon className="h-3.5 w-3.5 text-accent" strokeWidth={1.75} aria-hidden="true" />
+          Backhaul
+        </span>
+        <span className={value}>{backhaul.headline}</span>
+        <span className="truncate text-caption text-text-muted">
+          {wireless ? t('routerDetail.backhaul.wirelessLink') : t('routerDetail.backhaul.wiredLink')}
+        </span>
+      </div>
+      <div className={cell}>
+        <span className={`${label} flex items-center gap-1.5`}>
+          <Activity className="h-3.5 w-3.5 text-ok" strokeWidth={1.75} aria-hidden="true" />
+          {t('routers.gatewayLatency')}
+        </span>
+        <span className={value}>{latency}</span>
+        <span className="truncate text-caption text-text-muted">
+          {gwIp ? t('routerDetail.latency.toHost', { host: gwIp }) : ''}
+        </span>
+      </div>
+      <div className={cell}>
+        <span className={label}>{t('devices.colTraffic')}</span>
+        <span className={value}>↓ {ex.trafficNow.toFixed(1)} Mbps</span>
+        <span className="text-caption text-text-muted">WAN · LAN</span>
+      </div>
+      <div className={cell}>
+        <span className={label}>{t('routerDetail.info.lastReboot')}</span>
+        <span className={value}>{ex.lastReboot || '—'}</span>
+        <span className="text-caption text-text-muted">{ex.soc}</span>
+      </div>
+    </section>
   )
 }

+ 8 - 5
app/src/components/routers/PortPanel.tsx

@@ -34,7 +34,7 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
           initial={reduce ? false : { opacity: 0, y: 10 }}
           animate={{ opacity: 1, y: 0 }}
           transition={{ duration: 0.3, ease: 'easeOut', delay: 0.08 + index * 0.06 }}
-          className="group flex w-[84px] flex-col items-center"
+          className="group flex w-[84px] shrink-0 flex-col items-center"
           role="img"
           aria-label={aria}
         >
@@ -88,7 +88,9 @@ function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInf
             {port.up ? (
               <>
                 <div className="mt-0.5 w-full truncate text-caption font-medium text-text-primary">
-                  {port.connectedTo && port.deviceMac ? (
+                  {port.connectedTo && port.connectedTo === port.label ? (
+                    <span className="font-mono text-[10px] text-text-muted">{port.deviceMac ?? ''}</span>
+                  ) : port.connectedTo && port.deviceMac ? (
                     <Link
                       to={`/devices?q=${encodeURIComponent(port.deviceMac)}`}
                       className="transition-colors hover:text-accent hover:underline"
@@ -201,13 +203,14 @@ export function PortPanel({ router, extras, className }: { router: Router; extra
         {wirelessUplink && t('routerDetail.ports.wirelessUplink')}
       </p>
 
-      {/* Chasis */}
-      <div className="mt-4 flex flex-wrap items-start gap-x-4 gap-y-5 rounded-xl border border-border/70 bg-elevated/40 px-4 py-4">
+      {/* Chasis: TODAS las bocas en una sola horizontal (sin wrap); si no
+          caben (móvil, chasis largos), scroll horizontal en vez de apilar. */}
+      <div className="mt-4 flex flex-nowrap items-start gap-x-4 overflow-x-auto rounded-xl border border-border/70 bg-elevated/40 px-4 py-4">
         {wanPorts.map((p, i) => (
           <Jack key={p.id} port={p} index={i} wan={wan} />
         ))}
         {wanPorts.length > 0 && lanPorts.length > 0 && (
-          <div className="mx-1 hidden h-[104px] w-px self-center bg-border/70 sm:block" aria-hidden="true" />
+          <div className="mx-1 h-[104px] w-px shrink-0 self-center bg-border/70" aria-hidden="true" />
         )}
         {lanPorts.map((p, i) => (
           <Jack key={p.id} port={p} index={wanPorts.length + i} />

+ 8 - 2
app/src/components/routers/RadiosPorts.tsx

@@ -17,9 +17,14 @@ export function RadiosPorts({ router, extras }: { router: Router; extras?: Route
   const ex = extras ?? (isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS)
   const reduce = useReducedMotion()
 
+  // Equipos cableados (switches gestionados tipo RTLPlayground/KP-9000):
+  // sin radios no se muestra la sección WiFi ni estados vacíos (#291).
+  const hasRadios = ex.radios.length > 0
+
   return (
     <>
-      {/* Radios WiFi */}
+      {/* Radios WiFi (solo si el equipo tiene: switches cableados fuera) */}
+      {hasRadios && (
       <section className="rounded-2xl border border-border bg-surface p-5 md:p-6 lg:col-span-7">
         <SectionHeader title={t('routerDetail.radios.title')} />
         <div className="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
@@ -64,9 +69,10 @@ export function RadiosPorts({ router, extras }: { router: Router; extras?: Route
           ))}
         </div>
       </section>
+      )}
 
       {/* Puertos Ethernet (panel visual de bocas RJ45) */}
-      <PortPanel router={router} extras={extras} className="lg:col-span-5" />
+      <PortPanel router={router} extras={extras} className={hasRadios ? 'lg:col-span-5' : 'lg:col-span-12'} />
     </>
   )
 }

+ 4 - 4
app/src/data/DataProvider.tsx

@@ -174,7 +174,7 @@ export interface NetPulseApi extends NetPulseData {
    * server). El token rota en cada llamada (se muestra UNA vez); el comando
    * ya lleva el token nuevo. null si falló (demo siempre null).
    */
-  createAgentInstall: (slug: string) => Promise<{ install: string } | null>
+  createAgentInstall: (slug: string) => Promise<{ install: string; token?: string } | null>
 }
 
 // ---------------------------------------------------------------------------
@@ -886,7 +886,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
   }, [])
 
-  const createAgentInstall = useCallback(async (slug: string): Promise<{ install: string } | null> => {
+  const createAgentInstall = useCallback(async (slug: string): Promise<{ install: string; token?: string } | null> => {
     if (modeRef.current !== 'live') return null
     try {
       const res = await fetch('/api/agents', {
@@ -897,8 +897,8 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       })
       if (res.status === 401) redirectLogin()
       if (!res.ok) return null
-      const json = (await res.json()) as { install?: string }
-      return json.install ? { install: json.install } : null
+      const json = (await res.json()) as { install?: string; token?: string }
+      return json.install ? { install: json.install, token: json.token } : null
     } catch {
       return null
     }

+ 99 - 0
doc/BEACON.md

@@ -0,0 +1,99 @@
+# Beacon protocol v1.2 - embedded switches
+
+Canal UDP entre switches embebidos (8051 + uIP) y NetPulse. Tres tipos de
+datagrama, todos JSON ASCII de una línea, mismo socket de destino
+(`:5140` en el server), autenticados por el token del agente (salvo el
+announce). El emisor no tiene RTC: el server estampa la hora de llegada.
+
+## 1. Beacon periódico (unicast, pareado)
+
+- Cada 30 s (fijo en código) hacia `COLLECTOR_IP:5140`.
+- ~400-500 B, muy por debajo de UIP_BUFSIZE (2000).
+
+```json
+{"v":1,"seq":4271,"slug":"switch16","token":"<token>",
+ "ports":[{"n":1,"l":3,"tx":12345,"rx":678}, ...todas las bocas...],
+ "sfp":[{"n":9,"temp":34.5,"rxp":-12.1,"txp":-13.0}]}
+```
+
+- `v`: versión de esquema (1). `seq`: uint32 incremental con wrap.
+- `token`: el MISMO token del agente (kv sha256 en el server).
+- `ports`: SIEMPRE todas las bocas. `l`: 0 down · 1 10M · 2 100M · 3 1G ·
+  4 500M · 5 10G · 6 2.5G · 7 5G. `tx`/`rx`: tramas good acumuladas (u32).
+- `sfp`: opcional, solo bocas ópticas con DOM.
+
+## 2. Announce de descubrimiento (broadcast, sin parar)
+
+- Hasta estar pareado: broadcast `<subnet>.255:5140` cada ~60 s.
+- Token vacío + identidad. NetPulse lo lista como candidato y el admin
+  lo parea (slug + token + comando).
+
+```json
+{"v":1,"seq":7,"slug":"","token":"","dev":"KP-9000-9XHML-X",
+ "fw":"rtlplayground-v0.1.0","ports":[...]}
+```
+
+## 3. Eventos (inmediatos, no esperan al tick)
+
+Datagrama pequeño enviado EN CUANTO ocurre el hecho (mismo auth que el
+beacon). `ev` distingue el tipo:
+
+```json
+{"v":1,"ev":"loop","port":5,"mac":"AABBCCDDEEFF","seq":900,
+ "slug":"switch16","token":"<token>"}
+```
+
+- `loop`: bucle detectado (ver guardia abajo). `port` y `mac` implicados.
+- `port_down` / `port_up`: cambio de link en `port` (instantáneo, mejor
+  que esperar el delta del tick).
+- `port_disabled`: la guardia ha deshabilitado `port` (auto-protección).
+- `port_recovered`: re-enable tras cooldown.
+
+## Datagrama FDB (v1.2, cada 5 min)
+
+Tabla MAC completa en UN datagrama (~600 B con 30 MACs). Sustituye al
+scraper como fuente de FDB: con él, todo el switch habla por el beacon
+y el token tiene un único consumidor.
+
+```json
+{"v":1,"seq":4300,"slug":"switch16","token":"<token>",
+ "fdb":{"AABBCCDDEE01":"3","AABBCCDDEE02":"8"}}
+```
+
+- Puertos como número sin prefijo ("3"): el server los alinea con las
+  bocas (`lan3`) al construir el estado.
+- `{}` (objeto vacío presente) = sin entradas: estado real. Ausencia del
+  campo = este datagrama no toca la tabla.
+- El server conserva las bocas del último beacon periódico: el datagrama
+  FDB no viaja con ports y no borra nada.
+
+## Guardia de bucles - APLAZADA (decisión 27-Ago-2026)
+
+El RTL8372 no tiene STP, pero el mac-move es comportamiento LEGÍTIMO en
+redes con roaming WiFi (DAWN mueve clientes entre los puertos de los
+APs): un auto-disable tumbaría un AP en producción. Si algún día se
+recupera la idea, la restricción es innegociable:
+
+- SOLO alertar (`ev:"loop"`), JAMÁS deshabilitar puertos desde el
+  firmware.
+- Excluir del análisis las bocas de APs y uplink.
+- Prefiere la heurística de tormenta (delta de RxGood) al mac-move.
+
+Los eventos `port_disabled`/`port_recovered` quedan en la spec por si
+otras integraciones los usan, pero este firmware no los emitirá.
+
+## Comando de configuración (consola + Advanced Settings)
+
+```
+beacon <ip-netpulse> <slug> <token>     # pareo: unicast + token
+beacon off                               # apaga beacon y announce
+```
+
+Puerto destino (5140) y cadencia (30 s / 60 s announce) fijos en código.
+
+## Modelo de seguridad (decisión consciente v1)
+
+LAN de confianza: token en claro, sin HMAC (el 8051 no compensa SHA256
+por ahora). Mitigaciones: rate-limit por IP en el server, seq con wrap
+para detectar replay/reorden (se loguea), announce sin credenciales.
+Si algún día se endurece: HMAC truncado en un v2 con `v:2`.

+ 18 - 0
server-go/internal/adapters/agent.go

@@ -383,6 +383,24 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		}
 		if len(fd.Ports) > 0 {
 			out.ports = ethPortsToAdapter(fd.Ports)
+			// #291: los pushers externos declaran el puerto del FDB como
+			// número ("1") mientras sus bocas usan id "lan1". Normalizar
+			// para que el enriquecimiento del detalle (MAC→nombre por boca)
+			// y la topología casen ambas claves.
+			ids := map[string]bool{}
+			for _, ep := range out.ports {
+				ids[ep.ID] = true
+			}
+			if len(ids) > 0 {
+				for mac, port := range out.fdb {
+					if port == "wan" || ids[port] {
+						continue
+					}
+					if lan := "lan" + port; ids[lan] {
+						out.fdb[mac] = lan
+					}
+				}
+			}
 		}
 	}
 	// LuCI (issue #258): etiquetas de puertos/VLANs, fuente de nombres de

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

@@ -0,0 +1,56 @@
+// agent_fdb_test.go — #291: normalización del FDB de pushers externos.
+// El scraper del KP-9000 declara el puerto como número ("1") mientras sus
+// bocas usan id "lan1": polledFromAgent debe alinear las claves para que el
+// enriquecimiento del detalle (MAC→nombre por boca) case.
+package adapters
+
+import (
+	"context"
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestPolledFromAgentNormalizaFDBAPuertos(t *testing.T) {
+	l := NewLive(nil, nil, []RouterConfig{{ID: "switch16", Host: "192.168.1.6", Name: "Switch KP-9000"}}, nil)
+	payload := &probe.Payload{
+		Router: "switch16", Ts: 1, Version: "scraper-2.1",
+		Kind: "external", Interval: 300,
+		Data: probe.PayloadData{FDB: &probe.FDBData{
+			MACs: map[string]string{
+				"AA:BB:CC:DD:EE:01": "1",
+				"AA:BB:CC:DD:EE:02": "8",
+				"AA:BB:CC:DD:EE:03": "wan",
+				"AA:BB:CC:DD:EE:04": "lan3", // ya normalizado: se respeta
+			},
+			Ports: []probe.EthPort{
+				{ID: "lan1", Label: "uplink", Up: true, Speed: "1G"},
+				{ID: "lan3", Label: "rt3-entrada", Up: true, Speed: "2.5G"},
+				{ID: "lan8", Label: "citadel-02", Up: true, Speed: "1G"},
+			},
+		}},
+	}
+	p := l.polledFromAgent(l.routers[0], payload)
+	want := map[string]string{
+		"AA:BB:CC:DD:EE:01": "lan1",
+		"AA:BB:CC:DD:EE:02": "lan8",
+		"AA:BB:CC:DD:EE:03": "wan",
+		"AA:BB:CC:DD:EE:04": "lan3",
+	}
+	for mac, port := range want {
+		if got := p.fdb[mac]; got != port {
+			t.Fatalf("fdb[%s] = %q, want %q", mac, got, port)
+		}
+	}
+	// Sin bocas declaradas no se toca nada (FDB de routers SSH: lanN/wan ya).
+	p2 := l.polledFromAgent(l.routers[0], &probe.Payload{
+		Router: "switch16", Ts: 2, Version: "scraper-2.1",
+		Data: probe.PayloadData{FDB: &probe.FDBData{
+			MACs: map[string]string{"AA:BB:CC:DD:EE:01": "1"},
+		}},
+	})
+	if p2.fdb["AA:BB:CC:DD:EE:01"] != "1" {
+		t.Fatalf("sin puertos el FDB no debe reescribirse: %v", p2.fdb)
+	}
+	_ = context.Background()
+}

+ 209 - 7
server-go/internal/adapters/live.go

@@ -1532,11 +1532,31 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			}
 		}
 	}
+	// MACs de bridge de todos los routers sondeados: una boca de satélite
+	// que aprende una de ellas es un UPLINK (enlaza con otro equipo de red),
+	// y lo que aprende por ahí es el resto de la LAN en tránsito, no clientes
+	// locales. Sin esto, un switch agent-only (excepción de abajo) se
+	// atribuía toda la red vista por su uplink (#291).
+	brMacByRouter := map[string]bool{}
+	for _, pr := range polled {
+		if pr.brMac != "" {
+			brMacByRouter[pr.brMac] = true
+		}
+	}
 	for routerID, p := range polled {
 		if routerID == gwID {
 			continue
 		}
-		for mac := range p.fdb {
+		infraPorts := map[string]bool{}
+		for mac, port := range p.fdb {
+			if brMacByRouter[mac] {
+				infraPorts[port] = true
+			}
+		}
+		for mac, port := range p.fdb {
+			if infraPorts[port] {
+				continue // uplink: MACs en tránsito, no clientes de este equipo
+			}
 			if _, ok := seen[mac]; !ok {
 				if gwFDB[mac] && !p.cfg.AgentOnly {
 					continue // gateway bridge pasivo, no es cliente del satélite
@@ -2006,6 +2026,34 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 	// Mapa global MAC → lease + MAC de bridge → nombre de router
 	leaseMap := map[string]DhcpLease{}
 	routerByMac := map[string]string{}
+	// Clientes WiFi por MAC → AP que los sirve (#291): si la única MAC de
+	// una boca del switch es un cliente WiFi, el equipo ENCHUFADO es el AP,
+	// no el cliente. La atribución correcta de la boca es el AP.
+	wifiByMac := map[string]string{}
+	for _, polled := range polledAll {
+		apName := polled.cfg.Name
+		if apName == "" {
+			apName = polled.cfg.Host
+		}
+		for mac := range polled.wireless {
+			wifiByMac[mac] = apName
+		}
+	}
+	// Alias manuales (Settings > known_macs): fallback de nombre para MACs
+	// sin lease (estáticas, equipos sin DHCP), mismo criterio que la lista
+	// de dispositivos (#291: match MAC→nombre también en bocas de switch).
+	aliasByMac := map[string]string{}
+	if l.db != nil {
+		if rows, err := l.db.Query("SELECT mac, name FROM known_macs"); err == nil {
+			for rows.Next() {
+				var mac, name string
+				if rows.Scan(&mac, &name) == nil && name != "" {
+					aliasByMac[mac] = name
+				}
+			}
+			rows.Close()
+		}
+	}
 	for _, polled := range polledAll {
 		for _, le := range polled.leases {
 			if le.MAC != "" {
@@ -2057,15 +2105,66 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 			enriched = append(enriched, port)
 			continue
 		}
+		// 1.5) Cliente WiFi detrás de un AP: la boca del switch lleva al AP
+		// (el cliente viaja por su radio). Atribuir la boca al AP y señalar
+		// el cliente como "detrás" (#291). Guard de longitud PRIMERO: una
+		// boca up sin MACs aprendidas llega con all vacío.
+		if len(all) > 0 {
+			if ap, isWifi := wifiByMac[all[0]]; isWifi && allWifiOfOneAP(all, wifiByMac) {
+				port.ConnectedTo = ap
+				port.DeviceMac = all[0]
+				if lease, ok := leaseMap[all[0]]; ok && lease.Hostname != "" {
+					port.Detail = "AP · " + lease.Hostname + " por WiFi detrás"
+				} else {
+					port.Detail = "AP · cliente WiFi detrás"
+				}
+				enriched = append(enriched, port)
+				continue
+			}
+		}
 		// 2) Un solo dispositivo final
 		if len(all) == 1 {
 			mac := all[0]
 			lease, ok := leaseMap[mac]
+			// MAC de virtualización (QEMU/KVM, Proxmox, VMware, Hyper-V):
+			// el equipo enchufado es el hypervisor; lo aprendido es una
+			// NIC virtual de una VM/CT (#291).
+			if isVirtualMAC(mac) {
+				port.ConnectedTo = "Hypervisor"
+				port.DeviceMac = mac
+				port.Detail = virtualDetail(mac, leaseMap, aliasByMac)
+				enriched = append(enriched, port)
+				continue
+			}
+			// Label curada que no coincide con el dispositivo resuelto:
+			// - si el dispositivo tiene nombre real (lease/alias), la label
+			//   nombra la infraestructura física y lo aprendido está DETRÁS
+			//   (p. ej. ngxpm detrás de citadel-02);
+			// - si el dispositivo no tiene nombre mejor que su MAC, la label
+			//   ES su nombre (bautizada a mano: "hikvision"), y la MAC queda
+			//   como detalle.
+			if isCuratedLabel(port) && !labelMatchesDevice(port.Label, mac, leaseMap, aliasByMac) {
+				name := deviceDisplayName(mac, leaseMap, aliasByMac)
+				port.DeviceMac = mac
+				if name != mac {
+					port.ConnectedTo = name + " · detrás de " + port.Label
+				} else {
+					port.ConnectedTo = port.Label
+					port.Detail = "MAC " + mac
+				}
+				if lease, ok := leaseMap[mac]; ok && lease.IP != "" {
+					port.Detail = lease.IP
+				}
+				enriched = append(enriched, port)
+				continue
+			}
 			switch {
 			case ok && lease.Hostname != "":
 				port.ConnectedTo = lease.Hostname
 			case ok && lease.IP != "":
 				port.ConnectedTo = lease.IP
+			case aliasByMac[mac] != "":
+				port.ConnectedTo = aliasByMac[mac]
 			default:
 				port.ConnectedTo = mac
 			}
@@ -2076,8 +2175,18 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 			enriched = append(enriched, port)
 			continue
 		}
-		// 3) Varios: el vecino es un switch/hub
+		// 3) Varios: el vecino es un switch/hub/hipervisor
 		if len(all) > 1 {
+			// Muchas MACs detrás de una boca = agregación (hipervisor Proxmox
+			// con CTs, switch tonto): nombrar UN CT al azar engaña (la MAC es
+			// virtual, no el equipo enchufado). La label curada del puerto ya
+			// identifica el físico; aquí se cuenta lo que hay detrás (#291).
+			if len(all) > 3 {
+				port.ConnectedTo = fmt.Sprintf("%d dispositivos", len(all))
+				port.Detail = "agregación · ¿hipervisor o switch?"
+				enriched = append(enriched, port)
+				continue
+			}
 			// Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
 			// es mejor pista que el hostname DHCP.
 			if nb := lldpNeighborOnPort(p.lldp, port.ID); nb != nil && nb.displayName() != "" {
@@ -2097,12 +2206,25 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 					break
 				}
 			}
+			if infraMac == "" {
+				// Sin hostname DHCP: primer alias manual como pista (#291).
+				for _, mac := range all {
+					if aliasByMac[mac] != "" {
+						infraMac = mac
+						break
+					}
+				}
+			}
 			if infraMac != "" {
-				lease := leaseMap[infraMac]
-				port.ConnectedTo = lease.Hostname
-				port.DeviceMac = infraMac
-				if lease.IP != "" {
-					port.Detail = lease.IP
+				if lease, ok := leaseMap[infraMac]; ok && lease.Hostname != "" {
+					port.ConnectedTo = lease.Hostname
+					port.DeviceMac = infraMac
+					if lease.IP != "" {
+						port.Detail = lease.IP
+					}
+				} else if alias := aliasByMac[infraMac]; alias != "" {
+					port.ConnectedTo = alias
+					port.DeviceMac = infraMac
 				}
 			} else {
 				port.ConnectedTo = "Switch"
@@ -2819,3 +2941,83 @@ func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
 	out.Available = true
 	return &out, nil
 }
+
+// allWifiOfOneAP: ¿todas las MACs de la boca son clientes WiFi del mismo AP?
+func allWifiOfOneAP(macs []string, wifiByMac map[string]string) bool {
+	if len(macs) == 0 {
+		return false
+	}
+	ap := wifiByMac[macs[0]]
+	if ap == "" {
+		return false
+	}
+	for _, m := range macs[1:] {
+		if wifiByMac[m] != ap {
+			return false
+		}
+	}
+	return true
+}
+
+// prefijos OUI de virtualización: la MAC aprendida es una NIC virtual.
+var virtualMACPrefixes = []string{
+	"52:54:00", // QEMU/KVM (Proxmox VMs por defecto)
+	"BC:24:11", // Proxmox Server Solutions
+	"00:15:5D", // Microsoft Hyper-V
+	"00:50:56", // VMware ESX
+	"00:1C:14", // VMware
+	"08:00:27", // VirtualBox
+}
+
+func isVirtualMAC(mac string) bool {
+	m := strings.ToUpper(mac)
+	for _, p := range virtualMACPrefixes {
+		if strings.HasPrefix(m, p) {
+			return true
+		}
+	}
+	return false
+}
+
+// virtualDetail: nombre legible de la VM/CT detrás del hypervisor.
+func virtualDetail(mac string, leases map[string]DhcpLease, aliases map[string]string) string {
+	if n := deviceDisplayName(mac, leases, aliases); n != mac {
+		return n + " (VM/CT detrás)"
+	}
+	return "VM/CT detrás"
+}
+
+// isCuratedLabel: label renombrada a mano (no el "Port N" por defecto).
+func isCuratedLabel(port EthPort) bool {
+	if port.Label == "" {
+		return false
+	}
+	n := strings.TrimPrefix(port.Label, "Port ")
+	if n == port.Label {
+		return true // no sigue el patrón por defecto
+	}
+	_, err := strconv.Atoi(n)
+	return err != nil // "Port <número>" = default; cualquier otra cosa, curada
+}
+
+// labelMatchesDevice: ¿la label curada nombra al propio dispositivo
+// aprendido (p. ej. "hikvision") y no a la infraestructura que hay delante?
+func labelMatchesDevice(label, mac string, leases map[string]DhcpLease, aliases map[string]string) bool {
+	name := strings.ToLower(deviceDisplayName(mac, leases, aliases))
+	l := strings.ToLower(label)
+	if name == "" || l == "" {
+		return false
+	}
+	return strings.Contains(name, l) || strings.Contains(l, name)
+}
+
+// deviceDisplayName: hostname de lease > alias > MAC.
+func deviceDisplayName(mac string, leases map[string]DhcpLease, aliases map[string]string) string {
+	if le, ok := leases[mac]; ok && le.Hostname != "" {
+		return le.Hostname
+	}
+	if a := aliases[mac]; a != "" {
+		return a
+	}
+	return mac
+}

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

@@ -62,7 +62,8 @@ type Config struct {
 	GithubRepo    string
 	GithubToken   string
 	ServerRoot    string
-	AutoRearm     bool // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
+	AutoRearm     bool   // NETPULSE_AUTO_REARM=1: supervisor rearma agentes caídos
+	BeaconListen  string // NETPULSE_BEACON_LISTEN: socket UDP de beacons embebidos (#291); "" = off, p. ej. ":5140"
 	Onbox         bool // NETPULSE_ONBOX=1: modo on-box (Fase 9 — config UCI, bootstrap AUTH_PASS)
 }
 
@@ -283,6 +284,13 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 	}
 	githubToken := env["GITHUB_TOKEN"]
 
+	// NETPULSE_BEACON_LISTEN: opcional. Dirección UDP para el listener de
+	// beacons de pushers embebidos (#291); "" u "off" lo deshabilitan.
+	beaconListen := strings.TrimSpace(env["NETPULSE_BEACON_LISTEN"])
+	if beaconListen == "off" || beaconListen == "0" {
+		beaconListen = ""
+	}
+
 	// ADGUARD_*: cliente estándar solo si hay URL válida
 	var adguard *AdGuard
 	if v, ok := env["ADGUARD_URL"]; ok && v != "" {
@@ -397,6 +405,7 @@ func Load(env map[string]string, serverRoot string) (*Config, error) {
 		GithubToken:   githubToken,
 		ServerRoot:    serverRoot,
 		AutoRearm:     autoRearm,
+		BeaconListen:  beaconListen,
 		Onbox:         onbox,
 	}, nil
 }

+ 460 - 0
server-go/internal/httpapi/beacon.go

@@ -0,0 +1,460 @@
+// beacon.go — listener UDP de beacons de dispositivos embebidos (#291).
+//
+// Los pushers embebidos sin Linux (RTLPlayground en el KP-9000) emiten un
+// datagrama UDP cada 30 s con sus stats: payload NEUTRO (spec v1 documentada
+// en el repo del firmware), sin depender de NetPulse. Este listener valida
+// el token del agente (mismo kv sha256 que el ingest HTTP), estampa el ts de
+// llegada (el emisor no tiene RTC) y alimenta el MISMO registry: el agente
+// queda kind=external, interval=30 y fresh con cada beacon.
+//
+// La tabla MAC/FDB NO viaja en el beacon (crece con la red): se omite en el
+// payload y el merge anti-parpadeo de polledFromAgent conserva la última
+// buena del scraper. Reparto: beacon = estado/counters a 30 s; scraper =
+// FDB a 5 min.
+//
+// Seguridad (decisión consciente v1): token en claro y sin firma (modelo LAN
+// de confianza; ver #291). Mitigaciones: rate limit por IP origen (mismo
+// modelo que el ingest HTTP) y log de seq que retrocede (replay/reorden).
+package httpapi
+
+import (
+	"encoding/json"
+	"fmt"
+	"log"
+	"net"
+	"sort"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+// beaconPort: una boca del beacon. n = número 1..9; l = código de link
+// (0 down · 1 10M · 2 100M · 3 1G · 4 500M · 5 10G · 6 2.5G · 7 5G);
+// tx/rx = contadores acumulados de tramas good (uint32, decimal).
+type beaconPort struct {
+	N  int    `json:"n"`
+	L  int    `json:"l"`
+	Tx uint32 `json:"tx"`
+	Rx uint32 `json:"rx"`
+}
+
+// beaconPacket: spec v1 del datagrama (una línea JSON ASCII, ~400 B).
+// Dev/Fw son opcionales: los lleva el ANUNCIO de descubrimiento (broadcast,
+// sin token) para que el switch pueda encontrarse antes del pareado.
+// Ev (con Port/Mac) convierte el datagrama en EVENTO inmediato (spec v1.1:
+// loop, port_up, port_down, port_disabled, port_recovered).
+type beaconPacket struct {
+	V     int          `json:"v"` // versión de esquema; solo se acepta 1
+	Seq   uint32       `json:"seq"`
+	Slug  string       `json:"slug"`
+	Token string       `json:"token"`
+	Dev   string       `json:"dev,omitempty"`
+	Fw    string       `json:"fw,omitempty"`
+	Ev    string       `json:"ev,omitempty"`
+	Port  int          `json:"port,omitempty"`
+	Mac   string       `json:"mac,omitempty"`
+	Ports []beaconPort `json:"ports"`
+	// FDB (v1.2): datagrama dedicado de tabla MAC cada 5 min. nil = no va
+	// en este datagrama (el beacon periódico no la lleva); {} = sin entradas
+	// (estado real). Valores = puerto ("3", sin prefijo lan: la
+	// normalización de polledFromAgent los alinea con las bocas).
+	FDB map[string]string `json:"fdb,omitempty"`
+}
+
+// beaconCandidate: un switch embebido anunciándose por broadcast SIN parar
+// (token vacío). Se expone al admin para completar el pareado (#291).
+type beaconCandidate struct {
+	IP       string `json:"ip"`
+	Dev      string `json:"dev"`
+	Fw       string `json:"fw,omitempty"`
+	Ports    int    `json:"ports,omitempty"`
+	LastSeen int64  `json:"lastSeen"` // unix segundos
+}
+
+// beaconCandidateTTL: un anuncio sin refresco caduca a los 10 min.
+const beaconCandidateTTL = 10 * time.Minute
+
+// beaconLinkSpeed traduce el código de link a la etiqueta de velocidad del
+// resto de la app (0 = down).
+var beaconLinkSpeed = map[int]string{
+	0: "",
+	1: "10M",
+	2: "100M",
+	3: "1G",
+	4: "500M",
+	5: "10G",
+	6: "2.5G",
+	7: "5G",
+}
+
+const (
+	beaconVersion     = "beacon-1.0"
+	beaconIntervalSec = 30
+	// UIP_BUFSIZE del emisor es 2000: el datagrama no puede pasar de ahí
+	// (y de todos modos el MTU lo limita a ~1500).
+	beaconMaxDatagram = 2048
+)
+
+// ingestBeacon valida y aplica un datagrama recibido. src es la IP origen
+// (sin puerto) para el rate limit y los logs. Fallos se ignoran con log: el
+// beacon es best-effort, el emisor reintenta en la próxima cadencia.
+func (s *server) ingestBeacon(src string, raw []byte) {
+	if len(raw) == 0 || len(raw) > beaconMaxDatagram {
+		return
+	}
+	var p beaconPacket
+	if err := json.Unmarshal(raw, &p); err != nil {
+		log.Printf("[netpulse:beacon] datagrama malformado desde %s (%d B)", src, len(raw))
+		return
+	}
+	if p.V != 1 {
+		log.Printf("[netpulse:beacon] esquema v%d no soportado desde %s", p.V, src)
+		return
+	}
+	// ANUNCIO de descubrimiento (#291): broadcast sin token pero con
+	// identidad de firmware (dev/fw). No es un agente: queda como candidato
+	// hasta que el admin lo parea (POST /api/agents + beacon <ip> <token>).
+	if p.Token == "" && p.Dev != "" {
+		if ok, _ := s.ingestLimit.allow(src); ok {
+			s.recordBeaconCandidate(src, p)
+		}
+		return
+	}
+	if !agentSlugRe.MatchString(p.Slug) {
+		return
+	}
+	// Rate limit por IP origen, mismo modelo que el ingest HTTP.
+	if ok, _ := s.ingestLimit.allow(src); !ok {
+		return
+	}
+	if !s.checkAgentToken(p.Slug, p.Token) {
+		log.Printf("[netpulse:beacon] token inválido para %s (origen %s)", p.Slug, src)
+		return
+	}
+	// Beacon validado: si esa IP tenía un candidato pendiente, ya está parado.
+	s.dropBeaconCandidate(src)
+	if s.cfg != nil && s.cfg.DemoMode {
+		return
+	}
+	if s.agents == nil {
+		return
+	}
+
+	// EVENTO inmediato (spec v1.1): no lleva estado, solo la alerta. No pasa
+	// por el payload (un evento sin ports borraría las bocas del registry).
+	if p.Ev != "" {
+		s.handleBeaconEvent(p)
+		s.beaconSeqNote(p.Slug, p.Seq)
+		return
+	}
+
+	// Datagrama FDB (v1.2, cada 5 min): solo tabla MAC. Las bocas viajan por
+	// el beacon periódico; aquí se conservan las últimas conocidas para no
+	// borrarlas, y la tabla MAC se sustituye entera ({} = sin entradas).
+	if p.FDB != nil && len(p.Ports) == 0 {
+		ports := []probe.EthPort{}
+		if prev, okPrev := s.agents.StalePayload(p.Slug); okPrev && prev != nil && prev.Data.FDB != nil {
+			ports = prev.Data.FDB.Ports
+		}
+		// MACs sin separadores ("AABBCCDDEEFF") → formato canónico con dos
+		// puntos; las irrecuperables se descartan (firmware razonable).
+		macs := make(map[string]string, len(p.FDB))
+		for mac, port := range p.FDB {
+			if norm := normalizeBeaconMAC(mac); norm != "" {
+				macs[norm] = port
+			}
+		}
+		fdbPayload := &probe.Payload{
+			Router: p.Slug, Ts: time.Now().Unix(), Version: beaconVersion,
+			Kind: "external", Interval: beaconIntervalSec,
+			Data: probe.PayloadData{FDB: &probe.FDBData{MACs: macs, Ports: ports}},
+		}
+		s.agents.Ingest(fdbPayload)
+		s.persistAgentState(p.Slug, s.agents.Snapshot(p.Slug))
+		s.beaconSeqNote(p.Slug, p.Seq)
+		return
+	}
+
+	// Puertos → fdb.ports. El beacon viaja sin labels (ahorro de bytes en
+	// el 8051): se reinyectan los ÚLTIMOS labels conocidos del scraper para
+	// que los nombres (v2.1) no se pierdan entre push y push (#291).
+	labels := s.lastPortLabels(p.Slug)
+	ports := make([]probe.EthPort, 0, len(p.Ports))
+	for _, bp := range p.Ports {
+		if bp.N < 1 || bp.N > 32 {
+			continue
+		}
+		id := fmt.Sprintf("lan%d", bp.N)
+		ep := probe.EthPort{ID: id, Label: fmt.Sprintf("Port %d", bp.N)}
+		if l, ok := labels[id]; ok && l != "" {
+			ep.Label = l
+		}
+		if sp, ok := beaconLinkSpeed[bp.L]; ok && bp.L != 0 {
+			ep.Up = true
+			ep.Speed = sp
+		}
+		ports = append(ports, ep)
+	}
+	// El beacon no sondea MACs: viaja con la ÚLTIMA tabla conocida (del
+	// datagrama FDB) en vez de nil. Así el estado persistido sobrevive a los
+	// reinicios del server (restore con MACs) y no hay ventana de 5 min sin
+	// atribución tras cada arranque. Un FDB real vacío sigue llegando como {}
+	// (estado) y nunca como nil (ausencia).
+	var macs map[string]string
+	if prev, okPrev := s.agents.StalePayload(p.Slug); okPrev && prev != nil && prev.Data.FDB != nil {
+		macs = prev.Data.FDB.MACs
+	}
+	pl := &probe.Payload{
+		Router:   p.Slug,
+		Ts:       time.Now().Unix(),
+		Version:  beaconVersion,
+		Kind:     "external",
+		Interval: beaconIntervalSec,
+		Data:     probe.PayloadData{FDB: &probe.FDBData{MACs: macs, Ports: ports}},
+	}
+	// Fallback de cambios de link por delta entre beacons (#291): si el
+	// firmware no manda eventos, el cambio se detecta comparando el payload
+	// anterior. Con eventos, el título idéntico hace que el dedup del engine
+	// colapse el duplicado. Solo con datagramas que traen bocas (el FDB
+	// dedicado repite las anteriores: no hay cambio que evaluar).
+	if len(p.Ports) > 0 {
+		if prev, okPrev := s.agents.StalePayload(p.Slug); okPrev && prev != nil && prev.Data.FDB != nil {
+			was := map[string]bool{}
+			for _, ep := range prev.Data.FDB.Ports {
+				was[ep.ID] = ep.Up
+			}
+			for _, np := range ports {
+				if before, ok := was[np.ID]; ok && before != np.Up {
+					s.emitPortLinkChange(p.Slug, np.Label, np.Up)
+				}
+			}
+		}
+	}
+	s.agents.Ingest(pl)
+	s.persistAgentState(p.Slug, s.agents.Snapshot(p.Slug))
+	s.beaconSeqNote(p.Slug, p.Seq)
+}
+
+// handleBeaconEvent traduce un evento del firmware a alertas del feed (#291).
+func (s *server) handleBeaconEvent(p beaconPacket) {
+	eng := s.alertsEngine()
+	if eng == nil {
+		return
+	}
+	labels := s.lastPortLabels(p.Slug)
+	portName := fmt.Sprintf("boca %d", p.Port)
+	if l := labels[fmt.Sprintf("lan%d", p.Port)]; l != "" {
+		portName = fmt.Sprintf("%s (boca %d)", l, p.Port)
+	}
+	id := fmt.Sprintf("beacon-%s-%s-%d-%d", p.Ev, p.Slug, p.Port, time.Now().UnixMilli())
+	ev := alerts.AlertEvent{
+		ID: id, Category: alerts.CatSystem, Urgent: false,
+		Severity: "warn", Time: "ahora mismo", RouterID: p.Slug,
+	}
+	switch p.Ev {
+	case "loop":
+		ev.Urgent = true
+		ev.Title = "Bucle detectado en " + portName
+		ev.Description = fmt.Sprintf(
+			"La guardia del switch ha detectado la MAC %s en dos bocas y ha deshabilitado %s",
+			p.Mac, portName)
+	case "port_disabled":
+		ev.Title = "Boca deshabilitada: " + portName
+		ev.Description = "Desactivada por la guardia de bucles; se reintentará en 5 min (máx. 3 veces)"
+	case "port_recovered":
+		ev.Severity = "ok"
+		ev.Title = "Boca re-habilitada: " + portName
+		ev.Description = "La guardia de bucles ha vuelto a habilitar la boca"
+	case "port_down":
+		ev.Title = "Link caído en " + portName
+		ev.Description = "El beacon del switch reporta pérdida de link"
+	case "port_up":
+		ev.Severity = "ok"
+		ev.Title = "Link restablecido en " + portName
+		ev.Description = "El beacon del switch reporta link activo"
+	default:
+		log.Printf("[netpulse:beacon] evento desconocido %q de %s", p.Ev, p.Slug)
+		return
+	}
+	eng.Emit(ev)
+}
+
+// emitPortLinkChange: alerta de cambio de link detectada por delta (#291).
+// Mismos títulos que los eventos para que el dedup colapse duplicados.
+func (s *server) emitPortLinkChange(slug, label string, up bool) {
+	eng := s.alertsEngine()
+	if eng == nil {
+		return
+	}
+	name := label
+	if name == "" {
+		name = "una boca"
+	}
+	var ev alerts.AlertEvent
+	if up {
+		ev = alerts.AlertEvent{
+			ID: fmt.Sprintf("beacon-port-up-%s-%d", slug, time.Now().UnixMilli()),
+			Category: alerts.CatSystem, Severity: "ok", Time: "ahora mismo",
+			RouterID: slug, Title: "Link restablecido en " + name,
+			Description: "Detectado por el cambio entre beacons",
+		}
+	} else {
+		ev = alerts.AlertEvent{
+			ID: fmt.Sprintf("beacon-port-down-%s-%d", slug, time.Now().UnixMilli()),
+			Category: alerts.CatSystem, Severity: "warn", Time: "ahora mismo",
+			RouterID: slug, Title: "Link caído en " + name,
+			Description: "Detectado por el cambio entre beacons",
+		}
+	}
+	eng.Emit(ev)
+}
+
+// alertsEngine devuelve el motor de alertas del adapter (nil si no hay).
+func (s *server) alertsEngine() *alerts.Engine {
+	if s.adapter == nil {
+		return nil
+	}
+	return s.adapter.AlertsEngine()
+}
+
+// lastPortLabels extrae {id: label} del último payload conocido del slug
+// (el del scraper, que viaja con nombres desde v2.1). Usado para enriquecer
+// los puertos del beacon, que viajan sin labels.
+func (s *server) lastPortLabels(slug string) map[string]string {
+	out := map[string]string{}
+	if s.agents == nil {
+		return out
+	}
+	st, ok := s.agents.StalePayload(slug)
+	if !ok || st == nil || st.Data.FDB == nil {
+		return out
+	}
+	for _, p := range st.Data.FDB.Ports {
+		if p.Label != "" {
+			out[p.ID] = p.Label
+		}
+	}
+	return out
+}
+
+// beaconSeqNote registra el seq por slug: un salto distinto de +1 indica
+// pérdida, reorden o replay. Acepta siempre (el beacon es idempotente); el
+// salto queda logueado para diagnóstico.
+func (s *server) beaconSeqNote(slug string, seq uint32) {
+	s.beaconSeqMu.Lock()
+	old, had := s.beaconSeq[slug]
+	if s.beaconSeq == nil {
+		s.beaconSeq = map[string]uint32{}
+	}
+	if had && seq != old+1 {
+		log.Printf("[netpulse:beacon] %s: seq %d tras %d (pérdida, reorden o replay)", slug, seq, old)
+	}
+	s.beaconSeq[slug] = seq
+	s.beaconSeqMu.Unlock()
+
+	// Firma de reboot (regalo del firmware): el seq arranca en 1 tras el
+	// boot, así que un salto a 1 (o 0) desde uno mayor = reinicio del
+	// switch. El wrap de uint32 daría el mismo salto una vez cada 136 años.
+	if had && seq <= 1 && old > 1 {
+		if eng := s.alertsEngine(); eng != nil {
+			eng.Emit(alerts.AlertEvent{
+				ID:         fmt.Sprintf("beacon-reboot-%s-%d", slug, time.Now().UnixMilli()),
+				Category:   alerts.CatSystem, Severity: "info", Time: "ahora mismo",
+				RouterID:   slug, Title: "Switch reiniciado",
+				Description: fmt.Sprintf("El contador de beacons de %s volvió a empezar (seq %d tras %d): el switch ha arrancado de nuevo", slug, seq, old),
+			})
+		}
+	}
+}
+
+// startBeaconListener abre el socket UDP y sirve beacons hasta que el
+// proceso termine (o se cierre el conn). Devuelve la dirección bindeada
+// (útil con :0 en tests).
+func (s *server) startBeaconListener(addr string) (net.Addr, error) {
+	if s.agents == nil {
+		return nil, fmt.Errorf("sin registry de agentes")
+	}
+	pc, err := net.ListenPacket("udp", addr)
+	if err != nil {
+		return nil, err
+	}
+	s.beaconConn = pc
+	go func() {
+		buf := make([]byte, beaconMaxDatagram)
+		for {
+			n, src, err := pc.ReadFrom(buf)
+			if err != nil {
+				return // socket cerrado
+			}
+			if src == nil {
+				continue
+			}
+			host, _, splitErr := net.SplitHostPort(src.String())
+			if splitErr != nil {
+				host = src.String()
+			}
+			s.ingestBeacon(host, buf[:n])
+		}
+	}()
+	return pc.LocalAddr(), nil
+}
+
+// normalizeBeaconMAC: el firmware envía las MAC en MAYÚSCULAS sin
+// separadores ("AABBCCDDEEFF"); el resto de la app (leases, wifi, FDB,
+// enriquecimiento) usa "AA:BB:CC:DD:EE:FF". Devuelve "" si no es una MAC.
+func normalizeBeaconMAC(mac string) string {
+	clean := strings.ToUpper(strings.TrimSpace(mac))
+	if len(clean) == 12 && !strings.Contains(clean, ":") {
+		var b strings.Builder
+		for i := 0; i < 12; i += 2 {
+			if i > 0 {
+				b.WriteByte(':')
+			}
+			b.WriteString(clean[i : i+2])
+		}
+		return b.String()
+	}
+	if len(clean) == 17 && strings.Count(clean, ":") == 5 {
+		return clean
+	}
+	return ""
+}
+
+// recordBeaconCandidate guarda/refresca un anuncio de descubrimiento (#291).
+func (s *server) recordBeaconCandidate(src string, p beaconPacket) {
+	s.beaconCandMu.Lock()
+	defer s.beaconCandMu.Unlock()
+	if s.beaconCand == nil {
+		s.beaconCand = map[string]beaconCandidate{}
+	}
+	s.beaconCand[src] = beaconCandidate{
+		IP: src, Dev: p.Dev, Fw: p.Fw, Ports: len(p.Ports),
+		LastSeen: time.Now().Unix(),
+	}
+}
+
+// dropBeaconCandidate elimina el candidato de una IP (beacon validado).
+func (s *server) dropBeaconCandidate(src string) {
+	s.beaconCandMu.Lock()
+	defer s.beaconCandMu.Unlock()
+	delete(s.beaconCand, src)
+}
+
+// beaconCandidates lista los candidatos vivos (TTL), ordenados por IP.
+func (s *server) beaconCandidates() []beaconCandidate {
+	s.beaconCandMu.Lock()
+	defer s.beaconCandMu.Unlock()
+	out := []beaconCandidate{}
+	now := time.Now()
+	for ip, c := range s.beaconCand {
+		if now.Sub(time.Unix(c.LastSeen, 0)) > beaconCandidateTTL {
+			delete(s.beaconCand, ip)
+			continue
+		}
+		out = append(out, c)
+	}
+	sort.Slice(out, func(i, j int) bool { return out[i].IP < out[j].IP })
+	return out
+}

+ 339 - 0
server-go/internal/httpapi/beacon_test.go

@@ -0,0 +1,339 @@
+// beacon_test.go — #291: listener UDP de beacons de pushers embebidos.
+// Tests internos (package httpapi) para construir un *server mínimo con
+// db + registry y ejercitar ingestBeacon/startBeaconListener directamente.
+package httpapi
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+	"fmt"
+	"net"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+	"github.com/gnacho/netpulse/server-go/internal/adapters"
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+	"github.com/gnacho/netpulse/server-go/internal/config"
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// newBeaconTestServer: server mínimo (db + registry + rate limit) con el
+// token del agente "switch16" ya registrado en kv.
+func newBeaconTestServer(t *testing.T) (*server, string) {
+	t.Helper()
+	dataDir := t.TempDir()
+	cfg, err := config.Load(map[string]string{
+		"AUTH_USER": "admin", "AUTH_PASS": "test123456",
+		"DEMO_MODE": "0", "DATA_DIR": dataDir, "NODE_ENV": "test",
+	}, dataDir)
+	if err != nil {
+		t.Fatalf("config: %v", err)
+	}
+	d, err := db.Open(dataDir)
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	token := "beacontoken1234567890abcdef"
+	sum := sha256.Sum256([]byte(token))
+	if _, err := d.Exec("INSERT INTO kv (key, value) VALUES (?, ?)",
+		agentTokenKey("switch16"), hex.EncodeToString(sum[:])); err != nil {
+		t.Fatalf("token kv: %v", err)
+	}
+	eng := alerts.New(d, nil)
+	return &server{
+		cfg:         cfg,
+		db:          d,
+		agents:      adapters.NewAgentRegistry(90 * time.Second),
+		ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
+		adapter:     adapters.NewDemo(eng),
+	}, token
+}
+
+func sendUDP(t *testing.T, addr net.Addr, payload string) {
+	t.Helper()
+	c, err := net.Dial("udp", addr.String())
+	if err != nil {
+		t.Fatalf("dial: %v", err)
+	}
+	defer c.Close()
+	if _, err := c.Write([]byte(payload)); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+}
+
+func waitFresh(t *testing.T, s *server, slug string) *probe.Payload {
+	t.Helper()
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		if p, ok := s.agents.Fresh(slug); ok && p.Version == beaconVersion {
+			return p
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	t.Fatal("el beacon no dejó el agente fresh")
+	return nil
+}
+
+// Un beacon válido actualiza el registry: fresh, kind external, interval 30,
+// versión beacon-1.0 y puertos mapeados (up + velocidad, labels enriquecidos
+// desde el último push del scraper).
+func TestBeaconValidIngestOverUDP(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+
+	// Estado previo "scraper": MACs + puertos con labels (v2.1).
+	s.agents.Ingest(&probe.Payload{
+		Router: "switch16", Ts: time.Now().Unix() - 60, Version: "scraper-2.1",
+		Kind: "external", Interval: 300,
+		Data: probe.PayloadData{FDB: &probe.FDBData{
+			MACs: map[string]string{"AA:BB:CC:DD:EE:FF": "1"},
+			Ports: []probe.EthPort{
+				{ID: "lan1", Label: "uplink", Up: true, Speed: "1G"},
+				{ID: "lan2", Label: "hikvision", Up: true, Speed: "100M"},
+			},
+		}},
+	})
+
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":7,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3,"tx":10,"rx":20},{"n":2,"l":0,"tx":0,"rx":0}]}`,
+		token))
+
+	p := waitFresh(t, s, "switch16")
+	if p.Version != "beacon-1.0" || p.Kind != "external" || p.Interval != 30 {
+		t.Fatalf("payload: version=%q kind=%q interval=%d", p.Version, p.Kind, p.Interval)
+	}
+	if p.Data.FDB == nil || len(p.Data.FDB.Ports) != 2 {
+		t.Fatalf("fdb.ports: %+v", p.Data.FDB)
+	}
+	p1, p2 := p.Data.FDB.Ports[0], p.Data.FDB.Ports[1]
+	if !p1.Up || p1.Speed != "1G" || p1.Label != "uplink" {
+		t.Fatalf("puerto 1: %+v (label del scraper perdido)", p1)
+	}
+	if p2.Up || p2.Label != "hikvision" {
+		t.Fatalf("puerto 2: %+v", p2)
+	}
+	// El estado persistido en kv también lleva el payload del beacon.
+	var raw string
+	if err := s.db.QueryRow("SELECT value FROM kv WHERE key = ?", agentStateKey("switch16")).Scan(&raw); err != nil {
+		t.Fatalf("persist: %v", err)
+	}
+	if !strings.Contains(raw, "beacon-1.0") {
+		t.Fatalf("kv sin el estado del beacon: %.80s", raw)
+	}
+}
+
+// Token inválido, esquema distinto de 1 y JSON roto: sin efecto en el
+// registry (el agente NO queda fresh).
+func TestBeaconRejectsBadPackets(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, `{"v":1,"seq":1,"slug":"switch16","token":"wrong","ports":[]}`)
+	sendUDP(t, addr, fmt.Sprintf(`{"v":2,"seq":1,"slug":"switch16","token":"%s","ports":[]}`, token))
+	sendUDP(t, addr, `{no-json`)
+	sendUDP(t, addr, fmt.Sprintf(`{"v":1,"seq":2,"slug":"BAD slug","token":"%s","ports":[]}`, token))
+
+	deadline := time.Now().Add(1 * time.Second)
+	for time.Now().Before(deadline) {
+		if _, ok := s.agents.Fresh("switch16"); ok {
+			t.Fatal("un paquete rechazado dejó el agente fresh")
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+}
+
+// El anuncio de descubrimiento (broadcast sin token, con dev/fw) queda como
+// candidato; un beacon VALIDADO desde esa IP lo limpia (#291).
+func TestBeaconAnnounceBecomesCandidate(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, `{"v":1,"seq":1,"slug":"","token":"","dev":"KP-9000-9XHML-X","fw":"rtlplayground-v0.1.0","ports":[{"n":1,"l":3,"tx":0,"rx":0}]}`)
+	deadline := time.Now().Add(2 * time.Second)
+	got := []beaconCandidate{}
+	for time.Now().Before(deadline) {
+		got = s.beaconCandidates()
+		if len(got) == 1 {
+			break
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	if len(got) != 1 {
+		t.Fatalf("candidato: %+v", got)
+	}
+	if got[0].Dev != "KP-9000-9XHML-X" || got[0].Fw != "rtlplayground-v0.1.0" || got[0].Ports != 1 {
+		t.Fatalf("candidato mal: %+v", got[0])
+	}
+
+	// Beacon validado desde la misma IP → el candidato desaparece.
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":2,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3,"tx":1,"rx":1}]}`, token))
+	waitFresh(t, s, "switch16")
+	if got := s.beaconCandidates(); len(got) != 0 {
+		t.Fatalf("candidato debería limpiarse tras beacon validado: %+v", got)
+	}
+}
+
+// Un announce con token INVALIDO no es candidato ni agente: ruido desechado.
+func TestBeaconAnnounceWithBadTokenDropped(t *testing.T) {
+	s, _ := newBeaconTestServer(t)
+	// announce con token inventado: cae en la rama de token inválido (log)
+	s.ingestBeacon("10.0.0.9", []byte(`{"v":1,"seq":1,"slug":"switch16","token":"bad","dev":"X","fw":"y","ports":[]}`))
+	if got := s.beaconCandidates(); len(got) != 0 {
+		t.Fatalf("token inválido no debe crear candidato: %+v", got)
+	}
+}
+
+func waitForAlert(t *testing.T, s *server, substr string) alerts.AlertEvent {
+	t.Helper()
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		for _, a := range s.alertsEngine().List() {
+			if strings.Contains(a.Title, substr) {
+				return a
+			}
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	t.Fatalf("no llegó la alerta %q; feed: %+v", substr, s.alertsEngine().List())
+	return alerts.AlertEvent{}
+}
+
+// Un evento loop llega por UDP y produce una alerta urgente en el feed.
+func TestBeaconLoopEventEmitsUrgentAlert(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"ev":"loop","port":2,"mac":"AABBCCDDEEFF","seq":50,"slug":"switch16","token":"%s"}`, token))
+
+	a := waitForAlert(t, s, "Bucle detectado")
+	if !a.Urgent || a.RouterID != "switch16" || a.Severity != "warn" {
+		t.Fatalf("alerta mal: %+v", a)
+	}
+	if !strings.Contains(a.Title, "boca 2") {
+		t.Fatalf("título sin la boca: %q", a.Title)
+	}
+}
+
+// El fallback por delta: dos beacons seguidos con un link cambiado generan
+// la alerta de link caído sin necesidad de eventos del firmware.
+func TestBeaconDeltaFallbackEmitsLinkChange(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	up := fmt.Sprintf(`{"v":1,"seq":1,"slug":"switch16","token":"%s","ports":[{"n":2,"l":2,"tx":1,"rx":1}]}`, token)
+	sendUDP(t, addr, up)
+	waitFresh(t, s, "switch16")
+	down := fmt.Sprintf(`{"v":1,"seq":2,"slug":"switch16","token":"%s","ports":[{"n":2,"l":0,"tx":1,"rx":1}]}`, token)
+	sendUDP(t, addr, down)
+	waitForAlert(t, s, "Link caído")
+}
+
+// Datagrama FDB (v1.2): sustituye la tabla MAC conservando las bocas del
+// último beacon (nada se borra al llegar solo-MACs).
+func TestBeaconFDBDatagramPreservesPorts(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":1,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3,"tx":1,"rx":1},{"n":2,"l":0,"tx":0,"rx":0}]}`, token))
+	waitFresh(t, s, "switch16")
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":2,"slug":"switch16","token":"%s","fdb":{"AABBCCDDEE01":"1","AABBCCDDEE02":"2"}}`, token))
+
+	deadline := time.Now().Add(3 * time.Second)
+	var got *probe.Payload
+	for time.Now().Before(deadline) {
+		if p, ok := s.agents.StalePayload("switch16"); ok && p != nil && p.Data.FDB != nil && len(p.Data.FDB.MACs) == 2 {
+			got = p
+			break
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	if got == nil {
+		t.Fatal("el datagrama FDB no actualizó la tabla MAC")
+	}
+	if len(got.Data.FDB.Ports) != 2 || !got.Data.FDB.Ports[0].Up || got.Data.FDB.Ports[1].Up {
+		t.Fatalf("las bocas del beacon anterior no se conservaron: %+v", got.Data.FDB.Ports)
+	}
+	if got.Data.FDB.MACs["AA:BB:CC:DD:EE:01"] != "1" {
+		t.Fatalf("macs mal: %+v", got.Data.FDB.MACs)
+	}
+}
+
+// Las MACs del firmware llegan SIN separadores: se normalizan al formato
+// canónico con dos puntos para que leases/wifi/enriquecimiento casen.
+func TestBeaconFDBNormalizesBareMACs(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(
+		`{"v":1,"seq":1,"slug":"switch16","token":"%s","fdb":{"AABBCCDDEE01":"3","aa:bb:cc:dd:ee:02":"8","corta":"1"}}`, token))
+	deadline := time.Now().Add(3 * time.Second)
+	var macs map[string]string
+	for time.Now().Before(deadline) {
+		if p, ok := s.agents.StalePayload("switch16"); ok && p != nil && p.Data.FDB != nil && len(p.Data.FDB.MACs) == 2 {
+			macs = p.Data.FDB.MACs
+			break
+		}
+		time.Sleep(50 * time.Millisecond)
+	}
+	if macs == nil {
+		t.Fatal("el datagrama FDB no llegó al registry")
+	}
+	if macs["AA:BB:CC:DD:EE:01"] != "3" || macs["AA:BB:CC:DD:EE:02"] != "8" {
+		t.Fatalf("normalización de MACs mal: %+v", macs)
+	}
+}
+
+// Seq que vuelve a 1 = reboot del switch → alerta info en el feed.
+func TestBeaconSeqResetEmitsRebootAlert(t *testing.T) {
+	s, token := newBeaconTestServer(t)
+	addr, err := s.startBeaconListener("127.0.0.1:0")
+	if err != nil {
+		t.Fatalf("listener: %v", err)
+	}
+	defer s.beaconConn.Close()
+
+	sendUDP(t, addr, fmt.Sprintf(`{"v":1,"seq":40,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3,"tx":0,"rx":0}]}`, token))
+	waitFresh(t, s, "switch16")
+	sendUDP(t, addr, fmt.Sprintf(`{"v":1,"seq":1,"slug":"switch16","token":"%s","ports":[{"n":1,"l":3,"tx":0,"rx":0}]}`, token))
+	a := waitForAlert(t, s, "Switch reiniciado")
+	if a.Severity != "info" || a.RouterID != "switch16" {
+		t.Fatalf("alerta de reboot mal: %+v", a)
+	}
+}

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

@@ -16,6 +16,8 @@ import (
 	"encoding/hex"
 	"encoding/json"
 	"errors"
+	"log"
+	"net"
 	"net/http"
 	"strings"
 	"sync"
@@ -106,6 +108,14 @@ type server struct {
 	// por slug en memoria, expuesto en GET /api/agents.
 	upgrades *upgradeTracker
 
+	// Beacon UDP de pushers embebidos (#291): socket, último seq por slug y
+	// candidatos de descubrimiento (anuncios broadcast sin parar).
+	beaconConn   net.PacketConn
+	beaconSeqMu  sync.Mutex
+	beaconSeq    map[string]uint32
+	beaconCandMu sync.Mutex
+	beaconCand   map[string]beaconCandidate
+
 	// Ventana de frescura del `ts` del agente (anti-replay, auditoría #2).
 	maxTsDrift time.Duration
 }
@@ -148,6 +158,14 @@ func NewHandler(d Deps) http.Handler {
 	if s.agentHub != nil {
 		s.agentHub.SetOnConnect(s.FlushQueuedUpgrade)
 	}
+	// #291: listener UDP de beacons (NETPULSE_BEACON_LISTEN; vacío = off).
+	if d.Config != nil && d.Config.BeaconListen != "" {
+		if la, err := s.startBeaconListener(d.Config.BeaconListen); err != nil {
+			log.Printf("[netpulse] aviso: beacon UDP no arrancó en %s (%v)", d.Config.BeaconListen, err)
+		} else {
+			log.Printf("[netpulse] beacon UDP escuchando en %s", la)
+		}
+	}
 	mode := d.Adapter.Mode()
 
 	mux := http.NewServeMux()
@@ -194,6 +212,10 @@ func NewHandler(d Deps) http.Handler {
 	// lista es de lectura y se deja tras RequireAuth.
 	mux.Handle("POST /api/agents", auth.RequireAdmin(http.HandlerFunc(s.handleAgentsCreate)))
 	mux.HandleFunc("GET /api/agents", s.handleAgentsList)
+	// #291: switches embebidos anunciándose por broadcast sin parar.
+	mux.Handle("GET /api/agents/discovered", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		writeJSON(w, http.StatusOK, map[string]any{"discovered": s.beaconCandidates()})
+	})))
 	mux.Handle("DELETE /api/agents/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleAgentsDelete)))
 	// Fase 5 (Plan B): rearme del servicio procd del agente vía SSH.
 	mux.Handle("POST /api/agents/{slug}/rearm", auth.RequireAdmin(http.HandlerFunc(s.handleAgentRearm)))