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

feat(integrations): download, run and watch external router pushers from the app (#1677)

Nacho 1 месяц назад
Родитель
Сommit
a9fcdb2d77

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

@@ -693,9 +693,92 @@
     "orchestration": "Orchestration",
     "channelPlan": "Channels",
     "firmwareUpgrades": "Firmware upgrades",
+    "integrations": "Integrations",
     "help": "Help",
     "rack": "Rack"
   },
+  "integrations": {
+    "title": "Integrations",
+    "subtitle": "External router pushers",
+    "listTitle": "Configured integrations",
+    "loading": "Loading integrations...",
+    "emptyTitle": "No integrations yet",
+    "emptyDesc": "Add an external pusher for a router that NetPulse cannot reach directly.",
+    "fresh": "Fresh",
+    "never": "never",
+    "states": {
+      "running": "Running",
+      "stopped": "Stopped",
+      "error": "Error",
+      "installing": "Installing"
+    },
+    "ago": {
+      "s": "{{count}}s ago",
+      "min": "{{count}} min ago",
+      "h": "{{count}}h ago",
+      "d_one": "{{count}} day ago",
+      "d_other": "{{count}} days ago"
+    },
+    "actions": {
+      "start": "Start",
+      "stop": "Stop",
+      "update": "Update",
+      "check": "Check",
+      "delete": "Delete"
+    },
+    "confirm": {
+      "confirmDeleteTitle": "Delete integration?",
+      "confirmDeleteDesc": "Remove the {{slug}} integration? Its pusher is stopped if it is running."
+    },
+    "form": {
+      "add": "Add integration",
+      "selectVendor": "Select a vendor",
+      "fieldSlug": "Slug",
+      "fieldSlugHint": "Suggested from the host",
+      "fieldSlugInvalid": "Use lowercase letters, numbers and dashes",
+      "fieldVendor": "Vendor",
+      "fieldHost": "Host",
+      "fieldHostPlaceholder": "192.168.1.1",
+      "fieldUsername": "Username",
+      "fieldPassword": "Password",
+      "fieldInterval": "Interval (seconds)",
+      "fieldIntervalInvalid": "Interval must be between 10 and 86400 seconds",
+      "fieldArch": "Architecture",
+      "modeLocalHint": "This pusher runs on the NetPulse host.",
+      "modeSshHint": "In SSH mode the pusher is installed inside the router.",
+      "submit": "Create",
+      "creating": "Creating..."
+    },
+    "token": {
+      "tokenTitle": "Integration created",
+      "tokenDesc": "Copy the token now. It is shown only once and will not be shown again.",
+      "copyToken": "Copy token",
+      "copied": "Copied",
+      "copyHint": "Copy the token to a safe place."
+    },
+    "meta": {
+      "version": "Version",
+      "interval": "Interval",
+      "lastPush": "Last push"
+    },
+    "errors": {
+      "invalid_slug": "Invalid slug.",
+      "invalid_vendor": "Unknown vendor.",
+      "invalid_input": "Invalid input.",
+      "invalid_interval": "Invalid interval.",
+      "invalid_arch": "Unsupported architecture.",
+      "already_exists": "An integration with that slug already exists.",
+      "release_fetch_failed": "Could not fetch the release.",
+      "download_failed": "Download failed.",
+      "start_failed": "Could not start the pusher.",
+      "ssh_failed": "SSH connection failed.",
+      "ssh_unavailable": "SSH is not available for this vendor.",
+      "router_error": "The router reported an error.",
+      "not_found": "Integration not found.",
+      "db_error": "Database error.",
+      "generic": "Something went wrong."
+    }
+  },
   "roaming": {
     "subtitle": "Roaming and WiFi mesh status",
     "loading": "Loading usteer data…",

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

@@ -693,9 +693,92 @@
     "orchestration": "Orquestación",
     "channelPlan": "Canales",
     "firmwareUpgrades": "Actualizaciones",
+    "integrations": "Integraciones",
     "help": "Ayuda",
     "rack": "Rack"
   },
+  "integrations": {
+    "title": "Integraciones",
+    "subtitle": "Pushers externos de router",
+    "listTitle": "Integraciones configuradas",
+    "loading": "Cargando integraciones...",
+    "emptyTitle": "Aún no hay integraciones",
+    "emptyDesc": "Añade un pusher externo para un router al que NetPulse no llega directamente.",
+    "fresh": "Reciente",
+    "never": "nunca",
+    "states": {
+      "running": "En ejecución",
+      "stopped": "Detenido",
+      "error": "Error",
+      "installing": "Instalando"
+    },
+    "ago": {
+      "s": "hace {{count}} s",
+      "min": "hace {{count}} min",
+      "h": "hace {{count}} h",
+      "d_one": "hace {{count}} día",
+      "d_other": "hace {{count}} días"
+    },
+    "actions": {
+      "start": "Arrancar",
+      "stop": "Parar",
+      "update": "Actualizar",
+      "check": "Comprobar",
+      "delete": "Eliminar"
+    },
+    "confirm": {
+      "confirmDeleteTitle": "¿Eliminar la integración?",
+      "confirmDeleteDesc": "¿Eliminar la integración {{slug}}? Se detiene su pusher si está en marcha."
+    },
+    "form": {
+      "add": "Añadir integración",
+      "selectVendor": "Selecciona un proveedor",
+      "fieldSlug": "Slug",
+      "fieldSlugHint": "Se sugiere a partir del host",
+      "fieldSlugInvalid": "Usa minúsculas, números y guiones",
+      "fieldVendor": "Proveedor",
+      "fieldHost": "Host",
+      "fieldHostPlaceholder": "192.168.1.1",
+      "fieldUsername": "Usuario",
+      "fieldPassword": "Contraseña",
+      "fieldInterval": "Intervalo (segundos)",
+      "fieldIntervalInvalid": "El intervalo debe estar entre 10 y 86400 segundos",
+      "fieldArch": "Arquitectura",
+      "modeLocalHint": "Este pusher corre en el host de NetPulse.",
+      "modeSshHint": "En modo SSH el pusher se instala dentro del router.",
+      "submit": "Crear",
+      "creating": "Creando..."
+    },
+    "token": {
+      "tokenTitle": "Integración creada",
+      "tokenDesc": "Copia el token ahora. Solo se muestra una vez y no se volverá a mostrar.",
+      "copyToken": "Copiar token",
+      "copied": "Copiado",
+      "copyHint": "Guarda el token en un lugar seguro."
+    },
+    "meta": {
+      "version": "Versión",
+      "interval": "Intervalo",
+      "lastPush": "Último push"
+    },
+    "errors": {
+      "invalid_slug": "Slug inválido.",
+      "invalid_vendor": "Proveedor desconocido.",
+      "invalid_input": "Entrada inválida.",
+      "invalid_interval": "Intervalo inválido.",
+      "invalid_arch": "Arquitectura no soportada.",
+      "already_exists": "Ya existe una integración con ese slug.",
+      "release_fetch_failed": "No se pudo obtener la versión.",
+      "download_failed": "Falló la descarga.",
+      "start_failed": "No se pudo arrancar el pusher.",
+      "ssh_failed": "Falló la conexión SSH.",
+      "ssh_unavailable": "SSH no está disponible para este proveedor.",
+      "router_error": "El router devolvió un error.",
+      "not_found": "Integración no encontrada.",
+      "db_error": "Error de base de datos.",
+      "generic": "Algo salió mal."
+    }
+  },
   "roaming": {
     "subtitle": "Estado de la itinerancia WiFi y la malla WiFi",
     "loading": "Cargando datos de usteer…",

+ 2 - 0
app/src/App.tsx

@@ -18,6 +18,7 @@ import Reports from '@/pages/Reports'
 import Rack from '@/pages/Rack'
 import Orchestration from '@/pages/Orchestration'
 import FirmwareUpgrades from '@/pages/FirmwareUpgrades'
+import Integrations from '@/pages/Integrations'
 import Settings from '@/pages/Settings'
 import Help from '@/pages/Help'
 import Placeholder from '@/pages/Placeholder'
@@ -60,6 +61,7 @@ export default function App() {
         <Route path="roaming" element={<Roaming />} />
         <Route path="wifi/channel-plan" element={<ChannelPlan />} />
         <Route path="firmware-upgrades" element={<FirmwareUpgrades />} />
+        <Route path="integrations" element={<Integrations />} />
         <Route path="reports" element={<Reports />} />
         <Route path="orchestration" element={<Orchestration />} />
         <Route path="help" element={<Help />} />

+ 3 - 0
app/src/components/Layout.tsx

@@ -12,6 +12,7 @@ import {
   BarChart3,
   Bell,
   Bug,
+  Cable,
   ChevronsLeft,
   ChevronsRight,
   Cpu,
@@ -60,6 +61,7 @@ const NAV_ITEMS: NavItem[] = [
   { to: '/roaming', labelKey: 'nav.roaming', icon: Wifi },
   { to: '/wifi/channel-plan', labelKey: 'nav.channelPlan', icon: RadioTower },
   { to: '/firmware-upgrades', labelKey: 'nav.firmwareUpgrades', icon: Cpu, adminOnly: true },
+  { to: '/integrations', labelKey: 'nav.integrations', icon: Cable, adminOnly: true },
   { to: '/alerts', labelKey: 'nav.alerts', icon: Bell },
   { to: '/reports', labelKey: 'nav.reports', icon: BarChart3 },
   { to: '/orchestration', labelKey: 'nav.orchestration', icon: Wrench, adminOnly: true, badge: 'labs' },
@@ -94,6 +96,7 @@ const PAGE_TITLE_KEYS: [RegExp, string][] = [
   [/^\/roaming/, 'nav.roaming'],
   [/^\/wifi\/channel-plan/, 'nav.channelPlan'],
   [/^\/firmware-upgrades/, 'nav.firmwareUpgrades'],
+  [/^\/integrations/, 'nav.integrations'],
   [/^\/alerts/, 'nav.alerts'],
   [/^\/reports/, 'nav.reports'],
   [/^\/orchestration/, 'nav.orchestration'],

+ 117 - 0
app/src/lib/integrationsApi.ts

@@ -0,0 +1,117 @@
+// integrationsApi.ts - wire types and calls for the external router pushers
+// ("integrations") admin API. Mirrors rackApi.ts (req<T> + json helpers) but
+// the error envelope here carries a machine code in `error` plus an optional
+// human `message`, so ApiError keeps both for the i18n code -> key mapping.
+
+export interface Integration {
+  slug: string
+  vendor: string
+  mode: 'local' | 'ssh'
+  host: string
+  username: string
+  version: string
+  arch: string
+  intervalS: number
+  enabled: boolean
+  state: string
+  lastError: string
+  lastStartMs: number
+  lastPushMs: number
+  fresh: boolean
+}
+
+export interface Vendor {
+  id: string
+  mode: 'local' | 'ssh'
+  arches: string[]
+  tagPrefix: string
+  description: string
+}
+
+export interface CreateIntegrationInput {
+  slug: string
+  vendor: string
+  host: string
+  username: string
+  password: string
+  intervalS: number
+  arch?: string
+}
+
+/** Error carrying the backend machine code plus a human-readable message. */
+export class ApiError extends Error {
+  code?: string
+  constructor(message: string, code?: string) {
+    super(message)
+    this.name = 'ApiError'
+    this.code = code
+  }
+}
+
+async function req<T>(input: string, init?: RequestInit): Promise<T> {
+  const res = await fetch(input, init)
+  if (!res.ok) {
+    let code: string | undefined
+    let msg = `HTTP ${res.status}`
+    try {
+      const body = (await res.json()) as { error?: string; message?: string }
+      if (body?.error) code = body.error
+      if (body?.message) msg = body.message
+      else if (body?.error) msg = body.error
+    } catch {
+      /* default message */
+    }
+    throw new ApiError(msg, code)
+  }
+  if (res.status === 204) return undefined as T
+  return res.json() as Promise<T>
+}
+
+const json = (method: string, body: unknown): RequestInit => ({
+  method,
+  headers: { 'Content-Type': 'application/json' },
+  body: JSON.stringify(body),
+})
+
+export function fetchVendors(): Promise<{ vendors: Vendor[] }> {
+  return req<{ vendors: Vendor[] }>('/api/integrations/vendors')
+}
+
+export function fetchIntegrations(): Promise<{ integrations: Integration[] }> {
+  return req<{ integrations: Integration[] }>('/api/integrations')
+}
+
+export function createIntegration(
+  input: CreateIntegrationInput,
+): Promise<{ integration: Integration; token: string }> {
+  return req<{ integration: Integration; token: string }>('/api/integrations', json('POST', input))
+}
+
+export function startIntegration(slug: string): Promise<{ integration: Integration }> {
+  return req<{ integration: Integration }>(`/api/integrations/${encodeURIComponent(slug)}/start`, {
+    method: 'POST',
+  })
+}
+
+export function stopIntegration(slug: string): Promise<{ integration: Integration }> {
+  return req<{ integration: Integration }>(`/api/integrations/${encodeURIComponent(slug)}/stop`, {
+    method: 'POST',
+  })
+}
+
+export function updateIntegration(slug: string): Promise<{ integration: Integration }> {
+  return req<{ integration: Integration }>(`/api/integrations/${encodeURIComponent(slug)}/update`, {
+    method: 'POST',
+  })
+}
+
+export function checkIntegration(slug: string): Promise<{ integration: Integration; running: boolean }> {
+  return req<{ integration: Integration; running: boolean }>(
+    `/api/integrations/${encodeURIComponent(slug)}/check`,
+    { method: 'POST' },
+  )
+}
+
+export function deleteIntegration(slug: string): Promise<void> {
+  return req<void>(`/api/integrations/${encodeURIComponent(slug)}`, { method: 'DELETE' })
+}

+ 603 - 0
app/src/pages/Integrations.tsx

@@ -0,0 +1,603 @@
+import { useCallback, useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import type { TFunction } from 'i18next'
+import {
+  AlertTriangle,
+  Check,
+  Copy,
+  Loader2,
+  Play,
+  Plus,
+  RefreshCw,
+  RotateCw,
+  Search,
+  Square,
+  Trash2,
+} from 'lucide-react'
+import { cn, copyToClipboard } from '@/lib/utils'
+import { useAuth } from '@/data/AuthContext'
+import { useNetPulse } from '@/data/DataProvider'
+import { SectionHeader } from '@/components/SectionHeader'
+import { EmptyState } from '@/components/EmptyState'
+import { StatusPill, type PillTone } from '@/components/StatusPill'
+import {
+  AlertDialog,
+  AlertDialogAction,
+  AlertDialogCancel,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogFooter,
+  AlertDialogHeader,
+  AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
+import {
+  Dialog,
+  DialogContent,
+  DialogDescription,
+  DialogHeader,
+  DialogTitle,
+} from '@/components/ui/dialog'
+import {
+  ApiError,
+  checkIntegration,
+  createIntegration,
+  deleteIntegration,
+  fetchIntegrations,
+  fetchVendors,
+  startIntegration,
+  stopIntegration,
+  updateIntegration,
+} from '@/lib/integrationsApi'
+import type { CreateIntegrationInput, Integration, Vendor } from '@/lib/integrationsApi'
+
+const POLL_MS = 15_000
+const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/
+
+/** Maps a thrown error to a human message: known backend code -> i18n key,
+ *  falling back to the server message (or the raw code, or a generic label). */
+function errMessage(err: unknown, t: TFunction): string {
+  if (err instanceof ApiError) {
+    return t(`integrations.errors.${err.code ?? ''}`, { defaultValue: err.message })
+  }
+  if (err instanceof Error) return err.message
+  return t('integrations.errors.generic')
+}
+
+/** Lowercases a host and turns non-alphanumeric runs into dashes (auto slug). */
+function slugifyHost(host: string): string {
+  return host
+    .trim()
+    .toLowerCase()
+    .replace(/[^a-z0-9]+/g, '-')
+    .replace(/^-+|-+$/g, '')
+}
+
+function stateTone(state: string): PillTone {
+  if (state === 'running') return 'ok'
+  if (state === 'error') return 'danger'
+  return 'muted'
+}
+
+export default function Integrations() {
+  const { t, i18n } = useTranslation()
+  const auth = useAuth()
+  const { isDemo } = useNetPulse()
+  const isAdmin = auth?.role === 'admin'
+
+  const [vendors, setVendors] = useState<Vendor[]>([])
+  const [integrations, setIntegrations] = useState<Integration[]>([])
+  const [loading, setLoading] = useState(true)
+  const [refreshing, setRefreshing] = useState(false)
+  const [error, setError] = useState('')
+
+  // Formulario de alta.
+  const [showForm, setShowForm] = useState(false)
+  const [slug, setSlug] = useState('')
+  const [vendorId, setVendorId] = useState('')
+  const [host, setHost] = useState('')
+  const [username, setUsername] = useState('')
+  const [password, setPassword] = useState('')
+  const [intervalS, setIntervalS] = useState(30)
+  const [arch, setArch] = useState('')
+  const [submitting, setSubmitting] = useState(false)
+
+  // Token modal + confirmación de borrado + acciones en vuelo por fila.
+  const [token, setToken] = useState<string | null>(null)
+  const [tokenCopied, setTokenCopied] = useState(false)
+  const [confirmDelete, setConfirmDelete] = useState<Integration | null>(null)
+  const [busy, setBusy] = useState<Record<string, string>>({})
+
+  const load = useCallback(
+    async (silent = false) => {
+      if (silent) setRefreshing(true)
+      else setLoading(true)
+      try {
+        const [v, ints] = await Promise.all([fetchVendors(), fetchIntegrations()])
+        setVendors(v.vendors)
+        setIntegrations(ints.integrations)
+        setError('')
+      } catch (err) {
+        setError(errMessage(err, t))
+      } finally {
+        if (silent) setRefreshing(false)
+        else setLoading(false)
+      }
+    },
+    [t],
+  )
+
+  useEffect(() => {
+    if (isDemo) {
+      setLoading(false)
+      return
+    }
+    void load()
+  }, [load, isDemo])
+
+  // Polling cada 15 s mientras la página está montada (limpia en unmount).
+  useEffect(() => {
+    if (isDemo) return
+    const iv = window.setInterval(() => {
+      void load(true)
+    }, POLL_MS)
+    return () => window.clearInterval(iv)
+  }, [load, isDemo])
+
+  const selectedVendor = vendors.find((v) => v.id === vendorId)
+
+  const onHostChange = (value: string) => {
+    setHost(value)
+    if (slug.trim() === '') setSlug(slugifyHost(value))
+  }
+
+  const onVendorChange = (value: string) => {
+    setVendorId(value)
+    const v = vendors.find((x) => x.id === value)
+    setArch(v && v.arches.length > 0 ? (v.arches[0] ?? '') : '')
+  }
+
+  const slugInvalid = slug.trim() !== '' && !SLUG_RE.test(slug.trim())
+  const interval = Number(intervalS)
+  const intervalInvalid = !Number.isFinite(interval) || interval < 10 || interval > 86_400
+
+  const submit = async (e: React.FormEvent) => {
+    e.preventDefault()
+    if (submitting) return
+    if (!vendorId || !host.trim() || !SLUG_RE.test(slug.trim()) || intervalInvalid) return
+    setSubmitting(true)
+    setError('')
+    try {
+      const input: CreateIntegrationInput = {
+        slug: slug.trim(),
+        vendor: vendorId,
+        host: host.trim(),
+        username: username.trim(),
+        password,
+        intervalS: interval,
+      }
+      if (selectedVendor && selectedVendor.arches.length > 1 && arch) {
+        input.arch = arch
+      } else if (selectedVendor && selectedVendor.arches.length === 1) {
+        input.arch = selectedVendor.arches[0]
+      }
+      const res = await createIntegration(input)
+      setToken(res.token)
+      setShowForm(false)
+      setSlug('')
+      setHost('')
+      setUsername('')
+      setPassword('')
+      setIntervalS(30)
+      setArch('')
+      setVendorId('')
+      await load(true)
+    } catch (err) {
+      setError(errMessage(err, t))
+    } finally {
+      setSubmitting(false)
+    }
+  }
+
+  const runAction = async (slug: string, key: string, fn: () => Promise<unknown>) => {
+    setBusy((prev) => ({ ...prev, [slug]: key }))
+    setError('')
+    try {
+      await fn()
+      await load(true)
+    } catch (err) {
+      setError(errMessage(err, t))
+    } finally {
+      setBusy((prev) => {
+        const next = { ...prev }
+        delete next[slug]
+        return next
+      })
+    }
+  }
+
+  const doDelete = async (it: Integration) => {
+    await runAction(it.slug, 'delete', () => deleteIntegration(it.slug))
+    setConfirmDelete(null)
+  }
+
+  const copyToken = async () => {
+    if (!token) return
+    const ok = await copyToClipboard(token)
+    setTokenCopied(ok)
+    window.setTimeout(() => setTokenCopied(false), 1500)
+  }
+
+  /** "hace X min" (unidades i18n) o fecha corta para pushes muy antiguos. */
+  const lastPushLabel = (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')
+    const sec = Math.floor(age / 1000)
+    if (sec < 60) return t('integrations.ago.s', { count: sec })
+    const min = Math.floor(sec / 60)
+    if (min < 60) return t('integrations.ago.min', { count: min })
+    const h = Math.floor(min / 60)
+    if (h < 24) return t('integrations.ago.h', { count: h })
+    const d = Math.floor(h / 24)
+    if (d < 7) return t('integrations.ago.d', { count: d })
+    return new Date(ms).toLocaleDateString(i18n.language, { day: 'numeric', month: 'short' })
+  }
+
+  return (
+    <div className="space-y-4 md:space-y-5">
+      <header className="flex flex-wrap items-start justify-between gap-4">
+        <div>
+          <h1 className="font-display text-h1 text-text-primary">{t('integrations.title')}</h1>
+          <p className="mt-0.5 text-sm text-text-secondary">{t('integrations.subtitle')}</p>
+        </div>
+        <div className="flex items-center gap-2">
+          <button
+            type="button"
+            onClick={() => void load(true)}
+            disabled={refreshing}
+            className="inline-flex h-9 items-center gap-2 rounded-lg border border-border bg-surface px-3 text-sm font-medium text-text-primary transition-colors hover:bg-elevated disabled:opacity-50"
+          >
+            <RefreshCw className={cn('h-4 w-4', refreshing && 'animate-spin')} strokeWidth={1.75} />
+            {t('common.refresh')}
+          </button>
+          <button
+            type="button"
+            aria-expanded={showForm}
+            onClick={() => setShowForm((v) => !v)}
+            className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-accent bg-accent-soft px-3 text-sm font-medium text-accent transition-colors hover:brightness-105"
+          >
+            <Plus className="h-4 w-4" strokeWidth={1.75} />
+            {t('integrations.form.add')}
+          </button>
+        </div>
+      </header>
+
+      {!isAdmin && (
+        <div className="flex items-start gap-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm text-amber-700 dark:text-amber-300">
+          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
+          <span>{t('common.adminOnly')}</span>
+        </div>
+      )}
+
+      {error && (
+        <div className="flex items-start gap-3 rounded-xl border border-rose-500/40 bg-rose-500/10 px-4 py-3 text-sm text-rose-600 dark:text-rose-400">
+          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
+          <span>{error}</span>
+        </div>
+      )}
+
+      {showForm && (
+        <form onSubmit={(e) => void submit(e)} className="rounded-2xl border border-border bg-surface p-5">
+          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+            <label className="block">
+              <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldSlug')}</span>
+              <input
+                type="text"
+                value={slug}
+                onChange={(e) => setSlug(e.target.value)}
+                placeholder={t('integrations.form.fieldSlugHint')}
+                aria-label={t('integrations.form.fieldSlug')}
+                aria-invalid={slugInvalid}
+                spellCheck={false}
+                className={cn(
+                  'mt-1 w-full rounded-lg border bg-canvas px-3 py-2 font-mono text-mono-sm text-text-primary placeholder:text-text-muted focus:outline-none',
+                  slugInvalid ? 'border-danger' : 'border-border focus:border-accent',
+                )}
+              />
+              {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>
+              <select
+                value={vendorId}
+                onChange={(e) => onVendorChange(e.target.value)}
+                aria-label={t('integrations.form.fieldVendor')}
+                className="mt-1 h-[38px] w-full rounded-lg border border-border bg-canvas px-3 text-sm text-text-primary focus:border-accent focus:outline-none"
+              >
+                <option value="">{t('integrations.form.selectVendor')}</option>
+                {vendors.map((v) => (
+                  <option key={v.id} value={v.id}>
+                    {v.id}
+                  </option>
+                ))}
+              </select>
+            </label>
+            <label className="block">
+              <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldHost')}</span>
+              <input
+                type="text"
+                value={host}
+                onChange={(e) => onHostChange(e.target.value)}
+                placeholder={t('integrations.form.fieldHostPlaceholder')}
+                aria-label={t('integrations.form.fieldHost')}
+                className="mt-1 w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:border-accent focus:outline-none"
+              />
+            </label>
+            <label className="block">
+              <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldUsername')}</span>
+              <input
+                type="text"
+                value={username}
+                onChange={(e) => setUsername(e.target.value)}
+                aria-label={t('integrations.form.fieldUsername')}
+                autoComplete="off"
+                className="mt-1 w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
+              />
+            </label>
+            <label className="block">
+              <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldPassword')}</span>
+              <input
+                type="password"
+                value={password}
+                onChange={(e) => setPassword(e.target.value)}
+                aria-label={t('integrations.form.fieldPassword')}
+                autoComplete="new-password"
+                className="mt-1 w-full rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary focus:border-accent focus:outline-none"
+              />
+            </label>
+            <label className="block">
+              <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldInterval')}</span>
+              <input
+                type="number"
+                min={10}
+                max={86_400}
+                value={intervalS}
+                onChange={(e) => setIntervalS(Number(e.target.value))}
+                aria-label={t('integrations.form.fieldInterval')}
+                aria-invalid={intervalInvalid}
+                className={cn(
+                  'mt-1 w-full rounded-lg border bg-canvas px-3 py-2 text-sm text-text-primary focus:outline-none',
+                  intervalInvalid ? 'border-danger' : 'border-border focus:border-accent',
+                )}
+              />
+              {intervalInvalid && <span className="mt-1 block text-xs text-danger">{t('integrations.form.fieldIntervalInvalid')}</span>}
+            </label>
+            {selectedVendor && selectedVendor.arches.length > 1 && (
+              <label className="block">
+                <span className="text-label uppercase text-text-muted">{t('integrations.form.fieldArch')}</span>
+                <select
+                  value={arch}
+                  onChange={(e) => setArch(e.target.value)}
+                  aria-label={t('integrations.form.fieldArch')}
+                  className="mt-1 h-[38px] w-full rounded-lg border border-border bg-canvas px-3 text-sm text-text-primary focus:border-accent focus:outline-none"
+                >
+                  {selectedVendor.arches.map((a) => (
+                    <option key={a} value={a}>
+                      {a}
+                    </option>
+                  ))}
+                </select>
+              </label>
+            )}
+          </div>
+
+          {selectedVendor && (
+            <p className="mt-3 text-caption text-text-muted">
+              {selectedVendor.mode === 'ssh'
+                ? t('integrations.form.modeSshHint')
+                : t('integrations.form.modeLocalHint')}
+            </p>
+          )}
+
+          <div className="mt-3 flex items-center gap-2">
+            <button
+              type="submit"
+              disabled={submitting || !vendorId || !host.trim() || slugInvalid || intervalInvalid}
+              className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-accent px-3 text-sm font-medium text-canvas transition-opacity hover:opacity-90 disabled:opacity-40"
+            >
+              {submitting && <Loader2 className="h-4 w-4 animate-spin" strokeWidth={1.75} />}
+              {submitting ? t('integrations.form.creating') : t('integrations.form.submit')}
+            </button>
+            <button
+              type="button"
+              onClick={() => setShowForm(false)}
+              className="inline-flex h-9 items-center rounded-lg border border-border px-3 text-sm font-medium text-text-secondary transition-colors hover:text-text-primary"
+            >
+              {t('common.cancel')}
+            </button>
+          </div>
+        </form>
+      )}
+
+      <SectionHeader title={t('integrations.listTitle')} className="mt-6" />
+
+      {loading ? (
+        <p className="text-caption text-text-muted">{t('integrations.loading')}</p>
+      ) : integrations.length === 0 ? (
+        <div className="rounded-2xl border border-border bg-surface">
+          <EmptyState
+            image="/empty-devices.svg"
+            title={t('integrations.emptyTitle')}
+            description={t('integrations.emptyDesc')}
+          />
+        </div>
+      ) : (
+        <div className="space-y-3">
+          {integrations.map((it) => {
+            const running = it.state === 'running'
+            const installing = it.state === 'installing'
+            const isBusy = busy[it.slug] !== undefined
+            return (
+              <div key={it.slug} className="rounded-2xl border border-border bg-surface p-4">
+                <div className="flex items-start justify-between gap-3">
+                  <div className="min-w-0">
+                    <div className="flex flex-wrap items-center gap-2">
+                      <span className="font-mono text-sm font-medium text-text-primary">{it.slug}</span>
+                      <StatusPill
+                        tone={stateTone(it.state)}
+                        label={t(`integrations.states.${it.state}`, { defaultValue: it.state })}
+                      />
+                      {it.fresh && (
+                        <span className="rounded-full bg-ok/10 px-2 py-0.5 text-caption font-semibold uppercase tracking-[0.06em] text-ok">
+                          {t('integrations.fresh')}
+                        </span>
+                      )}
+                    </div>
+                    <div className="mt-1 font-mono text-caption text-text-muted">{it.host}</div>
+                    {it.lastError && (
+                      <div className="mt-1 text-xs text-danger">{it.lastError}</div>
+                    )}
+                  </div>
+                  <div className="flex shrink-0 items-center gap-1.5">
+                    <button
+                      type="button"
+                      onClick={() => void runAction(it.slug, 'start', () => startIntegration(it.slug))}
+                      disabled={running || installing || isBusy}
+                      aria-label={t('integrations.actions.start')}
+                      title={t('integrations.actions.start')}
+                      className="flex h-7 w-7 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:opacity-50"
+                    >
+                      {busy[it.slug] === 'start' ? (
+                        <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
+                      ) : (
+                        <Play className="h-3.5 w-3.5" strokeWidth={1.75} />
+                      )}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => void runAction(it.slug, 'stop', () => stopIntegration(it.slug))}
+                      disabled={!running || installing || isBusy}
+                      aria-label={t('integrations.actions.stop')}
+                      title={t('integrations.actions.stop')}
+                      className="flex h-7 w-7 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:opacity-50"
+                    >
+                      {busy[it.slug] === 'stop' ? (
+                        <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
+                      ) : (
+                        <Square className="h-3.5 w-3.5" strokeWidth={1.75} />
+                      )}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => void runAction(it.slug, 'update', () => updateIntegration(it.slug))}
+                      disabled={installing || isBusy}
+                      aria-label={t('integrations.actions.update')}
+                      title={t('integrations.actions.update')}
+                      className="flex h-7 w-7 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:opacity-50"
+                    >
+                      {busy[it.slug] === 'update' ? (
+                        <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
+                      ) : (
+                        <RotateCw className="h-3.5 w-3.5" strokeWidth={1.75} />
+                      )}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => void runAction(it.slug, 'check', () => checkIntegration(it.slug))}
+                      disabled={isBusy}
+                      aria-label={t('integrations.actions.check')}
+                      title={t('integrations.actions.check')}
+                      className="flex h-7 w-7 items-center justify-center rounded-lg border border-border text-text-muted transition-colors duration-150 hover:border-accent/40 hover:text-accent disabled:opacity-50"
+                    >
+                      {busy[it.slug] === 'check' ? (
+                        <Loader2 className="h-3.5 w-3.5 animate-spin" strokeWidth={1.75} />
+                      ) : (
+                        <Search className="h-3.5 w-3.5" strokeWidth={1.75} />
+                      )}
+                    </button>
+                    <button
+                      type="button"
+                      onClick={() => setConfirmDelete(it)}
+                      disabled={isBusy}
+                      aria-label={t('integrations.actions.delete')}
+                      title={t('integrations.actions.delete')}
+                      className="flex h-7 w-7 items-center justify-center rounded-lg border border-danger/30 text-danger transition-colors duration-150 hover:border-danger/60 hover:bg-danger/10 disabled:opacity-50"
+                    >
+                      <Trash2 className="h-3.5 w-3.5" strokeWidth={1.75} />
+                    </button>
+                  </div>
+                </div>
+                <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-caption text-text-muted">
+                  <span>
+                    {t('integrations.form.fieldVendor')}: {it.vendor}
+                  </span>
+                  <span>
+                    {t('integrations.meta.version')}: {it.version || '-'}
+                  </span>
+                  <span>
+                    {t('integrations.meta.interval')}: {it.intervalS} s
+                  </span>
+                  <span>
+                    {t('integrations.meta.lastPush')}: {lastPushLabel(it.lastPushMs)}
+                  </span>
+                </div>
+              </div>
+            )
+          })}
+        </div>
+      )}
+
+      <Dialog open={token !== null} onOpenChange={(open) => !open && setToken(null)}>
+        {token !== null && (
+          <DialogContent className="max-w-md">
+            <DialogHeader>
+              <DialogTitle>{t('integrations.token.tokenTitle')}</DialogTitle>
+              <DialogDescription>{t('integrations.token.tokenDesc')}</DialogDescription>
+            </DialogHeader>
+            <div className="flex items-center gap-2 rounded-lg border border-border bg-canvas px-3 py-2">
+              <code className="min-w-0 flex-1 break-all font-mono text-mono-sm text-text-primary">{token}</code>
+              <button
+                type="button"
+                onClick={() => void copyToken()}
+                aria-label={t('integrations.token.copyToken')}
+                className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+              >
+                {tokenCopied ? (
+                  <Check className="h-4 w-4 text-ok" strokeWidth={1.75} />
+                ) : (
+                  <Copy className="h-4 w-4" strokeWidth={1.75} />
+                )}
+              </button>
+            </div>
+            <p className="text-caption text-text-muted">
+              {tokenCopied ? t('integrations.token.copied') : t('integrations.token.copyHint')}
+            </p>
+          </DialogContent>
+        )}
+      </Dialog>
+
+      <AlertDialog open={confirmDelete !== null} onOpenChange={(open) => !open && setConfirmDelete(null)}>
+        <AlertDialogContent>
+          <AlertDialogHeader>
+            <AlertDialogTitle>{t('integrations.confirm.confirmDeleteTitle')}</AlertDialogTitle>
+            <AlertDialogDescription>
+              {t('integrations.confirm.confirmDeleteDesc', { slug: confirmDelete?.slug ?? '' })}
+            </AlertDialogDescription>
+          </AlertDialogHeader>
+          <AlertDialogFooter>
+            <AlertDialogCancel>{t('common.cancel')}</AlertDialogCancel>
+            <AlertDialogAction
+              onClick={() => {
+                if (confirmDelete) void doDelete(confirmDelete)
+              }}
+              className="bg-danger text-canvas hover:bg-danger/90"
+            >
+              <Trash2 className="mr-1.5 h-4 w-4" strokeWidth={2} />
+              {t('integrations.actions.delete')}
+            </AlertDialogAction>
+          </AlertDialogFooter>
+        </AlertDialogContent>
+      </AlertDialog>
+    </div>
+  )
+}

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

@@ -55,6 +55,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/push"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
 	"github.com/gnacho/netpulse/server-go/internal/roamevents"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
@@ -759,6 +760,10 @@ func run() error {
 		log.Printf("[netpulse] aviso: NETPULSE_MCP_ENABLED=1 pero no hay token store; MCP desactivado")
 	}
 
+	// Supervisor de pushers externos (#1674): procesos en memoria como usuario
+	// netpulse (sin systemd). La raíz de datos vive bajo DATA_DIR/integrations.
+	integrationsMgr := rintegration.NewManager(filepath.Join(cfg.DataDir, "integrations"))
+
 	handler := httpapi.NewHandler(httpapi.Deps{
 		Config:           cfg,
 		DB:               dbHandle,
@@ -790,8 +795,9 @@ func run() error {
 		LastOverview: func() *adapters.Overview {
 			return p.LastOverview()
 		},
-		PollNow: p.PollNow,
-		Started: serverStarted,
+		PollNow:      p.PollNow,
+		Started:      serverStarted,
+		Integrations: integrationsMgr,
 	})
 
 	// Envolver el handler con GET /fingerprint (sin auth) si on-box.
@@ -909,6 +915,7 @@ func run() error {
 			rearmSup.Stop()
 		}
 		p.Stop()
+		integrationsMgr.StopAll()
 		upd.Stop()
 		fwScheduler.Stop()
 		if fwReleases != nil {

+ 24 - 0
server-go/internal/db/db.go

@@ -476,6 +476,30 @@ CREATE TABLE IF NOT EXISTS rack_cables (
 CREATE INDEX IF NOT EXISTS idx_rack_cables_from ON rack_cables(from_mount);
 CREATE INDEX IF NOT EXISTS idx_rack_cables_to ON rack_cables(to_mount);
 
+-- External router integrations (#1674): pushers de routers externos
+-- (MikroTik RouterOS, Asuswrt) gestionados desde la app. El slug es el id
+-- del router external asociado (push autenticado por Bearer token de agente,
+-- agent.token.<slug>). La contraseña nunca se persiste: vive en el fichero
+-- de entorno <data>/integrations/<slug>.env (0600).
+CREATE TABLE IF NOT EXISTS router_integrations (
+  slug TEXT PRIMARY KEY,
+  vendor TEXT NOT NULL,
+  mode TEXT NOT NULL,
+  host TEXT NOT NULL,
+  username TEXT NOT NULL,
+  version TEXT NOT NULL DEFAULT '',
+  asset TEXT NOT NULL DEFAULT '',
+  arch TEXT NOT NULL,
+  interval_s INTEGER NOT NULL,
+  enabled INTEGER NOT NULL DEFAULT 0,
+  state TEXT NOT NULL DEFAULT 'pending',
+  last_error TEXT NOT NULL DEFAULT '',
+  last_start_ms INTEGER NOT NULL DEFAULT 0,
+  created_at INTEGER NOT NULL,
+  updated_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_router_integrations_vendor ON router_integrations(vendor);
+
 `
 
 // DB envuelve *sql.DB con los jobs y helpers de paridad.

+ 619 - 0
server-go/internal/httpapi/integrations.go

@@ -0,0 +1,619 @@
+// integrations.go — API de integraciones externas de routers (#1674):
+// pushers de routers externos (MikroTik RouterOS, Asuswrt) gestionados desde
+// la app con el contrato de agente externo. El slug de la integración es el
+// id del router external asociado, así el push del pusher (POST
+// /api/ingest/agent con Bearer token) se atribuye a la misma unidad.
+package httpapi
+
+import (
+	"fmt"
+	"net/http"
+	"path/filepath"
+	"sort"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
+	"github.com/gnacho/netpulse/server-go/internal/routerstore"
+)
+
+// integrationItem es la vista HTTP de una integración (nunca la contraseña).
+type integrationItem struct {
+	Slug        string `json:"slug"`
+	Vendor      string `json:"vendor"`
+	Mode        string `json:"mode"`
+	Host        string `json:"host"`
+	Username    string `json:"username"`
+	Version     string `json:"version"`
+	Arch        string `json:"arch"`
+	IntervalS   int    `json:"intervalS"`
+	Enabled     bool   `json:"enabled"`
+	State       string `json:"state"`
+	LastError   string `json:"lastError"`
+	LastStartMs int64  `json:"lastStartMs"`
+	LastPushMs  int64  `json:"lastPushMs"`
+	Fresh       bool   `json:"fresh"`
+}
+
+// vendorView es la vista HTTP del manifiesto de un vendor.
+type vendorView struct {
+	ID          string   `json:"id"`
+	Mode        string   `json:"mode"`
+	Arches      []string `json:"arches"`
+	TagPrefix   string   `json:"tagPrefix"`
+	Description string   `json:"description"`
+}
+
+// registerIntegrationRoutes registra las rutas /api/integrations/*. Todas
+// 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("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)))
+	mux.Handle("POST /api/integrations/{slug}/stop", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationStop)))
+	mux.Handle("POST /api/integrations/{slug}/check", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationCheck)))
+	mux.Handle("POST /api/integrations/{slug}/update", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationUpdate)))
+	mux.Handle("DELETE /api/integrations/{slug}", auth.RequireAdmin(http.HandlerFunc(s.handleIntegrationDelete)))
+}
+
+func (s *server) handleIntegrationsVendors(w http.ResponseWriter, _ *http.Request) {
+	vs := rintegration.Vendors()
+	out := make([]vendorView, 0, len(vs))
+	for _, v := range vs {
+		out = append(out, vendorView{
+			ID: v.ID, Mode: v.Mode, Arches: v.Arches,
+			TagPrefix: v.TagPrefix, Description: v.Description,
+		})
+	}
+	writeJSON(w, http.StatusOK, map[string]any{"vendors": out})
+}
+
+func (s *server) integrationsStore() *rintegration.Store {
+	return rintegration.NewStore(s.db.DB)
+}
+
+func (s *server) integrationFetcher() *rintegration.Fetcher {
+	if s.integrations != nil {
+		return s.integrations.Fetch()
+	}
+	return rintegration.NewFetcher()
+}
+
+func (s *server) getIntegrationRow(slug string) (rintegration.Row, bool) {
+	if s.db == nil {
+		return rintegration.Row{}, false
+	}
+	return s.integrationsStore().Get(slug)
+}
+
+// integrationLastPushMs lee agent.last_push_ts.<slug> (segundos unix) y lo
+// devuelve en milisegundos, 0 si nunca empujó.
+func (s *server) integrationLastPushMs(slug string) int64 {
+	if s.db == nil {
+		return 0
+	}
+	sec, err := strconv.ParseInt(kvGet(s.db.DB, "agent.last_push_ts."+slug), 10, 64)
+	if err != nil {
+		return 0
+	}
+	return sec * 1000
+}
+
+func (s *server) integrationItemOf(row rintegration.Row) integrationItem {
+	lastPush := s.integrationLastPushMs(row.Slug)
+	fresh := false
+	if lastPush > 0 && row.IntervalS > 0 {
+		fresh = time.Now().UnixMilli()-lastPush <= int64(row.IntervalS)*3*1000
+	}
+	return integrationItem{
+		Slug: row.Slug, Vendor: row.Vendor, Mode: row.Mode, Host: row.Host,
+		Username: row.Username, Version: row.Version, Arch: row.Arch,
+		IntervalS: row.IntervalS, Enabled: row.Enabled, State: row.State,
+		LastError: row.LastError, LastStartMs: row.LastStartMs,
+		LastPushMs: lastPush, Fresh: fresh,
+	}
+}
+
+func (s *server) integrationList() []integrationItem {
+	if s.db == nil {
+		return []integrationItem{}
+	}
+	rows, err := s.integrationsStore().List()
+	if err != nil {
+		return []integrationItem{}
+	}
+	out := make([]integrationItem, 0, len(rows))
+	for _, row := range rows {
+		out = append(out, s.integrationItemOf(row))
+	}
+	return out
+}
+
+func (s *server) broadcastIntegrations() {
+	if s.hub != nil {
+		s.hub.Broadcast("integrations", map[string]any{"integrations": s.integrationList()})
+	}
+}
+
+func (s *server) handleIntegrationsList(w http.ResponseWriter, _ *http.Request) {
+	writeJSON(w, http.StatusOK, map[string]any{"integrations": s.integrationList()})
+}
+
+type integrationCreateBody struct {
+	Slug      string `json:"slug"`
+	Vendor    string `json:"vendor"`
+	Host      string `json:"host"`
+	Username  string `json:"username"`
+	Password  string `json:"password"`
+	IntervalS int    `json:"intervalS"`
+	Arch      string `json:"arch"`
+}
+
+func (s *server) handleIntegrationsCreate(w http.ResponseWriter, r *http.Request) {
+	if s.db == nil {
+		writeError(w, http.StatusInternalServerError, "db_error")
+		return
+	}
+	var body integrationCreateBody
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", `Se esperaba { "slug", "vendor", "host", "username", "password", "intervalS", "arch"? }`)
+		return
+	}
+	if !agentSlugRe.MatchString(body.Slug) {
+		writeError(w, http.StatusBadRequest, "invalid_slug", "slug must match ^[a-z0-9][a-z0-9-]{0,63}$")
+		return
+	}
+	vendor, ok := rintegration.LookupVendor(body.Vendor)
+	if !ok {
+		writeError(w, http.StatusBadRequest, "invalid_vendor", "unknown vendor")
+		return
+	}
+	if body.Host == "" || body.Username == "" || body.Password == "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "host, username and password are required")
+		return
+	}
+	if body.IntervalS < 10 || body.IntervalS > 86400 {
+		writeError(w, http.StatusBadRequest, "invalid_interval", "intervalS must be between 10 and 86400")
+		return
+	}
+	arch := body.Arch
+	if arch == "" {
+		arch = vendor.Arches[0]
+	} else if !vendorSupportsArch(vendor, arch) {
+		writeError(w, http.StatusBadRequest, "invalid_arch", "unsupported arch "+arch)
+		return
+	}
+
+	store := s.integrationsStore()
+	if _, exists := store.Get(body.Slug); exists {
+		writeError(w, http.StatusConflict, "already_exists", "integration already exists")
+		return
+	}
+
+	// Resolver y descargar el último release verificado. En modo local se
+	// extrae el binario aquí (corre en este host); en modo ssh solo se
+	// verifica: el router descarga el asset él mismo.
+	fetch := s.integrationFetcher()
+	res, err := fetch.ResolveLatest(vendor, arch)
+	if err != nil {
+		writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
+		return
+	}
+	binPath := ""
+	if vendor.Mode == "local" {
+		if s.integrations == nil {
+			writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
+			return
+		}
+		installDir := filepath.Join(s.integrations.Dir(), body.Slug)
+		binPath, err = fetch.Download(res, vendor.Binary, installDir)
+		if err != nil {
+			writeError(w, http.StatusBadGateway, "download_failed", err.Error())
+			return
+		}
+	} else {
+		if s.pool == nil {
+			writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
+			return
+		}
+		if err := fetch.Verify(res); err != nil {
+			writeError(w, http.StatusBadGateway, "download_failed", err.Error())
+			return
+		}
+	}
+
+	now := time.Now().UnixMilli()
+	row := rintegration.Row{
+		Slug: body.Slug, Vendor: vendor.ID, Mode: vendor.Mode, Host: body.Host,
+		Username: body.Username, Version: res.Version, Asset: res.AssetName,
+		Arch: arch, IntervalS: body.IntervalS, Enabled: true, State: "pending",
+		CreatedAt: now, UpdatedAt: now,
+	}
+	if err := store.Upsert(row); err != nil {
+		writeError(w, http.StatusInternalServerError, "db_error")
+		return
+	}
+
+	// Router external cuyo id es el slug (push autenticado por token de
+	// agente, agent.token.<slug>).
+	router, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
+		Name: body.Slug, Host: body.Host, Type: "external", AgentOnly: true,
+	})
+	if err != nil || router.ID != body.Slug {
+		_ = store.Delete(body.Slug)
+		writeError(w, http.StatusInternalServerError, "router_error")
+		return
+	}
+	s.syncRouters()
+
+	rollback := func() {
+		if vendor.Mode == "local" && s.integrations != nil {
+			_ = s.integrations.Stop(body.Slug)
+			_ = s.integrations.Cleanup(body.Slug)
+		}
+		_ = routerstore.RemoveRouter(s.db.DB, body.Slug)
+		s.syncRouters()
+		_ = store.Delete(body.Slug)
+	}
+
+	serverURL := s.agentBaseURL(r)
+	token, err := s.rotateAgentTokenAtomic(body.Slug, func(tok string) error {
+		env := s.pusherEnv(vendor, row, body.Password, serverURL, tok)
+		if vendor.Mode == "local" {
+			return s.integrations.Start(body.Slug, env, binPath)
+		}
+		return s.runSSHInstall(vendor, row, env, res.URL, res.SHA256)
+	})
+	if err != nil {
+		rollback()
+		writeError(w, http.StatusBadGateway, "start_failed", err.Error())
+		return
+	}
+
+	_ = store.SetState(body.Slug, "running", "")
+	_ = store.SetLastStart(body.Slug, time.Now().UnixMilli())
+	s.broadcastIntegrations()
+
+	item, _ := s.getIntegrationRow(body.Slug)
+	writeJSON(w, http.StatusCreated, map[string]any{
+		"integration": s.integrationItemOf(item),
+		"token":       token,
+	})
+}
+
+func vendorSupportsArch(v rintegration.Vendor, arch string) bool {
+	for _, a := range v.Arches {
+		if a == arch {
+			return true
+		}
+	}
+	return false
+}
+
+// pusherEnv construye el entorno del pusher. En modo ssh el pusher corre en el
+// propio router, así que el host del dispositivo es la propia unidad
+// (127.0.0.1) en lugar del host SSH de la tabla.
+func (s *server) pusherEnv(v rintegration.Vendor, row rintegration.Row, password, serverURL, token string) map[string]string {
+	prefix := strings.ToUpper(v.ID) + "_"
+	host := row.Host
+	if v.Mode == "ssh" {
+		host = "127.0.0.1"
+	}
+	return map[string]string{
+		prefix + "HOST":     host,
+		prefix + "USER":     row.Username,
+		prefix + "PASS":     password,
+		prefix + "INSECURE": "1",
+		"NETPULSE_SERVER":   serverURL,
+		"NETPULSE_TOKEN":    token,
+		"NETPULSE_SLUG":     row.Slug,
+		"NETPULSE_INTERVAL": strconv.Itoa(row.IntervalS),
+	}
+}
+
+func (s *server) runSSHInstall(v rintegration.Vendor, row rintegration.Row, env map[string]string, assetURL, sha256 string) error {
+	_, err := s.pool.Run(row.Host, sshInstallScript(v, env, assetURL, sha256), 300*time.Second)
+	return err
+}
+
+func (s *server) handleIntegrationStart(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	row, ok := s.getIntegrationRow(slug)
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	if !ok {
+		writeError(w, http.StatusInternalServerError, "invalid_vendor")
+		return
+	}
+	store := s.integrationsStore()
+	if vendor.Mode == "local" {
+		if s.integrations == nil {
+			writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
+			return
+		}
+		if !s.integrations.Running(slug) {
+			binPath := filepath.Join(s.integrations.Dir(), slug, vendor.Binary)
+			if err := s.integrations.Start(slug, nil, binPath); err != nil && err != rintegration.ErrAlreadyRunning {
+				writeError(w, http.StatusBadGateway, "start_failed", err.Error())
+				return
+			}
+		}
+	} else {
+		if s.pool == nil {
+			writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
+			return
+		}
+		if _, err := s.pool.Run(row.Host, sshServiceScript(vendor, "restart"), 60*time.Second); err != nil {
+			writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
+			return
+		}
+	}
+	_ = store.SetState(slug, "running", "")
+	_ = store.SetLastStart(slug, time.Now().UnixMilli())
+	s.broadcastIntegrations()
+	item, _ := s.getIntegrationRow(slug)
+	writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
+}
+
+func (s *server) handleIntegrationStop(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	row, ok := s.getIntegrationRow(slug)
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	if !ok {
+		writeError(w, http.StatusInternalServerError, "invalid_vendor")
+		return
+	}
+	if vendor.Mode == "local" {
+		if s.integrations != nil {
+			_ = s.integrations.Stop(slug) // ErrNotRunning es no-op aquí
+		}
+	} else if s.pool != nil {
+		_, _ = s.pool.Run(row.Host, sshServiceScript(vendor, "stop"), 60*time.Second)
+	}
+	_ = s.integrationsStore().SetState(slug, "stopped", "")
+	s.broadcastIntegrations()
+	item, _ := s.getIntegrationRow(slug)
+	writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
+}
+
+func (s *server) handleIntegrationCheck(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	row, ok := s.getIntegrationRow(slug)
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	if !ok {
+		writeError(w, http.StatusInternalServerError, "invalid_vendor")
+		return
+	}
+	running := false
+	if vendor.Mode == "local" {
+		running = s.integrations != nil && s.integrations.Running(slug)
+	} else if s.pool != nil {
+		_, err := s.pool.Run(row.Host, sshServiceScript(vendor, "check"), 30*time.Second)
+		running = err == nil
+	}
+	writeJSON(w, http.StatusOK, map[string]any{
+		"integration": s.integrationItemOf(row),
+		"running":     running,
+	})
+}
+
+func (s *server) handleIntegrationUpdate(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	row, ok := s.getIntegrationRow(slug)
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	vendor, ok := rintegration.LookupVendor(row.Vendor)
+	if !ok {
+		writeError(w, http.StatusInternalServerError, "invalid_vendor")
+		return
+	}
+	fetch := s.integrationFetcher()
+	res, err := fetch.ResolveLatest(vendor, row.Arch)
+	if err != nil {
+		writeError(w, http.StatusBadGateway, "release_fetch_failed", err.Error())
+		return
+	}
+	store := s.integrationsStore()
+	if vendor.Mode == "local" {
+		if s.integrations == nil {
+			writeError(w, http.StatusServiceUnavailable, "unavailable", "integrations supervisor not configured")
+			return
+		}
+		_ = s.integrations.Stop(slug)
+		installDir := filepath.Join(s.integrations.Dir(), slug)
+		if _, err := fetch.Download(res, vendor.Binary, installDir); err != nil {
+			_ = store.SetState(slug, "error", err.Error())
+			s.broadcastIntegrations()
+			writeError(w, http.StatusBadGateway, "download_failed", err.Error())
+			return
+		}
+		if err := s.integrations.Start(slug, nil, filepath.Join(installDir, vendor.Binary)); err != nil {
+			_ = store.SetState(slug, "error", err.Error())
+			s.broadcastIntegrations()
+			writeError(w, http.StatusBadGateway, "start_failed", err.Error())
+			return
+		}
+	} else {
+		if s.pool == nil {
+			writeError(w, http.StatusServiceUnavailable, "ssh_unavailable", "el servidor no tiene pool SSH")
+			return
+		}
+		if err := fetch.Verify(res); err != nil {
+			writeError(w, http.StatusBadGateway, "download_failed", err.Error())
+			return
+		}
+		env := s.pusherEnv(vendor, row, "", s.agentBaseURL(r), "")
+		if err := s.runSSHInstall(vendor, row, env, res.URL, res.SHA256); err != nil {
+			writeError(w, http.StatusBadGateway, "ssh_failed", err.Error())
+			return
+		}
+	}
+	_ = store.SetVersion(slug, res.Version, res.AssetName, row.Arch)
+	_ = store.SetState(slug, "running", "")
+	_ = store.SetLastStart(slug, time.Now().UnixMilli())
+	s.broadcastIntegrations()
+	item, _ := s.getIntegrationRow(slug)
+	writeJSON(w, http.StatusOK, map[string]any{"integration": s.integrationItemOf(item)})
+}
+
+func (s *server) handleIntegrationDelete(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	row, ok := s.getIntegrationRow(slug)
+	if !ok {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	vendor, _ := rintegration.LookupVendor(row.Vendor)
+	if vendor.Mode == "local" {
+		if s.integrations != nil {
+			_ = s.integrations.Stop(slug)
+			_ = s.integrations.Cleanup(slug)
+		}
+	} else if s.pool != nil {
+		_, _ = s.pool.Run(row.Host, sshUninstallScript(vendor), 60*time.Second)
+	}
+	_ = s.integrationsStore().Delete(slug)
+	_ = routerstore.RemoveRouter(s.db.DB, slug)
+	s.syncRouters()
+	if s.db != nil {
+		_, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKey(slug))
+	}
+	s.broadcastIntegrations()
+	w.WriteHeader(http.StatusNoContent)
+}
+
+// ---------------------------------------------------------------------------
+// Scripts POSIX de instalación/gestión por SSH (modo ssh, p. ej. asuswrt)
+// ---------------------------------------------------------------------------
+
+func sshInstallScript(v rintegration.Vendor, env map[string]string, assetURL, sha256 string) string {
+	bin := "/usr/sbin/" + v.Binary
+	init := "/etc/init.d/" + v.Binary
+	envFile := "/etc/" + v.Binary + ".env"
+
+	keys := make([]string, 0, len(env))
+	for k := range env {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+	var envBlock strings.Builder
+	for _, k := range keys {
+		envBlock.WriteString(k)
+		envBlock.WriteString("=")
+		envBlock.WriteString(rintegration.EscapeEnvValue(env[k]))
+		envBlock.WriteString("\n")
+	}
+
+	return `#!/bin/sh
+set -e
+BIN="` + bin + `"
+INIT="` + init + `"
+ENV_FILE="` + envFile + `"
+SERVER="` + env["NETPULSE_SERVER"] + `"
+ASSET_URL="` + assetURL + `"
+SHA256="` + sha256 + `"
+
+# Preflight: el router debe alcanzar el server.
+if command -v curl >/dev/null 2>&1; then
+	curl -fsSL -m 10 "$SERVER/api/health" >/dev/null 2>&1 || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
+else
+	wget -q -T 10 -O /dev/null "$SERVER/api/health" || { echo "preflight: cannot reach $SERVER/api/health"; exit 10; }
+fi
+
+# Parar el servicio previo (el proceso vivo mantiene el binario abierto).
+[ -x "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
+
+# Descargar el asset desde la URL ya verificada en el server.
+if command -v curl >/dev/null 2>&1; then
+	curl -fsSL -m 600 -o /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
+else
+	wget -q -T 60 -O /tmp/` + v.Binary + `.tar.gz "$ASSET_URL"
+fi
+
+# Verificar sha256 antes de instalar.
+GOT=$(sha256sum /tmp/` + v.Binary + `.tar.gz | awk '{print $1}')
+[ "$GOT" = "$SHA256" ] || { echo "sha256 mismatch (want $SHA256, got $GOT)"; exit 21; }
+
+# Extraer y mover de forma atómica (.new -> rename).
+mkdir -p /tmp/` + v.Binary + `.extract
+tar -xzf /tmp/` + v.Binary + `.tar.gz -C /tmp/` + v.Binary + `.extract
+SRC=$(find /tmp/` + v.Binary + `.extract -type f -name "` + v.Binary + `" | head -n1)
+[ -n "$SRC" ] || { echo "binary not found in archive"; exit 22; }
+cp "$SRC" "$BIN.new"
+chmod 0755 "$BIN.new"
+mv -f "$BIN.new" "$BIN"
+rm -rf /tmp/` + v.Binary + `.extract /tmp/` + v.Binary + `.tar.gz
+
+# Env (chmod 600): solo se escribe en el alta; los updates preservan el
+# fichero existente (la contraseña y el token solo viven ahí).
+if [ ! -f "$ENV_FILE" ]; then
+cat > "$ENV_FILE" <<'ENVEOF'
+` + envBlock.String() + `ENVEOF
+chmod 600 "$ENV_FILE"
+fi
+
+# Init procd.
+cat > "$INIT" <<'INITEOF'
+#!/bin/sh /etc/rc.common
+START=99
+STOP=10
+USE_PROCD=1
+BIN="/usr/sbin/` + v.Binary + `"
+ENV_FILE="/etc/` + v.Binary + `.env"
+start_service() {
+	[ -x "$BIN" ] || return 1
+	procd_open_instance ` + v.Binary + `
+	procd_set_param command "$BIN"
+	procd_set_param respawn 3600 5 5
+	procd_set_param stdout 1
+	procd_set_param stderr 1
+	procd_set_param file "$ENV_FILE"
+	procd_close_instance
+}
+INITEOF
+chmod 0755 "$INIT"
+"$INIT" enable
+"$INIT" restart
+`
+}
+
+func sshServiceScript(v rintegration.Vendor, action string) string {
+	init := "/etc/init.d/" + v.Binary
+	switch action {
+	case "start":
+		return "test -x " + init + " && " + init + " enable && " + init + " start || true"
+	case "stop":
+		return "test -x " + init + " && " + init + " stop || true"
+	case "restart":
+		return "test -x " + init + " && " + init + " restart || true"
+	case "check":
+		return "pgrep -f " + v.Binary + " >/dev/null 2>&1"
+	}
+	return "true"
+}
+
+func sshUninstallScript(v rintegration.Vendor) string {
+	init := "/etc/init.d/" + v.Binary
+	bin := "/usr/sbin/" + v.Binary
+	envFile := "/etc/" + v.Binary + ".env"
+	return fmt.Sprintf(
+		"test -x %s && %s stop || true; test -x %s && %s disable || true; rm -f %s %s %s",
+		init, init, init, init, init, bin, envFile,
+	)
+}

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

@@ -45,6 +45,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/pathanalysis"
 	"github.com/gnacho/netpulse/server-go/internal/presence"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
+	"github.com/gnacho/netpulse/server-go/internal/rintegration"
 	"github.com/gnacho/netpulse/server-go/internal/security"
 	"github.com/gnacho/netpulse/server-go/internal/speedtest"
 	"github.com/gnacho/netpulse/server-go/internal/sse"
@@ -143,6 +144,9 @@ type Deps struct {
 	// monta, va FUERA de RequireAuth (auth Bearer propia por API token, nunca
 	// cookie) con rate limit y fail-closed sin TokenStore.
 	MCP *mcp.Server
+	// Integrations: supervisor de pushers externos (#1674). nil → sin
+	// arranque/parada de procesos en modo local (rutas responden 503).
+	Integrations *rintegration.Manager
 }
 
 type server struct {
@@ -231,6 +235,9 @@ type server struct {
 	// MCP: servidor MCP embebido (#1114). nil = sin endpoint /mcp.
 	mcp *mcp.Server
 
+	// Integrations: supervisor de pushers externos (#1674).
+	integrations *rintegration.Manager
+
 	// CollectorReader: lector read-only de metrics.db del sidecar (#328).
 	collectorReader *collectorreader.Reader
 
@@ -297,6 +304,7 @@ func NewHandler(d Deps) http.Handler {
 		speedtest:       d.Speedtest,
 		alertEmitter:    d.AlertEmitter,
 		mqtt:            d.MQTT,
+		integrations:    d.Integrations,
 	}
 	if s.imageResolver == nil {
 		s.imageResolver = firmware.NewImageResolver()
@@ -361,6 +369,19 @@ func NewHandler(d Deps) http.Handler {
 	if d.Config != nil {
 		s.rtlConsole = newRtlConsoleCache(d.Config.RTLConsolePass, d.Config.RTLConsolePollSec)
 	}
+	// #1674: al morir un pusher local de forma inesperada, marcar el estado
+	// error y re-emitir la lista por SSE. Los paros intencionales no pasan por
+	// aquí (los gestiona el handler).
+	if s.integrations != nil && s.db != nil {
+		s.integrations.SetOnExit(func(slug string, exitErr error) {
+			if exitErr == nil {
+				return
+			}
+			_ = rintegration.NewStore(s.db.DB).SetState(slug, "error", exitErr.Error())
+			s.broadcastIntegrations()
+		})
+	}
+
 	mode := d.Adapter.Mode()
 
 	mux := http.NewServeMux()
@@ -603,6 +624,9 @@ func NewHandler(d Deps) http.Handler {
 	// --- Overrides manuales de topología (issue #142; solo admin) ---
 	s.registerTopologyOverrideRoutes(mux)
 
+	// --- Integraciones externas de routers (#1674) ---
+	s.registerIntegrationRoutes(mux)
+
 	// --- SSE ---
 	mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
 

+ 290 - 0
server-go/internal/rintegration/fetch.go

@@ -0,0 +1,290 @@
+package rintegration
+
+import (
+	"archive/tar"
+	"compress/gzip"
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+	"time"
+)
+
+const (
+	githubAPIBase = "https://api.github.com"
+	maxDownload   = 64 << 20 // bytes
+	fetchTimeout  = 60 * time.Second
+	userAgent     = "netpulse"
+)
+
+// Fetcher resolves and downloads verified integration releases.
+type Fetcher struct {
+	Client  *http.Client
+	APIBase string // override for tests; default githubAPIBase
+}
+
+// NewFetcher builds a Fetcher with the default 60s timeout.
+func NewFetcher() *Fetcher {
+	return &Fetcher{Client: &http.Client{Timeout: fetchTimeout}, APIBase: githubAPIBase}
+}
+
+func (f *Fetcher) client() *http.Client {
+	if f.Client != nil {
+		return f.Client
+	}
+	return &http.Client{Timeout: fetchTimeout}
+}
+
+func (f *Fetcher) base() string {
+	if f.APIBase != "" {
+		return f.APIBase
+	}
+	return githubAPIBase
+}
+
+// Resolved is a verified release asset: the tarball URL and the digest its
+// publisher shipped next to it (the .sha256 companion asset).
+type Resolved struct {
+	Version   string
+	AssetName string
+	URL       string
+	SHA256    string
+}
+
+// ResolveLatest finds the first non-prerelease release whose tag starts with
+// the vendor's prefix and returns the asset matching the requested arch plus
+// its published sha256.
+func (f *Fetcher) ResolveLatest(v Vendor, arch string) (Resolved, error) {
+	var zero Resolved
+	url := f.base() + "/repos/" + v.Repo + "/releases"
+	req, err := http.NewRequest("GET", url, nil)
+	if err != nil {
+		return zero, err
+	}
+	req.Header.Set("Accept", "application/vnd.github+json")
+	req.Header.Set("User-Agent", userAgent)
+	resp, err := f.client().Do(req)
+	if err != nil {
+		return zero, err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return zero, fmt.Errorf("github releases: %s", resp.Status)
+	}
+	var releases []struct {
+		TagName    string `json:"tag_name"`
+		Prerelease bool   `json:"prerelease"`
+		Assets     []struct {
+			Name string `json:"name"`
+			URL  string `json:"browser_download_url"`
+		} `json:"assets"`
+	}
+	if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&releases); err != nil {
+		return zero, err
+	}
+	for _, rel := range releases {
+		if rel.Prerelease || !strings.HasPrefix(rel.TagName, v.TagPrefix) {
+			continue
+		}
+		version := strings.TrimPrefix(rel.TagName, v.TagPrefix)
+		assetName := v.AssetName(version, arch)
+		assetURL, shaURL := "", ""
+		for _, a := range rel.Assets {
+			switch a.Name {
+			case assetName:
+				assetURL = a.URL
+			case assetName + ".sha256":
+				shaURL = a.URL
+			}
+		}
+		if assetURL == "" || shaURL == "" {
+			continue
+		}
+		digest, err := f.fetchSHA256(shaURL)
+		if err != nil {
+			return zero, err
+		}
+		return Resolved{Version: version, AssetName: assetName, URL: assetURL, SHA256: digest}, nil
+	}
+	return zero, fmt.Errorf("no release found for prefix %q", v.TagPrefix)
+}
+
+func (f *Fetcher) fetchSHA256(url string) (string, error) {
+	req, err := http.NewRequest("GET", url, nil)
+	if err != nil {
+		return "", err
+	}
+	req.Header.Set("User-Agent", userAgent)
+	resp, err := f.client().Do(req)
+	if err != nil {
+		return "", err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("sha256 download: %s", resp.Status)
+	}
+	body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<16))
+	if err != nil {
+		return "", err
+	}
+	return parseSHA256(string(body))
+}
+
+// parseSHA256 extracts the leading hex digest from a .sha256 file, which may
+// be either the bare hash or "hash  filename" (sha256sum output).
+func parseSHA256(s string) (string, error) {
+	fields := strings.Fields(s)
+	if len(fields) == 0 {
+		return "", errors.New("empty sha256")
+	}
+	h := strings.ToLower(fields[0])
+	if len(h) != 64 || !isHex(h) {
+		return "", errors.New("invalid sha256")
+	}
+	return h, nil
+}
+
+func isHex(s string) bool {
+	for _, r := range s {
+		if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'f')) {
+			return false
+		}
+	}
+	return true
+}
+
+// Verify downloads the asset and checks its sha256 against the published
+// digest, then discards the bytes. Used for ssh-mode installs, where the
+// router downloads the asset itself from the URL the server has verified.
+func (f *Fetcher) Verify(res Resolved) error {
+	tmp, err := f.download(res)
+	if err != nil {
+		return err
+	}
+	return os.Remove(tmp)
+}
+
+// Download fetches the asset, verifies its sha256 and extracts the tar.gz
+// into destDir. It returns the path to the extracted binary.
+func (f *Fetcher) Download(res Resolved, binary, destDir string) (string, error) {
+	tmp, err := f.download(res)
+	if err != nil {
+		return "", err
+	}
+	defer os.Remove(tmp)
+	fh, err := os.Open(tmp)
+	if err != nil {
+		return "", err
+	}
+	defer fh.Close()
+	extracted, err := extractTarGz(fh, destDir)
+	if err != nil {
+		return "", err
+	}
+	for _, p := range extracted {
+		if filepath.Base(p) == binary {
+			return p, nil
+		}
+	}
+	return "", fmt.Errorf("binary %q not found in archive", binary)
+}
+
+// download fetches the asset into a temp file, enforcing maxDownload bytes and
+// verifying the sha256 against the published digest before returning the path.
+func (f *Fetcher) download(res Resolved) (string, error) {
+	req, err := http.NewRequest("GET", res.URL, nil)
+	if err != nil {
+		return "", err
+	}
+	req.Header.Set("User-Agent", userAgent)
+	resp, err := f.client().Do(req)
+	if err != nil {
+		return "", err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("download: %s", resp.Status)
+	}
+	tmp, err := os.CreateTemp("", "rintegration-*.tar.gz")
+	if err != nil {
+		return "", err
+	}
+	h := sha256.New()
+	n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(resp.Body, maxDownload+1))
+	if err != nil {
+		tmp.Close()
+		os.Remove(tmp.Name())
+		return "", err
+	}
+	tmp.Close()
+	if n > maxDownload {
+		os.Remove(tmp.Name())
+		return "", fmt.Errorf("asset exceeds %d bytes", maxDownload)
+	}
+	got := hex.EncodeToString(h.Sum(nil))
+	if !strings.EqualFold(got, res.SHA256) {
+		os.Remove(tmp.Name())
+		return "", fmt.Errorf("sha256 mismatch: got %s, want %s", got, res.SHA256)
+	}
+	return tmp.Name(), nil
+}
+
+// extractTarGz extracts a gzipped tarball into destDir, refusing absolute
+// paths and any entry that could escape destDir (".."). It returns the paths
+// of the extracted regular files.
+func extractTarGz(r io.Reader, destDir string) ([]string, error) {
+	gz, err := gzip.NewReader(r)
+	if err != nil {
+		return nil, err
+	}
+	defer gz.Close()
+	tr := tar.NewReader(gz)
+	var out []string
+	cleanDest := filepath.Clean(destDir)
+	for {
+		hdr, err := tr.Next()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return nil, err
+		}
+		name := hdr.Name
+		if name == "" || filepath.IsAbs(name) || strings.Contains(name, "..") {
+			return nil, fmt.Errorf("unsafe path in archive: %q", hdr.Name)
+		}
+		target := filepath.Join(destDir, name)
+		if !strings.HasPrefix(filepath.Clean(target), cleanDest+string(os.PathSeparator)) {
+			return nil, fmt.Errorf("path escapes dest dir: %q", hdr.Name)
+		}
+		switch hdr.Typeflag {
+		case tar.TypeDir:
+			if err := os.MkdirAll(target, 0o755); err != nil {
+				return nil, err
+			}
+		case tar.TypeReg:
+			if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+				return nil, err
+			}
+			f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
+			if err != nil {
+				return nil, err
+			}
+			if _, err := io.Copy(f, tr); err != nil {
+				f.Close()
+				return nil, err
+			}
+			if err := f.Close(); err != nil {
+				return nil, err
+			}
+			out = append(out, target)
+		}
+	}
+	return out, nil
+}

+ 226 - 0
server-go/internal/rintegration/fetch_test.go

@@ -0,0 +1,226 @@
+package rintegration
+
+import (
+	"archive/tar"
+	"bytes"
+	"compress/gzip"
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/json"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+)
+
+func buildTarGz(t *testing.T, entries map[string]string) []byte {
+	t.Helper()
+	var buf bytes.Buffer
+	gz := gzip.NewWriter(&buf)
+	tw := tar.NewWriter(gz)
+	for name, content := range entries {
+		hdr := &tar.Header{Name: name, Mode: 0o755, Size: int64(len(content)), Typeflag: tar.TypeReg}
+		if err := tw.WriteHeader(hdr); err != nil {
+			t.Fatalf("WriteHeader: %v", err)
+		}
+		if _, err := tw.Write([]byte(content)); err != nil {
+			t.Fatalf("Write: %v", err)
+		}
+	}
+	if err := tw.Close(); err != nil {
+		t.Fatalf("tar close: %v", err)
+	}
+	if err := gz.Close(); err != nil {
+		t.Fatalf("gzip close: %v", err)
+	}
+	return buf.Bytes()
+}
+
+func sha256Hex(b []byte) string {
+	sum := sha256.Sum256(b)
+	return hex.EncodeToString(sum[:])
+}
+
+// startReleaseServer serves a fixed release index plus the tarballs and their
+// sha256 companions, with absolute asset URLs derived from the request host.
+func startReleaseServer(t *testing.T, tarballs map[string][]byte, releases []map[string]any) *httptest.Server {
+	t.Helper()
+	mux := http.NewServeMux()
+	mux.HandleFunc("/repos/gnacho/netpulse-integrations/releases", func(w http.ResponseWriter, r *http.Request) {
+		base := "http://" + r.Host
+		rel := make([]map[string]any, len(releases))
+		for i, rel0 := range releases {
+			rel[i] = map[string]any{
+				"tag_name":   rel0["tag_name"],
+				"prerelease": rel0["prerelease"],
+			}
+			if assets, ok := rel0["assets"].([]map[string]any); ok {
+				abs := make([]map[string]any, len(assets))
+				for j, a := range assets {
+					abs[j] = map[string]any{
+						"name":                 a["name"],
+						"browser_download_url": base + a["browser_download_url"].(string),
+					}
+				}
+				rel[i]["assets"] = abs
+			}
+		}
+		w.Header().Set("Content-Type", "application/json")
+		_ = json.NewEncoder(w).Encode(rel)
+	})
+	for name, data := range tarballs {
+		data := data
+		mux.HandleFunc("/a/"+name, func(w http.ResponseWriter, _ *http.Request) {
+			_, _ = w.Write(data)
+		})
+	}
+	srv := httptest.NewServer(mux)
+	t.Cleanup(srv.Close)
+	return srv
+}
+
+func TestResolveLatestSkipsPrereleaseAndWrongPrefix(t *testing.T) {
+	v200 := buildTarGz(t, map[string]string{"routeros-pusher": "v2"})
+	releases := []map[string]any{
+		{
+			"tag_name": "routeros/v3.0.0-rc1", "prerelease": true,
+			"assets": []map[string]any{},
+		},
+		{
+			"tag_name": "routeros/v2.0.0", "prerelease": false,
+			"assets": []map[string]any{
+				{"name": "routeros_2.0.0_linux_amd64.tar.gz", "browser_download_url": "/a/routeros_2.0.0_linux_amd64.tar.gz"},
+				{"name": "routeros_2.0.0_linux_amd64.tar.gz.sha256", "browser_download_url": "/a/routeros_2.0.0_linux_amd64.tar.gz.sha256"},
+			},
+		},
+		{
+			"tag_name": "routeros/v1.0.0", "prerelease": false,
+			"assets": []map[string]any{},
+		},
+	}
+	srv := startReleaseServer(t, map[string][]byte{
+		"routeros_2.0.0_linux_amd64.tar.gz":        v200,
+		"routeros_2.0.0_linux_amd64.tar.gz.sha256": []byte(sha256Hex(v200)),
+	}, releases)
+
+	f := NewFetcher()
+	f.APIBase = srv.URL
+	v, _ := LookupVendor("routeros")
+	res, err := f.ResolveLatest(v, "amd64")
+	if err != nil {
+		t.Fatalf("ResolveLatest: %v", err)
+	}
+	if res.Version != "2.0.0" {
+		t.Fatalf("version = %q, want 2.0.0", res.Version)
+	}
+	if res.AssetName != "routeros_2.0.0_linux_amd64.tar.gz" {
+		t.Fatalf("asset = %q", res.AssetName)
+	}
+	if res.SHA256 != sha256Hex(v200) {
+		t.Fatalf("sha256 mismatch")
+	}
+}
+
+func TestResolveLatestAsuswrt(t *testing.T) {
+	asus := buildTarGz(t, map[string]string{"asuswrt-pusher": "a"})
+	releases := []map[string]any{
+		{
+			"tag_name": "asuswrt/v1.0.0", "prerelease": false,
+			"assets": []map[string]any{
+				{"name": "asuswrt_1.0.0_linux_arm64.tar.gz", "browser_download_url": "/a/asuswrt_1.0.0_linux_arm64.tar.gz"},
+				{"name": "asuswrt_1.0.0_linux_arm64.tar.gz.sha256", "browser_download_url": "/a/asuswrt_1.0.0_linux_arm64.tar.gz.sha256"},
+			},
+		},
+	}
+	srv := startReleaseServer(t, map[string][]byte{
+		"asuswrt_1.0.0_linux_arm64.tar.gz":        asus,
+		"asuswrt_1.0.0_linux_arm64.tar.gz.sha256": []byte(sha256Hex(asus)),
+	}, releases)
+
+	f := NewFetcher()
+	f.APIBase = srv.URL
+	v, _ := LookupVendor("asuswrt")
+	res, err := f.ResolveLatest(v, "arm64")
+	if err != nil {
+		t.Fatalf("ResolveLatest: %v", err)
+	}
+	if res.Version != "1.0.0" || res.AssetName != "asuswrt_1.0.0_linux_arm64.tar.gz" {
+		t.Fatalf("unexpected resolve: %+v", res)
+	}
+}
+
+func TestDownloadVerified(t *testing.T) {
+	content := "#!/bin/sh\necho ok\n"
+	tgz := buildTarGz(t, map[string]string{"routeros-pusher": content})
+	res := Resolved{
+		Version: "2.0.0", AssetName: "routeros_2.0.0_linux_amd64.tar.gz",
+		URL: "/a/x.tar.gz", SHA256: sha256Hex(tgz),
+	}
+	srv := startReleaseServer(t, map[string][]byte{"x.tar.gz": tgz}, nil)
+	res.URL = srv.URL + res.URL
+
+	f := NewFetcher()
+	dest := t.TempDir()
+	bin, err := f.Download(res, "routeros-pusher", dest)
+	if err != nil {
+		t.Fatalf("Download: %v", err)
+	}
+	got, err := os.ReadFile(bin)
+	if err != nil {
+		t.Fatalf("read binary: %v", err)
+	}
+	if string(got) != content {
+		t.Fatalf("binary content = %q", got)
+	}
+}
+
+func TestDownloadBadSHA256(t *testing.T) {
+	tgz := buildTarGz(t, map[string]string{"routeros-pusher": "x"})
+	res := Resolved{URL: "/a/x.tar.gz", SHA256: strings.Repeat("deadbeef", 8)}
+	srv := startReleaseServer(t, map[string][]byte{"x.tar.gz": tgz}, nil)
+	res.URL = srv.URL + res.URL
+
+	f := NewFetcher()
+	if _, err := f.Download(res, "routeros-pusher", t.TempDir()); err == nil {
+		t.Fatal("expected sha256 mismatch error")
+	}
+}
+
+func TestExtractTarGzRejectsUnsafePaths(t *testing.T) {
+	for _, name := range []string{"../evil", "/abs", "a/../../evil"} {
+		tgz := buildTarGz(t, map[string]string{name: "bad"})
+		if _, err := extractTarGz(bytes.NewReader(tgz), t.TempDir()); err == nil {
+			t.Fatalf("extractTarGz accepted unsafe path %q", name)
+		}
+	}
+}
+
+func TestExtractTarGzNestedBinary(t *testing.T) {
+	tgz := buildTarGz(t, map[string]string{"bin/routeros-pusher": "x", "README": "r"})
+	dest := t.TempDir()
+	got, err := extractTarGz(bytes.NewReader(tgz), dest)
+	if err != nil {
+		t.Fatalf("extractTarGz: %v", err)
+	}
+	if len(got) != 2 {
+		t.Fatalf("expected 2 files, got %d", len(got))
+	}
+	if _, err := os.Stat(filepath.Join(dest, "bin", "routeros-pusher")); err != nil {
+		t.Fatalf("binary not extracted: %v", err)
+	}
+}
+
+func TestParseSHA256(t *testing.T) {
+	digest := sha256Hex([]byte("x"))
+	if got, err := parseSHA256(digest); err != nil || got != digest {
+		t.Fatalf("bare digest: %q, %v", got, err)
+	}
+	if got, err := parseSHA256(digest + "  some-file.tar.gz\n"); err != nil || got != digest {
+		t.Fatalf("sha256sum form: %q, %v", got, err)
+	}
+	if _, err := parseSHA256("not-a-digest"); err == nil {
+		t.Fatal("expected error for invalid digest")
+	}
+}

+ 282 - 0
server-go/internal/rintegration/manager.go

@@ -0,0 +1,282 @@
+package rintegration
+
+import (
+	"errors"
+	"fmt"
+	"os"
+	"os/exec"
+	"path/filepath"
+	"sort"
+	"strings"
+	"sync"
+	"syscall"
+	"time"
+)
+
+var (
+	// ErrNotRunning is returned by Stop when no process exists for the slug.
+	ErrNotRunning = errors.New("integration process not running")
+	// ErrAlreadyRunning is returned by Start when a process is already up.
+	ErrAlreadyRunning = errors.New("integration process already running")
+)
+
+// Manager supervises pusher processes in memory (no systemd: the service runs
+// as an unprivileged user). It owns the on-disk directory that holds each
+// slug's environment file, log file and extracted binary.
+type Manager struct {
+	dir    string
+	mu     sync.Mutex
+	procs  map[string]*proc
+	fetch  *Fetcher
+	onExit func(slug string, err error)
+}
+
+type proc struct {
+	cmd      *exec.Cmd
+	done     chan struct{}
+	stopping bool // guarded by Manager.mu
+}
+
+// NewManager builds a Manager rooted at dir.
+func NewManager(dir string) *Manager {
+	return &Manager{dir: dir, procs: map[string]*proc{}, fetch: NewFetcher()}
+}
+
+// Fetch returns the shared release fetcher.
+func (m *Manager) Fetch() *Fetcher { return m.fetch }
+
+// Dir returns the on-disk root for environments, logs and binaries.
+func (m *Manager) Dir() string { return m.dir }
+
+// SetOnExit registers the callback invoked when a process exits unexpectedly
+// (a crash). Intentional stops do not fire it: the caller owns that state.
+func (m *Manager) SetOnExit(fn func(slug string, err error)) {
+	m.mu.Lock()
+	m.onExit = fn
+	m.mu.Unlock()
+}
+
+// Start launches the pusher binary for slug. When env is non-empty it is
+// written to <dir>/<slug>.env (0600); otherwise the existing env file is
+// reused, which is how restarts recover the password/token that live only
+// there. The process gets the vars in its environment, runs in its own
+// process group, and logs stdout/stderr to <dir>/<slug>.log.
+func (m *Manager) Start(slug string, env map[string]string, binPath string) error {
+	if m.Running(slug) {
+		return ErrAlreadyRunning
+	}
+	if err := os.MkdirAll(m.dir, 0o755); err != nil {
+		return err
+	}
+
+	envPath := filepath.Join(m.dir, slug+".env")
+	if len(env) > 0 {
+		if err := writeEnvFile(envPath, env); err != nil {
+			return err
+		}
+	}
+	processEnv, err := readEnvFile(envPath)
+	if err != nil {
+		return fmt.Errorf("integration %s: %w", slug, err)
+	}
+
+	logPath := filepath.Join(m.dir, slug+".log")
+	logf, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
+	if err != nil {
+		return err
+	}
+
+	cmd := exec.Command(binPath)
+	cmd.Dir = m.dir
+	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+	cmd.Stdout = logf
+	cmd.Stderr = logf
+	cmd.Env = append(os.Environ(), envMapToList(processEnv)...)
+	if err := cmd.Start(); err != nil {
+		logf.Close()
+		return err
+	}
+
+	p := &proc{cmd: cmd, done: make(chan struct{})}
+	m.mu.Lock()
+	m.procs[slug] = p
+	m.mu.Unlock()
+
+	go func() {
+		err := cmd.Wait()
+		logf.Close()
+		m.mu.Lock()
+		cur := m.procs[slug]
+		stopping := cur != nil && cur.stopping
+		delete(m.procs, slug)
+		onExit := m.onExit
+		m.mu.Unlock()
+		close(p.done)
+		if !stopping && onExit != nil {
+			onExit(slug, err)
+		}
+	}()
+
+	return nil
+}
+
+// Stop sends SIGTERM to the process group, waits up to 10s, then SIGKILL.
+func (m *Manager) Stop(slug string) error {
+	m.mu.Lock()
+	p, ok := m.procs[slug]
+	if !ok {
+		m.mu.Unlock()
+		return ErrNotRunning
+	}
+	p.stopping = true
+	m.mu.Unlock()
+
+	_ = syscall.Kill(-p.cmd.Process.Pid, syscall.SIGTERM)
+	select {
+	case <-p.done:
+		return nil
+	case <-time.After(10 * time.Second):
+		_ = syscall.Kill(-p.cmd.Process.Pid, syscall.SIGKILL)
+		<-p.done
+		return nil
+	}
+}
+
+// Running reports whether a process is currently tracked for the slug.
+func (m *Manager) Running(slug string) bool {
+	m.mu.Lock()
+	_, ok := m.procs[slug]
+	m.mu.Unlock()
+	return ok
+}
+
+// StopAll stops every tracked process (used on graceful shutdown).
+func (m *Manager) StopAll() {
+	m.mu.Lock()
+	slugs := make([]string, 0, len(m.procs))
+	for s := range m.procs {
+		slugs = append(slugs, s)
+	}
+	m.mu.Unlock()
+	sort.Strings(slugs)
+	for _, s := range slugs {
+		_ = m.Stop(s)
+	}
+}
+
+// Cleanup removes the env file, log file and extracted directory for a slug.
+// Errors are collected and returned; it is safe to call when nothing exists.
+func (m *Manager) Cleanup(slug string) error {
+	var errs []string
+	for _, p := range []string{
+		filepath.Join(m.dir, slug+".env"),
+		filepath.Join(m.dir, slug+".log"),
+	} {
+		if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
+			errs = append(errs, err.Error())
+		}
+	}
+	if err := os.RemoveAll(filepath.Join(m.dir, slug)); err != nil {
+		errs = append(errs, err.Error())
+	}
+	if len(errs) > 0 {
+		return errors.New(strings.Join(errs, "; "))
+	}
+	return nil
+}
+
+// EscapeEnvValue escapes a value so it stays on one line of a KEY=value env
+// file and can be read back losslessly by UnescapeEnvValue.
+func EscapeEnvValue(v string) string {
+	var b strings.Builder
+	for _, r := range v {
+		switch r {
+		case '\\':
+			b.WriteString(`\\`)
+		case '\n':
+			b.WriteString(`\n`)
+		case '\r':
+			b.WriteString(`\r`)
+		case '\t':
+			b.WriteString(`\t`)
+		default:
+			b.WriteRune(r)
+		}
+	}
+	return b.String()
+}
+
+// UnescapeEnvValue reverses EscapeEnvValue.
+func UnescapeEnvValue(v string) string {
+	runes := []rune(v)
+	var b strings.Builder
+	for i := 0; i < len(runes); i++ {
+		if runes[i] == '\\' && i+1 < len(runes) {
+			switch runes[i+1] {
+			case '\\':
+				b.WriteRune('\\')
+			case 'n':
+				b.WriteRune('\n')
+			case 'r':
+				b.WriteRune('\r')
+			case 't':
+				b.WriteRune('\t')
+			default:
+				b.WriteRune('\\')
+				b.WriteRune(runes[i+1])
+			}
+			i++
+			continue
+		}
+		b.WriteRune(runes[i])
+	}
+	return b.String()
+}
+
+func envMapToList(env map[string]string) []string {
+	keys := make([]string, 0, len(env))
+	for k := range env {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+	out := make([]string, 0, len(env))
+	for _, k := range keys {
+		out = append(out, k+"="+env[k])
+	}
+	return out
+}
+
+func writeEnvFile(path string, env map[string]string) error {
+	keys := make([]string, 0, len(env))
+	for k := range env {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+	var b strings.Builder
+	for _, k := range keys {
+		b.WriteString(k)
+		b.WriteByte('=')
+		b.WriteString(EscapeEnvValue(env[k]))
+		b.WriteByte('\n')
+	}
+	return os.WriteFile(path, []byte(b.String()), 0o600)
+}
+
+func readEnvFile(path string) (map[string]string, error) {
+	data, err := os.ReadFile(path)
+	if err != nil {
+		return nil, err
+	}
+	out := map[string]string{}
+	for _, line := range strings.Split(string(data), "\n") {
+		if line == "" {
+			continue
+		}
+		i := strings.IndexByte(line, '=')
+		if i < 0 {
+			continue
+		}
+		out[line[:i]] = UnescapeEnvValue(line[i+1:])
+	}
+	return out, nil
+}

+ 53 - 0
server-go/internal/rintegration/manager_test.go

@@ -0,0 +1,53 @@
+package rintegration
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+func TestEscapeEnvValueRoundTrip(t *testing.T) {
+	cases := []string{
+		"plain",
+		"with space",
+		`back\slash`,
+		"tab\there",
+		"line\nbreak",
+		`quote"inside`,
+		"español con acentos",
+	}
+	for _, c := range cases {
+		if got := UnescapeEnvValue(EscapeEnvValue(c)); got != c {
+			t.Fatalf("roundtrip %q -> %q", c, got)
+		}
+	}
+}
+
+func TestWriteReadEnvFile(t *testing.T) {
+	dir := t.TempDir()
+	path := filepath.Join(dir, "x.env")
+	env := map[string]string{
+		"ROUTEROS_PASS":     "p@ss word\nwith\\newline",
+		"NETPULSE_TOKEN":    "abc123",
+		"NETPULSE_INTERVAL": "30",
+	}
+	if err := writeEnvFile(path, env); err != nil {
+		t.Fatalf("writeEnvFile: %v", err)
+	}
+	fi, err := os.Stat(path)
+	if err != nil {
+		t.Fatalf("stat: %v", err)
+	}
+	if fi.Mode().Perm() != 0o600 {
+		t.Fatalf("perm = %v, want 0600", fi.Mode().Perm())
+	}
+	got, err := readEnvFile(path)
+	if err != nil {
+		t.Fatalf("readEnvFile: %v", err)
+	}
+	for k, want := range env {
+		if got[k] != want {
+			t.Fatalf("env[%s] = %q, want %q", k, got[k], want)
+		}
+	}
+}

+ 155 - 0
server-go/internal/rintegration/store.go

@@ -0,0 +1,155 @@
+package rintegration
+
+import (
+	"database/sql"
+	"time"
+)
+
+// Row is one row of the router_integrations table. The pusher password is
+// never stored here: it lives only in the on-disk environment file written by
+// the Manager.
+type Row struct {
+	Slug        string
+	Vendor      string
+	Mode        string
+	Host        string
+	Username    string
+	Version     string
+	Asset       string
+	Arch        string
+	IntervalS   int
+	Enabled     bool
+	State       string
+	LastError   string
+	LastStartMs int64
+	CreatedAt   int64
+	UpdatedAt   int64
+}
+
+// Store wraps the router_integrations table (created by db.schemaSQL).
+type Store struct {
+	db *sql.DB
+}
+
+// NewStore builds a Store over an open *sql.DB.
+func NewStore(db *sql.DB) *Store { return &Store{db: db} }
+
+const integrationCols = "slug, vendor, mode, host, username, version, asset, arch, interval_s, enabled, state, last_error, last_start_ms, created_at, updated_at"
+
+func scanIntegration(row interface{ Scan(...any) error }) (Row, error) {
+	var r Row
+	var enabled int
+	if err := row.Scan(
+		&r.Slug, &r.Vendor, &r.Mode, &r.Host, &r.Username, &r.Version, &r.Asset,
+		&r.Arch, &r.IntervalS, &enabled, &r.State, &r.LastError, &r.LastStartMs,
+		&r.CreatedAt, &r.UpdatedAt,
+	); err != nil {
+		return Row{}, err
+	}
+	r.Enabled = enabled == 1
+	return r, nil
+}
+
+// List returns all integrations ordered by creation time.
+func (st *Store) List() ([]Row, error) {
+	rows, err := st.db.Query("SELECT " + integrationCols + " FROM router_integrations ORDER BY created_at ASC")
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	out := []Row{}
+	for rows.Next() {
+		r, err := scanIntegration(rows)
+		if err != nil {
+			continue
+		}
+		out = append(out, r)
+	}
+	return out, rows.Err()
+}
+
+// Get returns the integration with the given slug, or ok=false.
+func (st *Store) Get(slug string) (Row, bool) {
+	r, err := scanIntegration(st.db.QueryRow("SELECT "+integrationCols+" FROM router_integrations WHERE slug = ?", slug))
+	if err != nil {
+		return Row{}, false
+	}
+	return r, true
+}
+
+// Upsert inserts or fully updates an integration row. created_at is preserved
+// on conflict; every other column is replaced.
+func (st *Store) Upsert(r Row) error {
+	now := time.Now().UnixMilli()
+	enabled := 0
+	if r.Enabled {
+		enabled = 1
+	}
+	if r.CreatedAt == 0 {
+		r.CreatedAt = now
+	}
+	if r.UpdatedAt == 0 {
+		r.UpdatedAt = now
+	}
+	_, err := st.db.Exec(
+		`INSERT INTO router_integrations
+			(slug, vendor, mode, host, username, version, asset, arch, interval_s, enabled, state, last_error, last_start_ms, created_at, updated_at)
+		 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+		 ON CONFLICT(slug) DO UPDATE SET
+			vendor=excluded.vendor, mode=excluded.mode, host=excluded.host,
+			username=excluded.username, version=excluded.version, asset=excluded.asset,
+			arch=excluded.arch, interval_s=excluded.interval_s, enabled=excluded.enabled,
+			state=excluded.state, last_error=excluded.last_error,
+			last_start_ms=excluded.last_start_ms, updated_at=excluded.updated_at`,
+		r.Slug, r.Vendor, r.Mode, r.Host, r.Username, r.Version, r.Asset,
+		r.Arch, r.IntervalS, enabled, r.State, r.LastError, r.LastStartMs,
+		r.CreatedAt, r.UpdatedAt,
+	)
+	return err
+}
+
+// SetState updates state and last_error.
+func (st *Store) SetState(slug, state, lastError string) error {
+	_, err := st.db.Exec(
+		"UPDATE router_integrations SET state = ?, last_error = ?, updated_at = ? WHERE slug = ?",
+		state, lastError, time.Now().UnixMilli(), slug,
+	)
+	return err
+}
+
+// SetEnabled updates the enabled flag.
+func (st *Store) SetEnabled(slug string, enabled bool) error {
+	e := 0
+	if enabled {
+		e = 1
+	}
+	_, err := st.db.Exec(
+		"UPDATE router_integrations SET enabled = ?, updated_at = ? WHERE slug = ?",
+		e, time.Now().UnixMilli(), slug,
+	)
+	return err
+}
+
+// SetVersion records the release that is installed.
+func (st *Store) SetVersion(slug, version, asset, arch string) error {
+	_, err := st.db.Exec(
+		"UPDATE router_integrations SET version = ?, asset = ?, arch = ?, updated_at = ? WHERE slug = ?",
+		version, asset, arch, time.Now().UnixMilli(), slug,
+	)
+	return err
+}
+
+// SetLastStart records the last successful process start timestamp (epoch ms).
+func (st *Store) SetLastStart(slug string, ms int64) error {
+	_, err := st.db.Exec(
+		"UPDATE router_integrations SET last_start_ms = ?, updated_at = ? WHERE slug = ?",
+		ms, time.Now().UnixMilli(), slug,
+	)
+	return err
+}
+
+// Delete removes the row with the given slug.
+func (st *Store) Delete(slug string) error {
+	_, err := st.db.Exec("DELETE FROM router_integrations WHERE slug = ?", slug)
+	return err
+}

+ 110 - 0
server-go/internal/rintegration/store_test.go

@@ -0,0 +1,110 @@
+package rintegration
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+func newTestStore(t *testing.T) *Store {
+	t.Helper()
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	return NewStore(d.DB)
+}
+
+func TestStoreCRUD(t *testing.T) {
+	st := newTestStore(t)
+
+	r := Row{
+		Slug: "mik", Vendor: "routeros", Mode: "local", Host: "10.0.0.1",
+		Username: "admin", IntervalS: 30, Enabled: true, State: "pending",
+	}
+	if err := st.Upsert(r); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+
+	got, ok := st.Get("mik")
+	if !ok {
+		t.Fatal("Get returned not found")
+	}
+	if got.Vendor != "routeros" || got.Mode != "local" || got.Host != "10.0.0.1" {
+		t.Fatalf("unexpected row: %+v", got)
+	}
+	if !got.Enabled || got.State != "pending" || got.IntervalS != 30 {
+		t.Fatalf("unexpected flags: %+v", got)
+	}
+
+	if err := st.SetState("mik", "running", ""); err != nil {
+		t.Fatalf("SetState: %v", err)
+	}
+	got, _ = st.Get("mik")
+	if got.State != "running" {
+		t.Fatalf("state = %q", got.State)
+	}
+
+	if err := st.SetVersion("mik", "2.0.0", "routeros_2.0.0_linux_amd64.tar.gz", "amd64"); err != nil {
+		t.Fatalf("SetVersion: %v", err)
+	}
+	got, _ = st.Get("mik")
+	if got.Version != "2.0.0" || got.Asset != "routeros_2.0.0_linux_amd64.tar.gz" || got.Arch != "amd64" {
+		t.Fatalf("version fields: %+v", got)
+	}
+
+	if err := st.SetEnabled("mik", false); err != nil {
+		t.Fatalf("SetEnabled: %v", err)
+	}
+	got, _ = st.Get("mik")
+	if got.Enabled {
+		t.Fatal("enabled should be false")
+	}
+
+	if err := st.SetLastStart("mik", 1234567890); err != nil {
+		t.Fatalf("SetLastStart: %v", err)
+	}
+	got, _ = st.Get("mik")
+	if got.LastStartMs != 1234567890 {
+		t.Fatalf("last_start_ms = %d", got.LastStartMs)
+	}
+
+	list, err := st.List()
+	if err != nil {
+		t.Fatalf("List: %v", err)
+	}
+	if len(list) != 1 || list[0].Slug != "mik" {
+		t.Fatalf("list = %+v", list)
+	}
+
+	if err := st.Delete("mik"); err != nil {
+		t.Fatalf("Delete: %v", err)
+	}
+	if _, ok := st.Get("mik"); ok {
+		t.Fatal("row still exists after delete")
+	}
+}
+
+func TestStoreUpsertPreservesCreatedAt(t *testing.T) {
+	st := newTestStore(t)
+	r := Row{Slug: "a", Vendor: "routeros", Mode: "local", Host: "h", Username: "u", IntervalS: 30}
+	if err := st.Upsert(r); err != nil {
+		t.Fatalf("Upsert: %v", err)
+	}
+	first, _ := st.Get("a")
+	if first.CreatedAt == 0 {
+		t.Fatal("created_at not set")
+	}
+	r2 := Row{Slug: "a", Vendor: "routeros", Mode: "local", Host: "h2", Username: "u", IntervalS: 60, Enabled: true}
+	if err := st.Upsert(r2); err != nil {
+		t.Fatalf("Upsert #2: %v", err)
+	}
+	second, _ := st.Get("a")
+	if second.CreatedAt != first.CreatedAt {
+		t.Fatalf("created_at changed: %d -> %d", first.CreatedAt, second.CreatedAt)
+	}
+	if second.Host != "h2" || !second.Enabled {
+		t.Fatalf("upsert did not update fields: %+v", second)
+	}
+}

+ 65 - 0
server-go/internal/rintegration/vendors.go

@@ -0,0 +1,65 @@
+// Package rintegration manages external router integrations (#1674): pushers
+// that run on the NetPulse server (mode "local") or on the router itself
+// (mode "ssh") and push data to the agent ingest endpoint with the external
+// agent contract.
+package rintegration
+
+import "strings"
+
+// Vendor is the static manifest of one supported external pusher.
+type Vendor struct {
+	ID          string // "routeros" | "asuswrt"
+	Mode        string // "local" (runs on this host) | "ssh" (installed on the router)
+	Repo        string // GitHub repo that publishes the releases
+	TagPrefix   string // release tags for this vendor (e.g. "routeros/v")
+	AssetTmpl   string // asset name template with {version} and {arch}
+	Arches      []string
+	Binary      string // binary name inside the tarball
+	Description string
+}
+
+// AssetName renders the asset name for a resolved version and architecture.
+func (v Vendor) AssetName(version, arch string) string {
+	name := v.AssetTmpl
+	name = strings.ReplaceAll(name, "{version}", version)
+	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",
+		Description: "Asuswrt (Asuswrt-Merlin) 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
+}

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

@@ -0,0 +1,42 @@
+package rintegration
+
+import "testing"
+
+func TestVendorsManifest(t *testing.T) {
+	vs := Vendors()
+	if len(vs) != 2 {
+		t.Fatalf("expected 2 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 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)
+	}
+
+	if _, ok := LookupVendor("bbox"); ok {
+		t.Fatal("bbox must not be present")
+	}
+}