Ver código fonte

Feat/routeros support (#969)

First-class RouterOS (MikroTik) router support, contributed by @samex.

- New fleet router type "routeros", polled server-side via the native REST API (RouterOS 7+): real CPU/RAM/uptime vitals, WAN metrics from interface counters, package update check.
- Hand-rolled minimal client for the binary API (port 8728, modern single-sentence login, read-only /print sentences) for routers whose admin keeps www closed: zero new dependencies.
- Optional routeros-pusher agent for units that only expose api/api-ssl.
- Password stays server-side (json:"-"), opt-in flag for factory self-signed TLS.

Closes #939.

Co-authored-by: Samet Güzeldemirci <samet.guzeldemirci@5werk.de>
Samet Güzeldemirci 2 meses atrás
pai
commit
2314a8faa2

+ 4 - 0
.gitignore

@@ -9,6 +9,7 @@ app/node_modules
 
 # Backend: datos y secretos
 server/data/
+server-go/data/
 server/.env
 legacy/server-node/data/
 legacy/server-node/.env
@@ -43,3 +44,6 @@ server-go/internal/agentbin/agents/netpulse-agent-*
 # Rutas prerenderizadas por idioma (generadas, ver web/build-langs.mjs)
 web/langs/
 web/node_modules/
+
+plans
+docs/premortem

+ 227 - 0
agent/cmd/routeros-pusher/main.go

@@ -0,0 +1,227 @@
+// routeros-pusher — external pusher for MikroTik RouterOS boxes.
+//
+// Unlike netpulse-agent (which runs locally on OpenWrt and shells out to
+// ubus/proc), RouterOS is a closed appliance OS: there is nowhere to run a
+// Go binary on the device itself. RouterOS 7+ does expose a REST API
+// remotely (https://<router>/rest/...), so this tool polls that API from
+// wherever it runs (the NetPulse host, a container, a cron box) and pushes
+// the result to NetPulse's existing external-pusher ingest endpoint
+// (POST /api/ingest/agent, Kind: "external") — no server-side changes
+// needed, same wire format as agent/probe.Payload.
+//
+// Config (env):
+//
+//	ROUTEROS_HOST     RouterOS REST API base URL (e.g. https://192.168.1.1)
+//	ROUTEROS_USER     RouterOS API user
+//	ROUTEROS_PASS     RouterOS API password
+//	ROUTEROS_INSECURE skip TLS verification ("1"; RouterOS ships self-signed certs)
+//	NETPULSE_SERVER   NetPulse server URL (e.g. https://netpulse.local:3000)
+//	NETPULSE_TOKEN    agent token for the slug (created via POST /api/agents)
+//	NETPULSE_SLUG     router slug in NetPulse
+//	NETPULSE_INTERVAL push interval, Go duration (default "30s")
+package main
+
+import (
+	"bytes"
+	"context"
+	"crypto/tls"
+	"encoding/json"
+	"fmt"
+	"io"
+	"log/slog"
+	"net/http"
+	"os"
+	"regexp"
+	"strconv"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// Version del pusher (se reporta en cada push).
+var Version = "0.1.0"
+
+type routerOSResource struct {
+	CPULoad      string `json:"cpu-load"`
+	FreeMemory   string `json:"free-memory"`
+	TotalMemory  string `json:"total-memory"`
+	Uptime       string `json:"uptime"`
+	Version      string `json:"version"`
+	BoardName    string `json:"board-name"`
+	Architecture string `json:"architecture-name"`
+}
+
+type routerOSIdentity struct {
+	Name string `json:"name"`
+}
+
+// durationRe: RouterOS uptime strings look like "1w2d3h4m5s" — any subset
+// of those units, in that order, no separators.
+var durationRe = regexp.MustCompile(`(\d+)([wdhms])`)
+
+// parseRouterOSUptime converts a RouterOS uptime string to seconds.
+// ponytail: regex parse, no full grammar — RouterOS's format is fixed and
+// documented, upgrade to a real parser only if a future RouterOS version
+// changes it.
+func parseRouterOSUptime(s string) (float64, error) {
+	matches := durationRe.FindAllStringSubmatch(s, -1)
+	if matches == nil {
+		return 0, fmt.Errorf("routeros-pusher: unparseable uptime %q", s)
+	}
+	unitSeconds := map[string]float64{"w": 604800, "d": 86400, "h": 3600, "m": 60, "s": 1}
+	var total float64
+	for _, m := range matches {
+		n, err := strconv.ParseFloat(m[1], 64)
+		if err != nil {
+			return 0, fmt.Errorf("routeros-pusher: bad uptime component %q: %w", m[0], err)
+		}
+		total += n * unitSeconds[m[2]]
+	}
+	return total, nil
+}
+
+// buildSystemData maps a RouterOS resource+identity pair to the SystemData
+// shape NetPulse already understands (SPEC-AGENTE-PILOTO §1 wire format).
+func buildSystemData(res routerOSResource, id routerOSIdentity) (*probe.SystemData, error) {
+	cpuLoad, err := strconv.Atoi(res.CPULoad)
+	if err != nil {
+		return nil, fmt.Errorf("routeros-pusher: bad cpu-load %q: %w", res.CPULoad, err)
+	}
+	uptime, err := parseRouterOSUptime(res.Uptime)
+	if err != nil {
+		return nil, err
+	}
+	total, _ := strconv.ParseFloat(res.TotalMemory, 64)
+	free, _ := strconv.ParseFloat(res.FreeMemory, 64)
+
+	sys := &probe.SystemData{CPU: &cpuLoad}
+	sys.SysInfo = &probe.SysInfo{Uptime: uptime}
+	sys.SysInfo.Memory.Total = total
+	sys.SysInfo.Memory.Free = free
+	sys.Board = &probe.BoardInfo{
+		Model:     res.BoardName,
+		Hostname:  id.Name,
+		System:    "routeros",
+		BoardName: res.BoardName,
+	}
+	sys.Board.Release.Version = res.Version
+	sys.Board.Release.Target = res.Architecture
+	return sys, nil
+}
+
+func fetchJSON(ctx context.Context, client *http.Client, url, user, pass string, out any) error {
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+	if err != nil {
+		return err
+	}
+	req.SetBasicAuth(user, pass)
+	resp, err := client.Do(req)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<12))
+		return fmt.Errorf("routeros-pusher: GET %s: %s: %s", url, resp.Status, body)
+	}
+	return json.NewDecoder(resp.Body).Decode(out)
+}
+
+func fetchRouterOS(ctx context.Context, client *http.Client, host, user, pass string) (*probe.SystemData, error) {
+	var res routerOSResource
+	if err := fetchJSON(ctx, client, host+"/rest/system/resource", user, pass, &res); err != nil {
+		return nil, err
+	}
+	var id routerOSIdentity
+	if err := fetchJSON(ctx, client, host+"/rest/system/identity", user, pass, &id); err != nil {
+		return nil, err
+	}
+	return buildSystemData(res, id)
+}
+
+func pushPayload(ctx context.Context, client *http.Client, server, token string, p probe.Payload) error {
+	body, err := json.Marshal(p)
+	if err != nil {
+		return err
+	}
+	req, err := http.NewRequestWithContext(ctx, http.MethodPost, server+"/api/ingest/agent", bytes.NewReader(body))
+	if err != nil {
+		return err
+	}
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer "+token)
+	resp, err := client.Do(req)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<12))
+		return fmt.Errorf("routeros-pusher: POST ingest: %s: %s", resp.Status, respBody)
+	}
+	return nil
+}
+
+func mustEnv(key string) string {
+	v := os.Getenv(key)
+	if v == "" {
+		slog.Error("routeros-pusher: missing required env var", "var", key)
+		os.Exit(1)
+	}
+	return v
+}
+
+func main() {
+	slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, nil)))
+
+	routerosHost := mustEnv("ROUTEROS_HOST")
+	routerosUser := mustEnv("ROUTEROS_USER")
+	routerosPass := mustEnv("ROUTEROS_PASS")
+	server := mustEnv("NETPULSE_SERVER")
+	token := mustEnv("NETPULSE_TOKEN")
+	slug := mustEnv("NETPULSE_SLUG")
+
+	interval := 30 * time.Second
+	if v := os.Getenv("NETPULSE_INTERVAL"); v != "" {
+		d, err := time.ParseDuration(v)
+		if err != nil {
+			slog.Error("routeros-pusher: bad NETPULSE_INTERVAL", "err", err)
+			os.Exit(1)
+		}
+		interval = d
+	}
+
+	routerosClient := &http.Client{Timeout: 10 * time.Second}
+	if os.Getenv("ROUTEROS_INSECURE") == "1" {
+		routerosClient.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} //nolint:gosec // opt-in for RouterOS self-signed certs
+	}
+	netpulseClient := &http.Client{Timeout: 10 * time.Second}
+
+	ctx := context.Background()
+	// ponytail: fixed-interval loop, no backoff/jitter — a failed tick just
+	// waits for the next one. Add real backoff if flapping RouterOS
+	// connectivity turns out to spam logs/NetPulse.
+	ticker := time.NewTicker(interval)
+	defer ticker.Stop()
+	for {
+		sys, err := fetchRouterOS(ctx, routerosClient, routerosHost, routerosUser, routerosPass)
+		if err != nil {
+			slog.Error("routeros-pusher: fetch failed", "err", err)
+		} else {
+			payload := probe.Payload{
+				Router:   slug,
+				Ts:       time.Now().Unix(),
+				Version:  Version,
+				Kind:     "external",
+				Interval: int(interval.Seconds()),
+				Data:     probe.PayloadData{System: sys},
+			}
+			if err := pushPayload(ctx, netpulseClient, server, token, payload); err != nil {
+				slog.Error("routeros-pusher: push failed", "err", err)
+			} else {
+				slog.Info("routeros-pusher: pushed", "slug", slug)
+			}
+		}
+		<-ticker.C
+	}
+}

+ 62 - 0
agent/cmd/routeros-pusher/main_test.go

@@ -0,0 +1,62 @@
+package main
+
+import "testing"
+
+func TestParseRouterOSUptime(t *testing.T) {
+	cases := map[string]float64{
+		"5s":         5,
+		"4m5s":       245,
+		"3h4m5s":     11045,
+		"2d3h4m5s":   183845,
+		"1w2d3h4m5s": 788645,
+	}
+	for input, want := range cases {
+		got, err := parseRouterOSUptime(input)
+		if err != nil {
+			t.Fatalf("parseRouterOSUptime(%q): %v", input, err)
+		}
+		if got != want {
+			t.Errorf("parseRouterOSUptime(%q) = %v, want %v", input, got, want)
+		}
+	}
+}
+
+func TestParseRouterOSUptimeInvalid(t *testing.T) {
+	if _, err := parseRouterOSUptime("not-a-duration"); err == nil {
+		t.Fatal("expected error for unparseable uptime")
+	}
+}
+
+func TestBuildSystemData(t *testing.T) {
+	res := routerOSResource{
+		CPULoad:      "3",
+		FreeMemory:   "104857600",
+		TotalMemory:  "134217728",
+		Uptime:       "1d02h03m04s",
+		Version:      "7.15",
+		BoardName:    "RB4011",
+		Architecture: "arm",
+	}
+	id := routerOSIdentity{Name: "MikroTik-Core"}
+
+	sys, err := buildSystemData(res, id)
+	if err != nil {
+		t.Fatalf("buildSystemData: %v", err)
+	}
+	if sys.CPU == nil || *sys.CPU != 3 {
+		t.Errorf("CPU = %v, want 3", sys.CPU)
+	}
+	if sys.SysInfo.Memory.Total != 134217728 || sys.SysInfo.Memory.Free != 104857600 {
+		t.Errorf("memory = %+v", sys.SysInfo.Memory)
+	}
+	if sys.Board.Hostname != "MikroTik-Core" || sys.Board.Release.Version != "7.15" {
+		t.Errorf("board = %+v", sys.Board)
+	}
+}
+
+func TestBuildSystemDataBadCPU(t *testing.T) {
+	res := routerOSResource{CPULoad: "n/a", Uptime: "1s"}
+	if _, err := buildSystemData(res, routerOSIdentity{}); err == nil {
+		t.Fatal("expected error for bad cpu-load")
+	}
+}

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

@@ -1496,7 +1496,11 @@
       "tempThresholdHint": "High-temperature alert threshold. Empty = 65 °C by default. A router that runs hotter can raise its own without hiding issues in cooler ones.",
       "openWrtBadge": "OpenWrt",
       "consolePolling": "Console polling",
-      "consolePollingHint": "The server logs into the switch web UI to read firmware, uptime and MAC. The firmware console allows a single session: every poll kicks whoever is logged in. Disable it if it kicks you out (with beacon v1.3+ the data arrives via UDP anyway)."
+      "consolePollingHint": "The server logs into the switch web UI to read firmware, uptime and MAC. The firmware console allows a single session: every poll kicks whoever is logged in. Disable it if it kicks you out (with beacon v1.3+ the data arrives via UDP anyway).",
+      "routerosUser": "RouterOS user",
+      "routerosPassword": "RouterOS password",
+      "routerosPasswordPlaceholder": "Leave blank to keep current",
+      "routerosInsecure": "Accept self-signed TLS certificate"
     },
     "overrides": {
       "title": "Topology — manual tagging",

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

@@ -1496,7 +1496,11 @@
       "tempThresholdHint": "Umbral de alerta por temperatura alta. Vacío = 65 °C por defecto. Un router que corre más caliente puede subir el suyo sin ocultar problemas en los más frescos.",
       "openWrtBadge": "OpenWrt",
       "consolePolling": "Sondeo por consola",
-      "consolePollingHint": "El server entra en la web del switch para leer firmware, uptime y MAC. La consola del firmware admite una sola sesión: cada sondeo cierra la sesión de cualquiera que esté dentro. Desactívalo si te echa de la web (con el beacon v1.3+ los datos llegan igual por UDP)."
+      "consolePollingHint": "El server entra en la web del switch para leer firmware, uptime y MAC. La consola del firmware admite una sola sesión: cada sondeo cierra la sesión de cualquiera que esté dentro. Desactívalo si te echa de la web (con el beacon v1.3+ los datos llegan igual por UDP).",
+      "routerosUser": "Usuario RouterOS",
+      "routerosPassword": "Contraseña RouterOS",
+      "routerosPasswordPlaceholder": "Déjalo en blanco para conservar la actual",
+      "routerosInsecure": "Aceptar certificado TLS autofirmado"
     },
     "overrides": {
       "title": "Topología — etiquetado manual",

+ 2 - 1
app/src/components/routers/AgentBadge.tsx

@@ -18,7 +18,8 @@ interface AgentBadgeProps {
 }
 
 function isOpenWrtDevice(t?: string): boolean {
-  return t === undefined || t === '' || t === 'glinet' || t === 'openwrt'
+  if (!t) return true
+  return t === 'glinet' || t === 'openwrt'
 }
 
 /**

+ 2 - 1
app/src/components/routers/AgentsSection.tsx

@@ -27,7 +27,8 @@ import { cn, copyToClipboard } from '@/lib/utils'
  */
 
 function isOpenWrtType(t: string | undefined): boolean {
-  return t === undefined || t === '' || t === 'glinet' || t === 'openwrt'
+  if (!t) return true
+  return t === 'glinet' || t === 'openwrt'
 }
 
 // copyText: alias del helper compartido con fallback para orígenes no

+ 9 - 3
app/src/components/routers/FleetCard.tsx

@@ -92,7 +92,7 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
   const inStartupGrace = (serverUptimeSec ?? Number.MAX_SAFE_INTEGER) < STARTUP_GRACE_SEC
   const extras = isDemo ? getRouterExtras(router.id) : EMPTY_EXTRAS
   const warn = router.status === 'warn'
-  const isOpenWrt = router.type === undefined || router.type === '' || router.type === 'glinet' || router.type === 'openwrt'
+  const isOpenWrt = !router.type || router.type === 'glinet' || router.type === 'openwrt'
   const agentDown = isOpenWrt && agent !== undefined && !agent.fresh
   const agentMissing = isOpenWrt && agent === undefined && router.agentOnly
   const reduce = useReducedMotion()
@@ -189,9 +189,15 @@ export function FleetCard({ router, index = 0, refreshKey = 0 }: FleetCardProps)
                 <AgentBadge agent={agent} agentOnly={router.agentOnly} deviceType={router.type} />
               </div>
               <div className="truncate text-caption text-text-muted">
-                {isPrimary ? router.model : `OpenWrt · ${router.modelShort}`}
+                {router.type === 'routeros'
+                  ? (router.model || 'RouterOS')
+                  : router.type === 'managed-switch'
+                    ? (router.model || 'Switch')
+                    : isPrimary
+                      ? router.model
+                      : `OpenWrt · ${router.modelShort}`}
               </div>
-              {isPrimary && (
+              {isPrimary && router.type !== 'routeros' && router.type !== 'managed-switch' && (
                 <div className="mt-1.5 inline-flex items-center gap-1.5 rounded-full bg-elevated px-2 py-0.5">
                   <span className="h-1.5 w-1.5 rounded-full bg-ok" />
                   <span className="text-[10px] font-semibold uppercase tracking-wide text-text-secondary">AdGuard</span>

+ 7 - 1
app/src/components/routers/RouterDetailHeader.tsx

@@ -67,7 +67,13 @@ export function RouterDetailHeader({ router }: { router: Router }) {
           <div className="min-w-0">
             <h1 className="font-display text-h1 text-text-primary">{router.name}</h1>
             <p className="text-caption text-text-muted">
-              {isGateway ? router.model : `OpenWrt · ${router.modelShort}`}
+              {router.type === 'routeros'
+                ? (router.model || 'RouterOS')
+                : router.type === 'managed-switch'
+                  ? (router.model || 'Switch')
+                  : isGateway
+                    ? router.model
+                    : `OpenWrt · ${router.modelShort}`}
             </p>
             <div className="mt-2 flex flex-wrap items-center gap-1.5">
               {pills.map((p, i) => (

+ 26 - 14
app/src/components/routers/RouterInfo.tsx

@@ -54,7 +54,7 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
     // aparecer en ningún sitio de la web; la fila ID lo hace visible.
     { label: 'ID', node: router.id },
     { label: 'IP LAN', node: router.ip },
-    { label: 'MAC', node: ex.mac },
+    { label: 'MAC', node: ex.mac && ex.mac !== '—' ? ex.mac : (router.mac || '—') },
     {
       label: 'Firmware',
       node: (
@@ -64,14 +64,14 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
           {router.firmwareTarget && (
             <span className="text-text-muted">{t('routerDetail.info.firmwareTarget', { target: router.firmwareTarget })}</span>
           )}
-          {router.firmwareOutdated ? (
+          {ex.firmwareAvailable ? (
+            <span title={t('routers.firmwareAvailable', { version: ex.firmwareAvailable })}>
+              <StatusPill tone="warn" label={t('routers.firmwareAvailable', { version: ex.firmwareAvailable })} />
+            </span>
+          ) : router.firmwareOutdated ? (
             <StatusPill tone="warn" label={t('routers.firmwareOutdated')} />
           ) : ex.firmwareUpdated ? (
             <StatusPill tone="ok" label={t('routerDetail.info.updated')} />
-          ) : ex.firmwareAvailable ? (
-            <span title={t('routers.firmwareAvailable', { version: ex.firmwareAvailable })}>
-              <StatusPill tone="warn" label={ex.firmwareAvailable} />
-            </span>
           ) : null}
         </span>
       ),
@@ -81,7 +81,17 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
     { label: t('routerDetail.info.timezone'), node: ex.timezone ?? '—' },
     {
       label: t('routerDetail.info.access'),
-      node: (
+      node: router.type === 'routeros' ? (
+        <span className="inline-flex items-center gap-1.5">
+          <Terminal className="h-3.5 w-3.5 text-text-muted" strokeWidth={1.75} />
+          RouterOS API
+          <span className="rounded-full bg-accent/10 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-accent">8728</span>
+        </span>
+      ) : router.type === 'managed-switch' || router.type === 'external' ? (
+        <span className="inline-flex items-center gap-1.5">
+          SNMP / API
+        </span>
+      ) : (
         <span className="inline-flex items-center gap-1.5">
           <Terminal className="h-3.5 w-3.5 text-text-muted" strokeWidth={1.75} />
           SSH
@@ -131,13 +141,15 @@ export function RouterInfo({ router, extras }: { router: Router; extras?: Router
             {t('routerDetail.info.openNetgrip')}
           </a>
         )}
-        <button
-          onClick={copySsh}
-          className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-caption font-semibold text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
-        >
-          <Terminal className="h-3.5 w-3.5" strokeWidth={1.75} />
-          {t('routerDetail.info.copySsh')}
-        </button>
+        {router.type !== 'routeros' && router.type !== 'managed-switch' && router.type !== 'external' && (
+          <button
+            onClick={copySsh}
+            className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-border px-3 text-caption font-semibold text-text-secondary transition-colors hover:border-accent/40 hover:text-accent"
+          >
+            <Terminal className="h-3.5 w-3.5" strokeWidth={1.75} />
+            {t('routerDetail.info.copySsh')}
+          </button>
+        )}
       </div>
 
       {/* Toast "Comando copiado" */}

+ 3 - 2
app/src/pages/RouterDetail.tsx

@@ -206,8 +206,9 @@ export default function RouterDetail() {
       {/* ⑤⑥ Servicios + Puertos (gateway) / Radios + Puertos (APs) */}
       {isGateway ? (
         <>
-          <AdGuardPanel />
-          <WireGuardPanel />
+          {/* AdGuard Home y WireGuard (vía ubus OpenWrt); no aplican a RouterOS. */}
+          {router.type !== 'routeros' && <AdGuardPanel />}
+          {router.type !== 'routeros' && <WireGuardPanel />}
           <PortPanel router={router} extras={detail?.extras} snmpStats={snmpStats} className="lg:col-span-12" />
         </>
       ) : (

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

@@ -357,7 +357,7 @@ function Confetti({ burstKey, reduce }: { burstKey: number; reduce: boolean }) {
 // Gestión de routers (modo live): CRUD contra /api/config/routers
 // ---------------------------------------------------------------------------
 
-type RouterType = 'glinet' | 'openwrt' | 'managed-switch' | 'external'
+type RouterType = 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'
 
 interface ConfigRouter {
   id: string
@@ -374,6 +374,11 @@ interface ConfigRouter {
   ssh_port?: number
   temp_threshold?: number | null
   console_polling?: boolean
+  // RouterOS: routeros_user viaja tal cual; routeros_password NUNCA se
+  // devuelve (json:"-" en el server, igual que la clave SSH) — dejar el
+  // campo en blanco en el form de edición conserva la password existente.
+  routeros_user?: string
+  routeros_insecure?: boolean
 }
 
 interface DiscoverCandidate {
@@ -425,6 +430,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [editSnmpPollInterval, setEditSnmpPollInterval] = useState(60)
   const [editSshPort, setEditSshPort] = useState(22)
   const [editTempThreshold, setEditTempThreshold] = useState('')
+  const [editRouterOSUser, setEditRouterOSUser] = useState('')
+  const [editRouterOSPassword, setEditRouterOSPassword] = useState('')
+  const [editRouterOSInsecure, setEditRouterOSInsecure] = useState(false)
   const [editSubmitting, setEditSubmitting] = useState(false)
   const [pubkey, setPubkey] = useState<{ publicKey: string; fingerprint: string } | null>(null)
   const [copied, setCopied] = useState(false)
@@ -618,6 +626,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     setEditSnmpPollInterval(r.snmp_poll_interval ?? 60)
     setEditSshPort(r.ssh_port ?? 22)
     setEditTempThreshold(r.temp_threshold != null ? String(r.temp_threshold) : '')
+    setEditRouterOSUser(r.routeros_user ?? '')
+    setEditRouterOSPassword('') // blank = conservar la password existente
+    setEditRouterOSInsecure(r.routeros_insecure ?? false)
     setError(null)
   }
 
@@ -644,6 +655,9 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           ssh_port: editSshPort,
           temp_threshold: editTempThreshold.trim() === '' ? 0 : Number(editTempThreshold),
           console_polling: editConsolePolling,
+          routeros_user: editType === 'routeros' ? editRouterOSUser.trim() : undefined,
+          routeros_password: editRouterOSPassword || undefined,
+          routeros_insecure: editType === 'routeros' ? editRouterOSInsecure : undefined,
         }),
       })
       if (res.status === 409) {
@@ -971,6 +985,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
             options={[
               { value: 'openwrt', label: 'OpenWrt' },
               { value: 'glinet', label: 'GL.iNet' },
+              { value: 'routeros', label: 'RouterOS' },
               { value: 'managed-switch', label: t('settings.routers.typeManaged') },
               { value: 'external', label: t('settings.routers.typeExternal') },
             ]}
@@ -1140,6 +1155,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   options={[
                     { value: 'openwrt', label: 'OpenWrt' },
                     { value: 'glinet', label: 'GL.iNet' },
+                    { value: 'routeros', label: 'RouterOS' },
                     { value: 'managed-switch', label: t('settings.routers.typeManaged') },
                     { value: 'external', label: t('settings.routers.typeExternal') },
                   ]}
@@ -1240,6 +1256,44 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   )}
                 </div>
               )}
+              {editType === 'routeros' && (
+                <div className="space-y-2.5 rounded-lg border border-border bg-canvas/50 p-3">
+                  <div className="grid grid-cols-2 gap-2.5">
+                    <div>
+                      <label htmlFor="routeros-user" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                        {t('settings.routers.routerosUser')}
+                      </label>
+                      <input
+                        id="routeros-user"
+                        type="text"
+                        value={editRouterOSUser}
+                        onChange={(e) => setEditRouterOSUser(e.target.value)}
+                        placeholder="admin"
+                        aria-label={t('settings.routers.routerosUser')}
+                        className="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"
+                      />
+                    </div>
+                    <div>
+                      <label htmlFor="routeros-password" className="mb-1 block text-caption font-medium uppercase tracking-[0.06em] text-text-muted">
+                        {t('settings.routers.routerosPassword')}
+                      </label>
+                      <input
+                        id="routeros-password"
+                        type="password"
+                        value={editRouterOSPassword}
+                        onChange={(e) => setEditRouterOSPassword(e.target.value)}
+                        placeholder={t('settings.routers.routerosPasswordPlaceholder')}
+                        aria-label={t('settings.routers.routerosPassword')}
+                        className="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"
+                      />
+                    </div>
+                  </div>
+                  <label className="flex cursor-pointer items-center gap-2 text-sm text-text-secondary">
+                    <Switch checked={editRouterOSInsecure} onCheckedChange={setEditRouterOSInsecure} />
+                    {t('settings.routers.routerosInsecure')}
+                  </label>
+                </div>
+              )}
               {error && <p className="text-caption text-danger">{error}</p>}
               <div className="flex items-center justify-between gap-2">
                 <button

+ 64 - 13
server-go/internal/adapters/live.go

@@ -97,8 +97,10 @@ type routerPolled struct {
 	board     *BoardInfo
 	cpu       int
 	ram       int
-	temp      int
-	uptimeSec float64
+	temp              int
+	flash             string
+	firmwareAvailable string
+	uptimeSec         float64
 	net       *NetDevBps
 	leases    []DhcpLease
 	// glClients (GL.iNet): base de clientes del firmware, superset de las
@@ -255,6 +257,10 @@ type Live struct {
 	snmpPorts map[string]map[string]snmpPortSample
 	// snmpLastPoll (issue #414): timestamp del último poll SNMP real por router.
 	snmpLastPoll map[string]time.Time
+	// roNetPrev: última muestra de contadores rx/tx del interfaz WAN de un
+	// router RouterOS, para calcular bps por delta entre polls (igual que
+	// GetNetDev de OpenWrt sobre /proc/net/dev, routeros_api.go).
+	roNetPrev map[string]netByteSample
 	// snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
 	// para loguear solo cuando el resultado cambia.
 	snmpFdbCount map[string]int
@@ -413,6 +419,7 @@ func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool
 		lastObsTs:            map[string]int64{},
 		snmpPorts:            map[string]map[string]snmpPortSample{},
 		snmpLastPoll:         map[string]time.Time{},
+		roNetPrev:            map[string]netByteSample{},
 		snmpFdbCount:         map[string]int{},
 		snmpBrMac:            map[string]string{},
 		snmpPollStats:        map[string]*snmpPollStat{},
@@ -517,7 +524,9 @@ func (l *Live) SetRouters(list []RouterConfig) {
 	l.gatewayCfg = pickGateway(l.routers)
 	l.clients = map[string]*OpenWrtClient{}
 	for _, c := range l.routers {
-		if !c.AgentOnly {
+		// RouterOS no habla SSH/ubus: se sondea por su REST API (routeros_live.go),
+		// sin cliente SSH.
+		if !c.AgentOnly && c.Type != "routeros" {
 			l.clients[c.ID] = NewOpenWrtClient(c, l.pool, "root", "")
 		}
 	}
@@ -575,6 +584,11 @@ func (l *Live) SetRouters(list []RouterConfig) {
 			delete(l.snmpBrMac, id)
 		}
 	}
+	for id := range l.roNetPrev {
+		if !ids[id] {
+			delete(l.roNetPrev, id)
+		}
+	}
 	for id := range l.snmpLastMetricsTick {
 		if !ids[id] {
 			delete(l.snmpLastMetricsTick, id)
@@ -954,6 +968,9 @@ func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled,
 	if cfg.SnmpEnabled {
 		return l.pollRouterSNMP(cfg)
 	}
+	if cfg.Type == "routeros" {
+		return l.pollRouterROS(cfg)
+	}
 	l.mu.Lock()
 	client := l.clients[cfg.ID]
 	gw := l.gatewayCfg
@@ -1214,7 +1231,9 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	}
 	if isGw {
 		r.Role, r.RoleBadge = "Gateway principal", "Principal"
-	} else if p.cfg.AgentOnly {
+	} else if p.cfg.Type == "routeros" {
+		r.Role, r.RoleBadge = "Router", "Router"
+	} else if p.cfg.AgentOnly || p.cfg.Type == "managed-switch" {
 		r.Role, r.RoleBadge = "Switch", "SW"
 	} else {
 		r.Role, r.RoleBadge = "Punto de acceso", "AP"
@@ -1243,7 +1262,10 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.cfg.Type != "" {
 		r.Type = p.cfg.Type
 	}
-	if outdatedFw {
+	if p.firmwareAvailable != "" && r.FirmwareTarget == "" {
+		r.FirmwareTarget = p.firmwareAvailable
+	}
+	if outdatedFw || p.firmwareAvailable != "" {
 		r.FirmwareOutdated = true
 		// Alerta no urgente (category system); el engine aplica dedup 5 min.
 		l.engine.Emit(AlertEvent{
@@ -1306,8 +1328,13 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 		r = *prev
 	} else {
 		model := "OpenWrt"
-		if cfg.Type == "glinet" {
+		switch cfg.Type {
+		case "glinet":
 			model = "GL.iNet"
+		case "routeros":
+			model = "RouterOS"
+		case "managed-switch":
+			model = "Managed Switch"
 		}
 		name := cfg.Name
 		if name == "" {
@@ -1318,13 +1345,19 @@ func (l *Live) offlineRouter(cfg RouterConfig) Router {
 			IP: cfg.Host, Health: 0,
 			CPU: iptr(0), RAM: iptr(0), Temp: iptr(0),
 			Uptime: "—", Clients: 0, Sparkline: []float64{},
+			Type: cfg.Type,
 		}
 		if gw != nil && cfg.ID == gw.ID {
 			r.Role, r.RoleBadge = "Gateway principal", "Principal"
+		} else if cfg.Type == "routeros" {
+			r.Role, r.RoleBadge = "Router", "Router"
+		} else if cfg.Type == "managed-switch" {
+			r.Role, r.RoleBadge = "Switch", "SW"
 		} else {
 			r.Role, r.RoleBadge = "Punto de acceso", "AP"
 		}
 	}
+	r.Type = cfg.Type
 	r.Status = "offline"
 	if l.accessMissing(cfg.ID) {
 		r.Status = "unreachable"
@@ -2228,15 +2261,17 @@ func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
 // FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
 func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 	leasesByMac := map[string]DhcpLease{}
+	leaseRouter := map[string]string{}
 	arpByMac := map[string]string{}
 	glByMac := map[string]DhcpLease{}
-	for _, p := range polled {
+	for rID, p := range polled {
 		for mac, ip := range p.arp {
 			arpByMac[mac] = ip
 		}
 		for _, le := range p.leases {
 			if le.MAC != "" {
 				leasesByMac[le.MAC] = le
+				leaseRouter[le.MAC] = rID
 			}
 		}
 		// gl-clients: fallback de IP para MACs sin lease (dnsmasq sin ese
@@ -2428,9 +2463,6 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			if _, ok := seen[mac]; ok {
 				continue
 			}
-			if _, ok := leasesByMac[mac]; ok {
-				continue
-			}
 			if _, ok := known[mac]; ok {
 				continue
 			}
@@ -2562,11 +2594,17 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 		// tiene idioma: "Desconocido" viajaba tal cual hasta la UI y salía en
 		// español en una interfaz en inglés. Quien pinta, traduce.
 		manufacturer := oui.Lookup(mac)
+		defaultRouterID := gwID
+		if defaultRouterID == "" {
+			if rID, ok := leaseRouter[mac]; ok {
+				defaultRouterID = rID
+			}
+		}
 		d := Device{
 			ID:  strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
 			MAC: mac, Manufacturer: manufacturer,
 			TrafficMbps: 0, Sparkline: []float64{},
-			RouterID: gwID, Band: "—",
+			RouterID: defaultRouterID, Band: "—",
 			Online: isSeen,
 		}
 		if hasLease {
@@ -2661,6 +2699,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled) []Device {
 			d.RouterID = k.routerID
 			d.Band = k.band
 			d.SignalDbm = k.signal
+		} else if rID, ok := leaseRouter[mac]; ok && d.RouterID == "" {
+			d.RouterID = rID
 		}
 		// #551: TrafficMbps del cliente desde el rate en memoria (nlbwmon u
 		// hostapd) sin consultar la store en cada rebuild. Solo online; los
@@ -3152,6 +3192,7 @@ type liveExtras struct {
 	MAC                 string        `json:"mac"`
 	Firmware            string        `json:"firmware"`
 	FirmwareUpdated     bool          `json:"firmwareUpdated"`
+	FirmwareAvailable   string        `json:"firmwareAvailable,omitempty"`
 	LastReboot          string        `json:"lastReboot"`
 	Soc                 string        `json:"soc"`
 	Flash               string        `json:"flash"`
@@ -3466,6 +3507,13 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 				extras.Soc = "—"
 			}
 		}
+		if p.firmwareAvailable != "" {
+			extras.FirmwareAvailable = p.firmwareAvailable
+			extras.FirmwareUpdated = false
+		}
+		if p.flash != "" {
+			extras.Flash = p.flash
+		}
 		if p.uptimeSec > 0 {
 			rb := time.Now().Add(-time.Duration(p.uptimeSec) * time.Second)
 			extras.LastReboot = fmt.Sprintf("%02d/%02d/%d, %02d:%02d", rb.Day(), int(rb.Month()), rb.Year(), rb.Hour(), rb.Minute())
@@ -3502,8 +3550,11 @@ func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, e
 		l.mu.Unlock()
 	}
 	if gw != nil && id == gw.ID {
-		detail.Adguard = l.pollAdGuard(ctx)
-		detail.Wireguard = l.pollWireGuard(clients)
+		// AdGuard Home y WireGuard (OpenWrt/GL.iNet ubus/SSH) no aplican a RouterOS.
+		if cfg.Type != "routeros" {
+			detail.Adguard = l.pollAdGuard(ctx)
+			detail.Wireguard = l.pollWireGuard(clients)
+		}
 	} else {
 		// Backhaul real del AP: boca que enlaza con otro router + latencia
 		var uplink *EthPort

+ 508 - 0
server-go/internal/adapters/routeros_api.go

@@ -0,0 +1,508 @@
+// routeros_api.go — cliente mínimo del API binario nativo de RouterOS
+// (puerto 8728), alternativa a la REST API (routeros_live.go) para routers
+// cuyo admin mantiene `www`/`www-ssl` cerrados por seguridad y solo permite
+// `api`/`api-ssl` — el mismo protocolo que usa Winbox y la mayoría de
+// herramientas de monitorización de RouterOS (LibreNMS, Zabbix...).
+//
+// Implementación mínima a propósito: login moderno (RouterOS 6.43+, una sola
+// sentencia, sin el challenge-response MD5 legacy) + sentencias de solo
+// lectura ("/algo/print"). Sin tags ni consultas concurrentes sobre la misma
+// conexión — una conexión nueva por poll, igual que el patrón ya usado para
+// SNMP (snmp_live.go). ponytail: puerto fijo 8728 sin TLS; api-ssl/8729
+// queda para más adelante si algún admin lo necesita (requiere manejar el
+// certificado del lado RouterOS, que muchas instalaciones no tienen listo).
+//
+// Protocolo: cada "palabra" lleva un prefijo de longitud de tamaño variable
+// (1-5 bytes según la magnitud); una "sentencia" es una secuencia de
+// palabras terminada por una palabra de longitud 0. Ver la wiki de MikroTik,
+// "API" — no hay biblioteca oficial en Go, y las de terceros son deps que
+// este proyecto prefiere evitar para algo de ~150 líneas.
+package adapters
+
+import (
+	"bufio"
+	"encoding/binary"
+	"fmt"
+	"io"
+	"net"
+	"strconv"
+	"strings"
+	"time"
+)
+
+type routerOSAPIConn struct {
+	conn net.Conn
+	r    *bufio.Reader
+}
+
+func dialRouterOSAPI(host, user, pass string, timeout time.Duration) (*routerOSAPIConn, error) {
+	conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, "8728"), timeout)
+	if err != nil {
+		return nil, err
+	}
+	_ = conn.SetDeadline(time.Now().Add(timeout))
+	c := &routerOSAPIConn{conn: conn, r: bufio.NewReader(conn)}
+	if err := c.writeSentence("/login", "=name="+user, "=password="+pass); err != nil {
+		conn.Close()
+		return nil, err
+	}
+	reply, err := c.readSentence()
+	if err != nil {
+		conn.Close()
+		return nil, err
+	}
+	if len(reply) == 0 || reply[0] != "!done" {
+		conn.Close()
+		return nil, fmt.Errorf("routeros api: login: %s", strings.Join(reply, " "))
+	}
+	return c, nil
+}
+
+func (c *routerOSAPIConn) Close() { _ = c.conn.Close() }
+
+// query ejecuta un comando de solo lectura (p.ej. "/system/resource/print")
+// y devuelve las filas !re como mapas atributo→valor.
+func (c *routerOSAPIConn) query(cmd string) ([]map[string]string, error) {
+	if err := c.writeSentence(cmd); err != nil {
+		return nil, err
+	}
+	var rows []map[string]string
+	for {
+		sentence, err := c.readSentence()
+		if err != nil {
+			return nil, err
+		}
+		if len(sentence) == 0 {
+			continue
+		}
+		switch sentence[0] {
+		case "!done":
+			return rows, nil
+		case "!trap":
+			return nil, fmt.Errorf("routeros api %s: %s", cmd, strings.Join(sentence[1:], " "))
+		case "!re":
+			row := map[string]string{}
+			for _, w := range sentence[1:] {
+				w = strings.TrimPrefix(w, "=")
+				if k, v, ok := strings.Cut(w, "="); ok {
+					row[k] = v
+				}
+			}
+			rows = append(rows, row)
+		}
+	}
+}
+
+func (c *routerOSAPIConn) writeSentence(words ...string) error {
+	for _, w := range words {
+		if err := writeRouterOSWord(c.conn, w); err != nil {
+			return err
+		}
+	}
+	return writeRouterOSWord(c.conn, "")
+}
+
+func (c *routerOSAPIConn) readSentence() ([]string, error) {
+	var words []string
+	for {
+		w, err := readRouterOSWord(c.r)
+		if err != nil {
+			return nil, err
+		}
+		if w == "" {
+			return words, nil
+		}
+		words = append(words, w)
+	}
+}
+
+func writeRouterOSWord(w io.Writer, word string) error {
+	if err := writeRouterOSLen(w, len(word)); err != nil {
+		return err
+	}
+	_, err := w.Write([]byte(word))
+	return err
+}
+
+// writeRouterOSLen codifica la longitud con el prefijo de tamaño variable
+// del protocolo RouterOS API.
+func writeRouterOSLen(w io.Writer, l int) error {
+	switch {
+	case l < 0x80:
+		_, err := w.Write([]byte{byte(l)})
+		return err
+	case l < 0x4000:
+		v := l | 0x8000
+		return binary.Write(w, binary.BigEndian, uint16(v))
+	case l < 0x200000:
+		buf := []byte{byte(l>>16) | 0xC0, byte(l >> 8), byte(l)}
+		_, err := w.Write(buf)
+		return err
+	case l < 0x10000000:
+		buf := []byte{byte(l>>24) | 0xE0, byte(l >> 16), byte(l >> 8), byte(l)}
+		_, err := w.Write(buf)
+		return err
+	default:
+		if _, err := w.Write([]byte{0xF0}); err != nil {
+			return err
+		}
+		return binary.Write(w, binary.BigEndian, uint32(l))
+	}
+}
+
+func readRouterOSWord(r *bufio.Reader) (string, error) {
+	l, err := readRouterOSLen(r)
+	if err != nil {
+		return "", err
+	}
+	if l == 0 {
+		return "", nil
+	}
+	buf := make([]byte, l)
+	if _, err := io.ReadFull(r, buf); err != nil {
+		return "", err
+	}
+	return string(buf), nil
+}
+
+// readRouterOSLen decodifica el prefijo de longitud de tamaño variable.
+func readRouterOSLen(r *bufio.Reader) (int, error) {
+	c0, err := r.ReadByte()
+	if err != nil {
+		return 0, err
+	}
+	switch {
+	case c0&0x80 == 0:
+		return int(c0), nil
+	case c0&0xC0 == 0x80:
+		c1, err := r.ReadByte()
+		if err != nil {
+			return 0, err
+		}
+		return int(c0&^0xC0)<<8 | int(c1), nil
+	case c0&0xE0 == 0xC0:
+		b := make([]byte, 2)
+		if _, err := io.ReadFull(r, b); err != nil {
+			return 0, err
+		}
+		return int(c0&^0xE0)<<16 | int(b[0])<<8 | int(b[1]), nil
+	case c0&0xF0 == 0xE0:
+		b := make([]byte, 3)
+		if _, err := io.ReadFull(r, b); err != nil {
+			return 0, err
+		}
+		return int(c0&^0xF0)<<24 | int(b[0])<<16 | int(b[1])<<8 | int(b[2]), nil
+	case c0 == 0xF0:
+		b := make([]byte, 4)
+		if _, err := io.ReadFull(r, b); err != nil {
+			return 0, err
+		}
+		return int(binary.BigEndian.Uint32(b)), nil
+	default:
+		return 0, fmt.Errorf("routeros api: invalid length prefix 0x%02x", c0)
+	}
+}
+
+// pollRouterROSAPI sondea RouterOS vía su API binario nativo — funciona
+// incluso si www/www-ssl están cerrados, siempre que `api` esté habilitado
+// para la IP del servidor NetPulse (lo más común: es el mismo puerto que usa
+// Winbox y la mayoría de herramientas de monitorización de terceros).
+func (l *Live) pollRouterROSAPI(cfg RouterConfig) (*routerPolled, error) {
+	conn, err := dialRouterOSAPI(cfg.Host, cfg.RouterOSUser, cfg.RouterOSPassword, 10*time.Second)
+	if err != nil {
+		return nil, err
+	}
+	defer conn.Close()
+
+	resRows, err := conn.query("/system/resource/print")
+	if err != nil {
+		return nil, err
+	}
+	if len(resRows) == 0 {
+		return nil, fmt.Errorf("routeros api %s: sin filas de /system/resource/print", cfg.ID)
+	}
+	idRows, err := conn.query("/system/identity/print")
+	if err != nil {
+		return nil, err
+	}
+	if len(idRows) == 0 {
+		return nil, fmt.Errorf("routeros api %s: sin filas de /system/identity/print", cfg.ID)
+	}
+
+	rr := resRows[0]
+	res := routerOSResource{
+		CPULoad:      rr["cpu-load"],
+		FreeMemory:   rr["free-memory"],
+		TotalMemory:  rr["total-memory"],
+		Uptime:       rr["uptime"],
+		Version:      rr["version"],
+		BoardName:    rr["board-name"],
+		Architecture: rr["architecture-name"],
+	}
+	id := routerOSIdentity{Name: idRows[0]["name"]}
+	p, err := buildRouterOSPoll(cfg, res, id)
+	if err != nil {
+		return nil, err
+	}
+	// Puertos y leases DHCP: best-effort — un router sin DHCP configurado o
+	// con permisos más estrechos en el usuario del API sigue reportando
+	// vitals aunque estas dos fallen (igual que el resto de sondas opcionales
+	// del pipeline OpenWrt: null/vacío en vez de tumbar todo el poll).
+	var ifRows []map[string]string
+	if rows, err := conn.query("/interface/print"); err == nil {
+		ifRows = rows
+		p.ports = routerOSPorts(rows)
+		p.brMac = routerOSBridgeMAC(rows)
+	}
+	if rows, err := conn.query("/ip/dhcp-server/lease/print"); err == nil {
+		p.leases = routerOSLeases(rows)
+	}
+	if rows, err := conn.query("/ip/arp/print"); err == nil {
+		p.arp, p.arpStale = routerOSArp(rows)
+	}
+	if rows, err := conn.query("/interface/bridge/host/print"); err == nil {
+		p.fdb = routerOSFDB(rows)
+	}
+	if rows, err := conn.query("/system/health/print"); err == nil {
+		p.temp = routerOSTemp(rows)
+	}
+	if cpuRows, err := conn.query("/system/resource/cpu/print"); err == nil && len(cpuRows) > 0 {
+		sum := 0
+		for _, row := range cpuRows {
+			l, _ := strconv.Atoi(row["load"])
+			sum += l
+		}
+		p.cpu = (sum + len(cpuRows)/2) / len(cpuRows)
+	}
+	if hdd, _ := strconv.ParseFloat(rr["total-hdd-space"], 64); hdd > 0 {
+		p.flash = fmt.Sprintf("%.0f MB", hdd/1e6)
+	}
+	if rows, err := conn.query("/system/package/update/print"); err == nil {
+		p.firmwareAvailable = routerOSPackageUpdate(rows)
+		if p.firmwareAvailable == "" {
+			_ = conn.writeSentence("/system/package/update/check-for-updates")
+			if _, err := conn.readSentence(); err == nil {
+				if rowsAfter, err := conn.query("/system/package/update/print"); err == nil {
+					p.firmwareAvailable = routerOSPackageUpdate(rowsAfter)
+				}
+			}
+		}
+	}
+	// Tráfico WAN (issue: "network traffic" en Overview daba 0 para
+	// RouterOS): identificar el interfaz de la ruta por defecto y calcular
+	// su bps por delta de contadores acumulados entre polls — mismo enfoque
+	// que GetNetDev de OpenWrt sobre /proc/net/dev, ponytail: solo IPv4
+	// (0.0.0.0/0); una ruta por defecto IPv6-only no se detecta.
+	if routeRows, err := conn.query("/ip/route/print"); err == nil {
+		if wanIface := routerOSWANInterface(routeRows); wanIface != "" {
+			p.net = l.routerOSNetRate(cfg.ID, ifRows, wanIface)
+		}
+	}
+	return p, nil
+}
+
+// netByteSample es la última muestra de contadores rx/tx de un interfaz
+// RouterOS, para calcular bps por delta entre polls.
+type netByteSample struct {
+	at      time.Time
+	rxBytes uint64
+	txBytes uint64
+}
+
+// routerOSWANInterface busca la ruta por defecto (0.0.0.0/0) en las filas de
+// /ip/route/print y devuelve su interfaz de salida, o "" si no hay ninguna.
+// Con gateway IP normal (NAT doméstico típico), RouterOS no expone un
+// "interface" resuelto en /ip/route/print — solo la IP del siguiente salto,
+// que no basta para identificar el interfaz sin resolver ARP/vecinos
+// (fuera de alcance por ahora). Con PPPoE/VPN (sin gateway IP tradicional),
+// el propio campo "gateway" YA es el nombre del interfaz (p.ej.
+// "telekom-pppoe") — ese caso sí se resuelve aquí.
+func routerOSWANInterface(routeRows []map[string]string) string {
+	for _, row := range routeRows {
+		if row["dst-address"] != "0.0.0.0/0" {
+			continue
+		}
+		if iface := row["interface"]; iface != "" {
+			return iface
+		}
+		if gw := row["gateway"]; gw != "" && net.ParseIP(gw) == nil {
+			return gw
+		}
+	}
+	return ""
+}
+
+// routerOSNetRate calcula bps rx/tx del interfaz WAN por delta de los
+// contadores acumulados de /interface/print entre este poll y el anterior.
+// nil en la primera muestra (sin delta posible) o si el contador se reinició
+// — misma convención que el resto del pipeline (null en vez de un pico falso).
+func (l *Live) routerOSNetRate(routerID string, ifRows []map[string]string, wanIface string) *NetDevBps {
+	var rxBytes, txBytes uint64
+	found := false
+	for _, row := range ifRows {
+		if row["name"] != wanIface {
+			continue
+		}
+		rxBytes, _ = strconv.ParseUint(row["rx-byte"], 10, 64)
+		txBytes, _ = strconv.ParseUint(row["tx-byte"], 10, 64)
+		found = true
+		break
+	}
+	if !found {
+		return nil
+	}
+	now := time.Now()
+	l.mu.Lock()
+	prev, ok := l.roNetPrev[routerID]
+	l.roNetPrev[routerID] = netByteSample{at: now, rxBytes: rxBytes, txBytes: txBytes}
+	l.mu.Unlock()
+	if !ok {
+		return nil
+	}
+	dt := now.Sub(prev.at).Seconds()
+	if dt <= 0 || rxBytes < prev.rxBytes || txBytes < prev.txBytes {
+		return nil
+	}
+	rx := float64(rxBytes-prev.rxBytes) * 8 / dt
+	tx := float64(txBytes-prev.txBytes) * 8 / dt
+	return &NetDevBps{RxBps: &rx, TxBps: &tx}
+}
+
+// routerOSPorts mapea /interface/print a EthPort — solo interfaces físicas
+// ("ether"): las virtuales (bridge, vlan, wireguard...) no son "puertos" en
+// el sentido que espera el panel de puertos del frontend.
+func routerOSPorts(rows []map[string]string) []EthPort {
+	ports := make([]EthPort, 0, len(rows))
+	for _, row := range rows {
+		if row["type"] != "ether" {
+			continue
+		}
+		name := row["name"]
+		ports = append(ports, EthPort{
+			ID:    name,
+			Label: name,
+			Up:    row["running"] == "true",
+			Iface: name,
+		})
+	}
+	return ports
+}
+
+// routerOSLeases mapea /ip/dhcp-server/lease/print a DhcpLease (MAC en
+// mayúsculas, misma convención que el resto del pipeline DHCP).
+func routerOSLeases(rows []map[string]string) []DhcpLease {
+	leases := make([]DhcpLease, 0, len(rows))
+	for _, row := range rows {
+		mac := strings.ToUpper(row["mac-address"])
+		if mac == "" {
+			continue
+		}
+		var expAt *int64
+		if exp := row["expires-after"]; exp != "" {
+			if sec, err := parseRouterOSUptime(exp); err == nil && sec > 0 {
+				at := time.Now().Unix() + int64(sec)
+				expAt = &at
+			}
+		}
+		leases = append(leases, DhcpLease{
+			MAC:            mac,
+			IP:             row["address"],
+			Hostname:       row["host-name"],
+			LeaseExpiresAt: expAt,
+		})
+	}
+	return leases
+}
+
+// routerOSBridgeMAC extrae la MAC principal del equipo (bridge o primer interface físico ether).
+func routerOSBridgeMAC(rows []map[string]string) string {
+	// 1. Interfaz bridge
+	for _, row := range rows {
+		if row["type"] == "bridge" {
+			mac := strings.ToUpper(strings.TrimSpace(row["mac-address"]))
+			if mac != "" && mac != "00:00:00:00:00:00" {
+				return mac
+			}
+		}
+	}
+	// 2. Primera interfaz ethernet física
+	for _, row := range rows {
+		if row["type"] == "ether" {
+			mac := strings.ToUpper(strings.TrimSpace(row["mac-address"]))
+			if mac != "" && mac != "00:00:00:00:00:00" {
+				return mac
+			}
+		}
+	}
+	// 3. Fallback a cualquier interfaz con MAC válida
+	for _, row := range rows {
+		mac := strings.ToUpper(strings.TrimSpace(row["mac-address"]))
+		if mac != "" && mac != "00:00:00:00:00:00" {
+			return mac
+		}
+	}
+	return ""
+}
+
+// routerOSArp mapea /ip/arp/print a map[MAC]IP y un conjunto de stale MACs.
+func routerOSArp(rows []map[string]string) (map[string]string, map[string]bool) {
+	arp := make(map[string]string, len(rows))
+	stale := make(map[string]bool)
+	for _, row := range rows {
+		if row["disabled"] == "true" || row["invalid"] == "true" {
+			continue
+		}
+		mac := strings.ToUpper(strings.TrimSpace(row["mac-address"]))
+		ip := strings.TrimSpace(row["address"])
+		if mac != "" && ip != "" {
+			arp[mac] = ip
+			if row["status"] == "failed" || row["status"] == "stale" {
+				stale[mac] = true
+			}
+		}
+	}
+	return arp, stale
+}
+
+// routerOSFDB mapea /interface/bridge/host/print a map[MAC]port, excluyendo
+// las entradas locales del propio router (local=true).
+func routerOSFDB(rows []map[string]string) map[string]string {
+	fdb := make(map[string]string, len(rows))
+	for _, row := range rows {
+		if row["local"] == "true" {
+			continue
+		}
+		mac := strings.ToUpper(strings.TrimSpace(row["mac-address"]))
+		port := strings.TrimSpace(row["on-interface"])
+		if mac != "" && port != "" {
+			fdb[mac] = port
+		}
+	}
+	return fdb
+}
+
+// routerOSTemp extrae la temperatura del CPU o placa desde /system/health/print.
+func routerOSTemp(rows []map[string]string) int {
+	for _, row := range rows {
+		name := row["name"]
+		if name == "cpu-temperature" || name == "temperature" || name == "board-temperature" {
+			if v, err := strconv.Atoi(row["value"]); err == nil && v > 0 {
+				return v
+			}
+		}
+	}
+	return 0
+}
+
+// routerOSPackageUpdate devuelve la versión disponible si hay una actualización pendiente.
+func routerOSPackageUpdate(rows []map[string]string) string {
+	for _, row := range rows {
+		latest := strings.TrimSpace(row["latest-version"])
+		installed := strings.TrimSpace(row["installed-version"])
+		if latest != "" && latest != installed {
+			return latest
+		}
+	}
+	return ""
+}
+

+ 244 - 0
server-go/internal/adapters/routeros_api_test.go

@@ -0,0 +1,244 @@
+package adapters
+
+import (
+	"bufio"
+	"bytes"
+	"net"
+	"testing"
+	"time"
+)
+
+func TestRouterOSLenRoundTrip(t *testing.T) {
+	for _, l := range []int{0, 1, 0x7F, 0x80, 0x3FFF, 0x4000, 0x1FFFFF, 0x200000, 0x0FFFFFFF, 0x10000000, 5_000_000} {
+		var buf bytes.Buffer
+		if err := writeRouterOSLen(&buf, l); err != nil {
+			t.Fatalf("writeRouterOSLen(%d): %v", l, err)
+		}
+		got, err := readRouterOSLen(bufio.NewReader(&buf))
+		if err != nil {
+			t.Fatalf("readRouterOSLen(%d): %v", l, err)
+		}
+		if got != l {
+			t.Errorf("roundtrip(%d) = %d", l, got)
+		}
+	}
+}
+
+func TestRouterOSWordRoundTrip(t *testing.T) {
+	words := []string{"", "/system/resource/print", "=cpu-load=6", "!re"}
+	for _, w := range words {
+		var buf bytes.Buffer
+		if err := writeRouterOSWord(&buf, w); err != nil {
+			t.Fatalf("writeRouterOSWord(%q): %v", w, err)
+		}
+		got, err := readRouterOSWord(bufio.NewReader(&buf))
+		if err != nil {
+			t.Fatalf("readRouterOSWord(%q): %v", w, err)
+		}
+		if got != w {
+			t.Errorf("roundtrip(%q) = %q", w, got)
+		}
+	}
+}
+
+func TestRouterOSPorts(t *testing.T) {
+	rows := []map[string]string{
+		{"name": "ether1", "type": "ether", "running": "true"},
+		{"name": "ether2", "type": "ether", "running": "false"},
+		{"name": "bridge1", "type": "bridge", "running": "true"}, // no es "ether" → excluida
+	}
+	ports := routerOSPorts(rows)
+	if len(ports) != 2 {
+		t.Fatalf("len(ports) = %d, want 2 (bridge excluded): %+v", len(ports), ports)
+	}
+	if ports[0].ID != "ether1" || !ports[0].Up {
+		t.Errorf("ports[0] = %+v", ports[0])
+	}
+	if ports[1].ID != "ether2" || ports[1].Up {
+		t.Errorf("ports[1] = %+v", ports[1])
+	}
+}
+
+func TestRouterOSLeases(t *testing.T) {
+	rows := []map[string]string{
+		{"address": "192.168.50.10", "mac-address": "aa:bb:cc:dd:ee:ff", "host-name": "laptop"},
+		{"address": "192.168.50.11", "mac-address": "", "host-name": "no-mac"}, // sin MAC → excluida
+	}
+	leases := routerOSLeases(rows)
+	if len(leases) != 1 {
+		t.Fatalf("len(leases) = %d, want 1: %+v", len(leases), leases)
+	}
+	if leases[0].MAC != "AA:BB:CC:DD:EE:FF" || leases[0].IP != "192.168.50.10" || leases[0].Hostname != "laptop" {
+		t.Errorf("leases[0] = %+v", leases[0])
+	}
+}
+
+func TestRouterOSWANInterface(t *testing.T) {
+	t.Run("explicit interface field", func(t *testing.T) {
+		rows := []map[string]string{
+			{"dst-address": "192.168.50.0/24", "interface": "bridge-lan"},
+			{"dst-address": "0.0.0.0/0", "interface": "ether1"},
+		}
+		if got := routerOSWANInterface(rows); got != "ether1" {
+			t.Errorf("routerOSWANInterface = %q, want ether1", got)
+		}
+	})
+	t.Run("PPPoE: gateway field IS the interface name", func(t *testing.T) {
+		// Caso real: RouterOS con WAN PPPoE no expone "interface" en la ruta
+		// por defecto, solo "gateway" con el nombre del interfaz PPPoE.
+		rows := []map[string]string{
+			{"dst-address": "0.0.0.0/0", "gateway": "telekom-pppoe", "immediate-gw": "telekom-pppoe"},
+		}
+		if got := routerOSWANInterface(rows); got != "telekom-pppoe" {
+			t.Errorf("routerOSWANInterface = %q, want telekom-pppoe", got)
+		}
+	})
+	t.Run("plain IP gateway: no resolvable interface", func(t *testing.T) {
+		rows := []map[string]string{
+			{"dst-address": "0.0.0.0/0", "gateway": "192.168.1.1"},
+		}
+		if got := routerOSWANInterface(rows); got != "" {
+			t.Errorf("routerOSWANInterface = %q, want empty (IP gateway, not an interface name)", got)
+		}
+	})
+	if got := routerOSWANInterface(nil); got != "" {
+		t.Errorf("routerOSWANInterface(nil) = %q, want empty", got)
+	}
+}
+
+func TestRouterOSNetRate(t *testing.T) {
+	l := &Live{roNetPrev: map[string]netByteSample{}}
+	ifRows := []map[string]string{
+		{"name": "ether1", "rx-byte": "1000000", "tx-byte": "500000"},
+	}
+
+	// Primera muestra: sin delta posible → nil.
+	if got := l.routerOSNetRate("gw", ifRows, "ether1"); got != nil {
+		t.Fatalf("first sample = %+v, want nil", got)
+	}
+
+	// Simular 1 segundo transcurrido con 125000 bytes rx / 62500 bytes tx más
+	// (=1 Mbps / 0.5 Mbps) forzando el timestamp cacheado hacia el pasado.
+	l.mu.Lock()
+	prev := l.roNetPrev["gw"]
+	prev.at = prev.at.Add(-1 * time.Second)
+	l.roNetPrev["gw"] = prev
+	l.mu.Unlock()
+	ifRows2 := []map[string]string{
+		{"name": "ether1", "rx-byte": "1125000", "tx-byte": "562500"},
+	}
+	got := l.routerOSNetRate("gw", ifRows2, "ether1")
+	if got == nil || got.RxBps == nil || got.TxBps == nil {
+		t.Fatalf("second sample = %+v, want non-nil rates", got)
+	}
+	if *got.RxBps < 990000 || *got.RxBps > 1010000 {
+		t.Errorf("RxBps = %v, want ~1000000", *got.RxBps)
+	}
+
+	// Contador reiniciado (reboot del router) → nil, no un pico negativo falso.
+	l.mu.Lock()
+	prev = l.roNetPrev["gw"]
+	prev.at = prev.at.Add(-1 * time.Second)
+	l.roNetPrev["gw"] = prev
+	l.mu.Unlock()
+	ifRowsReset := []map[string]string{
+		{"name": "ether1", "rx-byte": "100", "tx-byte": "50"},
+	}
+	if got := l.routerOSNetRate("gw", ifRowsReset, "ether1"); got != nil {
+		t.Errorf("reset counters = %+v, want nil", got)
+	}
+}
+
+// fakeRouterOSServer simula el suficiente protocolo API para probar
+// login+query de punta a punta sin hardware real: acepta cualquier login y
+// responde /system/resource/print con una fila fija.
+func fakeRouterOSServer(t *testing.T) (addr string, closeFn func()) {
+	t.Helper()
+	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	if err != nil {
+		t.Fatal(err)
+	}
+	go func() {
+		conn, err := ln.Accept()
+		if err != nil {
+			return
+		}
+		defer conn.Close()
+		c := &routerOSAPIConn{conn: conn, r: bufio.NewReader(conn)}
+
+		// /login
+		if _, err := c.readSentence(); err != nil {
+			return
+		}
+		_ = c.writeSentence("!done")
+
+		// /system/resource/print
+		if _, err := c.readSentence(); err != nil {
+			return
+		}
+		_ = c.writeSentence("!re", "=cpu-load=6", "=free-memory=892813312", "=total-memory=1073741824",
+			"=uptime=1d02h03m04s", "=version=7.23.3 (stable)", "=board-name=RB5009UG+S+", "=architecture-name=arm64")
+		_ = c.writeSentence("!done")
+
+		// /system/identity/print
+		if _, err := c.readSentence(); err != nil {
+			return
+		}
+		_ = c.writeSentence("!re", "=name=RB5009UG")
+		_ = c.writeSentence("!done")
+	}()
+	return ln.Addr().String(), func() { ln.Close() }
+}
+
+func TestRouterOSAPILoginAndQuery(t *testing.T) {
+	addr, closeFn := fakeRouterOSServer(t)
+	defer closeFn()
+	host, port, _ := net.SplitHostPort(addr)
+	_ = port // dialRouterOSAPI hardcodes 8728; dial the fake server directly instead
+
+	conn, err := net.DialTimeout("tcp", addr, 2*time.Second)
+	if err != nil {
+		t.Fatalf("dial fake server: %v", err)
+	}
+	c := &routerOSAPIConn{conn: conn, r: bufio.NewReader(conn)}
+	defer c.Close()
+
+	if err := c.writeSentence("/login", "=name=admin", "=password=test"); err != nil {
+		t.Fatalf("write login: %v", err)
+	}
+	reply, err := c.readSentence()
+	if err != nil {
+		t.Fatalf("read login reply: %v", err)
+	}
+	if len(reply) == 0 || reply[0] != "!done" {
+		t.Fatalf("login reply = %v, want !done", reply)
+	}
+
+	rows, err := c.query("/system/resource/print")
+	if err != nil {
+		t.Fatalf("query resource: %v", err)
+	}
+	if len(rows) != 1 || rows[0]["cpu-load"] != "6" || rows[0]["board-name"] != "RB5009UG+S+" {
+		t.Fatalf("resource rows = %+v", rows)
+	}
+
+	idRows, err := c.query("/system/identity/print")
+	if err != nil {
+		t.Fatalf("query identity: %v", err)
+	}
+	if len(idRows) != 1 || idRows[0]["name"] != "RB5009UG" {
+		t.Fatalf("identity rows = %+v", idRows)
+	}
+
+	res := routerOSResource{
+		CPULoad: rows[0]["cpu-load"], FreeMemory: rows[0]["free-memory"], TotalMemory: rows[0]["total-memory"],
+		Uptime: rows[0]["uptime"], Version: rows[0]["version"], BoardName: rows[0]["board-name"], Architecture: rows[0]["architecture-name"],
+	}
+	p, err := buildRouterOSPoll(RouterConfig{ID: "gw", Host: host}, res, routerOSIdentity{Name: idRows[0]["name"]})
+	if err != nil {
+		t.Fatalf("buildRouterOSPoll: %v", err)
+	}
+	if p.cpu != 6 || p.board.Hostname != "RB5009UG" || p.board.Release.Version != "7.23.3 (stable)" {
+		t.Errorf("polled = %+v board=%+v", p, p.board)
+	}
+}

+ 189 - 0
server-go/internal/adapters/routeros_live.go

@@ -0,0 +1,189 @@
+// routeros_live.go — sondeo nativo de routers MikroTik RouterOS.
+//
+// A diferencia de OpenWrt (SSH + ubus) o SNMP (switches gestionados sin
+// vitals), RouterOS 7+ expone una REST API HTTP directamente
+// (https://<host>/rest/...): se sondea desde el servidor sin SSH ni agente.
+// Router de primera clase igual que OpenWrt (Type "routeros" en vez de
+// "openwrt"/"glinet"): tiene vitals reales (CPU/RAM/uptime), a diferencia de
+// SNMP/external que van con VitalsAvailable=false (#441). Lo que SÍ queda
+// ausente por ahora son las features específicas de ubus (radios, DHCP,
+// LLDP, WireGuard...) — igual degradación amable que el resto de tipos no
+// completos del contrato Router.
+package adapters
+
+import (
+	"context"
+	"crypto/tls"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"regexp"
+	"strconv"
+	"time"
+)
+
+type routerOSResource struct {
+	CPULoad      string `json:"cpu-load"`
+	FreeMemory   string `json:"free-memory"`
+	TotalMemory  string `json:"total-memory"`
+	Uptime       string `json:"uptime"`
+	Version      string `json:"version"`
+	BoardName    string `json:"board-name"`
+	Architecture string `json:"architecture-name"`
+}
+
+type routerOSIdentity struct {
+	Name string `json:"name"`
+}
+
+var routerOSDurationRe = regexp.MustCompile(`(\d+)([wdhms])`)
+
+// parseRouterOSUptime convierte el uptime de RouterOS ("1w2d3h4m5s") a
+// segundos. ponytail: mismo parser que agent/cmd/routeros-pusher, duplicado
+// a propósito (módulos Go distintos, sin paquete compartido todavía) —
+// factorizar si aparece un tercer consumidor.
+func parseRouterOSUptime(s string) (float64, error) {
+	matches := routerOSDurationRe.FindAllStringSubmatch(s, -1)
+	if matches == nil {
+		return 0, fmt.Errorf("routeros: unparseable uptime %q", s)
+	}
+	unitSeconds := map[string]float64{"w": 604800, "d": 86400, "h": 3600, "m": 60, "s": 1}
+	var total float64
+	for _, m := range matches {
+		n, err := strconv.ParseFloat(m[1], 64)
+		if err != nil {
+			return 0, fmt.Errorf("routeros: bad uptime component %q: %w", m[0], err)
+		}
+		total += n * unitSeconds[m[2]]
+	}
+	return total, nil
+}
+
+func routerOSFetch(ctx context.Context, client *http.Client, baseURL, user, pass, path string, out any) error {
+	req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+path, nil)
+	if err != nil {
+		return err
+	}
+	req.SetBasicAuth(user, pass)
+	resp, err := client.Do(req)
+	if err != nil {
+		return err
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<12))
+		return fmt.Errorf("routeros: GET %s: %s: %s", path, resp.Status, body)
+	}
+	return json.NewDecoder(resp.Body).Decode(out)
+}
+
+// buildRouterOSPoll mapea resource+identity de RouterOS al routerPolled que
+// consume buildRouter. Separado de pollRouterROS para poder testear el
+// mapeo sin un servidor HTTP real.
+func buildRouterOSPoll(cfg RouterConfig, res routerOSResource, id routerOSIdentity) (*routerPolled, error) {
+	cpuLoad, err := strconv.Atoi(res.CPULoad)
+	if err != nil {
+		return nil, fmt.Errorf("routeros %s: bad cpu-load %q: %w", cfg.ID, res.CPULoad, err)
+	}
+	uptime, err := parseRouterOSUptime(res.Uptime)
+	if err != nil {
+		return nil, fmt.Errorf("routeros %s: %w", cfg.ID, err)
+	}
+	total, _ := strconv.ParseFloat(res.TotalMemory, 64)
+	free, _ := strconv.ParseFloat(res.FreeMemory, 64)
+	ramPct := 0
+	if total > 0 {
+		ramPct = int((total - free) / total * 100)
+	}
+
+	model := res.BoardName
+	if model == "" {
+		model = "RouterOS"
+	}
+	desc := "RouterOS " + res.Version
+	if res.BoardName != "" {
+		desc = "RouterOS " + res.Version + " (" + res.BoardName + ")"
+	}
+	soc := res.Architecture
+	if soc == "" {
+		soc = "routeros"
+	}
+	board := &BoardInfo{
+		Model:     model,
+		Hostname:  id.Name,
+		System:    soc,
+		BoardName: res.BoardName,
+	}
+	board.Release.Version = res.Version
+	board.Release.Target = res.Architecture
+	board.Release.Description = desc
+
+	sysInfo := &SysInfo{
+		Uptime: uptime,
+	}
+	sysInfo.Memory.Total = total
+	sysInfo.Memory.Free = free
+
+	return &routerPolled{
+		cfg:       cfg,
+		sysInfo:   sysInfo,
+		cpu:       cpuLoad,
+		ram:       ramPct,
+		uptimeSec: uptime,
+		board:     board,
+		polledAt:  time.Now().UnixMilli(),
+	}, nil
+}
+
+// pollRouterROS sondea un router RouterOS. Prueba primero el API binario
+// nativo (routeros_api.go, puerto 8728) — funciona aunque www/www-ssl estén
+// cerrados, que es justo la postura de seguridad habitual en RouterOS (el
+// admin expone `api`/`winbox` para gestión, no un panel web). Si el API
+// falla (deshabilitado, IP no permitida en su ACL), cae a REST como segundo
+// intento. ponytail: reintenta ambos caminos en CADA tick sin cachear cuál
+// funcionó — ambos fallan rápido (dial rechazado, no timeout); cachear
+// por-router si esto llega a pesar en la práctica.
+func (l *Live) pollRouterROS(cfg RouterConfig) (*routerPolled, error) {
+	if p, err := l.pollRouterROSAPI(cfg); err == nil {
+		return p, nil
+	} else if pRest, errRest := l.pollRouterROSRest(cfg); errRest == nil {
+		return pRest, nil
+	} else {
+		return nil, fmt.Errorf("routeros api: %w; rest: %v", err, errRest)
+	}
+}
+
+// pollRouterROSRest sondea un router RouterOS vía su REST API. Sin caché de
+// intervalo (a diferencia de SNMP, #414): dos GET ligeros por tick, mismo
+// coste que el sondeo SSH de OpenWrt.
+//
+// Prueba https primero y cae a http si la conexión es rechazada: muchos
+// RouterOS domésticos solo tienen el servicio `www` (HTTP) activo, no
+// `www-ssl`.
+func (l *Live) pollRouterROSRest(cfg RouterConfig) (*routerPolled, error) {
+	client := &http.Client{Timeout: 10 * time.Second}
+	if cfg.RouterOSInsecure {
+		client.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}} //nolint:gosec // opt-in, RouterOS de fábrica trae certs autofirmados
+	}
+
+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+	defer cancel()
+
+	var res routerOSResource
+	var id routerOSIdentity
+	var lastErr error
+	for _, scheme := range [...]string{"https", "http"} {
+		base := scheme + "://" + cfg.Host
+		if err := routerOSFetch(ctx, client, base, cfg.RouterOSUser, cfg.RouterOSPassword, "/rest/system/resource", &res); err != nil {
+			lastErr = err
+			continue
+		}
+		if err := routerOSFetch(ctx, client, base, cfg.RouterOSUser, cfg.RouterOSPassword, "/rest/system/identity", &id); err != nil {
+			lastErr = err
+			continue
+		}
+		return buildRouterOSPoll(cfg, res, id)
+	}
+	return nil, lastErr
+}

+ 68 - 0
server-go/internal/adapters/routeros_live_test.go

@@ -0,0 +1,68 @@
+package adapters
+
+import "testing"
+
+func TestParseRouterOSUptime(t *testing.T) {
+	cases := map[string]float64{
+		"5s":         5,
+		"4m5s":       245,
+		"3h4m5s":     11045,
+		"2d3h4m5s":   183845,
+		"1w2d3h4m5s": 788645,
+	}
+	for input, want := range cases {
+		got, err := parseRouterOSUptime(input)
+		if err != nil {
+			t.Fatalf("parseRouterOSUptime(%q): %v", input, err)
+		}
+		if got != want {
+			t.Errorf("parseRouterOSUptime(%q) = %v, want %v", input, got, want)
+		}
+	}
+}
+
+func TestParseRouterOSUptimeInvalid(t *testing.T) {
+	if _, err := parseRouterOSUptime("not-a-duration"); err == nil {
+		t.Fatal("expected error for unparseable uptime")
+	}
+}
+
+func TestBuildRouterOSPoll(t *testing.T) {
+	cfg := RouterConfig{ID: "core-router", Type: "routeros"}
+	res := routerOSResource{
+		CPULoad:      "3",
+		FreeMemory:   "33554432",  // 32 MiB free
+		TotalMemory:  "134217728", // 128 MiB total → 75% used
+		Uptime:       "1d02h03m04s",
+		Version:      "7.15",
+		BoardName:    "RB4011",
+		Architecture: "arm",
+	}
+	id := routerOSIdentity{Name: "MikroTik-Core"}
+
+	p, err := buildRouterOSPoll(cfg, res, id)
+	if err != nil {
+		t.Fatalf("buildRouterOSPoll: %v", err)
+	}
+	if p.cpu != 3 {
+		t.Errorf("cpu = %d, want 3", p.cpu)
+	}
+	if p.ram != 75 {
+		t.Errorf("ram = %d, want 75", p.ram)
+	}
+	if p.board == nil || p.board.Hostname != "MikroTik-Core" || p.board.Release.Version != "7.15" {
+		t.Errorf("board = %+v", p.board)
+	}
+	// noVitals no debe activarse para routeros: buildRouter solo lo hace por
+	// SnmpEnabled o agentKind=="external" (#441), ninguno aplica aquí.
+	if p.cfg.SnmpEnabled {
+		t.Error("routeros config should not have SnmpEnabled set")
+	}
+}
+
+func TestBuildRouterOSPollBadCPU(t *testing.T) {
+	res := routerOSResource{CPULoad: "n/a", Uptime: "1s"}
+	if _, err := buildRouterOSPoll(RouterConfig{ID: "r1"}, res, routerOSIdentity{}); err == nil {
+		t.Fatal("expected error for bad cpu-load")
+	}
+}

+ 8 - 2
server-go/internal/adapters/types.go

@@ -166,7 +166,7 @@ type Router struct {
 	// dispositivo ni entidades por router en ese caso. Ausente = no se
 	// expone (lo hace NetPulse).
 	SelfExpose *bool `json:"selfExpose,omitempty"`
-	// Type: "glinet"|"openwrt"|"managed-switch"|"external". El frontend lo usa
+	// Type: "glinet"|"openwrt"|"routeros"|"managed-switch"|"external". El frontend lo usa
 	// para NO ofrecer reinstall/upgrade de agentes en dispositivos que no usan
 	// el agente nativo (scrapers de switches, etc.).
 	Type   string `json:"type,omitempty"`
@@ -883,7 +883,7 @@ type RouterConfig struct {
 	ID        string `json:"id"`
 	Name      string `json:"name"`
 	Host      string `json:"host"`
-	Type      string `json:"type"` // "glinet"|"openwrt"
+	Type      string `json:"type"` // "glinet"|"openwrt"|"routeros"
 	IsGateway bool   `json:"is_gateway"`
 	AgentOnly bool   `json:"agent_only"`
 	CreatedAt int64  `json:"created_at"` // epoch ms
@@ -909,6 +909,12 @@ type RouterConfig struct {
 	// de este router. NULL/ausente = DefaultTempThreshold (65). Un router que
 	// corre más caliente sube el suyo sin ocultar problemas en los más frescos.
 	TempThreshold *int `json:"temp_threshold,omitempty"`
+	// RouterOS: credenciales de la REST API nativa (Type "routeros"). User no
+	// es secreto; Password nunca se serializa de vuelta (json:"-"), igual que
+	// la clave privada ed25519 del servidor.
+	RouterOSUser     string `json:"routeros_user,omitempty"`
+	RouterOSPassword string `json:"-"`
+	RouterOSInsecure bool   `json:"routeros_insecure"` // acepta TLS autofirmado (RouterOS de fábrica)
 }
 
 // TempThresholdValue resuelve el umbral efectivo de temperatura alta (°C) de

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

@@ -537,6 +537,11 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 		}
 	}
 
+	// RouterOS (Type "routeros"): credenciales de la REST API nativa.
+	migrate(sqldb, "routers", "routeros_user", "ALTER TABLE routers ADD COLUMN routeros_user TEXT")
+	migrate(sqldb, "routers", "routeros_password", "ALTER TABLE routers ADD COLUMN routeros_password TEXT")
+	migrate(sqldb, "routers", "routeros_insecure", "ALTER TABLE routers ADD COLUMN routeros_insecure INTEGER NOT NULL DEFAULT 0")
+
 	// Si no hubo migración Node (instalación fresca creada por Go), marca la
 	// DB para que el siguiente arranque no dispare una "migración" espuria
 	// (backup + reset de login_attempts) sobre una DB ya Go.

+ 28 - 5
server-go/internal/httpapi/config.go

@@ -115,6 +115,10 @@ type routerInput struct {
 	// TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
 	// Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
 	TempThreshold *int `json:"temp_threshold"`
+	// RouterOS: credenciales de la REST API nativa (Type "routeros").
+	RouterOSUser     *string `json:"routeros_user"`
+	RouterOSPassword *string `json:"routeros_password"`
+	RouterOSInsecure *bool   `json:"routeros_insecure"`
 }
 
 // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
@@ -192,8 +196,8 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 	if typ == "" {
 		typ = "openwrt"
 	}
-	if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
-		writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
+	if typ != "glinet" && typ != "openwrt" && typ != "routeros" && typ != "managed-switch" && typ != "external" {
+		writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
 		return
 	}
 	var firmwareTarget string
@@ -239,11 +243,24 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 		}
 		sshPort = p
 	}
+	routerosUser := ""
+	if in.RouterOSUser != nil {
+		routerosUser = strings.TrimSpace(*in.RouterOSUser)
+	}
+	routerosPassword := ""
+	if in.RouterOSPassword != nil {
+		routerosPassword = *in.RouterOSPassword
+	}
+	routerosInsecure := false
+	if in.RouterOSInsecure != nil {
+		routerosInsecure = *in.RouterOSInsecure
+	}
 	created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
 		Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
 		FirmwareTarget: firmwareTarget,
 		SnmpEnabled:    snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
-		SSHPort: sshPort,
+		SSHPort:        sshPort,
+		RouterOSUser:   routerosUser, RouterOSPassword: routerosPassword, RouterOSInsecure: routerosInsecure,
 	})
 	if err != nil {
 		writeError(w, http.StatusInternalServerError, "internal_error")
@@ -304,8 +321,8 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 	var typ *string
 	if in.Type != "" {
 		t := in.Type
-		if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
-			writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
+		if t != "glinet" && t != "openwrt" && t != "routeros" && t != "managed-switch" && t != "external" {
+			writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
 			return
 		}
 		typ = &t
@@ -358,6 +375,11 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 		}
 		tempThreshold = &v
 	}
+	var routerosUser *string
+	if in.RouterOSUser != nil {
+		v := strings.TrimSpace(*in.RouterOSUser)
+		routerosUser = &v
+	}
 	updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
 		Name: name, Host: host, Type: typ,
 		IsGateway: &gw, AgentOnly: &ao,
@@ -366,6 +388,7 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 		SSHPort:        sshPort,
 		TempThreshold:  tempThreshold,
 		ConsolePolling: in.ConsolePolling,
+		RouterOSUser:   routerosUser, RouterOSPassword: in.RouterOSPassword, RouterOSInsecure: in.RouterOSInsecure,
 	})
 	if !ok {
 		writeError(w, http.StatusNotFound, "not_found")

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

@@ -534,6 +534,47 @@ func TestConfigRoutersSNMP(t *testing.T) {
 	}
 }
 
+func TestConfigRoutersRouterOS(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+
+	// POST RouterOS con credenciales
+	res := doReq(t, "POST", srv.URL+"/api/config/routers", cookie,
+		`{"name":"mikrotik","host":"192.168.8.1","type":"routeros","routeros_user":"admin","routeros_password":"secretpassword","routeros_insecure":true}`)
+	if res.StatusCode != 201 {
+		t.Fatalf("POST router: %d", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	router := body["router"].(map[string]any)
+	if router["type"] != "routeros" {
+		t.Fatalf("type: %v", router["type"])
+	}
+	if router["routeros_user"] != "admin" {
+		t.Fatalf("routeros_user: %v", router["routeros_user"])
+	}
+	if router["routeros_insecure"] != true {
+		t.Fatalf("routeros_insecure: %v", router["routeros_insecure"])
+	}
+	if _, present := router["routeros_password"]; present {
+		t.Fatalf("routeros_password no debe devolverse en la API: %v", router)
+	}
+
+	// PUT actualiza usuario e insecure
+	res = doReq(t, "PUT", srv.URL+"/api/config/routers/mikrotik", cookie,
+		`{"host":"192.168.8.1","routeros_user":"netpulse","routeros_insecure":false}`)
+	if res.StatusCode != 200 {
+		t.Fatalf("PUT router: %d", res.StatusCode)
+	}
+	body = readJSON(t, res)
+	rt := body["router"].(map[string]any)
+	if rt["routeros_user"] != "netpulse" {
+		t.Fatalf("routeros_user tras PUT: %v", rt["routeros_user"])
+	}
+	if rt["routeros_insecure"] != false {
+		t.Fatalf("routeros_insecure tras PUT: %v", rt["routeros_insecure"])
+	}
+}
+
 // TestProxmoxConfig (#561): PUT/GET /api/config/proxmox
 //   - guardar url+token, GET no devuelve el secret (solo tokenSet)
 //   - url vacía desactiva (limpia kv)

+ 39 - 6
server-go/internal/routerstore/routerstore.go

@@ -27,7 +27,7 @@ const probeTimeout = 4 * time.Second
 // ListRouters devuelve la tabla routers ordenada is_gateway DESC,
 // created_at ASC, con is_gateway como booleano.
 func ListRouters(db *sql.DB) []adapters.RouterConfig {
-	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, temp_threshold, console_polling FROM routers ORDER BY is_gateway DESC, created_at ASC")
+	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, temp_threshold, console_polling, routeros_user, routeros_password, routeros_insecure FROM routers ORDER BY is_gateway DESC, created_at ASC")
 	if err != nil {
 		return []adapters.RouterConfig{}
 	}
@@ -35,10 +35,10 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 	out := []adapters.RouterConfig{}
 	for rows.Next() {
 		var r adapters.RouterConfig
-		var gw, ao, snmpEn, snmpPort, snmpInterval, sshPort, consolePoll int
-		var name, ft, snmpComm sql.NullString
+		var gw, ao, snmpEn, snmpPort, snmpInterval, sshPort, consolePoll, roInsecure int
+		var name, ft, snmpComm, roUser, roPass sql.NullString
 		var tt sql.NullInt64
-		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &sshPort, &tt, &consolePoll); err != nil {
+		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &sshPort, &tt, &consolePoll, &roUser, &roPass, &roInsecure); err != nil {
 			continue
 		}
 		// DEFAULT 1 de la migración, pero una fila insertada antes de la
@@ -58,6 +58,9 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 			v := int(tt.Int64)
 			r.TempThreshold = &v
 		}
+		r.RouterOSUser = roUser.String
+		r.RouterOSPassword = roPass.String
+		r.RouterOSInsecure = roInsecure == 1
 		out = append(out, r)
 	}
 	return out
@@ -147,6 +150,10 @@ type AddInput struct {
 	// ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
 	// nil = default ON (el sondeo no se desactiva por omisión).
 	ConsolePolling *bool
+	// RouterOS: credenciales de la REST API nativa (Type "routeros").
+	RouterOSUser     string
+	RouterOSPassword string
+	RouterOSInsecure bool
 }
 
 // AddRouter inserta un router (si IsGateway, el resto pierde el flag —
@@ -199,9 +206,13 @@ func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
 	if in.ConsolePolling != nil && !*in.ConsolePolling {
 		consolePoll = 0
 	}
+	roInsecure := 0
+	if in.RouterOSInsecure {
+		roInsecure = 1
+	}
 	if _, err := tx.Exec(
-		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, console_polling) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
-		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval, sshPort, consolePoll,
+		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, ssh_port, console_polling, routeros_user, routeros_password, routeros_insecure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval, sshPort, consolePoll, in.RouterOSUser, in.RouterOSPassword, roInsecure,
 	); err != nil {
 		return adapters.RouterConfig{}, err
 	}
@@ -249,6 +260,12 @@ type UpdateInput struct {
 	// ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
 	// nil = no tocar. DEFAULT ON (la columna migra a 1).
 	ConsolePolling *bool
+	// RouterOS: nil = no tocar. Password: string vacía se ignora (no borra
+	// una password ya guardada) — dejar el campo en blanco en el form de
+	// edición conserva la credencial existente.
+	RouterOSUser     *string
+	RouterOSPassword *string
+	RouterOSInsecure *bool
 }
 
 // UpdateRouter actualiza un router existente por id. Si IsGateway pasa a true,
@@ -355,6 +372,22 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 			sets = append(sets, "temp_threshold = NULL")
 		}
 	}
+	if in.RouterOSUser != nil {
+		sets = append(sets, "routeros_user = ?")
+		args = append(args, *in.RouterOSUser)
+	}
+	if in.RouterOSPassword != nil && *in.RouterOSPassword != "" {
+		sets = append(sets, "routeros_password = ?")
+		args = append(args, *in.RouterOSPassword)
+	}
+	if in.RouterOSInsecure != nil {
+		v := 0
+		if *in.RouterOSInsecure {
+			v = 1
+		}
+		sets = append(sets, "routeros_insecure = ?")
+		args = append(args, v)
+	}
 	if len(sets) > 0 {
 		args = append(args, id)
 		if _, err := tx.Exec("UPDATE routers SET "+strings.Join(sets, ", ")+" WHERE id = ?", args...); err != nil {