4
0
Эх сурвалжийг харах

feat(devices): apply device name as DHCP reservation hostname (#800) (#805)

feat(devices): apply device name as DHCP reservation hostname (#800)
Nacho 2 сар өмнө
parent
commit
25aba699cc

+ 6 - 0
CHANGELOG.md

@@ -5,6 +5,12 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
+## [Unreleased]
+
+### Added
+
+- **Aplicar el nombre del dispositivo como reserva DHCP (#800)**: renombrar un cliente en NetPulse solo cambiaba el nombre visible dentro de la app; el router seguía mostrando el hostname original (p. ej. en LuCI). La tarjeta de reserva DHCP del editor de dispositivos ofrece ahora "Aplicar nombre en el router": si la MAC ya tiene reserva se actualiza solo su hostname (la IP no se toca); si no, se crea la reserva con la IP actual. El hostname debe ser DNS válido (la acción se deshabilita con una pista si el nombre visible no lo es) y, como toda escritura en el router, se muestra primero el plan de comandos y solo se ejecuta tras la confirmación explícita.
+
 ## [2.28.28] - 2026-09-19
 
 ### Fixed

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

@@ -401,6 +401,9 @@
       "useCurrentIp": "Use current IP",
       "removeReserve": "Remove",
       "saveReserve": "Save IP",
+      "applyName": "Apply name on router",
+      "applyNameHint": "Creates or updates the DHCP reservation with this name (visible in LuCI).",
+      "applyNameInvalid": "The display name is not a valid DNS hostname; change it to apply it.",
       "blockTitle": "Block device",
       "blockHint": "Adds a firewall rule on the router it is attached to.",
       "blocked": "Blocked",

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

@@ -401,6 +401,9 @@
       "useCurrentIp": "Usar IP actual",
       "removeReserve": "Quitar",
       "saveReserve": "Guardar IP",
+      "applyName": "Aplicar nombre en el router",
+      "applyNameHint": "Crea o actualiza la reserva DHCP con este nombre (visible en LuCI).",
+      "applyNameInvalid": "El nombre visible no es un hostname DNS válido; cámbialo para poder aplicarlo.",
       "blockTitle": "Bloquear dispositivo",
       "blockHint": "Añade una regla de firewall en el router al que está conectado.",
       "blocked": "Bloqueado",

+ 43 - 0
app/src/components/DeviceEditSheet.tsx

@@ -120,6 +120,10 @@ export function DeviceEditSheet({
     onSave(device, { icon, name: name.trim(), type: devType })
   }
 
+  // #800: hostname DNS derivado del nombre visible (input del sheet o nombre
+  // actual). Vacío = el nombre visible no es aplicable como hostname DNS.
+  const appliedHostname = device ? asDhcpHostname(name.trim() || device.name) : ''
+
   const selectedIconName = icon || null
 
   const PreviewIcon = (selectedIconName ? (ICON_OVERRIDES[selectedIconName] ?? ICON_OVERRIDES['help-circle']) : ICON_OVERRIDES['help-circle']) as LucideIcon
@@ -298,6 +302,45 @@ export function DeviceEditSheet({
                   {t('devices.edit.saveReserve')}
                 </Button>
               </div>
+              {/* #800: aplicar el nombre visible como hostname de la reserva */}
+              <div className="space-y-1.5">
+                <Button
+                  variant="outline"
+                  size="sm"
+                  className="w-full"
+                  disabled={reservation.loading || !appliedHostname}
+                  onClick={async () => {
+                    if (!device || !appliedHostname) return
+                    setReservation((p) => ({ ...p, loading: true }))
+                    const path = `/api/devices/${encodeURIComponent(device.mac)}/reservation-hostname`
+                    const body = { hostname: appliedHostname, ip: reserveDraft || device.ip }
+                    const applyName = async () => {
+                      const res = await fetchJson<{ ip?: string }>(path, {
+                        method: 'PUT',
+                        headers: { 'Content-Type': 'application/json' },
+                        body: JSON.stringify(body),
+                      })
+                      if (res.ok) {
+                        setReservation({ reserved: true, ip: res.data?.ip ?? body.ip, loading: false })
+                      } else {
+                        setReservation((p) => ({ ...p, loading: false }))
+                      }
+                    }
+                    // #754: primero el plan de comandos; se aplica al confirmar.
+                    const planned = await openPlan(path, body, applyName)
+                    if (!planned) {
+                      await applyName()
+                    } else {
+                      setReservation((p) => ({ ...p, loading: false }))
+                    }
+                  }}
+                >
+                  {t('devices.edit.applyName')}
+                </Button>
+                <p className="text-caption text-text-muted">
+                  {appliedHostname ? t('devices.edit.applyNameHint') : t('devices.edit.applyNameInvalid')}
+                </p>
+              </div>
             </div>
 
             {/* Bloqueo de dispositivo */}

+ 107 - 0
server-go/internal/httpapi/device_actions.go

@@ -359,6 +359,113 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 	writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac, "ip": body.IP})
 }
 
+// handleDeviceReservationHostnamePut aplica el nombre visible de NetPulse como
+// hostname de la reserva DHCP del dispositivo (#800): si la MAC ya tiene
+// reserva se actualiza solo el `name` (la IP no se toca); si no, se crea la
+// reserva con la IP actual del dispositivo. El hostname debe ser DNS válido y
+// NO vacío (#693): es el objetivo de la acción, no un opcional. La UI deriva
+// el hostname del nombre visible y deshabilita la acción si no es aplicable.
+func (s *server) handleDeviceReservationHostnamePut(w http.ResponseWriter, r *http.Request) {
+	mac := normalizeMAC(r.PathValue("mac"))
+	if len(mac) != 17 {
+		writeError(w, http.StatusBadRequest, "invalid_mac")
+		return
+	}
+	var body struct {
+		IP       string `json:"ip"`
+		Hostname string `json:"hostname"`
+	}
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "body JSON inválido")
+		return
+	}
+	// A diferencia del PUT de reserva, aquí el hostname ES el objetivo de la
+	// acción: vacío no significa "no tocar", significa petición sin sentido.
+	if body.Hostname == "" || !validDHCPHostname(body.Hostname) {
+		writeError(w, http.StatusBadRequest, "invalid_hostname",
+			"el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
+		return
+	}
+	if net.ParseIP(body.IP) == nil {
+		writeError(w, http.StatusBadRequest, "invalid_ip")
+		return
+	}
+	host := s.reservationTargetHost(mac)
+	if host == "" {
+		writeError(w, http.StatusBadRequest, "no_gateway")
+		return
+	}
+	lines, err := s.uciShow(host, "dhcp")
+	if err != nil {
+		writeError(w, http.StatusInternalServerError, "ssh_error", err.Error())
+		return
+	}
+	hosts := parseDhcpHosts(lines)
+
+	// Conflicto: otra MAC (distinta de ésta) ya tiene esa IP reservada.
+	for _, h := range hosts {
+		if h.IP != body.IP {
+			continue
+		}
+		if findDhcpHost([]*dhcpHost{h}, mac) != nil {
+			continue // es la sección de esta misma MAC
+		}
+		writeError(w, http.StatusConflict, "ip_conflict",
+			fmt.Sprintf("la IP %s ya está reservada para %s", body.IP, h.MAC))
+		return
+	}
+
+	existing := findDhcpHost(hosts, mac)
+	var apply, rollback []string
+	created := false
+	if existing != nil {
+		if existing.Name == body.Hostname {
+			// No-op idempotente: el router ya tiene exactamente ese hostname.
+			writeJSON(w, http.StatusOK, map[string]any{
+				"ok": true, "mac": mac, "ip": existing.IP, "noop": true,
+			})
+			return
+		}
+		apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
+		if existing.Name != "" {
+			rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "name", existing.Name))
+		} else {
+			rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s.name", existing.Section))
+		}
+	} else {
+		created = true
+		section := dhcpHostSection(mac)
+		apply = append(apply,
+			fmt.Sprintf("uci set dhcp.%s=host", section),
+			uciSetCmd("dhcp", section, "name", body.Hostname),
+			uciSetCmd("dhcp", section, "mac", mac),
+			uciSetCmd("dhcp", section, "ip", body.IP),
+		)
+		rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
+	}
+
+	// Dry-run (#754): devolver el plan sin ejecutar nada en el router.
+	if r.URL.Query().Get("dry_run") == "1" {
+		writeDevicePlan(w, mac, host, apply, rollback)
+		return
+	}
+
+	if err := s.runUCICommands(host, "dhcp", apply); err != nil {
+		writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
+		return
+	}
+	if err := s.reloadService(host, "dnsmasq"); err != nil {
+		if rbErr := s.runUCICommands(host, "dhcp", rollback); rbErr != nil {
+			log.Printf("[netpulse] rollback hostname reserva %s falló: %v", mac, rbErr)
+		}
+		writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
+		return
+	}
+	writeJSON(w, http.StatusOK, map[string]any{
+		"ok": true, "mac": mac, "ip": body.IP, "created": created,
+	})
+}
+
 // writeDevicePlan responde un dry-run (#754): comandos que SE EJECUTARÍAN
 // (apply) y su plan de vuelta (rollback), sin tocar el router.
 func writeDevicePlan(w http.ResponseWriter, mac, host string, apply, rollback []string) {

+ 190 - 0
server-go/internal/httpapi/device_reservation_hostname_test.go

@@ -0,0 +1,190 @@
+// device_reservation_hostname_test.go — issue #800: aplicar el nombre visible
+// del dispositivo como hostname de su reserva DHCP. Con el fake SSHRunner
+// (scripteable); NINGÚN router real se toca. Cubre crear/actualizar/no-op,
+// dry-run, conflicto de IP, validación y rollback ante fallo de reload.
+package httpapi_test
+
+import (
+	"fmt"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// dhcpDevHostNoName: reserva existente SIN opción name (rollback = delete).
+const dhcpDevHostNoName = `dhcp.np_host_aabbccddeeff=host
+dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'
+dhcp.np_host_aabbccddeeff.ip='192.168.1.60'
+`
+
+func hostnameBody(ip, hostname string) string {
+	return fmt.Sprintf(`{"ip":%q,"hostname":%q}`, ip, hostname)
+}
+
+func TestReservationHostnameCreate(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	// Apply real: crea la sección host con name/mac/ip.
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname", ts.cookie, hostnameBody("192.168.1.60", "tv-salon"))
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	body := decodeBody(t, res)
+	if body["created"] != true {
+		t.Fatalf("created: %v", body["created"])
+	}
+	if !ssh.saw("uci set dhcp.np_host_aabbccddeeff=host") {
+		t.Fatalf("no creó la sección: %v", ssh.cmdsSnapshot())
+	}
+	if !ssh.saw(".name='tv-salon'") || !ssh.saw(".ip='192.168.1.60'") {
+		t.Fatalf("faltan set name/ip: %v", ssh.cmdsSnapshot())
+	}
+	if !ssh.saw("uci commit dhcp") || !ssh.saw("/etc/init.d/dnsmasq restart") {
+		t.Fatalf("falta commit/reload: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestReservationHostnameCreateDryRun(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname?dry_run=1", ts.cookie, hostnameBody("192.168.1.60", "tv-salon"))
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	body := decodeBody(t, res)
+	if body["dryRun"] != true {
+		t.Fatalf("dryRun: %v", body["dryRun"])
+	}
+	apply, _ := body["apply"].([]any)
+	if len(apply) != 4 {
+		t.Fatalf("apply: %v", apply)
+	}
+	if ssh.saw("uci commit dhcp") {
+		t.Fatalf("dry-run ejecutó comandos: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestReservationHostnameUpdate(t *testing.T) {
+	ssh := newSSH(dhcpDevHost, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	// Dry-run: apply solo toca el name y el rollback restaura el name anterior.
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname?dry_run=1", ts.cookie, hostnameBody("192.168.1.60", "movil-nacho"))
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("dry-run status: %d", res.StatusCode)
+	}
+	plan := decodeBody(t, res)
+	apply, _ := plan["apply"].([]any)
+	rollback, _ := plan["rollback"].([]any)
+	if len(apply) != 1 || !strings.Contains(fmt.Sprint(apply[0]), "name='movil-nacho'") {
+		t.Fatalf("apply: %v", apply)
+	}
+	if len(rollback) != 1 || !strings.Contains(fmt.Sprint(rollback[0]), "name='tv-salon'") {
+		t.Fatalf("rollback: %v", rollback)
+	}
+
+	// Apply real: actualiza el name; no recrea la sección.
+	res = deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname", ts.cookie, hostnameBody("192.168.1.60", "movil-nacho"))
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	body := decodeBody(t, res)
+	if body["created"] != false {
+		t.Fatalf("created: %v", body["created"])
+	}
+	if !ssh.saw("uci set dhcp.np_host_aabbccddeeff.name='movil-nacho'") {
+		t.Fatalf("no actualizó el name: %v", ssh.cmdsSnapshot())
+	}
+	if ssh.saw("np_host_aabbccddeeff=host") {
+		t.Fatalf("recreate innecesario de la sección: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestReservationHostnameUpdateNoNameRollback(t *testing.T) {
+	ssh := newSSH(dhcpEmpty+dhcpDevHostNoName, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	// La sección no tenía name: el dry-run planea BORRAR la opción en el rollback.
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname?dry_run=1", ts.cookie, hostnameBody("192.168.1.60", "tv-salon"))
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	plan := decodeBody(t, res)
+	rollback, _ := plan["rollback"].([]any)
+	if len(rollback) != 1 || !strings.Contains(fmt.Sprint(rollback[0]), "uci delete dhcp.np_host_aabbccddeeff.name") {
+		t.Fatalf("rollback: %v", rollback)
+	}
+}
+
+func TestReservationHostnameNoop(t *testing.T) {
+	ssh := newSSH(dhcpDevHost, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname", ts.cookie, hostnameBody("192.168.1.60", "tv-salon"))
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	body := decodeBody(t, res)
+	if body["noop"] != true {
+		t.Fatalf("noop: %v", body["noop"])
+	}
+	if ssh.saw("uci commit dhcp") {
+		t.Fatalf("no-op ejecutó escritura: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestReservationHostnameConflict(t *testing.T) {
+	ssh := newSSH(dhcpOtherHost, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname", ts.cookie, hostnameBody("192.168.1.50", "tv-salon"))
+	if res.StatusCode != http.StatusConflict {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	if ssh.saw("uci commit dhcp") {
+		t.Fatalf("conflicto ejecutó escritura: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestReservationHostnameApplyValidation(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	for _, body := range []string{
+		hostnameBody("192.168.1.60", "tv salón"), // espacio: no es hostname DNS
+		hostnameBody("192.168.1.60", ""),         // hostname vacío
+		`{"ip":"nop","hostname":"tv-salon"}`,     // IP inválida
+	} {
+		res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname", ts.cookie, body)
+		if res.StatusCode != http.StatusBadRequest {
+			t.Fatalf("body %s: status %d", body, res.StatusCode)
+		}
+		res.Body.Close()
+	}
+	if ssh.saw("uci commit dhcp") {
+		t.Fatalf("validación ejecutó escritura: %v", ssh.cmdsSnapshot())
+	}
+}
+
+func TestReservationHostnameReloadFailureRollsBack(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty, sshRule{
+		contains: "/etc/init.d/dnsmasq restart",
+		err:      fmt.Errorf("boom"),
+	})
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation-hostname", ts.cookie, hostnameBody("192.168.1.60", "tv-salon"))
+	if res.StatusCode != http.StatusInternalServerError {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	res.Body.Close()
+	// El rollback borra la sección creada.
+	if !ssh.saw("uci delete dhcp.np_host_aabbccddeeff") {
+		t.Fatalf("falta rollback: %v", ssh.cmdsSnapshot())
+	}
+	if !strings.Contains(strings.Join(ssh.cmdsSnapshot(), "\n"), "uci commit dhcp") {
+		t.Fatalf("falta commit del rollback: %v", ssh.cmdsSnapshot())
+	}
+}

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

@@ -336,6 +336,7 @@ func NewHandler(d Deps) http.Handler {
 	// Reserva DHCP y bloqueo de dispositivo (issue #439).
 	mux.Handle("GET /api/devices/{mac}/reservation", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceReservationGet)))
 	mux.Handle("PUT /api/devices/{mac}/reservation", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceReservationPut)))
+	mux.Handle("PUT /api/devices/{mac}/reservation-hostname", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceReservationHostnamePut)))
 	mux.Handle("DELETE /api/devices/{mac}/reservation", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceReservationDelete)))
 	mux.Handle("GET /api/devices/{mac}/block", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceBlockGet)))
 	mux.Handle("PUT /api/devices/{mac}/block", auth.RequireAdmin(http.HandlerFunc(s.handleDeviceBlockPut)))