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.
Go clidevice-discoverygolanghomelabinternet-of-thingslannetwork-discoverynetwork-monitoringnetwork-monitoring-toolnetwork-scannernetworkingnmapsecurityself-hostedselfhostedtailscaletailscale-networkweb-dashboard
v3.3.8
filebaya325599805e1
diff --git a/README.md b/README.mdindex 7297b92..d8d1caf 100644--- a/README.md+++ b/README.md@@ -10,7 +10,7 @@</p>-<a href="https://trendshift.io/repositories/17888?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-17888" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17888/daily?language=Go" alt="291-Group%2FLAN-Orangutan | Trendshift" width="250" height="55"/></a> <a href="https://www.producthunt.com/products/lan-orangutan?embed=true&utm_source=badge-featured&utm_medium=badge&utm_campaign=badge-lan-orangutan" target="_blank" rel="noopener noreferrer"><img alt="LAN Orangutan - Try LAN Orangutan, our all new lightweight network scanner. | Product Hunt" width="250" height="54" src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1203757&theme=dark&t=1784746217551"></a>+<a href="https://trendshift.io/repositories/17888?utm_source=trendshift-badge&utm_medium=badge&utm_campaign=badge-trendshift-17888" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/17888/daily?language=Go" alt="291-Group%2FLAN-Orangutan | Trendshift" width="250" height="55"/></a>**Self-hosted network discovery for homelabbers with Tailscale support.**@@ -162,7 +162,7 @@ The web dashboard provides:- Labels and notes for each device- Search and filter devices- Export to CSV/JSON-- Auto-refresh option+- Continuous scanning you can toggle on or off, keeping the view live- Keyboard shortcuts (/ to search, R to refresh, T to toggle theme)### Scan progress@@ -181,6 +181,8 @@ Only peers that are currently online are listed, and they are shown with their TYou can also control Tailscale from the app. The dashboard and settings pages show whether Tailscale is connected, with a button to connect or disconnect. If the machine still needs to sign in, the app shows you the sign-in link to open. Disconnecting warns you first, since you might be reaching the dashboard over Tailscale itself. This needs the Tailscale CLI on the machine running LAN Orangutan.+**Tailscale needs a host install, not Docker.** These features rely on the Tailscale CLI being present where LAN Orangutan runs. In the standard Docker setup the container has its own filesystem and cannot see the host's Tailscale, so the card will read "Not Installed" even when the host is on your tailnet. To use Tailscale with LAN Orangutan, run the binary directly on the host rather than in a container.+## SecurityLAN Orangutan listens on your network by default, because it is normally installed on a server or a Raspberry Pi and opened from another machine. To make that safe, it shows you nothing until a password exists.@@ -189,6 +191,8 @@ LAN Orangutan listens on your network by default, because it is normally install**Signing in.** After that you sign in with that password and stay signed in for a week by default. Sign out is in the header. Five wrong guesses lock that address out for fifteen minutes.+**Forgot your password?** Because LAN Orangutan is self-hosted, you own the machine, so there is always a way back in. The password is a single bcrypt hash in a file named `auth` inside your data directory (`data/auth` next to the Docker Compose file, or the `data_dir` you configured). Delete that file and restart LAN Orangutan; the dashboard returns to the "create a password" screen and you set a new one. Your discovered devices, labels and settings live in separate files and are left untouched. (There is no email reset and no recovery question by design: the app has no account system and sends nothing off the machine.)+**Keeping it private instead.** Set `bind_address = 127.0.0.1` and the dashboard is only reachable from the machine it runs on. No password is asked for, because nobody else can reach it.**Setting the password in advance.** Useful for Docker and automated installs:@@ -200,7 +204,7 @@ ORANGUTAN_PASSWORD=your-password orangutan serveORANGUTAN_PASSWORD_FILE=/run/secrets/orangutan orangutan serve```-**Turning authentication off.** If something else already controls access, such as a reverse proxy that handles login, set `allow_insecure = true` (or pass `--allow-insecure`). This disables password protection completely, so only do it when access control genuinely lives elsewhere.+**Turning authentication off.** If something else already controls access, such as a reverse proxy that handles login, set `allow_insecure = true` (or pass `--allow-insecure`). This disables password protection completely, so only do it when access control genuinely lives elsewhere. On a network bind (`0.0.0.0`) that means anyone who can route to the host can not only read your device list but also delete devices and connect or disconnect Tailscale, all without signing in. Never combine `allow_insecure` with a network bind unless a proxy or firewall in front of it is doing the authentication.There is no HTTPS built in, so put LAN Orangutan behind a reverse proxy or reach it over Tailscale if you need the connection encrypted. See [SECURITY.md](SECURITY.md) for the full picture, the known limitations, and how to report a vulnerability.diff --git a/config.example.ini b/config.example.iniindex 2ec8a93..5df5bcf 100644--- a/config.example.ini+++ b/config.example.ini@@ -43,7 +43,12 @@ allow_insecure = falseenable_api = true[scanning]-# Auto-scan interval in seconds (default: 300 = 5 minutes)+# Keep the device list current by re-scanning the detected networks on a timer,+# with no need to click Scan or keep a browser open (default: true). Set false+# to scan only on demand.+continuous_scan = true++# How often continuous scanning re-scans, in seconds (default: 300 = 5 minutes).scan_interval = 300# Minimum time between manual scans to prevent abuse (default: 30 seconds)@@ -55,6 +60,15 @@ enable_port_scan = false# Port range to scan when port scanning is enabledport_scan_range = 1-1024+# Identify devices more precisely with a light service probe (default: false).+#+# A normal scan is a quiet ping sweep that names devices from their vendor and+# hostname. Turn this on and each discovered device is also checked on a short+# list of well-known ports (web, printer, NAS, and so on) to sharpen its type+# and flag a web interface. It sends a little more traffic and takes a little+# longer, so it is off by default.+enable_service_detection = false+# Networks to scan, in addition to the ones detected automatically.## Detection reads this machine's own network interfaces, which is not always@@ -68,11 +82,32 @@ port_scan_range = 1-1024# devices that do not exist. Run LAN Orangutan natively on those platforms.# networks =+# Networks to hide from the automatically detected list (a blocklist).+#+# Detection offers every real interface it finds. If some of those are networks+# you never want scanned, a guest VLAN, an overlay, or a large slow subnet, list+# them here and they are dropped while everything else stays. Excluding a wide+# block also drops the smaller subnets inside it. A network you name in the+# "networks" setting above is always kept, even if it also appears here.+#+# exclude_networks = 10.99.0.0/16, 192.168.50.0/24+# exclude_networks =++# Scan only the networks declared in "networks", ignoring auto-detection+# entirely (default: false). Useful on a host with many Docker bridges, VLANs+# or routed interfaces where the automatic list is noisy. When true, set+# "networks" to the ones you actually want.+only_configured_networks = false+[storage]-# Maximum number of devices to track+# 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.max_devices = 1000-# Days to keep offline device history+# 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.retention_days = 90# Data storage directory (default varies by OS)@@ -105,6 +140,11 @@ theme = auto# ORANGUTAN_DATA_DIR ORANGUTAN_SCAN_INTERVAL# ORANGUTAN_THEME#+# ORANGUTAN_NETWORKS (comma-separated CIDRs to add)+# ORANGUTAN_EXCLUDE_NETWORKS (comma-separated CIDRs to hide)+# ORANGUTAN_ONLY_CONFIGURED_NETWORKS (true to ignore auto-detection)+# ORANGUTAN_ENABLE_SERVICE_DETECTION (true for deeper device typing)+## ORANGUTAN_PASSWORD_FILE points at a file containing the password, so the# secret never appears in the process environment. It wins over# ORANGUTAN_PASSWORD if both are set.diff --git a/docs/DOCKERHUB.md b/docs/DOCKERHUB.mdindex 5f6f78f..f91c42a 100644--- a/docs/DOCKERHUB.md+++ b/docs/DOCKERHUB.md@@ -79,7 +79,7 @@ services:| Tag | Meaning ||---|---|| `latest` | Most recent release |-| `3.1.4`, `3.1.3`, … | A specific release |+| `3.2.1`, `3.1.4`, … | A specific release |Built for **linux/amd64** and **linux/arm64** (multi-arch manifest, so Raspberry Pi 4/5 and other arm64 boards pull the right image automatically).diff --git a/docs/LO1.png b/docs/LO1.pngindex f35133f..38d2888 100644Binary files a/docs/LO1.png and b/docs/LO1.png differdiff --git a/docs/LO2.png b/docs/LO2.pngindex e58966e..ff7c681 100644Binary files a/docs/LO2.png and b/docs/LO2.png differdiff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 531aefa..a2a6c90 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -87,10 +87,10 @@ Or change the port in your config file.```bash# Allow external accessorangutan serve --bind 0.0.0.0+ ```This is the default. The first visit asks you to create a password, so thedashboard is not left open on your network.- ```## Tailscale not detected@@ -105,6 +105,12 @@ Or change the port in your config file./Applications/Tailscale.app/Contents/MacOS/Tailscale status```+3. **Running in Docker? Tailscale will read as "Not Installed."** The container+ has its own filesystem and cannot see the host's Tailscale, so the status and+ the connect/disconnect controls are unavailable there even when the host is on+ your tailnet. Run the binary directly on the host to use Tailscale with LAN+ Orangutan.+## Connect or disconnect button does nothingThe connect and disconnect buttons run the Tailscale CLI on the machine hostingdiff --git a/internal/api/api.go b/internal/api/api.goindex 5758e3c..9926f8e 100644--- a/internal/api/api.go+++ b/internal/api/api.go@@ -29,6 +29,13 @@ type Handler struct {// scan runs at a time.jobMu sync.Mutexjob *scanJob++ // scanCtx is the parent of every scan job's context, so cancelling it at+ // shutdown stops any scan in flight. scanWG tracks the running scan+ // goroutines so shutdown can wait for them to unwind rather than abandon a+ // scan mid-write.+ scanCtx context.Context+ scanWG sync.WaitGroup}// NewHandler creates a new API handler@@ -36,10 +43,21 @@ func NewHandler(store *storage.Storage, cfg *config.Config) *Handler {return &Handler{store: store,cfg: cfg,- scanner: scanner.New(cfg.Scanning.MinScanInterval),+ scanner: scanner.New(cfg.Scanning.MinScanInterval, cfg.Scanning.EnableServiceDetection),+ scanCtx: context.Background(),}}+// SetScanContext sets the parent context for all scan jobs. Cancelling it stops+// any scan in flight, so call it with the server's shutdown context before+// starting the server.+func (h *Handler) SetScanContext(ctx context.Context) { h.scanCtx = ctx }++// WaitForScans blocks until any running scan goroutine has returned. Call it at+// shutdown, after the scan context has been cancelled, so a scan is not left+// half-written.+func (h *Handler) WaitForScans() { h.scanWG.Wait() }+// ServeHTTP implements http.Handlerfunc (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {// Set JSON content type for all API responses@@ -75,6 +93,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {h.handleScanProgress(w, r)case path == "scan/cancel":h.handleScanCancel(w, r)+ case path == "scan/continuous":+ h.handleScanContinuous(w, r)case path == "tailscale":h.handleTailscale(w, r)case path == "tailscale/connect":@@ -219,7 +239,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, h.cfg.Scanning.Networks))+ h.success(w, network.WithConfigured(networks, network.Filter{Configured: h.cfg.Scanning.Networks, Excluded: h.cfg.Scanning.ExcludeNetworks, OnlyConfigured: h.cfg.Scanning.OnlyConfiguredNetworks}))}// handleScan handles GET /api/scan@@ -308,11 +328,11 @@ type scanAllResult struct {// so one bad interface cannot mask results from the others.func (h *Handler) scanAllNetworks(w http.ResponseWriter, r *http.Request) {detected, err := network.DetectNetworks()- detected = network.WithConfigured(detected, h.cfg.Scanning.Networks)if err != nil {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})if len(detected) == 0 {h.error(w, http.StatusNotFound, "no networks detected")return@@ -351,6 +371,29 @@ func (h *Handler) scanAllNetworks(w http.ResponseWriter, r *http.Request) {result.DeviceCount += scan.DeviceCount}+ // Supplemental sources, once for the whole request. IPv6 neighbors (an IPv6+ // subnet cannot be swept) enrich devices by MAC rather than being listed per+ // address, so they go through MergeIPv6Neighbors. mDNS announcements merge as+ // an ordinary secondary source.+ if ipv6 := h.scanner.DiscoverIPv6(r.Context()); len(ipv6) > 0 {+ if err := h.store.MergeIPv6Neighbors(ipv6); err == nil {+ result.Networks = append(result.Networks, networkScanSummary{+ Network: "IPv6 neighbors", Status: "scanned", DeviceCount: len(ipv6),+ })+ result.ScannedCount+++ result.DeviceCount += len(ipv6)+ }+ }+ if mdns := h.scanner.DiscoverMDNS(r.Context()); len(mdns) > 0 {+ if err := h.store.MergeSupplemental(mdns); err == nil {+ result.Networks = append(result.Networks, networkScanSummary{+ Network: "mDNS", Status: "scanned", DeviceCount: len(mdns),+ })+ result.ScannedCount+++ result.DeviceCount += len(mdns)+ }+ }+// Only a request where nothing at all could be scanned counts as a failure.result.Success = result.ScannedCount > 0h.success(w, result)@@ -367,10 +410,10 @@ func (h *Handler) resolveScanTargets(cidr string) ([]string, error) {}detected, err := network.DetectNetworks()- detected = network.WithConfigured(detected, h.cfg.Scanning.Networks)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})if len(detected) == 0 {return nil, errors.New("no networks detected")}@@ -408,11 +451,16 @@ func (h *Handler) handleScanStart(w http.ResponseWriter, r *http.Request) {defer h.jobMu.Unlock()if h.job != nil && h.job.isRunning() {- h.error(w, http.StatusConflict, "a scan is already running")+ // A scan is already running, most often the background scanner. Rather+ // than rejecting the user's click with a 409, attach to that scan and+ // adopt it as user-initiated so the progress overlay follows it and the+ // user gets the fresh results it is already producing.+ h.job.adopt()+ h.success(w, h.job.snapshot())return}- h.job = h.startScanJob(networks)+ h.job = h.startScanJob(networks, false)h.success(w, h.job.snapshot())}@@ -454,6 +502,39 @@ func (h *Handler) handleScanCancel(w http.ResponseWriter, r *http.Request) {h.success(w, map[string]string{"message": "scan cancelled"})}+// handleScanContinuous reports (GET) or sets (POST) whether the server keeps+// re-scanning the networks on its own. The choice is persisted so it survives a+// restart, letting a user scan once and sit on the snapshot without editing the+// config or restarting.+func (h *Handler) handleScanContinuous(w http.ResponseWriter, r *http.Request) {+ switch r.Method {+ case http.MethodGet:+ h.success(w, map[string]bool{"enabled": h.store.ContinuousScanEnabled(h.cfg.Scanning.ContinuousScan)})+ 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.SetContinuousScan(body.Enabled); err != nil {+ h.error(w, http.StatusInternalServerError, "could not save setting: "+err.Error())+ return+ }+ // Turning it on kicks off a scan right away, so the user sees fresh+ // results instead of waiting up to a full interval for the next tick.+ // Runs in the background; the one-scan-at-a-time guard and the+ // per-network rate limit keep it from piling up or hammering.+ if body.Enabled {+ go h.runBackgroundScan()+ }+ h.success(w, map[string]bool{"enabled": body.Enabled})+ default:+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")+ }+}+// 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)diff --git a/internal/api/scanjob.go b/internal/api/scanjob.goindex 64aba74..1c418e0 100644--- a/internal/api/scanjob.go+++ b/internal/api/scanjob.go@@ -7,10 +7,6 @@ import ("time")-// scanJobTimeout caps how long a single network may be scanned for before it is-// abandoned. Large networks are slow, so this is deliberately generous.-const scanJobTimeout = 10 * time.Minute-// percentUnknown is reported when a network has never been scanned before and// there is therefore no timing history to estimate progress from.const percentUnknown = -1@@ -35,6 +31,11 @@ type scanJob struct {estimatedSeconds float64results []networkScanSummaryerr string++ // automatic marks a scan the background scanner started, as opposed to one+ // the user clicked. Set once at creation. The UI uses it to stay quiet for+ // automatic scans instead of popping the progress overlay on its own.+ automatic bool}// scanProgress is the snapshot of a job returned to the UI.@@ -53,6 +54,10 @@ type scanProgress struct {Remaining *float64 `json:"remaining,omitempty"`Networks []networkScanSummary `json:"networks"`Error string `json:"error,omitempty"`+ // Automatic is true for a scan the background scanner started. The UI does+ // not show its progress overlay for these, so an automatic scan never pops+ // a dialog with a Cancel button on its own.+ Automatic bool `json:"automatic"`}// snapshot returns the current progress of the job. The estimate is based on@@ -74,6 +79,7 @@ func (j *scanJob) snapshot() scanProgress {Percent: percentUnknown,Networks: append([]networkScanSummary(nil), j.results...),Error: j.err,+ Automatic: j.automatic,}// Only a job that ran to completion is 100%. A cancelled or failed job@@ -110,9 +116,12 @@ func (j *scanJob) snapshot() scanProgress {}// startScanJob begins scanning the given networks in the background. The caller-// must hold h.jobMu.-func (h *Handler) startScanJob(networks []string) *scanJob {- ctx, cancel := context.WithCancel(context.Background())+// must hold h.jobMu. automatic marks a scan the background scanner started, so+// the UI can stay quiet for it.+func (h *Handler) startScanJob(networks []string, automatic bool) *scanJob {+ // Descend from h.scanCtx (the server's shutdown context) rather than+ // context.Background(), so cancelling it at shutdown cancels a running scan.+ ctx, cancel := context.WithCancel(h.scanCtx)job := &scanJob{id: fmt.Sprintf("scan-%d", time.Now().UnixNano()),@@ -121,9 +130,14 @@ func (h *Handler) startScanJob(networks []string) *scanJob {status: "running",startedAt: time.Now(),results: make([]networkScanSummary, 0, len(networks)),+ automatic: automatic,}- go job.run(ctx, h)+ h.scanWG.Add(1)+ go func() {+ defer h.scanWG.Done()+ job.run(ctx, h)+ }()return job}@@ -149,9 +163,8 @@ func (j *scanJob) run(ctx context.Context, h *Handler) {continue}- scanCtx, cancel := context.WithTimeout(ctx, scanJobTimeout)- result, err := h.scanNetwork(scanCtx, cidr)- cancel()+ // scanNetwork applies its own per-network timeout.+ result, err := h.scanNetwork(ctx, cidr)if err != nil {// A cancelled job surfaces as a scan error, but it is not a failure.@@ -171,6 +184,24 @@ func (j *scanJob) run(ctx context.Context, h *Handler) {j.addResult(summary, result.DeviceCount)}+ // Supplemental discovery, once for the whole job: IPv6 neighbors (an IPv6+ // subnet cannot be swept) and mDNS announcements. Both merge as secondary+ // sources so they enrich rather than overwrite. A cancelled job skips them.+ if ctx.Err() == nil {+ if ipv6 := h.scanner.DiscoverIPv6(ctx); len(ipv6) > 0 {+ if err := h.store.MergeIPv6Neighbors(ipv6); err == nil {+ j.addResult(networkScanSummary{Network: "IPv6 neighbors", Status: "scanned", DeviceCount: len(ipv6)}, len(ipv6))+ }+ }+ }+ if ctx.Err() == nil {+ if mdns := h.scanner.DiscoverMDNS(ctx); len(mdns) > 0 {+ if err := h.store.MergeSupplemental(mdns); err == nil {+ j.addResult(networkScanSummary{Network: "mDNS", Status: "scanned", DeviceCount: len(mdns)}, len(mdns))+ }+ }+ }+j.finish("done", "")}@@ -207,3 +238,75 @@ func (j *scanJob) isRunning() bool {defer j.mu.RUnlock()return j.status == "running"}++// adopt marks a running job as user-initiated. When someone clicks Scan while+// the background scanner is mid-scan, the manual request attaches to that scan+// (rather than being rejected) and adopts it so the progress overlay follows it+// to completion instead of treating it as a silent automatic scan.+func (j *scanJob) adopt() {+ j.mu.Lock()+ defer j.mu.Unlock()+ j.automatic = false+}++// StartBackgroundScanner re-scans the detected networks every interval so the+// device list stays current on its own, without anyone clicking Scan or keeping+// a browser open. It reuses the same job path, the one-scan-at-a-time guard and+// the per-network rate limiting as a manual scan, and stops when ctx is+// 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+ }++ go func() {+ // Scan shortly after startup so a freshly started server does not sit+ // empty until the first interval elapses.+ startup := time.NewTimer(5 * time.Second)+ defer startup.Stop()+ select {+ case <-ctx.Done():+ return+ case <-startup.C:+ }+ h.runBackgroundScan()++ ticker := time.NewTicker(interval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ h.runBackgroundScan()+ }+ }+ }()+}++// 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+// allows, however short the interval.+func (h *Handler) runBackgroundScan() {+ // The ticker always runs so the setting can be toggled at runtime; skip the+ // actual scan when continuous scanning is currently switched off.+ if !h.store.ContinuousScanEnabled(h.cfg.Scanning.ContinuousScan) {+ return+ }++ networks, err := h.resolveScanTargets("all")+ if err != nil || len(networks) == 0 {+ return+ }++ h.jobMu.Lock()+ defer h.jobMu.Unlock()++ if h.job != nil && h.job.isRunning() {+ return+ }+ h.job = h.startScanJob(networks, true)+}diff --git a/internal/cli/networks.go b/internal/cli/networks.goindex ea589bb..1dbd634 100644--- a/internal/cli/networks.go+++ b/internal/cli/networks.go@@ -16,7 +16,7 @@ var networksCmd = &cobra.Command{func runNetworks(cmd *cobra.Command, args []string) error {networks, err := network.DetectNetworks()- networks = network.WithConfigured(networks, cfg.Scanning.Networks)+ 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)}diff --git a/internal/cli/scan.go b/internal/cli/scan.goindex fb159cc..9e754cf 100644--- a/internal/cli/scan.go+++ b/internal/cli/scan.go@@ -32,7 +32,7 @@ func runScan(cmd *cobra.Command, args []string) error {}// Create scanner- s := scanner.New(cfg.Scanning.MinScanInterval)+ s := scanner.New(cfg.Scanning.MinScanInterval, cfg.Scanning.EnableServiceDetection)// Determine networks to scanvar networks []string@@ -40,7 +40,7 @@ func runScan(cmd *cobra.Command, args []string) error {if len(args) == 0 || args[0] == "" {// Scan first detected networkdetected, err := network.DetectNetworks()- detected = network.WithConfigured(detected, cfg.Scanning.Networks)+ detected = network.WithConfigured(detected, 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)}@@ -60,7 +60,7 @@ func runScan(cmd *cobra.Command, args []string) error {} else if args[0] == "all" {// Scan all detected networksdetected, err := network.DetectNetworks()- detected = network.WithConfigured(detected, cfg.Scanning.Networks)+ detected = network.WithConfigured(detected, 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)}@@ -157,6 +157,27 @@ func runScan(cmd *cobra.Command, args []string) error {}}+ // When scanning everything, also pick up IPv6 neighbors and mDNS+ // announcements, which cannot be reached by sweeping a range. Both merge as+ // secondary sources so they enrich rather than overwrite.+ if len(args) > 0 && args[0] == "all" {+ ctx := context.Background()+ if ipv6 := s.DiscoverIPv6(ctx); len(ipv6) > 0 {+ if err := store.MergeSupplemental(ipv6); err != nil {+ fmt.Fprintf(os.Stderr, "Error saving IPv6 neighbors: %v\n", err)+ } else {+ fmt.Printf("Found %d IPv6 neighbor(s)\n", len(ipv6))+ }+ }+ if mdns := s.DiscoverMDNS(ctx); len(mdns) > 0 {+ if err := store.MergeSupplemental(mdns); err != nil {+ fmt.Fprintf(os.Stderr, "Error saving mDNS devices: %v\n", err)+ } else {+ fmt.Printf("Found %d mDNS device(s)\n", len(mdns))+ }+ }+ }+return nil}diff --git a/internal/cli/serve.go b/internal/cli/serve.goindex 299a296..3caa2aa 100644--- a/internal/cli/serve.go+++ b/internal/cli/serve.go@@ -47,6 +47,12 @@ func runServe(cmd *cobra.Command, args []string) error {// problem, not a usage error. Report it without the flag listing.cmd.SilenceUsage = true+ // Repair any out-of-range scan timings before they are used, so a config+ // typo cannot silently switch off the background scanner or rate limiting.+ for _, note := range cfg.Normalize() {+ fmt.Fprintf(os.Stderr, "config: %s\n", note)+ }+// Use flags or configport := cfg.Server.Portif servePort > 0 {@@ -89,6 +95,18 @@ func runServe(cmd *cobra.Command, args []string) error {webHandler := web.NewHandler(store, cfg, authn, Version)apiHandler := api.NewHandler(store, cfg)+ // Keep the device list current on its own: re-scan the detected networks+ // every scan_interval seconds. Without this the list only changes when+ // someone clicks Scan, so "auto-refresh" would only ever re-draw the same+ // stored results. Cancelling scanCtx at shutdown stops the scheduler and+ // cancels any scan already in flight. The ticker always runs so continuous+ // scanning can be switched on and off from the UI at runtime; the scanner+ // itself skips scans while the setting is off (default comes from config).+ scanCtx, scanCancel := context.WithCancel(context.Background())+ defer scanCancel()+ apiHandler.SetScanContext(scanCtx)+ apiHandler.StartBackgroundScanner(scanCtx, time.Duration(cfg.Scanning.ScanInterval)*time.Second)+// Protected routes.mux.Handle("/api/", authn.Middleware(apiHandler))mux.Handle("/", authn.Middleware(webHandler))@@ -133,6 +151,7 @@ func runServe(cmd *cobra.Command, args []string) error {go func() {<-quitfmt.Println("\nShutting down server...")+ scanCancel() // stop the background scanner promptlyctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()@@ -141,6 +160,21 @@ func runServe(cmd *cobra.Command, args []string) error {if err := server.Shutdown(ctx); err != nil {fmt.Fprintf(os.Stderr, "Error shutting down: %v\n", err)}++ // scanCancel above cancels the context of any scan in flight, which+ // kills its nmap child and lets the job return. Wait for that goroutine+ // to unwind so we do not exit mid-write, bounded so a stuck scan cannot+ // block shutdown forever.+ scansDone := make(chan struct{})+ go func() {+ apiHandler.WaitForScans()+ close(scansDone)+ }()+ select {+ case <-scansDone:+ case <-time.After(5 * time.Second):+ }+close(done)}()@@ -179,7 +213,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, cfg.Scanning.Networks)+ detected = network.WithConfigured(detected, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})if warning := network.IsolationWarning(detected); warning != "" {fmt.Println()fmt.Println(" ┌─────────────────────────────────────────────────────────────┐")diff --git a/internal/cli/status.go b/internal/cli/status.goindex 0401518..7df9cb9 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, cfg.Scanning.Networks)+ networks = network.WithConfigured(networks, network.Filter{Configured: cfg.Scanning.Networks, Excluded: cfg.Scanning.ExcludeNetworks, OnlyConfigured: cfg.Scanning.OnlyConfiguredNetworks})if err != nil {fmt.Printf(" Error detecting: %v\n", err)} else {diff --git a/internal/config/config.go b/internal/config/config.goindex bce889e..d4b6482 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -117,6 +117,30 @@ type ScanningConfig struct {EnablePortScan boolPortScanRange string+ // ContinuousScan makes the server re-scan the detected networks on its own+ // every ScanInterval seconds, so the device list stays current without+ // anyone clicking Scan or keeping a browser open. On by default: a+ // discovery tool that only ever shows one stale scan is not much use. Set+ // it false to scan only on demand.+ ContinuousScan bool++ // EnableServiceDetection turns on a light probe of a few well-known ports+ // during a scan, used only to identify devices more precisely (a printer, a+ // NAS, a device with a web interface). Off by default so the scan stays a+ // quiet ping sweep unless the user opts in.+ EnableServiceDetection bool++ // OnlyConfiguredNetworks, when true, offers only the networks declared in+ // Networks and ignores everything auto-detection finds. Useful on a host+ // with many Docker bridges, VLANs or routed interfaces where the automatic+ // list is noisy.+ OnlyConfiguredNetworks bool++ // ExcludeNetworks are CIDRs to drop from the auto-detected list, for real+ // networks the user does not want scanned. A blocklist that complements+ // Networks (the allowlist): keep auto-detection but hide a few subnets.+ ExcludeNetworks []string+// Networks are CIDRs the user has declared explicitly, for cases where// automatic detection cannot see the right network. A container only sees// Docker's private network, so without this it can never scan the LAN.@@ -141,6 +165,13 @@ type UIConfig struct {Theme string}+// Sensible fallbacks for the scan timings, also used by Normalize to repair an+// out-of-range value rather than let it silently disable a feature.+const (+ defaultScanInterval = 300+ defaultMinScanInterval = 30+)+// Default returns a Config with default valuesfunc Default() *Config {return &Config{@@ -155,10 +186,12 @@ func Default() *Config {SessionHours: 24 * 7,},Scanning: ScanningConfig{- ScanInterval: 300,- MinScanInterval: 30,- EnablePortScan: false,- PortScanRange: "1-1024",+ ScanInterval: defaultScanInterval,+ MinScanInterval: defaultMinScanInterval,+ EnablePortScan: false,+ PortScanRange: "1-1024",+ ContinuousScan: true,+ EnableServiceDetection: false,},Storage: StorageConfig{MaxDevices: 1000,@@ -260,8 +293,16 @@ func (c *Config) setValue(section, key, value string) {c.Scanning.EnablePortScan = parseBool(value)case "port_scan_range":c.Scanning.PortScanRange = value+ case "continuous_scan":+ c.Scanning.ContinuousScan = parseBool(value)+ case "enable_service_detection":+ c.Scanning.EnableServiceDetection = parseBool(value)+ case "only_configured_networks":+ c.Scanning.OnlyConfiguredNetworks = parseBool(value)case "networks":c.Scanning.Networks = network.ParseNetworkList(value)+ case "exclude_networks":+ c.Scanning.ExcludeNetworks = network.ParseNetworkList(value)}case "storage":switch key {@@ -331,16 +372,55 @@ func (c *Config) ApplyEnv() {if v := os.Getenv("ORANGUTAN_NETWORKS"); v != "" {c.Scanning.Networks = network.ParseNetworkList(v)}+ if v := os.Getenv("ORANGUTAN_ENABLE_SERVICE_DETECTION"); v != "" {+ c.Scanning.EnableServiceDetection = parseBool(v)+ }+ if v := os.Getenv("ORANGUTAN_ONLY_CONFIGURED_NETWORKS"); v != "" {+ c.Scanning.OnlyConfiguredNetworks = parseBool(v)+ }+ if v := os.Getenv("ORANGUTAN_EXCLUDE_NETWORKS"); v != "" {+ c.Scanning.ExcludeNetworks = network.ParseNetworkList(v)+ }if v := os.Getenv("ORANGUTAN_SCAN_INTERVAL"); v != "" {if n, err := strconv.Atoi(v); err == nil {c.Scanning.ScanInterval = n}}+ if v := os.Getenv("ORANGUTAN_CONTINUOUS_SCAN"); v != "" {+ c.Scanning.ContinuousScan = parseBool(v)+ }if v := os.Getenv("ORANGUTAN_THEME"); v != "" {c.UI.Theme = v}}+// Normalize repairs out-of-range scan timings, clamping them back to the+// defaults, and returns a human-readable note for each value it had to correct.+// A non-positive scan_interval would otherwise silently disable the background+// scanner even with continuous_scan on, and a non-positive min_scan_interval+// would silently disable per-network rate limiting; both are corrected here so+// a config typo cannot quietly turn a feature off. Call it after loading the+// config from file and environment.+func (c *Config) Normalize() []string {+ var notes []string++ if c.Scanning.MinScanInterval <= 0 {+ notes = append(notes, fmt.Sprintf(+ "min_scan_interval was %d; using %d so per-network rate limiting stays on",+ c.Scanning.MinScanInterval, defaultMinScanInterval))+ c.Scanning.MinScanInterval = defaultMinScanInterval+ }++ if c.Scanning.ScanInterval <= 0 {+ notes = append(notes, fmt.Sprintf(+ "scan_interval was %d; using %d so continuous scanning works when enabled",+ c.Scanning.ScanInterval, defaultScanInterval))+ c.Scanning.ScanInterval = defaultScanInterval+ }++ return notes+}+// IsLoopbackBind reports whether the configured bind address only accepts// connections from the machine the app is running on.//diff --git a/internal/config/config_test.go b/internal/config/config_test.goindex 12d7dae..8c7e0cc 100644--- a/internal/config/config_test.go+++ b/internal/config/config_test.go@@ -79,6 +79,35 @@ allow_insecure = true}}+func TestContinuousScanDefaultsOn(t *testing.T) {+ if !Default().Scanning.ContinuousScan {+ t.Error("continuous_scan should default to true")+ }+}++func TestContinuousScanCanBeDisabled(t *testing.T) {+ path := writeConfig(t, `+[scanning]+continuous_scan = false+`)+ cfg, err := Load(path)+ if err != nil {+ t.Fatalf("Load: %v", err)+ }+ if cfg.Scanning.ContinuousScan {+ t.Error("continuous_scan = false in the file should disable it")+ }+}++func TestContinuousScanEnvOverride(t *testing.T) {+ t.Setenv("ORANGUTAN_CONTINUOUS_SCAN", "false")+ cfg := Default()+ cfg.ApplyEnv()+ if cfg.Scanning.ContinuousScan {+ t.Error("ORANGUTAN_CONTINUOUS_SCAN=false should disable continuous scan")+ }+}+func TestIsLoopbackBind(t *testing.T) {tests := []struct {addr string@@ -295,3 +324,59 @@ port = 4242t.Errorf("port = %d, want 4242", cfg.Server.Port)}}++func TestNormalizeClampsNonPositiveScanInterval(t *testing.T) {+ c := Default()+ c.Scanning.ContinuousScan = true+ c.Scanning.ScanInterval = 0++ notes := c.Normalize()++ if c.Scanning.ScanInterval != defaultScanInterval {+ t.Errorf("scan_interval = %d, want clamped to %d", c.Scanning.ScanInterval, defaultScanInterval)+ }+ if len(notes) == 0 {+ t.Error("expected a warning note about scan_interval, got none")+ }+}++func TestNormalizeClampsNonPositiveMinScanInterval(t *testing.T) {+ c := Default()+ c.Scanning.MinScanInterval = -5++ notes := c.Normalize()++ if c.Scanning.MinScanInterval != defaultMinScanInterval {+ t.Errorf("min_scan_interval = %d, want clamped to %d", c.Scanning.MinScanInterval, defaultMinScanInterval)+ }+ if len(notes) == 0 {+ t.Error("expected a warning note about min_scan_interval, got none")+ }+}++func TestNormalizeClampsScanIntervalEvenWhenContinuousScanOff(t *testing.T) {+ c := Default()+ c.Scanning.ContinuousScan = false+ c.Scanning.ScanInterval = 0++ c.Normalize()++ // Continuous scanning can be switched on at runtime from the UI, so the+ // interval must always be valid even if it starts disabled.+ if c.Scanning.ScanInterval != defaultScanInterval {+ t.Errorf("scan_interval = %d, want clamped to %d", c.Scanning.ScanInterval, defaultScanInterval)+ }+}++func TestNormalizeLeavesValidValuesAlone(t *testing.T) {+ c := Default()++ notes := c.Normalize()++ if len(notes) != 0 {+ t.Errorf("expected no warnings for default config, got %v", notes)+ }+ if c.Scanning.ScanInterval != defaultScanInterval || c.Scanning.MinScanInterval != defaultMinScanInterval {+ t.Error("Normalize changed already-valid values")+ }+}diff --git a/internal/network/configured.go b/internal/network/configured.goindex dfcec2d..4a1507b 100644--- a/internal/network/configured.go+++ b/internal/network/configured.go@@ -7,17 +7,40 @@ import ("github.com/291-Group/LAN-Orangutan/internal/types")-// WithConfigured returns the detected networks plus any the user has declared-// explicitly, with duplicates removed.+// Filter describes how the detected network list should be adjusted before it+// is offered for scanning.+type Filter struct {+ // Configured are CIDRs the user declared explicitly. They are always+ // included, even a container bridge, since the user asked for them.+ Configured []string+ // Excluded are CIDRs to drop from the detected list, for real networks the+ // user does not want scanned (a guest VLAN, a slow /16, an overlay). A+ // detected network is dropped when its address falls inside an excluded+ // range. Explicitly configured networks are never excluded.+ Excluded []string+ // OnlyConfigured, when true, ignores auto-detection entirely and offers only+ // the Configured networks. Useful where the automatic list is noisy with+ // container bridges, VLANs or routed interfaces.+ OnlyConfigured bool+}++// WithConfigured returns the detected networks, adjusted by the filter, plus any+// the user has declared explicitly, with duplicates removed.//// Automatic detection reads the machine's own interfaces, which is wrong in a// container: it sees only Docker's private network and never the LAN the user-// actually wants scanned. Declaring a network here makes it available to scan-// and visible on the dashboard even though no local interface belongs to it.-func WithConfigured(detected []types.Network, configured []string) []types.Network {- // Docker's own bridge is a real interface but holds containers, not devices- // on your network. Sweeping its /16 finds nothing and takes minutes.- detected = ExcludeContainerNetworks(detected)+// actually wants scanned. Declaring a network makes it available to scan and+// visible on the dashboard even though no local interface belongs to it.+func WithConfigured(detected []types.Network, f Filter) []types.Network {+ if f.OnlyConfigured {+ detected = nil+ } else {+ // A container bridge is a real interface but holds containers, not+ // devices on your network. Sweeping it finds nothing and takes minutes.+ detected = ExcludeContainerNetworks(detected)+ detected = excludeNetworks(detected, f.Excluded)+ }+ configured := f.Configuredseen := make(map[string]bool, len(detected)+len(configured))result := make([]types.Network, 0, len(detected)+len(configured))@@ -49,6 +72,49 @@ func WithConfigured(detected []types.Network, configured []string) []types.Networeturn result}+// excludeNetworks drops detected networks that fall inside any of the excluded+// CIDRs. A detected network matches when its own address is contained in an+// excluded range, so excluding a wide block (192.168.0.0/20) also drops the+// smaller subnets inside it. Unparseable excludes are ignored.+func excludeNetworks(detected []types.Network, excluded []string) []types.Network {+ if len(excluded) == 0 {+ return detected+ }++ blocks := make([]*net.IPNet, 0, len(excluded))+ for _, cidr := range excluded {+ if _, block, err := net.ParseCIDR(strings.TrimSpace(cidr)); err == nil {+ blocks = append(blocks, block)+ }+ }+ if len(blocks) == 0 {+ return detected+ }++ out := make([]types.Network, 0, len(detected))+ for _, n := range detected {+ ip, _, err := net.ParseCIDR(n.CIDR)+ if err != nil {+ out = append(out, n) // keep anything we cannot parse rather than drop it+ continue+ }+ if containsAny(blocks, ip) {+ continue+ }+ out = append(out, n)+ }+ return out+}++func containsAny(blocks []*net.IPNet, ip net.IP) bool {+ for _, b := range blocks {+ if b.Contains(ip) {+ return true+ }+ }+ return false+}+// friendlyNameFor labels a declared network so it is distinguishable from one// that was detected.func friendlyNameFor(cidr string) string {diff --git a/internal/network/configured_test.go b/internal/network/configured_test.goindex 3df395e..7f7e368 100644--- a/internal/network/configured_test.go+++ b/internal/network/configured_test.go@@ -23,7 +23,7 @@ func TestParseNetworkList(t *testing.T) {}func TestConfiguredNetworksAreAdded(t *testing.T) {- got := WithConfigured(nil, []string{"192.168.50.0/24"})+ got := WithConfigured(nil, Filter{Configured: []string{"192.168.50.0/24"}})if len(got) != 1 {t.Fatalf("expected the configured network to be added, got %d", len(got))}@@ -36,8 +36,8 @@ func TestConfiguredNetworksAreAdded(t *testing.T) {}func TestDuplicatesAreNotAddedTwice(t *testing.T) {- detected := WithConfigured(nil, []string{"192.168.50.0/24"})- again := WithConfigured(detected, []string{"192.168.50.0/24"})+ detected := WithConfigured(nil, Filter{Configured: []string{"192.168.50.0/24"}})+ again := WithConfigured(detected, Filter{Configured: []string{"192.168.50.0/24"}})if len(again) != 1 {t.Errorf("a network already present should not be added again, got %d", len(again))@@ -45,7 +45,7 @@ func TestDuplicatesAreNotAddedTwice(t *testing.T) {}func TestInvalidCIDRsAreIgnored(t *testing.T) {- got := WithConfigured(nil, []string{"not-a-network", "192.168.1.999/24", "192.168.50.0/24"})+ got := WithConfigured(nil, Filter{Configured: []string{"not-a-network", "192.168.1.999/24", "192.168.50.0/24"}})if len(got) != 1 {t.Fatalf("only the valid network should survive, got %d", len(got))}diff --git a/internal/network/container.go b/internal/network/container.goindex 4e5bb1d..47b70b0 100644--- a/internal/network/container.go+++ b/internal/network/container.go@@ -22,14 +22,44 @@ func InContainer() bool {return false}-// dockerPrivateRanges are the address ranges a container sees when it is-// attached to Docker's own network rather than the host's.+// dockerPrivateRanges are the address ranges a container is given when it is+// attached to a container runtime's own network rather than the host's. They are+// used only to detect that this process is isolated inside such a network, where+// interface names do not help because the container simply sees "eth0".+//+// The Docker range is the default bridge's 172.17.0.0/16, not the whole+// 172.16.0.0/12. The wider block is legitimate RFC1918 space that real LANs use,+// so matching all of it wrongly flags a real 172.x network as container-only.var dockerPrivateRanges = []string{- "172.16.0.0/12", // default bridge networks+ "172.17.0.0/16", // Docker default bridge"192.168.65.0/24", // Docker Desktop's virtual machine"10.88.0.0/16", // podman default}+// isContainerInterface reports whether an interface name belongs to a container+// runtime rather than a real network. Docker's bridge is docker0, its+// user-defined networks are br-<hash>, and the host side of a container's link+// is veth*. Podman uses podman0 or cni-podman*.+//+// A plain br0, bridge0 or similar is deliberately not matched: those are+// ordinary Linux bridges a user may legitimately put a real LAN on. Only the+// br- form (with the hyphen), which Docker generates, is treated as a container+// bridge.+func isContainerInterface(name string) bool {+ switch {+ case strings.HasPrefix(name, "docker"):+ return true+ case strings.HasPrefix(name, "br-"):+ return true+ case strings.HasPrefix(name, "veth"):+ return true+ case strings.HasPrefix(name, "podman"), strings.HasPrefix(name, "cni-podman"):+ return true+ default:+ return false+ }+}+// isDockerPrivate reports whether a CIDR belongs to Docker's own networking// rather than a real LAN.func isDockerPrivate(cidr string) bool {@@ -78,21 +108,26 @@ func IsolationWarning(detected []types.Network) string {"Use host networking on Linux, or run LAN Orangutan directly on macOS and Windows."}-// ExcludeContainerNetworks drops Docker's own bridge networks from a detected-// list.+// ExcludeContainerNetworks drops container bridge networks (Docker, Podman) from+// a detected list, identifying them by their interface name rather than by+// address range.//-// A host running Docker has a docker0 bridge, typically 172.17.0.0/16. It is a-// real interface, so detection finds it, but it holds containers rather than-// devices on your network. Scanning it sweeps 65,536 addresses to find nothing-// of interest, which on a Raspberry Pi takes minutes and makes "Scan All" look-// broken.+// A host running Docker has a docker0 bridge, and user-defined networks appear+// as br-<hash>. These are real interfaces, so detection finds them, but they+// hold containers rather than devices on your network. Scanning one sweeps+// thousands of addresses to find nothing of interest, which on a Raspberry Pi+// takes minutes and makes "Scan All" look broken.//-// Anyone who genuinely wants to scan it can still name it explicitly through-// the networks setting.+// The interface name is used deliberately, not the address range. Docker+// allocates from the same RFC1918 blocks (172.16/12, 192.168/16) that real LANs+// use, so an address guess would both hide a real LAN on 172.x and miss a Docker+// bridge on 192.168.x. The interface name is unambiguous. Anyone who genuinely+// wants to scan a container bridge can still name it explicitly through the+// networks setting.func ExcludeContainerNetworks(detected []types.Network) []types.Network {out := make([]types.Network, 0, len(detected))for _, n := range detected {- if isDockerPrivate(n.CIDR) {+ if isContainerInterface(n.Interface) {continue}out = append(out, n)diff --git a/internal/network/container_test.go b/internal/network/container_test.goindex a2266b1..dc8c18b 100644--- a/internal/network/container_test.go+++ b/internal/network/container_test.go@@ -7,17 +7,21 @@ import ()func TestDockerPrivateRangeDetection(t *testing.T) {+ // isDockerPrivate now backs only the in-container isolation check, and uses+ // the narrow Docker default bridge (172.17.0.0/16), not the whole /12, so a+ // real 172.x LAN is not mistaken for container networking.tests := []struct {cidr stringprivate bool}{- {"172.17.0.0/16", true}, // default docker bridge- {"172.18.0.0/16", true}, // user-defined bridge- {"192.168.65.0/24", true}, // Docker Desktop VM- {"10.88.0.0/16", true}, // podman- {"192.168.1.0/24", false}, // a real home LAN- {"192.168.68.0/22", false}, // a real home LAN- {"10.0.0.0/24", false}, // a real LAN+ {"172.17.0.0/16", true}, // Docker default bridge+ {"192.168.65.0/24", true}, // Docker Desktop VM+ {"10.88.0.0/16", true}, // podman+ {"172.18.0.0/16", false}, // no longer assumed to be Docker+ {"172.20.20.0/24", false}, // the reporter's real LAN, must not match+ {"192.168.1.0/24", false}, // a real home LAN+ {"192.168.68.0/22", false},+ {"10.0.0.0/24", false},{"not-a-cidr", false},}for _, tt := range tests {@@ -27,16 +31,37 @@ func TestDockerPrivateRangeDetection(t *testing.T) {}}+func TestIsContainerInterface(t *testing.T) {+ tests := []struct {+ name string+ want bool+ }{+ {"docker0", true},+ {"br-1a2b3c4d5e6f", true}, // Docker user-defined bridge+ {"veth3a2b1c", true},+ {"podman0", true},+ {"cni-podman0", true},+ {"eth0", false},+ {"enp3s0", false},+ {"wlan0", false},+ {"br0", false}, // an ordinary Linux bridge, could carry a real LAN+ {"bridge0", false}, // likewise+ {"", false},+ }+ for _, tt := range tests {+ if got := isContainerInterface(tt.name); got != tt.want {+ t.Errorf("isContainerInterface(%q) = %v, want %v", tt.name, got, tt.want)+ }+ }+}+func TestIsolationWarningOnlyWhenIsolated(t *testing.T) {- // Outside a container there is nothing to warn about, whatever the- // networks look like.if w := IsolationWarning([]types.Network{{CIDR: "172.17.0.0/16"}}); !InContainer() && w != "" {t.Error("no warning should be produced when not running in a container")}}func TestRealNetworkMeansNotIsolated(t *testing.T) {- // A container that can see a real LAN, as with host networking, is fine.networks := []types.Network{{CIDR: "172.17.0.0/16"},{CIDR: "192.168.1.0/24"},@@ -46,30 +71,89 @@ func TestRealNetworkMeansNotIsolated(t *testing.T) {}}+// TestExcludeContainerNetworks covers the reported bug: exclusion keys off the+// interface name, not the address range, so a real LAN on 172.x is kept while+// Docker bridges are dropped regardless of the range they use.func TestExcludeContainerNetworks(t *testing.T) {in := []types.Network{- {CIDR: "192.168.1.0/24"}, // real LAN- {CIDR: "172.17.0.0/16"}, // docker0 bridge- {CIDR: "192.168.68.0/22"}, // real LAN- {CIDR: "172.18.0.0/16"}, // user-defined docker bridge- {CIDR: "192.168.65.0/24"}, // Docker Desktop VM+ {CIDR: "172.20.20.0/24", Interface: "eth0"}, // the reporter's real LAN+ {CIDR: "172.17.0.0/16", Interface: "docker0"}, // Docker default bridge+ {CIDR: "172.18.0.0/16", Interface: "br-a1b2c3d4e5"}, // Docker user bridge+ {CIDR: "192.168.0.0/20", Interface: "br-9f8e7d6c"}, // Docker bridge on 192.168.x+ {CIDR: "192.168.1.0/24", Interface: "wlan0"}, // real LAN+ {CIDR: "10.0.5.0/24", Interface: "veth12ab34"}, // container veth}got := ExcludeContainerNetworks(in)- if len(got) != 2 {- t.Fatalf("expected only the two real networks, got %d: %v", len(got), got)- }+ kept := map[string]bool{}for _, n := range got {- if n.CIDR != "192.168.1.0/24" && n.CIDR != "192.168.68.0/22" {- t.Errorf("unexpected network kept: %s", n.CIDR)- }+ kept[n.CIDR] = true+ }+ if !kept["172.20.20.0/24"] {+ t.Error("the real 172.20 LAN on eth0 must be kept (the reported bug)")+ }+ if !kept["192.168.1.0/24"] {+ t.Error("the real LAN on wlan0 must be kept")+ }+ if kept["172.17.0.0/16"] || kept["172.18.0.0/16"] || kept["192.168.0.0/20"] || kept["10.0.5.0/24"] {+ t.Errorf("a container bridge was kept: %v", got)+ }+ if len(got) != 2 {+ t.Fatalf("expected exactly the two real LANs, got %d: %v", len(got), got)}}func TestConfiguredContainerNetworkIsStillHonoured(t *testing.T) {// Filtering applies to detection, not to a network the user asked for.- got := WithConfigured(nil, []string{"172.17.0.0/16"})+ got := WithConfigured(nil, Filter{Configured: []string{"172.17.0.0/16"}})if len(got) != 1 || got[0].CIDR != "172.17.0.0/16" {t.Errorf("an explicitly configured network should survive, got %v", got)}}++// TestOnlyConfiguredIgnoresDetected confirms that with only-configured on, the+// auto-detected networks are dropped entirely and only declared ones remain.+func TestOnlyConfiguredIgnoresDetected(t *testing.T) {+ detected := []types.Network{+ {CIDR: "192.168.1.0/24", Interface: "eth0"},+ {CIDR: "10.0.0.0/24", Interface: "wlan0"},+ }+ got := WithConfigured(detected, Filter{Configured: []string{"172.20.20.0/24"}, OnlyConfigured: true})+ if len(got) != 1 || got[0].CIDR != "172.20.20.0/24" {+ t.Errorf("only-configured should return just the declared network, got %v", got)+ }+}++// TestExcludeNetworks confirms the blocklist drops a real detected network the+// user does not want, including subnets inside a wider excluded block, while+// leaving the rest of auto-detection intact and never touching a configured net.+func TestExcludeNetworks(t *testing.T) {+ detected := []types.Network{+ {CIDR: "192.168.1.0/24", Interface: "eth0"}, // keep+ {CIDR: "192.168.5.0/24", Interface: "eth1"}, // inside excluded 192.168.4.0/22, drop+ {CIDR: "10.10.0.0/24", Interface: "eth2"}, // excluded exactly, drop+ }+ got := WithConfigured(detected, Filter{+ Excluded: []string{"192.168.4.0/22", "10.10.0.0/24"},+ })++ kept := map[string]bool{}+ for _, n := range got {+ kept[n.CIDR] = true+ }+ if !kept["192.168.1.0/24"] {+ t.Error("a network outside the excludes must be kept")+ }+ if kept["192.168.5.0/24"] || kept["10.10.0.0/24"] {+ t.Errorf("an excluded network was kept: %v", got)+ }++ // A configured network is never excluded, even if it falls in an exclude.+ got = WithConfigured(nil, Filter{+ Configured: []string{"10.10.0.0/24"},+ Excluded: []string{"10.10.0.0/24"},+ })+ if len(got) != 1 || got[0].CIDR != "10.10.0.0/24" {+ t.Errorf("an explicitly configured network must survive an exclude, got %v", got)+ }+}diff --git a/internal/network/tailscale_control.go b/internal/network/tailscale_control.goindex 7df28b0..708f3e5 100644--- a/internal/network/tailscale_control.go+++ b/internal/network/tailscale_control.go@@ -4,6 +4,7 @@ import ("bytes""context""fmt"+ "net/url""os/exec""regexp""strings"@@ -19,10 +20,27 @@ import (// detected and returned as soon as it appears, well before this fires.const tailscaleUpTimeout = 20 * time.Second-// loginURLPattern matches the sign-in URL that `tailscale up` prints when the-// machine is not yet authenticated to a tailnet.+// 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+`)+// 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+// 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 == "" {+ return ""+ }+ u, err := url.Parse(candidate)+ if err != nil || u.Scheme != "https" || u.Hostname() != "login.tailscale.com" {+ return ""+ }+ return candidate+}+// TailscaleActionResult describes the outcome of a connect attempt.type TailscaleActionResult struct {// Connected is true when the machine is up on the tailnet.@@ -69,7 +87,7 @@ func ConnectTailscale() (TailscaleActionResult, error) {select {case err := <-done:text := out.String()- if url := loginURLPattern.FindString(text); url != "" {+ if url := extractLoginURL(text); url != "" {return TailscaleActionResult{LoginURL: url}, nil}if err != nil {@@ -78,7 +96,7 @@ func ConnectTailscale() (TailscaleActionResult, error) {return TailscaleActionResult{Connected: IsTailscaleConnected()}, nilcase <-ticker.C:- if url := loginURLPattern.FindString(out.String()); url != "" {+ if url := extractLoginURL(out.String()); url != "" {cancel() // stop waiting; the user must sign in via the URL<-done // reap the processreturn TailscaleActionResult{LoginURL: url}, nildiff --git a/internal/network/tailscale_control_test.go b/internal/network/tailscale_control_test.goindex 7561d97..c8def3f 100644--- a/internal/network/tailscale_control_test.go+++ b/internal/network/tailscale_control_test.go@@ -92,3 +92,27 @@ func TestSyncBufferConcurrentWrites(t *testing.T) {t.Errorf("expected 1000 bytes written, got %d", len(b.String()))}}++func TestExtractLoginURL(t *testing.T) {+ // The URL appears in the middle of multi-line output; extraction still finds+ // it and confirms the host with a real parse.+ out := "\nTo authenticate, visit:\n\n\thttps://login.tailscale.com/a/1a2b3c4d5e6f\n\n"+ if got := extractLoginURL(out); got != "https://login.tailscale.com/a/1a2b3c4d5e6f" {+ t.Errorf("expected the login URL, got %q", got)+ }++ // No URL in the output.+ if got := extractLoginURL("Success.\n"); got != "" {+ t.Errorf("expected empty, got %q", got)+ }++ // A bare hostname without https:// is not a URL and must not be returned.+ if got := extractLoginURL("see login.tailscale.com/foo for details"); got != "" {+ 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.+ 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)+ }+}diff --git a/internal/scanner/classify.go b/internal/scanner/classify.gonew file mode 100644index 0000000..69bc1c5--- /dev/null+++ b/internal/scanner/classify.go@@ -0,0 +1,145 @@+package scanner++import "strings"++// Device type labels produced by Classify. They are stable strings so stored+// records, the API and the UI can all rely on them. TypeUnknown is the empty+// string so an unclassified device carries no type rather than a placeholder.+const (+ TypePhone = "Phone"+ TypeComputer = "Computer"+ TypePrinter = "Printer"+ TypeTV = "TV"+ TypeMediaPlayer = "Media Player"+ TypeRouter = "Router"+ TypeServer = "Server"+ TypeIoT = "IoT"+ TypeConsole = "Game Console"+ TypeUnknown = ""+)++// Classify infers a device's type from the signals a scan gathers: its vendor+// (from the MAC OUI), its hostname, and, when service detection is enabled, the+// open ports found. It returns one of the Type* labels, or TypeUnknown when+// nothing matches.+//+// Signals are weighed by how specific they are. A hostname or an open service+// port identifies a device far more reliably than its vendor, which is often+// shared across very different products: Apple makes phones, laptops and TVs+// under one OUI. So hostname wins first, then ports, and vendor is the broad+// fallback that still covers a device with no useful name.+func Classify(vendor, hostname string, openPorts []int) string {+ if t := classifyByHostname(hostname); t != TypeUnknown {+ return t+ }+ // Definitive ports identify one specific kind of hardware (a printer, an+ // iPhone) and outrank the broad vendor guess.+ if t := classifyByPorts(openPorts, definitivePorts); t != TypeUnknown {+ return t+ }+ if t := classifyByVendor(vendor); t != TypeUnknown {+ return t+ }+ // Indicative ports point to a role a device is playing (a media server, a+ // NAS service) rather than the hardware itself, so they only classify when+ // vendor and hostname gave nothing. A Mac running Plex stays a Computer.+ return classifyByPorts(openPorts, indicativePorts)+}++// rule pairs a set of lower-case substrings with the type they indicate. The+// first rule whose substring is contained in the (lower-cased) input wins, so+// more specific rules are listed before broader ones.+type rule struct {+ needles []string+ typ string+}++func matchRules(s string, rules []rule) string {+ s = strings.ToLower(s)+ if s == "" {+ return TypeUnknown+ }+ for _, r := range rules {+ for _, n := range r.needles {+ if strings.Contains(s, n) {+ return r.typ+ }+ }+ }+ return TypeUnknown+}++// hostnameRules read the friendly name a device advertises. These are the most+// reliable signal, so a printer that calls itself "laserjet" is a printer even+// if its vendor string is generic.+var hostnameRules = []rule{+ // Consoles first: "switch" is too generic alone, so match the full name.+ {[]string{"xbox", "playstation", "ps4", "ps5", "nintendo"}, TypeConsole},+ // Media players before TVs, since an Apple TV or Fire TV is a player.+ {[]string{"appletv", "apple-tv", "firetv", "fire-tv", "roku", "chromecast", "shield", "plex", "kodi", "sonos"}, TypeMediaPlayer},+ {[]string{"printer", "officejet", "laserjet", "deskjet", "envy", "mfc", "brother", "epson", "canon", "-hp"}, TypePrinter},+ {[]string{"iphone", "ipad", "android", "galaxy", "pixel", "oneplus", "-phone"}, TypePhone},+ {[]string{"macbook", "imac", "-mac", "desktop-", "laptop", "thinkpad", "surface", "-pc", "windows"}, TypeComputer},+ {[]string{"bravia", "vizio", "webos", "samsungtv", "-tv", "smarttv"}, TypeTV},+ {[]string{"router", "gateway", "unifi", "ubnt", "openwrt", "dd-wrt", "eero", "orbi", "-ap", "accesspoint", "gl-inet", "glinet"}, TypeRouter},+ {[]string{"nas", "synology", "diskstation", "qnap", "truenas", "raspberrypi", "raspberry", "pihole", "pi-hole", "proxmox", "server", "ubuntu", "debian"}, TypeServer},+ {[]string{"esp32", "esp8266", "esp-", "shelly", "sonoff", "tasmota", "tuya", "nest", "ring", "wyze", "-hue", "smartthings", "echo", "alexa"}, TypeIoT},+}++func classifyByHostname(hostname string) string {+ return matchRules(hostname, hostnameRules)+}++// definitivePorts point at exactly one kind of hardware: only a printer speaks+// JetDirect or IPP, only an iPhone answers the iOS lockdown port. These outrank+// the vendor guess. Generic ports like 80, 443 and 22 are deliberately absent:+// almost anything serves those, so they identify nothing on their own.+var definitivePorts = map[int]string{+ 9100: TypePrinter, // raw JetDirect printing+ 631: TypePrinter, // IPP+ 515: TypePrinter, // LPD+ 62078: TypePhone, // iOS lockdown / iTunes sync+}++// indicativePorts suggest a service a device is running rather than what the+// device is. Plex or a Synology admin port can appear on a NAS, a server or a+// repurposed PC, so these only classify a device whose vendor and hostname gave+// nothing, and never override a known vendor.+var indicativePorts = map[int]string{+ 32400: TypeMediaPlayer, // Plex+ 8096: TypeMediaPlayer, // Jellyfin+ 5000: TypeServer, // Synology DSM (http), also many dev servers+ 5001: TypeServer, // Synology DSM (https)+ 548: TypeServer, // AFP, typically a NAS+}++func classifyByPorts(openPorts []int, table map[int]string) string {+ for _, p := range openPorts {+ if t, ok := table[p]; ok {+ return t+ }+ }+ return TypeUnknown+}++// vendorRules read the manufacturer from the MAC OUI. This is the broadest+// signal and the one most devices have, but it is also the least precise, since+// large makers ship many kinds of hardware. Single-purpose makers (a printer or+// switch vendor) classify cleanly; multi-purpose makers get a best guess that+// the user can override with a label.+var vendorRules = []rule{+ {[]string{"hewlett packard ent", "aruba"}, TypeRouter}, // HPE networking, before generic HP+ {[]string{"canon", "epson", "brother", "lexmark", "xerox", "kyocera", "ricoh", "hewlett-packard", "hp inc"}, TypePrinter},+ {[]string{"ubiquiti", "tp-link", "netgear", "d-link", "mikrotik", "cisco", "juniper", "ruckus", "zyxel", "meraki", "eero", "gl technologies", "gl-inet"}, TypeRouter},+ {[]string{"synology", "qnap", "raspberry pi", "western digital", "supermicro"}, TypeServer},+ {[]string{"roku", "sonos", "google, inc"}, TypeMediaPlayer},+ {[]string{"vizio", "tcl", "hisense", "skyworth"}, TypeTV},+ {[]string{"espressif", "tuya", "shelly", "sonoff", "signify", "philips lighting", "wyze", "ecobee", "particle", "espressif inc"}, TypeIoT},+ {[]string{"nintendo", "sony interactive"}, TypeConsole},+ {[]string{"intel", "dell", "lenovo", "asustek", "micro-star", "gigabyte", "framework"}, TypeComputer},+ {[]string{"apple"}, TypeComputer}, // Apple: many products; Computer is the safe default without a hostname+}++func classifyByVendor(vendor string) string {+ return matchRules(vendor, vendorRules)+}diff --git a/internal/scanner/classify_test.go b/internal/scanner/classify_test.gonew file mode 100644index 0000000..1f49d99--- /dev/null+++ b/internal/scanner/classify_test.go@@ -0,0 +1,66 @@+package scanner++import "testing"++func TestClassify(t *testing.T) {+ cases := []struct {+ name string+ vendor string+ hostname string+ ports []int+ want string+ }{+ // Hostname wins: specific and reliable.+ {"iphone by hostname", "Apple, Inc.", "Sherifs-iPhone", nil, TypePhone},+ {"macbook by hostname", "Apple, Inc.", "MacBook-Pro", nil, TypeComputer},+ {"apple tv by hostname beats TV", "Apple, Inc.", "AppleTV-Living-Room", nil, TypeMediaPlayer},+ {"printer by hostname", "", "HPB4A2-LaserJet", nil, TypePrinter},+ {"windows pc by hostname", "Intel Corporate", "DESKTOP-8F3K1", nil, TypeComputer},+ {"roku by hostname", "", "roku-ultra", nil, TypeMediaPlayer},+ {"smart tv by hostname", "Samsung Electronics", "Samsung-TV-Bedroom", nil, TypeTV},+ {"unifi ap by hostname", "", "UniFi-AP-Office", nil, TypeRouter},+ {"raspberry pi by hostname", "", "raspberrypi", nil, TypeServer},+ {"esp iot by hostname", "", "esp32-sensor", nil, TypeIoT},+ {"xbox by hostname", "", "XBOX-SYSTEMOS", nil, TypeConsole},++ // Definitive ports (printer, iPhone) classify and outrank vendor.+ {"printer by port 9100", "", "", []int{9100}, TypePrinter},+ {"iphone by lockdown port", "", "", []int{62078}, TypePhone},+ {"definitive printer port beats apple vendor", "Apple, Inc.", "", []int{9100}, TypePrinter},++ // Indicative ports (media, NAS) only classify when nothing else does.+ {"plex classifies when vendor unknown", "", "", []int{80, 32400}, TypeMediaPlayer},+ {"synology port when vendor unknown", "", "", []int{5000}, TypeServer},+ {"apple running plex stays a computer", "Apple, Inc.", "", []int{32400}, TypeComputer},+ {"generic web port does not classify", "", "", []int{80, 443}, TypeUnknown},++ // GL.iNet router, found live, by hostname and by vendor.+ {"gl-inet router by hostname", "GL Technologies (Hong Kong) Limited", "console.gl-inet.com", nil, TypeRouter},+ {"gl technologies router by vendor", "GL Technologies (Hong Kong) Limited", "", nil, TypeRouter},++ // Vendor is the broad fallback.+ {"canon printer by vendor", "Canon Inc.", "", nil, TypePrinter},+ {"ubiquiti router by vendor", "Ubiquiti Networks Inc.", "", nil, TypeRouter},+ {"synology server by vendor", "Synology Incorporated", "", nil, TypeServer},+ {"espressif iot by vendor", "Espressif Inc.", "", nil, TypeIoT},+ {"nintendo console by vendor", "Nintendo Co.,Ltd", "", nil, TypeConsole},+ {"dell computer by vendor", "Dell Inc.", "", nil, TypeComputer},+ {"apple defaults to computer without hostname", "Apple, Inc.", "", nil, TypeComputer},++ // Priority: hostname beats a conflicting vendor guess.+ {"printer hostname beats intel vendor", "Intel Corporate", "office-laserjet", nil, TypePrinter},++ // Nothing to go on.+ {"all empty is unknown", "", "", nil, TypeUnknown},+ {"unrecognized vendor is unknown", "Some Random OEM Ltd", "box-1", nil, TypeUnknown},+ }++ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ got := Classify(c.vendor, c.hostname, c.ports)+ if got != c.want {+ t.Errorf("Classify(%q, %q, %v) = %q, want %q", c.vendor, c.hostname, c.ports, got, c.want)+ }+ })+ }+}diff --git a/internal/scanner/ipv6.go b/internal/scanner/ipv6.gonew file mode 100644index 0000000..37166a1--- /dev/null+++ b/internal/scanner/ipv6.go@@ -0,0 +1,198 @@+package scanner++import (+ "context"+ "net"+ "os/exec"+ "runtime"+ "strings"+ "time"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// ipv6CommandTimeout bounds each helper command (a ping or a neighbor-table+// read). Kept short; these answer locally in well under a second.+const ipv6CommandTimeout = 3 * time.Second++// DiscoverIPv6 finds IPv6 devices on the local links.+//+// An IPv6 subnet holds 2^64 addresses, so sweeping it the way IPv4 is swept is+// impossible. Instead this solicits neighbors with an all-nodes multicast ping,+// prompting hosts to reveal themselves, and then reads the neighbor cache, which+// is the IPv6 equivalent of the ARP table. Only routable neighbors are returned+// (link-local is skipped); storage folds these into the inventory by MAC rather+// than listing each address as its own device.+func (s *Scanner) DiscoverIPv6(ctx context.Context) []types.Device {+ solicitIPv6Neighbors(ctx)++ devices := readIPv6Neighbors(ctx)+ for i := range devices {+ if devices[i].Vendor == "" && devices[i].MAC != "" {+ devices[i].Vendor = GetMACVendor(devices[i].MAC)+ }+ devices[i].Type = Classify(devices[i].Vendor, devices[i].Hostname, nil)+ }+ return devices+}++// solicitIPv6Neighbors pings the all-nodes link-local multicast (ff02::1) on+// each IPv6 interface, so hosts reply and enter the neighbor cache. Best effort:+// failures are ignored, since the cache may already hold neighbors from ordinary+// traffic.+func solicitIPv6Neighbors(ctx context.Context) {+ for _, iface := range ipv6Interfaces() {+ target := "ff02::1%" + iface+ switch runtime.GOOS {+ case "linux":+ _, _ = runIPv6Command(ctx, "ping", "-6", "-c", "1", "-W", "1", target)+ case "darwin":+ _, _ = runIPv6Command(ctx, "ping6", "-c", "1", target)+ }+ }+}++// readIPv6Neighbors reads and parses the OS neighbor cache.+func readIPv6Neighbors(ctx context.Context) []types.Device {+ switch runtime.GOOS {+ case "linux":+ out, err := runIPv6Command(ctx, "ip", "-6", "neigh", "show")+ if err != nil {+ return nil+ }+ return parseIPNeigh(string(out))+ case "darwin":+ out, err := runIPv6Command(ctx, "ndp", "-an")+ if err != nil {+ return nil+ }+ return parseNdp(string(out))+ default:+ return nil+ }+}++func runIPv6Command(ctx context.Context, name string, args ...string) ([]byte, error) {+ c, cancel := context.WithTimeout(ctx, ipv6CommandTimeout)+ defer cancel()+ return exec.CommandContext(c, name, args...).Output()+}++// ipv6Interfaces returns the names of up, non-loopback interfaces that hold an+// IPv6 address.+func ipv6Interfaces() []string {+ ifaces, err := net.Interfaces()+ if err != nil {+ return nil+ }+ var names []string+ for _, iface := range ifaces {+ if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {+ continue+ }+ addrs, err := iface.Addrs()+ if err != nil {+ continue+ }+ for _, a := range addrs {+ if n, ok := a.(*net.IPNet); ok && n.IP.To4() == nil && !n.IP.IsLoopback() {+ names = append(names, iface.Name)+ break+ }+ }+ }+ return names+}++// parseIPNeigh parses Linux `ip -6 neigh show` output. Each line looks like+// "fe80::1 dev eth0 lladdr 00:11:22:33:44:55 router REACHABLE"; entries without+// a link-layer address, or in a FAILED or INCOMPLETE state, are skipped.+func parseIPNeigh(output string) []types.Device {+ var devices []types.Device+ for _, line := range strings.Split(output, "\n") {+ fields := strings.Fields(line)+ if len(fields) < 2 {+ continue+ }+ ip := fields[0]++ mac := ""+ for i, f := range fields {+ if f == "lladdr" && i+1 < len(fields) {+ mac = fields[i+1]+ break+ }+ }+ if mac == "" {+ continue+ }+ state := fields[len(fields)-1]+ if state == "FAILED" || state == "INCOMPLETE" {+ continue+ }+ if !isUsableIPv6(ip) {+ continue+ }+ devices = append(devices, types.Device{IP: ip, MAC: normalizeMAC(mac)})+ }+ return devices+}++// parseNdp parses macOS `ndp -an` output. The first column is the neighbor+// (address%interface), the second the link-layer address or "(incomplete)".+func parseNdp(output string) []types.Device {+ var devices []types.Device+ for _, line := range strings.Split(output, "\n") {+ fields := strings.Fields(line)+ if len(fields) < 2 {+ continue+ }+ if fields[0] == "Neighbor" { // header row+ continue+ }+ ip := fields[0]+ if i := strings.IndexByte(ip, '%'); i >= 0 {+ ip = ip[:i]+ }+ mac := fields[1]+ if !strings.Contains(mac, ":") { // "(incomplete)" or similar+ continue+ }+ if !isUsableIPv6(ip) {+ continue+ }+ devices = append(devices, types.Device{IP: ip, MAC: normalizeMAC(mac)})+ }+ return devices+}++// isUsableIPv6 reports whether s is an IPv6 address worth recording from the+// neighbour cache: a routable unicast address. Link-local (fe80::) is excluded+// on purpose -- every device has one, they are not routable, and modern devices+// rotate them behind randomised MACs, so treating each as a device produces+// hundreds of phantoms. Loopback, multicast and the unspecified address are+// dropped too.+func isUsableIPv6(s string) bool {+ ip := net.ParseIP(s)+ if ip == nil || ip.To4() != nil {+ return false+ }+ return !ip.IsLoopback() && !ip.IsMulticast() && !ip.IsUnspecified() && !ip.IsLinkLocalUnicast()+}++// normalizeMAC renders a MAC in a consistent AA:BB:CC:DD:EE:FF form. Some tools+// print octets without a leading zero (0:11:...), which would otherwise not+// match a vendor lookup.+func normalizeMAC(s string) string {+ parts := strings.Split(s, ":")+ if len(parts) != 6 {+ return strings.ToUpper(strings.TrimSpace(s))+ }+ for i, p := range parts {+ if len(p) == 1 {+ p = "0" + p+ }+ parts[i] = strings.ToUpper(p)+ }+ return strings.Join(parts, ":")+}diff --git a/internal/scanner/ipv6_test.go b/internal/scanner/ipv6_test.gonew file mode 100644index 0000000..7a821ad--- /dev/null+++ b/internal/scanner/ipv6_test.go@@ -0,0 +1,66 @@+package scanner++import "testing"++func TestParseIPNeigh(t *testing.T) {+ out := `2001:db8::5 dev eth0 lladdr aa:bb:cc:dd:ee:ff STALE+fe80::1 dev eth0 lladdr 00:11:22:33:44:55 router REACHABLE+fe80::dead dev eth0 FAILED+192.168.1.1 dev eth0 lladdr 11:22:33:44:55:66 REACHABLE+ff02::1 dev eth0 lladdr 33:33:00:00:00:01 NOARP+2001:db8::bad dev eth0 lladdr 22:33:44:55:66:77 FAILED`+ got := parseIPNeigh(out)++ // Only the routable, reachable IPv6 neighbor survives: link-local (fe80::),+ // the FAILED ones, the IPv4 one and the multicast one are all dropped.+ if len(got) != 1 {+ t.Fatalf("expected 1 device, got %d: %+v", len(got), got)+ }+ if got[0].IP != "2001:db8::5" || got[0].MAC != "AA:BB:CC:DD:EE:FF" {+ t.Errorf("device wrong: %+v", got[0])+ }+}++func TestParseNdp(t *testing.T) {+ out := `Neighbor Linklayer Address Netif Expire St Flgs Prbs+2001:db8::5%en0 aa:bb:cc:dd:ee:ff en0 permanent R+fe80::1%en0 0:11:22:33:44:55 en0 23h59m58s R R+::1 (incomplete) lo0 permanent R+fe80::2%en0 (incomplete) en0 expired R`+ got := parseNdp(out)++ // Link-local is dropped; only the routable neighbor remains.+ if len(got) != 1 {+ t.Fatalf("expected 1 device, got %d: %+v", len(got), got)+ }+ if got[0].IP != "2001:db8::5" || got[0].MAC != "AA:BB:CC:DD:EE:FF" {+ t.Errorf("device wrong: %+v", got[0])+ }+}++func TestIsUsableIPv6(t *testing.T) {+ cases := map[string]bool{+ "2001:db8::5": true, // global unicast+ "fd00::1": true, // unique local (ULA)+ "fe80::1": false, // link-local: never a device+ "::1": false, // loopback+ "ff02::1": false, // multicast+ "::": false, // unspecified+ "192.168.1.1": false, // IPv4+ "not-an-ip": false,+ }+ for ip, want := range cases {+ if got := isUsableIPv6(ip); got != want {+ t.Errorf("isUsableIPv6(%q) = %v, want %v", ip, got, want)+ }+ }+}++func TestNormalizeMAC(t *testing.T) {+ if got := normalizeMAC("0:11:22:33:44:5"); got != "00:11:22:33:44:05" {+ t.Errorf("got %q", got)+ }+ if got := normalizeMAC("aa:bb:cc:dd:ee:ff"); got != "AA:BB:CC:DD:EE:FF" {+ t.Errorf("got %q", got)+ }+}diff --git a/internal/scanner/mdns.go b/internal/scanner/mdns.gonew file mode 100644index 0000000..8f680db--- /dev/null+++ b/internal/scanner/mdns.go@@ -0,0 +1,282 @@+package scanner++import (+ "context"+ "errors"+ "net"+ "strings"+ "time"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// mDNS (multicast DNS / DNS-SD) passive discovery: ask the network what services+// it offers and listen to what devices announce, so they reveal themselves+// without a sweep. It is hand-rolled to keep the binary dependency-free.+//+// The query sets the unicast-response bit, so answers come back to our own+// ephemeral port. That avoids binding UDP 5353, which the host's own responder+// (avahi on Linux, mDNSResponder on macOS) already holds. Devices that only+// multicast their reply are missed; most common ones honour the unicast bit.++const (+ mdnsListenWindow = 2 * time.Second+ typePTR = 12+ typeA = 1+ typeAAAA = 28+ typeSRV = 33+)++var errMalformedDNS = errors.New("malformed dns message")++// mdnsServiceQueries are the service types worth asking about, keyed by the+// value people care about. A single PTR query for a service type usually brings+// back the whole chain (PTR, SRV and A) in one packet.+var mdnsServiceQueries = []string{+ "_services._dns-sd._udp.local", // enumerate offered service types+ "_ipp._tcp.local", "_ipps._tcp.local", "_printer._tcp.local",+ "_airplay._tcp.local", "_raop._tcp.local", "_googlecast._tcp.local",+ "_spotify-connect._tcp.local", "_sonos._tcp.local",+ "_hap._tcp.local", "_ssh._tcp.local", "_smb._tcp.local",+ "_afpovertcp._tcp.local", "_companion-link._tcp.local",+ "_apple-mobdev2._tcp.local", "_http._tcp.local", "_workstation._tcp.local",+}++// mdnsServiceTypes maps the leading label of a service type to a device type.+var mdnsServiceTypes = map[string]string{+ "_ipp": TypePrinter, "_ipps": TypePrinter, "_printer": TypePrinter,+ "_pdl-datastream": TypePrinter,+ "_airplay": TypeMediaPlayer, "_raop": TypeMediaPlayer,+ "_googlecast": TypeMediaPlayer, "_spotify-connect": TypeMediaPlayer,+ "_sonos": TypeMediaPlayer,+ "_hap": TypeIoT, "_homekit": TypeIoT, "_hue": TypeIoT,+ "_ssh": TypeServer, "_sftp-ssh": TypeServer, "_smb": TypeServer,+ "_afpovertcp": TypeServer, "_nfs": TypeServer,+ "_apple-mobdev2": TypePhone, "_companion-link": TypePhone,+}++type ptrEntry struct{ service, instance string }++// DiscoverMDNS finds devices that advertise themselves over mDNS, returning each+// with the friendly name it announces and, where a service type reveals it, a+// device type. These have no MAC (mDNS does not carry one); merging by IP folds+// them into whatever an IP scan found for the same address.+func (s *Scanner) DiscoverMDNS(ctx context.Context) []types.Device {+ packets := queryMDNS(ctx)++ aRecords := map[string]string{} // host name -> IP+ srv := map[string]string{} // service instance -> target host+ var ptrs []ptrEntry // service type -> instance++ for _, pkt := range packets {+ parseMDNSInto(pkt, aRecords, srv, &ptrs)+ }+ return buildDevicesFromMDNS(aRecords, srv, ptrs)+}++// buildDevicesFromMDNS turns the parsed records into devices: each host with an+// address becomes a device, named by what it announced and typed either from a+// service it offers or, failing that, from its name.+func buildDevicesFromMDNS(aRecords, srv map[string]string, ptrs []ptrEntry) []types.Device {+ // Resolve service type down to the host that answers for it.+ instanceType := map[string]string{}+ for _, p := range ptrs {+ if dt := mdnsTypeForService(p.service); dt != "" {+ instanceType[p.instance] = dt+ }+ }+ hostType := map[string]string{}+ for instance, host := range srv {+ if dt := instanceType[instance]; dt != "" {+ hostType[host] = dt+ }+ }++ devices := make([]types.Device, 0, len(aRecords))+ for host, ip := range aRecords {+ name := cleanMDNSName(host)+ dt := hostType[host]+ if dt == "" {+ dt = Classify("", name, nil) // fall back to name-based typing+ }+ devices = append(devices, types.Device{IP: ip, Hostname: name, Type: dt})+ }+ return devices+}++func cleanMDNSName(host string) string {+ name := strings.TrimSuffix(host, ".")+ name = strings.TrimSuffix(name, ".local")+ return name+}++func mdnsTypeForService(service string) string {+ label := service+ if i := strings.IndexByte(service, '.'); i >= 0 {+ label = service[:i]+ }+ return mdnsServiceTypes[label]+}++// queryMDNS sends the service queries and collects response packets for a short+// window. Best effort: any failure returns whatever was gathered so far.+func queryMDNS(ctx context.Context) [][]byte {+ conn, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero, Port: 0})+ if err != nil {+ return nil+ }+ defer conn.Close()++ dst := &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251), Port: 5353}+ for _, name := range mdnsServiceQueries {+ _, _ = conn.WriteToUDP(buildMDNSQuery(name, typePTR), dst)+ }++ _ = conn.SetReadDeadline(time.Now().Add(mdnsListenWindow))+ var packets [][]byte+ buf := make([]byte, 9000)+ for {+ if ctx.Err() != nil {+ break+ }+ n, _, err := conn.ReadFromUDP(buf)+ if err != nil {+ break // deadline reached+ }+ pkt := make([]byte, n)+ copy(pkt, buf[:n])+ packets = append(packets, pkt)+ }+ return packets+}++// buildMDNSQuery builds a single-question query. The class carries the+// unicast-response (QU) bit so answers return to our port.+func buildMDNSQuery(name string, qtype uint16) []byte {+ buf := []byte{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0} // header, one question+ buf = append(buf, encodeDNSName(name)...)+ buf = append(buf, byte(qtype>>8), byte(qtype))+ buf = append(buf, 0x80, 0x01) // class IN, unicast-response bit set+ return buf+}++func encodeDNSName(name string) []byte {+ var out []byte+ for _, label := range strings.Split(name, ".") {+ if label == "" {+ continue+ }+ out = append(out, byte(len(label)))+ out = append(out, label...)+ }+ return append(out, 0x00)+}++// parseMDNSInto parses one response packet, folding its A, AAAA, PTR and SRV+// records into the shared maps. It is defensive: any malformation stops parsing+// that packet without a panic.+func parseMDNSInto(msg []byte, aRecords, srv map[string]string, ptrs *[]ptrEntry) {+ if len(msg) < 12 {+ return+ }+ qd := int(msg[4])<<8 | int(msg[5])+ total := (int(msg[6])<<8 | int(msg[7])) + (int(msg[8])<<8 | int(msg[9])) + (int(msg[10])<<8 | int(msg[11]))++ off := 12+ for i := 0; i < qd; i++ {+ _, no, err := decodeDNSName(msg, off)+ if err != nil || no+4 > len(msg) {+ return+ }+ off = no + 4 // type + class+ }++ for i := 0; i < total; i++ {+ name, no, err := decodeDNSName(msg, off)+ if err != nil {+ return+ }+ off = no+ if off+10 > len(msg) {+ return+ }+ rtype := uint16(msg[off])<<8 | uint16(msg[off+1])+ rdlen := int(msg[off+8])<<8 | int(msg[off+9])+ off += 10+ if off+rdlen > len(msg) {+ return+ }+ rdata := msg[off : off+rdlen]++ switch rtype {+ case typeA:+ if len(rdata) == 4 {+ aRecords[name] = net.IP(rdata).String()+ }+ case typeAAAA:+ if len(rdata) == 16 {+ if _, ok := aRecords[name]; !ok { // prefer an IPv4 answer+ aRecords[name] = net.IP(rdata).String()+ }+ }+ case typePTR:+ if target, _, err := decodeDNSName(msg, off); err == nil {+ *ptrs = append(*ptrs, ptrEntry{service: name, instance: target})+ }+ case typeSRV:+ if rdlen > 6 {+ if target, _, err := decodeDNSName(msg, off+6); err == nil {+ srv[name] = target+ }+ }+ }+ off += rdlen+ }+}++// decodeDNSName reads a DNS name at off, following compression pointers with a+// jump limit so a malformed message cannot loop forever. It returns the name and+// the offset in the record stream immediately after the name.+func decodeDNSName(msg []byte, off int) (string, int, error) {+ var labels []string+ next := -1+ jumps := 0++ for {+ if off < 0 || off >= len(msg) {+ return "", 0, errMalformedDNS+ }+ b := msg[off]+ if b == 0x00 {+ off+++ break+ }+ if b&0xC0 == 0xC0 { // compression pointer+ if off+1 >= len(msg) {+ return "", 0, errMalformedDNS+ }+ if next == -1 {+ next = off + 2 // the record continues after the pointer+ }+ jumps+++ if jumps > 20 {+ return "", 0, errMalformedDNS+ }+ off = int(b&0x3F)<<8 | int(msg[off+1])+ continue+ }+ length := int(b)+ off+++ if off+length > len(msg) {+ return "", 0, errMalformedDNS+ }+ labels = append(labels, string(msg[off:off+length]))+ off += length+ }++ name := strings.Join(labels, ".")+ if next != -1 {+ return name, next, nil+ }+ return name, off, nil+}diff --git a/internal/scanner/mdns_test.go b/internal/scanner/mdns_test.gonew file mode 100644index 0000000..3aaabee--- /dev/null+++ b/internal/scanner/mdns_test.go@@ -0,0 +1,120 @@+package scanner++import (+ "testing"+)++// dnsName encodes a name as length-prefixed labels + terminator (no compression).+func dnsName(name string) []byte { return encodeDNSName(name) }++func u16(v int) []byte { return []byte{byte(v >> 8), byte(v)} }++// record builds one uncompressed resource record.+func record(name string, rtype int, rdata []byte) []byte {+ var r []byte+ r = append(r, dnsName(name)...)+ r = append(r, u16(rtype)...) // type+ r = append(r, u16(0x8001)...) // class (cache-flush bit; parser ignores class)+ r = append(r, 0, 0, 0, 60) // ttl+ r = append(r, u16(len(rdata))...)+ r = append(r, rdata...)+ return r+}++func TestParseAndBuildMDNS_FullChain(t *testing.T) {+ // A response advertising an IPP printer:+ // PTR _ipp._tcp.local -> Office._ipp._tcp.local+ // SRV Office._ipp._tcp.local -> printbox.local+ // A printbox.local -> 192.168.1.50+ var msg []byte+ msg = append(msg, 0, 0, 0x84, 0) // id, flags (response)+ msg = append(msg, u16(0)...) // questions+ msg = append(msg, u16(3)...) // answers+ msg = append(msg, u16(0)...) // authority+ msg = append(msg, u16(0)...) // additional++ msg = append(msg, record("_ipp._tcp.local", typePTR, dnsName("Office._ipp._tcp.local"))...)+ srvData := append([]byte{0, 0, 0, 0, 0x1F, 0x90}, dnsName("printbox.local")...) // prio,weight,port + target+ msg = append(msg, record("Office._ipp._tcp.local", typeSRV, srvData)...)+ msg = append(msg, record("printbox.local", typeA, []byte{192, 168, 1, 50})...)++ aRecords := map[string]string{}+ srv := map[string]string{}+ var ptrs []ptrEntry+ parseMDNSInto(msg, aRecords, srv, &ptrs)++ if aRecords["printbox.local"] != "192.168.1.50" {+ t.Errorf("A record wrong: %v", aRecords)+ }+ if srv["Office._ipp._tcp.local"] != "printbox.local" {+ t.Errorf("SRV record wrong: %v", srv)+ }+ if len(ptrs) != 1 || ptrs[0].service != "_ipp._tcp.local" {+ t.Errorf("PTR record wrong: %v", ptrs)+ }++ devices := buildDevicesFromMDNS(aRecords, srv, ptrs)+ if len(devices) != 1 {+ t.Fatalf("expected 1 device, got %d", len(devices))+ }+ d := devices[0]+ if d.IP != "192.168.1.50" || d.Hostname != "printbox" || d.Type != TypePrinter {+ t.Errorf("device wrong: %+v", d)+ }+}++func TestDecodeDNSName_Compression(t *testing.T) {+ // "local" at offset 12, then "printbox" + pointer to offset 12.+ msg := make([]byte, 12)+ localOff := len(msg)+ msg = append(msg, dnsName("local")...) // "local" root at localOff+ nameOff := len(msg)+ msg = append(msg, 8)+ msg = append(msg, []byte("printbox")...)+ msg = append(msg, 0xC0, byte(localOff)) // pointer to "local"++ name, next, err := decodeDNSName(msg, nameOff)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if name != "printbox.local" {+ t.Errorf("name = %q, want printbox.local", name)+ }+ if next != len(msg) {+ t.Errorf("next = %d, want %d", next, len(msg))+ }+}++func TestDecodeDNSName_Malformed(t *testing.T) {+ if _, _, err := decodeDNSName([]byte{0x05, 'a'}, 0); err == nil {+ t.Error("expected error on truncated label")+ }+ // A pointer that points to itself must not loop forever.+ if _, _, err := decodeDNSName([]byte{0xC0, 0x00}, 0); err == nil {+ t.Error("expected error on self-referential pointer")+ }+}++func TestMDNSTypeForService(t *testing.T) {+ if mdnsTypeForService("_airplay._tcp.local") != TypeMediaPlayer {+ t.Error("airplay should be media player")+ }+ if mdnsTypeForService("_ssh._tcp.local") != TypeServer {+ t.Error("ssh should be server")+ }+ if mdnsTypeForService("_unknown._tcp.local") != "" {+ t.Error("unknown service should be empty")+ }+}++func TestBuildMDNSQuery(t *testing.T) {+ q := buildMDNSQuery("_ipp._tcp.local", typePTR)+ if q[5] != 1 {+ t.Errorf("questions = %d, want 1", q[5])+ }+ // tail: type PTR, class with QU bit.+ tail := q[len(q)-4:]+ if tail[0] != 0 || tail[1] != typePTR || tail[2] != 0x80 || tail[3] != 0x01 {+ t.Errorf("tail = % x, want 00 0c 80 01", tail)+ }+}diff --git a/internal/scanner/netbios.go b/internal/scanner/netbios.gonew file mode 100644index 0000000..a2815fd--- /dev/null+++ b/internal/scanner/netbios.go@@ -0,0 +1,175 @@+package scanner++import (+ "context"+ "errors"+ "net"+ "strings"+ "sync"+ "time"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// netbiosTimeout bounds a single NetBIOS name query. A device on the LAN answers+// in milliseconds; one that is not listening should not stall the scan.+const netbiosTimeout = 500 * time.Millisecond++// netbiosNodeStatusRequest is the fixed "node status request" packet for the+// wildcard name "*", which asks a host to list its NetBIOS names. Windows+// machines answer it even with no reverse DNS entry, so it recovers a name a+// ping sweep alone would miss. It needs no elevated privileges (plain UDP).+var netbiosNodeStatusRequest = buildNodeStatusRequest()++func buildNodeStatusRequest() []byte {+ // The 16-byte NetBIOS name for a node status query is "*" followed by 15+ // null bytes, first-level encoded (each byte split into two nibbles, each+ // added to 'A'). 0x2A ('*') becomes "CK"; each 0x00 becomes "AA".+ encoded := "CK" + strings.Repeat("A", 30) // 32 characters++ buf := []byte{+ 0x00, 0x00, // transaction id+ 0x00, 0x00, // flags: standard query+ 0x00, 0x01, // questions: 1+ 0x00, 0x00, // answer records+ 0x00, 0x00, // authority records+ 0x00, 0x00, // additional records+ 0x20, // question name length: 32+ }+ buf = append(buf, []byte(encoded)...)+ buf = append(buf,+ 0x00, // name terminator+ 0x00, 0x21, // type: NBSTAT+ 0x00, 0x01, // class: IN+ )+ return buf+}++// netbiosName asks a host at ip for its NetBIOS name. It returns "" on any+// timeout, error, or response without a usable workstation name.+func netbiosName(ctx context.Context, ip string) string {+ dialCtx, cancel := context.WithTimeout(ctx, netbiosTimeout)+ defer cancel()++ var d net.Dialer+ conn, err := d.DialContext(dialCtx, "udp", net.JoinHostPort(ip, "137"))+ if err != nil {+ return ""+ }+ defer conn.Close()++ deadline := time.Now().Add(netbiosTimeout)+ _ = conn.SetDeadline(deadline)+ if _, err := conn.Write(netbiosNodeStatusRequest); err != nil {+ return ""+ }++ resp := make([]byte, 1024)+ n, err := conn.Read(resp)+ if err != nil {+ return ""+ }+ name, err := parseNodeStatusName(resp[:n])+ if err != nil {+ return ""+ }+ return name+}++// parseNodeStatusName extracts the machine's name from a NetBIOS node status+// response: the unique name carrying the workstation suffix (0x00).+func parseNodeStatusName(resp []byte) (string, error) {+ if len(resp) < 12 {+ return "", errors.New("short response")+ }+ ancount := int(resp[6])<<8 | int(resp[7])+ if ancount == 0 {+ return "", errors.New("no answer records")+ }++ // Skip the answer record's name, which is either a literal length-prefixed+ // name or a compression pointer (top two bits set).+ pos := 12+ if resp[pos]&0xC0 == 0xC0 {+ pos += 2+ } else {+ pos += 1 + int(resp[pos]) + 1 // length byte + encoded name + terminator+ }+ // Skip type(2) + class(2) + ttl(4) + rdlength(2).+ pos += 10+ if pos >= len(resp) {+ return "", errors.New("truncated before name list")+ }++ numNames := int(resp[pos])+ pos+++ for i := 0; i < numNames; i++ {+ if pos+18 > len(resp) {+ break+ }+ raw := resp[pos : pos+15]+ suffix := resp[pos+15]+ flags := uint16(resp[pos+16])<<8 | uint16(resp[pos+17])+ group := flags&0x8000 != 0++ // The workstation name is the unique (non-group) entry with suffix 0x00.+ if suffix == 0x00 && !group {+ if name := sanitizeNetBIOSName(raw); name != "" {+ return name, nil+ }+ }+ pos += 18+ }+ return "", errors.New("no workstation name")+}++// sanitizeNetBIOSName trims the padding NetBIOS uses and rejects a name with any+// non-printable byte, which would be a garbled or non-name entry.+func sanitizeNetBIOSName(raw []byte) string {+ s := strings.TrimRight(string(raw), " \x00")+ if s == "" {+ return ""+ }+ for _, r := range s {+ if r < 0x20 || r > 0x7e {+ return ""+ }+ }+ return s+}++// fillWindowsNames looks up a NetBIOS name for every device that a scan left+// without a hostname, concurrently and with a bound. Windows machines commonly+// have no reverse DNS entry, so this recovers their names. A recovered name may+// also yield a better device type than the vendor alone.+//+// It always runs, not only under service detection: it is name resolution, the+// same category as the reverse DNS lookup the scan already does, and it only+// touches devices that have no name yet.+func fillWindowsNames(ctx context.Context, devices []types.Device) {+ sem := make(chan struct{}, serviceProbeConcurrency)+ var wg sync.WaitGroup++ for i := range devices {+ if devices[i].Hostname != "" {+ continue+ }+ wg.Add(1)+ sem <- struct{}{}+ go func(d *types.Device) {+ defer wg.Done()+ defer func() { <-sem }()++ name := netbiosName(ctx, d.IP)+ if name == "" {+ return+ }+ d.Hostname = name+ if t := Classify(d.Vendor, d.Hostname, nil); t != "" {+ d.Type = t+ }+ }(&devices[i])+ }++ wg.Wait()+}diff --git a/internal/scanner/netbios_test.go b/internal/scanner/netbios_test.gonew file mode 100644index 0000000..27b6bbb--- /dev/null+++ b/internal/scanner/netbios_test.go@@ -0,0 +1,125 @@+package scanner++import "testing"++func TestBuildNodeStatusRequest(t *testing.T) {+ req := netbiosNodeStatusRequest+ // 12-byte header + 1 length + 32 encoded + 1 terminator + 2 type + 2 class.+ if len(req) != 50 {+ t.Fatalf("request length = %d, want 50", len(req))+ }+ if req[5] != 0x01 {+ t.Errorf("questions field = %d, want 1", req[5])+ }+ if req[12] != 0x20 {+ t.Errorf("name length = %#x, want 0x20", req[12])+ }+ // The wildcard "*" encodes to "CK" followed by 30 'A's.+ if got := string(req[13:15]); got != "CK" {+ t.Errorf("encoded name starts with %q, want \"CK\"", got)+ }+ // Type NBSTAT (0x0021), class IN (0x0001) at the tail.+ tail := req[len(req)-4:]+ if tail[0] != 0x00 || tail[1] != 0x21 || tail[2] != 0x00 || tail[3] != 0x01 {+ t.Errorf("tail = % x, want 00 21 00 01", tail)+ }+}++// buildNodeStatusResponse crafts a minimal but valid node status response+// advertising the given (name, suffix, group) entries.+func buildNodeStatusResponse(entries []struct {+ name string+ suffix byte+ group bool+}) []byte {+ resp := []byte{+ 0x00, 0x00, // txid+ 0x84, 0x00, // flags: response+ 0x00, 0x00, // questions+ 0x00, 0x01, // answers: 1+ 0x00, 0x00, // authority+ 0x00, 0x00, // additional+ }+ // Answer name: literal, echoing the query name (0x20 + 32 + 0x00).+ resp = append(resp, 0x20)+ resp = append(resp, []byte("CK")...)+ for i := 0; i < 30; i++ {+ resp = append(resp, 'A')+ }+ resp = append(resp, 0x00)+ // type, class, ttl, rdlength (rdlength value is not validated by the parser).+ resp = append(resp, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)+ // name list+ resp = append(resp, byte(len(entries)))+ for _, e := range entries {+ nameField := make([]byte, 15)+ copy(nameField, e.name)+ for i := len(e.name); i < 15; i++ {+ nameField[i] = ' '+ }+ resp = append(resp, nameField...)+ resp = append(resp, e.suffix)+ var flags uint16+ if e.group {+ flags |= 0x8000+ }+ resp = append(resp, byte(flags>>8), byte(flags))+ }+ return resp+}++func TestParseNodeStatusName(t *testing.T) {+ // A typical Windows response: the domain/group name plus the workstation.+ resp := buildNodeStatusResponse([]struct {+ name string+ suffix byte+ group bool+ }{+ {"WORKGROUP", 0x00, true}, // group, must be ignored+ {"DESKTOP-AB12", 0x00, false}, // the workstation name we want+ {"DESKTOP-AB12", 0x20, false}, // server service, wrong suffix+ })+ got, err := parseNodeStatusName(resp)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if got != "DESKTOP-AB12" {+ t.Errorf("name = %q, want DESKTOP-AB12", got)+ }+}++func TestParseNodeStatusName_NoWorkstation(t *testing.T) {+ resp := buildNodeStatusResponse([]struct {+ name string+ suffix byte+ group bool+ }{+ {"WORKGROUP", 0x00, true}, // only a group name+ })+ if _, err := parseNodeStatusName(resp); err == nil {+ t.Error("expected an error when there is no unique workstation name")+ }+}++func TestParseNodeStatusName_ShortOrEmpty(t *testing.T) {+ if _, err := parseNodeStatusName([]byte{0x00, 0x01}); err == nil {+ t.Error("expected an error for a short response")+ }+ // A response with zero answers.+ noans := make([]byte, 12)+ if _, err := parseNodeStatusName(noans); err == nil {+ t.Error("expected an error when there are no answer records")+ }+}++func TestSanitizeNetBIOSName(t *testing.T) {+ if got := sanitizeNetBIOSName([]byte("MYPC ")); got != "MYPC" {+ t.Errorf("padding not trimmed: %q", got)+ }+ if got := sanitizeNetBIOSName([]byte{'A', 0x01, 'B'}); got != "" {+ t.Errorf("control character not rejected: %q", got)+ }+ if got := sanitizeNetBIOSName([]byte(" ")); got != "" {+ t.Errorf("all-spaces should be empty, got %q", got)+ }+}diff --git a/internal/scanner/probe.go b/internal/scanner/probe.gonew file mode 100644index 0000000..95b8cff--- /dev/null+++ b/internal/scanner/probe.go@@ -0,0 +1,145 @@+package scanner++import (+ "context"+ "net"+ "strconv"+ "sync"+ "time"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// serviceProbePorts is the short, fixed set of ports the opt-in service probe+// checks. It is deliberately small: enough to sharpen device typing and spot a+// web interface, and never a general port scan. Every port here is one the+// classifier can act on, plus the common web ports for the web-interface flag.+var serviceProbePorts = []int{+ 21, // FTP (unencrypted, a security flag)+ 22, // SSH+ 23, // Telnet (unencrypted, a security flag)+ 80, // HTTP (web interface)+ 443, // HTTPS (web interface)+ 515, // LPD printing+ 548, // AFP (NAS)+ 631, // IPP printing+ 3389, // RDP+ 5000, // Synology DSM+ 5001, // Synology DSM (TLS)+ 8080, // alt HTTP (web interface)+ 8096, // Jellyfin+ 9100, // raw JetDirect printing+ 32400, // Plex+ 62078, // iOS lockdown+}++// riskyServices maps an open port to a plainly worded security concern. Kept+// deliberately high-signal: Telnet and FTP are unencrypted by design, so+// finding them open is a real red flag, not noise a router's web page would be.+var riskyServices = map[int]string{+ 23: "Telnet is open (unencrypted remote access)",+ 21: "FTP is open (unencrypted file transfer)",+}++// webPorts are the ports that, if open, mark a device as serving a web+// interface.+var webPorts = map[int]bool{80: true, 443: true, 8080: true}++// serviceProbeTimeout bounds a single TCP connection attempt. Short, because a+// device on the LAN answers in milliseconds and a closed port should not stall+// the scan waiting for it.+const serviceProbeTimeout = 400 * time.Millisecond++// serviceProbeConcurrency caps how many devices are probed at once, so a large+// network does not open thousands of sockets in the same instant.+const serviceProbeConcurrency = 24++// enrichWithServices probes each device's well-known ports and updates its type+// and web-interface flag from what it finds. It only runs when the user has+// enabled service detection. Devices are probed concurrently up to a cap; each+// device's ports are probed concurrently in turn, so the whole pass costs about+// one timeout per batch rather than one per closed port.+func enrichWithServices(ctx context.Context, devices []types.Device) {+ sem := make(chan struct{}, serviceProbeConcurrency)+ var wg sync.WaitGroup++ for i := range devices {+ wg.Add(1)+ sem <- struct{}{}+ go func(d *types.Device) {+ defer wg.Done()+ defer func() { <-sem }()++ ports := probeServices(ctx, d.IP)+ // Re-classify with the port evidence. Only overwrite when the fuller+ // signal yields a type, so a probe that finds nothing does not wipe+ // the vendor or hostname guess made earlier.+ if t := Classify(d.Vendor, d.Hostname, ports); t != "" {+ d.Type = t+ }+ d.WebUI = hasWebPort(ports)+ d.Risks = risksFromPorts(ports)+ }(&devices[i])+ }++ wg.Wait()+}++// probeServices attempts a TCP connection to each port in serviceProbePorts and+// returns those that accept one. Ports are tried concurrently with a short+// timeout, and the whole context deadline still applies so a cancelled scan+// stops promptly.+func probeServices(ctx context.Context, ip string) []int {+ var (+ mu sync.Mutex+ open []int+ wg sync.WaitGroup+ )++ for _, port := range serviceProbePorts {+ wg.Add(1)+ go func(p int) {+ defer wg.Done()+ dialer := net.Dialer{Timeout: serviceProbeTimeout}+ conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(ip, strconv.Itoa(p)))+ if err != nil {+ return+ }+ conn.Close()+ mu.Lock()+ open = append(open, p)+ mu.Unlock()+ }(port)+ }++ wg.Wait()+ return open+}++// hasWebPort reports whether any of the probed open ports is a web port.+func hasWebPort(ports []int) bool {+ for _, p := range ports {+ if webPorts[p] {+ return true+ }+ }+ return false+}++// risksFromPorts turns the open ports into any security concerns they imply, in+// the fixed order of serviceProbePorts so the result is stable.+func risksFromPorts(ports []int) []string {+ var risks []string+ seen := make(map[int]bool, len(ports))+ for _, p := range ports {+ seen[p] = true+ }+ for _, p := range serviceProbePorts {+ if seen[p] {+ if msg, ok := riskyServices[p]; ok {+ risks = append(risks, msg)+ }+ }+ }+ return risks+}diff --git a/internal/scanner/probe_test.go b/internal/scanner/probe_test.gonew file mode 100644index 0000000..2b0a36e--- /dev/null+++ b/internal/scanner/probe_test.go@@ -0,0 +1,119 @@+package scanner++import (+ "context"+ "net"+ "testing"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++func TestRisksFromPorts(t *testing.T) {+ // Telnet and FTP open: two risks, in the fixed serviceProbePorts order+ // (FTP=21 before Telnet=23).+ risks := risksFromPorts([]int{80, 23, 21})+ if len(risks) != 2 {+ t.Fatalf("expected 2 risks, got %d: %v", len(risks), risks)+ }+ if risks[0] != riskyServices[21] || risks[1] != riskyServices[23] {+ t.Errorf("risks not in stable order: %v", risks)+ }++ // Only safe ports: no risks.+ if r := risksFromPorts([]int{22, 443, 9100}); len(r) != 0 {+ t.Errorf("expected no risks, got %v", r)+ }+ if r := risksFromPorts(nil); len(r) != 0 {+ t.Errorf("expected no risks for empty ports, got %v", r)+ }+}++func TestHasWebPort(t *testing.T) {+ if !hasWebPort([]int{22, 80}) {+ t.Error("80 should count as a web port")+ }+ if !hasWebPort([]int{443}) {+ t.Error("443 should count as a web port")+ }+ if !hasWebPort([]int{8080}) {+ t.Error("8080 should count as a web port")+ }+ if hasWebPort([]int{22, 9100}) {+ t.Error("no web port present, should be false")+ }+ if hasWebPort(nil) {+ t.Error("empty ports should be false")+ }+}++// listenLoopback opens a TCP listener on an ephemeral loopback port and returns+// the listener and its port. The caller closes the listener.+func listenLoopback(t *testing.T) (net.Listener, int) {+ t.Helper()+ ln, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listen: %v", err)+ }+ return ln, ln.Addr().(*net.TCPAddr).Port+}++// TestProbeServices_FindsOpenPort confirms the probe reports a port that is+// actually listening. It overrides the probe set with the ephemeral test port so+// the test never depends on a well-known port being free.+func TestProbeServices_FindsOpenPort(t *testing.T) {+ ln, port := listenLoopback(t)+ defer ln.Close()++ orig := serviceProbePorts+ serviceProbePorts = []int{port}+ defer func() { serviceProbePorts = orig }()++ open := probeServices(context.Background(), "127.0.0.1")+ if len(open) != 1 || open[0] != port {+ t.Fatalf("expected [%d] open, got %v", port, open)+ }+}++// TestEnrichWithServices_SetsWebUI stands up a real listener and confirms the+// enrichment flags WebUI when that port counts as a web port, without disturbing+// a type already set from the hostname.+func TestEnrichWithServices_SetsWebUI(t *testing.T) {+ ln, port := listenLoopback(t)+ defer ln.Close()++ origPorts, origWeb := serviceProbePorts, webPorts+ serviceProbePorts = []int{port}+ webPorts = map[int]bool{port: true}+ defer func() { serviceProbePorts, webPorts = origPorts, origWeb }()++ devices := []types.Device{{IP: "127.0.0.1", Hostname: "raspberrypi"}}+ devices[0].Type = Classify(devices[0].Vendor, devices[0].Hostname, nil)+ if devices[0].Type != TypeServer {+ t.Fatalf("precondition: expected Server, got %q", devices[0].Type)+ }++ enrichWithServices(context.Background(), devices)++ if !devices[0].WebUI {+ t.Error("expected WebUI true after probing an open web port")+ }+ if devices[0].Type != TypeServer {+ t.Errorf("hostname type should still win, got %q", devices[0].Type)+ }+}++// TestProbeServices_NothingListening confirms a probe against closed ports+// returns nothing and does not hang.+func TestProbeServices_NothingListening(t *testing.T) {+ // Reserve a port then close it, so it is almost certainly closed.+ ln, port := listenLoopback(t)+ ln.Close()++ orig := serviceProbePorts+ serviceProbePorts = []int{port}+ defer func() { serviceProbePorts = orig }()++ if open := probeServices(context.Background(), "127.0.0.1"); len(open) != 0 {+ t.Errorf("expected no open ports, got %v", open)+ }+}diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.goindex d501ef4..3a4ceb3 100644--- a/internal/scanner/scanner.go+++ b/internal/scanner/scanner.go@@ -18,12 +18,17 @@ import (// Scanner performs network scanstype 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.+ serviceDetection bool}-// New creates a new Scanner-func New(minIntervalSeconds int) *Scanner {+// New creates a new Scanner. serviceDetection enables the opt-in port probe+// used to identify devices more precisely.+func New(minIntervalSeconds int, serviceDetection bool) *Scanner {return &Scanner{- minInterval: time.Duration(minIntervalSeconds) * time.Second,+ minInterval: time.Duration(minIntervalSeconds) * time.Second,+ serviceDetection: serviceDetection,}}@@ -101,6 +106,18 @@ func (s *Scanner) Scan(ctx context.Context, cidr string) (*types.ScanResult, err}}+ // Recover names for devices that reverse DNS could not name, over NetBIOS.+ // This is name resolution like the reverse DNS lookup above, so it always+ // runs, and only touches devices that still have no hostname.+ fillWindowsNames(ctx, devices)++ // 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 {+ enrichWithServices(ctx, devices)+ }+duration := time.Since(startTime).Seconds()return &types.ScanResult{@@ -207,6 +224,11 @@ func (s *Scanner) scanWithNmap(ctx context.Context, cidr string) ([]types.Device}}+ // Infer the device type from the vendor and hostname. Port signals are+ // not available here yet; a ping scan finds no open ports. Opt-in+ // service detection will pass them in a later step.+ device.Type = Classify(device.Vendor, device.Hostname, nil)+devices = append(devices, device)}@@ -272,6 +294,8 @@ func (s *Scanner) scanWithArpScan(ctx context.Context, cidr string) ([]types.Dev// Try reverse DNSdevice.Hostname = reverseDNS(ip)+ device.Type = Classify(device.Vendor, device.Hostname, nil)+devices = append(devices, device)}diff --git a/internal/storage/address_history_test.go b/internal/storage/address_history_test.gonew file mode 100644index 0000000..980d8e9--- /dev/null+++ b/internal/storage/address_history_test.go@@ -0,0 +1,109 @@+package storage++import (+ "testing"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// TestDeviceMovingIPIsTrackedByMAC covers a device that reappears at a new IP:+// it is recognised by its MAC, its identity and user data move with it, the+// stale entry is removed, and the change is recorded.+func TestDeviceMovingIPIsTrackedByMAC(t *testing.T) {+ s := newTestStorage(t)++ // First seen at .10, with user data and a type.+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.10", MAC: "aa:bb:cc:dd:ee:ff", Hostname: "nas", Type: "Server"},+ }); err != nil {+ t.Fatal(err)+ }+ if err := s.UpdateDeviceFields("192.168.1.10", strptr("File Server"), strptr("rack 1"), strptr("Infra")); err != nil {+ t.Fatal(err)+ }++ // Same MAC reappears at .25.+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.25", MAC: "aa:bb:cc:dd:ee:ff", Hostname: "nas"},+ }); err != nil {+ t.Fatal(err)+ }++ devices := s.GetDevices()+ if _, stale := devices["192.168.1.10"]; stale {+ t.Error("the old IP entry should be removed after the device moved")+ }+ moved := devices["192.168.1.25"]+ if moved == nil {+ t.Fatal("the device should now be at the new IP")+ }+ if moved.Label != "File Server" || moved.Notes != "rack 1" || moved.Group != "Infra" {+ t.Errorf("user data did not move with the device: %+v", moved)+ }+ if moved.Type != "Server" {+ t.Errorf("type should carry over, got %q", moved.Type)+ }+ if len(moved.AddressHistory) != 1 || moved.AddressHistory[0].IP != "192.168.1.10" {+ t.Errorf("address change not recorded: %+v", moved.AddressHistory)+ }+ if moved.AddressHistory[0].ChangedAt.IsZero() {+ t.Error("the change should carry a timestamp")+ }+}++// TestDifferentMACsAreDistinctDevices confirms two devices with different MACs+// at different IPs are not confused for a move.+func TestDifferentMACsAreDistinctDevices(t *testing.T) {+ s := newTestStorage(t)+ _ = s.MergeDevices([]types.Device{{IP: "192.168.1.10", MAC: "aa:aa:aa:aa:aa:aa"}})+ _ = s.MergeDevices([]types.Device{{IP: "192.168.1.11", MAC: "bb:bb:bb:bb:bb:bb"}})++ devices := s.GetDevices()+ if len(devices) != 2 {+ t.Fatalf("expected two distinct devices, got %d", len(devices))+ }+ if len(devices["192.168.1.11"].AddressHistory) != 0 {+ t.Error("a distinct device should have no address history")+ }+}++func strptr(s string) *string { return &s }++// TestSupplementalMergeDoesNotClobber confirms a secondary source (mDNS/IPv6)+// fills gaps but never erases a MAC, vendor, or probe result the primary scan+// established.+func TestSupplementalMergeDoesNotClobber(t *testing.T) {+ s := newTestStorage(t)++ // Primary scan: full device with MAC, vendor, web flag and a risk.+ if err := s.MergeDevices([]types.Device{{+ IP: "192.168.1.5", MAC: "aa:bb:cc:dd:ee:ff", Vendor: "Acme",+ Type: "Server", WebUI: true, Risks: []string{"Telnet is open"},+ }}); err != nil {+ t.Fatal(err)+ }++ // mDNS supplements the same IP: a friendly name, but no MAC, no probe data.+ if err := s.MergeSupplemental([]types.Device{{+ IP: "192.168.1.5", Hostname: "fileserver",+ }}); err != nil {+ t.Fatal(err)+ }++ d := s.GetDevice("192.168.1.5")+ if d == nil {+ t.Fatal("device vanished")+ }+ if d.MAC != "aa:bb:cc:dd:ee:ff" {+ t.Errorf("MAC was clobbered: %q", d.MAC)+ }+ if d.Vendor != "Acme" {+ t.Errorf("vendor was clobbered: %q", d.Vendor)+ }+ if !d.WebUI || len(d.Risks) != 1 {+ t.Errorf("probe fields were clobbered: WebUI=%v Risks=%v", d.WebUI, d.Risks)+ }+ if d.Hostname != "fileserver" {+ t.Errorf("supplemental hostname not filled in: %q", d.Hostname)+ }+}diff --git a/internal/storage/storage.go b/internal/storage/storage.goindex 1395bf0..e97aeb3 100644--- a/internal/storage/storage.go+++ b/internal/storage/storage.go@@ -4,6 +4,7 @@ package storageimport ("encoding/json""fmt"+ "net""os""path/filepath""sync"@@ -48,6 +49,14 @@ func New(devicesFile, stateFile string) (*Storage, error) {return nil, fmt.Errorf("could not read the scan history at %s: %w", stateFile, err)}+ // One-time cleanup: drop phantom devices created from noisy IPv6 neighbour+ // data (link-local and privacy addresses) before that path was fixed, so an+ // upgraded install heals down to the real device count. Safe here because+ // New runs before the store is shared with any other goroutine.+ if s.pruneEphemeralIPv6Locked() {+ _ = s.saveDevices()+ }+return s, nil}@@ -251,23 +260,247 @@ func (s *Storage) MergeDevices(discovered []types.Device) error {now := time.Now()for _, d := range discovered {if existing, ok := s.devices[d.IP]; ok {- // Update existing device, preserve user data- existing.MAC = d.MAC- existing.Hostname = d.Hostname- existing.Vendor = d.Vendor+ // A primary scan is authoritative. It replaces the probe fields+ // (WebUI and Risks reflect the latest probe, so a fixed risk stops+ // showing), but it does not wipe an identity field it happened to+ // gather less of this time: a scan without sudo has no MAC, and a+ // device that did not resolve this time keeps its known name.+ if d.MAC != "" {+ existing.MAC = d.MAC+ }+ if d.Hostname != "" {+ existing.Hostname = d.Hostname+ }+ if d.Vendor != "" {+ existing.Vendor = d.Vendor+ }+ if d.Type != "" {+ existing.Type = d.Type+ }+ if d.ResponseTime != nil {+ existing.ResponseTime = d.ResponseTime+ }+ existing.WebUI = d.WebUI+ existing.Risks = d.Risks+ existing.LastSeen = now+ } else {+ dev := d+ s.addNewDeviceLocked(&dev, now)+ }+ }++ return s.saveDevices()+}++// MergeSupplemental folds in devices from a secondary source, such as mDNS or+// IPv6 neighbor discovery, that carries only part of a device's picture. It+// fills gaps on a known device but never clobbers what the primary scan found,+// and never touches the probe fields, so an mDNS answer with no MAC cannot erase+// a MAC the scan discovered, nor clear a web or risk flag.+func (s *Storage) MergeSupplemental(discovered []types.Device) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ now := time.Now()+ for _, d := range discovered {+ // A link-local IPv6 address is never a device (same reasoning as+ // MergeIPv6Neighbors); skip it so a supplemental source like mDNS cannot+ // create a phantom keyed by fe80::.+ if parsed := net.ParseIP(d.IP); parsed != nil && parsed.To4() == nil && parsed.IsLinkLocalUnicast() {+ continue+ }+ if existing, ok := s.devices[d.IP]; ok {+ if existing.MAC == "" && d.MAC != "" {+ existing.MAC = d.MAC+ }+ if existing.Hostname == "" && d.Hostname != "" {+ existing.Hostname = d.Hostname+ }+ if existing.Vendor == "" && d.Vendor != "" {+ existing.Vendor = d.Vendor+ }+ if existing.Type == "" && d.Type != "" {+ existing.Type = d.Type+ }existing.LastSeen = now- existing.ResponseTime = d.ResponseTime} else {- // New device- d.FirstSeen = now- d.LastSeen = now- s.devices[d.IP] = &d+ dev := d+ s.addNewDeviceLocked(&dev, now)}}return s.saveDevices()}+// MergeIPv6Neighbors folds IPv6 neighbour-discovery results into the inventory.+// The IPv6 neighbour cache is noisy: it is full of link-local and rotating+// privacy addresses, each often behind a randomised MAC, so a device sighted+// over IPv6 can look brand new every time. Using it to create a device per+// address is what produces hundreds of phantom entries. Instead it ENRICHES a+// device already found by the reliable IPv4/ARP scan, matched by MAC across+// address families. A new device is created only for a routable address whose+// MAC is a real (universally-administered) hardware address not already known --+// a genuine IPv6-only device. Link-local, and randomised-MAC addresses with no+// match, are dropped, so privacy addresses cannot pile up.+func (s *Storage) MergeIPv6Neighbors(discovered []types.Device) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ now := time.Now()+ changed := false+ for _, d := range discovered {+ parsed := net.ParseIP(d.IP)+ if parsed == nil || parsed.To4() != nil || parsed.IsLinkLocalUnicast() || d.MAC == "" {+ continue // not a routable IPv6 address we can attribute+ }++ // Enrich the device we already know by this MAC rather than creating a+ // second entry for its IPv6 address.+ if existing := s.findAnyByMACLocked(d.MAC); existing != nil {+ if existing.Hostname == "" && d.Hostname != "" {+ existing.Hostname = d.Hostname+ }+ if existing.Vendor == "" && d.Vendor != "" {+ existing.Vendor = d.Vendor+ }+ if existing.Type == "" && d.Type != "" {+ existing.Type = d.Type+ }+ existing.LastSeen = now+ changed = true+ continue+ }++ // No match: create a device only for a real hardware MAC (a genuine+ // IPv6-only device). A randomised MAC with no match is a privacy+ // address, not a device -- skip it so it cannot accumulate.+ if !isRandomizedMAC(d.MAC) {+ dev := d+ s.addNewDeviceLocked(&dev, now)+ changed = true+ }+ }++ if changed {+ return s.saveDevices()+ }+ return nil+}++// addNewDeviceLocked stores a device newly seen at its IP. If one with the same+// MAC exists at another IP in the same address family, it moved: its identity+// and user data carry across and the change is recorded. Callers hold s.mu.+func (s *Storage) addNewDeviceLocked(d *types.Device, now time.Time) {+ if d.MAC != "" {+ if oldIP, old := s.findByMACLocked(d.MAC, d.IP); old != nil {+ d.Label = old.Label+ d.Notes = old.Notes+ d.Group = old.Group+ d.FirstSeen = old.FirstSeen+ if d.Type == "" {+ d.Type = old.Type+ }+ d.AddressHistory = appendAddressChange(old.AddressHistory, oldIP, now)+ delete(s.devices, oldIP)+ }+ }+ if d.FirstSeen.IsZero() {+ d.FirstSeen = now+ }+ d.LastSeen = now+ s.devices[d.IP] = d+}++// findByMACLocked returns the IP and device of a stored device with the given+// MAC at an IP other than excludeIP, or "" and nil if there is none. Callers+// must hold s.mu.+//+// The match is confined to the same address family. A dual-stack device has an+// IPv4 and an IPv6 address at once, and those are not a "move" from one to the+// other: matching across families would wrongly collapse the two into one when+// IPv6 discovery runs alongside an IPv4 scan.+func (s *Storage) findByMACLocked(mac, excludeIP string) (string, *types.Device) {+ wantV4 := isIPv4(excludeIP)+ for ip, dev := range s.devices {+ if ip != excludeIP && dev.MAC == mac && isIPv4(ip) == wantV4 {+ return ip, dev+ }+ }+ return "", nil+}++func isIPv4(ip string) bool {+ parsed := net.ParseIP(ip)+ return parsed != nil && parsed.To4() != nil+}++// findAnyByMACLocked returns any stored device with the given MAC, regardless of+// address family, or nil. Used to attach an IPv6 sighting to the device already+// known from the IPv4 scan. Callers hold s.mu.+func (s *Storage) findAnyByMACLocked(mac string) *types.Device {+ if mac == "" {+ return nil+ }+ for _, dev := range s.devices {+ if dev.MAC == mac {+ return dev+ }+ }+ return nil+}++// isRandomizedMAC reports whether a MAC is locally administered (the+// second-least-significant bit of the first octet is set), which is how phones+// and laptops mark privacy-randomised addresses. Such a MAC cannot reliably+// identify a device across sightings.+func isRandomizedMAC(mac string) bool {+ hw, err := net.ParseMAC(mac)+ if err != nil || len(hw) == 0 {+ return false+ }+ return hw[0]&0x02 != 0+}++// pruneEphemeralIPv6Locked removes phantom devices that noisy IPv6 neighbour+// data created before that path was fixed: link-local addresses, and privacy+// (randomised-MAC) IPv6 addresses, which are not real, persistent devices. It+// runs on load so existing installs heal down to the real device count; once+// healed it is a no-op, because no code path creates such entries any more.+//+// It never removes a device the user has curated (a label, notes or a group),+// so a real device that happens to be keyed by such an address keeps its data+// instead of being wiped and re-created on every restart. Returns whether+// anything was removed. Callers hold s.mu.+func (s *Storage) pruneEphemeralIPv6Locked() bool {+ removed := false+ for ip, dev := range s.devices {+ parsed := net.ParseIP(ip)+ if parsed == nil || parsed.To4() != nil {+ continue // not IPv6+ }+ if dev.Label != "" || dev.Notes != "" || dev.Group != "" {+ continue // curated by the user: never auto-delete+ }+ if parsed.IsLinkLocalUnicast() || (dev.MAC != "" && isRandomizedMAC(dev.MAC)) {+ 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++func appendAddressChange(history []types.AddressChange, ip string, at time.Time) []types.AddressChange {+ history = append(history, types.AddressChange{IP: ip, ChangedAt: at})+ if len(history) > maxAddressHistory {+ history = history[len(history)-maxAddressHistory:]+ }+ return history+}+// GetLastScan returns the last scan time for a networkfunc (s *Storage) GetLastScan(network string) time.Time {s.mu.RLock()@@ -324,6 +557,27 @@ func (s *Storage) SetLastDuration(network string, seconds float64) error {return s.saveState()}+// ContinuousScanEnabled reports whether background scanning should run. It+// honours a runtime override the user set from the UI, and falls back to the+// configured default when no override has been saved.+func (s *Storage) ContinuousScanEnabled(configDefault bool) bool {+ s.mu.RLock()+ defer s.mu.RUnlock()+ if s.state.ContinuousScan != nil {+ return *s.state.ContinuousScan+ }+ return configDefault+}++// SetContinuousScan saves the user's runtime override for background scanning so+// it survives a restart.+func (s *Storage) SetContinuousScan(enabled bool) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.state.ContinuousScan = &enabled+ return s.saveState()+}+// GetStats returns device statisticsfunc (s *Storage) GetStats() types.DeviceStats {s.mu.RLock()diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.goindex b11335a..00e8558 100644--- a/internal/storage/storage_test.go+++ b/internal/storage/storage_test.go@@ -1,9 +1,13 @@package storageimport (+ "encoding/json"+ "os""path/filepath""testing""time"++ "github.com/291-Group/LAN-Orangutan/internal/types")// newTestStorage returns storage backed by a throwaway directory.@@ -88,3 +92,214 @@ func TestMostRecentScanSurvivesReload(t *testing.T) {t.Errorf("after reload GetMostRecentScan() = %v, want %v", got, when)}}++func TestContinuousScanDefaultsToConfigWhenUnset(t *testing.T) {+ dir := t.TempDir()+ s, err := New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))+ if err != nil {+ t.Fatal(err)+ }+ if !s.ContinuousScanEnabled(true) {+ t.Error("with no override saved, want the config default (true) to win")+ }+ if s.ContinuousScanEnabled(false) {+ t.Error("with no override saved, want the config default (false) to win")+ }+}++func TestContinuousScanOverrideSurvivesReload(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.Fatal(err)+ }+ // User turns continuous scanning off even though config defaults it on.+ if err := first.SetContinuousScan(false); err != nil {+ t.Fatal(err)+ }++ second, err := New(devices, state)+ if err != nil {+ t.Fatal(err)+ }+ if second.ContinuousScanEnabled(true) {+ t.Error("saved override (false) should win over the config default (true) after reload")+ }+}++func TestMergeIPv6NeighborsEnrichesByMAC(t *testing.T) {+ s := newTestStorage(t)+ // A device found by the reliable IPv4 scan.+ if err := s.MergeDevices([]types.Device{{IP: "192.168.1.5", MAC: "00:1A:2B:3C:4D:5E"}}); err != nil {+ t.Fatal(err)+ }+ // The same physical device sighted over IPv6 (same MAC, routable address).+ if err := s.MergeIPv6Neighbors([]types.Device{{IP: "2001:db8::5", MAC: "00:1A:2B:3C:4D:5E", Hostname: "printer"}}); err != nil {+ t.Fatal(err)+ }+ devs := s.GetDevices()+ 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" {+ t.Errorf("expected the IPv4 device enriched with the hostname, got %+v", devs)+ }+}++func TestMergeIPv6NeighborsCreatesOnlyForRealMAC(t *testing.T) {+ s := newTestStorage(t)+ err := s.MergeIPv6Neighbors([]types.Device{+ {IP: "fe80::1", MAC: "00:1A:2B:3C:4D:5E"}, // link-local: never a device+ {IP: "2001:db8::a", MAC: "AA:BB:CC:DD:EE:FF"}, // randomised MAC, no match: privacy ghost+ {IP: "2001:db8::b", MAC: "00:1A:2B:3C:4D:99"}, // real MAC, no match: genuine IPv6-only device+ })+ if err != nil {+ t.Fatal(err)+ }+ devs := s.GetDevices()+ if len(devs) != 1 {+ t.Fatalf("only the real-MAC IPv6-only device should be created: got %d: %+v", len(devs), devs)+ }+ if _, ok := devs["2001:db8::b"]; !ok {+ t.Errorf("expected the real-MAC device created, got %+v", devs)+ }+}++func TestPruneEphemeralIPv6OnLoad(t *testing.T) {+ dir := t.TempDir()+ devicesFile := filepath.Join(dir, "devices.json")+ stateFile := filepath.Join(dir, "state.json")++ // An install that accumulated IPv6 phantoms.+ seed := map[string]types.Device{+ "192.168.1.5": {IP: "192.168.1.5", MAC: "00:1A:2B:3C:4D:5E"}, // real LAN device: keep+ "fe80::1": {IP: "fe80::1", MAC: "00:1A:2B:3C:4D:5E"}, // link-local phantom: drop+ "2001:db8::a": {IP: "2001:db8::a", MAC: "AA:BB:CC:DD:EE:FF"}, // randomised IPv6 phantom: drop+ "2001:db8::b": {IP: "2001:db8::b", MAC: "00:1A:2B:3C:4D:99"}, // real IPv6-only device: keep+ }+ data, err := json.MarshalIndent(seed, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(devicesFile, data, 0600); err != nil {+ t.Fatal(err)+ }++ s, err := New(devicesFile, stateFile)+ if err != nil {+ t.Fatal(err)+ }+ devs := s.GetDevices()+ if len(devs) != 2 {+ t.Fatalf("expected 2 real devices after pruning phantoms, got %d: %+v", len(devs), devs)+ }+ if _, ok := devs["192.168.1.5"]; !ok {+ t.Error("real LAN device was pruned")+ }+ if _, ok := devs["2001:db8::b"]; !ok {+ t.Error("real IPv6-only device was pruned")+ }+ if _, ok := devs["fe80::1"]; ok {+ t.Error("link-local phantom survived the prune")+ }+ if _, ok := devs["2001:db8::a"]; ok {+ t.Error("randomised IPv6 phantom survived the prune")+ }+}++func TestPruneKeepsCuratedIPv6Device(t *testing.T) {+ dir := t.TempDir()+ devicesFile := filepath.Join(dir, "devices.json")+ stateFile := filepath.Join(dir, "state.json")++ // A device keyed by a link-local address that the user has labelled: it must+ // survive the prune with its label intact, not be wiped on every restart.+ seed := map[string]types.Device{+ "fe80::abcd": {IP: "fe80::abcd", MAC: "AA:BB:CC:DD:EE:FF", Label: "Front door cam", Group: "IoT"},+ "fe80::dead": {IP: "fe80::dead", MAC: "02:00:00:00:00:01"}, // unlabelled phantom: drop+ }+ data, err := json.MarshalIndent(seed, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(devicesFile, data, 0600); err != nil {+ t.Fatal(err)+ }++ s, err := New(devicesFile, stateFile)+ if err != nil {+ t.Fatal(err)+ }+ devs := s.GetDevices()+ if d, ok := devs["fe80::abcd"]; !ok || d.Label != "Front door cam" {+ t.Errorf("a curated device must survive the prune with its label; got %+v", devs["fe80::abcd"])+ }+ if _, ok := devs["fe80::dead"]; ok {+ t.Error("unlabelled link-local phantom should have been pruned")+ }+}++// TestIPv6RealisticDualStackNetwork simulates a real IPv6-enabled home network+// (which the IPv4-only test LAN cannot exercise) and asserts LAN Orangutan+// discovers the legitimate IPv6 devices while dropping only the privacy noise.+func TestIPv6RealisticDualStackNetwork(t *testing.T) {+ s := newTestStorage(t)++ // The IPv4/ARP scan finds the routable dual-stack devices first.+ if err := s.MergeDevices([]types.Device{+ {IP: "192.168.1.1", MAC: "3C:37:86:11:22:33", Hostname: "router"},+ {IP: "192.168.1.20", MAC: "A4:83:E7:44:55:66", Hostname: "macbook"},+ }); err != nil {+ t.Fatal(err)+ }++ // Then the IPv6 neighbour cache is read on a dual-stack network:+ err := s.MergeIPv6Neighbors([]types.Device{+ // The macbook again, over its global IPv6 (same NIC MAC): must ENRICH,+ // not create a second entry.+ {IP: "2001:db8:1::20", MAC: "A4:83:E7:44:55:66"},+ // A genuinely IPv6-only device (e.g. a NAS) with a real hardware MAC and+ // no IPv4: must be CREATED and shown.+ {IP: "2001:db8:1::50", MAC: "B8:27:EB:77:88:99", Hostname: "nas"},+ // A ULA IPv6-only device with a real MAC: must be CREATED.+ {IP: "fd00:abcd::7", MAC: "DC:A6:32:AA:BB:CC", Hostname: "camera"},+ // A privacy phone: rotating global IPv6 + randomised MAC, not seen over+ // IPv4: must be SKIPPED (this is the phantom source).+ {IP: "2001:db8:1::f1ee", MAC: "AA:BB:CC:DD:EE:F1"},+ // Link-local: never a device.+ {IP: "fe80::1", MAC: "3C:37:86:11:22:33"},+ })+ if err != nil {+ t.Fatal(err)+ }++ devs := s.GetDevices()+ // Expect exactly 4 real devices: router + macbook (dual-stack, one entry) ++ // nas + camera (IPv6-only). No phantom, no link-local, no duplicate.+ if len(devs) != 4 {+ t.Fatalf("expected 4 real devices, got %d: %+v", len(devs), devs)+ }+ want := map[string]bool{"192.168.1.1": true, "192.168.1.20": true, "2001:db8:1::50": true, "fd00:abcd::7": true}+ for ip := range want {+ if _, ok := devs[ip]; !ok {+ t.Errorf("missing expected device %s", ip)+ }+ }+ if _, ok := devs["2001:db8:1::20"]; ok {+ t.Error("dual-stack macbook was duplicated by its IPv6 address instead of enriched")+ }+ if _, ok := devs["2001:db8:1::f1ee"]; ok {+ t.Error("privacy phantom (randomised MAC) was created")+ }+ if _, ok := devs["fe80::1"]; ok {+ t.Error("link-local was listed as a device")+ }++ t.Logf("Resulting inventory on a dual-stack network:")+ for ip, d := range devs {+ t.Logf(" %-18s %s", ip, d.Hostname)+ }+}diff --git a/internal/types/types.go b/internal/types/types.goindex e327ec2..2204519 100644--- a/internal/types/types.go+++ b/internal/types/types.go@@ -5,16 +5,39 @@ import "time"// Device represents a discovered network devicetype Device struct {- IP string `json:"ip"`- MAC string `json:"mac"`- Hostname string `json:"hostname"`- Vendor string `json:"vendor"`+ IP string `json:"ip"`+ MAC string `json:"mac"`+ Hostname string `json:"hostname"`+ Vendor string `json:"vendor"`+ // Type is the inferred device kind (Phone, Printer, TV, and so on), or ""+ // when it could not be determined. It is derived at scan time from the+ // vendor, the hostname and, when service detection is on, the open ports.+ Type string `json:"type,omitempty"`+ // WebUI is true when the device answered on a common web port during an+ // opt-in service probe, meaning it likely serves a dashboard or admin page.+ // Always false when service detection is off.+ WebUI bool `json:"web_ui,omitempty"`+ // 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"`FirstSeen time.Time `json:"first_seen"`LastSeen time.Time `json:"last_seen"`ResponseTime *float64 `json:"response_time,omitempty"`++ // AddressHistory lists earlier IPs this device (matched by its MAC) was seen+ // at, oldest first. Empty for a device that has never changed address.+ AddressHistory []AddressChange `json:"address_history,omitempty"`+}++// AddressChange records an IP a device was previously seen at, and when it moved+// away from it, so the dashboard can show that a device has changed address.+type AddressChange struct {+ IP string `json:"ip"`+ ChangedAt time.Time `json:"changed_at"`}// IsOnline returns true if the device was seen within the last hour@@ -43,6 +66,10 @@ type ScanState struct {// LastDuration records how long the previous scan of each network took,// in seconds, so the UI can estimate progress for subsequent scans.LastDuration map[string]float64 `json:"last_duration,omitempty"`+ // ContinuousScan is a runtime override for background scanning, set from the+ // 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"`}// ScanResult represents the outcome of a network scandiff --git a/internal/web/handler.go b/internal/web/handler.goindex 7869c48..01ea40f 100644--- a/internal/web/handler.go+++ b/internal/web/handler.go@@ -69,6 +69,17 @@ type PageData struct {// minute an hour later, which is the very confusion the footer exists to// prevent.LastScanUnix int64++ // Flagged is how many devices expose a risky service, and Moved how many+ // have changed IP. They fill the dashboard summary strip with information+ // worth glancing at rather than empty space.+ Flagged int+ Moved 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+ // stale data when it is actually being kept current.+ ContinuousScan bool}// DeviceView is a device with computed display properties@@ -82,14 +93,19 @@ type DeviceView struct {// Vendor shadows the stored value so it can be resolved for records that// predate the built-in manufacturer database.Vendor string++ // Type shadows the stored value so a device recorded before classification+ // existed still shows a type, inferred from its vendor and hostname now.+ Type string}// NewHandler creates a new web handlerfunc NewHandler(store *storage.Storage, cfg *config.Config, authn *auth.Authenticator, version string) *Handler {// Parse templates with custom functionsfuncMap := template.FuncMap{- "timeAgo": timeAgo,- "lower": strings.ToLower,+ "timeAgo": timeAgo,+ "lower": strings.ToLower,+ "typeIcon": typeIcon,}tmpl := template.Must(template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html"))@@ -301,15 +317,31 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {// Convert to view modelsvar deviceViews []*DeviceViewgroupSet := make(map[string]bool)+ var flagged, moved intfor _, d := range devices {+ if len(d.Risks) > 0 {+ flagged+++ }+ if len(d.AddressHistory) > 0 {+ moved+++ }+ // 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)+dv := &DeviceView{Device: d,TimeAgo: timeAgo(d.LastSeen),LastSeenUnix: d.LastSeen.Unix(),- // Devices recorded by an older version have no vendor stored, so- // look it up now rather than showing "Unknown" until a rescan.- Vendor: scanner.ResolveVendor(d.Vendor, d.MAC),+ Vendor: resolvedVendor,+ Type: d.Type,+ }+ // Backfill a type for records that predate classification, from the same+ // vendor and hostname the row already shows. Port evidence is not+ // available here, so this is the default path, not the opt-in probe.+ if dv.Type == "" {+ dv.Type = scanner.Classify(resolvedVendor, d.Hostname, nil)}if d.IsRecent() {@@ -344,7 +376,7 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {// Get networksnetworks, _ := network.DetectNetworks()- networks = network.WithConfigured(networks, h.cfg.Scanning.Networks)+ networks = network.WithConfigured(networks, network.Filter{Configured: h.cfg.Scanning.Networks, Excluded: h.cfg.Scanning.ExcludeNetworks, OnlyConfigured: h.cfg.Scanning.OnlyConfiguredNetworks})// Get Tailscale statustailscale := network.GetTailscaleStatus()@@ -353,14 +385,18 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {stats := h.store.GetStats()data := PageData{- Title: "LAN Orangutan",- Theme: h.cfg.UI.Theme,- Devices: deviceViews,- Networks: networks,- Tailscale: tailscale,- Stats: stats,- Groups: groups,- AuthEnabled: h.auth.Enabled(),+ Title: "LAN Orangutan",+ Theme: h.cfg.UI.Theme,+ Devices: deviceViews,+ Networks: networks,+ Tailscale: tailscale,+ Stats: stats,+ Groups: groups,+ AuthEnabled: h.auth.Enabled(),+ Flagged: flagged,+ Moved: moved,+ Version: h.version,+ ContinuousScan: h.store.ContinuousScanEnabled(h.cfg.Scanning.ContinuousScan),}data.NetworkWarning = network.IsolationWarning(networks)diff --git a/internal/web/icons.go b/internal/web/icons.gonew file mode 100644index 0000000..7a84331--- /dev/null+++ b/internal/web/icons.go@@ -0,0 +1,29 @@+package web++import "html/template"++// typeIcons maps a device type to a small inline SVG, in the same Lucide style+// (fill none, currentColor stroke) as the other icons in the UI. The strings are+// static, never user input, so rendering them as template.HTML is safe.+var typeIcons = map[string]string{+ "Phone": `<rect width="14" height="20" x="5" y="2" rx="2"/><path d="M12 18h.01"/>`,+ "Computer": `<rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/>`,+ "Printer": `<path d="M6 9V2h12v7"/><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><rect width="12" height="8" x="6" y="14"/>`,+ "TV": `<rect width="20" height="15" x="2" y="7" rx="2"/><polyline points="17 2 12 7 7 2"/>`,+ "Media Player": `<circle cx="12" cy="12" r="10"/><polygon points="10 8 16 12 10 16 10 8"/>`,+ "Router": `<rect width="20" height="8" x="2" y="14" rx="2"/><path d="M6.01 18H6"/><path d="M10.01 18H10"/><path d="M15 10v4"/><path d="M17.84 7.17a4 4 0 0 0-5.66 0"/><path d="M20.66 4.34a8 8 0 0 0-11.31 0"/>`,+ "Server": `<rect width="20" height="8" x="2" y="2" rx="2"/><rect width="20" height="8" x="2" y="14" rx="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/>`,+ "IoT": `<rect width="16" height="16" x="4" y="4" rx="2"/><rect width="6" height="6" x="9" y="9" rx="1"/><path d="M15 2v2M15 20v2M2 15h2M2 9h2M20 15h2M20 9h2M9 2v2M9 20v2"/>`,+ "Game Console": `<line x1="6" x2="10" y1="12" y2="12"/><line x1="8" x2="8" y1="10" y2="14"/><line x1="15" x2="15.01" y1="13" y2="13"/><line x1="18" x2="18.01" y1="11" y2="11"/><rect width="20" height="12" x="2" y="6" rx="2"/>`,+}++// typeIcon returns the inline SVG for a device type, or empty when the type is+// unknown. Used as a template function so the device list can show an icon+// beside each type badge.+func typeIcon(deviceType string) template.HTML {+ body, ok := typeIcons[deviceType]+ if !ok {+ return ""+ }+ return template.HTML(`<svg class="type-icon" 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">` + body + `</svg>`)+}diff --git a/internal/web/icons_test.go b/internal/web/icons_test.gonew file mode 100644index 0000000..e04c628--- /dev/null+++ b/internal/web/icons_test.go@@ -0,0 +1,23 @@+package web++import (+ "strings"+ "testing"+)++func TestTypeIcon(t *testing.T) {+ // Every type the classifier can produce should have an icon.+ for _, dt := range []string{"Phone", "Computer", "Printer", "TV", "Media Player", "Router", "Server", "IoT", "Game Console"} {+ html := string(typeIcon(dt))+ if !strings.Contains(html, "<svg") {+ t.Errorf("type %q has no icon", dt)+ }+ }+ // An unknown type yields no icon, not broken markup.+ if got := typeIcon("Nonsense"); got != "" {+ t.Errorf("unknown type should yield empty, got %q", got)+ }+ if got := typeIcon(""); got != "" {+ t.Errorf("empty type should yield empty, got %q", got)+ }+}diff --git a/internal/web/static/app.js b/internal/web/static/app.jsindex 7e86ce9..40745d6 100644--- a/internal/web/static/app.js+++ b/internal/web/static/app.js@@ -15,33 +15,118 @@ function applyTheme(theme) {void root.offsetWidth; // commit the new theme instantlyroot.classList.remove('theme-switching'); // restore transitions for hoverlocalStorage.setItem('theme', theme);+ syncThemeRadios(theme);+ updateThemeToggle(theme);}-// The header button is a plain light/dark switch. It used to cycle-// light -> dark -> auto, but "auto" looks identical to whichever mode the-// system is already in, so every third click appeared to do nothing. "Auto"-// (follow the system) still lives on the settings page for anyone who wants it.-function toggleTheme() {- let current = document.documentElement.getAttribute('data-theme');- if (!current || current === 'auto') {- current = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';+// Keep the Settings page's Light/Dark/Auto radios showing the theme that is+// actually applied. Without this they are checked from the server's config+// default, so a browser that pinned Light/Dark with the header button would+// still show "Auto" selected and leave the user unable to tell what is active+// (or to re-pick a value that already looks chosen). A no-op on pages without+// the radios (the dashboard).+function syncThemeRadios(theme) {+ document.querySelectorAll('input[name="theme"]').forEach(function (radio) {+ radio.checked = radio.value === theme;+ });+}++// Icons and labels for the header theme button, one per state. The icon always+// changes on click, so cycling into Auto is visibly different even when Auto+// happens to match the current system look (a sun for light, a moon for dark, a+// monitor for "follow the system"). Feather-style strokes, currentColor so they+// sit on the header in either theme.+const THEME_TOGGLE = {+ light: {+ title: 'Theme: Light — click for Dark',+ icon: '<svg width="18" height="18" 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="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/></svg>'+ },+ dark: {+ title: 'Theme: Dark — click for Auto',+ icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg>'+ },+ auto: {+ title: 'Theme: Auto (follows your system) — click for Light',+ icon: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>'}- applyTheme(current === 'dark' ? 'light' : 'dark');+};++// Point the header button(s) at the state the given theme will land on, so the+// icon and tooltip always describe what is actually active.+function updateThemeToggle(theme) {+ const state = THEME_TOGGLE[theme] ? theme : 'auto';+ document.querySelectorAll('.theme-toggle').forEach(function (btn) {+ btn.innerHTML = THEME_TOGGLE[state].icon;+ btn.setAttribute('title', THEME_TOGGLE[state].title);+ btn.setAttribute('aria-label', THEME_TOGGLE[state].title);+ });+}++// The header button cycles light -> dark -> auto -> light, matching the three+// choices on the settings page so the two controls can never disagree. The icon+// changes on every click (see updateThemeToggle), so landing on Auto is always+// a visible change even when Auto looks like the current system theme.+function toggleTheme() {+ const current = document.documentElement.getAttribute('data-theme');+ const next = current === 'light' ? 'dark' : current === 'dark' ? 'auto' : 'light';+ applyTheme(next);}// Initialize theme(function() {const saved = localStorage.getItem('theme');- if (saved) document.documentElement.setAttribute('data-theme', saved);+ if (saved) {+ document.documentElement.setAttribute('data-theme', saved);+ // Reflect the real (localStorage) choice in the Settings radios, which+ // the server rendered from the config default and would otherwise show+ // a value the browser is not actually using.+ syncThemeRadios(saved);+ }+ // Point the header button at whatever is actually active (the saved choice,+ // or the server's config default when nothing is saved).+ updateThemeToggle(document.documentElement.getAttribute('data-theme') || 'auto');+})();++// Accent colour. Blue is the default. Orange is the stylesheet's base and+// carries no attribute; every other accent (including blue) sets data-accent,+// which the stylesheet turns into the accent for both light and dark. The+// choice is stored so it applies on every page and every visit.+function applyAccent(name) {+ name = name || 'blue';+ if (name === 'orange') {+ document.documentElement.removeAttribute('data-accent');+ } else {+ document.documentElement.setAttribute('data-accent', name);+ }+ localStorage.setItem('accent', name);+}++// setAccent is called from the settings swatches: apply and mark the active one.+function setAccent(name) {+ applyAccent(name);+ document.querySelectorAll('.accent-swatch').forEach(function(sw) {+ sw.classList.toggle('active', sw.dataset.accent === name);+ });+}++(function() {+ applyAccent(localStorage.getItem('accent'));+ // Mark the active swatch on the settings page once it has rendered.+ document.addEventListener('DOMContentLoaded', function() {+ const current = localStorage.getItem('accent') || 'blue';+ document.querySelectorAll('.accent-swatch').forEach(function(sw) {+ sw.classList.toggle('active', sw.dataset.accent === current);+ });+ });})();// Toast notifications-function showToast(message, type = 'info') {+function showToast(message, type = 'info', duration = 3000) {const toast = document.getElementById('toast');if (!toast) return;toast.textContent = message;toast.className = 'toast ' + type + ' show';- setTimeout(() => toast.classList.remove('show'), 3000);+ setTimeout(() => toast.classList.remove('show'), duration);}// API helper@@ -193,9 +278,13 @@ async function followScan() {while (true) {await new Promise(r => setTimeout(r, SCAN_POLL_MS));const progress = (await api('scan/progress')).data;- if (progress.status !== 'running') {+ // Stop when the scan ends, or when the current job is an automatic+ // background scan: the user's scan has finished and the background+ // scanner has taken the single job slot, so there is nothing of the+ // user's left to follow. Automatic scans never own the overlay.+ if (progress.status !== 'running' || progress.automatic) {hideScanProgress();- reportScanOutcome(progress);+ if (!progress.automatic) reportScanOutcome(progress);return;}showScanProgress(progress);@@ -220,7 +309,10 @@ async function runScan(target) {async function resumeScanIfRunning() {try {const progress = (await api('scan/progress')).data;- if (progress && progress.status === 'running') {+ // Only resume a scan the user started. An automatic background scan+ // must not pop the progress overlay (with its Cancel button) on its+ // own; its results simply appear on the next refresh.+ if (progress && progress.status === 'running' && !progress.automatic) {showScanProgress(progress);await followScan();}@@ -240,14 +332,31 @@ async function scanAllNetworks() {}// Device filtering+// Filter set by clicking a summary chip ("flagged" / "moved"), or null.+let statChipFilter = null;++// Toggle the chip filter: a second click on the same chip clears it.+function applyStatChipFilter(kind) {+ statChipFilter = statChipFilter === kind ? null : kind;+ filterDevices();+ if (statChipFilter) {+ document.querySelector('.table-container')?.scrollIntoView({ behavior: 'smooth', block: 'start' });+ }+}+function filterDevices() {+ // Reflect the active chip filter on the chips, which an auto-refresh may+ // have just swapped out from under us.+ document.querySelectorAll('.stat-chip-filter').forEach(chip =>+ chip.classList.toggle('active', !!statChipFilter && chip.dataset.filter === statChipFilter));+const search = (document.getElementById('device-search')?.value || '').toLowerCase();const statusFilter = document.getElementById('device-filter')?.value || 'all';const groupFilter = document.getElementById('group-filter')?.value || 'all';let visible = 0;document.querySelectorAll('.device-row').forEach(row => {- const text = [row.dataset.ip, row.dataset.hostname, row.dataset.mac, row.dataset.vendor, row.dataset.label].join(' ').toLowerCase();+ const text = [row.dataset.ip, row.dataset.hostname, row.dataset.mac, row.dataset.vendor, row.dataset.label, row.dataset.type].join(' ').toLowerCase();const status = row.dataset.status;const group = row.dataset.group || '';@@ -256,8 +365,11 @@ function filterDevices() {(statusFilter === 'online' && (status === 'online' || status === 'recent')) ||(statusFilter === 'offline' && status === 'offline');const matchGroup = groupFilter === 'all' || group === groupFilter;+ const matchChip = !statChipFilter ||+ (statChipFilter === 'moved' && row.dataset.moved === '1') ||+ (statChipFilter === 'flagged' && row.dataset.flagged === '1');- const show = matchSearch && matchStatus && matchGroup;+ const show = matchSearch && matchStatus && matchGroup && matchChip;row.style.display = show ? '' : 'none';if (show) visible++;});@@ -332,9 +444,13 @@ async function updateDeviceGroup(select) {const result = await api('device', { ip, group }, 'POST');if (result.success) {showToast('Group updated', 'success');- // Update data attribute+ // Update data attribute, then re-apply the current filters so a row+ // moved out of the active group filter stops showing (and the+ // "Showing N devices" count stays honest) without waiting for the+ // next refresh.const row = select.closest('.device-row');if (row) row.dataset.group = group;+ filterDevices();} else {showToast(result.error || 'Failed to update', 'error');}@@ -343,20 +459,90 @@ async function updateDeviceGroup(select) {}}-// Copy to clipboard+// Copy to clipboard.+//+// The async Clipboard API (navigator.clipboard) is only exposed in a secure+// context: HTTPS, or localhost. On a phone opening the dashboard over plain+// http on the LAN (http://<pi-ip>:291) it is not available, so we fall back to+// the legacy execCommand path. That is how most people reach a self-hosted+// instance, so the fallback is the common case, not an edge one.function copyToClipboard(text, event) {- navigator.clipboard.writeText(text).then(() => {- // Show feedback at cursor position- const feedback = document.createElement('div');- feedback.className = 'copy-feedback';- feedback.textContent = 'Copied!';- feedback.style.left = event.pageX + 'px';- feedback.style.top = (event.pageY - 30) + 'px';- document.body.appendChild(feedback);- setTimeout(() => feedback.remove(), 800);- }).catch(() => {- showToast('Failed to copy', 'error');- });+ const ok = () => showCopied(event);+ const fail = () => showToast('Failed to copy', 'error');+ if (navigator.clipboard && window.isSecureContext) {+ navigator.clipboard.writeText(text).then(ok).catch(() => {+ if (legacyCopy(text)) ok(); else fail();+ });+ } else if (legacyCopy(text)) {+ ok();+ } else {+ fail();+ }+}++// The floating "Copied!" note at the tap/cursor point.+function showCopied(event) {+ const feedback = document.createElement('div');+ feedback.className = 'copy-feedback';+ feedback.textContent = 'Copied!';+ document.body.appendChild(feedback);+ // .copy-feedback is position: fixed, so it is placed in viewport+ // coordinates (clientX/clientY). pageX/pageY include the scroll offset,+ // which pushed the note far below the viewport once the page was scrolled+ // down (e.g. the IPv6 rows), so it never showed there. A synthetic event+ // may lack coordinates, so fall back to the centre of the screen.+ //+ // Centre the note on the tap, then clamp it inside the viewport keeping a+ // comfortable margin from every edge. On a phone the values are right+ // aligned in their cards, so the tap lands near the right edge; without a+ // real margin the note sits flush against (or off) the screen edge, which+ // is what looked wrong. Measured after append for its real size.+ const pad = 16;+ const w = feedback.offsetWidth;+ const x = event && event.clientX ? event.clientX : window.innerWidth / 2;+ const y = event && event.clientY ? event.clientY : 40;+ const left = Math.max(pad, Math.min(x - w / 2, window.innerWidth - w - pad));+ const top = Math.max(pad, y - 30);+ feedback.style.left = left + 'px';+ feedback.style.top = top + 'px';+ setTimeout(() => feedback.remove(), 800);+}++// Legacy clipboard copy for non-secure contexts (plain-http LAN access from a+// phone). Uses a hidden, selectable field and document.execCommand('copy'),+// which is deprecated but is the only clipboard path available without HTTPS+// and still works across current mobile and desktop browsers. The Range-based+// selection is what makes it work on iOS Safari, where textarea.select() alone+// does not. Returns whether the copy succeeded, and restores any prior page+// selection so the user's own text selection is left untouched.+function legacyCopy(text) {+ let ok = false;+ const field = document.createElement('textarea');+ field.value = text;+ field.contentEditable = 'true';+ field.readOnly = false;+ field.style.position = 'fixed';+ field.style.top = '-1000px';+ field.style.opacity = '0';+ document.body.appendChild(field);+ const selection = window.getSelection();+ const previous = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;+ try {+ const range = document.createRange();+ range.selectNodeContents(field);+ selection.removeAllRanges();+ selection.addRange(range);+ field.setSelectionRange(0, text.length);+ ok = document.execCommand('copy');+ } catch (e) {+ ok = false;+ }+ document.body.removeChild(field);+ if (selection) {+ selection.removeAllRanges();+ if (previous) selection.addRange(previous);+ }+ return ok;}// Export devices@@ -432,63 +618,87 @@ function toggleDropdown(id) {let sortColumn = null;let sortAsc = true;-function sortTable(column) {+// compareRows orders two device rows by the active column and direction. Split+// out so the sort can be re-applied after an auto-refresh without re-toggling+// the direction.+function compareRows(a, b, column) {+ let valA, valB;++ switch (column) {+ case 'ip':+ // Sort IP addresses numerically+ valA = a.dataset.ip.split('.').map(n => n.padStart(3, '0')).join('');+ valB = b.dataset.ip.split('.').map(n => n.padStart(3, '0')).join('');+ break;+ case 'hostname':+ valA = a.dataset.hostname || 'zzz';+ valB = b.dataset.hostname || 'zzz';+ break;+ case 'mac':+ valA = a.dataset.mac || 'zzz';+ valB = b.dataset.mac || 'zzz';+ break;+ case 'vendor':+ valA = a.dataset.vendor || 'zzz';+ valB = b.dataset.vendor || 'zzz';+ break;+ case 'status':+ const order = { online: 0, recent: 1, offline: 2 };+ valA = order[a.dataset.status] ?? 3;+ valB = order[b.dataset.status] ?? 3;+ break;+ case 'lastseen':+ valA = parseInt(a.dataset.lastseen) || 0;+ valB = parseInt(b.dataset.lastseen) || 0;+ break;+ default:+ valA = a.dataset[column] || '';+ valB = b.dataset[column] || '';+ }++ if (valA < valB) return sortAsc ? -1 : 1;+ if (valA > valB) return sortAsc ? 1 : -1;+ return 0;+}++// applyCurrentSort reorders the rows in the DOM to match the active sort. It+// does nothing when no column is sorted, so a freshly loaded (server-ordered)+// table is left as the server sent it.+function applyCurrentSort() {+ if (!sortColumn) return;const tbody = document.getElementById('devices-tbody');if (!tbody) return;+ const rows = Array.from(tbody.querySelectorAll('.device-row'));+ rows.sort((a, b) => compareRows(a, b, sortColumn));+ rows.forEach(row => tbody.appendChild(row));+}+// updateSortIndicator shows which column is sorted and in which direction. The+// arrow flips between ascending and descending; every other column shows the+// neutral glyph. The header row is not replaced on refresh, so this only needs+// to run when the sort itself changes.+function updateSortIndicator() {+ document.querySelectorAll('.table th[data-sort]').forEach(th => {+ const icon = th.querySelector('.sort-icon');+ if (th.dataset.sort === sortColumn) {+ th.classList.add('sorted');+ if (icon) icon.textContent = sortAsc ? '↑' : '↓';+ } else {+ th.classList.remove('sorted');+ if (icon) icon.textContent = '↕';+ }+ });+}++function sortTable(column) {if (sortColumn === column) {sortAsc = !sortAsc;} else {sortColumn = column;sortAsc = true;}-- const rows = Array.from(tbody.querySelectorAll('.device-row'));-- rows.sort((a, b) => {- let valA, valB;-- switch (column) {- case 'ip':- // Sort IP addresses numerically- valA = a.dataset.ip.split('.').map(n => n.padStart(3, '0')).join('');- valB = b.dataset.ip.split('.').map(n => n.padStart(3, '0')).join('');- break;- case 'hostname':- valA = a.dataset.hostname || 'zzz';- valB = b.dataset.hostname || 'zzz';- break;- case 'mac':- valA = a.dataset.mac || 'zzz';- valB = b.dataset.mac || 'zzz';- break;- case 'vendor':- valA = a.dataset.vendor || 'zzz';- valB = b.dataset.vendor || 'zzz';- break;- case 'status':- const order = { online: 0, recent: 1, offline: 2 };- valA = order[a.dataset.status] ?? 3;- valB = order[b.dataset.status] ?? 3;- break;- case 'lastseen':- valA = parseInt(a.dataset.lastseen) || 0;- valB = parseInt(b.dataset.lastseen) || 0;- break;- default:- valA = a.dataset[column] || '';- valB = b.dataset[column] || '';- }-- if (valA < valB) return sortAsc ? -1 : 1;- if (valA > valB) return sortAsc ? 1 : -1;- return 0;- });-- rows.forEach(row => tbody.appendChild(row));-- // Update sort indicators- document.querySelectorAll('.table th').forEach(th => th.classList.remove('sorted'));+ applyCurrentSort();+ updateSortIndicator();}// Auto-refresh@@ -523,16 +733,21 @@ async function refreshInPlace() {document.getElementById('devices-tbody')?.replaceWith(freshRows);- for (const selector of ['.stats-bar', '.table-footer', '#device-count']) {+ for (const selector of ['.stat-strip', '.table-footer', '#device-count', '#scan-time-top']) {const current = document.querySelector(selector);const replacement = doc.querySelector(selector);if (current && replacement) current.replaceWith(replacement);}- // The search box and filter dropdowns are deliberately left alone, so- // re-apply what they currently say to the rows that just arrived.+ // The search box, filter dropdowns and column sort are deliberately left+ // alone, so re-apply what they currently say to the rows that just arrived.+ // Without re-sorting, a live-refreshing table would jump back to server+ // order every interval, quietly undoing the user's chosen sort.updateRelativeTimes();filterDevices();+ applyCurrentSort();+ // Let the scroll-dock re-measure in case the new strip is a different height.+ window.dispatchEvent(new Event('devices-refreshed'));return true;}@@ -546,33 +761,64 @@ function startAutoRefresh() {}, AUTO_REFRESH_MS);}-function toggleAutoRefresh() {- const toggle = document.getElementById('auto-refresh-toggle');- if (!toggle) return;+// Continuous scan is the single control for "live vs snapshot". When on, the+// server keeps scanning AND the browser auto-refreshes to show it AND the "Live"+// cue appears; when off, everything is a static snapshot. Binding the view to+// this one setting removes the confusing "scanning but frozen" combination.+// The initial state is rendered into the toggle by the server.+let continuousScan = !!(document.getElementById('continuous-scan-toggle') &&+ document.getElementById('continuous-scan-toggle').classList.contains('active'));+function stopAutoRefresh() {if (autoRefreshInterval) {clearInterval(autoRefreshInterval);autoRefreshInterval = null;- toggle.classList.remove('active');- localStorage.setItem('autoRefresh', 'false');- } else {- startAutoRefresh();- toggle.classList.add('active');- localStorage.setItem('autoRefresh', 'true');- showToast('Auto-refresh enabled (30s)', 'info');}}-// Initialize auto-refresh from localStorage-(function() {- if (localStorage.getItem('autoRefresh') === 'true') {- const toggle = document.getElementById('auto-refresh-toggle');- if (toggle) {- toggle.classList.add('active');- startAutoRefresh();- }+// Bring the view (auto-refresh polling and the "Live" cue) in line with the+// current continuous-scan state.+function applyContinuousScanState() {+ document.documentElement.classList.toggle('live-view', continuousScan);+ if (continuousScan) startAutoRefresh();+ else stopAutoRefresh();+}++// toggleContinuousScan switches the server's background scanner on or off at+// runtime. The choice is persisted server-side, so it survives a restart and+// lets a user scan once and sit on the snapshot.+async function toggleContinuousScan() {+ const toggle = document.getElementById('continuous-scan-toggle');+ if (!toggle) return;+ const next = !continuousScan;+ try {+ const res = await api('scan/continuous', { enabled: next }, 'POST');+ if (!res || !res.success) throw new Error((res && res.error) || 'request failed');+ } catch (e) {+ showToast('Could not change continuous scan: ' + e.message, 'error');+ return;}-})();+ continuousScan = next;+ toggle.classList.toggle('active', next);+ toggle.setAttribute('aria-checked', next ? 'true' : 'false');+ applyContinuousScanState();+ showToast(next+ ? 'Continuous scan on: the server keeps scanning your networks and the view updates automatically.'+ : 'Continuous scan off: showing a static snapshot. Click Scan All whenever you want a fresh one.',+ 'info', 5000);+}++// Start the view in whatever state the server reports.+applyContinuousScanState();++// Keyboard support for the toolbar switch (role="switch" tabindex="0").+document.addEventListener('keydown', e => {+ const sw = e.target.closest && e.target.closest('.toggle-switch[role="switch"]');+ if (sw && (e.key === 'Enter' || e.key === ' ')) {+ e.preventDefault();+ sw.click();+ }+});// Keyboard shortcutsdocument.addEventListener('keydown', e => {@@ -590,9 +836,8 @@ document.addEventListener('keydown', e => {case 't':toggleTheme();break;- case 'escape':- closeModal();- break;+ // Escape is handled by a dedicated listener below so it also works+ // while focus is inside a modal input, where this handler bails out.}});@@ -701,3 +946,267 @@ async function disconnectTailscale() {showToast('Could not disconnect: ' + e.message, 'error');}}++// Summary strip scroll-dock: as the page scrolls and the strip's top reaches+// the header, add .strip-docked to <body>. CSS then lifts the strip to+// position: fixed in the header band (transparent + light). It snaps in the+// instant it touches, so the glass bar is never painted over the header.+//+// The whole thing is driven by a class on <body> and matched by CSS selector;+// the strip is never moved or held in a variable, so an auto-refresh that swaps+// the strip element out cannot break it. The holder reserves the strip's height+// (via --strip-h) so the page never jumps. No-ops on narrow screens and reduced+// motion.+(function initStatDock() {+ const holder = document.querySelector('.stat-strip-holder');+ const header = document.querySelector('.header');+ if (!holder || !header) return;++ const wide = window.matchMedia('(min-width: 1100px)');+ const reduce = window.matchMedia('(prefers-reduced-motion: reduce)');+ const brand = header.querySelector('.header-brand');+ const nav = header.querySelector('.header-nav');+ let touchAt = Infinity;++ // Bound the docked strip to the space between the logo and the nav, so it+ // can never slide under either. The nav widens when a "Sign out" link is+ // present (auth enabled) and shifts with the monitor width, so measure it+ // live rather than assuming a fixed layout.+ function measureDockBounds() {+ if (!brand || !nav) return;+ const gap = 20;+ const left = Math.round(brand.getBoundingClientRect().right + gap);+ const right = Math.round(window.innerWidth - nav.getBoundingClientRect().left + gap);+ document.documentElement.style.setProperty('--dock-left', Math.max(0, left) + 'px');+ document.documentElement.style.setProperty('--dock-right', Math.max(0, right) + 'px');+ }++ function measure() {+ // Reserve exactly the strip's height, and find the scroll offset at+ // which the holder's top reaches the header's bottom (the touch point).+ // Re-query the strip so a refreshed one is always measured.+ const strip = holder.querySelector('.stat-strip');+ if (strip) holder.style.setProperty('--strip-h', strip.offsetHeight + 'px');+ touchAt = Math.max(0, holder.getBoundingClientRect().top + window.scrollY - header.offsetHeight);+ measureDockBounds();+ }++ // Drop the least-critical pieces from the docked strip only as far as+ // needed to keep it on one line inside its band: the scanned/Live line+ // first, then the chips. Driven by the real overflow (scrollWidth beyond+ // the band's clientWidth), so it adapts to any monitor width and nav size+ // instead of guessing a breakpoint.+ function fitDock() {+ const strip = holder.querySelector('.stat-strip');+ if (!strip) return;+ document.body.classList.remove('dock-hide-scan', 'dock-hide-meta');+ if (strip.scrollWidth > strip.clientWidth + 1) document.body.classList.add('dock-hide-scan');+ if (strip.scrollWidth > strip.clientWidth + 1) document.body.classList.add('dock-hide-meta');+ }++ let wasDocked = false;+ function onScroll() {+ const docked = wide.matches && !reduce.matches && window.scrollY >= touchAt;+ document.body.classList.toggle('strip-docked', docked);+ if (docked && !wasDocked) fitDock();+ if (!docked) document.body.classList.remove('dock-hide-scan', 'dock-hide-meta');+ wasDocked = docked;+ }++ function remeasure() {+ // Only re-measure the reserve while undocked; a docked holder is a fixed+ // reserve. The dock bounds, though, must track the header at any width.+ if (!document.body.classList.contains('strip-docked')) measure();+ else measureDockBounds();+ onScroll();+ if (document.body.classList.contains('strip-docked')) fitDock();+ }++ measure();+ onScroll();+ window.addEventListener('scroll', onScroll, { passive: true });+ window.addEventListener('resize', remeasure);+ // An auto-refresh can swap in a strip of a different height (e.g. a flagged+ // chip appears), so re-measure the reserve and touch point after each one.+ window.addEventListener('devices-refreshed', remeasure);+})();++// Back-to-top button: a floating orangutan that appears once the page is+// scrolled past a threshold and smoothly returns to the top when clicked.+(function initScrollTop() {+ const btn = document.getElementById('scroll-top');+ if (!btn) return;++ const THRESHOLD = 300;+ const reduce = window.matchMedia('(prefers-reduced-motion: reduce)');++ // Sit the button in the bottom-right corner, always clear of the vertical+ // scrollbar. That scrollbar has real width on Linux/Windows (~15px) and+ // zero width on overlay-scrollbar systems like macOS, so measure it+ // (innerWidth includes it, clientWidth does not) and add it to the inset.+ // This keeps the button off the scrollbar on every platform and view.+ function place() {+ const scrollbar = Math.max(0, window.innerWidth - document.documentElement.clientWidth);+ btn.style.left = 'auto';+ btn.style.right = (18 + scrollbar) + 'px';+ }++ function onScroll() {+ btn.classList.toggle('visible', window.scrollY > THRESHOLD);+ }++ place();+ onScroll();+ window.addEventListener('scroll', onScroll, { passive: true });+ window.addEventListener('resize', place);+ window.addEventListener('devices-refreshed', place);++ btn.addEventListener('click', () => {+ window.scrollTo({ top: 0, behavior: reduce.matches ? 'auto' : 'smooth' });+ });+})();++// Instant tooltips for truncated table cells (hostname, vendor, label). The+// native `title` attribute waits ~1s before showing (and resets to that delay+// when "cold"), so those cells use this instead: one shared element at the body+// level, shown the moment the pointer enters a cell whose text is actually+// clipped. Positioned in fixed coordinates so the cell's overflow never clips it.+(function initCellTips() {+ const table = document.getElementById('devices-table');+ if (!table) return;++ const tip = document.createElement('div');+ tip.id = 'cell-tip';+ tip.setAttribute('role', 'tooltip');+ document.body.appendChild(tip);++ const SELECTOR = '.hostname-cell, .vendor-cell, .label-cell, .ip-cell, .mac-cell';++ function isClipped(cell) {+ return cell.scrollWidth > cell.clientWidth + 1;+ }++ function show(cell) {+ const text = (cell.textContent || '').trim();+ if (!text || !isClipped(cell)) return;++ // Match the cell's own text exactly so the reveal reads as the same text+ // un-truncating in place rather than a separate label.+ const cs = getComputedStyle(cell);+ const c = cell.getBoundingClientRect();+ tip.textContent = text;+ tip.style.fontFamily = cs.fontFamily;+ tip.style.fontSize = cs.fontSize;+ tip.style.fontWeight = cs.fontWeight;+ tip.style.fontStyle = cs.fontStyle;+ tip.style.letterSpacing = cs.letterSpacing;+ tip.style.color = cs.color;+ tip.style.paddingLeft = cs.paddingLeft;+ tip.style.paddingRight = cs.paddingRight;+ tip.style.height = Math.round(c.height) + 'px';+ tip.classList.add('show');++ // Overlay the cell and grow to the right; nudge left only if the full+ // value would run off the right edge of the window.+ const t = tip.getBoundingClientRect();+ let left = c.left;+ if (left + t.width > window.innerWidth - 6) {+ left = Math.max(6, window.innerWidth - t.width - 6);+ }+ tip.style.left = Math.round(left) + 'px';+ tip.style.top = Math.round(c.top) + 'px';+ }++ function hide() {+ tip.classList.remove('show');+ }++ // Delegated hover. mouseover/mouseout bubble, so they cover cells added by+ // an auto-refresh too. Only hide when the pointer truly leaves the cell.+ table.addEventListener('mouseover', function (e) {+ const cell = e.target.closest(SELECTOR);+ if (cell) show(cell);+ });+ table.addEventListener('mouseout', function (e) {+ const cell = e.target.closest(SELECTOR);+ if (cell && !cell.contains(e.relatedTarget)) hide();+ });+ // A stale tooltip must not linger over new content.+ window.addEventListener('scroll', hide, { passive: true });+})();++// Click-to-copy for value cells (IP, MAC, hostname, vendor). Driven by a+// data-copy attribute and event delegation rather than an inline onclick, so a+// 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.+(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 value = cell.getAttribute('data-copy');+ if (value) copyToClipboard(value, e);+ });+})();++// Clickable summary chips: clicking "N flagged" or "N moved" filters the device+// list to just those devices (and a second click clears it). Delegated on the+// document so it keeps working after an auto-refresh swaps the strip, and while+// the strip is docked in the header.+(function initStatChipFilters() {+ document.addEventListener('click', function (e) {+ const chip = e.target.closest && e.target.closest('.stat-chip-filter[data-filter]');+ if (chip) applyStatChipFilter(chip.dataset.filter);+ });+ document.addEventListener('keydown', function (e) {+ if (e.key !== 'Enter' && e.key !== ' ') return;+ const chip = e.target.closest && e.target.closest('.stat-chip-filter[data-filter]');+ if (chip) { e.preventDefault(); applyStatChipFilter(chip.dataset.filter); }+ });+})();++// Instant tooltips for small indicators carrying a data-tip attribute (moved,+// risk, web-interface, notes). One shared bubble at the body level shown the+// moment the pointer enters the element, so there is no native `title` delay.+// Delegated on the document, so it also covers rows added by an auto-refresh.+(function initHintTips() {+ let tip = null;+ function ensure() {+ if (!tip) {+ tip = document.createElement('div');+ tip.id = 'hint-tip';+ tip.setAttribute('role', 'tooltip');+ document.body.appendChild(tip);+ }+ return tip;+ }+ function show(el) {+ const text = el.getAttribute('data-tip');+ if (!text) return;+ const t = ensure();+ t.textContent = text;+ t.classList.add('show');+ const r = el.getBoundingClientRect();+ const tr = t.getBoundingClientRect();+ let left = r.left + r.width / 2 - tr.width / 2;+ left = Math.max(6, Math.min(left, window.innerWidth - tr.width - 6));+ let top = r.top - tr.height - 8; // above the icon by default+ if (top < 6) top = r.bottom + 8; // drop below when no room above+ t.style.left = Math.round(left) + 'px';+ t.style.top = Math.round(top) + 'px';+ }+ function hide() {+ if (tip) tip.classList.remove('show');+ }+ document.addEventListener('mouseover', function (e) {+ const el = e.target.closest && e.target.closest('[data-tip]');+ if (el) show(el);+ });+ document.addEventListener('mouseout', function (e) {+ const el = e.target.closest && e.target.closest('[data-tip]');+ if (el && !el.contains(e.relatedTarget)) hide();+ });+ window.addEventListener('scroll', hide, { passive: true });+})();diff --git a/internal/web/static/style.css b/internal/web/static/style.cssindex ff7b504..ce4f709 100644--- a/internal/web/static/style.css+++ b/internal/web/static/style.css@@ -1,60 +1,129 @@:root,[data-theme="light"] {+ /* 291 defacto palette (from LAN Sheriff), mapped onto LAN Orangutan's+ variable names. Orange stays the product's brand accent; the 291 gold,+ blue and greens fill the semantic roles. */--bg-primary: #ffffff;- --bg-secondary: #f8fafc;- --bg-tertiary: #f1f5f9;- --text-primary: #0f172a;- --text-secondary: #475569;- --text-muted: #94a3b8;- --border-color: #e2e8f0;- --accent-primary: #f97316;- --accent-secondary: #06b6d4;- --accent-hover: #ea580c;- --success: #22c55e;- --success-bg: rgba(34, 197, 94, 0.1);- --warning: #f59e0b;- --warning-bg: rgba(245, 158, 11, 0.1);- --danger: #ef4444;- --danger-bg: rgba(239, 68, 68, 0.1);- --card-shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06);- --card-shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);- --header-bg: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);+ --bg-secondary: #eef2f8;+ --bg-tertiary: #e4ecf6;+ --text-primary: #16202e;+ --text-secondary: #56637a;+ --text-muted: #8592a6;+ --border-color: rgba(16, 24, 40, 0.09);+ --accent-primary: #e0842c;+ --accent-secondary: #2f7fd4;+ --accent-hover: #c9721f;+ --success: #2c9e6b;+ --success-bg: rgba(44, 158, 107, 0.12);+ --warning: #d9a227;+ --warning-bg: rgba(217, 162, 39, 0.14);+ --danger: #d9483f;+ --danger-bg: rgba(217, 72, 63, 0.10);+ --card-shadow: 0 2px 10px rgba(16, 24, 40, 0.06);+ --card-shadow-lg: 0 8px 32px rgba(16, 24, 40, 0.09);+ --glass: rgba(255, 255, 255, 0.66);+ --glass-strong: rgba(255, 255, 255, 0.82);+ --blur: saturate(180%) blur(20px);+ --header-bg: linear-gradient(135deg, #16202e 0%, #0e141f 100%);--header-text: #ffffff;- --radius-sm: 6px;- --radius-md: 10px;+ --radius-sm: 9px;+ --radius-md: 12px;--radius-lg: 16px;--transition: all 0.2s ease;}[data-theme="dark"],html[data-theme="dark"] {- --bg-primary: #0f172a;- --bg-secondary: #1e293b;- --bg-tertiary: #334155;- --text-primary: #f1f5f9;- --text-secondary: #cbd5e1;- --text-muted: #64748b;- --border-color: #334155;- --card-shadow: 0 1px 3px rgba(0,0,0,0.3);- --card-shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.4);- --header-bg: linear-gradient(135deg, #0f172a 0%, #020617 100%);+ --bg-primary: #0e141f;+ --bg-secondary: #1a222f;+ --bg-tertiary: #26313f;+ --text-primary: #e4ebf5;+ --text-secondary: #97a5ba;+ --text-muted: #6c7b91;+ --border-color: rgba(255, 255, 255, 0.09);+ --accent-primary: #d98a3a;+ --accent-secondary: #4a9eda;+ --accent-hover: #c47a2c;+ --success: #4cc38a;+ --success-bg: rgba(76, 195, 138, 0.14);+ --warning: #e8b64c;+ --warning-bg: rgba(232, 182, 76, 0.16);+ --danger: #e05c5c;+ --danger-bg: rgba(224, 92, 92, 0.14);+ --card-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);+ --card-shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.45);+ --glass: rgba(26, 34, 47, 0.58);+ --glass-strong: rgba(26, 34, 47, 0.82);+ --blur: saturate(180%) blur(20px);+ --header-bg: linear-gradient(135deg, #0a0f17 0%, #141019 100%);}@media (prefers-color-scheme: dark) {[data-theme="auto"] {- --bg-primary: #0f172a;- --bg-secondary: #1e293b;- --bg-tertiary: #334155;- --text-primary: #f1f5f9;- --text-secondary: #cbd5e1;- --text-muted: #64748b;- --border-color: #334155;- --card-shadow: 0 1px 3px rgba(0,0,0,0.3);- --card-shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.4);- --header-bg: linear-gradient(135deg, #0f172a 0%, #020617 100%);+ --bg-primary: #0e141f;+ --bg-secondary: #1a222f;+ --bg-tertiary: #26313f;+ --text-primary: #e4ebf5;+ --text-secondary: #97a5ba;+ --text-muted: #6c7b91;+ --border-color: rgba(255, 255, 255, 0.09);+ --accent-primary: #d98a3a;+ --accent-secondary: #4a9eda;+ --accent-hover: #c47a2c;+ --success: #4cc38a;+ --success-bg: rgba(76, 195, 138, 0.14);+ --warning: #e8b64c;+ --warning-bg: rgba(232, 182, 76, 0.16);+ --danger: #e05c5c;+ --danger-bg: rgba(224, 92, 92, 0.14);+ --card-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);+ --card-shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.45);+ --glass: rgba(26, 34, 47, 0.58);+ --glass-strong: rgba(26, 34, 47, 0.82);+ --blur: saturate(180%) blur(20px);+ --header-bg: linear-gradient(135deg, #0a0f17 0%, #141019 100%);}}+/* ---- Selectable accent themes ---------------------------------------------+ The 291 palette carries several accents. Orange is the default (set in the+ base blocks above and used when no data-accent is present). Each alternative+ overrides the accent in BOTH light and dark, so whichever accent is chosen,+ light and dark both keep working. Set data-accent on the root to switch. */++[data-accent="gold"] { --accent-primary: #d9a227; --accent-hover: #bd8b18; }+[data-accent="blue"] { --accent-primary: #2f7fd4; --accent-hover: #2569b3; }+[data-accent="green"] { --accent-primary: #2c9e6b; --accent-hover: #248257; }+[data-accent="purple"] { --accent-primary: #8b6fc4; --accent-hover: #7458b0; }++[data-theme="dark"][data-accent="gold"] { --accent-primary: #e8b64c; --accent-hover: #d9a227; }+[data-theme="dark"][data-accent="blue"] { --accent-primary: #4a9eda; --accent-hover: #3f8ac5; }+[data-theme="dark"][data-accent="green"] { --accent-primary: #4cc38a; --accent-hover: #3faa76; }+[data-theme="dark"][data-accent="purple"] { --accent-primary: #9b82d4; --accent-hover: #8a6fc9; }++@media (prefers-color-scheme: dark) {+ [data-theme="auto"][data-accent="gold"] { --accent-primary: #e8b64c; --accent-hover: #d9a227; }+ [data-theme="auto"][data-accent="blue"] { --accent-primary: #4a9eda; --accent-hover: #3f8ac5; }+ [data-theme="auto"][data-accent="green"] { --accent-primary: #4cc38a; --accent-hover: #3faa76; }+ [data-theme="auto"][data-accent="purple"] { --accent-primary: #9b82d4; --accent-hover: #8a6fc9; }+}++/* Accent picker swatches on the settings page. */+.accent-swatches { display: flex; gap: 0.65rem; margin-top: 0.5rem; }+.accent-swatch {+ width: 30px;+ height: 30px;+ border-radius: 50%;+ border: 2px solid var(--border-color);+ cursor: pointer;+ padding: 0;+ transition: var(--transition);+}+.accent-swatch:hover { transform: scale(1.1); }+.accent-swatch.active {+ box-shadow: 0 0 0 2px var(--bg-primary), 0 0 0 4px var(--accent-primary);+}+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }/* While the theme is switching, turn transitions off so the whole page changes@@ -64,9 +133,21 @@ html[data-theme="dark"] {transition: none !important;}+/* The header is sticky and 64px tall, so a programmatic scroll to a target+ ("N moved" / "N flagged" jumps to the table, an anchor) would otherwise land+ with the target's top tucked under the header. Padding the scroll root by the+ header height plus a little breathing room stops every such scroll just below+ it. */+html {+ scroll-padding-top: 76px;+}+body {font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', sans-serif;- background: var(--bg-secondary);+ /* 291 style: a soft three-stop gradient across the page rather than a flat+ fill, giving cards something to sit against. Fixed so it does not scroll. */+ background: linear-gradient(160deg, var(--bg-secondary) 0%, var(--bg-tertiary) 55%, var(--bg-secondary) 100%);+ background-attachment: fixed;color: var(--text-primary);line-height: 1.6;-webkit-font-smoothing: antialiased;@@ -106,6 +187,84 @@ a:hover { color: var(--accent-hover); }.logo {font-size: 2rem;filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));+ /* Optical alignment: geometric centering leaves the mark reading a touch+ high next to the wordmark, so nudge it down 1px. */+ position: relative;+ top: 1px;+}++/* Back-to-top button: the orangutan under a single upward chevron, in a soft+ round button. Appears once the page is scrolled (.visible, toggled from JS)+ and returns to the top when clicked; hidden and click-through until then. JS+ sets its right offset so it always clears the scrollbar. */+.scroll-top {+ position: fixed;+ right: 1.5rem;+ bottom: 1.5rem;+ z-index: 200;+ width: 54px;+ height: 54px;+ padding: 0;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 1px;+ border: 1px solid var(--border-color);+ border-radius: 50%;+ /* Soft, theme-aware fill: a touch of accent over the surface, so it reads as+ a gentle button rather than a loud block. */+ background: color-mix(in srgb, var(--accent-primary) 15%, var(--bg-secondary));+ box-shadow: 0 6px 16px -4px rgba(0, 0, 0, 0.35);+ cursor: pointer;+ opacity: 0;+ transform: translateY(14px) scale(0.95);+ transition: opacity 0.25s ease, transform 0.25s ease, box-shadow 0.2s ease, border-color 0.2s ease, background 0.2s ease;+ pointer-events: none;+}++.scroll-top.visible {+ opacity: 1;+ transform: translateY(0) scale(1);+ pointer-events: auto;+}++.scroll-top:hover {+ border-color: var(--accent-primary);+ background: color-mix(in srgb, var(--accent-primary) 24%, var(--bg-secondary));+ box-shadow: 0 9px 20px -5px rgba(0, 0, 0, 0.42);+ transform: translateY(-2px) scale(1.03);+}++/* A single upward chevron above the mascot: a clean "up" cue, not a rank patch. */+.scroll-top-chevron {+ color: var(--accent-primary);+ margin-bottom: -1px;+ transition: transform 0.2s ease;+}++.scroll-top:hover .scroll-top-chevron {+ transform: translateY(-2px);+}++/* The mascot has no animation of its own; it just rides the button's hover+ lift so the whole button moves as one piece. */+.scroll-top-logo {+ display: block;+ filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.25));+}++@media (prefers-reduced-motion: reduce) {+ .scroll-top,+ .scroll-top-chevron {+ transition: opacity 0.2s ease;+ }+ .scroll-top:hover .scroll-top-chevron {+ transform: none;+ }+ .scroll-top.visible {+ transform: none;+ }}.header h1 {@@ -145,6 +304,9 @@ a:hover { color: var(--accent-hover); }padding: 0.5rem 0.75rem;border-radius: var(--radius-sm);transition: var(--transition);+ display: inline-flex;+ align-items: center;+ justify-content: center;}.theme-toggle:hover {@@ -196,7 +358,9 @@ a:hover { color: var(--accent-hover); }/* Cards */.card {- background: var(--bg-primary);+ background: var(--glass);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);border-radius: var(--radius-lg);padding: 1.5rem;box-shadow: var(--card-shadow);@@ -232,106 +396,385 @@ a:hover { color: var(--accent-hover); }/* Network Cards */.network-cards {display: grid;- grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));- gap: 1.25rem;- /* Let each card take only the height its own content needs. Stretching- them to match the tallest leaves short cards, such as a disconnected- Tailscale, with a large empty area below the text. */- align-items: start;+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));+ gap: 1rem;+ /* Cards in the same row stretch to a shared height so their bottoms line+ up instead of sitting at ragged levels. Each card then pushes its action+ button to that shared bottom edge (see .net-scan / .tailscale-actions),+ so a shorter card reads as intentional rather than half-empty. */+ align-items: stretch;}-.network-card {- position: relative;- overflow: hidden;+.net-card {+ background: var(--glass);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);+ border: 1px solid var(--border-color);+ border-radius: var(--radius-lg);+ padding: 1.1rem 1.2rem;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ transition: var(--transition);}-.network-card::before {- content: '';- position: absolute;- top: 0;- left: 0;- right: 0;- height: 4px;- background: var(--accent-primary);+.net-card:hover {+ transform: translateY(-2px);+ box-shadow: var(--card-shadow-lg);+ border-color: color-mix(in srgb, var(--accent-primary) 40%, var(--border-color));}-.network-card.tailscale::before {- background: var(--accent-secondary);+.net-card-top {+ display: flex;+ align-items: center;+ gap: 0.55rem;}-.network-name {- font-weight: 700;- font-size: 1.1rem;+/* Accent-tinted icon chip replaces the old full-width stripe on top of the+ card: it carries the same colour cue with far less visual weight. */+.net-icon {+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 30px;+ height: 30px;+ border-radius: var(--radius-sm);+ background: color-mix(in srgb, var(--accent-primary) 14%, transparent);+ color: var(--accent-primary);}-.network-detail {+.net-card.tailscale .net-icon {+ background: color-mix(in srgb, var(--accent-secondary) 14%, transparent);+ color: var(--accent-secondary);+}++.net-name {+ font-weight: 600;+ font-size: 1rem;+ flex: 1 1 auto;+ min-width: 0;+ /* Network names are short, meaningful labels (e.g. "Tailscale VPN", which+ we feature as native), so wrap to a second line rather than truncating.+ A featured name must never be cut down to "Tailscal...". */+ overflow-wrap: anywhere;+ line-height: 1.25;+}++/* Keep the status badge at its natural size so it never steals room from the+ name or gets squeezed itself. */+.net-card-top .status-badge {+ flex: 0 0 auto;+}++/* The old label/value rows became a single inline meta line: less vertical+ space, no dashed spec-sheet look. */+.net-meta {display: flex;- justify-content: space-between;- padding: 0.5rem 0;- font-size: 0.9rem;- border-bottom: 1px dashed var(--border-color);+ align-items: center;+ flex-wrap: wrap;+ gap: 0.4rem;+ font-size: 0.85rem;+ color: var(--text-secondary);}-.network-detail:last-child {- border-bottom: none;+.net-meta-muted {+ color: var(--text-muted);+ font-size: 0.8rem;}-.network-detail .label {+.net-sep {color: var(--text-muted);- font-weight: 500;+ opacity: 0.7;}-.network-detail .value {+.net-mono {font-family: 'SF Mono', 'Fira Code', monospace;- font-size: 0.85rem;- color: var(--text-secondary);+ font-size: 0.82rem;}-/* Stats Bar */-.stats-bar {- display: grid;- grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));- gap: 1.25rem;+.net-scan {+ align-self: flex-start;}-.stat-card {- background: var(--bg-primary);+/* On a plain network card the scan button is the footer: push it to the card's+ bottom edge so buttons line up across cards of differing content height. */+.net-card > .net-scan {+ margin-top: auto;+}++/* Stat strip: one slim summary row that replaces the four boxed stat cards,+ freeing the vertical space they used to eat for four numbers. The counts sit+ on the left; a security summary and last-scan time fill the right so the bar+ never reads as a half-empty pill. */+.stat-strip {+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: 0.5rem 1.5rem;+ padding: 0.7rem 1.2rem;+ background: var(--glass);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);+ border: 1px solid var(--border-color);border-radius: var(--radius-lg);- padding: 1.5rem;box-shadow: var(--card-shadow);+}++/* The holder wraps the strip and carries its spacing, so that when the strip is+ lifted out (position: fixed) to dock into the header, the holder can hold the+ vacated height and the page never jumps. */+.stat-strip-holder {+ margin-bottom: 2rem;+}++/* Scroll-dock: on wide screens the summary strip pins up into the header's+ empty middle as the page scrolls. app.js adds .docked once it reaches the+ header; it pops into a compact, transparent, light-text state so the dark+ header band stays one unbroken colour. The glass AND its blur are dropped+ entirely while docked, otherwise the blur would frost the header and read as+ a pale bar over it. */+/* Scroll-dock (wide screens): when the strip scrolls up and its top touches the+ header, app.js adds .strip-docked to <body>. The strip then lifts to+ position: fixed in the header band, transparent and light, so it reads as+ part of the header. It snaps in the instant it touches, so the glass bar is+ never drawn over the header on the way in. Everything is driven by the body+ class and matched by selector, so the strip is never moved or referenced and+ an auto-refresh that swaps it out cannot break the effect. The holder holds+ the vacated height so the page does not jump. */+@media (min-width: 1100px) {+ body.strip-docked .stat-strip-holder {+ height: var(--strip-h, 52px);+ }++ body.strip-docked .stat-strip {+ position: fixed;+ top: 8px;+ /* Bounded between the logo and the nav (set from JS) so the docked+ strip never slides under either, whatever the monitor width or+ whether a "Sign out" link widens the nav. */+ left: var(--dock-left, 0);+ right: var(--dock-right, 0);+ width: auto;+ margin: 0;+ z-index: 101; /* above the header (100) */+ transform: scale(0.92);+ transform-origin: top center;+ background: transparent;+ -webkit-backdrop-filter: none;+ backdrop-filter: none;+ border-color: transparent;+ box-shadow: none;+ justify-content: center;+ color: var(--header-text);+ /* Transparent display over the header, so clicks reach the nav under it. */+ pointer-events: none;+ /* Stay on a single line inside the header band, never wrap to two rows. */+ flex-wrap: nowrap;+ gap: 0.9rem;+ }+ body.strip-docked .stat-strip-main,+ body.strip-docked .stat-strip-meta {+ flex-wrap: nowrap;+ }+ /* When the docked strip is short of room beside the nav, drop the least+ important pieces first: the scanned/Live line (also shown at the table+ toolbar and footer), then the status chips. app.js measures the actual+ fit and toggles these, so there is no arbitrary width breakpoint. */+ body.strip-docked.dock-hide-scan .stat-scan {+ display: none;+ }+ body.strip-docked.dock-hide-meta .stat-strip-meta {+ display: none;+ }+ body.strip-docked .stat-strip .stat-num { color: var(--header-text); }+ body.strip-docked .stat-strip .stat-num.online { color: var(--success); }+ body.strip-docked .stat-strip .stat-cap,+ body.strip-docked .stat-strip .stat-scan {+ color: color-mix(in srgb, var(--header-text) 62%, transparent);+ }+ body.strip-docked .stat-strip .stat-sep {+ background: color-mix(in srgb, var(--header-text) 30%, transparent);+ }+ body.strip-docked .stat-strip .stat-chip {+ background: transparent;+ border-color: color-mix(in srgb, currentColor 42%, transparent);+ }+}++.stat-strip-main,+.stat-strip-meta {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+}++.stat-strip-main { gap: 0.5rem 1.25rem; }+.stat-strip-meta { gap: 0.5rem 0.75rem; }++/* Small pill summarising a class of finding (security, moved). Coloured by+ severity, and calm green when there is nothing to flag. */+.stat-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ /* Less padding on the left than the right: the leading icon's SVG box+ carries its own transparent space, so equal padding makes the left read+ roomier and the text sit tight against the right. */+ padding: 0.2rem 0.6rem 0.2rem 0.5rem;+ border-radius: 9999px;+ font-size: 0.78rem;+ font-weight: 600;border: 1px solid var(--border-color);- text-align: center;- transition: var(--transition);+ white-space: nowrap;}-.stat-card:hover {- transform: translateY(-2px);- box-shadow: var(--card-shadow-lg);+.stat-chip svg { flex: 0 0 auto; }++.stat-chip-ok {+ color: var(--success);+ background: color-mix(in srgb, var(--success) 12%, transparent);+ border-color: color-mix(in srgb, var(--success) 30%, transparent);}-.stat-icon {- font-size: 2rem;- margin-bottom: 0.5rem;+.stat-chip-danger {+ color: var(--danger);+ background: color-mix(in srgb, var(--danger) 12%, transparent);+ border-color: color-mix(in srgb, var(--danger) 30%, transparent);}-.stat-value {- font-size: 2.5rem;- font-weight: 800;- display: block;+.stat-chip-warn {+ color: var(--warning);+ background: color-mix(in srgb, var(--warning) 12%, transparent);+ border-color: color-mix(in srgb, var(--warning) 30%, transparent);+}++/* Flagged / moved chips are clickable: they filter the device list to just+ those devices, so the number is not a dead end. */+.stat-chip-filter {+ cursor: pointer;+ user-select: none;+}++.stat-chip-filter:hover {+ filter: brightness(0.97);+}++.stat-chip-filter.active {+ box-shadow: 0 0 0 2px currentColor;+}++.stat-chip-filter:focus-visible {+ outline: none;+ box-shadow: 0 0 0 2px currentColor;+}++/* The docked strip is click-through (pointer-events: none) so the header nav+ stays reachable, but the filter chips must still be clickable up there. */+body.strip-docked .stat-strip .stat-chip-filter {+ pointer-events: auto;+}++/* "Live" cue shown wherever the last-scan time appears when the server is+ re-scanning on its own, so the timestamp does not read as stale. */+.live-indicator {+ display: inline-flex;+ align-items: center;+ gap: 0.32rem;+ color: var(--success);+ font-weight: 600;+}++.live-dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--success);+ animation: livePulse 2.2s ease-out infinite;+}++@keyframes livePulse {+ 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 55%, transparent); }+ 70% { box-shadow: 0 0 0 6px color-mix(in srgb, var(--success) 0%, transparent); }+ 100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--success) 0%, transparent); }+}++@media (prefers-reduced-motion: reduce) {+ .live-dot { animation: none; }+}++.live-sep {+ color: var(--text-muted);+ opacity: 0.7;+}++/* Lay out the "Live" pill, its separator, and the scan time in a row so hiding+ the pill leaves no orphan separator. */+.stat-scan,+.table-scanned,+.table-footer-label {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+}++/* The "Live" cue only means anything while the view is actually auto-refreshing.+ app.js toggles .live-view on <html> from the Auto-refresh switch; with it off,+ the pill and its separator hide, leaving just the last-scan time. */+:root:not(.live-view) .live-indicator,+:root:not(.live-view) .live-sep {+ display: none;+}++.stat-scan {+ color: var(--text-muted);+ font-size: 0.8rem;+ white-space: nowrap;+}++.stat-item {+ display: inline-flex;+ align-items: baseline;+ gap: 0.4rem;+}++.stat-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ align-self: center;+ background: var(--text-muted);+}++.stat-dot.dot-online { background: var(--success); }++.stat-dot.dot-offline {+ background: transparent;+ border: 1.5px solid var(--text-muted);+ width: 7px;+ height: 7px;+}++.stat-num {+ font-size: 1.35rem;+ font-weight: 700;line-height: 1;- margin-bottom: 0.25rem;+ letter-spacing: -0.01em;}-.stat-value.online { color: var(--success); }-.stat-value.warning { color: var(--warning); }-.stat-value.danger { color: var(--danger); }+.stat-num.online { color: var(--success); }-.stat-label {- font-size: 0.85rem;+.stat-cap {+ font-size: 0.82rem;color: var(--text-muted);font-weight: 500;- text-transform: uppercase;- letter-spacing: 0.05em;+}++.stat-sep {+ width: 1px;+ height: 20px;+ background: var(--border-color);}/* Status Badges */@@ -346,6 +789,59 @@ a:hover { color: var(--accent-hover); }text-transform: uppercase;}+/* Device type pill in the device list. Neutral by default so it reads as a+ quiet label rather than competing with the status colours. */+.type-cell {+ white-space: nowrap;+}++.type-badge {+ display: inline-flex;+ align-items: center;+ /* Align the badge to the same middle line the web/moved/risk indicators use,+ so an icon and anything beside it in the cell sit on one centre line rather+ than the badge dropping to the text baseline. */+ vertical-align: middle;+ gap: 0.3rem;+ padding: 0.15rem 0.55rem;+ border-radius: 9999px;+ font-size: 0.72rem;+ font-weight: 600;+ background: var(--bg-tertiary);+ color: var(--text-secondary);+ border: 1px solid var(--border-color);+}++.type-icon {+ flex: 0 0 auto;+ opacity: 0.85;+}++.web-indicator {+ display: inline-flex;+ vertical-align: middle;+ margin-left: 0.35rem;+ color: var(--text-muted);+}++/* A device that has changed IP: worth a subtle nudge, so it uses the warning+ colour and a tooltip listing where it used to be. */+.moved-indicator {+ display: inline-flex;+ vertical-align: middle;+ margin-left: 0.35rem;+ color: var(--warning);+}++/* A device exposing an insecure service: the strongest cue in the list, in the+ danger colour, with the specific concern in the tooltip. */+.risk-indicator {+ display: inline-flex;+ vertical-align: middle;+ margin-left: 0.35rem;+ color: var(--danger);+}+.status-badge.online {background: var(--success-bg);color: var(--success);@@ -363,9 +859,14 @@ a:hover { color: var(--accent-hover); }/* Table */.table-container {- background: var(--bg-primary);+ background: var(--glass);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);border-radius: var(--radius-lg);- overflow: hidden;+ /* Safety net only: the fixed table layout and the responsive column-hiding+ below keep the table within this panel at every width, so this never+ actually scrolls in normal use. The page body never scrolls sideways. */+ overflow-x: auto;box-shadow: var(--card-shadow);border: 1px solid var(--border-color);}@@ -409,15 +910,158 @@ a:hover { color: var(--accent-hover); }color: var(--text-secondary);}+/* Data-freshness note in the top toolbar, mirroring the one in the footer, so+ the "last scanned" time is visible without scrolling to the bottom. */+.table-scanned {+ font-size: 0.85rem;+ color: var(--text-muted);+}++/* Key for the Status column colours. Kept quiet (footer, muted) so it explains+ the dots without competing with the data. */+.status-legend {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 0.4rem 1rem;+ color: var(--text-muted);+}++.legend-item {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+}++.legend-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex: 0 0 auto;+}++.legend-dot.online { background: var(--success); }+.legend-dot.seen { background: var(--warning); }+.legend-dot.offline {+ background: transparent;+ border: 1.5px solid var(--text-muted);+ width: 7px;+ height: 7px;+}++/* Value cells you can click to copy get a pointer. Empty ones carry+ data-copy="" (a placeholder like "Unknown") and stay a normal cursor. */+td[data-copy]:not([data-copy=""]) {+ cursor: pointer;+}++/* In-place reveal for a truncated table cell (hostname, vendor, label). Rather+ than a floating bubble, it sits exactly over the cell's own text and grows to+ the right, so the "..." appears to expand in place into the full value. One+ element at the body level driven by app.js (which copies the cell's font,+ colour and left padding so the overlap is seamless); it shows instantly on+ hover (no native `title` delay) and is not clipped by the cell's overflow.+ The row-coloured background and a soft shadow lift the overflow so it stays+ readable over the neighbouring columns. */+#cell-tip {+ position: fixed;+ z-index: 300;+ display: none;+ align-items: center;+ box-sizing: border-box;+ white-space: nowrap;+ max-width: 92vw;+ overflow: hidden;+ text-overflow: ellipsis;+ background: var(--bg-secondary);+ border-radius: 5px;+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.16);+ pointer-events: none;+}++#cell-tip.show {+ display: inline-flex;+}++/* Instant tooltip for small indicators (moved, risk, web interface, notes).+ One element at the body level driven by app.js off a data-tip attribute, so+ these show immediately on hover instead of waiting out the native title+ delay, and are positioned above the icon. */+#hint-tip {+ position: fixed;+ z-index: 400;+ max-width: 300px;+ padding: 0.4rem 0.6rem;+ font-size: 0.8rem;+ line-height: 1.4;+ font-weight: 400;+ color: var(--text-primary);+ background: var(--bg-primary);+ border: 1px solid var(--border-color);+ border-radius: var(--radius-sm);+ box-shadow: var(--card-shadow-lg);+ white-space: normal;+ overflow-wrap: anywhere;+ pointer-events: none;+ display: none;+}++#hint-tip.show {+ display: block;+}+.table {width: 100%;border-collapse: collapse;+ /* Fixed layout makes the columns share the panel width and hold their+ place, so no combination of long hostnames, vendors or MAC strings can+ push the table wider than its container. Overlong values truncate within+ their own column. */+ table-layout: fixed;}.table th, .table td {- padding: 1rem 1.25rem;+ padding: 0.7rem 0.65rem;text-align: left;border-bottom: 1px solid var(--border-color);+ /* With fixed layout, keep every cell's content inside its column: nothing+ may spill out and widen the row. */+ overflow: hidden;+ text-overflow: ellipsis;+}++/* Column widths for the fixed layout (they sum to 100%). When the responsive+ rules further down hide a column, its share is redistributed across the+ rest, so the table always fills its panel exactly. */+.table th:nth-child(1), .table td:nth-child(1) { width: 6%; } /* Status (just a dot) */+.table th:nth-child(2), .table td:nth-child(2) { width: 12%; } /* IP */+.table th:nth-child(3), .table td:nth-child(3) { width: 13%; } /* Hostname */+.table th:nth-child(4), .table td:nth-child(4) { width: 10%; } /* Type */+.table th:nth-child(5), .table td:nth-child(5) { width: 13%; } /* MAC */+.table th:nth-child(6), .table td:nth-child(6) { width: 10%; } /* Vendor */+.table th:nth-child(7), .table td:nth-child(7) { width: 5%; } /* Label (just an icon) */+.table th:nth-child(8), .table td:nth-child(8) { width: 11%; } /* Group (dropdown needs room) */+.table th:nth-child(9), .table td:nth-child(9) { width: 10%; } /* Last Seen*/+.table th:nth-child(10), .table td:nth-child(10) { width: 10%; } /* Actions (two icons) */++/* Single-line cells that should truncate rather than wrap. The group select+ fills its column so it never forces the row wider. */+.ip-cell, .mac-cell, .time-cell { white-space: nowrap; }+.group-select { width: 100%; max-width: 100%; }++/* The Actions cell holds icon buttons, not text: it must never show a text+ ellipsis in place of the delete button. The `.table td` selector above is+ more specific than a lone class, so this qualifies with `.table td` to win+ and turns the ellipsis off, letting both buttons show. */+.table td.actions-cell { white-space: nowrap; text-overflow: clip; overflow: visible; }++/* Keep the table inside its panel with no horizontal scroll: the two free-text+ columns truncate with an ellipsis rather than forcing the table wider. */+.hostname-cell, .vendor-cell {+ max-width: 150px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;}.table th {@@ -438,7 +1082,7 @@ a:hover { color: var(--accent-hover); }}.table th .sort-icon {- margin-left: 0.5rem;+ margin-left: 0.3rem;opacity: 0.5;}@@ -535,6 +1179,12 @@ a:hover { color: var(--accent-hover); }.label-cell {font-weight: 500;color: var(--accent-primary);+ /* Labels are free text, so cap and truncate them like hostname and vendor+ so a long one can never stretch the table past its panel. */+ max-width: 160px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;}.notes-indicator {@@ -582,7 +1232,7 @@ a:hover { color: var(--accent-hover); }/* Forms */.input, .select {padding: 0.65rem 1rem;- border: 2px solid var(--border-color);+ border: 1px solid var(--border-color);border-radius: var(--radius-md);background: var(--bg-primary);color: var(--text-primary);@@ -608,7 +1258,9 @@ a:hover { color: var(--accent-hover); }.input:focus, .select:focus {outline: none;border-color: var(--accent-primary);- box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.1);+ /* Tinted to the active accent rather than a fixed colour, so the focus ring+ follows whichever accent theme is chosen. */+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent-primary) 22%, transparent);}.input::placeholder {@@ -624,6 +1276,13 @@ a:hover { color: var(--accent-hover); }background-size: 1.25rem;}+/* The Notes field in the edit-device dialog is the only textarea. Allow it to+ grow taller but not wider: a horizontal drag would blow out the dialog+ layout. */+textarea.input {+ resize: vertical;+}+.form-group {margin-bottom: 1.25rem;}@@ -646,7 +1305,7 @@ a:hover { color: var(--accent-hover); }/* Buttons */.btn {padding: 0.65rem 1.25rem;- border: 2px solid var(--border-color);+ border: 1px solid var(--border-color);border-radius: var(--radius-md);background: var(--bg-primary);color: var(--text-primary);@@ -753,7 +1412,10 @@ a:hover { color: var(--accent-hover); }}.modal-content {- background: var(--bg-primary);+ background: var(--glass-strong);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);+ border: 1px solid var(--border-color);border-radius: var(--radius-lg);width: 90%;max-width: 480px;@@ -850,7 +1512,9 @@ a:hover { color: var(--accent-hover); }top: 80px;left: 50%;transform: translateX(-50%);- background: var(--bg-primary);+ background: var(--glass-strong);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);padding: 1rem 1.75rem;border-radius: var(--radius-lg);box-shadow: 0 10px 40px rgba(0,0,0,0.15);@@ -989,6 +1653,12 @@ a:hover { color: var(--accent-hover); }background: var(--success);}+/* Visible keyboard focus for the switch (it is a div role="switch"). */+.toggle-switch:focus-visible {+ outline: 2px solid var(--accent-primary);+ outline-offset: 2px;+}+.toggle-switch::after {content: '';position: absolute;@@ -1016,7 +1686,9 @@ a:hover { color: var(--accent-hover); }top: 100%;right: 0;margin-top: 0.5rem;- background: var(--bg-primary);+ background: var(--glass-strong);+ backdrop-filter: var(--blur);+ -webkit-backdrop-filter: var(--blur);border: 1px solid var(--border-color);border-radius: var(--radius-md);box-shadow: var(--card-shadow-lg);@@ -1068,22 +1740,165 @@ a:hover { color: var(--accent-hover); }/* Responsive */@media (max-width: 1024px) {.main { padding: 1.5rem; }- .network-cards { grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); }- .stats-bar { grid-template-columns: repeat(2, 1fr); }+}++/* Tablets only (phones switch to the card layout below): drop the widest+ optional columns (Vendor, Label) so the rest keep room without cramming. */+@media (min-width: 769px) and (max-width: 1024px) {+ .table th:nth-child(6), .table td:nth-child(6),+ .table th:nth-child(7), .table td:nth-child(7) { display: none; }+}++/* Discovered-devices toolbar: on a full desktop the section title sits on one+ line with its controls (continuous-scan toggle, search, the two filters,+ Export, Scan All) beside it. Below ~1150px those controls no longer fit next+ to the title and wrap into three or four ragged rows. Instead, drop them onto+ their own full-width row under the title and let the search field flex to+ absorb the slack, so the controls stay on one tidy line down to phone widths.+ The desktop layout above this width is left untouched. */+@media (max-width: 1150px) {+ .section-header {+ flex-direction: column;+ align-items: stretch;+ }+ .section-actions {+ flex-wrap: wrap;+ }+ .search-input {+ flex: 1 1 240px;+ width: auto;+ min-width: 200px;+ }+}++/* Summary strip: below full desktop width the horizontal bar's stats and status+ chips can wrap onto two ragged rows, and where exactly depends on the content+ (how many chips, how big the numbers), so any single "it wraps here" value is+ fragile. Instead, well above the worst-case wrap (~1024px), the strip becomes+ a tidy grid of bordered stat tiles with the chips and scan line beneath. On a+ tablet the four stats sit in one clean row; on a phone they drop to the 2x2+ grid. The horizontal bar is then only ever shown at desktop width, where it+ always fits on one line. Kept on its own breakpoint, separate from the 768px+ table-card one, so the strip restyles without dragging the device table into+ card mode with it. */+@media (max-width: 1024px) {+ .stat-strip {+ flex-direction: column;+ align-items: stretch;+ gap: 0.85rem;+ padding: 1rem;+ }+ .stat-strip-main {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.6rem;+ width: 100%;+ }+ .stat-item {+ gap: 0.45rem;+ padding: 0.7rem 0.85rem;+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: var(--radius-md);+ }+ .stat-sep { display: none; }+ .stat-strip-meta {+ justify-content: flex-start;+ gap: 0.5rem;+ }+ /* Keep the status chips on the left but push the "Live / scanned X ago"+ status to the right edge of the card. */+ .stat-scan { margin-left: auto; }+}++/* Narrow enough that four tiles in a row would be too cramped: fall back to the+ 2x2 grid. */+@media (max-width: 600px) {+ .stat-strip-main {+ grid-template-columns: 1fr 1fr;+ }}@media (max-width: 768px) {.header { padding: 0 1rem; }.header h1 { display: none; }.main { padding: 1rem; }- .section-header { flex-direction: column; align-items: stretch; }- .section-actions { justify-content: space-between; }- .table-container { overflow-x: auto; }- .table th, .table td { padding: 0.75rem; }- .search-input { width: 100%; }- .stat-card { padding: 1rem; }- .stat-value { font-size: 1.75rem; }+ /* Let the toolbar controls wrap onto more lines instead of squeezing, and+ give the search field its own full-width row above them. */+ .section-actions { gap: 0.5rem; }+ .search-input { flex-basis: 100%; }.toast { left: 1rem; right: 1rem; bottom: 1rem; }++ /* A ten-column table cannot be read on a phone, so each device becomes its+ own card: the header row is dropped and every cell shows its field name+ (from data-label) beside its value. No horizontal scroll, every field+ stays visible. */+ .table, .table tbody { display: block; }+ .table thead { display: none; }+ .table .device-row {+ display: block;+ margin-bottom: 0.75rem;+ padding: 0.1rem 0;+ border: 1px solid var(--border-color);+ border-radius: var(--radius-md);+ background: var(--bg-secondary);+ overflow: hidden;+ }+ .table .device-row td {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ width: auto;+ /* Lift the desktop truncation caps (hostname/vendor/label have a fixed+ max-width) so every cell fills the card and its value aligns to the+ right edge, consistently with IP, MAC and Last Seen. */+ max-width: none;+ padding: 0.5rem 0.9rem;+ border-bottom: 1px solid var(--border-color);+ text-align: right;+ white-space: normal;+ overflow: visible;+ text-overflow: clip;+ }+ .table .device-row td:last-child { border-bottom: none; }+ .table .device-row td::before {+ content: attr(data-label);+ flex: 0 0 auto;+ margin-right: auto;+ font-size: 0.7rem;+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--text-muted);+ }+ /* 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; }++ /* Each card carries its own surface, so drop the panel's glass background,+ border and shadow and let the cards sit directly on the page. The toolbar+ ("Showing N devices") and the footer legend lose their fills too, so they+ read as page content rather than a boxed panel. */+ .table-container {+ background: transparent;+ -webkit-backdrop-filter: none;+ backdrop-filter: none;+ border: none;+ box-shadow: none;+ border-radius: 0;+ overflow: visible;+ }+ .table-toolbar {+ background: transparent;+ border-bottom: none;+ padding: 0.25rem 0.15rem 0.85rem;+ }+ .table-footer {+ background: transparent;+ border-top: none;+ padding: 0.85rem 0.15rem;+ }}/* Copy Animation */@@ -1233,18 +2048,6 @@ a:hover { color: var(--accent-hover); }flex-shrink: 0;}-.stat-icon .icon {- color: var(--text-secondary);-}--.stat-icon-online .icon {- color: var(--success);-}--.stat-icon-offline .icon {- color: var(--text-muted);-}-.btn-icon .icon {color: var(--text-secondary);transition: var(--transition);@@ -1314,7 +2117,9 @@ img.login-logo {/* Tailscale connect/disconnect */.tailscale-actions {- margin-top: 1rem;+ /* Same footer treatment as a plain card's scan button: sink the Tailscale+ action group (with its message line just below) to the card's bottom. */+ margin-top: auto;display: flex;gap: 0.5rem;}@@ -1330,3 +2135,210 @@ img.login-logo {.tailscale-message:empty {display: none;}++/* ---- Scrollbar: slim and unobtrusive, tinted to the theme (291 style) ---- */+* {+ scrollbar-width: thin;+ scrollbar-color: var(--text-muted) transparent;+}+::-webkit-scrollbar {+ width: 10px;+ height: 10px;+}+::-webkit-scrollbar-track {+ background: transparent;+}+::-webkit-scrollbar-thumb {+ background: var(--text-muted);+ border-radius: 9999px;+ border: 3px solid transparent;+ background-clip: content-box;+}+::-webkit-scrollbar-thumb:hover {+ background: var(--text-secondary);+ background-clip: content-box;+}++/* No-JavaScript fallback: a full-screen, on-brand panel shown only when+ scripting is disabled (the markup lives in a <noscript> block, so it never+ appears when JS is on). It covers the otherwise non-functional dashboard with+ a clear explanation and a safety note. Uses theme tokens so it matches light+ and dark, and loads with the stylesheet regardless of JS. */+.noscript-screen {+ position: fixed;+ inset: 0;+ z-index: 9999;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 1.5rem;+ background: var(--bg-primary);+ overflow: auto;+}++.noscript-card {+ max-width: 780px;+ width: 100%;+ padding: 2rem 2.25rem;+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: var(--radius-lg);+ box-shadow: var(--card-shadow-lg);+ color: var(--text-secondary);+ text-align: left;+}++/* Header: logo beside the title/intro, so the page does not open as one tall+ centred column. */+.noscript-head {+ display: flex;+ align-items: center;+ gap: 1rem;+ margin-bottom: 1.5rem;+}++.noscript-logo {+ flex: 0 0 auto;+ filter: drop-shadow(0 2px 6px rgba(0, 0, 0, 0.25));+}++.noscript-card h1 {+ margin-bottom: 0.3rem;+ font-size: 1.4rem;+ font-weight: 700;+ letter-spacing: -0.02em;+ color: var(--text-primary);+}++.noscript-sub {+ line-height: 1.5;+}++.noscript-card p {+ line-height: 1.55;+}++/* Two side-by-side choices (dashboard vs CLI); stacks on narrow screens. */+.noscript-cols {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 1rem;+ margin-bottom: 1.25rem;+}++@media (max-width: 640px) {+ .noscript-cols {+ grid-template-columns: 1fr;+ }+}++.noscript-panel {+ padding: 1.1rem 1.2rem;+ background: var(--bg-primary);+ border: 1px solid var(--border-color);+ border-radius: var(--radius-md);+}++.noscript-panel h2 {+ margin-bottom: 0.6rem;+ font-size: 1rem;+ font-weight: 700;+ color: var(--text-primary);+}++.noscript-panel p {+ margin-bottom: 0.6rem;+}++.noscript-panel ul {+ margin: 0 0 0.7rem 1.1rem;+ line-height: 1.55;+}++.noscript-panel li {+ margin-bottom: 0.2rem;+}++.noscript-action {+ margin-bottom: 0 !important;+ font-weight: 600;+ color: var(--text-primary);+}++.noscript-action-muted {+ margin-bottom: 0 !important;+ font-size: 0.9em;+}++.noscript-cli {+ margin: 0 0 0.7rem;+ padding: 0.75rem 0.85rem;+ background: var(--bg-tertiary);+ border-radius: var(--radius-sm);+ overflow-x: auto;+}++.noscript-cli code {+ display: block;+ font-family: 'SF Mono', 'Fira Code', monospace;+ font-size: 0.82rem;+ line-height: 1.7;+ color: var(--text-primary);+ white-space: pre;+ background: none;+ padding: 0;+}++.noscript-safety {+ padding: 0.8rem 1rem;+ background: color-mix(in srgb, var(--accent-primary) 12%, var(--bg-primary));+ border-left: 3px solid var(--accent-primary);+ border-radius: var(--radius-md);+}++.noscript-safety strong {+ color: var(--text-primary);+}++.noscript-card code {+ font-family: 'SF Mono', 'Fira Code', monospace;+ font-size: 0.85em;+ background: var(--bg-tertiary);+ padding: 0.1rem 0.35rem;+ border-radius: 4px;+}++.noscript-footer {+ display: flex;+ align-items: center;+ flex-wrap: wrap;+ gap: 0.5rem;+ margin-top: 1.25rem;+ padding-top: 1rem;+ border-top: 1px solid var(--border-color);+ font-size: 0.85rem;+ color: var(--text-muted);+}++.noscript-footer-logo {+ flex: 0 0 auto;+ opacity: 0.9;+}++.noscript-footer-name {+ font-weight: 600;+ color: var(--text-secondary);+}++.noscript-footer-sep {+ color: var(--text-muted);+ opacity: 0.6;+}++.noscript-footer a {+ color: var(--accent-primary);+}++.noscript-footer a:hover {+ color: var(--accent-hover);+}diff --git a/internal/web/templates/index.html b/internal/web/templates/index.htmlindex 024e1ec..b3fb8b0 100644--- a/internal/web/templates/index.html+++ b/internal/web/templates/index.html@@ -1,13 +1,60 @@<!DOCTYPE html><html lang="en" data-theme="{{.Theme}}"><head>+ <script>(function(){try{var t=localStorage.getItem("theme");if(t)document.documentElement.setAttribute("data-theme",t);var a=localStorage.getItem("accent")||"blue";if(a!=="orange")document.documentElement.setAttribute("data-accent",a);if({{if .ContinuousScan}}true{{else}}false{{end}})document.documentElement.classList.add("live-view");}catch(e){}})();</script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>LAN Orangutan - Network Discovery</title>- <link rel="stylesheet" href="/static/style.css">+ <link rel="stylesheet" href="/static/style.css?v={{.Version}}"><link rel="icon" type="image/svg+xml" href="/static/orangutan.svg"></head><body>+ <noscript>+ <div class="noscript-screen">+ <div class="noscript-card">+ <div class="noscript-head">+ <img src="/static/orangutan.svg" alt="LAN Orangutan" class="noscript-logo" width="60" height="60">+ <div>+ <h1>JavaScript is switched off</h1>+ <p class="noscript-sub">The web dashboard needs JavaScript to run. Here's what it offers, and how to use LAN Orangutan without it. Pick whichever you prefer.</p>+ </div>+ </div>++ <div class="noscript-cols">+ <section class="noscript-panel">+ <h2>The web dashboard</h2>+ <p>A live, visual view of your network. It uses JavaScript for:</p>+ <ul>+ <li>Live device updates as the server scans</li>+ <li>Running scans, and sorting, filtering, searching</li>+ <li>Editing labels and groups, and copying addresses</li>+ </ul>+ <p class="noscript-action">Allow JavaScript for this site (in your browser or script blocker), then reload.</p>+ </section>++ <section class="noscript-panel">+ <h2>Or the command line</h2>+ <p>Same discovery, no browser or JavaScript needed, straight from your terminal:</p>+ <pre class="noscript-cli"><code>orangutan scan all # scan your networks+orangutan list # list found devices+orangutan status # service & network status+orangutan export out.csv</code></pre>+ <p class="noscript-action-muted">Run <code>orangutan --help</code> to see everything.</p>+ </section>+ </div>++ <p class="noscript-safety"><strong>Is the dashboard safe?</strong> Yes. LAN Orangutan is self-hosted: its JavaScript runs entirely in your own browser against your own server, and makes no third-party or external calls. It is served from this machine at <code>/static/app.js</code>.</p>++ <footer class="noscript-footer">+ <img src="/static/orangutan.svg" alt="" class="noscript-footer-logo" width="22" height="22">+ <span class="noscript-footer-name">LAN Orangutan by 291 Group</span>+ <span class="noscript-footer-sep">•</span>+ <a href="https://github.com/291-Group/LAN-Orangutan" target="_blank" rel="noopener">github.com/291-Group/LAN-Orangutan</a>+ </footer>+ </div>+ </div>+ </noscript>+<header class="header"><a href="/" class="header-brand"><img src="/static/orangutan.svg" alt="" class="logo" width="32" height="32">@@ -31,31 +78,65 @@{{.NetworkWarning}}</div>{{end}}- <!-- Stats Section -->- <section class="section">- <div class="stats-bar">- <div class="stat-card">- <div class="stat-icon"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="12" width="4" height="8"/><rect x="10" y="7" width="4" height="13"/><rect x="17" y="3" width="4" height="17"/></svg></div>- <span class="stat-value">{{.Stats.Total}}</span>- <span class="stat-label">Total Devices</span>- </div>- <div class="stat-card">- <div class="stat-icon stat-icon-online"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="12" cy="12" r="7"/></svg></div>- <span class="stat-value online">{{.Stats.Online}}</span>- <span class="stat-label">Online</span>- </div>- <div class="stat-card">- <div class="stat-icon stat-icon-offline"><svg class="icon" width="20" height="20" 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="7"/></svg></div>- <span class="stat-value">{{.Stats.Offline}}</span>- <span class="stat-label">Offline</span>+ <!-- Summary strip. On wide screens it pops up into the header's empty+ middle as you scroll (transparent + light), snapping in the instant+ it touches the header so it is never drawn over it. The docked state+ is a class on <body>, and the holder reserves the strip's space, so+ the strip is never moved or referenced by JS: an auto-refresh that+ swaps it out cannot break the effect, and the page never jumps. See+ .stat-strip in the CSS and initStatDock in app.js. -->+ <div class="stat-strip-holder">+ <div class="stat-strip">+ <div class="stat-strip-main">+ <div class="stat-item">+ <span class="stat-dot dot-total"></span>+ <span class="stat-num">{{.Stats.Total}}</span>+ <span class="stat-cap">device{{if ne .Stats.Total 1}}s{{end}}</span>+ </div>+ <span class="stat-sep"></span>+ <div class="stat-item">+ <span class="stat-dot dot-online"></span>+ <span class="stat-num online">{{.Stats.Online}}</span>+ <span class="stat-cap">online</span>+ </div>+ <span class="stat-sep"></span>+ <div class="stat-item">+ <span class="stat-dot dot-offline"></span>+ <span class="stat-num">{{.Stats.Offline}}</span>+ <span class="stat-cap">offline</span>+ </div>+ <span class="stat-sep"></span>+ <div class="stat-item">+ <span class="stat-num">{{len .Networks}}</span>+ <span class="stat-cap">network{{if ne (len .Networks) 1}}s{{end}}</span>+ </div></div>- <div class="stat-card">- <div class="stat-icon"><svg class="icon" width="20" height="20" 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="9"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18"/></svg></div>- <span class="stat-value">{{len .Networks}}</span>- <span class="stat-label">Networks</span>+ <div class="stat-strip-meta">+ {{if .Flagged}}+ <span class="stat-chip stat-chip-danger stat-chip-filter" data-filter="flagged" role="button" tabindex="0" title="Show the {{.Flagged}} device{{if ne .Flagged 1}}s{{end}} exposing a risky service">+ <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="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><path d="M12 9v4M12 17h.01"/></svg>+ {{.Flagged}} flagged+ </span>+ {{else if .Stats.Total}}+ <span class="stat-chip stat-chip-ok" title="No devices are exposing a risky service">+ <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="M20 6 9 17l-5-5"/></svg>+ All clear+ </span>+ {{end}}+ {{if .Moved}}+ <span class="stat-chip stat-chip-warn stat-chip-filter" data-filter="moved" role="button" tabindex="0" title="Show the {{.Moved}} device{{if ne .Moved 1}}s{{end}} that changed IP address">+ <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="M5 12h14M13 6l6 6-6 6"/></svg>+ {{.Moved}} moved+ </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">·</span><span class="scan-when">scanned <span data-relative-time="{{.LastScanUnix}}">{{.LastScanAgo}}</span></span>{{end}}+ </span>+ {{end}}</div></div>- </section>+ </div><!-- Networks Section --><section class="section">@@ -65,68 +146,50 @@single-address /32 that there is no point sweeping, so it isskipped here rather than shown twice. */}}{{range .Networks}}{{if not .IsTailscale}}- <div class="card network-card">- <div class="card-header">- <span class="network-name">{{.FriendlyName}}</span>+ <div class="net-card">+ <div class="net-card-top">+ <span class="net-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.55a11 11 0 0 1 14 0"/><path d="M8.5 16.1a6 6 0 0 1 7 0"/><path d="M2 8.82a15 15 0 0 1 20 0"/><line x1="12" y1="19.5" x2="12.01" y2="19.5"/></svg></span>+ <span class="net-name">{{.FriendlyName}}</span><span class="status-badge online">Active</span></div>- <div class="card-body">- <div class="network-detail">- <span class="label">Network</span>- <span class="value">{{.CIDR}}</span>- </div>- <div class="network-detail">- <span class="label">Interface</span>- <span class="value">{{.Interface}}</span>- </div>- <div class="network-detail">- <span class="label">Your IP</span>- <span class="value">{{.IP}}</span>- </div>- </div>- <div class="card-footer">- <button class="btn btn-primary btn-sm" onclick="scanNetwork('{{.CIDR}}')">Scan Network</button>+ <div class="net-meta">+ <span class="net-mono">{{.CIDR}}</span>+ <span class="net-sep">·</span>+ <span>{{.Interface}}</span></div>+ <div class="net-meta net-meta-muted">you <span class="net-mono">{{.IP}}</span></div>+ <button class="btn btn-primary btn-sm net-scan" onclick="scanNetwork('{{.CIDR}}')">Scan network</button></div>{{end}}{{end}}{{if and .Tailscale.Installed .Tailscale.Running}}- <div class="card network-card tailscale">- <div class="card-header">- <span class="network-name">Tailscale VPN</span>+ <div class="net-card tailscale">+ <div class="net-card-top">+ <span class="net-icon"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg></span>+ <span class="net-name">Tailscale VPN</span><span class="status-badge {{if .Tailscale.Connected}}online{{else}}offline{{end}}">{{.Tailscale.StatusLabel}}</span></div>- <div class="card-body">- {{/* The IP and peer list linger from the last session after- Tailscale is stopped, so only show them while connected. */}}+ {{/* The IP and peer list linger from the last session after+ Tailscale is stopped, so only show them while connected. */}}+ {{if .Tailscale.Connected}}+ <div class="net-meta">+ {{if .Tailscale.SelfIP}}<span class="net-mono">{{.Tailscale.SelfIP}}</span><span class="net-sep">·</span>{{end}}+ <span>{{.Tailscale.PeerCount}} peer{{if ne .Tailscale.PeerCount 1}}s{{end}}</span>+ </div>+ {{else}}+ <div class="net-meta net-meta-muted">Not connected</div>+ {{end}}++ {{if .Tailscale.Installed}}+ <div class="tailscale-actions">{{if .Tailscale.Connected}}- {{if .Tailscale.SelfIP}}- <div class="network-detail">- <span class="label">Your IP</span>- <span class="value">{{.Tailscale.SelfIP}}</span>- </div>- {{end}}- <div class="network-detail">- <span class="label">Peers</span>- <span class="value">{{.Tailscale.PeerCount}} devices</span>- </div>+ <button class="btn btn-sm net-scan" onclick="disconnectTailscale()">Disconnect</button>{{else}}- <div class="network-detail">- <span class="label">Not connected</span>- </div>- {{end}}-- {{if .Tailscale.Installed}}- <div class="tailscale-actions">- {{if .Tailscale.Connected}}- <button class="btn btn-sm" onclick="disconnectTailscale()">Disconnect</button>- {{else}}- <button class="btn btn-sm btn-primary" onclick="connectTailscale()">Connect</button>- {{end}}- </div>- <div id="tailscale-message" class="tailscale-message"></div>+ <button class="btn btn-sm btn-primary net-scan" onclick="connectTailscale()">Connect</button>{{end}}</div>+ <div id="tailscale-message" class="tailscale-message"></div>+ {{end}}</div>{{end}}</div>@@ -138,8 +201,8 @@<h2 class="section-title">Discovered Devices</h2><div class="section-actions"><div class="auto-refresh">- <span>Auto-refresh</span>- <div class="toggle-switch" id="auto-refresh-toggle" onclick="toggleAutoRefresh()"></div>+ <span>Continuous scan</span>+ <div class="toggle-switch{{if .ContinuousScan}} active{{end}}" id="continuous-scan-toggle" role="switch" aria-checked="{{if .ContinuousScan}}true{{else}}false{{end}}" tabindex="0" onclick="toggleContinuousScan()" data-tip="On: keeps scanning and the view stays live. Off: a static snapshot you can refresh with Scan All."></div></div><input type="text" id="device-search" class="input search-input" placeholder="Search devices..." oninput="filterDevices()"><select id="device-filter" class="select" style="width:auto" onchange="filterDevices()">@@ -171,18 +234,20 @@<div class="table-container"><div class="table-toolbar"><span class="table-info" id="device-count">Showing {{len .Devices}} device{{if ne (len .Devices) 1}}s{{end}}</span>+ <span class="table-scanned" id="scan-time-top"><span class="live-indicator"><span class="live-dot"></span>Live</span>{{if .LastScanAt}}<span class="live-sep">·</span><span class="scan-when">scanned <span data-relative-time="{{.LastScanUnix}}">{{.LastScanAgo}}</span></span>{{end}}</span></div><table class="table" id="devices-table"><thead><tr>- <th onclick="sortTable('status')">Status <span class="sort-icon">↕</span></th>- <th onclick="sortTable('ip')">IP Address <span class="sort-icon">↕</span></th>- <th onclick="sortTable('hostname')">Hostname <span class="sort-icon">↕</span></th>- <th onclick="sortTable('mac')">MAC Address <span class="sort-icon">↕</span></th>- <th onclick="sortTable('vendor')">Vendor <span class="sort-icon">↕</span></th>+ <th data-sort="status" onclick="sortTable('status')">Status <span class="sort-icon">↕</span></th>+ <th data-sort="ip" onclick="sortTable('ip')">IP Address <span class="sort-icon">↕</span></th>+ <th data-sort="hostname" onclick="sortTable('hostname')">Hostname <span class="sort-icon">↕</span></th>+ <th data-sort="type" onclick="sortTable('type')">Type <span class="sort-icon">↕</span></th>+ <th data-sort="mac" onclick="sortTable('mac')">MAC Address <span class="sort-icon">↕</span></th>+ <th data-sort="vendor" onclick="sortTable('vendor')">Vendor <span class="sort-icon">↕</span></th><th>Label</th><th>Group</th>- <th onclick="sortTable('lastseen')">Last Seen <span class="sort-icon">↕</span></th>+ <th data-sort="lastseen" onclick="sortTable('lastseen')">Last Seen <span class="sort-icon">↕</span></th><th>Actions</th></tr></thead>@@ -193,25 +258,33 @@data-hostname="{{lower .Hostname}}"data-mac="{{lower .MAC}}"data-vendor="{{lower .Vendor}}"+ data-type="{{lower .Type}}"data-label="{{lower .Label}}"data-label-original="{{.Label}}"data-notes="{{.Notes}}"data-group="{{.Group}}"data-status="{{.Status}}"+ data-moved="{{if .AddressHistory}}1{{end}}"+ data-flagged="{{if .Risks}}1{{end}}"data-lastseen="{{.LastSeenUnix}}">- <td>+ <td data-label="Status"><span class="status-indicator {{.StatusClass}}"></span></td>- <td class="ip-cell">- <span class="copyable" onclick="copyToClipboard('{{.IP}}', event)" title="Click to copy">{{.IP}}</span>+ <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}}+ </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">+ {{if .Type}}<span class="type-badge">{{typeIcon .Type}}{{.Type}}</span>{{end}}+ {{if .WebUI}}<span class="web-indicator" data-tip="Serves a web interface"><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="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg></span>{{end}}+ {{if .Risks}}<span class="risk-indicator" data-tip="Security: {{range $i, $r := .Risks}}{{if $i}}; {{end}}{{$r}}{{end}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><path d="M12 9v4M12 17h.01"/></svg></span>{{end}}</td>- <td class="hostname-cell">{{if .Hostname}}{{.Hostname}}{{else}}<span style="color:var(--text-muted)">-</span>{{end}}</td>- <td class="mac-cell">- {{if .MAC}}<span class="copyable" onclick="copyToClipboard('{{.MAC}}', event)" title="Click to copy">{{.MAC}}</span>{{else}}<span style="color:var(--text-muted)">-</span>{{end}}+ <td class="mac-cell" data-label="MAC Address" data-copy="{{.MAC}}">+ {{if .MAC}}{{.MAC}}{{else}}<span style="color:var(--text-muted)">-</span>{{end}}</td>- <td class="vendor-cell" title="{{.Vendor}}">{{if .Vendor}}{{.Vendor}}{{else}}<span style="color:var(--text-muted)">Unknown</span>{{end}}</td>- <td class="label-cell">{{.Label}}{{if .Notes}}<span class="notes-indicator" title="{{.Notes}}"><svg class="icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/><path d="M8 13h8M8 17h5"/></svg></span>{{end}}</td>- <td>+ <td class="vendor-cell" data-label="Vendor" data-copy="{{.Vendor}}">{{if .Vendor}}{{.Vendor}}{{else}}<span style="color:var(--text-muted)">Unknown</span>{{end}}</td>+ <td class="label-cell" data-label="Label">{{.Label}}{{if .Notes}}<span class="notes-indicator" data-tip="{{.Notes}}"><svg class="icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/><path d="M8 13h8M8 17h5"/></svg></span>{{end}}</td>+ <td data-label="Group"><select class="group-select" data-ip="{{.IP}}" onchange="updateDeviceGroup(this)"><option value="">-</option><option value="Server" {{if eq .Group "Server"}}selected{{end}}>Server</option>@@ -223,10 +296,10 @@<option value="Pi" {{if eq .Group "Pi"}}selected{{end}}>Pi</option></select></td>- <td class="time-cell" data-relative-time="{{.LastSeenUnix}}">{{.TimeAgo}}</td>- <td class="actions-cell">- <button class="btn-icon" onclick="editDevice('{{.IP}}')" title="Edit"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></button>- <button class="btn-icon danger" onclick="deleteDevice('{{.IP}}')" title="Delete"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6v14a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6"/><path d="M10 11v6M14 11v6"/></svg></button>+ <td class="time-cell" data-label="Last Seen" data-relative-time="{{.LastSeenUnix}}">{{.TimeAgo}}</td>+ <td class="actions-cell" data-label="Actions">+ <button class="btn-icon" onclick="editDevice('{{.IP}}')" data-tip="Edit" aria-label="Edit"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></button>+ <button class="btn-icon danger" onclick="deleteDevice('{{.IP}}')" data-tip="Delete" aria-label="Delete"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6v14a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6"/><path d="M10 11v6M14 11v6"/></svg></button></td></tr>{{end}}@@ -237,14 +310,17 @@live view. State when that was, so "last seen" times areread in the right context. */}}<div class="table-footer">- {{if .LastScanAt}}- <span class="table-footer-label">Scanned- <span data-relative-time="{{.LastScanUnix}}">{{.LastScanAgo}}</span>+ <div class="status-legend" aria-label="What the status colours mean">+ <span class="legend-item"><span class="legend-dot online"></span>Online</span>+ <span class="legend-item"><span class="legend-dot seen"></span>Seen recently</span>+ <span class="legend-item"><span class="legend-dot offline"></span>Offline</span>+ </div>+ {{if or .ContinuousScan .LastScanAt}}+ <span class="table-footer-label">+ <span class="live-indicator"><span class="live-dot"></span>Live</span>{{if .LastScanAt}}<span class="live-sep">·</span><span class="scan-when">scanned <span data-relative-time="{{.LastScanUnix}}">{{.LastScanAgo}}</span> <span class="table-footer-detail">· {{.LastScanAt}}</span></span>{{end}}</span>- <span class="table-footer-detail">{{.LastScanAt}}</span>{{else}}- <span class="table-footer-label">Not scanned yet</span>- <span class="table-footer-detail">Run a scan to discover devices</span>+ <span class="table-footer-label">Not scanned yet · run a scan to discover devices</span>{{end}}</div></div>@@ -324,6 +400,11 @@<p style="margin-top:0.5rem;font-size:0.8rem;">Press <kbd class="kbd">/</kbd> to search • <kbd class="kbd">R</kbd> to refresh • <kbd class="kbd">T</kbd> to toggle theme</p></footer>- <script src="/static/app.js"></script>+ <button type="button" id="scroll-top" class="scroll-top" aria-label="Back to top">+ <svg class="scroll-top-chevron" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 15l8-8 8 8"/></svg>+ <img src="/static/orangutan.svg" alt="" class="scroll-top-logo" width="28" height="28">+ </button>++ <script src="/static/app.js?v={{.Version}}"></script></body></html>diff --git a/internal/web/templates/login.html b/internal/web/templates/login.htmlindex b121219..7874068 100644--- a/internal/web/templates/login.html+++ b/internal/web/templates/login.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en" data-theme="{{.Theme}}"><head>+ <script>(function(){try{var t=localStorage.getItem("theme");if(t)document.documentElement.setAttribute("data-theme",t);var a=localStorage.getItem("accent")||"blue";if(a!=="orange")document.documentElement.setAttribute("data-accent",a);}catch(e){}})();</script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Sign in - LAN Orangutan</title>diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.htmlindex e507eeb..a58930d 100644--- a/internal/web/templates/settings.html+++ b/internal/web/templates/settings.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en" data-theme="{{.Theme}}"><head>+ <script>(function(){try{var t=localStorage.getItem("theme");if(t)document.documentElement.setAttribute("data-theme",t);var a=localStorage.getItem("accent")||"blue";if(a!=="orange")document.documentElement.setAttribute("data-accent",a);}catch(e){}})();</script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Settings - LAN Orangutan</title>@@ -8,6 +9,52 @@<link rel="icon" type="image/svg+xml" href="/static/orangutan.svg"></head><body>+ <noscript>+ <div class="noscript-screen">+ <div class="noscript-card">+ <div class="noscript-head">+ <img src="/static/orangutan.svg" alt="LAN Orangutan" class="noscript-logo" width="60" height="60">+ <div>+ <h1>JavaScript is switched off</h1>+ <p class="noscript-sub">The web dashboard needs JavaScript to run. Here's what it offers, and how to use LAN Orangutan without it. Pick whichever you prefer.</p>+ </div>+ </div>++ <div class="noscript-cols">+ <section class="noscript-panel">+ <h2>The web dashboard</h2>+ <p>A live, visual view of your network. It uses JavaScript for:</p>+ <ul>+ <li>Live device updates as the server scans</li>+ <li>Running scans, and sorting, filtering, searching</li>+ <li>Editing labels and groups, and copying addresses</li>+ </ul>+ <p class="noscript-action">Allow JavaScript for this site (in your browser or script blocker), then reload.</p>+ </section>++ <section class="noscript-panel">+ <h2>Or the command line</h2>+ <p>Same discovery, no browser or JavaScript needed, straight from your terminal:</p>+ <pre class="noscript-cli"><code>orangutan scan all # scan your networks+orangutan list # list found devices+orangutan status # service & network status+orangutan export out.csv</code></pre>+ <p class="noscript-action-muted">Run <code>orangutan --help</code> to see everything.</p>+ </section>+ </div>++ <p class="noscript-safety"><strong>Is the dashboard safe?</strong> Yes. LAN Orangutan is self-hosted: its JavaScript runs entirely in your own browser against your own server, and makes no third-party or external calls. It is served from this machine at <code>/static/app.js</code>.</p>++ <footer class="noscript-footer">+ <img src="/static/orangutan.svg" alt="" class="noscript-footer-logo" width="22" height="22">+ <span class="noscript-footer-name">LAN Orangutan by 291 Group</span>+ <span class="noscript-footer-sep">•</span>+ <a href="https://github.com/291-Group/LAN-Orangutan" target="_blank" rel="noopener">github.com/291-Group/LAN-Orangutan</a>+ </footer>+ </div>+ </div>+ </noscript>+<header class="header"><a href="/" class="header-brand"><img src="/static/orangutan.svg" alt="" class="logo" width="32" height="32">@@ -114,6 +161,17 @@</label></div></div>+ <div class="form-group" style="margin-top: 1rem;">+ <label>Accent color</label>+ <div class="accent-swatches">+ <button type="button" class="accent-swatch" data-accent="orange" style="background:#e0842c" onclick="setAccent('orange')" title="Orange" aria-label="Orange accent"></button>+ <button type="button" class="accent-swatch" data-accent="gold" style="background:#d9a227" onclick="setAccent('gold')" title="Gold" aria-label="Gold accent"></button>+ <button type="button" class="accent-swatch" data-accent="blue" style="background:#2f7fd4" onclick="setAccent('blue')" title="Blue" aria-label="Blue accent"></button>+ <button type="button" class="accent-swatch" data-accent="green" style="background:#2c9e6b" onclick="setAccent('green')" title="Green" aria-label="Green accent"></button>+ <button type="button" class="accent-swatch" data-accent="purple" style="background:#8b6fc4" onclick="setAccent('purple')" title="Purple" aria-label="Purple accent"></button>+ </div>+ <p class="form-help">Applies across the app, in both light and dark.</p>+ </div></div></section>diff --git a/internal/web/templates/setup.html b/internal/web/templates/setup.htmlindex 7a7d455..847811b 100644--- a/internal/web/templates/setup.html+++ b/internal/web/templates/setup.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en" data-theme="{{.Theme}}"><head>+ <script>(function(){try{var t=localStorage.getItem("theme");if(t)document.documentElement.setAttribute("data-theme",t);var a=localStorage.getItem("accent")||"blue";if(a!=="orange")document.documentElement.setAttribute("data-accent",a);}catch(e){}})();</script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Welcome - LAN Orangutan</title>