瀏覽代碼

feat(openwrt): LuCI test connection (P5) + server on-box package (P4) (#91)

P5 — Test Connection in LuCI:
- rpcd luci.netpulse: new 'test' method that reads the server URL from
  UCI and curls /api/health from the router (validates DNS, routing,
  port and server liveness — real connectivity from the device).
- status.js: 'Test connection' button with modal + notification
  (OK / failed with HTTP code or 'unreachable').

P4 — Server on-box package (Fase 9 R1):
- deploy/openwrt/netpulse-server/: Makefile (builds frontend + embedded
  agent binaries + server binary), procd init (NETPULSE_ONBOX=1, data_dir,
  respawn), UCI config (port, data_dir, auth_user), uci-defaults (section
  bootstrap + service enable).
- Same binary as the CT deployment; ONBOX flag activates TLS + UCI +
  pairing. Closes the Fase 9 packaging gap.

Both require a router with OpenWrt SDK for full testing; code patterns
mirror the netpulse-agent package. node --check and bash -n pass.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 月之前
父節點
當前提交
4da58cd929

+ 25 - 1
deploy/openwrt/luci-app-netpulse/files/usr/libexec/rpcd/luci.netpulse

@@ -8,6 +8,8 @@
 //             heartbeat (/tmp, epoch s) y si el servicio está habilitado.
 //   logs    → últimas N líneas de `logread -e netpulse` (10..300).
 //   restart → /etc/init.d/netpulse-agent restart (el "rearme" local).
+//   test    → curl al /api/health del servidor desde este router (valida
+//             conectividad real: DNS, ruta, puerto, server vivo).
 //
 // rpcd lo invoca como ejecutable: `list` imprime la firma de métodos;
 // `call <método>` recibe los argumentos JSON por stdin e imprime el
@@ -160,9 +162,27 @@ function do_restart() {
 	return { ok: rc == 0, code: rc };
 }
 
+// do_test: valida conectividad real desde este router al servidor NetPulse.
+// Lee la URL de UCI y hace curl al /api/health (sin auth, solo reachability).
+function do_test() {
+	let server = trim(popen_all('uci -q get netpulse-agent.main.server 2>/dev/null') || '');
+	if (!server)
+		return { ok: false, error: 'no_server' };
+
+	// curl: -sf silencia progreso y errores HTTP; -m 5 timeout 5s;
+	// -o /dev/null descarta body; -w "%{http_code}" captura el código.
+	let url = server + '/api/health';
+	let cmd = sprintf('curl -sf -m 5 -o /dev/null -w "%%{http_code}" %s 2>/dev/null', url);
+	let code = trim(popen_all(cmd) || '');
+
+	if (code == '200')
+		return { ok: true, code: 200 };
+	return { ok: false, code: code || 'unreachable' };
+}
+
 // ── Dispatcher del protocolo exec de rpcd ────────────────────────────────
 if (ARGV[0] == 'list') {
-	printf('%J\n', { status: {}, logs: { lines: 50 }, restart: {} });
+	printf('%J\n', { status: {}, logs: { lines: 50 }, restart: {}, test: {} });
 	exit(0);
 }
 
@@ -189,6 +209,10 @@ if (ARGV[0] == 'call') {
 		printf('%J\n', do_restart());
 		exit(0);
 	}
+	if (ARGV[1] == 'test') {
+		printf('%J\n', do_test());
+		exit(0);
+	}
 }
 
 exit(1);

+ 27 - 1
deploy/openwrt/luci-app-netpulse/files/www/luci-static/resources/view/netpulse/status.js

@@ -31,6 +31,12 @@ var callRestart = rpc.declare({
 	expect: { }
 });
 
+var callTest = rpc.declare({
+	object: 'luci.netpulse',
+	method: 'test',
+	expect: { }
+});
+
 var LOG_LINES = 80;
 
 function fmtDuration(s) {
@@ -121,6 +127,22 @@ function handleRestart() {
 	});
 }
 
+function handleTest() {
+	ui.showModal(_('Testing'), [
+		E('p', { 'class': 'cbi-modal-text' }, _('Testing connection to the server…'))
+	]);
+	return callTest().then(function(res) {
+		ui.hideModal();
+		if (res && res.ok)
+			ui.addNotification(null, E('p', _('Connection OK (HTTP 200).')), 'info');
+		else
+			ui.addNotification(null, E('p', _('Connection failed (%s).').format(res ? (res.code || res.error || 'unknown') : 'unknown')), 'error');
+	}).catch(function(err) {
+		ui.hideModal();
+		ui.addNotification(null, E('p', _('Test failed: %s').format(err.message)), 'error');
+	});
+}
+
 function row(label, id, initial) {
 	return E('tr', { 'class': 'tr' }, [
 		E('td', { 'class': 'td left', 'width': '33%' }, label),
@@ -151,7 +173,11 @@ return view.extend({
 			E('button', {
 				'class': 'btn cbi-button cbi-button-action',
 				'click': function() { handleRestart(); }
-			}, _('Restart agent'))
+			}, _('Restart agent')),
+			E('button', {
+				'class': 'btn cbi-button cbi-button-neutral',
+				'click': function() { handleTest(); }
+			}, _('Test connection'))
 		];
 		if (server != '') {
 			buttons.push(' ');

+ 82 - 0
deploy/openwrt/netpulse-server/Makefile

@@ -0,0 +1,82 @@
+# netpulse-server — OpenWrt Makefile (Fase 9 R1)
+# Empaqueta el servidor NetPulse (binario Go estático con la webapp embebida)
+# para correr on-box en el gateway. El mismo binario que el CT, con
+# NETPULSE_ONBOX=1 activando TLS autofirmado + config UCI + pairing.
+#
+# Uso (desde el SDK o buildroot de OpenWrt):
+#   cp -r netpulse-server package/utils/
+#   make menuconfig  # seleccionar Network → netpulse
+#   make package/netpulse/compile V=s
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=netpulse
+PKG_VERSION:=2.7.2
+PKG_RELEASE:=1
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_URL:=https://github.com/gnacho/netpulse.git
+PKG_SOURCE_VERSION:=main
+PKG_MIRROR_HASH:=skip
+
+PKG_LICENSE:=AGPL-3.0-only
+PKG_MAINTAINER:=Nacho <netpulse@example.com>
+
+include $(INCLUDE_DIR)/package.mk
+
+# Requisitos: curl para /fingerprint durante pairing, ca-bundle para HTTPS
+# saliente (updater). El binario Go es estático (CGO_ENABLED=0).
+define Package/netpulse
+	SECTION:=net
+	CATEGORY:=Network
+	TITLE:=NetPulse network monitor (on-box server)
+	URL:=https://github.com/gnacho/netpulse
+	DEPENDS:=+curl +ca-bundle @(aarch64||arm||x86_64)
+endef
+
+define Package/netpulse/description
+	NetPulse server running on-box: serves the web app and ingests agent
+	data over HTTPS with self-signed TLS + SPKI pinning. Stores data in
+	SQLite (overlay or USB). Same binary as the dedicated-node deployment;
+	NETPULSE_ONBOX=1 activates UCI config, TLS and pairing.
+endef
+
+GO_ARCH_DETECT:=$(shell echo $(ARCH) | sed 's/aarch64/arm64/;s/arm_cortex-a7/armv7/;s/arm_cortex-a9/armv7/;s/arm_cortex-a53/arm64/;s/arm_cortex-a55/arm64/;s/x86_64/amd64/')
+
+# El build compila el frontend (npm) y luego el binario Go con el dist
+# embebido. Requiere node + go en el host de compilación.
+define Build/Compile
+	# Frontend
+	(cd $(PKG_BUILD_DIR)/app && npm ci --no-audit --no-fund && npm run build)
+	# Copiar dist al embed del binario
+	rm -rf $(PKG_BUILD_DIR)/server-go/internal/staticspa/dist
+	cp -r $(PKG_BUILD_DIR)/app/dist $(PKG_BUILD_DIR)/server-go/internal/staticspa/dist
+	# Agent binaries para embed (Fase 6.2: GET /api/agents/{slug}/binary)
+	for arch in amd64 arm64 arm; do \
+		(cd $(PKG_BUILD_DIR)/agent && \
+		 CGO_ENABLED=0 GOOS=linux GOARCH=$${arch/armv7/arm/} GOARM=$$(test $$arch = arm && echo 7 || true) \
+		 go build -trimpath -ldflags "-s -w -X main.Version=$(PKG_VERSION)" \
+		 -o $(PKG_BUILD_DIR)/server-go/internal/agentbin/agents/netpulse-agent-$$arch ./cmd/netpulse-agent) || true; \
+	done
+	# Server binary
+	(cd $(PKG_BUILD_DIR)/server-go && \
+	 CGO_ENABLED=0 GOOS=linux GOARCH=$(GO_ARCH_DETECT) \
+	 go build -trimpath -ldflags "-s -w" \
+	 -o $(PKG_BUILD_DIR)/netpulse ./cmd/netpulse)
+endef
+
+define Package/netpulse/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_BUILD_DIR)/netpulse $(1)/usr/sbin/netpulse
+
+	$(INSTALL_DIR) $(1)/etc/init.d
+	$(INSTALL_BIN) ./files/netpulse-server.init $(1)/etc/init.d/netpulse
+
+	$(INSTALL_DIR) $(1)/etc/config
+	$(INSTALL_CONF) ./files/netpulse-server.config $(1)/etc/config/netpulse
+
+	$(INSTALL_DIR) $(1)/etc/uci-defaults
+	$(INSTALL_BIN) ./files/netpulse-server.defaults $(1)/etc/uci-defaults/90-netpulse-server
+endef
+
+$(eval $(call BuildPackage,netpulse))

+ 19 - 0
deploy/openwrt/netpulse-server/files/netpulse-server.config

@@ -0,0 +1,19 @@
+# /etc/config/netpulse — UCI config del servidor on-box (Fase 9)
+# Gestionado por opkg; se preserva en upgrades (conffiles).
+# El servidor lee esta sección vía internal/config/uci.go (R5).
+# Tras editar: /etc/init.d/netpulse reload + restart
+
+config server 'server'
+	# Puerto HTTP(S) del servidor (default 3000)
+	option port '3000'
+
+	# Directorio de datos (SQLite). Default: overlay.
+	# Si hay USB montado: option data_dir '/mnt/netpulse-data'
+	option data_dir '/usr/local/netpulse-data'
+
+	# Usuario admin inicial (default: admin; la contraseña se genera en
+	# el primer arranque y se muestra UNA vez en logread).
+	option auth_user 'admin'
+
+	# Modo demo (dataset de prueba; default 0)
+	option demo_mode '0'

+ 19 - 0
deploy/openwrt/netpulse-server/files/netpulse-server.defaults

@@ -0,0 +1,19 @@
+#!/bin/sh
+# netpulse-server uci-defaults — primer arranque (Fase 9 R1/R4)
+# Asegura que la sección UCI del servidor existe con valores sanos.
+# El propio binario genera AUTH_PASS (R4), cert TLS (R2) y pairing token
+# (R3) al arrancar si no los encuentra — este script solo prepara UCI.
+
+# Crear la sección server si no existe
+if ! uci -q get netpulse.server >/dev/null 2>&1; then
+	uci -q set netpulse.server=server
+	uci -q set netpulse.server.port=3000
+	uci -q set netpulse.server.data_dir=/usr/local/netpulse-data
+	uci -q set netpulse.server.auth_user=admin
+	uci -q commit netpulse
+fi
+
+# Habilitar el servicio al instalar
+/etc/init.d/netpulse enabled 2>/dev/null || /etc/init.d/netpulse enable
+
+exit 0

+ 34 - 0
deploy/openwrt/netpulse-server/files/netpulse-server.init

@@ -0,0 +1,34 @@
+#!/bin/sh /etc/rc.common
+# netpulse-server — procd init script (Fase 9 R1)
+# Arranca el servidor NetPulse en modo on-box con config UCI.
+
+START=95
+USE_PROCD=1
+
+PROG=/usr/sbin/netpulse
+DATA_DIR=/usr/local/netpulse-data
+
+start_service() {
+	# data_dir: overlay por defecto; USB si está montado
+	local data_dir
+	data_dir=$(uci -q get netpulse.server.data_dir 2>/dev/null)
+	[ -z "$data_dir" ] && data_dir="$DATA_DIR"
+	mkdir -p "$data_dir"
+
+	local port
+	port=$(uci -q get netpulse.server.port 2>/dev/null)
+	[ -z "$port" ] && port=3000
+
+	procd_open_instance
+	procd_set_param command "$PROG"
+	procd_set_param env NETPULSE_ONBOX=1
+	procd_set_param env DATA_DIR="$data_dir"
+	procd_set_param env PORT="$port"
+	procd_set_param stdout stderr  # logs vía procd a syslog
+	procd_set_param respawn 3600 5 0  # respawn tras crash (máx 5 en 1h)
+	procd_close_instance
+}
+
+service_triggers() {
+	procd_add_reload_trigger netpulse
+}