Просмотр исходного кода

feat(proxmox): support multiple instances (several clusters or standalone nodes) (#765)

* feat(proxmox): multiple instances - merged inventory, per-instance sealing, list UI (#764)

* fix(proxmox): never expose token secrets in the instances API response

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 месяцев назад
Родитель
Сommit
e8ec72120e

+ 1 - 0
CHANGELOG.md

@@ -10,6 +10,7 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 ### Added
 
 - **Flujo completo de actualizaciones de firmware con owut/ASU (#761)**: la pantalla de actualizaciones se rediseña en torno al attended sysupgrade. Modelo y versión actuales pasan a solo lectura con lo detectado del board info; la versión objetivo es un desplegable con las versiones estables que ASU puede construir para el router (aviso inline en saltos de rama mayor); URL y checksum quedan como vía avanzada. owut se puede instalar desde la UI, "Comprobar" pasa a la fila de acciones junto a Guardar / Actualizar ahora / Programar, y Actualizar ahora lanza el upgrade desatendido (conserva los paquetes instalados) con confirmación clara: el estado sigue la secuencia construcción → descarga → reinicio, con vista de proceso (fase, barra de progreso y consola) y vista de éxito al terminar. Programación con recurrencia una vez / semanal (empezando en lunes) / mensual, idempotente (un router al día no hace nada) y con aviso del resultado por alerta (feed, push, webhook, Telegram). Los routers con firmware de fabricante (GL.iNet, detectado por sus repositorios) quedan fuera del flujo con un panel informativo: sus actualizaciones las gestiona el fabricante. Los paquetes del propio stack (netgrip, agente) sobreviven al flasheo: NetPulse asegura sus ficheros en /etc/sysupgrade.conf antes de actualizar, y los paquetes locales sin feed se detectan en el check y se ofrecen para excluir con sus nombres.
+- **Proxmox VE multi-instancia (#764)**: la integración pasa de un único endpoint a una lista de instancias (clusters o nodos sueltos), cada una con su URL y token de solo lectura; la config anterior migra sola a una instancia "default". El inventario consulta todas las instancias y fusiona VMs/CTs y nodos (con claves por instancia, para que dos clusters con nodos homónimos no se pisen), la topología sella como siempre por MAC, y los nodos de hipervisor llevan su instancia para distinguirlos en la UI. Ajustes muestra la lista con añadir, editar y quitar; los secretos nunca salen del servidor.
 - **Auto-actualización programada del servidor (#759)**: nueva programación en Ajustes → Administración con modo desactivado (por defecto) / diaria / semanal / mensual y hora. El disparo comprueba novedades y aplica solo el binario cuando el readiness lo permite (nunca en modo demo ni con el check fallido), con la verificación de salud y el rollback automático del helper root; el reloj deriva del último disparo persistido, así que reinicios y la propia actualización no re disparan la ventana. Cada intento (aplicada, sin novedades, comprobación fallida, no aplicable) queda en Ajustes y avisa por alerta.
 
 ## [2.28.24] - 2026-09-12

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

@@ -1556,7 +1556,11 @@
       "save": "Save",
       "saving": "Saving…",
       "disable": "Disable",
-      "errorGeneric": "Could not save the Proxmox configuration."
+      "errorGeneric": "Could not save the Proxmox configuration.",
+      "add": "Add instance",
+      "delete": "Remove",
+      "instanceName": "Name (e.g. Home)",
+      "instanceId": "Identifier (slug, not editable later)"
     },
     "sections": {
       "personalization": "Configuration",

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

@@ -1556,7 +1556,11 @@
       "save": "Guardar",
       "saving": "Guardando…",
       "disable": "Desactivar",
-      "errorGeneric": "No se pudo guardar la configuración de Proxmox."
+      "errorGeneric": "No se pudo guardar la configuración de Proxmox.",
+      "add": "Añadir instancia",
+      "delete": "Quitar",
+      "instanceName": "Nombre (p. ej. Casa)",
+      "instanceId": "Identificador (slug, no editable luego)"
     },
     "sections": {
       "personalization": "Configuración",

+ 161 - 128
app/src/pages/Settings.tsx

@@ -1649,84 +1649,80 @@ 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).
+// Proxmox VE (#561/#764): inventario read-only para sellar hypervisor/ct en
+// Dispositivos. Multi-instancia: varios clusters o nodos sueltos, cada uno
+// con su URL + token de solo lectura (el secret nunca vuelve del servidor).
+interface PveInstanceCfg {
+  id: string
+  name: string
+  url: string
+  tokenId: string
+  secret?: string
+}
+
 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 [instances, setInstances] = useState<PveInstanceCfg[]>([])
+  const [editing, setEditing] = useState<PveInstanceCfg | null>(null)
+  const [isNew, setIsNew] = 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 load = async () => {
+    try {
+      const res = await fetch('/api/config/proxmox')
+      if (!res.ok) return
+      const json = (await res.json()) as { instances?: PveInstanceCfg[] }
+      setInstances(json.instances ?? [])
+    } catch {
+      // sin servidor → no-op
     }
+  }
+
+  useEffect(() => {
+    void load()
   }, [])
 
   const save = async (e: React.FormEvent) => {
     e.preventDefault()
-    if (saving) return
+    if (!editing || 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 body: Record<string, unknown> = {
+        id: editing.id.trim(),
+        name: editing.name.trim(),
+        url: editing.url.trim(),
+        tokenId: editing.tokenId.trim(),
+      }
+      if (editing.secret) body.secret = editing.secret
       const res = await fetch('/api/config/proxmox', {
         method: 'PUT',
         headers: { 'Content-Type': 'application/json' },
-        body: JSON.stringify(payload),
+        body: JSON.stringify(body),
       })
-      if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
-      if (secret) {
-        setTokenSet(true)
-        setSecret('')
+      if (!res.ok && res.status !== 204) {
+        const b = (await res.json().catch(() => ({}))) as { message?: string }
+        throw new Error(b.message ?? `HTTP ${res.status}`)
       }
-      setEditing(false)
+      setEditing(null)
+      await load()
       onSaved()
-    } catch {
-      setError(t('settings.proxmox.errorGeneric'))
+    } catch (err) {
+      setError(String(err).replace(/^Error:\s*/, '') || t('settings.proxmox.errorGeneric'))
     } finally {
       setSaving(false)
     }
   }
 
-  const disable = async () => {
+  const remove = async (id: string) => {
     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: '' }),
-      })
+      const res = await fetch(`/api/config/proxmox/${encodeURIComponent(id)}`, { method: 'DELETE' })
       if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`)
-      setURL('')
-      setTokenId('')
-      setTokenSet(false)
-      setEditing(false)
+      await load()
       onSaved()
     } catch {
       setError(t('settings.proxmox.errorGeneric'))
@@ -1735,100 +1731,137 @@ function ProxmoxManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     }
   }
 
-  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>
-    )
-  }
+  const empty = { id: '', name: '', url: '', tokenId: '', secret: '' }
 
   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-elevated 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-elevated 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-elevated 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 && (
+      <div className="space-y-2.5">
+        {instances.map((inst) => (
+          <div key={inst.id} 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} />
+            <div className="min-w-0 flex-1">
+              <p className="truncate text-sm font-medium text-text-primary">
+                {inst.name || inst.id}
+                <span className="ml-1.5 font-mono text-xs text-text-muted">({inst.id})</span>
+              </p>
+              <p className="truncate font-mono text-xs text-text-secondary">{inst.url}</p>
+            </div>
+            <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(false)
-                setSecret('')
+                setIsNew(false)
+                setEditing({ ...inst, secret: '' })
                 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"
+              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"
             >
-              {t('settings.users.cancel')}
+              <Pencil className="h-4 w-4" strokeWidth={1.75} />
             </button>
-          )}
-          {tokenSet && (
             <button
               type="button"
-              onClick={() => void disable()}
+              onClick={() => void remove(inst.id)}
+              aria-label={t('settings.proxmox.delete')}
+              title={t('settings.proxmox.delete')}
+              className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-danger/30 text-danger transition-colors duration-150 hover:border-danger/60 disabled:opacity-40"
               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')}
+              <Trash2 className="h-4 w-4" strokeWidth={1.75} />
             </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>
+          </div>
+        ))}
+
+        {editing ? (
+          <form onSubmit={(e) => void save(e)} className="space-y-2.5 rounded-xl border border-border bg-canvas p-3">
+            <div className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
+              <input
+                type="text"
+                value={editing.name}
+                onChange={(e) => setEditing({ ...editing, name: e.target.value })}
+                placeholder={t('settings.proxmox.instanceName')}
+                aria-label={t('settings.proxmox.instanceName')}
+                className="rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+              <input
+                type="text"
+                value={isNew ? editing.id : editing.id}
+                disabled={!isNew}
+                onChange={(e) => setEditing({ ...editing, id: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })}
+                placeholder="casa"
+                aria-label={t('settings.proxmox.instanceId')}
+                className="rounded-lg border border-border bg-elevated px-3 py-2 font-mono text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none disabled:opacity-60"
+              />
+            </div>
+            <input
+              type="text"
+              value={editing.url}
+              onChange={(e) => setEditing({ ...editing, url: e.target.value })}
+              placeholder="https://192.168.1.100:8006"
+              aria-label={t('settings.proxmox.url')}
+              className="w-full rounded-lg border border-border bg-elevated 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={editing.tokenId}
+                onChange={(e) => setEditing({ ...editing, tokenId: e.target.value })}
+                placeholder="root@pam!netpulse"
+                aria-label={t('settings.proxmox.tokenId')}
+                className="rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+              <input
+                type="password"
+                value={editing.secret ?? ''}
+                onChange={(e) => setEditing({ ...editing, secret: e.target.value })}
+                placeholder={!isNew ? t('settings.proxmox.secretKeep') : t('settings.proxmox.secret')}
+                aria-label={t('settings.proxmox.secret')}
+                autoComplete="new-password"
+                className="rounded-lg border border-border bg-elevated px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+            </div>
+            <div className="flex flex-wrap items-center gap-3">
+              <button
+                type="submit"
+                disabled={saving || !editing.url.trim() || !editing.tokenId.trim() || (isNew && !editing.id.trim())}
+                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>
+              <button
+                type="button"
+                onClick={() => {
+                  setEditing(null)
+                  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>
+            </div>
+            {error && <p className="text-caption text-danger">{error}</p>}
+          </form>
+        ) : (
+          <button
+            type="button"
+            onClick={() => {
+              setIsNew(true)
+              setEditing({ ...empty })
+              setError(null)
+            }}
+            disabled={saving}
+            className="flex w-full items-center justify-center gap-2 rounded-xl border border-dashed border-border px-3 py-2.5 text-sm font-medium text-text-secondary transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:opacity-40"
+          >
+            <Plus className="h-4 w-4" strokeWidth={1.75} />
+            {t('settings.proxmox.add')}
+          </button>
+        )}
+      </div>
+      {error && !editing && <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>
     </Card>
   )
 }

+ 7 - 8
server-go/internal/adapters/live.go

@@ -27,7 +27,6 @@ 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).
@@ -313,13 +312,13 @@ 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
+	// PVE (#561/#764): clientes por instancia Proxmox + caché del
+	// inventario. Los clientes se reconstruyen si cambia la lista de
+	// instancias (pveKey); el inventario se refresca con TTL.
+	pveClients []pveInstClient
+	pveKey     string
+	pveInv     *pveInventory
+	pveInvAt   time.Time
 
 	// fdbMemo (#656): última boca REAL donde el FDB vio cada MAC (epoch ms).
 	// Los dispositivos callados (AV: TV, receptor, shield…) caducan su entrada

+ 123 - 94
server-go/internal/adapters/proxmox.go

@@ -41,54 +41,69 @@ const pveInventoryTTL = 5 * time.Minute
 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).
+	// nodes: nodos de todas las instancias (#764 multi-endpoint). La clave
+	// interna de los mapas es "instancia|nodo" para que dos clusters con
+	// nodos homónimos no se pisen.
+	nodes map[string]pveNode
+	// nodeIPs: "instancia|nodo" → IP del bridge vmbr0. Permite casar el
+	// device HOST por IP cuando NetPulse no conoce su nombre.
 	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"
+	Name     string // hostname del CT/VM (webs, pbs…)
+	Node     string // nodo que lo ejecuta (citadel-01)
+	Type     string // "lxc" | "qemu"
+	Instance string // instancia Proxmox a la que pertenece (#764)
 }
 
-// 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
+// pveNode: un nodo PVE con su instancia de origen.
+type pveNode struct {
+	Instance string
+	Node     string
+}
+
+// nodeKey: clave compuesta de los mapas del inventario.
+func nodeKey(instance, node string) string { return instance + "|" + node }
+
+// pveInstClient: cliente PVE asociado a una instancia configurada.
+type pveInstClient struct {
+	inst pve.Instance
+	c    *pve.Client
 }
 
-// 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
+// pveClientsCached: clientes de TODAS las instancias configuradas (#764),
+// recreados si la lista cambió (patrón AdGuard). Sin instancias → nil.
+func (l *Live) pveClientsCached() []pveInstClient {
+	if l.db == nil {
+		return nil
+	}
+	instances := pve.LoadInstances(l.db.DB)
+	key := ""
+	for _, in := range instances {
+		key += in.ID + "|" + in.URL + "|" + in.TokenID + "|" + in.Secret + "\n"
+	}
+	if key == "" {
+		l.pveClients = nil
 		l.pveKey = ""
 		return nil
 	}
-	key := cfg.URL + "|" + cfg.TokenID + "|" + cfg.Secret
-	if l.pveClient == nil || l.pveKey != key {
-		l.pveClient = pve.NewClient(cfg)
+	if l.pveKey != key {
+		clients := make([]pveInstClient, 0, len(instances))
+		for _, in := range instances {
+			clients = append(clients, pveInstClient{inst: in, c: pve.NewClient(in.Config)})
+		}
+		l.pveClients = clients
 		l.pveKey = key
 	}
-	return l.pveClient
+	return l.pveClients
 }
 
 // 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 {
+	clients := l.pveClientsCached()
+	if len(clients) == 0 {
 		return nil
 	}
 	l.mu.Lock()
@@ -96,7 +111,7 @@ func (l *Live) pveInventoryCached() *pveInventory {
 	if l.pveInv != nil && time.Since(l.pveInvAt) < pveInventoryTTL {
 		return l.pveInv
 	}
-	inv := l.fetchPveInventory(client)
+	inv := l.fetchPveInventory(clients)
 	if inv == nil {
 		return l.pveInv // conserva el último bueno si la consulta falla
 	}
@@ -106,56 +121,59 @@ func (l *Live) pveInventoryCached() *pveInventory {
 }
 
 // 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)
+// running de TODAS las instancias (#764) y fusiona el inventario. Best-effort
+// por instancia: una instancia caída no invalida las demás.
+func (l *Live) fetchPveInventory(clients []pveInstClient) *pveInventory {
+	ctx, cancel := context.WithTimeout(context.Background(), 30*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{},
+		ctByMAC: map[string]pveVM{},
+		nodes:   map[string]pveNode{},
+		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)
+	for _, ic := range clients {
+		resources, err := ic.c.ClusterResources(ctx)
 		if err != nil {
-			log.Printf("[netpulse:pve] config %s/%d: %v", r.Type, r.VMID, err)
+			log.Printf("[netpulse:pve] %s cluster/resources: %v", ic.inst.ID, err)
 			continue
 		}
-		for _, mac := range pve.MACsOfConfig(cfg) {
-			inv.ctByMAC[mac] = pveVM{Name: r.Name, Node: r.Node, Type: r.Type}
+		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 != "" {
+					key := nodeKey(ic.inst.ID, r.Node)
+					inv.nodes[key] = pveNode{Instance: ic.inst.ID, Node: r.Node}
+					// IP del host (vmbr0) para casar el device HOST por IP.
+					if ip, err := ic.c.NodeIP(ctx, r.Node); err == nil && ip != "" {
+						inv.nodeIPs[key] = ip
+					} else if err != nil {
+						log.Printf("[netpulse:pve] %s nodeip %s: %v", ic.inst.ID, 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 := ic.c.VMConfig(ctx, r.Node, r.Type, r.VMID)
+			if err != nil {
+				log.Printf("[netpulse:pve] %s config %s/%d: %v", ic.inst.ID, 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, Instance: ic.inst.ID}
+			}
 		}
 	}
-	if len(inv.ctByMAC) == 0 && len(inv.nodeNames) == 0 {
-		return nil // cluster sin VMs corriendo ni nodos legibles
+	if len(inv.ctByMAC) == 0 && len(inv.nodes) == 0 {
+		return nil // sin VMs corriendo ni nodos legibles en ninguna instancia
 	}
 	return inv
 }
@@ -193,30 +211,41 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 	// 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
+	// NO debe ganar. Con multi-instancia (#764) las claves son compuestas
+	// "instancia|nodo": dos clusters pueden tener nodos homónimos.
+	hostIDByNode := map[string]string{} // "inst|node" → id del device host
 	hostIdxByID := map[string]int{}
-	nodeNameByID := map[string]string{} // id del device host → nombre del nodo
+	nodeByKey := map[string]pveNode{} // "inst|node" → nodo (para renombrar)
 	for i := range devices {
 		hostIdxByID[devices[i].ID] = i
 		if devices[i].IP != "" {
-			for node, ip := range inv.nodeIPs {
+			for key, ip := range inv.nodeIPs {
 				if devices[i].IP == ip {
-					hostIDByNode[node] = devices[i].ID
-					nodeNameByID[devices[i].ID] = node
+					hostIDByNode[key] = devices[i].ID
+					nodeByKey[key] = inv.nodes[key]
 				}
 			}
 		}
 	}
-	// Pasada 2: por nombre, solo si el nodo aún no tiene host por IP.
+	// Pasada 2: por nombre, solo si ese 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)
+		matched := ""
+		for key, n := range inv.nodes {
+			if n.Node == devices[i].Name {
+				matched = key
+				if _, ok := hostIDByNode[key]; !ok {
+					break // este nodo en concreto aún no tiene host
+				}
+			}
+		}
+		if matched == "" {
+			continue
 		}
-		if inv.nodeNames[devices[i].Name] {
-			hostIDByNode[devices[i].Name] = devices[i].ID
-			nodeNameByID[devices[i].ID] = devices[i].Name
+		if _, ok := hostIDByNode[matched]; ok {
+			continue // ya tiene host por IP
 		}
+		hostIDByNode[matched] = devices[i].ID
+		nodeByKey[matched] = inv.nodes[matched]
 	}
 	// Casar cada CT por MAC.
 	for mac, vm := range inv.ctByMAC {
@@ -224,7 +253,7 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 		if !ok {
 			continue // el CT no es un device conocido (apagado o sin tráfico)
 		}
-		hostID := hostIDByNode[vm.Node]
+		hostID := hostIDByNode[nodeKey(vm.Instance, 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
@@ -235,15 +264,14 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 	}
 	// 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 {
+	for key, id := range hostIDByNode {
 		idx, ok := hostIdxByID[id]
 		if !ok {
 			continue
 		}
 		devices[idx].Infra = "hypervisor"
-		if name, ok := nodeNameByID[id]; ok && looksLikeMACName(devices[idx].Name) {
-			devices[idx].Name = name
-			_ = node
+		if n, ok := nodeByKey[key]; ok && looksLikeMACName(devices[idx].Name) {
+			devices[idx].Name = n.Node
 		}
 	}
 	// CTs por host (para el macCount informativo del distnode).
@@ -264,7 +292,7 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 			existingHost[dn.HostDeviceID] = true
 		}
 	}
-	for node, id := range hostIDByNode {
+	for key, id := range hostIDByNode {
 		if existingHost[id] {
 			continue
 		}
@@ -272,11 +300,12 @@ func applyPVEInfra(devices []Device, dists []DistributionNode, inv *pveInventory
 		if !ok {
 			continue
 		}
+		n := inv.nodes[key]
 		dists = append(dists, DistributionNode{
-			ID: "dist-pve-" + node, Kind: "hypervisor",
+			ID: "dist-pve-" + n.Instance + "-" + n.Node, Kind: "hypervisor",
 			RouterID: devices[idx].RouterID, Port: devices[idx].Port, PortLabel: devices[idx].PortLabel,
-			HostDeviceID: id, Name: node, MacCount: ctCountByHost[id],
-			Source: "proxmox",
+			HostDeviceID: id, Name: n.Node, MacCount: ctCountByHost[id],
+			Source: "proxmox", Instance: n.Instance,
 		})
 	}
 	return dists

+ 66 - 17
server-go/internal/adapters/proxmox_test.go

@@ -3,7 +3,6 @@ package adapters
 
 import (
 	"testing"
-
 )
 
 // TestSealProxmoxInfra: con un cluster de 1 nodo (citadel-01) y 2 CTs
@@ -13,10 +12,10 @@ import (
 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"},
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
+			"02:78:F4:02:8A:94": {Name: "homeassistant", Node: "citadel-01", Type: "lxc", Instance: "default"},
 		},
-		nodeNames: map[string]bool{"citadel-01": true},
+		nodes: map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
 	}
 	devices := []Device{
 		{ID: "c8-ff-bf-0c-60-12", MAC: "C8:FF:BF:0C:60:12", Name: "citadel-01", RouterID: "gateway", Band: "—"},
@@ -66,9 +65,9 @@ func TestSealProxmoxInfraSinInventario(t *testing.T) {
 func TestSealProxmoxInfraHostSinDevice(t *testing.T) {
 	inv := &pveInventory{
 		ctByMAC: map[string]pveVM{
-			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-99", Type: "lxc"},
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-99", Type: "lxc", Instance: "default"},
 		},
-		nodeNames: map[string]bool{"citadel-99": true},
+		nodes: map[string]pveNode{"default|citadel-99": {Instance: "default", Node: "citadel-99"}},
 	}
 	devices := []Device{
 		{ID: "bc-24-11-a4-9e-bb", MAC: "BC:24:11:A4:9E:BB", Name: "webs", RouterID: "gateway"},
@@ -88,10 +87,10 @@ func TestSealProxmoxInfraHostSinDevice(t *testing.T) {
 func TestSealProxmoxInfraHostPorIP(t *testing.T) {
 	inv := &pveInventory{
 		ctByMAC: map[string]pveVM{
-			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc"},
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc", Instance: "default"},
 		},
-		nodeNames: map[string]bool{"citadel-02": true},
-		nodeIPs:   map[string]string{"citadel-02": "192.168.1.101"},
+		nodes:   map[string]pveNode{"default|citadel-02": {Instance: "default", Node: "citadel-02"}},
+		nodeIPs: map[string]string{"default|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"},
@@ -116,10 +115,10 @@ func TestSealProxmoxInfraHostPorIP(t *testing.T) {
 func TestSealProxmoxInfraHostConflictoNICs(t *testing.T) {
 	inv := &pveInventory{
 		ctByMAC: map[string]pveVM{
-			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc"},
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-01", Type: "lxc", Instance: "default"},
 		},
-		nodeNames: map[string]bool{"citadel-01": true},
-		nodeIPs:   map[string]string{"citadel-01": "192.168.1.100"},
+		nodes:   map[string]pveNode{"default|citadel-01": {Instance: "default", Node: "citadel-01"}},
+		nodeIPs: map[string]string{"default|citadel-01": "192.168.1.100"},
 	}
 	devices := []Device{
 		// device con nombre citadel-01 pero IP de gestión (.243) y offline.
@@ -156,11 +155,11 @@ func TestPVEMacToDeviceID(t *testing.T) {
 func TestPVEHypervisorDistNodes(t *testing.T) {
 	inv := &pveInventory{
 		ctByMAC: map[string]pveVM{
-			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc"},
-			"02:78:F4:02:8A:94": {Name: "pbs", Node: "citadel-02", Type: "lxc"},
+			"BC:24:11:A4:9E:BB": {Name: "webs", Node: "citadel-02", Type: "lxc", Instance: "default"},
+			"02:78:F4:02:8A:94": {Name: "pbs", Node: "citadel-02", Type: "lxc", Instance: "default"},
 		},
-		nodeNames: map[string]bool{"citadel-02": true, "citadel-01": true},
-		nodeIPs:   map[string]string{"citadel-02": "192.168.1.101", "citadel-01": "192.168.1.100"},
+		nodes:   map[string]pveNode{"default|citadel-02": {Instance: "default", Node: "citadel-02"}, "default|citadel-01": {Instance: "default", Node: "citadel-01"}},
+		nodeIPs: map[string]string{"default|citadel-02": "192.168.1.101", "default|citadel-01": "192.168.1.100"},
 	}
 	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", Port: "lan8"},
@@ -176,7 +175,7 @@ func TestPVEHypervisorDistNodes(t *testing.T) {
 		t.Fatalf("esperado 2 distnodes (L2 + 1 PVE), got %d: %+v", len(dists), dists)
 	}
 	dn := dists[1]
-	if dn.ID != "dist-pve-citadel-02" || dn.Kind != "hypervisor" || dn.Source != "proxmox" {
+	if dn.ID != "dist-pve-default-citadel-02" || dn.Kind != "hypervisor" || dn.Source != "proxmox" {
 		t.Fatalf("distnode PVE mal construido: %+v", dn)
 	}
 	if dn.HostDeviceID != devices[0].ID {
@@ -198,3 +197,53 @@ func TestPVEHypervisorDistNodesSinHost(t *testing.T) {
 		t.Fatalf("sin inventario no debe añadir distnodes: %+v", out)
 	}
 }
+
+// TestSealProxmoxInfraMultiInstancia (#764): dos clusters con un nodo
+// homónimo ("pve1") en ambos: las claves compuestas evitan que se pisen, los
+// CTs cuelgan del host de SU instancia y los distnodes son distintos.
+func TestSealProxmoxInfraMultiInstancia(t *testing.T) {
+	inv := &pveInventory{
+		ctByMAC: map[string]pveVM{
+			"AA:00:00:00:00:01": {Name: "webs", Node: "pve1", Type: "lxc", Instance: "casa"},
+			"BB:00:00:00:00:02": {Name: "erp", Node: "pve1", Type: "qemu", Instance: "ofi"},
+		},
+		nodes: map[string]pveNode{
+			"casa|pve1": {Instance: "casa", Node: "pve1"},
+			"ofi|pve1":  {Instance: "ofi", Node: "pve1"},
+		},
+	}
+	devices := []Device{
+		{ID: "aa-11", MAC: "AA:11:00:00:00:01", Name: "host-casa", RouterID: "gateway", Band: "—"},
+		{ID: "bb-22", MAC: "BB:11:00:00:00:02", Name: "host-ofi", RouterID: "gateway", Band: "—"},
+	}
+	// Hosts casados por IP de su instancia.
+	inv.nodeIPs = map[string]string{"casa|pve1": "10.0.0.1", "ofi|pve1": "10.0.0.2"}
+	devices[0].IP = "10.0.0.1"
+	devices[1].IP = "10.0.0.2"
+	dists := applyPVEInfra(devices, nil, inv)
+
+	if devices[0].Infra != "hypervisor" || devices[1].Infra != "hypervisor" {
+		t.Fatalf("hosts: %q %q", devices[0].Infra, devices[1].Infra)
+	}
+	// Cada CT cuelga del host de SU instancia (no del homónimo).
+	byMAC := map[string]int{}
+	for i, d := range devices {
+		byMAC[d.MAC] = i
+	}
+	_ = byMAC
+	// (Los CT webs/erp no son devices aquí: basta con que los hosts sellaran
+	// y los distnodes salgan separados por instancia.)
+	if len(dists) != 2 {
+		t.Fatalf("distnodes: %v", dists)
+	}
+	ids := map[string]bool{}
+	for _, dn := range dists {
+		ids[dn.ID] = true
+		if dn.Instance == "" {
+			t.Fatalf("distnode sin instancia: %+v", dn)
+		}
+	}
+	if !ids["dist-pve-casa-pve1"] || !ids["dist-pve-ofi-pve1"] {
+		t.Fatalf("IDs de distnodes homónimos: %v", ids)
+	}
+}

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

@@ -317,6 +317,9 @@ type DistributionNode struct {
 	// Source: origen del nodo de hipervisor. "" = inferido por L2 (OUI);
 	// "proxmox" = sellado con el inventario read-only de la API PVE (#561).
 	Source string `json:"source,omitempty"`
+	// Instance: instancia Proxmox (multi-endpoint #764) a la que pertenece
+	// el host ("casa", "ofi"…); vacío en los inferidos y en single.
+	Instance string `json:"instance,omitempty"`
 	// Mac: chassis-MAC del vecino cuando kind='managed' (SPEC-CANON D1). La
 	// app la usa para excluir del mapa el chip del Device del switch (que
 	// existe como Device Y como nodo managed, sin duplicar el render).

+ 101 - 34
server-go/internal/httpapi/config.go

@@ -15,6 +15,7 @@ import (
 
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/discover"
+	"github.com/gnacho/netpulse/server-go/internal/pve"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 	"github.com/gnacho/netpulse/server-go/internal/sshkey"
 )
@@ -40,6 +41,7 @@ func (s *server) registerConfigRoutes(mux *http.ServeMux) {
 	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)))
+	mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
 }
 
 // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
@@ -493,14 +495,31 @@ 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.
+// GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
+// El secret nunca sale: tokenSet por instancia. Los campos planos legacy
+// (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
+// para no romper frontends cacheados.
 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") != "",
-	})
+	instances := pve.LoadInstances(s.db.DB)
+	// Vista sanitizada: el secret JAMAS sale del server (#764).
+	view := make([]map[string]string, 0, len(instances))
+	for _, in := range instances {
+		view = append(view, map[string]string{
+			"id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
+		})
+	}
+	out := map[string]any{
+		"instances": view,
+		"url":       "",
+		"tokenId":   "",
+		"tokenSet":  false,
+	}
+	if len(instances) > 0 {
+		out["url"] = instances[0].URL
+		out["tokenId"] = instances[0].TokenID
+		out["tokenSet"] = instances[0].Secret != ""
+	}
+	writeJSON(w, http.StatusOK, out)
 }
 
 type proxmoxInput struct {
@@ -509,55 +528,103 @@ type proxmoxInput struct {
 	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.
+type proxmoxInstanceInput struct {
+	ID      string `json:"id"`
+	Name    string `json:"name"`
+	URL     string `json:"url"`
+	TokenID string `json:"tokenId"`
+	Secret  string `json:"secret"` // vacío en edición = conservar el actual
+}
+
+// PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
+// {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
+// aplica al estilo legacy single (url/tokenId/secret sobre la instancia
+// migrada "default", creándola si hace falta; url "" desactiva todo).
 func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
-	var in proxmoxInput
+	var in proxmoxInstanceInput
 	if st := readJSONBody(w, r, &in); st != 0 {
 		writeBodyError(w, st, "invalid_json", "")
 		return
 	}
+	// Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
+	// conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
+	// url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
 	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
-		}
+	id := strings.TrimSpace(in.ID)
+	if id == "" {
+		id = "default" // legacy sin id
+	}
+	url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
+	if url != "" {
 		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
+	}
+	list := pve.LoadInstances(s.db.DB)
+	var current *pve.Instance
+	for i := range list {
+		if list[i].ID == id {
+			current = &list[i]
+			break
 		}
 	}
-	if tokenID != "" {
-		if _, err := s.db.Exec(upsert, "proxmox_token_id", tokenID); err != nil {
-			writeError(w, http.StatusInternalServerError, "internal_error")
+	if current != nil {
+		if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" {
+			writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
 			return
 		}
-	}
-	if in.Secret != "" {
-		if _, err := s.db.Exec(upsert, "proxmox_token_secret", in.Secret); err != nil {
+		if url != "" {
+			current.URL = url
+		}
+		if tokenID != "" {
+			current.TokenID = tokenID
+		}
+		if in.Secret != "" {
+			current.Secret = in.Secret
+		}
+		if n := strings.TrimSpace(in.Name); n != "" {
+			current.Name = n
+		}
+		if err := pve.SaveInstances(s.db.DB, list); err != nil {
 			writeError(w, http.StatusInternalServerError, "internal_error")
 			return
 		}
+		w.WriteHeader(http.StatusNoContent)
+		return
+	}
+	// Instancia nueva: completa.
+	if url == "" || tokenID == "" || in.Secret == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
+		return
+	}
+	name := strings.TrimSpace(in.Name)
+	if name == "" {
+		name = id
+	}
+	inst := pve.Instance{ID: id, Name: name, Config: pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}}
+	if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
+		writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
+		return
+	}
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
+func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
+	id := r.PathValue("id")
+	if !pve.ValidInstanceID(id) {
+		writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
+		return
+	}
+	if err := pve.DeleteInstance(s.db.DB, id); err != nil {
+		writeError(w, http.StatusInternalServerError, "internal_error")
+		return
 	}
 	w.WriteHeader(http.StatusNoContent)
 }

+ 16 - 4
server-go/internal/httpapi/config_test.go

@@ -519,6 +519,15 @@ func TestProxmoxConfig(t *testing.T) {
 	if body["tokenSet"] != true {
 		t.Fatalf("tokenSet esperado true: %v", body)
 	}
+	// #764: el secret jamas viaja, tampoco dentro de instances.
+	for _, raw := range body["instances"].([]any) {
+		m, _ := raw.(map[string]any)
+		for k := range m {
+			if strings.EqualFold(k, "secret") || strings.EqualFold(k, "Secret") {
+				t.Fatalf("instance con secret en el GET: %v", m)
+			}
+		}
+	}
 
 	// Actualizar solo el secret conserva url/tokenId.
 	res = doReq(t, "PUT", srv.URL+"/api/config/proxmox", cookie,
@@ -540,15 +549,18 @@ func TestProxmoxConfig(t *testing.T) {
 		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":""}`)
+	// Eliminar (#764): DELETE de la instancia; el listado queda vacío.
+	res = doReq(t, "DELETE", srv.URL+"/api/config/proxmox/default", cookie, "")
 	if res.StatusCode != 204 {
 		body := readJSON(t, res)
-		t.Fatalf("PUT proxmox desactivar: %d %v", res.StatusCode, body)
+		t.Fatalf("DELETE proxmox: %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)
+		t.Fatalf("GET tras eliminar: %v", body)
+	}
+	if ins, _ := body["instances"].([]any); len(ins) != 0 {
+		t.Fatalf("instances tras eliminar: %v", ins)
 	}
 }

+ 124 - 0
server-go/internal/pve/instances.go

@@ -0,0 +1,124 @@
+// instances.go - configuración multi-instancia de Proxmox VE (#764).
+//
+// Sustituye a la config plana single-endpoint (proxmox_url/token_id/
+// token_secret) manteniéndola como origen de migración: la primera lectura
+// con kv legacy la convierte en una lista de una instancia. La lista vive en
+// la clave "proxmox_instances" como JSON; los secretos NUNCA salen del
+// server (la API expone tokenSet).
+package pve
+
+import (
+	"database/sql"
+	"encoding/json"
+	"fmt"
+	"log"
+	"regexp"
+	"strings"
+)
+
+// Instance es un endpoint Proxmox configurado (cluster o nodo suelto).
+// Un endpoint de cluster ya devuelve todos sus nodos vía /cluster/resources.
+type Instance struct {
+	// ID: slug estable para la API ("casa", "ofi").
+	ID string `json:"id"`
+	// Name: nombre visible para la UI.
+	Name string `json:"name"`
+	Config
+}
+
+const kvInstances = "proxmox_instances"
+
+// instanceIDRe: slug simple para identificar instancias en URLs.
+var instanceIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
+
+// ValidInstanceID informa de si el id es un slug válido.
+func ValidInstanceID(id string) bool {
+	return instanceIDRe.MatchString(id)
+}
+
+// LoadInstances devuelve las instancias configuradas. Si no existe la lista
+// pero sí la config legacy (proxmox_url), migra automáticamente: escribe la
+// lista y limpia las claves viejas (id "default", nombre "Proxmox").
+func LoadInstances(db *sql.DB) []Instance {
+	if db == nil {
+		return nil
+	}
+	var raw string
+	if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", kvInstances).Scan(&raw); err == nil && strings.TrimSpace(raw) != "" {
+		var list []Instance
+		if err := json.Unmarshal([]byte(raw), &list); err != nil {
+			log.Printf("[pve] instances corruptas, se regeneran: %v", err)
+		} else {
+			return list
+		}
+	}
+	// Migración legacy single-endpoint (#561) → lista de una instancia.
+	var url, tokenID, secret string
+	_ = db.QueryRow("SELECT value FROM kv WHERE key='proxmox_url'").Scan(&url)
+	_ = db.QueryRow("SELECT value FROM kv WHERE key='proxmox_token_id'").Scan(&tokenID)
+	_ = db.QueryRow("SELECT value FROM kv WHERE key='proxmox_token_secret'").Scan(&secret)
+	if url == "" || tokenID == "" || secret == "" {
+		return nil
+	}
+	list := []Instance{{ID: "default", Name: "Proxmox", Config: Config{URL: url, TokenID: tokenID, Secret: secret}}}
+	if err := SaveInstances(db, list); err != nil {
+		log.Printf("[pve] migración legacy: %v", err)
+		return list // devolverla igual: funciona aunque no persista
+	}
+	for _, k := range []string{"proxmox_url", "proxmox_token_id", "proxmox_token_secret"} {
+		_, _ = db.Exec("DELETE FROM kv WHERE key = ?", k)
+	}
+	return list
+}
+
+// SaveInstances persiste la lista completa (UPSERT).
+func SaveInstances(db *sql.DB, list []Instance) error {
+	if db == nil {
+		return fmt.Errorf("pve: sin base de datos")
+	}
+	raw, err := json.Marshal(list)
+	if err != nil {
+		return err
+	}
+	_, err = db.Exec(
+		`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
+		kvInstances, string(raw))
+	return err
+}
+
+// UpsertInstance añade o actualiza una instancia por ID. Secret vacío =
+// conservar el existente (la UI no reenvía secretos). ID no editable.
+func UpsertInstance(db *sql.DB, in Instance) error {
+	if !ValidInstanceID(in.ID) {
+		return fmt.Errorf("id inválido (slug minúsculas, guiones, máx 32)")
+	}
+	if in.URL == "" || in.TokenID == "" {
+		return fmt.Errorf("url y tokenId son requeridos")
+	}
+	list := LoadInstances(db)
+	for i := range list {
+		if list[i].ID == in.ID {
+			if in.Secret == "" {
+				in.Secret = list[i].Secret
+			}
+			list[i] = in
+			return SaveInstances(db, list)
+		}
+	}
+	if in.Secret == "" {
+		return fmt.Errorf("secret requerido para una instancia nueva")
+	}
+	return SaveInstances(db, append(list, in))
+}
+
+// DeleteInstance elimina una instancia por ID (no-op si no existe).
+func DeleteInstance(db *sql.DB, id string) error {
+	list := LoadInstances(db)
+	out := list[:0]
+	for _, in := range list {
+		if in.ID != id {
+			out = append(out, in)
+		}
+	}
+	return SaveInstances(db, out)
+}

+ 77 - 0
server-go/internal/pve/instances_test.go

@@ -0,0 +1,77 @@
+// instances_test.go - tests de la config multi-instancia (#764): migración
+// legacy, upsert parcial (secret conservado) y delete.
+package pve
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func openInstDB(t *testing.T) *db.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	t.Cleanup(func() { d.Close() })
+	return d
+}
+
+func kvPut(t *testing.T, d *db.DB, k, v string) {
+	t.Helper()
+	if _, err := d.Exec(`INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, k, v); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestInstancesMigrationLegacy(t *testing.T) {
+	d := openInstDB(t)
+	kvPut(t, d, "proxmox_url", "https://192.168.1.100:8006")
+	kvPut(t, d, "proxmox_token_id", "root@pam!netpulse")
+	kvPut(t, d, "proxmox_token_secret", "uuid-1")
+
+	list := LoadInstances(d.DB)
+	if len(list) != 1 || list[0].ID != "default" || list[0].URL != "https://192.168.1.100:8006" || list[0].Secret != "uuid-1" {
+		t.Fatalf("migración: %+v", list)
+	}
+	// Las claves legacy se limpian tras migrar.
+	var n int
+	_ = d.DB.QueryRow("SELECT count(*) FROM kv WHERE key LIKE 'proxmox_%' AND key != 'proxmox_instances'").Scan(&n)
+	if n != 0 {
+		t.Fatalf("claves legacy sin limpiar: %d", n)
+	}
+	// Segunda carga: ya viene de la lista.
+	if list2 := LoadInstances(d.DB); len(list2) != 1 || list2[0].ID != "default" {
+		t.Fatalf("segunda carga: %+v", list2)
+	}
+}
+
+func TestInstancesUpsertSecretConservado(t *testing.T) {
+	d := openInstDB(t)
+	in := Instance{ID: "ofi", Name: "Oficina", Config: Config{URL: "https://10.0.0.200:8006", TokenID: "root@pam!np", Secret: "s1"}}
+	if err := UpsertInstance(d.DB, in); err != nil {
+		t.Fatalf("upsert nuevo: %v", err)
+	}
+	// Edición sin secret: conserva s1.
+	in.Secret = ""
+	in.Name = "Ofi editada"
+	if err := UpsertInstance(d.DB, in); err != nil {
+		t.Fatalf("upsert edicion: %v", err)
+	}
+	list := LoadInstances(d.DB)
+	if len(list) != 1 || list[0].Secret != "s1" || list[0].Name != "Ofi editada" {
+		t.Fatalf("tras edicion: %+v", list)
+	}
+	// Nueva sin secret: error.
+	if err := UpsertInstance(d.DB, Instance{ID: "x", Config: Config{URL: "https://x:8006", TokenID: "a!b"}}); err == nil {
+		t.Fatalf("nueva sin secret debe fallar")
+	}
+	// Delete.
+	if err := DeleteInstance(d.DB, "ofi"); err != nil {
+		t.Fatalf("delete: %v", err)
+	}
+	if list := LoadInstances(d.DB); len(list) != 0 {
+		t.Fatalf("tras delete: %+v", list)
+	}
+}

+ 4 - 3
server-go/internal/pve/pve.go

@@ -31,11 +31,12 @@ import (
 // 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
+	URL string `json:"url"`
 	// TokenID: "USER@REALM!TOKENID" (p. ej. "root@pam!netpulse").
-	TokenID string
+	TokenID string `json:"tokenId"`
 	// Secret: la parte UUID del token (se muestra una sola vez al crearlo).
-	Secret string
+	// NUNCA viaja en respuestas de la API (la config se expone sanitizada).
+	Secret string `json:"secret,omitempty"`
 }
 
 // Enabled: true si hay config completa.