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

Tell NetGrip embedded agents apart; manage them safely (#371)

* feat: tell NetGrip embedded agents apart and refuse managing them (#363)

Agent pushes may now declare kind "netgrip" (panel-embedded
agent). The agents list exposes it, updateAvailable stays false,
and upgrade, rearm and reinstall answer 409 netgrip_managed: a
NetGrip router manages and updates its own agent. The auto-rearm
supervisor skips netgrip slugs without alert spam. Agents table
now separates Estado (active/inactive/not installed) from a new
Agente column (NetPulse/NetGrip/Externo), and NetGrip rows show
a hint instead of agent management actions.

The test server now wires an AgentHub like production so SSE
command routes are reachable from tests.

* fix: pre-existing tsc errors that broke the frontend build

Unused variables and imports in CollectorCharts and RulesManager,
an unused ACCENT_KEY constant, possibly-undefined palette lookups
(noUncheckedIndexedAccess) in theme-boot and Settings, and an
untyped select value. The dist CI job on main was failing on
these.

* feat: installer and apk hand off to NetGrip instead of installing the standalone agent (#363)

install-agent.sh detects NetGrip on the router and hands the
config to /etc/netgrip/netpulse.env (never overwriting an
existing one), restarts the panel and skips the standalone
install entirely. New --update-netgrip deploys the latest
NetGrip release (apk on 25.12, ipk otherwise) with a downgrade
guard (--force overrides). The agent package uci-defaults gets
the same guard so an apk install on a NetGrip router enables
nothing. Verified live on rt3: handoff preserves config, no
standalone artifacts, downgrade to v0.22.1 refused, embedded
agent keeps pushing.

* feat: NetPulse can drive NetGrip updates via the SSE upgrade event (#363)

The upgrade command is accepted again for netgrip-kind agents:
the embedded runtime receives it and runs NetGrip's own
self-updater (GitHub releases, sha verified), with its semver
guard refusing downgrades. updateAvailable for netgrip rows now
compares the reported version against the latest NetGrip release
(cached 5 min, honest empty on failure). Rearm and reinstall stay
refused. Verified live: server 202 sent, rt3 logs the trigger
and correctly reports already-latest for 0.23.0 vs v0.22.1.

---------

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

+ 11 - 2
app/public/locales/en/translation.json

@@ -692,7 +692,16 @@
       "discoveredSlug": "slug (e.g. switch16)",
       "discoveredPair": "Pair",
       "discoveredFail": "Could not create the token",
-      "discoveredHint": "Paste the command in the switch Advanced Settings"
+      "discoveredHint": "Paste the command in the switch Advanced Settings",
+      "colAgent": "Agent",
+      "active": "Active",
+      "inactive": "Inactive",
+      "notInstalled": "Not installed",
+      "kindNetpulse": "NetPulse",
+      "kindNetgrip": "NetGrip",
+      "kindExternal": "External",
+      "netgripTip": "The agent lives inside this router's NetGrip panel",
+      "netgripHint": "The agent lives in the NetGrip panel: Update upgrades the panel itself"
     },
     "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s"
   },
@@ -1452,4 +1461,4 @@
     "dhcpSuccess": "DHCP",
     "dnsLatency": "DNS"
   }
-}
+}

+ 11 - 2
app/public/locales/es/translation.json

@@ -692,7 +692,16 @@
       "discoveredSlug": "slug (p. ej. switch16)",
       "discoveredPair": "Parear",
       "discoveredFail": "No se pudo crear el token",
-      "discoveredHint": "Pega el comando en Advanced Settings del switch"
+      "discoveredHint": "Pega el comando en Advanced Settings del switch",
+      "colAgent": "Agente",
+      "active": "Activo",
+      "inactive": "Inactivo",
+      "notInstalled": "No instalado",
+      "kindNetpulse": "NetPulse",
+      "kindNetgrip": "NetGrip",
+      "kindExternal": "Externo",
+      "netgripTip": "El agente vive dentro del panel NetGrip de este router",
+      "netgripHint": "El agente vive en el panel NetGrip: Actualizar actualiza el propio panel"
     },
     "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s"
   },
@@ -1452,4 +1461,4 @@
     "dhcpSuccess": "DHCP",
     "dnsLatency": "DNS"
   }
-}
+}

+ 0 - 9
app/src/components/CollectorCharts.tsx

@@ -23,10 +23,6 @@ function isLatency(m: Metric): boolean {
   return m.key.startsWith('tcp_latency_ms.')
 }
 
-function isAvailability(m: Metric): boolean {
-  return m.key.startsWith('tcp_ok.')
-}
-
 function fmtTime(ts: number): string {
   return new Date(ts * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })
 }
@@ -170,14 +166,9 @@ export function CollectorCharts() {
   if (!available) return null
 
   const latencyMetrics = metrics.filter(isLatency)
-  const availMetrics = metrics.filter(isAvailability)
 
   if (!latencyMetrics.length) return null
 
-  const uptimeTargets = availMetrics.filter((m) => {
-    const name = targetName(m.key)
-    return latencyMetrics.some((l) => targetName(l.key) === name)
-  })
 
   return (
     <div>

+ 1 - 3
app/src/components/RulesManager.tsx

@@ -2,11 +2,9 @@ import { useCallback, useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { motion } from 'framer-motion'
 import {
-  AlertTriangle,
   Check,
   Globe,
   Info,
-  OctagonX,
   Plus,
   Router,
   Server,
@@ -292,7 +290,7 @@ export function RulesManager() {
             </div>
             <div>
               <label className="mb-1 block text-caption font-medium text-text-secondary">{t('alertRules.severity')}</label>
-              <Select value={editing.severity} onValueChange={(v) => setEditing({ ...editing, severity: v })}>
+              <Select value={editing.severity} onValueChange={(v) => setEditing({ ...editing, severity: v as 'info' | 'warn' | 'critical' })}>
                 <SelectTrigger size="sm" className="h-8">
                   <SelectValue />
                 </SelectTrigger>

+ 56 - 15
app/src/components/routers/AgentsSection.tsx

@@ -7,7 +7,6 @@ import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
 import type { AgentInfo, Router } from '@/data/types'
 import { relTimeFromTs } from '@/i18n'
-import { AgentBadge } from '@/components/routers/AgentBadge'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
 import { AgentUpgradeButton, activeUpgrade, upgradeStepText } from '@/components/routers/AgentUpgradeButton'
 import { cn } from '@/lib/utils'
@@ -77,6 +76,7 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
   const [copyState, setCopyState] = useState<CopyState>('idle')
   const [nowSec, setNowSec] = useState(() => Math.floor(Date.now() / 1000))
 
+  const isNetgrip = agent?.kind === 'netgrip'
   const isOpenWrt = isOpenWrtType(router?.type)
   const isStale = agent !== undefined && !agent.fresh
   const isMissing = agent === undefined && router?.agentOnly === true
@@ -150,7 +150,47 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
         </div>
       </td>
       <td className="py-3 pr-3">
-        <AgentBadge agent={agent} agentOnly={router?.agentOnly} deviceType={router?.type} />
+        {agent ? (
+          <span
+            title={agent.fresh ? t('routers.agent.freshTip', { version: agent.version }) : t('routers.agent.staleTip')}
+            className="inline-flex items-center gap-1.5 text-caption font-semibold"
+          >
+            <span className={cn('h-1.5 w-1.5 rounded-full', agent.fresh ? 'bg-ok' : 'bg-danger')} aria-hidden="true" />
+            <span className={agent.fresh ? 'text-ok' : 'text-danger'}>
+              {agent.fresh ? t('routers.agents.active') : t('routers.agents.inactive')}
+            </span>
+          </span>
+        ) : (
+          <span title={t('routers.agent.notInstalledTip')} className="inline-flex items-center gap-1.5 text-caption font-semibold text-danger">
+            <span className="h-1.5 w-1.5 rounded-full bg-danger" aria-hidden="true" />
+            {t('routers.agents.notInstalled')}
+          </span>
+        )}
+      </td>
+      <td className="py-3 pr-3">
+        {agent ? (
+          agent.kind === 'netgrip' ? (
+            <span
+              title={t('routers.agents.netgripTip')}
+              className="inline-flex items-center rounded-full border border-accent/40 bg-accent/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent"
+            >
+              {t('routers.agents.kindNetgrip')}
+            </span>
+          ) : agent.kind === 'external' ? (
+            <span
+              title={t('routers.agents.externalTip', { interval: agent.interval ?? 0 })}
+              className="inline-flex items-center rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted"
+            >
+              {t('routers.agents.kindExternal')}
+            </span>
+          ) : (
+            <span className="inline-flex items-center rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-text-secondary">
+              {t('routers.agents.kindNetpulse')}
+            </span>
+          )
+        ) : (
+          <span className="text-caption text-text-faint">-</span>
+        )}
       </td>
       <td className="py-3 pr-3">
         <span className="font-mono text-caption text-text-secondary">{lastSeen}</span>
@@ -158,26 +198,24 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
       <td className="py-3 pr-3">
         <span className="flex items-center gap-2">
           <span className="font-mono text-caption text-text-secondary">
-            {agent?.version ? (agent.kind === 'external' ? agent.version : `v${agent.version}`) : '-'}
+            {agent?.version ? (agent.kind === 'external' || agent.kind === 'netgrip' ? agent.version : `v${agent.version}`) : '-'}
           </span>
-          {agent?.kind === 'external' && (
-            <span
-              title={t('routers.agents.externalTip', { interval: agent.interval ?? 0 })}
-              className="inline-flex items-center rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-text-muted"
-            >
-              {t('routers.agents.external')}
-            </span>
-          )}
         </span>
       </td>
       <td className="py-3">
         <div className="flex flex-wrap items-center gap-2">
-          {/* Actualizar: self-update del agente con progreso en vivo (#243) */}
+          {/* Actualizar: self-update del agente con progreso en vivo (#243).
+              NetGrip (#363): el evento SSE dispara el self-update del propio
+              panel; rearm/reinstall no aplican (no hay proceso standalone). */}
           <AgentUpgradeButton agent={agent} className="h-8" />
+          {isNetgrip ? (
+            <span className="text-caption text-text-muted">{t('routers.agents.netgripHint')}</span>
+          ) : (
+            <>
           {/* Rearm: canal preferente para heartbeat stale (proceso vivo).
               Solo agentes NATIVOS OpenWrt: los externos (switch por beacon)
               no tienen SSH - solo alertan (#291). */}
-          {agent && agent.kind !== 'external' && <AgentRearmButton agent={agent} />}
+          {agent && agent.kind !== 'external' && agent.kind !== 'netgrip' && <AgentRearmButton agent={agent} />}
           {canRecover && (
             <button
               type="button"
@@ -203,7 +241,7 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
                     : t('routers.agents.reinstall')}
             </button>
           )}
-          {canRecover && (
+          {canRecover && !isNetgrip && (
             <button
               type="button"
               onClick={() => void copyCmd()}
@@ -229,6 +267,8 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
                   : t('routers.agents.copyCmd')}
             </button>
           )}
+            </>
+          )}
         </div>
         {reinstallMsg && reinstallState !== 'idle' && (
           <p className={cn('mt-1.5 text-caption', reinstallState === 'fail' ? 'text-danger' : 'text-text-muted')}>
@@ -244,7 +284,7 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
         transition={{ duration: 0.2 }}
         className="border-b border-border/60 last:border-0"
       >
-        <td colSpan={5} className="pb-3">
+        <td colSpan={6} className="pb-3">
           <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 rounded-xl bg-surface px-3.5 py-2.5">
             <span className="inline-flex items-center gap-1.5 text-label font-medium uppercase text-text-muted">
               <Clock className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden="true" />
@@ -423,6 +463,7 @@ export function AgentsSection() {
               <tr className="border-b border-border">
                 <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colDevice')}</th>
                 <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colStatus')}</th>
+                <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colAgent')}</th>
                 <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colLastSeen')}</th>
                 <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colVersion')}</th>
                 <th className="pb-2.5 text-label font-medium uppercase text-text-muted">{t('routers.agents.colActions')}</th>

+ 1 - 1
app/src/data/types.ts

@@ -400,7 +400,7 @@ export interface AgentInfo {
   /** Versión del binario netpulse-agent ("" si aún no se conoce) */
   version?: string
   /** "native" (agente netpulse-agent) o "external" (pusher tipo scraper, #285/#288) */
-  kind?: 'native' | 'external'
+  kind?: 'native' | 'external' | 'netgrip'
   /** Cadencia de push declarada en segundos (solo externos, #288) */
   interval?: number
   fresh: boolean

+ 1 - 2
app/src/lib/theme-boot.ts

@@ -106,7 +106,6 @@ export type PaletteId = (typeof PALETTES)[number]['id']
 
 const MODE_KEY = 'netpulse-theme-mode'
 const LEGACY_KEY = 'netpulse-theme'
-const ACCENT_KEY = 'netpulse-accent'
 const PALETTE_KEY = 'netpulse-palette'
 const DENSITY_KEY = 'netpulse-density'
 const REDUCE_MOTION_KEY = 'netpulse-reduce-motion'
@@ -152,7 +151,7 @@ export function applyTheme(mode: ThemeMode) {
 
 function applyPalette(light: boolean) {
   const id = readPalette()
-  const palette = PALETTES.find((x) => x.id === id) ?? PALETTES[0]
+  const palette = PALETTES.find((x) => x.id === id) ?? PALETTES[0]!
   const vars = light ? palette.light : palette.dark
   const root = document.documentElement
   for (const [key, value] of Object.entries(vars)) {

+ 1 - 1
app/src/pages/Settings.tsx

@@ -3020,7 +3020,7 @@ export default function Settings() {
   const [paletteId, setPaletteId] = useStoredState<PaletteId>('netpulse-palette', 'netpulse')
   const [accentId, setAccentId] = useStoredState<AccentId>('netpulse-accent', 'cyan')
   useEffect(() => {
-    const palette = PALETTES.find((x) => x.id === paletteId) ?? PALETTES[0]
+    const palette = PALETTES.find((x) => x.id === paletteId) ?? PALETTES[0]!
     const vars = resolvedLight ? palette.light : palette.dark
     const root = document.documentElement
     for (const [key, value] of Object.entries(vars)) {

+ 25 - 0
deploy/openwrt/netpulse-agent/files/netpulse-agent.defaults

@@ -6,6 +6,31 @@
 AGENT_ENV=/etc/netpulse-agent.env
 AGENT_UCI=netpulse-agent
 
+# NetGrip detectado (#363): el agente EMBEBIDO en el panel ya cubre este
+# router. Entregarle la config migrada (solo si aún no tiene) y NO instalar
+# el standalone (ni servicio ni watchdog ni cron).
+if [ -x /usr/sbin/netgrip ] || [ -f /etc/init.d/netgrip ]; then
+	NG_ENV=/etc/netgrip/netpulse.env
+	if [ ! -f "$NG_ENV" ] && [ -f "$AGENT_ENV" ]; then
+		. "$AGENT_ENV"
+		if [ -n "$NETPULSE_SERVER" ] && [ -n "$NETPULSE_SLUG" ] && [ -n "$NETPULSE_TOKEN" ]; then
+			mkdir -p /etc/netgrip
+			{
+				echo "# managed by netgrip; netpulse embedded agent config"
+				echo "NETPULSE_SERVER=$NETPULSE_SERVER"
+				echo "NETPULSE_SLUG=$NETPULSE_SLUG"
+				echo "NETPULSE_TOKEN=$NETPULSE_TOKEN"
+				echo "NETPULSE_ENABLED=1"
+			} > "$NG_ENV"
+			chmod 600 "$NG_ENV"
+			logger -t netpulse-agent "NetGrip detectado: config migrada a $NG_ENV"
+		fi
+	fi
+	/etc/init.d/netgrip restart >/dev/null 2>&1 || true
+	logger -t netpulse-agent "NetGrip detectado: agente standalone NO instalado"
+	exit 0
+fi
+
 # Migrar instalación manual previa (.env) a UCI
 if [ -f "$AGENT_ENV" ]; then
 	. "$AGENT_ENV"

+ 87 - 1
install-agent.sh

@@ -29,6 +29,10 @@
 #                   reiniciar — tras un reboot hay que reejecutar este script
 #                   (variante documentada del SPEC; el .ipk llega en el incr. 2)
 #   --uninstall     detiene y elimina servicio, binario y config del router
+#   --update-netgrip  si se detecta NetGrip en el router: actualizar el panel
+#                   NetGrip a su última release (apk/ipk de GitHub) en vez de
+#                   limitarse a entregarle la config (--force permite bajar de
+#                   versión)
 #
 # Requisitos: ssh/scp al router (OpenWrt con dropbear), curl o wget local.
 # =============================================================================
@@ -40,7 +44,7 @@ ENV_FILE="/etc/netpulse-agent.env"
 INIT_NAME="netpulse-agent"
 INIT_DST="/etc/init.d/$INIT_NAME"
 
-HOST=""; SERVER=""; SLUG=""; TOKEN=""; PAIRING_TOKEN=""; SERVER_FP=""; SSH_USER="root"; BINARY=""; NETPULSE_VERSION=""; USE_TMP=0; UNINSTALL=0
+HOST=""; SERVER=""; SLUG=""; TOKEN=""; PAIRING_TOKEN=""; SERVER_FP=""; SSH_USER="root"; BINARY=""; NETPULSE_VERSION=""; USE_TMP=0; UNINSTALL=0; UPDATE_NETGRIP=0; NETGRIP_FORCE=0
 
 if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
     C_G=$(printf '\033[32m'); C_R=$(printf '\033[31m'); C_Y=$(printf '\033[33m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
@@ -65,6 +69,8 @@ for arg in "$@"; do
         --version=*)  NETPULSE_VERSION="${arg#*=}" ;;
         --tmp)        USE_TMP=1 ;;
         --uninstall)  UNINSTALL=1 ;;
+        --update-netgrip) UPDATE_NETGRIP=1 ;;
+        --force)      NETGRIP_FORCE=1 ;;
         -h|--help)    usage ;;
         *) fatal 10 "opción desconocida: $arg (prueba --help)" ;;
     esac
@@ -103,6 +109,86 @@ SERVER="${SERVER%/}"
 ssh -o ConnectTimeout=8 -o BatchMode=yes "$SSH" true \
     || fatal 13 "no hay SSH a $SSH (¿dropbear + clave autorizada?)"
 
+# ----------------------------------------------------- netgrip handoff --
+# Si el router ya corre NetGrip, su agente EMBEBIDO cubre el sondeo: no se
+# instala el standalone. Se le entrega la config (sin pisar la existente) y
+# opcionalmente se actualiza el propio NetGrip (--update-netgrip).
+if ssh "$SSH" '[ -x /usr/sbin/netgrip ] || [ -f /etc/init.d/netgrip ]'; then
+    info "NetGrip detectado en $HOST: el agente embebido ya cubre este router"
+    # Token line igual que el flujo normal
+    if [ -n "$PAIRING_TOKEN" ]; then
+        HANDOFF_TOKEN="NETPULSE_PAIRING_TOKEN=$PAIRING_TOKEN"
+    else
+        HANDOFF_TOKEN="NETPULSE_TOKEN=$TOKEN"
+    fi
+    HANDOFF_FP=""
+    [ -n "$SERVER_FP" ] && HANDOFF_FP="NETPULSE_SERVER_FP=$SERVER_FP"
+    ssh "$SSH" "NG_ENV=/etc/netgrip/netpulse.env sh -s" <<HANDOFF
+set -eu
+if [ ! -f "\$NG_ENV" ]; then
+    mkdir -p /etc/netgrip
+    {
+        echo "# managed by netgrip; netpulse embedded agent config"
+        echo "NETPULSE_SERVER=$SERVER"
+        echo "NETPULSE_SLUG=$SLUG"
+        echo "$HANDOFF_TOKEN"
+        ${HANDOFF_FP:+echo "$HANDOFF_FP"}
+        echo "NETPULSE_ENABLED=1"
+    } > "\$NG_ENV"
+    chmod 600 "\$NG_ENV"
+    echo "config-escrita"
+else
+    echo "config-existente-conservada"
+fi
+HANDOFF
+
+    if [ "$UPDATE_NETGRIP" -eq 1 ]; then
+        # Versión instalada (registry apk/opkg; vacío si es binario manual)
+        CUR=$(ssh "$SSH" "(apk info netgrip 2>/dev/null || opkg status netgrip 2>/dev/null | sed -n 's/^Version: //p') | head -1")
+        if command -v curl >/dev/null 2>&1; then FETCH="curl -fsSL --retry 3 --connect-timeout 10"
+        elif command -v wget >/dev/null 2>&1; then FETCH="wget -q -O-"
+        else fatal 21 "necesito curl o wget"; fi
+        NG_TAG=$($FETCH "https://api.github.com/repos/gnacho/netgrip/releases/latest" \
+            | grep '"tag_name"' | head -1 | cut -d'"' -f4) || fatal 41 "no pude resolver la última release de NetGrip"
+        NG_VER=$(echo "$NG_TAG" | sed 's/^v//')
+        ARCH=$(ssh "$SSH" uname -m)
+        case "$ARCH" in
+            aarch64|arm64) NG_ARCH=arm64 ;;
+            *) fatal 20 "NetGrip solo publica builds arm64 (router: $ARCH)" ;;
+        esac
+        if ssh "$SSH" command -v apk >/dev/null 2>&1; then
+            NG_ASSET="netgrip-${NG_VER}-r1-${NG_ARCH}.apk"; NG_INST="apk add --allow-untrusted /tmp/netgrip-update.pkg"
+        else
+            NG_ASSET="netgrip_${NG_VER}-1_aarch64_cortex-a53.ipk"; NG_INST="opkg install /tmp/netgrip-update.pkg"
+        fi
+        NG_URL="https://github.com/gnacho/netgrip/releases/download/${NG_TAG}/${NG_ASSET}"
+        info "actualizando NetGrip a $NG_TAG (instalado: ${CUR:-desconocido})"
+        if [ -n "$CUR" ] && [ "$NETGRIP_FORCE" -ne 1 ]; then
+            CUR_V=$(echo "$CUR" | sed 's/^netgrip-//; s/ description:.*//; s/-r[0-9]*$//')
+            if [ "$CUR_V" = "$NG_VER" ]; then
+                ok "NetGrip ya está en $NG_VER; nada que hacer (usa --force para reinstalar)"
+                ssh "$SSH" "/etc/init.d/netgrip restart >/dev/null 2>&1 || true"
+                ok "agente embebido rearmado (slug $SLUG)"
+                exit 0
+            fi
+            OLDEST=$(printf '%s\n%s\n' "$CUR_V" "$NG_VER" | sort -V | head -1)
+            if [ "$OLDEST" = "$NG_VER" ]; then
+                warn "la release $NG_TAG es MÁS VIEJA que la instalada ($CUR_V): router con build no liberada"
+                fatal 43 "downgrade rechazado (usa --force si de verdad lo quieres)"
+            fi
+        fi
+        $FETCH "$NG_URL" -o "$TMP/netgrip-update.pkg" || fatal 42 "descarga falló: $NG_URL"
+        scp -Oq "$TMP/netgrip-update.pkg" "$SSH:/tmp/netgrip-update.pkg"
+        ssh "$SSH" "$NG_INST && rm -f /tmp/netgrip-update.pkg"
+        ok "NetGrip actualizado a $NG_TAG"
+    fi
+
+    ssh "$SSH" "/etc/init.d/netgrip restart >/dev/null 2>&1 || true"
+    ok "agente embebido de NetGrip rearmado (server $SERVER, slug $SLUG)"
+    info "el agente standalone NO se instala en routers con NetGrip"
+    exit 0
+fi
+
 # ------------------------------------------------------------------ binario --
 BIN_DST="/usr/sbin/$BIN_NAME"
 [ "$USE_TMP" -eq 1 ] && BIN_DST="/tmp/$BIN_NAME"

+ 114 - 4
server-go/internal/httpapi/agent.go

@@ -438,6 +438,7 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 				slug := strings.TrimPrefix(key, agentTokenKeyPrefix)
 				item := agentListItem{Slug: slug}
 				var payload *probe.Payload
+				agentKind := ""
 				if s.agents != nil {
 					if st := s.agents.Snapshot(slug); st != nil {
 						payload = st.Payload
@@ -446,9 +447,11 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 						ts := seen.Unix()
 						item.LastSeen = &ts
 						item.Version = version
-						if kind == "external" {
-							item.Kind = "external"
-						} else {
+						agentKind = kind
+						switch kind {
+						case "external", "netgrip":
+							item.Kind = kind
+						default:
 							item.Kind = "native"
 						}
 						item.Interval = interval
@@ -463,7 +466,14 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 				if r, ok := routerByID[item.RouterID]; ok {
 					matchedType = r.Type
 				}
-				item.UpdateAvailable = agentUpgradeable(matchedType) && item.Version != "" && item.Version != agentbin.EmbeddedAgentVersion
+				// #363: un agente embebido en NetGrip se actualiza vía el
+				// evento SSE upgrade (NetGrip corre su propio self-update);
+				// "hay novedad" = versión reportada < última release de NetGrip.
+				if agentKind == "netgrip" {
+					item.UpdateAvailable = item.Version != "" && cmpSemver(netgripLatest(), item.Version) > 0
+				} else {
+					item.UpdateAvailable = agentUpgradeable(matchedType) && item.Version != "" && item.Version != agentbin.EmbeddedAgentVersion
+				}
 				// Progreso en vivo del upgrade (#284), si hay actividad reciente.
 				if st, ok := s.upgrades.snapshot(slug); ok {
 					ts := st.Ts.Unix()
@@ -583,6 +593,8 @@ func (s *server) handleAgentRearm(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusConflict, "router_unknown", err.Error())
 	case errors.Is(err, rearmer.ErrExternalAgent):
 		writeError(w, http.StatusConflict, "not_openwrt", err.Error())
+	case errors.Is(err, rearmer.ErrNetgripAgent):
+		writeError(w, http.StatusConflict, "netgrip_managed", err.Error())
 	case errors.Is(err, rearmer.ErrNoSSH):
 		writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", err.Error())
 	default:
@@ -625,6 +637,12 @@ func (s *server) handleAgentReinstall(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
 		return
 	}
+	// #363: jamás desplegar el binario standalone sobre un router cuyo
+	// agente es el NetGrip embebido (lo destrozaría: duplicado + token roto).
+	if s.agentKindOf(slug) == "netgrip" {
+		writeError(w, http.StatusConflict, "netgrip_managed", "agente embebido en NetGrip: actualiza o reinstala el panel NetGrip en el propio router")
+		return
+	}
 
 	// Router del slug (tabla routers; mismo host que usa el rearm).
 	host := ""
@@ -792,3 +810,95 @@ func (s *server) handleAgentRefresh(w http.ResponseWriter, r *http.Request) {
 	}
 	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
 }
+
+// agentKindOf devuelve el kind del último push del slug ("" si no hay).
+func (s *server) agentKindOf(slug string) string {
+	if s.agents == nil {
+		return ""
+	}
+	if _, _, kind, _, ok := s.agents.Info(slug); ok {
+		return kind
+	}
+	return ""
+}
+
+// ------------------------------------------------------------ netgrip latest --
+// netgripLatest resuelve la última release de gnacho/netgrip con cache (TTL):
+// los agentes kind=netgrip comparan su versión contra ELLA (el binario
+// embebido del server no aplica). Falla de red → cache/"" → sin botón.
+var (
+	netgripLatestMu    sync.Mutex
+	netgripLatestVer   string
+	netgripLatestAt    time.Time
+	netgripLatestFetch = fetchNetgripLatestVersion // sustituible en tests
+)
+
+const netgripLatestTTL = 5 * time.Minute
+
+func fetchNetgripLatestVersion() string {
+	client := &http.Client{Timeout: 8 * time.Second}
+	req, err := http.NewRequest("GET", "https://api.github.com/repos/gnacho/netgrip/releases/latest", nil)
+	if err != nil {
+		return ""
+	}
+	req.Header.Set("Accept", "application/vnd.github+json")
+	req.Header.Set("User-Agent", "netpulse-server")
+	resp, err := client.Do(req)
+	if err != nil || resp.StatusCode != 200 {
+		if resp != nil {
+			resp.Body.Close()
+		}
+		return ""
+	}
+	defer resp.Body.Close()
+	var rel struct {
+		TagName string `json:"tag_name"`
+	}
+	if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<16)).Decode(&rel); err != nil {
+		return ""
+	}
+	return strings.TrimPrefix(rel.TagName, "v")
+}
+
+func netgripLatest() string {
+	netgripLatestMu.Lock()
+	defer netgripLatestMu.Unlock()
+	if netgripLatestVer != "" && time.Since(netgripLatestAt) < netgripLatestTTL {
+		return netgripLatestVer
+	}
+	if v := netgripLatestFetch(); v != "" {
+		netgripLatestVer, netgripLatestAt = v, time.Now()
+	}
+	return netgripLatestVer
+}
+
+// cmpSemver compara dos versiones x.y.z (-rN se ignora): -1, 0, 1. Malparse
+// → 0 (sin señal de novedad).
+func cmpSemver(a, b string) int {
+	pa, okA := parseSemver3(a)
+	pb, okB := parseSemver3(b)
+	if !okA || !okB {
+		return 0
+	}
+	for i := 0; i < 3; i++ {
+		if pa[i] != pb[i] {
+			if pa[i] > pb[i] {
+				return 1
+			}
+			return -1
+		}
+	}
+	return 0
+}
+
+func parseSemver3(v string) ([3]int, bool) {
+	v = strings.TrimPrefix(strings.TrimSpace(v), "v")
+	if i := strings.IndexAny(v, "- +"); i >= 0 {
+		v = v[:i]
+	}
+	var x [3]int
+	if n, _ := fmt.Sscanf(v, "%d.%d.%d", &x[0], &x[1], &x[2]); n != 3 {
+		return x, false
+	}
+	return x, true
+}

+ 11 - 1
server-go/internal/httpapi/agent_api_test.go

@@ -61,9 +61,19 @@ func makeAgentTestServer(t *testing.T) *agentTestServer {
 	}
 	reg := adapters.NewAgentRegistry(90 * time.Second)
 	hub := sse.NewHub(d, cfg.MaxSSEClients, func() any { return nil })
+	// AgentHub con el checkToken de producción (sha256 del token vs kv):
+	// registra rutas de comandos SSE (/upgrade, /refresh) como en prod.
+	agentHub := sse.NewAgentHub(func(slug, token string) bool {
+		var stored string
+		if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "agent.token."+slug).Scan(&stored); err != nil {
+			return false
+		}
+		sum := sha256.Sum256([]byte(token))
+		return hex.EncodeToString(sum[:]) == stored
+	})
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config: cfg, DB: d, Adapter: adapters.NewDemo(), Hub: hub, Secret: secret,
-		Agents: reg, Started: time.Now(),
+		Agents: reg, Started: time.Now(), AgentHub: agentHub,
 	})
 	srv := httptest.NewServer(handler)
 	status, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")

+ 82 - 0
server-go/internal/httpapi/agent_kind_test.go

@@ -0,0 +1,82 @@
+package httpapi_test
+
+import (
+	"fmt"
+	"net/http"
+	"strings"
+	"testing"
+	"time"
+)
+
+// TestAgentsNetgripKind (#363): un push con kind "netgrip" se lista como tal,
+// no marca updateAvailable y el servidor rechaza upgrade, rearm y reinstall
+// (el agente es el panel NetGrip; se gestiona desde el propio router).
+func TestAgentsNetgripKind(t *testing.T) {
+	ts := makeAgentTestServer(t)
+	_, token, _ := createAgentToken(t, ts, "patio")
+
+	payload := fmt.Sprintf(`{"router":"patio","ts":%d,"version":"0.23.0","kind":"netgrip","data":{"system":{"sysinfo":{"uptime":100,"load":[0,0,0],"memory":{"total":100,"free":50,"buffered":0,"available":50}},"cpu":10,"temp":40},"wireless":{"clients":{}},"dhcp":{"leases":[]},"fdb":{"macs":{}}}}`, time.Now().Unix())
+	res := ingest(t, ts, token, "10.0.3.7", payload)
+	res.Body.Close()
+	if res.StatusCode != 202 {
+		t.Fatalf("ingest netgrip: %d", res.StatusCode)
+	}
+
+	res = get(t, ts.URL, "/api/agents", ts.cookie)
+	body := readJSON(t, res)
+	agents, _ := body["agents"].([]any)
+	var patio map[string]any
+	for _, a := range agents {
+		m, _ := a.(map[string]any)
+		if m["slug"] == "patio" {
+			patio = m
+		}
+	}
+	if patio == nil {
+		t.Fatalf("patio no está en la lista: %v", body)
+	}
+	if patio["kind"] != "netgrip" {
+		t.Fatalf("patio kind: %v (want netgrip)", patio["kind"])
+	}
+	if patio["version"] != "0.23.0" {
+		t.Fatalf("patio version: %v", patio["version"])
+	}
+	if upd, ok := patio["updateAvailable"].(bool); ok && upd {
+		t.Fatalf("con netgrip latest 0.22.1 y router en 0.23.0 no debe ofrecer upgrade: %v", patio)
+	}
+
+	post := func(path string) int {
+		req, _ := http.NewRequest("POST", ts.URL+path, nil)
+		req.Header.Set("Cookie", "session="+ts.cookie)
+		r, err := http.DefaultClient.Do(req)
+		if err != nil {
+			t.Fatalf("%s: %v", path, err)
+		}
+		defer r.Body.Close()
+		return r.StatusCode
+	}
+
+	// #363 v2: el upgrade SÍ se acepta para NetGrip (dispara su self-update).
+	// Sin conexión SSE en el test el comando queda encolado → 202.
+	if c := post("/api/agents/patio/upgrade"); c != http.StatusAccepted {
+		t.Fatalf("upgrade netgrip: %d (want 202)", c)
+	}
+	if c := post("/api/agents/patio/rearm"); c != http.StatusConflict {
+		t.Fatalf("rearm netgrip: %d (want 409)", c)
+	}
+
+	// Un agente NATIVO sin kind sigue listándose como native.
+	_, tokenN, _ := createAgentToken(t, ts, "living")
+	payloadN := strings.Replace(strings.Replace(payload, `"patio"`, `"living"`, 1), `"kind":"netgrip",`, ``, 1)
+	resN := ingest(t, ts, tokenN, "10.0.3.8", payloadN)
+	resN.Body.Close()
+	res = get(t, ts.URL, "/api/agents", ts.cookie)
+	body = readJSON(t, res)
+	agents, _ = body["agents"].([]any)
+	for _, a := range agents {
+		m, _ := a.(map[string]any)
+		if m["slug"] == "living" && m["kind"] != "native" {
+			t.Fatalf("living kind: %v (want native)", m["kind"])
+		}
+	}
+}

+ 80 - 0
server-go/internal/httpapi/netgrip_latest_test.go

@@ -0,0 +1,80 @@
+package httpapi
+
+import (
+	"testing"
+	"time"
+)
+
+// NetgripTestFetch devuelve el resolver actual de la última release de
+// NetGrip (hooks de test para httpapi_test, patrón export_test).
+func NetgripTestFetch() func() string { return netgripLatestFetch }
+
+// NetgripTestSetFetch sustituye el resolver y limpia la cache.
+func NetgripTestSetFetch(f func() string) {
+	netgripLatestMu.Lock()
+	defer netgripLatestMu.Unlock()
+	netgripLatestFetch = f
+	netgripLatestVer = ""
+	netgripLatestAt = time.Time{}
+}
+
+func TestNetgripLatestCacheAndCmp(t *testing.T) {
+	orig := netgripLatestFetch
+	t.Cleanup(func() {
+		netgripLatestMu.Lock()
+		netgripLatestFetch = orig
+		netgripLatestVer = ""
+		netgripLatestAt = time.Time{}
+		netgripLatestMu.Unlock()
+	})
+
+	// cmpSemver: orden numérico por campo, tolerante a v/ y sufijos -rN.
+	if got := cmpSemver("v0.22.1", "0.23.0"); got != -1 {
+		t.Fatalf("cmpSemver(v0.22.1, 0.23.0) = %d, want -1", got)
+	}
+	if got := cmpSemver("0.23.0-r6", "0.23.0"); got != 0 {
+		t.Fatalf("cmpSemver(0.23.0-r6, 0.23.0) = %d, want 0", got)
+	}
+	if got := cmpSemver("0.23.0", "v0.22.9"); got != 1 {
+		t.Fatalf("cmpSemver(0.23.0, v0.22.9) = %d, want 1", got)
+	}
+	if got := cmpSemver("nonsense", "0.1.0"); got != 0 {
+		t.Fatalf("cmpSemver malparseado = %d, want 0", got)
+	}
+
+	// netgripLatest usa la cache dentro del TTL aunque el fetch cambie.
+	netgripLatestMu.Lock()
+	netgripLatestFetch = func() string { return "1.2.3" }
+	netgripLatestMu.Unlock()
+	if v := netgripLatest(); v != "1.2.3" {
+		t.Fatalf("netgripLatest tras fetch = %q, want 1.2.3", v)
+	}
+	netgripLatestMu.Lock()
+	netgripLatestFetch = func() string { return "9.9.9" }
+	netgripLatestMu.Unlock()
+	if v := netgripLatest(); v != "1.2.3" {
+		t.Fatalf("netgripLatest dentro del TTL = %q, want 1.2.3 (cache)", v)
+	}
+}
+
+func TestNetgripLatestFetchFailVacia(t *testing.T) {
+	orig := netgripLatestFetch
+	t.Cleanup(func() {
+		netgripLatestMu.Lock()
+		netgripLatestFetch = orig
+		netgripLatestVer = ""
+		netgripLatestMu.Unlock()
+	})
+	netgripLatestMu.Lock()
+	netgripLatestFetch = func() string { return "" }
+	netgripLatestVer = ""
+	netgripLatestAt = time.Time{}
+	netgripLatestMu.Unlock()
+	if v := netgripLatest(); v != "" {
+		t.Fatalf("fetch roto debe dar vacío, got %q", v)
+	}
+	// Sin latest conocida, cmpSemver da 0 → updateAvailable false (sin botón).
+	if cmpSemver(netgripLatest(), "0.23.0") > 0 {
+		t.Fatal("latest vacía no debe marcar updateAvailable")
+	}
+}

+ 3 - 0
server-go/internal/httpapi/upgrade.go

@@ -184,6 +184,9 @@ func (s *server) handleAgentUpgrade(w http.ResponseWriter, r *http.Request) {
 		writeError(w, http.StatusNotFound, "not_found")
 		return
 	}
+	// #363: un agente NetGrip SÍ acepta el upgrade: el evento SSE dispara
+	// el self-update del propio NetGrip (sus releases de GitHub). Rearm y
+	// reinstall siguen rechazados (no hay proceso standalone que gestionar).
 	// El agente conoce su propia arquitectura (runtime.GOARCH); no hace falta
 	// pasársela. Data vacía {}. Si no está conectado por SSE, el upgrade se
 	// ENCOLA y se enviará en cuanto vuelva a conectar (#284).

+ 16 - 0
server-go/internal/rearmer/rearmer.go

@@ -78,6 +78,9 @@ var (
 	// p. ej. switch gestionado por beacon): sin SSH, no se instala, no se
 	// rearmera ni se actualiza - solo alerta (#291).
 	ErrExternalAgent = fmt.Errorf("agente externo: sin SSH ni rearme")
+	// ErrNetgripAgent (#363): el agente de este slug es el NetGrip embebido;
+	// no se rearma ni se reinstala desde el servidor.
+	ErrNetgripAgent = fmt.Errorf("agente embebido en NetGrip: gestionarlo desde el panel NetGrip")
 	ErrNoSSH    = fmt.Errorf("el servidor no tiene pool SSH (modo demo o clave ausente)")
 	ErrNoDB     = fmt.Errorf("db no disponible")
 )
@@ -138,6 +141,13 @@ func (r *Rearmer) Rearm(slug string) (Result, error) {
 	if r.db == nil {
 		return Result{}, ErrNoDB
 	}
+	// #363: los agentes embebidos en NetGrip no se rearman por SSH (el
+	// servicio del agente es el propio panel).
+	if r.agents != nil {
+		if _, _, kind, _, ok := r.agents.Info(slug); ok && kind == "netgrip" {
+			return Result{}, ErrNetgripAgent
+		}
+	}
 	// El slug debe tener token registrado (si no, 404 como DELETE).
 	var exists int
 	if err := r.db.QueryRow("SELECT COUNT(*) FROM kv WHERE key = ?", TokenPrefix+slug).Scan(&exists); err != nil || exists == 0 {
@@ -325,6 +335,12 @@ func (s *Supervisor) CheckOnce() {
 			continue
 		}
 		res, err := s.rearmer.Rearm(slug)
+		if err == ErrNetgripAgent {
+			// #363: NetGrip embebido: ni rearme ni alerta de rearme (la caída
+			// ya la reporta el Dead Man's Switch como cualquier agente).
+			s.closeFailID(slug)
+			continue
+		}
 		if err != nil {
 			// ErrCooldown (rearme manual reciente), SSH caído, etc.:
 			// no consume el slot; se reintenta en el próximo tick.