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

feat(router-detail): rich port tooltips with device info and WAN connection details (#277)

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
4898ffe139

+ 55 - 0
agent/probe/probe.go

@@ -73,6 +73,9 @@ const (
 	// /etc/config/luci con nombres amigables para la topología. Se lee el
 	// fichero crudo (uci show luci sería más ruidoso: todo el paquete).
 	CmdLuCILabels = "cat /etc/config/luci 2>/dev/null"
+	// CmdWanStatus: estado de la interfaz WAN (solo gateway) vía ubus.
+	// Da proto ("pppoe"), IP, gateway (ptpaddress/nexthop) y DNS (issue #276).
+	CmdWanStatus = "ubus call network.interface.wan status 2>/dev/null || true"
 )
 
 // ---------------------------------------------------------------------------
@@ -102,6 +105,16 @@ type BoardInfo struct {
 	} `json:"release"`
 }
 
+// WanInfo: datos de la conexión WAN (issue #276). Solo el gateway lo rellena;
+// los campos vacíos significan "sin datos WAN" (APs/desconocido).
+type WanInfo struct {
+	Proto   string   `json:"proto,omitempty"`   // "pppoe"|"dhcp"|"static"...
+	Device  string   `json:"device,omitempty"`  // interfaz física (p.ej. "eth1.20")
+	IP      string   `json:"ip,omitempty"`      // dirección IPv4 pública
+	Gateway string   `json:"gateway,omitempty"` // puerta de enlace (nexthop/ptpaddress)
+	DNS     []string `json:"dns,omitempty"`     // servidores DNS
+}
+
 // DhcpLease es {mac, ip, hostname} (mac en mayúsculas).
 type DhcpLease struct {
 	MAC      string `json:"mac"`
@@ -296,6 +309,48 @@ func ParseDhcpUbus(raw []byte) ([]DhcpLease, error) {
 	return out, nil
 }
 
+// ParseWanStatus parsea `ubus call network.interface.wan status` (issue #276).
+// Extrae proto, interfaz física, IP pública, gateway (nexthop de la ruta por
+// defecto, con fallback al ptpaddress) y DNS. Devuelve un WanInfo con los
+// campos vacíos si el JSON no tiene datos utilizables.
+func ParseWanStatus(raw []byte) WanInfo {
+	var data struct {
+		Proto  string `json:"proto"`
+		Device string `json:"l3_device"`
+		IPV4   []struct {
+			Address    string `json:"address"`
+			PtpAddress string `json:"ptpaddress"`
+		} `json:"ipv4-address"`
+		Route []struct {
+			Target  string `json:"target"`
+			Mask    int    `json:"mask"`
+			Nexthop string `json:"nexthop"`
+		} `json:"route"`
+		DNS []string `json:"dns-server"`
+	}
+	info := WanInfo{}
+	if json.Unmarshal(raw, &data) != nil {
+		return info
+	}
+	info.Proto = data.Proto
+	info.Device = data.Device
+	if len(data.IPV4) > 0 {
+		info.IP = data.IPV4[0].Address
+		if data.IPV4[0].PtpAddress != "" {
+			info.Gateway = data.IPV4[0].PtpAddress
+		}
+	}
+	// El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0).
+	for _, r := range data.Route {
+		if r.Target == "0.0.0.0" && r.Nexthop != "" {
+			info.Gateway = r.Nexthop
+			break
+		}
+	}
+	info.DNS = data.DNS
+	return info
+}
+
 // ParseDhcpLeasesFile parsea /tmp/dhcp.leases:
 // <expiry> <mac> <ip> <hostname> <clientid>
 func ParseDhcpLeasesFile(out string) []DhcpLease {

+ 37 - 0
agent/probe/probe_test.go

@@ -329,3 +329,40 @@ func payloadJSON(t *testing.T, pl *Payload) string {
 	}
 	return string(data)
 }
+
+func TestParseWanStatus(t *testing.T) {
+	// Fixture real de `ubus call network.interface.wan status` (PPPoE Digi).
+	raw := `{"up":true,"proto":"pppoe","l3_device":"pppoe-wan","device":"eth1.20",` +
+		`"ipv4-address":[{"address":"79.112.56.116","mask":32,"ptpaddress":"10.0.28.237"}],` +
+		`"route":[{"target":"0.0.0.0","mask":0,"nexthop":"10.0.28.237","source":"0.0.0.0/0"}],` +
+		`"dns-server":["100.90.1.1","100.100.1.1"]}`
+	info := ParseWanStatus([]byte(raw))
+	if info.Proto != "pppoe" {
+		t.Fatalf("proto=%q, esperaba pppoe", info.Proto)
+	}
+	if info.Device != "pppoe-wan" {
+		t.Fatalf("device=%q, esperaba pppoe-wan", info.Device)
+	}
+	if info.IP != "79.112.56.116" {
+		t.Fatalf("ip=%q, esperaba 79.112.56.116", info.IP)
+	}
+	if info.Gateway != "10.0.28.237" {
+		t.Fatalf("gateway=%q, esperaba 10.0.28.237", info.Gateway)
+	}
+	if len(info.DNS) != 2 || info.DNS[0] != "100.90.1.1" || info.DNS[1] != "100.100.1.1" {
+		t.Fatalf("dns=%v, esperaba [100.90.1.1 100.100.1.1]", info.DNS)
+	}
+}
+
+func TestParseWanStatusVacioYMalFormado(t *testing.T) {
+	// Router sin interfaz wan (AP) → JSON sin ipv4-address ni rutas.
+	raw := `{"up":true,"proto":"dhcp"}`
+	info := ParseWanStatus([]byte(raw))
+	if info.IP != "" || info.Gateway != "" || len(info.DNS) != 0 {
+		t.Fatalf("AP sin wan debía quedar vacío: %+v", info)
+	}
+	// Malformado → vacío sin error.
+	if got := ParseWanStatus([]byte("no json")); got.IP != "" || got.Proto != "" {
+		t.Fatalf("JSON inválido debía quedar vacío: %+v", got)
+	}
+}

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

@@ -492,6 +492,10 @@
       "unknownDevice": "unknown device",
       "usedOf_one": "{{used}} of {{total}} port in use",
       "usedOf_other": "{{used}} of {{total}} ports in use",
+      "wanPublicIp": "Public IP",
+      "wanGateway": "Gateway",
+      "wanDns": "DNS",
+      "deviceDetail": "Detail",
       "wirelessUplink": " · wireless uplink (mesh)"
     },
     "radios": {
@@ -622,7 +626,6 @@
   "topology": {
     "animateFlow": "Animate packet flow",
     "clickDetail": "Click to view detail →",
-    "clickDevice": "Click to view the device →",
     "connectedClient": "Connected client",
     "flow": "Flow",
     "interactiveMap": "Interactive network map",
@@ -668,7 +671,6 @@
     "showLabels": "Show labels",
     "subtitle": "Live view of your network",
     "tapAgainDetail": "Tap again to view detail →",
-    "tapAgainDevice": "Tap again to view the device →",
     "tunnel": "Tunnel",
     "weakSignal": "Weak signal",
     "zoomControls": "Map zoom controls",

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

@@ -492,6 +492,10 @@
       "unknownDevice": "dispositivo desconocido",
       "usedOf_one": "{{used}} de {{total}} boca en uso",
       "usedOf_other": "{{used}} de {{total}} bocas en uso",
+      "wanPublicIp": "IP pública",
+      "wanGateway": "Puerta de enlace",
+      "wanDns": "Servidor DNS",
+      "deviceDetail": "Detalle",
       "wirelessUplink": " · uplink inalámbrico (mesh)"
     },
     "radios": {
@@ -622,7 +626,6 @@
   "topology": {
     "animateFlow": "Animar flujo de paquetes",
     "clickDetail": "Clic para ver el detalle →",
-    "clickDevice": "Clic para ver el dispositivo →",
     "connectedClient": "Cliente conectado",
     "flow": "Flujo",
     "interactiveMap": "Mapa interactivo de la red",
@@ -668,7 +671,6 @@
     "showLabels": "Mostrar etiquetas",
     "subtitle": "Vista en vivo de tu red",
     "tapAgainDetail": "Toca de nuevo para ver el detalle →",
-    "tapAgainDevice": "Toca de nuevo para ver el dispositivo →",
     "tunnel": "Túnel",
     "weakSignal": "Señal débil",
     "zoomControls": "Controles de zoom del mapa",

+ 147 - 73
app/src/components/routers/PortPanel.tsx

@@ -2,10 +2,12 @@ import { motion, useReducedMotion } from 'framer-motion'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
 import type { Router } from '@/data/mock'
+import type { WanInfo } from '@/data/types'
 import { SectionHeader } from '@/components/SectionHeader'
 import { getRouterExtras } from '@/components/routers/routerExtras'
 import type { EthPort, RouterExtras } from '@/components/routers/routerExtras'
 import { EMPTY_EXTRAS, useNetPulse } from '@/data/DataProvider'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
 import { cn } from '@/lib/utils'
 
 /**
@@ -14,7 +16,7 @@ import { cn } from '@/lib/utils'
  * Variante compacta (APs, col-span-5) y ancha (gateway, col-span-12).
  */
 
-function Jack({ port, index }: { port: EthPort; index: number }) {
+function Jack({ port, index, wan }: { port: EthPort; index: number; wan?: WanInfo }) {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
   const isWan = port.id === 'wan'
@@ -23,93 +25,165 @@ function Jack({ port, index }: { port: EthPort; index: number }) {
     ? t('routerDetail.ports.ariaUsed', { label: port.label, connectedTo: port.connectedTo ?? t('routerDetail.ports.unknownDevice'), speed: port.speed ? `, ${port.speed}` : '' })
     : t('routerDetail.ports.ariaFree', { label: port.label })
 
-  return (
-    <motion.div
-      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"
-      role="img"
-      aria-label={aria}
-      title={port.up ? `${port.connectedTo ?? ''}${port.detail ? ` — ${port.detail}` : ''}` : t('routerDetail.ports.freeLabel', { label: port.label })}
-    >
-      {/* LEDs link / act */}
-      <div className="mb-1 flex w-9 items-center justify-between">
-        <span className={cn('h-1.5 w-1.5 rounded-full', port.up ? 'bg-ok' : 'bg-border-strong/50')} />
-        <span
-          className={cn(
-            'h-1.5 w-1.5 rounded-full',
-            port.up ? 'bg-ok' : 'bg-border-strong/50',
-            port.up && !reduce && 'animate-pulse',
-          )}
-        />
-      </div>
+  const hasWanInfo = isWan && wan && (wan.proto || wan.publicIp || wan.gateway || (wan.dns?.length ?? 0) > 0)
 
-      {/* Cuerpo del conector */}
-      <div
-        className={cn(
-          'relative h-12 w-12 rounded-md border-2 transition-all duration-150 group-hover:-translate-y-0.5',
-          port.up && isWan && 'border-accent/60 bg-canvas shadow-glow-accent',
-          port.up && !isWan && 'border-ok/50 bg-canvas',
-          !port.up && 'border-border bg-canvas/50',
-        )}
-      >
-        {/* Pines dorados */}
-        <div className="absolute inset-x-[7px] top-[5px] flex justify-between">
-          {Array.from({ length: 8 }).map((_, i) => (
+  return (
+    <Tooltip>
+      <TooltipTrigger asChild>
+        <motion.div
+          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"
+          role="img"
+          aria-label={aria}
+        >
+          {/* LEDs link / act */}
+          <div className="mb-1 flex w-9 items-center justify-between">
+            <span className={cn('h-1.5 w-1.5 rounded-full', port.up ? 'bg-ok' : 'bg-border-strong/50')} />
             <span
-              key={i}
               className={cn(
-                'h-2.5 w-[2px] rounded-full',
-                port.up ? 'bg-warn/80' : 'bg-border-strong/50',
+                'h-1.5 w-1.5 rounded-full',
+                port.up ? 'bg-ok' : 'bg-border-strong/50',
+                port.up && !reduce && 'animate-pulse',
               )}
             />
-          ))}
-        </div>
-        {/* Apertura */}
-        <div
-          className={cn(
-            'absolute inset-x-[6px] bottom-[5px] h-[18px] rounded-[3px] border',
-            port.up ? 'border-border/80 bg-black/50' : 'border-border/50 bg-black/25',
-          )}
-        />
-      </div>
+          </div>
 
-      {/* Etiquetas */}
-      <div className="mt-1.5 w-full text-center">
-        <div className={cn('font-mono text-[10px] font-semibold tracking-wide', isWan ? 'text-accent' : 'text-text-secondary')}>
-          {port.label}
-        </div>
-        {port.up ? (
-          <>
-            <div className="mt-0.5 w-full truncate text-caption font-medium text-text-primary">
-              {port.connectedTo && port.deviceMac ? (
-                <Link
-                  to={`/devices?q=${encodeURIComponent(port.deviceMac)}`}
-                  className="transition-colors hover:text-accent hover:underline"
-                  onClick={(e) => e.stopPropagation()}
-                >
-                  {port.connectedTo}
-                </Link>
-              ) : port.connectedTo ? (
-                port.connectedTo
-              ) : (
-                t('routerDetail.ports.inUse')
+          {/* Cuerpo del conector */}
+          <div
+            className={cn(
+              'relative h-12 w-12 rounded-md border-2 transition-all duration-150 group-hover:-translate-y-0.5',
+              port.up && isWan && 'border-accent/60 bg-canvas shadow-glow-accent',
+              port.up && !isWan && 'border-ok/50 bg-canvas',
+              !port.up && 'border-border bg-canvas/50',
+            )}
+          >
+            {/* Pines dorados */}
+            <div className="absolute inset-x-[7px] top-[5px] flex justify-between">
+              {Array.from({ length: 8 }).map((_, i) => (
+                <span
+                  key={i}
+                  className={cn(
+                    'h-2.5 w-[2px] rounded-full',
+                    port.up ? 'bg-warn/80' : 'bg-border-strong/50',
+                  )}
+                />
+              ))}
+            </div>
+            {/* Apertura */}
+            <div
+              className={cn(
+                'absolute inset-x-[6px] bottom-[5px] h-[18px] rounded-[3px] border',
+                port.up ? 'border-border/80 bg-black/50' : 'border-border/50 bg-black/25',
               )}
+            />
+          </div>
+
+          {/* Etiquetas */}
+          <div className="mt-1.5 w-full text-center">
+            <div className={cn('font-mono text-[10px] font-semibold tracking-wide', isWan ? 'text-accent' : 'text-text-secondary')}>
+              {port.label}
             </div>
-            {port.speed && <div className="font-mono text-[10px] text-text-muted">{port.speed}</div>}
-          </>
+            {port.up ? (
+              <>
+                <div className="mt-0.5 w-full truncate text-caption font-medium text-text-primary">
+                  {port.connectedTo && port.deviceMac ? (
+                    <Link
+                      to={`/devices?q=${encodeURIComponent(port.deviceMac)}`}
+                      className="transition-colors hover:text-accent hover:underline"
+                      onClick={(e) => e.stopPropagation()}
+                    >
+                      {port.connectedTo}
+                    </Link>
+                  ) : port.connectedTo ? (
+                    port.connectedTo
+                  ) : (
+                    t('routerDetail.ports.inUse')
+                  )}
+                </div>
+                {port.speed && <div className="font-mono text-[10px] text-text-muted">{port.speed}</div>}
+              </>
+            ) : (
+              <div className="mt-0.5 text-caption text-text-muted">{t('routerDetail.ports.free')}</div>
+            )}
+          </div>
+        </motion.div>
+      </TooltipTrigger>
+      <TooltipContent
+        side="top"
+        align="center"
+        sideOffset={6}
+        className="w-56 border border-border-strong bg-elevated text-text-primary shadow-xl"
+      >
+        {!port.up ? (
+          <span className="text-caption text-text-muted">{t('routerDetail.ports.freeLabel', { label: port.label })}</span>
         ) : (
-          <div className="mt-0.5 text-caption text-text-muted">{t('routerDetail.ports.free')}</div>
+          <div>
+            {/* Cabecera: etiqueta + estado */}
+            <div className="flex items-center justify-between gap-2">
+              <span className="font-display text-sm font-semibold text-text-primary">{port.label}</span>
+              <span className="flex items-center gap-1.5 text-caption text-text-secondary">
+                <span className="h-1.5 w-1.5 rounded-full bg-ok" aria-hidden="true" />
+                {port.speed ?? t('routerDetail.ports.inUse')}
+              </span>
+            </div>
+
+            {isWan && hasWanInfo ? (
+              /* Boca WAN: conexión a Internet */
+              <div className="mt-1 text-caption leading-snug text-text-secondary">
+                {port.connectedTo && <div>{port.connectedTo}</div>}
+                {wan!.proto && <div className="mt-0.5 font-mono text-caption text-accent">{wan!.proto.toUpperCase()}</div>}
+              </div>
+            ) : (
+              /* Boca LAN: dispositivo conectado */
+              port.connectedTo && (
+                <div className="mt-1 text-caption font-medium text-text-primary">
+                  {port.connectedTo}
+                </div>
+              )
+            )}
+
+            {isWan && hasWanInfo && wan ? (
+              <div className="mt-2 grid grid-cols-2 gap-1.5">
+                {wan.publicIp && <MiniStat label={t('routerDetail.ports.wanPublicIp')} value={wan.publicIp} />}
+                {wan.gateway && <MiniStat label={t('routerDetail.ports.wanGateway')} value={wan.gateway} />}
+                {wan.dns && wan.dns.length > 0 && (
+                  <div className="col-span-2">
+                    <MiniStat label={t('routerDetail.ports.wanDns')} value={wan.dns.join(' · ')} />
+                  </div>
+                )}
+              </div>
+            ) : (
+              port.deviceMac && (
+                <div className="mt-2 grid grid-cols-2 gap-1.5">
+                  <MiniStat label="MAC" value={port.deviceMac} />
+                  {port.detail && <MiniStat label={t('routerDetail.ports.deviceDetail')} value={port.detail} />}
+                </div>
+              )
+            )}
+          </div>
         )}
+      </TooltipContent>
+    </Tooltip>
+  )
+}
+
+/** MiniStat: celda de dato del tooltip (mismo patrón que la topología). */
+function MiniStat({ label, value }: { label: string; value: string }) {
+  return (
+    <div className="rounded-lg bg-canvas/60 px-2 py-1.5">
+      <div className="text-caption uppercase tracking-[0.06em] text-text-muted">{label}</div>
+      <div className="truncate font-mono text-mono-sm text-text-primary" title={value}>
+        {value}
       </div>
-    </motion.div>
+    </div>
   )
 }
 
 export function PortPanel({ router, extras, className }: { router: Router; extras?: RouterExtras; className?: string }) {
   const { t } = useTranslation()
-  const { isDemo } = useNetPulse()
+  const { isDemo, wan } = useNetPulse()
   const ex = extras ?? (isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS)
   const ports = ex.ethPorts
   const used = ports.filter((p) => p.up).length
@@ -130,7 +204,7 @@ export function PortPanel({ router, extras, className }: { router: Router; extra
       {/* 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">
         {wanPorts.map((p, i) => (
-          <Jack key={p.id} port={p} index={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" />

+ 1 - 8
app/src/components/topology/TopologyMap.tsx

@@ -230,7 +230,7 @@ function TooltipCard({
         </div>
       )}
       {tip.kind === 'chip' && (
-        <ChipTooltip chip={tip.chip} touch={touch} hostCtCount={tip.hostCtCount} ctHost={tip.ctHost} />
+        <ChipTooltip chip={tip.chip} hostCtCount={tip.hostCtCount} ctHost={tip.ctHost} />
       )}
       {tip.kind === 'dist' && tip.node.kind === 'managed' && (
         <div>
@@ -282,12 +282,10 @@ function TooltipCard({
 /** Tooltip de un chip de dispositivo (cliente, hub, host hipervisor o CT). */
 function ChipTooltip({
   chip,
-  touch,
   hostCtCount = 0,
   ctHost,
 }: {
   chip: ChipNode
-  touch: boolean
   /** >0 si el chip es un host hipervisor (badge +N en el mapa) */
   hostCtCount?: number
   /** device host cuando el chip es un CT/VM anidado */
@@ -352,11 +350,6 @@ function ChipTooltip({
       {!chip.isCt && chip.weak && (
         <div className="mt-1 text-caption font-semibold text-warn">{t('topology.weakSignal')}</div>
       )}
-      {!chip.isCt && (
-        <div className="mt-2 text-caption font-semibold text-accent">
-          {touch ? t('topology.tapAgainDevice') : t('topology.clickDevice')}
-        </div>
-      )}
     </div>
   )
 }

+ 4 - 0
app/src/data/types.ts

@@ -72,6 +72,10 @@ export interface WanInfo {
   peakTodayTime: string
   avgDownMbps: number
   total24h: string
+  /** Conexión WAN real (issue #276), solo live: protocolo, gateway, DNS. */
+  proto?: string
+  gateway?: string
+  dns?: string[]
   /** Velocidad contratada declarada por el admin (Mbps, issue #151). Ausente si no configurada. */
   contractDownMbps?: number
   contractUpMbps?: number

+ 61 - 1
server-go/internal/adapters/live.go

@@ -120,6 +120,9 @@ type routerPolled struct {
 	// luci: etiquetas de puertos/VLANs de LuCI (issue #258), si el router las
 	// define en /etc/config/luci. Fuente de nombres para la topología.
 	luci *probe.LuCILabels
+	// wanInfo: estado de la conexión WAN (solo gateway, issue #276). Los APs
+	// dejan el struct vacío (sin datos WAN).
+	wanInfo probe.WanInfo
 }
 
 // extrasSnapshot es la caché anti-parpadeo por router.
@@ -153,6 +156,16 @@ type lldpCacheEntry struct {
 	at          time.Time
 }
 
+// wanInfoCacheTTL: tier lento del estado WAN del gateway. La conexión WAN no
+// cambia cada tick; un sondeo cada 60 s sobra y evita martillear ubus.
+const wanInfoCacheTTL = 60 * time.Second
+
+// wanInfoCacheEntry: WanInfo cacheado del gateway (issue #276).
+type wanInfoCacheEntry struct {
+	info probe.WanInfo
+	at   time.Time
+}
+
 // Live es el Snapshotter del modo live.
 type Live struct {
 	cfg  *config.Config
@@ -202,6 +215,7 @@ type Live struct {
 	wanDown        map[string]int
 	backhaulCache  map[string]backhaulCacheEntry
 	lldpCache      map[string]lldpCacheEntry
+	wanInfoCache   map[string]wanInfoCacheEntry
 
 	// Agentes nativos (Tier 2): último payload por slug + flag de caída
 	// (degradado a SSH tras emitir la alerta, SPEC-AGENTE-PILOTO §1).
@@ -255,6 +269,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		wanDown:              map[string]int{},
 		backhaulCache:        map[string]backhaulCacheEntry{},
 		lldpCache:            map[string]lldpCacheEntry{},
+		wanInfoCache:         map[string]wanInfoCacheEntry{},
 		agentDown:            map[string]bool{},
 		agentDownConfirm:     3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
 	}
@@ -367,6 +382,11 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.lldpCache, id)
 		}
 	}
+	for id := range l.wanInfoCache {
+		if !ids[id] {
+			delete(l.wanInfoCache, id)
+		}
+	}
 }
 
 // probeBackhaul detecta el medio del uplink (interfaz STA asociada → "wifi";
@@ -393,6 +413,23 @@ func (l *Live) probeBackhaul(routerID string, client *OpenWrtClient) string {
 	return value
 }
 
+// probeWanInfo: estado de la conexión WAN del gateway (issue #276) con caché
+// de 60 s. En routers sin interfaz wan (APs) devuelve WanInfo vacío. Fallo de
+// ubus → vacío cacheado (el detalle sigue mostrando lo demás, sin romper).
+func (l *Live) probeWanInfo(routerID string, client *OpenWrtClient) probe.WanInfo {
+	l.mu.Lock()
+	e, ok := l.wanInfoCache[routerID]
+	l.mu.Unlock()
+	if ok && time.Since(e.at) < wanInfoCacheTTL {
+		return e.info
+	}
+	info := client.GetWanInfo()
+	l.mu.Lock()
+	l.wanInfoCache[routerID] = wanInfoCacheEntry{info: info, at: time.Now()}
+	l.mu.Unlock()
+	return info
+}
+
 // probeLldp: vecinos LLDP del router con caché de 45 s (tier lento, como los
 // extras anti-parpadeo). Error o lldpd ausente → nil (sin datos; el FDB solo
 // sigue mandando, comportamiento actual intacto). Devuelve además si lldpd
@@ -639,6 +676,15 @@ func (l *Live) wanDayStats(gwID string) wanDayStatsResult {
 // y NO se toca SSH; si el agente expiró, se degrada a Tier 0 (SSH) con aviso.
 func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled, error) {
 	if fresh, p := l.pollRouterAgent(cfg); fresh {
+		// El agente no trae el estado WAN en el payload: si este router es el
+		// gateway, lo sondeamos por SSH (issue #276, cache de 60 s).
+		l.mu.Lock()
+		gw := l.gatewayCfg
+		client := l.clients[cfg.ID]
+		l.mu.Unlock()
+		if gw != nil && cfg.ID == gw.ID && client != nil {
+			p.wanInfo = l.probeWanInfo(cfg.ID, client)
+		}
 		return p, nil
 	}
 	l.mu.Lock()
@@ -748,6 +794,11 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	} else if gw != nil {
 		latencyMs, _ = client.GetGatewayLatency(gw.Host)
 	}
+	// Estado WAN solo en el gateway (issue #276), tier lento cacheado.
+	var wanInfo probe.WanInfo
+	if isGw {
+		wanInfo = l.probeWanInfo(cfg.ID, client)
+	}
 
 	cpuV := 0
 	if cpu != nil {
@@ -764,7 +815,7 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 		wireless: wirelessGood, ports: portsGood, radios: radiosGood,
 		fdb: fdbGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
 		backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
-		luci: luciGood,
+		luci: luciGood, wanInfo: wanInfo,
 	}, nil
 }
 
@@ -1666,6 +1717,15 @@ func (l *Live) defaultWan(gw *RouterConfig) WAN {
 		if p.lossPct != nil {
 			wan.LossPct = *p.lossPct
 		}
+		// Conexión WAN real (issue #276): proto/IP/gateway/DNS desde ubus.
+		if wi := p.wanInfo; wi.IP != "" || wi.Proto != "" {
+			wan.Proto = wi.Proto
+			if wi.IP != "" {
+				wan.PublicIP = wi.IP
+			}
+			wan.Gateway = wi.Gateway
+			wan.DNS = wi.DNS
+		}
 	}
 	// Resumen del día desde la BD (issue #169): pico de hoy, media y total
 	// 24h solo los poblaba el modo demo; aquí se calculan con la tabla raw.

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

@@ -331,6 +331,17 @@ func (c *OpenWrtClient) GetDhcpLeases() []DhcpLease {
 	return parseDhcpLeasesFile(out)
 }
 
+// GetWanInfo: estado de la interfaz WAN (solo gateway, issue #276).
+// Via ubus network.interface.wan status; si el router no lo tiene (AP),
+// devuelve WanInfo vacío.
+func (c *OpenWrtClient) GetWanInfo() probe.WanInfo {
+	raw, err := c.UbusCall("network.interface.wan", "status", nil)
+	if err == nil {
+		return probe.ParseWanStatus(raw)
+	}
+	return probe.WanInfo{}
+}
+
 // GetGlClients: base de clientes del firmware GL.iNet (`ubus call gl-clients
 // list`). SUPERSET de dhcp.leases: incluye equipos con IP estática o sin
 // lease que el dnsmasq del Flint2 no lista. En routers sin el objeto ubus

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

@@ -49,6 +49,11 @@ type WAN struct {
 	PeakTodayTime string  `json:"peakTodayTime"`
 	AvgDownMbps   float64 `json:"avgDownMbps"`
 	Total24h      string  `json:"total24h"`
+	// Conexión WAN real (issue #276), solo live (el demo las omite):
+	// protocolo ("pppoe"), gateway y DNS. Proto vacío en el demo/datos viejos.
+	Proto   string   `json:"proto,omitempty"`
+	Gateway string   `json:"gateway,omitempty"`
+	DNS     []string `json:"dns,omitempty"`
 	// ContractDownMbps/ContractUpMbps: velocidad contratada declarada por el
 	// admin en Ajustes (issue #151). Punteros: ausentes (null) si no está
 	// configurado. Los inyecta el server en handleOverview desde el kv — el