Harden API surface and station/wifi backends

Bind to localhost by default and stop echoing backend errors (which can
embed credentials or low-level details) back over the API and log
broadcast. Validate hotspot SSID/passphrase/channel before writing
hostapd.conf and tighten its mode to 0600 since it stores the WPA PSK.
Restrict WebSocket upgrades to same-origin so a LAN browser can't be
turned into a proxy for the API.

Guard shared state: status reads/writes go through StatusMutex (the
periodic updater races with the toggle and status handlers otherwise),
broadcastToWebSockets no longer mutates the client map under RLock, and
station-event callbacks now run under SafeGo so a panic in app code can't
take down the daemon. Stop channels in hostapd, dhcp, and iwd signal
monitors are now closed under sync.Once to survive concurrent Stop calls.

App.Shutdown is idempotent and waits for the periodic loops before
closing backends, so signal-driven and deferred shutdowns no longer race.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
nemunaire 2026-05-01 21:56:50 +08:00
commit 07f8673f2f
14 changed files with 237 additions and 85 deletions

View file

@ -79,16 +79,31 @@ func UnregisterWebSocketClient(conn *websocket.Conn) {
clientsMutex.Unlock()
}
// broadcastToWebSockets sends a log entry to all connected WebSocket clients
// broadcastToWebSockets sends a log entry to all connected WebSocket clients.
// Dead clients are collected during the read pass and pruned under the write
// lock afterwards — mutating the map while only holding RLock would race
// with concurrent Register/Unregister and panic Go's map runtime.
func broadcastToWebSockets(entry models.LogEntry) {
clientsMutex.RLock()
defer clientsMutex.RUnlock()
clients := make([]*websocket.Conn, 0, len(websocketClients))
for client := range websocketClients {
err := client.WriteJSON(entry)
if err != nil {
clients = append(clients, client)
}
clientsMutex.RUnlock()
var dead []*websocket.Conn
for _, client := range clients {
if err := client.WriteJSON(entry); err != nil {
client.Close()
delete(websocketClients, client)
dead = append(dead, client)
}
}
if len(dead) > 0 {
clientsMutex.Lock()
for _, c := range dead {
delete(websocketClients, c)
}
clientsMutex.Unlock()
}
}