Selaa lähdekoodia

feat(devices): prefer mDNS over placeholder names

Closes #2159
Nacho 2 viikkoa sitten
vanhempi
sitoutus
70932d9f4b

+ 1 - 0
CHANGELOG.md

@@ -10,6 +10,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ### Fixed
 
 - Devices named only by mDNS now use that hostname in the existing type rules, so a vacuum or console without a DHCP hostname no longer stays unknown (#2157).
+- Useful mDNS names now replace generated DHCP placeholders without overriding reservations, aliases or manual choices. The improved name and inferred type stay when mDNS temporarily disappears (#2159).
 
 ## [2.54.0] - 2026-11-21
 

+ 26 - 0
server-go/internal/adapters/device_name_placeholder.go

@@ -0,0 +1,26 @@
+package adapters
+
+import (
+	"regexp"
+	"strings"
+)
+
+var (
+	generatedPlatformNameRE  = regexp.MustCompile(`^(?:android|iphone|ipad|tablet|phone|device)[-_]([a-z0-9]{6,})$`)
+	generatedTechnicalNameRE = regexp.MustCompile(`^(?:shelly|esphome|esp|tasmota|plug)[a-z0-9]*[-_][0-9a-f]{6,12}$`)
+)
+
+// isGeneratedDeviceName reports whether a name is a generated placeholder,
+// not a useful device name chosen by the device owner. Keep the patterns
+// narrow: an ordinary model, version or location must never be demoted.
+func isGeneratedDeviceName(value string) bool {
+	name := strings.ToLower(strings.TrimSpace(value))
+	if name == "" {
+		return false
+	}
+	if generatedTechnicalNameRE.MatchString(name) {
+		return true
+	}
+	match := generatedPlatformNameRE.FindStringSubmatch(name)
+	return len(match) == 2 && strings.ContainsAny(match[1], "0123456789")
+}

+ 31 - 0
server-go/internal/adapters/device_name_placeholder_test.go

@@ -0,0 +1,31 @@
+package adapters
+
+import "testing"
+
+func TestIsGeneratedDeviceName(t *testing.T) {
+	tests := []struct {
+		name string
+		in   string
+		want bool
+	}{
+		{name: "android random suffix", in: "android-7F3A9C2D", want: true},
+		{name: "android random suffix with underscore", in: "android_7f3a9c2d", want: true},
+		{name: "shelly technical suffix", in: "shelly1-8CAAB50000A2", want: true},
+		{name: "esphome technical suffix", in: "esphome-abcdef12", want: true},
+		{name: "meaningful iphone name", in: "iPhone-de-Nacho", want: false},
+		{name: "meaningful vacuum name", in: "roomba-cocina", want: false},
+		{name: "android version is not a random suffix", in: "android-13", want: false},
+		{name: "ordinary hostname", in: "pixel-8-pro", want: false},
+		{name: "shelly location is not a technical suffix", in: "shelly1-kitchen", want: false},
+		{name: "unrelated technical looking hostname", in: "server-deadbeef", want: false},
+		{name: "empty", in: "", want: false},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := isGeneratedDeviceName(tt.in); got != tt.want {
+				t.Errorf("isGeneratedDeviceName(%q) = %v, want %v", tt.in, got, tt.want)
+			}
+		})
+	}
+}

+ 28 - 9
server-go/internal/adapters/device_seen.go

@@ -195,12 +195,16 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) []Device {
 	// alta otra vez; el borrado es un olvido, no un baneo.
 	l.reviveTombstoned(tomb, devices)
 	// MACs ya registradas: la diferencia serán las verdaderamente nuevas.
+	// Conservamos también la identidad retenida para que un placeholder que
+	// reaparece sin mDNS no pise el nombre y el tipo buenos del registro.
 	existing := map[string]bool{}
-	if rows, err := l.db.Query("SELECT mac FROM device_seen"); err == nil {
+	retainedNames := map[string]string{}
+	if rows, err := l.db.Query("SELECT mac, COALESCE(name, '') FROM device_seen"); err == nil {
 		for rows.Next() {
-			var m string
-			if rows.Scan(&m) == nil {
+			var m, name string
+			if rows.Scan(&m, &name) == nil {
 				existing[m] = true
+				retainedNames[m] = name
 			}
 		}
 		rows.Close()
@@ -233,19 +237,25 @@ func (l *Live) noteDevicesSeen(devices []Device, nowMs int64) []Device {
 			continue // #1278: borrado a mano, no re-alta (ni re-aviso, #1290)
 		}
 		name := d.Hostname
-		if isMACLike(name) {
+		if isMACLike(name) || (isGeneratedDeviceName(name) && !d.namePinned) {
 			name = ""
 		}
-		if name == "" && d.Name != "" && !isMACLike(d.Name) {
+		if name == "" && d.Name != "" && !isMACLike(d.Name) && (!isGeneratedDeviceName(d.Name) || d.namePinned) {
 			name = d.Name
 		}
+		deviceType := inferredDeviceType(d)
+		if name == "" && !d.namePinned && isGeneratedDeviceName(d.Name) && retainedNames[mac] != "" && !isGeneratedDeviceName(retainedNames[mac]) {
+			// A transient loss of mDNS brought the DHCP placeholder back. Empty
+			// name and type make the upsert keep the better retained identity.
+			deviceType = ""
+		}
 		// #1818: el alta guarda el primer avistamiento real, no el del ciclo en
 		// que el cliente supero el minuto de permanencia.
 		first := nowMs
 		if d.FirstSeenMs > 0 && d.FirstSeenMs < nowMs {
 			first = d.FirstSeenMs
 		}
-		if _, err := stmt.Exec(mac, first, nowMs, name, saneIP(d.IP), inferredDeviceType(d)); err != nil {
+		if _, err := stmt.Exec(mac, first, nowMs, name, saneIP(d.IP), deviceType); err != nil {
 			return nil
 		}
 		// #1323: primera vez CON nombre (los sin nombre los cubre
@@ -352,10 +362,16 @@ func (l *Live) applyDeviceSeen(devices []Device) {
 			// (#1151) el merge puede dejar como nombre la MAC de una alias,
 			// que tampoco es un nombre. Los alias/override reales nunca son
 			// MAC-shaped, así que siguen sin pisarse.
-			if s.name != "" && isMACLike(devices[i].Name) {
-				devices[i].Name = s.name
+			restoredGeneratedName := false
+			if s.name != "" && !isGeneratedDeviceName(s.name) {
+				if isMACLike(devices[i].Name) {
+					devices[i].Name = s.name
+				} else if isGeneratedDeviceName(devices[i].Name) && !devices[i].namePinned {
+					devices[i].Name = s.name
+					restoredGeneratedName = true
+				}
 			}
-			if s.name != "" && devices[i].Hostname == "" {
+			if s.name != "" && !isGeneratedDeviceName(s.name) && devices[i].Hostname == "" {
 				devices[i].Hostname = s.name
 			}
 			if s.ip != "" && devices[i].IP == "" {
@@ -369,6 +385,9 @@ func (l *Live) applyDeviceSeen(devices []Device) {
 			if devices[i].TypeOverride == "" && devices[i].Type == "desconocido" && s.deviceType != "" {
 				devices[i].Type = s.deviceType
 			}
+			if devices[i].TypeOverride == "" && restoredGeneratedName && s.deviceType != "" {
+				devices[i].Type = s.deviceType
+			}
 		}
 	}
 }

+ 12 - 5
server-go/internal/adapters/live.go

@@ -4083,10 +4083,14 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 				d.IP = ip
 			}
 		}
+		if hasRes && res.Name != "" && d.Name == res.Name {
+			d.namePinned = true
+		}
 		// issue #196: la allowlist manda sobre el nombre por defecto. Con
 		// alias (Name != MAC) el dispositivo deja de ser "desconocido".
 		if alias, ok := knownMacs[mac]; ok && alias != "" {
 			d.Name = alias
+			d.namePinned = true
 		}
 		// issue #437/#797: overrides manuales (icono, nombre) se aplican sobre
 		// el dispositivo auto-descubierto; el nombre manual manda incluso
@@ -4098,6 +4102,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 			if ov.Name != "" {
 				d.Name = ov.Name
 				d.NameOverride = ov.Name
+				d.namePinned = true
 			}
 		}
 		vendorClass := ""
@@ -4115,12 +4120,14 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 				if svcs, ok := mdnsSvcByHost[host]; ok {
 					d.MdnsServices = svcs
 				}
-				// If the device has no name (just MAC), use the mDNS hostname.
-				if d.Name == mac {
+				// mDNS can replace a MAC fallback or an unpinned generated name.
+				// A meaningful DHCP name, reservation, alias or manual name stays.
+				if !d.namePinned && !isGeneratedDeviceName(host) && (d.Name == mac || isGeneratedDeviceName(d.Name)) {
+					previousName := d.Name
 					d.Name = host
-					// The first guess only had the MAC. Let the mDNS hostname
-					// feed the same rules without replacing another source's type.
-					if d.Type == "desconocido" {
+					// The first guess only had the MAC or a placeholder. Let the
+					// mDNS hostname feed the same rules without replacing other evidence.
+					if d.Type == "desconocido" || isGeneratedDeviceName(previousName) {
 						d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
 					}
 				}

+ 204 - 0
server-go/internal/adapters/mdns_placeholder_test.go

@@ -0,0 +1,204 @@
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestBuildDevicesMdnsReplacesOnlyUnpinnedPlaceholders(t *testing.T) {
+	tests := []struct {
+		name            string
+		mac             string
+		ip              string
+		dhcpName        string
+		mdnsName        string
+		reservationName string
+		aliasName       string
+		overrideName    string
+		overrideType    string
+		wantName        string
+		wantType        string
+	}{
+		{
+			name:     "mDNS name replaces an Android DHCP placeholder",
+			mac:      "02:00:00:00:10:01",
+			ip:       "192.0.2.101",
+			dhcpName: "android-7F3A9C2D",
+			mdnsName: "iPhone-de-Nacho",
+			wantName: "iPhone-de-Nacho",
+			wantType: "movil",
+		},
+		{
+			name:     "mDNS name and type replace an Android DHCP placeholder",
+			mac:      "02:00:00:00:10:02",
+			ip:       "192.0.2.102",
+			dhcpName: "android-7F3A9C2D",
+			mdnsName: "roomba-cocina",
+			wantName: "roomba-cocina",
+			wantType: "aspirador",
+		},
+		{
+			name:     "meaningful DHCP hostname stays",
+			mac:      "02:00:00:00:10:03",
+			ip:       "192.0.2.103",
+			dhcpName: "laptop-ana",
+			mdnsName: "roomba-cocina",
+			wantName: "laptop-ana",
+			wantType: "portatil",
+		},
+		{
+			name:     "mDNS placeholder cannot replace a meaningful DHCP hostname",
+			mac:      "02:00:00:00:10:04",
+			ip:       "192.0.2.104",
+			dhcpName: "laptop-ana",
+			mdnsName: "android-7F3A9C2D",
+			wantName: "laptop-ana",
+			wantType: "portatil",
+		},
+		{
+			name:            "DHCP reservation name stays",
+			mac:             "02:00:00:00:10:05",
+			ip:              "192.0.2.105",
+			mdnsName:        "roomba-cocina",
+			reservationName: "Reserva Ana",
+			wantName:        "Reserva Ana",
+			wantType:        "desconocido",
+		},
+		{
+			name:      "known MAC alias stays",
+			mac:       "02:00:00:00:10:06",
+			ip:        "192.0.2.106",
+			mdnsName:  "roomba-cocina",
+			aliasName: "Alias Ana",
+			wantName:  "Alias Ana",
+			wantType:  "desconocido",
+		},
+		{
+			name:         "manual name and type stay",
+			mac:          "02:00:00:00:10:07",
+			ip:           "192.0.2.107",
+			dhcpName:     "android-7F3A9C2D",
+			mdnsName:     "roomba-cocina",
+			overrideName: "Consola salón",
+			overrideType: "consola",
+			wantName:     "Consola salón",
+			wantType:     "consola",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			cfg := RouterConfig{ID: "gateway", Host: "192.0.2.1", Name: "openwrt", IsGateway: true, AgentOnly: true}
+			var l *Live
+			if tt.aliasName != "" || tt.overrideName != "" || tt.overrideType != "" {
+				d := openLiveTestDB(t)
+				if tt.aliasName != "" {
+					if _, err := d.Exec("INSERT INTO known_macs (mac, name, created_at) VALUES (?, ?, 1)", tt.mac, tt.aliasName); err != nil {
+						t.Fatalf("seed alias: %v", err)
+					}
+				}
+				if tt.overrideName != "" || tt.overrideType != "" {
+					if _, err := d.Exec(`INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, created_at, updated_at)
+						VALUES (?, '', ?, ?, '', 1, 1)`, tt.mac, tt.overrideName, tt.overrideType); err != nil {
+						t.Fatalf("seed override: %v", err)
+					}
+				}
+				l = NewLive(nil, d, []RouterConfig{cfg}, nil)
+			} else {
+				l = NewLive(nil, nil, []RouterConfig{cfg}, nil)
+			}
+
+			dhcp := &probe.DHCPData{}
+			if tt.dhcpName != "" {
+				dhcp.Leases = []probe.DhcpLease{{MAC: tt.mac, IP: tt.ip, Hostname: tt.dhcpName}}
+			}
+			if tt.reservationName != "" {
+				dhcp.Reservations = []probe.DhcpReservation{{MAC: tt.mac, IP: tt.ip, Name: tt.reservationName}}
+			}
+			payload := &probe.Payload{
+				Router: "gateway", Ts: 1, Version: "2.54.0",
+				Data: probe.PayloadData{
+					FDB:  &probe.FDBData{MACs: map[string]string{tt.mac: "lan2"}},
+					Arp:  map[string]string{tt.mac: tt.ip},
+					DHCP: dhcp,
+					Discovery: &probe.DiscoveryData{
+						HostByIP: map[string]string{tt.ip: tt.mdnsName},
+						Services: map[string][]string{tt.mdnsName: nil},
+					},
+				},
+			}
+
+			devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
+			for _, d := range devices {
+				if d.MAC != tt.mac {
+					continue
+				}
+				if d.Name != tt.wantName {
+					t.Errorf("name = %q, want %q", d.Name, tt.wantName)
+				}
+				if d.Type != tt.wantType {
+					t.Errorf("type = %q, want %q", d.Type, tt.wantType)
+				}
+				return
+			}
+			t.Fatalf("device %s not found", tt.mac)
+		})
+	}
+}
+
+func TestMdnsImprovedNameSurvivesMissingAnnouncement(t *testing.T) {
+	d := openLiveTestDB(t)
+	cfg := RouterConfig{ID: "gateway", Host: "192.0.2.1", Name: "openwrt", IsGateway: true, AgentOnly: true}
+	l := NewLive(nil, d, []RouterConfig{cfg}, nil)
+	const mac = "02:00:00:00:10:08"
+	const ip = "192.0.2.108"
+
+	firstPayload := mdnsPlaceholderPayload(mac, ip, "android-7F3A9C2D", "roomba-cocina", true)
+	first := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, firstPayload)}, "")
+	if len(first) != 1 || first[0].Name != "roomba-cocina" || first[0].Type != "aspirador" {
+		t.Fatalf("first cycle = %+v, want roomba-cocina/aspirador", first)
+	}
+	l.noteDevicesSeen(first, 1000)
+	l.applyDeviceSeen(first)
+
+	secondPayload := mdnsPlaceholderPayload(mac, ip, "android-7F3A9C2D", "", false)
+	second := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, secondPayload)}, "")
+	l.noteDevicesSeen(second, 2000)
+	l.applyDeviceSeen(second)
+	if len(second) != 1 {
+		t.Fatalf("second cycle has %d devices, want 1", len(second))
+	}
+	if second[0].Name != "roomba-cocina" {
+		t.Errorf("second cycle name = %q, want retained roomba-cocina", second[0].Name)
+	}
+	if second[0].Type != "aspirador" {
+		t.Errorf("second cycle type = %q, want retained aspirador", second[0].Type)
+	}
+
+	var storedName, storedType string
+	if err := d.QueryRow("SELECT name, device_type FROM device_seen WHERE mac = ?", mac).Scan(&storedName, &storedType); err != nil {
+		t.Fatal(err)
+	}
+	if storedName != "roomba-cocina" || storedType != "aspirador" {
+		t.Errorf("stored identity = %q/%q, want roomba-cocina/aspirador", storedName, storedType)
+	}
+}
+
+func mdnsPlaceholderPayload(mac, ip, dhcpName, mdnsName string, withMDNS bool) *probe.Payload {
+	data := probe.PayloadData{
+		Wireless: &probe.WirelessData{Clients: map[string]probe.WirelessClient{
+			mac: {SignalDbm: -50, Band: "5 GHz"},
+		}},
+		FDB:  &probe.FDBData{MACs: map[string]string{mac: "lan2"}},
+		Arp:  map[string]string{mac: ip},
+		DHCP: &probe.DHCPData{Leases: []probe.DhcpLease{{MAC: mac, IP: ip, Hostname: dhcpName}}},
+	}
+	if withMDNS {
+		data.Discovery = &probe.DiscoveryData{
+			HostByIP: map[string]string{ip: mdnsName},
+			Services: map[string][]string{mdnsName: nil},
+		}
+	}
+	return &probe.Payload{Router: "gateway", Ts: 1, Version: "2.54.0", Data: data}
+}

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

@@ -406,6 +406,10 @@ type Device struct {
 	// el override crudo para que la UI de edición pueda mostrarlo y limpiarlo.
 	NameOverride string `json:"nameOverride,omitempty"`
 	TypeOverride string `json:"typeOverride,omitempty"`
+	// namePinned: el nombre viene de una reserva, un alias o una edición manual.
+	// Es interno y nunca viaja en JSON. mDNS no puede sustituirlo por un nombre
+	// automático mejor (#2159).
+	namePinned bool
 	// NotifyOffline (#1354): opt-in del usuario para alertar cuando este
 	// dispositivo se desconecta (override persistido notify_offline).
 	NotifyOffline bool `json:"notifyOffline,omitempty"`