Skip to content

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

v3.1.3

filebay181ef2854dd8
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..ff3b42a
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,24 @@
+# Keep the build context small and reproducible.
+.git
+.github
+.gitignore
+.DS_Store
+
+# Build output
+bin/
+orangutan
+*.exe
+
+# Local data and editor state
+data/
+*.log
+.claude/
+.vscode/
+.idea/
+
+# Docs and packaging that the image does not need
+docs/
+snap/
+systemd/
+*.md
+!README.md
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ad47733..3972ba7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -10,7 +10,7 @@ on:
branches: [main, master]
jobs:
- go-lint:
+ build:
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -27,67 +27,50 @@ jobs:
- name: Vet
run: go vet ./...
- - name: Test
- run: go test -v ./...
+ - name: Check formatting
+ run: |
+ unformatted=$(gofmt -l .)
+ if [ -n "$unformatted" ]; then
+ echo "These files need gofmt:"
+ echo "$unformatted"
+ exit 1
+ fi
- legacy-lint:
+ test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- - name: Setup Python
- uses: actions/setup-python@v5
+ - name: Set up Go
+ uses: actions/setup-go@v5
with:
- python-version: '3.11'
+ go-version: '1.22'
- - name: Lint Python
- run: |
- pip install flake8
- flake8 scanner/*.py --max-line-length=120 --ignore=E501,W503
+ - name: Test
+ run: go test -v -race ./...
- - name: Check shell scripts
- run: |
- sudo apt-get install -y shellcheck
- shellcheck install.sh uninstall.sh scripts/*.sh || true
+ shellcheck:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
- - name: Validate PHP syntax
+ - name: Check shell scripts
run: |
- php -l web/*.php || true
+ sudo apt-get update && sudo apt-get install -y shellcheck
+ shellcheck install.sh uninstall.sh scripts/*.sh
- test:
+ docker:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- - name: Set up Go
- uses: actions/setup-go@v5
- with:
- go-version: '1.22'
+ # The Docker image is the primary install route, so a broken Dockerfile
+ # should fail the build rather than be discovered at release time.
+ - name: Build image
+ run: docker build -t lan-orangutan:ci .
- - name: Go tests
- run: go test -v ./...
-
- - name: Setup Python
- uses: actions/setup-python@v5
- with:
- python-version: '3.11'
-
- - name: Test Python imports
- run: |
- cd scanner
- python3 -c "import scan; import utils"
-
- - name: Test CIDR validation
- run: |
- cd scanner
- python3 -c "
- from scan import is_valid_cidr
- assert is_valid_cidr('192.168.1.0/24') == True
- assert is_valid_cidr('10.0.0.0/8') == True
- assert is_valid_cidr('256.0.0.0/24') == False
- assert is_valid_cidr('192.168.1.0/33') == False
- assert is_valid_cidr('invalid') == False
- print('All CIDR validation tests passed')
- "
+ - name: Check the binary runs in the image
+ run: docker run --rm lan-orangutan:ci version
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index e0b8d9d..2cf9056 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -105,6 +105,10 @@ jobs:
context: .
platforms: linux/amd64,linux/arm64
push: true
+ build-args: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ COMMIT=${{ github.sha }}
+ BUILD_DATE=${{ github.event.repository.updated_at }}
tags: |
${{ steps.image.outputs.name }}:${{ steps.version.outputs.VERSION }}
${{ steps.image.outputs.name }}:latest
@@ -171,32 +175,33 @@ jobs:
echo "=== Final dist/ contents ==="
ls -la
- - name: Create legacy archive (for install.sh compatibility)
+ # Bundle for the install.sh route: the binaries for each Linux
+ # architecture, the service unit and the installer. Previous releases also
+ # shipped a separate Python and PHP implementation here; that has been
+ # removed, and install.sh now installs the binary.
+ - name: Create install archive
run: |
VERSION=${{ steps.version.outputs.VERSION }}
ARCHIVE_NAME="lan-orangutan-${VERSION}"
- # Create clean directory for legacy release
mkdir -p "dist/${ARCHIVE_NAME}"
- # Copy release files (for backwards compatibility with install.sh)
- cp -r scanner dist/${ARCHIVE_NAME}/
- cp -r web dist/${ARCHIVE_NAME}/
- cp -r cli dist/${ARCHIVE_NAME}/
- cp -r scripts dist/${ARCHIVE_NAME}/
- cp -r systemd dist/${ARCHIVE_NAME}/
- cp install.sh dist/${ARCHIVE_NAME}/
- cp uninstall.sh dist/${ARCHIVE_NAME}/
- cp config.example.ini dist/${ARCHIVE_NAME}/
- cp README.md dist/${ARCHIVE_NAME}/
- cp LICENSE dist/${ARCHIVE_NAME}/ 2>/dev/null || true
-
- # Also include the Go binary
- cp dist/orangutan-linux-amd64 dist/${ARCHIVE_NAME}/ 2>/dev/null || true
-
- # Create tarball
+ cp -r systemd "dist/${ARCHIVE_NAME}/"
+ cp install.sh "dist/${ARCHIVE_NAME}/"
+ cp uninstall.sh "dist/${ARCHIVE_NAME}/"
+ cp config.example.ini "dist/${ARCHIVE_NAME}/"
+ cp README.md "dist/${ARCHIVE_NAME}/"
+ cp SECURITY.md "dist/${ARCHIVE_NAME}/"
+ cp LICENSE "dist/${ARCHIVE_NAME}/" 2>/dev/null || true
+ chmod +x "dist/${ARCHIVE_NAME}/install.sh" "dist/${ARCHIVE_NAME}/uninstall.sh"
+
+ # install.sh picks the one matching the machine it runs on.
+ for arch in amd64 arm64 arm; do
+ cp "dist/orangutan-linux-${arch}" "dist/${ARCHIVE_NAME}/"
+ done
+
cd dist
- tar -czvf "${ARCHIVE_NAME}.tar.gz" "${ARCHIVE_NAME}"
+ tar -czf "${ARCHIVE_NAME}.tar.gz" "${ARCHIVE_NAME}"
rm -rf "${ARCHIVE_NAME}"
- name: Build .deb package
diff --git a/Dockerfile b/Dockerfile
index 6800a74..9de5798 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -13,8 +13,20 @@ RUN go mod download
# Copy source
COPY . .
+# Version details, supplied by the release workflow. Without these the image
+# reports whatever it can work out from the repository, which for a build
+# context with no .git means "unknown".
+ARG VERSION=""
+ARG COMMIT=""
+ARG BUILD_DATE=""
+
# Build binary
-RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o orangutan ./cmd/orangutan
+RUN CGO_ENABLED=0 GOOS=linux go build \
+ -ldflags="-s -w \
+ -X 'github.com/291-Group/LAN-Orangutan/internal/cli.Version=${VERSION}' \
+ -X 'github.com/291-Group/LAN-Orangutan/internal/cli.Commit=${COMMIT}' \
+ -X 'github.com/291-Group/LAN-Orangutan/internal/cli.BuildDate=${BUILD_DATE}'" \
+ -o orangutan ./cmd/orangutan
# Runtime stage
FROM alpine:3.19
@@ -22,12 +34,9 @@ FROM alpine:3.19
# Install runtime dependencies
RUN apk add --no-cache nmap nmap-scripts ca-certificates tzdata
-# Create non-root user
-RUN addgroup -S orangutan && adduser -S orangutan -G orangutan
# Create directories
-RUN mkdir -p /etc/lan-orangutan /var/lib/lan-orangutan \
- && chown -R orangutan:orangutan /var/lib/lan-orangutan
+RUN mkdir -p /etc/lan-orangutan /var/lib/lan-orangutan
# Copy binary from builder
COPY --from=builder /app/orangutan /usr/local/bin/orangutan
@@ -36,15 +45,34 @@ COPY config.example.ini /etc/lan-orangutan/config.ini
# Set permissions
RUN chmod +x /usr/local/bin/orangutan
+# The app resolves its data directory from the running user's home, which for
+# this non-root user would not be the volume mounted by docker-compose. Pin it
+# so the mount and the app agree; otherwise data silently vanishes on restart.
+ENV ORANGUTAN_DATA_DIR=/var/lib/lan-orangutan
+
# Expose port
EXPOSE 291
-# Run as non-root (but nmap needs NET_RAW capability)
-USER orangutan
+# Runs as root inside the container.
+#
+# This is the same choice the systemd service makes, and for the same reason:
+# 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 here meant
+# the container could neither bind its port nor identify a single device.
+#
+# The container itself remains the isolation boundary.
-# Health check
+# Health check.
+#
+# Targets a static asset over 127.0.0.1: it is served without authentication and
+# returns 200 in every state (before setup, after a password is set, signed out),
+# so the check reflects "is the server up" rather than "is it unlocked". Uses
+# 127.0.0.1 rather than localhost because the server binds IPv4 and localhost can
+# resolve to IPv6 ::1.
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
- CMD wget --no-verbose --tries=1 --spider http://localhost:291/api/status || exit 1
+ CMD wget --no-verbose --tries=1 --spider http://127.0.0.1:291/static/orangutan.svg || exit 1
ENTRYPOINT ["orangutan"]
CMD ["serve"]
diff --git a/Makefile b/Makefile
index 7890574..a609ec4 100644
--- a/Makefile
+++ b/Makefile
@@ -50,6 +50,10 @@ build-windows: build-windows-amd64
build-windows-amd64:
GOOS=windows GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-windows-amd64.exe ./cmd/orangutan
+# Refresh the embedded MAC vendor database from the IEEE registry
+oui:
+ ./scripts/gen-oui.sh
+
# Run tests
test:
go test -v ./...
@@ -110,6 +114,7 @@ help:
@echo " build-windows - Build for Windows (amd64)"
@echo ""
@echo " test - Run tests"
+ @echo " oui - Refresh the MAC vendor database"
@echo " lint - Run linter"
@echo " fmt - Format code"
@echo " tidy - Tidy dependencies"
diff --git a/README.md b/README.md
index 5bbc63f..eac7707 100644
--- a/README.md
+++ b/README.md
@@ -24,6 +24,7 @@ By [291 Group](https://291group.com)
## 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>
- Multi-network support<br>
- Tailscale integration - tailnet peers discovered automatically<br>
@@ -39,6 +40,17 @@ 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).
+### Docker
+
+```bash
+curl -O https://raw.githubusercontent.com/291-Group/LAN-Orangutan/main/docker-compose.yml
+docker compose up -d
+```
+
+Then open `http://<that-machine>:291` and create a password. Your data is kept in a `data/` folder next to the compose file.
+
+**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
```bash
@@ -49,7 +61,41 @@ sudo ./orangutan serve
orangutan.exe serve
```
-Open `http://localhost:291` in your browser.
+Open `http://localhost:291` in your browser, or `http://<that-machine>:291` from another computer on your network.
+
+The first time you open it, LAN Orangutan asks you to create a password. Nothing else is reachable until you do. That is the whole setup.
+
+### Upgrading from an earlier version
+
+If you installed LAN Orangutan with `install.sh` before this release, you were running a Python and PHP version of the app from `/opt/lan-orangutan`. Running the new `install.sh` replaces it with the single Go binary at `/usr/local/bin/orangutan` and removes that old directory.
+
+**Your config and your device list are kept.** Nothing in `/etc/lan-orangutan` or `/var/lib/lan-orangutan` is touched.
+
+Two things change that you will notice:
+
+- The dashboard now asks you to create a password the first time you open it after upgrading. Until you do, nothing else is reachable.
+- PHP and Python are no longer needed. You can remove them if you installed them only for LAN Orangutan.
+
+Upgrading through a package (`.deb`, `.rpm`, `.apk`) or Docker needs nothing extra, since those already ran the Go binary.
+
+## What works where
+
+Discovery needs to see your real network. How you run LAN Orangutan decides whether it can.
+
+| How you run it | Finds devices | MAC + manufacturer | Notes |
+|---|---|---|---|
+| Binary, Linux, with `sudo` | Yes | Yes | Everything works |
+| Binary, macOS, with `sudo` | Yes | Yes | Everything works |
+| Binary, Windows, as Administrator | Yes | Yes | Everything works |
+| Binary, any OS, without `sudo` | Yes | No | IP addresses and hostnames only |
+| `.deb` / `.rpm` / `.apk` package | Yes | Yes | Runs as a root service |
+| **Docker on Linux, host networking** | **Yes** | **Yes** | The supported Docker setup |
+| Docker on Linux, bridge networking | No | No | Sees only other containers |
+| **Docker on macOS or Windows** | **No** | **No** | **Not supported, see below** |
+
+**Why Docker on macOS and Windows does not work.** Docker Desktop runs Linux inside a virtual machine. The container never touches your real network, and the virtual machine's gateway answers probes on behalf of addresses that do not exist, so a scan appears to succeed while reporting devices that were never there. That is worse than finding nothing, because the result looks convincing. There is no setting that fixes this. Run the binary directly instead; it is a single file and takes one command.
+
+LAN Orangutan detects this situation itself. If it cannot reach a real network it says so at startup and puts a warning on the dashboard, so results are never silently wrong.
## Requirements
@@ -69,6 +115,8 @@ sudo orangutan scan all # Scan all detected networks
# Start web server
sudo orangutan serve # Default port 291
sudo orangutan serve --port 8080 # Custom port
+sudo orangutan serve --bind 127.0.0.1 # This machine only, no password needed
+sudo orangutan serve --allow-insecure # No password at all (see Security)
# List devices
orangutan list # List all devices
@@ -80,6 +128,8 @@ orangutan export devices.csv # Export to CSV
# Check status
orangutan status # Show system status
+orangutan config # Show settings in effect
+orangutan networks # Show detected networks
orangutan version # Show version info
```
@@ -117,6 +167,48 @@ Tailscale peers cannot be found by scanning, because Tailscale gives every node
Only 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.
+## Security
+
+LAN 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.
+
+**First run.** Opening the dashboard presents a "create a password" screen. Until you finish it, every page and every API endpoint is refused. There is no default password and none is generated for you. What you choose is stored as a bcrypt hash in a file readable only by its owner, never in plain text, and separately from your config file so setup never rewrites a file you maintain by hand.
+
+**Signing in.** After that you sign in with that password and stay signed in for a week by default. Sign out is in the header. Five wrong guesses lock that address out for fifteen minutes.
+
+**Keeping it private instead.** Set `bind_address = 127.0.0.1` and the dashboard is only reachable from the machine it runs on. No password is asked for, because nobody else can reach it.
+
+**Setting the password in advance.** Useful for Docker and automated installs:
+
+```bash
+ORANGUTAN_PASSWORD=your-password orangutan serve
+
+# or keep the secret out of the environment
+ORANGUTAN_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.
+
+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.
+
+### Scanning a network that is not detected
+
+LAN Orangutan finds networks by reading this machine's own interfaces. A subnet reachable through a router, or a VLAN, has no local interface and so is never offered. List those explicitly:
+
+```bash
+ORANGUTAN_NETWORKS=192.168.10.0/24,10.0.5.0/24 orangutan serve
+```
+
+or in the config file:
+
+```ini
+[scanning]
+networks = 192.168.10.0/24, 10.0.5.0/24
+```
+
+They appear on the dashboard alongside the detected ones and can be scanned the same way. Results for a routed network have no MAC addresses or manufacturer names, because those come from ARP and only work on the same network segment.
+
+This is not a way to make Docker work on macOS or Windows. There the container runs inside a virtual machine whose NAT answers probes on its own, so a scan reports devices that do not exist.
+
## Configuration
Config file location:
@@ -124,15 +216,34 @@ Config file location:
- macOS: `~/Library/Application Support/lan-orangutan/config.ini`
- Windows: `%APPDATA%\lan-orangutan\config.ini`
-See `config.example.ini` for available options.
+See `config.example.ini` for available options, and run `orangutan config` to print the settings actually in effect.
+
+Every setting can also be supplied through the environment, which is usually easier in Docker. These override the config file.
+
+| Variable | Purpose |
+|---|---|
+| `ORANGUTAN_PORT` | Port to listen on |
+| `ORANGUTAN_BIND_ADDRESS` | Address to bind to |
+| `ORANGUTAN_PASSWORD` | Set the password directly |
+| `ORANGUTAN_PASSWORD_FILE` | Read the password from a file (wins over the above) |
+| `ORANGUTAN_SESSION_HOURS` | How long a login lasts |
+| `ORANGUTAN_ALLOW_INSECURE` | Skip password protection |
+| `ORANGUTAN_DATA_DIR` | Where devices and settings are stored |
+| `ORANGUTAN_SCAN_INTERVAL` | Auto-scan interval in seconds |
+| `ORANGUTAN_NETWORKS` | Extra networks to scan, comma separated (see below) |
+| `ORANGUTAN_THEME` | `light`, `dark` or `auto` |
## Building from Source
```bash
git clone https://github.com/291-Group/LAN-Orangutan.git
cd LAN-Orangutan
-go build -o orangutan ./cmd/orangutan
+make build # builds to bin/orangutan with version details baked in
```
+
+`go build -o orangutan ./cmd/orangutan` also works. It reports the commit it was built from rather than a release number, since there is no tag to read.
+
+Run the tests with `make test`.
## Philosophy
LAN Orangutan isn't trying to be the most powerful scanner out there, and that's the point. It's built to be the simplest and fastest one to reach for.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..b97f207
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,57 @@
+# Security Policy
+
+LAN Orangutan scans your network and stores a record of what it finds, so it is worth being clear about what it does, what it does not do, and how to report a problem.
+
+## Reporting a vulnerability
+
+Please report security issues privately rather than opening a public issue.
+
+- Use [GitHub's private vulnerability reporting](https://github.com/291-Group/LAN-Orangutan/security/advisories/new)
+
+Please include what you found, how to reproduce it, and what an attacker could do with it. We will acknowledge your report within a few days and keep you updated while we work on a fix.
+
+Please do not test against networks or devices you do not own or have permission to scan.
+
+## Supported versions
+
+Fixes are released for the most recent version. Older releases are not patched, unless otherwise stated by 291 Group.
+
+## How access is protected
+
+**The dashboard listens on your network by default.** LAN Orangutan is normally installed on a server or a Raspberry Pi and opened from another machine, so restricting it to the local machine would break the usual setup.
+
+**Nothing is reachable until a password exists.** On first run, every page and every API endpoint refuses the request and sends you to a page that creates a password. There is no default password, and none is generated for you.
+
+**Passwords are stored hashed.** bcrypt, in a file readable only by its owner, kept separately from your config file so that completing setup never rewrites a file you maintain by hand. A password supplied through the config file or the environment may be given as plain text or as a bcrypt hash.
+
+**Sessions** are random 256-bit tokens held in memory, sent as an `HttpOnly` cookie with `SameSite=Lax`, and marked `Secure` when served over HTTPS. Signing out invalidates the session on the server, not just in the browser. Sessions are lost on restart, so everyone signs in again. Setting a new password invalidates all existing sessions.
+
+**Repeated failed logins** are limited to five per address per fifteen minutes, keyed on the address rather than the connection, so reconnecting does not reset the count.
+
+**Mutating API requests** must present a JSON content type or an `X-Requested-With` header, so a form on another site cannot make your browser change your data.
+
+## Known limitations
+
+Worth understanding before you deploy it.
+
+**No HTTPS.** Traffic between your browser and LAN Orangutan is unencrypted, including your password at sign-in. On a home network this is usually accepted. If it is not acceptable for you, put it behind a reverse proxy that terminates TLS, or reach it over Tailscale or a VPN.
+
+**It does not open a port on your router.** LAN Orangutan contains no UPnP or NAT-PMP code and makes no outbound connections at all, so it cannot ask your router to expose it. Behind a normal home router, a machine on your LAN is not reachable from the internet unless you deliberately forward a port.
+
+**Two situations where it would be reachable from the internet.** Running it on a machine that already has a public address, such as a VPS or cloud instance, publishes it the moment it starts. And a machine with a globally routable IPv6 address may be reachable directly, because IPv6 usually has no NAT: whether it is depends on your router's IPv6 firewall. `bind_address = 0.0.0.0` listens on IPv4 only, so IPv6 is not published unless you ask for it with `bind_address = ::`. In either case the setup screen still stands in the way, but do not rely on that alone on a public host: set a password up front with `ORANGUTAN_PASSWORD`, or bind to loopback and reach it over a VPN.
+
+**Whoever opens it first sets the password.** Between the server starting and someone completing setup, anyone who can reach it could claim it. On a home network the window is small and this is the same trade-off Home Assistant and Portainer make, but on an untrusted network you should set `ORANGUTAN_PASSWORD` in advance instead.
+
+**One shared password.** There are no user accounts, roles, or per-user permissions. Anyone with the password has full control.
+
+**`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.
+
+**Your data is not encrypted at rest.** The device list is plain JSON in the data directory. It records what is on your network, when it was seen, and any labels or notes you add. Protect that directory as you would any other private file.
+
+## What LAN Orangutan does not do
+
+- It does not phone home, send telemetry, or contact any external service
+- It does not require an account or an internet connection
+- Vendor lookups are done from a list built into the binary, not by querying an online service
diff --git a/cli/orangutan b/cli/orangutan
deleted file mode 100755
index 6014e70..0000000
--- a/cli/orangutan
+++ /dev/null
@@ -1,201 +0,0 @@
-#!/bin/bash
-set -e
-
-INSTALL_DIR="/opt/lan-orangutan"
-CONFIG_FILE="/etc/lan-orangutan/config.ini"
-DATA_DIR="/var/lib/lan-orangutan"
-SCANNER="$INSTALL_DIR/scanner/scan.py"
-SERVICE_NAME="lan-orangutan"
-
-RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; BLUE='\033[0;34m'; NC='\033[0m'
-
-if [[ ! -f "$SCANNER" ]]; then
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
- SCANNER="$SCRIPT_DIR/scanner/scan.py"
- CONFIG_FILE="$SCRIPT_DIR/config.example.ini"
- DATA_DIR="/tmp/lan-orangutan"
-fi
-
-cmd_scan() {
- local network="${1:-all}"
- if [[ "$network" == "all" ]]; then
- echo -e "${BLUE}→${NC} Scanning all networks..."
- python3 -c "
-import sys; sys.path.insert(0, '$(dirname "$SCANNER")')
-from utils import detect_networks
-for n in detect_networks(): print(n['cidr'])
-" | while read cidr; do
- [[ -n "$cidr" ]] && { echo -e "${BLUE}→${NC} Scanning $cidr..."; python3 "$SCANNER" "$cidr" 2>/dev/null || true; }
- done
- echo -e "${GREEN}✓${NC} Scan complete"
- else
- echo -e "${BLUE}→${NC} Scanning $network..."
- python3 "$SCANNER" "$network"
- fi
-}
-
-cmd_list() {
- local filter="" group_filter=""
- while [[ $# -gt 0 ]]; do
- case "$1" in
- --online) filter="online"; shift ;;
- --offline) filter="offline"; shift ;;
- --group=*) group_filter="${1#*=}"; shift ;;
- *) shift ;;
- esac
- done
- python3 << PYTHON
-import json, os
-from datetime import datetime, timedelta
-devices_file = "$DATA_DIR/devices.json"
-if not os.path.exists(devices_file):
- print("No devices found. Run 'orangutan scan' first.")
- exit(0)
-with open(devices_file) as f:
- data = json.load(f)
-devices = data.get('devices', {})
-if not devices:
- print("No devices found.")
- exit(0)
-now = datetime.now()
-one_hour_ago = now - timedelta(hours=1)
-print(f"{'STATUS':<8} {'IP ADDRESS':<16} {'HOSTNAME':<25} {'MAC ADDRESS':<18} {'VENDOR':<15} {'LABEL':<15}")
-print("-" * 110)
-def ip_sort_key(item):
- try:
- parts = item[0].split('.')
- if len(parts) == 4:
- return tuple(int(p) for p in parts)
- except (ValueError, AttributeError):
- pass
- return (999, 999, 999, 999) # Sort malformed IPs last
-for ip, dev in sorted(devices.items(), key=ip_sort_key):
- last_seen = dev.get('last_seen', '')
- status = 'offline'
- if last_seen:
- try:
- seen = datetime.fromisoformat(last_seen.replace('Z', '+00:00'))
- if seen.tzinfo: seen = seen.replace(tzinfo=None)
- if seen > one_hour_ago: status = 'online'
- except ValueError: pass
- filter_val = "$filter"
- if filter_val and filter_val != status: continue
- group_val = "$group_filter"
- if group_val and dev.get('group', '').lower() != group_val.lower(): continue
- color = '\033[0;32m' if status == 'online' else '\033[0;90m'
- reset = '\033[0m'
- hostname = dev.get('hostname', '-')[:24]
- mac = dev.get('mac', '-')
- vendor = dev.get('vendor', 'Unknown')[:14]
- label = dev.get('label', '')[:14]
- print(f"{color}{'●':<8}{reset} {ip:<16} {hostname:<25} {mac:<18} {vendor:<15} {label:<15}")
-PYTHON
-}
-
-cmd_status() {
- echo "=== LAN Orangutan Status ==="
- if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
- echo -e "${GREEN}✓${NC} Service: Running"
- else
- echo -e "${YELLOW}!${NC} Service: Not running"
- fi
- if [[ -f "$CONFIG_FILE" ]]; then
- port=$(grep "^port" "$CONFIG_FILE" 2>/dev/null | cut -d= -f2 | tr -d ' ' || echo "291")
- echo -e "${BLUE}→${NC} Port: $port"
- fi
- if [[ -f "$DATA_DIR/devices.json" ]]; then
- count=$(python3 -c "import json; print(len(json.load(open('$DATA_DIR/devices.json')).get('devices',{})))" 2>/dev/null || echo "0")
- echo -e "${BLUE}→${NC} Devices: $count"
- fi
- if command -v tailscale &>/dev/null && tailscale status &>/dev/null; then
- echo -e "${GREEN}✓${NC} Tailscale: Connected"
- fi
-}
-
-cmd_logs() { journalctl -u "$SERVICE_NAME" -n "${1:-50}" --no-pager; }
-cmd_config() { [[ -f "$CONFIG_FILE" ]] && cat "$CONFIG_FILE" || echo "Config not found"; }
-cmd_networks() {
- echo -e "${BLUE}→${NC} Detected networks:"
- python3 -c "
-import sys; sys.path.insert(0, '$(dirname "$SCANNER")')
-from utils import detect_networks
-for n in detect_networks():
- ts = ' [Tailscale]' if n.get('is_tailscale') else ''
- print(f\" {n['friendly_name']}: {n['cidr']} ({n['interface']}){ts}\")
-"
-}
-
-cmd_export() {
- local output="${1:-devices.csv}"
-
- # Validate output path - prevent path traversal
- local realpath_output
- realpath_output=$(realpath -m "$output" 2>/dev/null) || {
- echo -e "${RED}✗${NC} Invalid output path"
- exit 1
- }
-
- # Get current working directory realpath
- local cwd_realpath
- cwd_realpath=$(realpath "$(pwd)")
-
- # Ensure output is within current directory or /tmp
- if [[ "$realpath_output" != "$cwd_realpath"/* ]] && [[ "$realpath_output" != /tmp/* ]]; then
- echo -e "${RED}✗${NC} Output path must be within current directory or /tmp"
- exit 1
- fi
-
- python3 << PYTHON
-import json, csv, os
-devices_file = "$DATA_DIR/devices.json"
-if not os.path.exists(devices_file):
- print("No devices to export")
- exit(1)
-with open(devices_file) as f:
- data = json.load(f)
-devices = data.get('devices', {})
-output_path = '''$realpath_output'''
-with open(output_path, 'w', newline='') as f:
- writer = csv.writer(f)
- writer.writerow(['IP', 'Hostname', 'MAC', 'Vendor', 'Label', 'Group', 'First Seen', 'Last Seen'])
- for ip, dev in sorted(devices.items()):
- writer.writerow([ip, dev.get('hostname',''), dev.get('mac',''), dev.get('vendor',''),
- dev.get('label',''), dev.get('group',''), dev.get('first_seen',''), dev.get('last_seen','')])
-print(f"Exported {len(devices)} devices to {output_path}")
-PYTHON
-}
-
-cmd_help() {
- cat << EOF
-🦧 LAN Orangutan CLI
-
-Usage: orangutan <command> [options]
-
-Commands:
- scan [network] Scan network (CIDR) or 'all'
- list [options] List devices (--online, --offline, --group=X)
- status Show service status
- logs [n] Show last n log lines
- config Show configuration
- networks List detected networks
- export <file> Export to CSV
- help Show this help
-
-Examples:
- orangutan scan 192.168.1.0/24
- orangutan list --online
- orangutan export devices.csv
-EOF
-}
-
-case "${1:-help}" in
- scan) shift; cmd_scan "$@" ;;
- list) shift; cmd_list "$@" ;;
- status) cmd_status ;;
- logs) shift; cmd_logs "$@" ;;
- config) cmd_config ;;
- networks) cmd_networks ;;
- export) shift; cmd_export "$@" ;;
- help|--help|-h) cmd_help ;;
- *) echo -e "${RED}✗${NC} Unknown command: $1"; cmd_help; exit 1 ;;
-esac
diff --git a/config.example.ini b/config.example.ini
index 1615917..2ec8a93 100644
--- a/config.example.ini
+++ b/config.example.ini
@@ -8,9 +8,37 @@
# Port to listen on (default: 291)
port = 291
-# Address to bind to (default: 0.0.0.0 = all interfaces)
+# Address to bind to (default: 0.0.0.0 = reachable from your network).
+#
+# The default lets you open the dashboard from another machine, which is how
+# most people use it. The first time you visit, LAN Orangutan asks you to
+# create a password, and nothing else is reachable until you do.
+#
+# Set this to 127.0.0.1 to keep the dashboard private to the machine it runs
+# on. In that case no password is asked for, since nobody else can reach it.
bind_address = 0.0.0.0
+# 0.0.0.0 listens on IPv4 only. Use :: if you also want IPv6, but note that
+# IPv6 addresses are often reachable from the internet directly, because there
+# is usually no NAT in the way.
+
+# Password for the dashboard and API.
+#
+# You do not need to set this. Leave it empty and you will be asked to create
+# a password the first time you open the dashboard, which is stored separately
+# so this file is never rewritten.
+#
+# Setting it here overrides that. Plain text or a bcrypt hash both work.
+# password =
+
+# How long a login stays valid, in hours (default: 168 = one week)
+session_hours = 168
+
+# Skip password protection entirely, even when reachable from the network.
+# Only turn this on if something else already controls who can reach this
+# machine, such as a reverse proxy that handles authentication.
+allow_insecure = false
+
# Enable REST API endpoints
enable_api = true
@@ -27,6 +55,19 @@ enable_port_scan = false
# Port range to scan when port scanning is enabled
port_scan_range = 1-1024
+# Networks to scan, in addition to the ones detected automatically.
+#
+# Detection reads this machine's own network interfaces, which is not always
+# what you want: a subnet reachable through a router, or a VLAN, has no local
+# interface and so is never offered. List those here.
+#
+# networks = 192.168.10.0/24, 10.0.5.0/24
+#
+# This does NOT make Docker work on macOS or Windows. There the container runs
+# inside a virtual machine whose NAT answers probes itself, so a scan reports
+# devices that do not exist. Run LAN Orangutan natively on those platforms.
+# networks =
+
[storage]
# Maximum number of devices to track
max_devices = 1000
@@ -51,3 +92,20 @@ auto_detect = true
[ui]
# Theme: light, dark, or auto (follows system preference)
theme = auto
+
+# ---------------------------------------------------------------------------
+# Environment variables
+#
+# Every setting above can also be supplied through the environment, which is
+# usually easier in Docker. Environment variables override this file.
+#
+# ORANGUTAN_PORT ORANGUTAN_PASSWORD
+# ORANGUTAN_BIND_ADDRESS ORANGUTAN_PASSWORD_FILE
+# ORANGUTAN_SESSION_HOURS ORANGUTAN_ALLOW_INSECURE
+# ORANGUTAN_DATA_DIR ORANGUTAN_SCAN_INTERVAL
+# ORANGUTAN_THEME
+#
+# ORANGUTAN_PASSWORD_FILE points at a file containing the password, so the
+# secret never appears in the process environment. It wins over
+# ORANGUTAN_PASSWORD if both are set.
+# ---------------------------------------------------------------------------
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..e0f603f
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,62 @@
+# LAN Orangutan - Docker Compose
+#
+# SUPPORTED ON LINUX ONLY.
+#
+# Docker Desktop on macOS and Windows runs Linux inside a virtual machine. The
+# container never reaches your real network, and the virtual machine's gateway
+# answers probes for addresses that do not exist, so a scan looks successful
+# while reporting devices that were never there. No setting changes this.
+# On macOS and Windows, download the binary and run it directly instead.
+#
+# LAN Orangutan detects this and warns at startup and on the dashboard, but it
+# is better not to get there in the first place.
+
+services:
+ lan-orangutan:
+ image: ghcr.io/291-group/lan-orangutan:latest
+ container_name: lan-orangutan
+ restart: unless-stopped
+
+ # Scanning needs to see your real network, not Docker's private one. On a
+ # bridge network the container only ever discovers other containers
+ # (172.17.0.0/16), never the devices on your LAN. Host networking is what
+ # makes discovery work, and it means the port below is taken directly from
+ # the host.
+ #
+ # This requires Linux. Docker Desktop on macOS and Windows runs Linux inside
+ # a virtual machine, so "host" is that VM rather than your computer: the
+ # dashboard is unreachable and scanning sees only the VM's network. Run
+ # LAN Orangutan natively on those platforms instead.
+ network_mode: host
+
+ # nmap needs raw sockets to read the ARP table, which is what supplies MAC
+ # addresses and manufacturer names. NET_RAW is granted to a root container
+ # by default, but Docker's default set is easy to restrict, so it is listed
+ # explicitly. NET_ADMIN is not in the default set and helps some scan modes;
+ # NET_BIND_SERVICE covers the privileged port 291 under host networking.
+ cap_add:
+ - NET_RAW
+ - NET_ADMIN
+ - NET_BIND_SERVICE
+
+ environment:
+ # Leave the password unset and you will be asked to create one the first
+ # time you open the dashboard. Set it here instead if you would rather
+ # decide up front.
+ # - ORANGUTAN_PASSWORD=change-me
+ - ORANGUTAN_PORT=291
+ - TZ=UTC
+
+ volumes:
+ # Your device list, labels and password live here. Without this, they are
+ # lost every time the container is recreated.
+ - ./data:/var/lib/lan-orangutan
+
+ healthcheck:
+ # A static asset over 127.0.0.1: public, always 200, and IPv4 (the server
+ # binds IPv4, and localhost can resolve to IPv6 ::1).
+ test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:291/static/orangutan.svg"]
+ interval: 30s
+ timeout: 3s
+ start_period: 5s
+ retries: 3
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index f79e81a..4952262 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -133,5 +133,5 @@ sudo firewall-cmd --reload
```bash
orangutan version
orangutan status
-curl http://localhost:291/
+curl http://localhost:291/setup
```
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index b3bb744..b2f4319 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -87,6 +87,9 @@ Or change the port in your config file.
```bash
# Allow external access
orangutan serve --bind 0.0.0.0
+
+ This is the default. The first visit asks you to create a password, so the
+ dashboard is not left open on your network.
```
## Tailscale not detected
diff --git a/go.mod b/go.mod
index ad8ee31..9f65646 100644
--- a/go.mod
+++ b/go.mod
@@ -2,7 +2,10 @@ module github.com/291-Group/LAN-Orangutan
go 1.22
-require github.com/spf13/cobra v1.10.2
+require (
+ github.com/spf13/cobra v1.10.2
+ golang.org/x/crypto v0.31.0
+)
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
diff --git a/go.sum b/go.sum
index a6ee3e0..ff9fcb2 100644
--- a/go.sum
+++ b/go.sum
@@ -7,4 +7,6 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
+golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/install.sh b/install.sh
index 1030239..5fa962d 100755
--- a/install.sh
+++ b/install.sh
@@ -1,61 +1,83 @@
#!/bin/bash
+#
+# Installs LAN Orangutan from a release archive.
+#
+# This installs the single Go binary. Earlier versions installed a Python and
+# PHP application into /opt/lan-orangutan; if that is present it is removed,
+# because the two cannot both own the service and the `orangutan` command.
set -e
-INSTALL_DIR="/opt/lan-orangutan"
+BIN_PATH="/usr/local/bin/orangutan"
CONFIG_DIR="/etc/lan-orangutan"
DATA_DIR="/var/lib/lan-orangutan"
+LEGACY_DIR="/opt/lan-orangutan"
SERVICE_NAME="lan-orangutan"
DEFAULT_PORT=291
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; BLUE='\033[0;34m'; NC='\033[0m'
echo ""
-echo -e "${YELLOW}🦧 LAN Orangutan Installer${NC}"
+echo -e "${YELLOW}LAN Orangutan Installer${NC}"
echo "================================"
echo ""
[[ $EUID -ne 0 ]] && { echo -e "${RED}✗${NC} Run as root (sudo)"; exit 1; }
# Check OS
+# shellcheck disable=SC1091
source /etc/os-release 2>/dev/null || { echo -e "${RED}✗${NC} Cannot detect OS"; exit 1; }
case "$ID" in
ubuntu|debian|raspbian) echo -e "${GREEN}✓${NC} OS: $PRETTY_NAME" ;;
*) echo -e "${RED}✗${NC} Unsupported OS: $ID (need Ubuntu/Debian/Raspbian)"; exit 1 ;;
esac
-# Check/install dependencies
+# Dependencies. The binary is self-contained, so nmap is the only requirement.
echo -e "${BLUE}→${NC} Checking dependencies..."
-
-if ! command -v python3 &>/dev/null; then
- echo -e "${YELLOW}!${NC} Installing Python3..."
- apt-get update -qq && apt-get install -y python3
-fi
-echo -e "${GREEN}✓${NC} Python $(python3 --version | cut -d' ' -f2)"
-
-if ! command -v php &>/dev/null; then
- echo -e "${YELLOW}!${NC} Installing PHP..."
- apt-get update -qq && apt-get install -y php-cli php-json
-fi
-echo -e "${GREEN}✓${NC} PHP $(php -v | head -n1 | cut -d' ' -f2)"
-
if ! command -v nmap &>/dev/null; then
echo -e "${YELLOW}!${NC} Installing nmap..."
apt-get update -qq && apt-get install -y nmap
fi
echo -e "${GREEN}✓${NC} nmap installed"
+# Locate the binary shipped alongside this script.
+SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ARCH="$(uname -m)"
+case "$ARCH" in
+ x86_64|amd64) BIN_NAME="orangutan-linux-amd64" ;;
+ aarch64|arm64) BIN_NAME="orangutan-linux-arm64" ;;
+ armv7l|armhf) BIN_NAME="orangutan-linux-arm" ;;
+ *) echo -e "${RED}✗${NC} Unsupported architecture: $ARCH"; exit 1 ;;
+esac
+
+SOURCE_BIN=""
+for candidate in "$SOURCE_DIR/$BIN_NAME" "$SOURCE_DIR/orangutan"; do
+ [[ -f "$candidate" ]] && { SOURCE_BIN="$candidate"; break; }
+done
+
+NEW_VERSION=""
+if [[ -n "$SOURCE_BIN" ]]; then
+ NEW_VERSION="$("$SOURCE_BIN" version 2>/dev/null | head -1 | sed 's/^LAN Orangutan //')"
+fi
+
+if [[ -z "$SOURCE_BIN" ]]; then
+ echo -e "${RED}✗${NC} Could not find the orangutan binary next to this script."
+ echo " Expected $BIN_NAME or orangutan in $SOURCE_DIR"
+ echo " Download the release for your platform from:"
+ echo " https://github.com/291-Group/LAN-Orangutan/releases"
+ exit 1
+fi
+
# Select port
PORT=$DEFAULT_PORT
if ss -tuln | grep -q ":$PORT "; then
echo -e "${YELLOW}!${NC} Port $PORT in use"
echo "Select alternative: 1) 2910 2) 8090 3) Custom"
- read -p "Choice [1-3]: " choice
+ read -r -p "Choice [1-3]: " choice
case "$choice" in
1) PORT=2910 ;;
2) PORT=8090 ;;
3)
- read -p "Port: " PORT
- # Validate custom port is a number between 1-65535
+ read -r -p "Port: " PORT
if [[ ! "$PORT" =~ ^[0-9]+$ ]] || [[ "$PORT" -lt 1 ]] || [[ "$PORT" -gt 65535 ]]; then
echo -e "${YELLOW}!${NC} Invalid port '$PORT', using 2910"
PORT=2910
@@ -66,30 +88,43 @@ if ss -tuln | grep -q ":$PORT "; then
fi
echo -e "${GREEN}✓${NC} Using port: $PORT"
-# Install files
-SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-echo -e "${BLUE}→${NC} Installing to $INSTALL_DIR..."
-
-mkdir -p "$INSTALL_DIR" "$CONFIG_DIR" "$DATA_DIR"
-cp -r "$SOURCE_DIR/scanner" "$INSTALL_DIR/"
-cp -r "$SOURCE_DIR/web" "$INSTALL_DIR/"
-cp -r "$SOURCE_DIR/cli" "$INSTALL_DIR/"
-cp -r "$SOURCE_DIR/scripts" "$INSTALL_DIR/"
-
-chmod +x "$INSTALL_DIR/cli/orangutan"
-chmod +x "$INSTALL_DIR/scripts/start-server.sh"
-chmod +x "$INSTALL_DIR/scanner/scan.py"
-ln -sf "$INSTALL_DIR/cli/orangutan" /usr/local/bin/orangutan
+# Remove a previous Python/PHP installation. Its files are never read by the
+# binary, and leaving them behind means two things claiming the same service.
+if [[ -d "$LEGACY_DIR" ]]; then
+ echo -e "${BLUE}→${NC} Removing the previous installation in $LEGACY_DIR..."
+ systemctl stop "$SERVICE_NAME" 2>/dev/null || true
+ rm -rf "$LEGACY_DIR"
+ echo -e "${GREEN}✓${NC} Old installation removed (your config and data are kept)"
+fi
-echo -e "${GREEN}✓${NC} Files installed"
+if [[ -x "$BIN_PATH" ]]; then
+ OLD_VERSION="$("$BIN_PATH" version 2>/dev/null | head -1 | sed 's/^LAN Orangutan //')"
+ echo -e "${BLUE}→${NC} Upgrading ${OLD_VERSION:-unknown} to ${NEW_VERSION:-unknown}..."
+else
+ echo -e "${BLUE}→${NC} Installing ${NEW_VERSION:-unknown}..."
+fi
+mkdir -p "$CONFIG_DIR" "$DATA_DIR"
+install -m 755 "$SOURCE_BIN" "$BIN_PATH"
+echo -e "${GREEN}✓${NC} Installed $BIN_PATH ($("$BIN_PATH" version 2>/dev/null | head -1 | sed 's/^LAN Orangutan //'))"
-# Create config
-cat > "$CONFIG_DIR/config.ini" << EOF
+# Create config, but never overwrite one the user already has.
+if [[ -f "$CONFIG_DIR/config.ini" ]]; then
+ echo -e "${GREEN}✓${NC} Keeping your existing config"
+else
+ cat > "$CONFIG_DIR/config.ini" << EOF
[server]
port = $PORT
+# Reachable from your network. The first time you open the dashboard you will
+# be asked to create a password; nothing is reachable until you do.
+# Set bind_address to 127.0.0.1 instead to keep it to this machine only.
bind_address = 0.0.0.0
enable_api = true
+# Optional: set a password here to skip the first-run setup screen.
+# password =
+session_hours = 168
+allow_insecure = false
+
[scanning]
scan_interval = 300
min_scan_interval = 30
@@ -106,11 +141,12 @@ auto_detect = true
[ui]
theme = auto
EOF
-echo -e "${GREEN}✓${NC} Config created"
+ echo -e "${GREEN}✓${NC} Config created"
+fi
# Firewall
if command -v ufw &>/dev/null && ufw status | grep -q "active"; then
- read -p "Configure ufw for port $PORT? [y/N]: " fw
+ read -r -p "Configure ufw for port $PORT? [y/N]: " fw
[[ "$fw" =~ ^[Yy]$ ]] && { ufw allow "$PORT/tcp"; echo -e "${GREEN}✓${NC} Firewall configured"; }
fi
@@ -118,7 +154,7 @@ fi
cp "$SOURCE_DIR/systemd/lan-orangutan.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
-systemctl start "$SERVICE_NAME"
+systemctl restart "$SERVICE_NAME"
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
@@ -132,12 +168,14 @@ IP=$(ip route get 1.1.1.1 2>/dev/null | grep -oP 'src \K\S+' || hostname -I | aw
echo ""
echo "========================================"
-echo -e "${GREEN}🦧 LAN Orangutan installed!${NC}"
+echo -e "${GREEN}LAN Orangutan ${NEW_VERSION:-} installed!${NC}"
echo "========================================"
echo ""
echo -e "Web UI: ${BLUE}http://$IP:$PORT${NC}"
echo ""
+echo "You will be asked to create a password the first time you open it."
+echo ""
echo "CLI: orangutan scan all"
echo " orangutan list"
-echo " orangutan help"
+echo " orangutan --help"
echo ""
diff --git a/internal/api/api.go b/internal/api/api.go
index b46137f..18632ce 100644
--- a/internal/api/api.go
+++ b/internal/api/api.go
@@ -3,9 +3,11 @@ package api
import (
"context"
+ "encoding/csv"
"encoding/json"
"errors"
"net/http"
+ "sort"
"strings"
"sync"
"time"
@@ -94,9 +96,52 @@ func (h *Handler) handleDevices(w http.ResponseWriter, r *http.Request) {
}
devices := h.store.GetDevices()
+
+ if r.URL.Query().Get("format") == "csv" {
+ h.writeDevicesCSV(w, devices)
+ return
+ }
+
h.success(w, devices)
}
+// writeDevicesCSV sends the device list as a downloadable CSV file.
+//
+// The columns match `orangutan export`, so a file saved from the browser and
+// one saved from the command line are interchangeable.
+func (h *Handler) writeDevicesCSV(w http.ResponseWriter, devices map[string]*types.Device) {
+ sorted := make([]*types.Device, 0, len(devices))
+ for _, d := range devices {
+ sorted = append(sorted, d)
+ }
+ sort.Slice(sorted, func(i, j int) bool { return sorted[i].IP < sorted[j].IP })
+
+ // Set before writing: headers are ignored once the body has started.
+ w.Header().Set("Content-Type", "text/csv; charset=utf-8")
+ w.Header().Set("Content-Disposition", `attachment; filename="devices.csv"`)
+
+ cw := csv.NewWriter(w)
+ defer cw.Flush()
+
+ _ = cw.Write([]string{
+ "IP Address", "MAC Address", "Hostname", "Vendor", "Label",
+ "Notes", "Group", "First Seen", "Last Seen", "Status",
+ })
+
+ for _, d := range sorted {
+ status := "offline"
+ if d.IsOnline() {
+ status = "online"
+ }
+ _ = cw.Write([]string{
+ d.IP, d.MAC, d.Hostname, scanner.ResolveVendor(d.Vendor, d.MAC), d.Label, d.Notes, d.Group,
+ d.FirstSeen.Format("2006-01-02 15:04:05"),
+ d.LastSeen.Format("2006-01-02 15:04:05"),
+ status,
+ })
+ }
+}
+
// handleDevice handles GET/POST/DELETE /api/device
func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {
switch r.Method {
@@ -170,7 +215,7 @@ func (h *Handler) handleNetworks(w http.ResponseWriter, r *http.Request) {
h.error(w, http.StatusInternalServerError, err.Error())
return
}
- h.success(w, networks)
+ h.success(w, network.WithConfigured(networks, h.cfg.Scanning.Networks))
}
// handleScan handles GET /api/scan
@@ -259,6 +304,7 @@ type scanAllResult struct {
// so one bad interface cannot mask results from the others.
func (h *Handler) scanAllNetworks(w http.ResponseWriter, r *http.Request) {
detected, err := network.DetectNetworks()
+ detected = network.WithConfigured(detected, h.cfg.Scanning.Networks)
if err != nil {
h.error(w, http.StatusInternalServerError, "failed to detect networks: "+err.Error())
return
@@ -317,6 +363,7 @@ func (h *Handler) resolveScanTargets(cidr string) ([]string, error) {
}
detected, err := network.DetectNetworks()
+ detected = network.WithConfigured(detected, h.cfg.Scanning.Networks)
if err != nil {
return nil, errors.New("failed to detect networks: " + err.Error())
}
diff --git a/internal/auth/auth.go b/internal/auth/auth.go
new file mode 100644
index 0000000..1acbc0b
--- /dev/null
+++ b/internal/auth/auth.go
@@ -0,0 +1,424 @@
+// Package auth provides password protection for the web UI and API.
+//
+// A fresh install has no password. When the server is reachable from the
+// network, the first visitor is sent to a setup page and must create one before
+// anything else is shown. After that, a login form exchanges the password for a
+// session cookie, and every other request must present that cookie.
+//
+// When the server is bound to loopback only, or the operator has explicitly
+// opted out, no password is required at all.
+package auth
+
+import (
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ // SessionCookie is the name of the cookie holding the session token.
+ SessionCookie = "orangutan_session"
+
+ // These paths are reachable without a session.
+ LoginPath = "/login"
+ LogoutPath = "/logout"
+ SetupPath = "/setup"
+
+ // MinPasswordLength is the shortest password the setup page accepts.
+ MinPasswordLength = 8
+
+ // MaxPasswordBytes is bcrypt's own limit. Anything longer is rejected by
+ // the library, so it is checked here in order to explain it in plain terms
+ // rather than surfacing "bcrypt: password length exceeds 72 bytes".
+ MaxPasswordBytes = 72
+
+ // maxAttempts is how many failed logins an address may make within
+ // attemptWindow before it is locked out for the rest of the window.
+ maxAttempts = 5
+ attemptWindow = 15 * time.Minute
+ sessionIDBytes = 32
+)
+
+// Authenticator guards HTTP handlers with a password.
+//
+// The zero value is not usable; construct one with New.
+type Authenticator struct {
+ mu sync.Mutex
+
+ // hash is the bcrypt hash of the current password. Empty means no password
+ // has been set yet.
+ hash []byte
+
+ // setupRequired means that, with no password set, visitors should be sent
+ // to the setup page rather than let straight through.
+ setupRequired bool
+
+ // sessionTTL is how long a session stays valid after login.
+ sessionTTL time.Duration
+
+ sessions map[string]time.Time // token -> expiry
+ attempts map[string]*attemptRecord
+}
+
+type attemptRecord struct {
+ count int
+ // resets is when the count returns to zero.
+ resets time.Time
+}
+
+// New creates an Authenticator.
+//
+// password may be either a plaintext password or an existing bcrypt hash, so
+// callers can pass a stored hash straight through. An empty password leaves the
+// Authenticator unconfigured, ready for either setup or open access.
+func New(password string, sessionTTL time.Duration) (*Authenticator, error) {
+ a := &Authenticator{
+ sessionTTL: sessionTTL,
+ sessions: make(map[string]time.Time),
+ attempts: make(map[string]*attemptRecord),
+ }
+
+ if password == "" {
+ return a, nil
+ }
+
+ hash, err := hashOrPassthrough(password)
+ if err != nil {
+ return nil, err
+ }
+ a.hash = hash
+ return a, nil
+}
+
+// hashOrPassthrough returns password unchanged if it is already a bcrypt hash,
+// and otherwise hashes it.
+func hashOrPassthrough(password string) ([]byte, error) {
+ if isBcryptHash(password) {
+ return []byte(password), nil
+ }
+ return bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+}
+
+// isBcryptHash reports whether s looks like a bcrypt hash rather than a
+// plaintext password.
+func isBcryptHash(s string) bool {
+ return strings.HasPrefix(s, "$2a$") ||
+ strings.HasPrefix(s, "$2b$") ||
+ strings.HasPrefix(s, "$2y$")
+}
+
+// Enabled reports whether a password is currently set.
+func (a *Authenticator) Enabled() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return len(a.hash) > 0
+}
+
+// SetSetupRequired controls what happens when no password is set: either
+// visitors are sent to the setup page, or they are let through untouched.
+func (a *Authenticator) SetSetupRequired(required bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.setupRequired = required
+}
+
+// NeedsSetup reports whether the user still has to create a password.
+func (a *Authenticator) NeedsSetup() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.setupRequired && len(a.hash) == 0
+}
+
+// SetPassword establishes a new password and returns its hash so the caller can
+// persist it. It is used both by first-run setup and by later password changes.
+func (a *Authenticator) SetPassword(plaintext string) (string, error) {
+ if err := ValidatePassword(plaintext); err != nil {
+ return "", err
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(plaintext), bcrypt.DefaultCost)
+ if err != nil {
+ return "", err
+ }
+
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.hash = hash
+ // Any session issued while there was no password predates this one and
+ // should not survive it.
+ a.sessions = make(map[string]time.Time)
+
+ return string(hash), nil
+}
+
+// ValidatePassword reports whether a proposed password is acceptable.
+func ValidatePassword(password string) error {
+ if len(password) < MinPasswordLength {
+ return fmt.Errorf("password must be at least %d characters", MinPasswordLength)
+ }
+ // len() counts bytes, which is what bcrypt limits. Accented and non-Latin
+ // characters take more than one byte each, so say so.
+ if len(password) > MaxPasswordBytes {
+ return fmt.Errorf(
+ "password is too long: the limit is %d characters, and accented or non-Latin characters count as more than one",
+ MaxPasswordBytes)
+ }
+ return nil
+}
+
+// Middleware wraps next so that requests without a valid session are turned
+// away.
+//
+// The decision is made per request rather than once at startup, because a
+// password can come into existence partway through the process's life, when the
+// user completes setup.
+func (a *Authenticator) Middleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case a.NeedsSetup():
+ a.reject(w, r, SetupPath, "setup required")
+
+ case !a.Enabled():
+ // No password, and none required. Open access.
+ next.ServeHTTP(w, r)
+
+ case a.authenticated(r):
+ next.ServeHTTP(w, r)
+
+ default:
+ a.reject(w, r, LoginPath, "authentication required")
+ }
+ })
+}
+
+// reject turns away an unauthenticated request: JSON for the API, a redirect
+// for anything a browser is displaying.
+func (a *Authenticator) reject(w http.ResponseWriter, r *http.Request, redirectTo, reason string) {
+ if strings.HasPrefix(r.URL.Path, "/api/") {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ json.NewEncoder(w).Encode(map[string]any{
+ "success": false,
+ "error": reason,
+ })
+ return
+ }
+
+ http.Redirect(w, r, redirectTo, http.StatusSeeOther)
+}
+
+// authenticated reports whether r carries a valid, unexpired session cookie.
+func (a *Authenticator) authenticated(r *http.Request) bool {
+ cookie, err := r.Cookie(SessionCookie)
+ if err != nil || cookie.Value == "" {
+ return false
+ }
+
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ expiry, ok := a.sessions[cookie.Value]
+ if !ok {
+ return false
+ }
+ if time.Now().After(expiry) {
+ delete(a.sessions, cookie.Value)
+ return false
+ }
+ return true
+}
+
+// Login verifies password and, on success, returns a new session token.
+// The bool reports whether the attempt succeeded.
+func (a *Authenticator) Login(remoteAddr, password string) (string, bool) {
+ if !a.Enabled() {
+ return "", false
+ }
+
+ key := clientKey(remoteAddr)
+ if a.lockedOut(key) {
+ return "", false
+ }
+
+ a.mu.Lock()
+ hash := append([]byte(nil), a.hash...)
+ a.mu.Unlock()
+
+ if bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil {
+ a.recordFailure(key)
+ return "", false
+ }
+
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ delete(a.attempts, key)
+ a.pruneSessionsLocked()
+
+ token, err := newToken()
+ if err != nil {
+ return "", false
+ }
+ a.sessions[token] = time.Now().Add(a.sessionTTL)
+ return token, true
+}
+
+// StartSession issues a session without checking a password. It exists so that
+// completing setup signs the user straight in rather than bouncing them to a
+// login form for the password they just chose.
+func (a *Authenticator) StartSession() (string, bool) {
+ token, err := newToken()
+ if err != nil {
+ return "", false
+ }
+
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.pruneSessionsLocked()
+ a.sessions[token] = time.Now().Add(a.sessionTTL)
+ return token, true
+}
+
+// Logout invalidates the session carried by r, if any.
+func (a *Authenticator) Logout(r *http.Request) {
+ cookie, err := r.Cookie(SessionCookie)
+ if err != nil || cookie.Value == "" {
+ return
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ delete(a.sessions, cookie.Value)
+}
+
+// SetCookie writes the session cookie for token onto w.
+func (a *Authenticator) SetCookie(w http.ResponseWriter, r *http.Request, token string) {
+ http.SetCookie(w, &http.Cookie{
+ Name: SessionCookie,
+ Value: token,
+ Path: "/",
+ HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
+ Secure: r.TLS != nil,
+ MaxAge: int(a.sessionTTL.Seconds()),
+ })
+}
+
+// ClearCookie expires the session cookie on w.
+func (a *Authenticator) ClearCookie(w http.ResponseWriter, r *http.Request) {
+ http.SetCookie(w, &http.Cookie{
+ Name: SessionCookie,
+ Value: "",
+ Path: "/",
+ HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
+ Secure: r.TLS != nil,
+ MaxAge: -1,
+ })
+}
+
+// LockedOut reports whether the given address has failed too many logins
+// recently. Exposed so the login page can explain the wait.
+func (a *Authenticator) LockedOut(remoteAddr string) bool {
+ return a.lockedOut(clientKey(remoteAddr))
+}
+
+func (a *Authenticator) lockedOut(key string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ rec, ok := a.attempts[key]
+ if !ok {
+ return false
+ }
+ if time.Now().After(rec.resets) {
+ delete(a.attempts, key)
+ return false
+ }
+ return rec.count >= maxAttempts
+}
+
+func (a *Authenticator) recordFailure(key string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ now := time.Now()
+ rec, ok := a.attempts[key]
+ if !ok || now.After(rec.resets) {
+ a.attempts[key] = &attemptRecord{count: 1, resets: now.Add(attemptWindow)}
+ return
+ }
+ rec.count++
+}
+
+// pruneSessionsLocked drops expired sessions so the map does not grow without
+// bound on a long-running server. Callers must hold a.mu.
+func (a *Authenticator) pruneSessionsLocked() {
+ now := time.Now()
+ for token, expiry := range a.sessions {
+ if now.After(expiry) {
+ delete(a.sessions, token)
+ }
+ }
+}
+
+// clientKey reduces a remote address to the host portion, so that a client
+// cannot dodge the login rate limit by using a fresh source port.
+func clientKey(remoteAddr string) string {
+ host, _, err := net.SplitHostPort(remoteAddr)
+ if err != nil {
+ return remoteAddr
+ }
+ return host
+}
+
+// newToken returns a cryptographically random session token.
+func newToken() (string, error) {
+ buf := make([]byte, sessionIDBytes)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(buf), nil
+}
+
+// HashPassword returns a bcrypt hash of password, for users who would rather
+// not store plaintext in their config file.
+func HashPassword(password string) (string, error) {
+ hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
+ return string(hash), err
+}
+
+// LoadHash reads a stored password hash written by SaveHash.
+//
+// A missing file is not an error: it simply means no password has been set.
+func LoadHash(path string) string {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return ""
+ }
+
+ hash := strings.TrimSpace(string(data))
+ if !isBcryptHash(hash) {
+ return ""
+ }
+ return hash
+}
+
+// SaveHash writes a password hash to disk, readable only by its owner.
+func SaveHash(path, hash string) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ return fmt.Errorf("could not create the directory for the password file: %w", err)
+ }
+ if err := os.WriteFile(path, []byte(hash+"\n"), 0o600); err != nil {
+ return fmt.Errorf("could not save the password: %w", err)
+ }
+ return nil
+}
diff --git a/internal/auth/auth_test.go b/internal/auth/auth_test.go
new file mode 100644
index 0000000..5f8a838
--- /dev/null
+++ b/internal/auth/auth_test.go
@@ -0,0 +1,401 @@
+package auth
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+const testPassword = "correct-horse-battery-staple"
+
+func newTestAuth(t *testing.T) *Authenticator {
+ t.Helper()
+ a, err := New(testPassword, time.Hour)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ return a
+}
+
+// okHandler reports that the request reached the protected handler.
+func okHandler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte("protected"))
+ })
+}
+
+func TestDisabledWithoutPassword(t *testing.T) {
+ a, err := New("", time.Hour)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if a.Enabled() {
+ t.Fatal("authentication should be disabled when no password is set")
+ }
+
+ // With no password, the middleware must not interfere at all.
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected request to pass through, got status %d", rec.Code)
+ }
+}
+
+func TestEnabledWithPassword(t *testing.T) {
+ a := newTestAuth(t)
+ if !a.Enabled() {
+ t.Fatal("authentication should be enabled when a password is set")
+ }
+}
+
+func TestLoginCorrectPassword(t *testing.T) {
+ a := newTestAuth(t)
+
+ token, ok := a.Login("192.168.1.5:5000", testPassword)
+ if !ok {
+ t.Fatal("login with the correct password should succeed")
+ }
+ if token == "" {
+ t.Fatal("successful login should return a session token")
+ }
+}
+
+func TestLoginWrongPassword(t *testing.T) {
+ a := newTestAuth(t)
+
+ if _, ok := a.Login("192.168.1.5:5000", "wrong"); ok {
+ t.Fatal("login with the wrong password should fail")
+ }
+}
+
+func TestLoginIssuesUniqueTokens(t *testing.T) {
+ a := newTestAuth(t)
+
+ first, ok := a.Login("192.168.1.5:5000", testPassword)
+ if !ok {
+ t.Fatal("first login failed")
+ }
+ second, ok := a.Login("192.168.1.6:5000", testPassword)
+ if !ok {
+ t.Fatal("second login failed")
+ }
+ if first == second {
+ t.Fatal("each login must produce a distinct session token")
+ }
+}
+
+func TestSessionGrantsAccess(t *testing.T) {
+ a := newTestAuth(t)
+
+ token, ok := a.Login("192.168.1.5:5000", testPassword)
+ if !ok {
+ t.Fatal("login failed")
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: token})
+ rec := httptest.NewRecorder()
+
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("valid session should reach the handler, got status %d", rec.Code)
+ }
+}
+
+func TestNoCookieRedirectsToLogin(t *testing.T) {
+ a := newTestAuth(t)
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ rec := httptest.NewRecorder()
+
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("expected redirect to login, got status %d", rec.Code)
+ }
+ if got := rec.Header().Get("Location"); got != LoginPath {
+ t.Fatalf("expected redirect to %q, got %q", LoginPath, got)
+ }
+}
+
+func TestBogusCookieRejected(t *testing.T) {
+ a := newTestAuth(t)
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: "not-a-real-token"})
+ rec := httptest.NewRecorder()
+
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code == http.StatusOK {
+ t.Fatal("a forged session token must not grant access")
+ }
+}
+
+func TestAPIRequestGets401JSON(t *testing.T) {
+ a := newTestAuth(t)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/devices", nil)
+ rec := httptest.NewRecorder()
+
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("API should answer 401, got %d", rec.Code)
+ }
+
+ var body struct {
+ Success bool `json:"success"`
+ Error string `json:"error"`
+ }
+ if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
+ t.Fatalf("API 401 should carry a JSON body: %v", err)
+ }
+ if body.Success {
+ t.Fatal("API 401 body should report success=false")
+ }
+}
+
+func TestSessionExpires(t *testing.T) {
+ a, err := New(testPassword, 20*time.Millisecond)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+
+ token, ok := a.Login("192.168.1.5:5000", testPassword)
+ if !ok {
+ t.Fatal("login failed")
+ }
+
+ time.Sleep(40 * time.Millisecond)
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: token})
+ rec := httptest.NewRecorder()
+
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code == http.StatusOK {
+ t.Fatal("an expired session must not grant access")
+ }
+}
+
+func TestLogoutInvalidatesSession(t *testing.T) {
+ a := newTestAuth(t)
+
+ token, ok := a.Login("192.168.1.5:5000", testPassword)
+ if !ok {
+ t.Fatal("login failed")
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.AddCookie(&http.Cookie{Name: SessionCookie, Value: token})
+ a.Logout(req)
+
+ rec := httptest.NewRecorder()
+ a.Middleware(okHandler()).ServeHTTP(rec, req)
+
+ if rec.Code == http.StatusOK {
+ t.Fatal("a logged-out session must not grant access")
+ }
+}
+
+func TestLockoutAfterRepeatedFailures(t *testing.T) {
+ a := newTestAuth(t)
+ const addr = "192.168.1.50:5000"
+
+ for i := 0; i < maxAttempts; i++ {
+ if _, ok := a.Login(addr, "wrong"); ok {
+ t.Fatal("wrong password should never succeed")
+ }
+ }
+
+ if !a.LockedOut(addr) {
+ t.Fatalf("address should be locked out after %d failures", maxAttempts)
+ }
+
+ // Even the correct password is refused while locked out.
+ if _, ok := a.Login(addr, testPassword); ok {
+ t.Fatal("login should be refused while locked out")
+ }
+}
+
+func TestLockoutIsPerAddressNotPerPort(t *testing.T) {
+ a := newTestAuth(t)
+
+ // Same host, different source ports, as a real client would produce.
+ for i := 0; i < maxAttempts; i++ {
+ a.Login("192.168.1.50:600"+string(rune('0'+i)), "wrong")
+ }
+
+ if !a.LockedOut("192.168.1.50:9999") {
+ t.Fatal("lockout must key on host so a new source port does not reset it")
+ }
+}
+
+func TestLockoutDoesNotAffectOtherAddresses(t *testing.T) {
+ a := newTestAuth(t)
+
+ for i := 0; i < maxAttempts; i++ {
+ a.Login("192.168.1.50:5000", "wrong")
+ }
+
+ if a.LockedOut("192.168.1.51:5000") {
+ t.Fatal("one client's lockout must not lock out a different client")
+ }
+ if _, ok := a.Login("192.168.1.51:5000", testPassword); !ok {
+ t.Fatal("an unrelated client should still be able to log in")
+ }
+}
+
+func TestSuccessfulLoginClearsFailureCount(t *testing.T) {
+ a := newTestAuth(t)
+ const addr = "192.168.1.50:5000"
+
+ // Stay one below the limit, then succeed.
+ for i := 0; i < maxAttempts-1; i++ {
+ a.Login(addr, "wrong")
+ }
+ if _, ok := a.Login(addr, testPassword); !ok {
+ t.Fatal("login should succeed before the limit is reached")
+ }
+
+ // The counter should have reset, so a fresh run of failures is needed.
+ for i := 0; i < maxAttempts-1; i++ {
+ a.Login(addr, "wrong")
+ }
+ if a.LockedOut(addr) {
+ t.Fatal("a successful login should reset the failure count")
+ }
+}
+
+func TestAcceptsPreHashedPassword(t *testing.T) {
+ hash, err := HashPassword(testPassword)
+ if err != nil {
+ t.Fatalf("HashPassword: %v", err)
+ }
+
+ a, err := New(hash, time.Hour)
+ if err != nil {
+ t.Fatalf("New with hash: %v", err)
+ }
+ if !a.Enabled() {
+ t.Fatal("a pre-hashed password should enable authentication")
+ }
+ if _, ok := a.Login("192.168.1.5:5000", testPassword); !ok {
+ t.Fatal("the original password should work against a stored hash")
+ }
+ if _, ok := a.Login("192.168.1.6:5000", hash); ok {
+ t.Fatal("the hash itself must not be accepted as the password")
+ }
+}
+
+func TestPlaintextPasswordIsNotStored(t *testing.T) {
+ a := newTestAuth(t)
+ if string(a.hash) == testPassword {
+ t.Fatal("the password must be hashed, not stored as given")
+ }
+}
+
+func TestSetAndClearCookie(t *testing.T) {
+ a := newTestAuth(t)
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+
+ rec := httptest.NewRecorder()
+ a.SetCookie(rec, req, "token-value")
+ cookie := rec.Result().Cookies()[0]
+
+ if cookie.Value != "token-value" {
+ t.Fatalf("unexpected cookie value %q", cookie.Value)
+ }
+ if !cookie.HttpOnly {
+ t.Fatal("session cookie must be HttpOnly so scripts cannot read it")
+ }
+ if cookie.SameSite != http.SameSiteLaxMode {
+ t.Fatal("session cookie should set SameSite to limit cross-site use")
+ }
+
+ rec = httptest.NewRecorder()
+ a.ClearCookie(rec, req)
+ cleared := rec.Result().Cookies()[0]
+ if cleared.MaxAge >= 0 {
+ t.Fatal("clearing the cookie should expire it")
+ }
+}
+
+func TestExpiredSessionsArePruned(t *testing.T) {
+ a, err := New(testPassword, 10*time.Millisecond)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+
+ if _, ok := a.Login("192.168.1.5:5000", testPassword); !ok {
+ t.Fatal("login failed")
+ }
+ time.Sleep(30 * time.Millisecond)
+
+ // A later login prunes anything that has expired in the meantime.
+ if _, ok := a.Login("192.168.1.6:5000", testPassword); !ok {
+ t.Fatal("second login failed")
+ }
+
+ a.mu.Lock()
+ count := len(a.sessions)
+ a.mu.Unlock()
+
+ if count != 1 {
+ t.Fatalf("expected only the live session to remain, found %d", count)
+ }
+}
+
+func TestPasswordLengthLimits(t *testing.T) {
+ tests := []struct {
+ name string
+ password string
+ wantErr bool
+ }{
+ {"too short", strings.Repeat("a", MinPasswordLength-1), true},
+ {"exactly the minimum", strings.Repeat("a", MinPasswordLength), false},
+ {"a normal passphrase", "correct horse battery staple", false},
+ {"exactly bcrypt's limit", strings.Repeat("a", MaxPasswordBytes), false},
+ {"one byte over the limit", strings.Repeat("a", MaxPasswordBytes+1), true},
+ // Accented characters take two bytes each, so this is 74 bytes.
+ {"non-Latin over the byte limit", strings.Repeat("é", 37), true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidatePassword(tt.password)
+ if tt.wantErr && err == nil {
+ t.Error("expected this password to be rejected")
+ }
+ if !tt.wantErr && err != nil {
+ t.Errorf("expected this password to be accepted, got: %v", err)
+ }
+ // Whatever we say, it must not be library jargon.
+ if err != nil && strings.Contains(err.Error(), "bcrypt") {
+ t.Errorf("error text leaks implementation detail: %v", err)
+ }
+ })
+ }
+}
+
+func TestSetPasswordRejectsOverlongInput(t *testing.T) {
+ a, err := New("", time.Hour)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if _, err := a.SetPassword(strings.Repeat("a", MaxPasswordBytes+1)); err == nil {
+ t.Fatal("SetPassword should refuse a password bcrypt cannot hash")
+ }
+ if a.Enabled() {
+ t.Error("a refused password must not become the active one")
+ }
+}
diff --git a/internal/cli/config.go b/internal/cli/config.go
index 9d37363..0d772ea 100644
--- a/internal/cli/config.go
+++ b/internal/cli/config.go
@@ -4,6 +4,8 @@ import (
"fmt"
"github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/auth"
)
var configCmd = &cobra.Command{
@@ -21,6 +23,11 @@ func runConfig(cmd *cobra.Command, args []string) error {
fmt.Printf(" port = %d\n", cfg.Server.Port)
fmt.Printf(" bind_address = %s\n", cfg.Server.BindAddress)
fmt.Printf(" enable_api = %v\n", cfg.Server.EnableAPI)
+ // Never print the password or its hash. Show only whether one is set, and
+ // where it came from, which is what someone checking their setup needs.
+ fmt.Printf(" password = %s\n", passwordSummary())
+ fmt.Printf(" session_hours = %d\n", cfg.Server.SessionHours)
+ fmt.Printf(" allow_insecure = %v\n", cfg.Server.AllowInsecure)
fmt.Println()
fmt.Println("[scanning]")
@@ -46,3 +53,17 @@ func runConfig(cmd *cobra.Command, args []string) error {
return nil
}
+
+// passwordSummary describes the password state without revealing it.
+func passwordSummary() string {
+ if cfg.Server.Password != "" {
+ return "(set in config or environment)"
+ }
+ if auth.LoadHash(cfg.PasswordFile()) != "" {
+ return "(set during first run setup)"
+ }
+ if cfg.RequiresSetup() {
+ return "(not set - you will be asked to create one on first visit)"
+ }
+ return "(not set - not required with this bind address)"
+}
diff --git a/internal/cli/export.go b/internal/cli/export.go
index 0c0e857..ac41418 100644
--- a/internal/cli/export.go
+++ b/internal/cli/export.go
@@ -9,6 +9,7 @@ import (
"github.com/spf13/cobra"
+ "github.com/291-Group/LAN-Orangutan/internal/scanner"
"github.com/291-Group/LAN-Orangutan/internal/storage"
"github.com/291-Group/LAN-Orangutan/internal/types"
)
@@ -90,7 +91,7 @@ func runExport(cmd *cobra.Command, args []string) error {
d.IP,
d.MAC,
d.Hostname,
- d.Vendor,
+ scanner.ResolveVendor(d.Vendor, d.MAC),
d.Label,
d.Notes,
d.Group,
diff --git a/internal/cli/list.go b/internal/cli/list.go
index 6a61e80..40fe127 100644
--- a/internal/cli/list.go
+++ b/internal/cli/list.go
@@ -11,6 +11,7 @@ import (
"github.com/spf13/cobra"
+ "github.com/291-Group/LAN-Orangutan/internal/scanner"
"github.com/291-Group/LAN-Orangutan/internal/storage"
"github.com/291-Group/LAN-Orangutan/internal/types"
)
@@ -100,7 +101,7 @@ func outputTable(devices []*types.Device) error {
hostname = hostname[:22] + "..."
}
- vendor := d.Vendor
+ vendor := scanner.ResolveVendor(d.Vendor, d.MAC)
if len(vendor) > 20 {
vendor = vendor[:17] + "..."
}
@@ -126,7 +127,7 @@ func outputCSV(devices []*types.Device) error {
d.IP,
d.MAC,
d.Hostname,
- d.Vendor,
+ scanner.ResolveVendor(d.Vendor, d.MAC),
d.Label,
d.Notes,
d.Group,
@@ -149,7 +150,7 @@ func outputJSON(devices []*types.Device) error {
comma = ""
}
fmt.Printf(" {\"ip\": %q, \"mac\": %q, \"hostname\": %q, \"vendor\": %q, \"label\": %q, \"group\": %q}%s\n",
- d.IP, d.MAC, d.Hostname, d.Vendor, d.Label, d.Group, comma)
+ d.IP, d.MAC, d.Hostname, scanner.ResolveVendor(d.Vendor, d.MAC), d.Label, d.Group, comma)
}
fmt.Println("]")
return nil
diff --git a/internal/cli/networks.go b/internal/cli/networks.go
index 75715cc..ea589bb 100644
--- a/internal/cli/networks.go
+++ b/internal/cli/networks.go
@@ -16,6 +16,7 @@ var networksCmd = &cobra.Command{
func runNetworks(cmd *cobra.Command, args []string) error {
networks, err := network.DetectNetworks()
+ networks = network.WithConfigured(networks, cfg.Scanning.Networks)
if err != nil {
return fmt.Errorf("failed to detect networks: %w", err)
}
diff --git a/internal/cli/root.go b/internal/cli/root.go
index 039ec62..ab174d6 100644
--- a/internal/cli/root.go
+++ b/internal/cli/root.go
@@ -22,6 +22,18 @@ var rootCmd = &cobra.Command{
Long: `LAN Orangutan is a network discovery and monitoring tool.
It scans your local network to find devices and provides
a web interface for viewing and managing discovered devices.`,
+
+ // Execute prints errors itself; without this cobra prints them a second
+ // time.
+ SilenceErrors: true,
+
+ // Flags have parsed by the time this runs, so anything that fails from here
+ // is a runtime problem rather than a usage mistake. Silencing usage now
+ // keeps a real error visible instead of burying it under the flag listing,
+ // while a genuine flag mistake still gets the full help.
+ PersistentPreRun: func(cmd *cobra.Command, args []string) {
+ cmd.SilenceUsage = true
+ },
}
// Execute adds all child commands and runs the CLI
@@ -55,4 +67,8 @@ func initConfig() {
fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
os.Exit(1)
}
+
+ // Environment variables override the file, so containers can be configured
+ // without mounting one.
+ cfg.ApplyEnv()
}
diff --git a/internal/cli/scan.go b/internal/cli/scan.go
index 83b365c..fb159cc 100644
--- a/internal/cli/scan.go
+++ b/internal/cli/scan.go
@@ -40,6 +40,7 @@ func runScan(cmd *cobra.Command, args []string) error {
if len(args) == 0 || args[0] == "" {
// Scan first detected network
detected, err := network.DetectNetworks()
+ detected = network.WithConfigured(detected, cfg.Scanning.Networks)
if err != nil {
return fmt.Errorf("failed to detect networks: %w", err)
}
@@ -59,6 +60,7 @@ func runScan(cmd *cobra.Command, args []string) error {
} else if args[0] == "all" {
// Scan all detected networks
detected, err := network.DetectNetworks()
+ detected = network.WithConfigured(detected, cfg.Scanning.Networks)
if err != nil {
return fmt.Errorf("failed to detect networks: %w", err)
}
diff --git a/internal/cli/serve.go b/internal/cli/serve.go
index d9ddcb1..11c105c 100644
--- a/internal/cli/serve.go
+++ b/internal/cli/serve.go
@@ -2,23 +2,30 @@ package cli
import (
"context"
+ "errors"
"fmt"
+ "net"
"net/http"
"os"
"os/signal"
+ "strconv"
+ "strings"
"syscall"
"time"
"github.com/spf13/cobra"
"github.com/291-Group/LAN-Orangutan/internal/api"
+ "github.com/291-Group/LAN-Orangutan/internal/auth"
+ "github.com/291-Group/LAN-Orangutan/internal/network"
"github.com/291-Group/LAN-Orangutan/internal/storage"
"github.com/291-Group/LAN-Orangutan/internal/web"
)
var (
- servePort int
- serveBind string
+ servePort int
+ serveBind string
+ serveAllowInsecure bool
)
var serveCmd = &cobra.Command{
@@ -31,9 +38,15 @@ var serveCmd = &cobra.Command{
func init() {
serveCmd.Flags().IntVarP(&servePort, "port", "p", 0, "Port to listen on (default from config)")
serveCmd.Flags().StringVarP(&serveBind, "bind", "b", "", "Address to bind to (default from config)")
+ serveCmd.Flags().BoolVar(&serveAllowInsecure, "allow-insecure", false,
+ "Permit binding to the network without a password (not recommended)")
}
func runServe(cmd *cobra.Command, args []string) error {
+ // Flags parsed cleanly, so anything that fails from here is a runtime
+ // problem, not a usage error. Report it without the flag listing.
+ cmd.SilenceUsage = true
+
// Use flags or config
port := cfg.Server.Port
if servePort > 0 {
@@ -44,25 +57,54 @@ func runServe(cmd *cobra.Command, args []string) error {
bind = serveBind
}
+ // Flags win over the config file and environment.
+ cfg.Server.BindAddress = bind
+ if serveAllowInsecure {
+ cfg.Server.AllowInsecure = true
+ }
+
// Initialize storage
store, err := storage.New(cfg.DevicesFile(), cfg.StateFile())
if err != nil {
return fmt.Errorf("failed to initialize storage: %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
+ }
+
+ authn, err := auth.New(password, cfg.SessionTTL())
+ if err != nil {
+ return fmt.Errorf("failed to set up authentication: %w", err)
+ }
+ authn.SetSetupRequired(cfg.RequiresSetup())
+
// Create HTTP handler
mux := http.NewServeMux()
- // Register API routes
+ webHandler := web.NewHandler(store, cfg, authn, Version)
apiHandler := api.NewHandler(store, cfg)
- mux.Handle("/api/", apiHandler)
- // Register web routes
- webHandler := web.NewHandler(store, cfg, Version)
- mux.Handle("/", webHandler)
+ // Protected routes.
+ mux.Handle("/api/", authn.Middleware(apiHandler))
+ mux.Handle("/", authn.Middleware(webHandler))
- // Create server
- addr := fmt.Sprintf("%s:%d", bind, port)
+ // Public routes. Static assets stay open so the login and setup pages can
+ // style themselves, and those forms must be reachable while signed out.
+ mux.Handle("/static/", webHandler.StaticHandler())
+ mux.HandleFunc(auth.LoginPath, webHandler.HandleLogin)
+ mux.HandleFunc(auth.LogoutPath, webHandler.HandleLogout)
+ mux.HandleFunc(auth.SetupPath, webHandler.HandleSetup(func(hash string) error {
+ return auth.SaveHash(cfg.PasswordFile(), hash)
+ }))
+
+ // Create server. JoinHostPort rather than "host:port": an IPv6 address
+ // contains colons of its own and has to be bracketed.
+ addr := net.JoinHostPort(bind, strconv.Itoa(port))
server := &http.Server{
Addr: addr,
Handler: mux,
@@ -71,6 +113,17 @@ func runServe(cmd *cobra.Command, args []string) error {
IdleTimeout: 60 * time.Second,
}
+ // Claim the port before announcing anything. Printing "Starting..." and the
+ // whole status banner first means a failure to bind reads as though the
+ // server came up and then died.
+ listener, err := net.Listen(listenNetwork(bind), addr)
+ if err != nil {
+ if isAddrInUse(err) {
+ return fmt.Errorf("port %d is already in use. Stop whatever is using it, or choose another with --port", port)
+ }
+ return fmt.Errorf("could not listen on %s: %w", addr, err)
+ }
+
// Handle shutdown gracefully
done := make(chan bool, 1)
quit := make(chan os.Signal, 1)
@@ -91,9 +144,61 @@ func runServe(cmd *cobra.Command, args []string) error {
}()
fmt.Printf("Starting LAN Orangutan server on http://%s\n", addr)
+
+ // Be explicit about who can reach this and whether it is protected, so
+ // nobody has to guess at their own exposure.
+ if cfg.IsLoopbackBind() {
+ fmt.Println("Reachable from: this machine only")
+ } else {
+ // Name the actual addresses. "0.0.0.0" tells the user nothing about
+ // which networks they have just published this on.
+ reachable := listenAddresses(bind, port)
+ if len(reachable) == 0 {
+ fmt.Printf("Reachable from: any machine that can reach %s\n", bind)
+ } else {
+ fmt.Println("Reachable at:")
+ for _, a := range reachable {
+ fmt.Printf(" http://%s\n", a)
+ }
+ }
+ }
+
+ switch {
+ case authn.NeedsSetup():
+ fmt.Println("Password: not set yet, open the page above to create one")
+ case authn.Enabled():
+ fmt.Println("Password: required")
+ case cfg.IsLoopbackBind():
+ fmt.Println("Password: not set (not needed while local only)")
+ default:
+ fmt.Println("Password: NOT SET, and this server is exposed to the network")
+ }
+
+ // A container attached to Docker's own network cannot see the LAN, and the
+ // virtual gateway answers probes for addresses that do not exist. Say so
+ // before the user runs a scan and trusts the results.
+ if detected, err := network.DetectNetworks(); err == nil {
+ detected = network.WithConfigured(detected, cfg.Scanning.Networks)
+ if warning := network.IsolationWarning(detected); warning != "" {
+ fmt.Println()
+ fmt.Println(" ┌─────────────────────────────────────────────────────────────┐")
+ fmt.Println(" │ WARNING: no access to your local network │")
+ fmt.Println(" └─────────────────────────────────────────────────────────────┘")
+ fmt.Println()
+ fmt.Println(" This container can only see Docker's own network.")
+ fmt.Println(" Scans will miss your real devices, and may report devices that")
+ fmt.Println(" do not exist, because Docker's gateway answers on their behalf.")
+ fmt.Println()
+ fmt.Println(" Linux: use host networking (see docker-compose.yml)")
+ fmt.Println(" macOS / Windows: Docker cannot reach your LAN at all.")
+ fmt.Println(" Run LAN Orangutan directly instead.")
+ fmt.Println()
+ }
+ }
+
fmt.Println("Press Ctrl+C to stop")
- if err := server.ListenAndServe(); err != http.ErrServerClosed {
+ if err := server.Serve(listener); err != http.ErrServerClosed {
return fmt.Errorf("server error: %w", err)
}
@@ -101,3 +206,61 @@ func runServe(cmd *cobra.Command, args []string) error {
fmt.Println("Server stopped")
return nil
}
+
+// isAddrInUse reports whether err is the operating system refusing a port
+// because something else already holds it.
+func isAddrInUse(err error) bool {
+ return errors.Is(err, syscall.EADDRINUSE)
+}
+
+// listenNetwork picks the address family to listen on.
+//
+// Go treats "0.0.0.0" as a wildcard and answers it with a dual-stack IPv6
+// socket, so a user who asked for an IPv4 address would also be listening on
+// every IPv6 address the machine holds. On a home network IPv4 sits behind NAT
+// while IPv6 frequently does not, so that quietly turns a LAN service into one
+// that may be reachable from the internet.
+//
+// Bind the family that was actually requested. "::" still gives both, for
+// anyone who wants that.
+func listenNetwork(bind string) string {
+ ip := net.ParseIP(strings.Trim(bind, "[]"))
+ switch {
+ case ip == nil:
+ return "tcp" // a hostname; let the resolver decide
+ case ip.To4() != nil:
+ return "tcp4"
+ default:
+ return "tcp6"
+ }
+}
+
+// listenAddresses returns the addresses this machine can actually be reached on
+// for a wildcard bind, so the startup banner can name them instead of printing
+// "0.0.0.0" and leaving the user to guess.
+func listenAddresses(bind string, port int) []string {
+ ip := net.ParseIP(strings.Trim(bind, "[]"))
+ if ip != nil && !ip.IsUnspecified() {
+ return []string{net.JoinHostPort(bind, fmt.Sprint(port))}
+ }
+
+ addrs, err := net.InterfaceAddrs()
+ if err != nil {
+ return nil
+ }
+
+ wantV4 := ip == nil || ip.To4() != nil
+ var out []string
+ for _, a := range addrs {
+ n, ok := a.(*net.IPNet)
+ if !ok || n.IP.IsLoopback() || n.IP.IsLinkLocalUnicast() {
+ continue
+ }
+ isV4 := n.IP.To4() != nil
+ if isV4 != wantV4 {
+ continue
+ }
+ out = append(out, net.JoinHostPort(n.IP.String(), fmt.Sprint(port)))
+ }
+ return out
+}
diff --git a/internal/cli/status.go b/internal/cli/status.go
index 790a34d..0401518 100644
--- a/internal/cli/status.go
+++ b/internal/cli/status.go
@@ -51,6 +51,7 @@ func runStatus(cmd *cobra.Command, args []string) error {
fmt.Println()
fmt.Println("Networks:")
networks, err := network.DetectNetworks()
+ networks = network.WithConfigured(networks, cfg.Scanning.Networks)
if err != nil {
fmt.Printf(" Error detecting: %v\n", err)
} else {
diff --git a/internal/cli/version.go b/internal/cli/version.go
index 37c0fd2..8ffd93e 100644
--- a/internal/cli/version.go
+++ b/internal/cli/version.go
@@ -2,18 +2,125 @@ package cli
import (
"fmt"
+ "regexp"
"runtime"
+ "runtime/debug"
+ "strings"
"github.com/spf13/cobra"
)
-// Version information (set via ldflags at build time)
+// Version information, set via ldflags by the Makefile and by the release
+// workflow. When it is not set, resolveVersion fills these in from the build
+// information Go embeds automatically, so a plain `go build` still reports
+// something meaningful rather than "dev".
var (
- Version = "dev"
- Commit = "unknown"
- BuildDate = "unknown"
+ Version = ""
+ Commit = ""
+ BuildDate = ""
)
+func init() {
+ resolveVersion()
+
+ // The release workflow strips the tag's leading "v" while a local
+ // `make build` keeps it, so the same commit could report "3.1.3" or
+ // "v3.1.3". Normalise so every build of a release shows the same string.
+ Version = strings.TrimPrefix(Version, "v")
+}
+
+// resolveVersion fills in any version details that were not supplied at build
+// time.
+//
+// Go records the commit, its timestamp, and whether the tree was dirty for any
+// binary built inside a repository, so a source build can report its exact
+// provenance without needing the Makefile.
+func resolveVersion() {
+ info, ok := debug.ReadBuildInfo()
+ if !ok {
+ applyFallbacks()
+ return
+ }
+
+ var revision, vcsTime string
+ var modified bool
+ for _, setting := range info.Settings {
+ switch setting.Key {
+ case "vcs.revision":
+ revision = setting.Value
+ case "vcs.time":
+ vcsTime = setting.Value
+ case "vcs.modified":
+ modified = setting.Value == "true"
+ }
+ }
+
+ if Commit == "" && revision != "" {
+ Commit = shortCommit(revision)
+ }
+ if BuildDate == "" && vcsTime != "" {
+ BuildDate = vcsTime
+ }
+
+ if Version == "" {
+ // `go install [email protected]` records the real tag, which is what we want
+ // to show. A build from a working copy instead records either
+ // "(devel)" or a generated pseudo-version like
+ // v0.0.0-20260715193857-0c49f4c9dda2, which is accurate but unreadable.
+ // In that case show the short commit, which says the same thing.
+ if v := info.Main.Version; isReleaseVersion(v) {
+ Version = v
+ } else if revision != "" {
+ Version = shortCommit(revision)
+ if modified {
+ Version += "-dirty"
+ }
+ }
+ }
+
+ applyFallbacks()
+}
+
+// applyFallbacks covers the case where nothing could be determined at all, such
+// as a binary built from a source tarball with no repository present.
+func applyFallbacks() {
+ if Version == "" {
+ Version = "unknown"
+ }
+ if Commit == "" {
+ Commit = "unknown"
+ }
+ if BuildDate == "" {
+ BuildDate = "unknown"
+ }
+}
+
+// pseudoVersion matches the version string Go generates for a build that is not
+// at a tagged release, for example v0.0.0-20260715193857-0c49f4c9dda2.
+var pseudoVersion = regexp.MustCompile(`-\d{14}-[0-9a-f]{12}`)
+
+// isReleaseVersion reports whether v is a real tagged version worth showing to
+// a user, rather than a generated placeholder.
+func isReleaseVersion(v string) bool {
+ if v == "" || v == "(devel)" {
+ return false
+ }
+ return !pseudoVersion.MatchString(v)
+}
+
+// shortCommit trims a full git hash to the usual short form.
+func shortCommit(revision string) string {
+ if len(revision) > 7 {
+ return revision[:7]
+ }
+ return revision
+}
+
+// DisplayVersion returns the version string shown in the web interface.
+func DisplayVersion() string {
+ return Version
+}
+
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version information",
diff --git a/internal/config/config.go b/internal/config/config.go
index 6225375..bce889e 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -4,11 +4,15 @@ package config
import (
"bufio"
"fmt"
+ "net"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/network"
)
// GetDefaultDataDir returns the appropriate default data directory for the current OS
@@ -92,6 +96,18 @@ type ServerConfig struct {
Port int
BindAddress string
EnableAPI bool
+
+ // Password protects the dashboard and API. Empty means no login is
+ // required. May be given as plaintext or as a bcrypt hash.
+ Password string
+
+ // SessionHours is how long a login stays valid.
+ SessionHours int
+
+ // AllowInsecure permits binding to a non-loopback address without a
+ // password. Off by default: doing so exposes the API, which can modify
+ // stored data, to everyone on the network.
+ AllowInsecure bool
}
// ScanningConfig holds scanner settings
@@ -100,6 +116,11 @@ type ScanningConfig struct {
MinScanInterval int
EnablePortScan bool
PortScanRange string
+
+ // Networks are CIDRs the user has declared explicitly, for cases where
+ // automatic detection cannot see the right network. A container only sees
+ // Docker's private network, so without this it can never scan the LAN.
+ Networks []string
}
// StorageConfig holds data storage settings
@@ -124,9 +145,14 @@ type UIConfig struct {
func Default() *Config {
return &Config{
Server: ServerConfig{
- Port: 291,
- BindAddress: "0.0.0.0",
- EnableAPI: true,
+ Port: 291,
+ // Reachable from the network, because this is usually installed on
+ // a server or a Pi and opened from another machine. Safety comes
+ // from RequiresSetup: with no password set, the only thing a
+ // visitor can reach is the page that creates one.
+ BindAddress: "0.0.0.0",
+ EnableAPI: true,
+ SessionHours: 24 * 7,
},
Scanning: ScanningConfig{
ScanInterval: 300,
@@ -211,6 +237,14 @@ func (c *Config) setValue(section, key, value string) {
c.Server.BindAddress = value
case "enable_api":
c.Server.EnableAPI = parseBool(value)
+ case "password":
+ c.Server.Password = value
+ case "session_hours":
+ if v, err := strconv.Atoi(value); err == nil {
+ c.Server.SessionHours = v
+ }
+ case "allow_insecure":
+ c.Server.AllowInsecure = parseBool(value)
}
case "scanning":
switch key {
@@ -226,6 +260,8 @@ func (c *Config) setValue(section, key, value string) {
c.Scanning.EnablePortScan = parseBool(value)
case "port_scan_range":
c.Scanning.PortScanRange = value
+ case "networks":
+ c.Scanning.Networks = network.ParseNetworkList(value)
}
case "storage":
switch key {
@@ -255,6 +291,116 @@ func (c *Config) setValue(section, key, value string) {
}
}
+// ApplyEnv overlays settings from environment variables onto c.
+//
+// Environment variables take precedence over the config file, which makes the
+// app configurable in a container without mounting a config file. Command line
+// flags still win over both.
+func (c *Config) ApplyEnv() {
+ if v := os.Getenv("ORANGUTAN_PORT"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil {
+ c.Server.Port = n
+ }
+ }
+ if v := os.Getenv("ORANGUTAN_BIND_ADDRESS"); v != "" {
+ c.Server.BindAddress = v
+ }
+ if v := os.Getenv("ORANGUTAN_PASSWORD"); v != "" {
+ c.Server.Password = v
+ }
+ // A password file keeps the secret out of the process environment, which
+ // is how container secrets are normally delivered.
+ if v := os.Getenv("ORANGUTAN_PASSWORD_FILE"); v != "" {
+ if data, err := os.ReadFile(v); err == nil {
+ if pw := strings.TrimSpace(string(data)); pw != "" {
+ c.Server.Password = pw
+ }
+ }
+ }
+ if v := os.Getenv("ORANGUTAN_SESSION_HOURS"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil {
+ c.Server.SessionHours = n
+ }
+ }
+ if v := os.Getenv("ORANGUTAN_ALLOW_INSECURE"); v != "" {
+ c.Server.AllowInsecure = parseBool(v)
+ }
+ if v := os.Getenv("ORANGUTAN_DATA_DIR"); v != "" {
+ c.Storage.DataDir = v
+ }
+ if v := os.Getenv("ORANGUTAN_NETWORKS"); v != "" {
+ c.Scanning.Networks = network.ParseNetworkList(v)
+ }
+ if v := os.Getenv("ORANGUTAN_SCAN_INTERVAL"); v != "" {
+ if n, err := strconv.Atoi(v); err == nil {
+ c.Scanning.ScanInterval = n
+ }
+ }
+ if v := os.Getenv("ORANGUTAN_THEME"); v != "" {
+ c.UI.Theme = v
+ }
+}
+
+// IsLoopbackBind reports whether the configured bind address only accepts
+// connections from the machine the app is running on.
+//
+// An empty bind address means every interface, which is not loopback.
+func (c *Config) IsLoopbackBind() bool {
+ return isLoopbackAddress(c.Server.BindAddress)
+}
+
+func isLoopbackAddress(addr string) bool {
+ addr = strings.TrimSpace(addr)
+ if addr == "" {
+ return false
+ }
+ if strings.EqualFold(addr, "localhost") {
+ return true
+ }
+ // Strip brackets from IPv6 literals such as [::1].
+ addr = strings.TrimPrefix(strings.TrimSuffix(addr, "]"), "[")
+
+ ip := net.ParseIP(addr)
+ if ip == nil {
+ return false
+ }
+ return ip.IsLoopback()
+}
+
+// RequiresSetup reports whether the user must create a password before the
+// dashboard becomes usable.
+//
+// Setup is required whenever the server can be reached from the network and no
+// password exists yet. Bound to loopback the dashboard is already private, so
+// a password would be friction with no benefit, and an operator who has some
+// other protection in front can opt out entirely.
+func (c *Config) RequiresSetup() bool {
+ if c.Server.AllowInsecure {
+ return false
+ }
+ if c.IsLoopbackBind() {
+ return false
+ }
+ return c.Server.Password == ""
+}
+
+// PasswordFile returns the path where a password created through the setup page
+// is stored.
+//
+// It lives beside the data rather than in the config file, so that completing
+// setup does not rewrite a file the user maintains by hand.
+func (c *Config) PasswordFile() string {
+ return filepath.Join(c.Storage.DataDir, "auth")
+}
+
+// SessionTTL returns how long a login should remain valid.
+func (c *Config) SessionTTL() time.Duration {
+ if c.Server.SessionHours <= 0 {
+ return 24 * 7 * time.Hour
+ }
+ return time.Duration(c.Server.SessionHours) * time.Hour
+}
+
// DevicesFile returns the full path to the devices JSON file
func (c *Config) DevicesFile() string {
return filepath.Join(c.Storage.DataDir, "devices.json")
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
new file mode 100644
index 0000000..12d7dae
--- /dev/null
+++ b/internal/config/config_test.go
@@ -0,0 +1,297 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// writeConfig writes body to a temporary config file and returns its path.
+func writeConfig(t *testing.T, body string) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "config.ini")
+ if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
+ t.Fatalf("writing config: %v", err)
+ }
+ return path
+}
+
+func TestDefaultIsReachableButRequiresSetup(t *testing.T) {
+ cfg := Default()
+
+ // Reachable from the network, because that is how this is normally used.
+ if cfg.IsLoopbackBind() {
+ t.Fatalf("default bind address %q should accept connections from the network", cfg.Server.BindAddress)
+ }
+ if cfg.Server.Password != "" {
+ t.Fatal("no password should be set by default")
+ }
+ if cfg.Server.AllowInsecure {
+ t.Fatal("password protection must not be skipped by default")
+ }
+
+ // Safety comes from setup, not from being unreachable.
+ if !cfg.RequiresSetup() {
+ t.Fatal("a fresh install reachable from the network must require setup")
+ }
+}
+
+func TestMissingFileFallsBackToDefaults(t *testing.T) {
+ cfg, err := Load(filepath.Join(t.TempDir(), "does-not-exist.ini"))
+ if err != nil {
+ t.Fatalf("a missing config file should not be an error: %v", err)
+ }
+ if !cfg.RequiresSetup() {
+ t.Fatal("a missing config file should leave the setup requirement in place")
+ }
+}
+
+func TestLoadServerSettings(t *testing.T) {
+ path := writeConfig(t, `
+[server]
+port = 8080
+bind_address = 0.0.0.0
+password = hunter2
+session_hours = 12
+allow_insecure = true
+`)
+
+ cfg, err := Load(path)
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+
+ if cfg.Server.Port != 8080 {
+ t.Errorf("port = %d, want 8080", cfg.Server.Port)
+ }
+ if cfg.Server.BindAddress != "0.0.0.0" {
+ t.Errorf("bind_address = %q, want 0.0.0.0", cfg.Server.BindAddress)
+ }
+ if cfg.Server.Password != "hunter2" {
+ t.Errorf("password = %q, want hunter2", cfg.Server.Password)
+ }
+ if cfg.Server.SessionHours != 12 {
+ t.Errorf("session_hours = %d, want 12", cfg.Server.SessionHours)
+ }
+ if !cfg.Server.AllowInsecure {
+ t.Error("allow_insecure should be true")
+ }
+}
+
+func TestIsLoopbackBind(t *testing.T) {
+ tests := []struct {
+ addr string
+ want bool
+ }{
+ {"127.0.0.1", true},
+ {"127.0.0.53", true},
+ {"localhost", true},
+ {"LOCALHOST", true},
+ {"::1", true},
+ {"[::1]", true},
+ {"0.0.0.0", false},
+ {"192.168.1.10", false},
+ {"::", false},
+ {"", false}, // empty means every interface
+ {"not-an-address", false},
+ }
+
+ for _, tt := range tests {
+ cfg := Default()
+ cfg.Server.BindAddress = tt.addr
+ if got := cfg.IsLoopbackBind(); got != tt.want {
+ t.Errorf("IsLoopbackBind(%q) = %v, want %v", tt.addr, got, tt.want)
+ }
+ }
+}
+
+func TestRequiresSetupWhenReachableWithNoPassword(t *testing.T) {
+ cfg := Default()
+ cfg.Server.BindAddress = "0.0.0.0"
+
+ if !cfg.RequiresSetup() {
+ t.Fatal("a network-reachable install with no password must require setup")
+ }
+}
+
+func TestRequiresSetupWithEmptyBindAddress(t *testing.T) {
+ // An empty bind address listens on every interface, so it is just as
+ // exposed as 0.0.0.0 and must be caught too.
+ cfg := Default()
+ cfg.Server.BindAddress = ""
+
+ if !cfg.RequiresSetup() {
+ t.Fatal("an empty bind address with no password must require setup")
+ }
+}
+
+func TestNoSetupWhenPasswordAlreadySet(t *testing.T) {
+ cfg := Default()
+ cfg.Server.BindAddress = "0.0.0.0"
+ cfg.Server.Password = "hunter2"
+
+ if cfg.RequiresSetup() {
+ t.Fatal("an existing password means there is nothing to set up")
+ }
+}
+
+func TestNoSetupWhenLoopbackOnly(t *testing.T) {
+ // Nobody else can reach it, so a password would be friction with no gain.
+ cfg := Default()
+ cfg.Server.BindAddress = "127.0.0.1"
+
+ if cfg.RequiresSetup() {
+ t.Fatal("a loopback-only install should not demand a password")
+ }
+}
+
+func TestNoSetupWhenExplicitlyOptedOut(t *testing.T) {
+ cfg := Default()
+ cfg.Server.BindAddress = "0.0.0.0"
+ cfg.Server.AllowInsecure = true
+
+ if cfg.RequiresSetup() {
+ t.Fatal("an explicit opt-out should be honoured")
+ }
+}
+
+func TestPasswordFileLivesBesideTheData(t *testing.T) {
+ cfg := Default()
+ cfg.Storage.DataDir = "/tmp/example"
+
+ if got, want := cfg.PasswordFile(), filepath.Join("/tmp/example", "auth"); got != want {
+ t.Errorf("PasswordFile() = %q, want %q", got, want)
+ }
+}
+
+func TestEnvOverridesConfigFile(t *testing.T) {
+ path := writeConfig(t, `
+[server]
+port = 8080
+bind_address = 127.0.0.1
+password = from-file
+`)
+
+ cfg, err := Load(path)
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+
+ t.Setenv("ORANGUTAN_PORT", "9999")
+ t.Setenv("ORANGUTAN_BIND_ADDRESS", "0.0.0.0")
+ t.Setenv("ORANGUTAN_PASSWORD", "from-env")
+ t.Setenv("ORANGUTAN_ALLOW_INSECURE", "true")
+ cfg.ApplyEnv()
+
+ if cfg.Server.Port != 9999 {
+ t.Errorf("port = %d, want the environment value 9999", cfg.Server.Port)
+ }
+ if cfg.Server.BindAddress != "0.0.0.0" {
+ t.Errorf("bind_address = %q, want the environment value", cfg.Server.BindAddress)
+ }
+ if cfg.Server.Password != "from-env" {
+ t.Errorf("password = %q, want the environment value", cfg.Server.Password)
+ }
+ if !cfg.Server.AllowInsecure {
+ t.Error("allow_insecure should come from the environment")
+ }
+}
+
+func TestEnvLeavesUnsetValuesAlone(t *testing.T) {
+ cfg := Default()
+ original := cfg.Server.Port
+
+ cfg.ApplyEnv() // nothing set
+
+ if cfg.Server.Port != original {
+ t.Errorf("port changed to %d with no environment variable set", cfg.Server.Port)
+ }
+ if cfg.Server.BindAddress != Default().Server.BindAddress {
+ t.Error("bind address should be untouched with no environment variable set")
+ }
+}
+
+func TestPasswordFileIsRead(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "secret")
+ // Trailing newline is normal in a secret file and must be trimmed.
+ if err := os.WriteFile(path, []byte("file-secret\n"), 0o600); err != nil {
+ t.Fatalf("writing secret: %v", err)
+ }
+
+ cfg := Default()
+ t.Setenv("ORANGUTAN_PASSWORD_FILE", path)
+ cfg.ApplyEnv()
+
+ if cfg.Server.Password != "file-secret" {
+ t.Errorf("password = %q, want the trimmed file contents", cfg.Server.Password)
+ }
+}
+
+func TestPasswordFileWinsOverPasswordVar(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "secret")
+ if err := os.WriteFile(path, []byte("file-secret"), 0o600); err != nil {
+ t.Fatalf("writing secret: %v", err)
+ }
+
+ cfg := Default()
+ t.Setenv("ORANGUTAN_PASSWORD", "env-secret")
+ t.Setenv("ORANGUTAN_PASSWORD_FILE", path)
+ cfg.ApplyEnv()
+
+ if cfg.Server.Password != "file-secret" {
+ t.Errorf("password = %q, want the file to take precedence", cfg.Server.Password)
+ }
+}
+
+func TestMissingPasswordFileIsIgnored(t *testing.T) {
+ cfg := Default()
+ t.Setenv("ORANGUTAN_PASSWORD", "env-secret")
+ t.Setenv("ORANGUTAN_PASSWORD_FILE", filepath.Join(t.TempDir(), "nope"))
+ cfg.ApplyEnv()
+
+ // A missing file should not wipe out a password supplied another way.
+ if cfg.Server.Password != "env-secret" {
+ t.Errorf("password = %q, want the environment value kept", cfg.Server.Password)
+ }
+}
+
+func TestSessionTTL(t *testing.T) {
+ cfg := Default()
+ if got := cfg.SessionTTL(); got != 7*24*time.Hour {
+ t.Errorf("default SessionTTL = %v, want one week", got)
+ }
+
+ cfg.Server.SessionHours = 3
+ if got := cfg.SessionTTL(); got != 3*time.Hour {
+ t.Errorf("SessionTTL = %v, want 3h", got)
+ }
+
+ // Nonsense values fall back to the default rather than expiring instantly.
+ cfg.Server.SessionHours = 0
+ if got := cfg.SessionTTL(); got != 7*24*time.Hour {
+ t.Errorf("SessionTTL with 0 hours = %v, want the default", got)
+ }
+ cfg.Server.SessionHours = -5
+ if got := cfg.SessionTTL(); got != 7*24*time.Hour {
+ t.Errorf("SessionTTL with a negative value = %v, want the default", got)
+ }
+}
+
+func TestCommentsAndBlankLinesIgnored(t *testing.T) {
+ path := writeConfig(t, `
+# a comment
+; another comment
+
+[server]
+port = 4242
+`)
+
+ cfg, err := Load(path)
+ if err != nil {
+ t.Fatalf("Load: %v", err)
+ }
+ if cfg.Server.Port != 4242 {
+ t.Errorf("port = %d, want 4242", cfg.Server.Port)
+ }
+}
diff --git a/internal/network/configured.go b/internal/network/configured.go
new file mode 100644
index 0000000..dfcec2d
--- /dev/null
+++ b/internal/network/configured.go
@@ -0,0 +1,75 @@
+package network
+
+import (
+ "net"
+ "strings"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// WithConfigured returns the detected networks plus any the user has declared
+// explicitly, with duplicates removed.
+//
+// Automatic detection reads the machine's own interfaces, which is wrong in a
+// container: it sees only Docker's private network and never the LAN the user
+// actually wants scanned. Declaring a network here makes it available to scan
+// and visible on the dashboard even though no local interface belongs to it.
+func WithConfigured(detected []types.Network, configured []string) []types.Network {
+ // Docker's own bridge is a real interface but holds containers, not devices
+ // on your network. Sweeping its /16 finds nothing and takes minutes.
+ detected = ExcludeContainerNetworks(detected)
+
+ seen := make(map[string]bool, len(detected)+len(configured))
+ result := make([]types.Network, 0, len(detected)+len(configured))
+
+ for _, n := range detected {
+ if seen[n.CIDR] {
+ continue
+ }
+ seen[n.CIDR] = true
+ result = append(result, n)
+ }
+
+ for _, cidr := range configured {
+ cidr = strings.TrimSpace(cidr)
+ if cidr == "" || seen[cidr] {
+ continue
+ }
+ if !ValidateCIDR(cidr) {
+ continue
+ }
+ seen[cidr] = true
+ result = append(result, types.Network{
+ CIDR: cidr,
+ Interface: "configured",
+ FriendlyName: friendlyNameFor(cidr),
+ })
+ }
+
+ return result
+}
+
+// friendlyNameFor labels a declared network so it is distinguishable from one
+// that was detected.
+func friendlyNameFor(cidr string) string {
+ if ip, _, err := net.ParseCIDR(cidr); err == nil {
+ return "Configured (" + ip.String() + ")"
+ }
+ return "Configured"
+}
+
+// ParseNetworkList splits a comma or space separated list of CIDRs, as supplied
+// through the config file or the environment.
+func ParseNetworkList(s string) []string {
+ fields := strings.FieldsFunc(s, func(r rune) bool {
+ return r == ',' || r == ' ' || r == '\t'
+ })
+
+ out := make([]string, 0, len(fields))
+ for _, f := range fields {
+ if f = strings.TrimSpace(f); f != "" {
+ out = append(out, f)
+ }
+ }
+ return out
+}
diff --git a/internal/network/configured_test.go b/internal/network/configured_test.go
new file mode 100644
index 0000000..3df395e
--- /dev/null
+++ b/internal/network/configured_test.go
@@ -0,0 +1,55 @@
+package network
+
+import "testing"
+
+func TestParseNetworkList(t *testing.T) {
+ tests := []struct {
+ in string
+ want int
+ }{
+ {"192.168.1.0/24", 1},
+ {"192.168.1.0/24,10.0.0.0/24", 2},
+ {"192.168.1.0/24, 10.0.0.0/24", 2},
+ {"192.168.1.0/24 10.0.0.0/24", 2},
+ {" 192.168.1.0/24 , ", 1},
+ {"", 0},
+ {" ", 0},
+ }
+ for _, tt := range tests {
+ if got := ParseNetworkList(tt.in); len(got) != tt.want {
+ t.Errorf("ParseNetworkList(%q) returned %d entries, want %d", tt.in, len(got), tt.want)
+ }
+ }
+}
+
+func TestConfiguredNetworksAreAdded(t *testing.T) {
+ got := WithConfigured(nil, []string{"192.168.50.0/24"})
+ if len(got) != 1 {
+ t.Fatalf("expected the configured network to be added, got %d", len(got))
+ }
+ if got[0].CIDR != "192.168.50.0/24" {
+ t.Errorf("CIDR = %q", got[0].CIDR)
+ }
+ if got[0].Interface != "configured" {
+ t.Errorf("configured networks should be labelled as such, got %q", got[0].Interface)
+ }
+}
+
+func TestDuplicatesAreNotAddedTwice(t *testing.T) {
+ detected := WithConfigured(nil, []string{"192.168.50.0/24"})
+ again := WithConfigured(detected, []string{"192.168.50.0/24"})
+
+ if len(again) != 1 {
+ t.Errorf("a network already present should not be added again, got %d", len(again))
+ }
+}
+
+func TestInvalidCIDRsAreIgnored(t *testing.T) {
+ got := WithConfigured(nil, []string{"not-a-network", "192.168.1.999/24", "192.168.50.0/24"})
+ if len(got) != 1 {
+ t.Fatalf("only the valid network should survive, got %d", len(got))
+ }
+ if got[0].CIDR != "192.168.50.0/24" {
+ t.Errorf("kept the wrong network: %q", got[0].CIDR)
+ }
+}
diff --git a/internal/network/container.go b/internal/network/container.go
new file mode 100644
index 0000000..4e5bb1d
--- /dev/null
+++ b/internal/network/container.go
@@ -0,0 +1,101 @@
+package network
+
+import (
+ "net"
+ "os"
+ "strings"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// InContainer reports whether this process is running inside a container.
+func InContainer() bool {
+ if _, err := os.Stat("/.dockerenv"); err == nil {
+ return true
+ }
+ if data, err := os.ReadFile("/proc/1/cgroup"); err == nil {
+ s := string(data)
+ if strings.Contains(s, "docker") || strings.Contains(s, "containerd") || strings.Contains(s, "kubepods") {
+ return true
+ }
+ }
+ return false
+}
+
+// dockerPrivateRanges are the address ranges a container sees when it is
+// attached to Docker's own network rather than the host's.
+var dockerPrivateRanges = []string{
+ "172.16.0.0/12", // default bridge networks
+ "192.168.65.0/24", // Docker Desktop's virtual machine
+ "10.88.0.0/16", // podman default
+}
+
+// isDockerPrivate reports whether a CIDR belongs to Docker's own networking
+// rather than a real LAN.
+func isDockerPrivate(cidr string) bool {
+ ip, _, err := net.ParseCIDR(cidr)
+ if err != nil {
+ return false
+ }
+ for _, r := range dockerPrivateRanges {
+ if _, block, err := net.ParseCIDR(r); err == nil && block.Contains(ip) {
+ return true
+ }
+ }
+ return false
+}
+
+// IsolatedFromLAN reports whether this process can only see container
+// networking, with no route onto a real local network.
+//
+// In that state a scan is not merely empty: the virtual network's gateway
+// answers probes on behalf of addresses that do not exist, so results contain
+// devices that were never there. That is worse than finding nothing, because
+// nothing about the output looks wrong.
+func IsolatedFromLAN(detected []types.Network) bool {
+ if !InContainer() {
+ return false
+ }
+ if len(detected) == 0 {
+ return true
+ }
+ for _, n := range detected {
+ if !isDockerPrivate(n.CIDR) {
+ return false
+ }
+ }
+ return true
+}
+
+// IsolationWarning describes the problem in a form suitable for showing to a
+// user. It returns an empty string when there is nothing wrong.
+func IsolationWarning(detected []types.Network) string {
+ if !IsolatedFromLAN(detected) {
+ return ""
+ }
+ return "This container can only see Docker's own network, not your LAN. " +
+ "Scans will miss your real devices and may report devices that do not exist. " +
+ "Use host networking on Linux, or run LAN Orangutan directly on macOS and Windows."
+}
+
+// ExcludeContainerNetworks drops Docker's own bridge networks from a detected
+// list.
+//
+// A host running Docker has a docker0 bridge, typically 172.17.0.0/16. It is a
+// real interface, so detection finds it, but it holds containers rather than
+// devices on your network. Scanning it sweeps 65,536 addresses to find nothing
+// of interest, which on a Raspberry Pi takes minutes and makes "Scan All" look
+// broken.
+//
+// Anyone who genuinely wants to scan it can still name it explicitly through
+// the networks setting.
+func ExcludeContainerNetworks(detected []types.Network) []types.Network {
+ out := make([]types.Network, 0, len(detected))
+ for _, n := range detected {
+ if isDockerPrivate(n.CIDR) {
+ continue
+ }
+ out = append(out, n)
+ }
+ return out
+}
diff --git a/internal/network/container_test.go b/internal/network/container_test.go
new file mode 100644
index 0000000..a2266b1
--- /dev/null
+++ b/internal/network/container_test.go
@@ -0,0 +1,75 @@
+package network
+
+import (
+ "testing"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+func TestDockerPrivateRangeDetection(t *testing.T) {
+ tests := []struct {
+ cidr string
+ private bool
+ }{
+ {"172.17.0.0/16", true}, // default docker bridge
+ {"172.18.0.0/16", true}, // user-defined bridge
+ {"192.168.65.0/24", true}, // Docker Desktop VM
+ {"10.88.0.0/16", true}, // podman
+ {"192.168.1.0/24", false}, // a real home LAN
+ {"192.168.68.0/22", false}, // a real home LAN
+ {"10.0.0.0/24", false}, // a real LAN
+ {"not-a-cidr", false},
+ }
+ for _, tt := range tests {
+ if got := isDockerPrivate(tt.cidr); got != tt.private {
+ t.Errorf("isDockerPrivate(%q) = %v, want %v", tt.cidr, got, tt.private)
+ }
+ }
+}
+
+func TestIsolationWarningOnlyWhenIsolated(t *testing.T) {
+ // Outside a container there is nothing to warn about, whatever the
+ // networks look like.
+ if w := IsolationWarning([]types.Network{{CIDR: "172.17.0.0/16"}}); !InContainer() && w != "" {
+ t.Error("no warning should be produced when not running in a container")
+ }
+}
+
+func TestRealNetworkMeansNotIsolated(t *testing.T) {
+ // A container that can see a real LAN, as with host networking, is fine.
+ networks := []types.Network{
+ {CIDR: "172.17.0.0/16"},
+ {CIDR: "192.168.1.0/24"},
+ }
+ if IsolatedFromLAN(networks) {
+ t.Error("a visible real network means the container is not isolated")
+ }
+}
+
+func TestExcludeContainerNetworks(t *testing.T) {
+ in := []types.Network{
+ {CIDR: "192.168.1.0/24"}, // real LAN
+ {CIDR: "172.17.0.0/16"}, // docker0 bridge
+ {CIDR: "192.168.68.0/22"}, // real LAN
+ {CIDR: "172.18.0.0/16"}, // user-defined docker bridge
+ {CIDR: "192.168.65.0/24"}, // Docker Desktop VM
+ }
+ got := ExcludeContainerNetworks(in)
+
+ if len(got) != 2 {
+ t.Fatalf("expected only the two real networks, got %d: %v", len(got), got)
+ }
+ for _, n := range got {
+ if n.CIDR != "192.168.1.0/24" && n.CIDR != "192.168.68.0/22" {
+ t.Errorf("unexpected network kept: %s", n.CIDR)
+ }
+ }
+}
+
+func TestConfiguredContainerNetworkIsStillHonoured(t *testing.T) {
+ // Filtering applies to detection, not to a network the user asked for.
+ got := WithConfigured(nil, []string{"172.17.0.0/16"})
+ if len(got) != 1 || got[0].CIDR != "172.17.0.0/16" {
+ t.Errorf("an explicitly configured network should survive, got %v", got)
+ }
+}
diff --git a/internal/network/detect.go b/internal/network/detect.go
index ad6835f..89306cf 100644
--- a/internal/network/detect.go
+++ b/internal/network/detect.go
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"net"
- "os/exec"
"runtime"
"strings"
@@ -175,21 +174,24 @@ func isWirelessInterface(ifname string) bool {
// GetDefaultGateway returns the default gateway IP
func GetDefaultGateway() (string, error) {
- var cmd *exec.Cmd
+ var (
+ name string
+ args []string
+ )
switch runtime.GOOS {
case "darwin":
// macOS: use netstat
- cmd = exec.Command("netstat", "-rn")
+ name, args = "netstat", []string{"-rn"}
case "linux":
// Linux: try ip command first
- cmd = exec.Command("ip", "-j", "route", "show", "default")
+ name, args = "ip", []string{"-j", "route", "show", "default"}
default:
// Fallback for other systems
- cmd = exec.Command("netstat", "-rn")
+ name, args = "netstat", []string{"-rn"}
}
- output, err := cmd.Output()
+ output, err := runCommand(name, args...)
if err != nil {
return "", fmt.Errorf("failed to get default route: %w", err)
}
@@ -222,8 +224,7 @@ func GetDefaultGateway() (string, error) {
// GetDNSServers returns configured DNS servers
func GetDNSServers() []string {
// Try systemd-resolved first
- cmd := exec.Command("resolvectl", "status")
- output, err := cmd.Output()
+ output, err := runCommand("resolvectl", "status")
if err == nil {
return parseDNSFromResolvectl(string(output))
}
@@ -251,8 +252,7 @@ func parseDNSFromResolvectl(output string) []string {
}
func parseDNSFromResolvConf() []string {
- cmd := exec.Command("grep", "nameserver", "/etc/resolv.conf")
- output, err := cmd.Output()
+ output, err := runCommand("grep", "nameserver", "/etc/resolv.conf")
if err != nil {
return nil
}
diff --git a/internal/network/exec.go b/internal/network/exec.go
new file mode 100644
index 0000000..29fe398
--- /dev/null
+++ b/internal/network/exec.go
@@ -0,0 +1,32 @@
+package network
+
+import (
+ "context"
+ "os/exec"
+ "time"
+)
+
+// commandTimeout bounds how long any helper process may run.
+//
+// These commands feed the dashboard, which renders synchronously. Without a
+// bound, a wedged helper (a hung `tailscale status`, an unresponsive
+// `resolvectl`) would hang the page rather than degrade it.
+const commandTimeout = 5 * time.Second
+
+// runCommand executes name with args and returns its standard output, giving up
+// after commandTimeout.
+//
+// A timeout is reported as an error like any other failure, so callers keep
+// their existing "no data available" behaviour instead of blocking.
+func runCommand(name string, args ...string) ([]byte, error) {
+ return runCommandTimeout(commandTimeout, name, args...)
+}
+
+// runCommandTimeout is runCommand with an explicit deadline, for callers that
+// need to allow more or less time than the default.
+func runCommandTimeout(timeout time.Duration, name string, args ...string) ([]byte, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+
+ return exec.CommandContext(ctx, name, args...).Output()
+}
diff --git a/internal/network/tailscale.go b/internal/network/tailscale.go
index e51427a..b29208d 100644
--- a/internal/network/tailscale.go
+++ b/internal/network/tailscale.go
@@ -88,7 +88,7 @@ func GetTailscaleDevices() []types.Device {
return nil
}
- output, err := exec.Command(tailscaleBin, "status", "--json").Output()
+ output, err := runCommand(tailscaleBin, "status", "--json")
if err != nil {
return nil
}
@@ -176,10 +176,9 @@ func GetTailscaleStatus() types.TailscaleStatus {
status.Installed = true
// Get tailscale status
- cmd := exec.Command(tailscaleBin, "status", "--json")
- output, err := cmd.Output()
+ output, err := runCommand(tailscaleBin, "status", "--json")
if err != nil {
- // Tailscale is installed but not running or not connected
+ // Tailscale is installed but not running, not connected, or wedged.
status.Running = false
return status
}
diff --git a/internal/scanner/oui.txt.gz b/internal/scanner/oui.txt.gz
new file mode 100644
index 0000000..91f0de8
Binary files /dev/null and b/internal/scanner/oui.txt.gz differ
diff --git a/internal/scanner/vendor.go b/internal/scanner/vendor.go
index f6ac7e9..34dea5f 100644
--- a/internal/scanner/vendor.go
+++ b/internal/scanner/vendor.go
@@ -1,84 +1,133 @@
package scanner
-import "strings"
-
-// macVendors maps MAC address prefixes to vendor names
-var macVendors = map[string]string{
- "00:50:56": "VMware",
- "00:0C:29": "VMware",
- "08:00:27": "VirtualBox",
- "52:54:00": "QEMU/KVM",
- "B8:27:EB": "Raspberry Pi",
- "DC:A6:32": "Raspberry Pi",
- "E4:5F:01": "Raspberry Pi",
- "28:CD:C1": "Raspberry Pi",
- "D8:3A:DD": "Raspberry Pi",
- "00:E0:4C": "Realtek",
- "00:15:5D": "Microsoft Hyper-V",
- "00:23:AE": "Dell",
- "00:14:22": "Dell",
- "18:A9:9B": "Dell",
- "3C:D9:2B": "HP",
- "00:1E:0B": "HP",
- "00:21:5A": "HP",
- "00:1F:C6": "ASUSTek",
- "00:1A:92": "ASUSTek",
- "14:DA:E9": "ASUSTek",
- "00:1C:C0": "Intel",
- "00:1F:3B": "Intel",
- "3C:A9:F4": "Intel",
- "5C:B9:01": "Ubiquiti",
- "00:27:22": "Ubiquiti",
- "04:18:D6": "Ubiquiti",
- "74:83:C2": "Ubiquiti",
- "FC:EC:DA": "Ubiquiti",
- "00:18:0A": "Cisco",
- "00:1B:2A": "Cisco",
- "64:F6:9D": "Cisco",
- "00:14:BF": "Linksys",
- "00:1A:70": "Linksys",
- "C0:C1:C0": "Linksys",
- "00:1F:33": "Netgear",
- "00:22:3F": "Netgear",
- "A0:63:91": "Netgear",
- "08:86:3B": "Belkin",
- "94:10:3E": "Belkin",
- "00:26:5A": "D-Link",
- "00:1E:58": "D-Link",
- "1C:7E:E5": "D-Link",
- "00:1D:0F": "TP-Link",
- "14:CC:20": "TP-Link",
- "50:C7:BF": "TP-Link",
- "00:25:00": "Apple",
- "00:26:08": "Apple",
- "28:CF:DA": "Apple",
- "3C:15:C2": "Apple",
- "5C:F9:38": "Apple",
- "78:31:C1": "Apple",
- "18:65:90": "Samsung",
- "50:01:BB": "Samsung",
- "94:35:0A": "Samsung",
- "2C:54:91": "Microsoft",
- "7C:1E:52": "Microsoft",
+import (
+ "bufio"
+ "bytes"
+ "compress/gzip"
+ _ "embed"
+ "strings"
+ "sync"
+)
+
+// ouiData is the IEEE MAC address registry, compressed, as
+// "PREFIX<tab>Organization" lines.
+//
+// It is embedded rather than fetched so vendor lookups work with no network
+// access, which matters for a tool often run on an isolated network.
+// Regenerate it with `make oui`.
+//
+//go:embed oui.txt.gz
+var ouiData []byte
+
+var (
+ ouiOnce sync.Once
+ ouiVendors map[string]string
+)
+
+// loadOUI decompresses and indexes the registry on first use.
+//
+// Parsing roughly forty thousand entries costs a few milliseconds, so it is
+// done lazily: commands that never look up a vendor never pay for it.
+func loadOUI() {
+ ouiVendors = make(map[string]string, 40000)
+
+ zr, err := gzip.NewReader(bytes.NewReader(ouiData))
+ if err != nil {
+ return
+ }
+ defer zr.Close()
+
+ scanner := bufio.NewScanner(zr)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for scanner.Scan() {
+ prefix, name, ok := strings.Cut(scanner.Text(), "\t")
+ if !ok {
+ continue
+ }
+ ouiVendors[prefix] = name
+ }
}
-// GetMACVendor looks up the vendor for a MAC address
+// normaliseMAC reduces a MAC address to bare uppercase hex, accepting the
+// aa:bb:cc, AA-BB-CC and aabbcc forms that different tools produce.
+func normaliseMAC(mac string) string {
+ var sb strings.Builder
+ sb.Grow(12)
+ for _, r := range mac {
+ switch {
+ case r >= '0' && r <= '9', r >= 'A' && r <= 'F':
+ sb.WriteRune(r)
+ case r >= 'a' && r <= 'f':
+ sb.WriteRune(r - 'a' + 'A')
+ }
+ }
+ return sb.String()
+}
+
+// GetMACVendor returns the manufacturer registered to a MAC address.
+//
+// It reports "Unknown" when the address is empty, malformed, or in a range that
+// is not publicly registered.
func GetMACVendor(mac string) string {
- if mac == "" {
+ normalised := normaliseMAC(mac)
+ if len(normalised) < 6 {
return "Unknown"
}
- // Normalize MAC address format
- mac = strings.ToUpper(strings.ReplaceAll(mac, "-", ":"))
+ ouiOnce.Do(loadOUI)
- // Get prefix (first 8 characters: XX:XX:XX)
- if len(mac) < 8 {
- return "Unknown"
+ if vendor, ok := ouiVendors[normalised[:6]]; ok {
+ return vendor
}
- prefix := mac[:8]
+ return "Unknown"
+}
- if vendor, ok := macVendors[prefix]; ok {
+// IsLocallyAdministered reports whether a MAC address was generated rather than
+// assigned to a manufacturer.
+//
+// Phones and laptops randomise their address to avoid being tracked between
+// networks. Such an address has no manufacturer to look up, which is worth
+// distinguishing from a vendor we simply do not recognise.
+func IsLocallyAdministered(mac string) bool {
+ normalised := normaliseMAC(mac)
+ if len(normalised) < 2 {
+ return false
+ }
+
+ firstOctet := hexByte(normalised[0], normalised[1])
+
+ // Bit 1 of the first octet is the locally-administered flag.
+ return firstOctet&0x02 != 0
+}
+
+// hexByte combines two hex digits into a byte. Callers must pass characters
+// that normaliseMAC has already validated.
+func hexByte(hi, lo byte) byte {
+ return hexNibble(hi)<<4 | hexNibble(lo)
+}
+
+func hexNibble(c byte) byte {
+ if c >= '0' && c <= '9' {
+ return c - '0'
+ }
+ return c - 'A' + 10
+}
+
+// ResolveVendor returns the manufacturer to display for a device.
+//
+// The vendor is normally recorded when a device is discovered, but records
+// created by an older version predate the full registry and hold an empty or
+// "Unknown" value. Falling back to a live lookup means an upgrade shows real
+// manufacturer names immediately, rather than only after the next scan.
+func ResolveVendor(stored, mac string) string {
+ if stored != "" && stored != "Unknown" {
+ return stored
+ }
+ if mac == "" {
+ return stored
+ }
+ if vendor := GetMACVendor(mac); vendor != "Unknown" {
return vendor
}
- return "Unknown"
+ return stored
}
diff --git a/internal/scanner/vendor_test.go b/internal/scanner/vendor_test.go
new file mode 100644
index 0000000..9a87843
--- /dev/null
+++ b/internal/scanner/vendor_test.go
@@ -0,0 +1,135 @@
+package scanner
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestKnownVendorsResolve(t *testing.T) {
+ // Well-known assignments that should be present in any current copy of the
+ // IEEE registry. These are checked by substring because organisations
+ // change their registered names over time.
+ tests := []struct {
+ mac string
+ contains string
+ }{
+ {"B8:27:EB:12:34:56", "Raspberry Pi"},
+ {"DC:A6:32:00:00:01", "Raspberry Pi"},
+ {"00:50:56:AA:BB:CC", "VMware"},
+ {"08:00:27:11:22:33", "PCS Systemtechnik"}, // VirtualBox
+ {"00:1B:63:84:45:E6", "Apple"},
+ {"3C:D9:2B:00:00:01", "Hewlett Packard"},
+ {"00:18:0A:00:00:01", "Cisco"},
+ }
+
+ for _, tt := range tests {
+ got := GetMACVendor(tt.mac)
+ if got == "Unknown" {
+ t.Errorf("GetMACVendor(%s) = Unknown, expected something containing %q", tt.mac, tt.contains)
+ continue
+ }
+ if !strings.Contains(strings.ToLower(got), strings.ToLower(tt.contains)) {
+ t.Errorf("GetMACVendor(%s) = %q, expected it to mention %q", tt.mac, got, tt.contains)
+ }
+ }
+}
+
+func TestVendorLookupAcceptsAllFormats(t *testing.T) {
+ // nmap, arp and Windows all format MAC addresses differently.
+ forms := []string{
+ "B8:27:EB:12:34:56",
+ "b8:27:eb:12:34:56",
+ "B8-27-EB-12-34-56",
+ "b827eb123456",
+ "B827EB123456",
+ }
+
+ want := GetMACVendor(forms[0])
+ if want == "Unknown" {
+ t.Fatal("expected the reference address to resolve")
+ }
+
+ for _, form := range forms {
+ if got := GetMACVendor(form); got != want {
+ t.Errorf("GetMACVendor(%q) = %q, want %q", form, got, want)
+ }
+ }
+}
+
+func TestUnknownAndMalformedAddresses(t *testing.T) {
+ tests := []string{
+ "",
+ "xx",
+ "not-a-mac",
+ "12:34", // too short to carry a prefix
+ "FF:FF:FF:FF:FF:FF", // broadcast, not a registered assignment
+ }
+
+ for _, mac := range tests {
+ if got := GetMACVendor(mac); got != "Unknown" {
+ t.Errorf("GetMACVendor(%q) = %q, want Unknown", mac, got)
+ }
+ }
+}
+
+func TestDatabaseIsSubstantial(t *testing.T) {
+ // Guards against the embedded file being empty or truncated, which would
+ // otherwise show up only as every device reading "Unknown".
+ ouiOnce.Do(loadOUI)
+
+ if len(ouiVendors) < 30000 {
+ t.Fatalf("only %d vendors loaded; the embedded registry looks incomplete", len(ouiVendors))
+ }
+}
+
+func TestLocallyAdministeredDetection(t *testing.T) {
+ tests := []struct {
+ mac string
+ want bool
+ }{
+ {"B8:27:EB:12:34:56", false}, // Raspberry Pi, globally assigned
+ {"00:50:56:AA:BB:CC", false}, // VMware, globally assigned
+ {"02:00:00:00:00:01", true}, // bit 1 set
+ {"06:11:22:33:44:55", true},
+ {"0A:11:22:33:44:55", true},
+ {"0E:11:22:33:44:55", true},
+ {"", false},
+ }
+
+ for _, tt := range tests {
+ if got := IsLocallyAdministered(tt.mac); got != tt.want {
+ t.Errorf("IsLocallyAdministered(%q) = %v, want %v", tt.mac, got, tt.want)
+ }
+ }
+}
+
+func TestResolveVendorFillsInMissingValues(t *testing.T) {
+ tests := []struct {
+ name string
+ stored string
+ mac string
+ wantLookup bool
+ wantLiteral string
+ }{
+ {name: "record from an older version has no vendor", stored: "", mac: "B8:27:EB:11:22:33", wantLookup: true},
+ {name: "older version stored Unknown", stored: "Unknown", mac: "B8:27:EB:11:22:33", wantLookup: true},
+ {name: "an existing value is trusted", stored: "Custom Name", mac: "B8:27:EB:11:22:33", wantLiteral: "Custom Name"},
+ {name: "no MAC to look up, keep what we have", stored: "", mac: "", wantLiteral: ""},
+ {name: "unregistered MAC keeps the stored value", stored: "Unknown", mac: "02:00:00:00:00:01", wantLiteral: "Unknown"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := ResolveVendor(tt.stored, tt.mac)
+ if tt.wantLookup {
+ if got == "" || got == "Unknown" {
+ t.Errorf("ResolveVendor(%q, %q) = %q, expected a looked-up manufacturer", tt.stored, tt.mac, got)
+ }
+ return
+ }
+ if got != tt.wantLiteral {
+ t.Errorf("ResolveVendor(%q, %q) = %q, want %q", tt.stored, tt.mac, got, tt.wantLiteral)
+ }
+ })
+ }
+}
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
index 2262eda..5b45375 100644
--- a/internal/storage/storage.go
+++ b/internal/storage/storage.go
@@ -38,12 +38,14 @@ func New(devicesFile, stateFile string) (*Storage, error) {
return nil, fmt.Errorf("failed to create data directory: %w", err)
}
- // Load existing data
+ // Load existing data. Name the file in the error: a damaged file is
+ // something the user has to go and look at, and "invalid character 'h'"
+ // on its own does not say where to look.
if err := s.loadDevices(); err != nil && !os.IsNotExist(err) {
- return nil, fmt.Errorf("failed to load devices: %w", err)
+ return nil, fmt.Errorf("could not read the device list at %s: %w", devicesFile, err)
}
if err := s.loadState(); err != nil && !os.IsNotExist(err) {
- return nil, fmt.Errorf("failed to load state: %w", err)
+ return nil, fmt.Errorf("could not read the scan history at %s: %w", stateFile, err)
}
return s, nil
@@ -259,6 +261,26 @@ func (s *Storage) GetLastScan(network string) time.Time {
return s.state.LastScan[network]
}
+// GetMostRecentScan returns the time of the most recent scan of any network.
+//
+// The device list is only as current as the last scan, so the dashboard shows
+// this alongside the per-device "last seen" times. Without it, a device last
+// seen during a scan hours ago still reads as though it were just checked.
+//
+// The zero time means nothing has ever been scanned.
+func (s *Storage) GetMostRecentScan() time.Time {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ var latest time.Time
+ for _, t := range s.state.LastScan {
+ if t.After(latest) {
+ latest = t
+ }
+ }
+ return latest
+}
+
// SetLastScan updates the last scan time for a network
func (s *Storage) SetLastScan(network string, t time.Time) error {
s.mu.Lock()
diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go
new file mode 100644
index 0000000..b11335a
--- /dev/null
+++ b/internal/storage/storage_test.go
@@ -0,0 +1,90 @@
+package storage
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+// newTestStorage returns storage backed by a throwaway directory.
+func newTestStorage(t *testing.T) *Storage {
+ t.Helper()
+
+ dir := t.TempDir()
+ s, err := New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ return s
+}
+
+func TestMostRecentScanIsZeroBeforeAnyScan(t *testing.T) {
+ s := newTestStorage(t)
+
+ if got := s.GetMostRecentScan(); !got.IsZero() {
+ t.Errorf("GetMostRecentScan() = %v, want the zero time before any scan", got)
+ }
+}
+
+func TestMostRecentScanWithOneNetwork(t *testing.T) {
+ s := newTestStorage(t)
+
+ when := time.Now().Add(-30 * time.Minute).Truncate(time.Second)
+ if err := s.SetLastScan("192.168.1.0/24", when); err != nil {
+ t.Fatalf("SetLastScan: %v", err)
+ }
+
+ if got := s.GetMostRecentScan(); !got.Equal(when) {
+ t.Errorf("GetMostRecentScan() = %v, want %v", got, when)
+ }
+}
+
+func TestMostRecentScanPicksTheLatest(t *testing.T) {
+ s := newTestStorage(t)
+
+ older := time.Now().Add(-2 * time.Hour).Truncate(time.Second)
+ newer := time.Now().Add(-5 * time.Minute).Truncate(time.Second)
+ middle := time.Now().Add(-1 * time.Hour).Truncate(time.Second)
+
+ // Set them out of order, so the result cannot come from insertion order.
+ if err := s.SetLastScan("10.0.0.0/24", middle); err != nil {
+ t.Fatalf("SetLastScan: %v", err)
+ }
+ if err := s.SetLastScan("192.168.1.0/24", newer); err != nil {
+ t.Fatalf("SetLastScan: %v", err)
+ }
+ if err := s.SetLastScan("172.16.0.0/24", older); err != nil {
+ t.Fatalf("SetLastScan: %v", err)
+ }
+
+ if got := s.GetMostRecentScan(); !got.Equal(newer) {
+ t.Errorf("GetMostRecentScan() = %v, want the most recent %v", got, newer)
+ }
+}
+
+func TestMostRecentScanSurvivesReload(t *testing.T) {
+ dir := t.TempDir()
+ devices := filepath.Join(dir, "devices.json")
+ state := filepath.Join(dir, "state.json")
+
+ first, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+
+ when := time.Now().Add(-15 * time.Minute).Truncate(time.Second)
+ if err := first.SetLastScan("192.168.1.0/24", when); err != nil {
+ t.Fatalf("SetLastScan: %v", err)
+ }
+
+ // A restart must not lose the timestamp, otherwise the dashboard would
+ // claim nothing had ever been scanned.
+ second, err := New(devices, state)
+ if err != nil {
+ t.Fatalf("reopening storage: %v", err)
+ }
+
+ if got := second.GetMostRecentScan(); !got.Equal(when) {
+ t.Errorf("after reload GetMostRecentScan() = %v, want %v", got, when)
+ }
+}
diff --git a/internal/web/handler.go b/internal/web/handler.go
index 1665383..7869c48 100644
--- a/internal/web/handler.go
+++ b/internal/web/handler.go
@@ -6,14 +6,15 @@ import (
"embed"
"fmt"
"html/template"
- "io/fs"
"net/http"
"sort"
"strings"
"time"
+ "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/scanner"
"github.com/291-Group/LAN-Orangutan/internal/storage"
"github.com/291-Group/LAN-Orangutan/internal/types"
)
@@ -28,6 +29,7 @@ var templateFS embed.FS
type Handler struct {
store *storage.Storage
cfg *config.Config
+ auth *auth.Authenticator
version string
templates *template.Template
staticFS http.Handler
@@ -45,6 +47,28 @@ type PageData struct {
Groups []string
CurrentGroup string
Error string
+
+ // AuthEnabled reports whether a password is configured, so pages can show
+ // a sign out link only when there is a session to end.
+ AuthEnabled bool
+
+ // MinPasswordLength is shown on the setup page and enforced by the browser.
+ MinPasswordLength int
+
+ // LastScanAgo and LastScanAt describe when the device list was last
+ // refreshed. Both are empty when nothing has been scanned yet.
+ LastScanAgo string
+ LastScanAt string
+
+ // NetworkWarning explains that this instance cannot see the local network,
+ // which happens in a container without host networking. Empty when fine.
+ NetworkWarning string
+
+ // LastScanUnix lets the page keep the relative time ticking without a
+ // reload. A server-rendered "1 min ago" would otherwise still claim one
+ // minute an hour later, which is the very confusion the footer exists to
+ // prevent.
+ LastScanUnix int64
}
// DeviceView is a device with computed display properties
@@ -54,10 +78,14 @@ type DeviceView struct {
StatusClass string
TimeAgo string
LastSeenUnix int64
+
+ // Vendor shadows the stored value so it can be resolved for records that
+ // predate the built-in manufacturer database.
+ Vendor string
}
// NewHandler creates a new web handler
-func NewHandler(store *storage.Storage, cfg *config.Config, version string) *Handler {
+func NewHandler(store *storage.Storage, cfg *config.Config, authn *auth.Authenticator, version string) *Handler {
// Parse templates with custom functions
funcMap := template.FuncMap{
"timeAgo": timeAgo,
@@ -67,18 +95,183 @@ func NewHandler(store *storage.Storage, cfg *config.Config, version string) *Han
tmpl := template.Must(template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html"))
// Create static file server
- staticSub, _ := fs.Sub(staticFS, "static")
- staticHandler := http.StripPrefix("/static/", http.FileServer(http.FS(staticSub)))
+ staticSub, _ := staticSubFS()
+ staticHandler := newStaticHandler(staticSub)
return &Handler{
store: store,
cfg: cfg,
+ auth: authn,
version: version,
templates: tmpl,
staticFS: staticHandler,
}
}
+// StaticHandler serves the embedded static assets.
+//
+// Exposed separately so the server can leave static files unauthenticated,
+// which the login page needs in order to style itself.
+func (h *Handler) StaticHandler() http.Handler {
+ return h.staticFS
+}
+
+// HandleSetup renders the first run page and creates the initial password.
+//
+// onPasswordSet persists the new hash. It is supplied by the caller so this
+// package does not need to know where credentials live.
+func (h *Handler) HandleSetup(onPasswordSet func(hash string) error) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ // Once a password exists there is nothing to set up, and this page must
+ // not become a way to overwrite it.
+ if !h.auth.NeedsSetup() {
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+ return
+ }
+
+ switch r.Method {
+ case http.MethodGet:
+ h.renderSetup(w, "", http.StatusOK)
+
+ case http.MethodPost:
+ if err := r.ParseForm(); err != nil {
+ h.renderSetup(w, "Could not read that submission. Please try again.", http.StatusBadRequest)
+ return
+ }
+
+ password := r.FormValue("password")
+ if password != r.FormValue("confirm") {
+ h.renderSetup(w, "Those passwords do not match.", http.StatusBadRequest)
+ return
+ }
+
+ if err := auth.ValidatePassword(password); err != nil {
+ h.renderSetup(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+
+ hash, err := h.auth.SetPassword(password)
+ if err != nil {
+ h.renderSetup(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+
+ if err := onPasswordSet(hash); err != nil {
+ // The password is live in memory but could not be saved, so it
+ // would vanish on restart. Say so rather than pretend.
+ h.renderSetup(w,
+ "Your password was set, but could not be saved: "+err.Error(),
+ http.StatusInternalServerError)
+ return
+ }
+
+ // Sign the user straight in rather than bouncing them to a login
+ // form for the password they just typed twice.
+ if token, ok := h.auth.StartSession(); ok {
+ h.auth.SetCookie(w, r, token)
+ }
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+
+ default:
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ }
+ }
+}
+
+// renderSetup draws the first run page, optionally with an error message.
+func (h *Handler) renderSetup(w http.ResponseWriter, message string, status int) {
+ data := PageData{
+ Title: "Welcome - LAN Orangutan",
+ Theme: h.cfg.UI.Theme,
+ Error: message,
+ MinPasswordLength: auth.MinPasswordLength,
+ }
+
+ var buf bytes.Buffer
+ if err := h.templates.ExecuteTemplate(&buf, "setup.html", data); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(status)
+ buf.WriteTo(w)
+}
+
+// HandleLogin renders the sign in form and processes submissions.
+func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request) {
+ // Send first run visitors to setup rather than a login form for a password
+ // that does not exist yet.
+ if h.auth.NeedsSetup() {
+ http.Redirect(w, r, auth.SetupPath, http.StatusSeeOther)
+ return
+ }
+
+ // With no password configured there is nothing to sign in to.
+ if !h.auth.Enabled() {
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+ return
+ }
+
+ switch r.Method {
+ case http.MethodGet:
+ h.renderLogin(w, "")
+
+ case http.MethodPost:
+ if err := r.ParseForm(); err != nil {
+ h.renderLogin(w, "Could not read that submission. Please try again.")
+ return
+ }
+
+ if h.auth.LockedOut(r.RemoteAddr) {
+ h.renderLogin(w, "Too many failed attempts. Please wait a few minutes and try again.")
+ return
+ }
+
+ token, ok := h.auth.Login(r.RemoteAddr, r.FormValue("password"))
+ if !ok {
+ h.renderLogin(w, "Incorrect password.")
+ return
+ }
+
+ h.auth.SetCookie(w, r, token)
+ http.Redirect(w, r, "/", http.StatusSeeOther)
+
+ default:
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
+// HandleLogout ends the current session.
+func (h *Handler) HandleLogout(w http.ResponseWriter, r *http.Request) {
+ h.auth.Logout(r)
+ h.auth.ClearCookie(w, r)
+ http.Redirect(w, r, auth.LoginPath, http.StatusSeeOther)
+}
+
+// renderLogin draws the sign in page, optionally with an error message.
+func (h *Handler) renderLogin(w http.ResponseWriter, message string) {
+ data := PageData{
+ Title: "Sign in - LAN Orangutan",
+ Theme: h.cfg.UI.Theme,
+ Error: message,
+ }
+
+ var buf bytes.Buffer
+ if err := h.templates.ExecuteTemplate(&buf, "login.html", data); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ // A failed attempt is not a successful page load; say so for any client
+ // that pays attention to the status code.
+ if message != "" {
+ w.WriteHeader(http.StatusUnauthorized)
+ }
+ buf.WriteTo(w)
+}
+
// ServeHTTP implements http.Handler
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
@@ -114,6 +307,9 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
Device: d,
TimeAgo: timeAgo(d.LastSeen),
LastSeenUnix: d.LastSeen.Unix(),
+ // Devices recorded by an older version have no vendor stored, so
+ // look it up now rather than showing "Unknown" until a rescan.
+ Vendor: scanner.ResolveVendor(d.Vendor, d.MAC),
}
if d.IsRecent() {
@@ -148,6 +344,7 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
// Get networks
networks, _ := network.DetectNetworks()
+ networks = network.WithConfigured(networks, h.cfg.Scanning.Networks)
// Get Tailscale status
tailscale := network.GetTailscaleStatus()
@@ -156,13 +353,24 @@ func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
stats := h.store.GetStats()
data := PageData{
- Title: "LAN Orangutan",
- Theme: h.cfg.UI.Theme,
- Devices: deviceViews,
- Networks: networks,
- Tailscale: tailscale,
- Stats: stats,
- Groups: groups,
+ Title: "LAN Orangutan",
+ Theme: h.cfg.UI.Theme,
+ Devices: deviceViews,
+ Networks: networks,
+ Tailscale: tailscale,
+ Stats: stats,
+ Groups: groups,
+ AuthEnabled: h.auth.Enabled(),
+ }
+
+ data.NetworkWarning = network.IsolationWarning(networks)
+
+ // The table is only as current as the last scan. Say so, so that a "last
+ // seen" time is read against when the data was actually gathered.
+ if lastScan := h.store.GetMostRecentScan(); !lastScan.IsZero() {
+ data.LastScanAgo = timeAgo(lastScan)
+ data.LastScanAt = lastScan.Format("Jan 2, 2006 at 3:04 PM")
+ data.LastScanUnix = lastScan.Unix()
}
// Buffer the template output to avoid superfluous WriteHeader on error
@@ -184,11 +392,12 @@ func (h *Handler) handleSettings(w http.ResponseWriter, r *http.Request) {
stats := h.store.GetStats()
data := PageData{
- Title: "Settings - LAN Orangutan",
- Theme: h.cfg.UI.Theme,
- Version: h.version,
- Tailscale: tailscale,
- Stats: stats,
+ Title: "Settings - LAN Orangutan",
+ Theme: h.cfg.UI.Theme,
+ Version: h.version,
+ Tailscale: tailscale,
+ Stats: stats,
+ AuthEnabled: h.auth.Enabled(),
}
// Buffer the template output to avoid superfluous WriteHeader on error
diff --git a/internal/web/handler_test.go b/internal/web/handler_test.go
new file mode 100644
index 0000000..4f1fac0
--- /dev/null
+++ b/internal/web/handler_test.go
@@ -0,0 +1,516 @@
+package web
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/auth"
+ "github.com/291-Group/LAN-Orangutan/internal/config"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+)
+
+const testPassword = "test-password"
+
+// newTestHandler builds a web handler backed by throwaway storage.
+func newTestHandler(t *testing.T, password string) (*Handler, *auth.Authenticator) {
+ t.Helper()
+
+ dir := t.TempDir()
+ store, err := storage.New(filepath.Join(dir, "devices.json"), filepath.Join(dir, "state.json"))
+ if err != nil {
+ t.Fatalf("storage.New: %v", err)
+ }
+
+ cfg := config.Default()
+ cfg.Server.Password = password
+
+ authn, err := auth.New(password, time.Hour)
+ if err != nil {
+ t.Fatalf("auth.New: %v", err)
+ }
+
+ return NewHandler(store, cfg, authn, "test"), authn
+}
+
+func TestLoginPageRenders(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ rec := httptest.NewRecorder()
+ h.HandleLogin(rec, httptest.NewRequest(http.MethodGet, auth.LoginPath, nil))
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("login page status = %d, want 200", rec.Code)
+ }
+
+ body := rec.Body.String()
+ if !strings.Contains(body, `name="password"`) {
+ t.Error("login page should contain a password field")
+ }
+ if !strings.Contains(body, `type="password"`) {
+ t.Error("the password field should mask what is typed")
+ }
+}
+
+func TestLoginPageRedirectsWhenNoPasswordConfigured(t *testing.T) {
+ h, _ := newTestHandler(t, "")
+
+ rec := httptest.NewRecorder()
+ h.HandleLogin(rec, httptest.NewRequest(http.MethodGet, auth.LoginPath, nil))
+
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("status = %d, want a redirect when there is nothing to sign in to", rec.Code)
+ }
+}
+
+// postLogin submits the login form with the given password.
+func postLogin(t *testing.T, h *Handler, password string) *httptest.ResponseRecorder {
+ t.Helper()
+
+ form := url.Values{"password": {password}}
+ req := httptest.NewRequest(http.MethodPost, auth.LoginPath, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.RemoteAddr = "192.168.1.9:5000"
+
+ rec := httptest.NewRecorder()
+ h.HandleLogin(rec, req)
+ return rec
+}
+
+func TestSuccessfulLoginSetsCookieAndRedirects(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ rec := postLogin(t, h, testPassword)
+
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("status = %d, want a redirect after signing in", rec.Code)
+ }
+ if got := rec.Header().Get("Location"); got != "/" {
+ t.Errorf("redirected to %q, want the dashboard", got)
+ }
+
+ cookies := rec.Result().Cookies()
+ if len(cookies) == 0 {
+ t.Fatal("a successful login should set a session cookie")
+ }
+ if cookies[0].Name != auth.SessionCookie {
+ t.Errorf("cookie name = %q, want %q", cookies[0].Name, auth.SessionCookie)
+ }
+ if cookies[0].Value == "" {
+ t.Error("the session cookie should carry a token")
+ }
+}
+
+func TestFailedLoginShowsErrorAndSetsNoCookie(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ rec := postLogin(t, h, "wrong-password")
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("status = %d, want 401 for a rejected password", rec.Code)
+ }
+ if len(rec.Result().Cookies()) != 0 {
+ t.Fatal("a failed login must not set a session cookie")
+ }
+ if !strings.Contains(rec.Body.String(), "Incorrect password") {
+ t.Error("the page should tell the user the password was wrong")
+ }
+}
+
+func TestFailedLoginDoesNotEchoTheAttempt(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ const attempt = "my-secret-guess"
+ body := postLogin(t, h, attempt).Body.String()
+
+ // Reflecting the attempted password back into the page would leak it into
+ // browser history and any shared screenshot.
+ if strings.Contains(body, attempt) {
+ t.Error("the failed attempt must not be echoed back into the page")
+ }
+}
+
+func TestLockoutMessageAfterRepeatedFailures(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ var last *httptest.ResponseRecorder
+ for i := 0; i < 6; i++ {
+ last = postLogin(t, h, "wrong-password")
+ }
+
+ if !strings.Contains(last.Body.String(), "Too many failed attempts") {
+ t.Error("after repeated failures the page should explain the lockout")
+ }
+}
+
+func TestLogoutClearsCookieAndRedirects(t *testing.T) {
+ h, authn := newTestHandler(t, testPassword)
+
+ token, ok := authn.Login("192.168.1.9:5000", testPassword)
+ if !ok {
+ t.Fatal("login failed")
+ }
+
+ req := httptest.NewRequest(http.MethodGet, auth.LogoutPath, nil)
+ req.AddCookie(&http.Cookie{Name: auth.SessionCookie, Value: token})
+ rec := httptest.NewRecorder()
+
+ h.HandleLogout(rec, req)
+
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("status = %d, want a redirect after signing out", rec.Code)
+ }
+ if got := rec.Header().Get("Location"); got != auth.LoginPath {
+ t.Errorf("redirected to %q, want the login page", got)
+ }
+
+ cookies := rec.Result().Cookies()
+ if len(cookies) == 0 || cookies[0].MaxAge >= 0 {
+ t.Error("signing out should expire the session cookie")
+ }
+
+ // The session must be dead server side, not just cleared in the browser.
+ after := httptest.NewRequest(http.MethodGet, "/", nil)
+ after.AddCookie(&http.Cookie{Name: auth.SessionCookie, Value: token})
+ rec2 := httptest.NewRecorder()
+ authn.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })).ServeHTTP(rec2, after)
+
+ if rec2.Code == http.StatusOK {
+ t.Error("the old token should be rejected after signing out")
+ }
+}
+
+func TestLoginRejectsUnsupportedMethod(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ rec := httptest.NewRecorder()
+ h.HandleLogin(rec, httptest.NewRequest(http.MethodDelete, auth.LoginPath, nil))
+
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Errorf("status = %d, want 405", rec.Code)
+ }
+}
+
+// TestDashboardIsProtected checks the whole route wiring the way the server
+// assembles it, rather than testing the middleware in isolation.
+func TestDashboardIsProtected(t *testing.T) {
+ h, authn := newTestHandler(t, testPassword)
+
+ mux := http.NewServeMux()
+ mux.Handle("/", authn.Middleware(reached()))
+ mux.Handle("/static/", h.StaticHandler())
+ mux.HandleFunc(auth.LoginPath, h.HandleLogin)
+
+ tests := []struct {
+ name string
+ path string
+ wantStatus int
+ }{
+ {"dashboard requires a session", "/", http.StatusSeeOther},
+ {"settings requires a session", "/settings", http.StatusSeeOther},
+ {"login page stays reachable", auth.LoginPath, http.StatusOK},
+ {"stylesheet stays reachable", "/static/style.css", http.StatusOK},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, tt.path, nil))
+
+ if rec.Code != tt.wantStatus {
+ t.Errorf("GET %s = %d, want %d", tt.path, rec.Code, tt.wantStatus)
+ }
+ })
+ }
+}
+
+// reached stands in for the dashboard when the test cares about whether a
+// request got through the middleware, not about what the page renders.
+// Rendering the real dashboard shells out to network tools, which does not
+// belong in a test of the authentication wiring.
+func reached() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+}
+
+func TestDashboardReachableAfterSignIn(t *testing.T) {
+ _, authn := newTestHandler(t, testPassword)
+
+ mux := http.NewServeMux()
+ mux.Handle("/", authn.Middleware(reached()))
+
+ token, ok := authn.Login("192.168.1.9:5000", testPassword)
+ if !ok {
+ t.Fatal("login failed")
+ }
+
+ req := httptest.NewRequest(http.MethodGet, "/", nil)
+ req.AddCookie(&http.Cookie{Name: auth.SessionCookie, Value: token})
+ rec := httptest.NewRecorder()
+
+ mux.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("dashboard status = %d, want 200 once signed in", rec.Code)
+ }
+}
+
+func TestDashboardOpenWhenNoPasswordSet(t *testing.T) {
+ _, authn := newTestHandler(t, "")
+
+ mux := http.NewServeMux()
+ mux.Handle("/", authn.Middleware(reached()))
+
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("dashboard status = %d, want 200 when no password is configured", rec.Code)
+ }
+}
+
+// --- First run setup ---------------------------------------------------
+
+// newSetupHandler builds a handler in the first run state, plus a pointer to
+// wherever a saved password hash ends up.
+func newSetupHandler(t *testing.T) (*Handler, *auth.Authenticator, *string) {
+ t.Helper()
+
+ h, authn := newTestHandler(t, "")
+ authn.SetSetupRequired(true)
+
+ var saved string
+ return h, authn, &saved
+}
+
+func setupHandler(h *Handler, saved *string) http.HandlerFunc {
+ return h.HandleSetup(func(hash string) error {
+ *saved = hash
+ return nil
+ })
+}
+
+// postSetup submits the setup form.
+func postSetup(h *Handler, saved *string, password, confirm string) *httptest.ResponseRecorder {
+ form := url.Values{"password": {password}, "confirm": {confirm}}
+ req := httptest.NewRequest(http.MethodPost, auth.SetupPath, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.RemoteAddr = "192.168.1.9:5000"
+
+ rec := httptest.NewRecorder()
+ setupHandler(h, saved)(rec, req)
+ return rec
+}
+
+func TestSetupPageShownOnFirstRun(t *testing.T) {
+ h, _, saved := newSetupHandler(t)
+
+ rec := httptest.NewRecorder()
+ setupHandler(h, saved)(rec, httptest.NewRequest(http.MethodGet, auth.SetupPath, nil))
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("setup page status = %d, want 200", rec.Code)
+ }
+
+ body := rec.Body.String()
+ if !strings.Contains(body, "Create a password") {
+ t.Error("the setup page should ask the user to create a password")
+ }
+ if !strings.Contains(body, `name="confirm"`) {
+ t.Error("the setup page should ask for confirmation")
+ }
+}
+
+func TestEverythingRedirectsToSetupOnFirstRun(t *testing.T) {
+ h, authn, saved := newSetupHandler(t)
+
+ mux := http.NewServeMux()
+ mux.Handle("/", authn.Middleware(reached()))
+ mux.Handle("/static/", h.StaticHandler())
+ mux.HandleFunc(auth.SetupPath, setupHandler(h, saved))
+ mux.HandleFunc(auth.LoginPath, h.HandleLogin)
+
+ tests := []struct {
+ name string
+ path string
+ wantStatus int
+ wantLoc string
+ }{
+ {"dashboard goes to setup", "/", http.StatusSeeOther, auth.SetupPath},
+ {"settings goes to setup", "/settings", http.StatusSeeOther, auth.SetupPath},
+ {"login goes to setup", auth.LoginPath, http.StatusSeeOther, auth.SetupPath},
+ {"setup itself is reachable", auth.SetupPath, http.StatusOK, ""},
+ {"stylesheet is reachable", "/static/style.css", http.StatusOK, ""},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, tt.path, nil))
+
+ if rec.Code != tt.wantStatus {
+ t.Errorf("GET %s = %d, want %d", tt.path, rec.Code, tt.wantStatus)
+ }
+ if tt.wantLoc != "" {
+ if got := rec.Header().Get("Location"); got != tt.wantLoc {
+ t.Errorf("GET %s redirected to %q, want %q", tt.path, got, tt.wantLoc)
+ }
+ }
+ })
+ }
+}
+
+func TestAPIRefusedDuringSetup(t *testing.T) {
+ _, authn, _ := newSetupHandler(t)
+
+ mux := http.NewServeMux()
+ mux.Handle("/api/", authn.Middleware(reached()))
+
+ rec := httptest.NewRecorder()
+ mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/devices", nil))
+
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("API during setup = %d, want 401", rec.Code)
+ }
+}
+
+func TestSetupCreatesPasswordAndSignsIn(t *testing.T) {
+ h, authn, saved := newSetupHandler(t)
+
+ rec := postSetup(h, saved, "a-good-password", "a-good-password")
+
+ if rec.Code != http.StatusSeeOther {
+ t.Fatalf("status = %d, want a redirect after setup", rec.Code)
+ }
+ if got := rec.Header().Get("Location"); got != "/" {
+ t.Errorf("redirected to %q, want the dashboard", got)
+ }
+
+ if !authn.Enabled() {
+ t.Error("a password should exist after setup")
+ }
+ if authn.NeedsSetup() {
+ t.Error("setup should be complete")
+ }
+
+ // Signed straight in rather than bounced to a login form.
+ cookies := rec.Result().Cookies()
+ if len(cookies) == 0 || cookies[0].Name != auth.SessionCookie {
+ t.Error("completing setup should sign the user in")
+ }
+}
+
+func TestSetupPersistsTheHash(t *testing.T) {
+ h, _, saved := newSetupHandler(t)
+
+ postSetup(h, saved, "a-good-password", "a-good-password")
+
+ if *saved == "" {
+ t.Fatal("the new password should have been handed over for saving")
+ }
+ if strings.Contains(*saved, "a-good-password") {
+ t.Error("what gets saved must be a hash, not the password itself")
+ }
+ if !strings.HasPrefix(*saved, "$2") {
+ t.Errorf("saved value %q does not look like a bcrypt hash", *saved)
+ }
+}
+
+func TestSetupRejectsMismatchedConfirmation(t *testing.T) {
+ h, authn, saved := newSetupHandler(t)
+
+ rec := postSetup(h, saved, "a-good-password", "a-different-password")
+
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("status = %d, want 400", rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), "do not match") {
+ t.Error("the page should say the passwords do not match")
+ }
+ if authn.Enabled() {
+ t.Error("no password should have been set")
+ }
+ if *saved != "" {
+ t.Error("nothing should have been saved")
+ }
+}
+
+func TestSetupRejectsShortPassword(t *testing.T) {
+ h, authn, saved := newSetupHandler(t)
+
+ short := strings.Repeat("a", auth.MinPasswordLength-1)
+ rec := postSetup(h, saved, short, short)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("status = %d, want 400", rec.Code)
+ }
+ if authn.Enabled() {
+ t.Error("a too-short password should not be accepted")
+ }
+}
+
+func TestSetupCannotBeUsedTwice(t *testing.T) {
+ h, authn, saved := newSetupHandler(t)
+
+ postSetup(h, saved, "first-password", "first-password")
+ firstHash := *saved
+
+ // A second attempt must not be able to take the account over.
+ rec := postSetup(h, saved, "attacker-password", "attacker-password")
+
+ if rec.Code != http.StatusSeeOther {
+ t.Errorf("status = %d, want a redirect away from setup", rec.Code)
+ }
+ if *saved != firstHash {
+ t.Error("the stored password must not be overwritten by a second setup attempt")
+ }
+ if _, ok := authn.Login("192.168.1.9:5000", "attacker-password"); ok {
+ t.Fatal("the second password must not work")
+ }
+ if _, ok := authn.Login("192.168.1.9:5000", "first-password"); !ok {
+ t.Error("the original password should still work")
+ }
+}
+
+func TestSetupReportsSaveFailure(t *testing.T) {
+ h, _, _ := newSetupHandler(t)
+
+ failing := h.HandleSetup(func(string) error {
+ return fmt.Errorf("disk is full")
+ })
+
+ form := url.Values{"password": {"a-good-password"}, "confirm": {"a-good-password"}}
+ req := httptest.NewRequest(http.MethodPost, auth.SetupPath, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ rec := httptest.NewRecorder()
+
+ failing(rec, req)
+
+ if rec.Code != http.StatusInternalServerError {
+ t.Errorf("status = %d, want 500 when the password cannot be saved", rec.Code)
+ }
+ // Silently carrying on would lose the password at the next restart.
+ if !strings.Contains(rec.Body.String(), "disk is full") {
+ t.Error("the user should be told why the password could not be saved")
+ }
+}
+
+func TestNoSetupWhenPasswordAlreadyConfigured(t *testing.T) {
+ h, _ := newTestHandler(t, testPassword)
+
+ var saved string
+ rec := httptest.NewRecorder()
+ setupHandler(h, &saved)(rec, httptest.NewRequest(http.MethodGet, auth.SetupPath, nil))
+
+ if rec.Code != http.StatusSeeOther {
+ t.Errorf("status = %d, want a redirect when a password already exists", rec.Code)
+ }
+}
diff --git a/internal/web/static.go b/internal/web/static.go
new file mode 100644
index 0000000..3df5d3c
--- /dev/null
+++ b/internal/web/static.go
@@ -0,0 +1,98 @@
+package web
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "io"
+ "io/fs"
+ "net/http"
+ "path"
+ "strings"
+ "time"
+)
+
+// staticHandler serves the embedded assets with a content based ETag.
+//
+// The previous handler served these files with no ETag and no Cache-Control,
+// and embedded files all carry a zero modification time, so browsers cached
+// them heuristically and kept showing stale CSS and JS after an update. Here
+// each file gets an ETag derived from its own contents: the browser revalidates
+// on each load and receives a small 304 when nothing changed, or the fresh file
+// the moment it does. On a local network that revalidation costs nothing.
+type staticHandler struct {
+ fsys fs.FS
+ etags map[string]string
+}
+
+// staticSubFS returns the embedded static assets rooted at their directory.
+func staticSubFS() (fs.FS, error) {
+ return fs.Sub(staticFS, "static")
+}
+
+// newStaticHandler indexes the content hash of every embedded asset once, at
+// startup, so requests do not have to hash anything.
+func newStaticHandler(fsys fs.FS) *staticHandler {
+ h := &staticHandler{fsys: fsys, etags: make(map[string]string)}
+
+ fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
+ if err != nil || d.IsDir() {
+ return nil
+ }
+ data, err := fs.ReadFile(fsys, p)
+ if err != nil {
+ return nil
+ }
+ sum := sha256.Sum256(data)
+ // Eight bytes of the hash is ample to detect a change, and keeps the
+ // header short.
+ h.etags[p] = `"` + hex.EncodeToString(sum[:8]) + `"`
+ return nil
+ })
+
+ return h
+}
+
+// ServeHTTP serves a single asset. The request path is expected to begin with
+// "/static/".
+func (h *staticHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ name := path.Clean(strings.TrimPrefix(r.URL.Path, "/static/"))
+ if name == "." || strings.HasPrefix(name, "..") {
+ http.NotFound(w, r)
+ return
+ }
+
+ file, err := h.fsys.Open(name)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ defer file.Close()
+
+ info, err := file.Stat()
+ if err != nil || info.IsDir() {
+ http.NotFound(w, r)
+ return
+ }
+
+ if etag, ok := h.etags[name]; ok {
+ w.Header().Set("Etag", etag)
+ // Cache, but revalidate against the ETag every load so an update is
+ // never missed.
+ w.Header().Set("Cache-Control", "no-cache")
+ }
+
+ // http.ServeContent handles Range and, because an ETag is set above,
+ // If-None-Match: it replies 304 when the browser's copy is current. Files
+ // from an embed.FS are seekable; the buffer is only a fallback.
+ if rs, ok := file.(io.ReadSeeker); ok {
+ http.ServeContent(w, r, info.Name(), time.Time{}, rs)
+ return
+ }
+ data, err := io.ReadAll(file)
+ if err != nil {
+ http.Error(w, "could not read asset", http.StatusInternalServerError)
+ return
+ }
+ http.ServeContent(w, r, info.Name(), time.Time{}, bytes.NewReader(data))
+}
diff --git a/internal/web/static/app.js b/internal/web/static/app.js
index fb87aef..93454ac 100644
--- a/internal/web/static/app.js
+++ b/internal/web/static/app.js
@@ -1,10 +1,32 @@
-// Theme toggle
+// Theme
+
+// applyTheme switches the theme with transitions turned off for the switch, so
+// every element changes at the same instant. Left on, some elements fade over
+// their own transition while others (the page background) snap immediately,
+// which reads as the page changing in pieces.
+function applyTheme(theme) {
+ const root = document.documentElement;
+ // Do this synchronously with forced reflows rather than on an animation
+ // frame: requestAnimationFrame does not fire in a background tab, which
+ // would leave transitions disabled if the tab lost focus mid-switch.
+ root.classList.add('theme-switching');
+ void root.offsetWidth; // commit "transitions off"
+ root.setAttribute('data-theme', theme);
+ void root.offsetWidth; // commit the new theme instantly
+ root.classList.remove('theme-switching'); // restore transitions for hover
+ localStorage.setItem('theme', theme);
+}
+
+// The header button is a plain light/dark switch. It used to cycle
+// light -> dark -> auto, but "auto" looks identical to whichever mode the
+// system is already in, so every third click appeared to do nothing. "Auto"
+// (follow the system) still lives on the settings page for anyone who wants it.
function toggleTheme() {
- const html = document.documentElement;
- const current = html.getAttribute('data-theme');
- let next = current === 'light' ? 'dark' : current === 'dark' ? 'auto' : 'light';
- html.setAttribute('data-theme', next);
- localStorage.setItem('theme', next);
+ let current = document.documentElement.getAttribute('data-theme');
+ if (!current || current === 'auto') {
+ current = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
+ }
+ applyTheme(current === 'dark' ? 'light' : 'dark');
}
// Initialize theme
@@ -91,16 +113,38 @@ function showScanProgress(p) {
if (detail) {
const parts = [];
if (p.network_count > 1) parts.push(`Network ${p.network_index} of ${p.network_count}`);
- parts.push(`${p.device_count} device${p.device_count === 1 ? '' : 's'} found`);
+ if (p.current_network) parts.push(p.current_network);
+
detail.textContent = parts.join(' · ');
}
+ // The running total gets its own line. Appended to the line above it wrapped
+ // mid-sentence once more than one network was involved.
+ //
+ // Only claim a count once there is one: nmap reports nothing until its
+ // sweep finishes, so a permanent "0 devices found" reads as a failed scan
+ // rather than an unfinished one.
+ const count = document.getElementById('scan-count');
+ if (count) {
+ count.textContent = p.device_count > 0
+ ? `${p.device_count} device${p.device_count === 1 ? '' : 's'} found`
+ : '';
+ }
+
const eta = document.getElementById('scan-eta');
if (eta) {
eta.textContent = known && p.remaining != null
? `~${formatSeconds(p.remaining)} left · ${Math.round(p.percent)}%`
: `${formatSeconds(p.elapsed)} elapsed`;
}
+
+ // Set expectations explicitly while there is nothing to report yet.
+ const hint = document.getElementById('scan-hint');
+ if (hint) {
+ hint.textContent = p.device_count > 0
+ ? ''
+ : 'Checking every address on the network. Devices are listed once the sweep finishes.';
+ }
}
function hideScanProgress() {
@@ -123,7 +167,7 @@ function reportScanOutcome(p) {
const scanned = (p.networks || []).filter(n => n.status === 'scanned');
if (p.status === 'cancelled') {
showToast('Scan cancelled', 'warning');
- if (scanned.length) setTimeout(() => location.reload(), 1000);
+ if (scanned.length) setTimeout(refreshAfterScan, 1000);
return;
}
if (scanned.length === 0) {
@@ -133,24 +177,36 @@ function reportScanOutcome(p) {
}
const where = p.network_count > 1 ? ` across ${scanned.length} network${scanned.length === 1 ? '' : 's'}` : '';
showToast(`Found ${p.device_count} device${p.device_count === 1 ? '' : 's'}${where}`, 'success');
- setTimeout(() => location.reload(), 1000);
+ setTimeout(refreshAfterScan, 1000);
+}
+
+// refreshAfterScan brings in the newly discovered devices without throwing away
+// the user's scroll position, search text or filters.
+async function refreshAfterScan() {
+ if (!(await refreshInPlace())) location.reload();
+}
+
+// Follows a scan that is already running until it stops. Scans live on the
+// server, not in the page, so this is used both by the page that starts one and
+// by any page loaded while one is already in progress.
+async function followScan() {
+ while (true) {
+ await new Promise(r => setTimeout(r, SCAN_POLL_MS));
+ const progress = (await api('scan/progress')).data;
+ if (progress.status !== 'running') {
+ hideScanProgress();
+ reportScanOutcome(progress);
+ return;
+ }
+ showScanProgress(progress);
+ }
}
async function runScan(target) {
try {
const started = await api(`scan/start?network=${encodeURIComponent(target)}`, {}, 'POST');
showScanProgress(started.data);
-
- while (true) {
- await new Promise(r => setTimeout(r, SCAN_POLL_MS));
- const progress = (await api('scan/progress')).data;
- if (progress.status !== 'running') {
- hideScanProgress();
- reportScanOutcome(progress);
- return;
- }
- showScanProgress(progress);
- }
+ await followScan();
} catch (e) {
hideScanProgress();
const isRateLimit = e.message.toLowerCase().includes('rate limit');
@@ -158,6 +214,23 @@ async function runScan(target) {
}
}
+// Picks up a scan that was started before this page was loaded, for instance
+// when the user starts a scan and then moves to the settings page. Without
+// this, the scan carries on invisibly and the page never notices it finish.
+async function resumeScanIfRunning() {
+ try {
+ const progress = (await api('scan/progress')).data;
+ if (progress && progress.status === 'running') {
+ showScanProgress(progress);
+ await followScan();
+ }
+ } catch (e) {
+ // No scan has ever run, or this page cannot ask. Nothing to show.
+ }
+}
+
+resumeScanIfRunning();
+
async function scanNetwork(cidr) {
await runScan(cidr);
}
@@ -190,7 +263,7 @@ function filterDevices() {
});
const countEl = document.getElementById('device-count');
- if (countEl) countEl.textContent = `Showing ${visible} devices`;
+ if (countEl) countEl.textContent = `Showing ${visible} device${visible === 1 ? '' : 's'}`;
}
// Device editing
@@ -221,7 +294,9 @@ async function saveDevice() {
if (result.success) {
showToast('Device updated', 'success');
closeModal();
- location.reload();
+ // Keep the user where they were; editing a device halfway down a
+ // long list should not jump back to the top.
+ if (!(await refreshInPlace())) location.reload();
} else {
showToast(result.error || 'Failed to update device', 'error');
}
@@ -417,8 +492,60 @@ function sortTable(column) {
}
// Auto-refresh
+//
+// Refreshing must never disturb what the user is doing. Reloading the page
+// would reset the scroll position, empty the search box, drop the status and
+// group filters and undo any sorting, every thirty seconds. Instead the page is
+// fetched in the background and only the parts that carry data are swapped in.
+const AUTO_REFRESH_MS = 30000;
let autoRefreshInterval = null;
+// refreshInPlace replaces the device table, the summary cards and the scan
+// footer with fresh copies from the server.
+//
+// The markup comes from the server rather than being rebuilt here, so there is
+// only ever one definition of how a device row looks.
+//
+// Returns false if the refresh could not be applied, which usually means the
+// session has ended and the response was the login page.
+async function refreshInPlace() {
+ let doc;
+ try {
+ const response = await fetch(location.href, { credentials: 'same-origin' });
+ if (!response.ok) return false;
+ doc = new DOMParser().parseFromString(await response.text(), 'text/html');
+ } catch (e) {
+ return false;
+ }
+
+ const freshRows = doc.getElementById('devices-tbody');
+ if (!freshRows) return false;
+
+ document.getElementById('devices-tbody')?.replaceWith(freshRows);
+
+ for (const selector of ['.stats-bar', '.table-footer', '#device-count']) {
+ const current = document.querySelector(selector);
+ const replacement = doc.querySelector(selector);
+ if (current && replacement) current.replaceWith(replacement);
+ }
+
+ // The search box and filter dropdowns are deliberately left alone, so
+ // re-apply what they currently say to the rows that just arrived.
+ updateRelativeTimes();
+ filterDevices();
+ return true;
+}
+
+function startAutoRefresh() {
+ if (autoRefreshInterval) return;
+ autoRefreshInterval = setInterval(async () => {
+ // If the refresh could not be applied the session has probably ended.
+ // Reload so the user is taken to the login page rather than left
+ // looking at a table that has quietly stopped updating.
+ if (!(await refreshInPlace())) location.reload();
+ }, AUTO_REFRESH_MS);
+}
+
function toggleAutoRefresh() {
const toggle = document.getElementById('auto-refresh-toggle');
if (!toggle) return;
@@ -429,7 +556,7 @@ function toggleAutoRefresh() {
toggle.classList.remove('active');
localStorage.setItem('autoRefresh', 'false');
} else {
- autoRefreshInterval = setInterval(() => location.reload(), 30000);
+ startAutoRefresh();
toggle.classList.add('active');
localStorage.setItem('autoRefresh', 'true');
showToast('Auto-refresh enabled (30s)', 'info');
@@ -442,7 +569,7 @@ function toggleAutoRefresh() {
const toggle = document.getElementById('auto-refresh-toggle');
if (toggle) {
toggle.classList.add('active');
- autoRefreshInterval = setInterval(() => location.reload(), 30000);
+ startAutoRefresh();
}
}
})();
@@ -458,7 +585,7 @@ document.addEventListener('keydown', e => {
document.getElementById('device-search')?.focus();
break;
case 'r':
- location.reload();
+ refreshAfterScan();
break;
case 't':
toggleTheme();
@@ -478,3 +605,43 @@ document.addEventListener('click', e => {
document.addEventListener('keydown', e => {
if (e.key === 'Escape') closeModal();
});
+
+// --- Relative times ---------------------------------------------------
+//
+// "3 min ago" is rendered once by the server. Left alone it freezes, so a page
+// open for an hour still claims three minutes, which is exactly the false
+// impression these timestamps exist to prevent. Anything carrying a
+// data-relative-time attribute (a unix timestamp) is rewritten periodically.
+
+function relativeTime(unixSeconds) {
+ const diff = Math.floor(Date.now() / 1000) - unixSeconds;
+
+ if (diff < 0) return 'just now';
+ if (diff < 60) return 'just now';
+
+ const minutes = Math.floor(diff / 60);
+ if (minutes < 60) return minutes === 1 ? '1 min ago' : `${minutes} min ago`;
+
+ const hours = Math.floor(diff / 3600);
+ if (hours < 24) return hours === 1 ? '1 hr ago' : `${hours} hr ago`;
+
+ const days = Math.floor(diff / 86400);
+ if (days < 7) return days === 1 ? '1 day ago' : `${days} days ago`;
+
+ // Older than a week, show the date instead, matching the server format.
+ return new Date(unixSeconds * 1000).toLocaleDateString('en-US', {
+ month: 'short', day: 'numeric', year: 'numeric'
+ });
+}
+
+function updateRelativeTimes() {
+ document.querySelectorAll('[data-relative-time]').forEach(el => {
+ const ts = parseInt(el.dataset.relativeTime, 10);
+ if (!isNaN(ts) && ts > 0) {
+ el.textContent = relativeTime(ts);
+ }
+ });
+}
+
+updateRelativeTimes();
+setInterval(updateRelativeTimes, 30000);
diff --git a/internal/web/static/orangutan.svg b/internal/web/static/orangutan.svg
index 156d467..e42a4fb 100644
--- a/internal/web/static/orangutan.svg
+++ b/internal/web/static/orangutan.svg
@@ -1,23 +1,59 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="200" height="200">
- <ellipse cx="100" cy="100" rx="60" ry="65" fill="#FF6B35"/>
- <ellipse cx="48" cy="105" rx="26" ry="32" fill="#C94C27"/>
- <ellipse cx="152" cy="105" rx="26" ry="32" fill="#C94C27"/>
- <ellipse cx="100" cy="108" rx="38" ry="44" fill="#8B5A3C"/>
- <ellipse cx="85" cy="98" rx="9" ry="12" fill="#1A1A1A"/>
- <ellipse cx="87" cy="94" rx="3" ry="4" fill="white"/>
- <ellipse cx="115" cy="98" rx="9" ry="12" fill="#1A1A1A"/>
- <ellipse cx="117" cy="94" rx="3" ry="4" fill="white"/>
- <ellipse cx="100" cy="118" rx="12" ry="10" fill="#6B4423"/>
- <ellipse cx="95" cy="115" rx="4" ry="5" fill="#1A1A1A"/>
- <ellipse cx="105" cy="115" rx="4" ry="5" fill="#1A1A1A"/>
- <path d="M 82 132 Q 100 140 118 132" stroke="#4A2D16" stroke-width="3" fill="none" stroke-linecap="round"/>
- <ellipse cx="56" cy="80" rx="14" ry="18" fill="#C94C27"/>
- <ellipse cx="144" cy="80" rx="14" ry="18" fill="#C94C27"/>
- <g opacity="0.8">
- <circle cx="80" cy="60" r="4" fill="#4ECDC4"/>
- <circle cx="120" cy="60" r="4" fill="#4ECDC4"/>
- <circle cx="100" cy="52" r="4" fill="#4ECDC4"/>
- <line x1="80" y1="60" x2="100" y2="52" stroke="#4ECDC4" stroke-width="2"/>
- <line x1="120" y1="60" x2="100" y2="52" stroke="#4ECDC4" stroke-width="2"/>
- </g>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256" role="img" aria-label="LAN Orangutan">
+ <title>LAN Orangutan</title>
+
+ <defs>
+ <radialGradient id="loFur" cx="50%" cy="38%" r="68%">
+ <stop offset="0%" stop-color="#A9541F"/>
+ <stop offset="62%" stop-color="#8C4318"/>
+ <stop offset="100%" stop-color="#6E3411"/>
+ </radialGradient>
+
+ <radialGradient id="loFace" cx="50%" cy="42%" r="62%">
+ <stop offset="0%" stop-color="#F7B27A"/>
+ <stop offset="58%" stop-color="#EE9455"/>
+ <stop offset="100%" stop-color="#DD7A3C"/>
+ </radialGradient>
+
+ <radialGradient id="loMuzzle" cx="50%" cy="35%" r="70%">
+ <stop offset="0%" stop-color="#FBD3AE"/>
+ <stop offset="100%" stop-color="#F0AF7E"/>
+ </radialGradient>
+ </defs>
+
+ <!-- Cheek flanges: the wide side pads of an adult male orangutan, and the
+ feature that keeps the silhouette recognisable at favicon size. -->
+ <ellipse cx="41" cy="132" rx="30" ry="46" fill="#8C4318"/>
+ <ellipse cx="215" cy="132" rx="30" ry="46" fill="#8C4318"/>
+ <ellipse cx="39" cy="132" rx="21" ry="37" fill="#A9541F"/>
+ <ellipse cx="217" cy="132" rx="21" ry="37" fill="#A9541F"/>
+
+ <!-- Head -->
+ <path d="M128 44c50 0 84 22 84 74s-34 94-84 94-84-42-84-94 34-74 84-74Z" fill="url(#loFur)"/>
+
+ <!-- Crown tuft -->
+ <path d="M96 52c8-14 20-22 32-22s24 8 32 22c-10-6-21-9-32-9s-22 3-32 9Z" fill="#6E3411"/>
+
+ <!-- Face disc -->
+ <ellipse cx="128" cy="130" rx="62" ry="70" fill="url(#loFace)"/>
+
+ <!-- Brow ridge -->
+ <path d="M86 106c10-9 22-13 34-12M136 94c12-1 24 3 34 12"
+ stroke="#C4682F" stroke-width="7" stroke-linecap="round" fill="none" opacity="0.55"/>
+
+ <!-- Eyes -->
+ <ellipse cx="104" cy="120" rx="10.5" ry="12" fill="#2B1A10"/>
+ <ellipse cx="152" cy="120" rx="10.5" ry="12" fill="#2B1A10"/>
+ <circle cx="107.5" cy="115.5" r="3.6" fill="#FFFFFF" opacity="0.92"/>
+ <circle cx="155.5" cy="115.5" r="3.6" fill="#FFFFFF" opacity="0.92"/>
+
+ <!-- Muzzle -->
+ <ellipse cx="128" cy="164" rx="35" ry="27" fill="url(#loMuzzle)"/>
+
+ <!-- Nostrils -->
+ <ellipse cx="119" cy="155" rx="4.6" ry="3.4" fill="#8A4A24" opacity="0.85"/>
+ <ellipse cx="137" cy="155" rx="4.6" ry="3.4" fill="#8A4A24" opacity="0.85"/>
+
+ <!-- Mouth -->
+ <path d="M110 173c6 7 12 10 18 10s12-3 18-10"
+ stroke="#8A4A24" stroke-width="5.5" stroke-linecap="round" fill="none"/>
</svg>
diff --git a/internal/web/static/style.css b/internal/web/static/style.css
index b441297..a3e2524 100644
--- a/internal/web/static/style.css
+++ b/internal/web/static/style.css
@@ -57,6 +57,13 @@ html[data-theme="dark"] {
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
+/* While the theme is switching, turn transitions off so the whole page changes
+ in one step instead of some elements fading while others snap. Applied for a
+ single frame by applyTheme(), so hover transitions are unaffected. */
+.theme-switching, .theme-switching *, .theme-switching *::before, .theme-switching *::after {
+ transition: none !important;
+}
+
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', sans-serif;
background: var(--bg-secondary);
@@ -197,6 +204,13 @@ a:hover { color: var(--accent-hover); }
transition: var(--transition);
}
+/* The last element's own bottom margin would otherwise stack on top of the
+ card's padding, so cards ending in a form group sat lower than cards ending
+ in a plain row. Let the padding alone define the bottom gap. */
+.card > *:last-child {
+ margin-bottom: 0;
+}
+
.card:hover {
box-shadow: var(--card-shadow-lg);
transform: translateY(-2px);
@@ -220,6 +234,10 @@ a:hover { color: var(--accent-hover); }
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.25rem;
+ /* Let each card take only the height its own content needs. Stretching
+ them to match the tallest leaves short cards, such as a disconnected
+ Tailscale, with a large empty area below the text. */
+ align-items: start;
}
.network-card {
@@ -363,6 +381,29 @@ a:hover { color: var(--accent-hover); }
flex-wrap: wrap;
}
+/* Mirrors the toolbar above the table, closing the panel and stating how
+ current the data is. */
+.table-footer {
+ padding: 0.85rem 1.25rem;
+ background: var(--bg-tertiary);
+ border-top: 1px solid var(--border-color);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 1rem;
+ flex-wrap: wrap;
+ font-size: 0.85rem;
+}
+
+.table-footer-label {
+ color: var(--text-secondary);
+ font-weight: 500;
+}
+
+.table-footer-detail {
+ color: var(--text-muted);
+}
+
.table-info {
font-size: 0.9rem;
color: var(--text-secondary);
@@ -442,30 +483,37 @@ a:hover { color: var(--accent-hover); }
margin-right: 0.5rem;
}
-.status-indicator.online {
+/* These class names must match the StatusClass values produced in
+ internal/web/handler.go: status-online, status-seen, status-offline. */
+.status-indicator.status-online {
background: var(--success);
box-shadow: 0 0 0 3px var(--success-bg);
}
-.status-indicator.recent {
+.status-indicator.status-seen {
background: var(--warning);
box-shadow: 0 0 0 3px var(--warning-bg);
}
-.status-indicator.offline {
+.status-indicator.status-offline {
background: var(--text-muted);
}
-.device-row.online {
- border-left: 3px solid var(--success);
+/* The status stripe is drawn inside the first cell rather than as a border on
+ the row. The table uses border-collapse, which merges a row's border with its
+ neighbours: the stripes fused into one unbroken bar down the table and bled
+ up against the header instead of marking each row. An inset shadow is not
+ part of border collapsing, so each row keeps its own mark. */
+.device-row.status-online td:first-child {
+ box-shadow: inset 3px 0 0 var(--success);
}
-.device-row.recent {
- border-left: 3px solid var(--warning);
+.device-row.status-seen td:first-child {
+ box-shadow: inset 3px 0 0 var(--warning);
}
-.device-row.offline {
- border-left: 3px solid transparent;
+.device-row.status-offline td:first-child {
+ box-shadow: none;
}
.hostname-cell {
@@ -543,6 +591,20 @@ a:hover { color: var(--accent-hover); }
transition: var(--transition);
}
+/* Draw our own chevron. The native one is positioned by the operating system,
+ which leaves the label looking off-centre and renders differently on macOS,
+ Windows and Linux. */
+.select {
+ appearance: none;
+ -webkit-appearance: none;
+ padding-right: 2.75rem;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2394a3b8'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2.5' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 0.9rem center;
+ background-size: 1rem;
+ cursor: pointer;
+}
+
.input:focus, .select:focus {
outline: none;
border-color: var(--accent-primary);
@@ -574,6 +636,13 @@ a:hover { color: var(--accent-hover); }
color: var(--text-secondary);
}
+/* Radio labels are ordinary labels, so the rule above gives each one a bottom
+ margin to stack them. The last one would otherwise push the card's bottom
+ padding out of line with the other cards. */
+.radio-group .radio-label:last-child {
+ margin-bottom: 0;
+}
+
/* Buttons */
.btn {
padding: 0.65rem 1.25rem;
@@ -593,6 +662,10 @@ a:hover { color: var(--accent-hover); }
.btn:hover {
background: var(--bg-tertiary);
transform: translateY(-1px);
+ /* A button styled as a link (<a class="btn">) otherwise inherits the
+ global a:hover colour, which turns its text the same shade as the
+ hovered background. Keep the button's own text colour. */
+ color: var(--text-primary);
}
.btn-primary {
@@ -604,6 +677,21 @@ a:hover { color: var(--accent-hover); }
.btn-primary:hover {
background: var(--accent-hover);
border-color: var(--accent-hover);
+ /* Stay white on hover. Without this the text follows the global a:hover
+ colour and disappears into the orange background. */
+ color: white;
+}
+
+/* Help text under a button or field. The global reset zeroes margins, so
+ without this it sits flush against the control above it.
+ line-height is kept tight: a taller line box leaves invisible leading below
+ the text, which makes a card ending in help text look bottom-heavy next to
+ the card padding. */
+.form-help {
+ margin-top: 0.5rem;
+ font-size: 0.85rem;
+ color: var(--text-muted);
+ line-height: 1.2;
}
.btn-sm {
@@ -627,10 +715,16 @@ a:hover { color: var(--accent-hover); }
/* Group Select */
.group-select {
- padding: 0.35rem 0.75rem;
+ appearance: none;
+ -webkit-appearance: none;
+ padding: 0.35rem 2rem 0.35rem 0.75rem;
border: 1px solid var(--border-color);
border-radius: var(--radius-sm);
- background: var(--bg-primary);
+ background-color: var(--bg-primary);
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='%2394a3b8'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2.5' d='M19 9l-7 7-7-7'%3E%3C/path%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 0.6rem center;
+ background-size: 0.8rem;
color: var(--text-primary);
font-size: 0.85rem;
cursor: pointer;
@@ -832,6 +926,13 @@ a:hover { color: var(--accent-hover); }
100% { transform: translateX(340%); }
}
+.scan-progress-hint {
+ margin-top: 0.5rem;
+ font-size: 0.8rem;
+ color: var(--text-muted);
+ line-height: 1.4;
+}
+
.scan-progress-meta {
display: flex;
align-items: center;
@@ -1003,3 +1104,210 @@ a:hover { color: var(--accent-hover); }
80% { opacity: 1; }
100% { opacity: 0; transform: translateY(-10px); }
}
+
+/* Alerts */
+.alert {
+ padding: 0.75rem 1rem;
+ border-radius: var(--radius-sm);
+ border: 1px solid transparent;
+ font-size: 0.9rem;
+ line-height: 1.45;
+}
+
+.alert-error {
+ color: var(--danger);
+ background: var(--danger-bg);
+ border-color: var(--danger);
+}
+
+.alert-warning {
+ color: var(--warning);
+ background: var(--warning-bg);
+ border-color: var(--warning);
+}
+
+.alert-success {
+ color: var(--success);
+ background: var(--success-bg);
+ border-color: var(--success);
+}
+
+/* Login Page */
+.login-body {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 100vh;
+ background: var(--bg-secondary);
+ padding: 1.5rem;
+}
+
+.login-main {
+ width: 100%;
+ max-width: 380px;
+}
+
+.login-card {
+ background: var(--bg-primary);
+ border: 1px solid var(--border-color);
+ border-radius: var(--radius-lg);
+ box-shadow: var(--card-shadow-lg);
+ padding: 2.5rem 2rem;
+}
+
+.login-brand {
+ text-align: center;
+ margin-bottom: 2rem;
+}
+
+.login-logo {
+ display: block;
+ font-size: 3rem;
+ line-height: 1;
+ margin-bottom: 0.75rem;
+}
+
+.login-brand h1 {
+ font-size: 1.35rem;
+ color: var(--text-primary);
+}
+
+.login-form .form-group {
+ margin-bottom: 1.25rem;
+}
+
+.login-submit {
+ width: 100%;
+ justify-content: center;
+ padding: 0.7rem;
+ font-size: 1rem;
+}
+
+.login-card .alert {
+ margin-bottom: 1.25rem;
+}
+
+/* Setup Page */
+.setup-welcome {
+ color: var(--text-primary);
+ text-align: center;
+ font-size: 1.1rem;
+ font-weight: 600;
+ margin-bottom: 0.35rem;
+}
+
+.setup-intro {
+ color: var(--text-secondary);
+ text-align: center;
+ margin-bottom: 1.5rem;
+ line-height: 1.5;
+}
+
+.setup-note {
+ margin-top: 1.5rem;
+ padding-top: 1.25rem;
+ border-top: 1px solid var(--border-color);
+ color: var(--text-muted);
+ font-size: 0.85rem;
+ line-height: 1.5;
+ text-align: center;
+}
+
+/* Shown when the app has no route to a real network, so scan results cannot
+ be trusted. Deliberately prominent: the alternative is a user believing a
+ list of devices that were never there. */
+.network-warning {
+ margin-bottom: 1.5rem;
+ line-height: 1.5;
+}
+
+/* Inline icons
+ *
+ * These replaced emoji. Several emoji, including the orangutan itself and the
+ * delete icon, have no glyph in the fonts shipped with a minimal Debian or
+ * Raspberry Pi OS install, so they rendered as empty boxes on exactly the
+ * platform this app is most often installed on. */
+.icon {
+ display: inline-block;
+ vertical-align: middle;
+ flex-shrink: 0;
+}
+
+.stat-icon .icon {
+ color: var(--text-secondary);
+}
+
+.stat-icon-online .icon {
+ color: var(--success);
+}
+
+.stat-icon-offline .icon {
+ color: var(--text-muted);
+}
+
+.btn-icon .icon {
+ color: var(--text-secondary);
+ transition: var(--transition);
+}
+
+.btn-icon:hover .icon {
+ color: var(--accent-primary);
+}
+
+.btn-icon.danger:hover .icon {
+ color: var(--danger);
+}
+
+.notes-indicator .icon {
+ color: var(--text-muted);
+ margin-left: 0.35rem;
+}
+
+.empty-state-icon .icon {
+ color: var(--text-muted);
+}
+
+img.logo {
+ display: block;
+}
+
+img.login-logo {
+ display: block;
+ margin: 0 auto 0.75rem;
+}
+
+/* Running device total during a scan.
+ *
+ * On its own line rather than appended to the network line: with more than one
+ * network that line grew past the width of the panel and wrapped mid-sentence. */
+.scan-progress-count {
+ font-size: 0.85rem;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.scan-progress-count:empty {
+ display: none;
+}
+
+.scan-progress-hint:empty {
+ display: none;
+}
+
+/* Scan panel meta row.
+ *
+ * The elapsed time and estimate must never wrap: a wrapped second line is
+ * shorter than the first, which reads as stray padding on the right rather
+ * than as wrapped text. Keep it on one line and let the network name on the
+ * left give up space instead. */
+#scan-eta {
+ white-space: nowrap;
+ flex-shrink: 0;
+}
+
+#scan-detail {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
diff --git a/internal/web/static_test.go b/internal/web/static_test.go
new file mode 100644
index 0000000..e67f54b
--- /dev/null
+++ b/internal/web/static_test.go
@@ -0,0 +1,98 @@
+package web
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func staticServer(t *testing.T) http.Handler {
+ t.Helper()
+ sub, err := staticSubFS()
+ if err != nil {
+ t.Fatalf("staticSubFS: %v", err)
+ }
+ return newStaticHandler(sub)
+}
+
+func TestStaticServesWithETag(t *testing.T) {
+ h := staticServer(t)
+
+ req := httptest.NewRequest(http.MethodGet, "/static/style.css", nil)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+ if rec.Header().Get("Etag") == "" {
+ t.Error("expected an ETag so browsers can revalidate")
+ }
+ if rec.Header().Get("Cache-Control") != "no-cache" {
+ t.Errorf("Cache-Control = %q, want no-cache", rec.Header().Get("Cache-Control"))
+ }
+ if rec.Body.Len() == 0 {
+ t.Error("expected the stylesheet body")
+ }
+}
+
+func TestStaticReturns304WhenETagMatches(t *testing.T) {
+ h := staticServer(t)
+
+ // First request to learn the ETag.
+ first := httptest.NewRecorder()
+ h.ServeHTTP(first, httptest.NewRequest(http.MethodGet, "/static/app.js", nil))
+ etag := first.Header().Get("Etag")
+ if etag == "" {
+ t.Fatal("no ETag on first response")
+ }
+
+ // Second request presenting that ETag should be told nothing changed.
+ req := httptest.NewRequest(http.MethodGet, "/static/app.js", nil)
+ req.Header.Set("If-None-Match", etag)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusNotModified {
+ t.Fatalf("status = %d, want 304 when the ETag matches", rec.Code)
+ }
+ if rec.Body.Len() != 0 {
+ t.Error("a 304 must not resend the body")
+ }
+}
+
+func TestStaticETagDiffersByFile(t *testing.T) {
+ h := staticServer(t).(*staticHandler)
+
+ css := h.etags["style.css"]
+ js := h.etags["app.js"]
+ if css == "" || js == "" {
+ t.Fatal("expected ETags for both assets")
+ }
+ if css == js {
+ t.Error("different files should hash to different ETags")
+ }
+}
+
+func TestStaticMissingFileIs404(t *testing.T) {
+ h := staticServer(t)
+
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/static/does-not-exist.css", nil))
+
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("status = %d, want 404", rec.Code)
+ }
+}
+
+func TestStaticRejectsTraversal(t *testing.T) {
+ h := staticServer(t)
+
+ for _, p := range []string{"/static/../handler.go", "/static/../../go.mod"} {
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, p, nil))
+ if rec.Code == http.StatusOK {
+ t.Errorf("%s should not be served", p)
+ }
+ }
+}
diff --git a/internal/web/templates/index.html b/internal/web/templates/index.html
index 5f97559..9f28988 100644
--- a/internal/web/templates/index.html
+++ b/internal/web/templates/index.html
@@ -5,42 +5,52 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LAN Orangutan - Network Discovery</title>
<link rel="stylesheet" href="/static/style.css">
- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🦧</text></svg>">
+ <link rel="icon" type="image/svg+xml" href="/static/orangutan.svg">
</head>
<body>
<header class="header">
<a href="/" class="header-brand">
- <span class="logo">🦧</span>
+ <img src="/static/orangutan.svg" alt="" class="logo" width="32" height="32">
<h1>LAN Orangutan</h1>
</a>
<nav class="header-nav">
<a href="/" class="nav-link active">Dashboard</a>
<a href="/settings" class="nav-link">Settings</a>
+ {{if .AuthEnabled}}<a href="/logout" class="nav-link">Sign out</a>{{end}}
<button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme (T)">◐</button>
</nav>
</header>
<main class="main">
+ {{if .NetworkWarning}}
+ {{/* Shown when the app cannot reach a real network, which happens in a
+ container without host networking. Scans would look successful
+ while reporting devices that do not exist. */}}
+ <div class="alert alert-warning network-warning">
+ <strong>No access to your local network.</strong>
+ {{.NetworkWarning}}
+ </div>
+ {{end}}
<!-- Stats Section -->
<section class="section">
<div class="stats-bar">
<div class="stat-card">
- <div class="stat-icon">📊</div>
+ <div class="stat-icon"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="12" width="4" height="8"/><rect x="10" y="7" width="4" height="13"/><rect x="17" y="3" width="4" height="17"/></svg></div>
<span class="stat-value">{{.Stats.Total}}</span>
<span class="stat-label">Total Devices</span>
</div>
<div class="stat-card">
- <div class="stat-icon">🟢</div>
+ <div class="stat-icon stat-icon-online"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="12" cy="12" r="7"/></svg></div>
<span class="stat-value online">{{.Stats.Online}}</span>
<span class="stat-label">Online</span>
</div>
<div class="stat-card">
- <div class="stat-icon">⚪</div>
+ <div class="stat-icon stat-icon-offline"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="7"/></svg></div>
<span class="stat-value">{{.Stats.Offline}}</span>
<span class="stat-label">Offline</span>
</div>
<div class="stat-card">
- <div class="stat-icon">🌐</div>
+ <div class="stat-icon"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a15 15 0 0 1 0 18a15 15 0 0 1 0-18"/></svg></div>
<span class="stat-value">{{len .Networks}}</span>
<span class="stat-label">Networks</span>
</div>
@@ -149,7 +159,7 @@
<div class="table-container">
<div class="table-toolbar">
- <span class="table-info" id="device-count">Showing {{len .Devices}} devices</span>
+ <span class="table-info" id="device-count">Showing {{len .Devices}} device{{if ne (len .Devices) 1}}s{{end}}</span>
</div>
<table class="table" id="devices-table">
<thead>
@@ -189,7 +199,7 @@
{{if .MAC}}<span class="copyable" onclick="copyToClipboard('{{.MAC}}', event)" title="Click to copy">{{.MAC}}</span>{{else}}<span style="color:var(--text-muted)">-</span>{{end}}
</td>
<td class="vendor-cell" title="{{.Vendor}}">{{if .Vendor}}{{.Vendor}}{{else}}<span style="color:var(--text-muted)">Unknown</span>{{end}}</td>
- <td class="label-cell">{{.Label}}{{if .Notes}}<span class="notes-indicator" title="{{.Notes}}">📝</span>{{end}}</td>
+ <td class="label-cell">{{.Label}}{{if .Notes}}<span class="notes-indicator" title="{{.Notes}}"><svg class="icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"/><path d="M14 2v6h6"/><path d="M8 13h8M8 17h5"/></svg></span>{{end}}</td>
<td>
<select class="group-select" data-ip="{{.IP}}" onchange="updateDeviceGroup(this)">
<option value="">-</option>
@@ -202,19 +212,34 @@
<option value="Pi" {{if eq .Group "Pi"}}selected{{end}}>Pi</option>
</select>
</td>
- <td class="time-cell">{{.TimeAgo}}</td>
+ <td class="time-cell" data-relative-time="{{.LastSeenUnix}}">{{.TimeAgo}}</td>
<td class="actions-cell">
- <button class="btn-icon" onclick="editDevice('{{.IP}}')" title="Edit">✏️</button>
- <button class="btn-icon danger" onclick="deleteDevice('{{.IP}}')" title="Delete">🗑️</button>
+ <button class="btn-icon" onclick="editDevice('{{.IP}}')" title="Edit"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg></button>
+ <button class="btn-icon danger" onclick="deleteDevice('{{.IP}}')" title="Delete"><svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/><path d="M19 6v14a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V6"/><path d="M10 11v6M14 11v6"/></svg></button>
</td>
</tr>
{{end}}
</tbody>
</table>
+
+ {{/* Everything above is a snapshot from the last scan, not a
+ live view. State when that was, so "last seen" times are
+ read in the right context. */}}
+ <div class="table-footer">
+ {{if .LastScanAt}}
+ <span class="table-footer-label">Scanned
+ <span data-relative-time="{{.LastScanUnix}}">{{.LastScanAgo}}</span>
+ </span>
+ <span class="table-footer-detail">{{.LastScanAt}}</span>
+ {{else}}
+ <span class="table-footer-label">Not scanned yet</span>
+ <span class="table-footer-detail">Run a scan to discover devices</span>
+ {{end}}
+ </div>
</div>
{{if not .Devices}}
<div class="empty-state">
- <div class="empty-state-icon">🔍</div>
+ <div class="empty-state-icon"><svg class="icon" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg></div>
<h3>No devices discovered yet</h3>
<p>Click "Scan All" to discover devices on your network.</p>
</div>
@@ -279,10 +304,12 @@
<span id="scan-detail"></span>
<span id="scan-eta"></span>
</div>
+ <div class="scan-progress-count" id="scan-count"></div>
+ <div class="scan-progress-hint" id="scan-hint"></div>
</div>
<footer class="footer">
- <p>🦧 LAN Orangutan &bull; <a href="https://github.com/291-Group/LAN-Orangutan" target="_blank">GitHub</a></p>
+ <p>LAN Orangutan &bull; <a href="https://github.com/291-Group/LAN-Orangutan" target="_blank">GitHub</a></p>
<p style="margin-top:0.5rem;font-size:0.8rem;">Press <kbd class="kbd">/</kbd> to search &bull; <kbd class="kbd">R</kbd> to refresh &bull; <kbd class="kbd">T</kbd> to toggle theme</p>
</footer>
diff --git a/internal/web/templates/login.html b/internal/web/templates/login.html
new file mode 100644
index 0000000..b121219
--- /dev/null
+++ b/internal/web/templates/login.html
@@ -0,0 +1,50 @@
+<!DOCTYPE html>
+<html lang="en" data-theme="{{.Theme}}">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Sign in - LAN Orangutan</title>
+ <link rel="stylesheet" href="/static/style.css">
+ <link rel="icon" type="image/svg+xml" href="/static/orangutan.svg">
+</head>
+<body class="login-body">
+ <main class="login-main">
+ <div class="login-card">
+ <div class="login-brand">
+ <img src="/static/orangutan.svg" alt="" class="login-logo" width="72" height="72">
+ <h1>LAN Orangutan</h1>
+ </div>
+
+ {{if .Error}}
+ <div class="alert alert-error">{{.Error}}</div>
+ {{end}}
+
+ <form method="POST" action="/login" class="login-form">
+ <div class="form-group">
+ <label for="password">Password</label>
+ <input
+ type="password"
+ id="password"
+ name="password"
+ class="input"
+ autocomplete="current-password"
+ autofocus
+ required>
+ </div>
+ <button type="submit" class="btn btn-primary login-submit">Sign in</button>
+ </form>
+ </div>
+ </main>
+
+ <script>
+ // Apply the saved theme before anything is shown, matching the rest of
+ // the app so the login page does not flash the wrong colours.
+ (function () {
+ var saved = localStorage.getItem('theme');
+ if (saved) {
+ document.documentElement.setAttribute('data-theme', saved);
+ }
+ })();
+ </script>
+</body>
+</html>
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
index 48fc72c..a2ac252 100644
--- a/internal/web/templates/settings.html
+++ b/internal/web/templates/settings.html
@@ -5,17 +5,18 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings - LAN Orangutan</title>
<link rel="stylesheet" href="/static/style.css">
- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🦧</text></svg>">
+ <link rel="icon" type="image/svg+xml" href="/static/orangutan.svg">
</head>
<body>
<header class="header">
<a href="/" class="header-brand">
- <span class="logo">🦧</span>
+ <img src="/static/orangutan.svg" alt="" class="logo" width="32" height="32">
<h1>LAN Orangutan</h1>
</a>
<nav class="header-nav">
<a href="/" class="nav-link">Dashboard</a>
<a href="/settings" class="nav-link active">Settings</a>
+ {{if .AuthEnabled}}<a href="/logout" class="nav-link">Sign out</a>{{end}}
<button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">◐</button>
</nav>
</header>
@@ -103,6 +104,22 @@
</div>
</section>
+ {{if .AuthEnabled}}
+ <section class="section">
+ <h2 class="section-title">Security</h2>
+ <div class="card">
+ <div class="status-row">
+ <span class="status-label">Password:</span>
+ <span class="status-value online">✓ Enabled</span>
+ </div>
+ <div class="form-group" style="margin-top: 1rem;">
+ <a href="/logout" class="btn btn-primary">Sign out</a>
+ <p class="form-help">Ends this session on this browser.</p>
+ </div>
+ </div>
+ </section>
+ {{end}}
+
<section class="section">
<h2 class="section-title">Data Management</h2>
<div class="card">
@@ -125,15 +142,37 @@
</section>
</main>
+ {{/* A scan runs on the server, not in the page, so it can still be going
+ while the user is on this page. Without somewhere to show it, the scan
+ would carry on invisibly and this page would never notice it finish. */}}
+ <div id="scan-progress" class="scan-progress" style="display:none">
+ <div class="scan-progress-head">
+ <span id="scan-title">Scanning network...</span>
+ <button type="button" class="btn btn-sm scan-cancel" id="scan-cancel" onclick="cancelScan()">Cancel</button>
+ </div>
+ <div class="scan-bar" id="scan-bar">
+ <div class="scan-bar-fill" id="scan-bar-fill"></div>
+ </div>
+ <div class="scan-progress-meta">
+ <span id="scan-detail"></span>
+ <span id="scan-eta"></span>
+ </div>
+ <div class="scan-progress-count" id="scan-count"></div>
+ <div class="scan-progress-hint" id="scan-hint"></div>
+ </div>
+
+ <div id="toast" class="toast"></div>
+
<footer class="footer">
- <p>🦧 LAN Orangutan by <a href="https://291group.com" target="_blank">291 Group</a></p>
+ <p>LAN Orangutan by <a href="https://291group.com" target="_blank">291 Group</a></p>
</footer>
<script src="/static/app.js"></script>
<script>
function setTheme(theme) {
- document.documentElement.setAttribute('data-theme', theme);
- localStorage.setItem('theme', theme);
+ // Shared with the header toggle so the radios also switch without the
+ // staggered transition. applyTheme is defined in app.js.
+ applyTheme(theme);
}
function exportDevices() {
diff --git a/internal/web/templates/setup.html b/internal/web/templates/setup.html
new file mode 100644
index 0000000..7a7d455
--- /dev/null
+++ b/internal/web/templates/setup.html
@@ -0,0 +1,73 @@
+<!DOCTYPE html>
+<html lang="en" data-theme="{{.Theme}}">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Welcome - LAN Orangutan</title>
+ <link rel="stylesheet" href="/static/style.css">
+ <link rel="icon" type="image/svg+xml" href="/static/orangutan.svg">
+</head>
+<body class="login-body">
+ <main class="login-main">
+ <div class="login-card">
+ <div class="login-brand">
+ <img src="/static/orangutan.svg" alt="" class="login-logo" width="72" height="72">
+ <h1>LAN Orangutan</h1>
+ </div>
+
+ <p class="setup-welcome">Welcome</p>
+ <p class="setup-intro">Create a password to secure your dashboard.</p>
+
+ {{if .Error}}
+ <div class="alert alert-error">{{.Error}}</div>
+ {{end}}
+
+ <form method="POST" action="/setup" class="login-form">
+ <div class="form-group">
+ <label for="password">Password</label>
+ <input
+ type="password"
+ id="password"
+ name="password"
+ class="input"
+ autocomplete="new-password"
+ minlength="{{.MinPasswordLength}}"
+ autofocus
+ required>
+ <p class="form-help">At least {{.MinPasswordLength}} characters.</p>
+ </div>
+
+ <div class="form-group">
+ <label for="confirm">Confirm password</label>
+ <input
+ type="password"
+ id="confirm"
+ name="confirm"
+ class="input"
+ autocomplete="new-password"
+ minlength="{{.MinPasswordLength}}"
+ required>
+ </div>
+
+ <button type="submit" class="btn btn-primary login-submit">Get started</button>
+ </form>
+
+ <p class="setup-note">
+ This dashboard can be reached by other machines on your network,
+ which is why it needs a password.
+ </p>
+ </div>
+ </main>
+
+ <script>
+ // Apply the saved theme before anything is shown, matching the rest of
+ // the app so the page does not flash the wrong colours.
+ (function () {
+ var saved = localStorage.getItem('theme');
+ if (saved) {
+ document.documentElement.setAttribute('data-theme', saved);
+ }
+ })();
+ </script>
+</body>
+</html>
diff --git a/scanner/requirements.txt b/scanner/requirements.txt
deleted file mode 100644
index 218f8b5..0000000
--- a/scanner/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-# LAN Orangutan Scanner Dependencies
-# Uses Python standard library - no external dependencies required
diff --git a/scanner/scan.py b/scanner/scan.py
deleted file mode 100755
index 9b8838d..0000000
--- a/scanner/scan.py
+++ /dev/null
@@ -1,318 +0,0 @@
-#!/usr/bin/env python3
-"""
-LAN Orangutan Network Scanner
-Discovers devices on local networks using nmap or arp-scan
-"""
-
-import json
-import sys
-import subprocess
-import socket
-import re
-import time
-import os
-from datetime import datetime
-
-STATE_FILE = "/var/lib/lan-orangutan/scan_state.json"
-DEVICES_FILE = "/var/lib/lan-orangutan/devices.json"
-CONFIG_FILE = "/etc/lan-orangutan/config.ini"
-MIN_SCAN_INTERVAL = 30
-
-# Common MAC vendor prefixes
-MAC_VENDORS = {
- "00:50:56": "VMware", "00:0C:29": "VMware", "08:00:27": "VirtualBox",
- "52:54:00": "QEMU/KVM", "B8:27:EB": "Raspberry Pi", "DC:A6:32": "Raspberry Pi",
- "E4:5F:01": "Raspberry Pi", "28:CD:C1": "Raspberry Pi", "D8:3A:DD": "Raspberry Pi",
- "00:E0:4C": "Realtek", "00:15:5D": "Microsoft Hyper-V",
- "00:23:AE": "Dell", "00:14:22": "Dell", "18:A9:9B": "Dell",
- "3C:D9:2B": "HP", "00:1E:0B": "HP", "00:21:5A": "HP",
- "00:1F:C6": "ASUSTek", "00:1A:92": "ASUSTek", "14:DA:E9": "ASUSTek",
- "00:1C:C0": "Intel", "00:1F:3B": "Intel", "3C:A9:F4": "Intel",
- "5C:B9:01": "Ubiquiti", "00:27:22": "Ubiquiti", "04:18:D6": "Ubiquiti",
- "74:83:C2": "Ubiquiti", "FC:EC:DA": "Ubiquiti",
- "00:18:0A": "Cisco", "00:1B:2A": "Cisco", "64:F6:9D": "Cisco",
- "00:14:BF": "Linksys", "00:1A:70": "Linksys", "C0:C1:C0": "Linksys",
- "00:1F:33": "Netgear", "00:22:3F": "Netgear", "A0:63:91": "Netgear",
- "08:86:3B": "Belkin", "94:10:3E": "Belkin",
- "00:26:5A": "D-Link", "00:1E:58": "D-Link", "1C:7E:E5": "D-Link",
- "00:1D:0F": "TP-Link", "14:CC:20": "TP-Link", "50:C7:BF": "TP-Link",
- "00:25:00": "Apple", "00:26:08": "Apple", "28:CF:DA": "Apple",
- "3C:15:C2": "Apple", "5C:F9:38": "Apple", "78:31:C1": "Apple",
- "18:65:90": "Samsung", "50:01:BB": "Samsung", "94:35:0A": "Samsung",
- "2C:54:91": "Microsoft", "7C:1E:52": "Microsoft",
-}
-
-
-def get_mac_vendor(mac):
- if not mac:
- return "Unknown"
- mac = mac.upper().replace("-", ":")
- prefix = mac[:8]
- return MAC_VENDORS.get(prefix, "Unknown")
-
-
-def reverse_dns(ip):
- try:
- return socket.gethostbyaddr(ip)[0]
- except (socket.herror, socket.gaierror, socket.timeout):
- return ""
-
-
-def load_scan_state():
- try:
- if os.path.exists(STATE_FILE):
- with open(STATE_FILE, 'r') as f:
- return json.load(f)
- except (IOError, json.JSONDecodeError, OSError) as e:
- print(f"Warning: Could not load scan state: {e}", file=sys.stderr)
- return {"last_scan": {}}
-
-
-def save_scan_state(state):
- os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
- with open(STATE_FILE, 'w') as f:
- json.dump(state, f)
-
-
-def check_rate_limit(network):
- state = load_scan_state()
- last_scan = state.get("last_scan", {}).get(network, 0)
- elapsed = time.time() - last_scan
- if elapsed < MIN_SCAN_INTERVAL:
- return False, int(MIN_SCAN_INTERVAL - elapsed)
- return True, 0
-
-
-def update_scan_time(network):
- state = load_scan_state()
- if "last_scan" not in state:
- state["last_scan"] = {}
- state["last_scan"][network] = time.time()
- save_scan_state(state)
-
-
-def run_nmap(cidr):
- """Run nmap scan. Returns tuple of (devices_list, success_bool)."""
- devices = []
- try:
- result = subprocess.run(
- ["nmap", "-sn", "-oX", "-", cidr],
- capture_output=True, text=True, timeout=300
- )
- if result.returncode != 0:
- return devices, False
-
- output = result.stdout
- host_pattern = r'<host[^>]*>(.*?)</host>'
- addr_pattern = r'<address addr="([^"]+)" addrtype="([^"]+)"'
- hostname_pattern = r'<hostname name="([^"]+)"'
- status_pattern = r'<status state="([^"]+)"'
-
- for host_match in re.finditer(host_pattern, output, re.DOTALL):
- host_block = host_match.group(1)
- status_match = re.search(status_pattern, host_block)
- if not status_match or status_match.group(1) != "up":
- continue
-
- device = {"ip": "", "mac": "", "hostname": "", "vendor": "",
- "last_seen": datetime.now().isoformat(), "response_time": None}
-
- for addr_match in re.finditer(addr_pattern, host_block):
- addr, addr_type = addr_match.groups()
- if addr_type == "ipv4":
- device["ip"] = addr
- elif addr_type == "mac":
- device["mac"] = addr
-
- hostname_match = re.search(hostname_pattern, host_block)
- if hostname_match:
- device["hostname"] = hostname_match.group(1)
-
- if not device["hostname"] and device["ip"]:
- device["hostname"] = reverse_dns(device["ip"])
-
- if device["mac"]:
- device["vendor"] = get_mac_vendor(device["mac"])
-
- if device["ip"]:
- devices.append(device)
-
- return devices, True
-
- except subprocess.TimeoutExpired:
- print("nmap scan timed out", file=sys.stderr)
- return devices, False
- except FileNotFoundError:
- print("nmap not found", file=sys.stderr)
- return devices, False
- except Exception as e:
- print(f"nmap error: {e}", file=sys.stderr)
- return devices, False
-
-
-def run_arp_scan(cidr, interface=None):
- devices = []
- cmd = ["arp-scan"]
- if interface:
- cmd.extend(["--interface", interface])
- cmd.append(cidr)
-
- try:
- result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
- if result.returncode != 0:
- return devices
-
- for line in result.stdout.split('\n'):
- parts = line.split('\t')
- if len(parts) >= 2:
- ip = parts[0].strip()
- mac = parts[1].strip() if len(parts) > 1 else ""
- vendor = parts[2].strip() if len(parts) > 2 else ""
-
- if not re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', ip):
- continue
-
- device = {
- "ip": ip, "mac": mac, "hostname": reverse_dns(ip),
- "vendor": vendor or get_mac_vendor(mac),
- "last_seen": datetime.now().isoformat(), "response_time": None
- }
- devices.append(device)
-
- except subprocess.TimeoutExpired:
- print("arp-scan timed out", file=sys.stderr)
- except FileNotFoundError:
- print("arp-scan not found", file=sys.stderr)
- except Exception as e:
- print(f"arp-scan error: {e}", file=sys.stderr)
-
- return devices
-
-
-def scan_network(cidr, interface=None):
- allowed, wait_time = check_rate_limit(cidr)
- if not allowed:
- return {"success": False, "error": f"Rate limited. Wait {wait_time} seconds.",
- "devices": [], "network": cidr, "timestamp": datetime.now().isoformat()}
-
- devices, nmap_success = run_nmap(cidr)
- scanner_used = "nmap"
-
- # Only fallback to arp-scan if nmap actually failed, not if it found 0 devices
- if not nmap_success:
- devices = run_arp_scan(cidr, interface)
- scanner_used = "arp-scan" if devices else "none"
-
- update_scan_time(cidr)
-
- return {"success": True, "devices": devices, "device_count": len(devices),
- "network": cidr, "scanner": scanner_used, "timestamp": datetime.now().isoformat()}
-
-
-def load_devices():
- try:
- if os.path.exists(DEVICES_FILE):
- with open(DEVICES_FILE, 'r') as f:
- return json.load(f)
- except (IOError, json.JSONDecodeError, OSError) as e:
- print(f"Warning: Could not load devices file: {e}", file=sys.stderr)
- backup = DEVICES_FILE + ".backup"
- if os.path.exists(backup):
- try:
- with open(backup, 'r') as f:
- return json.load(f)
- except (IOError, json.JSONDecodeError, OSError) as e2:
- print(f"Warning: Could not load backup file: {e2}", file=sys.stderr)
- return {"devices": {}, "networks": {}}
-
-
-def save_devices(data):
- os.makedirs(os.path.dirname(DEVICES_FILE), exist_ok=True)
- backup_file = DEVICES_FILE + ".backup"
- temp_file = DEVICES_FILE + ".tmp"
-
- # Write to temp file first for atomic operation
- try:
- with open(temp_file, 'w') as f:
- json.dump(data, f, indent=2)
-
- # Backup existing file if present
- if os.path.exists(DEVICES_FILE):
- try:
- os.replace(DEVICES_FILE, backup_file)
- except OSError as e:
- print(f"Warning: Could not create backup: {e}", file=sys.stderr)
-
- # Atomic rename of temp to target
- os.replace(temp_file, DEVICES_FILE)
- except OSError as e:
- print(f"Error saving devices: {e}", file=sys.stderr)
- if os.path.exists(temp_file):
- os.remove(temp_file)
-
-
-def merge_devices(existing, new_devices, network):
- if "devices" not in existing:
- existing["devices"] = {}
- if "networks" not in existing:
- existing["networks"] = {}
-
- for device in new_devices:
- ip = device["ip"]
- if ip in existing["devices"]:
- old = existing["devices"][ip]
- old["last_seen"] = device["last_seen"]
- old["mac"] = device["mac"] or old.get("mac", "")
- old["hostname"] = device["hostname"] or old.get("hostname", "")
- old["vendor"] = device["vendor"] or old.get("vendor", "")
- else:
- device["first_seen"] = device["last_seen"]
- device["label"] = ""
- device["notes"] = ""
- device["group"] = ""
- existing["devices"][ip] = device
-
- existing["networks"][network] = {
- "last_scan": datetime.now().isoformat(),
- "device_count": len(new_devices)
- }
- return existing
-
-
-def is_valid_cidr(cidr):
- """Validate CIDR notation with proper octet range checking."""
- match = re.match(r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})$', cidr)
- if not match:
- return False
- octets = [int(match.group(i)) for i in range(1, 5)]
- if any(o > 255 for o in octets):
- return False
- prefix = int(match.group(5))
- return 0 <= prefix <= 32
-
-
-def main():
- if len(sys.argv) < 2:
- print(json.dumps({"success": False, "error": "Usage: scan.py <network_cidr> [interface]"}))
- sys.exit(1)
-
- cidr = sys.argv[1]
- interface = sys.argv[2] if len(sys.argv) > 2 else None
-
- if not is_valid_cidr(cidr):
- print(json.dumps({"success": False, "error": f"Invalid CIDR format: {cidr}"}))
- sys.exit(1)
-
- result = scan_network(cidr, interface)
-
- if result["success"] and result["devices"]:
- existing = load_devices()
- updated = merge_devices(existing, result["devices"], cidr)
- save_devices(updated)
-
- print(json.dumps(result, indent=2))
- sys.exit(0 if result["success"] else 1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/scanner/utils.py b/scanner/utils.py
deleted file mode 100755
index 8550b19..0000000
--- a/scanner/utils.py
+++ /dev/null
@@ -1,255 +0,0 @@
-#!/usr/bin/env python3
-"""
-LAN Orangutan Utilities
-Network detection, Tailscale integration, and helper functions
-"""
-
-import json
-import subprocess
-import os
-import sys
-from datetime import datetime, timedelta
-
-CONFIG_FILE = "/etc/lan-orangutan/config.ini"
-DEVICES_FILE = "/var/lib/lan-orangutan/devices.json"
-
-
-def get_network_interfaces():
- interfaces = []
- try:
- result = subprocess.run(["ip", "-j", "addr", "show"],
- capture_output=True, text=True, timeout=10)
- if result.returncode == 0:
- data = json.loads(result.stdout)
- for iface in data:
- name = iface.get("ifname", "")
- if name == "lo":
- continue
- state = iface.get("operstate", "unknown")
- for addr_info in iface.get("addr_info", []):
- if addr_info.get("family") == "inet":
- interfaces.append({
- "name": name,
- "ip": addr_info.get("local", ""),
- "netmask": addr_info.get("prefixlen", 24),
- "broadcast": addr_info.get("broadcast", ""),
- "state": state,
- "is_tailscale": name.startswith("tailscale"),
- "is_wireless": name.startswith("wlan") or name.startswith("wlp")
- })
- except Exception as e:
- print(f"Error getting interfaces: {e}", file=sys.stderr)
- return interfaces
-
-
-def detect_networks():
- networks = []
- interfaces = get_network_interfaces()
-
- for iface in interfaces:
- if iface["state"] not in ("UP", "up"):
- continue
-
- ip = iface["ip"]
- prefix = iface["netmask"]
- ip_split = ip.split('.')
- if len(ip_split) != 4:
- continue # Skip malformed IPs
- try:
- ip_parts = [int(x) for x in ip_split]
- except ValueError:
- continue # Skip if parts aren't integers
- mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF
- mask_parts = [(mask >> 24) & 0xFF, (mask >> 16) & 0xFF,
- (mask >> 8) & 0xFF, mask & 0xFF]
- net_parts = [ip_parts[i] & mask_parts[i] for i in range(4)]
- network = f"{net_parts[0]}.{net_parts[1]}.{net_parts[2]}.{net_parts[3]}/{prefix}"
-
- if iface["is_tailscale"]:
- friendly_name = "Tailscale"
- elif iface["is_wireless"]:
- friendly_name = f"WiFi ({iface['name']})"
- else:
- friendly_name = f"LAN ({iface['name']})"
-
- networks.append({
- "cidr": network, "interface": iface["name"],
- "friendly_name": friendly_name, "ip": ip,
- "is_tailscale": iface["is_tailscale"]
- })
- return networks
-
-
-def get_tailscale_status():
- result = {"installed": False, "running": False, "ip": "", "hostname": "",
- "peers": 0, "exit_node": None, "advertised_routes": []}
- try:
- proc = subprocess.run(["tailscale", "status", "--json"],
- capture_output=True, text=True, timeout=10)
- result["installed"] = True
- if proc.returncode == 0:
- data = json.loads(proc.stdout)
- result["running"] = data.get("BackendState") == "Running"
- self_info = data.get("Self", {})
- result["ip"] = self_info.get("TailscaleIPs", [""])[0] if self_info.get("TailscaleIPs") else ""
- result["hostname"] = self_info.get("HostName", "")
- result["advertised_routes"] = self_info.get("AllowedIPs", [])
- peers = data.get("Peer", {})
- result["peers"] = len(peers) if peers else 0
- exit_node_status = data.get("ExitNodeStatus")
- if exit_node_status:
- result["exit_node"] = exit_node_status.get("ID", "")
- except FileNotFoundError:
- pass
- except Exception as e:
- result["error"] = str(e)
- return result
-
-
-def get_gateway():
- try:
- result = subprocess.run(["ip", "route", "show", "default"],
- capture_output=True, text=True, timeout=5)
- if result.returncode == 0:
- parts = result.stdout.split()
- if len(parts) >= 3 and parts[0] == "default":
- return parts[2]
- except (subprocess.TimeoutExpired, OSError) as e:
- print(f"Warning: Could not get gateway: {e}", file=sys.stderr)
- return ""
-
-
-def get_dns_servers():
- servers = []
- try:
- result = subprocess.run(["resolvectl", "status"],
- capture_output=True, text=True, timeout=5)
- if result.returncode == 0:
- for line in result.stdout.split('\n'):
- if "DNS Servers:" in line:
- servers.extend(line.split(':')[1].strip().split())
- if not servers:
- with open('/etc/resolv.conf', 'r') as f:
- for line in f:
- if line.startswith('nameserver'):
- servers.append(line.split()[1])
- except (subprocess.TimeoutExpired, FileNotFoundError, OSError, IndexError) as e:
- print(f"Warning: Could not get DNS servers: {e}", file=sys.stderr)
- return servers
-
-
-def get_device_count():
- stats = {"total": 0, "online": 0, "new_24h": 0}
- if not os.path.exists(DEVICES_FILE):
- return stats
- try:
- with open(DEVICES_FILE, 'r') as f:
- data = json.load(f)
- devices = data.get("devices", {})
- stats["total"] = len(devices)
- now = datetime.now()
- one_hour_ago = now - timedelta(hours=1)
- one_day_ago = now - timedelta(days=1)
-
- for device in devices.values():
- last_seen = device.get("last_seen", "")
- first_seen = device.get("first_seen", "")
- if last_seen:
- try:
- # Parse timestamp and make timezone-naive for comparison
- seen = datetime.fromisoformat(last_seen.replace('Z', '+00:00'))
- if seen.tzinfo is not None:
- seen = seen.replace(tzinfo=None)
- if seen > one_hour_ago:
- stats["online"] += 1
- except ValueError:
- pass
- if first_seen:
- try:
- first = datetime.fromisoformat(first_seen.replace('Z', '+00:00'))
- if first.tzinfo is not None:
- first = first.replace(tzinfo=None)
- if first > one_day_ago:
- stats["new_24h"] += 1
- except ValueError:
- pass
- except (IOError, json.JSONDecodeError, OSError) as e:
- print(f"Warning: Could not get device count: {e}", file=sys.stderr)
- return stats
-
-
-def parse_config():
- config = {
- "server": {"port": 291, "bind_address": "0.0.0.0", "enable_api": True},
- "scanning": {"scan_interval": 300, "min_scan_interval": 30,
- "enable_port_scan": False, "port_scan_range": "1-1024"},
- "networks": {},
- "storage": {"max_devices": 1000, "retention_days": 90,
- "data_dir": "/var/lib/lan-orangutan"},
- "tailscale": {"enable": True, "auto_detect": True},
- "ui": {"theme": "auto"}
- }
- if not os.path.exists(CONFIG_FILE):
- return config
- try:
- current_section = None
- with open(CONFIG_FILE, 'r') as f:
- for line in f:
- line = line.strip()
- if not line or line.startswith('#') or line.startswith(';'):
- continue
- if line.startswith('[') and line.endswith(']'):
- current_section = line[1:-1]
- if current_section not in config:
- config[current_section] = {}
- continue
- if '=' in line and current_section:
- key, value = line.split('=', 1)
- key = key.strip()
- value = value.strip()
- if '#' in value:
- value = value.split('#')[0].strip()
- if value.lower() in ('true', 'yes', 'on'):
- value = True
- elif value.lower() in ('false', 'no', 'off'):
- value = False
- else:
- # Try to parse as int or float
- try:
- value = int(value)
- except ValueError:
- try:
- value = float(value)
- except ValueError:
- pass # Keep as string
- config[current_section][key] = value
- except Exception as e:
- print(f"Error parsing config: {e}", file=sys.stderr)
- return config
-
-
-def check_disk_space(path="/var/lib/lan-orangutan"):
- try:
- stat = os.statvfs(path if os.path.exists(path) else "/")
- free_bytes = stat.f_bavail * stat.f_frsize
- total_bytes = stat.f_blocks * stat.f_frsize
- return {
- "free_mb": free_bytes // (1024 * 1024),
- "total_mb": total_bytes // (1024 * 1024),
- "percent_free": (free_bytes / total_bytes * 100) if total_bytes > 0 else 0,
- "ok": free_bytes > (100 * 1024 * 1024)
- }
- except OSError as e:
- print(f"Warning: Could not check disk space: {e}", file=sys.stderr)
- return {"free_mb": 0, "total_mb": 0, "percent_free": 0, "ok": False}
-
-
-if __name__ == "__main__":
- print("=== Network Interfaces ===")
- for iface in get_network_interfaces():
- print(json.dumps(iface, indent=2))
- print("\n=== Detected Networks ===")
- for net in detect_networks():
- print(json.dumps(net, indent=2))
- print("\n=== Tailscale Status ===")
- print(json.dumps(get_tailscale_status(), indent=2))
diff --git a/scripts/gen-oui.sh b/scripts/gen-oui.sh
new file mode 100755
index 0000000..09505af
--- /dev/null
+++ b/scripts/gen-oui.sh
@@ -0,0 +1,41 @@
+#!/usr/bin/env bash
+# Regenerates the embedded IEEE MAC address registry used for vendor lookups.
+#
+# The registry changes as new blocks are assigned, so refresh it occasionally
+# and commit the result. Output: internal/scanner/oui.txt.gz
+set -euo pipefail
+
+SRC="https://standards-oui.ieee.org/oui/oui.csv"
+OUT="internal/scanner/oui.txt.gz"
+TMP="$(mktemp -t oui.XXXXXX)"
+trap 'rm -f "$TMP"' EXIT
+
+echo "Downloading $SRC"
+curl -sfL --max-time 180 "$SRC" -o "$TMP"
+
+echo "Building $OUT"
+python3 - "$TMP" "$OUT" <<'PY'
+import csv, gzip, re, sys
+
+src, out = sys.argv[1], sys.argv[2]
+rows = []
+with open(src, newline='', encoding='utf-8', errors='replace') as fh:
+ for r in csv.DictReader(fh):
+ prefix = (r.get('Assignment') or '').strip().upper()
+ name = ' '.join((r.get('Organization Name') or '').split())
+ if not prefix or not name:
+ continue
+ if not re.fullmatch(r'[0-9A-F]{6,9}', prefix):
+ continue
+ if name.lower() in ('private', 'ieee registration authority'):
+ continue
+ rows.append((prefix, name))
+
+rows.sort()
+with gzip.open(out, 'wt', encoding='utf-8', compresslevel=9) as fh:
+ fh.write('\n'.join(f'{p}\t{n}' for p, n in rows) + '\n')
+
+print(f" {len(rows)} entries")
+PY
+
+echo "Done. Commit $OUT to embed it in the binary."
diff --git a/scripts/start-server.sh b/scripts/start-server.sh
deleted file mode 100755
index cf1d32f..0000000
--- a/scripts/start-server.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!/bin/bash
-set -e
-
-INSTALL_DIR="/opt/lan-orangutan"
-CONFIG_FILE="/etc/lan-orangutan/config.ini"
-WEB_DIR="$INSTALL_DIR/web"
-
-PORT=291
-BIND="0.0.0.0"
-
-if [[ -f "$CONFIG_FILE" ]]; then
- PORT=$(grep "^port" "$CONFIG_FILE" 2>/dev/null | cut -d= -f2 | tr -d ' ' || echo "291")
- BIND=$(grep "^bind_address" "$CONFIG_FILE" 2>/dev/null | cut -d= -f2 | tr -d ' ' || echo "0.0.0.0")
-fi
-
-# Validate port is a number between 1-65535
-if [[ ! "$PORT" =~ ^[0-9]+$ ]] || [[ "$PORT" -lt 1 ]] || [[ "$PORT" -gt 65535 ]]; then
- echo "Warning: Invalid port '$PORT', using default 291" >&2
- PORT=291
-fi
-
-# Validate bind address is a valid IPv4 address
-if [[ ! "$BIND" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
- echo "Warning: Invalid bind address '$BIND', using default 0.0.0.0" >&2
- BIND="0.0.0.0"
-fi
-
-cd "$WEB_DIR"
-echo "Starting LAN Orangutan on $BIND:$PORT"
-exec php -S "$BIND:$PORT" -t "$WEB_DIR"
diff --git a/systemd/lan-orangutan.service b/systemd/lan-orangutan.service
index 46212de..5513cdd 100644
--- a/systemd/lan-orangutan.service
+++ b/systemd/lan-orangutan.service
@@ -6,10 +6,11 @@ Wants=network-online.target
[Service]
Type=simple
+# Runs as root so nmap can read the ARP table, which is what supplies MAC
+# addresses and manufacturer names. Without it you get IP addresses only.
User=root
Group=root
-WorkingDirectory=/opt/lan-orangutan
-ExecStart=/opt/lan-orangutan/scripts/start-server.sh
+ExecStart=/usr/local/bin/orangutan serve
Restart=on-failure
RestartSec=10
StandardOutput=journal
diff --git a/uninstall.sh b/uninstall.sh
index 6ee15c1..f25abeb 100755
--- a/uninstall.sh
+++ b/uninstall.sh
@@ -11,7 +11,7 @@ RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'; NC='\033[0m'
[[ $EUID -ne 0 ]] && { echo -e "${RED}✗${NC} Run as root (sudo)"; exit 1; }
echo ""
-echo -e "${YELLOW}🦧 LAN Orangutan Uninstaller${NC}"
+echo -e "${YELLOW}LAN Orangutan Uninstaller${NC}"
echo "================================"
echo ""
@@ -21,7 +21,16 @@ if [[ -f "$CONFIG_DIR/config.ini" ]]; then
CONFIGURED_PORT=$(grep "^port" "$CONFIG_DIR/config.ini" 2>/dev/null | cut -d= -f2 | tr -d ' ' || true)
fi
-read -p "Remove LAN Orangutan completely? [y/N]: " confirm
+INSTALLED_VERSION=""
+if [[ -x /usr/local/bin/orangutan ]]; then
+ INSTALLED_VERSION="$(/usr/local/bin/orangutan version 2>/dev/null | head -1 | sed 's/^LAN Orangutan //')"
+fi
+if [[ -n "$INSTALLED_VERSION" ]]; then
+ echo "Installed version: $INSTALLED_VERSION"
+ echo ""
+fi
+
+read -r -p "Uninstall LAN Orangutan? [y/N]: " confirm
[[ ! "$confirm" =~ ^[Yy]$ ]] && { echo "Aborted."; exit 0; }
# Stop service
@@ -38,7 +47,7 @@ rm -rf "$CONFIG_DIR"
echo -e "${GREEN}✓${NC} Files removed"
# Data
-read -p "Remove device data ($DATA_DIR)? [y/N]: " data
+read -r -p "Also remove your device list and password ($DATA_DIR)? [y/N]: " data
[[ "$data" =~ ^[Yy]$ ]] && { rm -rf "$DATA_DIR"; echo -e "${GREEN}✓${NC} Data removed"; }
# Firewall - clean up configured port and common alternatives
@@ -53,5 +62,5 @@ if command -v ufw &>/dev/null; then
fi
echo ""
-echo -e "${GREEN}🦧 LAN Orangutan uninstalled${NC}"
+echo -e "${GREEN}LAN Orangutan ${INSTALLED_VERSION:-} uninstalled${NC}"
echo ""
diff --git a/web/api.php b/web/api.php
deleted file mode 100644
index 63566e1..0000000
--- a/web/api.php
+++ /dev/null
@@ -1,333 +0,0 @@
-<?php
-/**
- * LAN Orangutan API
- */
-class LanOrangutanAPI {
- private $configFile = '/etc/lan-orangutan/config.ini';
- private $devicesFile = '/var/lib/lan-orangutan/devices.json';
- private $scannerPath = '/opt/lan-orangutan/scanner/scan.py';
- private $utilsPath = '/opt/lan-orangutan/scanner/utils.py';
-
- public function __construct() {
- if (!file_exists($this->scannerPath)) {
- $this->scannerPath = __DIR__ . '/../scanner/scan.py';
- $this->utilsPath = __DIR__ . '/../scanner/utils.py';
- }
- if (!file_exists($this->configFile)) {
- $this->configFile = __DIR__ . '/../config.example.ini';
- }
- if (!file_exists(dirname($this->devicesFile))) {
- $this->devicesFile = '/tmp/lan-orangutan-devices.json';
- }
- }
-
- public function getConfig() {
- $defaults = [
- 'server' => ['port' => 291, 'bind_address' => '0.0.0.0', 'enable_api' => true],
- 'scanning' => ['scan_interval' => 300, 'min_scan_interval' => 30, 'enable_port_scan' => false],
- 'storage' => ['max_devices' => 1000, 'retention_days' => 90],
- 'tailscale' => ['enable' => true, 'auto_detect' => true],
- 'ui' => ['theme' => 'auto'],
- 'networks' => []
- ];
- if (!file_exists($this->configFile)) return $defaults;
- $config = parse_ini_file($this->configFile, true);
- if (!$config) return $defaults;
- // Deep merge: merge each section individually
- foreach ($defaults as $section => $values) {
- if (!isset($config[$section])) {
- $config[$section] = $values;
- } elseif (is_array($values)) {
- $config[$section] = array_merge($values, $config[$section]);
- }
- }
- return $config;
- }
-
- public function saveConfig($config) {
- $content = "";
- foreach ($config as $section => $values) {
- $content .= "[$section]\n";
- if (is_array($values)) {
- foreach ($values as $key => $value) {
- if (is_bool($value)) $value = $value ? 'true' : 'false';
- $content .= "$key = $value\n";
- }
- }
- $content .= "\n";
- }
- $dir = dirname($this->configFile);
- if (!is_dir($dir)) {
- if (!mkdir($dir, 0755, true)) {
- error_log("LAN Orangutan: Failed to create config directory: $dir");
- return false;
- }
- }
- return file_put_contents($this->configFile, $content) !== false;
- }
-
- public function getDevices() {
- if (!file_exists($this->devicesFile)) return ['devices' => [], 'networks' => []];
- $content = file_get_contents($this->devicesFile);
- $data = json_decode($content, true);
- if (!$data) {
- $backup = $this->devicesFile . '.backup';
- if (file_exists($backup)) {
- $content = file_get_contents($backup);
- $data = json_decode($content, true);
- }
- }
- return $data ?: ['devices' => [], 'networks' => []];
- }
-
- public function saveDevices($data) {
- $dir = dirname($this->devicesFile);
- if (!is_dir($dir)) {
- if (!mkdir($dir, 0755, true)) {
- error_log("LAN Orangutan: Failed to create devices directory: $dir");
- return false;
- }
- }
- if (file_exists($this->devicesFile)) {
- if (!copy($this->devicesFile, $this->devicesFile . '.backup')) {
- error_log("LAN Orangutan: Failed to create devices backup");
- }
- }
- return file_put_contents($this->devicesFile, json_encode($data, JSON_PRETTY_PRINT)) !== false;
- }
-
- private function isValidIp($ip) {
- return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
- }
-
- public function getDevice($ip) {
- if (!$this->isValidIp($ip)) return null;
- $data = $this->getDevices();
- return $data['devices'][$ip] ?? null;
- }
-
- public function updateDevice($ip, $updates) {
- if (!$this->isValidIp($ip)) return false;
- $data = $this->getDevices();
- if (!isset($data['devices'][$ip])) return false;
- foreach ($updates as $key => $value) {
- if (in_array($key, ['label', 'notes', 'group'])) {
- $data['devices'][$ip][$key] = $value;
- }
- }
- return $this->saveDevices($data);
- }
-
- public function deleteDevice($ip) {
- if (!$this->isValidIp($ip)) return false;
- $data = $this->getDevices();
- if (isset($data['devices'][$ip])) {
- unset($data['devices'][$ip]);
- return $this->saveDevices($data);
- }
- return false;
- }
-
- public function getNetworks() {
- $networks = [];
- $utilsDir = dirname($this->utilsPath);
- $cmd = sprintf(
- 'PYTHONPATH=%s python3 -c %s 2>/dev/null',
- escapeshellarg($utilsDir),
- escapeshellarg('from utils import detect_networks; import json; print(json.dumps(detect_networks()))')
- );
- $output = shell_exec($cmd);
- if ($output) {
- $detected = json_decode($output, true);
- if ($detected) $networks = $detected;
- }
- if (empty($networks)) $networks = $this->detectNetworksFallback();
- return $networks;
- }
-
- private function detectNetworksFallback() {
- $networks = [];
- $output = shell_exec("ip -4 addr show 2>/dev/null");
- if (!$output) return $networks;
- $lines = explode("\n", $output);
- $currentInterface = '';
- foreach ($lines as $line) {
- if (preg_match('/^\d+:\s+(\S+):/', $line, $m)) $currentInterface = $m[1];
- if (preg_match('/inet\s+(\d+\.\d+\.\d+\.\d+)\/(\d+)/', $line, $m)) {
- $ip = $m[1];
- $prefix = $m[2];
- if ($currentInterface === 'lo' || $ip === '127.0.0.1') continue;
- $ipLong = ip2long($ip);
- $mask = -1 << (32 - $prefix);
- $netLong = $ipLong & $mask;
- $network = long2ip($netLong);
- $cidr = "$network/$prefix";
- $isTailscale = strpos($currentInterface, 'tailscale') === 0;
- $isWireless = strpos($currentInterface, 'wlan') === 0 || strpos($currentInterface, 'wlp') === 0;
- $friendlyName = $isTailscale ? 'Tailscale' : ($isWireless ? "WiFi ($currentInterface)" : "LAN ($currentInterface)");
- $networks[] = ['cidr' => $cidr, 'interface' => $currentInterface, 'friendly_name' => $friendlyName, 'ip' => $ip, 'is_tailscale' => $isTailscale];
- }
- }
- return $networks;
- }
-
- public function scanNetwork($cidr) {
- if (!$this->isValidCidr($cidr)) {
- return ['success' => false, 'error' => 'Invalid CIDR format'];
- }
- $cmd = sprintf(
- '%s %s %s 2>&1',
- escapeshellarg('python3'),
- escapeshellarg($this->scannerPath),
- escapeshellarg($cidr)
- );
- $output = shell_exec($cmd);
- if (!$output) return ['success' => false, 'error' => 'Scanner failed'];
- $result = json_decode($output, true);
- return $result ?: ['success' => false, 'error' => 'Invalid scanner output'];
- }
-
- private function isValidCidr($cidr) {
- if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/', $cidr, $matches)) {
- return false;
- }
- for ($i = 1; $i <= 4; $i++) {
- if ((int)$matches[$i] > 255) return false;
- }
- $prefix = (int)$matches[5];
- return $prefix >= 0 && $prefix <= 32;
- }
-
- public function scanAllNetworks() {
- $networks = $this->getNetworks();
- $results = [];
- foreach ($networks as $net) {
- $results[$net['cidr']] = $this->scanNetwork($net['cidr']);
- }
- return $results;
- }
-
- public function getTailscaleStatus() {
- $result = ['installed' => false, 'running' => false, 'ip' => '', 'hostname' => '', 'peers' => 0, 'exit_node' => null];
- $which = shell_exec("which tailscale 2>/dev/null");
- if (!$which) return $result;
- $result['installed'] = true;
- $output = shell_exec("tailscale status --json 2>/dev/null");
- if (!$output) return $result;
- $data = json_decode($output, true);
- if (!$data) return $result;
- $result['running'] = ($data['BackendState'] ?? '') === 'Running';
- $self = $data['Self'] ?? [];
- $result['ip'] = $self['TailscaleIPs'][0] ?? '';
- $result['hostname'] = $self['HostName'] ?? '';
- $result['peers'] = count($data['Peer'] ?? []);
- $result['exit_node'] = ($data['ExitNodeStatus'] ?? [])['ID'] ?? null;
- return $result;
- }
-
- public function getStats() {
- $data = $this->getDevices();
- $devices = $data['devices'] ?? [];
- $stats = ['total' => count($devices), 'online' => 0, 'new_24h' => 0];
- $now = time();
- foreach ($devices as $device) {
- $lastSeen = strtotime($device['last_seen'] ?? '');
- $firstSeen = strtotime($device['first_seen'] ?? '');
- if ($lastSeen && $lastSeen > $now - 3600) $stats['online']++;
- if ($firstSeen && $firstSeen > $now - 86400) $stats['new_24h']++;
- }
- return $stats;
- }
-
- public function getSystemStatus() {
- $diskFree = disk_free_space('/var/lib/lan-orangutan') ?: disk_free_space('/');
- $diskTotal = disk_total_space('/var/lib/lan-orangutan') ?: disk_total_space('/');
- return [
- 'disk_free_mb' => round($diskFree / 1024 / 1024),
- 'disk_total_mb' => round($diskTotal / 1024 / 1024),
- 'disk_ok' => $diskFree > (100 * 1024 * 1024),
- 'php_version' => PHP_VERSION,
- 'scanner_available' => file_exists($this->scannerPath),
- 'nmap_available' => !empty(shell_exec("which nmap 2>/dev/null"))
- ];
- }
-}
-
-if (basename($_SERVER['SCRIPT_NAME']) === 'api.php') {
- header('Content-Type: application/json');
- $api = new LanOrangutanAPI();
- $method = $_SERVER['REQUEST_METHOD'];
- $path = $_GET['action'] ?? '';
-
- // CSRF protection for state-changing API calls
- // Require X-Requested-With header for POST/DELETE (set by JavaScript fetch)
- $isMutatingRequest = in_array($method, ['POST', 'PUT', 'DELETE']);
- $hasXhrHeader = isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
- strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
- $hasContentTypeJson = isset($_SERVER['CONTENT_TYPE']) &&
- strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false;
-
- if ($isMutatingRequest && !$hasXhrHeader && !$hasContentTypeJson) {
- http_response_code(403);
- echo json_encode(['success' => false, 'error' => 'CSRF validation failed']);
- exit;
- }
-
- try {
- switch ($path) {
- case 'networks':
- echo json_encode(['success' => true, 'networks' => $api->getNetworks()]);
- break;
- case 'devices':
- echo json_encode(['success' => true, 'data' => $api->getDevices()]);
- break;
- case 'device':
- $ip = $_GET['ip'] ?? '';
- if ($method === 'GET') {
- $device = $api->getDevice($ip);
- echo json_encode($device ? ['success' => true, 'device' => $device] : ['success' => false, 'error' => 'Not found']);
- } elseif ($method === 'POST') {
- $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
- // Get IP from body if not in URL (for POST requests from JavaScript)
- if (empty($ip) && isset($input['ip'])) {
- $ip = $input['ip'];
- }
- echo json_encode(['success' => $api->updateDevice($ip, $input)]);
- } elseif ($method === 'DELETE') {
- echo json_encode(['success' => $api->deleteDevice($ip)]);
- }
- break;
- case 'scan':
- $network = $_GET['network'] ?? '';
- if ($network === 'all') {
- echo json_encode(['success' => true, 'results' => $api->scanAllNetworks()]);
- } else {
- echo json_encode($api->scanNetwork($network));
- }
- break;
- case 'tailscale':
- echo json_encode(['success' => true, 'data' => $api->getTailscaleStatus()]);
- break;
- case 'stats':
- echo json_encode(['success' => true, 'stats' => $api->getStats()]);
- break;
- case 'status':
- echo json_encode(['success' => true, 'status' => $api->getSystemStatus()]);
- break;
- case 'settings':
- if ($method === 'GET') {
- echo json_encode(['success' => true, 'config' => $api->getConfig()]);
- } elseif ($method === 'POST') {
- $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
- echo json_encode(['success' => $api->saveConfig($input)]);
- }
- break;
- default:
- http_response_code(404);
- echo json_encode(['success' => false, 'error' => 'Unknown endpoint']);
- }
- } catch (Exception $e) {
- http_response_code(500);
- echo json_encode(['success' => false, 'error' => $e->getMessage()]);
- }
-}
diff --git a/web/assets/app.js b/web/assets/app.js
deleted file mode 100644
index 8251412..0000000
--- a/web/assets/app.js
+++ /dev/null
@@ -1,172 +0,0 @@
-function toggleTheme() {
- const html = document.documentElement;
- const current = html.getAttribute('data-theme');
- let next = current === 'light' ? 'dark' : current === 'dark' ? 'auto' : 'light';
- html.setAttribute('data-theme', next);
- localStorage.setItem('theme', next);
-}
-
-(function() {
- const saved = localStorage.getItem('theme');
- if (saved) document.documentElement.setAttribute('data-theme', saved);
-})();
-
-function showToast(message, type = 'info') {
- const toast = document.getElementById('toast');
- if (!toast) return;
- toast.textContent = message;
- toast.className = 'toast ' + type + ' show';
- setTimeout(() => toast.classList.remove('show'), 3000);
-}
-
-async function api(action, params = {}, method = 'GET') {
- let url = `api.php?action=${action}`;
- const options = { method };
- if (method === 'GET') {
- Object.keys(params).forEach(key => url += `&${key}=${encodeURIComponent(params[key])}`);
- } else {
- options.headers = { 'Content-Type': 'application/json' };
- options.body = JSON.stringify(params);
- }
- try {
- const response = await fetch(url, options);
- if (!response.ok) {
- throw new Error(`HTTP error: ${response.status}`);
- }
- const text = await response.text();
- if (!text) {
- throw new Error('Empty response from server');
- }
- try {
- return JSON.parse(text);
- } catch (parseError) {
- console.error('JSON parse error:', parseError, 'Response:', text);
- throw new Error('Invalid JSON response from server');
- }
- } catch (error) {
- console.error('API error:', error);
- throw error;
- }
-}
-
-async function scanNetwork(cidr) {
- const progress = document.getElementById('scan-progress');
- if (progress) progress.style.display = 'flex';
- try {
- const result = await api('scan', { network: cidr });
- if (result.success) {
- showToast(`Found ${result.device_count || 0} devices`, 'success');
- setTimeout(() => location.reload(), 1000);
- } else {
- showToast(result.error || 'Scan failed', 'error');
- }
- } catch (e) {
- showToast('Scan failed: ' + e.message, 'error');
- } finally {
- if (progress) progress.style.display = 'none';
- }
-}
-
-async function scanAllNetworks() {
- const progress = document.getElementById('scan-progress');
- if (progress) progress.style.display = 'flex';
- try {
- const result = await api('scan', { network: 'all' });
- if (result.success) {
- let total = 0;
- Object.values(result.results || {}).forEach(r => { if (r.device_count) total += r.device_count; });
- showToast(`Scan complete. Found ${total} devices.`, 'success');
- setTimeout(() => location.reload(), 1000);
- } else {
- showToast('Scan failed', 'error');
- }
- } catch (e) {
- showToast('Scan failed: ' + e.message, 'error');
- } finally {
- if (progress) progress.style.display = 'none';
- }
-}
-
-function filterDevices() {
- const search = (document.getElementById('device-search')?.value || '').toLowerCase();
- const filter = document.getElementById('device-filter')?.value || 'all';
- document.querySelectorAll('.device-row').forEach(row => {
- const text = [row.dataset.ip, row.dataset.hostname, row.dataset.mac, row.dataset.vendor, row.dataset.label].join(' ');
- const matchSearch = !search || text.includes(search);
- const matchFilter = filter === 'all' || (filter === 'online' && (row.dataset.status === 'online' || row.dataset.status === 'recent')) || (filter === 'offline' && row.dataset.status === 'offline');
- row.style.display = matchSearch && matchFilter ? '' : 'none';
- });
-}
-
-function editDevice(ip) {
- const modal = document.getElementById('edit-modal');
- const row = document.querySelector(`.device-row[data-ip="${CSS.escape(ip)}"]`);
- if (!modal || !row) return;
- document.getElementById('edit-ip').value = ip;
- document.getElementById('edit-ip-display').value = ip;
- document.getElementById('edit-label').value = row.dataset.labelOriginal || '';
- document.getElementById('edit-group').value = row.querySelector('.group-select')?.value || '';
- document.getElementById('edit-notes').value = '';
- modal.style.display = 'flex';
-}
-
-function closeModal() {
- const modal = document.getElementById('edit-modal');
- if (modal) modal.style.display = 'none';
-}
-
-async function saveDevice() {
- const ip = document.getElementById('edit-ip').value;
- const label = document.getElementById('edit-label').value;
- const group = document.getElementById('edit-group').value;
- const notes = document.getElementById('edit-notes').value;
- try {
- const result = await api('device', { ip, label, group, notes }, 'POST');
- if (result.success) {
- showToast('Device updated', 'success');
- closeModal();
- location.reload();
- } else {
- showToast(result.error || 'Failed to update device', 'error');
- }
- } catch (e) {
- showToast('Error: ' + e.message, 'error');
- }
-}
-
-async function deleteDevice(ip) {
- if (!confirm(`Delete device ${ip}?`)) return;
- try {
- const response = await fetch(`api.php?action=device&ip=${encodeURIComponent(ip)}`, {
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json' }
- });
- const result = await response.json();
- if (result.success) {
- showToast('Device deleted', 'success');
- document.querySelector(`.device-row[data-ip="${CSS.escape(ip)}"]`)?.remove();
- } else {
- showToast(result.error || 'Failed to delete device', 'error');
- }
- } catch (e) {
- showToast('Error: ' + e.message, 'error');
- }
-}
-
-async function updateDeviceGroup(select) {
- const ip = select.dataset.ip;
- const group = select.value;
- try {
- const result = await api('device', { ip, group }, 'POST');
- if (result.success) {
- showToast('Group updated', 'success');
- } else {
- showToast(result.error || 'Failed to update group', 'error');
- }
- } catch (e) {
- showToast('Failed to update group', 'error');
- }
-}
-
-document.addEventListener('click', e => { if (e.target.classList.contains('modal')) closeModal(); });
-document.addEventListener('keydown', e => { if (e.key === 'Escape') closeModal(); });
diff --git a/web/assets/orangutan.svg b/web/assets/orangutan.svg
deleted file mode 100644
index 156d467..0000000
--- a/web/assets/orangutan.svg
+++ /dev/null
@@ -1,23 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" width="200" height="200">
- <ellipse cx="100" cy="100" rx="60" ry="65" fill="#FF6B35"/>
- <ellipse cx="48" cy="105" rx="26" ry="32" fill="#C94C27"/>
- <ellipse cx="152" cy="105" rx="26" ry="32" fill="#C94C27"/>
- <ellipse cx="100" cy="108" rx="38" ry="44" fill="#8B5A3C"/>
- <ellipse cx="85" cy="98" rx="9" ry="12" fill="#1A1A1A"/>
- <ellipse cx="87" cy="94" rx="3" ry="4" fill="white"/>
- <ellipse cx="115" cy="98" rx="9" ry="12" fill="#1A1A1A"/>
- <ellipse cx="117" cy="94" rx="3" ry="4" fill="white"/>
- <ellipse cx="100" cy="118" rx="12" ry="10" fill="#6B4423"/>
- <ellipse cx="95" cy="115" rx="4" ry="5" fill="#1A1A1A"/>
- <ellipse cx="105" cy="115" rx="4" ry="5" fill="#1A1A1A"/>
- <path d="M 82 132 Q 100 140 118 132" stroke="#4A2D16" stroke-width="3" fill="none" stroke-linecap="round"/>
- <ellipse cx="56" cy="80" rx="14" ry="18" fill="#C94C27"/>
- <ellipse cx="144" cy="80" rx="14" ry="18" fill="#C94C27"/>
- <g opacity="0.8">
- <circle cx="80" cy="60" r="4" fill="#4ECDC4"/>
- <circle cx="120" cy="60" r="4" fill="#4ECDC4"/>
- <circle cx="100" cy="52" r="4" fill="#4ECDC4"/>
- <line x1="80" y1="60" x2="100" y2="52" stroke="#4ECDC4" stroke-width="2"/>
- <line x1="120" y1="60" x2="100" y2="52" stroke="#4ECDC4" stroke-width="2"/>
- </g>
-</svg>
diff --git a/web/assets/style.css b/web/assets/style.css
deleted file mode 100644
index 969c407..0000000
--- a/web/assets/style.css
+++ /dev/null
@@ -1,141 +0,0 @@
-:root {
- --bg-primary: #ffffff;
- --bg-secondary: #f5f6fa;
- --bg-tertiary: #e8e9ed;
- --text-primary: #1a1a2e;
- --text-secondary: #4a4a6a;
- --text-muted: #8888a0;
- --border-color: #e0e0e8;
- --accent-primary: #FF6B35;
- --accent-secondary: #4ECDC4;
- --accent-hover: #e55a28;
- --success: #22c55e;
- --warning: #f59e0b;
- --danger: #ef4444;
- --card-shadow: 0 2px 8px rgba(0,0,0,0.08);
- --header-bg: #1a1a2e;
- --header-text: #ffffff;
-}
-[data-theme="dark"] {
- --bg-primary: #1a1a2e;
- --bg-secondary: #252540;
- --bg-tertiary: #2f2f4a;
- --text-primary: #f0f0f5;
- --text-secondary: #b0b0c0;
- --text-muted: #707088;
- --border-color: #3a3a55;
- --card-shadow: 0 2px 8px rgba(0,0,0,0.3);
- --header-bg: #12121f;
-}
-@media (prefers-color-scheme: dark) {
- [data-theme="auto"] {
- --bg-primary: #1a1a2e;
- --bg-secondary: #252540;
- --bg-tertiary: #2f2f4a;
- --text-primary: #f0f0f5;
- --text-secondary: #b0b0c0;
- --text-muted: #707088;
- --border-color: #3a3a55;
- --card-shadow: 0 2px 8px rgba(0,0,0,0.3);
- --header-bg: #12121f;
- }
-}
-*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
-body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg-secondary); color: var(--text-primary); line-height: 1.5; }
-a { color: var(--accent-primary); text-decoration: none; }
-a:hover { text-decoration: underline; }
-.header { background: var(--header-bg); color: var(--header-text); padding: 0 1.5rem; display: flex; justify-content: space-between; align-items: center; height: 60px; position: sticky; top: 0; z-index: 100; }
-.header-brand { display: flex; align-items: center; gap: 0.75rem; }
-.logo { font-size: 1.75rem; }
-.header h1 { font-size: 1.25rem; font-weight: 600; }
-.header-nav { display: flex; align-items: center; gap: 1rem; }
-.nav-link { color: var(--header-text); opacity: 0.8; padding: 0.5rem 1rem; border-radius: 6px; transition: opacity 0.2s; }
-.nav-link:hover, .nav-link.active { opacity: 1; background: rgba(255,255,255,0.1); text-decoration: none; }
-.theme-toggle { background: none; border: none; color: var(--header-text); font-size: 1.25rem; cursor: pointer; padding: 0.5rem; }
-.main { max-width: 1400px; margin: 0 auto; padding: 1.5rem; }
-.section { margin-bottom: 2rem; }
-.section-title { font-size: 1.25rem; font-weight: 600; margin-bottom: 1rem; }
-.section-header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem; margin-bottom: 1rem; }
-.section-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; }
-.card { background: var(--bg-primary); border-radius: 12px; padding: 1.25rem; box-shadow: var(--card-shadow); border: 1px solid var(--border-color); margin-bottom: 1rem; }
-.card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
-.card-footer { margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border-color); }
-.network-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 1rem; }
-.network-card.tailscale { border-left: 4px solid var(--accent-secondary); }
-.network-name { font-weight: 600; }
-.network-detail { display: flex; justify-content: space-between; padding: 0.35rem 0; font-size: 0.9rem; }
-.network-detail .label { color: var(--text-muted); }
-.network-detail .value { font-family: monospace; font-size: 0.85rem; }
-.stats-bar { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 1rem; background: var(--bg-primary); border-radius: 12px; padding: 1.25rem; box-shadow: var(--card-shadow); border: 1px solid var(--border-color); }
-.stat { text-align: center; }
-.stat-value { font-size: 2rem; font-weight: 700; display: block; }
-.stat-value.online { color: var(--success); }
-.stat-label { font-size: 0.85rem; color: var(--text-muted); }
-.table-container { background: var(--bg-primary); border-radius: 12px; overflow: hidden; box-shadow: var(--card-shadow); border: 1px solid var(--border-color); }
-.table { width: 100%; border-collapse: collapse; }
-.table th, .table td { padding: 0.75rem 1rem; text-align: left; border-bottom: 1px solid var(--border-color); }
-.table th { background: var(--bg-tertiary); font-weight: 600; font-size: 0.85rem; color: var(--text-secondary); text-transform: uppercase; }
-.table tbody tr:hover { background: var(--bg-secondary); }
-.ip-cell, .mac-cell { font-family: monospace; font-size: 0.9rem; }
-.time-cell { color: var(--text-muted); font-size: 0.85rem; }
-.status-indicator.online, .status-badge.online { color: var(--success); }
-.status-indicator.recent { color: var(--warning); }
-.status-indicator.offline, .status-badge.offline { color: var(--text-muted); }
-.device-row.online { border-left: 3px solid var(--success); }
-.device-row.recent { border-left: 3px solid var(--warning); }
-.input, .select { padding: 0.6rem 0.75rem; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-primary); color: var(--text-primary); font-size: 0.95rem; width: 100%; }
-.input:focus, .select:focus { outline: none; border-color: var(--accent-primary); }
-.form-group { margin-bottom: 1rem; }
-.form-group label { display: block; margin-bottom: 0.4rem; font-weight: 500; font-size: 0.9rem; }
-.form-help { font-size: 0.8rem; color: var(--text-muted); margin-top: 0.3rem; }
-.checkbox-label, .radio-label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; }
-.radio-group { display: flex; gap: 1.5rem; flex-wrap: wrap; }
-.btn { padding: 0.6rem 1.25rem; border: 1px solid var(--border-color); border-radius: 6px; background: var(--bg-primary); color: var(--text-primary); font-size: 0.95rem; font-weight: 500; cursor: pointer; transition: all 0.2s; }
-.btn:hover { background: var(--bg-tertiary); }
-.btn-primary { background: var(--accent-primary); border-color: var(--accent-primary); color: white; }
-.btn-primary:hover { background: var(--accent-hover); }
-.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.85rem; }
-.btn-large { padding: 0.8rem 2rem; }
-.btn-icon { background: none; border: none; padding: 0.4rem; cursor: pointer; color: var(--text-muted); font-size: 1rem; border-radius: 4px; }
-.btn-icon:hover { color: var(--text-primary); background: var(--bg-tertiary); }
-.btn-icon.danger:hover { color: var(--danger); }
-.form-actions { display: flex; gap: 1rem; margin-top: 2rem; }
-.group-select { padding: 0.3rem 0.5rem; border: 1px solid var(--border-color); border-radius: 4px; background: var(--bg-primary); color: var(--text-primary); font-size: 0.85rem; }
-.modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
-.modal-content { background: var(--bg-primary); border-radius: 12px; width: 90%; max-width: 500px; max-height: 90vh; overflow: auto; }
-.modal-header { padding: 1.25rem; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }
-.modal-header h3 { font-size: 1.1rem; }
-.modal-close { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: var(--text-muted); }
-.modal-body { padding: 1.25rem; }
-.modal-footer { padding: 1rem 1.25rem; border-top: 1px solid var(--border-color); display: flex; justify-content: flex-end; gap: 0.75rem; }
-.toast { position: fixed; bottom: 2rem; right: 2rem; padding: 1rem 1.5rem; background: var(--text-primary); color: var(--bg-primary); border-radius: 8px; transform: translateY(100px); opacity: 0; transition: all 0.3s; z-index: 1100; }
-.toast.show { transform: translateY(0); opacity: 1; }
-.toast.success { background: var(--success); color: white; }
-.toast.error { background: var(--danger); color: white; }
-.alert { padding: 1rem 1.25rem; border-radius: 8px; margin-bottom: 1.5rem; }
-.alert-success { background: rgba(34,197,94,0.15); border: 1px solid var(--success); color: var(--success); }
-.alert-error { background: rgba(239,68,68,0.15); border: 1px solid var(--danger); color: var(--danger); }
-.scan-progress { position: fixed; top: 70px; left: 50%; transform: translateX(-50%); background: var(--bg-primary); padding: 0.75rem 1.5rem; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.15); display: flex; align-items: center; gap: 0.75rem; z-index: 200; }
-.scan-spinner { width: 18px; height: 18px; border: 2px solid var(--border-color); border-top-color: var(--accent-primary); border-radius: 50%; animation: spin 1s linear infinite; }
-@keyframes spin { to { transform: rotate(360deg); } }
-.empty-state { text-align: center; padding: 3rem; color: var(--text-muted); }
-.subsection-title { font-size: 1rem; font-weight: 600; margin-bottom: 1rem; color: var(--text-secondary); }
-.network-list { display: flex; flex-direction: column; gap: 0.5rem; }
-.network-item { display: flex; gap: 1rem; align-items: center; padding: 0.75rem; background: var(--bg-secondary); border-radius: 6px; }
-.network-cidr { font-family: monospace; font-size: 0.85rem; color: var(--text-secondary); }
-.network-interface { font-size: 0.8rem; color: var(--text-muted); }
-.status-row { display: flex; justify-content: space-between; padding: 0.5rem 0; border-bottom: 1px solid var(--border-color); }
-.status-row:last-child { border-bottom: none; }
-.status-label { color: var(--text-secondary); }
-.status-value { font-weight: 500; }
-.status-value.online { color: var(--success); }
-.status-value.offline { color: var(--danger); }
-.status-value.warning { color: var(--warning); }
-.footer { text-align: center; padding: 2rem; color: var(--text-muted); font-size: 0.9rem; }
-@media (max-width: 768px) {
- .header h1 { display: none; }
- .main { padding: 1rem; }
- .table-container { overflow-x: auto; }
- .stats-bar { grid-template-columns: repeat(2, 1fr); }
- .stat-value { font-size: 1.5rem; }
-}
diff --git a/web/index.php b/web/index.php
deleted file mode 100644
index bed0e0b..0000000
--- a/web/index.php
+++ /dev/null
@@ -1,264 +0,0 @@
-<?php
-/**
- * LAN Orangutan - Network Discovery Dashboard
- */
-require_once __DIR__ . '/api.php';
-
-$api = new LanOrangutanAPI();
-$config = $api->getConfig();
-$devices = $api->getDevices();
-$networks = $api->getNetworks();
-$tailscale = $api->getTailscaleStatus();
-$stats = $api->getStats();
-$theme = $config['ui']['theme'] ?? 'auto';
-
-function timeAgo($timestamp) {
- $diff = time() - $timestamp;
- if ($diff < 60) return 'Just now';
- if ($diff < 3600) return floor($diff / 60) . ' min ago';
- if ($diff < 86400) return floor($diff / 3600) . ' hr ago';
- if ($diff < 604800) return floor($diff / 86400) . ' days ago';
- return date('M j', $timestamp);
-}
-?>
-<!DOCTYPE html>
-<html lang="en" data-theme="<?= htmlspecialchars($theme) ?>">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>LAN Orangutan - Network Discovery</title>
- <link rel="stylesheet" href="assets/style.css">
- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🦧</text></svg>">
-</head>
-<body>
- <header class="header">
- <div class="header-brand">
- <span class="logo">🦧</span>
- <h1>LAN Orangutan</h1>
- </div>
- <nav class="header-nav">
- <a href="index.php" class="nav-link active">Dashboard</a>
- <a href="settings.php" class="nav-link">Settings</a>
- <button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">◐</button>
- </nav>
- </header>
-
- <main class="main">
- <section class="section">
- <h2 class="section-title">Network Status</h2>
- <div class="network-cards">
- <?php foreach ($networks as $network): ?>
- <div class="card network-card <?= $network['is_tailscale'] ? 'tailscale' : '' ?>">
- <div class="card-header">
- <span class="network-name"><?= htmlspecialchars($network['friendly_name']) ?></span>
- <span class="status-badge online">●</span>
- </div>
- <div class="card-body">
- <div class="network-detail">
- <span class="label">CIDR</span>
- <span class="value"><?= htmlspecialchars($network['cidr']) ?></span>
- </div>
- <div class="network-detail">
- <span class="label">Interface</span>
- <span class="value"><?= htmlspecialchars($network['interface']) ?></span>
- </div>
- <div class="network-detail">
- <span class="label">IP</span>
- <span class="value"><?= htmlspecialchars($network['ip']) ?></span>
- </div>
- </div>
- <div class="card-footer">
- <button class="btn btn-primary btn-sm" onclick="scanNetwork('<?= htmlspecialchars($network['cidr'], ENT_QUOTES, 'UTF-8') ?>')">Scan Now</button>
- </div>
- </div>
- <?php endforeach; ?>
-
- <?php if ($tailscale['installed'] && $tailscale['running']): ?>
- <div class="card network-card tailscale">
- <div class="card-header">
- <span class="network-name">Tailscale</span>
- <span class="status-badge online">●</span>
- </div>
- <div class="card-body">
- <div class="network-detail">
- <span class="label">Status</span>
- <span class="value">✓ Connected</span>
- </div>
- <?php if ($tailscale['ip']): ?>
- <div class="network-detail">
- <span class="label">IP</span>
- <span class="value"><?= htmlspecialchars($tailscale['ip']) ?></span>
- </div>
- <?php endif; ?>
- <div class="network-detail">
- <span class="label">Peers</span>
- <span class="value"><?= intval($tailscale['peers']) ?></span>
- </div>
- </div>
- </div>
- <?php endif; ?>
- </div>
- </section>
-
- <section class="section">
- <div class="stats-bar">
- <div class="stat">
- <span class="stat-value"><?= intval($stats['total']) ?></span>
- <span class="stat-label">Total Devices</span>
- </div>
- <div class="stat">
- <span class="stat-value online"><?= intval($stats['online']) ?></span>
- <span class="stat-label">Online Now</span>
- </div>
- <div class="stat">
- <span class="stat-value"><?= intval($stats['new_24h']) ?></span>
- <span class="stat-label">New (24h)</span>
- </div>
- <div class="stat">
- <span class="stat-value"><?= count($networks) ?></span>
- <span class="stat-label">Networks</span>
- </div>
- </div>
- </section>
-
- <section class="section">
- <div class="section-header">
- <h2 class="section-title">Discovered Devices</h2>
- <div class="section-actions">
- <input type="text" id="device-search" class="input" placeholder="Search..." oninput="filterDevices()">
- <select id="device-filter" class="select" onchange="filterDevices()">
- <option value="all">All</option>
- <option value="online">Online</option>
- <option value="offline">Offline</option>
- </select>
- <button class="btn btn-primary" onclick="scanAllNetworks()">Scan All</button>
- </div>
- </div>
-
- <div class="table-container">
- <table class="table" id="devices-table">
- <thead>
- <tr>
- <th>Status</th>
- <th>IP Address</th>
- <th>Hostname</th>
- <th>MAC Address</th>
- <th>Vendor</th>
- <th>Label</th>
- <th>Group</th>
- <th>Last Seen</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody id="devices-tbody">
- <?php
- $deviceList = $devices['devices'] ?? [];
- uksort($deviceList, function($a, $b) {
- return ip2long($a) <=> ip2long($b);
- });
- foreach ($deviceList as $ip => $device):
- $lastSeen = strtotime($device['last_seen'] ?? '');
- $isOnline = $lastSeen && (time() - $lastSeen) < 3600;
- $isRecent = $lastSeen && (time() - $lastSeen) < 300;
- $statusClass = $isRecent ? 'online' : ($isOnline ? 'recent' : 'offline');
- ?>
- <tr class="device-row <?= $statusClass ?>"
- data-ip="<?= htmlspecialchars($ip) ?>"
- data-hostname="<?= htmlspecialchars(strtolower($device['hostname'] ?? '')) ?>"
- data-mac="<?= htmlspecialchars(strtolower($device['mac'] ?? '')) ?>"
- data-vendor="<?= htmlspecialchars(strtolower($device['vendor'] ?? '')) ?>"
- data-label="<?= htmlspecialchars(strtolower($device['label'] ?? '')) ?>"
- data-label-original="<?= htmlspecialchars($device['label'] ?? '', ENT_QUOTES, 'UTF-8') ?>"
- data-status="<?= $statusClass ?>">
- <td><span class="status-indicator <?= $statusClass ?>">●</span></td>
- <td class="ip-cell"><?= htmlspecialchars($ip) ?></td>
- <td><?= htmlspecialchars($device['hostname'] ?? '-') ?></td>
- <td class="mac-cell"><?= htmlspecialchars($device['mac'] ?? '-') ?></td>
- <td><?= htmlspecialchars($device['vendor'] ?? 'Unknown') ?></td>
- <td><?= htmlspecialchars($device['label'] ?? '') ?></td>
- <td>
- <select class="group-select" data-ip="<?= htmlspecialchars($ip, ENT_QUOTES, 'UTF-8') ?>" onchange="updateDeviceGroup(this)">
- <option value="">-</option>
- <option value="Server" <?= ($device['group'] ?? '') === 'Server' ? 'selected' : '' ?>>Server</option>
- <option value="Desktop" <?= ($device['group'] ?? '') === 'Desktop' ? 'selected' : '' ?>>Desktop</option>
- <option value="Laptop" <?= ($device['group'] ?? '') === 'Laptop' ? 'selected' : '' ?>>Laptop</option>
- <option value="Mobile" <?= ($device['group'] ?? '') === 'Mobile' ? 'selected' : '' ?>>Mobile</option>
- <option value="IoT" <?= ($device['group'] ?? '') === 'IoT' ? 'selected' : '' ?>>IoT</option>
- <option value="Network" <?= ($device['group'] ?? '') === 'Network' ? 'selected' : '' ?>>Network</option>
- <option value="Pi" <?= ($device['group'] ?? '') === 'Pi' ? 'selected' : '' ?>>Pi</option>
- </select>
- </td>
- <td class="time-cell"><?= $lastSeen ? timeAgo($lastSeen) : '-' ?></td>
- <td class="actions-cell">
- <button class="btn-icon" onclick="editDevice('<?= htmlspecialchars($ip, ENT_QUOTES, 'UTF-8') ?>')" title="Edit">✎</button>
- <button class="btn-icon danger" onclick="deleteDevice('<?= htmlspecialchars($ip, ENT_QUOTES, 'UTF-8') ?>')" title="Delete">✕</button>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- <?php if (empty($deviceList)): ?>
- <div class="empty-state">
- <p>No devices discovered yet. Click "Scan All" to discover devices.</p>
- </div>
- <?php endif; ?>
- </section>
- </main>
-
- <div id="edit-modal" class="modal" style="display:none">
- <div class="modal-content">
- <div class="modal-header">
- <h3>Edit Device</h3>
- <button class="modal-close" onclick="closeModal()">×</button>
- </div>
- <div class="modal-body">
- <form id="edit-form">
- <input type="hidden" id="edit-ip" name="ip">
- <div class="form-group">
- <label>IP Address</label>
- <input type="text" id="edit-ip-display" class="input" disabled>
- </div>
- <div class="form-group">
- <label>Label</label>
- <input type="text" id="edit-label" name="label" class="input" placeholder="e.g., Living Room TV">
- </div>
- <div class="form-group">
- <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>
- </select>
- </div>
- <div class="form-group">
- <label>Notes</label>
- <textarea id="edit-notes" name="notes" class="input" rows="3"></textarea>
- </div>
- </form>
- </div>
- <div class="modal-footer">
- <button class="btn" onclick="closeModal()">Cancel</button>
- <button class="btn btn-primary" onclick="saveDevice()">Save</button>
- </div>
- </div>
- </div>
-
- <div id="toast" class="toast"></div>
- <div id="scan-progress" class="scan-progress" style="display:none">
- <div class="scan-spinner"></div>
- <span>Scanning...</span>
- </div>
-
- <footer class="footer">
- <p>🦧 LAN Orangutan by <a href="https://291group.com" target="_blank">291 Group</a></p>
- </footer>
-
- <script src="assets/app.js"></script>
-</body>
-</html>
diff --git a/web/settings.php b/web/settings.php
deleted file mode 100644
index 7184b72..0000000
--- a/web/settings.php
+++ /dev/null
@@ -1,270 +0,0 @@
-<?php
-/**
- * LAN Orangutan - Settings Page
- */
-require_once __DIR__ . '/api.php';
-
-// CSRF token generation and validation
-session_start();
-if (empty($_SESSION['csrf_token'])) {
- $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
-}
-
-function validateCsrfToken($token) {
- return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
-}
-
-function sanitizeBindAddress($value) {
- $allowed = ['0.0.0.0', '127.0.0.1'];
- return in_array($value, $allowed, true) ? $value : '0.0.0.0';
-}
-
-function sanitizeTheme($value) {
- $allowed = ['light', 'dark', 'auto'];
- return in_array($value, $allowed, true) ? $value : 'auto';
-}
-
-function sanitizePortRange($value) {
- // Only allow valid port range format: number-number or single number
- if (preg_match('/^(\d{1,5})(-(\d{1,5}))?$/', $value, $m)) {
- $start = (int)$m[1];
- $end = isset($m[3]) ? (int)$m[3] : $start;
- if ($start >= 1 && $start <= 65535 && $end >= 1 && $end <= 65535 && $start <= $end) {
- return $value;
- }
- }
- return '1-1024';
-}
-
-$api = new LanOrangutanAPI();
-$config = $api->getConfig();
-$networks = $api->getNetworks();
-$tailscale = $api->getTailscaleStatus();
-$status = $api->getSystemStatus();
-$message = '';
-$messageType = '';
-
-if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_settings') {
- // Validate CSRF token
- if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
- $message = 'Invalid security token. Please try again.';
- $messageType = 'error';
- } else {
- $port = intval($_POST['port'] ?? 291);
- $port = ($port >= 1 && $port <= 65535) ? $port : 291;
-
- $maxDevices = intval($_POST['max_devices'] ?? 1000);
- $maxDevices = ($maxDevices >= 10 && $maxDevices <= 10000) ? $maxDevices : 1000;
-
- $retentionDays = intval($_POST['retention_days'] ?? 90);
- $retentionDays = ($retentionDays >= 1 && $retentionDays <= 365) ? $retentionDays : 90;
-
- $scanInterval = intval($_POST['scan_interval'] ?? 300);
- $allowedIntervals = [0, 300, 900, 1800, 3600];
- $scanInterval = in_array($scanInterval, $allowedIntervals, true) ? $scanInterval : 300;
-
- $newConfig = [
- 'server' => [
- 'port' => $port,
- 'bind_address' => sanitizeBindAddress($_POST['bind_address'] ?? '0.0.0.0'),
- 'enable_api' => isset($_POST['enable_api'])
- ],
- 'scanning' => [
- 'scan_interval' => $scanInterval,
- 'min_scan_interval' => 30,
- 'enable_port_scan' => isset($_POST['enable_port_scan']),
- 'port_scan_range' => sanitizePortRange($_POST['port_scan_range'] ?? '1-1024')
- ],
- 'storage' => [
- 'max_devices' => $maxDevices,
- 'retention_days' => $retentionDays,
- 'data_dir' => '/var/lib/lan-orangutan'
- ],
- 'tailscale' => [
- 'enable' => isset($_POST['tailscale_enable']),
- 'auto_detect' => isset($_POST['tailscale_auto_detect'])
- ],
- 'ui' => ['theme' => sanitizeTheme($_POST['theme'] ?? 'auto')]
- ];
- if ($api->saveConfig($newConfig)) {
- $message = 'Settings saved successfully';
- $messageType = 'success';
- $config = $newConfig;
- } else {
- $message = 'Failed to save settings';
- $messageType = 'error';
- }
- }
-}
-$theme = $config['ui']['theme'] ?? 'auto';
-?>
-<!DOCTYPE html>
-<html lang="en" data-theme="<?= htmlspecialchars($theme) ?>">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Settings - LAN Orangutan</title>
- <link rel="stylesheet" href="assets/style.css">
- <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🦧</text></svg>">
-</head>
-<body>
- <header class="header">
- <div class="header-brand">
- <span class="logo">🦧</span>
- <h1>LAN Orangutan</h1>
- </div>
- <nav class="header-nav">
- <a href="index.php" class="nav-link">Dashboard</a>
- <a href="settings.php" class="nav-link active">Settings</a>
- <button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">◐</button>
- </nav>
- </header>
-
- <main class="main">
- <?php if ($message): ?>
- <div class="alert alert-<?= $messageType ?>"><?= htmlspecialchars($message) ?></div>
- <?php endif; ?>
-
- <form method="POST" class="settings-form">
- <input type="hidden" name="action" value="save_settings">
- <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
-
- <section class="section">
- <h2 class="section-title">Server Settings</h2>
- <div class="card">
- <div class="form-group">
- <label for="port">Port</label>
- <input type="number" id="port" name="port" class="input" value="<?= intval($config['server']['port'] ?? 291) ?>" min="1" max="65535">
- <p class="form-help">Default: 291. Changing requires service restart.</p>
- </div>
- <div class="form-group">
- <label for="bind_address">Bind Address</label>
- <select id="bind_address" name="bind_address" class="select">
- <option value="0.0.0.0" <?= ($config['server']['bind_address'] ?? '') === '0.0.0.0' ? 'selected' : '' ?>>0.0.0.0 (All interfaces)</option>
- <option value="127.0.0.1" <?= ($config['server']['bind_address'] ?? '') === '127.0.0.1' ? 'selected' : '' ?>>127.0.0.1 (Localhost only)</option>
- </select>
- </div>
- <div class="form-group">
- <label class="checkbox-label">
- <input type="checkbox" name="enable_api" <?= ($config['server']['enable_api'] ?? true) ? 'checked' : '' ?>>
- Enable API
- </label>
- </div>
- </div>
- </section>
-
- <section class="section">
- <h2 class="section-title">Scanning</h2>
- <div class="card">
- <div class="form-group">
- <label for="scan_interval">Auto-scan Interval</label>
- <select id="scan_interval" name="scan_interval" class="select">
- <option value="0" <?= ($config['scanning']['scan_interval'] ?? 0) == 0 ? 'selected' : '' ?>>Manual Only</option>
- <option value="300" <?= ($config['scanning']['scan_interval'] ?? 0) == 300 ? 'selected' : '' ?>>5 minutes</option>
- <option value="900" <?= ($config['scanning']['scan_interval'] ?? 0) == 900 ? 'selected' : '' ?>>15 minutes</option>
- <option value="1800" <?= ($config['scanning']['scan_interval'] ?? 0) == 1800 ? 'selected' : '' ?>>30 minutes</option>
- <option value="3600" <?= ($config['scanning']['scan_interval'] ?? 0) == 3600 ? 'selected' : '' ?>>1 hour</option>
- </select>
- </div>
- <div class="form-group">
- <label class="checkbox-label">
- <input type="checkbox" name="enable_port_scan" <?= ($config['scanning']['enable_port_scan'] ?? false) ? 'checked' : '' ?>>
- Enable Port Scanning
- </label>
- </div>
- </div>
- </section>
-
- <section class="section">
- <h2 class="section-title">Networks</h2>
- <div class="card">
- <h3 class="subsection-title">Detected Networks</h3>
- <div class="network-list">
- <?php foreach ($networks as $net): ?>
- <div class="network-item">
- <strong><?= htmlspecialchars($net['friendly_name']) ?></strong>
- <span class="network-cidr"><?= htmlspecialchars($net['cidr']) ?></span>
- <span class="network-interface"><?= htmlspecialchars($net['interface']) ?></span>
- </div>
- <?php endforeach; ?>
- </div>
- </div>
- </section>
-
- <section class="section">
- <h2 class="section-title">Tailscale</h2>
- <div class="card">
- <div class="status-row">
- <span class="status-label">Status:</span>
- <span class="status-value <?= $tailscale['running'] ? 'online' : ($tailscale['installed'] ? 'offline' : 'warning') ?>">
- <?= $tailscale['running'] ? '✓ Connected' : ($tailscale['installed'] ? '✗ Disconnected' : 'Not Installed') ?>
- </span>
- </div>
- <?php if ($tailscale['ip']): ?>
- <div class="status-row">
- <span class="status-label">IP:</span>
- <span class="status-value"><?= htmlspecialchars($tailscale['ip']) ?></span>
- </div>
- <?php endif; ?>
- <div class="form-group">
- <label class="checkbox-label">
- <input type="checkbox" name="tailscale_enable" <?= ($config['tailscale']['enable'] ?? true) ? 'checked' : '' ?>>
- Enable Tailscale Integration
- </label>
- </div>
- </div>
- </section>
-
- <section class="section">
- <h2 class="section-title">Storage</h2>
- <div class="card">
- <div class="form-group">
- <label for="max_devices">Max Devices</label>
- <input type="number" id="max_devices" name="max_devices" class="input" value="<?= intval($config['storage']['max_devices'] ?? 1000) ?>" min="10" max="10000">
- </div>
- <div class="form-group">
- <label for="retention_days">Device Retention (days)</label>
- <input type="number" id="retention_days" name="retention_days" class="input" value="<?= intval($config['storage']['retention_days'] ?? 90) ?>" min="1" max="365">
- </div>
- <div class="status-row">
- <span class="status-label">Disk Space:</span>
- <span class="status-value <?= $status['disk_ok'] ? 'online' : 'offline' ?>"><?= intval($status['disk_free_mb']) ?> MB free</span>
- </div>
- </div>
- </section>
-
- <section class="section">
- <h2 class="section-title">Appearance</h2>
- <div class="card">
- <div class="form-group">
- <label>Theme</label>
- <div class="radio-group">
- <label class="radio-label"><input type="radio" name="theme" value="light" <?= ($config['ui']['theme'] ?? '') === 'light' ? 'checked' : '' ?>> Light</label>
- <label class="radio-label"><input type="radio" name="theme" value="dark" <?= ($config['ui']['theme'] ?? '') === 'dark' ? 'checked' : '' ?>> Dark</label>
- <label class="radio-label"><input type="radio" name="theme" value="auto" <?= ($config['ui']['theme'] ?? 'auto') === 'auto' ? 'checked' : '' ?>> Auto</label>
- </div>
- </div>
- </div>
- </section>
-
- <section class="section">
- <h2 class="section-title">System Status</h2>
- <div class="card">
- <div class="status-row"><span class="status-label">PHP:</span><span class="status-value"><?= htmlspecialchars($status['php_version']) ?></span></div>
- <div class="status-row"><span class="status-label">Scanner:</span><span class="status-value <?= $status['scanner_available'] ? 'online' : 'offline' ?>"><?= $status['scanner_available'] ? '✓ Available' : '✗ Not found' ?></span></div>
- <div class="status-row"><span class="status-label">nmap:</span><span class="status-value <?= $status['nmap_available'] ? 'online' : 'warning' ?>"><?= $status['nmap_available'] ? '✓ Installed' : '⚠ Not installed' ?></span></div>
- </div>
- </section>
-
- <div class="form-actions">
- <button type="submit" class="btn btn-primary btn-large">Save Settings</button>
- </div>
- </form>
- </main>
-
- <footer class="footer">
- <p>🦧 LAN Orangutan by <a href="https://291group.com" target="_blank">291 Group</a></p>
- </footer>
- <script src="assets/app.js"></script>
-</body>
-</html>