Skip to content

LAN-Orangutan is a self-hosted network discovery tool. Find every device on your LAN, label and group them, snapshot your network and compare it later, and get flagged when something unexpected shows up. Single binary, no setup, Tailscale built in. Built by 291 Group.

v3.4.2 checkpoint: snapshots, backup/restore, report, settings parity

filebaya0bbcfd550ea
diff --git a/.dockerignore b/.dockerignore
index ff3b42a..b08d608 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -12,7 +12,6 @@ orangutan
# Local data and editor state
data/
*.log
-.claude/
.vscode/
.idea/
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 07d1375..57eed90 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -84,7 +84,7 @@ jobs:
-X 'github.com/291-Group/LAN-Orangutan/internal/cli.Commit=${COMMIT}' \
-X 'github.com/291-Group/LAN-Orangutan/internal/cli.BuildDate=${BUILD_DATE}'"
- go build -ldflags "${LDFLAGS}" -o orangutan-${{ matrix.suffix }}${{ matrix.ext }} ./cmd/orangutan
+ go build -trimpath -ldflags "${LDFLAGS}" -o orangutan-${{ matrix.suffix }}${{ matrix.ext }} ./cmd/orangutan
- name: Upload artifact
uses: actions/upload-artifact@v4
diff --git a/Makefile b/Makefile
index a609ec4..7d7cbb1 100644
--- a/Makefile
+++ b/Makefile
@@ -18,7 +18,7 @@ all: build
# Build for current platform
build:
- go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY) ./cmd/orangutan
+ go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY) ./cmd/orangutan
# Build for all platforms
build-all: build-linux build-darwin build-windows
@@ -27,28 +27,28 @@ build-all: build-linux build-darwin build-windows
build-linux: build-linux-amd64 build-linux-arm64 build-linux-arm
build-linux-amd64:
- GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-amd64 ./cmd/orangutan
+ GOOS=linux GOARCH=amd64 go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-amd64 ./cmd/orangutan
build-linux-arm64:
- GOOS=linux GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-arm64 ./cmd/orangutan
+ GOOS=linux GOARCH=arm64 go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-arm64 ./cmd/orangutan
build-linux-arm:
- GOOS=linux GOARCH=arm GOARM=7 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-arm ./cmd/orangutan
+ GOOS=linux GOARCH=arm GOARM=7 go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-arm ./cmd/orangutan
# macOS builds
build-darwin: build-darwin-amd64 build-darwin-arm64
build-darwin-amd64:
- GOOS=darwin GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-darwin-amd64 ./cmd/orangutan
+ GOOS=darwin GOARCH=amd64 go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-darwin-amd64 ./cmd/orangutan
build-darwin-arm64:
- GOOS=darwin GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-darwin-arm64 ./cmd/orangutan
+ GOOS=darwin GOARCH=arm64 go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-darwin-arm64 ./cmd/orangutan
# Windows builds
build-windows: build-windows-amd64
build-windows-amd64:
- GOOS=windows GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-windows-amd64.exe ./cmd/orangutan
+ GOOS=windows GOARCH=amd64 go build -trimpath $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-windows-amd64.exe ./cmd/orangutan
# Refresh the embedded MAC vendor database from the IEEE registry
oui:
diff --git a/config.example.ini b/config.example.ini
index 5df5bcf..f2f31dd 100644
--- a/config.example.ini
+++ b/config.example.ini
@@ -54,10 +54,14 @@ scan_interval = 300
# Minimum time between manual scans to prevent abuse (default: 30 seconds)
min_scan_interval = 30
-# Enable port scanning (slower, more detailed)
+# Enable port scanning (slower, more detailed).
+# NOTE: reserved for a future release, not wired up yet. For port-based device
+# identification today, use enable_service_detection below. The value is accepted
+# and preserved.
enable_port_scan = false
-# Port range to scan when port scanning is enabled
+# Port range to scan when port scanning is enabled.
+# NOTE: reserved for a future release, not wired up yet (see enable_port_scan).
port_scan_range = 1-1024
# Identify devices more precisely with a light service probe (default: false).
@@ -100,14 +104,15 @@ enable_service_detection = false
only_configured_networks = false
[storage]
-# Maximum number of devices to track.
-# NOTE: reserved for a future release, not enforced yet. The device list is not
-# currently capped. The value is accepted and preserved.
+# Maximum number of devices to track. When the list grows past this, the devices
+# seen longest ago are dropped first to make room. Devices you have labelled,
+# grouped, or added notes to are always kept, and so are devices currently
+# online, so the count can sit above this when that many are pinned.
max_devices = 1000
-# Days to keep offline device history.
-# NOTE: reserved for a future release, not enforced yet. Offline devices are
-# currently kept until you delete them. The value is accepted and preserved.
+# Days to keep a device that has gone offline. A device not seen for this many
+# days is removed, unless you have labelled, grouped, or added notes to it, in
+# which case it is kept. Online devices are never removed.
retention_days = 90
# Data storage directory (default varies by OS)
diff --git a/internal/api/api.go b/internal/api/api.go
index 9926f8e..da041cf 100644
--- a/internal/api/api.go
+++ b/internal/api/api.go
@@ -6,6 +6,8 @@ import (
"encoding/csv"
"encoding/json"
"errors"
+ "fmt"
+ "net"
"net/http"
"sort"
"strings"
@@ -14,7 +16,9 @@ import (
"github.com/291-Group/LAN-Orangutan/internal/config"
"github.com/291-Group/LAN-Orangutan/internal/network"
+ "github.com/291-Group/LAN-Orangutan/internal/report"
"github.com/291-Group/LAN-Orangutan/internal/scanner"
+ "github.com/291-Group/LAN-Orangutan/internal/snapshot"
"github.com/291-Group/LAN-Orangutan/internal/storage"
"github.com/291-Group/LAN-Orangutan/internal/types"
)
@@ -41,9 +45,14 @@ type Handler struct {
// NewHandler creates a new API handler
func NewHandler(store *storage.Storage, cfg *config.Config) *Handler {
return &Handler{
- store: store,
- cfg: cfg,
- scanner: scanner.New(cfg.Scanning.MinScanInterval, cfg.Scanning.EnableServiceDetection),
+ store: store,
+ cfg: cfg,
+ // Honour a saved UI override for service detection at startup, falling
+ // back to the config default.
+ scanner: scanner.New(
+ cfg.Scanning.MinScanInterval,
+ store.ServiceDetectionEnabled(cfg.Scanning.EnableServiceDetection),
+ ),
scanCtx: context.Background(),
}
}
@@ -83,6 +92,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handleDevices(w, r)
case path == "device":
h.handleDevice(w, r)
+ case path == "devices/mark-expected":
+ h.handleMarkAllExpected(w, r)
case path == "networks":
h.handleNetworks(w, r)
case path == "scan":
@@ -95,6 +106,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handleScanCancel(w, r)
case path == "scan/continuous":
h.handleScanContinuous(w, r)
+ case path == "scan/service-detection":
+ h.handleScanServiceDetection(w, r)
+ case path == "scan/interval":
+ h.handleScanInterval(w, r)
+ case path == "scan/networks":
+ h.handleScanNetworks(w, r)
case path == "tailscale":
h.handleTailscale(w, r)
case path == "tailscale/connect":
@@ -107,6 +124,16 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.handleStatus(w, r)
case path == "settings":
h.handleSettings(w, r)
+ case path == "snapshots":
+ h.handleSnapshots(w, r)
+ case path == "snapshots/compare":
+ h.handleSnapshotCompare(w, r)
+ case path == "backup":
+ h.handleBackup(w, r)
+ case path == "backup/restore":
+ h.handleBackupRestore(w, r)
+ case path == "report":
+ h.handleReport(w, r)
default:
h.error(w, http.StatusNotFound, "endpoint not found")
}
@@ -184,10 +211,11 @@ func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {
case http.MethodPost:
var req struct {
- IP string `json:"ip"`
- Label *string `json:"label"`
- Notes *string `json:"notes"`
- Group *string `json:"group"`
+ IP string `json:"ip"`
+ Label *string `json:"label"`
+ Notes *string `json:"notes"`
+ Group *string `json:"group"`
+ Expected *bool `json:"expected"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.error(w, http.StatusBadRequest, "invalid JSON")
@@ -204,7 +232,7 @@ func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {
return
}
- if err := h.store.UpdateDeviceFields(ip, req.Label, req.Notes, req.Group); err != nil {
+ if err := h.store.UpdateDeviceFields(ip, req.Label, req.Notes, req.Group, req.Expected); err != nil {
h.error(w, http.StatusNotFound, err.Error())
return
}
@@ -227,6 +255,27 @@ func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {
}
}
+// handleMarkAllExpected handles POST /api/devices/mark-expected, setting or
+// clearing the Expected flag on every device at once to baseline the network.
+func (h *Handler) handleMarkAllExpected(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ var body struct {
+ Expected bool `json:"expected"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ h.error(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if err := h.store.MarkAllExpected(body.Expected); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not update devices: "+err.Error())
+ return
+ }
+ h.success(w, map[string]bool{"expected": body.Expected})
+}
+
// handleNetworks handles GET /api/networks
func (h *Handler) handleNetworks(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
@@ -239,7 +288,7 @@ func (h *Handler) handleNetworks(w http.ResponseWriter, r *http.Request) {
h.error(w, http.StatusInternalServerError, err.Error())
return
}
- h.success(w, network.WithConfigured(networks, network.Filter{Configured: h.cfg.Scanning.Networks, Excluded: h.cfg.Scanning.ExcludeNetworks, OnlyConfigured: h.cfg.Scanning.OnlyConfiguredNetworks}))
+ h.success(w, network.WithConfigured(networks, h.networkFilter()))
}
// handleScan handles GET /api/scan
@@ -332,7 +381,7 @@ func (h *Handler) scanAllNetworks(w http.ResponseWriter, r *http.Request) {
h.error(w, http.StatusInternalServerError, "failed to detect networks: "+err.Error())
return
}
- detected = network.WithConfigured(detected, network.Filter{Configured: h.cfg.Scanning.Networks, Excluded: h.cfg.Scanning.ExcludeNetworks, OnlyConfigured: h.cfg.Scanning.OnlyConfiguredNetworks})
+ detected = network.WithConfigured(detected, h.networkFilter())
if len(detected) == 0 {
h.error(w, http.StatusNotFound, "no networks detected")
return
@@ -413,7 +462,7 @@ func (h *Handler) resolveScanTargets(cidr string) ([]string, error) {
if err != nil {
return nil, errors.New("failed to detect networks: " + err.Error())
}
- detected = network.WithConfigured(detected, network.Filter{Configured: h.cfg.Scanning.Networks, Excluded: h.cfg.Scanning.ExcludeNetworks, OnlyConfigured: h.cfg.Scanning.OnlyConfiguredNetworks})
+ detected = network.WithConfigured(detected, h.networkFilter())
if len(detected) == 0 {
return nil, errors.New("no networks detected")
}
@@ -535,6 +584,346 @@ func (h *Handler) handleScanContinuous(w http.ResponseWriter, r *http.Request) {
}
}
+// handleScanServiceDetection handles GET/POST /api/scan/service-detection, the
+// runtime toggle for the opt-in port probe. Like continuous scan, the choice is
+// saved as an override in the data dir and survives a restart; the change is
+// pushed to the live scanner and takes effect on the next scan.
+func (h *Handler) handleScanServiceDetection(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ h.success(w, map[string]bool{"enabled": h.store.ServiceDetectionEnabled(h.cfg.Scanning.EnableServiceDetection)})
+ case http.MethodPost:
+ var body struct {
+ Enabled bool `json:"enabled"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ h.error(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if err := h.store.SetServiceDetection(body.Enabled); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not save setting: "+err.Error())
+ return
+ }
+ h.scanner.SetServiceDetection(body.Enabled)
+ h.success(w, map[string]bool{"enabled": body.Enabled})
+ default:
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// Bounds for the background scan interval override (seconds).
+const (
+ minScanIntervalSeconds = 10
+ maxScanIntervalSeconds = 86400 // one day
+)
+
+// handleScanInterval handles GET/POST /api/scan/interval, the runtime setting for
+// how often the background scanner runs, in seconds. Saved as an override in the
+// data dir; the scanner re-reads it before each cycle, so a change takes effect
+// on the next automatic scan.
+func (h *Handler) handleScanInterval(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ h.success(w, map[string]int{
+ "seconds": h.store.ScanIntervalOrDefault(h.cfg.Scanning.ScanInterval),
+ "default": h.cfg.Scanning.ScanInterval,
+ })
+ case http.MethodPost:
+ var body struct {
+ Seconds int `json:"seconds"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ h.error(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ secs := clampInt(body.Seconds, minScanIntervalSeconds, maxScanIntervalSeconds)
+ if err := h.store.SetScanInterval(secs); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not save setting: "+err.Error())
+ return
+ }
+ h.success(w, map[string]int{"seconds": secs, "default": h.cfg.Scanning.ScanInterval})
+ default:
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// handleScanNetworks handles GET/POST /api/scan/networks, the runtime settings
+// for which networks to scan: an extra include list, an exclude list, and
+// whether to scan only the configured ones. Saved as overrides in the data dir
+// and read fresh when scan targets are resolved, so a change applies on the next
+// scan. GET also returns the auto-detected networks so the editor can offer real
+// choices rather than a blank box.
+func (h *Handler) handleScanNetworks(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ h.success(w, h.networkSettingsView())
+
+ case http.MethodPost:
+ var body struct {
+ Networks *[]string `json:"networks"`
+ ExcludeNetworks *[]string `json:"exclude_networks"`
+ OnlyConfigured *bool `json:"only_configured"`
+ Reset bool `json:"reset"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ h.error(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if body.Reset {
+ if err := h.store.SetNetworkOverrides(nil, nil, nil); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not save settings: "+err.Error())
+ return
+ }
+ h.success(w, h.networkSettingsView())
+ return
+ }
+ if body.Networks != nil {
+ cleaned, err := validateCIDRs(*body.Networks)
+ if err != nil {
+ h.error(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ body.Networks = &cleaned
+ }
+ if body.ExcludeNetworks != nil {
+ cleaned, err := validateCIDRs(*body.ExcludeNetworks)
+ if err != nil {
+ h.error(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ body.ExcludeNetworks = &cleaned
+ }
+ if err := h.store.SetNetworkOverrides(body.Networks, body.ExcludeNetworks, body.OnlyConfigured); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not save settings: "+err.Error())
+ return
+ }
+ h.success(w, h.networkSettingsView())
+
+ default:
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// networkSettingsView returns the effective scan-target lists, whether an
+// override is in effect, and the currently detected networks for the editor to
+// offer as choices.
+func (h *Handler) networkSettingsView() map[string]interface{} {
+ f := h.networkFilter()
+ detected := []string{}
+ if nets, err := network.DetectNetworks(); err == nil {
+ for _, n := range nets {
+ detected = append(detected, n.CIDR)
+ }
+ }
+ nOver, eOver, oOver := h.store.GetNetworkOverrides()
+ // Never return a nil slice: the JSON should be [] so the UI can treat it as
+ // an empty list rather than null.
+ return map[string]interface{}{
+ "networks": nonNil(f.Configured),
+ "exclude_networks": nonNil(f.Excluded),
+ "only_configured": f.OnlyConfigured,
+ "detected": detected,
+ "overridden": nOver != nil || eOver != nil || oOver != nil,
+ }
+}
+
+// validateCIDRs checks each entry parses as a CIDR, returning them trimmed and
+// de-duplicated, or an error naming the first bad one. Blank entries are dropped.
+func validateCIDRs(list []string) ([]string, error) {
+ seen := map[string]bool{}
+ out := []string{}
+ for _, raw := range list {
+ c := strings.TrimSpace(raw)
+ if c == "" {
+ continue
+ }
+ if _, _, err := net.ParseCIDR(c); err != nil {
+ return nil, fmt.Errorf("%q is not a valid network (use CIDR form, e.g. 192.168.1.0/24)", c)
+ }
+ if !seen[c] {
+ seen[c] = true
+ out = append(out, c)
+ }
+ }
+ return out, nil
+}
+
+func nonNil(s []string) []string {
+ if s == nil {
+ return []string{}
+ }
+ return s
+}
+
+// handleSnapshots handles GET/POST/DELETE /api/snapshots: list saved snapshots,
+// save the current device list as a new one, or delete one by id.
+func (h *Handler) handleSnapshots(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ metas, err := h.store.ListSnapshots()
+ if err != nil {
+ h.error(w, http.StatusInternalServerError, "could not list snapshots: "+err.Error())
+ return
+ }
+ h.success(w, metas)
+
+ case http.MethodPost:
+ var body struct {
+ Name string `json:"name"`
+ }
+ // An empty body is fine; the name then defaults to the date and time.
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ meta, err := h.store.SaveSnapshot(body.Name)
+ if err != nil {
+ h.error(w, http.StatusInternalServerError, "could not save snapshot: "+err.Error())
+ return
+ }
+ h.success(w, meta)
+
+ case http.MethodDelete:
+ id := r.URL.Query().Get("id")
+ if id == "" {
+ h.error(w, http.StatusBadRequest, "id parameter required")
+ return
+ }
+ if err := h.store.DeleteSnapshot(id); err != nil {
+ h.error(w, http.StatusNotFound, "could not delete snapshot: "+err.Error())
+ return
+ }
+ h.success(w, map[string]string{"message": "snapshot deleted"})
+
+ default:
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// handleSnapshotCompare handles GET /api/snapshots/compare?from=<id>&to=<id|current>,
+// reporting what appeared, disappeared, and changed from the earlier list to the
+// later one. "to=current" compares against the live device list.
+func (h *Handler) handleSnapshotCompare(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ from := r.URL.Query().Get("from")
+ to := r.URL.Query().Get("to")
+ if from == "" || to == "" {
+ h.error(w, http.StatusBadRequest, "from and to parameters are required")
+ return
+ }
+
+ fromSnap, err := h.store.GetSnapshot(from)
+ if err != nil {
+ h.error(w, http.StatusNotFound, "'from' snapshot not found")
+ return
+ }
+
+ var after []types.Device
+ if to == "current" {
+ for _, d := range h.store.GetDevices() {
+ after = append(after, *d)
+ }
+ } else {
+ toSnap, err := h.store.GetSnapshot(to)
+ if err != nil {
+ h.error(w, http.StatusNotFound, "'to' snapshot not found")
+ return
+ }
+ after = toSnap.Devices
+ }
+
+ h.success(w, snapshot.Compare(fromSnap.Devices, after))
+}
+
+// handleBackup handles GET /api/backup, sending the whole device list, settings
+// overrides, and snapshots as a single downloadable JSON file. The password is
+// not included.
+func (h *Handler) handleBackup(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ data, err := json.MarshalIndent(h.store.ExportBackup(), "", " ")
+ if err != nil {
+ h.error(w, http.StatusInternalServerError, "could not build backup")
+ return
+ }
+ filename := "lan-orangutan-backup-" + time.Now().Format("2006-01-02") + ".json"
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Content-Disposition", `attachment; filename="`+filename+`"`)
+ _, _ = w.Write(data)
+}
+
+// handleBackupRestore handles POST /api/backup/restore, replacing the current
+// devices, settings and snapshots with those in the uploaded backup. It is
+// destructive; the UI confirms first.
+func (h *Handler) handleBackupRestore(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ var backup types.Backup
+ if err := json.NewDecoder(r.Body).Decode(&backup); err != nil {
+ h.error(w, http.StatusBadRequest, "that is not a valid backup file")
+ return
+ }
+ // A real backup always carries a creation time. Requiring it guards against
+ // restoring some unrelated JSON file and silently wiping everything.
+ if backup.CreatedAt.IsZero() {
+ h.error(w, http.StatusBadRequest, "that file does not look like a LAN Orangutan backup")
+ return
+ }
+ if err := h.store.ImportBackup(backup); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not restore: "+err.Error())
+ return
+ }
+ // Re-apply the settings that are pushed into live components (the storage
+ // limits and the scanner's service-detection flag) from the restored state.
+ if err := h.store.SetLimits(
+ h.store.RetentionDaysOrDefault(h.cfg.Storage.RetentionDays),
+ h.store.MaxDevicesOrDefault(h.cfg.Storage.MaxDevices),
+ ); err != nil {
+ h.error(w, http.StatusInternalServerError, "restored, but could not apply limits: "+err.Error())
+ return
+ }
+ h.scanner.SetServiceDetection(h.store.ServiceDetectionEnabled(h.cfg.Scanning.EnableServiceDetection))
+ h.success(w, map[string]string{"message": "backup restored"})
+}
+
+// handleReport handles GET /api/report, rendering a self-contained HTML summary
+// of the network as a single downloadable file to save or share.
+func (h *Handler) handleReport(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+ devices := h.store.GetDevices()
+ list := make([]types.Device, 0, len(devices))
+ for _, d := range devices {
+ dc := *d
+ dc.Vendor = scanner.ResolveVendor(dc.Vendor, dc.MAC)
+ list = append(list, dc)
+ }
+ sort.Slice(list, func(i, j int) bool { return list[i].IP < list[j].IP })
+
+ stats := h.store.GetStats()
+ networkCount := 0
+ if nets, err := network.DetectNetworks(); err == nil {
+ networkCount = len(network.WithConfigured(nets, h.networkFilter()))
+ }
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Content-Disposition", `attachment; filename="lan-orangutan-report-`+time.Now().Format("2006-01-02")+`.html"`)
+ _ = report.Render(w, report.Data{
+ GeneratedAt: time.Now(),
+ Total: stats.Total,
+ Online: stats.Online,
+ Offline: stats.Offline,
+ NetworkCount: networkCount,
+ Devices: list,
+ })
+}
+
// scanNetwork scans a single network and merges the results into storage.
func (h *Handler) scanNetwork(ctx context.Context, cidr string) (*types.ScanResult, error) {
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
@@ -633,27 +1022,112 @@ func (h *Handler) handleStatus(w http.ResponseWriter, r *http.Request) {
h.success(w, status)
}
-// handleSettings handles GET/POST /api/settings
+// Bounds for the editable numeric settings. A value of 0 turns the limit off
+// (keep devices forever / no cap); the upper bounds guard against absurd input.
+const (
+ maxRetentionDays = 36500 // 100 years
+ maxMaxDevicesCap = 1000000
+)
+
+// handleSettings handles GET/POST /api/settings.
+//
+// Settings the user edits from the dashboard are stored as overrides in the data
+// directory, never written back to config.ini, so a file the user maintains by
+// hand is left untouched. GET reports each value, its config default, and whether
+// an override is in effect; POST saves overrides and applies them immediately.
+// Only the storage limits are editable so far; scan interval and theme are
+// reported for information.
func (h *Handler) handleSettings(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
- settings := map[string]interface{}{
- "theme": h.cfg.UI.Theme,
- "scan_interval": h.cfg.Scanning.ScanInterval,
- "retention_days": h.cfg.Storage.RetentionDays,
- }
- h.success(w, settings)
+ h.success(w, h.settingsView())
case http.MethodPost:
- // Settings update would require config file write
- // For now, return not implemented
- h.error(w, http.StatusNotImplemented, "settings update not yet implemented")
+ // Both fields are sent every time: a number sets the override, JSON null
+ // clears it (falling back to the config default).
+ var body struct {
+ RetentionDays *int `json:"retention_days"`
+ MaxDevices *int `json:"max_devices"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ h.error(w, http.StatusBadRequest, "invalid JSON")
+ return
+ }
+ if body.RetentionDays != nil {
+ v := clampInt(*body.RetentionDays, 0, maxRetentionDays)
+ body.RetentionDays = &v
+ }
+ if body.MaxDevices != nil {
+ v := clampInt(*body.MaxDevices, 0, maxMaxDevicesCap)
+ body.MaxDevices = &v
+ }
+ if err := h.store.SetLimitOverrides(body.RetentionDays, body.MaxDevices); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not save settings: "+err.Error())
+ return
+ }
+ // Apply immediately so the new retention window and cap take effect now,
+ // not just on the next scan.
+ if err := h.store.SetLimits(
+ h.store.RetentionDaysOrDefault(h.cfg.Storage.RetentionDays),
+ h.store.MaxDevicesOrDefault(h.cfg.Storage.MaxDevices),
+ ); err != nil {
+ h.error(w, http.StatusInternalServerError, "could not apply settings: "+err.Error())
+ return
+ }
+ h.success(w, h.settingsView())
default:
h.error(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
+// settingsView builds the current effective settings for the UI: each editable
+// value, its config default, and whether a UI override is in effect.
+func (h *Handler) settingsView() map[string]interface{} {
+ rOver, mOver := h.store.GetLimitOverrides()
+ field := func(override *int, def int) map[string]interface{} {
+ return map[string]interface{}{
+ "value": valueOr(override, def),
+ "default": def,
+ "overridden": override != nil,
+ }
+ }
+ return map[string]interface{}{
+ "retention_days": field(rOver, h.cfg.Storage.RetentionDays),
+ "max_devices": field(mOver, h.cfg.Storage.MaxDevices),
+ // Reported for information; not editable from the UI yet.
+ "scan_interval": h.cfg.Scanning.ScanInterval,
+ "theme": h.cfg.UI.Theme,
+ }
+}
+
+func clampInt(v, lo, hi int) int {
+ if v < lo {
+ return lo
+ }
+ if v > hi {
+ return hi
+ }
+ return v
+}
+
+func valueOr(p *int, def int) int {
+ if p != nil {
+ return *p
+ }
+ return def
+}
+
+// networkFilter builds the effective scan-target filter, preferring the UI
+// overrides over the configured defaults.
+func (h *Handler) networkFilter() network.Filter {
+ return network.Filter{
+ Configured: h.store.NetworksOrDefault(h.cfg.Scanning.Networks),
+ Excluded: h.store.ExcludeNetworksOrDefault(h.cfg.Scanning.ExcludeNetworks),
+ OnlyConfigured: h.store.OnlyConfiguredOrDefault(h.cfg.Scanning.OnlyConfiguredNetworks),
+ }
+}
+
// success sends a successful JSON response
func (h *Handler) success(w http.ResponseWriter, data interface{}) {
resp := types.APIResponse{
diff --git a/internal/api/scanjob.go b/internal/api/scanjob.go
index 1c418e0..9f3ed3c 100644
--- a/internal/api/scanjob.go
+++ b/internal/api/scanjob.go
@@ -256,11 +256,7 @@ func (j *scanJob) adopt() {
// cancelled. A non-positive interval disables it. The ticker always runs so the
// user can switch continuous scanning on and off at runtime; runBackgroundScan
// skips the actual scan while the setting is off.
-func (h *Handler) StartBackgroundScanner(ctx context.Context, interval time.Duration) {
- if interval <= 0 {
- return
- }
-
+func (h *Handler) StartBackgroundScanner(ctx context.Context) {
go func() {
// Scan shortly after startup so a freshly started server does not sit
// empty until the first interval elapses.
@@ -273,19 +269,37 @@ func (h *Handler) StartBackgroundScanner(ctx context.Context, interval time.Dura
}
h.runBackgroundScan()
- ticker := time.NewTicker(interval)
- defer ticker.Stop()
+ // The interval is read fresh before each wait, so a change from the
+ // Settings page takes effect on the next cycle without a restart. A
+ // per-cycle timer rather than a fixed ticker is what makes that possible.
for {
+ timer := time.NewTimer(h.backgroundScanInterval())
select {
case <-ctx.Done():
+ timer.Stop()
return
- case <-ticker.C:
+ case <-timer.C:
h.runBackgroundScan()
}
}
}()
}
+// minBackgroundScanSeconds floors the automatic scan interval so a stray small
+// override cannot spin the loop; the per-network rate limit already prevents any
+// one network from being scanned more often than min_scan_interval.
+const minBackgroundScanSeconds = 10
+
+// backgroundScanInterval is how long to wait between automatic scans: the UI
+// override if set, otherwise the configured interval, floored for safety.
+func (h *Handler) backgroundScanInterval() time.Duration {
+ secs := h.store.ScanIntervalOrDefault(h.cfg.Scanning.ScanInterval)
+ if secs < minBackgroundScanSeconds {
+ secs = minBackgroundScanSeconds
+ }
+ return time.Duration(secs) * time.Second
+}
+
// runBackgroundScan starts one scan of all detected networks, unless a scan is
// already running. The job itself skips any network that was scanned too
// recently, so this never scans a network more often than the rate limit
diff --git a/internal/cli/filter.go b/internal/cli/filter.go
new file mode 100644
index 0000000..b95ebb9
--- /dev/null
+++ b/internal/cli/filter.go
@@ -0,0 +1,19 @@
+package cli
+
+import (
+ "github.com/291-Group/LAN-Orangutan/internal/config"
+ "github.com/291-Group/LAN-Orangutan/internal/network"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+)
+
+// networkFilter builds the effective scan-target filter for CLI commands,
+// preferring the UI overrides (saved in the data dir) over the config defaults,
+// so the command line agrees with the dashboard about which networks are in
+// scope.
+func networkFilter(store *storage.Storage, cfg *config.Config) network.Filter {
+ return network.Filter{
+ Configured: store.NetworksOrDefault(cfg.Scanning.Networks),
+ Excluded: store.ExcludeNetworksOrDefault(cfg.Scanning.ExcludeNetworks),
+ OnlyConfigured: store.OnlyConfiguredOrDefault(cfg.Scanning.OnlyConfiguredNetworks),
+ }
+}
diff --git a/internal/cli/networks.go b/internal/cli/networks.go
index 1dbd634..3b7edba 100644
--- a/internal/cli/networks.go
+++ b/internal/cli/networks.go
@@ -6,6 +6,7 @@ import (
"github.com/spf13/cobra"
"github.com/291-Group/LAN-Orangutan/internal/network"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
)
var networksCmd = &cobra.Command{
@@ -16,11 +17,22 @@ var networksCmd = &cobra.Command{
func runNetworks(cmd *cobra.Command, args []string) error {
networks, err := network.DetectNetworks()
- networks = network.WithConfigured(networks, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})
if err != nil {
return fmt.Errorf("failed to detect networks: %w", err)
}
+ // Resolve the effective filter, honouring any UI override saved in the data
+ // directory; fall back to the config values if the store cannot be opened.
+ filter := network.Filter{
+ Configured: cfg.Scanning.Networks,
+ Excluded: cfg.Scanning.ExcludeNetworks,
+ OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks,
+ }
+ if store, serr := storage.New(cfg.DevicesFile(), cfg.StateFile()); serr == nil {
+ filter = networkFilter(store, cfg)
+ }
+ networks = network.WithConfigured(networks, filter)
+
if len(networks) == 0 {
fmt.Println("No networks detected")
return nil
diff --git a/internal/cli/scan.go b/internal/cli/scan.go
index 9e754cf..8745fb8 100644
--- a/internal/cli/scan.go
+++ b/internal/cli/scan.go
@@ -30,6 +30,15 @@ func runScan(cmd *cobra.Command, args []string) error {
if err != nil {
return fmt.Errorf("failed to initialize storage: %w", err)
}
+ // Apply the retention window and device cap (a UI override wins over the
+ // config default), so a CLI scan bounds the stored list the same way the
+ // server does.
+ if err := store.SetLimits(
+ store.RetentionDaysOrDefault(cfg.Storage.RetentionDays),
+ store.MaxDevicesOrDefault(cfg.Storage.MaxDevices),
+ ); err != nil {
+ return fmt.Errorf("failed to apply storage limits: %w", err)
+ }
// Create scanner
s := scanner.New(cfg.Scanning.MinScanInterval, cfg.Scanning.EnableServiceDetection)
@@ -40,7 +49,7 @@ func runScan(cmd *cobra.Command, args []string) error {
if len(args) == 0 || args[0] == "" {
// Scan first detected network
detected, err := network.DetectNetworks()
- detected = network.WithConfigured(detected, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})
+ detected = network.WithConfigured(detected, networkFilter(store, cfg))
if err != nil {
return fmt.Errorf("failed to detect networks: %w", err)
}
@@ -60,7 +69,7 @@ func runScan(cmd *cobra.Command, args []string) error {
} else if args[0] == "all" {
// Scan all detected networks
detected, err := network.DetectNetworks()
- detected = network.WithConfigured(detected, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})
+ detected = network.WithConfigured(detected, networkFilter(store, cfg))
if err != nil {
return fmt.Errorf("failed to detect networks: %w", err)
}
diff --git a/internal/cli/serve.go b/internal/cli/serve.go
index 3caa2aa..6631410 100644
--- a/internal/cli/serve.go
+++ b/internal/cli/serve.go
@@ -74,6 +74,15 @@ func runServe(cmd *cobra.Command, args []string) error {
if err != nil {
return fmt.Errorf("failed to initialize storage: %w", err)
}
+ // Apply the retention window and device cap, preferring a UI override over
+ // the config default. This heals an existing install on startup and then
+ // bounds the list on every scan.
+ if err := store.SetLimits(
+ store.RetentionDaysOrDefault(cfg.Storage.RetentionDays),
+ store.MaxDevicesOrDefault(cfg.Storage.MaxDevices),
+ ); err != nil {
+ return fmt.Errorf("failed to apply storage limits: %w", err)
+ }
// A password from the config file or environment wins. Otherwise fall back
// to one created earlier through the setup page.
@@ -105,7 +114,7 @@ func runServe(cmd *cobra.Command, args []string) error {
scanCtx, scanCancel := context.WithCancel(context.Background())
defer scanCancel()
apiHandler.SetScanContext(scanCtx)
- apiHandler.StartBackgroundScanner(scanCtx, time.Duration(cfg.Scanning.ScanInterval)*time.Second)
+ apiHandler.StartBackgroundScanner(scanCtx)
// Protected routes.
mux.Handle("/api/", authn.Middleware(apiHandler))
@@ -213,7 +222,7 @@ func runServe(cmd *cobra.Command, args []string) error {
// virtual gateway answers probes for addresses that do not exist. Say so
// before the user runs a scan and trusts the results.
if detected, err := network.DetectNetworks(); err == nil {
- detected = network.WithConfigured(detected, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})
+ detected = network.WithConfigured(detected, networkFilter(store, cfg))
if warning := network.IsolationWarning(detected); warning != "" {
fmt.Println()
fmt.Println(" ┌─────────────────────────────────────────────────────────────┐")
diff --git a/internal/cli/status.go b/internal/cli/status.go
index 7df9cb9..a32c2a2 100644
--- a/internal/cli/status.go
+++ b/internal/cli/status.go
@@ -51,7 +51,7 @@ func runStatus(cmd *cobra.Command, args []string) error {
fmt.Println()
fmt.Println("Networks:")
networks, err := network.DetectNetworks()
- networks = network.WithConfigured(networks, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})
+ networks = network.WithConfigured(networks, networkFilter(store, cfg))
if err != nil {
fmt.Printf(" Error detecting: %v\n", err)
} else {
diff --git a/internal/network/tailscale_control.go b/internal/network/tailscale_control.go
index 708f3e5..bb6ab64 100644
--- a/internal/network/tailscale_control.go
+++ b/internal/network/tailscale_control.go
@@ -20,20 +20,26 @@ import (
// detected and returned as soon as it appears, well before this fires.
const tailscaleUpTimeout = 20 * time.Second
-// loginURLPattern finds a candidate sign-in URL in the output that `tailscale
-// up` prints when the machine is not yet authenticated to a tailnet.
-var loginURLPattern = regexp.MustCompile(`https://login\.tailscale\.com/\S+`)
+// loginURLPattern captures the sign-in URL that `tailscale up` prints on its own
+// (indented) line when the machine is not yet authenticated to a tailnet. It is
+// anchored to the start of a line in multi-line mode (?m) and captures the URL,
+// so it can only match a URL that begins a line, never one embedded mid-line
+// inside some larger string. That anchoring is what the CodeQL
+// go/regex/missing-regexp-anchor rule asks for; the host is still re-checked
+// below with a real URL parse, which remains the actual security boundary.
+var loginURLPattern = regexp.MustCompile(`(?m)^[ \t]*(https://login\.tailscale\.com/\S+)`)
// extractLoginURL pulls the Tailscale sign-in URL out of `tailscale up` output.
-// The regex locates a candidate in the multi-line output, and its host is then
+// The regex locates a candidate at the start of a line, and its host is then
// confirmed with a real URL parse rather than trusted from the pattern, so only
// a genuine https://login.tailscale.com URL is ever returned. It returns "" when
// there is no such URL.
func extractLoginURL(text string) string {
- candidate := loginURLPattern.FindString(text)
- if candidate == "" {
+ m := loginURLPattern.FindStringSubmatch(text)
+ if m == nil {
return ""
}
+ candidate := m[1]
u, err := url.Parse(candidate)
if err != nil || u.Scheme != "https" || u.Hostname() != "login.tailscale.com" {
return ""
diff --git a/internal/network/tailscale_control_test.go b/internal/network/tailscale_control_test.go
index c8def3f..83a6661 100644
--- a/internal/network/tailscale_control_test.go
+++ b/internal/network/tailscale_control_test.go
@@ -12,18 +12,18 @@ func TestLoginURLPattern(t *testing.T) {
https://login.tailscale.com/a/1234567890abcdef
Success.`
- got := loginURLPattern.FindString(sample)
+ m := loginURLPattern.FindStringSubmatch(sample)
want := "https://login.tailscale.com/a/1234567890abcdef"
- if got != want {
- t.Errorf("extracted %q, want %q", got, want)
+ if m == nil || m[1] != want {
+ t.Errorf("extracted %v, want %q", m, want)
}
}
func TestLoginURLPatternAbsentWhenConnected(t *testing.T) {
// A normal reconnect prints no login URL.
for _, s := range []string{"", "Success.", "some other output"} {
- if url := loginURLPattern.FindString(s); url != "" {
- t.Errorf("found a login URL in %q where there is none: %q", s, url)
+ if m := loginURLPattern.FindStringSubmatch(s); m != nil {
+ t.Errorf("found a login URL in %q where there is none: %q", s, m[1])
}
}
}
@@ -111,8 +111,17 @@ func TestExtractLoginURL(t *testing.T) {
t.Errorf("a bare hostname is not a login URL, got %q", got)
}
- // A valid URL with a query is accepted; the host parse pins it to Tailscale.
+ // A valid URL at the start of a line is accepted; the host parse pins it to
+ // Tailscale and \S+ stops the capture at the trailing space.
if got := extractLoginURL("https://login.tailscale.com/path?q=1 rest"); got != "https://login.tailscale.com/path?q=1" {
t.Errorf("valid URL rejected, got %q", got)
}
+
+ // A genuine Tailscale URL embedded mid-line, not at the start of a line, is
+ // not extracted. Anchoring the pattern to the line start is what guarantees
+ // this, so a URL cannot be picked up from an unexpected position in the
+ // output.
+ if got := extractLoginURL("visit https://login.tailscale.com/a/deadbeef now"); got != "" {
+ t.Errorf("a mid-line URL should not be extracted, got %q", got)
+ }
}
diff --git a/internal/report/report.go b/internal/report/report.go
new file mode 100644
index 0000000..57c49dd
--- /dev/null
+++ b/internal/report/report.go
@@ -0,0 +1,92 @@
+// Package report renders a self-contained HTML summary of the network that can
+// be saved and shared as a single file (no external assets).
+package report
+
+import (
+ "html/template"
+ "io"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// Data is everything the report template needs. Devices are expected already
+// sorted and with their vendor resolved by the caller.
+type Data struct {
+ GeneratedAt time.Time
+ Total int
+ Online int
+ Offline int
+ NetworkCount int
+ Devices []types.Device
+}
+
+var tmpl = template.Must(template.New("report").Parse(reportHTML))
+
+// Render writes the HTML report to w.
+func Render(w io.Writer, d Data) error {
+ return tmpl.Execute(w, d)
+}
+
+const reportHTML = `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>LAN Orangutan &mdash; Network Report</title>
+<style>
+ :root { --fg:#16202e; --muted:#56637a; --border:#e4ecf6; --bg:#ffffff; --green:#2c9e6b; --grey:#8592a6; }
+ * { box-sizing: border-box; }
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: var(--fg); background: var(--bg); margin: 0; padding: 2rem; line-height: 1.5; }
+ .wrap { max-width: 980px; margin: 0 auto; }
+ h1 { font-size: 1.5rem; margin: 0 0 0.25rem; }
+ .sub { color: var(--muted); font-size: 0.9rem; margin: 0 0 1.5rem; }
+ .stats { display: flex; flex-wrap: wrap; gap: 1.75rem; margin: 0 0 1.5rem; padding: 1rem 1.25rem; border: 1px solid var(--border); border-radius: 12px; }
+ .stat b { font-size: 1.35rem; }
+ .stat span { color: var(--muted); font-size: 0.85rem; margin-left: 0.35rem; }
+ table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
+ th, td { text-align: left; padding: 0.5rem 0.6rem; border-bottom: 1px solid var(--border); vertical-align: top; }
+ th { color: var(--muted); font-weight: 600; text-transform: uppercase; font-size: 0.72rem; letter-spacing: 0.03em; }
+ td.mono { font-family: 'SF Mono', 'Fira Code', monospace; }
+ .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; }
+ .dot.on { background: var(--green); }
+ .dot.off { background: transparent; border: 1.5px solid var(--grey); }
+ .muted { color: var(--muted); }
+ footer { margin-top: 2rem; color: var(--muted); font-size: 0.8rem; }
+ @media print { body { padding: 0; } .stats { break-inside: avoid; } thead { display: table-header-group; } }
+</style>
+</head>
+<body>
+<div class="wrap">
+ <h1>&#129446; LAN Orangutan &mdash; Network Report</h1>
+ <p class="sub">Generated {{.GeneratedAt.Format "Mon, 02 Jan 2006 at 15:04"}}</p>
+ <div class="stats">
+ <div class="stat"><b>{{.Total}}</b><span>devices</span></div>
+ <div class="stat"><b>{{.Online}}</b><span>online</span></div>
+ <div class="stat"><b>{{.Offline}}</b><span>offline</span></div>
+ <div class="stat"><b>{{.NetworkCount}}</b><span>network{{if ne .NetworkCount 1}}s{{end}}</span></div>
+ </div>
+ <table>
+ <thead>
+ <tr><th></th><th>IP Address</th><th>Hostname</th><th>Type</th><th>MAC</th><th>Vendor</th><th>Group</th><th>Last Seen</th></tr>
+ </thead>
+ <tbody>
+ {{range .Devices}}
+ <tr>
+ <td><span class="dot {{if .IsOnline}}on{{else}}off{{end}}" title="{{if .IsOnline}}online{{else}}offline{{end}}"></span></td>
+ <td class="mono">{{.IP}}</td>
+ <td>{{if .Hostname}}{{.Hostname}}{{else}}<span class="muted">&mdash;</span>{{end}}</td>
+ <td>{{if .Type}}{{.Type}}{{else}}<span class="muted">&mdash;</span>{{end}}</td>
+ <td class="mono">{{if .MAC}}{{.MAC}}{{else}}<span class="muted">&mdash;</span>{{end}}</td>
+ <td>{{if .Vendor}}{{.Vendor}}{{else}}<span class="muted">&mdash;</span>{{end}}</td>
+ <td>{{if .Group}}{{.Group}}{{else}}<span class="muted">&mdash;</span>{{end}}</td>
+ <td class="muted">{{.LastSeen.Format "2006-01-02 15:04"}}</td>
+ </tr>
+ {{end}}
+ </tbody>
+ </table>
+ <footer>Generated by LAN Orangutan &middot; 291 Group</footer>
+</div>
+</body>
+</html>
+`
diff --git a/internal/report/report_test.go b/internal/report/report_test.go
new file mode 100644
index 0000000..bb216e8
--- /dev/null
+++ b/internal/report/report_test.go
@@ -0,0 +1,39 @@
+package report
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+func TestRenderContainsDevicesAndStats(t *testing.T) {
+ var b strings.Builder
+ err := Render(&b, Data{
+ GeneratedAt: time.Date(2026, 1, 2, 15, 4, 0, 0, time.UTC),
+ Total: 2,
+ Online: 1,
+ Offline: 1,
+ NetworkCount: 1,
+ Devices: []types.Device{
+ {IP: "192.168.1.5", MAC: "aa:bb:cc:00:00:01", Hostname: "nas", Vendor: "Synology", LastSeen: time.Now()},
+ {IP: "192.168.1.6", LastSeen: time.Now()},
+ },
+ })
+ if err != nil {
+ t.Fatalf("Render: %v", err)
+ }
+ out := b.String()
+ for _, want := range []string{"<!doctype html>", "Network Report", "192.168.1.5", "nas", "Synology", "<b>2</b>", "</body>", "</html>"} {
+ if !strings.Contains(out, want) {
+ t.Errorf("report missing %q", want)
+ }
+ }
+ // A value with markup must be escaped, not injected.
+ var b2 strings.Builder
+ _ = Render(&b2, Data{Devices: []types.Device{{IP: "10.0.0.1", Hostname: "<script>x</script>", LastSeen: time.Now()}}})
+ if strings.Contains(b2.String(), "<script>x</script>") {
+ t.Error("hostname was not HTML-escaped in the report")
+ }
+}
diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go
index 3a4ceb3..bf883ef 100644
--- a/internal/scanner/scanner.go
+++ b/internal/scanner/scanner.go
@@ -9,6 +9,7 @@ import (
"os/exec"
"runtime"
"strings"
+ "sync"
"time"
"github.com/291-Group/LAN-Orangutan/internal/network"
@@ -19,7 +20,10 @@ import (
type Scanner struct {
minInterval time.Duration
// serviceDetection turns on the opt-in probe that identifies devices by
- // their open ports. Off by default; a scan stays a quiet ping sweep.
+ // their open ports. Off by default; a scan stays a quiet ping sweep. It can
+ // be toggled at runtime from the Settings page, and a scan may be running on
+ // another goroutine when that happens, so it is guarded by mu.
+ mu sync.RWMutex
serviceDetection bool
}
@@ -32,6 +36,21 @@ func New(minIntervalSeconds int, serviceDetection bool) *Scanner {
}
}
+// SetServiceDetection turns the opt-in port probe on or off. The change takes
+// effect on the next scan.
+func (s *Scanner) SetServiceDetection(on bool) {
+ s.mu.Lock()
+ s.serviceDetection = on
+ s.mu.Unlock()
+}
+
+// serviceDetectionEnabled reports whether the port probe is currently on.
+func (s *Scanner) serviceDetectionEnabled() bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.serviceDetection
+}
+
// nmapRun represents the root element of nmap XML output
type nmapRun struct {
XMLName xml.Name `xml:"nmaprun"`
@@ -114,7 +133,7 @@ func (s *Scanner) Scan(ctx context.Context, cidr string) (*types.ScanResult, err
// With service detection on, probe each device's well-known ports to refine
// its type and flag a web interface. This is the only step that sends more
// than a ping or a name query, so it stays behind the opt-in flag.
- if s.serviceDetection {
+ if s.serviceDetectionEnabled() {
enrichWithServices(ctx, devices)
}
diff --git a/internal/snapshot/diff.go b/internal/snapshot/diff.go
new file mode 100644
index 0000000..34b4bb6
--- /dev/null
+++ b/internal/snapshot/diff.go
@@ -0,0 +1,93 @@
+// Package snapshot compares two device lists to report what changed on the
+// network between them.
+package snapshot
+
+import (
+ "sort"
+ "strings"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// Diff is the result of comparing an earlier device list with a later one.
+type Diff struct {
+ Added []types.Device `json:"added"`
+ Removed []types.Device `json:"removed"`
+ Changed []DeviceChange `json:"changed"`
+}
+
+// DeviceChange is a device present in both lists whose identifying details
+// differ, with the names of the fields that changed.
+type DeviceChange struct {
+ Before types.Device `json:"before"`
+ After types.Device `json:"after"`
+ Fields []string `json:"fields"`
+}
+
+// key identifies a device across two lists. MAC is preferred because it is
+// stable when a device only changes IP (so that reads as a change, not a
+// removal plus an addition); IP is the fallback for a device with no MAC.
+func key(d types.Device) string {
+ if d.MAC != "" {
+ return "mac:" + strings.ToLower(d.MAC)
+ }
+ return "ip:" + d.IP
+}
+
+// changedFields lists the identifying fields that differ between two matched
+// devices. Only network-facing details are compared: not LastSeen (which always
+// moves) and not the user's own label, notes, or group.
+func changedFields(before, after types.Device) []string {
+ var f []string
+ if before.IP != after.IP {
+ f = append(f, "ip")
+ }
+ if before.Hostname != after.Hostname {
+ f = append(f, "hostname")
+ }
+ if before.Vendor != after.Vendor {
+ f = append(f, "vendor")
+ }
+ if before.Type != after.Type {
+ f = append(f, "type")
+ }
+ return f
+}
+
+// Compare reports what appeared, disappeared, and changed going from the earlier
+// list to the later one. The result slices are never nil and are sorted by IP so
+// the output is stable.
+func Compare(before, after []types.Device) Diff {
+ beforeByKey := make(map[string]types.Device, len(before))
+ for _, d := range before {
+ beforeByKey[key(d)] = d
+ }
+ afterByKey := make(map[string]types.Device, len(after))
+ for _, d := range after {
+ afterByKey[key(d)] = d
+ }
+
+ diff := Diff{Added: []types.Device{}, Removed: []types.Device{}, Changed: []DeviceChange{}}
+
+ for k, a := range afterByKey {
+ b, ok := beforeByKey[k]
+ if !ok {
+ diff.Added = append(diff.Added, a)
+ continue
+ }
+ if fields := changedFields(b, a); len(fields) > 0 {
+ diff.Changed = append(diff.Changed, DeviceChange{Before: b, After: a, Fields: fields})
+ }
+ }
+ for k, b := range beforeByKey {
+ if _, ok := afterByKey[k]; !ok {
+ diff.Removed = append(diff.Removed, b)
+ }
+ }
+
+ sort.Slice(diff.Added, func(i, j int) bool { return diff.Added[i].IP < diff.Added[j].IP })
+ sort.Slice(diff.Removed, func(i, j int) bool { return diff.Removed[i].IP < diff.Removed[j].IP })
+ sort.Slice(diff.Changed, func(i, j int) bool { return diff.Changed[i].After.IP < diff.Changed[j].After.IP })
+
+ return diff
+}
diff --git a/internal/snapshot/diff_test.go b/internal/snapshot/diff_test.go
new file mode 100644
index 0000000..f89917e
--- /dev/null
+++ b/internal/snapshot/diff_test.go
@@ -0,0 +1,83 @@
+package snapshot
+
+import (
+ "testing"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+func TestCompareAddedRemovedChanged(t *testing.T) {
+ before := []types.Device{
+ {IP: "192.168.1.5", MAC: "aa:bb:cc:00:00:01", Hostname: "nas"},
+ {IP: "192.168.1.6", MAC: "aa:bb:cc:00:00:02", Hostname: "printer"},
+ {IP: "192.168.1.7", MAC: "aa:bb:cc:00:00:03"},
+ }
+ after := []types.Device{
+ {IP: "192.168.1.5", MAC: "aa:bb:cc:00:00:01", Hostname: "nas"}, // unchanged
+ {IP: "192.168.1.9", MAC: "aa:bb:cc:00:00:02", Hostname: "printer"}, // moved IP (same MAC)
+ // .7 is gone
+ {IP: "192.168.1.20", MAC: "aa:bb:cc:00:00:04", Hostname: "laptop"}, // new
+ }
+ d := Compare(before, after)
+
+ if len(d.Added) != 1 || d.Added[0].IP != "192.168.1.20" {
+ t.Errorf("added = %+v, want just the laptop", d.Added)
+ }
+ if len(d.Removed) != 1 || d.Removed[0].IP != "192.168.1.7" {
+ t.Errorf("removed = %+v, want just .7", d.Removed)
+ }
+ if len(d.Changed) != 1 {
+ t.Fatalf("changed = %+v, want 1", d.Changed)
+ }
+ ch := d.Changed[0]
+ if ch.Before.IP != "192.168.1.6" || ch.After.IP != "192.168.1.9" {
+ t.Errorf("changed before/after IP wrong: %+v", ch)
+ }
+ if len(ch.Fields) != 1 || ch.Fields[0] != "ip" {
+ t.Errorf("changed fields = %v, want [ip]", ch.Fields)
+ }
+}
+
+func TestCompareMatchesByMACNotIP(t *testing.T) {
+ // Same device, MAC stable, IP moved: exactly one "changed", not an add plus a
+ // remove.
+ before := []types.Device{{IP: "10.0.0.5", MAC: "aa:bb:cc:dd:ee:ff"}}
+ after := []types.Device{{IP: "10.0.0.99", MAC: "aa:bb:cc:dd:ee:ff"}}
+ d := Compare(before, after)
+ if len(d.Added) != 0 || len(d.Removed) != 0 {
+ t.Errorf("a MAC-stable IP move should not add or remove: added %v removed %v", d.Added, d.Removed)
+ }
+ if len(d.Changed) != 1 || d.Changed[0].Fields[0] != "ip" {
+ t.Errorf("want one ip change, got %+v", d.Changed)
+ }
+}
+
+func TestCompareNoMACMatchesByIP(t *testing.T) {
+ before := []types.Device{{IP: "10.0.0.5", Hostname: "a"}}
+ after := []types.Device{{IP: "10.0.0.5", Hostname: "b"}}
+ d := Compare(before, after)
+ if len(d.Changed) != 1 || d.Changed[0].Fields[0] != "hostname" {
+ t.Errorf("want one hostname change, got %+v", d.Changed)
+ }
+}
+
+func TestCompareIgnoresUserFieldsAndLastSeen(t *testing.T) {
+ // Label/notes/group and LastSeen are not network changes, so a device that
+ // only differs in those is not reported as changed.
+ before := []types.Device{{IP: "10.0.0.5", MAC: "aa:bb:cc:dd:ee:01", Label: "old"}}
+ after := []types.Device{{IP: "10.0.0.5", MAC: "aa:bb:cc:dd:ee:01", Label: "new", Group: "Server"}}
+ d := Compare(before, after)
+ if len(d.Changed) != 0 {
+ t.Errorf("label/group-only differences should not count as changed, got %+v", d.Changed)
+ }
+}
+
+func TestCompareEmptyLists(t *testing.T) {
+ d := Compare(nil, nil)
+ if d.Added == nil || d.Removed == nil || d.Changed == nil {
+ t.Error("result slices should be non-nil (empty)")
+ }
+ if len(d.Added)+len(d.Removed)+len(d.Changed) != 0 {
+ t.Error("empty comparison should report no changes")
+ }
+}
diff --git a/internal/storage/address_history_test.go b/internal/storage/address_history_test.go
index 980d8e9..ac4e288 100644
--- a/internal/storage/address_history_test.go
+++ b/internal/storage/address_history_test.go
@@ -18,7 +18,7 @@ func TestDeviceMovingIPIsTrackedByMAC(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
- if err := s.UpdateDeviceFields("192.168.1.10", strptr("File Server"), strptr("rack 1"), strptr("Infra")); err != nil {
+ if err := s.UpdateDeviceFields("192.168.1.10", strptr("File Server"), strptr("rack 1"), strptr("Infra"), nil); err != nil {
t.Fatal(err)
}
diff --git a/internal/storage/backup.go b/internal/storage/backup.go
new file mode 100644
index 0000000..d5ce238
--- /dev/null
+++ b/internal/storage/backup.go
@@ -0,0 +1,117 @@
+package storage
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// ExportBackup gathers the whole device list, the settings overrides (scan
+// state), and every saved snapshot into a portable Backup. Maps are deep-copied
+// so the result can be marshalled without holding the lock.
+func (s *Storage) ExportBackup() types.Backup {
+ s.mu.RLock()
+ devices := make(map[string]*types.Device, len(s.devices))
+ for ip, d := range s.devices {
+ dc := *d
+ devices[ip] = &dc
+ }
+ st := *s.state
+ st.LastScan = make(map[string]time.Time, len(s.state.LastScan))
+ for k, v := range s.state.LastScan {
+ st.LastScan[k] = v
+ }
+ st.LastDuration = make(map[string]float64, len(s.state.LastDuration))
+ for k, v := range s.state.LastDuration {
+ st.LastDuration[k] = v
+ }
+ s.mu.RUnlock()
+
+ snaps := []types.Snapshot{}
+ if metas, err := s.ListSnapshots(); err == nil {
+ for _, m := range metas {
+ if full, err := s.GetSnapshot(m.ID); err == nil {
+ snaps = append(snaps, *full)
+ }
+ }
+ }
+
+ return types.Backup{
+ CreatedAt: time.Now(),
+ Devices: devices,
+ State: &st,
+ Snapshots: snaps,
+ }
+}
+
+// ImportBackup replaces the current device list, settings overrides, and saved
+// snapshots with those from the backup, and persists them. This is destructive:
+// it is the "restore" half of a backup and overwrites what is there.
+func (s *Storage) ImportBackup(b types.Backup) error {
+ s.mu.Lock()
+ if b.Devices != nil {
+ s.devices = b.Devices
+ } else {
+ s.devices = make(map[string]*types.Device)
+ }
+ if b.State != nil {
+ s.state = b.State
+ }
+ if s.state.LastScan == nil {
+ s.state.LastScan = make(map[string]time.Time)
+ }
+ if s.state.LastDuration == nil {
+ s.state.LastDuration = make(map[string]float64)
+ }
+ errD := s.saveDevices()
+ errS := s.saveState()
+ s.mu.Unlock()
+ if errD != nil {
+ return errD
+ }
+ if errS != nil {
+ return errS
+ }
+ return s.replaceSnapshots(b.Snapshots)
+}
+
+// replaceSnapshots clears the saved snapshots and writes the given ones. Each
+// gets a freshly generated, guaranteed-numeric id rather than trusting the
+// backup's, so a crafted backup cannot write outside the snapshots directory.
+func (s *Storage) replaceSnapshots(snaps []types.Snapshot) error {
+ dir := s.snapshotDir()
+ if entries, err := os.ReadDir(dir); err == nil {
+ for _, e := range entries {
+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".json") {
+ _ = os.Remove(filepath.Join(dir, e.Name()))
+ }
+ }
+ }
+ if len(snaps) == 0 {
+ return nil
+ }
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return err
+ }
+ base := time.Now().UnixNano()
+ for i, snap := range snaps {
+ snap.ID = strconv.FormatInt(base+int64(i), 10) // unique and numeric
+ data, err := json.MarshalIndent(snap, "", " ")
+ if err != nil {
+ continue
+ }
+ path, err := s.snapshotPath(snap.ID)
+ if err != nil {
+ continue
+ }
+ if err := atomicWrite(path, data); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/storage/snapshots.go b/internal/storage/snapshots.go
new file mode 100644
index 0000000..1ea638c
--- /dev/null
+++ b/internal/storage/snapshots.go
@@ -0,0 +1,129 @@
+package storage
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// snapshotDir is where saved snapshots live: a "snapshots" subdirectory of the
+// data directory, next to devices.json.
+func (s *Storage) snapshotDir() string {
+ return filepath.Join(filepath.Dir(s.devicesFile), "snapshots")
+}
+
+// snapshotPath maps a snapshot id to its file, rejecting anything that is not a
+// plain numeric id so a crafted id cannot escape the snapshots directory.
+func (s *Storage) snapshotPath(id string) (string, error) {
+ if id == "" || strings.IndexFunc(id, func(r rune) bool { return r < '0' || r > '9' }) >= 0 {
+ return "", fmt.Errorf("invalid snapshot id")
+ }
+ return filepath.Join(s.snapshotDir(), id+".json"), nil
+}
+
+func readSnapshotFile(path string) (*types.Snapshot, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ var snap types.Snapshot
+ if err := json.Unmarshal(data, &snap); err != nil {
+ return nil, err
+ }
+ return &snap, nil
+}
+
+// SaveSnapshot captures the current device list under the given name and returns
+// its metadata. A blank name defaults to the current date and time.
+func (s *Storage) SaveSnapshot(name string) (types.SnapshotMeta, error) {
+ s.mu.RLock()
+ devices := make([]types.Device, 0, len(s.devices))
+ for _, d := range s.devices {
+ devices = append(devices, *d)
+ }
+ s.mu.RUnlock()
+
+ now := time.Now()
+ name = strings.TrimSpace(name)
+ if name == "" {
+ name = now.Format("2006-01-02 15:04")
+ }
+ snap := types.Snapshot{
+ ID: strconv.FormatInt(now.UnixNano(), 10),
+ Name: name,
+ CreatedAt: now,
+ Devices: devices,
+ }
+
+ if err := os.MkdirAll(s.snapshotDir(), 0755); err != nil {
+ return types.SnapshotMeta{}, err
+ }
+ data, err := json.MarshalIndent(snap, "", " ")
+ if err != nil {
+ return types.SnapshotMeta{}, err
+ }
+ if err := atomicWrite(filepath.Join(s.snapshotDir(), snap.ID+".json"), data); err != nil {
+ return types.SnapshotMeta{}, err
+ }
+ return types.SnapshotMeta{
+ ID: snap.ID,
+ Name: snap.Name,
+ CreatedAt: snap.CreatedAt,
+ DeviceCount: len(devices),
+ }, nil
+}
+
+// ListSnapshots returns the metadata of every saved snapshot, newest first. A
+// snapshot file that cannot be read is skipped rather than failing the listing.
+func (s *Storage) ListSnapshots() ([]types.SnapshotMeta, error) {
+ entries, err := os.ReadDir(s.snapshotDir())
+ if err != nil {
+ if os.IsNotExist(err) {
+ return []types.SnapshotMeta{}, nil
+ }
+ return nil, err
+ }
+ metas := []types.SnapshotMeta{}
+ for _, e := range entries {
+ if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
+ continue
+ }
+ snap, err := readSnapshotFile(filepath.Join(s.snapshotDir(), e.Name()))
+ if err != nil {
+ continue
+ }
+ metas = append(metas, types.SnapshotMeta{
+ ID: snap.ID,
+ Name: snap.Name,
+ CreatedAt: snap.CreatedAt,
+ DeviceCount: len(snap.Devices),
+ })
+ }
+ sort.Slice(metas, func(i, j int) bool { return metas[i].CreatedAt.After(metas[j].CreatedAt) })
+ return metas, nil
+}
+
+// GetSnapshot loads a full snapshot (including its devices) by id.
+func (s *Storage) GetSnapshot(id string) (*types.Snapshot, error) {
+ path, err := s.snapshotPath(id)
+ if err != nil {
+ return nil, err
+ }
+ return readSnapshotFile(path)
+}
+
+// DeleteSnapshot removes a saved snapshot by id.
+func (s *Storage) DeleteSnapshot(id string) error {
+ path, err := s.snapshotPath(id)
+ if err != nil {
+ return err
+ }
+ return os.Remove(path)
+}
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index e97aeb3..efcf1a8 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -7,6 +7,7 @@ import (
"net"
"os"
"path/filepath"
+ "sort"
"sync"
"time"
@@ -20,6 +21,13 @@ type Storage struct {
mu sync.RWMutex
devices map[string]*types.Device
state *types.ScanState
+
+ // retentionDays and maxDevices bound the stored device list, set from config
+ // via SetLimits. Zero means the corresponding limit is off. See
+ // enforceLimitsLocked for the exact rules (curated and online devices are
+ // never dropped).
+ retentionDays int
+ maxDevices int
}
// New creates a new Storage instance
@@ -217,7 +225,7 @@ func (s *Storage) UpdateDevice(device *types.Device) error {
}
// UpdateDeviceFields updates specific fields of a device
-func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string) error {
+func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string, expected *bool) error {
s.mu.Lock()
defer s.mu.Unlock()
@@ -235,10 +243,25 @@ func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string) err
if group != nil {
device.Group = *group
}
+ if expected != nil {
+ device.Expected = *expected
+ }
return s.saveDevices()
}
+// MarkAllExpected sets (or clears) the Expected flag on every stored device, so a
+// user can baseline their whole network in one action and then be flagged only on
+// what changes afterwards.
+func (s *Storage) MarkAllExpected(expected bool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for _, d := range s.devices {
+ d.Expected = expected
+ }
+ return s.saveDevices()
+}
+
// DeleteDevice removes a device by IP
func (s *Storage) DeleteDevice(ip string) error {
s.mu.Lock()
@@ -289,6 +312,7 @@ func (s *Storage) MergeDevices(discovered []types.Device) error {
}
}
+ s.enforceLimitsLocked(now)
return s.saveDevices()
}
@@ -329,6 +353,7 @@ func (s *Storage) MergeSupplemental(discovered []types.Device) error {
}
}
+ s.enforceLimitsLocked(now)
return s.saveDevices()
}
@@ -366,6 +391,12 @@ func (s *Storage) MergeIPv6Neighbors(discovered []types.Device) error {
if existing.Type == "" && d.Type != "" {
existing.Type = d.Type
}
+ // Record the routable IPv6 address on the IPv4-primary device so a
+ // dual-stack device can show both. Skipped when the device we matched
+ // is itself keyed by an IPv6 address, since its IP already shows it.
+ if isIPv4(existing.IP) {
+ existing.IPv6 = d.IP
+ }
existing.LastSeen = now
changed = true
continue
@@ -382,6 +413,7 @@ func (s *Storage) MergeIPv6Neighbors(discovered []types.Device) error {
}
if changed {
+ s.enforceLimitsLocked(now)
return s.saveDevices()
}
return nil
@@ -396,6 +428,7 @@ func (s *Storage) addNewDeviceLocked(d *types.Device, now time.Time) {
d.Label = old.Label
d.Notes = old.Notes
d.Group = old.Group
+ d.Expected = old.Expected
d.FirstSeen = old.FirstSeen
if d.Type == "" {
d.Type = old.Type
@@ -478,7 +511,7 @@ func (s *Storage) pruneEphemeralIPv6Locked() bool {
if parsed == nil || parsed.To4() != nil {
continue // not IPv6
}
- if dev.Label != "" || dev.Notes != "" || dev.Group != "" {
+ if isCurated(dev) {
continue // curated by the user: never auto-delete
}
if parsed.IsLinkLocalUnicast() || (dev.MAC != "" && isRandomizedMAC(dev.MAC)) {
@@ -489,6 +522,83 @@ func (s *Storage) pruneEphemeralIPv6Locked() bool {
return removed
}
+// isCurated reports whether the user has personalised a device with a label,
+// notes, or a group. Curated devices are never removed by any automatic cleanup:
+// the user told us this one matters, so retention, the device cap, and the IPv6
+// phantom prune all leave it alone.
+func isCurated(d *types.Device) bool {
+ return d.Label != "" || d.Notes != "" || d.Group != "" || d.Expected
+}
+
+// SetLimits records the retention window (in days) and the maximum device count,
+// normally from config, and applies them once immediately so an existing install
+// heals on startup rather than only on the next scan. A zero value turns that
+// limit off. Call it once after New, before the store is shared with request
+// handlers.
+func (s *Storage) SetLimits(retentionDays, maxDevices int) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.retentionDays = retentionDays
+ s.maxDevices = maxDevices
+ if s.enforceLimitsLocked(time.Now()) {
+ return s.saveDevices()
+ }
+ return nil
+}
+
+// enforceLimitsLocked applies the storage limits and reports whether it removed
+// anything. First retention: drop devices last seen longer ago than
+// retentionDays. Then the cap: if the list still exceeds maxDevices, evict the
+// devices with the oldest LastSeen until it fits.
+//
+// Two kinds of device are never removed by either step: ones the user has
+// curated (isCurated), and ones that are currently online. So the cleanup only
+// ever reclaims stale, untouched entries, and the count can legitimately sit
+// above maxDevices when that many devices are pinned by those rules -- keeping
+// real, in-use data matters more than honouring a number. A zero limit is off.
+// Callers hold s.mu.
+func (s *Storage) enforceLimitsLocked(now time.Time) bool {
+ removed := false
+
+ if s.retentionDays > 0 {
+ cutoff := now.Add(-time.Duration(s.retentionDays) * 24 * time.Hour)
+ for ip, dev := range s.devices {
+ if isCurated(dev) || now.Sub(dev.LastSeen) < time.Hour {
+ continue
+ }
+ if dev.LastSeen.Before(cutoff) {
+ delete(s.devices, ip)
+ removed = true
+ }
+ }
+ }
+
+ if s.maxDevices > 0 && len(s.devices) > s.maxDevices {
+ // Collect the devices eligible for eviction (not curated, not online),
+ // oldest LastSeen first, and drop from the front until we are within the
+ // cap or run out of eligible devices.
+ evictable := make([]string, 0, len(s.devices))
+ for ip, dev := range s.devices {
+ if isCurated(dev) || now.Sub(dev.LastSeen) < time.Hour {
+ continue
+ }
+ evictable = append(evictable, ip)
+ }
+ sort.Slice(evictable, func(i, j int) bool {
+ return s.devices[evictable[i]].LastSeen.Before(s.devices[evictable[j]].LastSeen)
+ })
+ for _, ip := range evictable {
+ if len(s.devices) <= s.maxDevices {
+ break
+ }
+ delete(s.devices, ip)
+ removed = true
+ }
+ }
+
+ return removed
+}
+
// maxAddressHistory bounds how many previous addresses a device keeps, so the
// history cannot grow without limit on a device that changes IP often.
const maxAddressHistory = 10
@@ -578,6 +688,162 @@ func (s *Storage) SetContinuousScan(enabled bool) error {
return s.saveState()
}
+// RetentionDaysOrDefault resolves the retention window: the UI override if one
+// has been saved, otherwise the configured default.
+func (s *Storage) RetentionDaysOrDefault(configDefault int) int {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.RetentionDays != nil {
+ return *s.state.RetentionDays
+ }
+ return configDefault
+}
+
+// MaxDevicesOrDefault resolves the device cap: the UI override if one has been
+// saved, otherwise the configured default.
+func (s *Storage) MaxDevicesOrDefault(configDefault int) int {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.MaxDevices != nil {
+ return *s.state.MaxDevices
+ }
+ return configDefault
+}
+
+// GetLimitOverrides returns the saved UI overrides for the storage limits, or nil
+// for a limit that is following the config default. The returned pointers are
+// copies, so the caller can read them without holding the lock.
+func (s *Storage) GetLimitOverrides() (retentionDays, maxDevices *int) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.RetentionDays != nil {
+ v := *s.state.RetentionDays
+ retentionDays = &v
+ }
+ if s.state.MaxDevices != nil {
+ v := *s.state.MaxDevices
+ maxDevices = &v
+ }
+ return
+}
+
+// SetLimitOverrides saves the UI overrides for the storage limits so they survive
+// a restart. A nil pointer clears that override, falling back to the config
+// default. It only persists the choice; the caller applies it with SetLimits.
+func (s *Storage) SetLimitOverrides(retentionDays, maxDevices *int) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.state.RetentionDays = retentionDays
+ s.state.MaxDevices = maxDevices
+ return s.saveState()
+}
+
+// ServiceDetectionEnabled reports whether the opt-in port probe should run,
+// honouring a UI override and falling back to the configured default.
+func (s *Storage) ServiceDetectionEnabled(configDefault bool) bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.EnableServiceDetection != nil {
+ return *s.state.EnableServiceDetection
+ }
+ return configDefault
+}
+
+// SetServiceDetection saves the user's runtime override for the port probe so it
+// survives a restart.
+func (s *Storage) SetServiceDetection(enabled bool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.state.EnableServiceDetection = &enabled
+ return s.saveState()
+}
+
+// ScanIntervalOrDefault resolves how often the background scanner runs, in
+// seconds: the UI override if one has been saved, otherwise the config default.
+func (s *Storage) ScanIntervalOrDefault(configDefault int) int {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.ScanInterval != nil {
+ return *s.state.ScanInterval
+ }
+ return configDefault
+}
+
+// SetScanInterval saves the user's runtime override for the background scan
+// interval (in seconds) so it survives a restart.
+func (s *Storage) SetScanInterval(seconds int) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.state.ScanInterval = &seconds
+ return s.saveState()
+}
+
+// NetworksOrDefault resolves the include list (extra CIDRs to scan): the UI
+// override if one has been saved, otherwise the configured default. The returned
+// slice is a copy.
+func (s *Storage) NetworksOrDefault(configDefault []string) []string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.Networks != nil {
+ return append([]string(nil), *s.state.Networks...)
+ }
+ return configDefault
+}
+
+// ExcludeNetworksOrDefault resolves the exclude list (CIDRs to hide) the same
+// way as NetworksOrDefault.
+func (s *Storage) ExcludeNetworksOrDefault(configDefault []string) []string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.ExcludeNetworks != nil {
+ return append([]string(nil), *s.state.ExcludeNetworks...)
+ }
+ return configDefault
+}
+
+// OnlyConfiguredOrDefault resolves whether to scan only the configured networks:
+// the UI override if set, otherwise the configured default.
+func (s *Storage) OnlyConfiguredOrDefault(configDefault bool) bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.OnlyConfiguredNetworks != nil {
+ return *s.state.OnlyConfiguredNetworks
+ }
+ return configDefault
+}
+
+// GetNetworkOverrides returns the saved UI overrides for the scan-target lists,
+// or nil for a setting that is following the config default. Slices are copied.
+func (s *Storage) GetNetworkOverrides() (networks, exclude *[]string, onlyConfigured *bool) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.state.Networks != nil {
+ v := append([]string(nil), *s.state.Networks...)
+ networks = &v
+ }
+ if s.state.ExcludeNetworks != nil {
+ v := append([]string(nil), *s.state.ExcludeNetworks...)
+ exclude = &v
+ }
+ if s.state.OnlyConfiguredNetworks != nil {
+ v := *s.state.OnlyConfiguredNetworks
+ onlyConfigured = &v
+ }
+ return
+}
+
+// SetNetworkOverrides saves the UI overrides for the scan-target lists so they
+// survive a restart. A nil pointer clears that override, falling back to the
+// config default.
+func (s *Storage) SetNetworkOverrides(networks, exclude *[]string, onlyConfigured *bool) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.state.Networks = networks
+ s.state.ExcludeNetworks = exclude
+ s.state.OnlyConfiguredNetworks = onlyConfigured
+ return s.saveState()
+}
+
// GetStats returns device statistics
func (s *Storage) GetStats() types.DeviceStats {
s.mu.RLock()
diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go
index 00e8558..85d527f 100644
--- a/internal/storage/storage_test.go
+++ b/internal/storage/storage_test.go
@@ -2,6 +2,7 @@ package storage
import (
"encoding/json"
+ "fmt"
"os"
"path/filepath"
"testing"
@@ -144,9 +145,13 @@ func TestMergeIPv6NeighborsEnrichesByMAC(t *testing.T) {
if len(devs) != 1 {
t.Fatalf("an IPv6 sighting of a known device should enrich it, not add a second entry: got %d", len(devs))
}
- if d, ok := devs["192.168.1.5"]; !ok || d.Hostname != "printer" {
+ d, ok := devs["192.168.1.5"]
+ if !ok || d.Hostname != "printer" {
t.Errorf("expected the IPv4 device enriched with the hostname, got %+v", devs)
}
+ if d.IPv6 != "2001:db8::5" {
+ t.Errorf("expected the device's routable IPv6 address recorded, got %q", d.IPv6)
+ }
}
func TestMergeIPv6NeighborsCreatesOnlyForRealMAC(t *testing.T) {
@@ -303,3 +308,488 @@ func TestIPv6RealisticDualStackNetwork(t *testing.T) {
t.Logf(" %-18s %s", ip, d.Hostname)
}
}
+
+// --- Storage limits: retention + max_devices enforcement (v3.4.2) ---
+
+// seedDevice inserts a device straight into the map with a chosen LastSeen, so a
+// test can create devices that are already "old" without waiting. Same-package
+// (white-box) access. MAC is set to the IP just to keep it unique.
+func seedDevice(s *Storage, ip string, lastSeen time.Time, mut func(*types.Device)) {
+ d := &types.Device{IP: ip, MAC: ip, LastSeen: lastSeen, FirstSeen: lastSeen}
+ if mut != nil {
+ mut(d)
+ }
+ s.mu.Lock()
+ s.devices[ip] = d
+ s.mu.Unlock()
+}
+
+func TestRetentionPrunesOldOfflineDevices(t *testing.T) {
+ s := newTestStorage(t)
+ now := time.Now()
+ seedDevice(s, "10.0.0.1", now, nil) // online: keep
+ seedDevice(s, "10.0.0.2", now.Add(-48*time.Hour), nil) // offline 2d, within 90d: keep
+ seedDevice(s, "10.0.0.3", now.Add(-100*24*time.Hour), nil) // offline 100d: prune
+
+ if err := s.SetLimits(90, 0); err != nil {
+ t.Fatalf("SetLimits: %v", err)
+ }
+ devs := s.GetDevices()
+ if _, ok := devs["10.0.0.3"]; ok {
+ t.Error("a device offline past retention_days should be pruned")
+ }
+ if len(devs) != 2 {
+ t.Errorf("want 2 devices kept, got %d", len(devs))
+ }
+}
+
+func TestRetentionKeepsCuratedDevice(t *testing.T) {
+ s := newTestStorage(t)
+ now := time.Now()
+ seedDevice(s, "10.0.0.9", now.Add(-365*24*time.Hour), func(d *types.Device) {
+ d.Label = "NAS"
+ })
+ if err := s.SetLimits(90, 0); err != nil {
+ t.Fatalf("SetLimits: %v", err)
+ }
+ if _, ok := s.GetDevices()["10.0.0.9"]; !ok {
+ t.Error("a curated device must never be pruned by retention, even a year offline")
+ }
+}
+
+func TestMaxDevicesEvictsOldestOffline(t *testing.T) {
+ s := newTestStorage(t)
+ now := time.Now()
+ // Five offline devices (all > 1h old, so evictable), staggered by age.
+ for i := 1; i <= 5; i++ {
+ seedDevice(s, fmt.Sprintf("10.0.1.%d", i), now.Add(-time.Duration(i)*24*time.Hour), nil)
+ }
+ if err := s.SetLimits(0, 3); err != nil { // cap 3, retention off
+ t.Fatalf("SetLimits: %v", err)
+ }
+ devs := s.GetDevices()
+ if len(devs) != 3 {
+ t.Fatalf("want cap of 3, got %d", len(devs))
+ }
+ for _, gone := range []string{"10.0.1.4", "10.0.1.5"} { // the two oldest
+ if _, ok := devs[gone]; ok {
+ t.Errorf("%s (oldest) should have been evicted", gone)
+ }
+ }
+ for _, kept := range []string{"10.0.1.1", "10.0.1.2", "10.0.1.3"} {
+ if _, ok := devs[kept]; !ok {
+ t.Errorf("%s (newer) should have been kept", kept)
+ }
+ }
+}
+
+func TestMaxDevicesNeverEvictsCuratedOrOnline(t *testing.T) {
+ s := newTestStorage(t)
+ now := time.Now()
+ seedDevice(s, "10.0.2.1", now, nil) // online
+ seedDevice(s, "10.0.2.2", now.Add(-500*time.Hour), func(d *types.Device) { d.Group = "Server" }) // curated, old
+ seedDevice(s, "10.0.2.3", now.Add(-500*time.Hour), nil) // plain old: evictable
+ seedDevice(s, "10.0.2.4", now.Add(-400*time.Hour), nil) // plain old: evictable
+
+ if err := s.SetLimits(0, 1); err != nil { // cap 1, but only 2 are evictable
+ t.Fatalf("SetLimits: %v", err)
+ }
+ devs := s.GetDevices()
+ if _, ok := devs["10.0.2.1"]; !ok {
+ t.Error("online device must never be evicted by the cap")
+ }
+ if _, ok := devs["10.0.2.2"]; !ok {
+ t.Error("curated device must never be evicted by the cap")
+ }
+ if _, ok := devs["10.0.2.3"]; ok {
+ t.Error("plain old device should be evicted")
+ }
+ if _, ok := devs["10.0.2.4"]; ok {
+ t.Error("plain old device should be evicted")
+ }
+ if len(devs) != 2 {
+ t.Errorf("only the pinned (online + curated) devices remain, want 2, got %d", len(devs))
+ }
+}
+
+func TestZeroLimitsDisableEnforcement(t *testing.T) {
+ s := newTestStorage(t)
+ now := time.Now()
+ seedDevice(s, "10.0.3.1", now.Add(-1000*24*time.Hour), nil) // ancient
+ for i := 0; i < 50; i++ {
+ seedDevice(s, fmt.Sprintf("10.0.4.%d", i), now.Add(-1000*time.Hour), nil)
+ }
+ if err := s.SetLimits(0, 0); err != nil { // both off
+ t.Fatalf("SetLimits: %v", err)
+ }
+ if got := len(s.GetDevices()); got != 51 {
+ t.Errorf("zero limits must not remove anything, kept %d of 51", got)
+ }
+}
+
+func TestEnforcementRunsAndPersistsOnScan(t *testing.T) {
+ dir := t.TempDir()
+ devicesFile := filepath.Join(dir, "devices.json")
+ stateFile := filepath.Join(dir, "state.json")
+ s, err := New(devicesFile, stateFile)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ now := time.Now()
+ seedDevice(s, "10.0.5.1", now.Add(-200*24*time.Hour), nil) // old, should go on the next scan
+ // Enable retention without SetLimits' immediate sweep, to prove the scan
+ // (merge) path itself enforces.
+ s.mu.Lock()
+ s.retentionDays = 90
+ s.mu.Unlock()
+
+ if err := s.MergeDevices([]types.Device{{IP: "10.0.5.2", MAC: "aa:bb:cc:dd:ee:01"}}); err != nil {
+ t.Fatalf("MergeDevices: %v", err)
+ }
+ if _, ok := s.GetDevices()["10.0.5.1"]; ok {
+ t.Error("a scan should have pruned the device offline past retention")
+ }
+ // The prune is saved, not just in memory: a reload does not resurrect it.
+ s2, err := New(devicesFile, stateFile)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ if _, ok := s2.GetDevices()["10.0.5.1"]; ok {
+ t.Error("the prune should have been written to disk")
+ }
+}
+
+func TestLimitOverridesResolveAndPersist(t *testing.T) {
+ dir := t.TempDir()
+ devices := filepath.Join(dir, "devices.json")
+ state := filepath.Join(dir, "state.json")
+
+ first, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ // No override yet: the config default wins.
+ if got := first.RetentionDaysOrDefault(90); got != 90 {
+ t.Errorf("with no override, want config default 90, got %d", got)
+ }
+ if got := first.MaxDevicesOrDefault(1000); got != 1000 {
+ t.Errorf("with no override, want config default 1000, got %d", got)
+ }
+
+ // Save overrides: retention 30, cap 250.
+ r, m := 30, 250
+ if err := first.SetLimitOverrides(&r, &m); err != nil {
+ t.Fatalf("SetLimitOverrides: %v", err)
+ }
+ if got := first.RetentionDaysOrDefault(90); got != 30 {
+ t.Errorf("override should win, want 30, got %d", got)
+ }
+
+ // Survives a restart.
+ second, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ if got := second.RetentionDaysOrDefault(90); got != 30 {
+ t.Errorf("override should survive reload, want 30, got %d", got)
+ }
+ if got := second.MaxDevicesOrDefault(1000); got != 250 {
+ t.Errorf("override should survive reload, want 250, got %d", got)
+ }
+ ro, mo := second.GetLimitOverrides()
+ if ro == nil || *ro != 30 || mo == nil || *mo != 250 {
+ t.Errorf("GetLimitOverrides = %v,%v want 30,250", ro, mo)
+ }
+
+ // Clearing an override falls back to the config default.
+ if err := second.SetLimitOverrides(nil, &m); err != nil {
+ t.Fatalf("clear retention override: %v", err)
+ }
+ if got := second.RetentionDaysOrDefault(90); got != 90 {
+ t.Errorf("cleared override should fall back to default 90, got %d", got)
+ }
+ if got := second.MaxDevicesOrDefault(1000); got != 250 {
+ t.Errorf("max override should remain 250, got %d", got)
+ }
+}
+
+func TestServiceDetectionOverrideResolvesAndPersists(t *testing.T) {
+ dir := t.TempDir()
+ devices := filepath.Join(dir, "devices.json")
+ state := filepath.Join(dir, "state.json")
+
+ first, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ // No override: config default wins, both ways.
+ if !first.ServiceDetectionEnabled(true) {
+ t.Error("with no override, want config default true")
+ }
+ if first.ServiceDetectionEnabled(false) {
+ t.Error("with no override, want config default false")
+ }
+ // Turn it on even though config defaults it off.
+ if err := first.SetServiceDetection(true); err != nil {
+ t.Fatalf("SetServiceDetection: %v", err)
+ }
+ if !first.ServiceDetectionEnabled(false) {
+ t.Error("override (true) should win over config default (false)")
+ }
+ // Survives a restart.
+ second, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ if !second.ServiceDetectionEnabled(false) {
+ t.Error("override should survive reload")
+ }
+}
+
+func TestScanIntervalOverrideResolvesAndPersists(t *testing.T) {
+ dir := t.TempDir()
+ devices := filepath.Join(dir, "devices.json")
+ state := filepath.Join(dir, "state.json")
+
+ first, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if got := first.ScanIntervalOrDefault(300); got != 300 {
+ t.Errorf("with no override, want config default 300, got %d", got)
+ }
+ if err := first.SetScanInterval(60); err != nil {
+ t.Fatalf("SetScanInterval: %v", err)
+ }
+ if got := first.ScanIntervalOrDefault(300); got != 60 {
+ t.Errorf("override should win, want 60, got %d", got)
+ }
+ second, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ if got := second.ScanIntervalOrDefault(300); got != 60 {
+ t.Errorf("override should survive reload, want 60, got %d", got)
+ }
+}
+
+func TestNetworkOverridesResolveAndPersist(t *testing.T) {
+ dir := t.TempDir()
+ devices := filepath.Join(dir, "devices.json")
+ state := filepath.Join(dir, "state.json")
+
+ first, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ // No override: config defaults win.
+ if got := first.NetworksOrDefault([]string{"10.0.0.0/24"}); len(got) != 1 || got[0] != "10.0.0.0/24" {
+ t.Errorf("no override should return the config default, got %v", got)
+ }
+ if first.OnlyConfiguredOrDefault(false) {
+ t.Error("no override should return the config default (false)")
+ }
+
+ // Save overrides.
+ inc := []string{"192.168.10.0/24", "10.5.0.0/16"}
+ exc := []string{"10.5.99.0/24"}
+ only := true
+ if err := first.SetNetworkOverrides(&inc, &exc, &only); err != nil {
+ t.Fatalf("SetNetworkOverrides: %v", err)
+ }
+ if got := first.NetworksOrDefault(nil); len(got) != 2 {
+ t.Errorf("include override should win, got %v", got)
+ }
+ if !first.OnlyConfiguredOrDefault(false) {
+ t.Error("only_configured override should win")
+ }
+
+ // Survives a restart.
+ second, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ if got := second.ExcludeNetworksOrDefault(nil); len(got) != 1 || got[0] != "10.5.99.0/24" {
+ t.Errorf("exclude override should survive reload, got %v", got)
+ }
+
+ // An explicit empty override is distinct from "no override": include is
+ // cleared to empty, exclude falls back to the config default.
+ empty := []string{}
+ if err := second.SetNetworkOverrides(&empty, nil, nil); err != nil {
+ t.Fatalf("set empty: %v", err)
+ }
+ if got := second.NetworksOrDefault([]string{"cfg"}); len(got) != 0 {
+ t.Errorf("an explicit empty override should win over the config default, got %v", got)
+ }
+ if got := second.ExcludeNetworksOrDefault([]string{"cfgexc"}); len(got) != 1 || got[0] != "cfgexc" {
+ t.Errorf("cleared exclude override should fall back to the config default, got %v", got)
+ }
+}
+
+func TestSnapshotSaveListGetDelete(t *testing.T) {
+ s := newTestStorage(t)
+ if err := s.MergeDevices([]types.Device{
+ {IP: "192.168.1.5", MAC: "aa:bb:cc:00:00:01", Hostname: "nas"},
+ {IP: "192.168.1.6", MAC: "aa:bb:cc:00:00:02"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ meta, err := s.SaveSnapshot("baseline")
+ if err != nil {
+ t.Fatalf("SaveSnapshot: %v", err)
+ }
+ if meta.Name != "baseline" || meta.DeviceCount != 2 {
+ t.Errorf("meta = %+v, want name baseline / count 2", meta)
+ }
+ metas, err := s.ListSnapshots()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(metas) != 1 || metas[0].ID != meta.ID {
+ t.Fatalf("list = %+v, want the one snapshot", metas)
+ }
+ full, err := s.GetSnapshot(meta.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(full.Devices) != 2 {
+ t.Errorf("snapshot devices = %d, want 2", len(full.Devices))
+ }
+ if err := s.DeleteSnapshot(meta.ID); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if metas, _ = s.ListSnapshots(); len(metas) != 0 {
+ t.Errorf("after delete, list = %+v, want empty", metas)
+ }
+}
+
+func TestSnapshotRejectsBadID(t *testing.T) {
+ s := newTestStorage(t)
+ for _, bad := range []string{"", "../etc/passwd", "abc", "12a", "1/2"} {
+ if _, err := s.GetSnapshot(bad); err == nil {
+ t.Errorf("GetSnapshot(%q) should reject a non-numeric id", bad)
+ }
+ }
+}
+
+func TestSnapshotEmptyNameDefaults(t *testing.T) {
+ s := newTestStorage(t)
+ meta, err := s.SaveSnapshot(" ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if meta.Name == "" {
+ t.Error("a blank name should default to a timestamp, not stay empty")
+ }
+}
+
+func TestBackupExportImportRoundtrip(t *testing.T) {
+ dir := t.TempDir()
+ s, err := New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ // Seed a curated device, a settings override, and a snapshot.
+ if err := s.MergeDevices([]types.Device{
+ {IP: "192.168.1.5", MAC: "aa:bb:cc:00:00:01", Label: "NAS", Group: "Server"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ rv := 45
+ if err := s.SetLimitOverrides(&rv, nil); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.SaveSnapshot("snap1"); err != nil {
+ t.Fatal(err)
+ }
+
+ backup := s.ExportBackup()
+ if len(backup.Devices) != 1 || len(backup.Snapshots) != 1 {
+ t.Fatalf("backup should have 1 device and 1 snapshot, got %d/%d", len(backup.Devices), len(backup.Snapshots))
+ }
+ if backup.CreatedAt.IsZero() {
+ t.Error("backup should carry a creation time")
+ }
+
+ // Restore into a fresh, separate instance.
+ dir2 := t.TempDir()
+ s2, err := New(filepath.Join(dir2, "devices.json"), filepath.Join(dir2, "state.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s2.ImportBackup(backup); err != nil {
+ t.Fatalf("ImportBackup: %v", err)
+ }
+ devs := s2.GetDevices()
+ if len(devs) != 1 || devs["192.168.1.5"] == nil || devs["192.168.1.5"].Label != "NAS" {
+ t.Errorf("restored devices wrong: %+v", devs)
+ }
+ if s2.RetentionDaysOrDefault(90) != 45 {
+ t.Errorf("restored retention override should be 45, got %d", s2.RetentionDaysOrDefault(90))
+ }
+ metas, _ := s2.ListSnapshots()
+ if len(metas) != 1 || metas[0].Name != "snap1" {
+ t.Errorf("restored snapshots wrong: %+v", metas)
+ }
+
+ // A reload sees the restored, persisted data.
+ s3, err := New(filepath.Join(dir2, "devices.json"), filepath.Join(dir2, "state.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(s3.GetDevices()) != 1 {
+ t.Error("restored devices should persist across reload")
+ }
+}
+
+func boolptr(b bool) *bool { return &b }
+
+func TestExpectedFlagAndBaseline(t *testing.T) {
+ s := newTestStorage(t)
+ if err := s.MergeDevices([]types.Device{
+ {IP: "192.168.1.5", MAC: "aa:bb:cc:00:00:01"},
+ {IP: "192.168.1.6", MAC: "aa:bb:cc:00:00:02"},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ // Mark one expected via UpdateDeviceFields.
+ if err := s.UpdateDeviceFields("192.168.1.5", nil, nil, nil, boolptr(true)); err != nil {
+ t.Fatal(err)
+ }
+ if !s.GetDevices()["192.168.1.5"].Expected {
+ t.Error("device should be marked expected")
+ }
+ if s.GetDevices()["192.168.1.6"].Expected {
+ t.Error("other device should not be expected")
+ }
+ // An expected device is curated, so retention must never prune it even when
+ // long offline.
+ s.mu.Lock()
+ s.devices["192.168.1.5"].LastSeen = time.Now().Add(-365 * 24 * time.Hour)
+ s.retentionDays = 90
+ removed := s.enforceLimitsLocked(time.Now())
+ s.mu.Unlock()
+ _ = removed
+ if _, ok := s.GetDevices()["192.168.1.5"]; !ok {
+ t.Error("an expected device offline past retention must not be pruned")
+ }
+ // Baseline the whole list.
+ if err := s.MarkAllExpected(true); err != nil {
+ t.Fatal(err)
+ }
+ for ip, d := range s.GetDevices() {
+ if !d.Expected {
+ t.Errorf("%s should be expected after MarkAllExpected(true)", ip)
+ }
+ }
+ // And clear it.
+ if err := s.MarkAllExpected(false); err != nil {
+ t.Fatal(err)
+ }
+ for ip, d := range s.GetDevices() {
+ if d.Expected {
+ t.Errorf("%s should not be expected after MarkAllExpected(false)", ip)
+ }
+ }
+}
diff --git a/internal/types/types.go b/internal/types/types.go
index 2204519..218576f 100644
--- a/internal/types/types.go
+++ b/internal/types/types.go
@@ -5,7 +5,13 @@ import "time"
// Device represents a discovered network device
type Device struct {
- IP string `json:"ip"`
+ IP string `json:"ip"`
+ // IPv6 is a routable IPv6 address the same device was also seen at, recorded
+ // when IPv6 neighbour discovery matches this device by MAC alongside its IPv4
+ // address. It is shown next to the IPv4 address so a dual-stack device
+ // displays both. Empty when no routable IPv6 sighting has been attributed to
+ // the device (the common case on an IPv4-only home network).
+ IPv6 string `json:"ipv6,omitempty"`
MAC string `json:"mac"`
Hostname string `json:"hostname"`
Vendor string `json:"vendor"`
@@ -20,10 +26,16 @@ type Device struct {
// Risks lists security concerns found during an opt-in service probe, such as
// an exposed unencrypted service. Empty when nothing notable was found or the
// probe is off.
- Risks []string `json:"risks,omitempty"`
- Label string `json:"label"`
- Notes string `json:"notes"`
- Group string `json:"group"`
+ Risks []string `json:"risks,omitempty"`
+ Label string `json:"label"`
+ Notes string `json:"notes"`
+ Group string `json:"group"`
+ // Expected marks a device the user has confirmed belongs on the network. It
+ // is set from the UI (individually or by baselining the whole list). An
+ // online device that is not expected is "unexpected"; an expected device that
+ // has gone offline is "missing". Like the other curated fields, it is
+ // preserved across scans and protects the device from automatic cleanup.
+ Expected bool `json:"expected,omitempty"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
ResponseTime *float64 `json:"response_time,omitempty"`
@@ -50,6 +62,35 @@ func (d *Device) IsRecent() bool {
return time.Since(d.LastSeen) < 5*time.Minute
}
+// Snapshot is a saved copy of the device list at a point in time, so the network
+// can be compared against it later to see what has changed.
+type Snapshot struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ CreatedAt time.Time `json:"created_at"`
+ Devices []Device `json:"devices"`
+}
+
+// SnapshotMeta is a snapshot without its device list, for listings.
+type SnapshotMeta struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ CreatedAt time.Time `json:"created_at"`
+ DeviceCount int `json:"device_count"`
+}
+
+// Backup is a portable copy of everything a user would not want to lose: the
+// device list (with labels, notes and groups), the runtime settings overrides
+// (the scan state), and the saved snapshots. It deliberately does NOT include the
+// password, which lives in a separate file and is not the user's data to carry
+// between machines.
+type Backup struct {
+ CreatedAt time.Time `json:"created_at"`
+ Devices map[string]*Device `json:"devices"`
+ State *ScanState `json:"state,omitempty"`
+ Snapshots []Snapshot `json:"snapshots"`
+}
+
// Network represents a detected network interface
type Network struct {
CIDR string `json:"cidr"`
@@ -70,6 +111,29 @@ type ScanState struct {
// UI. nil means "use the configured default"; a set value wins over config
// so the user's choice survives a restart.
ContinuousScan *bool `json:"continuous_scan,omitempty"`
+ // RetentionDays and MaxDevices are runtime overrides for the storage limits,
+ // set from the Settings page. As with ContinuousScan, nil means "use the
+ // configured default" and a set value survives a restart, so a user who never
+ // edits config.ini can still change these. 0 means the limit is off (keep
+ // devices forever / no cap).
+ RetentionDays *int `json:"retention_days,omitempty"`
+ MaxDevices *int `json:"max_devices,omitempty"`
+ // EnableServiceDetection is a runtime override for the opt-in port probe, set
+ // from the Settings page. nil means "use the configured default".
+ EnableServiceDetection *bool `json:"enable_service_detection,omitempty"`
+ // ScanInterval is a runtime override for how often the background scanner
+ // re-scans, in seconds, set from the Settings page. nil means "use the
+ // configured default". The scanner reads it fresh before each wait, so a
+ // change takes effect on the next cycle.
+ ScanInterval *int `json:"scan_interval,omitempty"`
+ // Networks, ExcludeNetworks and OnlyConfiguredNetworks are runtime overrides
+ // for the scan-target lists, set from the Settings page. A nil pointer means
+ // "use the configured default"; a non-nil slice (even empty) is an explicit
+ // override. They are read fresh when scan targets are resolved, so a change
+ // takes effect on the next scan.
+ Networks *[]string `json:"networks,omitempty"`
+ ExcludeNetworks *[]string `json:"exclude_networks,omitempty"`
+ OnlyConfiguredNetworks *bool `json:"only_configured_networks,omitempty"`
}
// ScanResult represents the outcome of a network scan
diff --git a/internal/web/handler.go b/internal/web/handler.go
index 01ea40f..a648a3a 100644
--- a/internal/web/handler.go
+++ b/internal/web/handler.go
@@ -35,6 +35,17 @@ type Handler struct {
staticFS http.Handler
}
+// networkFilter builds the effective scan-target filter, preferring the UI
+// overrides over the configured defaults, so the dashboard shows the same
+// networks a scan will actually use.
+func (h *Handler) networkFilter() network.Filter {
+ return network.Filter{
+ Configured: h.store.NetworksOrDefault(h.cfg.Scanning.Networks),
+ Excluded: h.store.ExcludeNetworksOrDefault(h.cfg.Scanning.ExcludeNetworks),
+ OnlyConfigured: h.store.OnlyConfiguredOrDefault(h.cfg.Scanning.OnlyConfiguredNetworks),
+ }
+}
+
// PageData holds data passed to templates
type PageData struct {
Title string
@@ -75,6 +86,11 @@ type PageData struct {
// worth glancing at rather than empty space.
Flagged int
Moved int
+ // Unexpected is how many devices are online but not marked expected, and
+ // Missing how many expected devices are currently offline. Both are zero until
+ // the user baselines their network by marking devices as expected.
+ Unexpected int
+ Missing int
// ContinuousScan reports whether the server re-scans on its own. When true
// the dashboard shows a "live" cue so the last-scan time does not read as
@@ -317,7 +333,7 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
// Convert to view models
var deviceViews []*DeviceView
groupSet := make(map[string]bool)
- var flagged, moved int
+ var flagged, moved, unexpected, missing int
for _, d := range devices {
if len(d.Risks) > 0 {
@@ -326,6 +342,12 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
if len(d.AddressHistory) > 0 {
moved++
}
+ if d.IsOnline() && !d.Expected {
+ unexpected++
+ }
+ if d.Expected && !d.IsOnline() {
+ missing++
+ }
// Devices recorded by an older version have no vendor stored, so look it
// up now rather than showing "Unknown" until a rescan.
resolvedVendor := scanner.ResolveVendor(d.Vendor, d.MAC)
@@ -376,7 +398,7 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
// Get networks
networks, _ := network.DetectNetworks()
- networks = network.WithConfigured(networks, network.Filter{Configured: h.cfg.Scanning.Networks, Excluded: h.cfg.Scanning.ExcludeNetworks, OnlyConfigured: h.cfg.Scanning.OnlyConfiguredNetworks})
+ networks = network.WithConfigured(networks, h.networkFilter())
// Get Tailscale status
tailscale := network.GetTailscaleStatus()
@@ -395,6 +417,8 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
AuthEnabled: h.auth.Enabled(),
Flagged: flagged,
Moved: moved,
+ Unexpected: unexpected,
+ Missing: missing,
Version: h.version,
ContinuousScan: h.store.ContinuousScanEnabled(h.cfg.Scanning.ContinuousScan),
}
diff --git a/internal/web/static/app.js b/internal/web/static/app.js
index 40745d6..b6649ef 100644
--- a/internal/web/static/app.js
+++ b/internal/web/static/app.js
@@ -367,7 +367,9 @@ function filterDevices() {
const matchGroup = groupFilter === 'all' || group === groupFilter;
const matchChip = !statChipFilter ||
(statChipFilter === 'moved' && row.dataset.moved === '1') ||
- (statChipFilter === 'flagged' && row.dataset.flagged === '1');
+ (statChipFilter === 'flagged' && row.dataset.flagged === '1') ||
+ (statChipFilter === 'unexpected' && row.dataset.unexpected === '1') ||
+ (statChipFilter === 'missing' && row.dataset.missing === '1');
const show = matchSearch && matchStatus && matchGroup && matchChip;
row.style.display = show ? '' : 'none';
@@ -388,12 +390,146 @@ function editDevice(ip) {
document.getElementById('edit-label').value = row.dataset.labelOriginal || '';
document.getElementById('edit-group').value = row.dataset.group || '';
document.getElementById('edit-notes').value = row.dataset.notes || '';
+ document.getElementById('edit-expected').checked = row.dataset.expected === '1';
modal.style.display = 'flex';
}
function closeModal() {
- const modal = document.getElementById('edit-modal');
- if (modal) modal.style.display = 'none';
+ // Close whichever modal is open, so Escape and a backdrop click work for all
+ // of them (edit device, snapshots).
+ document.querySelectorAll('.modal').forEach(m => { m.style.display = 'none'; });
+}
+
+// --- Snapshots ---------------------------------------------------------------
+
+function openSnapshots() {
+ document.getElementById('snapshots-modal').style.display = 'flex';
+ document.getElementById('compare-result').textContent = '';
+ loadSnapshots();
+}
+
+function formatSnapDate(iso) {
+ try { return new Date(iso).toLocaleString(); } catch (e) { return iso; }
+}
+
+async function loadSnapshots() {
+ const res = await api('snapshots');
+ const snaps = (res && res.success && Array.isArray(res.data)) ? res.data : [];
+ const list = document.getElementById('snapshot-list');
+ const fromSel = document.getElementById('compare-from');
+ const toSel = document.getElementById('compare-to');
+ list.textContent = '';
+ fromSel.innerHTML = '';
+ toSel.innerHTML = '';
+
+ if (snaps.length === 0) {
+ const p = document.createElement('p');
+ p.className = 'form-help';
+ p.style.margin = '0';
+ p.textContent = 'No snapshots yet.';
+ list.appendChild(p);
+ } else {
+ snaps.forEach(s => {
+ const row = document.createElement('div');
+ row.className = 'snapshot-row';
+ const info = document.createElement('span');
+ info.textContent = `${s.name} · ${formatSnapDate(s.created_at)} · ${s.device_count} device${s.device_count === 1 ? '' : 's'}`;
+ const del = document.createElement('button');
+ del.className = 'btn btn-sm';
+ del.textContent = 'Delete';
+ del.onclick = () => deleteSnapshot(s.id);
+ row.appendChild(info);
+ row.appendChild(del);
+ list.appendChild(row);
+ fromSel.add(new Option(s.name, s.id));
+ toSel.add(new Option(s.name, s.id));
+ });
+ }
+ // "Current network" is always a valid comparison target.
+ toSel.add(new Option('Current network', 'current'));
+ toSel.value = 'current';
+}
+
+async function saveSnapshot() {
+ const name = document.getElementById('snapshot-name').value.trim();
+ const status = document.getElementById('snapshot-status');
+ const res = await api('snapshots', { name }, 'POST');
+ if (res && res.success) {
+ document.getElementById('snapshot-name').value = '';
+ status.textContent = 'Saved';
+ status.style.color = 'var(--success)';
+ loadSnapshots();
+ } else {
+ status.textContent = (res && res.error) || 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ setTimeout(() => { status.textContent = ''; }, 2500);
+}
+
+async function deleteSnapshot(id) {
+ try {
+ // DELETE takes the id as a query param and needs the CSRF header.
+ await fetch(`/api/snapshots?id=${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ headers: { 'X-Requested-With': 'XMLHttpRequest' }
+ });
+ } catch (e) { /* ignore; the reload below reflects reality */ }
+ document.getElementById('compare-result').textContent = '';
+ loadSnapshots();
+}
+
+async function runCompare() {
+ const from = document.getElementById('compare-from').value;
+ const to = document.getElementById('compare-to').value;
+ const result = document.getElementById('compare-result');
+ if (!from || !to) { result.textContent = 'Pick two snapshots to compare.'; return; }
+ if (from === to) { result.textContent = 'Pick two different snapshots.'; return; }
+ const res = await api('snapshots/compare', { from, to });
+ if (!res || !res.success) {
+ result.textContent = (res && res.error) || 'Could not compare.';
+ return;
+ }
+ renderDiff(res.data);
+}
+
+function renderDiff(d) {
+ const result = document.getElementById('compare-result');
+ result.textContent = '';
+ const total = d.added.length + d.removed.length + d.changed.length;
+ if (total === 0) {
+ const p = document.createElement('p');
+ p.className = 'form-help';
+ p.style.margin = '0';
+ p.textContent = 'No differences — the network is unchanged between these two.';
+ result.appendChild(p);
+ return;
+ }
+ const groups = [
+ { key: 'added', label: 'New', cls: 'diff-added', sign: '+' },
+ { key: 'removed', label: 'Gone', cls: 'diff-removed', sign: '−' },
+ { key: 'changed', label: 'Changed', cls: 'diff-changed', sign: '~' }
+ ];
+ groups.forEach(g => {
+ const items = d[g.key];
+ if (!items || items.length === 0) return;
+ const head = document.createElement('div');
+ head.className = 'diff-group-head ' + g.cls;
+ head.textContent = `${g.label} (${items.length})`;
+ result.appendChild(head);
+ items.forEach(item => {
+ const dev = g.key === 'changed' ? item.after : item;
+ let text = `${g.sign} ${dev.ip}`;
+ if (dev.hostname) text += ` · ${dev.hostname}`;
+ else if (dev.vendor) text += ` · ${dev.vendor}`;
+ if (g.key === 'changed') {
+ text += ' (' + item.fields.map(f => `${f}: ${item.before[f] || '—'} → ${item.after[f] || '—'}`).join(', ') + ')';
+ }
+ const line = document.createElement('div');
+ line.className = 'diff-line';
+ line.textContent = text;
+ result.appendChild(line);
+ });
+ });
}
async function saveDevice() {
@@ -401,8 +537,9 @@ async function saveDevice() {
const label = document.getElementById('edit-label').value;
const group = document.getElementById('edit-group').value;
const notes = document.getElementById('edit-notes').value;
+ const expected = document.getElementById('edit-expected').checked;
try {
- const result = await api('device', { ip, label, group, notes }, 'POST');
+ const result = await api('device', { ip, label, group, notes, expected }, 'POST');
if (result.success) {
showToast('Device updated', 'success');
closeModal();
@@ -417,6 +554,22 @@ async function saveDevice() {
}
}
+// Mark every current device as expected, baselining the network so the
+// "unexpected" and "missing" flags become meaningful afterwards.
+async function markAllExpected() {
+ try {
+ const result = await api('devices/mark-expected', { expected: true }, 'POST');
+ if (result && result.success) {
+ showToast('All current devices marked as expected', 'success');
+ if (!(await refreshInPlace())) location.reload();
+ } else {
+ showToast((result && result.error) || 'Could not update devices', 'error');
+ }
+ } catch (e) {
+ showToast('Error: ' + e.message, 'error');
+ }
+}
+
async function deleteDevice(ip) {
if (!confirm(`Delete device ${ip}?`)) return;
try {
@@ -521,13 +674,25 @@ function legacyCopy(text) {
field.value = text;
field.contentEditable = 'true';
field.readOnly = false;
+ // Keep the field in the viewport (top/left 0, 1px, transparent). Several
+ // browsers refuse to copy from an element scrolled off-screen, which made the
+ // copy work only sometimes on a plain-http instance where this path is the
+ // only one available. Tiny and opacity 0 so it is never actually seen.
field.style.position = 'fixed';
- field.style.top = '-1000px';
+ field.style.top = '0';
+ field.style.left = '0';
+ field.style.width = '1px';
+ field.style.height = '1px';
+ field.style.padding = '0';
+ field.style.border = 'none';
field.style.opacity = '0';
document.body.appendChild(field);
const selection = window.getSelection();
const previous = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
try {
+ // Focusing the field first is what makes execCommand reliably copy from
+ // it rather than from whatever was selected on the page.
+ field.focus();
const range = document.createRange();
range.selectNodeContents(field);
selection.removeAllRanges();
@@ -1140,12 +1305,16 @@ async function disconnectTailscale() {
// value that contains quotes (a vendor name, say) can never break out of the
// handler, and rows added by an auto-refresh are covered automatically. Empty
// values (a placeholder like "Unknown") carry data-copy="" and are skipped.
+//
+// The target is the nearest element carrying data-copy, not just the cell, so a
+// value nested inside a cell (the IPv6 address shown under the IPv4 one) copies
+// itself rather than the cell's primary value.
(function initCopyCells() {
const table = document.getElementById('devices-table');
if (!table) return;
table.addEventListener('click', function (e) {
- const cell = e.target.closest('td[data-copy]');
- if (!cell) return;
+ const cell = e.target.closest('[data-copy]');
+ if (!cell || !table.contains(cell)) return;
const value = cell.getAttribute('data-copy');
if (value) copyToClipboard(value, e);
});
diff --git a/internal/web/static/style.css b/internal/web/static/style.css
index ce4f709..efc40d1 100644
--- a/internal/web/static/style.css
+++ b/internal/web/static/style.css
@@ -375,10 +375,11 @@ a:hover { color: var(--accent-hover); }
margin-bottom: 0;
}
-.card:hover {
- box-shadow: var(--card-shadow-lg);
- transform: translateY(-2px);
-}
+/* No hover-lift on .card: it is used only for the Settings page's form cards,
+ which contain text fields and toggles. Lifting the whole card (and its fields)
+ 2px whenever the cursor entered its area read as a glitchy "something triggers
+ in the field" jump. The dashboard's network cards keep their own .net-card
+ hover effect, which is unaffected. */
.card-header {
display: flex;
@@ -1108,6 +1109,27 @@ td[data-copy]:not([data-copy=""]) {
font-weight: 600;
}
+/* A device's routable IPv6 address, shown on its own muted line under the IPv4
+ in the IP cell for dual-stack devices. Inherits the cell's monospace font and
+ is independently click-to-copy (data-copy on the span itself). In the narrow
+ desktop column it truncates with an ellipsis, with the full address in the
+ tooltip and on copy; the wider mobile card shows more of it. */
+.ipv6-addr {
+ display: block;
+ max-width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 0.78rem;
+ font-weight: 500;
+ color: var(--text-muted);
+ margin-top: 0.15rem;
+}
+
+.ipv6-addr:hover {
+ color: var(--text-secondary);
+}
+
.mac-cell {
font-family: 'SF Mono', 'Fira Code', monospace;
font-size: 0.85rem;
@@ -1283,6 +1305,43 @@ textarea.input {
resize: vertical;
}
+/* The CIDR list editor on the Settings > Networks card: each entry is a small
+ monospace chip with a remove (x) button. */
+.cidr-list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.4rem;
+ align-items: center;
+ min-height: 1.6rem;
+}
+
+.cidr-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ padding: 0.2rem 0.3rem 0.2rem 0.6rem;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-color);
+ border-radius: var(--radius-sm);
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 0.82rem;
+}
+
+.cidr-chip button {
+ background: none;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+ font-size: 1.1rem;
+ line-height: 1;
+ padding: 0 0.15rem;
+ border-radius: 4px;
+}
+
+.cidr-chip button:hover {
+ color: var(--danger);
+}
+
.form-group {
margin-bottom: 1.25rem;
}
@@ -1425,6 +1484,57 @@ textarea.input {
animation: slideUp 0.3s ease;
}
+/* The snapshots modal holds lists and a diff, so it gets more room. */
+.modal-content.modal-wide {
+ max-width: 640px;
+}
+
+/* Snapshots modal: one row per saved snapshot, and a colour-coded diff. */
+.snapshot-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 1rem;
+ padding: 0.5rem 0;
+ border-bottom: 1px solid var(--border-color);
+ font-size: 0.88rem;
+}
+
+.snapshot-row:last-child {
+ border-bottom: none;
+}
+
+.btn-sm {
+ padding: 0.25rem 0.6rem;
+ font-size: 0.8rem;
+}
+
+.diff-group-head {
+ font-weight: 700;
+ font-size: 0.85rem;
+ margin: 0.85rem 0 0.35rem;
+}
+
+.diff-added {
+ color: var(--success);
+}
+
+.diff-removed {
+ color: var(--danger);
+}
+
+.diff-changed {
+ color: var(--warning);
+}
+
+.diff-line {
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 0.82rem;
+ padding: 0.15rem 0;
+ color: var(--text-secondary);
+ word-break: break-word;
+}
+
@keyframes slideUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
@@ -1872,6 +1982,17 @@ textarea.input {
letter-spacing: 0.04em;
color: var(--text-muted);
}
+ /* On a card the IP cell is a flex row, so let the IPv6 line wrap onto its own
+ full-width row under the IPv4 and align right with the other values,
+ instead of sitting inline beside it. The card is wide enough to show the
+ whole address. */
+ .table .device-row td.ip-cell { flex-wrap: wrap; }
+ .table .device-row td.ip-cell .ipv6-addr {
+ flex-basis: 100%;
+ max-width: 100%;
+ text-align: right;
+ }
+
/* The group dropdown and the action buttons sit to the right of the label. */
.table .device-row .group-select { width: auto; min-width: 130px; }
.table .device-row .actions-cell { gap: 0.5rem; }
diff --git a/internal/web/templates/index.html b/internal/web/templates/index.html
index b3fb8b0..19cbe84 100644
--- a/internal/web/templates/index.html
+++ b/internal/web/templates/index.html
@@ -129,6 +129,18 @@ orangutan export out.csv</code></pre>
{{.Moved}} moved
</span>
{{end}}
+ {{if .Unexpected}}
+ <span class="stat-chip stat-chip-warn stat-chip-filter" data-filter="unexpected" role="button" tabindex="0" title="Show the {{.Unexpected}} online device{{if ne .Unexpected 1}}s{{end}} not marked as expected">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
+ {{.Unexpected}} unexpected
+ </span>
+ {{end}}
+ {{if .Missing}}
+ <span class="stat-chip stat-chip-danger stat-chip-filter" data-filter="missing" role="button" tabindex="0" title="Show the {{.Missing}} expected device{{if ne .Missing 1}}s{{end}} that {{if ne .Missing 1}}are{{else}}is{{end}} currently offline">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2h8M12 2v6M5 13a7 7 0 1 0 14 0 7 7 0 0 0-14 0z"/></svg>
+ {{.Missing}} missing
+ </span>
+ {{end}}
{{if or .ContinuousScan .LastScanAt}}
<span class="stat-scan">
<span class="live-indicator"><span class="live-dot"></span>Live</span>{{if .LastScanAt}}<span class="live-sep">&middot;</span><span class="scan-when">scanned <span data-relative-time="{{.LastScanUnix}}">{{.LastScanAgo}}</span></span>{{end}}
@@ -220,6 +232,8 @@ orangutan export out.csv</code></pre>
<option value="Network">Network</option>
<option value="Pi">Pi</option>
</select>
+ <button class="btn" onclick="markAllExpected()" title="Mark every current device as expected, so you are flagged only when something new appears or a known device goes missing">Mark all expected</button>
+ <button class="btn" onclick="openSnapshots()">Snapshots</button>
<div class="dropdown">
<button class="btn" onclick="toggleDropdown('export-menu')">Export</button>
<div id="export-menu" class="dropdown-menu">
@@ -266,12 +280,15 @@ orangutan export out.csv</code></pre>
data-status="{{.Status}}"
data-moved="{{if .AddressHistory}}1{{end}}"
data-flagged="{{if .Risks}}1{{end}}"
+ data-expected="{{if .Expected}}1{{end}}"
+ data-unexpected="{{if and .IsOnline (not .Expected)}}1{{end}}"
+ data-missing="{{if and .Expected (not .IsOnline)}}1{{end}}"
data-lastseen="{{.LastSeenUnix}}">
<td data-label="Status">
<span class="status-indicator {{.StatusClass}}"></span>
</td>
<td class="ip-cell" data-label="IP Address" data-copy="{{.IP}}">
- {{.IP}}{{if .AddressHistory}}<span class="moved-indicator" data-tip="Changed address{{range .AddressHistory}}, was {{.IP}}{{end}}"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/></svg></span>{{end}}
+ {{.IP}}{{if .AddressHistory}}<span class="moved-indicator" data-tip="Changed address{{range .AddressHistory}}, was {{.IP}}{{end}}"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/></svg></span>{{end}}{{if .IPv6}}<span class="ipv6-addr" data-copy="{{.IPv6}}" data-tip="IPv6: {{.IPv6}} (click to copy)">{{.IPv6}}</span>{{end}}
</td>
<td class="hostname-cell" data-label="Hostname" data-copy="{{.Hostname}}">{{if .Hostname}}{{.Hostname}}{{else}}<span style="color:var(--text-muted)">-</span>{{end}}</td>
<td class="type-cell" data-label="Type">
@@ -369,6 +386,12 @@ orangutan export out.csv</code></pre>
<label>Notes</label>
<textarea id="edit-notes" name="notes" class="input" rows="3" placeholder="Add notes about this device..."></textarea>
</div>
+ <div class="form-group">
+ <label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
+ <input type="checkbox" id="edit-expected">
+ <span>Expected device &mdash; part of my known network</span>
+ </label>
+ </div>
</form>
</div>
<div class="modal-footer">
@@ -378,6 +401,35 @@ orangutan export out.csv</code></pre>
</div>
</div>
+ <div id="snapshots-modal" class="modal" style="display:none">
+ <div class="modal-content modal-wide">
+ <div class="modal-header">
+ <h3>Snapshots</h3>
+ <button class="modal-close" onclick="closeModal()">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p class="form-help" style="margin-top:0;">Save a snapshot of the network now, then compare it later to see what is new, gone, or changed.</p>
+ <div class="form-group" style="display:flex; gap:0.5rem; align-items:center; margin-bottom:0.35rem;">
+ <input type="text" id="snapshot-name" class="input" placeholder="Snapshot name (optional)" style="flex:1;">
+ <button class="btn btn-primary" onclick="saveSnapshot()">Save current</button>
+ </div>
+ <span id="snapshot-status" class="form-help" style="margin:0;"></span>
+
+ <h4 style="margin:1.25rem 0 0.5rem;">Saved snapshots</h4>
+ <div id="snapshot-list"></div>
+
+ <h4 style="margin:1.5rem 0 0.5rem;">Compare</h4>
+ <div style="display:flex; gap:0.5rem; align-items:center; flex-wrap:wrap;">
+ <select id="compare-from" class="select" style="width:auto;"></select>
+ <span class="form-help" style="margin:0;">&rarr;</span>
+ <select id="compare-to" class="select" style="width:auto;"></select>
+ <button class="btn" onclick="runCompare()">Compare</button>
+ </div>
+ <div id="compare-result" style="margin-top:1rem;"></div>
+ </div>
+ </div>
+ </div>
+
<div id="toast" class="toast"></div>
<div id="scan-progress" class="scan-progress" style="display:none">
<div class="scan-progress-head">
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
index a58930d..d270848 100644
--- a/internal/web/templates/settings.html
+++ b/internal/web/templates/settings.html
@@ -175,6 +175,86 @@ orangutan export out.csv</code></pre>
</div>
</section>
+ <section class="section">
+ <h2 class="section-title">Scanning</h2>
+ <div class="card">
+ <div class="form-group" style="display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem;">
+ <div>
+ <label style="margin-bottom: 0.35rem;">Service detection</label>
+ <p class="form-help" style="margin: 0;">Also check each device on a short list of well-known ports (web, printer, NAS, and so on) to identify it more precisely and flag a web interface. Sends a little more traffic and takes a little longer, so it is off by default. Applies on the next scan.</p>
+ </div>
+ <div class="toggle-switch" id="service-detection-toggle" role="switch" aria-checked="false" tabindex="0" onclick="toggleServiceDetection()" data-tip="Deeper device identification via a light port probe"></div>
+ </div>
+ <div class="form-group" style="margin-bottom: 0;">
+ <label for="set-scan-interval">Automatic scan interval (seconds)</label>
+ <div style="display: flex; align-items: center; gap: 0.6rem;">
+ <input type="number" id="set-scan-interval" class="input" min="10" max="86400" style="width: 160px;">
+ <button class="btn btn-primary" onclick="saveScanInterval()">Save</button>
+ <span id="scan-interval-status" class="form-help" style="margin: 0;"></span>
+ </div>
+ <p class="form-help">How often the background scanner re-scans while continuous scan is on. Takes effect on the next cycle. Default: <span id="def-scan-interval">300</span> seconds.</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="section">
+ <h2 class="section-title">Networks</h2>
+ <div class="card">
+ <div class="form-group" style="display: flex; align-items: flex-start; justify-content: space-between; gap: 1.5rem;">
+ <div>
+ <label style="margin-bottom: 0.35rem;">Scan only the networks I list</label>
+ <p class="form-help" style="margin: 0;">Ignore the auto-detected interfaces and scan only the "Networks to scan" list below. Useful on a host with many Docker bridges, VLANs, or routed interfaces.</p>
+ </div>
+ <div class="toggle-switch" id="only-configured-toggle" role="switch" aria-checked="false" tabindex="0" onclick="toggleOnlyConfigured()" data-tip="Scan only the networks you list, not the detected ones"></div>
+ </div>
+ <div class="form-group">
+ <label>Networks to scan</label>
+ <div id="include-list" class="cidr-list"></div>
+ <div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;">
+ <input type="text" id="include-input" class="input" placeholder="e.g. 192.168.10.0/24" style="width: 220px;" onkeydown="if(event.key==='Enter'){event.preventDefault();addCidr('include');}">
+ <button class="btn" onclick="addCidr('include')">Add</button>
+ </div>
+ <p class="form-help" id="detected-suggestions" style="margin-top: 0.5rem;"></p>
+ </div>
+ <div class="form-group">
+ <label>Networks to hide</label>
+ <div id="exclude-list" class="cidr-list"></div>
+ <div style="display: flex; gap: 0.5rem; margin-top: 0.5rem;">
+ <input type="text" id="exclude-input" class="input" placeholder="e.g. 10.99.0.0/16" style="width: 220px;" onkeydown="if(event.key==='Enter'){event.preventDefault();addCidr('exclude');}">
+ <button class="btn" onclick="addCidr('exclude')">Add</button>
+ </div>
+ </div>
+ <div class="form-group" style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0;">
+ <button class="btn btn-primary" onclick="saveNetworks()">Save</button>
+ <button class="btn" onclick="resetNetworks()">Reset to defaults</button>
+ <span id="networks-status" class="form-help" style="margin: 0;"></span>
+ </div>
+ <p class="form-help">A routed network (reached through a router, not on a local interface) is scanned but has no MAC addresses. Applies on the next scan. Saved to this instance, not your config file.</p>
+ </div>
+ </section>
+
+ <section class="section">
+ <h2 class="section-title">Storage</h2>
+ <div class="card">
+ <div class="form-group">
+ <label for="set-retention">Days to keep offline devices</label>
+ <input type="number" id="set-retention" class="input" min="0" max="36500" style="width: 160px;">
+ <p class="form-help">A device not seen for this many days is removed. Devices you have labelled, grouped, or added notes to, and devices currently online, are always kept. 0 keeps them forever. Default: <span id="def-retention">90</span>.</p>
+ </div>
+ <div class="form-group">
+ <label for="set-maxdevices">Maximum devices to track</label>
+ <input type="number" id="set-maxdevices" class="input" min="0" max="1000000" style="width: 160px;">
+ <p class="form-help">When the list grows past this, the devices seen longest ago are dropped first (labelled, grouped, noted, and online devices are kept). 0 means no cap. Default: <span id="def-maxdevices">1000</span>.</p>
+ </div>
+ <div class="form-group" style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0;">
+ <button class="btn btn-primary" onclick="saveStorageSettings()">Save</button>
+ <button class="btn" onclick="resetStorageSettings()">Reset to defaults</button>
+ <span id="storage-status" class="form-help" style="margin: 0;"></span>
+ </div>
+ <p class="form-help">Changes apply immediately: lowering these can remove stale devices right away. Saved to this instance, not your config file.</p>
+ </div>
+ </section>
+
{{if .AuthEnabled}}
<section class="section">
<h2 class="section-title">Security</h2>
@@ -196,7 +276,23 @@ orangutan export out.csv</code></pre>
<div class="card">
<div class="form-group">
<button class="btn btn-primary" onclick="exportDevices()">Export Devices (CSV)</button>
- <p class="form-help">Download all device data as a CSV file.</p>
+ <a class="btn" href="/api/report">Download report (HTML)</a>
+ <p class="form-help">A CSV of the device list, or a shareable, self-contained HTML report of the whole network.</p>
+ </div>
+ <div class="form-group" style="margin-bottom: 0;">
+ <label>Backup</label>
+ <div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
+ <a class="btn btn-primary" href="/api/backup">Back up everything</a>
+ <input type="file" id="restore-file" accept="application/json,.json" style="display:none" onchange="onRestoreFile()">
+ <button class="btn" onclick="document.getElementById('restore-file').click()">Restore from backup…</button>
+ <span id="restore-status" class="form-help" style="margin: 0;"></span>
+ </div>
+ <div id="restore-confirm" style="display: none; margin-top: 0.6rem;">
+ <p class="form-help" style="margin: 0 0 0.4rem;">Restore <strong id="restore-filename"></strong>? This <strong>replaces</strong> the current devices, settings, and snapshots on this instance.</p>
+ <button class="btn btn-primary" onclick="doRestore()">Confirm restore</button>
+ <button class="btn" onclick="cancelRestore()">Cancel</button>
+ </div>
+ <p class="form-help">Download a copy of your devices, settings, and snapshots (not your password) as a single file, or restore from one.</p>
</div>
</div>
</section>
@@ -249,6 +345,322 @@ orangutan export out.csv</code></pre>
function exportDevices() {
window.location.href = '/api/devices?format=csv';
}
+
+ // Storage settings (retention window + device cap). These are stored as
+ // overrides on this instance, not written to config.ini, and applied
+ // immediately by the server.
+ async function loadStorageSettings() {
+ try {
+ const res = await fetch('/api/settings').then(r => r.json());
+ if (!res.success) return;
+ const d = res.data;
+ document.getElementById('set-retention').value = d.retention_days.value;
+ document.getElementById('set-maxdevices').value = d.max_devices.value;
+ document.getElementById('def-retention').textContent = d.retention_days.default;
+ document.getElementById('def-maxdevices').textContent = d.max_devices.default;
+ } catch (e) { /* leave the fields blank if the API is unreachable */ }
+ }
+
+ function saveStorageSettings() {
+ // A blank field clears that override (falls back to the default).
+ const r = document.getElementById('set-retention').value.trim();
+ const m = document.getElementById('set-maxdevices').value.trim();
+ postStorageSettings({
+ retention_days: r === '' ? null : parseInt(r, 10),
+ max_devices: m === '' ? null : parseInt(m, 10)
+ });
+ }
+
+ function resetStorageSettings() {
+ postStorageSettings({ retention_days: null, max_devices: null });
+ }
+
+ async function postStorageSettings(body) {
+ const status = document.getElementById('storage-status');
+ try {
+ const res = await fetch('/api/settings', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ }).then(r => r.json());
+ if (res.success) {
+ // Reflect what the server actually applied (it clamps out-of-range
+ // values), so the fields never disagree with the stored setting.
+ document.getElementById('set-retention').value = res.data.retention_days.value;
+ document.getElementById('set-maxdevices').value = res.data.max_devices.value;
+ status.textContent = 'Saved';
+ status.style.color = 'var(--success)';
+ } else {
+ status.textContent = res.error || 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ } catch (e) {
+ status.textContent = 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ setTimeout(() => { status.textContent = ''; }, 2500);
+ }
+
+ loadStorageSettings();
+
+ // Scanning: service-detection toggle. Its own endpoint (like continuous
+ // scan), saved as an override on this instance and applied on the next
+ // scan.
+ function setServiceDetectionToggle(on) {
+ const t = document.getElementById('service-detection-toggle');
+ t.classList.toggle('active', on);
+ t.setAttribute('aria-checked', on ? 'true' : 'false');
+ }
+
+ async function loadScanningSettings() {
+ try {
+ const res = await fetch('/api/scan/service-detection').then(r => r.json());
+ if (res.success) setServiceDetectionToggle(res.data.enabled);
+ } catch (e) { /* leave it off if unreachable */ }
+ }
+
+ async function toggleServiceDetection() {
+ const t = document.getElementById('service-detection-toggle');
+ const next = t.getAttribute('aria-checked') !== 'true';
+ setServiceDetectionToggle(next); // optimistic
+ try {
+ const res = await fetch('/api/scan/service-detection', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enabled: next })
+ }).then(r => r.json());
+ setServiceDetectionToggle(res.success ? res.data.enabled : !next);
+ } catch (e) {
+ setServiceDetectionToggle(!next); // revert on failure
+ }
+ }
+
+ loadScanningSettings();
+
+ // Scanning: automatic scan interval (seconds). Its own endpoint; the
+ // background scanner re-reads it before each cycle.
+ async function loadScanInterval() {
+ try {
+ const res = await fetch('/api/scan/interval').then(r => r.json());
+ if (!res.success) return;
+ document.getElementById('set-scan-interval').value = res.data.seconds;
+ document.getElementById('def-scan-interval').textContent = res.data.default;
+ } catch (e) { /* leave blank if unreachable */ }
+ }
+
+ async function saveScanInterval() {
+ const status = document.getElementById('scan-interval-status');
+ const secs = parseInt(document.getElementById('set-scan-interval').value, 10);
+ if (isNaN(secs)) {
+ status.textContent = 'Enter a number';
+ status.style.color = 'var(--danger)';
+ setTimeout(() => { status.textContent = ''; }, 2500);
+ return;
+ }
+ try {
+ const res = await fetch('/api/scan/interval', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ seconds: secs })
+ }).then(r => r.json());
+ if (res.success) {
+ // Reflect the clamped value the server actually applied.
+ document.getElementById('set-scan-interval').value = res.data.seconds;
+ status.textContent = 'Saved';
+ status.style.color = 'var(--success)';
+ } else {
+ status.textContent = res.error || 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ } catch (e) {
+ status.textContent = 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ setTimeout(() => { status.textContent = ''; }, 2500);
+ }
+
+ loadScanInterval();
+
+ // Networks: include/exclude CIDR lists + only-configured toggle. Backed by
+ // /api/scan/networks; the server validates every CIDR and the change
+ // applies on the next scan. Chips are built with the DOM (textContent) so
+ // a value can never inject markup.
+ let includeList = [];
+ let excludeList = [];
+
+ function setOnlyConfiguredToggle(on) {
+ const t = document.getElementById('only-configured-toggle');
+ t.classList.toggle('active', on);
+ t.setAttribute('aria-checked', on ? 'true' : 'false');
+ }
+ function toggleOnlyConfigured() {
+ const t = document.getElementById('only-configured-toggle');
+ setOnlyConfiguredToggle(t.getAttribute('aria-checked') !== 'true');
+ }
+
+ function renderCidrList(kind) {
+ const arr = kind === 'include' ? includeList : excludeList;
+ const el = document.getElementById(kind + '-list');
+ el.textContent = '';
+ if (arr.length === 0) {
+ const none = document.createElement('span');
+ none.className = 'form-help';
+ none.style.margin = '0';
+ none.textContent = 'None yet.';
+ el.appendChild(none);
+ return;
+ }
+ arr.forEach((c, i) => {
+ const chip = document.createElement('span');
+ chip.className = 'cidr-chip';
+ chip.textContent = c;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.setAttribute('aria-label', 'Remove ' + c);
+ btn.innerHTML = '&times;';
+ btn.onclick = () => removeCidr(kind, i);
+ chip.appendChild(btn);
+ el.appendChild(chip);
+ });
+ }
+
+ function addCidr(kind) {
+ const input = document.getElementById(kind + '-input');
+ const v = input.value.trim();
+ if (!v) return;
+ const arr = kind === 'include' ? includeList : excludeList;
+ if (!arr.includes(v)) arr.push(v);
+ input.value = '';
+ renderCidrList(kind);
+ }
+ function removeCidr(kind, i) {
+ const arr = kind === 'include' ? includeList : excludeList;
+ arr.splice(i, 1);
+ renderCidrList(kind);
+ }
+ function quickAddDetected(cidr) {
+ if (!includeList.includes(cidr)) {
+ includeList.push(cidr);
+ renderCidrList('include');
+ applyDetectedSuggestions(lastDetected);
+ }
+ }
+
+ let lastDetected = [];
+ function applyDetectedSuggestions(detected) {
+ lastDetected = detected || [];
+ const sug = document.getElementById('detected-suggestions');
+ sug.textContent = '';
+ const det = lastDetected.filter(c => !includeList.includes(c) && !excludeList.includes(c));
+ if (det.length === 0) return;
+ sug.appendChild(document.createTextNode('Detected: '));
+ det.forEach((c, idx) => {
+ if (idx) sug.appendChild(document.createTextNode(' · '));
+ const a = document.createElement('a');
+ a.href = '#';
+ a.textContent = c;
+ a.onclick = (e) => { e.preventDefault(); quickAddDetected(c); };
+ sug.appendChild(a);
+ });
+ }
+
+ function applyNetworksData(d) {
+ includeList = (d.networks || []).slice();
+ excludeList = (d.exclude_networks || []).slice();
+ setOnlyConfiguredToggle(!!d.only_configured);
+ renderCidrList('include');
+ renderCidrList('exclude');
+ applyDetectedSuggestions(d.detected);
+ }
+
+ async function loadNetworks() {
+ try {
+ const res = await fetch('/api/scan/networks').then(r => r.json());
+ if (res.success) applyNetworksData(res.data);
+ } catch (e) { /* leave empty if unreachable */ }
+ }
+
+ async function saveNetworks(reset) {
+ const status = document.getElementById('networks-status');
+ const only = document.getElementById('only-configured-toggle').getAttribute('aria-checked') === 'true';
+ const body = reset ? { reset: true } :
+ { networks: includeList, exclude_networks: excludeList, only_configured: only };
+ try {
+ const res = await fetch('/api/scan/networks', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ }).then(r => r.json());
+ if (res.success) {
+ applyNetworksData(res.data);
+ status.textContent = 'Saved';
+ status.style.color = 'var(--success)';
+ } else {
+ status.textContent = res.error || 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ } catch (e) {
+ status.textContent = 'Could not save';
+ status.style.color = 'var(--danger)';
+ }
+ setTimeout(() => { status.textContent = ''; }, 3500);
+ }
+ function resetNetworks() { saveNetworks(true); }
+
+ loadNetworks();
+
+ // Backup / restore. Backup is a plain download link. Restore reads the
+ // chosen file, shows an inline confirm (destructive), then POSTs it.
+ let restoreData = null;
+ function onRestoreFile() {
+ const input = document.getElementById('restore-file');
+ const status = document.getElementById('restore-status');
+ const file = input.files[0];
+ if (!file) return;
+ const reader = new FileReader();
+ reader.onload = () => {
+ try {
+ restoreData = JSON.parse(reader.result);
+ } catch (e) {
+ status.textContent = 'That file is not valid JSON.';
+ status.style.color = 'var(--danger)';
+ input.value = '';
+ return;
+ }
+ status.textContent = '';
+ document.getElementById('restore-filename').textContent = file.name;
+ document.getElementById('restore-confirm').style.display = 'block';
+ };
+ reader.readAsText(file);
+ }
+ function cancelRestore() {
+ restoreData = null;
+ document.getElementById('restore-confirm').style.display = 'none';
+ document.getElementById('restore-file').value = '';
+ }
+ async function doRestore() {
+ if (!restoreData) return;
+ const status = document.getElementById('restore-status');
+ try {
+ const res = await fetch('/api/backup/restore', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(restoreData)
+ }).then(r => r.json());
+ if (res.success) {
+ status.textContent = 'Restored. Reloading…';
+ status.style.color = 'var(--success)';
+ setTimeout(() => location.reload(), 900);
+ } else {
+ status.textContent = res.error || 'Restore failed';
+ status.style.color = 'var(--danger)';
+ }
+ } catch (e) {
+ status.textContent = 'Restore failed';
+ status.style.color = 'var(--danger)';
+ }
+ document.getElementById('restore-confirm').style.display = 'none';
+ }
</script>
</body>
</html>