Bladeren bron

feat: identify Proxmox hosts and their CTs via read-only PVE API (#562)

* feat(server): identify Proxmox hosts and CTs via read-only PVE API (#561)

* feat(ui): add Proxmox VE integration settings (#561)

* fix(server): accept self-signed PVE TLS, match host by node IP with online priority (#561)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 maanden geleden
bovenliggende
commit
92e70a0882

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

@@ -1309,6 +1309,22 @@
       "hint": "Each test saturates the link for a few seconds and consumes data: avoid short intervals on capped connections.",
       "lastResult": "Last test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "unavailable": "Not available in this mode"
+    },
+    "proxmox": {
+      "title": "Proxmox VE",
+      "caption": "Cluster inventory to identify hosts and their containers",
+      "hint": "Connects to the Proxmox cluster read-only API (token with Sys.Audit and VM.Audit privileges). The inventory seals the host as hypervisor and its CTs/VMs as containers attached to it in Devices, with real names and IPs. Create the token in Datacenter > Permissions > API Tokens.",
+      "configured": "Configured",
+      "notConfigured": "Not configured",
+      "edit": "Edit Proxmox configuration",
+      "url": "Cluster URL",
+      "tokenId": "Token ID (user@realm!name)",
+      "secret": "Token secret",
+      "secretKeep": "Current secret (leave empty to keep it)",
+      "save": "Save",
+      "saving": "Saving…",
+      "disable": "Disable",
+      "errorGeneric": "Could not save the Proxmox configuration."
     }
   },
   "statcard": {

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

@@ -1309,6 +1309,22 @@
       "hint": "Cada test satura el enlace durante unos segundos y consume datos: evita intervalos cortos en líneas con límite de datos.",
       "lastResult": "Último test: {{when}} · {{down}} Mbps ↓ / {{up}} Mbps ↑",
       "unavailable": "No disponible en este modo"
+    },
+    "proxmox": {
+      "title": "Proxmox VE",
+      "caption": "Inventario del cluster para identificar hosts y sus contenedores",
+      "hint": "Conecta con la API de solo lectura del cluster Proxmox (token con permisos Sys.Audit y VM.Audit). El inventario sella el host como hipervisor y sus CTs/VMs como contenedores colgados de él en Dispositivos, con nombres e IPs reales. Crea el token en Datacenter > Permisos > API Tokens.",
+      "configured": "Configurado",
+      "notConfigured": "Sin configurar",
+      "edit": "Editar configuración de Proxmox",
+      "url": "URL del cluster",
+      "tokenId": "Token ID (usuario@realm!nombre)",
+      "secret": "Secret del token",
+      "secretKeep": "Secret actual (déjalo vacío para conservarlo)",
+      "save": "Guardar",
+      "saving": "Guardando…",
+      "disable": "Desactivar",
+      "errorGeneric": "No se pudo guardar la configuración de Proxmox."
     }
   },
   "statcard": {

+ 195 - 2
app/src/pages/Settings.tsx

@@ -31,8 +31,9 @@ import {
   RefreshCw,
   RotateCw,
   Router as RouterIcon,
-   Shield,
-   ShieldCheck,
+   Server,
+    Shield,
+    ShieldCheck,
    Sun,
    Trash2,
    UserCog,
@@ -1471,6 +1472,190 @@ function AdGuardManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   )
 }
 
+// Proxmox VE (#561): inventario read-only del cluster para sellar
+// hypervisor/ct en Dispositivos. Config en kv del servidor (url + API token).
+function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => void }) {
+  const { t } = useTranslation()
+  const [url, setURL] = useState('')
+  const [tokenId, setTokenId] = useState('')
+  const [secret, setSecret] = useState('')
+  const [tokenSet, setTokenSet] = useState(false)
+  const [editing, setEditing] = useState(false)
+  const [saving, setSaving] = useState(false)
+  const [error, setError] = useState<string | null>(null)
+
+  useEffect(() => {
+    let disposed = false
+    void (async () => {
+      try {
+        const res = await fetch('/api/config/proxmox')
+        if (!res.ok) return
+        const json = (await res.json()) as { url: string; tokenId: string; tokenSet: boolean }
+        if (disposed) return
+        setURL(json.url || '')
+        setTokenId(json.tokenId || '')
+        setTokenSet(json.tokenSet)
+      } catch {
+        // sin servidor → no-op
+      }
+    })()
+    return () => {
+      disposed = true
+    }
+  }, [])
+
+  const save = async (e: React.FormEvent) => {
+    e.preventDefault()
+    if (saving) return
+    setSaving(true)
+    setError(null)
+    try {
+      const payload: Record<string, unknown> = {}
+      // url siempre se manda ("" = desactivar; si hay url previa y no se tocó,
+      // se conserva igualmente porque el input está precargado).
+      payload.url = url.trim()
+      if (tokenId.trim()) payload.tokenId = tokenId.trim()
+      if (secret) payload.secret = secret
+      const res = await fetch('/api/config/proxmox', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify(payload),
+      })
+      if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
+      if (secret) {
+        setTokenSet(true)
+        setSecret('')
+      }
+      setEditing(false)
+      onSaved()
+    } catch {
+      setError(t('settings.proxmox.errorGeneric'))
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  const disable = async () => {
+    if (saving) return
+    setSaving(true)
+    setError(null)
+    try {
+      const res = await fetch('/api/config/proxmox', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ url: '' }),
+      })
+      if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
+      setURL('')
+      setTokenId('')
+      setTokenSet(false)
+      setEditing(false)
+      onSaved()
+    } catch {
+      setError(t('settings.proxmox.errorGeneric'))
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  if (tokenSet && !editing) {
+    return (
+      <Card title={t('settings.proxmox.title')} caption={t('settings.proxmox.caption')} index={5} reduce={reduce}>
+        <div className="flex items-center gap-3 rounded-xl border border-border bg-elevated px-3.5 py-2.5">
+          <Server className="h-4 w-4 shrink-0 text-text-muted" strokeWidth={1.75} />
+          <span className="min-w-0 flex-1 truncate font-mono text-sm font-medium text-text-primary">{url}</span>
+          <span className="flex shrink-0 items-center gap-1.5 rounded-full bg-ok/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-ok">
+            {t('settings.proxmox.configured')}
+          </span>
+          <button
+            type="button"
+            onClick={() => setEditing(true)}
+            aria-label={t('settings.proxmox.edit')}
+            title={t('settings.proxmox.edit')}
+            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent"
+          >
+            <Pencil className="h-4 w-4" strokeWidth={1.75} />
+          </button>
+        </div>
+        <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.proxmox.hint')}</p>
+      </Card>
+    )
+  }
+
+  return (
+    <Card title={t('settings.proxmox.title')} caption={t('settings.proxmox.caption')} index={5} reduce={reduce}>
+      <form onSubmit={(e) => void save(e)}>
+        <div className="grid grid-cols-1 gap-2.5">
+          <input
+            type="text"
+            value={url}
+            onChange={(e) => setURL(e.target.value)}
+            placeholder="https://192.168.1.100:8006"
+            aria-label={t('settings.proxmox.url')}
+            className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+          />
+          <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+            <input
+              type="text"
+              value={tokenId}
+              onChange={(e) => setTokenId(e.target.value)}
+              placeholder="root@pam!netpulse"
+              aria-label={t('settings.proxmox.tokenId')}
+              className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+            />
+            <input
+              type="password"
+              value={secret}
+              onChange={(e) => setSecret(e.target.value)}
+              placeholder={tokenSet ? t('settings.proxmox.secretKeep') : t('settings.proxmox.secret')}
+              aria-label={t('settings.proxmox.secret')}
+              autoComplete="new-password"
+              className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+            />
+          </div>
+        </div>
+        <div className="mt-2.5 flex flex-wrap items-center gap-3">
+          <span className={cn('flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider', tokenSet ? 'bg-ok/10 text-ok' : 'bg-warn/10 text-warn')}>
+            {tokenSet ? t('settings.proxmox.configured') : t('settings.proxmox.notConfigured')}
+          </span>
+          <button
+            type="submit"
+            disabled={saving || (!url.trim() && !tokenSet)}
+            className="ml-auto flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-medium text-canvas transition-opacity duration-150 hover:opacity-90 disabled:opacity-40"
+          >
+            {saving ? t('settings.proxmox.saving') : t('settings.proxmox.save')}
+          </button>
+          {tokenSet && editing && (
+            <button
+              type="button"
+              onClick={() => {
+                setEditing(false)
+                setSecret('')
+                setError(null)
+              }}
+              className="rounded-lg border border-border px-3 py-2 text-sm font-medium text-text-secondary transition-colors duration-150 hover:text-text-primary"
+            >
+              {t('settings.users.cancel')}
+            </button>
+          )}
+          {tokenSet && (
+            <button
+              type="button"
+              onClick={() => void disable()}
+              disabled={saving}
+              className="rounded-lg border border-danger/30 px-3 py-2 text-sm font-medium text-danger transition-colors duration-150 hover:border-danger/60 disabled:opacity-40"
+            >
+              {t('settings.proxmox.disable')}
+            </button>
+          )}
+        </div>
+        {error && <p className="mt-2 text-caption text-danger">{error}</p>}
+        <p className="mt-3 text-caption leading-relaxed text-text-muted">{t('settings.proxmox.hint')}</p>
+      </form>
+    </Card>
+  )
+}
+
 
 // ---------------------------------------------------------------------------
 // Bloque «Sistema» en Acerca de (SPEC-65 D65-6/7e): GET /api/system/info
@@ -3924,6 +4109,14 @@ export default function Settings() {
           </div>
         )}
 
+        {/* Proxmox VE (#561): inventario read-only del cluster para sellar
+            hypervisor/ct. Media anchura junto a AdGuard/adopción. */}
+        {!isDemo && auth?.role === 'admin' && (
+          <div className="lg:col-span-6">
+            <ProxmoxManager reduce={reduce} onSaved={notify} />
+          </div>
+        )}
+
         {/* Mi perfil (issue #119): card canónica del shared-shell — avatar,
             nombre editable (clic → input inline ✓/✕), idioma, contraseña y
             salir en UNA línea en desktop (envuelve en móvil). */}

+ 16 - 0
server-go/internal/adapters/live.go

@@ -27,6 +27,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/deviceevents"
 	"github.com/gnacho/netpulse/server-go/internal/oui"
 	"github.com/gnacho/netpulse/server-go/internal/portseries"
+	"github.com/gnacho/netpulse/server-go/internal/pve"
 )
 
 // fmtUptime: "<d>d <h>h" (index.js:32-36).
@@ -312,6 +313,14 @@ type Live struct {
 	agGL  *AdGuardGlinetClient
 	agKey string
 
+	// PVE (#561): cliente del cluster Proxmox + caché del inventario. El
+	// cliente se reconstruye si cambia la config (pveKey); el inventario
+	// (resources + MACs por VM) se refresca con TTL para no martillear la API.
+	pveClient *pve.Client
+	pveKey    string
+	pveInv    *pveInventory
+	pveInvAt  time.Time
+
 	sfMu   sync.Mutex
 	sfCall *sfCall
 }
@@ -2258,6 +2267,11 @@ func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
 	if l.db != nil {
 		devices, distNodes = applyTopologyOverrides(devices, distNodes, loadTopologyOverrides(l.db))
 	}
+	// Capa 3 PVE (#561): si hay cluster Proxmox configurado, el inventario
+	// read-only sella hypervisor/ct con attachTo correcto (la relación
+	// CT→host no es deducible del L2). Va DESPUÉS de los overrides manuales:
+	// un override explícito del usuario tiene prioridad sobre el sello.
+	l.sealProxmoxInfra(devices)
 	// Supresión topológica (#332): actualizar grafo parent→child.
 	// Todos los no-gateway cuelgan del gateway.
 	l.mu.Lock()
@@ -2815,6 +2829,8 @@ func (l *Live) GetDevices(context.Context) []Device {
 	polled := l.lastPolled
 	l.mu.Unlock()
 	devices, _ := inferTopology(polled, l.buildDevices(polled))
+	// #561: sellado de infraestructura con el inventario PVE (si configurado).
+	l.sealProxmoxInfra(devices)
 	return devices
 }
 

+ 260 - 0
server-go/internal/adapters/proxmox.go

@@ -0,0 +1,260 @@
+// proxmox.go — integración read-only con Proxmox VE (issue #561).
+//
+// El problema que resuelve: la relación CT→host NO es deducible del tráfico
+// L2 (un puerto del router mezcla dispositivos), así que la heurística de
+// topología no puede sellar hypervisor/ct en redes reales. La fuente de
+// verdad vive en el cluster PVE, que se consulta con un token de SOLO LECTURA
+// (GET únicamente; Sys.Audit + VM.Audit).
+//
+// Diseño:
+//   - Config en kv (proxmox_url/token_id/token_secret), admin por API/UI.
+//   - Inventario cacheado (TTL): cluster/resources (VM→node en 1 llamada) +
+//     config por VM (N+1) para sacar las MACs de cada CT/VM.
+//   - Sellado en buildDevices (tras inferTopology): el device cuya MAC es la
+//     de un CT/VM se marca infra=ct y cuelga del device HOST (infra=hypervisor)
+//     cuyo MAC es la del nodo físico. El host se identifica porque su MAC
+//     aparece como la del nodo en el inventario (ver pveHostMAC).
+//
+// Si la integración no está configurada o falla, todo sigue igual (no-op).
+package adapters
+
+import (
+	"context"
+	"log"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/pve"
+)
+
+// pveInventoryTTL: refresco del inventario (resources + MACs). Un cluster
+// pequeño (~10-20 VMs) cuesta N+1 GETs; cada 5 min es razonable.
+const pveInventoryTTL = 5 * time.Minute
+
+// pveHostMAC: la MAC del host físico de un nodo. No viene en cluster/resources
+// (que lista VMs/CTs, no interfaces del nodo). La resolvemos consultando la
+// config de la primera VM running de ese nodo NO nos sirve (es la MAC de la
+// VM). En su lugar usamos el hecho de que el HOST (citadel-01) aparece como
+// device de NetPulse por su propia MAC de gestión, y el nodo PVE se llama
+// igual que ese device ("citadel-01"): el sellado cruza por NOMBRE del device
+// == nombre del nodo como fallback, y por MAC de VM para los CTs.
+type pveInventory struct {
+	// ctByMAC: MAC (upper ':') → datos del CT/VM que la usa.
+	ctByMAC map[string]pveVM
+	// nodeNames: nodos del cluster (p. ej. "citadel-01").
+	nodeNames map[string]bool
+	// nodeIPs: nodo → IP del bridge vmbr0 (p. ej. citadel-02 → 192.168.1.101).
+	// Permite casar el device HOST por IP cuando NetPulse no conoce su nombre
+	// (el host aparece solo por MAC/IP).
+	nodeIPs map[string]string
+}
+
+type pveVM struct {
+	Name string // hostname del CT/VM (webs, pbs…)
+	Node string // nodo que lo ejecuta (citadel-01)
+	Type string // "lxc" | "qemu"
+}
+
+// pveConfigFromKV: lee la config de la integración desde el kv.
+func (l *Live) pveConfigFromKV() pve.Config {
+	var cfg pve.Config
+	if l.db == nil {
+		return cfg
+	}
+	_ = l.db.QueryRow("SELECT value FROM kv WHERE key='proxmox_url'").Scan(&cfg.URL)
+	_ = l.db.QueryRow("SELECT value FROM kv WHERE key='proxmox_token_id'").Scan(&cfg.TokenID)
+	_ = l.db.QueryRow("SELECT value FROM kv WHERE key='proxmox_token_secret'").Scan(&cfg.Secret)
+	return cfg
+}
+
+// pveClientCached: devuelve el cliente PVE para la config actual, recreándolo
+// si cambió (patrón AdGuard). Sin config → nil.
+func (l *Live) pveClientCached() *pve.Client {
+	cfg := l.pveConfigFromKV()
+	if !cfg.Enabled() {
+		l.pveClient = nil
+		l.pveKey = ""
+		return nil
+	}
+	key := cfg.URL + "|" + cfg.TokenID + "|" + cfg.Secret
+	if l.pveClient == nil || l.pveKey != key {
+		l.pveClient = pve.NewClient(cfg)
+		l.pveKey = key
+	}
+	return l.pveClient
+}
+
+// pveInventoryCached: inventario PVE (VM→MAC→node) con TTL. Devuelve nil si
+// no configurado o si la consulta falla (no-op, no rompe el overview).
+func (l *Live) pveInventoryCached() *pveInventory {
+	client := l.pveClientCached()
+	if client == nil {
+		return nil
+	}
+	l.mu.Lock()
+	defer l.mu.Unlock()
+	if l.pveInv != nil && time.Since(l.pveInvAt) < pveInventoryTTL {
+		return l.pveInv
+	}
+	inv := l.fetchPveInventory(client)
+	if inv == nil {
+		return l.pveInv // conserva el último bueno si la consulta falla
+	}
+	l.pveInv = inv
+	l.pveInvAt = time.Now()
+	return inv
+}
+
+// fetchPveInventory: consulta cluster/resources + config de cada VM/CT
+// running para construir mac→VM y la lista de nodos. Best-effort: una VM que
+// no se pueda leer no invalida el resto.
+func (l *Live) fetchPveInventory(client *pve.Client) *pveInventory {
+	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+	defer cancel()
+	resources, err := client.ClusterResources(ctx)
+	if err != nil {
+		log.Printf("[netpulse:pve] cluster/resources: %v", err)
+		return nil
+	}
+	inv := &pveInventory{
+		ctByMAC:   map[string]pveVM{},
+		nodeNames: map[string]bool{},
+		nodeIPs:   map[string]string{},
+	}
+	for _, r := range resources {
+		if r.Type == "node" {
+			// El nombre del nodo viene en `node`, no en `name` (que los
+			// nodos dejan vacío en cluster/resources).
+			if r.Node != "" {
+				inv.nodeNames[r.Node] = true
+				// IP del host (vmbr0) para casar el device HOST por IP.
+				if ip, err := client.NodeIP(ctx, r.Node); err == nil && ip != "" {
+					inv.nodeIPs[r.Node] = ip
+				} else if err != nil {
+					log.Printf("[netpulse:pve] nodeip %s: %v", r.Node, err)
+				}
+			}
+			continue
+		}
+		if r.Type != "lxc" && r.Type != "qemu" {
+			continue
+		}
+		if r.Node == "" || r.VMID == 0 {
+			continue
+		}
+		if r.Status == "stopped" {
+			continue // sin tráfico → no está en la red; no aporta MAC
+		}
+		cfg, err := client.VMConfig(ctx, r.Node, r.Type, r.VMID)
+		if err != nil {
+			log.Printf("[netpulse:pve] config %s/%d: %v", r.Type, r.VMID, err)
+			continue
+		}
+		for _, mac := range pve.MACsOfConfig(cfg) {
+			inv.ctByMAC[mac] = pveVM{Name: r.Name, Node: r.Node, Type: r.Type}
+		}
+	}
+	if len(inv.ctByMAC) == 0 && len(inv.nodeNames) == 0 {
+		return nil // cluster sin VMs corriendo ni nodos legibles
+	}
+	return inv
+}
+
+// sealProxmoxInfra aplica el inventario PVE sobre los devices ya construidos
+// (tras inferTopology): el device cuyo MAC es la de un CT/VM se marca
+// infra=ct y cuelga del device HOST del nodo (infra=hypervisor).
+//
+// El host se casa por nombre del device == nombre del nodo (p. ej. el device
+// "citadel-01"). Esto resuelve el caso real donde el host PVE está en la LAN
+// con su nombre y sus CTs (MACs BC:24:11 o locally-administered) ya visibles
+// como devices sin sellar.
+func (l *Live) sealProxmoxInfra(devices []Device) {
+	inv := l.pveInventoryCached()
+	if inv == nil {
+		return
+	}
+	applyPVEInfra(devices, inv)
+}
+
+// applyPVEInfra sella devices con un inventario dado (función pura, testeable
+// sin red ni kv). Ver sealProxmoxInfra para el diseño.
+func applyPVEInfra(devices []Device, inv *pveInventory) {
+	if inv == nil || len(inv.ctByMAC) == 0 {
+		return
+	}
+	// Índices. El host de un nodo se casa por IP del nodo (vmbr0, la que da
+	// el cluster) con prioridad, y por nombre del device como fallback. Un
+	// host físico con dos NICs aparece como dos devices (p. ej. citadel-01
+	// con .100 vmbr0 y .243 de gestión): el device con la IP del nodo es el
+	// host correcto (online); el otro (nombre coincidente pero IP distinta)
+	// NO debe ganar.
+	hostIDByNode := map[string]string{} // node → id del device host
+	hostIdxByID := map[string]int{}
+	nodeNameByID := map[string]string{} // id del device host → nombre del nodo
+	for i := range devices {
+		hostIdxByID[devices[i].ID] = i
+		if devices[i].IP != "" {
+			for node, ip := range inv.nodeIPs {
+				if devices[i].IP == ip {
+					hostIDByNode[node] = devices[i].ID
+					nodeNameByID[devices[i].ID] = node
+				}
+			}
+		}
+	}
+	// Pasada 2: por nombre, solo si el nodo aún no tiene host por IP.
+	for i := range devices {
+		if _, ok := hostIDByNode[devices[i].Name]; ok {
+			continue // el nodo ya tiene host (por IP)
+		}
+		if inv.nodeNames[devices[i].Name] {
+			hostIDByNode[devices[i].Name] = devices[i].ID
+			nodeNameByID[devices[i].ID] = devices[i].Name
+		}
+	}
+	// Casar cada CT por MAC.
+	for mac, vm := range inv.ctByMAC {
+		idx, ok := hostIdxByID[macToDeviceID(mac)]
+		if !ok {
+			continue // el CT no es un device conocido (apagado o sin tráfico)
+		}
+		hostID := hostIDByNode[vm.Node]
+		devices[idx].Infra = "ct"
+		// El sello PVE es ground truth: si el CT tiene host conocido, cuelga
+		// de él (sobreescribe el attachTo inferido por L2, que en puertos
+		// mezclados apunta a un nodo "inferred" genérico).
+		if hostID != "" {
+			devices[idx].AttachTo = hostID
+		}
+	}
+	// Sellar los hosts y renombrarlos con el nombre del nodo cuando el device
+	// solo se conoce por MAC (p. ej. "FE:C9:95:97:15:30" → "citadel-01").
+	for node, id := range hostIDByNode {
+		if idx, ok := hostIdxByID[id]; ok {
+			devices[idx].Infra = "hypervisor"
+			if name, ok := nodeNameByID[id]; ok && looksLikeMACName(devices[idx].Name) {
+				devices[idx].Name = name
+				_ = node
+			}
+		}
+	}
+}
+
+// looksLikeMACName: true si el nombre del device es una MAC (no tiene nombre
+// real asignado por lease/alias). Formato "AA:BB:CC:DD:EE:FF" o con guiones.
+func looksLikeMACName(name string) bool {
+	hex := 0
+	for _, r := range name {
+		if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F') {
+			hex++
+		} else if r != ':' && r != '-' {
+			return false
+		}
+	}
+	return hex == 12
+}
+
+// macToDeviceID: el ID de device es la MAC en minúsculas con guiones.
+func macToDeviceID(mac string) string {
+	return strings.ToLower(strings.ReplaceAll(mac, ":", "-"))
+}

+ 150 - 0
server-go/internal/adapters/proxmox_test.go

@@ -0,0 +1,150 @@
+// proxmox_test.go — sellado de infraestructura desde el inventario PVE (#561).
+package adapters
+
+import (
+	"testing"
+
+)
+
+// TestSealProxmoxInfra: con un cluster de 1 nodo (citadel-01) y 2 CTs
+// (webs + pbs con MACs BC:24:11 y locally-administered), los devices que
+// coinciden por MAC se sellan ct y cuelgan del host; el host se sella
+// hypervisor. El caso que la heurística L2 NO puede resolver (puerto mezclado).
+func TestSealProxmoxInfra(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc"},
+			"02:78:F4:02:8A:94": {Name: "homeassistant", Node: "citadel-01", Type: "lxc"},
+		},
+		nodeNames: map[string]bool{"citadel-01": true},
+	}
+	devices := []Device{
+		{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01", RouterID: "gateway", Band: "—"},
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", RouterID: "gateway", Band: "cable", Port: "lan3", AttachTo: "dist-gateway-lan3"},
+		{ID: "02-78-f4-02-8a-94", MAC: "02:78:F4:02:8A:94", Name: "homeassistant", RouterID: "gateway", Band: "cable", Port: "lan3", AttachTo: "dist-gateway-lan3"},
+		{ID: "aa-bb-cc-dd-ee-ff", MAC: "AA:BB:CC:DD:EE:FF", Name: "shield", RouterID: "gateway", Band: "cable", Port: "lan3"},
+	}
+	applyPVEInfra(devices, inv)
+
+	if devices[0].Infra != "hypervisor" {
+		t.Fatalf("host citadel-01: infra=%q (want hypervisor)", devices[0].Infra)
+	}
+	hostID := devices[0].ID
+	for i, want := range map[int]string{
+		1: "ct", 2: "ct", 3: "",
+	} {
+		if devices[i].Infra != want {
+			t.Errorf("device[%d] %s: infra=%q (want %q)", i, devices[i].Name, devices[i].Infra, want)
+		}
+	}
+	// El sello PVE sobreescribe el attachTo inferido por L2 (dist-gateway-lan3)
+	// y cuelga los CTs del host.
+	if devices[1].AttachTo != hostID {
+		t.Errorf("webs attachTo=%q (want host %q, sobreescribe el inferred)", devices[1].AttachTo, hostID)
+	}
+	if devices[2].AttachTo != hostID {
+		t.Errorf("homeassistant attachTo=%q (want host %q)", devices[2].AttachTo, hostID)
+	}
+	// El device no relacionado (shield) queda intacto.
+	if devices[3].Infra != "" || devices[3].AttachTo != "" {
+		t.Errorf("shield tocado: %+v", devices[3])
+	}
+}
+
+// TestSealProxmoxInfraSinInventario: sin cluster configurado o sin CTs
+// conocidos → no-op (los devices no cambian).
+func TestSealProxmoxInfraSinInventario(t *testing.T) {
+	devices := []Device{{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01"}}
+	applyPVEInfra(devices, nil)
+	if devices[0].Infra != "" || devices[0].AttachTo != "" {
+		t.Fatalf("sin inventario no debe tocar devices: %+v", devices[0])
+	}
+}
+
+// TestSealProxmoxInfraHostSinDevice: un nodo PVE cuyo host NO es un device
+// conocido (no habla a la LAN) no rompe nada: los CTs se sellan ct sin host.
+func TestSealProxmoxInfraHostSinDevice(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-99", Type: "lxc"},
+		},
+		nodeNames: map[string]bool{"citadel-99": true},
+	}
+	devices := []Device{
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", RouterID: "gateway"},
+	}
+	applyPVEInfra(devices, inv)
+	if devices[0].Infra != "ct" {
+		t.Fatalf("webs infra=%q (want ct aunque no haya host device)", devices[0].Infra)
+	}
+	if devices[0].AttachTo != "" {
+		t.Fatalf("sin host device no debe haber attachTo: %q", devices[0].AttachTo)
+	}
+}
+
+// TestSealProxmoxInfraHostPorIP: cuando NetPulse no conoce el NOMBRE del host
+// (aparece solo por MAC/IP, p. ej. citadel-02 = E8:FF:1E... con IP .101), el
+// host se casa por IP del nodo (vmbr0).
+func TestSealProxmoxInfraHostPorIP(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc"},
+		},
+		nodeNames: map[string]bool{"citadel-02": true},
+		nodeIPs:   map[string]string{"citadel-02": "192.168.1.101"},
+	}
+	devices := []Device{
+		{ID: "e8-ff-1e-dd-c7-ed", MAC: "E8:FF:1E:DD:C7:ED", Name: "E8:FF:1E:DD:C7:ED", IP: "192.168.1.101", RouterID: "switch16"},
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", IP: "192.168.1.226", RouterID: "switch16", AttachTo: "dist-switch16-lan8"},
+	}
+	applyPVEInfra(devices, inv)
+	if devices[0].Infra != "hypervisor" {
+		t.Fatalf("host por IP: infra=%q (want hypervisor)", devices[0].Infra)
+	}
+	if devices[0].Name != "citadel-02" {
+		t.Fatalf("host renombrado: name=%q (want citadel-02)", devices[0].Name)
+	}
+	if devices[1].AttachTo != devices[0].ID {
+		t.Fatalf("webs attachTo=%q (want host por IP %q)", devices[1].AttachTo, devices[0].ID)
+	}
+}
+
+// TestSealProxmoxInfraHostConflictoNICs: un host físico con dos NICs aparece
+// como dos devices (p. ej. citadel-01 online con IP vmbr0 .100, y el mismo
+// host offline con IP de gestión .243). El host correcto es el de la IP del
+// nodo (vmbr0), aunque otro device tenga el nombre "citadel-01".
+func TestSealProxmoxInfraHostConflictoNICs(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc"},
+		},
+		nodeNames: map[string]bool{"citadel-01": true},
+		nodeIPs:   map[string]string{"citadel-01": "192.168.1.100"},
+	}
+	devices := []Device{
+		// device con nombre citadel-01 pero IP de gestión (.243) y offline.
+		{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01", IP: "192.168.1.243", Online: false},
+		// device online con la IP vmbr0 del nodo (.100): host correcto.
+		{ID: "fe-c9-95-97-15-30", MAC: "FE:C9:95:97:15:30", Name: "FE:C9:95:97:15:30", IP: "192.168.1.100", Online: true},
+		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", IP: "192.168.1.226", Online: true},
+	}
+	applyPVEInfra(devices, inv)
+	// El hypervisor debe ser el device con IP .100 (online), no el offline.
+	if devices[1].Infra != "hypervisor" || devices[1].Name != "citadel-01" {
+		t.Fatalf("host por IP debería ganar: %+v (infra=%q name=%q)", devices[1], devices[1].Infra, devices[1].Name)
+	}
+	if devices[0].Infra == "hypervisor" {
+		t.Fatalf("el device offline con nombre citadel-01 NO debe ser hypervisor: %+v", devices[0])
+	}
+	if devices[2].AttachTo != devices[1].ID {
+		t.Fatalf("webs attachTo=%q (want host online %q)", devices[2].AttachTo, devices[1].ID)
+	}
+}
+
+// TestPVEHostMACDeviceID: el id del device (MAC minúsculas con guiones) casa
+// con la clave del inventario (MAC mayúsculas con ':') para CTs.
+func TestPVEMacToDeviceID(t *testing.T) {
+	if got := macToDeviceID("BC:24:11:A4:9E:BB"); got != "bc-24-11-a4-9e-bb" {
+		t.Fatalf("macToDeviceID: %q", got)
+	}
+}

+ 72 - 0
server-go/internal/httpapi/config.go

@@ -8,6 +8,7 @@ package httpapi
 import (
 	"database/sql"
 	"net/http"
+	urlpkg "net/url"
 	"regexp"
 	"strconv"
 	"strings"
@@ -37,6 +38,8 @@ func (s *server) registerConfigRoutes(mux *http.ServeMux) {
 	mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
 	mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
 	mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
+	mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
+	mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
 }
 
 // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
@@ -453,3 +456,72 @@ func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request)
 	}
 	w.WriteHeader(http.StatusNoContent)
 }
+
+// GET /api/config/proxmox — {url, tokenId, tokenSet} (el secret nunca se
+// devuelve). Config de la integración PVE del #561.
+func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
+	writeJSON(w, http.StatusOK, map[string]any{
+		"url":      kvGet(s.db.DB, "proxmox_url"),
+		"tokenId":  kvGet(s.db.DB, "proxmox_token_id"),
+		"tokenSet": kvGet(s.db.DB, "proxmox_token_secret") != "",
+	})
+}
+
+type proxmoxInput struct {
+	URL     *string `json:"url"` // nil = no tocar; "" = desactivar
+	TokenID string  `json:"tokenId"`
+	Secret  string  `json:"secret"` // solo si viene (se conserva el anterior)
+}
+
+// PUT /api/config/proxmox — upsert en kv (secret solo si viene). 204.
+// url: base del cluster pve (p. ej. "https://192.168.1.100:8006").
+// tokenId: "USER@REALM!TOKENID"; secret: la parte UUID del token.
+func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
+	var in proxmoxInput
+	if st := readJSONBody(w, r, &in); st != 0 {
+		writeBodyError(w, st, "invalid_json", "")
+		return
+	}
+	tokenID := strings.TrimSpace(in.TokenID)
+	if len(tokenID) > 128 || len(in.Secret) > 256 {
+		writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
+		return
+	}
+	upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
+	if in.URL != nil {
+		url := strings.TrimRight(strings.TrimSpace(*in.URL), "/")
+		if url == "" {
+			// url vacío = desactivar la integración: limpia todo.
+			for _, k := range []string{"proxmox_url", "proxmox_token_id", "proxmox_token_secret"} {
+				if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
+					writeError(w, http.StatusInternalServerError, "internal_error")
+					return
+				}
+			}
+			w.WriteHeader(http.StatusNoContent)
+			return
+		}
+		u, err := urlpkg.Parse(url)
+		if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
+			writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
+			return
+		}
+		if _, err := s.db.Exec(upsert, "proxmox_url", url); err != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+	}
+	if tokenID != "" {
+		if _, err := s.db.Exec(upsert, "proxmox_token_id", tokenID); err != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+	}
+	if in.Secret != "" {
+		if _, err := s.db.Exec(upsert, "proxmox_token_secret", in.Secret); err != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+	}
+	w.WriteHeader(http.StatusNoContent)
+}

+ 63 - 0
server-go/internal/httpapi/config_test.go

@@ -421,3 +421,66 @@ func TestConfigRoutersSNMP(t *testing.T) {
 		t.Fatalf("POST invalid snmp_port: %d; want 400", res.StatusCode)
 	}
 }
+
+// TestProxmoxConfig (#561): PUT/GET /api/config/proxmox
+//   - guardar url+token, GET no devuelve el secret (solo tokenSet)
+//   - url vacía desactiva (limpia kv)
+//   - url inválida → 400
+func TestProxmoxConfig(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	res := doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
+		`{"url":"https://192.168.1.100:8006","tokenId":"root@pam!netpulse","secret":"uuid-1234"}`)
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("PUT proxmox: %d %v", res.StatusCode, body)
+	}
+
+	res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
+	if res.StatusCode != 200 {
+		t.Fatalf("GET proxmox: %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	if body["url"] != "https://192.168.1.100:8006" || body["tokenId"] != "root@pam!netpulse" {
+		t.Fatalf("GET proxmox body: %v", body)
+	}
+	if _, present := body["secret"]; present {
+		t.Fatalf("GET proxmox no debe devolver el secret: %v", body)
+	}
+	if body["tokenSet"] != true {
+		t.Fatalf("tokenSet esperado true: %v", body)
+	}
+
+	// Actualizar solo el secret conserva url/tokenId.
+	res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
+		`{"secret":"uuid-9999"}`)
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("PUT proxmox secret: %d %v", res.StatusCode, body)
+	}
+	res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
+	body = readJSON(t, res)
+	if body["url"] != "https://192.168.1.100:8006" || body["tokenId"] != "root@pam!netpulse" {
+		t.Fatalf("GET tras update secret: %v", body)
+	}
+
+	// URL inválida → 400
+	res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
+		`{"url":"no-es-url","tokenId":"a!b","secret":"c"}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("url inválida: esperado 400, got %d", res.StatusCode)
+	}
+
+	// Desactivar: url vacía limpia todo.
+	res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie, `{"url":""}`)
+	if res.StatusCode != 204 {
+		body := readJSON(t, res)
+		t.Fatalf("PUT proxmox desactivar: %d %v", res.StatusCode, body)
+	}
+	res = doReq(t, "GET", srv.URL+"/api/config/proxmox", cookie, "")
+	body = readJSON(t, res)
+	if body["url"] != "" || body["tokenId"] != "" || body["tokenSet"] != false {
+		t.Fatalf("GET tras desactivar: %v", body)
+	}
+}

+ 232 - 0
server-go/internal/pve/pve.go

@@ -0,0 +1,232 @@
+// Package pve — cliente read-only de la API de Proxmox VE (issue #561).
+//
+// Objetivo: obtener el inventario del cluster (VMs/CTs → nodo/host) como
+// ground truth para sellar la infraestructura en NetPulse (hypervisor + ct
+// con attachTo). La relación CT→host NO es deducible del tráfico L2 (un
+// puerto del router mezcla dispositivos); vive en el cluster.
+//
+// Auth: API token de Proxmox (PVEAPIToken) con privilegios de solo lectura
+// (Sys.Audit para cluster/resources; VM.Audit para leer la config de cada
+// VM/CT y extraer sus MACs). El token se envía en el header Authorization:
+//
+//	Authorization: PVEAPIToken=USER@REALM!TOKENID=UUID
+//
+// TLS: el certificado del cluster es self-signed (pve-api-daemon genera uno
+// propio); el cliente acepta cualquier cert (configurable en el futuro con
+// CA fija). Solo lectura: GET únicamente.
+package pve
+
+import (
+	"context"
+	"crypto/tls"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+)
+
+// Config: datos de conexión al cluster (persistidos en kv por el server).
+type Config struct {
+	// URL base, p. ej. "https://192.168.1.100:8006" (sin barra final).
+	URL string
+	// TokenID: "USER@REALM!TOKENID" (p. ej. "root@pam!netpulse").
+	TokenID string
+	// Secret: la parte UUID del token (se muestra una sola vez al crearlo).
+	Secret string
+}
+
+// Enabled: true si hay config completa.
+func (c Config) Enabled() bool {
+	return c.URL != "" && c.TokenID != "" && c.Secret != ""
+}
+
+const httpTimeout = 5 * time.Second
+
+// Client consulta la API PVE de un cluster.
+type Client struct {
+	cfg Config
+	hc  *http.Client
+}
+
+// NewClient crea el cliente (sin red: solo guarda config). TLS: los clusters
+// PVE usan un certificado self-signed (pve-api-daemon genera uno propio al
+// instalar); el cliente acepta cualquier cert (InsecureSkipVerify) porque la
+// autenticación real es el token API, no el cert. Una CA fija configurable se
+// podría añadir en el futuro si hiciera falta.
+func NewClient(cfg Config) *Client {
+	transport := http.DefaultTransport.(*http.Transport).Clone()
+	transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #561
+	return &Client{
+		cfg: cfg,
+		hc:  &http.Client{Timeout: httpTimeout, Transport: transport},
+	}
+}
+
+func (c *Client) authHeader() string {
+	return "PVEAPIToken=" + c.cfg.TokenID + "=" + c.cfg.Secret
+}
+
+func (c *Client) get(ctx context.Context, path string, dst any) error {
+	req, err := http.NewRequestWithContext(ctx, "GET", c.cfg.URL+path, nil)
+	if err != nil {
+		return err
+	}
+	req.Header.Set("Authorization", c.authHeader())
+	req.Header.Set("Accept", "application/json")
+	res, err := c.hc.Do(req)
+	if err != nil {
+		return fmt.Errorf("PVE %s: %w", path, err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 200 {
+		body, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
+		return fmt.Errorf("PVE %s → HTTP %d: %s", path, res.StatusCode, strings.TrimSpace(string(body)))
+	}
+	// La API PVE envuelve todo en {"data": ...}.
+	var wrapper struct {
+		Data json.RawMessage `json:"data"`
+	}
+	if err := json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&wrapper); err != nil {
+		return err
+	}
+	return json.Unmarshal(wrapper.Data, dst)
+}
+
+// Resource: un elemento de cluster/resources (VM, CT, storage, node…).
+// Verificado contra pve-docs: los campos que NetPulse necesita para el
+// sellado de infra son vmid/name/type/node/status.
+type Resource struct {
+	ID     string `json:"id"`     // "qemu/100" | "lxc/200" | "node/citadel-01"…
+	VMID   int    `json:"vmid"`   // 0 para nodos/storage
+	Name   string `json:"name"`   // hostname del CT/VM, o nombre del nodo
+	Type   string `json:"type"`   // "lxc" | "qemu" | "node" | "storage" | …
+	Node   string `json:"node"`   // nodo que lo ejecuta ("" para storage)
+	Status string `json:"status"` // "running" | "stopped" | …
+}
+
+// ClusterResources: GET /api2/json/cluster/resources → VMs/CTs de TODO el
+// cluster con su nodo (host). Una sola llamada.
+func (c *Client) ClusterResources(ctx context.Context) ([]Resource, error) {
+	var out []Resource
+	if err := c.get(ctx, "/api2/json/cluster/resources", &out); err != nil {
+		return nil, err
+	}
+	return out, nil
+}
+
+// VMConfig: GET /nodes/{node}/lxc|qemu/{vmid}/config. Devuelve el objeto de
+// config crudo; NetPulse usa netN → MAC de cada interfaz.
+func (c *Client) VMConfig(ctx context.Context, node, typ string, vmid int) (map[string]any, error) {
+	path := fmt.Sprintf("/api2/json/nodes/%s/%s/%d/config", url.PathEscape(node), typ, vmid)
+	var out map[string]any
+	if err := c.get(ctx, path, &out); err != nil {
+		return nil, err
+	}
+	return out, nil
+}
+
+// NodeIP: GET /nodes/{node}/network → IP IPv4 del bridge vmbr0 (o el primer
+// iface con address IPv4). Identifica al host físico del nodo en la LAN.
+func (c *Client) NodeIP(ctx context.Context, node string) (string, error) {
+	path := fmt.Sprintf("/api2/json/nodes/%s/network", url.PathEscape(node))
+	var out []struct {
+		Iface   string `json:"iface"`
+		Type    string `json:"type"`
+		Address string `json:"address"`
+	}
+	if err := c.get(ctx, path, &out); err != nil {
+		return "", err
+	}
+	// Preferencia: vmbr0 (bridge principal); si no, cualquier iface con IPv4.
+	var fallback string
+	for _, i := range out {
+		if !strings.Contains(i.Address, ".") {
+			continue
+		}
+		if i.Iface == "vmbr0" {
+			return i.Address, nil
+		}
+		if fallback == "" {
+			fallback = i.Address
+		}
+	}
+	return fallback, nil
+}
+
+// MACsOfConfig extrae las MACs de una config de VM/CT. Proxmox expone cada
+// NIC como "net0": "…" con el formato:
+//
+//	LXC:  net0: bridge=vmbr0,hwaddr=BC:24:11:XX:XX:XX,ip=dhcp,name=eth0,type=veth
+//	QEMU: net0: virtio=BC:24:11:XX:XX:XX,bridge=vmbr0   (MAC tras el nombre del modelo)
+//
+// Devuelve las MACs normalizadas a mayúsculas con ':'.
+func MACsOfConfig(cfg map[string]any) []string {
+	var out []string
+	for k, v := range cfg {
+		if !strings.HasPrefix(k, "net") {
+			continue
+		}
+		s, ok := v.(string)
+		if !ok {
+			continue
+		}
+		for _, field := range strings.Split(s, ",") {
+			if strings.HasPrefix(field, "hwaddr=") {
+				if mac := normMAC(field[len("hwaddr="):]); mac != "" {
+					out = append(out, mac)
+				}
+				continue
+			}
+			// QEMU: el primer campo es <modelo>=<MAC> (virtio=XX, e1000=XX…)
+			if eq := strings.Index(field, "="); eq > 0 {
+				val := field[eq+1:]
+				if looksLikeMAC(val) {
+					if mac := normMAC(val); mac != "" {
+						out = append(out, mac)
+					}
+				}
+			}
+		}
+	}
+	return out
+}
+
+func looksLikeMAC(s string) bool {
+	if len(s) != 17 {
+		return false
+	}
+	for i, r := range s {
+		if i%3 == 2 {
+			if r != ':' {
+				return false
+			}
+		} else if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') || (r >= 'A' && r <= 'F')) {
+			return false
+		}
+	}
+	return true
+}
+
+func normMAC(s string) string {
+	var b strings.Builder
+	for _, r := range strings.ToUpper(s) {
+		if (r >= '0' && r <= '9') || (r >= 'A' && r <= 'F') {
+			b.WriteRune(r)
+		}
+	}
+	hex := b.String()
+	if len(hex) != 12 {
+		return ""
+	}
+	var out strings.Builder
+	for i := 0; i < 12; i += 2 {
+		if i > 0 {
+			out.WriteByte(':')
+		}
+		out.WriteString(hex[i : i+2])
+	}
+	return out.String()
+}

+ 139 - 0
server-go/internal/pve/pve_test.go

@@ -0,0 +1,139 @@
+package pve
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"reflect"
+	"sort"
+	"testing"
+)
+
+// Fixtures del formato REAL de las configs de Proxmox (verificado en
+// pve-docs chapter-pct/chapter-qm).
+func TestMACsOfConfigLXC(t *testing.T) {
+	cfg := map[string]any{
+		"hostname": "webs",
+		"net0":     "bridge=vmbr0,hwaddr=BC:24:11:A4:9E:BB,ip=dhcp,name=eth0,type=veth",
+		"net1":     "bridge=vmbr0,hwaddr=bc:24:11:00:00:01,ip=dhcp,name=eth1,type=veth",
+		"memory":   float64(2048),
+	}
+	macs := MACsOfConfig(cfg)
+	want := []string{"BC:24:11:A4:9E:BB", "BC:24:11:00:00:01"}
+	if !reflect.DeepEqual(macs, want) {
+		t.Fatalf("macs lxc: %v (want %v)", macs, want)
+	}
+}
+
+func TestMACsOfConfigQEMU(t *testing.T) {
+	cfg := map[string]any{
+		"name": "pbs-vm",
+		"net0": "e1000=EE:D2:28:5F:B6:3E,bridge=vmbr0",
+		"net1": "virtio=52:54:00:12:34:56,bridge=vmbr0",
+	}
+	macs := MACsOfConfig(cfg)
+	sort.Strings(macs)
+	want := []string{"52:54:00:12:34:56", "EE:D2:28:5F:B6:3E"}
+	sort.Strings(want)
+	if !reflect.DeepEqual(macs, want) {
+		t.Fatalf("macs qemu: %v (want %v)", macs, want)
+	}
+}
+
+func TestMACsOfConfigIgnoraCampos(t *testing.T) {
+	// net0 sin MAC (ip estática sin hwaddr explícita), otros campos, basura.
+	cfg := map[string]any{
+		"net0":   "name=eth0,bridge=vmbr0,ip=192.168.1.10/24",
+		"net1":   "bridge=vmbr0,hwaddr=00:11:22:33:44:55,ip=dhcp,name=eth1",
+		"memory": "2048",               // no es net*, se ignora
+		"netx":   "no es una NIC real", // prefijo net pero sin MAC
+	}
+	macs := MACsOfConfig(cfg)
+	want := []string{"00:11:22:33:44:55"}
+	if !reflect.DeepEqual(macs, want) {
+		t.Fatalf("macs: %v (want %v)", macs, want)
+	}
+}
+
+// TestClientClusterResources: el cliente parsea {"data":[...]} de la API PVE
+// y manda el header de token.
+func TestClientClusterResources(t *testing.T) {
+	var gotAuth string
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		gotAuth = r.Header.Get("Authorization")
+		if r.URL.Path != "/api2/json/cluster/resources" {
+			t.Errorf("path: %s", r.URL.Path)
+		}
+		w.Header().Set("Content-Type", "application/json")
+		w.Write([]byte(`{"data":[
+			{"id":"node/citadel-01","node":"citadel-01","type":"node","status":"online","name":"citadel-01"},
+			{"id":"lxc/100","vmid":100,"node":"citadel-01","type":"lxc","status":"running","name":"webs"},
+			{"id":"qemu/200","vmid":200,"node":"citadel-02","type":"qemu","status":"running","name":"pbs"},
+			{"id":"lxc/101","vmid":101,"node":"citadel-01","type":"lxc","status":"stopped","name":"apagado"}
+		]}`))
+	}))
+	defer srv.Close()
+
+	c := NewClient(Config{URL: srv.URL, TokenID: "root@pam!netpulse", Secret: "uuid-secret"})
+	res, err := c.ClusterResources(context.Background())
+	if err != nil {
+		t.Fatalf("cluster: %v", err)
+	}
+	if len(res) != 4 {
+		t.Fatalf("resources: %d", len(res))
+	}
+	if res[1].VMID != 100 || res[1].Type != "lxc" || res[1].Node != "citadel-01" || res[1].Name != "webs" || res[1].Status != "running" {
+		t.Fatalf("lxc webs: %+v", res[1])
+	}
+	if res[2].VMID != 200 || res[2].Type != "qemu" || res[2].Node != "citadel-02" {
+		t.Fatalf("qemu pbs: %+v", res[2])
+	}
+	if res[0].VMID != 0 || res[0].Type != "node" {
+		t.Fatalf("node: %+v", res[0])
+	}
+	if want := "PVEAPIToken=root@pam!netpulse=uuid-secret"; gotAuth != want {
+		t.Fatalf("auth: %q (want %q)", gotAuth, want)
+	}
+}
+
+func TestClientErrors(t *testing.T) {
+	// 401 sin token válido
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusUnauthorized)
+		w.Write([]byte(`{"errors":{"root@pam!netpulse":"no such token"}}`))
+	}))
+	defer srv.Close()
+	c := NewClient(Config{URL: srv.URL, TokenID: "root@pam!netpulse", Secret: "mal"})
+	if _, err := c.ClusterResources(context.Background()); err == nil {
+		t.Fatal("401 debería dar error")
+	}
+}
+
+func TestConfigEnabled(t *testing.T) {
+	if (Config{}).Enabled() {
+		t.Fatal("config vacía no enabled")
+	}
+	if !(Config{URL: "https://x:8006", TokenID: "a!b", Secret: "c"}).Enabled() {
+		t.Fatal("config completa debería ser enabled")
+	}
+}
+
+func TestNodeIP(t *testing.T) {
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "application/json")
+		w.Write([]byte(`{"data":[
+			{"iface":"eno1","type":"eth","address":""},
+			{"iface":"vmbr0","type":"bridge","address":"192.168.1.101"},
+			{"iface":"vmbr0","type":"bridge","address":"fe80::1"}
+		]}`))
+	}))
+	defer srv.Close()
+	c := NewClient(Config{URL: srv.URL, TokenID: "a!b", Secret: "c"})
+	ip, err := c.NodeIP(context.Background(), "citadel-02")
+	if err != nil {
+		t.Fatalf("nodeip: %v", err)
+	}
+	if ip != "192.168.1.101" {
+		t.Fatalf("ip: %q", ip)
+	}
+}