Explorar el Código

feat(alerts): new neighbor SSID alert with dwell (#1359) (#1394)

A neighbor SSID never seen before that STICKS AROUND is worth a look (a
new router plugged in, an IoT in pairing mode, a fixed hotspot), while a
drive-by hotspot should stay quiet.

- EvalNewNeighborSsids runs at the same ingest hook as the impostor
  check: SSIDs active in the 48h retention window, excluding the fleet
  (auto-approved via LocalSsids) and hidden (empty) ones.
- wifi_scans only retains 48h, so 'never seen' cannot come from the
  table: known SSIDs persist in kv (ssid_known:), alerted ones in
  ssid_alerted: - one-shot survives restarts and pruning.
- Dwell: alerts only when the SSID has been around >=4h and is still
  active (<=2h since last sighting). Transients stay silent.
- Anti-stampede seeding: the first evaluation marks every currently
  active SSID as known without alerting, so pre-existing neighbors never
  fire. Seeding runs even with zero active SSIDs (a first-run with no
  scans must not swallow the first real new SSID).
- Info severity, not urgent, clients category (signal defaults to
  LevelNone); i18n es/en.

Tests: seeding does not alert, transient stays quiet, dwell alerts
exactly once (kv persisted), fleet/hidden SSIDs ignored.

Closes #1359
Nacho hace 1 mes
padre
commit
df86adec8c

+ 5 - 0
app/public/locales/en/translation.json

@@ -89,6 +89,7 @@
       "port-flapping": "Check the cable or switch port: an unstable link is usually the culprit.",
       "unknown-device": "If you do not recognize it, block it or mark it as trusted in Settings.",
       "wifi-ssid-impostor": "An unknown radio is broadcasting your network name. Check the area around the hearing AP; if you do not recognize the BSSID, treat it as a rogue AP.",
+      "new-neighbor-ssid": "A new network name has been broadcasting nearby for hours. If it is not yours, find out what it is (a new router, an IoT device in pairing mode, a hotspot); if it is a permanent neighbor you do not care about, dismiss the alert - it will not repeat.",
       "uplink-switched": "Check the line that dropped: the router goes back to it on its own once it recovers.",
       "wan-down": "Check the modem/ONT and contact your ISP if the outage persists.",
       "wan-slow": "Restart the router and the modem/ONT and run the test again; if it stays low, contact your ISP (line degradation or congestion in your area).",
@@ -223,6 +224,10 @@
         "title": "SSID impostor detected",
         "description": "{{bssid}} advertises {{ssid}} (heard by {{router}}, {{signal}} dBm)"
       },
+      "new-neighbor-ssid": {
+        "title": "New neighbor SSID",
+        "description": "{{ssid}} heard for the first time (by {{router}}, {{signal}} dBm, since {{since}})"
+      },
       "uplink-restored": {
         "title": "Internet is back on {{to}}",
         "description": "{{router}} moved the traffic back to {{to}}"

+ 5 - 0
app/public/locales/es/translation.json

@@ -89,6 +89,7 @@
       "port-flapping": "Revisa el cable o el puerto del switch: un enlace inestable suele ser el culpable.",
       "unknown-device": "Si no lo reconoces, bloquéalo o márcalo como de confianza en Ajustes.",
       "wifi-ssid-impostor": "Una radio desconocida está emitiendo el nombre de tu red. Mira qué hay cerca del AP que la oyó; si no reconoces el BSSID, trátala como un AP malicioso.",
+      "new-neighbor-ssid": "Un nombre de red nuevo lleva horas emitiendo cerca. Si no es tuyo, averigua qué es (un router nuevo, un IoT en modo pairing, un hotspot); si es un vecino fijo que no te importa, descarta la alerta - no se repetirá.",
       "uplink-switched": "Revisa la línea que se ha caído: el router volverá a ella solo cuando se recupere.",
       "wan-down": "Comprueba el módem/ONT y contacta con tu operador si la caída persiste.",
       "wan-slow": "Reinicia el router y el módem/ONT y repite el test; si sigue bajo, contacta con tu operador (degrada la línea o hay saturación en tu área).",
@@ -223,6 +224,10 @@
         "title": "SSID impostor detectado",
         "description": "{{bssid}} anuncia {{ssid}} (oído por {{router}}, {{signal}} dBm)"
       },
+      "new-neighbor-ssid": {
+        "title": "Nuevo SSID vecino",
+        "description": "{{ssid}} se oye por primera vez ({{router}}, {{signal}} dBm, desde las {{since}})"
+      },
       "uplink-restored": {
         "title": "Internet vuelve por {{to}}",
         "description": "{{router}} ha devuelto el tráfico a {{to}}"

+ 157 - 0
server-go/internal/adapters/neighborssid.go

@@ -0,0 +1,157 @@
+package adapters
+
+// neighborssid.go — alerta new-neighbor-ssid (#1359): un SSID vecino que
+// nunca se había visto y que SE QUEDA (dwell) merece un aviso info (un
+// router nuevo enchufado, un IoT en modo pairing, un hotspot fijo); un
+// hotspot de paso no dice nada.
+//
+// wifi_scans solo retiene 48h (#475), así que "nunca visto" NO se puede
+// derivar de la tabla: los SSIDs conocidos se persisten en kv
+// (ssid_known:<ssid>) y los ya alertados en ssid_alerted:<ssid> (one-shot
+// de verdad, sobrevive a reinicios y a la poda).
+//
+// Anti-avalancha de arranque: en la primera evaluación de la feature (kv
+// ssid_known_seeded ausente) TODOS los SSIDs activos se siembran como
+// conocidos sin alertar - solo alertan los verdaderamente nuevos.
+//
+// La flota está auto-aprobada por definición (LocalSsids): nada que
+// configurar para el caso común.
+
+import (
+	"fmt"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/alerts"
+)
+
+const (
+	// newSsidDwell: el SSID nuevo debe llevar visto al menos este tiempo
+	// (minTs dentro de la retención) para alertar. Con scans cada 30 min,
+	// un hotspot de paso nunca llega.
+	newSsidDwell = 4 * time.Hour
+	// newSsidActive: el SSID debe seguir activo (visto dentro de esta
+	// ventana) para que el dwell cuente como cumplido ahora.
+	newSsidActive = 2 * time.Hour
+	// newSsidScanWindow: historia consultada = la retención de wifi_scans.
+	newSsidScanWindow = 48 * time.Hour
+)
+
+// EvalNewNeighborSsids: una pasada sobre los SSIDs activos. La llama el
+// handler de ingesta tras guardar un scan nuevo, igual que el impostor
+// (#1358): es el momento exacto en que la evidencia cambia.
+func (l *Live) EvalNewNeighborSsids() {
+	if l.db == nil || l.agents == nil || l.engine == nil {
+		return
+	}
+	now := time.Now()
+
+	fleetSsids := map[string]bool{}
+	for _, s := range l.agents.LocalSsids() {
+		fleetSsids[s] = true
+	}
+
+	// SSIDs activos en la retención: primero/último sighting por SSID.
+	// Sin fleet ni vacíos (redes ocultas no anuncian nombre).
+	rows, err := l.db.Query(
+		`SELECT ssid, MIN(ts), MAX(ts) FROM wifi_scans
+		 WHERE ts >= ? AND ssid <> '' GROUP BY ssid`,
+		now.Add(-newSsidScanWindow).Unix())
+	if err != nil {
+		return
+	}
+	type ssidSeen struct {
+		minTs int64
+		maxTs int64
+	}
+	active := map[string]ssidSeen{}
+	for rows.Next() {
+		var ssid string
+		var minTs, maxTs int64
+		if rows.Scan(&ssid, &minTs, &maxTs) != nil {
+			continue
+		}
+		if fleetSsids[ssid] {
+			continue
+		}
+		active[ssid] = ssidSeen{minTs: minTs, maxTs: maxTs}
+	}
+	rows.Close()
+
+	// Siembra anti-avalancha (una vez por instalación de la feature). Debe
+	// correr AUNQUE no haya activos ahora: si no, la siembra se pospondría
+	// al primer SSID nuevo de verdad y se tragaría su alerta.
+	var seeded int
+	_ = l.db.QueryRow(`SELECT COUNT(1) FROM kv WHERE key='ssid_known_seeded'`).Scan(&seeded)
+	if seeded == 0 {
+		for ssid := range active {
+			_, _ = l.db.Exec(`INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING`, "ssid_known:"+ssid)
+		}
+		_, _ = l.db.Exec(`INSERT INTO kv (key, value) VALUES ('ssid_known_seeded', '1') ON CONFLICT(key) DO NOTHING`)
+		return
+	}
+	if len(active) == 0 {
+		return
+	}
+
+	known, alerted := map[string]bool{}, map[string]bool{}
+	if kvs, err := l.db.Query(`SELECT key FROM kv WHERE key LIKE 'ssid_known:%' OR key LIKE 'ssid_alerted:%'`); err == nil {
+		for kvs.Next() {
+			var k string
+			if kvs.Scan(&k) == nil {
+				if rest, ok := strings.CutPrefix(k, "ssid_known:"); ok {
+					known[rest] = true
+				} else if rest, ok := strings.CutPrefix(k, "ssid_alerted:"); ok {
+					alerted[rest] = true
+				}
+			}
+		}
+		kvs.Close()
+	}
+
+	for ssid, seen := range active {
+		if known[ssid] || alerted[ssid] {
+			continue
+		}
+		first := time.Unix(seen.minTs, 0)
+		last := time.Unix(seen.maxTs, 0)
+		if now.Sub(first) < newSsidDwell || last.Before(now.Add(-newSsidActive)) {
+			continue // aún en dwell o ya desapareció
+		}
+		// Router y señal del sighting más reciente (para que el aviso diga
+		// dónde se oye).
+		var routerID string
+		var signal int
+		_ = l.db.QueryRow(
+			`SELECT router_id, signal_dbm FROM wifi_scans WHERE ssid = ? ORDER BY ts DESC LIMIT 1`,
+			ssid).Scan(&routerID, &signal)
+		l.mu.Lock()
+		routerName := routerID
+		if rn := l.routerDisplayName(routerID); rn != "" {
+			routerName = rn
+		}
+		l.mu.Unlock()
+		alertID := "alert-new-ssid-" + ssid
+		l.engine.Emit(AlertEvent{
+			ID:       alertID,
+			Category: alerts.CatClients, // visible por defecto (signal=none)
+			Urgent:   false,
+			Severity: "info",
+			Title:    "New neighbor SSID",
+			Description: fmt.Sprintf("%s heard for the first time (by %s, %d dBm, since %s)",
+				ssid, routerName, signal, first.Format("15:04")),
+			Hint: alerts.HintFor(alerts.HintNewNeighborSsid),
+			Type: alerts.HintNewNeighborSsid,
+			Vars: map[string]string{
+				"ssid":   ssid,
+				"router": routerName,
+				"signal": fmt.Sprintf("%d", signal),
+				"since":  first.Format("15:04"),
+			},
+			RouterID: routerID,
+		})
+		// One-shot: alertado y conocido aunque desaparezca y vuelva.
+		_, _ = l.db.Exec(`INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING`, "ssid_alerted:"+ssid)
+		_, _ = l.db.Exec(`INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING`, "ssid_known:"+ssid)
+	}
+}

+ 107 - 0
server-go/internal/adapters/neighborssid_test.go

@@ -0,0 +1,107 @@
+package adapters
+
+// neighborssid_test.go — #1359: new-neighbor-ssid con dwell y one-shot.
+
+import (
+	"testing"
+	"time"
+)
+
+func newSsidAlerts(l *Live) []AlertEvent {
+	var out []AlertEvent
+	for _, a := range l.engine.List() {
+		if a.Type == "new-neighbor-ssid" {
+			out = append(out, a)
+		}
+	}
+	return out
+}
+
+func TestNewSsidSeedingDoesNotAlert(t *testing.T) {
+	l, _ := newImpostorLive(t) // flota: "temiscira" propio
+	now := time.Now()
+	// Vecino de siempre (lleva 10h): en la primera evaluación se siembra,
+	// no alerta (anti-avalancha de arranque).
+	insertScan(t, l, "ap1", "11:22:33:44:55:01", "vecino-historico", now.Add(-10*time.Hour))
+	insertScan(t, l, "ap1", "11:22:33:44:55:01", "vecino-historico", now)
+	l.EvalNewNeighborSsids()
+	if got := newSsidAlerts(l); len(got) != 0 {
+		t.Fatalf("la siembra no debe alertar: %+v", got)
+	}
+	var seeded int
+	_ = l.db.QueryRow(`SELECT COUNT(1) FROM kv WHERE key='ssid_known_seeded'`).Scan(&seeded)
+	if seeded != 1 {
+		t.Fatal("kv ssid_known_seeded no escrito")
+	}
+	_ = l.db.QueryRow(`SELECT COUNT(1) FROM kv WHERE key='ssid_known:vecino-historico'`).Scan(&seeded)
+	if seeded != 1 {
+		t.Fatal("vecino histórico no quedó sembrado como conocido")
+	}
+}
+
+func TestNewSsidTransientStaysQuiet(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	// Siembra con la flota sola.
+	l.EvalNewNeighborSsids()
+	// Hotspot de paso: 2 sightings separados 1h (< dwell 4h), ya no activo.
+	insertScan(t, l, "ap1", "11:22:33:44:55:02", "hotspot-movil", now.Add(-90*time.Minute))
+	insertScan(t, l, "ap1", "11:22:33:44:55:02", "hotspot-movil", now.Add(-30*time.Minute))
+	l.EvalNewNeighborSsids()
+	if got := newSsidAlerts(l); len(got) != 0 {
+		t.Fatalf("transitorio no debe alertar: %+v", got)
+	}
+}
+
+func TestNewSsidAlertsAfterDwellOnce(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	l.EvalNewNeighborSsids() // siembra
+	// SSID nuevo que persiste 5h y sigue activo.
+	insertScan(t, l, "ap1", "11:22:33:44:55:03", "iot-pairing", now.Add(-5*time.Hour))
+	insertScan(t, l, "ap1", "11:22:33:44:55:03", "iot-pairing", now.Add(-3*time.Hour))
+	l.EvalNewNeighborSsids()
+	if got := newSsidAlerts(l); len(got) != 0 {
+		t.Fatalf("a los 3h de dwell no debe alertar aún... espera, esto ya son 5h")
+	}
+	insertScan(t, l, "ap1", "11:22:33:44:55:03", "iot-pairing", now)
+	l.EvalNewNeighborSsids()
+	got := newSsidAlerts(l)
+	if len(got) != 1 {
+		t.Fatalf("dwell cumplido y activo debe alertar: %d", len(got))
+	}
+	a := got[0]
+	if a.Urgent || a.Severity != "info" || a.Category != "clients" {
+		t.Fatalf("info/no urgente/clients: %+v", a)
+	}
+	if a.Vars["ssid"] != "iot-pairing" || a.Vars["router"] != "AP Uno" || a.Vars["signal"] != "-55" {
+		t.Fatalf("vars: %+v", a.Vars)
+	}
+	// One-shot: re-evaluar con más sightings no repite.
+	insertScan(t, l, "ap1", "11:22:33:44:55:03", "iot-pairing", now.Add(1*time.Minute))
+	l.EvalNewNeighborSsids()
+	if got := newSsidAlerts(l); len(got) != 1 {
+		t.Fatalf("one-shot: no debe repetir; alertas: %d", len(got))
+	}
+	// Persistido en kv (sobrevive a la poda de 48h y a reinicios).
+	var n int
+	_ = l.db.QueryRow(`SELECT COUNT(1) FROM kv WHERE key='ssid_alerted:iot-pairing'`).Scan(&n)
+	if n != 1 {
+		t.Fatal("ssid_alerted no persistido en kv")
+	}
+}
+
+func TestNewSsidFleetAndEmptyIgnored(t *testing.T) {
+	l, _ := newImpostorLive(t)
+	now := time.Now()
+	l.EvalNewNeighborSsids() // siembra
+	// SSID propio de la flota y SSID vacío (red oculta): nunca alertan.
+	insertScan(t, l, "ap1", "AA:BB:CC:00:00:09", "temiscira", now.Add(-6*time.Hour))
+	insertScan(t, l, "ap1", "AA:BB:CC:00:00:09", "temiscira", now)
+	insertScan(t, l, "ap1", "11:22:33:44:55:04", "", now.Add(-6*time.Hour))
+	insertScan(t, l, "ap1", "11:22:33:44:55:04", "", now)
+	l.EvalNewNeighborSsids()
+	if got := newSsidAlerts(l); len(got) != 0 {
+		t.Fatalf("flota/vacío no alertan: %+v", got)
+	}
+}

+ 2 - 0
server-go/internal/alerts/alerts.go

@@ -96,6 +96,7 @@ const (
 	HintDeviceOffline = "device-offline"
 	HintUnknownDevice = "unknown-device"
 	HintSsidImpostor  = "wifi-ssid-impostor"
+	HintNewNeighborSsid = "new-neighbor-ssid"
 	HintFirmware      = "firmware-outdated"
 	HintWanDown       = "wan-down"
 	HintWifiWeak      = "wifi-weak"
@@ -152,6 +153,7 @@ var Hints = map[string]string{
 	HintDeviceOffline: "Verify the device power and network cable.",
 	HintUnknownDevice: "If you do not recognize it, block it or mark it as trusted in Settings.",
 	HintSsidImpostor:  "An unknown radio is broadcasting your network name. Check the area around the hearing AP; if you do not recognize the BSSID, treat it as a rogue AP.",
+	HintNewNeighborSsid: "A new network name has been broadcasting nearby for hours. If it is not yours, find out what it is (a new router, an IoT device in pairing mode, a hotspot); if it is a permanent neighbor you do not care about, dismiss the alert - it will not repeat.",
 	HintFirmware:      "Your router has newer firmware available; check Firmware upgrades (Labs) or LuCI.",
 	HintWanDown:       "Check the modem/ONT and contact your ISP if the outage persists.",
 	HintWifiWeak:      "Move the device closer to an access point or relocate the AP.",

+ 4 - 0
server-go/internal/httpapi/agent.go

@@ -275,6 +275,10 @@ func (s *server) handleIngestAgent(w http.ResponseWriter, r *http.Request) {
 		if ev, ok := s.adapter.(interface{ EvalSsidImpostors() }); ok {
 			ev.EvalSsidImpostors()
 		}
+		// #1359: misma coyuntura para SSIDs vecinos nuevos con dwell.
+		if ev, ok := s.adapter.(interface{ EvalNewNeighborSsids() }); ok {
+			ev.EvalNewNeighborSsids()
+		}
 	}
 	// #1214: survey crudo del agente para la lente "Ahora" en unidades
 	// agent-only. El adaptador Live lo cachea en memoria con TTL; los