Ver Fonte

fix: batch of issue fixes across firmware, SNMP, agent packaging and topology (#1805)

* fix(firmware): isolate config backups and expose them on upgrades (#1795)

* feat(firmware): schedule automatic configuration backups (#1795)

* fix(channels): scan only on demand, never when the page opens (#1794)

* fix(openwrt): pass UCI config to the agent through procd env (#1772)

* fix(snmp): read firmware and short model from ENTITY-MIB (#1767)

* feat(snmp): read TP-Link identity and vitals from its enterprise MIB (#1802)

* fix(topology): absorb the gateway default route and show it on the internet card (#1791)

* fix(topology): resolve chip collisions before drawing the links (#1791)

* fix(topology): hang inferred leaf clients from their switch node (#1791)

* fix(topology): fan right-edge chips outward (#1791)

* feat(agent): report own interface MACs so the server absorbs them (#1765)

* docs(changelog): record the scheduled configuration backups of #1795

* feat(topology): show the VLAN of wired clients (#1757)

* feat(firmware): reset a stuck upgrade state from the card (#1776)

* fix(reinstall): keep the packaged agent UCI config in sync (#1476)

* feat(openwrt): install the agent as a package served by the server (#1476)

* feat(openwrt): serve and install the agent .apk on OpenWrt 25.12 (#1476)

* feat(topology): show the VLAN of wireless clients too (#1757)

* test(agentbin): stop assuming the tree has no embedded binaries (#1476)
Nacho há 1 mês atrás
pai
commit
cacc8a7c4d
60 ficheiros alterados com 3126 adições e 207 exclusões
  1. 21 0
      CHANGELOG.md
  2. 67 0
      agent/probe/ifacemacs.go
  3. 37 0
      agent/probe/ifacemacs_test.go
  4. 10 1
      agent/probe/iw.go
  5. 52 0
      agent/probe/iw_test.go
  6. 6 0
      agent/probe/local.go
  7. 6 0
      agent/probe/payload.go
  8. 15 1
      agent/probe/probe.go
  9. 16 2
      app/public/locales/en/translation.json
  10. 16 2
      app/public/locales/es/translation.json
  11. 23 1
      app/src/components/topology/TopologyMap.tsx
  12. 101 75
      app/src/components/topology/model.ts
  13. 13 0
      app/src/data/types.ts
  14. 4 55
      app/src/pages/ChannelPlan.tsx
  15. 181 1
      app/src/pages/FirmwareUpgrades.tsx
  16. 13 0
      deploy/openwrt/netpulse-agent/files/netpulse-agent.init
  17. 1 1
      docs/manual.en.md
  18. 1 1
      docs/manual.es.md
  19. 22 0
      server-go/cmd/netpulse/main.go
  20. 26 0
      server-go/cmd/netpulse/main_test.go
  21. 5 0
      server-go/internal/adapters/agent.go
  22. 29 0
      server-go/internal/adapters/defaultroute_test.go
  23. 51 14
      server-go/internal/adapters/live.go
  24. 45 0
      server-go/internal/adapters/selfmacs_1765_test.go
  25. 28 0
      server-go/internal/adapters/snmp_live.go
  26. 22 0
      server-go/internal/adapters/snmp_live_test.go
  27. 8 0
      server-go/internal/adapters/topology.go
  28. 26 6
      server-go/internal/adapters/topology_lldp_test.go
  29. 25 15
      server-go/internal/adapters/types.go
  30. 39 0
      server-go/internal/adapters/vlans_router_test.go
  31. 32 0
      server-go/internal/adapters/wifi_vlan_1757_test.go
  32. 12 1
      server-go/internal/agentbin/agentbin.go
  33. 58 0
      server-go/internal/agentbin/asset_test.go
  34. 5 1
      server-go/internal/db/db.go
  35. 22 0
      server-go/internal/firmware/store.go
  36. 60 0
      server-go/internal/firmware/store_test.go
  37. 81 0
      server-go/internal/httpapi/agent.go
  38. 10 4
      server-go/internal/httpapi/backup.go
  39. 193 0
      server-go/internal/httpapi/config_backup_schedule.go
  40. 97 0
      server-go/internal/httpapi/config_backup_schedule_test.go
  41. 24 0
      server-go/internal/httpapi/firmware.go
  42. 97 0
      server-go/internal/httpapi/firmware_backup_internal_test.go
  43. 69 0
      server-go/internal/httpapi/firmware_reset_test.go
  44. 133 16
      server-go/internal/httpapi/firmware_upload.go
  45. 5 0
      server-go/internal/httpapi/server.go
  46. 33 0
      server-go/internal/openwrtpkg/files/netpulse-agent.config
  47. 79 0
      server-go/internal/openwrtpkg/files/netpulse-agent.defaults
  48. 111 0
      server-go/internal/openwrtpkg/files/netpulse-agent.init
  49. 188 0
      server-go/internal/openwrtpkg/ipk.go
  50. 226 0
      server-go/internal/openwrtpkg/ipk_test.go
  51. 73 0
      server-go/internal/reinstall/apk_pkg_test.go
  52. 81 2
      server-go/internal/reinstall/reinstall.go
  53. 126 0
      server-go/internal/reinstall/script_test.go
  54. 135 0
      server-go/internal/snmp/entity.go
  55. 87 0
      server-go/internal/snmp/entity_test.go
  56. 4 3
      server-go/internal/snmp/oids.go
  57. 4 1
      server-go/internal/snmp/system.go
  58. 112 0
      server-go/internal/snmp/tplinkVitals.go
  59. 48 0
      server-go/internal/snmp/tplinkVitals_test.go
  60. 12 4
      server-go/internal/updater/stable.go

+ 21 - 0
CHANGELOG.md

@@ -7,6 +7,14 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- The server can serve the OpenWrt agent as an installable package (#1476). It builds the `.ipk` on the fly from the embedded binary and serves it from `/api/agents/{slug}/package`, so a reinstall installs the agent with its own init script and `/etc/config/netpulse-agent` as a conffile that survives a sysupgrade. Routers on OpenWrt 25.12 get the same treatment through `apk`: the package format of apk-tools 3 is signed, so the server does not fabricate it and instead serves the `.apk` the release workflow already builds, once it sits next to the binary in `agents/`. The script tries `opkg` first, then `apk`, and falls back to the previous loose-file install if there is no package manager or the download or the install fails, so nothing that worked before can break.
+- The firmware card can reset the upgrade state of a router (#1776). An attempt stuck in `running` or `rebooting` for more than fifteen minutes used to need an API call to clear, because the dismiss button only handled finished attempts. The status badge now offers a reset that drops the stale record, and a genuinely live upgrade is still respected.
+- Clients in the topology show their VLAN, wired and wireless (#1757): the router list carries the bridge VLAN filtering table, and each chip is coloured by the VLAN of the port it sits on, with the id and the LuCI name in its tooltip. The agent now also reports the access interface and the SSID of every wireless station, so a wireless client resolves its VLAN through the AP interface listed in the bridge table, the same way a wired client resolves it through its port. A client with neither a port nor an interface stays unlabelled instead of guessing.
+- Configuration backups can now run on a schedule (#1795): a card on the Firmware upgrades page picks a weekday and a time, and the server keeps the last and next run so a restart does not lose the cadence. The archives are isolated from the firmware uploads, which also makes them visible from the upgrades page instead of being buried in the generic backup listing.
+- Pending upgrades show their configuration backup (#1795): the upgrade card exposes the archive that belongs to the unit, so restoring after a flash no longer means hunting for a file by date.
+
 ### Changed
 
 - The per-unit actions live together now (#1803). **Regenerate token** moved from Settings > Fleet to the Actions column of the agents card, and **Forget host key** moved from the unit detail to the same card, so a unit's configuration is not split across three screens. Both keep their confirmation dialog and only appear where they apply: the token for netpulse agents, the host key for units NetPulse polls over SSH.
@@ -20,6 +28,19 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 - The rack picker lists every wired client that can be racked (#1804), not a short list of guessed types. The old filter only offered switches, servers, desktops and cameras, so modems, single-board computers, printers and anything the classifier could not name stayed hidden: the reporter saw 7 of their 32 clients and could not mount three of them. Phones, tablets, laptops and room appliances are still left out, and the panel says so.
 - The front panel of a racked unit only shows its physical ports (#1804). SNMP units publish their VLAN interface and their LAG as ethernet, so a TP-Link Omada put `vlan1` (ifIndex 1) and the port-channel (32769) on the faceplate next to the 28 real ports. The poller already classifies each interface by its IANA `ifType`; the faceplate now skips anything with a family, so VLANs, LAGs, bridges and tunnels stay out of the drawing while cables and profiles keep resolving by ifIndex.
 
+### Fixed
+
+- A reinstall now keeps the UCI configuration of the packaged agent in sync (#1476). On a router that already carries the `.ipk`/`.apk`, `/etc/config/netpulse-agent` is the conffile the init reads and the one that survives a sysupgrade, but the SSH reinstall only rewrote the agent environment file, so the native config kept the old token and could point at a server that no longer exists. The script now sets server, slug, token, SPKI fingerprint, scan interval and both ping targets through `uci` when the config file is present, deletes the target keys when they resolve to nothing, and adds the config and its uci-defaults to the sysupgrade list. Routers without the package are untouched: they keep working from the environment file.
+- Units now report the MACs of all their interfaces (#1765). Only the bridge MAC was absorbed, so the CPU port of a DSA switch, a VLAN interface or a radio could be learned by a neighbour and published as an unknown client forever. The agent sends the list and the server absorbs it; the field is optional, so older agents and pushers keep working unchanged and an external pusher will populate it when it is updated in its own repository.
+- The default route of the gateway no longer appears as a client (#1791). Its MAC sits in the ARP table and nothing else claimed it, so it showed up as an unknown device with no name and inflated the client count. It is now absorbed by the WAN gateway IP learned from the router, and the Internet card shows that address as **Default route** next to the public IP.
+- Topology links now end on the client node (#1791). Collision separation moved the chips after their cable paths were built, so the links kept pointing at the old coordinates and ended in empty space. Separation now runs first and every wired link lands on its chip.
+- Clients behind an inferred leaf switch now hang from it (#1791). The inferred node was created but its clients kept pointing at the gateway that handed them their IP, so the node showed up empty and the cables went straight to the router. They are attached to the inferred node now, which in turn hangs from the managed switch.
+- Chips of right-edge units now fan to the right (#1791). The old bias pushed them inward and piled them over the incoming links. The right edge uses the outward arc, so the cluster clears the center of the diagram.
+- TP-Link switches now report model, firmware, CPU and memory through their enterprise MIB (#1802). The firmware answers neither ENTITY-MIB nor HOST-RESOURCES-MIB, so `sysObjectID` selects the vendor and four private OIDs fill values that used to stay empty. The private MIB wins over the generic fallback, and a missing OID leaves the field unknown instead of zero.
+- SNMP switches now read the generic ENTITY-MIB (#1767): the chassis row supplies `entPhysicalSoftwareRev` as the firmware (falling back to `entPhysicalFirmwareRev`) and `entPhysicalModelName` as the short model. Units that only advertised a long sysDescr now show a real firmware version and a usable model name.
+- The packaged OpenWrt agent now receives its UCI configuration (#1772): the procd service passes server, token, slug, interval, scan interval, ping targets and SPKI fingerprint in a single `procd_set_param env` call. Bare `export`s never reached the daemon, so setting the ping targets in LuCI left the latency cards empty.
+- Opening the Channels page no longer starts a WiFi scan (#1794): with the periodic scan off, stale data used to trigger one automatically after six hours. Scanning happens only when you press **Scan now**, so beacon-sensitive clients keep their association.
+
 ## [2.50.0] - 2026-10-31
 
 **Router integrations are here.** This release completes the Integrations section that deploys, runs, updates and edits vendor pushers for you: MikroTik RouterOS, Asuswrt and Asuswrt-Merlin (installed on the router itself over SSH, the Merlin way under `/jffs` or with a password sign-in on stock dropbear), UniFi controllers, and a vendor catalog that grows without touching the core. The integration code lives in a separate repository, [netpulse-integrations](https://github.com/gnacho/netpulse-integrations), and each vendor ships as its own standalone binary speaking the same signed ingest contract as the native agent. You only ever download and run the code for hardware you actually own: no UniFi controller, no UniFi code on your box. That is the deal that makes NetPulse compatible with more platforms every release while the server binary carries no vendor code inside and the shared code stays a small contract anyone can review.

+ 67 - 0
agent/probe/ifacemacs.go

@@ -0,0 +1,67 @@
+// ifacemacs.go — identidades MAC de las interfaces del propio equipo (#1765).
+//
+// Un equipo de la flota puede responder por varias MACs: la del bridge, la de
+// cada VLAN, la del puerto CPU de un switch DSA y la de cada radio. Algunas de
+// ellas no son la MAC del router que se guarda en la flota, así que un vecino
+// las aprende en su FDB y las publica como clientes desconocidos sin nombre ni
+// IP. El equipo es la única fuente fiable de esa lista: nadie mejor que él sabe
+// qué MACs son suyas.
+//
+// El campo es opcional y aditivo: un agente o pusher que no lo envíe sigue
+// funcionando igual, y el servidor no inventa identidades que no recibe.
+package probe
+
+import (
+	"sort"
+	"strings"
+)
+
+// ParseIfaceMACs convierte la salida de CmdIfaceMACs ("iface mac" por línea)
+// en la lista de MACs propias, en mayúsculas, sin duplicados y ordenada.
+// Descarta la MAC nula (loopback) y cualquier línea que no traiga una MAC
+// ethernet válida.
+func ParseIfaceMACs(out string) []string {
+	seen := make(map[string]bool, 8)
+	macs := make([]string, 0, 8)
+	for _, line := range strings.Split(out, "\n") {
+		fields := strings.Fields(line)
+		if len(fields) < 2 {
+			continue
+		}
+		mac := normalizeIfaceMAC(fields[len(fields)-1])
+		if mac == "" || seen[mac] {
+			continue
+		}
+		seen[mac] = true
+		macs = append(macs, mac)
+	}
+	sort.Strings(macs)
+	return macs
+}
+
+// normalizeIfaceMAC acepta solo MAC ethernet de 6 octetos en hex. La MAC nula
+// es la de loopback y no identifica a nadie.
+func normalizeIfaceMAC(raw string) string {
+	mac := strings.ToUpper(strings.TrimSpace(raw))
+	if len(mac) != 17 {
+		return ""
+	}
+	for i := 0; i < 17; i++ {
+		c := mac[i]
+		if i%3 == 2 {
+			if c != ':' && c != '-' {
+				return ""
+			}
+			continue
+		}
+		isHex := (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')
+		if !isHex {
+			return ""
+		}
+	}
+	mac = strings.ReplaceAll(mac, "-", ":")
+	if mac == "00:00:00:00:00:00" {
+		return ""
+	}
+	return mac
+}

+ 37 - 0
agent/probe/ifacemacs_test.go

@@ -0,0 +1,37 @@
+package probe
+
+import (
+	"reflect"
+	"testing"
+)
+
+// #1765: el equipo reporta las MACs de todas sus interfaces para que el
+// servidor las absorba como identidades propias.
+func TestParseIfaceMACs(t *testing.T) {
+	out := "" +
+		"lo 00:00:00:00:00:00\n" +
+		"br-lan 94:83:C4:00:00:01\n" +
+		"eth0 94:83:C4:00:00:02\n" +
+		"eth0.20 94:83:C4:00:00:02\n" +
+		"wlan0 94:83:C4:12:34:56\n" +
+		"lan1 04:f4:1c:f3:46:66\n" +
+		"basura\n" +
+		"wan 94:83:C4:00:00:0\n"
+	got := ParseIfaceMACs(out)
+	want := []string{
+		"04:F4:1C:F3:46:66",
+		"94:83:C4:00:00:01",
+		"94:83:C4:00:00:02",
+		"94:83:C4:12:34:56",
+	}
+	if !reflect.DeepEqual(got, want) {
+		t.Fatalf("got %v, want %v", got, want)
+	}
+}
+
+// Una salida vacía no inventa identidades.
+func TestParseIfaceMACsEmpty(t *testing.T) {
+	if got := ParseIfaceMACs(""); len(got) != 0 {
+		t.Fatalf("got %v, want empty", got)
+	}
+}

+ 10 - 1
agent/probe/iw.go

@@ -38,6 +38,9 @@ type iwIface struct {
 	band    string
 	channel int
 	width   int
+	// ssid: `iw dev` la imprime en las interfaces AP/STA activas. Vacia en
+	// interfaces down o sin ESSID, y en kernels que no la publican.
+	ssid string
 }
 
 // ParseIwWireless parsea la salida combinada de CmdIwStationDump: clientes
@@ -89,6 +92,8 @@ func ParseIwWireless(out string) (map[string]WirelessClient, []Radio) {
 				cur.addr = strings.ToUpper(strings.TrimPrefix(trim, "addr "))
 			case cur != nil && strings.HasPrefix(trim, "type "):
 				cur.kind = strings.TrimPrefix(trim, "type ")
+			case cur != nil && strings.HasPrefix(trim, "ssid "):
+				cur.ssid = strings.TrimSpace(strings.TrimPrefix(trim, "ssid "))
 			case cur != nil && strings.HasPrefix(trim, "channel "):
 				f := strings.Fields(trim)
 				if len(f) >= 2 {
@@ -119,7 +124,11 @@ func ParseIwWireless(out string) (map[string]WirelessClient, []Radio) {
 				iface := strings.TrimSuffix(strings.TrimPrefix(f[3], "("), ")")
 				stationIface[station] = iface
 				if _, ok := clients[station]; !ok {
-					clients[station] = WirelessClient{Band: ifaces[iface].band}
+					c := WirelessClient{Band: ifaces[iface].band, Iface: iface}
+					// #1757: sin SSID no se puede ubicar la estacion en una
+					// VLAN; se deja vacio antes que inventarlo.
+					c.SSID = ifaces[iface].ssid
+					clients[station] = c
 				}
 			}
 			continue

+ 52 - 0
agent/probe/iw_test.go

@@ -0,0 +1,52 @@
+package probe
+
+import "testing"
+
+// #1757: `iw dev` declara el SSID de la interfaz AP y el cliente del station
+// dump lo hereda, para poder ubicarlo despues en su VLAN. La banda y el
+// signal siguen saliendo como siempre.
+func TestParseIwWirelessCarriesIfaceAndSSID(t *testing.T) {
+	out := "==DEV==\n" +
+		"phy#0\n" +
+		"\tInterface wlan0\n" +
+		"\t\taddr 24:9E:7D:0A:C3:1A\n" +
+		"\t\tssid IoT\n" +
+		"\t\ttype AP\n" +
+		"\t\tchannel 6 (2437 MHz), width: 20 MHz\n" +
+		"==IF==wlan0\n" +
+		"Station aa:bb:cc:dd:ee:01 (on wlan0)\n" +
+		"\tsignal:  -55 dBm\n" +
+		"\trx bytes:\t1234\n" +
+		"\ttx bytes:\t5678\n"
+	clients, _ := ParseIwWireless(out)
+	c, ok := clients["AA:BB:CC:DD:EE:01"]
+	if !ok {
+		t.Fatalf("falta el cliente: %+v", clients)
+	}
+	if c.Iface != "wlan0" || c.SSID != "IoT" {
+		t.Errorf("iface=%q ssid=%q, want wlan0 / IoT", c.Iface, c.SSID)
+	}
+	if c.Band != "2.4 GHz" || c.SignalDbm != -55 {
+		t.Errorf("band=%q signal=%d, want 2.4 GHz / -55", c.Band, c.SignalDbm)
+	}
+}
+
+// Una interfaz sin linea `ssid` deja el campo vacio: no se hereda el SSID de
+// otra interfaz ni se inventa uno.
+func TestParseIwWirelessWithoutSSIDLeavesItEmpty(t *testing.T) {
+	out := "==DEV==\n" +
+		"phy#0\n" +
+		"\tInterface wlan1\n" +
+		"\t\ttype AP\n" +
+		"==IF==wlan1\n" +
+		"Station aa:bb:cc:dd:ee:02 (on wlan1)\n" +
+		"\tsignal:  -70 dBm\n"
+	clients, _ := ParseIwWireless(out)
+	c, ok := clients["AA:BB:CC:DD:EE:02"]
+	if !ok {
+		t.Fatalf("falta el cliente: %+v", clients)
+	}
+	if c.Iface != "wlan1" || c.SSID != "" {
+		t.Errorf("iface=%q ssid=%q, want wlan1 / vacio", c.Iface, c.SSID)
+	}
+}

+ 6 - 0
agent/probe/local.go

@@ -498,6 +498,12 @@ func (p *Prober) probeSystem(ctx context.Context) *SystemData {
 		sd.BridgeMAC = strings.ToUpper(strings.TrimSpace(out))
 		any = true
 	}
+	if out := p.runBest(ctx, CmdIfaceMACs, 0); out != "" {
+		if macs := ParseIfaceMACs(out); len(macs) > 0 {
+			sd.IfaceMACs = macs
+			any = true
+		}
+	}
 
 	if !any {
 		return nil

+ 6 - 0
agent/probe/payload.go

@@ -109,6 +109,12 @@ type SystemData struct {
 	LossPct   *float64   `json:"lossPct"`             // solo gateway (ping WAN)
 	Backhaul  string     `json:"backhaul,omitempty"`  // "cable"|"wifi" (ausente = desconocido)
 	BridgeMAC string     `json:"bridgeMac,omitempty"` // MAC de br-lan (uplinks/topología)
+	// IfaceMACs (#1765): MACs de TODAS las interfaces del propio equipo
+	// (bridge, VLANs, puerto CPU de un switch DSA, radios). El servidor las
+	// absorbe como identidades de la unidad aunque las aprenda un vecino.
+	// Vacío o ausente con agentes y pushers antiguos: ningún cambio de
+	// contrato para ellos.
+	IfaceMACs []string `json:"ifaceMacs,omitempty"`
 	// Flash and FirmwareAvailable let an external pusher report storage and
 	// pending firmware without a vendor-specific server adapter. Both are
 	// optional and remain empty when the source does not expose them.

+ 15 - 1
agent/probe/probe.go

@@ -205,7 +205,15 @@ const (
 		`echo "==PORTS=="; for d in /sys/class/net/$BR/brif/*; do [ -r "$d/port_no" ] && echo "$(cat $d/port_no) $(basename $d)"; done; ` +
 		`echo "==MACS=="; (brctl showmacs $BR 2>/dev/null | awk 'NR>1 && $3=="no" {print $1, $2}') 2>/dev/null; ` +
 		`(bridge fdb show br $BR 2>/dev/null | awk 'NF>=3 && $1!="01:" && $1!="33:33:" && $1!="ff:ff:" && $1!="00:00:00:00:00:00" && $0 !~ /permanent/ {for(i=1;i<=NF;i++) if($i=="dev"){print $(i+1), $1}}') 2>/dev/null; true`
-	CmdBridgeMAC       = bridgeDetect + "cat /sys/class/net/$BR/address 2>/dev/null"
+	CmdBridgeMAC = bridgeDetect + "cat /sys/class/net/$BR/address 2>/dev/null"
+	// CmdIfaceMACs (#1765): "iface mac" de TODAS las interfaces del kernel.
+	// Un equipo responde por la MAC del bridge, la de cada VLAN, la del puerto
+	// CPU de un switch DSA y la de cada radio. Las que no son la MAC del router
+	// guardado en la flota se aprenden en la FDB de un vecino y salían como
+	// clientes desconocidos sin nombre ni IP. El equipo es la única fuente
+	// fiable de su propia lista.
+	CmdIfaceMACs = `for d in /sys/class/net/*; do i=$(basename "$d"); ` +
+		`[ -r "$d/address" ] && echo "$i $(cat "$d/address" 2>/dev/null)"; done`
 	CmdUbusSystemBoard = "ubus call system board"
 	CmdUbusSystemInfo  = "ubus call system info"
 	CmdUbusWireless    = "ubus call network.wireless status"
@@ -331,6 +339,12 @@ type WirelessClient struct {
 	Band      string `json:"band"`
 	RxBytes   uint64 `json:"rxBytes,omitempty"`
 	TxBytes   uint64 `json:"txBytes,omitempty"`
+	// Iface/SSID (#1757): interfaz AP y SSID con la que la estacion esta
+	// asociada. Permiten al servidor cruzar la estacion con el bridge VLAN
+	// filtering y saber en que segmento vive. Omitidos cuando la fuente no
+	// los expone (wl, iwinfo, drivers sin esa salida): el campo es opcional.
+	Iface string `json:"iface,omitempty"`
+	SSID  string `json:"ssid,omitempty"`
 }
 
 // PortState es {name, up, speed} de una interfaz (/sys operstate+speed).

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

@@ -1518,7 +1518,9 @@
       "pill": "VM",
       "note": "Virtual machine on the hypervisor · its traffic rides the host's cable",
       "noteIn": "Virtual machine on {{host}} · virtual bridge ({{port}}) · traffic rides the host's cable"
-    }
+    },
+    "defaultRoute": "Default route",
+    "vlan": "VLAN"
   },
   "settings": {
     "admin": {
@@ -2566,7 +2568,19 @@
     "tipUpgradeOwut": "Flashes the target version now with owut (keeping current packages)",
     "tipSchedule": "Schedule the upgrade for later or recurring",
     "tipSave": "Saves model and target for the classic flow (URL/image)",
-    "owutStepsGroup": "owut steps"
+    "owutStepsGroup": "owut steps",
+    "backupScheduleTitle": "Scheduled configuration backups",
+    "backupScheduleCaption": "Sends a weekly backup to connected agents. If none are online, it retries after reconnection.",
+    "backupScheduleEnabled": "Enable",
+    "backupScheduleDay": "Weekday",
+    "backupScheduleTime": "Time",
+    "backupScheduleSave": "Save",
+    "backupScheduleSaved": "Schedule saved",
+    "backupScheduleError": "Could not save the schedule",
+    "backupScheduleLastRun": "Last: {{when}}",
+    "backupScheduleNextRun": "Next: {{when}}",
+    "resetStale": "Reset state",
+    "resetStaleHint": "Clears the record of an attempt that has been stuck for more than 15 minutes (the router never came back or the SSH session died), so you can start it again."
   },
   "orchestration": {
     "title": "Orchestration",

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

@@ -1518,7 +1518,9 @@
       "pill": "VM",
       "note": "Máquina virtual en el hipervisor · su tráfico viaja por el cable del host",
       "noteIn": "Máquina virtual en {{host}} · bridge virtual ({{port}}) · tráfico por el cable del host"
-    }
+    },
+    "defaultRoute": "Ruta por defecto",
+    "vlan": "VLAN"
   },
   "settings": {
     "admin": {
@@ -2566,7 +2568,19 @@
     "tipUpgradeOwut": "Flashea ahora la versión de destino con owut (con los paquetes actuales)",
     "tipSchedule": "Programa la actualización para más tarde o de forma recurrente",
     "tipSave": "Guarda modelo y target para el flujo clásico (URL/imagen)",
-    "owutStepsGroup": "Pasos owut"
+    "owutStepsGroup": "Pasos owut",
+    "backupScheduleTitle": "Backups de configuración programados",
+    "backupScheduleCaption": "Envía un backup semanal a los agentes conectados. Si no hay ninguno, se reintenta al reconectar.",
+    "backupScheduleEnabled": "Activar",
+    "backupScheduleDay": "Día de la semana",
+    "backupScheduleTime": "Hora",
+    "backupScheduleSave": "Guardar",
+    "backupScheduleSaved": "Programación guardada",
+    "backupScheduleError": "No se pudo guardar la programación",
+    "backupScheduleLastRun": "Último: {{when}}",
+    "backupScheduleNextRun": "Próximo: {{when}}",
+    "resetStale": "Reiniciar estado",
+    "resetStaleHint": "Borra el registro de un intento que lleva más de 15 minutos sin avanzar (el router no volvió o el SSH murió), para poder lanzarlo otra vez."
   },
   "orchestration": {
     "title": "Orquestación",

+ 23 - 1
app/src/components/topology/TopologyMap.tsx

@@ -244,6 +244,7 @@ function TooltipCard({
           </div>
           <div className="mt-2 grid grid-cols-2 gap-1.5">
             <MiniStat label={t('routerDetail.wan.publicIp')} value={wan.publicIp} />
+            <MiniStat label={t('topology.defaultRoute')} value={wan.gateway || '—'} />
             <MiniStat label={t('topology.plan')} value={wan.plan} />
             <MiniStat label={t('home.latency')} value={wan.latencyMs > 0 ? `${Math.round(wan.latencyMs)} ms` : '—'} />
             <MiniStat label={t('home.traffic.loss')} value={`${wan.lossPct} %`} />
@@ -449,6 +450,12 @@ function ChipTooltip({
           />
           <MiniStat label={t('topology.traffic')} value={`${d.trafficMbps >= 1 ? fmtEs(d.trafficMbps, 1) : fmtEs(d.trafficMbps, 2)} Mbps`} />
         </div>
+        {chip.vlan && (
+          <MiniStat
+            label={t('topology.vlan')}
+            value={`${chip.vlan.id}${chip.vlan.name ? ` · ${chip.vlan.name}` : ''}`}
+          />
+        )}
       </div>
       {d.lldp && (
         <div className="mt-2 text-caption font-semibold text-accent">
@@ -1917,6 +1924,12 @@ const DistNodeGroup = memo(function DistNodeGroup({
 // Chip de dispositivo (cliente wifi/cable, hub, host hipervisor o CT)
 // ---------------------------------------------------------------------------
 
+/** #1757: color estable por id de VLAN. Paleta corta y repetible: el objetivo
+ *  es distinguir segmentos de un vistazo, no codificar una semántica fija. */
+const VLAN_COLORS = ['#60A5FA', '#F472B6', '#FBBF24', '#34D399', '#A78BFA', '#FB923C'] as const
+const vlanColor = (id: number) =>
+  VLAN_COLORS[((Math.trunc(id) % VLAN_COLORS.length) + VLAN_COLORS.length) % VLAN_COLORS.length]!
+
 const ChipGroup = memo(function ChipGroup({
   chip,
   ctCount,
@@ -1953,7 +1966,15 @@ const ChipGroup = memo(function ChipGroup({
   const half = S / 2
   // #845: el icono elegido por el usuario manda sobre el tipo deducido.
   const Icon = deviceIcon(d)
-  const stroke = d.lldp ? COLOR.accent : chip.wired ? COLOR.ok : 'rgb(var(--border-strong))'
+  // #1757: la VLAN manda sobre el color del borde para que dos clientes del
+  // mismo puerto/VLAN se lean como el mismo segmento. LLDP sigue con su badge.
+  const stroke = chip.vlan
+    ? vlanColor(chip.vlan.id)
+    : d.lldp
+      ? COLOR.accent
+      : chip.wired
+        ? COLOR.ok
+        : 'rgb(var(--border-strong))'
   // Host hipervisor (Proxmox…): mini NODO redondo con sus CTs detrás, no un
   // chip cuadrado más (#656 feedback). Acento cuando viene de la API PVE.
   // #1446: un host sin invitados sigue siendo host (si no, caía a cliente).
@@ -1963,6 +1984,7 @@ const ChipGroup = memo(function ChipGroup({
     <g
       transform={`translate(${chip.x} ${chip.y})`}
       data-node-id={chip.id}
+      data-vlan-id={chip.vlan ? String(chip.vlan.id) : undefined}
       className={onDragStart ? 'cursor-grab' : undefined}
       onPointerDown={onDragStart}
     >

+ 101 - 75
app/src/components/topology/model.ts

@@ -60,6 +60,9 @@ export interface ChipNode {
   hubId: string
   /** CT/VM anidado bajo un hipervisor (grid, sin enlace propio al router) */
   isCt: boolean
+  /** #1757: VLAN del puerto del cliente cableado (bridge VLAN filtering).
+   *  Ausente si la unidad no publica VLANs o el puerto no aparece. */
+  vlan?: { id: number; name?: string; pvid: boolean }
 }
 
 /** Vista de un DistributionNode kind=inferred (círculo dashed, sin IP). */
@@ -507,14 +510,15 @@ function ringLayoutCount<T extends { x: number; y: number; size?: number }>(
   const free = freeArcs(excludes)
   const totalFree = free.reduce((a, [s, e]) => a + (e - s), 0)
   if (totalFree <= 0) return 0
-  // #1416: unidad pegada a un borde lateral del lienzo → rellenar primero
-  // los arcos que apuntan hacia DENTRO (el lado con más sitio). Los chips de
-  // los arcos exteriores caen fuera del viewport y ensuciaban el centro del
-  // diagrama. El hint es el ángulo cardinal de ese lado; los arcos se
-  // reordenan por distancia angular de su punto medio al hint (los de su
-  // lado primero; orden estable en el resto). Unidades centradas: sin
-  // cambio (sideHint null conserva el orden documental 0°→360°).
-  const sideHint = node.x < VB_W / 3 ? 0 : node.x > (2 * VB_W) / 3 ? 180 : null
+  // #1416: unidad pegada al borde izquierdo → rellenar primero los arcos que
+  // apuntan hacia DENTRO (el lado con más sitio). #1791: en el borde derecho
+  // el abanico va hacia FUERA, a la derecha, para no amontonar los chips
+  // sobre los enlaces que llegan desde el centro del diagrama. El hint es el
+  // ángulo cardinal de ese lado; los arcos se reordenan por distancia
+  // angular de su punto medio al hint (los de su lado primero; orden estable
+  // en el resto). Unidades centradas: sin cambio (sideHint null conserva el
+  // orden documental 0°→360°).
+  const sideHint = node.x < VB_W / 3 ? 0 : node.x > (2 * VB_W) / 3 ? 0 : null
   const arcMid = ([s, e]: [number, number]) => norm(s + (e - s) / 2)
   const angDist = (a: number, b: number) => {
     const d = norm(a - b)
@@ -1046,6 +1050,27 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
 
   // -- chips de dispositivos --------------------------------------------------
   const chips: ChipNode[] = []
+  // #1757: VLAN del puerto del cliente cableado. El bridge VLAN filtering del
+  // router dice qué VLANs lleva cada puerto; PVID es la nativa y manda, y sin
+  // PVID se toma la primera entrada. Solo cableado: la API no declara la VLAN
+  // de un cliente WiFi, y suponerla sería inventar el dato.
+  const vlanOf = (d: Device): ChipNode['vlan'] => {
+    // #1757: `bridge vlan show` lista también las interfaces AP (wlan0,
+    // wlan1) como puertos del bridge, así que la estación inalámbrica se
+    // resuelve por su interfaz igual que un cliente cableado por su puerto.
+    // Si el agente no declara ninguna de las dos cosas, no hay VLAN.
+    const port = isWired(d) ? d.port : d.wifiIface
+    if (!port) return undefined
+    const ports = routers.find((r) => r.id === d.routerId)?.vlans
+    if (!ports) return undefined
+    for (const entry of ports) {
+      if (entry.port !== port) continue
+      const hit = entry.vlans.find((v) => v.pvid) ?? entry.vlans[0]
+      if (hit) return { id: hit.id, name: hit.name, pvid: hit.pvid }
+    }
+    return undefined
+  }
+
   const mkChip = (d: Device, hubId: string, isCt = false): ChipNode => ({
     kind: 'chip',
     id: d.id,
@@ -1058,6 +1083,7 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     weak: d.signalDbm != null && d.signalDbm <= -65,
     hubId,
     isCt,
+    vlan: vlanOf(d),
   })
 
   // wifi: anillos con arcos prohibidos (uplink, etiqueta, WAN, fan cableado)
@@ -1393,6 +1419,73 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
     return `M ${start.x} ${start.y} Q ${mx} ${my}, ${end.x} ${end.y}`
   }
 
+  // --- NORMA DE SEPARACIÓN DE CABLES (9-Ago-2026) ---
+  // Se recogen los segmentos hub→chip de todos los enlaces (uplinks, dist,
+  // wired, CTs). El resolver empuja cada chip fuera de los cables AJENOS (los
+  // que no le pertenecen) con un margen, para que ningún dispositivo quede
+  // encima de un cable de otro.
+  const repelSegments: { x1: number; y1: number; x2: number; y2: number; ownerId?: string }[] = []
+  for (const c of chips) {
+    if (!c.wired || c.isCt) continue
+    const hub = routerNodes.find(rn => rn.id === c.hubId) ?? distNodes.find(dn => dn.id === c.hubId)
+    if (!hub) continue
+    repelSegments.push({ x1: hub.x, y1: hub.y, x2: c.x, y2: c.y, ownerId: c.id })
+  }
+  for (const [hostId, cts] of ctsByHost) {
+    const hostChip = chips.find((c) => c.id === hostId)
+    if (!hostChip) continue
+    for (const ct of cts) repelSegments.push({ x1: hostChip.x, y1: hostChip.y, x2: ct.x, y2: ct.y, ownerId: ct.id })
+  }
+  for (const dn of distNodes) {
+    const from = dn.node.parent
+      ? distNodes.find((n) => n.id === dn.node.parent)
+      : routerById.get(dn.node.routerId)
+    if (from) repelSegments.push({ x1: from.x, y1: from.y, x2: dn.x, y2: dn.y })
+  }
+  for (const rn of routerNodes) {
+    if (rn.id === gatewayNode?.id || !gatewayNode) continue
+    repelSegments.push({ x1: gatewayNode.x, y1: gatewayNode.y, x2: rn.x, y2: rn.y })
+  }
+
+  // --- Resolución de colisiones ---
+  // Routers fijos (no se mueven); chips se empujan y atraen hacia su hub padre.
+  // restDist = distancia inicial hub→chip (la posición canónica del layout);
+  // el resolver la usa como radio objetivo para que los chips no se dispersen
+  // tras una colisión ni se amontonen sobre el hub.
+  // Los nodos fijos llevan MARGEN (norma de separación): un chip no puede
+  // quedar pegado al borde de un router/distnode/Internet — mínimo
+  // r_nodo + r_chip + margin + padding. El gateway (r40) usa margen mayor.
+  const collidables: { x: number; y: number; r: number; fixed?: boolean; margin?: number; hubX?: number; hubY?: number; restDist?: number; id?: string }[] = [
+    ...routerNodes.map((rn) => ({ x: rn.x, y: rn.y, r: rn.r, fixed: true, margin: rn.id === gatewayNode?.id ? 40 : 26 })),
+    { x: internetNode.x, y: internetNode.y, r: 30, fixed: true, margin: 30 },
+  ]
+  // chips: buscar coords del hub padre
+  for (const c of chips) {
+    const hub = routerNodes.find(rn => rn.id === c.hubId) ?? distNodes.find(dn => dn.id === c.hubId)
+    const isHost = hypervisorHosts.has(c.id)
+    if (hub) {
+      const restDist = Math.sqrt((c.x - hub.x) ** 2 + (c.y - hub.y) ** 2)
+      // Los hosts hipervisores son NODOS con hijos (CTs): fijos, como los
+      // distnodes — no deben ser desplazados por los cables ajenos (si no, el
+      // resolver los lanza a la esquina). Sus CTs sí se acomodan a su alrededor.
+      collidables.push({
+        id: c.id, x: c.x, y: c.y, r: c.size / 2,
+        fixed: isHost, margin: isHost ? 16 : undefined,
+        hubX: hub.x, hubY: hub.y, restDist,
+      })
+    } else {
+      collidables.push({ id: c.id, x: c.x, y: c.y, r: c.size / 2, fixed: isHost, margin: isHost ? 16 : undefined })
+    }
+  }
+  // distnodes fijos
+  for (const dn of distNodes) {
+    collidables.push({ x: dn.x, y: dn.y, r: dn.r, fixed: true, margin: 14 })
+  }
+  resolveCollisions(collidables, 80, 14, repelSegments)
+  // Escribir posiciones de vuelta (solo chips; routers y distnodes son fixed)
+  let ci = routerNodes.length + 1 // +1 = Internet (añadido tras los routers)
+  for (const c of chips) { const ref = collidables[ci]!; c.x = ref.x; c.y = ref.y; ci++ }
+
   // -- enlaces -----------------------------------------------------------------
   const links: TopoLink[] = []
   if (gatewayNode) {
@@ -1906,73 +1999,6 @@ export function buildTopologyModel({ routers, devices, wan, wireguard, distribut
   const relatedTo = (nodeId: string) =>
     adjacency.get(nodeId) ?? { nodes: new Set([nodeId]), links: new Set<string>() }
 
-  // --- NORMA DE SEPARACIÓN DE CABLES (9-Ago-2026) ---
-  // Se recogen los segmentos hub→chip de todos los enlaces (uplinks, dist,
-  // wired, CTs). El resolver empuja cada chip fuera de los cables AJENOS (los
-  // que no le pertenecen) con un margen, para que ningún dispositivo quede
-  // encima de un cable de otro.
-  const repelSegments: { x1: number; y1: number; x2: number; y2: number; ownerId?: string }[] = []
-  for (const c of chips) {
-    if (!c.wired || c.isCt) continue
-    const hub = routerNodes.find(rn => rn.id === c.hubId) ?? distNodes.find(dn => dn.id === c.hubId)
-    if (!hub) continue
-    repelSegments.push({ x1: hub.x, y1: hub.y, x2: c.x, y2: c.y, ownerId: c.id })
-  }
-  for (const [hostId, cts] of ctsByHost) {
-    const hostChip = chips.find((c) => c.id === hostId)
-    if (!hostChip) continue
-    for (const ct of cts) repelSegments.push({ x1: hostChip.x, y1: hostChip.y, x2: ct.x, y2: ct.y, ownerId: ct.id })
-  }
-  for (const dn of distNodes) {
-    const from = dn.node.parent
-      ? distNodes.find((n) => n.id === dn.node.parent)
-      : routerById.get(dn.node.routerId)
-    if (from) repelSegments.push({ x1: from.x, y1: from.y, x2: dn.x, y2: dn.y })
-  }
-  for (const rn of routerNodes) {
-    if (rn.id === gatewayNode?.id || !gatewayNode) continue
-    repelSegments.push({ x1: gatewayNode.x, y1: gatewayNode.y, x2: rn.x, y2: rn.y })
-  }
-
-  // --- Resolución de colisiones ---
-  // Routers fijos (no se mueven); chips se empujan y atraen hacia su hub padre.
-  // restDist = distancia inicial hub→chip (la posición canónica del layout);
-  // el resolver la usa como radio objetivo para que los chips no se dispersen
-  // tras una colisión ni se amontonen sobre el hub.
-  // Los nodos fijos llevan MARGEN (norma de separación): un chip no puede
-  // quedar pegado al borde de un router/distnode/Internet — mínimo
-  // r_nodo + r_chip + margin + padding. El gateway (r40) usa margen mayor.
-  const collidables: { x: number; y: number; r: number; fixed?: boolean; margin?: number; hubX?: number; hubY?: number; restDist?: number; id?: string }[] = [
-    ...routerNodes.map((rn) => ({ x: rn.x, y: rn.y, r: rn.r, fixed: true, margin: rn.id === gatewayNode?.id ? 40 : 26 })),
-    { x: internetNode.x, y: internetNode.y, r: 30, fixed: true, margin: 30 },
-  ]
-  // chips: buscar coords del hub padre
-  for (const c of chips) {
-    const hub = routerNodes.find(rn => rn.id === c.hubId) ?? distNodes.find(dn => dn.id === c.hubId)
-    const isHost = hypervisorHosts.has(c.id)
-    if (hub) {
-      const restDist = Math.sqrt((c.x - hub.x) ** 2 + (c.y - hub.y) ** 2)
-      // Los hosts hipervisores son NODOS con hijos (CTs): fijos, como los
-      // distnodes — no deben ser desplazados por los cables ajenos (si no, el
-      // resolver los lanza a la esquina). Sus CTs sí se acomodan a su alrededor.
-      collidables.push({
-        id: c.id, x: c.x, y: c.y, r: c.size / 2,
-        fixed: isHost, margin: isHost ? 16 : undefined,
-        hubX: hub.x, hubY: hub.y, restDist,
-      })
-    } else {
-      collidables.push({ id: c.id, x: c.x, y: c.y, r: c.size / 2, fixed: isHost, margin: isHost ? 16 : undefined })
-    }
-  }
-  // distnodes fijos
-  for (const dn of distNodes) {
-    collidables.push({ x: dn.x, y: dn.y, r: dn.r, fixed: true, margin: 14 })
-  }
-  resolveCollisions(collidables, 80, 14, repelSegments)
-  // Escribir posiciones de vuelta (solo chips; routers y distnodes son fixed)
-  let ci = routerNodes.length + 1 // +1 = Internet (añadido tras los routers)
-  for (const c of chips) { const ref = collidables[ci]!; c.x = ref.x; c.y = ref.y; ci++ }
-
   return {
     gatewayNode,
     apNodes,

+ 13 - 0
app/src/data/types.ts

@@ -38,6 +38,10 @@ export interface Router {
   disabled?: boolean
   /** Tipo de dispositivo: "glinet"|"openwrt"|"managed-switch"|"external". */
   type?: string
+  /** #1757: bridge VLAN filtering por puerto (id, tagged, pvid y nombre de
+   *  LuCI). La topología cruza el puerto del cliente con esta lista para
+   *  etiquetar su VLAN. Ausente si la unidad no lo reporta. */
+  vlans?: VlanPort[]
   status: Status
   /** Salud 0–100 */
   health: number
@@ -264,6 +268,15 @@ export interface Device {
    * nombre preferente sobre `port` cuando existe.
    */
   portLabel?: string
+  /**
+   * #1757: interfaz AP y red a la que está asociado un cliente inalámbrico.
+   * Las declara el agente desde `iw`. Vacías cuando la fuente no las expone.
+   * La topología cruza `wifiIface` con el bridge VLAN filtering del router
+   * para etiquetar la VLAN de la estación, igual que hace con `port` en los
+   * cableados.
+   */
+  wifiIface?: string
+  ssid?: string
   /** Datos LLDP cuando el vecino se anuncia (switch gestionado identificado). */
   lldp?: LldpInfo | null
   /**

+ 4 - 55
app/src/pages/ChannelPlan.tsx

@@ -63,10 +63,6 @@ interface ChannelPlanData {
   scans: Scan[]
 }
 
-// #1561: abrir la vista pide un scan si el último dato tiene más de 6 h (o no
-// hay), como mucho una vez cada 30 min por unidad.
-const AUTO_SCAN_STALE_MS = 6 * 60 * 60 * 1000
-const AUTO_SCAN_COOLDOWN_MS = 30 * 60 * 1000
 
 function bandFromFreq(freq: number): string {
   if (freq >= 2412 && freq <= 2484) return '2.4 GHz'
@@ -150,7 +146,7 @@ const FleetMenuTrigger = forwardRef<
 
 export default function ChannelPlan() {
   const { t, i18n } = useTranslation()
-  const { routers, connectionStatus, isDemo } = useNetPulse()
+  const { routers } = useNetPulse()
   const [routerId, setRouterId] = useState('')
   const [data, setData] = useState<ChannelPlanData | null>(null)
   const [loading, setLoading] = useState(false)
@@ -285,60 +281,13 @@ export default function ChannelPlan() {
       })
   }, [routerId, scanning, loadPlan, t])
 
-  // #1561: con el scan periódico apagado (#1558) el plan se queda viejo si
-  // nadie pulsa "Escanear ahora". Abrir la vista con datos de más de 6 h (o
-  // sin datos) pide un scan, como mucho una vez cada 30 min por unidad. El
-  // polling de fondo no lo dispara nunca, y el servidor limita a uno cada
-  // 5 min por agente.
-  const autoScanDone = useRef<string>('')
-  const autoScanIfStale = useCallback((rid: string, plan: ChannelPlanData | undefined) => {
-    // #1565: el bundle inicial contiene routers mock. Antes de la primera
-    // carga live no se puede pedir un scan para uno de esos ids; en demo sí.
-    if (!plan || (!isDemo && connectionStatus !== 'connected') || autoScanDone.current === rid) return
-    autoScanDone.current = rid
-    // wifi_scans.ts viene en segundos; Date.now() y los throttles van en ms.
-    const newest = plan.scans.reduce((max, s) => Math.max(max, (s.ts ?? 0) * 1000), 0)
-    if (newest > 0 && Date.now() - newest < AUTO_SCAN_STALE_MS) return
-    const key = `netpulse.channelPlan.autoScan.${rid}`
-    try {
-      const last = Number(sessionStorage.getItem(key) ?? 0)
-      if (last > 0 && Date.now() - last < AUTO_SCAN_COOLDOWN_MS) return
-    } catch {
-      return // sin almacenamiento no se autoescanea: mejor no encadenar
-    }
-    setScanning(true)
-    setScanRequested(true)
-    fetch(`/api/wifi/channel-plan/scan?routerId=${encodeURIComponent(rid)}`, { method: 'POST' })
-      .then((res) => {
-        if (!res.ok && res.status !== 429) {
-          setScanning(false)
-          setScanRequested(false)
-          return
-        }
-        try {
-          sessionStorage.setItem(key, String(Date.now()))
-        } catch {
-          /* idem */
-        }
-        scanTimers.current.push(window.setTimeout(() => { void loadPlan(rid, true) }, 12000))
-        scanTimers.current.push(window.setTimeout(() => {
-          void loadPlan(rid, true)
-          setScanning(false)
-          setScanRequested(false)
-        }, 35000))
-      })
-      .catch(() => {
-        setScanning(false)
-        setScanRequested(false)
-      })
-  }, [loadPlan, connectionStatus, isDemo])
-
   useEffect(() => {
     if (!routerId) return
     setActiveRadio('')
     setHidden(new Set())
     setSelected(null)
-    void loadPlan(routerId).then((plan) => autoScanIfStale(routerId, plan))
+    // #1794: abrir la vista nunca pide un scan. Solo lo hace el boton.
+    void loadPlan(routerId)
     if (pollTimer.current) clearInterval(pollTimer.current)
     // Refresco silencioso: sigue el último scan sin recargar a mano. No
     // pide scans (eso es del montaje y del botón).
@@ -346,7 +295,7 @@ export default function ChannelPlan() {
     return () => {
       if (pollTimer.current) clearInterval(pollTimer.current)
     }
-  }, [routerId, loadPlan, autoScanIfStale])
+  }, [routerId, loadPlan])
 
   const radioKey = (r: RadioRec) => `${r.section || r.iface}-${r.name}-${r.channel}`
   const radios: RadioRec[] = data?.radios ?? []

+ 181 - 1
app/src/pages/FirmwareUpgrades.tsx

@@ -6,6 +6,8 @@ import { useServicesVisibility } from '@/hooks/useServicesVisibility'
 import { AlertCircle, CalendarClock, Cpu, PartyPopper, Radar, RefreshCw, Rocket, ShieldCheck, Terminal, TriangleAlert, Download } from 'lucide-react'
 import { cn } from '@/lib/utils'
 import { relTimeFromTs } from '@/i18n'
+import { findAgentFor } from '@/lib/agentMatch'
+import { AgentBackupButton } from '@/components/routers/AgentBackupButton'
 import {
   AlertDialog,
   AlertDialogAction,
@@ -16,6 +18,7 @@ import {
   AlertDialogHeader,
   AlertDialogTitle,
 } from '@/components/ui/alert-dialog'
+import { Switch } from '@/components/ui/switch'
 
 interface FirmwareUpgrade {
   id: number
@@ -126,7 +129,7 @@ function dowLabel(lang: string, dow: number): string {
 export default function FirmwareUpgrades() {
   const { t, i18n } = useTranslation()
   const auth = useAuth()
-  const { routers } = useNetPulse()
+  const { routers, agents } = useNetPulse()
   // #1146: la visibilidad de la página la controla el toggle de Servicios.
   const [services] = useServicesVisibility()
   const isAdmin = auth?.role === 'admin'
@@ -435,6 +438,29 @@ export default function FirmwareUpgrades() {
     }
   }
 
+  // #1776: un intento que lleva mas de 15 min en requested/running/rebooting
+  // esta atascado (el router no volvio, el SSH murio y nadie cerro el
+  // registro). El reset lo borra para poder relanzar sin llamar a la API a
+  // mano. Un intento reciente se respeta: puede estar trabajando de verdad.
+  const STALE_UPGRADE_MS = 15 * 60 * 1000
+  const isStaleUpgrade = (item: FirmwareItem) => {
+    const s = item.upgrade?.status
+    if (s !== 'requested' && s !== 'running' && s !== 'rebooting') return false
+    return Date.now() - (item.upgrade?.startedAt ?? 0) * 1000 > STALE_UPGRADE_MS
+  }
+  const resetUpgrade = async (id: string) => {
+    setBusy((prev) => ({ ...prev, [id]: 'reset' }))
+    try {
+      const res = await fetch(`/api/firmware-upgrades/${encodeURIComponent(id)}/reset`, { method: 'POST' })
+      if (!res.ok) throw new Error(await res.text())
+      await fetchItems()
+    } catch (err) {
+      setError(String(err))
+    } finally {
+      setBusy((prev) => ({ ...prev, [id]: '' }))
+    }
+  }
+
   const startUpgrade = async (id: string) => {
     setBusy((prev) => ({ ...prev, [id]: 'upgrade' }))
     try {
@@ -688,6 +714,8 @@ export default function FirmwareUpgrades() {
       {/* #1444: estado del chequeo periódico de releases (cadencia + último chequeo). */}
       <ReleasesCheckCard />
 
+      <ConfigBackupScheduleCard />
+
       {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">
           <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" strokeWidth={1.75} />
@@ -905,6 +933,16 @@ export default function FirmwareUpgrades() {
                     {t(`firmwareUpgrades.status.${item.upgrade.status}`, { defaultValue: item.upgrade.status })}
                   </span>
                 )}
+                {isAdmin && isStaleUpgrade(item) && (
+                  <button
+                    onClick={() => void resetUpgrade(item.routerId)}
+                    disabled={busy[item.routerId] === 'reset'}
+                    title={t('firmwareUpgrades.resetStaleHint')}
+                    className="rounded-lg border border-border bg-surface px-2.5 py-1 text-xs font-medium text-text-primary transition-colors hover:bg-canvas disabled:opacity-50"
+                  >
+                    {busy[item.routerId] === 'reset' ? t('common.loading') : t('firmwareUpgrades.resetStale')}
+                  </button>
+                )}
               </div>
 
               <div className="mt-3 flex flex-wrap items-center gap-2">
@@ -1164,6 +1202,10 @@ export default function FirmwareUpgrades() {
                 </div>
               )}
 
+              <div className="mt-3 flex justify-end">
+                <AgentBackupButton agent={findAgentFor(agents, item.routerId)} routerId={item.routerId} />
+              </div>
+
               <details
                 className="mt-3 rounded-lg border border-border bg-canvas px-3 py-2"
                 onToggle={(ev) => {
@@ -1787,3 +1829,141 @@ function ReleasesCheckCard() {
     </div>
   )
 }
+
+
+function ConfigBackupScheduleCard() {
+  const { t, i18n } = useTranslation()
+  const { isDemo } = useNetPulse()
+  const auth = useAuth()
+  const isAdmin = auth?.role === 'admin'
+  const [schedule, setSchedule] = useState<{
+    enabled: boolean
+    dayOfWeek: number
+    time: string
+    lastRunMs?: number
+    nextRunMs?: number
+  } | null>(null)
+  const [saving, setSaving] = useState(false)
+  const [feedback, setFeedback] = useState<'saved' | 'error' | null>(null)
+
+  useEffect(() => {
+    if (!isAdmin || isDemo) return
+    let cancelled = false
+    fetch('/api/settings/config-backup-schedule')
+      .then((r) => (r.ok ? r.json() : null))
+      .then((data) => {
+        if (!cancelled && data) setSchedule(data)
+      })
+      .catch(() => {})
+    return () => {
+      cancelled = true
+    }
+  }, [isAdmin, isDemo])
+
+  if (isDemo || !isAdmin) return null
+  if (!schedule) return null
+
+  const locale = i18n.language.startsWith('en') ? 'en-GB' : 'es-ES'
+  const days = Array.from({ length: 7 }, (_, i) =>
+    new Intl.DateTimeFormat(locale, { weekday: 'long' }).format(new Date(2026, 8, 6 + i)),
+  )
+  const lastRun = relTimeFromTs(schedule.lastRunMs)
+  const nextRun = relTimeFromTs(schedule.nextRunMs)
+
+  const save = async () => {
+    setSaving(true)
+    setFeedback(null)
+    try {
+      const res = await fetch('/api/settings/config-backup-schedule', {
+        method: 'PUT',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({
+          enabled: schedule.enabled,
+          dayOfWeek: schedule.dayOfWeek,
+          time: schedule.time,
+        }),
+      })
+      if (!res.ok) throw new Error('save failed')
+      const saved = await res.json()
+      setSchedule(saved)
+      setFeedback('saved')
+    } catch {
+      setFeedback('error')
+    } finally {
+      setSaving(false)
+    }
+  }
+
+  return (
+    <div className="rounded-2xl border border-border bg-surface p-4">
+      <div className="flex flex-wrap items-center gap-x-5 gap-y-3">
+        <div className="min-w-0 flex-1">
+          <p className="text-sm font-medium text-text-primary">{t('firmwareUpgrades.backupScheduleTitle')}</p>
+          <p className="mt-0.5 text-caption text-text-muted">{t('firmwareUpgrades.backupScheduleCaption')}</p>
+        </div>
+        <label className="flex items-center gap-2 text-sm text-text-primary">
+          <Switch
+            checked={schedule.enabled}
+            onCheckedChange={(enabled) => {
+              setSchedule({ ...schedule, enabled })
+              setFeedback(null)
+            }}
+            aria-label={t('firmwareUpgrades.backupScheduleEnabled')}
+          />
+          {t('firmwareUpgrades.backupScheduleEnabled')}
+        </label>
+        <label className="flex items-center gap-2 text-sm text-text-muted">
+          {t('firmwareUpgrades.backupScheduleDay')}
+          <select
+            className="rounded-lg border border-border bg-canvas px-2 py-1 text-sm text-text-primary disabled:opacity-50"
+            value={schedule.dayOfWeek}
+            disabled={!schedule.enabled}
+            onChange={(e) => {
+              setSchedule({ ...schedule, dayOfWeek: Number(e.target.value) })
+              setFeedback(null)
+            }}
+          >
+            {days.map((day, i) => (
+              <option key={i} value={i}>
+                {day}
+              </option>
+            ))}
+          </select>
+        </label>
+        <label className="flex items-center gap-2 text-sm text-text-muted">
+          {t('firmwareUpgrades.backupScheduleTime')}
+          <input
+            type="time"
+            className="rounded-lg border border-border bg-canvas px-2 py-1 text-sm text-text-primary disabled:opacity-50"
+            value={schedule.time}
+            disabled={!schedule.enabled}
+            onChange={(e) => {
+              setSchedule({ ...schedule, time: e.target.value })
+              setFeedback(null)
+            }}
+          />
+        </label>
+        <button
+          type="button"
+          className="rounded-lg bg-accent px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
+          onClick={() => void save()}
+          disabled={saving}
+        >
+          {t('firmwareUpgrades.backupScheduleSave')}
+        </button>
+      </div>
+      {(lastRun || nextRun) && (
+        <p className="mt-2 text-caption text-text-muted">
+          {lastRun && t('firmwareUpgrades.backupScheduleLastRun', { when: lastRun })}
+          {lastRun && nextRun ? ' · ' : ''}
+          {nextRun && t('firmwareUpgrades.backupScheduleNextRun', { when: nextRun })}
+        </p>
+      )}
+      {feedback && (
+        <p className={cn('mt-2 text-caption', feedback === 'saved' ? 'text-emerald-500' : 'text-rose-400')}>
+          {t(feedback === 'saved' ? 'firmwareUpgrades.backupScheduleSaved' : 'firmwareUpgrades.backupScheduleError')}
+        </p>
+      )}
+    </div>
+  )
+}

+ 13 - 0
deploy/openwrt/netpulse-agent/files/netpulse-agent.init

@@ -83,6 +83,19 @@ start_service() {
 
 	procd_open_instance
 	procd_set_param command "$PROG"
+	# #1772: procd lanza el binario desde su propio entorno, asi que los
+	# export de load_config no llegan al proceso. Una sola llamada env con
+	# todas las variables (varias llamadas se pisan entre si en 21.02).
+	procd_set_param env \
+		NETPULSE_SERVER="$NETPULSE_SERVER" \
+		NETPULSE_TOKEN="$NETPULSE_TOKEN" \
+		NETPULSE_SLUG="$NETPULSE_SLUG" \
+		NETPULSE_INTERVAL="$NETPULSE_INTERVAL" \
+		NETPULSE_HEARTBEAT_FILE="$NETPULSE_HEARTBEAT_FILE" \
+		NETPULSE_SCAN_INTERVAL="$NETPULSE_SCAN_INTERVAL" \
+		NETPULSE_WAN_TARGET="$NETPULSE_WAN_TARGET" \
+		NETPULSE_GW_TARGET="$NETPULSE_GW_TARGET" \
+		NETPULSE_SERVER_FP="$NETPULSE_SERVER_FP"
 	# Booleanos explícitos: "procd_set_param stdout stderr" no es válido y en
 	# OpenWrt 21.02 deja los logs sin redirigir a syslog (#1701).
 	procd_set_param stdout 1

+ 1 - 1
docs/manual.en.md

@@ -403,7 +403,7 @@ Per router, one card per WiFi radio with the **current channel**, the **recommen
 
 The plan is computed from each radio's **neighbor scans**. There is a key difference here: routers running the **NetGrip** panel (the gateway and the APs managed by its panel) **do not scan neighbors**; routers with the **NetPulse agent** do. That is why some routers show no recommendation.
 
-Since agent 3.0.25 the periodic scan is **off by default** (`NETPULSE_SCAN_INTERVAL=0` in `/etc/netpulse-agent.env`): `iw scan` takes the radio off-channel for 2-4s and some beacon-sensitive clients (ESP8266/ESP32 devices, Cast speakers) get disassociated in that window (see #1557). Neighbors refresh when you open this page if the data is older than 6 hours (one scan per physical radio, with a 5 minute gap between requests) and with the **Scan now** button. To go back to periodic scans, set `NETPULSE_SCAN_INTERVAL=30m` (or any interval) in `/etc/netpulse-agent.env` and restart the agent.
+Since agent 3.0.25 the periodic scan is **off by default** (`NETPULSE_SCAN_INTERVAL=0` in `/etc/netpulse-agent.env`): `iw scan` takes the radio off-channel for 2-4s and some beacon-sensitive clients (ESP8266/ESP32 devices, Cast speakers) get disassociated in that window (see #1557). Neighbors refresh only with the **Scan now** button, never when the page opens (#1794). To go back to periodic scans, set `NETPULSE_SCAN_INTERVAL=30m` (or any interval) in `/etc/netpulse-agent.env` and restart the agent.
 
 ### How to read it
 

+ 1 - 1
docs/manual.es.md

@@ -403,7 +403,7 @@ Por cada router, una tarjeta por radio WiFi con el **canal actual**, el **canal
 
 El plan se calcula con los **scans de vecinos** de cada radio. Aquí hay una diferencia clave: los routers que corren el panel **NetGrip** (el gateway y los APs gestionados por su panel) **no escanean vecinos**; los routers con el **agente NetPulse** sí. Por eso a veces un router no muestra recomendación.
 
-Desde el agente 3.0.25 el sondeo periódico viene **desactivado** (`NETPULSE_SCAN_INTERVAL=0` en `/etc/netpulse-agent.env`): el `iw scan` saca la radio de su canal 2-4 s y algunos clientes sensibles a los beacons (ESP8266/ESP32, altavoces Cast) se desasocian en esa ventana (ver #1557). Los vecinos se refrescan al abrir esta página si los datos tienen más de 6 horas (un scan por radio física, con 5 minutos de margen entre peticiones) y con el botón **Escanear ahora**. Para volver al sondeo periódico, pon `NETPULSE_SCAN_INTERVAL=30m` (o el intervalo que quieras) en `/etc/netpulse-agent.env` y reinicia el agente.
+Desde el agente 3.0.25 el sondeo periódico viene **desactivado** (`NETPULSE_SCAN_INTERVAL=0` en `/etc/netpulse-agent.env`): el `iw scan` saca la radio de su canal 2-4 s y algunos clientes sensibles a los beacons (ESP8266/ESP32, altavoces Cast) se desasocian en esa ventana (ver #1557). Los vecinos se refrescan solo con el botón **Escanear ahora**, nunca al abrir la página (#1794). Para volver al sondeo periódico, pon `NETPULSE_SCAN_INTERVAL=30m` (o el intervalo que quieras) en `/etc/netpulse-agent.env` y reinicia el agente.
 
 ### Cómo leerlo
 

+ 22 - 0
server-go/cmd/netpulse/main.go

@@ -189,6 +189,9 @@ func run() error {
 	if err != nil {
 		return err
 	}
+	if err := ensureDataLayout(cfg.DataDir); err != nil {
+		return err
+	}
 
 	// Modo mantenimiento: `-rollup` ejecuta el rollup nocturno de la escalera
 	// de retención y sale. Con `-rollup-repair` primero purga metrics_buckets
@@ -1083,3 +1086,22 @@ func pruneWifiScans(store *channelplan.Store) {
 		}
 	}
 }
+
+// ensureDataLayout normaliza los directorios persistentes para que los
+// miembros del grupo netpulse puedan leer backups y artefactos (#1795).
+func ensureDataLayout(dataDir string) error {
+	for _, dir := range []string{
+		dataDir,
+		filepath.Join(dataDir, "backups"),
+		filepath.Join(dataDir, "backups", "firmware"),
+		filepath.Join(dataDir, "updates"),
+	} {
+		if err := os.MkdirAll(dir, 0o770); err != nil {
+			return err
+		}
+		if err := os.Chmod(dir, 0o770); err != nil {
+			return err
+		}
+	}
+	return nil
+}

+ 26 - 0
server-go/cmd/netpulse/main_test.go

@@ -5,6 +5,8 @@ package main
 import (
 	"net/http"
 	"net/http/httptest"
+	"os"
+	"path/filepath"
 	"strings"
 	"testing"
 	"time"
@@ -149,3 +151,27 @@ func TestUrgencyGateDefaultUrgentOnly(t *testing.T) {
 type spyN struct{ got []alerts.AlertEvent }
 
 func (s *spyN) Notify(ev alerts.AlertEvent) { s.got = append(s.got, ev) }
+
+func TestEnsureDataLayout(t *testing.T) {
+	dataDir := filepath.Join(t.TempDir(), "data")
+	if err := os.MkdirAll(filepath.Join(dataDir, "backups", "firmware"), 0o700); err != nil {
+		t.Fatal(err)
+	}
+	if err := ensureDataLayout(dataDir); err != nil {
+		t.Fatal(err)
+	}
+	for _, dir := range []string{
+		dataDir,
+		filepath.Join(dataDir, "backups"),
+		filepath.Join(dataDir, "backups", "firmware"),
+		filepath.Join(dataDir, "updates"),
+	} {
+		st, err := os.Stat(dir)
+		if err != nil {
+			t.Fatalf("%s: %v", dir, err)
+		}
+		if got := st.Mode().Perm(); got != 0o770 {
+			t.Fatalf("%s mode = %o want 770", dir, got)
+		}
+	}
+}

+ 5 - 0
server-go/internal/adapters/agent.go

@@ -809,6 +809,11 @@ func (l *Live) polledFromAgent(cfg RouterConfig, p *probe.Payload) *routerPolled
 		out.lossPct = sd.LossPct
 		out.backhaul = sd.Backhaul
 		out.brMac = sd.BridgeMAC
+		// #1765: identidades propias del equipo. El agente manda las MACs de
+		// todas sus interfaces; sin esto solo se absorbía la del bridge y el
+		// resto (VLANs, puerto CPU de un switch DSA, radios) aparecía como
+		// cliente desconocido cuando un vecino las aprendía en su FDB.
+		out.selfMacs = sd.IfaceMACs
 		out.flash = sd.Flash
 		out.firmwareAvailable = sd.FirmwareAvailable
 	} else if cached != nil && cached.system != nil && cached.systemKind == agentSourceClass(p.Kind) {

+ 29 - 0
server-go/internal/adapters/defaultroute_test.go

@@ -0,0 +1,29 @@
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// #1791: el siguiente salto WAN del gateway no es un cliente LAN. Su MAC
+// aparece en ARP y, sin este filtro, buildDevices la publica como un
+// dispositivo desconocido.
+func TestBuildDevicesAbsorbsDefaultRoute(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"gw": {
+			cfg:     RouterConfig{ID: "gw", IsGateway: true},
+			wanInfo: probe.WanInfo{Gateway: "192.168.2.1"},
+			arp: map[string]string{
+				"04:F4:1C:F3:46:65": "192.168.2.1",  // siguiente salto WAN
+				"AA:BB:CC:00:00:09": "192.168.1.50", // cliente real
+			},
+			arpStale: map[string]bool{},
+		},
+	}
+	devs := l.buildDevices(polled, "")
+	if len(devs) != 1 || devs[0].MAC != "AA:BB:CC:00:00:09" {
+		t.Fatalf("devices: %+v, want solo el cliente real", devs)
+	}
+}

+ 51 - 14
server-go/internal/adapters/live.go

@@ -114,7 +114,11 @@ type routerPolled struct {
 	sysDescr string
 	// sysName (#1256): hostname que el usuario define en el equipo; para
 	// SNMP alimenta el Name visible de la unidad en flota.
-	sysName           string
+	sysName string
+	// snmpFirmware/snmpModelShort (#1767): identity read from ENTITY-MIB.
+	// Empty when the unit has no table, so the sysDescr fallback stays.
+	snmpFirmware      string
+	snmpModelShort    string
 	flash             string
 	firmwareAvailable string
 	uptimeSec         float64
@@ -1638,6 +1642,11 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.brMac != "" {
 		r.MAC = p.brMac
 	}
+	// #1757: bridge VLAN filtering por puerto. nil cuando la unidad no lo
+	// reporta, para no publicar una lista vacía como si no hubiera VLANs.
+	if len(p.vlans) > 0 {
+		r.Vlans = vlanPortsWithNames(p.vlans, p.luci)
+	}
 	if p.backhaul != "" {
 		r.Backhaul = p.backhaul
 	}
@@ -1653,6 +1662,13 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	if p.board != nil {
 		r.Firmware = p.board.Release.Description
 	}
+	// #1767: an SNMP switch has no board; ENTITY-MIB is its own declaration.
+	if p.snmpFirmware != "" {
+		r.Firmware = p.snmpFirmware
+	}
+	if p.snmpModelShort != "" {
+		r.ModelShort = p.snmpModelShort
+	}
 	if p.cfg.FirmwareTarget != "" {
 		r.FirmwareTarget = p.cfg.FirmwareTarget
 	}
@@ -3042,9 +3058,11 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 	now := time.Now().UnixMilli()
 
 	type seenInfo struct {
-		routerID string
-		band     string
-		signal   *int
+		routerID  string
+		band      string
+		wifiIface string
+		ssid      string
+		signal    *int
 	}
 	seen := map[string]seenInfo{}
 	// assocSeen (#1740): en qué routers vio ESTE ciclo a cada MAC. Solo se usa
@@ -3055,8 +3073,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 	for routerID, p := range polled {
 		for mac, w := range p.wireless {
 			sig := w.SignalDbm
-			seen[mac] = seenInfo{routerID, w.Band, &sig}
-			assocSeen[mac] = append(assocSeen[mac], seenInfo{routerID, w.Band, &sig})
+			seen[mac] = seenInfo{routerID: routerID, band: w.Band, wifiIface: w.Iface, ssid: w.SSID, signal: &sig}
+			assocSeen[mac] = append(assocSeen[mac], seenInfo{routerID: routerID, band: w.Band, wifiIface: w.Iface, ssid: w.SSID, signal: &sig})
 			if l.db != nil {
 				_, _ = l.db.Exec(
 					`INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?, ?, ?, ?, ?)
@@ -3129,7 +3147,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 				if _, ok := seen[mac]; ok {
 					continue
 				}
-				seen[mac] = seenInfo{routerID, band, nil}
+				seen[mac] = seenInfo{routerID: routerID, band: band}
 				if l.db != nil {
 					// Sin signal_dbm en el DO UPDATE: el hint no trae RSSI y
 					// pisar con NULL el último bueno de una asociación real
@@ -3205,7 +3223,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 				continue // uplink: MACs en tránsito, no clientes de este equipo
 			}
 			if _, ok := seen[mac]; !ok {
-				seen[mac] = seenInfo{routerID, "cable", nil}
+				seen[mac] = seenInfo{routerID: routerID, band: "cable"}
 			}
 		}
 	}
@@ -3215,7 +3233,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 			for mac := range gwPolled.fdb {
 				if _, ok := seen[mac]; !ok {
 					if _, ok := known[mac]; !ok {
-						seen[mac] = seenInfo{gwID, "cable", nil}
+						seen[mac] = seenInfo{routerID: gwID, band: "cable"}
 					}
 				}
 			}
@@ -3256,7 +3274,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 				if _, ok := seen[mac]; ok {
 					continue
 				}
-				seen[mac] = seenInfo{gwID, "cable", nil}
+				seen[mac] = seenInfo{routerID: gwID, band: "cable"}
 				wanSide[mac] = true
 			}
 		}
@@ -3285,7 +3303,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 			if !arpConfirmed[mac] {
 				continue
 			}
-			seen[mac] = seenInfo{routerID, "cable", nil}
+			seen[mac] = seenInfo{routerID: routerID, band: "cable"}
 		}
 	}
 	// (5) Atribución sticky (#678): un cableado que este tick solo aparece en el
@@ -3320,7 +3338,7 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 					continue // boca local del gateway: evidencia fresca, no tocar
 				}
 			}
-			seen[mac] = seenInfo{m.routerID, "cable", nil}
+			seen[mac] = seenInfo{routerID: m.routerID, band: "cable"}
 		}
 	}
 
@@ -3394,6 +3412,23 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 			}
 		}
 	}
+	// #1791: el vecino de la ruta por defecto del gateway (su siguiente salto
+	// WAN) no es un cliente de la LAN. Aparecía en la lista porque su MAC está
+	// en la tabla ARP y ninguna otra evidencia lo reclamaba. Se absorbe por la
+	// IP de la puerta de enlace WAN, no por un prefijo de MAC ni por un puerto,
+	// que en PPPoE no existe.
+	defaultRouteMacs := map[string]bool{}
+	for _, p := range polled {
+		gwIP := strings.TrimSpace(p.wanInfo.Gateway)
+		if gwIP == "" {
+			continue
+		}
+		for mac, ip := range p.arp {
+			if strings.TrimSpace(ip) == gwIP {
+				defaultRouteMacs[strings.ToUpper(mac)] = true
+			}
+		}
+	}
 	// issue #196: allowlist de dispositivos confiables (mac → alias).
 	knownMacs := map[string]string{}
 	if l.db != nil {
@@ -3443,8 +3478,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 	}
 	devices := []Device{}
 	for mac := range allMacs {
-		if routerMacs[mac] {
-			continue // los routers no son clientes
+		if routerMacs[mac] || defaultRouteMacs[strings.ToUpper(mac)] {
+			continue // los routers y la ruta por defecto no son clientes
 		}
 		lease, hasLease := leasesByMac[mac]
 		s, isSeen := seen[mac]
@@ -3578,6 +3613,8 @@ func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []D
 		if isSeen {
 			d.RouterID = s.routerID
 			d.Band = s.band
+			d.WifiIface = s.wifiIface
+			d.SSID = s.ssid
 			d.SignalDbm = s.signal
 		} else if k, ok := known[mac]; ok {
 			d.RouterID = k.routerID

+ 45 - 0
server-go/internal/adapters/selfmacs_1765_test.go

@@ -0,0 +1,45 @@
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// #1765: el propio equipo responde por más MACs que la del router guardado en
+// la flota. El agente las reporta y el servidor las absorbe: sin esto, la MAC
+// del puerto CPU de un switch o la de una VLAN se aprende en la FDB de un
+// vecino y sale como cliente desconocido.
+func TestBuildDevicesAbsorbsAgentSelfMacs(t *testing.T) {
+	cfg := RouterConfig{ID: "gateway", Host: "192.0.2.1", Name: "openwrt", IsGateway: true, AgentOnly: true}
+	l := NewLive(nil, nil, []RouterConfig{cfg}, nil)
+	payload := &probe.Payload{
+		Router: "gateway", Ts: 1, Version: "2.51.0",
+		Data: probe.PayloadData{
+			System: &probe.SystemData{
+				BridgeMAC: "94:83:C4:00:00:01",
+				IfaceMACs: []string{"94:83:C4:00:00:01", "04:F4:1C:F3:46:66"},
+			},
+			FDB: &probe.FDBData{MACs: map[string]string{
+				"04:F4:1C:F3:46:66": "lan2",
+				"AA:BB:CC:00:00:09": "lan2",
+			}},
+		},
+	}
+	devices := l.buildDevices(map[string]*routerPolled{"gateway": l.polledFromAgent(cfg, payload)}, "")
+	var real, self bool
+	for _, d := range devices {
+		switch d.MAC {
+		case "04:F4:1C:F3:46:66":
+			self = true
+		case "AA:BB:CC:00:00:09":
+			real = true
+		}
+	}
+	if self {
+		t.Error("la MAC propia de la interfaz salió como cliente")
+	}
+	if !real {
+		t.Errorf("el cliente real no aparece (%d devices)", len(devices))
+	}
+}

+ 28 - 0
server-go/internal/adapters/snmp_live.go

@@ -83,6 +83,18 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		l.snmpBrMac[cfg.ID] = brMac
 	}
 	l.mu.Unlock()
+	// #1767: ENTITY-MIB identity (firmware and short model). Generic RFC
+	// 6933 columns; one walk, and a switch without the table leaves both
+	// fields empty. Best-effort like the bridge MAC above.
+	entity, _ := npsnmp.PollEntityInfo(session)
+	// #1802: TP-Link firmware ignores ENTITY-MIB and HOST-RESOURCES-MIB but
+	// publishes the same identity and vitals in its enterprise subtree. The
+	// sysObjectID selects the vendor before paying for its OIDs; the private
+	// MIB wins over the generic fallback, as the panel of the unit does.
+	tpLink := npsnmp.TpLinkInfo{}
+	if sysInfo != nil && npsnmp.IsTpLink(sysInfo.ObjectID) {
+		tpLink = npsnmp.PollTpLinkInfo(session)
+	}
 	ports, ifErr := npsnmp.PollIfTable(session)
 	if ifErr != nil {
 		log.Printf("[netpulse] SNMP ifTable %s: %v", cfg.LogLabel(), ifErr)
@@ -219,6 +231,22 @@ func (l *Live) pollRouterSNMP(cfg RouterConfig) (*routerPolled, error) {
 		lldp:      snmpLldpNeighbors(lldpRem, portIdxToName),
 		polledAt:  now.UnixMilli(),
 	}
+	// #1767: ENTITY-MIB is optional identity, not a vitals source.
+	p.snmpFirmware = entity.Firmware
+	p.snmpModelShort = entity.ModelShort
+	// #1802: fill only what the generic readers could not answer.
+	if p.snmpFirmware == "" {
+		p.snmpFirmware = tpLink.Firmware
+	}
+	if p.snmpModelShort == "" {
+		p.snmpModelShort = tpLink.Hardware
+	}
+	if tpLink.HasCPU {
+		p.cpu, p.hasCpu = tpLink.CPU, true
+	}
+	if tpLink.HasMemory {
+		p.ram, p.hasRam = tpLink.Memory, true
+	}
 	if sysInfo != nil {
 		// #1256: sysDescr declara el modelo completo del equipo (p. ej.
 		// "CSS610-8G-2S+ SwOS v2.21") y sysName el hostname que define el

+ 22 - 0
server-go/internal/adapters/snmp_live_test.go

@@ -184,6 +184,28 @@ func TestBuildRouterExposeSnmpEnabled(t *testing.T) {
 	}
 }
 
+// #1767: an SNMP switch shows the ENTITY-MIB firmware and short model while
+// keeping sysDescr as the full model.
+func TestBuildRouterUsesEntityIdentity(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	p := &routerPolled{
+		cfg:            RouterConfig{ID: "sw1", Host: "192.168.2.6", SnmpEnabled: true},
+		sysDescr:       "XS708T 8-Port 10-Gigabit Copper Smart Managed Pro Switch with 2 Copper/SFP+ Combo Ports",
+		snmpFirmware:   "7.0.0.24",
+		snmpModelShort: "XS708T",
+	}
+	r := l.buildRouter(p, nil)
+	if r.Firmware != "7.0.0.24" {
+		t.Errorf("firmware = %q, want 7.0.0.24", r.Firmware)
+	}
+	if r.ModelShort != "XS708T" {
+		t.Errorf("modelShort = %q, want XS708T", r.ModelShort)
+	}
+	if r.Model != p.sysDescr {
+		t.Errorf("model = %q, want full sysDescr", r.Model)
+	}
+}
+
 // #930: 3 fallos seguidos con ping OK emiten UNA alerta warn "snmp-failing";
 // la recuperación la resuelve y emite la ok; los contadores son correctos.
 func TestSnmpPollHealthAlertAndRecovery(t *testing.T) {

+ 8 - 0
server-go/internal/adapters/topology.go

@@ -637,6 +637,14 @@ func inferTopology(polled map[string]*routerPolled, devices []Device) ([]Device,
 					ID: id, Kind: "inferred", RouterID: switchID, Port: port,
 					PortLabel: portLabel(p, port), MacCount: len(kept), Parent: dn.ID,
 				})
+				// #1791: los clientes del puerto cuelgan del nodo hoja, no del
+				// gateway que les dio la IP. Sin AttachTo, hubOf los anclaba al
+				// router y el nodo inferido quedaba vacío.
+				for _, mac := range kept {
+					if idx, ok := byMAC[mac]; ok {
+						devices[idx].AttachTo = id
+					}
+				}
 			}
 		}
 	}

+ 26 - 6
server-go/internal/adapters/topology_lldp_test.go

@@ -263,11 +263,12 @@ func TestInferTopologySwitchHojaTrasGestionado(t *testing.T) {
 	managedRoot := distSummary{id: "dist-flint2-lan3", kind: "managed", routerID: "flint2", port: "lan3", mac: macGS308E, name: "GS308E", ip: "192.168.8.13", macCount: 2}
 
 	tests := []struct {
-		name    string
-		swFdb   map[string]string
-		swLldp  []LldpNeighbor
-		devices []Device
-		want    []distSummary
+		name     string
+		swFdb    map[string]string
+		swLldp   []LldpNeighbor
+		devices  []Device
+		want     []distSummary
+		attachTo map[string]string
 	}{
 		{
 			name:  "hoja en puerto no-uplink",
@@ -280,6 +281,10 @@ func TestInferTopologySwitchHojaTrasGestionado(t *testing.T) {
 				managedRoot,
 				{id: "dist-swA-ge3", kind: "inferred", routerID: "swA", port: "ge3", parent: "dist-flint2-lan3", macCount: 2},
 			},
+			attachTo: map[string]string{
+				"10:20:30:40:50:60": "dist-swA-ge3",
+				"10:20:30:40:50:61": "dist-swA-ge3",
+			},
 		},
 		{
 			// El uplink (root port) también aprende clientes en tránsito, pero
@@ -329,11 +334,26 @@ func TestInferTopologySwitchHojaTrasGestionado(t *testing.T) {
 				polled["ap1"] = &routerPolled{cfg: RouterConfig{ID: "ap1"}, brMac: "94:83:C4:00:00:02", fdb: map[string]string{}}
 			}
 			devices := append(append([]Device{}, gwDevices...), tt.devices...)
-			_, dists := inferTopology(polled, devices)
+			gotDevices, dists := inferTopology(polled, devices)
 			got := summarizeDists(dists)
 			if !reflect.DeepEqual(got, tt.want) {
 				t.Fatalf("dists:\n got: %+v\nwant: %+v", got, tt.want)
 			}
+			for mac, wantAttach := range tt.attachTo {
+				found := false
+				for _, d := range gotDevices {
+					if d.MAC != mac {
+						continue
+					}
+					found = true
+					if d.AttachTo != wantAttach {
+						t.Fatalf("%s AttachTo = %q, want %q", mac, d.AttachTo, wantAttach)
+					}
+				}
+				if !found {
+					t.Fatalf("%s no aparece en los devices", mac)
+				}
+			}
 		})
 	}
 }

+ 25 - 15
server-go/internal/adapters/types.go

@@ -180,9 +180,13 @@ type Router struct {
 	// Type: "glinet"|"openwrt"|"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"`
-	Status string `json:"status"` // "online"|"warn"|"offline"|"unreachable"
-	Health int    `json:"health"`
+	Type string `json:"type,omitempty"`
+	// Vlans (#1757): bridge VLAN filtering por puerto (id, tagged, pvid y el
+	// nombre declarado en LuCI). La topología cruza el puerto del cliente con
+	// esta lista para etiquetar su VLAN. Ausente si la unidad no lo reporta.
+	Vlans  []VlanPort `json:"vlans,omitempty"`
+	Status string     `json:"status"` // "online"|"warn"|"offline"|"unreachable"
+	Health int        `json:"health"`
 	// LatencyMs (#1384): latencia sondeada de la unidad (ping unidad→gateway
 	// en no-gateway; latencia WAN en el gateway). Null cuando la fuente no la
 	// sondea (agent-only/external/SNMP) - la tabla de enlaces pinta "—".
@@ -267,18 +271,24 @@ type DeviceTotals struct {
 // (SPEC §2.9); el resto solo existe en demo (ausentes en live).
 // SignalDbm es null cuando no hay medida (nunca ausente).
 type Device struct {
-	ID           string    `json:"id"`
-	Name         string    `json:"name"`
-	Type         string    `json:"type"`
-	Manufacturer string    `json:"manufacturer"`
-	IP           string    `json:"ip"`
-	MAC          string    `json:"mac"`
-	RouterID     string    `json:"routerId"`
-	Band         string    `json:"band"` // "5 GHz"|"2.4 GHz"|"cable"|"—"
-	SignalDbm    *int      `json:"signalDbm"`
-	TrafficMbps  float64   `json:"trafficMbps"`
-	Online       bool      `json:"online"`
-	Sparkline    []float64 `json:"sparkline"`
+	ID           string `json:"id"`
+	Name         string `json:"name"`
+	Type         string `json:"type"`
+	Manufacturer string `json:"manufacturer"`
+	IP           string `json:"ip"`
+	MAC          string `json:"mac"`
+	RouterID     string `json:"routerId"`
+	Band         string `json:"band"` // "5 GHz"|"2.4 GHz"|"cable"|"—"
+	// WifiIface/SSID (#1757): interfaz AP y red a la que esta asociado un
+	// cliente inalambrico. El agente los declara desde iw; vacios cuando la
+	// fuente no los expone. La topologia cruza WifiIface con el bridge VLAN
+	// filtering del router para etiquetar la VLAN de la estacion.
+	WifiIface   string    `json:"wifiIface,omitempty"`
+	SSID        string    `json:"ssid,omitempty"`
+	SignalDbm   *int      `json:"signalDbm"`
+	TrafficMbps float64   `json:"trafficMbps"`
+	Online      bool      `json:"online"`
+	Sparkline   []float64 `json:"sparkline"`
 	// --- topología v5 (FDB/LLDP; omitempty: ausentes si no hay datos) ---
 	// Port: puerto físico del bridge donde se aprende la MAC (cableados, FDB).
 	Port string `json:"port,omitempty"`

+ 39 - 0
server-go/internal/adapters/vlans_router_test.go

@@ -0,0 +1,39 @@
+package adapters
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/probe"
+)
+
+// #1757: la lista de flota lleva el bridge VLAN filtering por puerto, con el
+// nombre declarado en LuCI, para que la topología pueda etiquetar los
+// clientes cableados de cada VLAN.
+func TestBuildRouterExposesVlans(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	p := &routerPolled{
+		cfg: RouterConfig{ID: "gw", Host: "192.168.1.1"},
+		vlans: []probe.VlanPort{
+			{Port: "lan1", Vlans: []probe.VlanEntry{{ID: 20, Tagged: true}, {ID: 1, PVID: true}}},
+		},
+		luci: &probe.LuCILabels{VlanLabels: map[string]string{"20": "IoT"}},
+	}
+	r := l.buildRouter(p, nil)
+	if len(r.Vlans) != 1 || r.Vlans[0].Port != "lan1" {
+		t.Fatalf("vlans = %+v, want el puerto lan1", r.Vlans)
+	}
+	got := r.Vlans[0].Vlans
+	if len(got) != 2 || got[0].ID != 20 || got[0].Name != "IoT" || !got[0].Tagged || got[1].ID != 1 || !got[1].PVID {
+		t.Fatalf("entradas = %+v", got)
+	}
+}
+
+// Sin bridge vlan filtering el campo queda nil: la UI no debe pintar VLANs
+// que la unidad no ha declarado.
+func TestBuildRouterWithoutVlans(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	r := l.buildRouter(&routerPolled{cfg: RouterConfig{ID: "ap", Host: "192.168.1.2"}}, nil)
+	if r.Vlans != nil {
+		t.Fatalf("vlans = %+v, want nil", r.Vlans)
+	}
+}

+ 32 - 0
server-go/internal/adapters/wifi_vlan_1757_test.go

@@ -0,0 +1,32 @@
+package adapters
+
+import "testing"
+
+// #1757: la interfaz AP y el SSID de una estacion viajan hasta el Device. La
+// topologia los cruza con el bridge VLAN filtering del router para etiquetar
+// la VLAN del cliente inalambrico; sin estos campos solo se podia etiquetar
+// el cableado.
+func TestBuildDevicesCarriesWifiIfaceAndSSID(t *testing.T) {
+	l := NewLive(nil, nil, nil, nil)
+	polled := map[string]*routerPolled{
+		"gw": {
+			cfg: RouterConfig{ID: "gw", IsGateway: true},
+			wireless: map[string]WirelessClient{
+				"AA:BB:CC:DD:EE:01": {SignalDbm: -55, Band: "5 GHz", Iface: "wlan0", SSID: "IoT"},
+			},
+			arp:      map[string]string{},
+			arpStale: map[string]bool{},
+		},
+	}
+	devs := l.buildDevices(polled, "")
+	if len(devs) != 1 {
+		t.Fatalf("devices = %d, want 1: %+v", len(devs), devs)
+	}
+	d := devs[0]
+	if d.WifiIface != "wlan0" || d.SSID != "IoT" {
+		t.Errorf("iface=%q ssid=%q, want wlan0 / IoT", d.WifiIface, d.SSID)
+	}
+	if d.Band != "5 GHz" || d.SignalDbm == nil || *d.SignalDbm != -55 {
+		t.Errorf("band=%q signal=%v, want 5 GHz / -55", d.Band, d.SignalDbm)
+	}
+}

+ 12 - 1
server-go/internal/agentbin/agentbin.go

@@ -93,7 +93,18 @@ func normalizeArch(arch string) string {
 // "amd64", "arm64", "armv7". Normaliza sinónimos (armv7 -> arm) para que el
 // one-liner del agente, que reporta GOARCH=armv7, encuentre el binario.
 func Open(arch string) (fs.File, error) {
-	name := "agents/netpulse-agent-" + normalizeArch(arch)
+	return openEmbedded("agents/netpulse-agent-" + normalizeArch(arch))
+}
+
+// OpenAsset abre un asset extra del agente empaquetado junto al binario. Hoy
+// solo se usa para el .apk de OpenWrt 25.12, que firma el CI: el formato v3 de
+// apk-tools no se puede fabricar aqui sin su SDK, asi que el servidor solo lo
+// sirve cuando el operador lo deja en agents/ con el nombre esperado.
+func OpenAsset(arch, ext string) (fs.File, error) {
+	return openEmbedded("agents/netpulse-agent-" + normalizeArch(arch) + "." + ext)
+}
+
+func openEmbedded(name string) (fs.File, error) {
 	f, err := agentsFS.Open(name)
 	if err != nil {
 		return nil, err

+ 58 - 0
server-go/internal/agentbin/asset_test.go

@@ -0,0 +1,58 @@
+package agentbin
+
+import (
+	"errors"
+	"io/fs"
+	"testing"
+)
+
+// #1476: el .apk de OpenWrt 25.12 no se fabrica aqui (lo firma el CI), asi que
+// el servidor solo puede servirlo cuando el operador lo deja junto al binario.
+// Una extension que nunca existe tiene que responder ausencia, nunca un
+// fichero vacio ni un error de otra clase. No se comprueba "apk" a proposito:
+// en un build con assets empaquetados el fichero puede estar y el test debe
+// seguir siendo valido en los dos entornos.
+func TestOpenAssetMissingIsNotExist(t *testing.T) {
+	f, err := OpenAsset("arm64", "noexiste")
+	if err == nil {
+		f.Close()
+		t.Fatal("OpenAsset(arm64, noexiste) devolvio un fichero; debe fallar")
+	}
+	if !errors.Is(err, fs.ErrNotExist) {
+		t.Fatalf("OpenAsset(arm64, noexiste) error = %v, want fs.ErrNotExist", err)
+	}
+}
+
+// El binario sigue abriendose con el nombre sin extension: Open y OpenAsset no
+// comparten namespace y el helper extraido no cambio su contrato. Se compara
+// contra openEmbedded en vez de exigir ausencia, porque un build con binarios
+// embebidos (CI) si los tiene y un arbol de desarrollo no.
+func TestOpenKeepsBinaryName(t *testing.T) {
+	got, gotErr := Open("arm64")
+	if got != nil {
+		got.Close()
+	}
+	want, wantErr := openEmbedded("agents/netpulse-agent-arm64")
+	if want != nil {
+		want.Close()
+	}
+	if (gotErr == nil) != (wantErr == nil) {
+		t.Fatalf("Open y openEmbedded discrepan: %v vs %v", gotErr, wantErr)
+	}
+	if gotErr != nil && !errors.Is(gotErr, fs.ErrNotExist) {
+		t.Fatalf("Open error = %v, want fs.ErrNotExist", gotErr)
+	}
+}
+
+// normalizeArch sigue aplicandose en OpenAsset: aarch64 y arm64 piden el mismo
+// asset, y un arch desconocido no inventa un nombre valido.
+func TestOpenAssetNormalizesArch(t *testing.T) {
+	_, errA := OpenAsset("aarch64", "apk")
+	_, errB := OpenAsset("arm64", "apk")
+	if (errA == nil) != (errB == nil) {
+		t.Fatalf("aarch64 y arm64 deben resolver al mismo asset: %v vs %v", errA, errB)
+	}
+	if _, err := OpenAsset("sparc", "apk"); !errors.Is(err, fs.ErrNotExist) {
+		t.Fatalf("arch desconocida: error = %v, want fs.ErrNotExist", err)
+	}
+}

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

@@ -566,7 +566,11 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	for _, opt := range opts {
 		opt(&o)
 	}
-	if err := os.MkdirAll(dataDir, 0o755); err != nil {
+	// #1795: el grupo del servicio puede leer backups y datos sin ser owner.
+	if err := os.MkdirAll(dataDir, 0o770); err != nil {
+		return nil, err
+	}
+	if err := os.Chmod(dataDir, 0o770); err != nil {
 		return nil, err
 	}
 	dbPath := filepath.Join(dataDir, databaseFile)

+ 22 - 0
server-go/internal/firmware/store.go

@@ -246,6 +246,28 @@ func (s *Store) DismissLatest(routerID string) error {
 	return err
 }
 
+// ResetLatest borra el estado de upgrade del router para desatascarlo (#1776):
+// un intento terminado (failed/done) o un registro en curso que lleva más de
+// staleBefore sin avanzar. Un upgrade realmente vivo no se toca, para no
+// cancelar una operación por accidente. Devuelve si borró algo.
+func (s *Store) ResetLatest(routerID string, now time.Time, staleFor time.Duration) (bool, error) {
+	up, err := s.LatestUpgrade(routerID)
+	if err != nil || up == nil {
+		return false, err
+	}
+	switch up.Status {
+	case "failed", "done":
+	default:
+		if staleFor <= 0 || now.Sub(time.Unix(up.StartedAt, 0)) < staleFor {
+			return false, nil
+		}
+	}
+	if _, err := s.db.Exec(`DELETE FROM firmware_upgrades WHERE id = ?`, up.ID); err != nil {
+		return false, err
+	}
+	return true, nil
+}
+
 // ScheduleUpgrade crea o actualiza la fila 'scheduled' del router (#494).
 // Una fila por router: si ya hay una pendiente, se actualizan target y hora;
 // si no, se inserta. scheduledFor es epoch ms UTC.

+ 60 - 0
server-go/internal/firmware/store_test.go

@@ -4,6 +4,7 @@ package firmware
 
 import (
 	"testing"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/db"
 )
@@ -160,3 +161,62 @@ func TestStartScheduled(t *testing.T) {
 		t.Fatalf("segundo start debe ser no-op: ok=%v err=%v", ok, err)
 	}
 }
+
+// #1776: un registro en curso que dejó de avanzar se puede limpiar, pero uno
+// reciente no: eso sería cancelar un upgrade vivo.
+func TestResetLatestClearsStaleRunning(t *testing.T) {
+	s := open(t)
+	id, err := s.BeginUpgrade("rt1", "v2", "http://x", "abc")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	if err := s.SetStatus(id, "running", "", ""); err != nil {
+		t.Fatalf("set running: %v", err)
+	}
+	// El intento se creó justo ahora: para que cuente como rancio se evalúa
+	// dos horas más tarde, con un umbral de una hora.
+	now := time.Now().Add(2 * time.Hour)
+	cleared, err := s.ResetLatest("rt1", now, time.Hour)
+	if err != nil {
+		t.Fatalf("reset: %v", err)
+	}
+	if !cleared {
+		t.Fatal("esperaba limpiar el running rancio")
+	}
+	if up, _ := s.LatestUpgrade("rt1"); up != nil {
+		t.Fatalf("tras reset no debería haber upgrade: %+v", up)
+	}
+}
+
+func TestResetLatestKeepsFreshRunning(t *testing.T) {
+	s := open(t)
+	id, err := s.BeginUpgrade("rt1", "v2", "http://x", "abc")
+	if err != nil {
+		t.Fatalf("begin: %v", err)
+	}
+	if err := s.SetStatus(id, "running", "", ""); err != nil {
+		t.Fatalf("set running: %v", err)
+	}
+	cleared, err := s.ResetLatest("rt1", time.Now(), time.Hour)
+	if err != nil {
+		t.Fatalf("reset: %v", err)
+	}
+	if cleared {
+		t.Fatal("no debe limpiar un upgrade vivo")
+	}
+	if up, _ := s.LatestUpgrade("rt1"); up == nil || up.Status != "running" {
+		t.Fatalf("el upgrade debe seguir: %+v", up)
+	}
+}
+
+func TestResetLatestClearsFailed(t *testing.T) {
+	s := open(t)
+	id, _ := s.BeginUpgrade("rt1", "v2", "http://x", "abc")
+	if err := s.SetStatus(id, "failed", "boom", ""); err != nil {
+		t.Fatalf("set failed: %v", err)
+	}
+	cleared, err := s.ResetLatest("rt1", time.Now(), time.Hour)
+	if err != nil || !cleared {
+		t.Fatalf("reset = (%v, %v), esperaba limpiar el failed", cleared, err)
+	}
+}

+ 81 - 0
server-go/internal/httpapi/agent.go

@@ -35,6 +35,7 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
 	"github.com/gnacho/netpulse/server-go/internal/agentinstall"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
+	"github.com/gnacho/netpulse/server-go/internal/openwrtpkg"
 	"github.com/gnacho/netpulse/server-go/internal/rearmer"
 	"github.com/gnacho/netpulse/server-go/internal/reinstall"
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
@@ -383,6 +384,86 @@ func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
 	http.ServeContent(w, r, st.Name(), st.ModTime(), rs)
 }
 
+// handleAgentPackage sirve el paquete .ipk del agente, generado al vuelo
+// desde el binario embebido (#1476). Misma auth que el binario: el instalador
+// ya lleva el token del equipo.
+//
+// Es el camino que instala el agente como paquete OpenWrt, con su config UCI
+// nativa como conffile, en vez de dejar binario, init y fichero de entorno
+// sueltos por SSH. Un router sin opkg (o con un fallo de descarga) sigue
+// teniendo el camino de ficheros sueltos en el script de reinstall.
+func (s *server) handleAgentPackage(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	if !agentSlugRe.MatchString(slug) {
+		writeError(w, http.StatusNotFound, "not_found")
+		return
+	}
+	token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+	if !s.checkAgentToken(slug, token) {
+		writeError(w, http.StatusUnauthorized, "unauthorized")
+		return
+	}
+	arch := r.URL.Query().Get("arch")
+	if arch == "" {
+		writeError(w, http.StatusBadRequest, "invalid_request",
+			"falta ?arch= (amd64, arm64, arm, mips, mipsle)")
+		return
+	}
+	// #1476: format=ipk (por defecto) lo compone el servidor al vuelo desde el
+	// binario embebido. format=apk sirve el asset que firma el CI: el formato
+	// v3 de apk-tools no se puede fabricar aqui sin su SDK.
+	format := r.URL.Query().Get("format")
+	if format == "" {
+		format = "ipk"
+	}
+	switch format {
+	case "ipk":
+		f, err := agentbin.Open(arch)
+		if err != nil {
+			writeError(w, http.StatusNotFound, "not_found",
+				"binario no disponible para "+arch+" (compila el servidor con los binarios de agente embebidos)")
+			return
+		}
+		binary, readErr := io.ReadAll(f)
+		f.Close()
+		if readErr != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+		ipk, err := openwrtpkg.BuildIPK(arch, agentbin.EmbeddedAgentVersion, binary)
+		if err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
+			return
+		}
+		w.Header().Set("Content-Type", "application/octet-stream")
+		w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-agent_%s_%s.ipk"`, agentbin.EmbeddedAgentVersion, arch))
+		if d := agentbin.Digest(arch); d != "" {
+			w.Header().Set("X-Binary-Checksum-Sha256", d)
+		}
+		w.Header().Set("Content-Length", strconv.Itoa(len(ipk)))
+		_, _ = w.Write(ipk)
+	case "apk":
+		f, err := agentbin.OpenAsset(arch, "apk")
+		if err != nil {
+			writeError(w, http.StatusNotFound, "not_found",
+				"paquete .apk no empaquetado para "+arch+" (lo firma el CI y se copia a agents/)")
+			return
+		}
+		pkg, readErr := io.ReadAll(f)
+		f.Close()
+		if readErr != nil {
+			writeError(w, http.StatusInternalServerError, "internal_error")
+			return
+		}
+		w.Header().Set("Content-Type", "application/octet-stream")
+		w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-agent_%s_%s.apk"`, agentbin.EmbeddedAgentVersion, arch))
+		w.Header().Set("Content-Length", strconv.Itoa(len(pkg)))
+		_, _ = w.Write(pkg)
+	default:
+		writeError(w, http.StatusBadRequest, "invalid_request", "format no soportado: "+format)
+	}
+}
+
 // ---------------------------------------------------------------------------
 // Gestión de tokens (sesión): POST/GET /api/agents, DELETE /api/agents/{slug}
 // ---------------------------------------------------------------------------

+ 10 - 4
server-go/internal/httpapi/backup.go

@@ -107,7 +107,7 @@ func (s *server) runBackup() (string, error) {
 
 	cfg := getBackupConfig(s.db)
 	backupDir := filepath.Join(filepath.Dir(s.db.Path), "backups")
-	if err := os.MkdirAll(backupDir, 0755); err != nil {
+	if err := ensureBackupDir(backupDir); err != nil {
 		return "", err
 	}
 
@@ -256,7 +256,7 @@ func (s *server) registerBackupRoutes(mux *http.ServeMux) {
 	// log on-box con el admin que descargó.
 	mux.Handle("GET /api/backup/download", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		backupDir := filepath.Join(filepath.Dir(s.db.Path), "backups")
-		os.MkdirAll(backupDir, 0755)
+		_ = ensureBackupDir(backupDir)
 		tmpFile := filepath.Join(backupDir, "export-temp.db")
 		if err := copyFile(s.db.Path, tmpFile); err != nil {
 			writeError(w, http.StatusInternalServerError, "backup_error")
@@ -281,11 +281,14 @@ func copyFile(src, dst string) error {
 	}
 	defer srcFile.Close()
 
-	dstFile, err := os.Create(dst)
+	dstFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, backupFileMode)
 	if err != nil {
 		return err
 	}
 	defer dstFile.Close()
+	if err := dstFile.Chmod(backupFileMode); err != nil {
+		return err
+	}
 
 	_, err = dstFile.ReadFrom(srcFile)
 	return err
@@ -301,11 +304,14 @@ func gzipFile(src, dst string) error {
 	}
 	defer in.Close()
 
-	out, err := os.Create(dst)
+	out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, backupFileMode)
 	if err != nil {
 		return err
 	}
 	defer out.Close()
+	if err := out.Chmod(backupFileMode); err != nil {
+		return err
+	}
 
 	zw := gzip.NewWriter(out)
 	if _, err := io.Copy(zw, in); err != nil {

+ 193 - 0
server-go/internal/httpapi/config_backup_schedule.go

@@ -0,0 +1,193 @@
+package httpapi
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"log"
+	"net/http"
+	"strconv"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/auth"
+)
+
+// #1795: programación semanal del backup de configuración de los agentes.
+// El backup lo ejecuta cada agente al recibir config_backup y sube el
+// tar.gz resultante, así que el disparo solo alcanza agentes SSE conectados.
+const (
+	configBackupScheduleTick = 30 * time.Second
+	cfgBackupSchedulePrefix  = "config_backup.schedule."
+)
+
+// ConfigBackupSchedule: día 0=domingo..6 y hora local HH:MM, igual que la
+// recurrencia de firmware.
+type ConfigBackupSchedule struct {
+	Enabled   bool   `json:"enabled"`
+	DayOfWeek int    `json:"dayOfWeek"`
+	Time      string `json:"time"`
+	LastRunMs int64  `json:"lastRunMs"`
+	NextRunMs int64  `json:"nextRunMs,omitempty"`
+}
+
+func defaultConfigBackupSchedule() ConfigBackupSchedule {
+	return ConfigBackupSchedule{DayOfWeek: 0, Time: "03:00"}
+}
+
+func (s *server) loadConfigBackupSchedule() ConfigBackupSchedule {
+	sched := defaultConfigBackupSchedule()
+	if s.db == nil {
+		return sched
+	}
+	sched.Enabled = kvGetBool(s.db.DB, cfgBackupSchedulePrefix+"enabled")
+	sched.DayOfWeek = kvGetInt(s.db.DB, cfgBackupSchedulePrefix+"day_of_week", 0)
+	if v := kvGet(s.db.DB, cfgBackupSchedulePrefix+"time"); v != "" {
+		sched.Time = v
+	}
+	if v := kvGet(s.db.DB, cfgBackupSchedulePrefix+"last_run_ms"); v != "" {
+		sched.LastRunMs, _ = strconv.ParseInt(v, 10, 64)
+	}
+	if validateConfigBackupSchedule(sched) != nil {
+		sched.Enabled = false
+		sched.DayOfWeek = 0
+		sched.Time = "03:00"
+	}
+	sched.NextRunMs = nextConfigBackupSchedule(sched.DayOfWeek, sched.Time, time.Now()).UnixMilli()
+	return sched
+}
+
+func (s *server) saveConfigBackupSchedule(sched ConfigBackupSchedule) error {
+	if s.db == nil {
+		return fmt.Errorf("no_db")
+	}
+	if err := validateConfigBackupSchedule(sched); err != nil {
+		return err
+	}
+	if err := kvSetBool(s.db.DB, cfgBackupSchedulePrefix+"enabled", sched.Enabled); err != nil {
+		return err
+	}
+	if err := kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"day_of_week", strconv.Itoa(sched.DayOfWeek)); err != nil {
+		return err
+	}
+	if err := kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"time", sched.Time); err != nil {
+		return err
+	}
+	return kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"last_run_ms", strconv.FormatInt(sched.LastRunMs, 10))
+}
+
+func validateConfigBackupSchedule(sched ConfigBackupSchedule) error {
+	if sched.DayOfWeek < 0 || sched.DayOfWeek > 6 {
+		return fmt.Errorf("dayOfWeek debe estar entre 0 y 6")
+	}
+	parsed, err := time.Parse("15:04", sched.Time)
+	if err != nil || parsed.Format("15:04") != sched.Time {
+		return fmt.Errorf("time debe ser HH:MM")
+	}
+	return nil
+}
+
+// configBackupScheduleDue sigue el contrato de la recurrencia semanal de
+// firmware: solo el día elegido, con el slot ya alcanzado, y sin catch-up de
+// días perdidos.
+func configBackupScheduleDue(sched ConfigBackupSchedule, now time.Time) bool {
+	if !sched.Enabled || int(now.Weekday()) != sched.DayOfWeek {
+		return false
+	}
+	parsed, err := time.Parse("15:04", sched.Time)
+	if err != nil {
+		return false
+	}
+	slot := time.Date(now.Year(), now.Month(), now.Day(), parsed.Hour(), parsed.Minute(), 0, 0, now.Location())
+	return !now.Before(slot) && sched.LastRunMs < slot.UnixMilli()
+}
+
+func nextConfigBackupSchedule(day int, clock string, now time.Time) time.Time {
+	parsed, err := time.Parse("15:04", clock)
+	if err != nil {
+		parsed = time.Date(0, 1, 1, 3, 0, 0, 0, time.UTC)
+	}
+	days := (day - int(now.Weekday()) + 7) % 7
+	next := time.Date(now.Year(), now.Month(), now.Day()+days, parsed.Hour(), parsed.Minute(), 0, 0, now.Location())
+	if !next.After(now) {
+		next = next.AddDate(0, 0, 7)
+	}
+	return next
+}
+
+func (s *server) registerConfigBackupScheduleRoutes(mux *http.ServeMux) {
+	mux.Handle("GET /api/settings/config-backup-schedule", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		writeJSON(w, http.StatusOK, s.loadConfigBackupSchedule())
+	})))
+	mux.Handle("PUT /api/settings/config-backup-schedule", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if s.db == nil {
+			writeError(w, http.StatusServiceUnavailable, "no_db")
+			return
+		}
+		var req ConfigBackupSchedule
+		dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes))
+		if err := dec.Decode(&req); err != nil {
+			writeError(w, http.StatusBadRequest, "bad_request", "JSON inválido")
+			return
+		}
+		if err := validateConfigBackupSchedule(req); err != nil {
+			writeError(w, http.StatusBadRequest, "invalid_schedule", err.Error())
+			return
+		}
+		prev := s.loadConfigBackupSchedule()
+		req.LastRunMs = prev.LastRunMs
+		// Al activar, el slot ya pasado no se ejecuta de inmediato. Si hoy
+		// aún no ha llegado, last_run=ahora sigue siendo anterior al slot.
+		if req.Enabled && !prev.Enabled {
+			req.LastRunMs = time.Now().UnixMilli()
+		}
+		if err := s.saveConfigBackupSchedule(req); err != nil {
+			writeError(w, http.StatusInternalServerError, "save_failed", err.Error())
+			return
+		}
+		req.NextRunMs = nextConfigBackupSchedule(req.DayOfWeek, req.Time, time.Now()).UnixMilli()
+		writeJSON(w, http.StatusOK, req)
+	})))
+}
+
+func (s *server) configBackupScheduleLoop(ctx context.Context, tick time.Duration) {
+	t := time.NewTicker(tick)
+	defer t.Stop()
+	for {
+		select {
+		case <-ctx.Done():
+			return
+		case <-t.C:
+			s.configBackupScheduleTick()
+		}
+	}
+}
+
+func (s *server) configBackupScheduleTick() {
+	s.configBackupScheduleTickAt(time.Now())
+}
+
+func (s *server) configBackupScheduleTickAt(now time.Time) {
+	sched := s.loadConfigBackupSchedule()
+	if !configBackupScheduleDue(sched, now) || s.agentHub == nil {
+		return
+	}
+	sent := 0
+	for _, slug := range s.agentHub.ConnectedSlugs() {
+		if err := s.agentHub.SendPrivileged(slug, "config_backup", map[string]any{}); err != nil {
+			log.Printf("[netpulse] config backup programado: %s: %v", slug, err)
+			continue
+		}
+		sent++
+	}
+	if sent == 0 {
+		// Sin agentes conectados no se quema el slot: se reintenta al
+		// reconectar dentro de la misma semana.
+		return
+	}
+	lastRun := time.Now().UnixMilli()
+	if err := kvSetStr(s.db.DB, cfgBackupSchedulePrefix+"last_run_ms", strconv.FormatInt(lastRun, 10)); err != nil {
+		log.Printf("[netpulse] config backup programado: guardar last_run: %v", err)
+		return
+	}
+	log.Printf("[netpulse] config backup programado enviado a %d agentes", sent)
+}

+ 97 - 0
server-go/internal/httpapi/config_backup_schedule_test.go

@@ -0,0 +1,97 @@
+package httpapi
+
+import (
+	"path/filepath"
+	"testing"
+	"time"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+	"github.com/gnacho/netpulse/server-go/internal/sse"
+)
+
+func newScheduleTestServer(t *testing.T) *server {
+	t.Helper()
+	d, err := db.Open(filepath.Join(t.TempDir(), "test.db"))
+	if err != nil {
+		t.Fatalf("db.Open: %v", err)
+	}
+	t.Cleanup(func() { _ = d.Close() })
+	return &server{db: d, agentHub: sse.NewAgentHub(nil)}
+}
+
+func TestConfigBackupScheduleDefaultsAndRoundTrip(t *testing.T) {
+	s := newScheduleTestServer(t)
+	got := s.loadConfigBackupSchedule()
+	if got.Enabled || got.DayOfWeek != 0 || got.Time != "03:00" {
+		t.Fatalf("defaults: %+v", got)
+	}
+	want := ConfigBackupSchedule{Enabled: true, DayOfWeek: 5, Time: "04:25", LastRunMs: 1234}
+	if err := s.saveConfigBackupSchedule(want); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	got = s.loadConfigBackupSchedule()
+	if !got.Enabled || got.DayOfWeek != 5 || got.Time != "04:25" || got.LastRunMs != 1234 {
+		t.Fatalf("round trip: %+v", got)
+	}
+}
+
+func TestConfigBackupScheduleValidation(t *testing.T) {
+	for _, tc := range []ConfigBackupSchedule{
+		{DayOfWeek: 7, Time: "03:00"},
+		{DayOfWeek: -1, Time: "03:00"},
+		{DayOfWeek: 0, Time: "3:00"},
+		{DayOfWeek: 0, Time: "25:00"},
+	} {
+		if err := validateConfigBackupSchedule(tc); err == nil {
+			t.Fatalf("validó %+v", tc)
+		}
+	}
+}
+
+func TestConfigBackupScheduleDue(t *testing.T) {
+	loc := time.FixedZone("test", 3600)
+	monday := time.Date(2026, time.November, 2, 4, 0, 0, 0, loc) // lunes
+	sched := ConfigBackupSchedule{Enabled: true, DayOfWeek: 1, Time: "03:00"}
+	if !configBackupScheduleDue(sched, monday) {
+		t.Fatal("el slot del lunes debería vencer")
+	}
+	sched.LastRunMs = monday.Add(-time.Hour).UnixMilli()
+	if configBackupScheduleDue(sched, monday) {
+		t.Fatal("un run posterior al slot no debe repetirse")
+	}
+	sched.LastRunMs = 0
+	if configBackupScheduleDue(sched, monday.AddDate(0, 0, 1)) {
+		t.Fatal("martes no debe hacer catch-up del lunes")
+	}
+	sched.Enabled = false
+	if configBackupScheduleDue(sched, monday) {
+		t.Fatal("desactivado no debe vencer")
+	}
+}
+
+func TestNextConfigBackupSchedule(t *testing.T) {
+	loc := time.FixedZone("test", 3600)
+	monday := time.Date(2026, time.November, 2, 4, 0, 0, 0, loc)
+	next := nextConfigBackupSchedule(1, "03:00", monday)
+	if !next.Equal(time.Date(2026, time.November, 9, 3, 0, 0, 0, loc)) {
+		t.Fatalf("next = %v", next)
+	}
+	sunday := time.Date(2026, time.November, 8, 4, 0, 0, 0, loc)
+	next = nextConfigBackupSchedule(0, "05:00", sunday)
+	if !next.Equal(time.Date(2026, time.November, 8, 5, 0, 0, 0, loc)) {
+		t.Fatalf("next domingo = %v", next)
+	}
+}
+
+func TestConfigBackupScheduleTickWithoutAgentsKeepsSlot(t *testing.T) {
+	s := newScheduleTestServer(t)
+	loc := time.FixedZone("test", 3600)
+	monday := time.Date(2026, time.November, 2, 4, 0, 0, 0, loc)
+	if err := s.saveConfigBackupSchedule(ConfigBackupSchedule{Enabled: true, DayOfWeek: 1, Time: "03:00"}); err != nil {
+		t.Fatalf("save: %v", err)
+	}
+	s.configBackupScheduleTickAt(monday)
+	if got := s.loadConfigBackupSchedule().LastRunMs; got != 0 {
+		t.Fatalf("sin agentes no debe marcar last_run: %d", got)
+	}
+}

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

@@ -4,6 +4,7 @@ package httpapi
 import (
 	"errors"
 	"net/http"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/adapters"
 	"github.com/gnacho/netpulse/server-go/internal/auth"
@@ -11,6 +12,11 @@ import (
 	"github.com/gnacho/netpulse/server-go/internal/routerstore"
 )
 
+// upgradeResetStaleAfter: antigüedad mínima de un intento en curso para que
+// el reset lo considere atascado (#1776). Por debajo de eso se respeta, para
+// no cancelar un upgrade que está trabajando.
+const upgradeResetStaleAfter = 15 * time.Minute
+
 // firmwareStatusResponse es la vista completa de un router para upgrades.
 type firmwareStatusResponse struct {
 	RouterID       string `json:"routerId"`
@@ -129,6 +135,24 @@ func (s *server) registerFirmwareRoutes(mux *http.ServeMux) {
 		writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
 	})))
 
+	// POST /api/firmware-upgrades/{routerId}/reset: desatasca el estado de
+	// upgrade del router (#1776). Borra un intento terminado (failed/done) y
+	// también un registro en curso que lleva más de upgradeResetStaleAfter sin
+	// avanzar; un upgrade vivo no se toca, para no cancelarlo por accidente.
+	mux.Handle("POST /api/firmware-upgrades/{routerId}/reset", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		routerID := r.PathValue("routerId")
+		if routerID == "" {
+			writeError(w, http.StatusBadRequest, "invalid_input", "routerId requerido")
+			return
+		}
+		cleared, err := s.firmware.ResetLatest(routerID, time.Now(), upgradeResetStaleAfter)
+		if err != nil {
+			writeError(w, http.StatusInternalServerError, "firmware_error")
+			return
+		}
+		writeJSON(w, http.StatusOK, map[string]any{"ok": true, "cleared": cleared})
+	})))
+
 	mux.Handle("GET /api/firmware-upgrades/{routerId}", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		id := r.PathValue("routerId")
 		item, err := s.firmwareStatus(id)

+ 97 - 0
server-go/internal/httpapi/firmware_backup_internal_test.go

@@ -0,0 +1,97 @@
+package httpapi
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+func TestFirmwareBackupTimestampMatchesExactUnit(t *testing.T) {
+	cases := []struct {
+		name string
+		slug string
+		ts   int64
+		ok   bool
+	}{
+		{"gateway-1793293266-gateway.tar.gz", "gateway", 1793293266, true},
+		{"AP1-1793224785-netgear-wax220.tar.gz", "netgear-wax220", 1793224785, true},
+		{"AP1-1793224785-netgear-wax220-2.tar.gz", "netgear-wax220-2", 1793224785, true},
+		{"AP1-1793224785-netgear-wax220-2.tar.gz", "netgear-wax220", 0, false},
+		{"netgear-wax220-1793224785.tar.gz", "netgear-wax220", 1793224785, true},
+		{"netgear-wax220-2-1793087496.tar.gz", "netgear-wax220", 0, false},
+		{"netgear-wax220-2-1793087496.tar.gz", "netgear-wax220-2", 1793087496, true},
+		{"gateway-1793293266.tar.gz", "gateway", 1793293266, true},
+		{"gateway-179329326-gateway.tar.gz", "gateway", 0, false},
+		{"gateway.tar.gz", "gateway", 0, false},
+	}
+	for _, tc := range cases {
+		ts, ok := firmwareBackupTimestamp(tc.name, tc.slug)
+		if ts != tc.ts || ok != tc.ok {
+			t.Errorf("firmwareBackupTimestamp(%q,%q) = (%d,%v), want (%d,%v)", tc.name, tc.slug, ts, ok, tc.ts, tc.ok)
+		}
+	}
+}
+
+func TestPruneFirmwareBackupsKeepsOnlyExactUnit(t *testing.T) {
+	dir := t.TempDir()
+	for i := 0; i < 7; i++ {
+		name := firmwareBackupFileName("AP1", "netgear-wax220", int64(1793224785+i))
+		if err := os.WriteFile(filepath.Join(dir, name), []byte("x"), 0o640); err != nil {
+			t.Fatal(err)
+		}
+	}
+	other := firmwareBackupFileName("AP2", "netgear-wax220-2", 1793087496)
+	if err := os.WriteFile(filepath.Join(dir, other), []byte("x"), 0o640); err != nil {
+		t.Fatal(err)
+	}
+
+	pruneFirmwareBackups(dir, "netgear-wax220")
+
+	entries, err := os.ReadDir(dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if len(entries) != maxFirmwareBackupsPerRouter+1 {
+		t.Fatalf("quedan %d archivos, quiero %d", len(entries), maxFirmwareBackupsPerRouter+1)
+	}
+	if _, err := os.Stat(filepath.Join(dir, other)); err != nil {
+		t.Fatalf("el backup de la otra unidad se borró: %v", err)
+	}
+	for _, want := range []string{
+		firmwareBackupFileName("AP1", "netgear-wax220", 1793224789),
+		firmwareBackupFileName("AP1", "netgear-wax220", 1793224791),
+	} {
+		if _, err := os.Stat(filepath.Join(dir, want)); err != nil {
+			t.Fatalf("falta el backup reciente %q: %v", want, err)
+		}
+	}
+	oldest := firmwareBackupFileName("AP1", "netgear-wax220", 1793224785)
+	if _, err := os.Stat(filepath.Join(dir, oldest)); !os.IsNotExist(err) {
+		t.Fatalf("el backup más antiguo debería haberse podado: %v", err)
+	}
+}
+
+func TestFirmwareBackupFileNameUsesReadableUnit(t *testing.T) {
+	got := firmwareBackupFileName(" AP1 salón ", "netgear-wax220", 1793224785)
+	want := "AP1-salón-1793224785-netgear-wax220.tar.gz"
+	if got != want {
+		t.Fatalf("nombre = %q, quiero %q", got, want)
+	}
+	if got := sanitizeBackupLabel(" --- "); got != "netpulse" {
+		t.Fatalf("fallback = %q", got)
+	}
+}
+
+func TestEnsureBackupDirGroupAccess(t *testing.T) {
+	dir := filepath.Join(t.TempDir(), "backups", "firmware")
+	if err := ensureBackupDir(dir); err != nil {
+		t.Fatal(err)
+	}
+	st, err := os.Stat(dir)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if got := st.Mode().Perm(); got != 0o770 {
+		t.Fatalf("permisos = %o, quiero 770", got)
+	}
+}

+ 69 - 0
server-go/internal/httpapi/firmware_reset_test.go

@@ -0,0 +1,69 @@
+// firmware_reset_test.go - contrato HTTP del reset del estado de upgrade
+// (#1776): un intento atascado se limpia desde la UI sin tocar la API a mano.
+package httpapi_test
+
+import (
+	"net/http"
+	"testing"
+)
+
+// upgradeOf busca la fila del router en la lista y devuelve su objeto
+// "upgrade", o nil cuando no hay ninguno.
+func upgradeOf(t *testing.T, ts *testServer, rid, cookie string) map[string]any {
+	t.Helper()
+	res := getJSONPath(t, ts.URL, "/api/firmware-upgrades", cookie)
+	for _, it := range readJSONArray(t, res) {
+		m, _ := it.(map[string]any)
+		if m["routerId"] != rid {
+			continue
+		}
+		up, _ := m["upgrade"].(map[string]any)
+		return up
+	}
+	t.Fatalf("%s no aparece en la lista", rid)
+	return nil
+}
+
+// #1776: un intento terminado en failed se limpia con el reset y la fila deja
+// de anunciarlo. Es el caso que antes exigía borrar la fila a mano.
+func TestFirmwareResetClearsFailedUpgrade(t *testing.T) {
+	ssh := &scriptedSSH{rules: []sshRule{
+		{contains: "command -v owut", out: "__owut__\n"},
+		{contains: "owut upgrade", out: "Update checks reveal errors, can't proceed\n__owut_exit__=1\n"},
+	}}
+	ts, rid := makeOwutTestServer(t, ssh)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	if res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/owut-upgrade", `{"targetVersion":"25.12.7"}`, cookie); res.StatusCode != 202 {
+		t.Fatalf("status del upgrade %d", res.StatusCode)
+	}
+	waitForUpgradeStatus(t, ts, rid, "failed", cookie)
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/reset", "{}", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if body["ok"] != true || body["cleared"] != true {
+		t.Fatalf("respuesta del reset: %v", body)
+	}
+	if up := upgradeOf(t, ts, rid, cookie); up != nil {
+		t.Fatalf("tras el reset no debería quedar upgrade: %v", up)
+	}
+}
+
+// #1776: sin nada que limpiar el endpoint es idempotente y lo dice, en vez de
+// inventar un borrado.
+func TestFirmwareResetWithoutUpgrade(t *testing.T) {
+	ts, rid := makeOwutTestServer(t, nil)
+	_, cookie, _ := loginCookie(t, ts.URL, "admin", "test123456")
+
+	res := postJSON(t, ts.URL, "/api/firmware-upgrades/"+rid+"/reset", "{}", cookie)
+	body := readJSON(t, res)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status %d: %v", res.StatusCode, body)
+	}
+	if body["cleared"] != false {
+		t.Fatalf("cleared: %v, quería false sin upgrade", body["cleared"])
+	}
+}

+ 133 - 16
server-go/internal/httpapi/firmware_upload.go

@@ -5,6 +5,7 @@
 package httpapi
 
 import (
+	"context"
 	"crypto/sha256"
 	"encoding/hex"
 	"errors"
@@ -17,6 +18,7 @@ import (
 	"strconv"
 	"strings"
 	"time"
+	"unicode"
 
 	"github.com/gnacho/netpulse/server-go/internal/auth"
 	"github.com/gnacho/netpulse/server-go/internal/firmware"
@@ -195,17 +197,23 @@ func (s *server) registerFirmwareBackupRoutes(mux *http.ServeMux) {
 			return
 		}
 		dir := s.firmwareBackupDir()
-		if err := os.MkdirAll(dir, 0o700); err != nil {
+		if err := ensureBackupDir(dir); err != nil {
 			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
 			return
 		}
-		name := fmt.Sprintf("%s-%d.tar.gz", slug, time.Now().Unix())
+		name := s.firmwareBackupName(r.Context(), slug)
 		dest := filepath.Join(dir, name)
-		df, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
+		df, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, backupFileMode)
 		if err != nil {
 			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
 			return
 		}
+		if err := df.Chmod(backupFileMode); err != nil {
+			df.Close()
+			os.Remove(dest)
+			writeError(w, http.StatusInternalServerError, "firmware_error", err.Error())
+			return
+		}
 		n, copyErr := io.Copy(df, io.LimitReader(r.Body, maxFirmwareUpload+1))
 		closeErr := df.Close()
 		if copyErr != nil || closeErr != nil {
@@ -241,15 +249,14 @@ func (s *server) registerFirmwareBackupRoutes(mux *http.ServeMux) {
 		}
 		out := []info{}
 		for _, e := range entries {
-			if e.IsDir() || !strings.HasPrefix(e.Name(), id+"-") || !strings.HasSuffix(e.Name(), ".tar.gz") {
+			if e.IsDir() {
+				continue
+			}
+			ts, ok := firmwareBackupTimestamp(e.Name(), id)
+			if !ok {
 				continue
 			}
 			if fi, err := e.Info(); err == nil {
-				// ts = parte numérica del nombre (<slug>-<ts>.tar.gz)
-				ts := int64(0)
-				if n, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimPrefix(e.Name(), id+"-"), ".tar.gz"), 10, 64); err == nil {
-					ts = n
-				}
 				out = append(out, info{Name: e.Name(), Size: fi.Size(), Ts: ts})
 			}
 		}
@@ -261,7 +268,11 @@ func (s *server) registerFirmwareBackupRoutes(mux *http.ServeMux) {
 	mux.Handle("GET /api/firmware-backups/{routerId}/file", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		id := r.PathValue("routerId")
 		name := filepath.Base(r.URL.Query().Get("name"))
-		if name == "." || name == "" || !strings.HasPrefix(name, id+"-") || !strings.HasSuffix(name, ".tar.gz") {
+		if name == "." || name == "" {
+			writeError(w, http.StatusNotFound, "not_found")
+			return
+		}
+		if _, ok := firmwareBackupTimestamp(name, id); !ok {
 			writeError(w, http.StatusNotFound, "not_found")
 			return
 		}
@@ -282,22 +293,128 @@ func (s *server) registerFirmwareBackupRoutes(mux *http.ServeMux) {
 }
 
 // pruneFirmwareBackups deja los maxFirmwareBackupsPerRouter más recientes de
-// una unidad (el nombre lleva ts, ordenar por nombre = ordenar por ts).
+// una unidad. El id se compara con el sufijo exacto del nombre, no con un
+// prefijo: "netgear-wax220" no debe capturar los backups de
+// "netgear-wax220-2" (#1795).
 func pruneFirmwareBackups(dir, slug string) {
 	entries, err := os.ReadDir(dir)
 	if err != nil {
 		return
 	}
-	var mine []os.DirEntry
+	type backup struct {
+		name string
+		ts   int64
+	}
+	var mine []backup
 	for _, e := range entries {
-		if !e.IsDir() && strings.HasPrefix(e.Name(), slug+"-") && strings.HasSuffix(e.Name(), ".tar.gz") {
-			mine = append(mine, e)
+		if e.IsDir() {
+			continue
+		}
+		if ts, ok := firmwareBackupTimestamp(e.Name(), slug); ok {
+			mine = append(mine, backup{name: e.Name(), ts: ts})
 		}
 	}
-	sort.Slice(mine, func(i, j int) bool { return mine[i].Name() > mine[j].Name() })
+	sort.Slice(mine, func(i, j int) bool {
+		if mine[i].ts == mine[j].ts {
+			return mine[i].name > mine[j].name
+		}
+		return mine[i].ts > mine[j].ts
+	})
 	for i := maxFirmwareBackupsPerRouter; i < len(mine); i++ {
-		os.Remove(filepath.Join(dir, mine[i].Name()))
+		os.Remove(filepath.Join(dir, mine[i].name))
+	}
+}
+
+// firmwareBackupTimestamp reconoce el formato nuevo
+// (<unidad>-<unix10>-<slug>.tar.gz) y el legacy (<slug>-<unix10>.tar.gz).
+// Compara el slug por su límite exacto y devuelve el ts común de ambos.
+func firmwareBackupTimestamp(name, slug string) (int64, bool) {
+	if slug == "" || !strings.HasSuffix(name, ".tar.gz") {
+		return 0, false
+	}
+	stem := strings.TrimSuffix(name, ".tar.gz")
+	if strings.HasSuffix(stem, "-"+slug) {
+		prefix := strings.TrimSuffix(stem, "-"+slug)
+		if i := strings.LastIndexByte(prefix, '-'); i > 0 {
+			if ts, ok := parseBackupTimestamp(prefix[i+1:]); ok {
+				return ts, true
+			}
+		}
+	}
+	legacyPrefix := slug + "-"
+	if strings.HasPrefix(stem, legacyPrefix) {
+		if ts, ok := parseBackupTimestamp(strings.TrimPrefix(stem, legacyPrefix)); ok {
+			return ts, true
+		}
+	}
+	return 0, false
+}
+
+func parseBackupTimestamp(s string) (int64, bool) {
+	if len(s) != 10 {
+		return 0, false
+	}
+	for _, r := range s {
+		if r < '0' || r > '9' {
+			return 0, false
+		}
+	}
+	ts, err := strconv.ParseInt(s, 10, 64)
+	return ts, err == nil
+}
+
+// firmwareBackupName usa el nombre visible de la unidad para que el archivo
+// se reconozca fuera de la UI, y mantiene el slug al final para resolverlo
+// sin ambigüedad. Si la unidad ya no existe, cae al slug.
+func (s *server) firmwareBackupName(ctx context.Context, slug string) string {
+	label := slug
+	if s.adapter != nil {
+		for _, router := range s.adapter.GetRouters(ctx) {
+			if router.ID == slug && strings.TrimSpace(router.Name) != "" {
+				label = router.Name
+				break
+			}
+		}
+	}
+	return firmwareBackupFileName(label, slug, time.Now().Unix())
+}
+
+func firmwareBackupFileName(label, slug string, ts int64) string {
+	return fmt.Sprintf("%s-%d-%s.tar.gz", sanitizeBackupLabel(label), ts, slug)
+}
+
+func sanitizeBackupLabel(label string) string {
+	var b strings.Builder
+	lastDash := false
+	for _, r := range strings.TrimSpace(label) {
+		ok := unicode.IsLetter(r) || unicode.IsDigit(r) || r == '.' || r == '_'
+		if ok {
+			b.WriteRune(r)
+			lastDash = false
+			continue
+		}
+		if !lastDash {
+			b.WriteByte('-')
+			lastDash = true
+		}
+	}
+	out := strings.Trim(b.String(), "-.")
+	if out == "" {
+		return "netpulse"
+	}
+	return out
+}
+
+const (
+	backupDirMode  = 0o770
+	backupFileMode = 0o640
+)
+
+func ensureBackupDir(path string) error {
+	if err := os.MkdirAll(path, backupDirMode); err != nil {
+		return err
 	}
+	return os.Chmod(path, backupDirMode)
 }
 
 // handleFirmwareImage sirve la imagen subida de un router. El id se sanea:

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

@@ -527,6 +527,7 @@ func NewHandler(d Deps) http.Handler {
 	// Auth por token de agente (Bearer), igual que la ingesta — el one-liner de
 	// instalación incluye el token y se ejecuta en el router, sin sesión admin.
 	mux.HandleFunc("GET /api/agents/{slug}/binary", s.handleAgentBinary)
+	mux.HandleFunc("GET /api/agents/{slug}/package", s.handleAgentPackage)
 	// #1751: el instalador también se sirve desde el servidor, atado a su
 	// versión. Público: el script no lleva secretos y el one-liner le pasa el
 	// host y el token como argumentos.
@@ -615,6 +616,7 @@ func NewHandler(d Deps) http.Handler {
 
 	// --- Copias de seguridad (issue #158) ---
 	s.registerBackupRoutes(mux)
+	s.registerConfigBackupScheduleRoutes(mux)
 
 	// --- Rack canvas (fase 1) ---
 	s.registerRackRoutes(mux)
@@ -634,6 +636,9 @@ func NewHandler(d Deps) http.Handler {
 		// Barrido de versiones disponibles (#1777): check semanal por router,
 		// una alerta info por router+versión.
 		go s.firmwareSweepLoop(context.Background(), fwSweepTick)
+		// Backup de configuración semanal (#1795): dispara config_backup a
+		// los agentes conectados en el día y hora elegidos.
+		go s.configBackupScheduleLoop(context.Background(), configBackupScheduleTick)
 	}
 
 	// --- Overrides manuales de topología (issue #142; solo admin) ---

+ 33 - 0
server-go/internal/openwrtpkg/files/netpulse-agent.config

@@ -0,0 +1,33 @@
+# /etc/config/netpulse-agent — UCI config (OpenWrt)
+# Gestionado por opkg; se preserva en upgrades (conffiles).
+# Tras instalar, edita con `uci set netpulse-agent.main.server=...` o
+# `uci commit netpulse-agent` + `/etc/init.d/netpulse-agent restart`.
+
+config main 'main'
+	# URL del servidor NetPulse (obligatorio)
+	option server ''
+
+	# Token del equipo (64 hex; se muestra UNA vez al crearlo en el servidor)
+	option token ''
+
+	# Slug del equipo en NetPulse (obligatorio)
+	option slug ''
+
+	# Intervalo de sondeo completo (default 30s)
+	option interval '30s'
+
+	# Minimo entre scans de vecinos para "Analisis de canales" (default 30m;
+	# "0" los desactiva, solo on-demand). En APs con clientes Intel cada scan
+	# saca la radio del canal ~2-5s y puede costar un deauth (#699)
+	# option scan_interval '0'
+
+	# Ping WAN (solo gateway; p. ej. 1.1.1.1)
+	# option wan_target '1.1.1.1'
+
+	# Ping al gateway (solo APs; p. ej. 192.168.1.1)
+	# option gw_target '192.168.1.1'
+
+	# Fingerprint SPKI del servidor (obligatorio si server es https://)
+	# SHA-256 hex del SubjectPublicKeyInfo; se obtiene con:
+	#   curl http://<server>:<port>/fingerprint
+	# option server_fp ''

+ 79 - 0
server-go/internal/openwrtpkg/files/netpulse-agent.defaults

@@ -0,0 +1,79 @@
+#!/bin/sh
+# uci-defaults: ejecutado UNA vez tras instalar el .ipk.
+# Migra una instalación manual previa (si existe /etc/netpulse-agent.env)
+# al formato UCI, y retira el watchdog cron de versiones anteriores (#851).
+
+AGENT_ENV=/etc/netpulse-agent.env
+AGENT_UCI=netpulse-agent
+
+# NetGrip detectado (#363): el agente EMBEBIDO en el panel ya cubre este
+# router. Entregarle la config migrada (solo si aún no tiene) y NO instalar
+# el standalone (ni servicio ni watchdog ni cron).
+if [ -x /usr/sbin/netgrip ] || [ -f /etc/init.d/netgrip ]; then
+	NG_ENV=/etc/netgrip/netpulse.env
+	if [ ! -f "$NG_ENV" ] && [ -f "$AGENT_ENV" ]; then
+		. "$AGENT_ENV"
+		if [ -n "$NETPULSE_SERVER" ] && [ -n "$NETPULSE_SLUG" ] && [ -n "$NETPULSE_TOKEN" ]; then
+			mkdir -p /etc/netgrip
+			{
+				echo "# managed by netgrip; netpulse embedded agent config"
+				echo "NETPULSE_SERVER=$NETPULSE_SERVER"
+				echo "NETPULSE_SLUG=$NETPULSE_SLUG"
+				echo "NETPULSE_TOKEN=$NETPULSE_TOKEN"
+				echo "NETPULSE_ENABLED=1"
+			} > "$NG_ENV"
+			chmod 600 "$NG_ENV"
+			logger -t netpulse-agent "NetGrip detectado: config migrada a $NG_ENV"
+		fi
+	fi
+	/etc/init.d/netgrip restart >/dev/null 2>&1 || true
+	logger -t netpulse-agent "NetGrip detectado: agente standalone NO instalado"
+	exit 0
+fi
+
+# Migrar instalación manual previa (.env) a UCI
+if [ -f "$AGENT_ENV" ]; then
+	. "$AGENT_ENV"
+	[ -n "$NETPULSE_SERVER" ]  && uci set "$AGENT_UCI.main.server=$NETPULSE_SERVER"
+	[ -n "$NETPULSE_TOKEN" ]   && uci set "$AGENT_UCI.main.token=$NETPULSE_TOKEN"
+	[ -n "$NETPULSE_SLUG" ]    && uci set "$AGENT_UCI.main.slug=$NETPULSE_SLUG"
+	[ -n "$NETPULSE_INTERVAL" ] && uci set "$AGENT_UCI.main.interval=$NETPULSE_INTERVAL"
+	[ "$NETPULSE_INSECURE_TLS" = "1" ] && uci set "$AGENT_UCI.main.insecure_tls=1"
+	[ -n "$NETPULSE_WAN_TARGET" ] && uci set "$AGENT_UCI.main.wan_target=$NETPULSE_WAN_TARGET"
+	[ -n "$NETPULSE_GW_TARGET" ]  && uci set "$AGENT_UCI.main.gw_target=$NETPULSE_GW_TARGET"
+	uci commit "$AGENT_UCI"
+fi
+
+# Watchdog cron (#851): YA NO se programa. Si venimos de una versión que lo
+# instalaba, limpiarlo aquí: el reinicio a ciegas de un agente en bucle de
+# crash no lo arregla (solo ensucia el log); la detección efectiva es el
+# dead-man del servidor (alerta) y el crash puntual lo cubre el respawn de
+# procd. El binario tras sysupgrade lo restaura el self-heal del init.
+rm -f /usr/sbin/netpulse-watchdog
+crontab -l 2>/dev/null | grep -v netpulse-watchdog | crontab - 2>/dev/null || true
+
+# Habilitar y arrancar el servicio
+/etc/init.d/netpulse-agent enable
+/etc/init.d/netpulse-agent restart
+
+# Config vacía (#462): el servicio NO arrancará hasta definir server, token
+# y slug. Banner claro en consola y syslog en vez de un fallo silencioso.
+SERVER_CFG=$(uci -q get netpulse-agent.main.server)
+TOKEN_CFG=$(uci -q get netpulse-agent.main.token)
+SLUG_CFG=$(uci -q get netpulse-agent.main.slug)
+if [ -z "$SERVER_CFG" ] || [ -z "$TOKEN_CFG" ] || [ -z "$SLUG_CFG" ]; then
+	logger -t netpulse-agent "config vacía: define server, token y slug; el servicio no arrancará hasta completarla"
+	echo ""
+	echo "netpulse-agent: PENDIENTE DE CONFIGURAR: el servicio no arrancará hasta completarla."
+	echo "  1. Crea el agente en el servidor NetPulse (Ajustes → Agents) y copia su token (se muestra una sola vez)."
+	echo "  2. En este router:"
+	echo "       uci set netpulse-agent.main.server='http://<netpulse-server-ip>:3000'"
+	echo "       uci set netpulse-agent.main.slug='<slug>'"
+	echo "       uci set netpulse-agent.main.token='<token-64-hex>'"
+	echo "       uci commit netpulse-agent"
+	echo "       /etc/init.d/netpulse-agent enable && /etc/init.d/netpulse-agent restart"
+	echo "  (Si el servidor ya puede entrar por SSH a este router, usa el botón Reinstalar de la web y se configura solo.)"
+	echo ""
+fi
+
+exit 0

+ 111 - 0
server-go/internal/openwrtpkg/files/netpulse-agent.init

@@ -0,0 +1,111 @@
+#!/bin/sh /etc/rc.common
+# netpulse-agent — procd init script (OpenWrt)
+# Instalado por el paquete .ipk; config en /etc/config/netpulse-agent
+
+START=90
+USE_PROCD=1
+
+PROG=/usr/sbin/netpulse-agent
+HEARTBEAT_FILE=/tmp/netpulse-agent.heartbeat
+
+# Leer config UCI, con fallback a variables de entorno
+load_config() {
+	local server token slug interval
+
+	config_load netpulse-agent
+
+	config_get server  main server  ""
+	config_get token   main token   ""
+	config_get slug    main slug    ""
+
+	# Si no hay token/slug en UCI, heredar de /etc/netpulse-agent.env
+	# (instalación manual previa a .ipk)
+	if [ -z "$token" ] && [ -f /etc/netpulse-agent.env ]; then
+		. /etc/netpulse-agent.env
+	fi
+	if [ -z "$server" ]; then
+		server="$NETPULSE_SERVER"
+	fi
+	if [ -z "$token" ]; then
+		token="$NETPULSE_TOKEN"
+	fi
+	if [ -z "$slug" ]; then
+		slug="$NETPULSE_SLUG"
+	fi
+
+	config_get interval main interval "30s"
+
+	export NETPULSE_SERVER="$server"
+	export NETPULSE_TOKEN="$token"
+	export NETPULSE_SLUG="$slug"
+	export NETPULSE_INTERVAL="$interval"
+	export NETPULSE_HEARTBEAT_FILE="$HEARTBEAT_FILE"
+
+	# Intervalo entre scans de vecinos (#699): "0" los desactiva (solo
+	# on-demand). Vacío = default del agente (30m).
+	local scan_interval
+	config_get scan_interval main scan_interval ""
+	[ -n "$scan_interval" ] && export NETPULSE_SCAN_INTERVAL="$scan_interval"
+
+	# Targets de ping (solo se usan si están definidos)
+	local wan_target gw_target
+	config_get wan_target main wan_target ""
+	config_get gw_target  main gw_target  ""
+	[ -n "$wan_target" ] && export NETPULSE_WAN_TARGET="$wan_target"
+	[ -n "$gw_target" ]  && export NETPULSE_GW_TARGET="$gw_target"
+
+	# Fingerprint SPKI del servidor (obligatorio si server es https://)
+	local server_fp
+	config_get server_fp main server_fp ""
+	[ -n "$server_fp" ] && export NETPULSE_SERVER_FP="$server_fp"
+}
+
+
+# (#879) self-heal: tras un sysupgrade /etc sobrevive pero el binario del
+# watchdog no: si quedó la entrada de cron del antiguo watchdog, retirarla
+# (cron loguearía un comando inexistente cada 2 min).
+cleanup_stale_watchdog_cron() {
+	[ -f /usr/sbin/netpulse-watchdog ] && return 0
+	crontab -l 2>/dev/null | grep -q netpulse-watchdog || return 0
+	( crontab -l 2>/dev/null | grep -v netpulse-watchdog ) | crontab - 2>/dev/null || true
+	logger -t netpulse-agent "watchdog cron huérfano retirado (#879)"
+}
+
+start_service() {
+	cleanup_stale_watchdog_cron
+	load_config
+
+	# Validación mínima
+	if [ -z "$NETPULSE_SERVER" ] || [ -z "$NETPULSE_TOKEN" ] || [ -z "$NETPULSE_SLUG" ]; then
+		echo "netpulse-agent: falta server, token o slug en /etc/config/netpulse-agent"
+		return 1
+	fi
+
+	procd_open_instance
+	procd_set_param command "$PROG"
+	# #1772: procd lanza el binario desde su propio entorno, asi que los
+	# export de load_config no llegan al proceso. Una sola llamada env con
+	# todas las variables (varias llamadas se pisan entre si en 21.02).
+	procd_set_param env \
+		NETPULSE_SERVER="$NETPULSE_SERVER" \
+		NETPULSE_TOKEN="$NETPULSE_TOKEN" \
+		NETPULSE_SLUG="$NETPULSE_SLUG" \
+		NETPULSE_INTERVAL="$NETPULSE_INTERVAL" \
+		NETPULSE_HEARTBEAT_FILE="$NETPULSE_HEARTBEAT_FILE" \
+		NETPULSE_SCAN_INTERVAL="$NETPULSE_SCAN_INTERVAL" \
+		NETPULSE_WAN_TARGET="$NETPULSE_WAN_TARGET" \
+		NETPULSE_GW_TARGET="$NETPULSE_GW_TARGET" \
+		NETPULSE_SERVER_FP="$NETPULSE_SERVER_FP"
+	# Booleanos explícitos: "procd_set_param stdout stderr" no es válido y en
+	# OpenWrt 21.02 deja los logs sin redirigir a syslog (#1701).
+	procd_set_param stdout 1
+	procd_set_param stderr 1
+	procd_set_param respawn 3600 3600 0  # respawn con backoff de 1h (#851: ya sin watchdog cron)
+	procd_close_instance
+}
+
+service_triggers() {
+	procd_add_reload_trigger netpulse-agent
+}
+
+# stop_service lo gestiona procd automáticamente (SIGTERM al comando)

+ 188 - 0
server-go/internal/openwrtpkg/ipk.go

@@ -0,0 +1,188 @@
+package openwrtpkg
+
+import (
+	"archive/tar"
+	"bytes"
+	"compress/gzip"
+	"embed"
+	"fmt"
+	"time"
+)
+
+// files: copia de deploy/openwrt/netpulse-agent/files. go:embed no puede salir
+// del modulo, asi que el paquete lleva su propia copia y un test comprueba que
+// sigue identica a la del repo (#1476).
+//
+//go:embed files/*
+var files embed.FS
+
+// PkgName es el nombre del paquete OpenWrt y de la seccion UCI que crea.
+const PkgName = "netpulse-agent"
+
+// pkgEpoch fija los mtime del tar para que dos generaciones del mismo binario
+// produzcan exactamente los mismos bytes.
+var pkgEpoch = time.Unix(1700000000, 0).UTC()
+
+// OpenWrtArch traduce el GOARCH del agente al nombre de arquitectura que usan
+// los repos de OpenWrt. Devuelve "" para una arquitectura no soportada.
+func OpenWrtArch(goarch string) string {
+	switch goarch {
+	case "amd64":
+		return "x86_64"
+	case "arm64":
+		return "aarch64_cortex-a53"
+	case "arm":
+		return "arm_cortex-a7_neon-vfpv4"
+	case "mipsle":
+		return "mipsel_24kc"
+	case "mips":
+		return "mips_24kc"
+	}
+	return ""
+}
+
+// BuildIPK construye el paquete .ipk del agente para una arquitectura, a
+// partir del binario ya compilado.
+//
+// Desde OpenWrt 24.10 el .ipk NO es un archivo ar: es un tar.gz exterior que
+// contiene ./debian-binary, ./control.tar.gz y ./data.tar.gz, comprobado
+// contra un paquete real de downloads.openwrt.org. Los tres miembros llevan
+// prefijo "./" y el control declara /etc/config/netpulse-agent como conffile,
+// que es lo que hace que la config sobreviva a un sysupgrade.
+func BuildIPK(goarch, version string, binary []byte) ([]byte, error) {
+	arch := OpenWrtArch(goarch)
+	if arch == "" {
+		return nil, fmt.Errorf("openwrt pkg: arquitectura no soportada %q", goarch)
+	}
+	if len(binary) == 0 {
+		return nil, fmt.Errorf("openwrt pkg: binario vacio")
+	}
+	if version == "" {
+		version = "0.0.0"
+	}
+	initScript, err := files.ReadFile("files/netpulse-agent.init")
+	if err != nil {
+		return nil, err
+	}
+	configFile, err := files.ReadFile("files/netpulse-agent.config")
+	if err != nil {
+		return nil, err
+	}
+	defaults, err := files.ReadFile("files/netpulse-agent.defaults")
+	if err != nil {
+		return nil, err
+	}
+
+	control, err := tarGz([]tarEntry{
+		{name: "./control", mode: 0o644, body: controlFile(version, arch)},
+		{name: "./conffiles", mode: 0o644, body: []byte("/etc/config/netpulse-agent\n")},
+		{name: "./postinst", mode: 0o755, body: postinst},
+		{name: "./prerm", mode: 0o755, body: prerm},
+	})
+	if err != nil {
+		return nil, err
+	}
+	data, err := tarGz([]tarEntry{
+		{name: "./usr/sbin/netpulse-agent", mode: 0o755, body: binary},
+		{name: "./etc/init.d/netpulse-agent", mode: 0o755, body: initScript},
+		{name: "./etc/config/netpulse-agent", mode: 0o644, body: configFile},
+		{name: "./etc/uci-defaults/90-netpulse-agent", mode: 0o755, body: defaults},
+	})
+	if err != nil {
+		return nil, err
+	}
+	return tarGzNoDir([]tarEntry{
+		{name: "./debian-binary", mode: 0o644, body: []byte("2.0\n")},
+		{name: "./data.tar.gz", mode: 0o644, body: data},
+		{name: "./control.tar.gz", mode: 0o644, body: control},
+	})
+}
+
+// controlFile es el CONTROL/control del paquete. Depends replica el Makefile
+// del repo: el agente sondea las radios con iw.
+func controlFile(version, arch string) []byte {
+	return []byte(fmt.Sprintf(`Package: %s
+Version: %s
+Depends: libc, iw
+License: AGPL-3.0-only
+Section: utils
+Architecture: %s
+Maintainer: Nacho <netpulse@cloudless.club>
+Description: Native OpenWrt agent for NetPulse network monitor.
+`, PkgName, version, arch))
+}
+
+// postinst arranca el servicio si ya estaba habilitado y aplica los
+// uci-defaults, que migran una instalacion manual previa al formato UCI.
+var postinst = []byte(`#!/bin/sh
+[ -n "${IPKG_INSTROOT}" ] && exit 0
+if [ -x /etc/init.d/netpulse-agent ]; then
+	/etc/init.d/netpulse-agent enabled && /etc/init.d/netpulse-agent restart
+fi
+[ -x /etc/uci-defaults/90-netpulse-agent ] && sh /etc/uci-defaults/90-netpulse-agent
+exit 0
+`)
+
+// prerm para el servicio y retira el watchdog cron de versiones anteriores.
+var prerm = []byte(`#!/bin/sh
+[ -n "${IPKG_INSTROOT}" ] && exit 0
+if [ -x /etc/init.d/netpulse-agent ]; then
+	/etc/init.d/netpulse-agent stop 2>/dev/null
+	/etc/init.d/netpulse-agent disable 2>/dev/null
+fi
+crontab -l 2>/dev/null | grep -v netpulse-watchdog | crontab - 2>/dev/null
+exit 0
+`)
+
+type tarEntry struct {
+	name string
+	mode int64
+	body []byte
+	dir  bool
+}
+
+// tarGz empaqueta entradas con la cabecera de directorio "./" delante, como
+// hacen ipkg-build y apk en los paquetes reales de OpenWrt.
+func tarGz(entries []tarEntry) ([]byte, error) {
+	return tarGzNoDir(append([]tarEntry{{name: "./", mode: 0o755, dir: true}}, entries...))
+}
+
+// tarGzNoDir empaqueta sin cabecera de directorio (es el tar exterior del ipk,
+// que solo lleva los tres miembros).
+func tarGzNoDir(entries []tarEntry) ([]byte, error) {
+	var buf bytes.Buffer
+	gz := gzip.NewWriter(&buf)
+	gz.Header.ModTime = pkgEpoch
+	tw := tar.NewWriter(gz)
+	for _, e := range entries {
+		hdr := &tar.Header{
+			Name:    e.name,
+			Mode:    e.mode,
+			ModTime: pkgEpoch,
+			Uid:     0,
+			Gid:     0,
+			Format:  tar.FormatGNU,
+		}
+		if e.dir {
+			hdr.Typeflag = tar.TypeDir
+		} else {
+			hdr.Typeflag = tar.TypeReg
+			hdr.Size = int64(len(e.body))
+		}
+		if err := tw.WriteHeader(hdr); err != nil {
+			return nil, err
+		}
+		if !e.dir && len(e.body) > 0 {
+			if _, err := tw.Write(e.body); err != nil {
+				return nil, err
+			}
+		}
+	}
+	if err := tw.Close(); err != nil {
+		return nil, err
+	}
+	if err := gz.Close(); err != nil {
+		return nil, err
+	}
+	return buf.Bytes(), nil
+}

+ 226 - 0
server-go/internal/openwrtpkg/ipk_test.go

@@ -0,0 +1,226 @@
+package openwrtpkg
+
+import (
+	"archive/tar"
+	"bytes"
+	"compress/gzip"
+	"io"
+	"os"
+	"path/filepath"
+	"testing"
+)
+
+// #1476: el paquete lleva su propia copia de los ficheros de deploy porque
+// go:embed no puede salir del modulo. Si alguien edita el original y olvida la
+// copia, el .ipk generado serviria un init o un config viejos.
+func TestEmbeddedFilesMatchDeploy(t *testing.T) {
+	pairs := map[string]string{
+		"files/netpulse-agent.init":     "netpulse-agent.init",
+		"files/netpulse-agent.config":   "netpulse-agent.config",
+		"files/netpulse-agent.defaults": "netpulse-agent.defaults",
+	}
+	for embedded, deployName := range pairs {
+		want, err := os.ReadFile(filepath.Join(repoRel, "deploy/openwrt/netpulse-agent/files", deployName))
+		if err != nil {
+			t.Fatalf("leer %s: %v", deployName, err)
+		}
+		got, err := files.ReadFile(embedded)
+		if err != nil {
+			t.Fatalf("leer %s del embed: %v", embedded, err)
+		}
+		if !bytes.Equal(got, want) {
+			t.Fatalf("%s difiere de deploy/openwrt/netpulse-agent/files/%s; copia el fichero al paquete", embedded, deployName)
+		}
+	}
+}
+
+func TestOpenWrtArch(t *testing.T) {
+	cases := map[string]string{
+		"amd64":  "x86_64",
+		"arm64":  "aarch64_cortex-a53",
+		"arm":    "arm_cortex-a7_neon-vfpv4",
+		"mipsle": "mipsel_24kc",
+		"mips":   "mips_24kc",
+		"riscv":  "",
+	}
+	for in, want := range cases {
+		if got := OpenWrtArch(in); got != want {
+			t.Errorf("OpenWrtArch(%q) = %q, want %q", in, got, want)
+		}
+	}
+}
+
+// #1476: el .ipk de OpenWrt 24.10 es un tar.gz exterior con tres miembros.
+// Esta prueba lo desmonta igual que `tar tzf` sobre un paquete real.
+func TestBuildIPKLayout(t *testing.T) {
+	ipk, err := BuildIPK("arm64", "3.0.31", bytes.Repeat([]byte("binary"), 100))
+	if err != nil {
+		t.Fatalf("BuildIPK: %v", err)
+	}
+	outer := ungzip(t, ipk)
+	members := listTar(t, outer)
+	wantOrder := []string{"./debian-binary", "./data.tar.gz", "./control.tar.gz"}
+	if len(members) != len(wantOrder) {
+		t.Fatalf("miembros = %v, want %v", members, wantOrder)
+	}
+	for i, want := range wantOrder {
+		if members[i] != want {
+			t.Fatalf("miembro %d = %q, want %q", i, members[i], want)
+		}
+	}
+	if got := string(tarFile(t, outer, "./debian-binary")); got != "2.0\n" {
+		t.Errorf("debian-binary = %q", got)
+	}
+
+	control := ungzip(t, tarFile(t, outer, "./control.tar.gz"))
+	controlFiles := listTar(t, control)
+	for _, want := range []string{"./control", "./conffiles", "./postinst", "./prerm"} {
+		if !contains(controlFiles, want) {
+			t.Errorf("control.tar.gz no lleva %s: %v", want, controlFiles)
+		}
+	}
+	controlBody := string(tarFile(t, control, "./control"))
+	for _, want := range []string{
+		"Package: netpulse-agent",
+		"Version: 3.0.31",
+		"Architecture: aarch64_cortex-a53",
+		"Depends: libc, iw",
+	} {
+		if !bytes.Contains([]byte(controlBody), []byte(want)) {
+			t.Errorf("control no contiene %q:\n%s", want, controlBody)
+		}
+	}
+	if got := string(tarFile(t, control, "./conffiles")); got != "/etc/config/netpulse-agent\n" {
+		t.Errorf("conffiles = %q, want la config UCI", got)
+	}
+
+	data := ungzip(t, tarFile(t, outer, "./data.tar.gz"))
+	dataFiles := listTar(t, data)
+	for _, want := range []string{
+		"./usr/sbin/netpulse-agent",
+		"./etc/init.d/netpulse-agent",
+		"./etc/config/netpulse-agent",
+		"./etc/uci-defaults/90-netpulse-agent",
+	} {
+		if !contains(dataFiles, want) {
+			t.Errorf("data.tar.gz no lleva %s: %v", want, dataFiles)
+		}
+	}
+	// opkg necesita el binario y el init ejecutables; la config, 0644.
+	modes := tarModes(t, data)
+	for name, want := range map[string]int64{
+		"./usr/sbin/netpulse-agent":            0o755,
+		"./etc/init.d/netpulse-agent":          0o755,
+		"./etc/uci-defaults/90-netpulse-agent": 0o755,
+		"./etc/config/netpulse-agent":          0o644,
+	} {
+		if got := modes[name]; got != want {
+			t.Errorf("modo de %s = %o, want %o", name, got, want)
+		}
+	}
+}
+
+func TestBuildIPKDeterministic(t *testing.T) {
+	bin := bytes.Repeat([]byte("x"), 64)
+	a, err := BuildIPK("arm64", "1.2.3", bin)
+	if err != nil {
+		t.Fatalf("BuildIPK: %v", err)
+	}
+	b, err := BuildIPK("arm64", "1.2.3", bin)
+	if err != nil {
+		t.Fatalf("BuildIPK: %v", err)
+	}
+	if !bytes.Equal(a, b) {
+		t.Fatal("dos generaciones del mismo paquete deben ser identicas")
+	}
+}
+
+func TestBuildIPKRejectsUnsupported(t *testing.T) {
+	if _, err := BuildIPK("riscv", "1.0.0", []byte("x")); err == nil {
+		t.Fatal("esperaba error para una arquitectura no soportada")
+	}
+	if _, err := BuildIPK("arm64", "1.0.0", nil); err == nil {
+		t.Fatal("esperaba error sin binario")
+	}
+}
+
+func ungzip(t *testing.T, raw []byte) []byte {
+	t.Helper()
+	zr, err := gzip.NewReader(bytes.NewReader(raw))
+	if err != nil {
+		t.Fatalf("gzip: %v", err)
+	}
+	defer zr.Close()
+	out, err := io.ReadAll(zr)
+	if err != nil {
+		t.Fatalf("gzip read: %v", err)
+	}
+	return out
+}
+
+func listTar(t *testing.T, raw []byte) []string {
+	t.Helper()
+	tr := tar.NewReader(bytes.NewReader(raw))
+	var names []string
+	for {
+		hdr, err := tr.Next()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			t.Fatalf("tar: %v", err)
+		}
+		names = append(names, hdr.Name)
+	}
+	return names
+}
+
+func tarFile(t *testing.T, raw []byte, name string) []byte {
+	t.Helper()
+	tr := tar.NewReader(bytes.NewReader(raw))
+	for {
+		hdr, err := tr.Next()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			t.Fatalf("tar: %v", err)
+		}
+		if hdr.Name != name {
+			continue
+		}
+		body, err := io.ReadAll(tr)
+		if err != nil {
+			t.Fatalf("tar read %s: %v", name, err)
+		}
+		return body
+	}
+	t.Fatalf("no encontrado %s", name)
+	return nil
+}
+
+func tarModes(t *testing.T, raw []byte) map[string]int64 {
+	t.Helper()
+	tr := tar.NewReader(bytes.NewReader(raw))
+	out := map[string]int64{}
+	for {
+		hdr, err := tr.Next()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			t.Fatalf("tar: %v", err)
+		}
+		out[hdr.Name] = hdr.Mode
+	}
+	return out
+}
+
+func contains(list []string, want string) bool {
+	for _, s := range list {
+		if s == want {
+			return true
+		}
+	}
+	return false
+}

+ 73 - 0
server-go/internal/reinstall/apk_pkg_test.go

@@ -0,0 +1,73 @@
+package reinstall_test
+
+import (
+	"os/exec"
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/reinstall"
+)
+
+// #1476: OpenWrt 25.12 trae apk y no opkg, asi que el paquete del servidor
+// tiene que instalarse tambien por ahi. El .apk lo firma el CI y el servidor
+// solo lo sirve con format=apk; si falta, el script cae al camino de ficheros
+// sueltos como antes.
+func TestScriptInstallsPackageWithAPK(t *testing.T) {
+	s := reinstall.ScriptWithTargets(
+		"test-router",
+		strings.Repeat("a1", 32),
+		"https://192.168.1.226:3000",
+		"sha256//AAAA",
+		map[string]string{"arm64": "cafebabe"},
+		reinstall.WanTargets{},
+	)
+
+	for _, want := range []string{
+		`elif command -v apk >/dev/null 2>&1; then`,
+		`pkg_fetch "$PKG_URL&format=apk" /tmp/netpulse-agent.apk`,
+		`apk add --allow-untrusted /tmp/netpulse-agent.apk`,
+		`rm -f /tmp/netpulse-agent.apk`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("el script no contiene %q", want)
+		}
+	}
+
+	// El bloque opkg sigue existiendo y va ANTES que el de apk: en un router
+	// con ambos gestores manda el .ipk, que el servidor compone al vuelo y no
+	// depende de que el operador haya copiado el asset.
+	opkg := strings.Index(s, `command -v opkg`)
+	apk := strings.Index(s, `elif command -v apk`)
+	if opkg < 0 || apk < 0 {
+		t.Fatalf("faltan los bloques de gestor de paquetes (opkg=%d apk=%d)", opkg, apk)
+	}
+	if opkg > apk {
+		t.Error("el bloque opkg debe ir antes que el de apk")
+	}
+
+	if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
+		t.Fatalf("script invalido para sh -n: %v\n%s", err, out)
+	}
+}
+
+// La funcion pkg_fetch centraliza la descarga autenticada con curl o wget, de
+// modo que ambos formatos comparten el mismo manejo de TLS y cabeceras.
+func TestScriptPackageFetchIsShared(t *testing.T) {
+	s := reinstall.ScriptWithTargets(
+		"test-router",
+		strings.Repeat("a1", 32),
+		"https://192.168.1.226:3000",
+		"",
+		map[string]string{"arm64": "cafebabe"},
+		reinstall.WanTargets{},
+	)
+	if !strings.Contains(s, `PKG_URL="$SERVER/api/agents/$SLUG/package?arch=$GOARCH"`) {
+		t.Error("falta la base URL del paquete")
+	}
+	if strings.Count(s, `pkg_fetch "$PKG_URL&format=`) != 2 {
+		t.Error("los dos formatos deben descargarse por pkg_fetch")
+	}
+	if !strings.Contains(s, `-H "Authorization: Bearer $TOKEN"`) {
+		t.Error("la descarga debe autenticarse con el token del agente")
+	}
+}

+ 81 - 2
server-go/internal/reinstall/reinstall.go

@@ -158,6 +158,45 @@ chmod 600 "$ENV_FILE"
 `
 }
 
+// uciConfigBlock (#1476) sincroniza la configuración nativa del paquete con
+// el env que acaba de escribir envRewriteBlock. /etc/config/netpulse-agent es
+// un conffile, así que sobrevive a sysupgrade, y el init procd del paquete lee
+// UCI (#1772): sin este bloque un reinstall dejaba el env al día y la config
+// nativa con el token viejo. Solo actúa si el fichero existe, es decir, si el
+// router tiene el paquete instalado; una instalación por ficheros sueltos
+// sigue funcionando con el env. No toca `interval`: no lo gestiona el
+// reinstall y pisarlo borraría un ajuste del usuario. Los campos opcionales
+// vacíos se borran para no dejar un target falso.
+func uciConfigBlock(targets WanTargets) string {
+	return `UCI_CFG=/etc/config/netpulse-agent
+if [ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1; then
+	uci -q set netpulse-agent.main.server="$SERVER" || true
+	uci -q set netpulse-agent.main.slug="$SLUG" || true
+	uci -q set netpulse-agent.main.token="$TOKEN" || true
+	if [ -n "$SERVER_FP" ]; then
+		uci -q set netpulse-agent.main.server_fp="$SERVER_FP" || true
+	else
+		uci -q delete netpulse-agent.main.server_fp || true
+	fi
+	uci -q set netpulse-agent.main.scan_interval="$SCAN_VALUE" || true
+` + func() string {
+		out := ""
+		if targets.WanTarget != "" {
+			out += "\tuci -q set netpulse-agent.main.wan_target=\"" + targets.WanTarget + "\" || true\n"
+		} else {
+			out += "\tuci -q delete netpulse-agent.main.wan_target || true\n"
+		}
+		if targets.GwTarget != "" {
+			out += "\tuci -q set netpulse-agent.main.gw_target=\"" + targets.GwTarget + "\" || true\n"
+		} else {
+			out += "\tuci -q delete netpulse-agent.main.gw_target || true\n"
+		}
+		return out
+	}() + `	uci -q commit netpulse-agent || true
+fi
+`
+}
+
 // preserveOnSysupgrade (#1476) añade los ficheros del agente a
 // /etc/sysupgrade.conf. OpenWrt solo conserva en una actualización de imagen los
 // conffiles declarados por los paquetes instalados, lo listado en ese fichero y
@@ -174,6 +213,12 @@ ensure_sysupgrade /usr/sbin/netpulse-agent
 ensure_sysupgrade /etc/netpulse-agent.env
 ensure_sysupgrade /etc/init.d/netpulse-agent
 for f in /etc/rc.d/*netpulse-agent*; do [ -e "$f" ] && ensure_sysupgrade "$f"; done
+# Conffile y defaults del paquete: en una instalación por paquete OpenWrt los
+# conserva por sí solo, pero declararlos aquí cubre el caso de un router que
+# recibió el paquete y luego un reinstall por SSH.
+for f in /etc/config/netpulse-agent /etc/uci-defaults/90-netpulse-agent; do
+	[ -e "$f" ] && ensure_sysupgrade "$f"
+done
 true
 `
 
@@ -202,7 +247,7 @@ SERVER="` + serverURL + `"
 SLUG="` + slug + `"
 TOKEN="` + token + `"
 SERVER_FP="` + serverFP + `"
-` + caSetupBlock(tr) + envRewriteBlock(targets) + preserveOnSysupgrade + `
+` + caSetupBlock(tr) + envRewriteBlock(targets) + uciConfigBlock(targets) + preserveOnSysupgrade + `
 # Releer el env: el agente lo lee del fichero en cada arranque (#1287), así
 # que basta un restart del init procd (respawn inmediato).
 if [ -f "$INIT" ]; then
@@ -254,9 +299,40 @@ case "$ARCH" in
 	*) echo "arch no soportado: $ARCH"; exit 20 ;;
 esac
 
+# #1476: si el router habla opkg o apk, instala el paquete que sirve el propio
+# servidor. Deja binario, init y /etc/config/netpulse-agent, que es conffile y
+# sobrevive a un sysupgrade. El .ipk lo compone el servidor al vuelo desde el
+# binario embebido; el .apk lo firma el CI y solo esta si el operador lo dejo
+# junto al binario. Cualquier fallo (sin gestor, descarga rota, paquete
+# rechazado) cae al camino de ficheros sueltos de abajo: el paquete es una
+# mejora, no un requisito.
+PKG_OK=0
+PKG_URL="$SERVER/api/agents/$SLUG/package?arch=$GOARCH"
+pkg_fetch() {
+	if command -v curl >/dev/null 2>&1; then
+		curl -fsSL $CURL_TLS --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$1" -o "$2" 2>/dev/null
+	else
+		wget -q $WGET_TLS -T 60 -O "$2" --header="Authorization: Bearer $TOKEN" "$1" 2>/dev/null
+	fi
+}
+if command -v opkg >/dev/null 2>&1; then
+	pkg_fetch "$PKG_URL&format=ipk" /tmp/netpulse-agent.ipk || rm -f /tmp/netpulse-agent.ipk
+	if [ -s /tmp/netpulse-agent.ipk ] && opkg install --force-reinstall /tmp/netpulse-agent.ipk >/dev/null 2>&1; then
+		PKG_OK=1
+	fi
+	rm -f /tmp/netpulse-agent.ipk
+elif command -v apk >/dev/null 2>&1; then
+	pkg_fetch "$PKG_URL&format=apk" /tmp/netpulse-agent.apk || rm -f /tmp/netpulse-agent.apk
+	if [ -s /tmp/netpulse-agent.apk ] && apk add --allow-untrusted /tmp/netpulse-agent.apk >/dev/null 2>&1; then
+		PKG_OK=1
+	fi
+	rm -f /tmp/netpulse-agent.apk
+fi
+
 # Parar servicio previo si existe (el proceso vivo mantiene el binario abierto)
 [ -f "$INIT" ] && "$INIT" stop >/dev/null 2>&1 || true
 
+if [ "$PKG_OK" != "1" ]; then
 # Descargar el binario del propio server (auth por token)
 if command -v curl >/dev/null 2>&1; then
 	curl -fsSL $CURL_TLS --connect-timeout 10 -m 600 -H "Authorization: Bearer $TOKEN" "$SERVER/api/agents/$SLUG/binary?arch=$GOARCH" -o /tmp/netpulse-agent.new
@@ -271,11 +347,13 @@ if [ -n "$SHA256" ]; then
 fi
 chmod 0755 /tmp/netpulse-agent.new
 mv -f /tmp/netpulse-agent.new "$BIN"
+fi
 
 # Config (chmod 600). El rewrite toca SOLO las vars gestionadas (SERVER,
 # SLUG, TOKEN, SERVER_FP, WAN_TARGET, GW_TARGET): las NETPULSE_* del usuario
 # (p. ej. NETPULSE_SCAN_INTERVAL=0) se conservan tal cual (#851).
-` + envRewriteBlock(targets) + `
+` + envRewriteBlock(targets) + uciConfigBlock(targets) + `
+if [ "$PKG_OK" != "1" ]; then
 # Init procd con self-heal (#457): un sysupgrade no conserva los ficheros
 # sueltos, así que el binario, el init y el env se añaden a
 # /etc/sysupgrade.conf (#1476); si aun así falta el binario al arrancar se
@@ -375,6 +453,7 @@ selfheal_binary() {
 }
 INITEOF
 chmod 0755 "$INIT"
+fi
 
 # #851: el watchdog cron YA NO se instala (un reinicio a ciegas de un crash
 # loop no arregla nada y ensucia el log; la detección es el dead-man del

+ 126 - 0
server-go/internal/reinstall/script_test.go

@@ -529,3 +529,129 @@ func TestInstallScriptPreflightAndAtomicBinary(t *testing.T) {
 		t.Error("install-agent.sh sigue copiando el binario directo al destino final")
 	}
 }
+
+// #1476 (paso 2): cuando el router ya lleva el paquete, la config vive en
+// /etc/config/netpulse-agent (conffile que sobrevive a sysupgrade) y el init
+// la lee por UCI. Un reinstall que solo reescribiera el env dejaba la config
+// nativa con el token viejo, asi que el script sincroniza las dos.
+func TestScriptSyncsUCIConfig(t *testing.T) {
+	slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA"
+	digests := map[string]string{"arm64": "cafebabe"}
+	s := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{
+		WanTarget: "1.1.1.1",
+		GwTarget:  "192.168.1.1",
+	})
+	for _, want := range []string{
+		`UCI_CFG=/etc/config/netpulse-agent`,
+		`[ -f "$UCI_CFG" ] && command -v uci >/dev/null 2>&1`,
+		`uci -q set netpulse-agent.main.server="$SERVER"`,
+		`uci -q set netpulse-agent.main.slug="$SLUG"`,
+		`uci -q set netpulse-agent.main.token="$TOKEN"`,
+		`uci -q set netpulse-agent.main.server_fp="$SERVER_FP"`,
+		`uci -q set netpulse-agent.main.scan_interval="$SCAN_VALUE"`,
+		`uci -q set netpulse-agent.main.wan_target="1.1.1.1"`,
+		`uci -q set netpulse-agent.main.gw_target="192.168.1.1"`,
+		`uci -q commit netpulse-agent`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("falta en el script: %q", want)
+		}
+	}
+	// Los targets se inyectan entre comillas desde Go: un escapado roto
+	// dejaria el script invalido justo antes de tocar la config del router.
+	if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
+		t.Fatalf("not valid sh: %v\n%s", err, out)
+	}
+}
+
+// Sin objetivos resueltos, el bloque UCI borra las claves en vez de dejarlas
+// con el valor de un router anterior.
+func TestScriptUCIClearsEmptyTargets(t *testing.T) {
+	slug, token, url, fp := "test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", ""
+	digests := map[string]string{"arm64": "cafebabe"}
+	s := reinstall.ScriptWithTargets(slug, token, url, fp, digests, reinstall.WanTargets{})
+	for _, want := range []string{
+		`uci -q delete netpulse-agent.main.wan_target`,
+		`uci -q delete netpulse-agent.main.gw_target`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("falta en el script: %q", want)
+		}
+	}
+	if strings.Contains(s, `uci -q set netpulse-agent.main.wan_target=""`) {
+		t.Error("un target vacío no debe escribirse como cadena vacía")
+	}
+	if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
+		t.Fatalf("not valid sh: %v\n%s", err, out)
+	}
+}
+
+// La variante ligera (#1294) migra HTTPS sin reinstalar binario, pero también
+// debe dejar la config UCI al día.
+func TestEnvScriptSyncsUCIConfig(t *testing.T) {
+	s := reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", reinstall.WanTargets{})
+	if !strings.Contains(s, `uci -q set netpulse-agent.main.token="$TOKEN"`) {
+		t.Error("EnvScript debe sincronizar el token en UCI")
+	}
+	if !strings.Contains(s, `uci -q delete netpulse-agent.main.server_fp`) {
+		t.Error("sin FP debe borrar la clave en UCI")
+	}
+	if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
+		t.Fatalf("not valid sh: %v\n%s", err, out)
+	}
+}
+
+// En una instalación por paquete la config UCI ya se conserva, pero un router
+// que recibió el paquete y luego un reinstall por SSH tiene que preservarla
+// igual que el resto de ficheros del agente.
+func TestScriptsPreserveUCIConfig(t *testing.T) {
+	for name, s := range map[string]string{
+		"full": reinstall.Script("test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", "", map[string]string{"arm64": "cafebabe"}),
+		"env":  reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "http://192.168.1.226:3000", "", reinstall.WanTargets{}),
+	} {
+		for _, want := range []string{
+			`for f in /etc/config/netpulse-agent /etc/uci-defaults/90-netpulse-agent; do`,
+			`ensure_sysupgrade "$f"`,
+		} {
+			if !strings.Contains(s, want) {
+				t.Errorf("%s: falta en el script: %q", name, want)
+			}
+		}
+	}
+}
+
+// #1476: el reinstall instala el paquete .ipk cuando el router tiene opkg, y
+// conserva el camino de ficheros sueltos como respaldo si el paquete falla.
+func TestScriptInstallsPackageWithFallback(t *testing.T) {
+	s := reinstall.ScriptWithTargets("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", map[string]string{"arm64": "cafebabe"}, reinstall.WanTargets{})
+	for _, want := range []string{
+		`if command -v opkg >/dev/null 2>&1; then`,
+		`"$SERVER/api/agents/$SLUG/package?arch=$GOARCH"`,
+		`opkg install --force-reinstall /tmp/netpulse-agent.ipk`,
+		`PKG_OK=1`,
+		`if [ "$PKG_OK" != "1" ]; then`,
+		`"$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"`,
+	} {
+		if !strings.Contains(s, want) {
+			t.Errorf("falta en el script: %q", want)
+		}
+	}
+	// El bloque del paquete va antes de la descarga del binario suelto: si
+	// instalase despues, pisaria el init del paquete con el de ficheros sueltos.
+	pkgIdx := strings.Index(s, `if command -v opkg >/dev/null 2>&1; then`)
+	binIdx := strings.Index(s, `"$SERVER/api/agents/$SLUG/binary?arch=$GOARCH"`)
+	if pkgIdx < 0 || binIdx < 0 || pkgIdx > binIdx {
+		t.Fatalf("orden incorrecto: paquete en %d, binario en %d", pkgIdx, binIdx)
+	}
+	if out, err := exec.Command("sh", "-n", "-c", s).CombinedOutput(); err != nil {
+		t.Fatalf("sh -n: %v\n%s", err, out)
+	}
+}
+
+// El script ligero de entorno no instala paquetes: solo sincroniza config.
+func TestEnvScriptDoesNotInstallPackage(t *testing.T) {
+	s := reinstall.EnvScript("test-router", strings.Repeat("a1", 32), "https://192.168.1.226:3000", "sha256//AAAA", reinstall.WanTargets{})
+	if strings.Contains(s, "opkg install") {
+		t.Fatal("el script ligero no debe instalar el paquete")
+	}
+}

+ 135 - 0
server-go/internal/snmp/entity.go

@@ -0,0 +1,135 @@
+// entity.go — ENTITY-MIB (RFC 6933, before RFC 4133) best-effort reader.
+//
+// Some SNMP switches leave sysDescr as the only identity and publish no
+// firmware anywhere else, yet they carry the firmware and the short model in
+// entPhysicalTable. The chassis(3) row is the unit itself: a stackable switch
+// can put a stack(11) row first, so choosing by row index is wrong.
+//
+// Firmware uses entPhysicalSoftwareRev first and entPhysicalFirmwareRev as
+// the fallback: both columns are standard but vendors populate different
+// ones. A missing column stays empty, the same null contract as #441/#1036.
+package snmp
+
+import (
+	"sort"
+	"strconv"
+	"strings"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+const (
+	OidEntPhysicalTable = ".1.3.6.1.2.1.47.1.1.1.1"
+
+	oidEntPhysicalClass       = OidEntPhysicalTable + ".5"
+	oidEntPhysicalHardwareRev = OidEntPhysicalTable + ".8"
+	oidEntPhysicalFirmwareRev = OidEntPhysicalTable + ".9"
+	oidEntPhysicalSoftwareRev = OidEntPhysicalTable + ".10"
+	oidEntPhysicalSerialNum   = OidEntPhysicalTable + ".11"
+	oidEntPhysicalModelName   = OidEntPhysicalTable + ".13"
+)
+
+const entPhysicalClassChassis = 3
+
+// EntityInfo is the identity the ENTITY-MIB publishes for the unit.
+type EntityInfo struct {
+	Firmware   string
+	ModelShort string
+}
+
+type entityRow struct {
+	index       int
+	class       int
+	firmwareRev string
+	softwareRev string
+	modelName   string
+	serialNum   string
+}
+
+// PollEntityInfo walks entPhysicalTable once and returns the chassis row.
+// A device without the table yields an empty EntityInfo and no error, like
+// the other optional probes.
+func PollEntityInfo(s *gosnmp.GoSNMP) (EntityInfo, error) {
+	pdus, err := walkSafe(s, OidEntPhysicalTable)
+	if err != nil {
+		return EntityInfo{}, nil
+	}
+	return ParseEntityTable(pdus), nil
+}
+
+// ParseEntityTable selects the chassis row and falls back to the first row
+// that publishes anything, in index order.
+func ParseEntityTable(pdus []gosnmp.SnmpPDU) EntityInfo {
+	rows := map[int]*entityRow{}
+	for _, v := range pdus {
+		col, idx := entityColumn(v.Name)
+		if col == "" || idx == 0 {
+			continue
+		}
+		row := rows[idx]
+		if row == nil {
+			row = &entityRow{index: idx}
+			rows[idx] = row
+		}
+		switch col {
+		case oidEntPhysicalClass:
+			row.class = int(uint64Val(v))
+		case oidEntPhysicalFirmwareRev:
+			row.firmwareRev = strings.TrimSpace(stringVal(v))
+		case oidEntPhysicalSoftwareRev:
+			row.softwareRev = strings.TrimSpace(stringVal(v))
+		case oidEntPhysicalModelName:
+			row.modelName = strings.TrimSpace(stringVal(v))
+		case oidEntPhysicalSerialNum:
+			row.serialNum = strings.TrimSpace(stringVal(v))
+		}
+	}
+	if len(rows) == 0 {
+		return EntityInfo{}
+	}
+	ordered := make([]*entityRow, 0, len(rows))
+	for _, row := range rows {
+		ordered = append(ordered, row)
+	}
+	sort.Slice(ordered, func(i, j int) bool { return ordered[i].index < ordered[j].index })
+
+	chosen := ordered[0]
+	for _, row := range ordered {
+		if row.class == entPhysicalClassChassis && row.hasIdentity() {
+			chosen = row
+			break
+		}
+		if !chosen.hasIdentity() && row.hasIdentity() {
+			chosen = row
+		}
+	}
+	return EntityInfo{Firmware: chosen.firmware(), ModelShort: chosen.modelName}
+}
+
+func (r *entityRow) hasIdentity() bool {
+	return r.firmware() != "" || r.modelName != "" || r.serialNum != ""
+}
+
+func (r *entityRow) firmware() string {
+	if r.softwareRev != "" {
+		return r.softwareRev
+	}
+	return r.firmwareRev
+}
+
+// entityColumn splits an entPhysicalTable OID into its column and row index.
+func entityColumn(name string) (string, int) {
+	if !strings.HasPrefix(name, OidEntPhysicalTable+".") {
+		return "", 0
+	}
+	rest := strings.TrimPrefix(name, OidEntPhysicalTable+".")
+	col, idx, ok := strings.Cut(rest, ".")
+	if !ok || strings.Contains(idx, ".") {
+		return "", 0
+	}
+	n, err := strconv.Atoi(idx)
+	if err != nil || n <= 0 {
+		return "", 0
+	}
+	return OidEntPhysicalTable + "." + col, n
+}

+ 87 - 0
server-go/internal/snmp/entity_test.go

@@ -0,0 +1,87 @@
+package snmp
+
+import (
+	"math/big"
+	"testing"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+func entPDU(col, idx string, typ gosnmp.Asn1BER, value any) gosnmp.SnmpPDU {
+	return gosnmp.SnmpPDU{Name: OidEntPhysicalTable + "." + col + "." + idx, Type: typ, Value: value}
+}
+
+func entClass(idx string, class int) gosnmp.SnmpPDU {
+	return entPDU("5", idx, gosnmp.Integer, big.NewInt(int64(class)))
+}
+
+func entString(col, idx, value string) gosnmp.SnmpPDU {
+	return entPDU(col, idx, gosnmp.OctetString, value)
+}
+
+// #1767: XS708T leaves entPhysicalFirmwareRev empty and publishes the
+// firmware in entPhysicalSoftwareRev on the chassis row.
+func TestParseEntitySoftwareRevOnChassis(t *testing.T) {
+	info := ParseEntityTable([]gosnmp.SnmpPDU{
+		entClass("1", 3),
+		entString("9", "1", ""),
+		entString("10", "1", "7.0.0.24"),
+		entString("11", "1", "4KN3837U8009A"),
+		entString("13", "1", "XS708T"),
+	})
+	if info.Firmware != "7.0.0.24" {
+		t.Errorf("firmware = %q, want 7.0.0.24", info.Firmware)
+	}
+	if info.ModelShort != "XS708T" {
+		t.Errorf("modelShort = %q, want XS708T", info.ModelShort)
+	}
+}
+
+// #1767: S3300-28X-PoE+ publishes a stack(11) row first and the chassis
+// identity on row 2. Selection is by class, not by index.
+func TestParseEntityPicksChassisAfterStackRow(t *testing.T) {
+	info := ParseEntityTable([]gosnmp.SnmpPDU{
+		entClass("1", 11),
+		entString("13", "1", "Stack row"),
+		entClass("2", 3),
+		entString("10", "2", "6.6.4.28"),
+		entString("11", "2", "3TM1447L80041"),
+		entString("13", "2", "S3300-28X-PoE+"),
+	})
+	if info.Firmware != "6.6.4.28" || info.ModelShort != "S3300-28X-PoE+" {
+		t.Errorf("got %+v, want chassis row of S3300", info)
+	}
+}
+
+// #1767: when softwareRev is empty, firmwareRev is the fallback.
+func TestParseEntityFirmwareRevFallback(t *testing.T) {
+	info := ParseEntityTable([]gosnmp.SnmpPDU{
+		entClass("1", 3),
+		entString("9", "1", "3.6.11.55242"),
+		entString("10", "1", ""),
+		entString("13", "1", "FN-SWITCH-8 PRO"),
+	})
+	if info.Firmware != "3.6.11.55242" {
+		t.Errorf("firmware = %q, want firmwareRev fallback", info.Firmware)
+	}
+}
+
+// #1767: a missing table must not invent identity.
+func TestParseEntityEmpty(t *testing.T) {
+	if info := ParseEntityTable(nil); info.Firmware != "" || info.ModelShort != "" {
+		t.Errorf("empty table gave %+v", info)
+	}
+}
+
+// An empty chassis row does not hide a later row that does publish identity.
+func TestParseEntityEmptyChassisFallsThrough(t *testing.T) {
+	info := ParseEntityTable([]gosnmp.SnmpPDU{
+		entClass("1", 3),
+		entClass("2", 11),
+		entString("10", "2", "1.2.3"),
+		entString("13", "2", "Fallback"),
+	})
+	if info.Firmware != "1.2.3" || info.ModelShort != "Fallback" {
+		t.Errorf("got %+v, want first populated row", info)
+	}
+}

+ 4 - 3
server-go/internal/snmp/oids.go

@@ -1,9 +1,10 @@
 package snmp
 
 const (
-	OidSysDescr  = ".1.3.6.1.2.1.1.1.0"
-	OidSysName   = ".1.3.6.1.2.1.1.5.0"
-	OidSysUpTime = ".1.3.6.1.2.1.1.3.0"
+	OidSysDescr    = ".1.3.6.1.2.1.1.1.0"
+	OidSysObjectID = ".1.3.6.1.2.1.1.2.0"
+	OidSysName     = ".1.3.6.1.2.1.1.5.0"
+	OidSysUpTime   = ".1.3.6.1.2.1.1.3.0"
 
 	OidIfNumber     = ".1.3.6.1.2.1.2.1.0"
 	OidIfTable      = ".1.3.6.1.2.1.2.2.1"

+ 4 - 1
server-go/internal/snmp/system.go

@@ -10,12 +10,13 @@ import (
 
 type SystemInfo struct {
 	Descr     string
+	ObjectID  string
 	Name      string
 	UpTimeSec uint64
 }
 
 func PollSystem(s *gosnmp.GoSNMP) (*SystemInfo, error) {
-	oids := []string{OidSysDescr, OidSysName, OidSysUpTime}
+	oids := []string{OidSysDescr, OidSysObjectID, OidSysName, OidSysUpTime}
 	result, err := s.Get(oids)
 	if err != nil {
 		return nil, fmt.Errorf("snmp system get: %w", err)
@@ -25,6 +26,8 @@ func PollSystem(s *gosnmp.GoSNMP) (*SystemInfo, error) {
 		switch v.Name {
 		case OidSysDescr:
 			info.Descr = stringVal(v)
+		case OidSysObjectID:
+			info.ObjectID = stringVal(v)
 		case OidSysName:
 			info.Name = stringVal(v)
 		case OidSysUpTime:

+ 112 - 0
server-go/internal/snmp/tplinkVitals.go

@@ -0,0 +1,112 @@
+// tplinkVitals.go — identity and vitals of TP-Link switches through their
+// private enterprise MIB (enterprise 11863). Their firmware answers neither
+// ENTITY-MIB nor HOST-RESOURCES-MIB, so the generic readers leave model,
+// firmware, CPU and memory empty even though the data is available.
+//
+//   - tpSysInfoHwVersion.0   1.3.6.1.4.1.11863.6.1.1.5.0  "SG3210X-M2 1.0"
+//   - tpSysInfoSwVersion.0   1.3.6.1.4.1.11863.6.1.1.6.0  "1.0.21 Build ..."
+//   - tpSysMonitorCpu5Minutes.1
+//     1.3.6.1.4.1.11863.6.4.1.1.1.1.4.1  INTEGER, percentage
+//   - tpSysMonitorMemoryUtilization.1
+//     1.3.6.1.4.1.11863.6.4.1.2.1.1.2.1  INTEGER, percentage
+//
+// The table entry is read with Get instead of a walk: the columns are known
+// and walking the monitoring subtree can be expensive on these agents. A
+// device without the MIB answers NoSuchObject and every field stays empty.
+package snmp
+
+import (
+	"math/big"
+	"strings"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+const (
+	// EnterpriseTpLink: TP-Link enterprise number in sysObjectID.
+	EnterpriseTpLink = 11863
+
+	OidTpLinkHwVersion = ".1.3.6.1.4.1.11863.6.1.1.5.0"
+	OidTpLinkSwVersion = ".1.3.6.1.4.1.11863.6.1.1.6.0"
+	OidTpLinkCpu5Min   = ".1.3.6.1.4.1.11863.6.4.1.1.1.1.4.1"
+	OidTpLinkMemUtil   = ".1.3.6.1.4.1.11863.6.4.1.2.1.1.2.1"
+)
+
+// TpLinkInfo carries the vendor fields that map onto the router contract.
+// Empty strings and false flags mean the agent did not answer that OID.
+type TpLinkInfo struct {
+	Hardware  string
+	Firmware  string
+	CPU       int
+	HasCPU    bool
+	Memory    int
+	HasMemory bool
+}
+
+// IsTpLink reports whether sysObjectID belongs to the TP-Link enterprise
+// subtree. The MIB-2 object ID is the stable vendor signal: sysDescr varies
+// between firmware families and is not reliable enough to choose a quirk.
+func IsTpLink(sysObjectID string) bool {
+	id := strings.TrimSpace(sysObjectID)
+	if id != "" && !strings.HasPrefix(id, ".") {
+		id = "." + id
+	}
+	return strings.HasPrefix(id, ".1.3.6.1.4.1.11863.")
+}
+
+// PollTpLinkInfo reads the TP-Link identity and vitals in one Get. Failures
+// are silent by design: a switch that does not publish these OIDs must keep
+// its generic or empty values, never a fabricated zero.
+func PollTpLinkInfo(s *gosnmp.GoSNMP) TpLinkInfo {
+	if s == nil {
+		return TpLinkInfo{}
+	}
+	var info TpLinkInfo
+	result, err := s.Get([]string{
+		OidTpLinkHwVersion,
+		OidTpLinkSwVersion,
+		OidTpLinkCpu5Min,
+		OidTpLinkMemUtil,
+	})
+	if err != nil {
+		return info
+	}
+	for _, v := range result.Variables {
+		switch v.Name {
+		case OidTpLinkHwVersion:
+			info.Hardware = strings.TrimSpace(stringVal(v))
+		case OidTpLinkSwVersion:
+			info.Firmware = strings.TrimSpace(stringVal(v))
+		case OidTpLinkCpu5Min:
+			info.CPU, info.HasCPU = tpLinkPercent(v)
+		case OidTpLinkMemUtil:
+			info.Memory, info.HasMemory = tpLinkPercent(v)
+		}
+	}
+	return info
+}
+
+// tpLinkPercent accepts only numeric PDUs within 0..100. Anything else is
+// unknown: a malformed value is not a measurement.
+func tpLinkPercent(v gosnmp.SnmpPDU) (int, bool) {
+	if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
+		return 0, false
+	}
+	switch v.Type {
+	case gosnmp.Gauge32, gosnmp.Integer, gosnmp.Counter32, gosnmp.Counter64:
+	default:
+		return 0, false
+	}
+	bi, ok := v.Value.(*big.Int)
+	if !ok {
+		bi = gosnmp.ToBigInt(v.Value)
+	}
+	if bi == nil || !bi.IsInt64() {
+		return 0, false
+	}
+	n := bi.Int64()
+	if n < 0 || n > 100 {
+		return 0, false
+	}
+	return int(n), true
+}

+ 48 - 0
server-go/internal/snmp/tplinkVitals_test.go

@@ -0,0 +1,48 @@
+package snmp
+
+import (
+	"testing"
+
+	"github.com/gosnmp/gosnmp"
+)
+
+func TestIsTpLink(t *testing.T) {
+	tests := []struct {
+		oid  string
+		want bool
+	}{
+		{".1.3.6.1.4.1.11863.5.214", true},
+		{"1.3.6.1.4.1.11863.5.214", true},
+		{".1.3.6.1.4.1.4526.11.1", false},
+		{".1.3.6.1.4.1.118630.1", false},
+		{"", false},
+	}
+	for _, tt := range tests {
+		if got := IsTpLink(tt.oid); got != tt.want {
+			t.Errorf("IsTpLink(%q) = %v; want %v", tt.oid, got, tt.want)
+		}
+	}
+}
+
+func TestTpLinkPercent(t *testing.T) {
+	tests := []struct {
+		name string
+		pdu  gosnmp.SnmpPDU
+		want int
+		ok   bool
+	}{
+		{"integer", gosnmp.SnmpPDU{Type: gosnmp.Integer, Value: 7}, 7, true},
+		{"gauge", gosnmp.SnmpPDU{Type: gosnmp.Gauge32, Value: uint(29)}, 29, true},
+		{"zero is a measurement", gosnmp.SnmpPDU{Type: gosnmp.Integer, Value: 0}, 0, true},
+		{"above one hundred", gosnmp.SnmpPDU{Type: gosnmp.Integer, Value: 101}, 0, false},
+		{"negative", gosnmp.SnmpPDU{Type: gosnmp.Integer, Value: -1}, 0, false},
+		{"string", gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: "7"}, 0, false},
+		{"no such object", gosnmp.SnmpPDU{Type: gosnmp.NoSuchObject}, 0, false},
+	}
+	for _, tt := range tests {
+		got, ok := tpLinkPercent(tt.pdu)
+		if got != tt.want || ok != tt.ok {
+			t.Errorf("%s: tpLinkPercent() = (%d, %v); want (%d, %v)", tt.name, got, ok, tt.want, tt.ok)
+		}
+	}
+}

+ 12 - 4
server-go/internal/updater/stable.go

@@ -128,7 +128,11 @@ func (u *Updater) applyStable(historyID int64, tag string, startedAt time.Time)
 	staging := filepath.Join(u.dataDir, "updates")
 	_ = os.RemoveAll(staging) // restos de intentos previos
 	_ = os.Remove(filepath.Join(u.dataDir, stableErrorName))
-	if err := os.MkdirAll(staging, 0o755); err != nil {
+	if err := os.MkdirAll(staging, 0o770); err != nil {
+		fail("stable_staging_failed")
+		return
+	}
+	if err := os.Chmod(staging, 0o770); err != nil {
 		fail("stable_staging_failed")
 		return
 	}
@@ -187,7 +191,7 @@ func (u *Updater) applyStable(historyID int64, tag string, startedAt time.Time)
 	marker := filepath.Join(u.dataDir, stableMarkerName)
 	tmp := marker + ".tmp"
 	content := fmt.Sprintf("target=%s\nsha256=%s\nstaged=%s\n", tag, binSHA, binNew)
-	if err := os.WriteFile(tmp, []byte(content), 0o644); err != nil {
+	if err := os.WriteFile(tmp, []byte(content), 0o640); err != nil {
 		fail("stable_marker_failed")
 		return
 	}
@@ -223,10 +227,14 @@ func downloadToFile(url, dst string) error {
 	if resp.StatusCode != http.StatusOK {
 		return fmt.Errorf("http %d para %s", resp.StatusCode, url)
 	}
-	f, err := os.Create(dst)
+	f, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o640)
 	if err != nil {
 		return err
 	}
+	if err := f.Chmod(0o640); err != nil {
+		f.Close()
+		return err
+	}
 	defer f.Close()
 	_, err = io.Copy(f, io.LimitReader(resp.Body, stableMaxBinSize))
 	return err
@@ -291,7 +299,7 @@ func extractBinary(tgz, staging string) (string, error) {
 			return "", fmt.Errorf("entrada %s demasiado grande (%d)", name, hdr.Size)
 		}
 		dst := filepath.Join(staging, "netpulse.new")
-		out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
+		out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o750)
 		if err != nil {
 			return "", err
 		}