Selaa lähdekoodia

feat(topology): show the WAN upstream device under the Internet node (#1042) (#1048)

The ISP modem/ONT in front of the gateway is discovered by ARP as a
regular client, but it lives on the WAN side. When its IP matches the
router's WAN gateway, the semantics now flag it as the WAN peer (out of
the rings, internet→device link), and the map renders it as a chip next
to the WAN line, hanging off the Internet cloud instead of the client
rings.
Nacho 2 kuukautta sitten
vanhempi
sitoutus
837a72d4a7

+ 35 - 2
app/src/components/topology/model.ts

@@ -72,7 +72,7 @@ export interface DistNodeView {
   r: number
 }
 
-export type TopoLinkKind = 'wan' | 'uplink' | 'wired' | 'dist' | 'wg'
+export type TopoLinkKind = 'wan' | 'wan-peer' | 'uplink' | 'wired' | 'dist' | 'wg'
 
 export interface TopoLink {
   id: string
@@ -752,7 +752,20 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const managedMacs = new Set(
     distributionNodes.filter((n) => n.kind === 'managed' && n.mac).map((n) => n.mac!.toUpperCase()),
   )
-  const online = devices.filter((d) => d.online && !managedMacs.has(d.mac.toUpperCase()))
+  // #1042: el equipo aguas arriba del gateway (módem/ONT del ISP) se descubre
+  // por ARP como un cliente más, pero vive en el lado WAN: si su IP coincide
+  // con la puerta de enlace WAN se dibuja bajo el nodo Internet (chip propio
+  // junto al enlace WAN), no como cliente LAN. La semántica server ya lo
+  // excluye de los anillos; aquí se excluye de la lista online para el
+  // fallback sin semántica y se reserva el device para el chip.
+  const wanPeerDev = devices.find(
+    (d) => d.online && wan.gateway && d.ip && d.ip === wan.gateway,
+  )
+  // Chip del wan peer, creado tras fijar la posición final de Internet.
+  let wanPeerChip: ChipNode | null = null
+  const online = devices.filter(
+    (d) => d.online && !managedMacs.has(d.mac.toUpperCase()) && d.id !== wanPeerDev?.id,
+  )
   const deviceById = new Map(online.map((d) => [d.id, d]))
   const distById = new Map(distributionNodes.map((n) => [n.id, n]))
   /** hub al que cuelga un dispositivo: attachTo (si existe y resuelve) o su router.
@@ -1034,6 +1047,15 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       // Internet: sobre el gateway (misma x), empujado hacia arriba del viewport.
       const targetY = Math.max(24, gatewayNode.y - clearDist)
       internetNode.y = targetY
+      // #1042: el módem/ONT aguas arriba cuelga del nodo Internet: chip junto
+      // a la línea WAN (punto medio Internet↔gateway, desplazado a un lado).
+      if (wanPeerDev) {
+        const gwTop = { x: gatewayNode.x, y: gatewayNode.y - gatewayNode.r }
+        const mx = (internetNode.x + gwTop.x) / 2
+        const my = (internetNode.y + gwTop.y) / 2
+        wanPeerChip = { ...mkChip(wanPeerDev, 'internet'), x: mx + 46, y: my }
+        chips.push(wanPeerChip)
+      }
       // APs y switches: a lo largo del vector desde el gateway hasta su posición
       // canónica, empujados hasta quedar a >= clearDist (fuera del círculo).
       const pushOut = (rn: RouterNode) => {
@@ -1258,6 +1280,17 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
       width: 3, ...flowFor(600),
       from: 'internet', to: gatewayNode.id,
     })
+    // #1042: el módem/ONT aguas arriba cuelga de Internet, junto a la línea WAN.
+    if (wanPeerChip) {
+      const a = pos(internetNode.x, internetNode.y, angleTo(internetNode.x, internetNode.y, wanPeerChip.x, wanPeerChip.y), internetNode.r + 2)
+      links.push({
+        id: 'wan-peer', kind: 'wan-peer',
+        d: `M ${a.x} ${a.y} L ${wanPeerChip.x} ${wanPeerChip.y}`,
+        lx: 0, ly: 0, label: '',
+        width: 1.5, ...flowFor(30),
+        from: 'internet', to: wanPeerChip.id,
+      })
+    }
   }
   const makeUplink = (node: RouterNode) => {
     const isWifi = node.router.backhaul === 'wifi'

+ 1 - 1
server-go/internal/adapters/demo.go

@@ -225,7 +225,7 @@ func (d *Demo) buildOverview() *Overview {
 		Alerts:            d.alertsCopy(),
 		UnreadAlerts:      d.engine.UnreadCount(),
 		DistributionNodes: dists,
-		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists), // SPEC-65 D65-3
+		Topology:          BuildTopoSemantics(d.routers, d.devices, wg, dists, ""), // SPEC-65 D65-3
 		VM:                ViewModelVersion,                                    // SPEC-65 D65-4
 		Ts:                time.Now().Unix(),
 	}

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

@@ -3009,7 +3009,7 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 		},
 		TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
 		DistributionNodes: distNodes,
-		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes), // SPEC-65 D65-3
+		Topology:          BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway), // SPEC-65 D65-3 + #1042
 		Devices:           devices,
 		Usteer:            &UsteerOverview{Available: usteerAvailable},
 		DawnDeprecated:    dawnDetected,

+ 27 - 1
server-go/internal/adapters/topo_semantics.go

@@ -34,7 +34,7 @@ const maxTopoPeerChips = 4
 
 // BuildTopoSemantics deriva enlaces, anillos y peers ocultos del mismo bundle
 // que hoy consume la app (routers, devices, wireguard, distributionNodes).
-func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode) *TopoSemantics {
+func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, dists []DistributionNode, wanGateway string) *TopoSemantics {
 	sem := &TopoSemantics{Links: []TopoLink{}, Rings: map[string][]string{}}
 	if len(routers) == 0 {
 		return sem
@@ -78,6 +78,28 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 		}
 		online = append(online, d)
 	}
+	// #1042: el equipo aguas arriba del gateway (módem/ONT del ISP) se
+	// descubre por ARP como un cliente más, pero vive en el lado WAN: si su
+	// IP coincide con la puerta de enlace WAN se representa bajo el nodo
+	// Internet, no como cliente LAN. Se excluye de anillos y enlaces.
+	wanPeerID := ""
+	if wanGateway != "" {
+		for _, d := range online {
+			if d.IP != "" && d.IP == wanGateway {
+				wanPeerID = d.ID
+				break
+			}
+		}
+		if wanPeerID != "" {
+			filtered := online[:0]
+			for _, d := range online {
+				if d.ID != wanPeerID {
+					filtered = append(filtered, d)
+				}
+			}
+			online = filtered
+		}
+	}
 	deviceByID := map[string]Device{}
 	for _, d := range online {
 		deviceByID[d.ID] = d
@@ -135,6 +157,10 @@ func BuildTopoSemantics(routers []Router, devices []Device, wg WireGuardStats, d
 
 	// -- enlaces (mismo orden que model.ts) --------------------------------
 	sem.Links = append(sem.Links, TopoLink{From: "internet", To: gateway.ID, Kind: "wan"})
+	if wanPeerID != "" {
+		sem.WanPeer = wanPeerID
+		sem.Links = append(sem.Links, TopoLink{From: "internet", To: wanPeerID, Kind: "wan-peer"})
+	}
 	for _, ap := range nonGateway {
 		l := TopoLink{From: gateway.ID, To: ap.ID, Kind: "uplink"}
 		if ap.Lldp != nil {

+ 44 - 5
server-go/internal/adapters/topo_semantics_test.go

@@ -23,7 +23,7 @@ import (
 //   - hiddenPeers ausente: todos los anillos bajo el límite de chips visibles
 //     de la app (gateway 13, AP 20)
 func TestTopoSemanticsGoldenCanon(t *testing.T) {
-	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes())
+	sem := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "")
 
 	wantLinks := []TopoLink{
 		{From: "internet", To: "flint2", Kind: "wan"},
@@ -109,7 +109,7 @@ func TestTopoSemanticsHiddenPeers(t *testing.T) {
 			RouterID: "ap", Band: "2.4 GHz", Online: true,
 		})
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil)
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
 	want := map[string]int{"gw": 2, "ap": 2} // 62-60 y 42-40
 	if !reflect.DeepEqual(sem.HiddenPeers, want) {
 		t.Fatalf("hiddenPeers: got %+v want %+v", sem.HiddenPeers, want)
@@ -133,7 +133,7 @@ func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
 		t.Fatal("overview.Topology ausente en demo")
 	}
 	// Mismo resultado que el builder puro sobre el canon.
-	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes())
+	want := BuildTopoSemantics(canonRouters(), canonAllDevices(), canonWireguard(), canonDistributionNodes(), "")
 	if !reflect.DeepEqual(ov.Topology, want) {
 		t.Fatalf("overview.Topology != builder canon:\n got: %+v\nwant: %+v", ov.Topology, want)
 	}
@@ -141,7 +141,7 @@ func TestDemoOverviewIncluyeTopologyYVM(t *testing.T) {
 
 // Sin routers: semántica vacía pero no nil (la app cae a su cálculo propio).
 func TestTopoSemanticsSinRouters(t *testing.T) {
-	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil)
+	sem := BuildTopoSemantics(nil, nil, WireGuardStats{}, nil, "")
 	if sem == nil || sem.Links == nil || sem.Rings == nil {
 		t.Fatalf("semántica vacía debe tener links/rings no-nil: %+v", sem)
 	}
@@ -161,7 +161,7 @@ func TestTopoSemanticsDeviceHubBajoDistnode(t *testing.T) {
 	}
 	routers := []Router{{ID: "gateway", Name: "gateway", RoleBadge: "Principal", Status: "online"}}
 	dists := []DistributionNode{{ID: "dist-gateway-lan1", Kind: "inferred", RouterID: "gateway", Port: "lan1"}}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists)
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "")
 
 	var toHost []TopoLink
 	for _, l := range sem.Links {
@@ -189,3 +189,42 @@ func TestTopoSemanticsDeviceHubBajoDistnode(t *testing.T) {
 		}
 	}
 }
+
+// #1042: el dispositivo cuya IP coincide con la puerta de enlace WAN es el
+// módem/ONT aguas arriba: va bajo el nodo Internet (sem.WanPeer), queda
+// fuera de los anillos y no genera enlace de cliente LAN.
+func TestTopoSemanticsWanPeer(t *testing.T) {
+	routers := []Router{
+		{ID: "gw", Name: "gateway", RoleBadge: "Principal"},
+	}
+	devices := []Device{
+		{ID: "modem", MAC: "AA:BB:CC:00:00:01", RouterID: "gw", Band: "cable", Online: true, IP: "100.64.0.1"},
+		{ID: "nas", MAC: "AA:BB:CC:00:00:02", RouterID: "gw", Band: "cable", Online: true, IP: "192.168.1.10"},
+	}
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "100.64.0.1")
+	if sem.WanPeer != "modem" {
+		t.Fatalf("WanPeer = %q, want modem", sem.WanPeer)
+	}
+	for _, id := range sem.Rings["gw"] {
+		if id == "modem" {
+			t.Fatal("el wan peer no debe estar en el anillo del gateway")
+		}
+	}
+	found := false
+	for _, l := range sem.Links {
+		if l.Kind == "wan-peer" && l.From == "internet" && l.To == "modem" {
+			found = true
+		}
+		if l.Kind == "wired" && l.To == "modem" {
+			t.Fatal("el wan peer no debe tener enlace de cliente cableado")
+		}
+	}
+	if !found {
+		t.Fatal("falta el enlace internet→modem (wan-peer)")
+	}
+	// Sin gateway WAN no hay wan peer aunque haya dispositivos.
+	sem2 := BuildTopoSemantics(routers, devices, WireGuardStats{}, nil, "")
+	if sem2.WanPeer != "" {
+		t.Fatalf("WanPeer sin gateway WAN = %q, want vacío", sem2.WanPeer)
+	}
+}

+ 1 - 1
server-go/internal/adapters/topology_lldp_test.go

@@ -225,7 +225,7 @@ func TestTopoSemanticsCadenaLldp(t *testing.T) {
 		{RouterID: "flint2", Band: "cable", Port: "lan3", ID: "pc1", MAC: "04:D4:C4:8B:30:A7", AttachTo: "dist-flint2-lan3", Online: true},
 		{RouterID: "swA", Band: "cable", Port: "ge5", ID: "pc2", MAC: "DC:A6:32:4F:77:02", AttachTo: "dist-swA-ge5", Online: true},
 	}
-	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists)
+	sem := BuildTopoSemantics(routers, devices, WireGuardStats{}, dists, "")
 
 	var gotDist []TopoLink
 	for _, l := range sem.Links {

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

@@ -400,6 +400,11 @@ type TopoSemantics struct {
 	Rings map[string][]string `json:"rings"`
 	// HiddenPeers: routerId → nº de clientes no pintados como chip (el "+N").
 	HiddenPeers map[string]int `json:"hiddenPeers,omitempty"`
+	// WanPeer (#1042): id del Device aguas arriba del gateway (módem/ONT del
+	// ISP), identificado porque su IP coincide con la puerta de enlace WAN.
+	// El mapa lo dibuja bajo el nodo Internet en vez de como cliente LAN.
+	// Vacío si no hay coincidencia.
+	WanPeer string `json:"wanPeer,omitempty"`
 }
 
 // TopoLink es un enlace semántico del mapa (sin geometría).