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.4.2
filebay7dae83bdfcdb
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlnew file mode 100644index 0000000..a2653e3--- /dev/null+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -0,0 +1,62 @@+name: Bug report+description: Something is broken or behaving unexpectedly+labels: [bug]+body:+ - type: markdown+ attributes:+ value: |+ Thanks for the report. The three questions below answer most of what we would otherwise have to ask, so please fill them in.+ - type: input+ id: version+ attributes:+ label: Version+ description: Shown in the dashboard footer, or run `orangutan version`. For Docker, `docker exec <container> orangutan version`.+ placeholder: "3.4.2"+ validations:+ required: true+ - type: dropdown+ id: install+ attributes:+ label: How is it installed?+ options:+ - Binary download+ - Docker+ - Homebrew+ - Scoop+ - .deb / .rpm / .apk package+ - Built from source+ validations:+ required: true+ - type: input+ id: os+ attributes:+ label: Operating system+ description: Include the version. For Docker, the host OS.+ placeholder: "Windows 11, Ubuntu 24.04, macOS 15, Raspberry Pi OS"+ validations:+ required: true+ - type: dropdown+ id: access+ attributes:+ label: How do you open the dashboard?+ description: Some browser features behave differently over plain http from another machine, so this matters for anything in the web UI.+ options:+ - http on the same machine (localhost)+ - http from another machine on the network+ - https, through a reverse proxy+ - Not relevant, this is a command line problem+ validations:+ required: true+ - type: textarea+ id: what+ attributes:+ label: What happened?+ description: What you did, what you saw, and what you expected instead. Paste the exact error text if there is one.+ validations:+ required: true+ - type: textarea+ id: logs+ attributes:+ label: Output or logs+ description: The startup banner or the relevant part of `docker logs <container>` often shows the cause straight away. Pasted here it is formatted as code automatically.+ render: shelldiff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlnew file mode 100644index 0000000..8e9af35--- /dev/null+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -0,0 +1,5 @@+blank_issues_enabled: true+contact_links:+ - name: Security problem+ url: https://github.com/291-Group/LAN-Orangutan/security/advisories/new+ about: Please report security issues privately here, not as a public issue.diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.ymlnew file mode 100644index 0000000..706d0f5--- /dev/null+++ b/.github/ISSUE_TEMPLATE/feature_request.yml@@ -0,0 +1,27 @@+name: Feature request+description: An idea for something LAN Orangutan should do+labels: [enhancement]+body:+ - type: markdown+ attributes:+ value: |+ Ideas are welcome. One thing to know first: LAN Orangutan is meant to be the simplest and fastest scanner to reach for, so anything that adds setup or complexity for the user is a hard sell. If your idea fits that, say so. If it does not, we would still rather hear it.+ - type: textarea+ id: problem+ attributes:+ label: What are you trying to do?+ description: The situation, not the solution. What is awkward or missing today?+ validations:+ required: true+ - type: textarea+ id: idea+ attributes:+ label: What would you like to see?+ description: How you imagine it working. Rough is fine.+ validations:+ required: true+ - type: textarea+ id: alternatives+ attributes:+ label: What do you do instead today?+ description: Workarounds, other tools, or nothing.diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdnew file mode 100644index 0000000..921e429--- /dev/null+++ b/.github/pull_request_template.md@@ -0,0 +1,13 @@+## What this changes++<!-- One or two sentences. Link the issue it relates to, if there is one. -->++## Why++<!-- The problem it solves. If this adds a setting, a step, or a dependency, say why it is worth it: keeping LAN Orangutan simple is the whole point. -->++## Checks++- [ ] `go build ./...`, `go vet ./...` and `go test -race ./...` are clean+- [ ] One change per pull request+- [ ] Docs updated if behaviour changeddiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 57eed90..7700ee9 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -649,5 +649,87 @@ jobs:dist/SHA256SUMS.txtgenerate_release_notes: truedraft: false+ # A tag with a hyphen (v3.4.2-beta.1) is a pre-release. Without this+ # it would publish as a normal release and GitHub would mark it+ # "Latest" on the repository front page, above the real one. Evaluates+ # to false for an ordinary tag, so release behaviour is unchanged.+ prerelease: ${{ contains(github.event.inputs.tag || github.ref_name, '-') }}env:GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}++ # Publish the Homebrew formula and Scoop manifest into the org's shared+ # tap and bucket, so `brew install 291-group/tap/lan-orangutan` and+ # `scoop install lan-orangutan` pick up this release. Both repositories+ # are shared with LAN Sheriff. Each product owns one file by name+ # (Sheriff a cask, this a formula), so the only thing that can collide is+ # the push itself, which is handled below.+ #+ # Deliberately after the release exists: the formula and manifest point at+ # this release's download URLs, which must resolve before anyone installs.+ # Deliberately unable to block the release: with no TAP_TOKEN secret the+ # step says so and stops, and a failure here leaves the release already+ # published, so the fix is to re-run this job, not to re-release.+ - name: Publish to Homebrew tap and Scoop bucket+ env:+ TAP_TOKEN: ${{ secrets.TAP_TOKEN }}+ TAG: ${{ github.event.inputs.tag || github.ref_name }}+ run: |+ set -euo pipefail+ VERSION=${{ steps.version.outputs.VERSION }}++ if [ -z "${TAP_TOKEN:-}" ]; then+ echo "TAP_TOKEN secret is not set; skipping the tap and bucket update."+ echo "Add it under Settings > Secrets and variables > Actions to enable this step."+ exit 0+ fi++ # A pre-release tag (v3.4.2-beta.1) must not reach the channels people+ # install from. Report what would change and stop short of committing.+ case "$TAG" in+ *-*) PUBLIC=false ;;+ *) PUBLIC=true ;;+ esac++ git config --global user.name "291 Group release"+ git config --global user.email "[email protected]"++ publish() { # repo, source file, destination path+ local repo=$1 src=$2 dst=$3+ local dir="$RUNNER_TEMP/$repo"+ # The clone is the real test of the token: wrong scope, wrong+ # repository or an expired token all fail here, plainly.+ git clone --depth 1 "https://x-access-token:${TAP_TOKEN}@github.com/291-Group/${repo}.git" "$dir"+ mkdir -p "$dir/$(dirname "$dst")"+ cp "$src" "$dir/$dst"+ ( cd "$dir"+ git add "$dst"+ if git diff --cached --quiet; then+ echo " $repo already has $VERSION"+ return+ fi+ if [ "$PUBLIC" != "true" ]; then+ echo " $repo would be updated to $VERSION; not committing, this is a pre-release"+ git --no-pager diff --cached --stat | sed 's/^/ /'+ return+ fi+ git commit -m "lan-orangutan $VERSION"+ # These repositories are shared, so the push can lose a race: if+ # the other product commits between our clone and our push, the+ # push is rejected as non-fast-forward. Our change is a single+ # file nobody else touches, so a rebase is never a merge decision.+ pushed=0+ for attempt in 1 2 3; do+ if git push; then pushed=1; break; fi+ echo " $repo: push rejected on attempt $attempt, rebasing onto what landed first"+ git pull --rebase --quiet || true+ done+ if [ "$pushed" -ne 1 ]; then+ echo "::error::$repo: could not push after three attempts"+ exit 1+ fi+ echo " $repo updated to $VERSION"+ )+ }++ publish homebrew-tap dist/lan-orangutan.rb Formula/lan-orangutan.rb+ publish scoop-bucket dist/lan-orangutan.json bucket/lan-orangutan.jsondiff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.mdnew file mode 100644index 0000000..e4de268--- /dev/null+++ b/CODE_OF_CONDUCT.md@@ -0,0 +1,54 @@+# Code of Conduct++## Our Pledge++We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.++We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.++## Our Standards++Examples of behavior that contributes to a positive environment for our community include:++- Demonstrating empathy and kindness toward other people+- Being respectful of differing opinions, viewpoints, and experiences+- Giving and gracefully accepting constructive feedback+- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience+- Focusing on what is best not just for us as individuals, but for the overall community++Examples of unacceptable behavior include:++- The use of sexualized language or imagery, and sexual attention or advances of any kind+- Trolling, insulting or derogatory comments, and personal or political attacks+- Public or private harassment+- Publishing others' private information, such as a physical or email address, without their explicit permission+- Other conduct which could reasonably be considered inappropriate in a professional setting++## Enforcement Responsibilities++Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.++Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.++## Scope++This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces.++## Enforcement++Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [email protected]. All complaints will be reviewed and investigated promptly and fairly.++All community leaders are obligated to respect the privacy and security of the reporter of any incident.++## Enforcement Guidelines++Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:++1. **Correction.** A private, written warning, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.+2. **Warning.** A warning with consequences for continued behavior. No interaction with the people involved for a specified period of time. Violating these terms may lead to a temporary or permanent ban.+3. **Temporary Ban.** A temporary ban from any sort of interaction or public communication with the community for a specified period of time.+4. **Permanent Ban.** A permanent ban from any sort of public interaction within the community.++## Attribution++This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1, available at https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..7d281c8--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,31 @@+# Contributing++Thanks for wanting to help. LAN Orangutan is a small project with a clear idea of what it is, so this page is short.++## The one rule++LAN Orangutan is meant to be the simplest and fastest scanner to reach for. One binary, almost no configuration, running in seconds. Every change is judged against that first. If something adds setup, options, or steps for the user, it is probably not a fit, however good the idea. We would still rather hear it than not.++## Bugs++Open an issue using the bug report form. It asks for the version, your OS, and how you installed it, because those answer most questions before we have to ask them. If you can, include the exact error text and what you expected to happen instead.++## Ideas++Open an issue using the feature request form before writing code. That way we can talk about whether it fits, and how, before you spend an evening on it.++## Pull requests++- Open an issue first for anything beyond a small fix, so the direction is agreed.+- Keep a pull request to one change. Small and focused is much easier to review and much more likely to merge.+- Match the surrounding code. Comments explain why, not what.+- Run `go build ./...`, `go vet ./...` and `go test -race ./...` before you push. All three must be clean.+- Do not add dependencies without saying why in the pull request.++## Security++Please do not open a public issue for a security problem. See [SECURITY.md](SECURITY.md) for how to report one privately.++## Code of conduct++Be decent to each other. The full version is in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).diff --git a/README.md b/README.mdindex d8d1caf..c918df5 100644--- a/README.md+++ b/README.md@@ -23,11 +23,18 @@ By [291 Group](https://291group.com)<img src="docs/LO2.png" width="48%" /></p>+## Why the name+"Orangutan" is Malay for "person of the forest" [orang, person; hutan, forest]. LAN Orangutan is the person of your network. It sits quietly in your spanning tree, watches everything that moves, remembers every device it has ever met, tells you what is on your network and what has changed, and bothers no one. Orangutans are also the most solitary of the great apes: no troop, no cloud, no phoning home.+## Features- Auto-discover devices using nmap<br>- Password protected, with a password you set the first time you open it<br>-- Label, group, and add notes to devices<br>+- Label, group, and add notes to devices, with your own group names<br>+- Save a snapshot of your network and compare it later to see what changed<br>+- Mark the devices you expect, and get told when something new appears or something goes missing<br>+- Back up and restore everything, or export a shareable HTML report of your network<br>+- Change scanning and network settings from the Settings page, no config file needed<br>- Multi-network support<br>- Tailscale integration - connect, disconnect, and discover tailnet peers from inside the app<br>- Live scan progress you can cancel<br>@@ -42,6 +49,19 @@ By [291 Group](https://291group.com)Grab the latest release of LAN Orangutan for your platform from [GitHub Releases](https://github.com/291-Group/LAN-Orangutan/releases).+### Package managers++```bash+# macOS (Homebrew)+brew install 291-group/tap/lan-orangutan++# Windows (Scoop)+scoop bucket add 291group https://github.com/291-Group/scoop-bucket+scoop install lan-orangutan+```++Both channels update on every release. Linux packages (`.deb`, `.rpm`, `.apk`) are on the [Releases](https://github.com/291-Group/LAN-Orangutan/releases) page.+### DockerPull the image from Docker Hub:@@ -204,7 +224,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. 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.+**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, including a password you created earlier through the setup page, 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.@@ -269,10 +289,25 @@ There are already excellent, deeply capable tools in this space, and they're theIf you don't need the extra features, and the extra friction that comes with them, then this is for you. We'll keep pushing back on anything that makes it harder to use or deploy, because staying simple and fast is the whole reason it exists.-## Feedback & Contributing-Found a bug, hit a problem, or have an idea? Open an [issue](https://github.com/291-Group/LAN-Orangutan/issues) and let us know.+## No manual+There is no manual for LAN Orangutan, and there isn't going to be one. This README is the whole of it.++That's a rule we hold ourselves to, not a gap we haven't got around to. If you need a manual to use something, it has already failed at being simple. So when a feature turns out to need explaining, we treat that as a bug in the feature, and we change the tool rather than write the explanation.++Please hold us to that. If you had to stop and work something out, or you found something by accident that the tool should have shown you, open an issue and say so. That isn't a complaint, it's the report we want most, because it points at the exact spot where the tool wasn't obvious enough. Hold each other to it too: if you're helping someone in an issue and find yourself writing a paragraph of instructions, that paragraph is a bug report.++## Contributing+LAN Orangutan was built by 291 Group, but it belongs to the community, and it always will. Nothing would make us prouder than to see the people who use it make it better.++This is the people's tool, and the people's tool has to work for any skill level. Advanced users know what they need and have serious tools that meet it; when that's you, we'll happily point you to them. LAN Orangutan isn't trying to win on feature count or go head to head with those. It wins on getting the job done faster, and sometimes the first hour is the one that matters. It's also for everyone who doesn't have the time, or the background, for a complicated setup. This tool shouldn't make anyone contend with technology. It should make technology help them out.++So if you can make it better, please do. Found a bug, hit a problem, or have an idea? Open an [issue](https://github.com/291-Group/LAN-Orangutan/issues). Want to change something yourself? [CONTRIBUTING.md](CONTRIBUTING.md) has the short version of how. Feature requests are welcome, with one caveat that follows from everything above: if something would add real complexity or setup for the user, it's probably not a fit. We'd still rather hear the idea, so don't hold back.++## Thanks++LAN Orangutan is shaped by the people who use it. Nearly everything in recent releases started as somebody opening an issue or a discussion, and several of them went back and forth with us until the fix was right.-Feature requests are welcome too, with one caveat that follows from the philosophy above: if something would add real complexity or setup, it's probably not a fit for LAN Orangutan. But we'd still rather hear the idea, so don't hold back.+Thank you to [@Bluesguy1984](https://github.com/Bluesguy1984), [@chraso](https://github.com/chraso), [@dax29](https://github.com/dax29), [@dbm26](https://github.com/dbm26), [@dcchillin46](https://github.com/dcchillin46), [@devra1](https://github.com/devra1), [@Extra-Citron-7630](https://github.com/Extra-Citron-7630), [@forke24x7](https://github.com/forke24x7), [@GrafDogi](https://github.com/GrafDogi), [@Louai199](https://github.com/Louai199), [@luciancelmare](https://github.com/luciancelmare), [@msanaullahsahar](https://github.com/msanaullahsahar), [@technoplayer](https://github.com/technoplayer), [@tolga-balci](https://github.com/tolga-balci), [@wmgordon3](https://github.com/wmgordon3) and [@y90ziv](https://github.com/y90ziv).## Licensediff --git a/docs/DOCKERHUB.md b/docs/DOCKERHUB.mdindex f91c42a..1fdb9d4 100644--- a/docs/DOCKERHUB.md+++ b/docs/DOCKERHUB.md@@ -136,7 +136,7 @@ If Tailscale is connected, its online peers are added to your device list alongs- **First run** presents a "create a password" screen. Until you finish it, every page and every API endpoint is refused. The password is stored as a bcrypt hash in a file readable only by its owner, separately from your config.- **Sign-in** lasts a week by default. Five wrong guesses lock that address out for fifteen minutes.- **Set the password in advance** with `ORANGUTAN_PASSWORD`, or keep it out of the environment with `ORANGUTAN_PASSWORD_FILE=/run/secrets/orangutan`.-- **Turn auth off** with `ORANGUTAN_ALLOW_INSECURE=true` only when access control genuinely lives elsewhere, such as a reverse proxy that handles login.+- **Turn auth off** with `ORANGUTAN_ALLOW_INSECURE=true` only when access control genuinely lives elsewhere, such as a reverse proxy that handles login. This also overrides a password created earlier through the setup page, which is stored in the data volume.- **No built-in HTTPS.** Put LAN Orangutan behind a reverse proxy, or reach it over Tailscale, if you need the connection encrypted.Full details, known limitations, and how to report a vulnerability: [SECURITY.md](https://github.com/291-Group/LAN-Orangutan/blob/main/SECURITY.md).diff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex 4952262..39ab477 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -17,6 +17,14 @@ sudo ./orangutan serve### macOS+With Homebrew:++```bash+brew install 291-group/tap/lan-orangutan+```++Or by hand:+```bash# Download and extractcurl -LO https://github.com/291-Group/LAN-Orangutan/releases/latest/download/orangutan-darwin-arm64.tar.gz@@ -28,6 +36,15 @@ sudo ./orangutan serve### Windows+With Scoop:++```powershell+scoop bucket add 291group https://github.com/291-Group/scoop-bucket+scoop install lan-orangutan+```++Or by hand:+Download `orangutan-windows-amd64.zip` from [GitHub Releases](https://github.com/291-Group/LAN-Orangutan/releases), extract, and run as Administrator.## Requirementsdiff --git a/internal/api/api.go b/internal/api/api.goindex da041cf..0a469f0 100644--- a/internal/api/api.go+++ b/internal/api/api.go@@ -96,6 +96,8 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {h.handleMarkAllExpected(w, r)case path == "networks":h.handleNetworks(w, r)+ case path == "groups":+ h.handleGroups(w, r)case path == "scan":h.handleScan(w, r)case path == "scan/start":@@ -629,14 +631,22 @@ func (h *Handler) handleScanInterval(w http.ResponseWriter, r *http.Request) {"default": h.cfg.Scanning.ScanInterval,})case http.MethodPost:+ // A pointer, so a body that omits "seconds" (or misspells it) is rejected+ // rather than decoding to 0 and being clamped up to the floor. Silently+ // turning a malformed request into a 10-second scan loop is the wrong+ // kind of forgiving. Matches how the storage limits are handled below.var body struct {- Seconds int `json:"seconds"`+ Seconds *int `json:"seconds"`}if err := json.NewDecoder(r.Body).Decode(&body); err != nil {h.error(w, http.StatusBadRequest, "invalid request body")return}- secs := clampInt(body.Seconds, minScanIntervalSeconds, maxScanIntervalSeconds)+ if body.Seconds == nil {+ h.error(w, http.StatusBadRequest, "seconds is required")+ return+ }+ secs := clampInt(*body.Seconds, minScanIntervalSeconds, maxScanIntervalSeconds)if err := h.store.SetScanInterval(secs); err != nil {h.error(w, http.StatusInternalServerError, "could not save setting: "+err.Error())return@@ -727,6 +737,69 @@ func (h *Handler) networkSettingsView() map[string]interface{} {}}+// handleGroups handles GET/POST /api/groups, the device-group list shown in the+// dashboard dropdowns and the Settings page.+//+// Groups were a fixed list baked into the template even though storage has+// always accepted any value, so a user could not name a group after their own+// kit. The list now lives in the scan state (nil = the built-in defaults) and is+// edited here. A rename rewrites the group on every device that used it and a+// delete clears it, so the list and the devices stay consistent.+func (h *Handler) handleGroups(w http.ResponseWriter, r *http.Request) {+ switch r.Method {+ case http.MethodGet:+ h.success(w, h.groupsView())++ case http.MethodPost:+ var body struct {+ Action string `json:"action"`+ Name string `json:"name"`+ NewName string `json:"new_name"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ h.error(w, http.StatusBadRequest, "invalid request body")+ return+ }++ var err error+ switch body.Action {+ case "add":+ err = h.store.AddGroup(body.Name)+ case "rename":+ err = h.store.RenameGroup(body.Name, body.NewName)+ case "delete":+ err = h.store.DeleteGroup(body.Name)+ case "reset":+ err = h.store.SetGroups(nil)+ default:+ h.error(w, http.StatusBadRequest, "action must be one of: add, rename, delete, reset")+ return+ }+ if err != nil {+ // These are all user-input problems (empty name, duplicate, unknown+ // group), so they are a 400 rather than a server error.+ h.error(w, http.StatusBadRequest, err.Error())+ return+ }+ h.success(w, h.groupsView())++ default:+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")+ }+}++// groupsView returns the effective group list, whether it has been customised,+// and how many devices carry each group so the UI can warn before a destructive+// edit.+func (h *Handler) groupsView() map[string]interface{} {+ return map[string]interface{}{+ "groups": nonNil(h.store.GetGroups()),+ "defaults": storage.DefaultGroups(),+ "customised": h.store.GroupsCustomised(),+ "counts": h.store.GroupCounts(),+ }+}+// validateCIDRs checks each entry parses as a CIDR, returning them trimmed and// de-duplicated, or an error naming the first bad one. Blank entries are dropped.func validateCIDRs(list []string) ([]string, error) {diff --git a/internal/cli/config.go b/internal/cli/config.goindex 0d772ea..6444aac 100644--- a/internal/cli/config.go+++ b/internal/cli/config.go@@ -2,10 +2,12 @@ package cliimport ("fmt"+ "strings""github.com/spf13/cobra""github.com/291-Group/LAN-Orangutan/internal/auth"+ "github.com/291-Group/LAN-Orangutan/internal/storage")var configCmd = &cobra.Command{@@ -15,8 +17,19 @@ var configCmd = &cobra.Command{}func runConfig(cmd *cobra.Command, args []string) error {+ // Settings changed from the Settings page are saved as overrides in the data+ // directory, not written back to the config file, so the file alone no longer+ // says what the app will actually do. Resolve through storage when it opens so+ // this command reports the EFFECTIVE value and marks where it came from.+ // Degrade gracefully: with no readable data directory the config file is still+ // the whole truth, which is exactly what we then print.+ store, _ := storage.New(cfg.DevicesFile(), cfg.StateFile())+fmt.Println("=== LAN Orangutan Configuration ===")fmt.Printf("Config file: %s\n", cfgFile)+ if store != nil {+ fmt.Printf("Overrides: %s\n", cfg.StateFile())+ }fmt.Println()fmt.Println("[server]")@@ -31,15 +44,21 @@ func runConfig(cmd *cobra.Command, args []string) error {fmt.Println()fmt.Println("[scanning]")- fmt.Printf(" scan_interval = %d\n", cfg.Scanning.ScanInterval)+ fmt.Printf(" continuous_scan = %v%s\n", effBool(store, cfg.Scanning.ContinuousScan, storeContinuous), mark(store, cfg.Scanning.ContinuousScan, storeContinuous))+ fmt.Printf(" scan_interval = %d%s\n", effInt(store, cfg.Scanning.ScanInterval, storeInterval), markInt(store, cfg.Scanning.ScanInterval, storeInterval))fmt.Printf(" min_scan_interval = %d\n", cfg.Scanning.MinScanInterval)- fmt.Printf(" enable_port_scan = %v\n", cfg.Scanning.EnablePortScan)- fmt.Printf(" port_scan_range = %s\n", cfg.Scanning.PortScanRange)+ fmt.Printf(" enable_service_detection = %v%s\n", effBool(store, cfg.Scanning.EnableServiceDetection, storeServiceDetection), mark(store, cfg.Scanning.EnableServiceDetection, storeServiceDetection))+ fmt.Printf(" networks = %s%s\n", listOrNone(effList(store, cfg.Scanning.Networks, storeNetworks)), markList(store, cfg.Scanning.Networks, storeNetworks))+ fmt.Printf(" exclude_networks = %s%s\n", listOrNone(effList(store, cfg.Scanning.ExcludeNetworks, storeExclude)), markList(store, cfg.Scanning.ExcludeNetworks, storeExclude))+ fmt.Printf(" only_configured_networks = %v%s\n", effBool(store, cfg.Scanning.OnlyConfiguredNetworks, storeOnlyConfigured), mark(store, cfg.Scanning.OnlyConfiguredNetworks, storeOnlyConfigured))+ // Reserved keys: parsed and preserved, but nothing consumes them yet.+ fmt.Printf(" enable_port_scan = %v (reserved, not wired up yet)\n", cfg.Scanning.EnablePortScan)+ fmt.Printf(" port_scan_range = %s (reserved, not wired up yet)\n", cfg.Scanning.PortScanRange)fmt.Println()fmt.Println("[storage]")- fmt.Printf(" max_devices = %d\n", cfg.Storage.MaxDevices)- fmt.Printf(" retention_days = %d\n", cfg.Storage.RetentionDays)+ fmt.Printf(" max_devices = %d%s\n", effInt(store, cfg.Storage.MaxDevices, storeMaxDevices), markInt(store, cfg.Storage.MaxDevices, storeMaxDevices))+ fmt.Printf(" retention_days = %d%s\n", effInt(store, cfg.Storage.RetentionDays, storeRetention), markInt(store, cfg.Storage.RetentionDays, storeRetention))fmt.Printf(" data_dir = %s\n", cfg.Storage.DataDir)fmt.Println()@@ -67,3 +86,71 @@ func passwordSummary() string {}return "(not set - not required with this bind address)"}++// Resolving an effective value needs the config default and the matching storage+// resolver. These small adapters name each pairing once so the printing above+// stays readable, and so a nil store (unreadable data directory) simply falls+// back to the config value.++func storeContinuous(s *storage.Storage, d bool) bool { return s.ContinuousScanEnabled(d) }+func storeServiceDetection(s *storage.Storage, d bool) bool { return s.ServiceDetectionEnabled(d) }+func storeOnlyConfigured(s *storage.Storage, d bool) bool { return s.OnlyConfiguredOrDefault(d) }+func storeInterval(s *storage.Storage, d int) int { return s.ScanIntervalOrDefault(d) }+func storeMaxDevices(s *storage.Storage, d int) int { return s.MaxDevicesOrDefault(d) }+func storeRetention(s *storage.Storage, d int) int { return s.RetentionDaysOrDefault(d) }+func storeNetworks(s *storage.Storage, d []string) []string { return s.NetworksOrDefault(d) }+func storeExclude(s *storage.Storage, d []string) []string { return s.ExcludeNetworksOrDefault(d) }++func effBool(s *storage.Storage, def bool, f func(*storage.Storage, bool) bool) bool {+ if s == nil {+ return def+ }+ return f(s, def)+}++func effInt(s *storage.Storage, def int, f func(*storage.Storage, int) int) int {+ if s == nil {+ return def+ }+ return f(s, def)+}++func effList(s *storage.Storage, def []string, f func(*storage.Storage, []string) []string) []string {+ if s == nil {+ return def+ }+ return f(s, def)+}++// mark* append a note when the effective value differs from the config file, so+// it is obvious that the Settings page, not the file, is deciding this one.+const overridden = " <- set in Settings"++func mark(s *storage.Storage, def bool, f func(*storage.Storage, bool) bool) string {+ if s != nil && f(s, def) != def {+ return overridden+ }+ return ""+}++func markInt(s *storage.Storage, def int, f func(*storage.Storage, int) int) string {+ if s != nil && f(s, def) != def {+ return overridden+ }+ return ""+}++func markList(s *storage.Storage, def []string, f func(*storage.Storage, []string) []string) string {+ if s != nil && strings.Join(f(s, def), ",") != strings.Join(def, ",") {+ return overridden+ }+ return ""+}++// listOrNone renders an empty list as something readable rather than a blank.+func listOrNone(v []string) string {+ if len(v) == 0 {+ return "(none)"+ }+ return strings.Join(v, ", ")+}diff --git a/internal/cli/config_test.go b/internal/cli/config_test.gonew file mode 100644index 0000000..c85e132--- /dev/null+++ b/internal/cli/config_test.go@@ -0,0 +1,74 @@+package cli++import (+ "path/filepath"+ "testing"++ "github.com/291-Group/LAN-Orangutan/internal/storage"+)++// `orangutan config` has to keep working when the data directory cannot be read,+// because the config file is still worth printing. In that case every value falls+// back to the config default and nothing is marked as overridden.+func TestEffectiveValuesFallBackWhenStoreIsNil(t *testing.T) {+ if got := effBool(nil, true, storeContinuous); !got {+ t.Error("effBool with no store should return the config default")+ }+ if got := effInt(nil, 300, storeInterval); got != 300 {+ t.Errorf("effInt with no store = %d, want the config default 300", got)+ }+ if got := effList(nil, []string{"10.0.0.0/24"}, storeNetworks); len(got) != 1 {+ t.Errorf("effList with no store = %v, want the config default", got)+ }+ if mark(nil, true, storeContinuous) != "" || markInt(nil, 300, storeInterval) != "" ||+ markList(nil, nil, storeNetworks) != "" {+ t.Error("nothing should be marked as overridden when there is no store")+ }+}++// With a store and no override saved, the config value wins and is not marked.+func TestNoOverrideMeansConfigValueAndNoMark(t *testing.T) {+ s := newConfigTestStore(t)++ if got := effInt(s, 300, storeInterval); got != 300 {+ t.Errorf("effInt = %d, want 300 from config", got)+ }+ if markInt(s, 300, storeInterval) != "" {+ t.Error("an unset override should not be marked")+ }+}++// The case this was written for: a value changed from the Settings page must be+// reported by `orangutan config`, and flagged as coming from there.+func TestOverrideIsReportedAndMarked(t *testing.T) {+ s := newConfigTestStore(t)+ if err := s.SetScanInterval(90); err != nil {+ t.Fatalf("SetScanInterval: %v", err)+ }++ if got := effInt(s, 300, storeInterval); got != 90 {+ t.Errorf("effInt = %d, want the override 90, not the config default", got)+ }+ if markInt(s, 300, storeInterval) == "" {+ t.Error("an override should be marked so its source is obvious")+ }+}++func TestListRendersEmptyReadably(t *testing.T) {+ if got := listOrNone(nil); got != "(none)" {+ t.Errorf("listOrNone(nil) = %q, want \"(none)\"", got)+ }+ if got := listOrNone([]string{"a", "b"}); got != "a, b" {+ t.Errorf("listOrNone = %q, want \"a, b\"", got)+ }+}++func newConfigTestStore(t *testing.T) *storage.Storage {+ t.Helper()+ dir := t.TempDir()+ s, err := storage.New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))+ if err != nil {+ t.Fatalf("storage.New: %v", err)+ }+ return s+}diff --git a/internal/cli/serve.go b/internal/cli/serve.goindex 6631410..f60cffa 100644--- a/internal/cli/serve.go+++ b/internal/cli/serve.go@@ -17,6 +17,7 @@ import ("github.com/291-Group/LAN-Orangutan/internal/api""github.com/291-Group/LAN-Orangutan/internal/auth"+ "github.com/291-Group/LAN-Orangutan/internal/config""github.com/291-Group/LAN-Orangutan/internal/network""github.com/291-Group/LAN-Orangutan/internal/storage""github.com/291-Group/LAN-Orangutan/internal/web"@@ -84,13 +85,8 @@ func runServe(cmd *cobra.Command, args []string) error {return fmt.Errorf("failed to apply storage limits: %w", err)}- // A password from the config file or environment wins. Otherwise fall back- // to one created earlier through the setup page.- password := cfg.Server.Password- if password == "" {- password = auth.LoadHash(cfg.PasswordFile())- cfg.Server.Password = password- }+ password, ignoredPassword := authPassword(cfg)+ cfg.Server.Password = passwordauthn, err := auth.New(password, cfg.SessionTTL())if err != nil {@@ -208,6 +204,11 @@ func runServe(cmd *cobra.Command, args []string) error {}switch {+ case cfg.Server.AllowInsecure:+ fmt.Println("Password: OFF (allow_insecure is set: anyone who can reach this address has full access)")+ if ignoredPassword != "" {+ fmt.Printf(" %s is being ignored because allow_insecure is set\n", ignoredPassword)+ }case authn.NeedsSetup():fmt.Println("Password: not set yet, open the page above to create one")case authn.Enabled():@@ -351,3 +352,30 @@ func listenAddresses(bind string, port int) []string {}return out}++// authPassword decides which password, if any, protects this instance, and+// names anything it deliberately ignored so the startup banner can say so.+//+// A password from the config file or environment wins over one created through+// the setup page, which lives in the data dir. allow_insecure means what the+// docs say, no password protection at all, so it wins over both. It has to: the+// setup-page password is easy to forget you ever created, and a user who set one+// on first visit and later opted out (a container behind a reverse proxy, say)+// otherwise found the flag did nothing. Setup was skipped, but the old hash still+// gated every page and sent them to the login screen. That was GitHub #45.+func authPassword(cfg *config.Config) (password, ignored string) {+ stored := auth.LoadHash(cfg.PasswordFile())+ if cfg.Server.AllowInsecure {+ switch {+ case cfg.Server.Password != "":+ return "", "The configured password"+ case stored != "":+ return "", "The password created through the setup page"+ }+ return "", ""+ }+ if cfg.Server.Password != "" {+ return cfg.Server.Password, ""+ }+ return stored, ""+}diff --git a/internal/cli/serve_test.go b/internal/cli/serve_test.goindex 7b0a546..f0050d8 100644--- a/internal/cli/serve_test.go+++ b/internal/cli/serve_test.go@@ -4,6 +4,9 @@ import ("net/http""net/http/httptest""testing"++ "github.com/291-Group/LAN-Orangutan/internal/auth"+ "github.com/291-Group/LAN-Orangutan/internal/config")func TestHostIsLoopback(t *testing.T) {@@ -82,3 +85,86 @@ func TestGuardHost_NetworkBindIsPassthrough(t *testing.T) {t.Fatalf("network bind should pass any Host: reached=%v code=%d", reached, w.Code)}}++// authPassword is the one place that decides whether a password gates the+// dashboard, so these pin down the precedence, and in particular that+// allow_insecure wins over a password stored by the setup page (GitHub #45).++func authTestConfig(t *testing.T) *config.Config {+ t.Helper()+ cfg := config.Default()+ cfg.Storage.DataDir = t.TempDir()+ return cfg+}++func storeSetupPassword(t *testing.T, cfg *config.Config) {+ t.Helper()+ // A real bcrypt hash of "correct horse", so LoadHash accepts it.+ const hash = "$2a$10$7EqJtq98hPqEX7fNZaFWoOa5aL1ScuGUHyvFuVvYQWD/2lmGhDHPa"+ if err := auth.SaveHash(cfg.PasswordFile(), hash); err != nil {+ t.Fatalf("SaveHash: %v", err)+ }+}++func TestAuthPasswordFallsBackToSetupPagePassword(t *testing.T) {+ cfg := authTestConfig(t)+ storeSetupPassword(t, cfg)++ got, ignored := authPassword(cfg)+ if got == "" {+ t.Fatal("with no configured password, the stored setup-page password should be used")+ }+ if ignored != "" {+ t.Errorf("nothing should be reported as ignored, got %q", ignored)+ }+}++func TestAuthPasswordConfiguredWinsOverStored(t *testing.T) {+ cfg := authTestConfig(t)+ storeSetupPassword(t, cfg)+ cfg.Server.Password = "from-config"++ got, _ := authPassword(cfg)+ if got != "from-config" {+ t.Fatalf("configured password should win over the stored one, got %q", got)+ }+}++// The #45 case: a password was created on first visit, then allow_insecure was+// set. The stored hash must not gate the dashboard any more.+func TestAllowInsecureIgnoresSetupPagePassword(t *testing.T) {+ cfg := authTestConfig(t)+ storeSetupPassword(t, cfg)+ cfg.Server.AllowInsecure = true++ got, ignored := authPassword(cfg)+ if got != "" {+ t.Fatalf("allow_insecure must disable the stored password, got %q", got)+ }+ if ignored == "" {+ t.Error("the banner should be told a stored password was ignored")+ }+}++func TestAllowInsecureIgnoresConfiguredPassword(t *testing.T) {+ cfg := authTestConfig(t)+ cfg.Server.Password = "from-config"+ cfg.Server.AllowInsecure = true++ got, ignored := authPassword(cfg)+ if got != "" {+ t.Fatalf("allow_insecure must disable the configured password, got %q", got)+ }+ if ignored == "" {+ t.Error("the banner should be told a configured password was ignored")+ }+}++func TestAllowInsecureWithNoPasswordReportsNothingIgnored(t *testing.T) {+ cfg := authTestConfig(t)+ cfg.Server.AllowInsecure = true++ if got, ignored := authPassword(cfg); got != "" || ignored != "" {+ t.Fatalf("got password %q, ignored %q; want both empty", got, ignored)+ }+}diff --git a/internal/cli/status.go b/internal/cli/status.goindex a32c2a2..09fba52 100644--- a/internal/cli/status.go+++ b/internal/cli/status.go@@ -10,6 +10,7 @@ import ("github.com/spf13/cobra""github.com/291-Group/LAN-Orangutan/internal/network"+ "github.com/291-Group/LAN-Orangutan/internal/scanner""github.com/291-Group/LAN-Orangutan/internal/storage")@@ -32,7 +33,11 @@ func runStatus(cmd *cobra.Command, args []string) error {fmt.Println()fmt.Println("Tools:")checkTool("nmap")- checkTool("arp-scan")+ // arp-scan has no Windows build, so listing it there only ever reports a+ // tool the user cannot install as missing.+ if scanner.ArpScanAvailable() {+ checkTool("arp-scan")+ }checkTool("tailscale")// Storage@@ -101,7 +106,7 @@ func runStatus(cmd *cobra.Command, args []string) error {}func checkTool(name string) {- path, err := exec.LookPath(name)+ path, err := toolPath(name)if err != nil {fmt.Printf(" %s: not found\n", name)} else {@@ -115,11 +120,27 @@ func checkTool(name string) {}}+// toolPath resolves a tool the same way the scanner does, so `status` and a+// real scan never disagree about whether nmap is present. For nmap that means+// checking the standard install locations as well as PATH.+func toolPath(name string) (string, error) {+ if name == "nmap" {+ return scanner.NmapPath()+ }+ return exec.LookPath(name)+}+func getToolVersion(name string) string {var cmd *exec.Cmdswitch name {case "nmap":- cmd = exec.Command("nmap", "--version")+ // Resolved path, not the bare name: this has to work in the same case+ // NmapPath exists for, where nmap is installed but not yet on PATH.+ bin, err := scanner.NmapPath()+ if err != nil {+ return ""+ }+ cmd = exec.Command(bin, "--version")case "arp-scan":cmd = exec.Command("arp-scan", "--version")case "tailscale":diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.goindex bf883ef..9623f57 100644--- a/internal/scanner/scanner.go+++ b/internal/scanner/scanner.go@@ -110,15 +110,21 @@ func (s *Scanner) Scan(ctx context.Context, cidr string) (*types.ScanResult, errreturn s.scanTailscale(cidr, startTime), nil}- // Try nmap first+ // Try nmap first, then arp-scan, but only where arp-scan can exist. It has+ // no Windows build, so there a failed nmap scan is the whole story, and+ // falling through would replace the real reason with "arp-scan not found".devices, scanner, err := s.scanWithNmap(ctx, cidr)if err != nil {- // Fallback to arp-scan- devices, scanner, err = s.scanWithArpScan(ctx, cidr)+ nmapErr := err+ var arpErr error+ if ArpScanAvailable() {+ devices, scanner, err = s.scanWithArpScan(ctx, cidr)+ arpErr = err+ }if err != nil {return &types.ScanResult{Success: false,- Error: err.Error(),+ Error: ScanFailureMessage(nmapErr, arpErr),Network: cidr,Timestamp: time.Now(),}, nil@@ -175,13 +181,16 @@ func (s *Scanner) scanTailscale(cidr string, startTime time.Time) *types.ScanRes// scanWithNmap performs a scan using nmapfunc (s *Scanner) scanWithNmap(ctx context.Context, cidr string) ([]types.Device, string, error) {- // Check if nmap is available- if _, err := exec.LookPath("nmap"); err != nil {- return nil, "", fmt.Errorf("nmap not found")+ // Resolve nmap by path rather than name: NmapPath also checks the standard+ // install locations, so an install that PATH has not picked up yet still+ // works instead of reporting the tool missing.+ nmapBin, err := NmapPath()+ if err != nil {+ return nil, "", err}// Run nmap with ping scan and XML output- cmd := exec.CommandContext(ctx, "nmap", "-sn", "-oX", "-", cidr)+ cmd := exec.CommandContext(ctx, nmapBin, "-sn", "-oX", "-", cidr)output, err := cmd.Output()if err != nil {return nil, "", fmt.Errorf("nmap failed: %w", err)diff --git a/internal/scanner/tools.go b/internal/scanner/tools.gonew file mode 100644index 0000000..720709d--- /dev/null+++ b/internal/scanner/tools.go@@ -0,0 +1,118 @@+package scanner++import (+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+)++// ErrNmapNotFound reports that no nmap executable could be located, as opposed+// to one that was found and then failed to run. The two need different advice,+// so callers distinguish them with errors.Is.+var ErrNmapNotFound = errors.New("nmap not found")++// ArpScanAvailable reports whether arp-scan can exist on this platform at all.+//+// arp-scan has no Windows build. Treating it as a universal fallback is what+// made every failed Windows scan report "arp-scan not found", sending users+// after a tool they cannot install no matter what the real problem was.+func ArpScanAvailable() bool {+ return runtime.GOOS != "windows"+}++// NmapPath locates the nmap executable.+//+// exec.LookPath searches PATH and nothing else. On Windows the installer does+// add its directory to PATH, but a shell or a service that was already running+// when nmap was installed keeps the environment it started with, so a perfectly+// good install looks missing until the session is restarted. Checking the+// standard install locations turns that into a scan that simply works. The same+// applies to a macOS Homebrew install invoked from a launchd service with a+// minimal PATH.+func NmapPath() (string, error) {+ if path, err := exec.LookPath("nmap"); err == nil {+ return path, nil+ }+ for _, candidate := range nmapFallbackPaths() {+ if info, err := os.Stat(candidate); err == nil && !info.IsDir() {+ return candidate, nil+ }+ }+ return "", ErrNmapNotFound+}++// nmapFallbackPaths lists the usual install locations to try when nmap is not+// on PATH, most likely first.+func nmapFallbackPaths() []string {+ switch runtime.GOOS {+ case "windows":+ var paths []string+ // The 32-bit tree first: the Nmap installer is 32-bit and lands in+ // "Program Files (x86)" on every 64-bit Windows.+ for _, env := range []string{"ProgramFiles(x86)", "ProgramFiles", "ProgramW6432"} {+ if base := os.Getenv(env); base != "" {+ paths = append(paths, filepath.Join(base, "Nmap", "nmap.exe"))+ }+ }+ return paths+ case "darwin":+ return []string{+ "/opt/homebrew/bin/nmap", // Apple silicon Homebrew+ "/usr/local/bin/nmap", // Intel Homebrew+ "/opt/local/bin/nmap", // MacPorts+ }+ default:+ return []string{+ "/usr/bin/nmap",+ "/usr/local/bin/nmap",+ "/usr/sbin/nmap",+ }+ }+}++// ScanFailureMessage explains why a scan could not run.+//+// Only the last error used to survive, so on Windows every failure read+// "arp-scan not found" regardless of the actual cause. nmap is the scanner we+// actually want, so its error leads, arp-scan's is appended only where arp-scan+// is a real option, and a platform-specific hint says what to do about it.+func ScanFailureMessage(nmapErr, arpErr error) string {+ var b strings.Builder+ b.WriteString(nmapErr.Error())+ if arpErr != nil {+ fmt.Fprintf(&b, "; %s", arpErr.Error())+ }+ if hint := nmapHint(nmapErr); hint != "" {+ fmt.Fprintf(&b, ". %s", hint)+ }+ return b.String()+}++// nmapHint returns the actionable advice for an nmap failure on this platform.+func nmapHint(nmapErr error) string {+ if errors.Is(nmapErr, ErrNmapNotFound) {+ switch runtime.GOOS {+ case "windows":+ return "Install nmap from nmap.org, including Npcap, then open a NEW Administrator " ++ "Command Prompt so it picks up the updated PATH. Run \"orangutan status\" to see " ++ "which tools LAN Orangutan can find"+ case "darwin":+ return "Install it with: brew install nmap"+ default:+ return "Install it with your package manager, for example: sudo apt install nmap"+ }+ }+ // nmap was found but did not complete.+ switch runtime.GOOS {+ case "windows":+ return "nmap is installed but did not complete. Check that Npcap was installed alongside " ++ "it, and run LAN Orangutan as Administrator"+ default:+ return "nmap is installed but did not complete. Try running as root, which nmap needs for " ++ "MAC addresses and vendor details"+ }+}diff --git a/internal/scanner/tools_test.go b/internal/scanner/tools_test.gonew file mode 100644index 0000000..ff0f774--- /dev/null+++ b/internal/scanner/tools_test.go@@ -0,0 +1,71 @@+package scanner++import (+ "errors"+ "runtime"+ "strings"+ "testing"+)++func TestArpScanAvailableIsFalseOnWindows(t *testing.T) {+ if got, want := ArpScanAvailable(), runtime.GOOS != "windows"; got != want {+ t.Fatalf("ArpScanAvailable() = %v, want %v on %s", got, want, runtime.GOOS)+ }+}++// The reported reason must be nmap's, not arp-scan's. Reporting only the second+// error is what made every Windows failure read "arp-scan not found".+func TestScanFailureMessageLeadsWithNmapError(t *testing.T) {+ msg := ScanFailureMessage(ErrNmapNotFound, errors.New("arp-scan not found"))+ if !strings.HasPrefix(msg, "nmap not found") {+ t.Fatalf("message should lead with the nmap error, got %q", msg)+ }+ if !strings.Contains(msg, "arp-scan not found") {+ t.Fatalf("message should still mention arp-scan when it was tried, got %q", msg)+ }+}++// On Windows arp-scan is never attempted, so its error must not appear at all.+func TestScanFailureMessageOmitsArpScanWhenNotTried(t *testing.T) {+ msg := ScanFailureMessage(ErrNmapNotFound, nil)+ if strings.Contains(msg, "arp-scan") {+ t.Fatalf("message must not mention arp-scan when it was not tried, got %q", msg)+ }+ if !strings.Contains(msg, "nmap not found") {+ t.Fatalf("message should name the real problem, got %q", msg)+ }+}++// A missing nmap and a broken nmap need different advice.+func TestScanFailureMessageHintDistinguishesMissingFromFailed(t *testing.T) {+ missing := ScanFailureMessage(ErrNmapNotFound, nil)+ failed := ScanFailureMessage(errors.New("nmap failed: exit status 1"), nil)+ if missing == failed {+ t.Fatal("a missing nmap and a failed nmap should not give the same advice")+ }+ if !strings.Contains(missing, "Install") {+ t.Fatalf("a missing nmap should say how to install it, got %q", missing)+ }+ if !strings.Contains(failed, "did not complete") {+ t.Fatalf("a failed nmap should say it ran but did not finish, got %q", failed)+ }+}++func TestNmapNotFoundIsIdentifiable(t *testing.T) {+ if !errors.Is(ErrNmapNotFound, ErrNmapNotFound) {+ t.Fatal("ErrNmapNotFound should match itself under errors.Is")+ }+}++// Every candidate must be an absolute path to a file named nmap, so a lookup+// can never be satisfied by something relative to the working directory.+func TestNmapFallbackPathsAreAbsolute(t *testing.T) {+ for _, p := range nmapFallbackPaths() {+ if !strings.HasPrefix(p, "/") && !strings.Contains(p, `:\`) {+ t.Errorf("fallback path %q is not absolute", p)+ }+ if !strings.Contains(strings.ToLower(p), "nmap") {+ t.Errorf("fallback path %q does not point at nmap", p)+ }+ }+}diff --git a/internal/storage/groups.go b/internal/storage/groups.gonew file mode 100644index 0000000..a751679--- /dev/null+++ b/internal/storage/groups.go@@ -0,0 +1,255 @@+package storage++import (+ "fmt"+ "sort"+ "strings"+ "unicode"+)++// defaultGroups is the built-in group list, in the order it is offered. It is+// only a starting point: the user can add, rename and remove entries, at which+// point the whole list lives in the scan state instead.+var defaultGroups = []string{"Server", "Desktop", "Laptop", "Mobile", "IoT", "Network", "Pi"}++// maxGroupNameLen bounds a group name so the dropdown and the table column stay+// usable. Generous enough for anything descriptive, short enough that one entry+// cannot distort the UI.+const maxGroupNameLen = 32++// DefaultGroups returns a copy of the built-in group list.+func DefaultGroups() []string {+ return append([]string(nil), defaultGroups...)+}++// GetGroups returns the effective group list: the user's own if they have+// customised it, otherwise the built-in defaults.+//+// Any group actually set on a device is appended if it is missing from the list.+// Without that, a group that arrived with a restored backup, or that was removed+// from the list by hand, would leave devices carrying a value the UI cannot show+// or select, and a later edit would silently drop it.+func (s *Storage) GetGroups() []string {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.effectiveGroupsLocked()+}++// GroupsCustomised reports whether the user has replaced the built-in list, so+// the UI can offer "reset to defaults" only when it would do something.+func (s *Storage) GroupsCustomised() bool {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.state.Groups != nil+}++// GroupCounts returns how many devices carry each group, so the UI can warn+// before a delete or a rename that affects real devices.+func (s *Storage) GroupCounts() map[string]int {+ s.mu.RLock()+ defer s.mu.RUnlock()+ counts := make(map[string]int)+ for _, d := range s.devices {+ if d.Group != "" {+ counts[d.Group]+++ }+ }+ return counts+}++// effectiveGroupsLocked builds the list the UI should show. Callers hold s.mu.+func (s *Storage) effectiveGroupsLocked() []string {+ var groups []string+ if s.state.Groups != nil {+ groups = append(groups, *s.state.Groups...)+ } else {+ groups = append(groups, defaultGroups...)+ }++ seen := make(map[string]bool, len(groups))+ for _, g := range groups {+ seen[strings.ToLower(g)] = true+ }+ // Pick up any group in use that the list does not mention, so no device is+ // left holding a value the UI cannot represent.+ var extra []string+ for _, d := range s.devices {+ if d.Group == "" || seen[strings.ToLower(d.Group)] {+ continue+ }+ seen[strings.ToLower(d.Group)] = true+ extra = append(extra, d.Group)+ }+ sort.Strings(extra)+ return append(groups, extra...)+}++// SetGroups replaces the whole group list. An empty slice is a valid list (the+// user removed every group); nil resets to the built-in defaults.+func (s *Storage) SetGroups(groups []string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ if groups == nil {+ s.state.Groups = nil+ return s.saveState()+ }++ cleaned, err := validateGroupNames(groups)+ if err != nil {+ return err+ }+ s.state.Groups = &cleaned+ return s.saveState()+}++// AddGroup appends a new group to the list.+func (s *Storage) AddGroup(name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ clean, err := validateGroupName(name)+ if err != nil {+ return err+ }+ groups := s.effectiveGroupsLocked()+ for _, g := range groups {+ if strings.EqualFold(g, clean) {+ return fmt.Errorf("group %q already exists", clean)+ }+ }+ groups = append(groups, clean)+ s.state.Groups = &groups+ return s.saveState()+}++// RenameGroup renames a group and rewrites it on every device that used it, so+// the list and the devices can never drift apart.+//+// Renaming to a name that differs only in case is allowed (it is the same group+// being re-spelled); renaming onto a different existing group is not, because+// that is a merge, and silently merging two groups would lose the distinction+// without the user asking for it.+func (s *Storage) RenameGroup(oldName, newName string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ clean, err := validateGroupName(newName)+ if err != nil {+ return err+ }+ oldName = strings.TrimSpace(oldName)++ groups := s.effectiveGroupsLocked()+ idx := -1+ for i, g := range groups {+ if strings.EqualFold(g, oldName) {+ idx = i+ break+ }+ }+ if idx < 0 {+ return fmt.Errorf("group %q not found", oldName)+ }+ for i, g := range groups {+ if i != idx && strings.EqualFold(g, clean) {+ return fmt.Errorf("group %q already exists", clean)+ }+ }++ from := groups[idx]+ groups[idx] = clean+ s.state.Groups = &groups+ if err := s.saveState(); err != nil {+ return err+ }++ changed := false+ for _, d := range s.devices {+ if strings.EqualFold(d.Group, from) {+ d.Group = clean+ changed = true+ }+ }+ if changed {+ return s.saveDevices()+ }+ return nil+}++// DeleteGroup removes a group from the list and clears it from every device that+// carried it, leaving those devices ungrouped rather than pointing at a group+// that no longer exists.+func (s *Storage) DeleteGroup(name string) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ name = strings.TrimSpace(name)+ groups := s.effectiveGroupsLocked()+ kept := make([]string, 0, len(groups))+ found := false+ for _, g := range groups {+ if strings.EqualFold(g, name) {+ found = true+ continue+ }+ kept = append(kept, g)+ }+ if !found {+ return fmt.Errorf("group %q not found", name)+ }++ s.state.Groups = &kept+ if err := s.saveState(); err != nil {+ return err+ }++ changed := false+ for _, d := range s.devices {+ if strings.EqualFold(d.Group, name) {+ d.Group = ""+ changed = true+ }+ }+ if changed {+ return s.saveDevices()+ }+ return nil+}++// validateGroupName trims and checks a single name.+func validateGroupName(name string) (string, error) {+ name = strings.TrimSpace(name)+ if name == "" {+ return "", fmt.Errorf("group name cannot be empty")+ }+ if len([]rune(name)) > maxGroupNameLen {+ return "", fmt.Errorf("group name cannot be longer than %d characters", maxGroupNameLen)+ }+ // Control characters would break the dropdown and the table without being+ // visible to whoever typed them.+ for _, r := range name {+ if unicode.IsControl(r) {+ return "", fmt.Errorf("group name cannot contain control characters")+ }+ }+ return name, nil+}++// validateGroupNames cleans a whole list and rejects duplicates.+func validateGroupNames(names []string) ([]string, error) {+ cleaned := make([]string, 0, len(names))+ seen := make(map[string]bool, len(names))+ for _, n := range names {+ clean, err := validateGroupName(n)+ if err != nil {+ return nil, err+ }+ if seen[strings.ToLower(clean)] {+ return nil, fmt.Errorf("duplicate group %q", clean)+ }+ seen[strings.ToLower(clean)] = true+ cleaned = append(cleaned, clean)+ }+ return cleaned, nil+}diff --git a/internal/storage/groups_test.go b/internal/storage/groups_test.gonew file mode 100644index 0000000..aed318c--- /dev/null+++ b/internal/storage/groups_test.go@@ -0,0 +1,301 @@+package storage++import (+ "testing"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// seedGrouped puts devices in storage and assigns each one a group.+func seedGrouped(t *testing.T, s *Storage, groups map[string]string) {+ t.Helper()+ var devices []types.Device+ for ip := range groups {+ devices = append(devices, types.Device{IP: ip, MAC: "aa:bb:cc:00:00:" + ip[len(ip)-2:]})+ }+ if err := s.MergeDevices(devices); err != nil {+ t.Fatalf("MergeDevices: %v", err)+ }+ for ip, g := range groups {+ group := g+ if err := s.UpdateDeviceFields(ip, nil, nil, &group, nil); err != nil {+ t.Fatalf("UpdateDeviceFields(%s): %v", ip, err)+ }+ }+}++func TestGroupsDefaultToBuiltInList(t *testing.T) {+ s := newTestStorage(t)++ got := s.GetGroups()+ want := DefaultGroups()+ if len(got) != len(want) {+ t.Fatalf("GetGroups() = %v, want the %d built-in defaults", got, len(want))+ }+ for i := range want {+ if got[i] != want[i] {+ t.Errorf("group %d = %q, want %q (declaration order matters)", i, got[i], want[i])+ }+ }+ if s.GroupsCustomised() {+ t.Error("GroupsCustomised() = true before any edit")+ }+}++func TestAddGroupAppearsAndPersists(t *testing.T) {+ s := newTestStorage(t)++ if err := s.AddGroup("Wearables"); err != nil {+ t.Fatalf("AddGroup: %v", err)+ }+ if !contains(s.GetGroups(), "Wearables") {+ t.Fatalf("GetGroups() = %v, want it to contain Wearables", s.GetGroups())+ }+ if !s.GroupsCustomised() {+ t.Error("GroupsCustomised() = false after adding a group")+ }+}++func TestAddGroupRejectsDuplicateRegardlessOfCase(t *testing.T) {+ s := newTestStorage(t)++ if err := s.AddGroup("iot"); err == nil {+ t.Fatal("AddGroup(\"iot\") should be rejected: IoT already exists")+ }+}++func TestAddGroupRejectsEmptyAndOverlongNames(t *testing.T) {+ s := newTestStorage(t)++ if err := s.AddGroup(" "); err == nil {+ t.Error("a blank group name should be rejected")+ }+ long := ""+ for i := 0; i < maxGroupNameLen+1; i++ {+ long += "x"+ }+ if err := s.AddGroup(long); err == nil {+ t.Errorf("a %d-character name should be rejected", len(long))+ }+}++func TestAddGroupRejectsControlCharacters(t *testing.T) {+ s := newTestStorage(t)++ if err := s.AddGroup("Bad\nName"); err == nil {+ t.Error("a name containing a control character should be rejected")+ }+}++// The point of the feature: renaming must follow through to the devices, or the+// list and the data drift apart.+func TestRenameGroupRewritesEveryDeviceUsingIt(t *testing.T) {+ s := newTestStorage(t)+ seedGrouped(t, s, map[string]string{+ "192.168.1.11": "IoT",+ "192.168.1.12": "IoT",+ "192.168.1.13": "Server",+ })++ if err := s.RenameGroup("IoT", "Wearables"); err != nil {+ t.Fatalf("RenameGroup: %v", err)+ }++ if contains(s.GetGroups(), "IoT") {+ t.Error("the old group name should be gone from the list")+ }+ if !contains(s.GetGroups(), "Wearables") {+ t.Error("the new group name should be in the list")+ }+ for _, ip := range []string{"192.168.1.11", "192.168.1.12"} {+ if got := s.GetDevice(ip).Group; got != "Wearables" {+ t.Errorf("device %s group = %q, want Wearables", ip, got)+ }+ }+ if got := s.GetDevice("192.168.1.13").Group; got != "Server" {+ t.Errorf("an unrelated device was changed: group = %q, want Server", got)+ }+}++func TestRenameGroupKeepsItsPositionInTheList(t *testing.T) {+ s := newTestStorage(t)++ before := s.GetGroups()+ idx := indexOf(before, "IoT")+ if idx < 0 {+ t.Fatal("expected IoT in the default list")+ }+ if err := s.RenameGroup("IoT", "Wearables"); err != nil {+ t.Fatalf("RenameGroup: %v", err)+ }+ if got := indexOf(s.GetGroups(), "Wearables"); got != idx {+ t.Errorf("renamed group moved to position %d, want %d", got, idx)+ }+}++// Renaming onto another existing group would silently merge them, losing a+// distinction the user never asked to give up.+func TestRenameGroupRejectsCollisionWithAnotherGroup(t *testing.T) {+ s := newTestStorage(t)++ if err := s.RenameGroup("IoT", "Server"); err == nil {+ t.Fatal("renaming IoT onto the existing Server group should be rejected")+ }+}++// Re-spelling the same group is not a collision with itself.+func TestRenameGroupAllowsCaseOnlyChange(t *testing.T) {+ s := newTestStorage(t)++ if err := s.RenameGroup("IoT", "IOT"); err != nil {+ t.Fatalf("re-spelling a group should be allowed: %v", err)+ }+ if !contains(s.GetGroups(), "IOT") {+ t.Errorf("GetGroups() = %v, want the new spelling", s.GetGroups())+ }+}++func TestRenameUnknownGroupIsAnError(t *testing.T) {+ s := newTestStorage(t)++ if err := s.RenameGroup("Nope", "Something"); err == nil {+ t.Fatal("renaming a group that does not exist should be an error")+ }+}++// Deleting a group must clear it from devices, never delete the devices.+func TestDeleteGroupClearsItFromDevicesButKeepsThem(t *testing.T) {+ s := newTestStorage(t)+ seedGrouped(t, s, map[string]string{+ "192.168.1.21": "IoT",+ "192.168.1.22": "Server",+ })++ if err := s.DeleteGroup("IoT"); err != nil {+ t.Fatalf("DeleteGroup: %v", err)+ }++ if contains(s.GetGroups(), "IoT") {+ t.Error("the deleted group should be gone from the list")+ }+ d := s.GetDevice("192.168.1.21")+ if d == nil {+ t.Fatal("deleting a group must never delete the device")+ }+ if d.Group != "" {+ t.Errorf("device group = %q, want it cleared", d.Group)+ }+ if got := s.GetDevice("192.168.1.22").Group; got != "Server" {+ t.Errorf("an unrelated device was changed: group = %q, want Server", got)+ }+}++func TestDeleteUnknownGroupIsAnError(t *testing.T) {+ s := newTestStorage(t)++ if err := s.DeleteGroup("Nope"); err == nil {+ t.Fatal("deleting a group that does not exist should be an error")+ }+}++func TestResetGroupsRestoresTheDefaults(t *testing.T) {+ s := newTestStorage(t)++ if err := s.AddGroup("Wearables"); err != nil {+ t.Fatalf("AddGroup: %v", err)+ }+ if err := s.SetGroups(nil); err != nil {+ t.Fatalf("SetGroups(nil): %v", err)+ }+ if s.GroupsCustomised() {+ t.Error("GroupsCustomised() = true after a reset")+ }+ if contains(s.GetGroups(), "Wearables") {+ t.Error("a reset should drop the custom group")+ }+ if len(s.GetGroups()) != len(DefaultGroups()) {+ t.Errorf("GetGroups() = %v, want the defaults back", s.GetGroups())+ }+}++// A group that arrives on a device without being in the list (a restored backup,+// a hand-edited file) must still be selectable, or editing that device would+// silently drop its group.+func TestGroupInUseButMissingFromTheListStillAppears(t *testing.T) {+ s := newTestStorage(t)+ seedGrouped(t, s, map[string]string{"192.168.1.31": "Imported"})++ if err := s.SetGroups([]string{"Server", "Desktop"}); err != nil {+ t.Fatalf("SetGroups: %v", err)+ }+ if !contains(s.GetGroups(), "Imported") {+ t.Errorf("GetGroups() = %v, want the in-use group to be included", s.GetGroups())+ }+}++func TestGroupCountsReportDevicesPerGroup(t *testing.T) {+ s := newTestStorage(t)+ seedGrouped(t, s, map[string]string{+ "192.168.1.41": "IoT",+ "192.168.1.42": "IoT",+ "192.168.1.43": "Server",+ })++ counts := s.GroupCounts()+ if counts["IoT"] != 2 {+ t.Errorf("counts[IoT] = %d, want 2", counts["IoT"])+ }+ if counts["Server"] != 1 {+ t.Errorf("counts[Server] = %d, want 1", counts["Server"])+ }+ if _, ok := counts["Desktop"]; ok {+ t.Error("an unused group should not appear in the counts")+ }+}++func TestSetGroupsRejectsDuplicates(t *testing.T) {+ s := newTestStorage(t)++ if err := s.SetGroups([]string{"Server", "server"}); err == nil {+ t.Fatal("a list containing the same group twice should be rejected")+ }+}++// Edits must survive a restart, which means they are in the state file.+func TestGroupEditsPersistAcrossReload(t *testing.T) {+ dir := t.TempDir()+ devicesFile := dir + "/devices.json"+ stateFile := dir + "/state.json"++ s, err := New(devicesFile, stateFile)+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ if err := s.RenameGroup("IoT", "Wearables"); err != nil {+ t.Fatalf("RenameGroup: %v", err)+ }++ reopened, err := New(devicesFile, stateFile)+ if err != nil {+ t.Fatalf("New (reopen): %v", err)+ }+ if !contains(reopened.GetGroups(), "Wearables") {+ t.Errorf("GetGroups() = %v after reload, want the rename to have survived", reopened.GetGroups())+ }+ if contains(reopened.GetGroups(), "IoT") {+ t.Error("the old name came back after a reload")+ }+}++func contains(haystack []string, needle string) bool {+ return indexOf(haystack, needle) >= 0+}++func indexOf(haystack []string, needle string) int {+ for i, s := range haystack {+ if s == needle {+ return i+ }+ }+ return -1+}diff --git a/internal/types/types.go b/internal/types/types.goindex 218576f..fba50b8 100644--- a/internal/types/types.go+++ b/internal/types/types.go@@ -134,6 +134,11 @@ type ScanState struct {Networks *[]string `json:"networks,omitempty"`ExcludeNetworks *[]string `json:"exclude_networks,omitempty"`OnlyConfiguredNetworks *bool `json:"only_configured_networks,omitempty"`+ // Groups is the user's device-group list, set from the Settings page. nil+ // means "use the built-in defaults"; a non-nil slice replaces them outright,+ // so a group can be added, renamed or removed. Renaming rewrites the group+ // on every device that used it, so the list and the devices never disagree.+ Groups *[]string `json:"groups,omitempty"`}// ScanResult represents the outcome of a network scandiff --git a/internal/web/handler.go b/internal/web/handler.goindex a648a3a..7e37753 100644--- a/internal/web/handler.go+++ b/internal/web/handler.go@@ -332,7 +332,6 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {// Convert to view modelsvar deviceViews []*DeviceView- groupSet := make(map[string]bool)var flagged, moved, unexpected, missing intfor _, d := range devices {@@ -378,10 +377,6 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {}deviceViews = append(deviceViews, dv)-- if d.Group != "" {- groupSet[d.Group] = true- }}// Sort by IP@@ -389,12 +384,12 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {return ipToLong(deviceViews[i].IP) < ipToLong(deviceViews[j].IP)})- // Get groups- var groups []string- for g := range groupSet {- groups = append(groups, g)- }- sort.Strings(groups)+ // The group list the dropdowns are built from: the user's own list if they+ // have customised it, otherwise the built-in defaults. GetGroups already+ // folds in any group a device carries that the list is missing, so this+ // covers everything in use as well as everything on offer. Declaration order+ // is kept, so a user's ordering is not re-sorted out from under them.+ groups := h.store.GetGroups()// Get networksnetworks, _ := network.DetectNetworks()diff --git a/internal/web/static/app.js b/internal/web/static/app.jsindex b6649ef..5d13ba8 100644--- a/internal/web/static/app.js+++ b/internal/web/static/app.js@@ -622,22 +622,38 @@ async function updateDeviceGroup(select) {function copyToClipboard(text, event) {const ok = () => showCopied(event);const fail = () => showToast('Failed to copy', 'error');+ // Chromium over plain http cannot be written to at all (see+ // clipboardWriteBlocked). The one copy the browser still honours there is+ // the user's own keyboard shortcut, so select the value for them and say so,+ // instead of claiming a copy that did not happen.+ if (clipboardWriteBlocked()) {+ if (selectValueText(event, text)) {+ showCopied(event, 'Press ' + copyShortcutName() + ' to copy');+ } else {+ fail();+ }+ return;+ }+ // Non-secure fallbacks, in order: the copy-event route first (nothing to+ // tear down, so nothing to race), the hidden-field route last.+ const fallback = () => copyViaEvent(text) || legacyCopy(text);if (navigator.clipboard && window.isSecureContext) {navigator.clipboard.writeText(text).then(ok).catch(() => {- if (legacyCopy(text)) ok(); else fail();+ if (fallback()) ok(); else fail();});- } else if (legacyCopy(text)) {+ } else if (fallback()) {ok();} else {fail();}}-// The floating "Copied!" note at the tap/cursor point.-function showCopied(event) {+// The floating "Copied!" note at the tap/cursor point. A different message+// can be given for the case where the user has to finish the copy themselves.+function showCopied(event, message) {const feedback = document.createElement('div');feedback.className = 'copy-feedback';- feedback.textContent = 'Copied!';+ feedback.textContent = message || '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,@@ -658,16 +674,101 @@ function showCopied(event) {const top = Math.max(pad, y - 30);feedback.style.left = left + 'px';feedback.style.top = top + 'px';- setTimeout(() => feedback.remove(), 800);+ // "Copied!" is a flash; an instruction needs long enough to be read and+ // acted on.+ setTimeout(() => feedback.remove(), message ? 2500 : 800);+}++// Chromium (Chrome, Edge, Brave) no longer writes the clipboard from a page+// served over plain http, whichever route is used: execCommand reports success,+// the copy event fires, and nothing lands. Reproduced on Chromium 153 against+// this dashboard (GitHub #43: Brave and Edge fail, Firefox copies, all on the+// same http://<ip> instance). There is no page-side way around it and no way to+// detect it after the fact, since every call reports success, so it has to be+// decided up front from the two facts that define it: not a secure context, and+// a Chromium browser. window.chrome is present in Chrome, Edge and Brave on every+// page and absent in Firefox and Safari. (navigator.userAgentData would be the+// tidier signal, but it is itself secure-context-only, so it is undefined on+// precisely the pages this check exists for.) The user-agent test is a backstop+// for a Chromium build that hides window.chrome.+function clipboardWriteBlocked() {+ if (window.isSecureContext) return false;+ return !!window.chrome || /\b(Chrome|Chromium|Edg|Brave)\//.test(navigator.userAgent);+}++// Select the copied value's own text in the clicked cell, so a keyboard copy+// takes exactly that value and nothing else in the cell (an icon, the IPv6+// line under an IPv4 address). Returns whether a selection was made.+function selectValueText(event, text) {+ const cell = event && event.target && event.target.closest ? event.target.closest('[data-copy]') : null;+ if (!cell || !window.getSelection) return false;+ let node = null;+ for (const child of cell.childNodes) {+ if (child.nodeType === Node.TEXT_NODE && child.textContent.trim() === text) {+ node = child;+ break;+ }+ }+ const range = document.createRange();+ if (node) {+ const start = node.textContent.indexOf(text);+ range.setStart(node, start);+ range.setEnd(node, start + text.length);+ } else {+ range.selectNodeContents(cell);+ }+ const selection = window.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ return true;+}++// The copy shortcut as the user knows it on their platform.+function copyShortcutName() {+ const p = navigator.platform || ((navigator.userAgentData && navigator.userAgentData.platform) || '');+ return /mac|iphone|ipad/i.test(p) ? '\u2318C' : 'Ctrl+C';}-// 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.+// Clipboard copy for non-secure contexts (plain-http LAN access, the common+// case for a self-hosted instance) with no element involved at all.+//+// execCommand('copy') fires a `copy` event; a listener that sets the event's+// clipboardData and prevents the default is what the browser then puts on the+// clipboard. Nothing is added to the page and nothing is removed afterwards.+// That matters because the hidden-field route below removes its field the+// instant execCommand returns, and on some systems the clipboard is served+// lazily by whichever element owns it, so tearing that element down at once+// can leave an empty clipboard while the copy still reported success (the+// "Copied!" note with nothing to paste that was reported against v3.3.8).+// Returns whether the browser accepted the copy.+function copyViaEvent(text) {+ if (typeof document.execCommand !== 'function') return false;+ let handled = false;+ const onCopy = (e) => {+ if (!e.clipboardData) return;+ e.clipboardData.setData('text/plain', text);+ e.preventDefault();+ handled = true;+ };+ document.addEventListener('copy', onCopy, { once: true });+ let ok = false;+ try {+ ok = document.execCommand('copy');+ } catch (e) {+ ok = false;+ }+ // { once } already removed it if the event fired; this covers the case+ // where execCommand did not dispatch a copy event at all.+ document.removeEventListener('copy', onCopy);+ return ok && handled;+}++// Last-resort clipboard copy: a hidden, selectable field and+// document.execCommand('copy'). Deprecated, but still the widest-supported+// path when copyViaEvent is refused. 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');@@ -702,11 +803,15 @@ function legacyCopy(text) {} catch (e) {ok = false;}- document.body.removeChild(field);+ // Restore the user's selection now, but take the field itself down on the+ // next tick rather than synchronously: it is the clipboard's owner until+ // the handoff completes, and removing it in the same task has been seen to+ // leave the clipboard empty despite execCommand reporting success.if (selection) {selection.removeAllRanges();if (previous) selection.addRange(previous);}+ setTimeout(() => { if (field.parentNode) field.parentNode.removeChild(field); }, 0);return ok;}@@ -807,6 +912,14 @@ function compareRows(a, b, column) {valA = a.dataset.vendor || 'zzz';valB = b.dataset.vendor || 'zzz';break;+ case 'label':+ case 'group':+ // The two the user types themselves, so compare them the way the+ // user reads them: case-insensitively, with devices that have no+ // value sorted to the end rather than to the top.+ valA = (a.dataset[column] || '').toLowerCase() || 'zzz';+ valB = (b.dataset[column] || '').toLowerCase() || 'zzz';+ break;case 'status':const order = { online: 0, recent: 1, offline: 2 };valA = order[a.dataset.status] ?? 3;@@ -1298,6 +1411,54 @@ async function disconnectTailscale() {});// A stale tooltip must not linger over new content.window.addEventListener('scroll', hide, { passive: true });++ // Discoverability. The reveal existed but nothing said so: a clipped cell+ // looked identical to a normal one apart from the ellipsis, which reads as+ // "cut off", not "hover me" (GitHub #41). Two signals, both present only+ // when something is actually clipped, so a table whose values all fit shows+ // neither: the cell itself fades out at its right edge instead of ending in+ // an ellipsis (.is-clipped), and the footer legend gains a one-line hint.+ //+ // Re-run whenever widths can change: after load and font loading (metrics+ // shift once web fonts arrive), on resize, and after an auto-refresh swaps+ // the rows and the footer (which is why the hint is server-rendered and+ // toggled here rather than injected once).+ function markClipped() {+ let any = false;+ table.querySelectorAll(SELECTOR).forEach(cell => {+ const clipped = isClipped(cell);+ cell.classList.toggle('is-clipped', clipped);+ if (clipped) any = true;+ });+ const hint = document.getElementById('clip-hint');+ if (hint) hint.hidden = !any;+ }+ // Coalesced with a timer rather than requestAnimationFrame: a frame never+ // fires while the tab is hidden, so a dashboard opened in a background tab+ // would sit unmarked until something else nudged it. A timer runs either+ // way, and a zero delay still folds a burst of resize events into one pass.+ let markPending = false;+ function scheduleMark() {+ if (markPending) return;+ markPending = true;+ setTimeout(() => { markPending = false; markClipped(); }, 0);+ }+ scheduleMark();+ window.addEventListener('load', scheduleMark);+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(scheduleMark);+ window.addEventListener('resize', scheduleMark, { passive: true });+ window.addEventListener('devices-refreshed', scheduleMark);++ // Touch has no hover. On a touch device wide enough to show the table (an+ // iPad in landscape), a tap on a clipped cell reveals it briefly. The tap+ // also copies the value, and the two do not conflict: the copy note sits at+ // the finger, the reveal overlays the cell.+ table.addEventListener('touchstart', function (e) {+ const cell = e.target.closest(SELECTOR);+ if (!cell || !isClipped(cell)) return;+ show(cell);+ setTimeout(hide, 1800);+ }, { passive: true });})();// Click-to-copy for value cells (IP, MAC, hostname, vendor). Driven by adiff --git a/internal/web/static/style.css b/internal/web/static/style.cssindex efc40d1..9a083e9 100644--- a/internal/web/static/style.css+++ b/internal/web/static/style.css@@ -1034,16 +1034,16 @@ td[data-copy]:not([data-copy=""]) {/* Column widths for the fixed layout (they sum to 100%). When the responsiverules further down hide a column, its share is redistributed across therest, 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(1), .table td:nth-child(1) { width: 5%; } /* 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(3), .table td:nth-child(3) { width: 12%; } /* Hostname */+.table th:nth-child(4), .table td:nth-child(4) { width: 9%; } /* Type */+.table th:nth-child(5), .table td:nth-child(5) { width: 12%; } /* 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(7), .table td:nth-child(7) { width: 14%; } /* Label (free text, the widest user-set value) */.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) */+.table th:nth-child(9), .table td:nth-child(9) { width: 8%; } /* Last Seen*/+.table th:nth-child(10), .table td:nth-child(10) { width: 7%; } /* Actions (two icons) *//* Single-line cells that should truncate rather than wrap. The group selectfills its column so it never forces the row wider. */@@ -1058,6 +1058,24 @@ td[data-copy]:not([data-copy=""]) {/* Keep the table inside its panel with no horizontal scroll: the two free-textcolumns truncate with an ellipsis rather than forcing the table wider. */+/* A value that does not fit its column fades out at the right edge instead of+ ending in an ellipsis. The fade is the signal that there is more and that+ hovering shows it; a value that fits gets no fade at all. The class is set+ by JS from a real overflow measurement, so it is never applied by guess. The+ fade ends before the cell's right padding so the last visible glyphs are not+ swallowed by it. */+.table td.is-clipped {+ text-overflow: clip;+ -webkit-mask-image: linear-gradient(90deg, #000 calc(100% - 2.4rem), transparent calc(100% - 0.65rem));+ mask-image: linear-gradient(90deg, #000 calc(100% - 2.4rem), transparent calc(100% - 0.65rem));+}++/* The footer hint that pairs with the fade; JS shows it only while at least+ one cell on the page is clipped. */+.clip-hint {+ font-style: italic;+}+.hostname-cell, .vendor-cell {max-width: 150px;overflow: hidden;@@ -1202,8 +1220,10 @@ td[data-copy]:not([data-copy=""]) {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;+ so a long one can never stretch the table past its panel. The column+ percentage above is the real constraint at normal widths; this only binds+ on a very wide screen. */+ max-width: 260px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;@@ -1342,6 +1362,54 @@ textarea.input {color: var(--danger);}+/* Device-group editor on the Settings page. One row per group: the name, how+ many devices carry it, and the rename/delete actions. The row doubles as the+ inline rename and delete-confirm surface, so nothing shifts when either+ opens. */+.group-list {+ display: flex;+ flex-direction: column;+ gap: 0.4rem;+ margin-top: 0.5rem;+}++.group-row {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ padding: 0.45rem 0.6rem;+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: var(--radius-sm);+ min-height: 2.35rem;+}++.group-name {+ font-weight: 500;+}++.group-count {+ color: var(--text-muted);+ font-size: 0.82rem;+}++/* Push the buttons to the right edge, leaving the name and count on the left. */+.group-actions {+ display: flex;+ gap: 0.4rem;+ margin-left: auto;+}++@media (max-width: 600px) {+ .group-row {+ flex-wrap: wrap;+ }+ .group-actions {+ margin-left: 0;+ width: 100%;+ }+}+.form-group {margin-bottom: 1.25rem;}@@ -1504,7 +1572,13 @@ textarea.input {border-bottom: none;}-.btn-sm {+/* Buttons inside a dense row list (snapshots, device groups) sit tighter than+ the page-level .btn-sm defined above, so a row stays one line tall. Scoped to+ the rows on purpose: an unscoped second .btn-sm here once overrode the+ original for every small button on the site, silently shrinking the released+ "Scan network", Tailscale and scan-cancel buttons. */+.snapshot-row .btn-sm,+.group-row .btn-sm {padding: 0.25rem 0.6rem;font-size: 0.8rem;}@@ -1970,7 +2044,12 @@ textarea.input {white-space: normal;overflow: visible;text-overflow: clip;+ /* Values wrap in full here, so the desktop clipped-cell fade must never+ apply, even if a resize races the JS that clears the class. */+ -webkit-mask-image: none;+ mask-image: none;}+ .clip-hint { display: none; }.table .device-row td:last-child { border-bottom: none; }.table .device-row td::before {content: attr(data-label);diff --git a/internal/web/templates/index.html b/internal/web/templates/index.htmlindex 19cbe84..b82a3ec 100644--- a/internal/web/templates/index.html+++ b/internal/web/templates/index.html@@ -224,13 +224,7 @@ orangutan export out.csv</code></pre></select><select id="group-filter" class="select" style="width:auto" onchange="filterDevices()"><option value="all">All Groups</option>- <option value="Server">Server</option>- <option value="Desktop">Desktop</option>- <option value="Laptop">Laptop</option>- <option value="Mobile">Mobile</option>- <option value="IoT">IoT</option>- <option value="Network">Network</option>- <option value="Pi">Pi</option>+ {{range .Groups}}<option value="{{.}}">{{.}}</option>{{end}}</select><button class="btn" onclick="markAllExpected()" title="Mark every current device as expected, so you are flagged only when something new appears or a known device goes missing">Mark all expected</button><button class="btn" onclick="openSnapshots()">Snapshots</button>@@ -259,8 +253,8 @@ orangutan export out.csv</code></pre><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 data-sort="label" onclick="sortTable('label')">Label <span class="sort-icon">↕</span></th>+ <th data-sort="group" onclick="sortTable('group')">Group <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>@@ -304,13 +298,7 @@ orangutan export out.csv</code></pre><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>- <option value="Desktop" {{if eq .Group "Desktop"}}selected{{end}}>Desktop</option>- <option value="Laptop" {{if eq .Group "Laptop"}}selected{{end}}>Laptop</option>- <option value="Mobile" {{if eq .Group "Mobile"}}selected{{end}}>Mobile</option>- <option value="IoT" {{if eq .Group "IoT"}}selected{{end}}>IoT</option>- <option value="Network" {{if eq .Group "Network"}}selected{{end}}>Network</option>- <option value="Pi" {{if eq .Group "Pi"}}selected{{end}}>Pi</option>+ {{$g := .Group}}{{range $.Groups}}<option value="{{.}}" {{if eq $g .}}selected{{end}}>{{.}}</option>{{end}}</select></td><td class="time-cell" data-label="Last Seen" data-relative-time="{{.LastSeenUnix}}">{{.TimeAgo}}</td>@@ -331,6 +319,7 @@ orangutan export out.csv</code></pre><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>+ <span class="legend-item clip-hint" id="clip-hint" hidden>Shortened values show in full on hover</span></div>{{if or .ContinuousScan .LastScanAt}}<span class="table-footer-label">@@ -373,13 +362,7 @@ orangutan export out.csv</code></pre><label>Group</label><select id="edit-group" name="group" class="select"><option value="">None</option>- <option value="Server">Server</option>- <option value="Desktop">Desktop</option>- <option value="Laptop">Laptop</option>- <option value="Mobile">Mobile</option>- <option value="IoT">IoT</option>- <option value="Network">Network</option>- <option value="Pi">Pi</option>+ {{range .Groups}}<option value="{{.}}">{{.}}</option>{{end}}</select></div><div class="form-group">diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.htmlindex d270848..954b05d 100644--- a/internal/web/templates/settings.html+++ b/internal/web/templates/settings.html@@ -233,6 +233,26 @@ orangutan export out.csv</code></pre></div></section>+ <section class="section">+ <h2 class="section-title">Device Groups</h2>+ <div class="card">+ <div class="form-group">+ <label>Your groups</label>+ <p class="form-help" style="margin-top: 0;">Rename a group to fit your own kit, or add ones that suit it better. Renaming updates every device already in that group. Deleting a group leaves its devices ungrouped, it never deletes a device.</p>+ <div id="group-list" class="group-list"></div>+ <div style="display: flex; gap: 0.5rem; margin-top: 0.75rem;">+ <input type="text" id="group-input" class="input" placeholder="e.g. Wearables" maxlength="32" style="width: 220px;" onkeydown="if(event.key==='Enter'){event.preventDefault();addGroup();}">+ <button class="btn" onclick="addGroup()">Add group</button>+ </div>+ </div>+ <div class="form-group" style="display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0;">+ <button class="btn" onclick="resetGroups()">Reset to defaults</button>+ <span id="groups-status" class="form-help" style="margin: 0;"></span>+ </div>+ <p class="form-help">Changes apply immediately. Saved to this instance, not your config file.</p>+ </div>+ </section>+<section class="section"><h2 class="section-title">Storage</h2><div class="card">@@ -609,6 +629,179 @@ orangutan export out.csv</code></pre>loadNetworks();+ // Device groups. The list is built with the DOM (textContent), never by+ // string-concatenating markup, so a group name can never inject anything.+ // Rename edits in place; delete asks first when devices would be affected.+ let groupCounts = {};++ function renderGroups(data) {+ groupCounts = data.counts || {};+ const el = document.getElementById('group-list');+ el.textContent = '';+ const groups = data.groups || [];+ if (groups.length === 0) {+ const none = document.createElement('span');+ none.className = 'form-help';+ none.style.margin = '0';+ none.textContent = 'No groups. Add one below, or reset to the defaults.';+ el.appendChild(none);+ return;+ }+ groups.forEach(name => el.appendChild(groupRow(name)));+ }++ function groupRow(name) {+ const row = document.createElement('div');+ row.className = 'group-row';++ const label = document.createElement('span');+ label.className = 'group-name';+ label.textContent = name;+ row.appendChild(label);++ const count = groupCounts[name] || 0;+ const meta = document.createElement('span');+ meta.className = 'group-count';+ meta.textContent = count === 1 ? '1 device' : count + ' devices';+ row.appendChild(meta);++ const actions = document.createElement('span');+ actions.className = 'group-actions';++ const rename = document.createElement('button');+ rename.type = 'button';+ rename.className = 'btn btn-sm';+ rename.textContent = 'Rename';+ rename.onclick = () => startRename(row, name);+ actions.appendChild(rename);++ const del = document.createElement('button');+ del.type = 'button';+ del.className = 'btn btn-sm danger';+ del.textContent = 'Delete';+ del.onclick = () => confirmDeleteGroup(row, name, count);+ actions.appendChild(del);++ row.appendChild(actions);+ return row;+ }++ // Rename in place: swap the row for an input seeded with the current+ // name, so the user edits the name rather than retyping it.+ function startRename(row, name) {+ row.textContent = '';+ const input = document.createElement('input');+ input.type = 'text';+ input.className = 'input';+ input.value = name;+ input.maxLength = 32;+ input.style.width = '220px';+ input.onkeydown = (e) => {+ if (e.key === 'Enter') { e.preventDefault(); commit(); }+ if (e.key === 'Escape') { e.preventDefault(); loadGroups(); }+ };+ row.appendChild(input);++ const save = document.createElement('button');+ save.type = 'button';+ save.className = 'btn btn-sm btn-primary';+ save.textContent = 'Save';+ save.onclick = commit;+ row.appendChild(save);++ const cancel = document.createElement('button');+ cancel.type = 'button';+ cancel.className = 'btn btn-sm';+ cancel.textContent = 'Cancel';+ cancel.onclick = () => loadGroups();+ row.appendChild(cancel);++ input.focus();+ input.select();++ function commit() {+ const next = input.value.trim();+ if (!next || next === name) { loadGroups(); return; }+ groupAction({ action: 'rename', name: name, new_name: next });+ }+ }++ // Deleting a group that devices are using is worth a confirm, since it+ // clears the group from all of them. An empty group just goes.+ function confirmDeleteGroup(row, name, count) {+ if (count === 0) {+ groupAction({ action: 'delete', name: name });+ return;+ }+ row.textContent = '';+ const msg = document.createElement('span');+ msg.className = 'group-name';+ msg.textContent = 'Remove "' + name + '" from ' + (count === 1 ? '1 device' : count + ' devices') + '?';+ row.appendChild(msg);++ const yes = document.createElement('button');+ yes.type = 'button';+ yes.className = 'btn btn-sm danger';+ yes.textContent = 'Delete group';+ yes.onclick = () => groupAction({ action: 'delete', name: name });+ row.appendChild(yes);++ const no = document.createElement('button');+ no.type = 'button';+ no.className = 'btn btn-sm';+ no.textContent = 'Cancel';+ no.onclick = () => loadGroups();+ row.appendChild(no);+ }++ function addGroup() {+ const input = document.getElementById('group-input');+ const v = input.value.trim();+ if (!v) return;+ groupAction({ action: 'add', name: v }, () => { input.value = ''; });+ }++ function resetGroups() {+ groupAction({ action: 'reset' });+ }++ async function loadGroups() {+ try {+ const res = await fetch('/api/groups').then(r => r.json());+ if (res.success) renderGroups(res.data);+ } catch (e) { /* leave empty if unreachable */ }+ }++ async function groupAction(body, onOk) {+ const status = document.getElementById('groups-status');+ try {+ const res = await fetch('/api/groups', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body)+ }).then(r => r.json());+ if (res.success) {+ renderGroups(res.data);+ if (onOk) onOk();+ status.textContent = 'Saved';+ status.style.color = 'var(--success)';+ } else {+ // The server rejected it (duplicate, empty, too long). Show+ // its message and put the list back the way it was.+ status.textContent = res.error || 'Could not save';+ status.style.color = 'var(--danger)';+ loadGroups();+ }+ } catch (e) {+ status.textContent = 'Could not save';+ status.style.color = 'var(--danger)';+ loadGroups();+ }+ setTimeout(() => { status.textContent = ''; }, 3500);+ }++ loadGroups();+// Backup / restore. Backup is a plain download link. Restore reads the// chosen file, shows an inline confirm (destructive), then POSTs it.let restoreData = null;