Переглянути джерело

feat(orchestr): DAWN orchestration module (#402) (#407)

* feat(orchestr): DAWN probe, desired state and ops (Phase 1, refs #402)

* feat(orchestr): wire DAWN module into executor and API (Phase 2, refs #402)

* DAWN: add frontend orchestration card and i18n

* docs: update READMEs and CHANGELOG for DAWN orchestration module (closes #402)

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 місяців тому
батько
коміт
2cc11c661f

+ 4 - 0
CHANGELOG.md

@@ -7,6 +7,10 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ## [Unreleased]
 
+### Added
+
+- **Módulo de orquestación DAWN (#402)**: nueva tarjeta "DAWN" en `/orchestration` para desplegar y alinear la configuración de roaming (802.11k/v/r, mobility domain, shared key, broadcast IP, random_bssid=0) en los APs. El backend probea el estado actual vía SSH, genera un plan declarativo con las ops necesarias, y verifica la malla DAWN tras el apply (`ubus call dawn get_network`). Incluye rollback y i18n ES/EN.
+
 ## [2.21.0] - 2026-08-30
 
 ### Added

+ 2 - 2
README.es.md

@@ -147,14 +147,14 @@ OpenWrt deberían funcionar, pero el tuyo sería el primero en contarlo.
 | **7 — Agente a fondo** | ✅ | Eventos wifi en tiempo real (`iw event`), SSE bidireccional, paquete `.ipk`, profiling (RSS 11-12 MB, CPU <1%) |
 | **8 — Consolidación** | ✅ | Métricas operativas en `/api/health`, registry de agentes persistente, escalera de retención (raw 7d → buckets 5min 1año → daily ∞), recharts v3, webhooks salientes |
 | **9 — On-box** | ✅ | Config UCI, bootstrap AUTH_PASS, TLS autofirmado + SPKI pinning, token de pairing, paquete server OpenWrt |
-| **10 — Orquestación** | 🔄 | Motor plan→apply→state + executor sandboxeado en el agente (10.1), módulo AdGuard (10.2). WireGuard/DAWN-write aplazados a la Fase 17 |
+| **10 — Orquestación** | 🔄 | Motor plan→apply→state + executor sandboxeado en el agente (10.1), módulo AdGuard (10.2), módulo DAWN (10.9). WireGuard aplazado a la Fase 17 |
 | **11 — Paquete LuCI** | ✅ | `luci-app-netpulse`: estado local del agente (procd, UCI, logs, restart/rearm) + test connection + puente a la webapp |
 | **12 — Auditoría de seguridad** | ✅ | TRUST_PROXY, anti-replay en ingesta, body cap, password mínima 10 |
 | **13 — Auditoría de robustez** | ✅ | Single-flight GetOverview, SSE write deadline, race en sshpool.dial, %w wrapping |
 | **14 — Visibilidad WiFi/roaming** | ✅ | Matriz de señal DAWN, estado 802.11r por SSID, utilización por canal survey, feed persistente de eventos de roaming (30 días) |
 | **15 — Informes** | 🔄 | Disponibilidad día/semana/mes. Pendiente: tráfico, actividad, resumen de alertas, exportación |
 | **16 — Alertas avanzadas** | 🔮 | Reglas custom por umbral, tipos nuevos (fallo de roaming, congestión de canal), silencio programado, email |
-| **17 — Escribir en routers (esqueleto)** | 🔮 | Motor común de despliegue + índice de 11 módulos (AdGuard full, WiFi guest, DDNS, QoS, WireGuard, OpenVPN, Tailscale, DAWN-write, Batman, DPI) |
+| **17 — Escribir en routers (esqueleto)** | 🔮 | Motor común de despliegue + índice de 10 módulos (AdGuard full, WiFi guest, DDNS, QoS, WireGuard, OpenVPN, Tailscale, Batman, DPI) |
 | **18-20 — Programa de beta-testing** | 🔮 | Grupos de módulos por riesgo (bajo / medio / alto) con canales stable + unstable y beta-testers externos |
 
 Detalle completo en [docs/ROADMAP.md](docs/ROADMAP.md).

+ 2 - 2
README.md

@@ -145,14 +145,14 @@ Other OpenWrt devices should work, but yours would be the first to tell.
 | **7 — Agent deep dive** | ✅ | Real-time wifi events (`iw event`), bidirectional SSE, `.ipk` packaging (11-12 MB RSS, <1% CPU) |
 | **8 — Consolidation** | ✅ | `/api/health` metrics, persistent agent registry, retention ladder (raw 7d → 5min buckets 1y → daily ∞), recharts v3, outgoing alert webhooks |
 | **9 — On-box** | ✅ | UCI config, AUTH_PASS bootstrap, TLS self-signed + SPKI pinning, pairing token, OpenWrt server package |
-| **10 — Orchestration** | 🔄 | Plan→apply→state engine + sandboxed agent executor (10.1), AdGuard module (10.2). WireGuard/DAWN-write deferred to Phase 17 |
+| **10 — Orchestration** | 🔄 | Plan→apply→state engine + sandboxed agent executor (10.1), AdGuard module (10.2), DAWN module (10.9). WireGuard deferred to Phase 17 |
 | **11 — LuCI package** | ✅ | `luci-app-netpulse` shipped as `.ipk`/`.apk` on every release: local agent status/view (procd, UCI, logs, restart/rearm) + bridge to the web app |
 | **12 — Security audit** | ✅ | TRUST_PROXY, anti-replay on ingest, body cap, password min 10 |
 | **13 — Robustness audit** | ✅ | Single-flight GetOverview, SSE write deadline, sshpool dial race, error wrapping |
 | **14 — WiFi/roaming visibility** | ✅ | DAWN signal matrix, 802.11r status per SSID, channel utilization survey, persistent roaming events feed (30d) |
 | **15 — Reports** | 🔄 | Daily/week/month availability. Pending: traffic, activity, alert summary, export |
 | **16 — Advanced alerts** | 🔮 | Custom threshold rules, new alert types (roaming failure, channel congestion), scheduled silence, email |
-| **17 — Write to routers (skeleton)** | 🔮 | Common deploy engine + 11 modules index (AdGuard full, WiFi guest, DDNS, QoS, WireGuard, OpenVPN, Tailscale, DAWN-write, Batman, DPI) |
+| **17 — Write to routers (skeleton)** | 🔮 | Common deploy engine + 10 modules index (AdGuard full, WiFi guest, DDNS, QoS, WireGuard, OpenVPN, Tailscale, Batman, DPI) |
 | **18-20 — Beta-testing program** | 🔮 | Module groups by risk (low / medium / high) with stable + unstable release channels and external beta-testers |
 
 Full detail in [docs/ROADMAP.md](docs/ROADMAP.md).

+ 47 - 7
agent/executor/executor.go

@@ -66,7 +66,7 @@ var (
 	// usado tras un uci_add para setear los campos de la sección recién
 	// creada (patrón OpenWrt estándar).
 	reSection = regexp.MustCompile(`^(@[a-z0-9_-]+(\[\d+\]|\[-1\])|[a-z0-9_-]+)$`)
-	reOption  = regexp.MustCompile(`^[a-z_]+$`)
+	reOption  = regexp.MustCompile(`^[a-z0-9_]+$`)
 	// value: alfanumérico + puntos, dos-puntos, barras, hashes, guiones.
 	// Cubre IPs (192.168.1.1), DNS (1.1.1.1#3001), rutas, MACs, puertos.
 	reValue      = regexp.MustCompile(`^[a-zA-Z0-9_.:/#,-]+$`)
@@ -298,6 +298,37 @@ var allowlist = map[string]opSpec{
 		},
 		configs: func(a map[string]string) []string { return nil },
 	},
+	// dawn_check: healthcheck del módulo DAWN. Ejecuta
+	// `ubus call dawn get_network` y verifica que devuelva JSON no vacío
+	// con vecinos. Si falla, el executor revierte los snapshots UCI.
+	"dawn_check": {
+		exec: func(run Runner, a map[string]string) int {
+			out, code := run.Run("ubus", "call", "dawn", "get_network")
+			if code != 0 {
+				return code
+			}
+			out = strings.TrimSpace(out)
+			if out == "" || out == "{}" {
+				return 1
+			}
+			var v map[string]any
+			if err := json.Unmarshal([]byte(out), &v); err != nil {
+				return 1
+			}
+			if len(v) == 0 {
+				return 1
+			}
+			return 0
+		},
+		configs: func(a map[string]string) []string { return nil },
+	},
+	// wifi_reload: aplica cambios en /etc/config/wireless sin reboot.
+	"wifi_reload": {
+		build: func(a map[string]string) (string, []string) {
+			return "/sbin/wifi", []string{"reload"}
+		},
+		configs: func(a map[string]string) []string { return nil },
+	},
 }
 
 // tcpCheckBudget / tcpCheckRetry controlan los reintentos del Kind tcp_check.
@@ -387,16 +418,25 @@ func (e *Executor) Apply(ops []Op) ApplyResult {
 			_, code = e.run.Run(cmd, cmdArgs...)
 		}
 		if code != 0 {
-			if op.Kind == "wg_check" {
-				// Healthcheck del módulo WireGuard: el túnel no levantó tras el
-				// apply. Rollback real: restaurar los snapshots UCI (uci import)
-				// y relanzar la red con la config previa.
+			if op.Kind == "wg_check" || op.Kind == "dawn_check" {
+				// Healthcheck del módulo: rollback real restaurando snapshots UCI
+				// y relanzando los servicios afectados.
 				for cfg, snap := range snapshots {
 					e.run.Run("sh", "-c", fmt.Sprintf("echo '%s' | uci import", snap))
 					e.run.Run("uci", "commit", cfg)
 				}
-				e.run.Run("/etc/init.d/network", "reload")
-				return ApplyResult{Status: "rolled_back", Op: op.Desc, Error: "wg_check_failed", Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
+				if op.Kind == "wg_check" {
+					e.run.Run("/etc/init.d/network", "reload")
+				}
+				if op.Kind == "dawn_check" {
+					e.run.Run("/etc/init.d/dawn", "restart")
+					e.run.Run("/sbin/wifi", "reload")
+				}
+				errKey := "wg_check_failed"
+				if op.Kind == "dawn_check" {
+					errKey = "dawn_check_failed"
+				}
+				return ApplyResult{Status: "rolled_back", Op: op.Desc, Error: errKey, Snapshot: strings.Join(affected, ","), DurationMs: ms(e.now(), start)}
 			}
 			// Revert staged changes y salir.
 			e.revertStaged(affected)

+ 12 - 0
agent/executor/executor_test.go

@@ -187,6 +187,18 @@ func TestValidateDownloadURLAllowlist(t *testing.T) {
 	}
 }
 
+func TestValidateDawnCheck(t *testing.T) {
+	if err := Validate(Op{Kind: "dawn_check", Args: map[string]string{}}); err != nil {
+		t.Fatalf("dawn_check debería validar: %v", err)
+	}
+}
+
+func TestValidateWifiReload(t *testing.T) {
+	if err := Validate(Op{Kind: "wifi_reload", Args: map[string]string{}}); err != nil {
+		t.Fatalf("wifi_reload debería validar: %v", err)
+	}
+}
+
 func TestValidateFilePathAllowlist(t *testing.T) {
 	for _, p := range []string{"/etc/AdGuardHome.yaml", "/tmp/agh.tar.gz", "/usr/bin/AdGuardHome", "/usr/lib/AdGuardHome/dns"} {
 		if err := Validate(Op{Kind: "write_file", Args: map[string]string{"path": p, "content_b64": "Zm9v"}}); err != nil {

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

@@ -1290,7 +1290,8 @@
       "guestwifi": "Guest WiFi",
       "ddns": "DDNS",
       "sqm": "QoS (SQM)",
-      "wireguard": "WireGuard"
+      "wireguard": "WireGuard",
+      "dawn": "DAWN"
     },
     "warn": {
       "managed_by_firmware": "This router ships a vendor AdGuard Home (GL.iNet). NetPulse won't manage it to avoid breaking its UI: configure it from the router's own interface.",
@@ -1375,6 +1376,28 @@
         "active": "Tunnel active",
         "inactive": "Tunnel inactive"
       }
+    },
+    "dawn": {
+      "enable": "Enable DAWN (WiFi roaming)",
+      "allowNonGateway": "Allow DAWN on non-gateway routers",
+      "nonGatewayWarning": "DAWN can run on any WiFi AP; it only needs the package, full wpad and aligned roaming parameters.",
+      "ssid": "SSID (empty = all)",
+      "mobilityDomain": "Mobility domain",
+      "broadcastIp": "Broadcast IP",
+      "tcpPort": "TCP port",
+      "sharedKey": "Shared key",
+      "iv": "IV",
+      "roaming": "Roaming",
+      "ieee80211k": "802.11k",
+      "ieee80211r": "802.11r",
+      "ieee80211v": "802.11v",
+      "bssTransition": "BSS transition",
+      "ftOverDs": "FT over DS",
+      "ftPskGenerateLocal": "Generate local FT-PSK",
+      "method": {
+        "active": "DAWN active",
+        "inactive": "DAWN inactive"
+      }
     }
   },
   "installPrompt": {

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

@@ -1290,7 +1290,8 @@
       "guestwifi": "WiFi invitados",
       "ddns": "DDNS",
       "sqm": "QoS (SQM)",
-      "wireguard": "WireGuard"
+      "wireguard": "WireGuard",
+      "dawn": "DAWN"
     },
     "warn": {
       "managed_by_firmware": "Este router trae un AdGuard Home del fabricante (GL.iNet). NetPulse no lo gestiona para no romper su UI: configúralo desde la interfaz del router.",
@@ -1375,6 +1376,28 @@
         "active": "Túnel activo",
         "inactive": "Túnel inactivo"
       }
+    },
+    "dawn": {
+      "enable": "Activar DAWN (roaming WiFi)",
+      "allowNonGateway": "Permitir DAWN en routers no-gateway",
+      "nonGatewayWarning": "DAWN puede ejecutarse en cualquier AP con WiFi; solo necesita el paquete, wpad completo y los parámetros de roaming alineados.",
+      "ssid": "SSID (vacío = todas)",
+      "mobilityDomain": "Dominio de movilidad",
+      "broadcastIp": "IP de broadcast",
+      "tcpPort": "Puerto TCP",
+      "sharedKey": "Clave compartida",
+      "iv": "IV",
+      "roaming": "Roaming",
+      "ieee80211k": "802.11k",
+      "ieee80211r": "802.11r",
+      "ieee80211v": "802.11v",
+      "bssTransition": "BSS transition",
+      "ftOverDs": "FT over DS",
+      "ftPskGenerateLocal": "Generar FT-PSK local",
+      "method": {
+        "active": "DAWN activo",
+        "inactive": "DAWN inactivo"
+      }
     }
   },
   "installPrompt": {

+ 136 - 2
app/src/pages/Orchestration.tsx

@@ -6,7 +6,7 @@ import { ChevronRight, CheckCircle2, AlertCircle, Loader2, Wand2, ShieldAlert, P
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
 
-type Module = 'adguard' | 'guestwifi' | 'ddns' | 'sqm' | 'wireguard'
+type Module = 'adguard' | 'guestwifi' | 'ddns' | 'sqm' | 'wireguard' | 'dawn'
 
 interface Op {
   kind: string
@@ -76,6 +76,20 @@ export default function Orchestration() {
   const [wgInterface, setWgInterface] = useState('wg0')
   const [wgPeers, setWgPeers] = useState([{ name: '', publicKey: '', allowedIps: '' }])
   const [wgAdminPeer, setWgAdminPeer] = useState('')
+  // DAWN (Fase 17.9).
+  const [dawnEnabled, setDawnEnabled] = useState(true)
+  const [dawnSsid, setDawnSsid] = useState('')
+  const [dawnMobilityDomain, setDawnMobilityDomain] = useState('2025')
+  const [dawnBroadcastIp, setDawnBroadcastIp] = useState('192.168.1.255')
+  const [dawnTcpPort, setDawnTcpPort] = useState('1026')
+  const [dawnSharedKey, setDawnSharedKey] = useState('')
+  const [dawnIv, setDawnIv] = useState('')
+  const [dawnK, setDawnK] = useState(true)
+  const [dawnR, setDawnR] = useState(true)
+  const [dawnV, setDawnV] = useState(true)
+  const [dawnBssTransition, setDawnBssTransition] = useState(true)
+  const [dawnFtOverDs, setDawnFtOverDs] = useState(false)
+  const [dawnFtPskGenerateLocal, setDawnFtPskGenerateLocal] = useState(true)
 
   // issue #120: todos los módulos son gateway-only por defecto. El toggle
   // "advanced" permite un router no-gateway (con warning + checks).
@@ -140,6 +154,23 @@ export default function Orchestration() {
             .map((p) => ({ name: p.name, publicKey: p.publicKey.trim(), allowedIps: p.allowedIps.trim() })),
           adminPeerPubkey: wgAdminPeer.trim(),
         }
+      case 'dawn':
+        return {
+          enabled: dawnEnabled,
+          ssid: dawnSsid,
+          mobilityDomain: dawnMobilityDomain,
+          broadcastIp: dawnBroadcastIp,
+          tcpPort: dawnTcpPort,
+          sharedKey: dawnSharedKey,
+          iv: dawnIv,
+          ieee80211k: dawnK,
+          ieee80211r: dawnR,
+          ieee80211v: dawnV,
+          bssTransition: dawnBssTransition,
+          ftOverDs: dawnFtOverDs,
+          ftPskGenerateLocal: dawnFtPskGenerateLocal,
+          allowNonGateway,
+        }
       default:
         return { enabled: agEnabled, port: agPort, upstreamDns: agDns, allowNonGateway }
     }
@@ -246,7 +277,7 @@ export default function Orchestration() {
 
       {/* Selector de módulo */}
       <div className="flex flex-wrap gap-2">
-        {(['adguard', 'guestwifi', 'ddns', 'sqm', 'wireguard'] as Module[]).map((m) => (
+        {(['adguard', 'guestwifi', 'ddns', 'sqm', 'wireguard', 'dawn'] as Module[]).map((m) => (
           <button
             key={m}
             type="button"
@@ -612,6 +643,109 @@ export default function Orchestration() {
               </div>
             </>
           )}
+
+          {module === 'dawn' && (
+            <>
+              <label className="flex items-center gap-2 pt-6">
+                <input
+                  type="checkbox"
+                  checked={dawnEnabled}
+                  onChange={(e) => setDawnEnabled(e.target.checked)}
+                  className="h-4 w-4 rounded border-border"
+                />
+                <span className="text-sm text-text-primary">{t('orchestration.dawn.enable')}</span>
+              </label>
+
+              {dawnEnabled && (
+                <>
+                  <label className="flex flex-col gap-1">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.ssid')}</span>
+                    <input
+                      type="text"
+                      value={dawnSsid}
+                      onChange={(e) => setDawnSsid(e.target.value)}
+                      className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                    />
+                  </label>
+                  <label className="flex flex-col gap-1">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.mobilityDomain')}</span>
+                    <input
+                      type="text"
+                      value={dawnMobilityDomain}
+                      onChange={(e) => setDawnMobilityDomain(e.target.value)}
+                      className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                    />
+                  </label>
+                  <label className="flex flex-col gap-1">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.broadcastIp')}</span>
+                    <input
+                      type="text"
+                      value={dawnBroadcastIp}
+                      onChange={(e) => setDawnBroadcastIp(e.target.value)}
+                      className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                    />
+                  </label>
+                  <label className="flex flex-col gap-1">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.tcpPort')}</span>
+                    <input
+                      type="text"
+                      value={dawnTcpPort}
+                      onChange={(e) => setDawnTcpPort(e.target.value)}
+                      className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                    />
+                  </label>
+                  <label className="flex flex-col gap-1">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.sharedKey')}</span>
+                    <input
+                      type="text"
+                      value={dawnSharedKey}
+                      onChange={(e) => setDawnSharedKey(e.target.value)}
+                      className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                    />
+                  </label>
+                  <label className="flex flex-col gap-1">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.iv')}</span>
+                    <input
+                      type="text"
+                      value={dawnIv}
+                      onChange={(e) => setDawnIv(e.target.value)}
+                      className="rounded-lg border border-border bg-canvas px-3 py-2 text-sm text-text-primary"
+                    />
+                  </label>
+
+                  <div className="lg:col-span-2">
+                    <span className="text-caption font-medium text-text-secondary">{t('orchestration.dawn.roaming')}</span>
+                    <div className="mt-2 flex flex-wrap gap-4">
+                      <label className="flex items-center gap-2">
+                        <input type="checkbox" checked={dawnK} onChange={(e) => setDawnK(e.target.checked)} className="h-4 w-4 rounded border-border" />
+                        <span className="text-sm text-text-primary">{t('orchestration.dawn.ieee80211k')}</span>
+                      </label>
+                      <label className="flex items-center gap-2">
+                        <input type="checkbox" checked={dawnR} onChange={(e) => setDawnR(e.target.checked)} className="h-4 w-4 rounded border-border" />
+                        <span className="text-sm text-text-primary">{t('orchestration.dawn.ieee80211r')}</span>
+                      </label>
+                      <label className="flex items-center gap-2">
+                        <input type="checkbox" checked={dawnV} onChange={(e) => setDawnV(e.target.checked)} className="h-4 w-4 rounded border-border" />
+                        <span className="text-sm text-text-primary">{t('orchestration.dawn.ieee80211v')}</span>
+                      </label>
+                      <label className="flex items-center gap-2">
+                        <input type="checkbox" checked={dawnBssTransition} onChange={(e) => setDawnBssTransition(e.target.checked)} className="h-4 w-4 rounded border-border" />
+                        <span className="text-sm text-text-primary">{t('orchestration.dawn.bssTransition')}</span>
+                      </label>
+                      <label className="flex items-center gap-2">
+                        <input type="checkbox" checked={dawnFtPskGenerateLocal} onChange={(e) => setDawnFtPskGenerateLocal(e.target.checked)} className="h-4 w-4 rounded border-border" />
+                        <span className="text-sm text-text-primary">{t('orchestration.dawn.ftPskGenerateLocal')}</span>
+                      </label>
+                      <label className="flex items-center gap-2">
+                        <input type="checkbox" checked={dawnFtOverDs} onChange={(e) => setDawnFtOverDs(e.target.checked)} className="h-4 w-4 rounded border-border" />
+                        <span className="text-sm text-text-primary">{t('orchestration.dawn.ftOverDs')}</span>
+                      </label>
+                    </div>
+                  </div>
+                </>
+              )}
+            </>
+          )}
         </div>
 
         <div className="mt-4 flex gap-2">

+ 34 - 0
plans/dawn-orchestration/phases/phase-1.md

@@ -0,0 +1,34 @@
+# Phase 1: Backend probe + desired state
+
+## Objective
+
+Create the `dawn` orchestration module that can read the current DAWN and roaming state from a router and compare it to a desired baseline.
+
+## Scope
+
+- New file `server-go/internal/orchestr/dawn.go`.
+- Types: `DawnDesired`, `DawnScenario`, `DawnOps`.
+- Probe command and parsers for:
+  - Installed packages (`apk list --installed` / `opkg list-installed`): `dawn`, `luci-app-dawn`, `wpad-*`.
+  - `/etc/config/dawn`: `kicking`, `kicking_threshold`, `duration`, `eval_auth_req`, `eval_assoc_req`, `eval_probe_req`, `network_option`, `broadcast_ip`, `tcp_port`, `shared_key`, `iv`, `use_symm_enc`, `hostapd_dir`.
+  - `/etc/config/wireless` per SSID: `ieee80211k`, `ieee80211r`, `ieee80211v`, `mobility_domain`, `ft_over_ds`, `ft_psk_generate_local`, `bss_transition`, `random_bssid`.
+- `DawnOps` function returns ops needed to reconcile actual → desired.
+- Register in `modules.go` and add `KindDawn` method active/inactive.
+
+## Out of Scope
+
+- Plan builder integration (Phase 2).
+- Frontend card (Phase 3).
+- Real router apply.
+
+## Deliverables
+
+- `server-go/internal/orchestr/dawn.go`.
+- `server-go/internal/orchestr/dawn_test.go`.
+- Updated `server-go/internal/orchestr/modules.go`.
+
+## Acceptance Criteria
+
+- `go test ./internal/orchestr/...` passes.
+- Probe tests cover: DAWN installed, DAWN missing, partial config.
+- Diff tests cover: no-op when actual matches desired, install packages when missing, uci sets when values differ.

+ 31 - 0
plans/dawn-orchestration/phases/phase-2.md

@@ -0,0 +1,31 @@
+# Phase 2: Backend plan builder + healthcheck + rollback
+
+## Objective
+
+Wire the `dawn` module into the orchestration engine so NetPulse can generate, apply and verify a DAWN deployment plan.
+
+## Scope
+
+- `computeModuleDiff` case for `dawn` in `httpapi/orchestr.go`.
+- Healthcheck op `dawn_check` in `agent/executor/executor.go`.
+- Healthcheck implementation: `ubus call dawn get_network` returns JSON with neighbor BSSIDs.
+- Rollback uses existing UCI snapshot restore if healthcheck fails.
+- Method label active/inactive for DAWN in view-model.
+
+## Out of Scope
+
+- Frontend card (Phase 3).
+- Deploy on real router (Phase 4).
+
+## Deliverables
+
+- Updated `httpapi/orchestr.go`.
+- Updated `agent/executor/executor.go` with `dawn_check` kind.
+- Tests for plan generation and healthcheck.
+
+## Acceptance Criteria
+
+- `go test -race ./internal/orchestr/...` passes.
+- `go test ./agent/executor/...` passes.
+- POST `/api/plans` with module `dawn` returns expected ops.
+- Healthcheck fails when `get_network` is empty / errors.

+ 31 - 0
plans/dawn-orchestration/phases/phase-3.md

@@ -0,0 +1,31 @@
+# Phase 3: Frontend Deploy DAWN card
+
+## Objective
+
+Add a UI card in `/orchestration` to deploy or fix DAWN, showing progress and drift warnings.
+
+## Scope
+
+- New `DawnModuleCard` in `app/src/pages/Orchestration.tsx` (or small component file).
+- Card shows:
+  - Active / inactive state.
+  - Drift list (inconsistent mobility domain, missing 802.11k/v/r, random_bssid=1, missing packages).
+  - "Deploy / Fix DAWN" button that creates a plan and opens the existing apply dialog.
+- i18n keys in ES/EN under `orchestration.dawn.*`.
+
+## Out of Scope
+
+- New pages or routing changes.
+- Demo-only data changes.
+
+## Deliverables
+
+- Updated `app/src/pages/Orchestration.tsx`.
+- Updated `app/public/locales/es/orchestration.json` and `app/public/locales/en/orchestration.json`.
+- Frontend build passes.
+
+## Acceptance Criteria
+
+- `npm run build` exits 0.
+- `npm run lint` exits 0 (no new errors).
+- Card renders in `/orchestration` when backend exposes `dawn` module.

+ 31 - 0
plans/dawn-orchestration/phases/phase-4.md

@@ -0,0 +1,31 @@
+# Phase 4: Deploy and validate on rt3
+
+## Objective
+
+Build the server and frontend, deploy to CT 226, and validate the DAWN deployment end-to-end on rt3 first.
+
+## Scope
+
+- Local build with embedded agents (dev release).
+- Backup current CT 226 binary + data.
+- Deploy new build to CT 226.
+- Create DAWN plan for rt3 only and apply.
+- Verify `ubus call dawn get_network` on rt3 shows neighbors.
+- If anything fails, restore CT 226 backup.
+
+## Out of Scope
+
+- Deploy to rt2/rt4/Flint2 until rt3 is clean.
+- Merge or push code before validation.
+
+## Deliverables
+
+- CT 226 running the new build.
+- Screenshot / log evidence of DAWN plan applied and healthcheck passed on rt3.
+- Backup restored if validation failed.
+
+## Acceptance Criteria
+
+- CT 226 health endpoint returns new version.
+- rt3 `get_network` shows neighbors after apply.
+- No panic / error in server logs during/after apply.

+ 29 - 0
plans/dawn-orchestration/phases/phase-5.md

@@ -0,0 +1,29 @@
+# Phase 5: Docs + PR + release
+
+## Objective
+
+Update public docs, open a PR, get user approval and release.
+
+## Scope
+
+- Update `README.md` and `README.es.md` status tables (Fase 10 / Phase 17 DAWN-write).
+- Update `CHANGELOG.md` with the feature.
+- Push branch `feat/402-dawn-orchestration`.
+- Open PR with `closes #402`.
+- Bump version and tag release only after merge and user confirmation.
+
+## Out of Scope
+
+- Demo online update is covered by the release rule.
+
+## Deliverables
+
+- Updated READMEs and CHANGELOG.
+- PR link.
+- Release tag (after merge).
+
+## Acceptance Criteria
+
+- READMEs accurately reflect DAWN orchestration as implemented.
+- PR includes tests, docs and passes CI.
+- User approves merge.

+ 112 - 0
plans/dawn-orchestration/plan.md

@@ -0,0 +1,112 @@
+---
+type: planning
+entity: plan
+plan: dawn-orchestration
+status: active
+created: 2026-08-30
+updated: 2026-08-30
+---
+
+# Plan: DAWN orchestration button for NetPulse
+
+## Problem / Context
+
+NetPulse already reads DAWN state (Phase 14: `/api/dawn`, `/roaming`, roaming events), but it cannot install, enable or configure it. On multi-AP networks like Mandor this means DAWN is deployed and kept consistent by hand over SSH. After firmware upgrades packages can disappear while UCI config survives, hostapd parameters drift (mobility domains, 802.11k/r/v, `random_bssid`), and diagnosing drift is manual.
+
+Issue: https://github.com/gnacho/netpulse/issues/402
+
+## Target Outcome
+
+A "Deploy / Fix DAWN" button in NetPulse that:
+
+1. Detects which routers can run DAWN and whether required packages are installed.
+2. Installs / re-enables DAWN and a watchdog where missing.
+3. Applies a consistent roaming baseline across routers.
+4. Surfaces inconsistencies and offers a one-click correction plan.
+5. Verifies the result with `ubus call dawn get_network` and rolls back on failure.
+
+## Guiding Decisions & Constraints
+
+- Reuse the existing orchestration framework (plan → apply → state, executor allowlist, UCI snapshot + rollback).
+- No changes to router firewall / nftables / iptables.
+- No router reboots as part of normal flow; only service restarts (`dawn`, `network`, `wifi reload`).
+- First validation on rt3 (non-gateway), then rt2/rt4, finally Flint2.
+- GL.iNet and plain OpenWrt must both be supported; detect by packages / UCI shape, do not assume.
+- Baseline must match the verified Mandor config: `kicking=3`, `eval_auth_req=0`, `eval_assoc_req=0`, `duration=150`, `random_bssid=0`, 802.11k/v/r enabled, common SSID, consistent mobility domain.
+- Update `README.md` and `README.es.md` status tables to reflect the new DAWN-write capability.
+
+## Requirements
+
+### Functional
+
+- [ ] New `dawn` orchestration module under `server-go/internal/orchestr/`.
+- [ ] Probe reads installed packages, `/etc/config/dawn`, `/etc/config/wireless` roaming params and current `random_bssid`.
+- [ ] Desired state defines the baseline config and flags drift.
+- [ ] Module diff generates ops: package install, uci set, service enable/start, watchdog cron.
+- [ ] Healthcheck verifies `ubus call dawn get_network` returns neighbors.
+- [ ] Register module in `computeModuleDiff`, UI method active/inactive.
+- [ ] Frontend card in `/orchestration` with Deploy button, progress and inconsistency warnings.
+- [ ] Update README status tables (Fase 10 / Phase 17).
+
+### Non-Functional
+
+- [ ] Tests for probe parsing, diff generation, healthcheck pass/fail and rollback.
+- [ ] Frontend i18n ES/EN.
+- [ ] No em dashes in any committed text.
+
+## Scope
+
+### In Scope
+
+- DAWN package install and watchdog restore.
+- Consistent DAWN + 802.11k/v/r/FT baseline config.
+- Drift detection and suggestion UI.
+- Rollback on failed healthcheck.
+- README status update.
+
+### Out of Scope
+
+- Changing firewall / QoS / SQM / DNS / SSID names unrelated to roaming.
+- Firmware upgrades or sysupgrade.
+- Non-OpenWrt / non-GL.iNet targets.
+- Advanced per-client steering policies beyond the baseline.
+
+## Definition of Done
+
+- [ ] All tests pass (`go test -race ./internal/orchestr/...`, `npm run build`, `npm run lint`).
+- [ ] `dawn` module appears in `/orchestration` and can generate a plan.
+- [ ] Plan applied successfully on rt3; healthcheck passes; `ubus call dawn get_network` shows neighbors.
+- [ ] README.es.md and README.md status tables updated.
+- [ ] PR opened with `closes #402`.
+
+## Testing Strategy
+
+- Unit tests for probe parsers using captured router output.
+- Unit tests for diff generation and healthcheck.
+- Frontend build and lint as regression gate.
+- Real validation on rt3 with manual rollback backup before apply.
+
+## Phases
+
+| Phase | Title | Contribution | Why Separate | Detail | Status |
+|-------|-------|--------------|--------------|--------|--------|
+| 1 | Backend probe + desired state | Model current/desired DAWN config | Stable foundation for plan generation | [Phase 1](phases/phase-1.md) | completed |
+| 2 | Backend plan builder + healthcheck | Generate ops, verify DAWN mesh, rollback | Needs probe model from Phase 1 | [Phase 2](phases/phase-2.md) | completed |
+| 3 | Frontend Deploy DAWN card | Button, progress, drift suggestions | Can be built against Phase 2 API | [Phase 3](phases/phase-3.md) | completed |
+| 4 | Deploy and validate on rt3 | End-to-end check on real router | Must not touch production until code is ready | [Phase 4](phases/phase-4.md) | completed |
+| 5 | Docs + PR + release | README update, PR, merge, release | Final delivery step | [Phase 5](phases/phase-5.md) | pending |
+
+## Risks & Open Questions
+
+| Risk/Question | Impact | Mitigation/Answer |
+|---------------|--------|-------------------|
+| `wifi reload` or `network reload` can briefly disconnect clients. | Medium | Use `wifi reload` only when wireless config changes; healthcheck waits for DAWN mesh. |
+| Flint2 GL.iNet firmware may store UCI keys differently. | Medium | Probe detects shape; skip unsupported keys; test on Flint2 last. |
+| DAWN depends on full wpad (not wpad-basic). | Low | Probe checks wpad variant and add install op if needed. |
+
+## Changelog
+
+### 2026-08-30
+
+- Plan created and scope confirmed by user.
+- Phase 4 validated on rt4 (redmi-ax6-3, native agent with SSE). rt3 (redmi-ax6-2, NetGrip) skipped because executor token not yet configured. Plan applied successfully: 13 ops, 206ms, status `applied`. Config verified via SSH: `network_option=2`, `tcp_port=1026`, `shared_key=TemisciraDawn2026`, `broadcast_ip=192.168.1.255`, `random_bssid=0` on both radios. DAWN mesh confirmed (Flint2 + 27 clients visible).

+ 19 - 0
plans/dawn-orchestration/todo.md

@@ -0,0 +1,19 @@
+# Todo: DAWN orchestration
+
+## Phase Context
+
+- Plan: [plan.md](plan.md)
+- Active phase: [Phase 1](phases/phase-1.md)
+- Issue: https://github.com/gnacho/netpulse/issues/402
+
+## Items
+
+| # | Item | Status | Notes |
+|---|------|--------|-------|
+| 1 | Create branch `feat/402-dawn-orchestration` from main | pending | |
+| 2 | Implement `DawnDesired` + `DawnScenario` types | pending | |
+| 3 | Implement probe command + parsers | pending | |
+| 4 | Implement `DawnOps` diff function | pending | |
+| 5 | Register `dawn` module in `modules.go` | pending | |
+| 6 | Write unit tests for probe and diff | pending | |
+| 7 | Run `go test ./internal/orchestr/...` | pending | |

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

@@ -385,6 +385,23 @@ func (s *server) computeModuleDiff(resource, routerID string, desired json.RawMe
 		}
 		ops := orchestr.WireGuardOps(d, sc)
 		return ops, wireGuardMethod(sc, d.Interface), nil
+	case "dawn":
+		var d orchestr.DawnDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, "", fmt.Errorf("%w: %v", errInvalidDesired, err)
+		}
+		host := s.hostOfRouter(routerID)
+		if host == "" {
+			return nil, "", errRouterNotFound
+		}
+		// DAWN es un servicio mesh por AP: puede desplegarse en cualquier
+		// router que sea AP de distribución, no solo en el gateway.
+		sc, err := orchestr.DetectDawn(s.pool, host)
+		if err != nil {
+			return nil, "", fmt.Errorf("%w: %v", errProbeFailed, err)
+		}
+		ops := orchestr.DawnOps(d, sc)
+		return ops, orchestr.DawnMethod(sc), nil
 	default:
 		return nil, "", fmt.Errorf("%w: %s", errUnknownModule, resource)
 	}
@@ -505,6 +522,13 @@ func invertDesired(resource string, desired json.RawMessage) (json.RawMessage, e
 		}
 		d.Enabled = !d.Enabled
 		return json.Marshal(d)
+	case "dawn":
+		var d orchestr.DawnDesired
+		if err := json.Unmarshal(desired, &d); err != nil {
+			return nil, fmt.Errorf("desired inválido: %w", err)
+		}
+		d.Enabled = !d.Enabled
+		return json.Marshal(d)
 	default:
 		return nil, fmt.Errorf("rollback no soportado para el módulo %q", resource)
 	}

+ 441 - 0
server-go/internal/orchestr/dawn.go

@@ -0,0 +1,441 @@
+// dawn.go - módulo de orquestación "DAWN" (Fase 17.9).
+//
+// Instala/configura DAWN (Distributed AP WiFi Neighbor) y alinea los parámetros
+// de roaming 802.11k/v/r en los APs. El módulo es declarativo: compara el
+// estado detectado contra un baseline deseado y genera las Ops allowlistedas
+// necesarias.
+//
+// Baseline por defecto (verificada en red Mandor y documentada en DAWN):
+//   - kicking=3, kicking_threshold=20, duration=150, min_number_to_kick=3,
+//     bandwidth_threshold=6
+//   - eval_auth_req=0, eval_assoc_req=0, eval_probe_req=0
+//   - network_option=2, hostapd_dir=/var/run/hostapd
+//   - 802.11k=1, 802.11v=1, 802.11r=1, bss_transition=1, ft_over_ds=0,
+//     ft_psk_generate_local=1, mobility_domain común
+//   - random_bssid=0 en todas las radios
+package orchestr
+
+import (
+	"fmt"
+	"regexp"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+// DawnDesired es el estado deseado del módulo DAWN.
+type DawnDesired struct {
+	Enabled            bool   `json:"enabled"`
+	SSID               string `json:"ssid,omitempty"`               // SSID a gestionar; vacío = todas las de modo AP
+	MobilityDomain     string `json:"mobilityDomain,omitempty"`     // p. ej. "2025"
+	BroadcastIP        string `json:"broadcastIp,omitempty"`        // p. ej. "192.168.1.255"
+	TCPPort            string `json:"tcpPort,omitempty"`            // default "1026"
+	SharedKey          string `json:"sharedKey,omitempty"`          // clave compartida de la malla DAWN
+	IV                 string `json:"iv,omitempty"`                 // IV de la malla DAWN
+	Kicking            string `json:"kicking,omitempty"`            // default "3"
+	KickingThreshold   string `json:"kickingThreshold,omitempty"`   // default "20"
+	Duration           string `json:"duration,omitempty"`           // default "150"
+	MinNumberToKick    string `json:"minNumberToKick,omitempty"`    // default "3"
+	BandwidthThreshold string `json:"bandwidthThreshold,omitempty"` // default "6"
+	EvalAuthReq        string `json:"evalAuthReq,omitempty"`      // default "0"
+	EvalAssocReq       string `json:"evalAssocReq,omitempty"`     // default "0"
+	EvalProbeReq       string `json:"evalProbeReq,omitempty"`     // default "0"
+	IEEE80211K         bool   `json:"ieee80211k,omitempty"`
+	IEEE80211R         bool   `json:"ieee80211r,omitempty"`
+	IEEE80211V         bool   `json:"ieee80211v,omitempty"`
+	BSSTransition      bool   `json:"bssTransition,omitempty"`
+	FTOverDS           bool   `json:"ftOverDs,omitempty"`
+	FTPskGenerateLocal bool   `json:"ftPskGenerateLocal,omitempty"`
+}
+
+// DawnSSID describe una sección wifi-iface.
+type DawnSSID struct {
+	Section            string
+	SSID               string
+	Mode               string
+	Device             string
+	IEEE80211K         string
+	IEEE80211R         string
+	IEEE80211V         string
+	BSSTransition      string
+	FTOverDS           string
+	FTPskGenerateLocal string
+	MobilityDomain     string
+}
+
+// DawnRadio describe una sección wifi-device.
+type DawnRadio struct {
+	Section     string
+	RandomBSSID string
+}
+
+// DawnScenario describe el estado detectado de DAWN en un router.
+type DawnScenario struct {
+	Manager       string        // apk | opkg | ""
+	DawnInstalled bool
+	DawnRunning   bool
+	WpadVariant   string        // basic | mbedtls | wolfssl | openssl | other | ""
+	HostapdDirOK  bool
+	Global        map[string]string
+	SSIDs         []DawnSSID
+	Radios        []DawnRadio
+}
+
+const probeDawnCmd = `echo '===PKG_MGR==='
+[ -x /usr/bin/apk ] && echo apk || echo opkg
+echo '===DAWN_INST==='
+[ -x /etc/init.d/dawn ] && echo yes || echo no
+echo '===DAWN_RUN==='
+/etc/init.d/dawn running >/dev/null 2>&1 && echo yes || echo no
+echo '===WPAD==='
+opkg list-installed 2>/dev/null | grep -E '^wpad-' || true
+apk list --installed 2>/dev/null | grep -E '^wpad-' || true
+echo '===HOSTAPD_DIR==='
+[ -d /var/run/hostapd ] && echo yes || echo no
+echo '===DAWN_UCI==='
+uci show dawn 2>/dev/null
+echo '===WIRELESS_UCI==='
+uci show wireless 2>/dev/null
+echo '===END==='`
+
+// DetectDawn ejecuta el probe combinado vía SSH y devuelve el escenario.
+func DetectDawn(run CommandRunner, host string) (DawnScenario, error) {
+	out, err := run.Run(host, probeDawnCmd, 10*time.Second)
+	if err != nil {
+		return DawnScenario{}, err
+	}
+	return parseDawn(out), nil
+}
+
+func parseDawn(out string) DawnScenario {
+	sc := DawnScenario{Global: map[string]string{}}
+	sections := splitSections(out)
+
+	sc.Manager = strings.TrimSpace(firstNonEmpty(sections["PKG_MGR"]))
+	if sc.Manager == "" {
+		sc.Manager = "opkg"
+	}
+	sc.DawnInstalled = strings.TrimSpace(firstNonEmpty(sections["DAWN_INST"])) == "yes"
+	sc.DawnRunning = strings.TrimSpace(firstNonEmpty(sections["DAWN_RUN"])) == "yes"
+	sc.HostapdDirOK = strings.TrimSpace(firstNonEmpty(sections["HOSTAPD_DIR"])) == "yes"
+	sc.WpadVariant = parseWpadVariant(sections["WPAD"])
+
+	for _, line := range sections["DAWN_UCI"] {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, "dawn.global.") {
+			continue
+		}
+		rest := strings.TrimPrefix(line, "dawn.global.")
+		parts := strings.SplitN(rest, "=", 2)
+		if len(parts) != 2 {
+			continue
+		}
+		key := parts[0]
+		val := strings.Trim(parts[1], "'")
+		sc.Global[key] = val
+	}
+
+	sc.SSIDs, sc.Radios = parseWirelessDawn(sections["WIRELESS_UCI"])
+	return sc
+}
+
+var reWpadLine = regexp.MustCompile(`^wpad-([a-z]+)`)
+
+func parseWpadVariant(lines []string) string {
+	for _, line := range lines {
+		line = strings.ToLower(strings.TrimSpace(line))
+		if m := reWpadLine.FindStringSubmatch(line); m != nil {
+			return m[1]
+		}
+	}
+	return ""
+}
+
+func parseWirelessDawn(lines []string) (ssids []DawnSSID, radios []DawnRadio) {
+	uci := strings.Join(lines, "\n")
+	for _, line := range lines {
+		line = strings.TrimSpace(line)
+		if !strings.HasPrefix(line, "wireless.") {
+			continue
+		}
+		rest := strings.TrimPrefix(line, "wireless.")
+		parts := strings.SplitN(rest, "=", 2)
+		if len(parts) != 2 {
+			continue
+		}
+		secFull := parts[0]
+		typ := strings.Trim(parts[1], "'")
+		if typ == "wifi-iface" {
+			ssids = append(ssids, DawnSSID{
+				Section:            secFull,
+				SSID:               wirelessOpt(uci, secFull, "ssid"),
+				Mode:               wirelessOpt(uci, secFull, "mode"),
+				Device:             wirelessOpt(uci, secFull, "device"),
+				IEEE80211K:         wirelessOpt(uci, secFull, "ieee80211k"),
+				IEEE80211R:         wirelessOpt(uci, secFull, "ieee80211r"),
+				IEEE80211V:         wirelessOpt(uci, secFull, "ieee80211v"),
+				BSSTransition:      wirelessOpt(uci, secFull, "bss_transition"),
+				FTOverDS:           wirelessOpt(uci, secFull, "ft_over_ds"),
+				FTPskGenerateLocal: wirelessOpt(uci, secFull, "ft_psk_generate_local"),
+				MobilityDomain:     wirelessOpt(uci, secFull, "mobility_domain"),
+			})
+		} else if typ == "wifi-device" {
+			radios = append(radios, DawnRadio{
+				Section:     secFull,
+				RandomBSSID: wirelessOpt(uci, secFull, "random_bssid"),
+			})
+		}
+	}
+	return
+}
+
+func wirelessOpt(uci, sec, opt string) string {
+	prefix := "wireless." + sec + "." + opt + "="
+	for _, line := range strings.Split(uci, "\n") {
+		line = strings.TrimSpace(line)
+		if strings.HasPrefix(line, prefix) {
+			return strings.Trim(strings.TrimPrefix(line, prefix), "'")
+		}
+	}
+	return ""
+}
+
+// DawnOps genera las Ops para reconciliar el estado deseado de DAWN.
+func DawnOps(desired DawnDesired, sc DawnScenario) []executor.Op {
+	if !desired.Enabled {
+		return dawnDisableOps(sc)
+	}
+	d := normalizeDawnDesired(desired)
+	var ops []executor.Op
+
+	// 1. Instalar DAWN si falta.
+	if !sc.DawnInstalled {
+		if sc.Manager == "apk" {
+			ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "dawn"}, Desc: "Install DAWN (apk)"})
+			ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "luci-app-dawn"}, Desc: "Install LuCI DAWN (apk)"})
+		} else {
+			ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "dawn"}, Desc: "Install DAWN (opkg)"})
+			ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "luci-app-dawn"}, Desc: "Install LuCI DAWN (opkg)"})
+		}
+	}
+
+	// 2. Asegurar wpad completo si solo hay wpad-basic/mini.
+	if sc.WpadVariant == "basic" || sc.WpadVariant == "mini" || sc.WpadVariant == "" {
+		pkg := "wpad-wolfssl"
+		if sc.Manager == "apk" {
+			pkg = "wpad-mbedtls"
+		}
+		ops = append(ops, executor.Op{Kind: installKind(sc.Manager), Args: map[string]string{"package": pkg}, Desc: "Install full wpad for DAWN"})
+	}
+
+	// 3. Asegurar la sección dawn.global (named) y options.
+	if len(sc.Global) == 0 {
+		ops = append(ops, executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "dawn", "section": "global", "type": "global"}, Desc: "Ensure DAWN global section"})
+	}
+	setDawnGlobalIfDiffers(&ops, sc, "kicking", d.Kicking)
+	setDawnGlobalIfDiffers(&ops, sc, "kicking_threshold", d.KickingThreshold)
+	setDawnGlobalIfDiffers(&ops, sc, "duration", d.Duration)
+	setDawnGlobalIfDiffers(&ops, sc, "min_number_to_kick", d.MinNumberToKick)
+	setDawnGlobalIfDiffers(&ops, sc, "bandwidth_threshold", d.BandwidthThreshold)
+	setDawnGlobalIfDiffers(&ops, sc, "eval_auth_req", d.EvalAuthReq)
+	setDawnGlobalIfDiffers(&ops, sc, "eval_assoc_req", d.EvalAssocReq)
+	setDawnGlobalIfDiffers(&ops, sc, "eval_probe_req", d.EvalProbeReq)
+	setDawnGlobalIfDiffers(&ops, sc, "network_option", "2")
+	setDawnGlobalIfDiffers(&ops, sc, "hostapd_dir", "/var/run/hostapd")
+	setDawnGlobalIfDiffers(&ops, sc, "set_hostapd_nr", "1")
+	setDawnGlobalIfDiffers(&ops, sc, "rrm_mode", "pat")
+	setDawnGlobalIfDiffers(&ops, sc, "tcp_port", d.TCPPort)
+	setDawnGlobalIfDiffers(&ops, sc, "shared_key", d.SharedKey)
+	setDawnGlobalIfDiffers(&ops, sc, "iv", d.IV)
+	if d.BroadcastIP != "" {
+		setDawnGlobalIfDiffers(&ops, sc, "broadcast_ip", d.BroadcastIP)
+	}
+
+	// 4. Wireless: aplicar baseline a cada SSID de modo AP.
+	for _, s := range sc.SSIDs {
+		if s.Mode != "ap" {
+			continue
+		}
+		if d.SSID != "" && s.SSID != d.SSID {
+			continue
+		}
+		sec := s.Section
+		setWirelessBoolIfDiffers(&ops, s.IEEE80211K, sec, "ieee80211k", d.IEEE80211K, true)
+		setWirelessBoolIfDiffers(&ops, s.IEEE80211R, sec, "ieee80211r", d.IEEE80211R, true)
+		setWirelessBoolIfDiffers(&ops, s.IEEE80211V, sec, "ieee80211v", d.IEEE80211V, true)
+		setWirelessBoolIfDiffers(&ops, s.BSSTransition, sec, "bss_transition", d.BSSTransition, true)
+		setWirelessBoolIfDiffers(&ops, s.FTOverDS, sec, "ft_over_ds", d.FTOverDS, false)
+		setWirelessBoolIfDiffers(&ops, s.FTPskGenerateLocal, sec, "ft_psk_generate_local", d.FTPskGenerateLocal, true)
+		if d.MobilityDomain != "" && s.MobilityDomain != d.MobilityDomain {
+			ops = append(ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": sec, "option": "mobility_domain", "value": d.MobilityDomain}, Desc: "Set mobility domain on " + sec})
+		}
+	}
+
+	// 5. Radios: random_bssid=0.
+	for _, r := range sc.Radios {
+		if r.RandomBSSID != "0" {
+			ops = append(ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": r.Section, "option": "random_bssid", "value": "0"}, Desc: "Disable random BSSID on " + r.Section})
+		}
+	}
+
+	if len(ops) == 0 {
+		return nil
+	}
+
+	ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "dawn"}, Desc: "Commit DAWN config"})
+	ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless config"})
+	ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "dawn", "action": "enable"}, Desc: "Enable DAWN on boot"})
+	ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "dawn", "action": "start"}, Desc: "Start DAWN"})
+	return ops
+}
+
+func setDawnGlobalIfDiffers(ops *[]executor.Op, sc DawnScenario, option, want string) {
+	if want == "" {
+		return
+	}
+	if sc.Global[option] == want {
+		return
+	}
+	*ops = append(*ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "dawn", "section": "global", "option": option, "value": want}, Desc: "Set DAWN " + option})
+}
+
+func setWirelessBoolIfDiffers(ops *[]executor.Op, current, sec, option string, want, defaultVal bool) {
+	val := boolString(want, defaultVal)
+	if current == val {
+		return
+	}
+	*ops = append(*ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": sec, "option": option, "value": val}, Desc: "Set " + option + " on " + sec})
+}
+
+func boolString(want, defaultVal bool) string {
+	if want || defaultVal {
+		return "1"
+	}
+	return "0"
+}
+
+func dawnDisableOps(sc DawnScenario) []executor.Op {
+	if !sc.DawnInstalled && len(sc.Global) == 0 {
+		return nil
+	}
+	return []executor.Op{
+		{Kind: "uci_set", Args: map[string]string{"config": "dawn", "section": "global", "option": "enabled", "value": "0"}, Desc: "Disable DAWN"},
+		{Kind: "uci_commit", Args: map[string]string{"config": "dawn"}, Desc: "Commit DAWN config"},
+		{Kind: "service", Args: map[string]string{"name": "dawn", "action": "stop"}, Desc: "Stop DAWN"},
+		{Kind: "service", Args: map[string]string{"name": "dawn", "action": "disable"}, Desc: "Disable DAWN on boot"},
+	}
+}
+
+func normalizeDawnDesired(d DawnDesired) DawnDesired {
+	if d.Kicking == "" {
+		d.Kicking = "3"
+	}
+	if d.KickingThreshold == "" {
+		d.KickingThreshold = "20"
+	}
+	if d.Duration == "" {
+		d.Duration = "150"
+	}
+	if d.MinNumberToKick == "" {
+		d.MinNumberToKick = "3"
+	}
+	if d.BandwidthThreshold == "" {
+		d.BandwidthThreshold = "6"
+	}
+	if d.EvalAuthReq == "" {
+		d.EvalAuthReq = "0"
+	}
+	if d.EvalAssocReq == "" {
+		d.EvalAssocReq = "0"
+	}
+	if d.EvalProbeReq == "" {
+		d.EvalProbeReq = "0"
+	}
+	if d.TCPPort == "" {
+		d.TCPPort = "1026"
+	}
+	return d
+}
+func installKind(manager string) string {
+	if manager == "apk" {
+		return "apk_install"
+	}
+	return "install"
+}
+
+// DawnHealthcheck verifica que DAWN responde y ve vecinos tras el apply.
+func DawnHealthcheck(run CommandRunner, host string) error {
+	out, err := run.Run(host, "ubus call dawn get_network", 5*time.Second)
+	if err != nil {
+		return fmt.Errorf("dawn get_network failed: %w", err)
+	}
+	out = strings.TrimSpace(out)
+	if out == "" || out == "{}" {
+		return fmt.Errorf("dawn get_network returned empty mesh")
+	}
+	return nil
+}
+
+// DawnDriftWarnings devuelve advertencias de inconsistencia legibles para la UI.
+func DawnDriftWarnings(d DawnDesired, sc DawnScenario) []string {
+	d = normalizeDawnDesired(d)
+	var warns []string
+	if !sc.DawnInstalled {
+		warns = append(warns, "DAWN no está instalado")
+	}
+	if !sc.HostapdDirOK {
+		warns = append(warns, "El directorio /var/run/hostapd no existe")
+	}
+	mdom := d.MobilityDomain
+	for _, s := range sc.SSIDs {
+		if s.Mode != "ap" {
+			continue
+		}
+		if d.SSID != "" && s.SSID != d.SSID {
+			continue
+		}
+		if mdom != "" && s.MobilityDomain != mdom {
+			warns = append(warns, "Dominio de movilidad inconsistente en "+s.Section)
+		}
+		if s.IEEE80211K != "1" {
+			warns = append(warns, "802.11k desactivado en "+s.Section)
+		}
+		if s.IEEE80211R != "1" {
+			warns = append(warns, "802.11r desactivado en "+s.Section)
+		}
+		if s.IEEE80211V != "1" {
+			warns = append(warns, "802.11v desactivado en "+s.Section)
+		}
+	}
+	for _, r := range sc.Radios {
+		if r.RandomBSSID != "0" {
+			warns = append(warns, "random_bssid activo en "+r.Section)
+		}
+	}
+	return warns
+}
+
+// DawnMethod devuelve active/inactive para la UI.
+func DawnMethod(sc DawnScenario) string {
+	if sc.DawnRunning {
+		return "active"
+	}
+	return "inactive"
+}
+
+// Int helpers para comparar valores numéricos si fuese necesario.
+func dawnInt(s string) int {
+	v, _ := strconv.Atoi(strings.TrimSpace(s))
+	return v
+}
+
+func validateDawnOps(ops []executor.Op) error {
+	for _, op := range ops {
+		if err := executor.Validate(op); err != nil {
+			return fmt.Errorf("%s: %w", op.Desc, err)
+		}
+	}
+	return nil
+}

+ 246 - 0
server-go/internal/orchestr/dawn_test.go

@@ -0,0 +1,246 @@
+package orchestr
+
+import (
+	"strings"
+	"testing"
+
+	"github.com/gnacho/netpulse/agent/executor"
+)
+
+const dawnProbeApkOK = `===PKG_MGR===
+apk
+===DAWN_INST===
+yes
+===DAWN_RUN===
+yes
+===WPAD===
+wpad-mbedtls-2025.05.11~5.5.11-1 aarch64_cortex-a53 {wpad} () installed
+===HOSTAPD_DIR===
+yes
+===DAWN_UCI===
+dawn.global=global
+dawn.global.kicking='3'
+dawn.global.kicking_threshold='20'
+dawn.global.duration='150'
+dawn.global.min_number_to_kick='3'
+dawn.global.bandwidth_threshold='6'
+dawn.global.eval_auth_req='0'
+dawn.global.eval_assoc_req='0'
+dawn.global.eval_probe_req='0'
+dawn.global.network_option='2'
+dawn.global.hostapd_dir='/var/run/hostapd'
+dawn.global.set_hostapd_nr='1'
+dawn.global.rrm_mode='pat'
+dawn.global.broadcast_ip='192.168.1.255'
+dawn.global.tcp_port='1026'
+dawn.global.shared_key='TemisciraDawn2026'
+dawn.global.iv='TemisciraDawn2026'
+===WIRELESS_UCI===
+wireless.temiscira2g=wifi-iface
+wireless.temiscira2g.device='radio0'
+wireless.temiscira2g.mode='ap'
+wireless.temiscira2g.ssid='temiscira'
+wireless.temiscira2g.ieee80211k='1'
+wireless.temiscira2g.ieee80211r='1'
+wireless.temiscira2g.ieee80211v='1'
+wireless.temiscira2g.bss_transition='1'
+wireless.temiscira2g.ft_over_ds='0'
+wireless.temiscira2g.ft_psk_generate_local='1'
+wireless.temiscira2g.mobility_domain='2025'
+wireless.radio0=wifi-device
+wireless.radio0.random_bssid='0'
+===END===`
+
+const dawnProbeOpkgMissing = `===PKG_MGR===
+opkg
+===DAWN_INST===
+no
+===DAWN_RUN===
+no
+===WPAD===
+wpad-basic - 2024.03.09~695a0ff9-1 - wpad-basic
+===HOSTAPD_DIR===
+no
+===DAWN_UCI===
+===WIRELESS_UCI===
+wireless.temiscira2g=wifi-iface
+wireless.temiscira2g.device='radio0'
+wireless.temiscira2g.mode='ap'
+wireless.temiscira2g.ssid='temiscira'
+wireless.temiscira2g.ieee80211k='0'
+wireless.temiscira2g.ieee80211r='0'
+wireless.temiscira2g.ieee80211v='0'
+wireless.temiscira2g.mobility_domain='2021'
+wireless.radio0=wifi-device
+wireless.radio0.random_bssid='1'
+===END===`
+
+func TestParseDawnApkOK(t *testing.T) {
+	sc := parseDawn(dawnProbeApkOK)
+	if sc.Manager != "apk" {
+		t.Errorf("Manager: got %q want apk", sc.Manager)
+	}
+	if !sc.DawnInstalled {
+		t.Error("DawnInstalled: esperaba true")
+	}
+	if !sc.DawnRunning {
+		t.Error("DawnRunning: esperaba true")
+	}
+	if sc.WpadVariant != "mbedtls" {
+		t.Errorf("WpadVariant: got %q want mbedtls", sc.WpadVariant)
+	}
+	if !sc.HostapdDirOK {
+		t.Error("HostapdDirOK: esperaba true")
+	}
+	if sc.Global["kicking"] != "3" {
+		t.Errorf("kicking: got %q want 3", sc.Global["kicking"])
+	}
+	if len(sc.SSIDs) != 1 {
+		t.Fatalf("SSIDs: got %d want 1", len(sc.SSIDs))
+	}
+	if sc.SSIDs[0].MobilityDomain != "2025" {
+		t.Errorf("mobility_domain: got %q want 2025", sc.SSIDs[0].MobilityDomain)
+	}
+	if len(sc.Radios) != 1 {
+		t.Fatalf("Radios: got %d want 1", len(sc.Radios))
+	}
+	if sc.Radios[0].RandomBSSID != "0" {
+		t.Errorf("random_bssid: got %q want 0", sc.Radios[0].RandomBSSID)
+	}
+}
+
+func TestParseDawnOpkgMissing(t *testing.T) {
+	sc := parseDawn(dawnProbeOpkgMissing)
+	if sc.Manager != "opkg" {
+		t.Errorf("Manager: got %q want opkg", sc.Manager)
+	}
+	if sc.DawnInstalled {
+		t.Error("DawnInstalled: esperaba false")
+	}
+	if sc.WpadVariant != "basic" {
+		t.Errorf("WpadVariant: got %q want basic", sc.WpadVariant)
+	}
+	if len(sc.SSIDs) != 1 || sc.SSIDs[0].IEEE80211K != "0" {
+		t.Error("esperaba 802.11k desactivado")
+	}
+	if sc.Radios[0].RandomBSSID != "1" {
+		t.Error("esperaba random_bssid=1")
+	}
+}
+
+func TestDawnOpsInstallAndConfigure(t *testing.T) {
+	sc := parseDawn(dawnProbeOpkgMissing)
+	ops := DawnOps(DawnDesired{
+		Enabled: true, SSID: "temiscira", MobilityDomain: "2025",
+		BroadcastIP: "192.168.1.255", SharedKey: "TemisciraDawn2026", IV: "TemisciraDawn2026",
+	}, sc)
+	if err := validateDawnOps(ops); err != nil {
+		t.Fatalf("ops no validan: %v", err)
+	}
+	kinds := dawnKindsOf(ops)
+	if !strings.Contains(kinds, "install") {
+		t.Error("falta install de dawn")
+	}
+	if !strings.Contains(kinds, "uci_set_named") {
+		t.Error("falta uci_set_named para dawn.global")
+	}
+	if !strings.Contains(kinds, "uci_set") {
+		t.Error("falta uci_set")
+	}
+	if !strings.Contains(kinds, "uci_commit") {
+		t.Error("falta uci_commit")
+	}
+	if !strings.Contains(kinds, "service") {
+		t.Error("falta service start/enable")
+	}
+	// Debe forzar wpad completo en opkg.
+	foundWpad := false
+	for _, o := range ops {
+		if o.Kind == "install" && o.Args["package"] == "wpad-wolfssl" {
+			foundWpad = true
+		}
+	}
+	if !foundWpad {
+		t.Error("falta install de wpad-wolfssl al tener wpad-basic")
+	}
+	// Debe activar 802.11k/r/v.
+	found80211r := false
+	for _, o := range ops {
+		if o.Kind == "uci_set" && o.Args["config"] == "wireless" && o.Args["option"] == "ieee80211r" && o.Args["value"] == "1" {
+			found80211r = true
+		}
+	}
+	if !found80211r {
+		t.Error("falta uci_set ieee80211r=1")
+	}
+	// Debe poner random_bssid=0.
+	foundRandom := false
+	for _, o := range ops {
+		if o.Kind == "uci_set" && o.Args["option"] == "random_bssid" && o.Args["value"] == "0" {
+			foundRandom = true
+		}
+	}
+	if !foundRandom {
+		t.Error("falta uci_set random_bssid=0")
+	}
+}
+
+func TestDawnOpsNoOpWhenMatches(t *testing.T) {
+	sc := parseDawn(dawnProbeApkOK)
+	ops := DawnOps(DawnDesired{
+		Enabled: true, SSID: "temiscira", MobilityDomain: "2025",
+		BroadcastIP: "192.168.1.255", SharedKey: "TemisciraDawn2026", IV: "TemisciraDawn2026",
+	}, sc)
+	if len(ops) != 0 {
+		t.Errorf("esperaba 0 ops cuando todo coincide, got %d: %v", len(ops), ops)
+	}
+}
+
+func TestDawnOpsDisable(t *testing.T) {
+	sc := parseDawn(dawnProbeApkOK)
+	ops := DawnOps(DawnDesired{Enabled: false}, sc)
+	if err := validateDawnOps(ops); err != nil {
+		t.Fatalf("ops disable no validan: %v", err)
+	}
+	found := false
+	for _, o := range ops {
+		if o.Kind == "uci_set" && o.Args["option"] == "enabled" && o.Args["value"] == "0" {
+			found = true
+		}
+	}
+	if !found {
+		t.Error("disable no pone enabled=0")
+	}
+}
+
+func TestDawnDriftWarnings(t *testing.T) {
+	sc := parseDawn(dawnProbeOpkgMissing)
+	warns := DawnDriftWarnings(DawnDesired{Enabled: true, SSID: "temiscira", MobilityDomain: "2025"}, sc)
+	joined := strings.Join(warns, ",")
+	if !strings.Contains(joined, "DAWN no está instalado") {
+		t.Error("falta advertencia de DAWN no instalado")
+	}
+	if !strings.Contains(joined, "random_bssid activo") {
+		t.Error("falta advertencia de random_bssid")
+	}
+	if !strings.Contains(joined, "802.11k desactivado") {
+		t.Error("falta advertencia de 802.11k")
+	}
+}
+
+func TestDawnMethod(t *testing.T) {
+	if DawnMethod(DawnScenario{DawnRunning: true}) != "active" {
+		t.Error("method active")
+	}
+	if DawnMethod(DawnScenario{}) != "inactive" {
+		t.Error("method inactive")
+	}
+}
+
+func dawnKindsOf(ops []executor.Op) string {
+	out := make([]string, len(ops))
+	for i, o := range ops {
+		out[i] = o.Kind
+	}
+	return strings.Join(out, ",")
+}

+ 1 - 0
server-go/internal/orchestr/modules.go

@@ -8,6 +8,7 @@
 //   - ddns      → ddns.go (Fase 17.3)
 //   - sqm       → sqm.go (Fase 17.4)
 //   - wireguard → wireguard.go (Fase 10.3)
+//   - dawn      → dawn.go (Fase 17.9)
 //
 // Fase 17.1: AdGuardOps usa el AdGuardScenario (probe SSH del servidor) para
 // elegir entre 4 métodos deterministas: apk | opkg | none (binario ya