Ver código fonte

feat(devices): identify products from mDNS TXT metadata

Closes #2158
Nacho 1 semana atrás
pai
commit
5dcb74b4de

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- mDNS TXT model and manufacturer metadata can now disambiguate products that share a service. Real fixtures distinguish LG TVs from Marantz speakers over AirPlay, and old agents keep the existing generic behavior (#2158).
+
 ### 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).

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.46
+3.0.47

+ 2 - 7
agent/probe/local.go

@@ -1303,12 +1303,7 @@ func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *Di
 	// which is the service's label rather than the device's own.
 	if out := p.runBest(ctx, CmdMdnsHosts, 5*time.Second); strings.TrimSpace(out) != "" {
 		if hosts := ParseMdnsHosts([]byte(out)); len(hosts) > 0 {
-			if dd.HostByIP == nil {
-				dd.HostByIP = map[string]string{}
-			}
-			for ip, name := range hosts {
-				dd.HostByIP[ip] = name
-			}
+			dd.MergeMdnsHosts(hosts)
 		}
 	}
 
@@ -1320,7 +1315,7 @@ func (p *Prober) probeDiscovery(ctx context.Context, wireless *WirelessData) *Di
 			}
 		}
 	}
-	if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.RandomMACs) == 0 {
+	if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.Models) == 0 && len(dd.Manufacturers) == 0 && len(dd.RandomMACs) == 0 {
 		return nil
 	}
 	return dd

+ 292 - 0
agent/probe/mdns_discovery.go

@@ -0,0 +1,292 @@
+package probe
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"strings"
+	"unicode"
+	"unicode/utf8"
+)
+
+const (
+	maxMdnsTXTRecords     = 64
+	maxMdnsTXTValueLength = 4096
+	maxMdnsMetadataLength = 128
+)
+
+type mdnsWireRecord struct {
+	IPv4 string
+	Host string
+	TXT  []string
+}
+
+// UnmarshalJSON preserves repeated TXT keys emitted by umdns. Decoding into a
+// Go map would silently keep only the last one.
+func (r *mdnsWireRecord) UnmarshalJSON(data []byte) error {
+	dec := json.NewDecoder(bytes.NewReader(data))
+	opening, err := dec.Token()
+	if err != nil {
+		return err
+	}
+	if opening != json.Delim('{') {
+		return fmt.Errorf("mDNS record is not an object")
+	}
+	for dec.More() {
+		token, err := dec.Token()
+		if err != nil {
+			return err
+		}
+		key, ok := token.(string)
+		if !ok {
+			return fmt.Errorf("mDNS record key is not a string")
+		}
+		if key == "txt" {
+			var value any
+			if err := dec.Decode(&value); err != nil {
+				return err
+			}
+			r.TXT = appendMdnsTXT(r.TXT, value)
+			continue
+		}
+		var raw json.RawMessage
+		if err := dec.Decode(&raw); err != nil {
+			return err
+		}
+		switch key {
+		case "ipv4":
+			if err := json.Unmarshal(raw, &r.IPv4); err != nil {
+				return err
+			}
+		case "host":
+			if err := json.Unmarshal(raw, &r.Host); err != nil {
+				return err
+			}
+		}
+	}
+	_, err = dec.Token()
+	return err
+}
+
+func appendMdnsTXT(dst []string, value any) []string {
+	if len(dst) >= maxMdnsTXTRecords {
+		return dst
+	}
+	switch v := value.(type) {
+	case string:
+		if len(v) <= maxMdnsTXTValueLength {
+			return append(dst, v)
+		}
+	case []any:
+		for _, item := range v {
+			text, ok := item.(string)
+			if ok && len(text) <= maxMdnsTXTValueLength && len(dst) < maxMdnsTXTRecords {
+				dst = append(dst, text)
+			}
+		}
+	}
+	return dst
+}
+
+func parseMdnsBrowseRecords(raw []byte) *DiscoveryData {
+	if len(raw) == 0 {
+		return nil
+	}
+	var top map[string]json.RawMessage
+	if json.Unmarshal(raw, &top) != nil || len(top) == 0 {
+		return nil
+	}
+	dd := &DiscoveryData{
+		Services:      map[string][]string{},
+		HostByIP:      map[string]string{},
+		Models:        map[string]string{},
+		Manufacturers: map[string]string{},
+	}
+	for key, rawRecord := range top {
+		var direct mdnsWireRecord
+		if json.Unmarshal(rawRecord, &direct) == nil && (direct.IPv4 != "" || direct.Host != "" || len(direct.TXT) > 0) {
+			host := direct.Host
+			if host == "" {
+				host = mdnsShortName(key)
+			}
+			dd.addMdnsRecord(host, mdnsServiceFromFQDN(key), direct)
+			continue
+		}
+
+		var instances map[string]json.RawMessage
+		if json.Unmarshal(rawRecord, &instances) != nil {
+			continue
+		}
+		for instance, rawInstance := range instances {
+			var record mdnsWireRecord
+			if json.Unmarshal(rawInstance, &record) != nil {
+				continue
+			}
+			host := record.Host
+			if host == "" {
+				host = instance
+			}
+			dd.addMdnsRecord(host, key, record)
+		}
+	}
+	if len(dd.Services) == 0 && len(dd.HostByIP) == 0 && len(dd.Models) == 0 && len(dd.Manufacturers) == 0 {
+		return nil
+	}
+	return dd
+}
+
+func mdnsShortName(value string) string {
+	name := strings.TrimSpace(strings.TrimSuffix(value, "."))
+	if idx := strings.Index(name, "."); idx > 0 {
+		name = name[:idx]
+	}
+	return name
+}
+
+func mdnsServiceFromFQDN(fqdn string) string {
+	parts := strings.SplitN(fqdn, ".", 3)
+	if len(parts) < 2 || !strings.HasPrefix(parts[1], "_") {
+		return ""
+	}
+	service := parts[1]
+	if len(parts) >= 3 {
+		service += "." + strings.SplitN(parts[2], ".", 2)[0]
+	}
+	return service
+}
+
+func (dd *DiscoveryData) addMdnsRecord(host, service string, record mdnsWireRecord) {
+	host = mdnsShortName(host)
+	if host == "" {
+		return
+	}
+	if service != "" {
+		dd.Services[host] = appendUnique(dd.Services[host], service)
+	}
+	if record.IPv4 != "" {
+		dd.HostByIP[record.IPv4] = host
+	}
+	for _, entry := range record.TXT {
+		key, value, ok := strings.Cut(entry, "=")
+		if !ok {
+			continue
+		}
+		value = cleanMdnsMetadata(value)
+		if value == "" {
+			continue
+		}
+		switch strings.ToLower(strings.TrimSpace(key)) {
+		case "model":
+			if dd.Models[host] == "" {
+				dd.Models[host] = value
+			}
+		case "manufacturer":
+			if dd.Manufacturers[host] == "" {
+				dd.Manufacturers[host] = value
+			}
+		}
+	}
+}
+
+func cleanMdnsMetadata(value string) string {
+	value = strings.TrimSpace(value)
+	if value == "" || len(value) > maxMdnsMetadataLength || !utf8.ValidString(value) {
+		return ""
+	}
+	for _, r := range value {
+		if unicode.IsControl(r) {
+			return ""
+		}
+	}
+	return value
+}
+
+// MergeMdnsHosts joins host records with service metadata. A host with no SRV
+// target can only inherit metadata when exactly one model candidate matches
+// its name prefix. Ambiguous candidates stay unattributed.
+func (dd *DiscoveryData) MergeMdnsHosts(hosts map[string]string) {
+	if dd == nil {
+		return
+	}
+	if dd.HostByIP == nil {
+		dd.HostByIP = map[string]string{}
+	}
+	if dd.Services == nil {
+		dd.Services = map[string][]string{}
+	}
+	if dd.Models == nil {
+		dd.Models = map[string]string{}
+	}
+	if dd.Manufacturers == nil {
+		dd.Manufacturers = map[string]string{}
+	}
+	for ip, rawHost := range hosts {
+		host := mdnsShortName(rawHost)
+		if host == "" {
+			continue
+		}
+		dd.HostByIP[ip] = host
+		if dd.Models[host] != "" || dd.Manufacturers[host] != "" {
+			continue
+		}
+		candidate := dd.uniqueMetadataHost(host)
+		if candidate != "" {
+			dd.moveMdnsHost(candidate, host)
+		}
+	}
+}
+
+func (dd *DiscoveryData) uniqueMetadataHost(host string) string {
+	normalizedHost := normalizeMdnsHost(host)
+	if len(normalizedHost) < 6 {
+		return ""
+	}
+	candidate := ""
+	for key := range dd.Models {
+		if key == host || !strings.HasPrefix(normalizeMdnsHost(key), normalizedHost) {
+			continue
+		}
+		if candidate != "" {
+			return ""
+		}
+		candidate = key
+	}
+	return candidate
+}
+
+func normalizeMdnsHost(value string) string {
+	var b strings.Builder
+	for _, r := range strings.ToLower(value) {
+		if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
+			b.WriteRune(r)
+		}
+	}
+	return b.String()
+}
+
+func (dd *DiscoveryData) moveMdnsHost(from, to string) {
+	if from == "" || from == to {
+		return
+	}
+	for _, service := range dd.Services[from] {
+		dd.Services[to] = appendUnique(dd.Services[to], service)
+	}
+	delete(dd.Services, from)
+	if model := dd.Models[from]; model != "" {
+		if dd.Models[to] == "" {
+			dd.Models[to] = model
+		}
+		delete(dd.Models, from)
+	}
+	if manufacturer := dd.Manufacturers[from]; manufacturer != "" {
+		if dd.Manufacturers[to] == "" {
+			dd.Manufacturers[to] = manufacturer
+		}
+		delete(dd.Manufacturers, from)
+	}
+	for ip, host := range dd.HostByIP {
+		if host == from {
+			dd.HostByIP[ip] = to
+		}
+	}
+}

+ 106 - 0
agent/probe/mdns_discovery_test.go

@@ -0,0 +1,106 @@
+package probe
+
+import (
+	"strings"
+	"testing"
+)
+
+// Real AirPlay records captured from umdns on 21 Nov 2026. IPs are TEST-NET-1
+// and serials, device IDs, public keys and other identifiers are omitted.
+const mdnsNestedAirplayFixture = `{
+  "_airplay._tcp": {
+    "marantz": {
+      "iface": "br-lan",
+      "txt": "acl=0",
+      "txt": "model=Marantz NR1608",
+      "txt": "manufacturer=Marantz",
+      "host": "marantz.local",
+      "port": 7000,
+      "ipv4": "192.0.2.22"
+    },
+    "[LG] webOS TV OLED77CX6LA": {
+      "iface": "br-lan",
+      "txt": "acl=0",
+      "txt": "model=OLED77CX6LA",
+      "txt": "manufacturer=LG Electronics"
+    }
+  }
+}`
+
+func TestParseMdnsBrowseNestedAirplayWithRepeatedTXT(t *testing.T) {
+	dd := ParseMdnsBrowse([]byte(mdnsNestedAirplayFixture))
+	if dd == nil {
+		t.Fatal("expected nested mDNS records to parse")
+	}
+	dd.MergeMdnsHosts(map[string]string{
+		"192.0.2.22": "marantz",
+		"192.0.2.33": "LGwebOSTV",
+	})
+
+	if got := dd.HostByIP["192.0.2.22"]; got != "marantz" {
+		t.Errorf("Marantz host = %q, want marantz", got)
+	}
+	if got := dd.HostByIP["192.0.2.33"]; got != "LGwebOSTV" {
+		t.Errorf("LG host = %q, want LGwebOSTV", got)
+	}
+	if got := dd.Models["marantz"]; got != "Marantz NR1608" {
+		t.Errorf("Marantz model = %q, want Marantz NR1608", got)
+	}
+	if got := dd.Manufacturers["marantz"]; got != "Marantz" {
+		t.Errorf("Marantz manufacturer = %q, want Marantz", got)
+	}
+	if got := dd.Models["LGwebOSTV"]; got != "OLED77CX6LA" {
+		t.Errorf("LG model = %q, want OLED77CX6LA", got)
+	}
+	if got := dd.Manufacturers["LGwebOSTV"]; got != "LG Electronics" {
+		t.Errorf("LG manufacturer = %q, want LG Electronics", got)
+	}
+	for _, host := range []string{"marantz", "LGwebOSTV"} {
+		services := dd.Services[host]
+		found := false
+		for _, service := range services {
+			if service == "_airplay._tcp" {
+				found = true
+			}
+		}
+		if !found {
+			t.Errorf("services for %q = %v, want _airplay._tcp", host, services)
+		}
+	}
+}
+
+func TestParseMdnsBrowseMetadataBounds(t *testing.T) {
+	raw := `{"_airplay._tcp":{"bad":{"txt":"model=` + strings.Repeat("x", maxMdnsMetadataLength+1) + `","txt":"manufacturer=LG Electronics","ipv4":"192.0.2.33"}}}`
+	dd := ParseMdnsBrowse([]byte(raw))
+	if dd == nil {
+		t.Fatal("expected record with valid manufacturer")
+	}
+	if got := dd.Models["bad"]; got != "" {
+		t.Errorf("oversized model = %q, want empty", got)
+	}
+	if got := dd.Manufacturers["bad"]; got != "LG Electronics" {
+		t.Errorf("manufacturer = %q, want LG Electronics", got)
+	}
+
+	control := ParseMdnsBrowse([]byte(`{"_airplay._tcp":{"bad":{"txt":"model=OLED\n77","ipv4":"192.0.2.33"}}}`))
+	if control == nil || control.Models["bad"] != "" {
+		t.Errorf("model with control character = %q, want empty", control.Models["bad"])
+	}
+}
+
+func TestMergeMdnsHostsDoesNotGuessAmbiguousModel(t *testing.T) {
+	raw := `{
+		"_airplay._tcp": {
+			"[LG] webOS TV OLED77CX6LA": {"txt":"model=OLED77CX6LA"},
+			"[LG] webOS TV OLED55CX6LA": {"txt":"model=OLED55CX6LA"}
+		}
+	}`
+	dd := ParseMdnsBrowse([]byte(raw))
+	dd.MergeMdnsHosts(map[string]string{"192.0.2.33": "LGwebOSTV"})
+	if got := dd.Models["LGwebOSTV"]; got != "" {
+		t.Errorf("ambiguous model = %q, want empty", got)
+	}
+	if got := dd.Services["LGwebOSTV"]; len(got) != 0 {
+		t.Errorf("ambiguous services = %v, want none", got)
+	}
+}

+ 5 - 0
agent/probe/payload.go

@@ -308,6 +308,11 @@ type DiscoveryData struct {
 	// HostByIP: IP -> hostname from mDNS PTR records. Helps resolve devices
 	// that have no DHCP hostname.
 	HostByIP map[string]string `json:"hostByIp,omitempty"`
+	// Models: hostname -> model declared in mDNS TXT records. Optional, so
+	// older agents and servers remain compatible.
+	Models map[string]string `json:"models,omitempty"`
+	// Manufacturers: hostname -> manufacturer declared in mDNS TXT records.
+	Manufacturers map[string]string `json:"manufacturers,omitempty"`
 	// RandomMACs: MACs detected as locally-administered (bit 1 of byte 0 set).
 	// These are typically iOS/Android private WiFi addresses that rotate.
 	RandomMACs []string `json:"randomMacs,omitempty"`

+ 1 - 44
agent/probe/probe.go

@@ -2261,50 +2261,7 @@ func ParseMdnsHosts(raw []byte) map[string]string {
 // Extrae: hostname (de la clave, antes del primer punto) y tipos de servicio
 // (el segmento _service._tcp). También recoge IPs si aparecen en registros A.
 func ParseMdnsBrowse(raw []byte) *DiscoveryData {
-	if len(raw) == 0 {
-		return nil
-	}
-	// umdns browse devuelve un objeto JSON con claves "fqdn" y valores que
-	// contienen "port", "txt", "ipv4", etc. Parseamos como map genérico.
-	var browse map[string]json.RawMessage
-	if json.Unmarshal(raw, &browse) != nil {
-		return nil
-	}
-	if len(browse) == 0 {
-		return nil
-	}
-
-	dd := &DiscoveryData{
-		Services: map[string][]string{},
-		HostByIP: map[string]string{},
-	}
-	for fqdn, val := range browse {
-		// Extraer hostname: primera parte antes del "."
-		hostname := fqdn
-		if idx := strings.Index(fqdn, "."); idx > 0 {
-			hostname = fqdn[:idx]
-		}
-		// Extraer tipo de servicio: segundo segmento "_svc._tcp" o "_svc._udp"
-		parts := strings.SplitN(fqdn, ".", 3)
-		if len(parts) >= 2 && strings.HasPrefix(parts[1], "_") {
-			svcType := parts[1]
-			if len(parts) >= 3 {
-				svcType = parts[1] + "." + strings.SplitN(parts[2], ".", 2)[0]
-			}
-			dd.Services[hostname] = appendUnique(dd.Services[hostname], svcType)
-		}
-		// Extraer IP si disponible
-		var entry struct {
-			IPv4 string `json:"ipv4"`
-		}
-		if json.Unmarshal(val, &entry) == nil && entry.IPv4 != "" {
-			dd.HostByIP[entry.IPv4] = hostname
-		}
-	}
-	if len(dd.Services) == 0 && len(dd.HostByIP) == 0 {
-		return nil
-	}
-	return dd
+	return parseMdnsBrowseRecords(raw)
 }
 
 func appendUnique(slice []string, s string) []string {

+ 71 - 0
server-go/internal/adapters/classify_mdns_signatures.go

@@ -0,0 +1,71 @@
+package adapters
+
+import "strings"
+
+type mdnsProductSignature struct {
+	id           string
+	service      string
+	modelPrefix  string
+	manufacturer string
+	deviceType   string
+	fixture      string
+}
+
+var mdnsProductSignatures = []mdnsProductSignature{
+	{
+		id:           "marantz-airplay-speaker",
+		service:      "_airplay._tcp",
+		modelPrefix:  "marantz ",
+		manufacturer: "Marantz",
+		deviceType:   "altavoz",
+		fixture:      "real",
+	},
+	{
+		id:           "lg-airplay-tv",
+		service:      "_airplay._tcp",
+		modelPrefix:  "oled",
+		manufacturer: "LG Electronics",
+		deviceType:   "tv",
+		fixture:      "real",
+	},
+	{
+		id:           "apple-tv-airplay",
+		service:      "_airplay._tcp",
+		modelPrefix:  "appletv",
+		manufacturer: "Apple",
+		deviceType:   "tv",
+		fixture:      "simulated",
+	},
+	{
+		id:           "apple-homepod-airplay",
+		service:      "_airplay._tcp",
+		modelPrefix:  "audioaccessory",
+		manufacturer: "Apple",
+		deviceType:   "altavoz",
+		fixture:      "simulated",
+	},
+}
+
+// guessFromMdnsSignatures applies only product signatures backed by a real
+// fixture. Simulated entries document candidates and never classify.
+func guessFromMdnsSignatures(services []string, model, manufacturer string) string {
+	model = strings.ToLower(strings.TrimSpace(model))
+	manufacturer = strings.TrimSpace(manufacturer)
+	if model == "" {
+		return ""
+	}
+	for _, signature := range mdnsProductSignatures {
+		if signature.fixture != "real" || !ValidDeviceTypes[signature.deviceType] {
+			continue
+		}
+		if !strings.EqualFold(manufacturer, signature.manufacturer) || !strings.HasPrefix(model, strings.ToLower(signature.modelPrefix)) {
+			continue
+		}
+		for _, service := range services {
+			if strings.EqualFold(service, signature.service) {
+				return signature.deviceType
+			}
+		}
+	}
+	return ""
+}

+ 74 - 0
server-go/internal/adapters/classify_mdns_signatures_test.go

@@ -0,0 +1,74 @@
+package adapters
+
+import "testing"
+
+func TestGuessFromMdnsSignatures(t *testing.T) {
+	tests := []struct {
+		name         string
+		services     []string
+		model        string
+		manufacturer string
+		want         string
+	}{
+		{
+			name:         "Marantz real fixture is a speaker",
+			services:     []string{"_airplay._tcp"},
+			model:        "Marantz NR1608",
+			manufacturer: "Marantz",
+			want:         "altavoz",
+		},
+		{
+			name:         "LG real fixture is a TV",
+			services:     []string{"_airplay._tcp"},
+			model:        "OLED77CX6LA",
+			manufacturer: "LG Electronics",
+			want:         "tv",
+		},
+		{
+			name:         "Apple TV simulated candidate stays unclassified",
+			services:     []string{"_airplay._tcp"},
+			model:        "AppleTV14,1",
+			manufacturer: "Apple",
+			want:         "",
+		},
+		{
+			name:         "HomePod simulated candidate stays unclassified",
+			services:     []string{"_airplay._tcp"},
+			model:        "AudioAccessory5,1",
+			manufacturer: "Apple",
+			want:         "",
+		},
+		{
+			name:         "missing model gives no signature",
+			services:     []string{"_airplay._tcp"},
+			manufacturer: "Marantz",
+			want:         "",
+		},
+		{
+			name:         "unknown model gives no signature",
+			services:     []string{"_airplay._tcp"},
+			model:        "Unknown 2000",
+			manufacturer: "Unknown",
+			want:         "",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := guessFromMdnsSignatures(tt.services, tt.model, tt.manufacturer); got != tt.want {
+				t.Errorf("guessFromMdnsSignatures(%v, %q, %q) = %q, want %q", tt.services, tt.model, tt.manufacturer, got, tt.want)
+			}
+		})
+	}
+}
+
+func TestMdnsSignatureCatalogIsValid(t *testing.T) {
+	for _, signature := range mdnsProductSignatures {
+		if signature.fixture != "real" && signature.fixture != "simulated" {
+			t.Errorf("signature %s has invalid fixture %q", signature.id, signature.fixture)
+		}
+		if !ValidDeviceTypes[signature.deviceType] {
+			t.Errorf("signature %s returns unknown type %q", signature.id, signature.deviceType)
+		}
+	}
+}

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

@@ -3570,6 +3570,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 	mdnsHostByIP := map[string]string{}
 	randomMACs := map[string]bool{}
 	mdnsSvcByHost := map[string][]string{}
+	mdnsModelByHost := map[string]string{}
+	mdnsManufacturerByHost := map[string]string{}
 	for _, p := range polled {
 		if p.discovery == nil {
 			continue
@@ -3583,6 +3585,12 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		for host, svcs := range p.discovery.Services {
 			mdnsSvcByHost[host] = svcs
 		}
+		for host, model := range p.discovery.Models {
+			mdnsModelByHost[host] = model
+		}
+		for host, manufacturer := range p.discovery.Manufacturers {
+			mdnsManufacturerByHost[host] = manufacturer
+		}
 	}
 	type knownInfo struct {
 		routerID string
@@ -4115,8 +4123,11 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		// capacidades LLDP). Con nombre-MAC (sin hostname) queda "desconocido".
 		d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
 		// mDNS enrichment (#338): resolve hostname from IP → lookup services.
+		mdnsModel, mdnsManufacturer := "", ""
 		if d.IP != "" {
 			if host, ok := mdnsHostByIP[d.IP]; ok {
+				mdnsModel = mdnsModelByHost[host]
+				mdnsManufacturer = mdnsManufacturerByHost[host]
 				if svcs, ok := mdnsSvcByHost[host]; ok {
 					d.MdnsServices = svcs
 				}
@@ -4151,8 +4162,13 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		}
 		// mDNS-based type refinement (#338): if the hostname/DHCP classification
 		// yielded "desconocido" but mDNS services are available, try to classify.
+		// A real product signature is more specific than the generic service map.
 		if d.Type == "desconocido" && len(d.MdnsServices) > 0 {
-			d.Type = guessFromMdns(d.MdnsServices)
+			if signature := guessFromMdnsSignatures(d.MdnsServices, mdnsModel, mdnsManufacturer); signature != "" {
+				d.Type = signature
+			} else {
+				d.Type = guessFromMdns(d.MdnsServices)
+			}
 		}
 		// issue #797: el tipo manual manda sobre la clasificación (reglas,
 		// huella DHCP y refinación mDNS).

+ 106 - 0
server-go/internal/adapters/mdns_signatures_builddevices_test.go

@@ -0,0 +1,106 @@
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+func TestBuildDevicesUsesMdnsProductSignatures(t *testing.T) {
+	tests := []struct {
+		name         string
+		mac          string
+		ip           string
+		host         string
+		model        string
+		manufacturer string
+		overrideType string
+		wantType     string
+	}{
+		{
+			name:         "LG AirPlay signature beats the generic speaker fallback",
+			mac:          "02:00:00:00:20:01",
+			ip:           "192.0.2.201",
+			host:         "device-lg",
+			model:        "OLED77CX6LA",
+			manufacturer: "LG Electronics",
+			wantType:     "tv",
+		},
+		{
+			name:         "Marantz AirPlay signature stays a speaker",
+			mac:          "02:00:00:00:20:02",
+			ip:           "192.0.2.202",
+			host:         "device-marantz",
+			model:        "Marantz NR1608",
+			manufacturer: "Marantz",
+			wantType:     "altavoz",
+		},
+		{
+			name:         "payload without metadata keeps the generic fallback",
+			mac:          "02:00:00:00:20:03",
+			ip:           "192.0.2.203",
+			host:         "device-other",
+			manufacturer: "Marantz",
+			wantType:     "altavoz",
+		},
+		{
+			name:         "simulated Apple TV candidate keeps the generic fallback",
+			mac:          "02:00:00:00:20:04",
+			ip:           "192.0.2.204",
+			host:         "device-apple",
+			model:        "AppleTV14,1",
+			manufacturer: "Apple",
+			wantType:     "altavoz",
+		},
+		{
+			name:         "manual type override wins over a signature",
+			mac:          "02:00:00:00:20:05",
+			ip:           "192.0.2.205",
+			host:         "device-lg",
+			model:        "OLED77CX6LA",
+			manufacturer: "LG Electronics",
+			overrideType: "consola",
+			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}
+			l := NewLive(nil, nil, []RouterConfig{cfg}, nil)
+			if tt.overrideType != "" {
+				d := openLiveTestDB(t)
+				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.overrideType); err != nil {
+					t.Fatalf("seed override: %v", err)
+				}
+				l = NewLive(nil, d, []RouterConfig{cfg}, nil)
+			}
+			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},
+					Discovery: &probe.DiscoveryData{
+						HostByIP:      map[string]string{tt.ip: tt.host},
+						Services:      map[string][]string{tt.host: {"_airplay._tcp"}},
+						Models:        map[string]string{tt.host: tt.model},
+						Manufacturers: map[string]string{tt.host: tt.manufacturer},
+					},
+				},
+			}
+
+			devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
+			for _, d := range devices {
+				if d.MAC != tt.mac {
+					continue
+				}
+				if d.Type != tt.wantType {
+					t.Errorf("type = %q, want %q", d.Type, tt.wantType)
+				}
+				return
+			}
+			t.Fatalf("device %s not found", tt.mac)
+		})
+	}
+}