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.2.1
filebay9f2f30b6542f
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 412b784..07d1375 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -122,6 +122,12 @@ jobs:username: ${{ github.actor }}password: ${{ secrets.GITHUB_TOKEN }}+ - name: Login to Docker Hub+ uses: docker/login-action@v3+ with:+ username: ${{ secrets.DOCKERHUB_USERNAME }}+ password: ${{ secrets.DOCKERHUB_TOKEN }}+- name: Prepare image nameid: imagerun: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT@@ -139,6 +145,8 @@ jobs:tags: |${{ steps.image.outputs.name }}:${{ steps.version.outputs.VERSION }}${{ steps.image.outputs.name }}:latest+ docker.io/291group/lan-orangutan:${{ steps.version.outputs.VERSION }}+ docker.io/291group/lan-orangutan:latestrelease:needs: builddiff --git a/Dockerfile b/Dockerfileindex aa1cb8f..4da5b09 100644--- a/Dockerfile+++ b/Dockerfile@@ -29,7 +29,7 @@ RUN CGO_ENABLED=0 GOOS=linux go build \-o orangutan ./cmd/orangutan# Runtime stage-FROM alpine:3.19+FROM alpine:3.24# Install runtime dependenciesRUN apk add --no-cache nmap nmap-scripts ca-certificates tzdatadiff --git a/README.md b/README.mdindex 6b834ae..d26d4f2 100644--- a/README.md+++ b/README.md@@ -29,7 +29,7 @@ By [291 Group](https://291group.com)- Password protected, with a password you set the first time you open it<br>- Label, group, and add notes to devices<br>- Multi-network support<br>-- Tailscale integration - tailnet peers discovered automatically<br>+- Tailscale integration - connect, disconnect, and discover tailnet peers from inside the app<br>- Live scan progress you can cancel<br>- Modern web dashboard with light/dark mode<br>- Full CLI with JSON output<br>@@ -44,6 +44,14 @@ Grab the latest release of LAN Orangutan for your platform from [GitHub Releases### Docker+Pull the image from Docker Hub:++```bash+docker pull 291group/lan-orangutan+```++Or use the compose file for the full setup with host networking and a persistent data folder:+```bashcurl -O https://raw.githubusercontent.com/291-Group/LAN-Orangutan/main/docker-compose.ymldocker compose up -d@@ -51,6 +59,8 @@ docker compose up -dThen open `http://<that-machine>:291` and create a password. Your data is kept in a `data/` folder next to the compose file.+The image is published to both [Docker Hub](https://hub.docker.com/r/291group/lan-orangutan) (`291group/lan-orangutan`) and [GitHub Container Registry](https://github.com/291-Group/LAN-Orangutan/pkgs/container/lan-orangutan) (`ghcr.io/291-group/lan-orangutan`). The compose file uses GHCR; pull from whichever you prefer.+**Docker requires Linux.** The container uses host networking, because on Docker's own private network it would only ever see other containers (`172.17.0.0/16`) rather than the devices on your LAN. Docker Desktop on macOS and Windows runs Linux inside a virtual machine, so host networking attaches to that VM instead of your computer: the dashboard is unreachable and a scan finds nothing but the VM. On macOS and Windows, download the binary and run it directly, as described below.### Run@@ -169,6 +179,8 @@ Tailscale peers cannot be found by scanning, because Tailscale gives every nodeOnly peers that are currently online are listed, and they are shown with their Tailscale hostname and operating system. Peers have no MAC address, so no hardware vendor is looked up for them.+You can also control Tailscale from the app. The dashboard and settings pages show whether Tailscale is connected, with a button to connect or disconnect. If the machine still needs to sign in, the app shows you the sign-in link to open. Disconnecting warns you first, since you might be reaching the dashboard over Tailscale itself. This needs the Tailscale CLI on the machine running LAN Orangutan.+## SecurityLAN Orangutan listens on your network by default, because it is normally installed on a server or a Raspberry Pi and opened from another machine. To make that safe, it shows you nothing until a password exists.diff --git a/SECURITY.md b/SECURITY.mdindex b97f207..59e95c4 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -44,6 +44,8 @@ Worth understanding before you deploy it.**One shared password.** There are no user accounts, roles, or per-user permissions. Anyone with the password has full control.+**The app can control Tailscale.** An authenticated user can connect or disconnect this machine's tailnet from the dashboard, which runs `tailscale up` or `tailscale down` on the host. This is behind the same password and CSRF checks as everything else, but it is worth knowing that the shared password grants control over the machine's Tailscale connection, not just the device list.+**`allow_insecure` disables authentication completely.** It exists for people running behind a proxy that already handles access control. Setting it on an otherwise open network leaves your device list readable and writable by anyone.**Scanning needs elevated privileges to be useful.** Without `sudo` or Administrator, nmap cannot read the ARP table, so you get IP addresses without MAC addresses or vendor names. Running as root is a trade-off you are choosing; it is not required for the app to run.diff --git a/docs/DOCKERHUB.md b/docs/DOCKERHUB.mdnew file mode 100644index 0000000..5f6f78f--- /dev/null+++ b/docs/DOCKERHUB.md@@ -0,0 +1,177 @@+# 🦧 LAN Orangutan++**Self-hosted network discovery for homelabbers, with Tailscale support.**++Scan your networks, discover devices, label and track them, all from a clean web UI or CLI. One binary, almost no configuration, running in seconds.++By [291 Group](https://291group.com) · [GitHub](https://github.com/291-Group/LAN-Orangutan) · MIT licensed++<p align="center">+ <img src="https://raw.githubusercontent.com/291-Group/LAN-Orangutan/main/docs/LO1.png" width="48%" />+ <img src="https://raw.githubusercontent.com/291-Group/LAN-Orangutan/main/docs/LO2.png" width="48%" />+</p>++---++## ⚠️ Linux only++This image needs **host networking**, which means it only works on Linux.++Docker Desktop on macOS and Windows runs Linux inside a virtual machine. `network_mode: host` attaches to that VM, not your computer: the dashboard is unreachable, and the VM's gateway answers probes for addresses that do not exist, so a scan *looks* successful while reporting devices that were never there. No setting fixes this.++On macOS and Windows, [download the binary](https://github.com/291-Group/LAN-Orangutan/releases) and run it directly instead. It is a single file and takes one command.++LAN Orangutan detects this situation itself and warns at startup and on the dashboard, so results are never silently wrong.++| How you run it | Finds devices | MAC + manufacturer |+|---|---|---|+| **Docker on Linux, host networking** | **Yes** | **Yes** |+| Docker on Linux, bridge networking | No | No |+| Docker on macOS or Windows | No | No |++---++## Quick start++```bash+docker run -d \+ --name lan-orangutan \+ --network host \+ --cap-add NET_RAW --cap-add NET_ADMIN --cap-add NET_BIND_SERVICE \+ -v $(pwd)/data:/var/lib/lan-orangutan \+ --restart unless-stopped \+ 291group/lan-orangutan:latest+```++Then open `http://<that-machine>:291` and create a password. Nothing is reachable until you do. There is no default password and none is generated for you.++### docker compose++```bash+curl -O https://raw.githubusercontent.com/291-Group/LAN-Orangutan/main/docker-compose.yml+docker compose up -d+```++The published compose file pulls from GHCR. To use Docker Hub instead, change the `image:` line to `291group/lan-orangutan:latest`.++```yaml+services:+ lan-orangutan:+ image: 291group/lan-orangutan:latest+ container_name: lan-orangutan+ restart: unless-stopped+ network_mode: host+ cap_add:+ - NET_RAW+ - NET_ADMIN+ - NET_BIND_SERVICE+ environment:+ - ORANGUTAN_PORT=291+ - TZ=UTC+ volumes:+ - ./data:/var/lib/lan-orangutan+```++---++## Tags & architectures++| Tag | Meaning |+|---|---|+| `latest` | Most recent release |+| `3.1.4`, `3.1.3`, … | A specific release |++Built for **linux/amd64** and **linux/arm64** (multi-arch manifest, so Raspberry Pi 4/5 and other arm64 boards pull the right image automatically).++Also published to GHCR as `ghcr.io/291-group/lan-orangutan`. Identical images; pull from whichever you prefer.++---++## Configuration++Every setting can be supplied through the environment, which overrides the config file at `/etc/lan-orangutan/config.ini`.++| Variable | Purpose |+|---|---|+| `ORANGUTAN_PORT` | Port to listen on (default `291`) |+| `ORANGUTAN_BIND_ADDRESS` | Address to bind to |+| `ORANGUTAN_PASSWORD` | Set the password up front instead of on first open |+| `ORANGUTAN_PASSWORD_FILE` | Read the password from a file, e.g. a Docker secret (wins over the above) |+| `ORANGUTAN_SESSION_HOURS` | How long a login lasts (default one week) |+| `ORANGUTAN_ALLOW_INSECURE` | Skip password protection entirely |+| `ORANGUTAN_DATA_DIR` | Where devices and settings are stored (preset to `/var/lib/lan-orangutan`) |+| `ORANGUTAN_SCAN_INTERVAL` | Auto-scan interval in seconds |+| `ORANGUTAN_NETWORKS` | Extra networks to scan, comma separated |+| `ORANGUTAN_THEME` | `light`, `dark` or `auto` |+| `TZ` | Container timezone |++**Volume:** `/var/lib/lan-orangutan`: your device list, labels, notes and password hash. Without it, everything is lost when the container is recreated.++**Port:** `291` (under host networking this is taken directly from the host).++**Scanning networks that aren't detected.** LAN Orangutan finds networks by reading the machine's own interfaces, so a routed subnet or VLAN is never offered automatically. List them explicitly with `ORANGUTAN_NETWORKS=192.168.10.0/24,10.0.5.0/24`. Results for a routed network have no MAC addresses or manufacturer names, since those come from ARP and only work on the same segment.++---++## Features++- Auto-discovers devices with **nmap** (bundled in the image)+- Password protected, you set the password the first time you open it+- Label, group and add notes to devices+- Multi-network support+- **Tailscale integration**: connect, disconnect, and discover tailnet peers from inside the app+- Live scan progress you can cancel, with a time estimate+- Modern web dashboard, light/dark mode, keyboard shortcuts+- Full CLI with JSON output+- Export to CSV/JSON++### Tailscale++If Tailscale is connected, its online peers are added to your device list alongside the machines on your local networks. Peers are read from Tailscale directly rather than scanned, because Tailscale gives every node its own single-address network, so there is no range to sweep. Peers show their Tailscale hostname and OS; they have no MAC address, so no vendor is looked up. Controlling Tailscale from the dashboard requires the Tailscale CLI on the host.++---++## Security++- **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.+- **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).++### Why the container runs as root++nmap needs raw sockets to read the ARP table, which is what supplies MAC addresses and manufacturer names, and port 291 is privileged. Capabilities granted with `cap_add` land in the permitted set but never become effective for a process that starts as a non-root user, so running unprivileged meant the container could neither bind its port nor identify a single device. This is the same choice the systemd service makes. The container itself remains the isolation boundary.++---++## Image details++- Base: `alpine:3.24`, statically linked Go binary (`CGO_ENABLED=0`)+- Includes `nmap`, `nmap-scripts`, `ca-certificates`, `tzdata`+- Built-in `HEALTHCHECK` polling a public static asset over `127.0.0.1`, so it reports "is the server up" rather than "is it unlocked"+- Entrypoint `orangutan`, default command `serve`++Run any CLI command by overriding the command:++```bash+docker exec lan-orangutan orangutan list --format json+docker exec lan-orangutan orangutan status+docker exec lan-orangutan orangutan networks+```++---++## Philosophy++LAN Orangutan isn't trying to be the most powerful scanner out there, and that's the point. There are already excellent, deeply capable tools in this space, and they're the right choice when you need everything they offer. LAN Orangutan is for the other times, when you just want to scan a network now, without the setup and complexity heavier tools bring.++## Feedback++Bugs, problems and ideas: [open an issue](https://github.com/291-Group/LAN-Orangutan/issues).++---++Built with ❤️ by [291 Group](https://291group.com)diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex b2f4319..531aefa 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -105,6 +105,21 @@ Or change the port in your config file./Applications/Tailscale.app/Contents/MacOS/Tailscale status```+## Connect or disconnect button does nothing++The connect and disconnect buttons run the Tailscale CLI on the machine hosting+LAN Orangutan, so they need that CLI reachable, the same requirement as detection+above.++1. **Confirm the CLI works from that machine:** `tailscale status`. If it is not+ found, the buttons cannot work either.+2. **Connecting shows a sign-in link instead of connecting.** That is expected+ when the machine is not signed in yet. Open the link, finish signing in, then+ refresh the page.+3. **The disconnect warning is deliberate.** If you reach the dashboard over+ Tailscale, disconnecting cuts your own connection and you will need local+ access to bring it back.+## Rate limiting errorsIf you see "Rate limited" errors when scanning, wait 30 seconds between scans. This prevents overloading your network.diff --git a/go.mod b/go.modindex 23ad7b5..b5a853f 100644--- a/go.mod+++ b/go.mod@@ -1,6 +1,6 @@module github.com/291-Group/LAN-Orangutan-go 1.25.0+go 1.25.12require (github.com/spf13/cobra v1.10.2diff --git a/internal/api/api.go b/internal/api/api.goindex 18632ce..5758e3c 100644--- a/internal/api/api.go+++ b/internal/api/api.go@@ -77,6 +77,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {h.handleScanCancel(w, r)case path == "tailscale":h.handleTailscale(w, r)+ case path == "tailscale/connect":+ h.handleTailscaleConnect(w, r)+ case path == "tailscale/disconnect":+ h.handleTailscaleDisconnect(w, r)case path == "stats":h.handleStats(w, r)case path == "status":@@ -485,6 +489,39 @@ func (h *Handler) handleTailscale(w http.ResponseWriter, r *http.Request) {h.success(w, status)}+// handleTailscaleConnect handles POST /api/tailscale/connect.+//+// It is behind the same authentication and CSRF checks as every other mutating+// endpoint. A successful call may still report that the machine needs to sign+// in, in which case the response carries a login URL.+func (h *Handler) handleTailscaleConnect(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")+ return+ }++ result, err := network.ConnectTailscale()+ if err != nil {+ h.error(w, http.StatusServiceUnavailable, err.Error())+ return+ }+ h.success(w, result)+}++// handleTailscaleDisconnect handles POST /api/tailscale/disconnect.+func (h *Handler) handleTailscaleDisconnect(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")+ return+ }++ if err := network.DisconnectTailscale(); err != nil {+ h.error(w, http.StatusServiceUnavailable, err.Error())+ return+ }+ h.success(w, map[string]string{"message": "disconnected"})+}+// handleStats handles GET /api/statsfunc (h *Handler) handleStats(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {diff --git a/internal/cli/serve.go b/internal/cli/serve.goindex 11c105c..299a296 100644--- a/internal/cli/serve.go+++ b/internal/cli/serve.go@@ -106,8 +106,9 @@ func runServe(cmd *cobra.Command, args []string) error {// contains colons of its own and has to be bracketed.addr := net.JoinHostPort(bind, strconv.Itoa(port))server := &http.Server{- Addr: addr,- Handler: mux,+ Addr: addr,+ // guardHost wraps the mux to reject DNS rebinding when bound to loopback.+ Handler: guardHost(cfg.IsLoopbackBind(), mux),ReadTimeout: 30 * time.Second,WriteTimeout: 30 * time.Second,IdleTimeout: 60 * time.Second,@@ -213,6 +214,49 @@ func isAddrInUse(err error) bool {return errors.Is(err, syscall.EADDRINUSE)}+// guardHost rejects requests whose Host header is not a loopback identifier,+// but only when the server is bound to loopback.+//+// This closes a DNS rebinding vector. A malicious website can point its own+// hostname at 127.0.0.1 and, from the victim's browser, reach a dashboard bound+// to loopback that requires no password because it believed it was private.+// Such a request arrives with the attacker's hostname in the Host header, never+// a loopback address, so checking the Host turns it away.+//+// It applies to loopback binds only. On a network bind the Host is legitimately+// the server's LAN address or hostname, which cannot be enumerated here; that+// mode is protected instead by the password and the SameSite=Lax cookie, which+// a rebound cross-site request does not carry.+func guardHost(loopbackBind bool, next http.Handler) http.Handler {+ if !loopbackBind {+ return next+ }+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if !hostIsLoopback(r.Host) {+ http.Error(w, "forbidden: unexpected Host header", http.StatusForbidden)+ return+ }+ next.ServeHTTP(w, r)+ })+}++// hostIsLoopback reports whether an HTTP Host header names the local machine.+// The Host may carry a port and an IPv6 literal may be bracketed, both of which+// are stripped before the address is examined.+func hostIsLoopback(host string) bool {+ hostname := host+ if h, _, err := net.SplitHostPort(host); err == nil {+ hostname = h+ }+ hostname = strings.TrimPrefix(strings.TrimSuffix(hostname, "]"), "[")++ if strings.EqualFold(hostname, "localhost") {+ return true+ }+ ip := net.ParseIP(hostname)+ return ip != nil && ip.IsLoopback()+}+// listenNetwork picks the address family to listen on.//// Go treats "0.0.0.0" as a wildcard and answers it with a dual-stack IPv6diff --git a/internal/cli/serve_test.go b/internal/cli/serve_test.gonew file mode 100644index 0000000..7b0a546--- /dev/null+++ b/internal/cli/serve_test.go@@ -0,0 +1,84 @@+package cli++import (+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestHostIsLoopback(t *testing.T) {+ cases := []struct {+ host string+ want bool+ }{+ {"localhost", true},+ {"localhost:291", true},+ {"127.0.0.1", true},+ {"127.0.0.1:291", true},+ {"127.0.0.5:8080", true}, // all of 127.0.0.0/8 is loopback+ {"[::1]", true},+ {"[::1]:291", true},+ {"LocalHost:291", true}, // case-insensitive+ {"evil.com", false},+ {"evil.com:291", false},+ {"192.168.1.50:291", false}, // a LAN address is not loopback+ {"attacker.example:80", false},+ {"", false},+ }+ for _, c := range cases {+ if got := hostIsLoopback(c.host); got != c.want {+ t.Errorf("hostIsLoopback(%q) = %v, want %v", c.host, got, c.want)+ }+ }+}++func TestGuardHost_LoopbackBind(t *testing.T) {+ reached := false+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ reached = true+ w.WriteHeader(http.StatusOK)+ })+ guard := guardHost(true, next)++ // A loopback Host is allowed through.+ reached = false+ r := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:291/api/devices", nil)+ r.Host = "127.0.0.1:291"+ w := httptest.NewRecorder()+ guard.ServeHTTP(w, r)+ if !reached || w.Code != http.StatusOK {+ t.Fatalf("loopback Host should pass: reached=%v code=%d", reached, w.Code)+ }++ // A rebound attacker hostname is rejected before reaching the handler.+ reached = false+ r = httptest.NewRequest(http.MethodGet, "http://127.0.0.1:291/api/devices", nil)+ r.Host = "evil.example:291" // browser sends the attacker's domain+ w = httptest.NewRecorder()+ guard.ServeHTTP(w, r)+ if reached {+ t.Fatal("rebound Host reached the handler; DNS rebinding not blocked")+ }+ if w.Code != http.StatusForbidden {+ t.Fatalf("rebound Host should be 403, got %d", w.Code)+ }+}++func TestGuardHost_NetworkBindIsPassthrough(t *testing.T) {+ // On a network bind the Host is not checked: any hostname must pass, since+ // the server is legitimately reached by its LAN address or name.+ reached := false+ next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ reached = true+ w.WriteHeader(http.StatusOK)+ })+ guard := guardHost(false, next)++ r := httptest.NewRequest(http.MethodGet, "http://myserver.lan:291/", nil)+ r.Host = "myserver.lan:291"+ w := httptest.NewRecorder()+ guard.ServeHTTP(w, r)+ if !reached || w.Code != http.StatusOK {+ t.Fatalf("network bind should pass any Host: reached=%v code=%d", reached, w.Code)+ }+}diff --git a/internal/network/tailscale_control.go b/internal/network/tailscale_control.gonew file mode 100644index 0000000..7df28b0--- /dev/null+++ b/internal/network/tailscale_control.go@@ -0,0 +1,141 @@+package network++import (+ "bytes"+ "context"+ "fmt"+ "os/exec"+ "regexp"+ "strings"+ "sync"+ "time"+)++// tailscaleUpTimeout bounds how long we wait for `tailscale up`.+//+// A machine that is already signed in reconnects within a few seconds. One that+// needs to sign in prints a login URL almost immediately and then blocks+// waiting for the user to visit it, so this is only a safety net: the URL is+// detected and returned as soon as it appears, well before this fires.+const tailscaleUpTimeout = 20 * time.Second++// loginURLPattern matches the sign-in URL that `tailscale up` prints when the+// machine is not yet authenticated to a tailnet.+var loginURLPattern = regexp.MustCompile(`https://login\.tailscale\.com/\S+`)++// TailscaleActionResult describes the outcome of a connect attempt.+type TailscaleActionResult struct {+ // Connected is true when the machine is up on the tailnet.+ Connected bool `json:"connected"`+ // LoginURL is set when the machine must sign in before it can connect. The+ // user opens it themselves; the app does not automate browser auth.+ LoginURL string `json:"login_url,omitempty"`+}++// ConnectTailscale runs `tailscale up`.+//+// If the machine is already authenticated it simply reconnects. If it needs to+// sign in, Tailscale prints a login URL and then waits; that URL is captured+// and returned so the request does not block, and the user can open it and+// finish signing in.+func ConnectTailscale() (TailscaleActionResult, error) {+ bin := findTailscaleBinary()+ if bin == "" {+ return TailscaleActionResult{}, fmt.Errorf("tailscale is not installed")+ }++ ctx, cancel := context.WithTimeout(context.Background(), tailscaleUpTimeout)+ defer cancel()++ cmd := exec.CommandContext(ctx, bin, "up")+ var out syncBuffer+ cmd.Stdout = &out+ cmd.Stderr = &out++ if err := cmd.Start(); err != nil {+ return TailscaleActionResult{}, fmt.Errorf("could not run tailscale: %w", err)+ }++ done := make(chan error, 1)+ go func() { done <- cmd.Wait() }()++ // Poll the output. The login URL appears almost immediately when sign-in is+ // needed, so return it right away rather than waiting for the blocked+ // process to be killed at the timeout.+ ticker := time.NewTicker(200 * time.Millisecond)+ defer ticker.Stop()++ for {+ select {+ case err := <-done:+ text := out.String()+ if url := loginURLPattern.FindString(text); url != "" {+ return TailscaleActionResult{LoginURL: url}, nil+ }+ if err != nil {+ return TailscaleActionResult{}, fmt.Errorf("tailscale up failed: %s", firstLine(text, err))+ }+ return TailscaleActionResult{Connected: IsTailscaleConnected()}, nil++ case <-ticker.C:+ if url := loginURLPattern.FindString(out.String()); url != "" {+ cancel() // stop waiting; the user must sign in via the URL+ <-done // reap the process+ return TailscaleActionResult{LoginURL: url}, nil+ }+ }+ }+}++// DisconnectTailscale runs `tailscale down`, disconnecting the machine from its+// tailnet.+func DisconnectTailscale() error {+ bin := findTailscaleBinary()+ if bin == "" {+ return fmt.Errorf("tailscale is not installed")+ }++ ctx, cancel := context.WithTimeout(context.Background(), commandTimeout)+ defer cancel()++ out, err := exec.CommandContext(ctx, bin, "down").CombinedOutput()+ if err != nil {+ return fmt.Errorf("tailscale down failed: %s", firstLine(string(out), err))+ }+ return nil+}++// firstLine reduces command output to a single line for an error message,+// falling back to the error itself when there is no output.+func firstLine(output string, err error) string {+ output = strings.TrimSpace(output)+ if output == "" {+ if err != nil {+ return err.Error()+ }+ return "unknown error"+ }+ if i := strings.IndexByte(output, '\n'); i >= 0 {+ return strings.TrimSpace(output[:i])+ }+ return output+}++// syncBuffer is an io.Writer safe for the concurrent writes that os/exec makes+// from its output-copying goroutines while another goroutine reads it.+type syncBuffer struct {+ mu sync.Mutex+ buf bytes.Buffer+}++func (s *syncBuffer) Write(p []byte) (int, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.buf.Write(p)+}++func (s *syncBuffer) String() string {+ s.mu.Lock()+ defer s.mu.Unlock()+ return s.buf.String()+}diff --git a/internal/network/tailscale_control_test.go b/internal/network/tailscale_control_test.gonew file mode 100644index 0000000..7561d97--- /dev/null+++ b/internal/network/tailscale_control_test.go@@ -0,0 +1,94 @@+package network++import (+ "strings"+ "testing"+)++func TestLoginURLPattern(t *testing.T) {+ // The shape of the message tailscale prints when a machine must sign in.+ sample := `To authenticate, visit:++ https://login.tailscale.com/a/1234567890abcdef++Success.`+ got := loginURLPattern.FindString(sample)+ want := "https://login.tailscale.com/a/1234567890abcdef"+ if got != want {+ t.Errorf("extracted %q, want %q", got, want)+ }+}++func TestLoginURLPatternAbsentWhenConnected(t *testing.T) {+ // A normal reconnect prints no login URL.+ for _, s := range []string{"", "Success.", "some other output"} {+ if url := loginURLPattern.FindString(s); url != "" {+ t.Errorf("found a login URL in %q where there is none: %q", s, url)+ }+ }+}++func TestFirstLine(t *testing.T) {+ tests := []struct {+ output string+ want string+ }{+ {"single line", "single line"},+ {"first\nsecond\nthird", "first"},+ {" padded \nnext", "padded"},+ {"\n\nleading blanks\nmore", "leading blanks"},+ }+ for _, tt := range tests {+ if got := firstLine(tt.output, nil); got != tt.want {+ t.Errorf("firstLine(%q) = %q, want %q", tt.output, got, tt.want)+ }+ }+}++func TestFirstLineFallsBackToError(t *testing.T) {+ if got := firstLine("", errStub("boom")); got != "boom" {+ t.Errorf("with empty output, want the error text, got %q", got)+ }+ if got := firstLine("", nil); got != "unknown error" {+ t.Errorf("with no output and no error, got %q", got)+ }+}++type errStub string++func (e errStub) Error() string { return string(e) }++func TestControlRefusesWhenTailscaleMissing(t *testing.T) {+ // With no tailscale binary present, both actions must fail cleanly rather+ // than trying to run something.+ if findTailscaleBinary() != "" {+ t.Skip("tailscale is installed on this machine; skipping the missing-binary check")+ }++ if _, err := ConnectTailscale(); err == nil || !strings.Contains(err.Error(), "not installed") {+ t.Errorf("ConnectTailscale should report tailscale is not installed, got %v", err)+ }+ if err := DisconnectTailscale(); err == nil || !strings.Contains(err.Error(), "not installed") {+ t.Errorf("DisconnectTailscale should report tailscale is not installed, got %v", err)+ }+}++func TestSyncBufferConcurrentWrites(t *testing.T) {+ // The buffer is written by exec's copy goroutines while another goroutine+ // reads it, so writing and reading at once must not race. Run with -race.+ var b syncBuffer+ done := make(chan struct{})+ go func() {+ for i := 0; i < 1000; i++ {+ b.Write([]byte("x"))+ }+ close(done)+ }()+ for i := 0; i < 1000; i++ {+ _ = b.String()+ }+ <-done+ if len(b.String()) != 1000 {+ t.Errorf("expected 1000 bytes written, got %d", len(b.String()))+ }+}diff --git a/internal/storage/storage.go b/internal/storage/storage.goindex 5b45375..1395bf0 100644--- a/internal/storage/storage.go+++ b/internal/storage/storage.go@@ -149,23 +149,37 @@ func atomicWrite(path string, data []byte) error {return nil}-// GetDevices returns all devices+// GetDevices returns all devices.+//+// Each device is copied, not shared. A later scan merges results by mutating+// the stored structs in place, so handing out the live pointers would let a+// caller read a field while it is being written. The copies are snapshots the+// caller can read freely.func (s *Storage) GetDevices() map[string]*types.Device {s.mu.RLock()defer s.mu.RUnlock()result := make(map[string]*types.Device, len(s.devices))for k, v := range s.devices {- result[k] = v+ cp := *v+ result[k] = &cp}return result}-// GetDevice returns a single device by IP+// GetDevice returns a single device by IP, or nil if there is none.+//+// The returned device is a copy, for the same reason as GetDevices: the stored+// struct is mutated in place by later scans.func (s *Storage) GetDevice(ip string) *types.Device {s.mu.RLock()defer s.mu.RUnlock()- return s.devices[ip]+ d, ok := s.devices[ip]+ if !ok {+ return nil+ }+ cp := *d+ return &cp}// UpdateDevice updates or creates a devicediff --git a/internal/storage/storage_concurrency_test.go b/internal/storage/storage_concurrency_test.gonew file mode 100644index 0000000..14753dc--- /dev/null+++ b/internal/storage/storage_concurrency_test.go@@ -0,0 +1,48 @@+package storage++import (+ "path/filepath"+ "sync"+ "testing"++ "github.com/291-Group/LAN-Orangutan/internal/types"+)++// TestConcurrentReadDuringMerge guards against the data race where a reader of+// GetDevices touches device fields while a scan merge mutates the same structs.+// It must stay race-clean: run the package with -race.+func TestConcurrentReadDuringMerge(t *testing.T) {+ dir := t.TempDir()+ s, err := New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))+ if err != nil {+ t.Fatal(err)+ }+ if err := s.MergeDevices([]types.Device{{IP: "10.0.0.1", Hostname: "a"}}); err != nil {+ t.Fatal(err)+ }++ const iterations = 2000+ var wg sync.WaitGroup++ // Reader: mimic the web handler reading fields after GetDevices returns.+ wg.Add(1)+ go func() {+ defer wg.Done()+ for i := 0; i < iterations; i++ {+ for _, d := range s.GetDevices() {+ _ = d.Hostname + d.MAC + d.Vendor+ }+ }+ }()++ // Writer: mimic a scan merging new data for the same IP.+ wg.Add(1)+ go func() {+ defer wg.Done()+ for i := 0; i < iterations; i++ {+ _ = s.MergeDevices([]types.Device{{IP: "10.0.0.1", Hostname: "bbbbbbbb", MAC: "cc", Vendor: "dd"}})+ }+ }()++ wg.Wait()+}diff --git a/internal/web/static/app.js b/internal/web/static/app.jsindex 93454ac..7e86ce9 100644--- a/internal/web/static/app.js+++ b/internal/web/static/app.js@@ -645,3 +645,59 @@ function updateRelativeTimes() {updateRelativeTimes();setInterval(updateRelativeTimes, 30000);++// --- Tailscale control ------------------------------------------------++// connectTailscale brings the machine up on its tailnet.+//+// If the machine still needs to sign in, the server returns a login URL+// instead of connecting, which is shown as a link rather than trying to+// automate the browser sign-in.+async function connectTailscale() {+ const msg = document.getElementById('tailscale-message');+ if (msg) msg.textContent = 'Connecting...';+ try {+ const result = await api('tailscale/connect', {}, 'POST');+ const data = result.data || {};++ if (data.login_url) {+ if (msg) {+ // Build the link with the DOM rather than innerHTML so the URL+ // cannot inject markup.+ msg.textContent = 'Tailscale needs you to sign in: ';+ const a = document.createElement('a');+ a.href = data.login_url;+ a.target = '_blank';+ a.rel = 'noopener';+ a.textContent = 'open sign in';+ msg.appendChild(a);+ msg.appendChild(document.createTextNode('. Finish it, then refresh this page.'));+ }+ return;+ }++ showToast('Tailscale connected', 'success');+ setTimeout(() => location.reload(), 1000);+ } catch (e) {+ if (msg) msg.textContent = '';+ showToast('Could not connect: ' + e.message, 'error');+ }+}++// disconnectTailscale takes the machine off its tailnet, after warning that+// this can cut the connection the user is reaching the dashboard through.+async function disconnectTailscale() {+ const warning =+ 'Disconnect Tailscale?\n\n' ++ 'If you are reaching this dashboard over Tailscale, disconnecting will ' ++ 'cut your connection and you will need local access to reconnect.';+ if (!confirm(warning)) return;++ try {+ await api('tailscale/disconnect', {}, 'POST');+ showToast('Tailscale disconnected', 'warning');+ setTimeout(() => location.reload(), 1000);+ } catch (e) {+ showToast('Could not disconnect: ' + e.message, 'error');+ }+}diff --git a/internal/web/static/style.css b/internal/web/static/style.cssindex a3e2524..ff7b504 100644--- a/internal/web/static/style.css+++ b/internal/web/static/style.css@@ -1311,3 +1311,22 @@ img.login-logo {text-overflow: ellipsis;white-space: nowrap;}++/* Tailscale connect/disconnect */+.tailscale-actions {+ margin-top: 1rem;+ display: flex;+ gap: 0.5rem;+}++/* Feedback line under the Tailscale buttons: the sign-in link, or an error. */+.tailscale-message {+ margin-top: 0.75rem;+ font-size: 0.85rem;+ color: var(--text-secondary);+ line-height: 1.4;+}++.tailscale-message:empty {+ display: none;+}diff --git a/internal/web/templates/index.html b/internal/web/templates/index.htmlindex 9f28988..024e1ec 100644--- a/internal/web/templates/index.html+++ b/internal/web/templates/index.html@@ -115,6 +115,17 @@<span class="label">Not connected</span></div>{{end}}++ {{if .Tailscale.Installed}}+ <div class="tailscale-actions">+ {{if .Tailscale.Connected}}+ <button class="btn btn-sm" onclick="disconnectTailscale()">Disconnect</button>+ {{else}}+ <button class="btn btn-sm btn-primary" onclick="connectTailscale()">Connect</button>+ {{end}}+ </div>+ <div id="tailscale-message" class="tailscale-message"></div>+ {{end}}</div></div>{{end}}diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.htmlindex a2ac252..e507eeb 100644--- a/internal/web/templates/settings.html+++ b/internal/web/templates/settings.html@@ -81,6 +81,19 @@<span class="status-value">{{.Tailscale.PeerCount}}</span></div>{{end}}++ {{if .Tailscale.Installed}}+ <div class="form-group" style="margin-top: 1rem;">+ {{if .Tailscale.Connected}}+ <button class="btn btn-primary" onclick="disconnectTailscale()">Disconnect</button>+ <p class="form-help">Disconnects this machine from your tailnet.</p>+ {{else}}+ <button class="btn btn-primary" onclick="connectTailscale()">Connect</button>+ <p class="form-help">Connects this machine to your tailnet.</p>+ {{end}}+ <div id="tailscale-message" class="tailscale-message"></div>+ </div>+ {{end}}</div></section>