Răsfoiți Sursa

feat(integrations): discover the vendor catalog from netpulse-integrations (#1706)

* feat(integrations): discover the vendor catalog from netpulse-integrations

* feat(integrations): vendor catalog refresh action in the UI
Nacho 1 lună în urmă
părinte
comite
3ec540d459

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

@@ -760,6 +760,11 @@
       "submit": "Create",
       "creating": "Creating..."
     },
+    "catalog": {
+      "refresh": "Refresh catalog",
+      "refreshing": "Refreshing...",
+      "updated": "Catalog updated {{time}}"
+    },
     "token": {
       "tokenTitle": "Integration created",
       "tokenDesc": "Copy the token now. It is shown only once and will not be shown again.",
@@ -787,6 +792,7 @@
       "router_error": "The router reported an error.",
       "not_found": "Integration not found.",
       "db_error": "Database error.",
+      "refresh_failed": "Could not refresh the catalog.",
       "generic": "Something went wrong."
     },
     "edit": {

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

@@ -760,6 +760,11 @@
       "submit": "Crear",
       "creating": "Creando..."
     },
+    "catalog": {
+      "refresh": "Refrescar catálogo",
+      "refreshing": "Refrescando...",
+      "updated": "Catálogo actualizado {{time}}"
+    },
     "token": {
       "tokenTitle": "Integración creada",
       "tokenDesc": "Copia el token ahora. Solo se muestra una vez y no se volverá a mostrar.",
@@ -787,6 +792,7 @@
       "router_error": "El router devolvió un error.",
       "not_found": "Integración no encontrada.",
       "db_error": "Error de base de datos.",
+      "refresh_failed": "No se pudo refrescar el catálogo.",
       "generic": "Algo salió mal."
     },
     "edit": {

+ 14 - 2
app/src/lib/integrationsApi.ts

@@ -28,6 +28,13 @@ export interface Vendor {
   description: string
 }
 
+/** Catalog served by GET /api/integrations/vendors (#1697). */
+export interface VendorsResponse {
+  vendors: Vendor[]
+  /** Unix ms of the last successful fetch, 0 when only the seed was served. */
+  lastRefreshedAt?: number
+}
+
 export interface CreateIntegrationInput {
   slug: string
   vendor: string
@@ -81,8 +88,13 @@ const json = (method: string, body: unknown): RequestInit => ({
   body: JSON.stringify(body),
 })
 
-export function fetchVendors(): Promise<{ vendors: Vendor[] }> {
-  return req<{ vendors: Vendor[] }>('/api/integrations/vendors')
+export function fetchVendors(): Promise<VendorsResponse> {
+  return req<VendorsResponse>('/api/integrations/vendors')
+}
+
+/** Forces the vendor catalog discovery (admin). Returns the refreshed catalog. */
+export function refreshVendors(): Promise<VendorsResponse> {
+  return req<VendorsResponse>('/api/integrations/vendors/refresh', { method: 'POST' })
 }
 
 export function fetchIntegrations(): Promise<{ integrations: Integration[] }> {

+ 44 - 4
app/src/pages/Integrations.tsx

@@ -46,6 +46,7 @@ import {
   editIntegration,
   fetchIntegrations,
   fetchVendors,
+  refreshVendors,
   startIntegration,
   stopIntegration,
   updateIntegration,
@@ -87,6 +88,8 @@ export default function Integrations() {
   const isAdmin = auth?.role === 'admin'
 
   const [vendors, setVendors] = useState<Vendor[]>([])
+  const [lastRefreshedMs, setLastRefreshedMs] = useState(0)
+  const [catalogRefreshing, setCatalogRefreshing] = useState(false)
   const [integrations, setIntegrations] = useState<Integration[]>([])
   const [loading, setLoading] = useState(true)
   const [refreshing, setRefreshing] = useState(false)
@@ -124,6 +127,7 @@ export default function Integrations() {
       try {
         const [v, ints] = await Promise.all([fetchVendors(), fetchIntegrations()])
         setVendors(v.vendors)
+        setLastRefreshedMs(v.lastRefreshedAt ?? 0)
         setIntegrations(ints.integrations)
         setError('')
       } catch (err) {
@@ -264,6 +268,22 @@ export default function Integrations() {
     }
   }
 
+  /** Forces the vendor catalog discovery (#1697) and swaps in the response. */
+  const refreshCatalog = async () => {
+    if (catalogRefreshing) return
+    setCatalogRefreshing(true)
+    setError('')
+    try {
+      const v = await refreshVendors()
+      setVendors(v.vendors)
+      setLastRefreshedMs(v.lastRefreshedAt ?? 0)
+    } catch (err) {
+      setError(errMessage(err, t))
+    } finally {
+      setCatalogRefreshing(false)
+    }
+  }
+
   const copyToken = async () => {
     if (!token) return
     const ok = await copyToClipboard(token)
@@ -271,8 +291,8 @@ export default function Integrations() {
     window.setTimeout(() => setTokenCopied(false), 1500)
   }
 
-  /** "hace X min" (unidades i18n) o fecha corta para pushes muy antiguos. */
-  const lastPushLabel = (ms: number): string => {
+  /** "hace X min" (unidades i18n) o fecha corta para eventos muy antiguos. */
+  const agoLabel = (ms: number): string => {
     if (!ms || !Number.isFinite(ms) || ms <= 0) return t('integrations.never')
     const age = Date.now() - ms
     if (age < 0) return t('integrations.never')
@@ -351,7 +371,22 @@ export default function Integrations() {
               {slugInvalid && <span className="mt-1 block text-xs text-danger">{t('integrations.form.fieldSlugInvalid')}</span>}
             </label>
             <label className="block">
-              <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldVendor')}</span>
+              <span className="flex items-center justify-between gap-2">
+                <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldVendor')}</span>
+                {!isDemo && (
+                  <button
+                    type="button"
+                    onClick={() => void refreshCatalog()}
+                    disabled={catalogRefreshing}
+                    aria-label={t('integrations.catalog.refresh')}
+                    title={t('integrations.catalog.refresh')}
+                    className="inline-flex h-6 items-center gap-1 rounded-md border border-border px-1.5 text-caption font-medium text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:opacity-50"
+                  >
+                    <RefreshCw className={cn('h-3 w-3', catalogRefreshing && 'animate-spin')} strokeWidth={1.75} />
+                    {catalogRefreshing ? t('integrations.catalog.refreshing') : t('integrations.catalog.refresh')}
+                  </button>
+                )}
+              </span>
               <select
                 value={vendorId}
                 onChange={(e) => onVendorChange(e.target.value)}
@@ -365,6 +400,11 @@ export default function Integrations() {
                   </option>
                 ))}
               </select>
+              {!isDemo && lastRefreshedMs > 0 && (
+                <span className="mt-1 block text-caption text-text-muted">
+                  {t('integrations.catalog.updated', { time: agoLabel(lastRefreshedMs) })}
+                </span>
+              )}
             </label>
             <label className="block">
               <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldHost')}</span>
@@ -592,7 +632,7 @@ export default function Integrations() {
                     {t('integrations.meta.interval')}: {it.intervalS} s
                   </span>
                   <span>
-                    {t('integrations.meta.lastPush')}: {lastPushLabel(it.lastPushMs)}
+                    {t('integrations.meta.lastPush')}: {agoLabel(it.lastPushMs)}
                   </span>
                 </div>
                 {editing?.slug === it.slug && (

+ 9 - 3
server-go/cmd/netpulse/main.go

@@ -764,6 +764,11 @@ func run() error {
 	// netpulse (sin systemd). La raíz de datos vive bajo DATA_DIR/integrations.
 	integrationsMgr := rintegration.NewManager(filepath.Join(cfg.DataDir, "integrations"))
 
+	// Catálogo de vendors por descubrimiento (#1697): fetch de vendors.json
+	// del repo de integraciones con TTL y caché en kv, semilla embebida como
+	// respaldo offline.
+	vendorCatalog := rintegration.NewCatalog(dbHandle.DB)
+
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config:           cfg,
 		DB:               dbHandle,
@@ -795,9 +800,10 @@ func run() error {
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},
-		PollNow:      p.PollNow,
-		Started:      serverStarted,
-		Integrations: integrationsMgr,
+		PollNow:       p.PollNow,
+		Started:       serverStarted,
+		Integrations:  integrationsMgr,
+		VendorCatalog: vendorCatalog,
 	})
 
 	// Envolver el handler con GET /fingerprint (sin auth) si on-box.

+ 46 - 11
server-go/internal/httpapi/integrations.go

@@ -6,6 +6,7 @@
 package httpapi
 
 import (
+	"context"
 	"fmt"
 	"log"
 	"net/http"
@@ -51,6 +52,7 @@ type vendorView struct {
 // exigen rol admin salvo el GET de vendors (solo sesión).
 func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
 	mux.HandleFunc("GET /api/integrations/vendors", s.handleIntegrationsVendors)
+	mux.Handle("POST /api/integrations/vendors/refresh", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsVendorsRefresh)))
 	mux.Handle("GET /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsList)))
 	mux.Handle("POST /api/integrations", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationsCreate)))
 	mux.Handle("POST /api/integrations/{slug}/start", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStart)))
@@ -61,8 +63,41 @@ func (s *server) registerIntegrationRoutes(mux *http.ServeMux) {
 	mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
 }
 
-func (s *server) handleIntegrationsVendors(w http.ResponseWriter, _ *http.Request) {
-	vs := rintegration.Vendors()
+// vendorCatalogRefreshTimeout acota el fetch forzado del endpoint admin.
+const vendorCatalogRefreshTimeout = 15 * time.Second
+
+func (s *server) handleIntegrationsVendors(w http.ResponseWriter, r *http.Request) {
+	vs := s.vendorCatalog.Vendors(r.Context())
+	writeJSON(w, http.StatusOK, map[string]any{
+		"vendors":         vendorViews(vs),
+		"lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
+	})
+}
+
+// handleIntegrationsVendorsRefresh fuerza el descubrimiento del catálogo
+// (#1697): fetch inmediato, caché actualizada y catálogo devuelto en la
+// misma respuesta para que la UI no encadene un segundo GET. Un fallo de
+// fetch o de validación deja el catálogo anterior en su sitio (502).
+func (s *server) handleIntegrationsVendorsRefresh(w http.ResponseWriter, r *http.Request) {
+	if s.db == nil || s.vendorCatalog == nil {
+		writeError(w, http.StatusServiceUnavailable, "unavailable", "vendor catalog is not available without a database")
+		return
+	}
+	ctx, cancel := context.WithTimeout(r.Context(), vendorCatalogRefreshTimeout)
+	defer cancel()
+	if err := s.vendorCatalog.Refresh(ctx); err != nil {
+		writeError(w, http.StatusBadGateway, "refresh_failed", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{
+		"vendors":         vendorViews(s.vendorCatalog.Current()),
+		"lastRefreshedAt": s.vendorCatalog.LastRefreshedAtMs(),
+	})
+}
+
+// vendorViews es la vista HTTP del catálogo: mismos campos que servía el
+// manifiesto estático para no romper el contrato con la UI.
+func vendorViews(vs []rintegration.Vendor) []vendorView {
 	out := make([]vendorView, 0, len(vs))
 	for _, v := range vs {
 		out = append(out, vendorView{
@@ -70,7 +105,7 @@ func (s *server) handleIntegrationsVendors(w http.ResponseWriter, _ *http.Reques
 			TagPrefix: v.TagPrefix, Description: v.Description,
 		})
 	}
-	writeJSON(w, http.StatusOK, map[string]any{"vendors": out})
+	return out
 }
 
 func (s *server) integrationsStore() *rintegration.Store {
@@ -202,7 +237,7 @@ func (s *server) resumeIntegrations() {
 		if s.integrations.Running(row.Slug) {
 			continue
 		}
-		vendor, ok := rintegration.LookupVendor(row.Vendor)
+		vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
 		if !ok {
 			_ = store.SetState(row.Slug, "error", "unknown vendor "+row.Vendor)
 			log.Printf("[netpulse] aviso: integración %s con vendor desconocido %q al arrancar", row.Slug, row.Vendor)
@@ -249,7 +284,7 @@ func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request
 		writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
 		return
 	}
-	vendor, ok := rintegration.LookupVendor(body.Vendor)
+	vendor, ok := s.vendorCatalog.Lookup(body.Vendor)
 	if !ok {
 		writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
 		return
@@ -433,7 +468,7 @@ func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request)
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
 	if !ok {
 		writeError(w, http.StatusInternalServerError, "invalid_vendor")
 		return
@@ -475,7 +510,7 @@ func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
 	if !ok {
 		writeError(w, http.StatusInternalServerError, "invalid_vendor")
 		return
@@ -500,7 +535,7 @@ func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request)
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
 	if !ok {
 		writeError(w, http.StatusInternalServerError, "invalid_vendor")
 		return
@@ -535,7 +570,7 @@ func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request)
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
 	if !ok {
 		writeError(w, http.StatusInternalServerError, "invalid_vendor")
 		return
@@ -606,7 +641,7 @@ func (s *server) handleIntegrationEdit(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	vendor, ok := s.vendorCatalog.Lookup(row.Vendor)
 	if !ok {
 		writeError(w, http.StatusInternalServerError, "invalid_vendor")
 		return
@@ -744,7 +779,7 @@ func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request)
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
-	vendor, _ := rintegration.LookupVendor(row.Vendor)
+	vendor, _ := s.vendorCatalog.Lookup(row.Vendor)
 	if vendor.Mode == "local" {
 		if s.integrations != nil {
 			_ = s.integrations.Stop(slug)

+ 23 - 23
server-go/internal/httpapi/integrations_boot_test.go

@@ -32,6 +32,13 @@ import (
 // de construir el handler: las filas de router_integrations deben existir al
 // "arrancar" para que el resume del boot las vea.
 func makeIntegrationsTestServerSeeded(t *testing.T, seed func(d *db.DB, mgr *rintegration.Manager)) (*testServer, *rintegration.Manager) {
+	return makeIntegrationsTestServerFull(t, seed, nil)
+}
+
+// makeIntegrationsTestServerFull es la variante con catálogo de vendors
+// inyectable (#1697): catFn construye el VendorCatalog con la base ya abierta
+// (nil → fallback de NewHandler: semilla embebida sin red).
+func makeIntegrationsTestServerFull(t *testing.T, seed func(d *db.DB, mgr *rintegration.Manager), catFn func(d *db.DB) *rintegration.Catalog) (*testServer, *rintegration.Manager) {
 	t.Helper()
 	auth.SetTrustProxy(true)
 	t.Cleanup(func() { auth.SetTrustProxy(false) })
@@ -66,15 +73,20 @@ func makeIntegrationsTestServerSeeded(t *testing.T, seed func(d *db.DB, mgr *rin
 	if seed != nil {
 		seed(d, mgr)
 	}
+	var cat *rintegration.Catalog
+	if catFn != nil {
+		cat = catFn(d)
+	}
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
-		Started:      time.Now(),
-		TokenStore:   apitoken.NewStore(d, secret),
-		ConfigBackup: configBackup,
-		Orchestr:     orchestr.New(d),
-		Agents:       adapters.NewAgentRegistry(0),
-		ChannelPlan:  channelplan.NewStore(d.DB),
-		Integrations: mgr,
+		Started:       time.Now(),
+		TokenStore:    apitoken.NewStore(d, secret),
+		ConfigBackup:  configBackup,
+		Orchestr:      orchestr.New(d),
+		Agents:        adapters.NewAgentRegistry(0),
+		ChannelPlan:   channelplan.NewStore(d.DB),
+		Integrations:  mgr,
+		VendorCatalog: cat,
 	})
 	srv := httptest.NewServer(handler)
 	ts := &testServer{Server: srv, db: d, secret: secret}
@@ -162,10 +174,7 @@ func waitIntegrationState(t *testing.T, store *rintegration.Store, slug, state s
 // tiene binario queda en error sin tirar el arranque; la deshabilitada no se
 // toca; la de modo ssh deja de decir running (no verificada desde aquí).
 func TestIntegrationsResumeOnBoot(t *testing.T) {
-	v, ok := rintegration.LookupVendor("routeros")
-	if !ok {
-		t.Fatal("vendor routeros missing")
-	}
+	v := seedVendor(t, "routeros")
 	ts, mgr := makeIntegrationsTestServerSeeded(t, func(d *db.DB, mgr *rintegration.Manager) {
 		store := rintegration.NewStore(d.DB)
 		installFakePusher(t, mgr, "lab", v.Binary, "sleep 30")
@@ -234,10 +243,7 @@ func TestIntegrationsDeadChildFlipsToError(t *testing.T) {
 		{"killed", `kill -9 $$`, "signal: killed"},
 	} {
 		t.Run(tc.name, func(t *testing.T) {
-			v, ok := rintegration.LookupVendor("routeros")
-			if !ok {
-				t.Fatal("vendor routeros missing")
-			}
+			v := seedVendor(t, "routeros")
 			slug := "dead-" + tc.name
 			ts, mgr := makeIntegrationsTestServer(t)
 			store := rintegration.NewStore(ts.db.DB)
@@ -266,10 +272,7 @@ func TestIntegrationsDeadChildFlipsToError(t *testing.T) {
 // TestIntegrationsIntentionalStopDoesNotError: parar por API es un paro
 // intencional: la fila queda stopped y el callback de muerte no la marca error.
 func TestIntegrationsIntentionalStopDoesNotError(t *testing.T) {
-	v, ok := rintegration.LookupVendor("routeros")
-	if !ok {
-		t.Fatal("vendor routeros missing")
-	}
+	v := seedVendor(t, "routeros")
 	ts, mgr := makeIntegrationsTestServer(t)
 	store := rintegration.NewStore(ts.db.DB)
 	bin := installFakePusher(t, mgr, "manual", v.Binary, "sleep 30")
@@ -305,10 +308,7 @@ func TestIntegrationsIntentionalStopDoesNotError(t *testing.T) {
 // reinicio del servidor) y la devuelve a running; sin proceso, la fila no se
 // toca (el error sigue siendo error).
 func TestIntegrationsCheckReconcilesState(t *testing.T) {
-	v, ok := rintegration.LookupVendor("routeros")
-	if !ok {
-		t.Fatal("vendor routeros missing")
-	}
+	v := seedVendor(t, "routeros")
 	ts, mgr := makeIntegrationsTestServer(t)
 	store := rintegration.NewStore(ts.db.DB)
 	bin := installFakePusher(t, mgr, "verify", v.Binary, "sleep 30")

+ 158 - 0
server-go/internal/httpapi/integrations_catalog_test.go

@@ -0,0 +1,158 @@
+// integrations_catalog_test.go - #1697: GET /api/integrations/vendors sirve el
+// catálogo por descubrimiento (con lastRefreshedAt) y degrada a la semilla sin
+// red; POST /api/integrations/vendors/refresh (admin) fuerza el fetch y
+// devuelve el catálogo actualizado. Sin red: fetch inyectado.
+package httpapi_test
+
+import (
+	"errors"
+	"net/http"
+	"strings"
+	"sync/atomic"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+)
+
+// seedVendor devuelve un vendor de la semilla embebida (helper de tests).
+func seedVendor(t *testing.T, id string) rintegration.Vendor {
+	t.Helper()
+	v, ok := rintegration.NewCatalog(nil).Lookup(id)
+	if !ok {
+		t.Fatalf("vendor %q missing from the embedded seed", id)
+	}
+	return v
+}
+
+func post(t *testing.T, base, path, cookie, body string) *http.Response {
+	t.Helper()
+	req, _ := http.NewRequest("POST", base+path, strings.NewReader(body))
+	if cookie != "" {
+		req.Header.Set("Cookie", "session="+cookie)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("POST %s: %v", path, err)
+	}
+	return res
+}
+
+const labVendorCatalog = `{"vendors":[{"id":"labvendor","mode":"local","arches":["amd64"],"tagPrefix":"lab/v","binary":"lab-pusher","target":"lab/cmd/lab-pusher","description":"Lab vendor"}]}`
+
+// TestVendorsEndpointServesSeedAndDegradesOffline: con el fetch roto, el GET
+// sirve la semilla embebida (nunca una lista vacía), lastRefreshedAt se
+// mantiene a cero y el intento fallido no tira la respuesta.
+func TestVendorsEndpointServesSeedAndDegradesOffline(t *testing.T) {
+	var calls atomic.Int32
+	ts, _ := makeIntegrationsTestServerFull(t, nil, func(d *db.DB) *rintegration.Catalog {
+		c := rintegration.NewCatalog(d.DB)
+		c.FetchOverride = func(string) ([]byte, error) {
+			calls.Add(1)
+			return nil, errors.New("dial tcp: connection refused")
+		}
+		return c
+	})
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := get(t, ts.URL, "/api/integrations/vendors", cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET vendors: status %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	rawVendors, ok := body["vendors"].([]any)
+	if !ok {
+		t.Fatalf("vendors missing: %v", body)
+	}
+	if len(rawVendors) != 4 {
+		t.Fatalf("seed must be served when offline: %d vendors (%v)", len(rawVendors), rawVendors)
+	}
+	if got := body["lastRefreshedAt"].(float64); got != 0 {
+		t.Fatalf("lastRefreshedAt = %v, want 0 without a successful fetch", got)
+	}
+	if calls.Load() != 1 {
+		t.Fatalf("the endpoint must attempt the discovery once (calls %d)", calls.Load())
+	}
+}
+
+// TestVendorsRefreshEndpointUpdatesCatalog: el refresco admin fuerza el fetch
+// y devuelve el catálogo nuevo con lastRefreshedAt actualizado.
+func TestVendorsRefreshEndpointUpdatesCatalog(t *testing.T) {
+	var calls atomic.Int32
+	ts, _ := makeIntegrationsTestServerFull(t, nil, func(d *db.DB) *rintegration.Catalog {
+		c := rintegration.NewCatalog(d.DB)
+		c.FetchOverride = func(string) ([]byte, error) {
+			if calls.Add(1) == 1 {
+				// Primer intento (GET): roto, se sirve la semilla.
+				return nil, errors.New("connection refused")
+			}
+			return []byte(labVendorCatalog), nil
+		}
+		return c
+	})
+
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	// Estado inicial: el GET de arranque falla y sirve la semilla.
+	res0 := get(t, ts.URL, "/api/integrations/vendors", cookie)
+	body0 := readJSON(t, res0)
+	if rawVendors0, ok := body0["vendors"].([]any); !ok || len(rawVendors0) != 4 {
+		t.Fatalf("seed must be served while the fetch fails: %v", body0)
+	}
+
+	res := post(t, ts.URL, "/api/integrations/vendors/refresh", cookie, "")
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("POST refresh: status %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	rawVendors, ok := body["vendors"].([]any)
+	if !ok || len(rawVendors) != 1 {
+		t.Fatalf("refreshed catalog = %v", body)
+	}
+	first, _ := rawVendors[0].(map[string]any)
+	if first["id"] != "labvendor" || first["tagPrefix"] != "lab/v" {
+		t.Fatalf("refreshed vendor = %v", first)
+	}
+	if got := body["lastRefreshedAt"].(float64); got <= 0 {
+		t.Fatalf("lastRefreshedAt = %v, want > 0 after a successful refresh", got)
+	}
+
+	// El GET posterior sirve el catálogo refrescado desde la caché.
+	res2 := get(t, ts.URL, "/api/integrations/vendors", cookie)
+	body2 := readJSON(t, res2)
+	if rawVendors2, ok := body2["vendors"].([]any); !ok || len(rawVendors2) != 1 {
+		t.Fatalf("GET after refresh must serve the cached catalog: %v", body2)
+	}
+}
+
+// TestVendorsRefreshRequiresSession: el refresco del catálogo es admin-only.
+func TestVendorsRefreshRequiresSession(t *testing.T) {
+	ts, _ := makeIntegrationsTestServerFull(t, nil, func(d *db.DB) *rintegration.Catalog {
+		return rintegration.NewCatalog(d.DB)
+	})
+	res := post(t, ts.URL, "/api/integrations/vendors/refresh", "", "")
+	defer res.Body.Close()
+	if res.StatusCode != http.StatusUnauthorized {
+		t.Fatalf("unauthenticated refresh: status %d, want 401", res.StatusCode)
+	}
+}
+
+// TestVendorsFallbackCatalogHasNoNetwork: el catálogo por defecto de
+// NewHandler (sin Deps.VendorCatalog) sirve la semilla sin intentar fetch
+// alguno: los tests y el demo no tocan la red.
+func TestVendorsFallbackCatalogHasNoNetwork(t *testing.T) {
+	ts, _ := makeIntegrationsTestServer(t)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+	res := get(t, ts.URL, "/api/integrations/vendors", cookie)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("GET vendors: status %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	rawVendors, ok := body["vendors"].([]any)
+	if !ok || len(rawVendors) != 4 {
+		t.Fatalf("fallback catalog must serve the seed: %v", body)
+	}
+	if got := body["lastRefreshedAt"].(float64); got != 0 {
+		t.Fatalf("fallback catalog must never fetch: lastRefreshedAt = %v", got)
+	}
+}

+ 1 - 1
server-go/internal/httpapi/integrations_edit_test.go

@@ -50,7 +50,7 @@ func TestSSHEnvReadScriptTargetsEnvFile(t *testing.T) {
 
 func TestPusherEnvIntervalMatchesEditFormat(t *testing.T) {
 	s := &server{}
-	v, _ := rintegration.LookupVendor("routeros")
+	v := seedVendor(t, "routeros")
 	env := s.pusherEnv(v, rintegration.Row{Slug: "chr-lab", Host: "10.0.0.1", Username: "u", IntervalS: 60}, "pw", "https://np", "tok")
 	if env["NETPULSE_INTERVAL"] != "60s" {
 		t.Fatalf("interval = %q, want 60s", env["NETPULSE_INTERVAL"])

+ 12 - 8
server-go/internal/httpapi/integrations_env_test.go

@@ -6,12 +6,19 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/rintegration"
 )
 
-func TestPusherEnvWritesIntervalWithUnit(t *testing.T) {
-	s := &server{}
-	v, ok := rintegration.LookupVendor("routeros")
+// seedVendor devuelve un vendor de la semilla embebida del catálogo (#1697).
+func seedVendor(t *testing.T, id string) rintegration.Vendor {
+	t.Helper()
+	v, ok := rintegration.NewCatalog(nil).Lookup(id)
 	if !ok {
-		t.Fatal("routeros vendor missing")
+		t.Fatalf("vendor %q missing from the embedded seed", id)
 	}
+	return v
+}
+
+func TestPusherEnvWritesIntervalWithUnit(t *testing.T) {
+	s := &server{}
+	v := seedVendor(t, "routeros")
 	row := rintegration.Row{Slug: "lab", Host: "10.0.0.1", Username: "u", IntervalS: 30}
 	env := s.pusherEnv(v, row, "secret", "https://np.example", "tok")
 	if got := env["NETPULSE_INTERVAL"]; got != "30s" {
@@ -21,10 +28,7 @@ func TestPusherEnvWritesIntervalWithUnit(t *testing.T) {
 		t.Fatalf("ROUTEROS_HOST = %q, want 10.0.0.1", got)
 	}
 
-	asus, ok := rintegration.LookupVendor("asuswrt")
-	if !ok {
-		t.Fatal("asuswrt vendor missing")
-	}
+	asus := seedVendor(t, "asuswrt")
 	sshEnv := s.pusherEnv(asus, row, "secret", "https://np.example", "tok")
 	if got := sshEnv["ASUSWRT_HOST"]; got != "127.0.0.1" {
 		t.Fatalf("ASUSWRT_HOST = %q, want 127.0.0.1", got)

+ 1 - 5
server-go/internal/httpapi/integrations_merlin_test.go

@@ -11,11 +11,7 @@ import (
 // one with Init "merlin" (#1681).
 func merlinVendor(t *testing.T) rintegration.Vendor {
 	t.Helper()
-	v, ok := rintegration.LookupVendor("asuswrt")
-	if !ok {
-		t.Fatal("asuswrt vendor missing")
-	}
-	return v
+	return seedVendor(t, "asuswrt")
 }
 
 func merlinTestEnv() map[string]string {

+ 12 - 0
server-go/internal/httpapi/server.go

@@ -147,6 +147,10 @@ type Deps struct {
 	// Integrations: supervisor de pushers externos (#1674). nil → sin
 	// arranque/parada de procesos en modo local (rutas responden 503).
 	Integrations *rintegration.Manager
+	// VendorCatalog: descubrimiento del catálogo de vendors (#1697). nil →
+	// catálogo de semilla embebida sin red ni persistencia (demo y tests
+	// que no ejercitan el descubrimiento).
+	VendorCatalog *rintegration.Catalog
 }
 
 type server struct {
@@ -238,6 +242,10 @@ type server struct {
 	// Integrations: supervisor de pushers externos (#1674).
 	integrations *rintegration.Manager
 
+	// VendorCatalog: descubrimiento del catálogo de vendors (#1697). Sin
+	// fetch ni kv si nadie aporta uno (demo): sirve la semilla embebida.
+	vendorCatalog *rintegration.Catalog
+
 	// CollectorReader: lector read-only de metrics.db del sidecar (#328).
 	collectorReader *collectorreader.Reader
 
@@ -305,6 +313,10 @@ func NewHandler(d Deps) http.Handler {
 		alertEmitter:    d.AlertEmitter,
 		mqtt:            d.MQTT,
 		integrations:    d.Integrations,
+		vendorCatalog:   d.VendorCatalog,
+	}
+	if s.vendorCatalog == nil {
+		s.vendorCatalog = rintegration.NewCatalog(nil)
 	}
 	if s.imageResolver == nil {
 		s.imageResolver = firmware.NewImageResolver()

+ 386 - 0
server-go/internal/rintegration/catalog.go

@@ -0,0 +1,386 @@
+// catalog.go - vendor catalog discovery (#1697). The list of supported
+// integrations is no longer compiled into the binary: it is fetched from
+// vendors.json in gnacho/netpulse-integrations (the same repository that
+// publishes the releases), cached in the kv table with a TTL, and served with
+// an embedded seed so a fresh offline install still has something to show.
+// A failed fetch or a malformed catalog never empties the vendor list: the
+// previous cache (or the seed) keeps being served.
+package rintegration
+
+import (
+	"context"
+	"database/sql"
+	_ "embed"
+	"encoding/json"
+	"fmt"
+	"io"
+	"log"
+	"net/http"
+	"regexp"
+	"sync"
+	"time"
+)
+
+const (
+	// CatalogRepo is the GitHub repository that publishes the vendor catalog
+	// and every integration release.
+	CatalogRepo = "gnacho/netpulse-integrations"
+	// rawCatalogURL is the raw URL of the catalog on the main branch.
+	rawCatalogURL = "https://raw.githubusercontent.com/" + CatalogRepo + "/main/vendors.json"
+	// catalogTTL is how long a fetched catalog is considered fresh. The
+	// issue leaves the value open; 24h keeps GitHub raw traffic negligible
+	// while new vendors still show up the same day they are published.
+	catalogTTL = 24 * time.Hour
+	// catalogFetchTimeout bounds every catalog fetch attempt.
+	catalogFetchTimeout = 10 * time.Second
+	// catalogRetryCooldown is the minimum wait between fetch attempts after
+	// a failure, so an offline instance does not hammer GitHub raw on every
+	// page view.
+	catalogRetryCooldown = 10 * time.Minute
+	// catalogMaxBytes caps the catalog body (it is a small JSON file).
+	catalogMaxBytes = 1 << 20
+	// kvCatalogKey persists the last fetched catalog plus its timestamp.
+	kvCatalogKey = "integrations.vendor_catalog"
+)
+
+//go:embed vendors_seed.json
+var seedJSON []byte
+
+// seedCatalog is the embedded copy of the current vendors.json, generated
+// from netpulse-integrations main. Regenerate it from that file when the
+// upstream catalog gains the first vendor that must work out of the box.
+var seedCatalog = parseSeed()
+
+func parseSeed() []Vendor {
+	var f catalogFile
+	if err := json.Unmarshal(seedJSON, &f); err != nil {
+		log.Printf("[netpulse] aviso: la semilla del catálogo de vendors no parsea: %v", err)
+		return nil
+	}
+	return validVendors(f.Vendors)
+}
+
+// catalogEntry mirrors the vendors.json schema (netpulse-integrations PR #24):
+// id, mode, arches, tagPrefix, binary, target, description.
+type catalogEntry struct {
+	ID          string   `json:"id"`
+	Mode        string   `json:"mode"`
+	Arches      []string `json:"arches"`
+	TagPrefix   string   `json:"tagPrefix"`
+	Binary      string   `json:"binary"`
+	Target      string   `json:"target"`
+	Description string   `json:"description"`
+}
+
+type catalogFile struct {
+	Vendors []catalogEntry `json:"vendors"`
+}
+
+// assetPrefixes holds execution knowledge the catalog schema does not carry:
+// vendor ids whose release asset name prefix differs from the vendor id. The
+// integrations release workflow names assets "<name>_<version>_linux_<arch>.
+// tar.gz"; bbox ships the shared integrations-supervisor binary instead of a
+// per-vendor one. A vendor following the default convention needs no entry.
+var assetPrefixes = map[string]string{
+	"bbox": "integrations-supervisor",
+}
+
+// initSystems holds the on-router layout of ssh vendors (how to install, not
+// who exists). Empty means procd (OpenWrt); asuswrt ships a Merlin layout
+// (#1681).
+var initSystems = map[string]string{
+	"asuswrt": "merlin",
+}
+
+var catalogIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
+
+// validVendors validates catalog entries and converts them to Vendors.
+// Invalid entries are dropped individually (a bad vendor must never break the
+// rest of the catalog); an empty result means the whole catalog is unusable.
+func validVendors(entries []catalogEntry) []Vendor {
+	seen := map[string]bool{}
+	out := make([]Vendor, 0, len(entries))
+	for _, e := range entries {
+		v, ok := vendorFromEntry(e, seen)
+		if !ok {
+			log.Printf("[netpulse] aviso: entrada del catálogo de vendors descartada por no válida: id=%q mode=%q", e.ID, e.Mode)
+			continue
+		}
+		out = append(out, v)
+	}
+	return out
+}
+
+func vendorFromEntry(e catalogEntry, seen map[string]bool) (Vendor, bool) {
+	if !catalogIDRe.MatchString(e.ID) || seen[e.ID] {
+		return Vendor{}, false
+	}
+	if e.Mode != "local" && e.Mode != "ssh" {
+		return Vendor{}, false
+	}
+	if e.TagPrefix == "" || e.Binary == "" || len(e.Arches) == 0 {
+		return Vendor{}, false
+	}
+	for _, a := range e.Arches {
+		if a == "" {
+			return Vendor{}, false
+		}
+	}
+	seen[e.ID] = true
+	prefix := e.ID
+	if p := assetPrefixes[e.ID]; p != "" {
+		prefix = p
+	}
+	return Vendor{
+		ID:          e.ID,
+		Mode:        e.Mode,
+		Repo:        CatalogRepo,
+		TagPrefix:   e.TagPrefix,
+		AssetTmpl:   prefix + "_{version}_linux_{arch}.tar.gz",
+		Arches:      append([]string(nil), e.Arches...),
+		Binary:      e.Binary,
+		Init:        initSystems[e.ID],
+		Description: e.Description,
+	}, true
+}
+
+// kvCatalog is the persisted form of the last fetched catalog: the raw body
+// (so future schema evolution re-validates from the source format) plus the
+// timestamp of the successful fetch.
+type kvCatalog struct {
+	FetchedAtMs int64  `json:"fetchedAtMs"`
+	Body        string `json:"body"`
+}
+
+// Catalog discovers and serves the vendor catalog. The zero-value knobs
+// (Client, RawURL, Now, FetchOverride) mirror the Fetcher style: unset fields
+// get production defaults; tests set them to stay offline. A Catalog built
+// without a db (demo, nil fallback in tests) never fetches: it serves the
+// embedded seed only.
+type Catalog struct {
+	Client        *http.Client // default: 10s timeout
+	RawURL        string       // default: rawCatalogURL
+	Now           func() time.Time
+	FetchOverride func(url string) ([]byte, error) // test injection; nil = real fetch
+
+	db *sql.DB
+
+	mu         sync.Mutex
+	loaded     bool
+	vendors    []Vendor
+	fetchedAt  time.Time // zero = never fetched from the network
+	retryAfter time.Time // cooldown after a failed fetch
+	lastErr    string
+}
+
+// NewCatalog builds a catalog. A nil db keeps it in memory (seed only, no
+// network); a real db enables the kv cache and the TTL auto-fetch.
+func NewCatalog(db *sql.DB) *Catalog {
+	return &Catalog{db: db}
+}
+
+func (c *Catalog) client() *http.Client {
+	if c.Client != nil {
+		return c.Client
+	}
+	return &http.Client{Timeout: catalogFetchTimeout}
+}
+
+func (c *Catalog) url() string {
+	if c.RawURL != "" {
+		return c.RawURL
+	}
+	return rawCatalogURL
+}
+
+func (c *Catalog) now() time.Time {
+	if c.Now != nil {
+		return c.Now()
+	}
+	return time.Now()
+}
+
+// Current returns the last known catalog (cache or seed) without any network
+// access. Use it when freshness is not worth a fetch.
+func (c *Catalog) Current() []Vendor {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	c.ensureLoadedLocked()
+	return append([]Vendor(nil), c.vendors...)
+}
+
+// Lookup resolves one vendor from the last known catalog (cache or seed),
+// with no network access, so create/edit/start/stop/update/check keep working
+// offline exactly as they did against the compiled manifest.
+func (c *Catalog) Lookup(id string) (Vendor, bool) {
+	for _, v := range c.Current() {
+		if v.ID == id {
+			return v, true
+		}
+	}
+	return Vendor{}, false
+}
+
+// LastRefreshedAt reports the last successful fetch from the network (zero
+// when only the seed has ever been served).
+func (c *Catalog) LastRefreshedAt() time.Time {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	c.ensureLoadedLocked()
+	return c.fetchedAt
+}
+
+// LastRefreshedAtMs is LastRefreshedAt as unix milliseconds, 0 when the seed
+// has never been replaced by a successful fetch. It is the shape the API and
+// the UI use for timestamps.
+func (c *Catalog) LastRefreshedAtMs() int64 {
+	t := c.LastRefreshedAt()
+	if t.IsZero() {
+		return 0
+	}
+	return t.UnixMilli()
+}
+
+// LastError reports the last fetch or validation error, for diagnostics.
+func (c *Catalog) LastError() string {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	return c.lastErr
+}
+
+// Vendors serves the current catalog, refreshing it first when the TTL has
+// expired (or nothing was ever fetched). The fetch is best effort: on failure
+// the previously known catalog (or the seed) is served, never an empty list.
+func (c *Catalog) Vendors(ctx context.Context) []Vendor {
+	c.mu.Lock()
+	c.ensureLoadedLocked()
+	stale := c.db != nil && (c.fetchedAt.IsZero() || c.now().Sub(c.fetchedAt) >= catalogTTL)
+	cooldown := c.now().Before(c.retryAfter)
+	c.mu.Unlock()
+	if stale && !cooldown {
+		// Best effort: Refresh keeps the old catalog on failure.
+		_ = c.Refresh(ctx)
+	}
+	return c.Current()
+}
+
+// Refresh forces a fetch from the network regardless of the TTL, validates
+// the catalog and persists it. On failure the previous catalog stays in
+// place, a cooldown is stamped and the error is returned.
+func (c *Catalog) Refresh(ctx context.Context) error {
+	body, err := c.fetchRaw(ctx)
+	if err == nil {
+		var f catalogFile
+		if err = json.Unmarshal(body, &f); err == nil {
+			vs := validVendors(f.Vendors)
+			if len(vs) == 0 {
+				err = fmt.Errorf("vendor catalog: no valid entries")
+			} else {
+				now := c.now()
+				c.mu.Lock()
+				c.vendors = vs
+				c.fetchedAt = now
+				c.lastErr = ""
+				c.mu.Unlock()
+				c.persist(now, body)
+				return nil
+			}
+		}
+	}
+	c.mu.Lock()
+	c.retryAfter = c.now().Add(catalogRetryCooldown)
+	c.lastErr = err.Error()
+	c.mu.Unlock()
+	log.Printf("[netpulse] aviso: no se pudo refrescar el catálogo de vendors (%v); se sigue sirviendo el último conocido", err)
+	return err
+}
+
+func (c *Catalog) fetchRaw(ctx context.Context) ([]byte, error) {
+	if c.FetchOverride != nil {
+		return c.FetchOverride(c.url())
+	}
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.url(), nil)
+	if err != nil {
+		return nil, err
+	}
+	req.Header.Set("User-Agent", userAgent)
+	resp, err := c.client().Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return nil, fmt.Errorf("vendor catalog: %s", resp.Status)
+	}
+	body, err := io.ReadAll(io.LimitReader(resp.Body, catalogMaxBytes))
+	if err != nil {
+		return nil, err
+	}
+	return body, nil
+}
+
+// persist stores the raw catalog and its timestamp in kv. Failures are logged
+// and swallowed: the in-memory catalog already serves this process, and the
+// next successful fetch will persist again.
+func (c *Catalog) persist(fetchedAt time.Time, body []byte) {
+	if c.db == nil {
+		return
+	}
+	raw, err := json.Marshal(kvCatalog{FetchedAtMs: fetchedAt.UnixMilli(), Body: string(body)})
+	if err != nil {
+		log.Printf("[netpulse] aviso: catálogo de vendors no serializable: %v", err)
+		return
+	}
+	if err := kvSet(c.db, kvCatalogKey, string(raw)); err != nil {
+		log.Printf("[netpulse] aviso: no se pudo persistir el catálogo de vendors: %v", err)
+	}
+}
+
+// ensureLoadedLocked loads the kv cache on first use, falling back to the
+// embedded seed. Any corrupt or empty cache silently degrades to the seed.
+func (c *Catalog) ensureLoadedLocked() {
+	if c.loaded {
+		return
+	}
+	c.loaded = true
+	c.vendors = seedCatalog
+	if c.db == nil {
+		return
+	}
+	raw, ok := kvGet(c.db, kvCatalogKey)
+	if !ok {
+		return
+	}
+	var w kvCatalog
+	if err := json.Unmarshal([]byte(raw), &w); err != nil || w.Body == "" {
+		log.Printf("[netpulse] aviso: caché del catálogo de vendors corrupta, se usa la semilla")
+		return
+	}
+	var f catalogFile
+	if err := json.Unmarshal([]byte(w.Body), &f); err != nil {
+		log.Printf("[netpulse] aviso: caché del catálogo de vendors no parsea, se usa la semilla")
+		return
+	}
+	vs := validVendors(f.Vendors)
+	if len(vs) == 0 {
+		return
+	}
+	c.vendors = vs
+	if w.FetchedAtMs > 0 {
+		c.fetchedAt = time.UnixMilli(w.FetchedAtMs)
+	}
+}
+
+func kvGet(d *sql.DB, key string) (string, bool) {
+	var val string
+	err := d.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&val)
+	if err != nil {
+		return "", false
+	}
+	return val, true
+}
+
+func kvSet(d *sql.DB, key, val string) error {
+	_, err := d.Exec("INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", key, val)
+	return err
+}

+ 363 - 0
server-go/internal/rintegration/catalog_test.go

@@ -0,0 +1,363 @@
+// catalog_test.go - #1697: descubrimiento del catálogo de vendors. Todos los
+// tests corren sin red: el fetch se inyecta con FetchOverride y el reloj con
+// Catalog.Now.
+package rintegration
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// seedVendor devuelve un vendor de la semilla embebida (helper de tests).
+func seedVendor(t *testing.T, id string) Vendor {
+	t.Helper()
+	v, ok := (&Catalog{}).Lookup(id)
+	if !ok {
+		t.Fatalf("vendor %q missing from the embedded seed", id)
+	}
+	return v
+}
+
+// fakeClock es un reloj inyectable para probar el TTL sin esperar.
+type fakeClock struct {
+	t time.Time
+}
+
+func (c *fakeClock) Now() time.Time { return c.t }
+func (c *fakeClock) Add(d time.Duration) {
+	c.t = c.t.Add(d)
+}
+
+// overrideOf devuelve un FetchOverride que sirve los cuerpos en orden y
+// cuenta las llamadas; al agotarse repite el último.
+func overrideOf(t *testing.T, calls *atomic.Int32, bodies ...string) func(string) ([]byte, error) {
+	t.Helper()
+	return func(string) ([]byte, error) {
+		n := int(calls.Add(1)) - 1
+		if n >= len(bodies) {
+			n = len(bodies) - 1
+		}
+		return []byte(bodies[n]), nil
+	}
+}
+
+func failingOverride(calls *atomic.Int32) func(string) ([]byte, error) {
+	return func(string) ([]byte, error) {
+		calls.Add(1)
+		return nil, errors.New("dial tcp: connection refused")
+	}
+}
+
+const labVendorA = `{"vendors":[{"id":"labvendor","mode":"local","arches":["amd64"],"tagPrefix":"lab/v","binary":"lab-pusher","target":"lab/cmd/lab-pusher","description":"Lab vendor"}]}`
+
+const labVendorB = `{"vendors":[{"id":"labvendor","mode":"local","arches":["amd64","arm64"],"tagPrefix":"lab/v","binary":"lab-pusher","target":"lab/cmd/lab-pusher","description":"Lab vendor with two arches"}]}`
+
+func newTestCatalogDB(t *testing.T) *db.DB {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	return d
+}
+
+// TestSeedCatalogServesCurrentVendors: la semilla embebida (generada del
+// vendors.json real, con el campo target) cubre los cuatro vendors
+// publicados, y la resolución deriva Repo/AssetTmpl/Init que el schema no
+// lleva: bbox usa el prefijo del binario compartido y asuswrt es merlin.
+func TestSeedCatalogServesCurrentVendors(t *testing.T) {
+	want := []struct {
+		id      string
+		mode    string
+		arches  string
+		prefix  string
+		binary  string
+		init    string
+		version string
+		arch    string
+		asset   string
+	}{
+		{"routeros", "local", "[amd64]", "routeros/v", "routeros-pusher", "procd", "1.2.3", "amd64", "routeros_1.2.3_linux_amd64.tar.gz"},
+		{"asuswrt", "ssh", "[arm64]", "asuswrt/v", "asuswrt-pusher", "merlin", "1.0.0", "arm64", "asuswrt_1.0.0_linux_arm64.tar.gz"},
+		{"bbox", "local", "[amd64 arm64]", "bbox/v", "netpulse-integrations", "procd", "0.1.0", "amd64", "integrations-supervisor_0.1.0_linux_amd64.tar.gz"},
+		{"unifi", "local", "[amd64]", "unifi/v", "unifi-pusher", "procd", "1.0.0", "amd64", "unifi_1.0.0_linux_amd64.tar.gz"},
+	}
+	c := NewCatalog(nil)
+	if got := len(c.Current()); got != len(want) {
+		t.Fatalf("seed serves %d vendors, want %d", got, len(want))
+	}
+	for _, w := range want {
+		v, ok := c.Lookup(w.id)
+		if !ok {
+			t.Fatalf("seed vendor %q missing", w.id)
+		}
+		if v.Mode != w.mode || v.TagPrefix != w.prefix || v.Binary != w.binary {
+			t.Fatalf("%s: %+v", w.id, v)
+		}
+		if fmt.Sprint(v.Arches) != w.arches {
+			t.Fatalf("%s arches = %v, want %s", w.id, v.Arches, w.arches)
+		}
+		if got := v.InitSystem(); got != w.init {
+			t.Fatalf("%s init = %q, want %q", w.id, got, w.init)
+		}
+		if v.Repo != CatalogRepo {
+			t.Fatalf("%s repo = %q, want %q", w.id, v.Repo, CatalogRepo)
+		}
+		if got := v.AssetName(w.version, w.arch); got != w.asset {
+			t.Fatalf("%s asset = %q, want %q", w.id, got, w.asset)
+		}
+	}
+	if _, ok := c.Lookup("nope"); ok {
+		t.Fatal("unknown vendor must not resolve")
+	}
+}
+
+// TestCatalogServesSeedWithoutNetwork: un catálogo sin base de datos (demo,
+// fallback de tests) no intenta fetch nunca y sirve la semilla.
+func TestCatalogServesSeedWithoutNetwork(t *testing.T) {
+	c := NewCatalog(nil)
+	c.FetchOverride = func(url string) ([]byte, error) {
+		t.Fatalf("fetch must not be attempted without a db (url %s)", url)
+		return nil, nil
+	}
+	vs := c.Vendors(context.Background())
+	if len(vs) != 4 {
+		t.Fatalf("seed vendors = %d, want 4", len(vs))
+	}
+	if !c.LastRefreshedAt().IsZero() {
+		t.Fatal("seed-only catalog must have zero lastRefreshedAt")
+	}
+}
+
+// TestCatalogFetchPersistsAndReloads: el catálogo descargado se sirve, se
+// persiste en kv y una segunda apertura sobre la misma base lo recupera sin
+// tocar la red.
+func TestCatalogFetchPersistsAndReloads(t *testing.T) {
+	d := newTestCatalogDB(t)
+	clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
+	var calls atomic.Int32
+
+	c := NewCatalog(d.DB)
+	c.Now = clock.Now
+	c.FetchOverride = overrideOf(t, &calls, labVendorA)
+	vs := c.Vendors(context.Background())
+	if len(vs) != 1 || vs[0].ID != "labvendor" {
+		t.Fatalf("fetched catalog = %+v", vs)
+	}
+	if calls.Load() != 1 {
+		t.Fatalf("fetch calls = %d, want 1", calls.Load())
+	}
+	if !c.LastRefreshedAt().Equal(clock.t) {
+		t.Fatalf("lastRefreshedAt = %v, want %v", c.LastRefreshedAt(), clock.t)
+	}
+	if _, ok := kvGet(d.DB, kvCatalogKey); !ok {
+		t.Fatal("catalog not persisted in kv")
+	}
+
+	// Reapertura sobre la misma base: sin red, desde kv.
+	c2 := NewCatalog(d.DB)
+	c2.Now = clock.Now
+	c2.FetchOverride = func(url string) ([]byte, error) {
+		t.Fatalf("reopened catalog must serve from kv without fetching (url %s)", url)
+		return nil, nil
+	}
+	got, ok := c2.Lookup("labvendor")
+	if !ok || got.Binary != "lab-pusher" {
+		t.Fatalf("reloaded vendor = %+v ok=%v", got, ok)
+	}
+	if !c2.LastRefreshedAt().Equal(clock.t) {
+		t.Fatalf("reloaded lastRefreshedAt = %v, want %v", c2.LastRefreshedAt(), clock.t)
+	}
+}
+
+// TestCatalogTTLExpiredRefetches: dentro del TTL no hay segunda descarga;
+// pasado el TTL la siguiente lectura refresca.
+func TestCatalogTTLExpiredRefetches(t *testing.T) {
+	d := newTestCatalogDB(t)
+	clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
+	var calls atomic.Int32
+
+	c := NewCatalog(d.DB)
+	c.Now = clock.Now
+	c.FetchOverride = overrideOf(t, &calls, labVendorA, labVendorB)
+
+	if vs := c.Vendors(context.Background()); len(vs[0].Arches) != 1 {
+		t.Fatalf("first serve should be body A: %+v", vs)
+	}
+	clock.Add(catalogTTL - time.Minute)
+	if vs := c.Vendors(context.Background()); len(vs[0].Arches) != 1 {
+		t.Fatalf("within TTL the cache must still be served: %+v", vs)
+	}
+	if calls.Load() != 1 {
+		t.Fatalf("fetch calls within TTL = %d, want 1", calls.Load())
+	}
+	clock.Add(2 * time.Minute)
+	vs := c.Vendors(context.Background())
+	if calls.Load() != 2 {
+		t.Fatalf("fetch calls after TTL = %d, want 2", calls.Load())
+	}
+	if len(vs[0].Arches) != 2 {
+		t.Fatalf("after TTL the refreshed catalog must be served: %+v", vs)
+	}
+}
+
+// TestCatalogFetchFailsKeepsCache: con caché previa, un fetch fallido sirve
+// la caché vieja, no cambia lastRefreshedAt y no reintenta dentro del
+// cooldown.
+func TestCatalogFetchFailsKeepsCache(t *testing.T) {
+	d := newTestCatalogDB(t)
+	clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
+	var calls atomic.Int32
+
+	c := NewCatalog(d.DB)
+	c.Now = clock.Now
+	c.FetchOverride = overrideOf(t, &calls, labVendorA)
+	if vs := c.Vendors(context.Background()); len(vs) != 1 {
+		t.Fatalf("setup fetch failed: %+v", vs)
+	}
+	firstRefresh := c.LastRefreshedAt()
+
+	clock.Add(catalogTTL + time.Hour)
+	c.FetchOverride = failingOverride(&calls)
+	vs := c.Vendors(context.Background())
+	if len(vs) != 1 || vs[0].ID != "labvendor" {
+		t.Fatalf("stale cache must be served after a failed fetch: %+v", vs)
+	}
+	if calls.Load() != 2 {
+		t.Fatalf("fetch calls = %d, want 2 (setup + failed attempt)", calls.Load())
+	}
+	if !c.LastRefreshedAt().Equal(firstRefresh) {
+		t.Fatalf("lastRefreshedAt changed on failure: %v", c.LastRefreshedAt())
+	}
+
+	// Cooldown: la siguiente lectura no reintenta.
+	if vs := c.Vendors(context.Background()); len(vs) != 1 {
+		t.Fatalf("cache must survive: %+v", vs)
+	}
+	if calls.Load() != 2 {
+		t.Fatalf("retry happened within the cooldown (%d calls)", calls.Load())
+	}
+	if c.LastError() == "" {
+		t.Fatal("last error must be recorded for diagnostics")
+	}
+}
+
+// TestCatalogFetchFailsNoCacheServesSeed: sin caché y sin red, la semilla se
+// sirve sin error y la lista nunca queda vacía.
+func TestCatalogFetchFailsNoCacheServesSeed(t *testing.T) {
+	d := newTestCatalogDB(t)
+	var calls atomic.Int32
+	c := NewCatalog(d.DB)
+	c.FetchOverride = failingOverride(&calls)
+	vs := c.Vendors(context.Background())
+	if len(vs) != 4 {
+		t.Fatalf("seed must be served when the fetch fails without cache: %d vendors", len(vs))
+	}
+	if _, ok := c.Lookup("routeros"); !ok {
+		t.Fatal("seed lookup broken after failed fetch")
+	}
+	if !c.LastRefreshedAt().IsZero() {
+		t.Fatal("lastRefreshedAt must stay zero without a successful fetch")
+	}
+}
+
+// TestCatalogInvalidEntriesDropped: las entradas inválidas se descartan una a
+// una sin romper el resto; un catálogo sin ninguna entrada válida no se
+// aplica y devuelve error conservando el anterior.
+func TestCatalogInvalidEntriesDropped(t *testing.T) {
+	d := newTestCatalogDB(t)
+	clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
+	var calls atomic.Int32
+
+	mixed := `{"vendors":[
+		{"id":"badmode","mode":"telnet","arches":["amd64"],"tagPrefix":"bad/v","binary":"b","target":"x","description":"bad mode"},
+		{"id":"noduplicates","mode":"local","arches":["amd64"],"tagPrefix":"dup/v","binary":"b","target":"x","description":"first"},
+		{"id":"noduplicates","mode":"local","arches":["amd64"],"tagPrefix":"dup/v","binary":"b","target":"x","description":"duplicate id"},
+		{"id":"noarches","mode":"local","arches":[],"tagPrefix":"na/v","binary":"b","target":"x","description":"empty arches"},
+		{"id":"goodone","mode":"ssh","arches":["arm64"],"tagPrefix":"good/v","binary":"good-pusher","target":"good/cmd/good-pusher","description":"Good one"}
+	]}`
+	c := NewCatalog(d.DB)
+	c.Now = clock.Now
+	c.FetchOverride = overrideOf(t, &calls, mixed)
+	if err := c.Refresh(context.Background()); err != nil {
+		t.Fatalf("Refresh with mixed entries: %v", err)
+	}
+	vs := c.Current()
+	if len(vs) != 2 {
+		t.Fatalf("valid vendors = %d, want 2 (goodone + noduplicates): %+v", len(vs), vs)
+	}
+	if _, ok := c.Lookup("goodone"); !ok {
+		t.Fatal("good entry must survive invalid siblings")
+	}
+	if _, ok := c.Lookup("badmode"); ok {
+		t.Fatal("entry with unknown mode must be dropped")
+	}
+	if _, ok := c.Lookup("noarches"); ok {
+		t.Fatal("entry with empty arches must be dropped")
+	}
+
+	// Todo inválido: error y catálogo anterior intacto.
+	empty := `{"vendors":[{"id":"Bad ID","mode":"local","arches":["amd64"],"tagPrefix":"x/v","binary":"b","target":"x","description":"bad id"}]}`
+	c.FetchOverride = overrideOf(t, &calls, empty)
+	if err := c.Refresh(context.Background()); err == nil {
+		t.Fatal("Refresh must fail when no entry is valid")
+	}
+	if len(c.Current()) != 2 {
+		t.Fatalf("previous catalog must survive a fully invalid refresh: %+v", c.Current())
+	}
+	if !c.LastRefreshedAt().Equal(clock.t) {
+		t.Fatal("lastRefreshedAt must not advance on a failed refresh")
+	}
+
+	// JSON malformado: mismo trato.
+	c.FetchOverride = overrideOf(t, &calls, `{"vendors": [[["bad`)
+	if err := c.Refresh(context.Background()); err == nil {
+		t.Fatal("Refresh must fail on malformed JSON")
+	}
+	if len(c.Current()) != 2 {
+		t.Fatalf("previous catalog must survive malformed JSON: %+v", c.Current())
+	}
+}
+
+// TestCatalogRefreshForcesFetch: el refresco admin salta el TTL, actualiza el
+// catálogo y lastRefreshedAt, y devuelve el error si el fetch falla sin tocar
+// lo servido.
+func TestCatalogRefreshForcesFetch(t *testing.T) {
+	d := newTestCatalogDB(t)
+	clock := &fakeClock{t: time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)}
+	var calls atomic.Int32
+
+	c := NewCatalog(d.DB)
+	c.Now = clock.Now
+	c.FetchOverride = overrideOf(t, &calls, labVendorA, labVendorB)
+	_ = c.Vendors(context.Background())
+	clock.Add(time.Minute) // fresco: Vendors no refrescaría
+
+	if err := c.Refresh(context.Background()); err != nil {
+		t.Fatalf("forced Refresh: %v", err)
+	}
+	if calls.Load() != 2 {
+		t.Fatalf("forced refresh must fetch even within the TTL (calls %d)", calls.Load())
+	}
+	if vs := c.Current(); len(vs[0].Arches) != 2 {
+		t.Fatalf("refreshed catalog not served: %+v", vs)
+	}
+	if !c.LastRefreshedAt().Equal(clock.t) {
+		t.Fatalf("lastRefreshedAt = %v, want %v", c.LastRefreshedAt(), clock.t)
+	}
+
+	c.FetchOverride = failingOverride(&calls)
+	if err := c.Refresh(context.Background()); err == nil {
+		t.Fatal("failed forced refresh must return the error")
+	}
+	if vs := c.Current(); len(vs[0].Arches) != 2 {
+		t.Fatalf("failed refresh must keep the previous catalog: %+v", vs)
+	}
+}

+ 2 - 2
server-go/internal/rintegration/fetch_test.go

@@ -107,7 +107,7 @@ func TestResolveLatestSkipsPrereleaseAndWrongPrefix(t *testing.T) {
 
 	f := NewFetcher()
 	f.APIBase = srv.URL
-	v, _ := LookupVendor("routeros")
+	v := seedVendor(t, "routeros")
 	res, err := f.ResolveLatest(v, "amd64")
 	if err != nil {
 		t.Fatalf("ResolveLatest: %v", err)
@@ -141,7 +141,7 @@ func TestResolveLatestAsuswrt(t *testing.T) {
 
 	f := NewFetcher()
 	f.APIBase = srv.URL
-	v, _ := LookupVendor("asuswrt")
+	v := seedVendor(t, "asuswrt")
 	res, err := f.ResolveLatest(v, "arm64")
 	if err != nil {
 		t.Fatalf("ResolveLatest: %v", err)

+ 9 - 55
server-go/internal/rintegration/vendors.go

@@ -6,16 +6,19 @@ package rintegration
 
 import "strings"
 
-// Vendor is the static manifest of one supported external pusher.
+// Vendor is one supported external pusher as resolved from the vendor
+// catalog. The catalog entries (vendors.json in netpulse-integrations) decide
+// which vendors exist; the fields the schema does not carry (Repo, AssetTmpl,
+// Init) are derived server-side by the Catalog when it builds this struct.
 type Vendor struct {
-	ID          string // "routeros" | "asuswrt"
+	ID          string // catalog "id"
 	Mode        string // "local" (runs on this host) | "ssh" (installed on the router)
-	Repo        string // GitHub repo that publishes the releases
+	Repo        string // GitHub repo that publishes the releases (derived: CatalogRepo)
 	TagPrefix   string // release tags for this vendor (e.g. "routeros/v")
-	AssetTmpl   string // asset name template with {version} and {arch}
+	AssetTmpl   string // asset name template with {version} and {arch} (derived)
 	Arches      []string
-	Binary      string // binary name inside the tarball
-	Init        string // on-router init system for Mode "ssh": "procd" (default when empty) | "merlin" (#1681)
+	Binary      string // binary name inside the tarball (catalog "binary")
+	Init        string // on-router init system for Mode "ssh": "procd" (default when empty) | "merlin" (#1681, derived)
 	Description string
 }
 
@@ -36,52 +39,3 @@ func (v Vendor) AssetName(version, arch string) string {
 	name = strings.ReplaceAll(name, "{arch}", arch)
 	return name
 }
-
-// vendors is the static manifest. bbox is intentionally absent: its PR is
-// still open and is not part of this package.
-var vendors = []Vendor{
-	{
-		ID:          "routeros",
-		Mode:        "local",
-		Repo:        "gnacho/netpulse-integrations",
-		TagPrefix:   "routeros/v",
-		AssetTmpl:   "routeros_{version}_linux_{arch}.tar.gz",
-		Arches:      []string{"amd64"},
-		Binary:      "routeros-pusher",
-		Description: "MikroTik RouterOS external pusher",
-	},
-	{
-		ID:          "asuswrt",
-		Mode:        "ssh",
-		Repo:        "gnacho/netpulse-integrations",
-		TagPrefix:   "asuswrt/v",
-		AssetTmpl:   "asuswrt_{version}_linux_{arch}.tar.gz",
-		Arches:      []string{"arm64"},
-		Binary:      "asuswrt-pusher",
-		Init:        "merlin",
-		Description: "Asuswrt (Asuswrt-Merlin) external pusher",
-	},
-	{
-		ID:          "unifi",
-		Mode:        "local",
-		Repo:        "gnacho/netpulse-integrations",
-		TagPrefix:   "unifi/v",
-		AssetTmpl:   "unifi_{version}_linux_{arch}.tar.gz",
-		Arches:      []string{"amd64"},
-		Binary:      "unifi-pusher",
-		Description: "UniFi controller external pusher",
-	},
-}
-
-// Vendors returns the supported vendor manifest.
-func Vendors() []Vendor { return vendors }
-
-// LookupVendor returns the vendor with the given id and whether it exists.
-func LookupVendor(id string) (Vendor, bool) {
-	for _, v := range vendors {
-		if v.ID == id {
-			return v, true
-		}
-	}
-	return Vendor{}, false
-}

+ 40 - 0
server-go/internal/rintegration/vendors_seed.json

@@ -0,0 +1,40 @@
+{
+  "vendors": [
+    {
+      "id": "asuswrt",
+      "mode": "ssh",
+      "arches": ["arm64"],
+      "tagPrefix": "asuswrt/v",
+      "binary": "asuswrt-pusher",
+      "target": "asuswrt/cmd/asuswrt-pusher",
+      "description": "Read-only Asuswrt/Merlin pusher that runs the portable NetPulse probes on the router itself"
+    },
+    {
+      "id": "bbox",
+      "mode": "local",
+      "arches": ["amd64", "arm64"],
+      "tagPrefix": "bbox/v",
+      "binary": "netpulse-integrations",
+      "target": "cmd/integrations-supervisor",
+      "description": "Read-only Bouygues Bbox poller shipped inside the shared integrations supervisor binary"
+    },
+    {
+      "id": "routeros",
+      "mode": "local",
+      "arches": ["amd64"],
+      "tagPrefix": "routeros/v",
+      "binary": "routeros-pusher",
+      "target": "routeros/cmd/routeros-pusher",
+      "description": "Read-only MikroTik RouterOS pusher over the binary API (REST fallback) for any host that reaches the router"
+    },
+    {
+      "id": "unifi",
+      "mode": "local",
+      "arches": ["amd64"],
+      "tagPrefix": "unifi/v",
+      "binary": "unifi-pusher",
+      "target": "unifi/cmd/unifi-pusher",
+      "description": "Read-only UniFi controller pusher covering gateways, switches and APs of one site"
+    }
+  ]
+}

+ 0 - 63
server-go/internal/rintegration/vendors_test.go

@@ -1,63 +0,0 @@
-package rintegration
-
-import "testing"
-
-func TestVendorsManifest(t *testing.T) {
-	vs := Vendors()
-	if len(vs) != 3 {
-		t.Fatalf("expected 3 vendors, got %d", len(vs))
-	}
-
-	r, ok := LookupVendor("routeros")
-	if !ok {
-		t.Fatal("routeros vendor missing")
-	}
-	if r.Mode != "local" || r.TagPrefix != "routeros/v" || r.Binary != "routeros-pusher" {
-		t.Fatalf("routeros manifest mismatch: %+v", r)
-	}
-	if len(r.Arches) != 1 || r.Arches[0] != "amd64" {
-		t.Fatalf("routeros arches = %v, want [amd64]", r.Arches)
-	}
-	if got := r.AssetName("1.2.3", "amd64"); got != "routeros_1.2.3_linux_amd64.tar.gz" {
-		t.Fatalf("routeros asset name = %q", got)
-	}
-
-	a, ok := LookupVendor("asuswrt")
-	if !ok {
-		t.Fatal("asuswrt vendor missing")
-	}
-	if a.Mode != "ssh" || a.TagPrefix != "asuswrt/v" || a.Binary != "asuswrt-pusher" {
-		t.Fatalf("asuswrt manifest mismatch: %+v", a)
-	}
-	if a.InitSystem() != "merlin" {
-		t.Fatalf("asuswrt init system = %q, want merlin", a.InitSystem())
-	}
-	r2, _ := LookupVendor("routeros")
-	if r2.InitSystem() != "procd" {
-		t.Fatalf("routeros init system = %q, want procd (empty Init default)", r2.InitSystem())
-	}
-	if len(a.Arches) != 1 || a.Arches[0] != "arm64" {
-		t.Fatalf("asuswrt arches = %v, want [arm64]", a.Arches)
-	}
-	if got := a.AssetName("1.0.0", "arm64"); got != "asuswrt_1.0.0_linux_arm64.tar.gz" {
-		t.Fatalf("asuswrt asset name = %q", got)
-	}
-
-	u, ok := LookupVendor("unifi")
-	if !ok {
-		t.Fatal("unifi vendor missing")
-	}
-	if u.Mode != "local" || u.TagPrefix != "unifi/v" || u.Binary != "unifi-pusher" {
-		t.Fatalf("unifi manifest mismatch: %+v", u)
-	}
-	if len(u.Arches) != 1 || u.Arches[0] != "amd64" {
-		t.Fatalf("unifi arches = %v, want [amd64]", u.Arches)
-	}
-	if got := u.AssetName("1.0.0", "amd64"); got != "unifi_1.0.0_linux_amd64.tar.gz" {
-		t.Fatalf("unifi asset name = %q", got)
-	}
-
-	if _, ok := LookupVendor("bbox"); ok {
-		t.Fatal("bbox must not be present")
-	}
-}