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.

Initial release v2.1.11

filebay9c0130bcf530
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..c4c0fa7
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,90 @@
+name: CI
+
+on:
+ push:
+ branches: [main, master]
+ pull_request:
+ branches: [main, master]
+
+jobs:
+ go-lint:
+ 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'
+
+ - name: Build
+ run: go build -v ./...
+
+ - name: Vet
+ run: go vet ./...
+
+ - name: Test
+ run: go test -v ./...
+
+ legacy-lint:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Setup Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - name: Lint Python
+ run: |
+ pip install flake8
+ flake8 scanner/*.py --max-line-length=120 --ignore=E501,W503
+
+ - name: Check shell scripts
+ run: |
+ sudo apt-get install -y shellcheck
+ shellcheck install.sh uninstall.sh scripts/*.sh || true
+
+ - name: Validate PHP syntax
+ run: |
+ php -l web/*.php || true
+
+ test:
+ 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'
+
+ - 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')
+ "
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..e0b8d9d
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,603 @@
+name: Release
+
+on:
+ push:
+ tags:
+ - 'v*'
+
+permissions:
+ contents: write
+ packages: write
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ include:
+ - goos: linux
+ goarch: amd64
+ suffix: linux-amd64
+ - goos: linux
+ goarch: arm64
+ suffix: linux-arm64
+ - goos: linux
+ goarch: arm
+ goarm: "7"
+ suffix: linux-arm
+ - goos: darwin
+ goarch: amd64
+ suffix: darwin-amd64
+ - goos: darwin
+ goarch: arm64
+ suffix: darwin-arm64
+ - goos: windows
+ goarch: amd64
+ suffix: windows-amd64
+ ext: .exe
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Set up Go
+ uses: actions/setup-go@v5
+ with:
+ go-version: '1.22'
+
+ - name: Get version from tag
+ id: version
+ run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
+
+ - name: Build binary
+ env:
+ GOOS: ${{ matrix.goos }}
+ GOARCH: ${{ matrix.goarch }}
+ GOARM: ${{ matrix.goarm }}
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ COMMIT=$(git rev-parse --short HEAD)
+ BUILD_DATE=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+
+ 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}'"
+
+ go build -ldflags "${LDFLAGS}" -o orangutan-${{ matrix.suffix }}${{ matrix.ext }} ./cmd/orangutan
+
+ - name: Upload artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: orangutan-${{ matrix.suffix }}
+ path: orangutan-${{ matrix.suffix }}${{ matrix.ext }}
+
+ docker:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Get version from tag
+ id: version
+ run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
+
+ - name: Set up QEMU
+ uses: docker/setup-qemu-action@v3
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Login to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Prepare image name
+ id: image
+ run: echo "name=ghcr.io/${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT
+
+ - name: Build and push Docker image
+ uses: docker/build-push-action@v5
+ with:
+ context: .
+ platforms: linux/amd64,linux/arm64
+ push: true
+ tags: |
+ ${{ steps.image.outputs.name }}:${{ steps.version.outputs.VERSION }}
+ ${{ steps.image.outputs.name }}:latest
+
+ release:
+ needs: build
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Get version from tag
+ id: version
+ run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
+
+ - name: Download all artifacts
+ uses: actions/download-artifact@v4
+ with:
+ path: dist
+
+ - name: Debug - Show downloaded artifacts
+ run: |
+ echo "=== Contents of dist/ ==="
+ ls -la dist/
+ echo "=== Contents of each artifact directory ==="
+ for dir in dist/orangutan-*/; do
+ echo "--- $dir ---"
+ ls -la "$dir"
+ done
+
+ - name: Prepare release files
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ cd dist
+
+ # Process each artifact directory
+ for dir in orangutan-*/; do
+ [ -d "$dir" ] || continue
+
+ dir_name="${dir%/}"
+ echo "Processing: $dir_name"
+
+ # Get the binary file (should be only one file in the directory)
+ binary_path=$(find "$dir" -type f | head -1)
+ binary_name=$(basename "$binary_path")
+
+ echo " Found binary: $binary_name"
+
+ # Move binary to temp location first to avoid path conflicts
+ mv "$binary_path" "../${binary_name}.tmp"
+ rm -rf "$dir"
+ mv "../${binary_name}.tmp" "./$binary_name"
+
+ # Create archive
+ if [[ "$binary_name" == *.exe ]]; then
+ echo " Creating zip: ${binary_name%.exe}.zip"
+ zip "${binary_name%.exe}.zip" "$binary_name"
+ else
+ echo " Creating tar.gz: ${binary_name}.tar.gz"
+ tar -czvf "${binary_name}.tar.gz" "$binary_name"
+ fi
+ done
+
+ echo "=== Final dist/ contents ==="
+ ls -la
+
+ - name: Create legacy archive (for install.sh compatibility)
+ 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
+ cd dist
+ tar -czvf "${ARCHIVE_NAME}.tar.gz" "${ARCHIVE_NAME}"
+ rm -rf "${ARCHIVE_NAME}"
+
+ - name: Build .deb package
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ PKG_NAME="lan-orangutan"
+
+ # Build for each architecture
+ for arch_info in "amd64:linux-amd64" "arm64:linux-arm64" "armhf:linux-arm"; do
+ DEB_ARCH="${arch_info%%:*}"
+ BIN_SUFFIX="${arch_info##*:}"
+ PKG_DIR="dist/${PKG_NAME}_${VERSION}_${DEB_ARCH}"
+
+ # Create package structure
+ mkdir -p "${PKG_DIR}/DEBIAN"
+ mkdir -p "${PKG_DIR}/usr/local/bin"
+ mkdir -p "${PKG_DIR}/etc/lan-orangutan"
+ mkdir -p "${PKG_DIR}/var/lib/lan-orangutan"
+ mkdir -p "${PKG_DIR}/lib/systemd/system"
+
+ # Copy binary
+ cp "dist/orangutan-${BIN_SUFFIX}" "${PKG_DIR}/usr/local/bin/orangutan"
+ chmod 755 "${PKG_DIR}/usr/local/bin/orangutan"
+
+ # Copy config
+ cp config.example.ini "${PKG_DIR}/etc/lan-orangutan/config.ini"
+
+ # Create systemd service for Go version
+ cat > "${PKG_DIR}/lib/systemd/system/lan-orangutan.service" << EOF
+ [Unit]
+ Description=LAN Orangutan Network Discovery
+ After=network.target
+
+ [Service]
+ Type=simple
+ ExecStart=/usr/local/bin/orangutan serve
+ Restart=on-failure
+ RestartSec=5
+
+ [Install]
+ WantedBy=multi-user.target
+ EOF
+
+ # Create control file
+ cat > "${PKG_DIR}/DEBIAN/control" << EOF
+ Package: lan-orangutan
+ Version: ${VERSION}
+ Section: net
+ Priority: optional
+ Architecture: ${DEB_ARCH}
+ Depends: nmap
+ Maintainer: 291 Group <[email protected]>
+ Description: LAN Orangutan - Network Discovery Tool
+ A lightweight network discovery and device tracking tool
+ with a web dashboard and CLI. Discover devices on your
+ local network, track online/offline status, and organize
+ with labels and groups.
+ Homepage: https://github.com/291-Group/LAN-Orangutan
+ EOF
+
+ # Create postinst script
+ cat > "${PKG_DIR}/DEBIAN/postinst" << 'POSTINST'
+ #!/bin/bash
+ set -e
+ systemctl daemon-reload
+ systemctl enable lan-orangutan
+ echo ""
+ echo "LAN Orangutan installed successfully!"
+ echo ""
+ echo "Start the service with: sudo systemctl start lan-orangutan"
+ echo "Access the web UI at: http://localhost:291"
+ echo ""
+ POSTINST
+ chmod 755 "${PKG_DIR}/DEBIAN/postinst"
+
+ # Create prerm script
+ cat > "${PKG_DIR}/DEBIAN/prerm" << 'PRERM'
+ #!/bin/bash
+ set -e
+ systemctl stop lan-orangutan 2>/dev/null || true
+ systemctl disable lan-orangutan 2>/dev/null || true
+ PRERM
+ chmod 755 "${PKG_DIR}/DEBIAN/prerm"
+
+ # Create postrm script
+ cat > "${PKG_DIR}/DEBIAN/postrm" << 'POSTRM'
+ #!/bin/bash
+ set -e
+ systemctl daemon-reload
+ POSTRM
+ chmod 755 "${PKG_DIR}/DEBIAN/postrm"
+
+ # Create conffiles
+ echo "/etc/lan-orangutan/config.ini" > "${PKG_DIR}/DEBIAN/conffiles"
+
+ # Build the package
+ dpkg-deb --build "${PKG_DIR}"
+ done
+
+ - name: Build .rpm package
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ sudo apt-get update && sudo apt-get install -y rpm
+
+ # Build for each architecture
+ for arch_info in "x86_64:linux-amd64" "aarch64:linux-arm64"; do
+ RPM_ARCH="${arch_info%%:*}"
+ BIN_SUFFIX="${arch_info##*:}"
+
+ # Create RPM build structure
+ mkdir -p rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS}
+ mkdir -p "rpmbuild/BUILDROOT/lan-orangutan-${VERSION}-1.${RPM_ARCH}"
+
+ BUILDROOT="rpmbuild/BUILDROOT/lan-orangutan-${VERSION}-1.${RPM_ARCH}"
+ mkdir -p "${BUILDROOT}/usr/local/bin"
+ mkdir -p "${BUILDROOT}/etc/lan-orangutan"
+ mkdir -p "${BUILDROOT}/var/lib/lan-orangutan"
+ mkdir -p "${BUILDROOT}/usr/lib/systemd/system"
+
+ # Copy binary
+ cp "dist/orangutan-${BIN_SUFFIX}" "${BUILDROOT}/usr/local/bin/orangutan"
+ chmod 755 "${BUILDROOT}/usr/local/bin/orangutan"
+
+ # Copy config
+ cp config.example.ini "${BUILDROOT}/etc/lan-orangutan/config.ini"
+
+ # Create systemd service
+ cat > "${BUILDROOT}/usr/lib/systemd/system/lan-orangutan.service" << EOF
+ [Unit]
+ Description=LAN Orangutan Network Discovery
+ After=network.target
+
+ [Service]
+ Type=simple
+ ExecStart=/usr/local/bin/orangutan serve
+ Restart=on-failure
+ RestartSec=5
+
+ [Install]
+ WantedBy=multi-user.target
+ EOF
+
+ # Create spec file
+ cat > "rpmbuild/SPECS/lan-orangutan.spec" << EOF
+ Name: lan-orangutan
+ Version: ${VERSION}
+ Release: 1
+ Summary: Network Discovery Tool
+ License: MIT
+ URL: https://github.com/291-Group/LAN-Orangutan
+ Requires: nmap
+
+ %description
+ A lightweight network discovery and device tracking tool
+ with a web dashboard and CLI.
+
+ %files
+ /usr/local/bin/orangutan
+ %config(noreplace) /etc/lan-orangutan/config.ini
+ /usr/lib/systemd/system/lan-orangutan.service
+ %dir /var/lib/lan-orangutan
+ %dir /etc/lan-orangutan
+
+ %post
+ systemctl daemon-reload
+ systemctl enable lan-orangutan
+
+ %preun
+ systemctl stop lan-orangutan 2>/dev/null || true
+ systemctl disable lan-orangutan 2>/dev/null || true
+
+ %postun
+ systemctl daemon-reload
+ EOF
+
+ # Build RPM
+ rpmbuild --define "_topdir $(pwd)/rpmbuild" \
+ --define "_arch ${RPM_ARCH}" \
+ --target "${RPM_ARCH}" \
+ -bb "rpmbuild/SPECS/lan-orangutan.spec"
+
+ # Move to dist
+ cp rpmbuild/RPMS/${RPM_ARCH}/*.rpm dist/ 2>/dev/null || true
+
+ # Clean up for next iteration
+ rm -rf rpmbuild
+ done
+
+ - name: Build Alpine .apk package
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+
+ # Build for x86_64 only (most common Alpine use case)
+ mkdir -p apk-build
+ cd apk-build
+
+ # Create package directory structure
+ mkdir -p pkg/usr/local/bin
+ mkdir -p pkg/etc/lan-orangutan
+ mkdir -p pkg/var/lib/lan-orangutan
+ mkdir -p pkg/etc/init.d
+
+ # Copy binary
+ cp "../dist/orangutan-linux-amd64" "pkg/usr/local/bin/orangutan"
+ chmod 755 "pkg/usr/local/bin/orangutan"
+
+ # Copy config
+ cp ../config.example.ini "pkg/etc/lan-orangutan/config.ini"
+
+ # Create OpenRC init script (Alpine uses OpenRC, not systemd)
+ cat > "pkg/etc/init.d/lan-orangutan" << 'INITSCRIPT'
+ #!/sbin/openrc-run
+
+ name="lan-orangutan"
+ description="LAN Orangutan Network Discovery"
+ command="/usr/local/bin/orangutan"
+ command_args="serve"
+ command_background="yes"
+ pidfile="/run/${RC_SVCNAME}.pid"
+
+ depend() {
+ need net
+ after firewall
+ }
+ INITSCRIPT
+ chmod 755 "pkg/etc/init.d/lan-orangutan"
+
+ # Create APKBUILD info file (note: .PKGINFO is a file, not a directory)
+ cat > "pkg/.PKGINFO" << EOF
+ pkgname = lan-orangutan
+ pkgver = ${VERSION}-r0
+ pkgdesc = Network Discovery Tool
+ url = https://github.com/291-Group/LAN-Orangutan
+ size = $(du -sb pkg | cut -f1)
+ arch = x86_64
+ license = MIT
+ depend = nmap
+ EOF
+
+ # Create the package (simple tar.gz with specific structure)
+ cd pkg
+ tar -czvf "../../dist/lan-orangutan-${VERSION}-r0.apk" .
+ cd ../..
+ rm -rf apk-build
+
+ - name: Create Homebrew formula
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+
+ # Calculate SHA256 for macOS binaries
+ SHA_AMD64=$(sha256sum dist/orangutan-darwin-amd64.tar.gz | cut -d' ' -f1)
+ SHA_ARM64=$(sha256sum dist/orangutan-darwin-arm64.tar.gz | cut -d' ' -f1)
+
+ cat > dist/lan-orangutan.rb << EOF
+ class LanOrangutan < Formula
+ desc "Network discovery and device tracking tool"
+ homepage "https://github.com/291-Group/LAN-Orangutan"
+ version "${VERSION}"
+ license "MIT"
+
+ on_macos do
+ if Hardware::CPU.arm?
+ url "https://github.com/291-Group/LAN-Orangutan/releases/download/v${VERSION}/orangutan-darwin-arm64.tar.gz"
+ sha256 "${SHA_ARM64}"
+ else
+ url "https://github.com/291-Group/LAN-Orangutan/releases/download/v${VERSION}/orangutan-darwin-amd64.tar.gz"
+ sha256 "${SHA_AMD64}"
+ end
+ end
+
+ depends_on "nmap"
+
+ def install
+ bin.install "orangutan-darwin-arm64" => "orangutan" if Hardware::CPU.arm?
+ bin.install "orangutan-darwin-amd64" => "orangutan" unless Hardware::CPU.arm?
+
+ # Create config directory
+ (etc/"lan-orangutan").mkpath
+ (var/"lib/lan-orangutan").mkpath
+ end
+
+ service do
+ run [opt_bin/"orangutan", "serve"]
+ keep_alive true
+ working_dir var/"lib/lan-orangutan"
+ log_path var/"log/lan-orangutan.log"
+ error_log_path var/"log/lan-orangutan.log"
+ end
+
+ test do
+ system "#{bin}/orangutan", "version"
+ end
+ end
+ EOF
+
+ - name: Create Scoop manifest (Windows)
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ SHA_WIN=$(sha256sum dist/orangutan-windows-amd64.zip | cut -d' ' -f1)
+
+ cat > dist/lan-orangutan.json << EOF
+ {
+ "version": "${VERSION}",
+ "description": "Network discovery and device tracking tool",
+ "homepage": "https://github.com/291-Group/LAN-Orangutan",
+ "license": "MIT",
+ "architecture": {
+ "64bit": {
+ "url": "https://github.com/291-Group/LAN-Orangutan/releases/download/v${VERSION}/orangutan-windows-amd64.zip",
+ "hash": "${SHA_WIN}"
+ }
+ },
+ "bin": "orangutan-windows-amd64.exe",
+ "checkver": "github",
+ "autoupdate": {
+ "architecture": {
+ "64bit": {
+ "url": "https://github.com/291-Group/LAN-Orangutan/releases/download/v\$version/orangutan-windows-amd64.zip"
+ }
+ }
+ }
+ }
+ EOF
+
+ - name: Create AUR PKGBUILD (Arch Linux)
+ run: |
+ VERSION=${{ steps.version.outputs.VERSION }}
+ SHA_AMD64=$(sha256sum dist/orangutan-linux-amd64.tar.gz | cut -d' ' -f1)
+
+ cat > dist/PKGBUILD << EOF
+ # Maintainer: 291 Group <[email protected]>
+ pkgname=lan-orangutan
+ pkgver=${VERSION}
+ pkgrel=1
+ pkgdesc="Network discovery and device tracking tool"
+ arch=('x86_64')
+ url="https://github.com/291-Group/LAN-Orangutan"
+ license=('MIT')
+ depends=('nmap')
+ source=("https://github.com/291-Group/LAN-Orangutan/releases/download/v\${pkgver}/orangutan-linux-amd64.tar.gz")
+ sha256sums=('${SHA_AMD64}')
+
+ package() {
+ install -Dm755 orangutan-linux-amd64 "\${pkgdir}/usr/bin/orangutan"
+ install -Dm644 /dev/stdin "\${pkgdir}/usr/lib/systemd/system/lan-orangutan.service" << SYSTEMD
+ [Unit]
+ Description=LAN Orangutan Network Discovery
+ After=network.target
+
+ [Service]
+ Type=simple
+ ExecStart=/usr/bin/orangutan serve
+ Restart=on-failure
+ RestartSec=5
+
+ [Install]
+ WantedBy=multi-user.target
+ SYSTEMD
+ install -dm755 "\${pkgdir}/etc/lan-orangutan"
+ install -dm755 "\${pkgdir}/var/lib/lan-orangutan"
+ }
+ EOF
+
+ - name: Debug - List all release files
+ run: |
+ echo "=== All files in dist/ before release ==="
+ ls -la dist/
+ echo ""
+ echo "=== tar.gz files ==="
+ ls -la dist/*.tar.gz 2>/dev/null || echo "No tar.gz files"
+ echo ""
+ echo "=== zip files ==="
+ ls -la dist/*.zip 2>/dev/null || echo "No zip files"
+ echo ""
+ echo "=== deb files ==="
+ ls -la dist/*.deb 2>/dev/null || echo "No deb files"
+ echo ""
+ echo "=== rpm files ==="
+ ls -la dist/*.rpm 2>/dev/null || echo "No rpm files"
+
+ - name: Generate checksums
+ run: |
+ cd dist
+ sha256sum *.tar.gz *.zip *.deb *.rpm *.apk 2>/dev/null > SHA256SUMS.txt || true
+ echo "=== SHA256SUMS.txt contents ==="
+ cat SHA256SUMS.txt
+
+ - name: Create GitHub Release
+ uses: softprops/action-gh-release@v1
+ with:
+ files: |
+ dist/*.tar.gz
+ dist/*.zip
+ dist/*.deb
+ dist/*.rpm
+ dist/*.apk
+ dist/*.rb
+ dist/*.json
+ dist/PKGBUILD
+ dist/SHA256SUMS.txt
+ generate_release_notes: true
+ draft: false
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f5a2494
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,18 @@
+# Binaries
+orangutan
+orangutan-*
+*.exe
+
+# Data
+*.json
+!package.json
+
+# Config with secrets
+config.ini
+
+# IDE
+.idea/
+.vscode/
+
+# OS
+.DS_Store
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..6800a74
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,50 @@
+# Build stage
+FROM golang:1.22-alpine AS builder
+
+WORKDIR /app
+
+# Install build dependencies
+RUN apk add --no-cache git
+
+# Copy go mod files
+COPY go.mod go.sum ./
+RUN go mod download
+
+# Copy source
+COPY . .
+
+# Build binary
+RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o orangutan ./cmd/orangutan
+
+# Runtime stage
+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
+
+# Copy binary from builder
+COPY --from=builder /app/orangutan /usr/local/bin/orangutan
+COPY config.example.ini /etc/lan-orangutan/config.ini
+
+# Set permissions
+RUN chmod +x /usr/local/bin/orangutan
+
+# Expose port
+EXPOSE 291
+
+# Run as non-root (but nmap needs NET_RAW capability)
+USER orangutan
+
+# Health check
+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
+ CMD wget --no-verbose --tries=1 --spider http://localhost:291/api/status || exit 1
+
+ENTRYPOINT ["orangutan"]
+CMD ["serve"]
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..825a07b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 291 Group
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..7890574
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,122 @@
+# LAN Orangutan Makefile
+
+VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
+COMMIT ?= $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown")
+BUILD_DATE ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
+
+LDFLAGS := -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)'"
+
+BINARY := orangutan
+BUILD_DIR := bin
+
+.PHONY: all build clean test lint install
+
+all: build
+
+# Build for current platform
+build:
+ go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY) ./cmd/orangutan
+
+# Build for all platforms
+build-all: build-linux build-darwin build-windows
+
+# Linux builds
+build-linux: build-linux-amd64 build-linux-arm64 build-linux-arm
+
+build-linux-amd64:
+ GOOS=linux GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-amd64 ./cmd/orangutan
+
+build-linux-arm64:
+ GOOS=linux GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-arm64 ./cmd/orangutan
+
+build-linux-arm:
+ GOOS=linux GOARCH=arm GOARM=7 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-linux-arm ./cmd/orangutan
+
+# macOS builds
+build-darwin: build-darwin-amd64 build-darwin-arm64
+
+build-darwin-amd64:
+ GOOS=darwin GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-darwin-amd64 ./cmd/orangutan
+
+build-darwin-arm64:
+ GOOS=darwin GOARCH=arm64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-darwin-arm64 ./cmd/orangutan
+
+# Windows builds
+build-windows: build-windows-amd64
+
+build-windows-amd64:
+ GOOS=windows GOARCH=amd64 go build $(LDFLAGS) -o $(BUILD_DIR)/$(BINARY)-windows-amd64.exe ./cmd/orangutan
+
+# Run tests
+test:
+ go test -v ./...
+
+# Run linter
+lint:
+ golangci-lint run
+
+# Format code
+fmt:
+ go fmt ./...
+
+# Tidy dependencies
+tidy:
+ go mod tidy
+
+# Clean build artifacts
+clean:
+ rm -rf $(BUILD_DIR)
+ go clean
+
+# Install locally
+install: build
+ sudo cp $(BUILD_DIR)/$(BINARY) /usr/local/bin/$(BINARY)
+
+# Development run
+run: build
+ ./$(BUILD_DIR)/$(BINARY) serve
+
+# Check for vulnerabilities
+vuln:
+ go install golang.org/x/vuln/cmd/govulncheck@latest
+ govulncheck ./...
+
+# Generate checksums for release
+checksums:
+ cd $(BUILD_DIR) && sha256sum $(BINARY)-* > SHA256SUMS.txt
+
+# Create release archives
+release: build-all checksums
+ cd $(BUILD_DIR) && for f in $(BINARY)-*; do \
+ if [ -f "$$f" ] && [ "$$f" != "SHA256SUMS.txt" ]; then \
+ if echo "$$f" | grep -q ".exe"; then \
+ zip "$${f%.exe}.zip" "$$f"; \
+ else \
+ tar -czvf "$$f.tar.gz" "$$f"; \
+ fi \
+ fi \
+ done
+
+help:
+ @echo "LAN Orangutan Build Targets:"
+ @echo ""
+ @echo " build - Build for current platform"
+ @echo " build-all - Build for all platforms"
+ @echo " build-linux - Build for Linux (amd64, arm64, arm)"
+ @echo " build-darwin - Build for macOS (amd64, arm64)"
+ @echo " build-windows - Build for Windows (amd64)"
+ @echo ""
+ @echo " test - Run tests"
+ @echo " lint - Run linter"
+ @echo " fmt - Format code"
+ @echo " tidy - Tidy dependencies"
+ @echo ""
+ @echo " clean - Clean build artifacts"
+ @echo " install - Install to /usr/local/bin"
+ @echo " run - Build and run server"
+ @echo ""
+ @echo " release - Build all platforms and create archives"
+ @echo " checksums - Generate SHA256 checksums"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0d71624
--- /dev/null
+++ b/README.md
@@ -0,0 +1,118 @@
+# 🦧 LAN Orangutan
+
+**Self-hosted network discovery for homelabbers.**
+
+Scan your networks, discover devices, label and track them - all from a clean web UI or CLI.
+
+By [291 Group](https://291group.com)
+
+<p align="center">
+ <img src="docs/LO1.png" width="48%" />
+ <img src="docs/LO2.png" width="48%" />
+</p>
+
+## Features
+
+- 🔍 Auto-discover devices using nmap
+- 🏷️ Label, group, and add notes to devices
+- 🌐 Multi-network support
+- 🔗 Tailscale integration
+- 💻 Modern web dashboard with light/dark mode
+- ⌨️ Full CLI with JSON output
+- 🍎 Cross-platform (Linux, macOS, Windows)
+- 📦 Single binary, no dependencies
+
+## Quick Start
+
+### Download
+
+Grab the latest release for your platform from [GitHub Releases](https://github.com/291-Group/LAN-Orangutan/releases).
+
+### Run
+
+```bash
+# Linux/macOS - Run with sudo for full device info (MAC addresses, vendors)
+sudo ./orangutan serve
+
+# Windows (run as Administrator for full device info)
+orangutan.exe serve
+```
+
+Open `http://localhost:291` in your browser.
+
+## Requirements
+
+- **nmap** must be installed:
+ - macOS: `brew install nmap`
+ - Ubuntu/Debian: `sudo apt install nmap`
+ - Windows: Download from [nmap.org](https://nmap.org/download.html)
+
+## CLI Usage
+
+```bash
+# Scan network (use sudo for MAC addresses and vendor info)
+sudo orangutan scan # Scan default network
+sudo orangutan scan 192.168.1.0/24 # Scan specific network
+sudo orangutan scan all # Scan all detected networks
+
+# Start web server
+sudo orangutan serve # Default port 291
+sudo orangutan serve --port 8080 # Custom port
+
+# List devices
+orangutan list # List all devices
+orangutan list --online # List online devices only
+orangutan list --format json # JSON output
+
+# Export
+orangutan export devices.csv # Export to CSV
+
+# Check status
+orangutan status # Show system status
+orangutan version # Show version info
+```
+
+### Why sudo?
+
+Running with `sudo` (or as Administrator on Windows) allows nmap to:
+- Read the ARP table to get MAC addresses
+- Look up device vendors from MAC addresses
+- Get more accurate hostname resolution
+
+Without elevated privileges, you'll still see device IPs but MAC addresses and vendors will be missing.
+
+## Web Dashboard
+
+The web dashboard provides:
+- Real-time device status (online/offline)
+- Device grouping (Server, Desktop, Laptop, Mobile, IoT, etc.)
+- Labels and notes for each device
+- Search and filter devices
+- Export to CSV/JSON
+- Auto-refresh option
+- Keyboard shortcuts (/ to search, R to refresh, T to toggle theme)
+
+## Configuration
+
+Config file location:
+- Linux: `~/.config/lan-orangutan/config.ini` or `/etc/lan-orangutan/config.ini` (as root)
+- macOS: `~/Library/Application Support/lan-orangutan/config.ini`
+- Windows: `%APPDATA%\lan-orangutan\config.ini`
+
+See `config.example.ini` for available options.
+
+## Building from Source
+
+```bash
+git clone https://github.com/291-Group/LAN-Orangutan.git
+cd LAN-Orangutan
+go build -o orangutan ./cmd/orangutan
+```
+
+## License
+
+MIT License
+
+---
+
+Built with ❤️ by [291 Group](https://291group.com)
diff --git a/cli/orangutan b/cli/orangutan
new file mode 100755
index 0000000..6014e70
--- /dev/null
+++ b/cli/orangutan
@@ -0,0 +1,201 @@
+#!/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/cmd/orangutan/main.go b/cmd/orangutan/main.go
new file mode 100644
index 0000000..1c74140
--- /dev/null
+++ b/cmd/orangutan/main.go
@@ -0,0 +1,10 @@
+// LAN Orangutan - Network Discovery Tool
+package main
+
+import (
+ "github.com/291-Group/LAN-Orangutan/internal/cli"
+)
+
+func main() {
+ cli.Execute()
+}
diff --git a/config.example.ini b/config.example.ini
new file mode 100644
index 0000000..1615917
--- /dev/null
+++ b/config.example.ini
@@ -0,0 +1,53 @@
+# LAN Orangutan Configuration
+# Copy this file to your config directory:
+# Linux: ~/.config/lan-orangutan/config.ini (or /etc/lan-orangutan/config.ini as root)
+# macOS: ~/Library/Application Support/lan-orangutan/config.ini
+# Windows: %APPDATA%\lan-orangutan\config.ini
+
+[server]
+# Port to listen on (default: 291)
+port = 291
+
+# Address to bind to (default: 0.0.0.0 = all interfaces)
+bind_address = 0.0.0.0
+
+# Enable REST API endpoints
+enable_api = true
+
+[scanning]
+# Auto-scan interval in seconds (default: 300 = 5 minutes)
+scan_interval = 300
+
+# Minimum time between manual scans to prevent abuse (default: 30 seconds)
+min_scan_interval = 30
+
+# Enable port scanning (slower, more detailed)
+enable_port_scan = false
+
+# Port range to scan when port scanning is enabled
+port_scan_range = 1-1024
+
+[storage]
+# Maximum number of devices to track
+max_devices = 1000
+
+# Days to keep offline device history
+retention_days = 90
+
+# Data storage directory (default varies by OS)
+# Linux: ~/.local/share/lan-orangutan or /var/lib/lan-orangutan (as root)
+# macOS: ~/Library/Application Support/lan-orangutan
+# Windows: %APPDATA%\lan-orangutan
+# Uncomment to override:
+# data_dir = /var/lib/lan-orangutan
+
+[tailscale]
+# Enable Tailscale integration
+enable = true
+
+# Auto-detect Tailscale peers
+auto_detect = true
+
+[ui]
+# Theme: light, dark, or auto (follows system preference)
+theme = auto
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
new file mode 100644
index 0000000..f79e81a
--- /dev/null
+++ b/docs/INSTALL.md
@@ -0,0 +1,137 @@
+# Installation Guide
+
+## Quick Install (Recommended)
+
+Download the latest release for your platform from [GitHub Releases](https://github.com/291-Group/LAN-Orangutan/releases).
+
+### Linux
+
+```bash
+# Download and extract
+wget https://github.com/291-Group/LAN-Orangutan/releases/latest/download/orangutan-linux-amd64.tar.gz
+tar xzf orangutan-linux-amd64.tar.gz
+
+# Run (use sudo for MAC addresses and vendor info)
+sudo ./orangutan serve
+```
+
+### macOS
+
+```bash
+# Download and extract
+curl -LO https://github.com/291-Group/LAN-Orangutan/releases/latest/download/orangutan-darwin-arm64.tar.gz
+tar xzf orangutan-darwin-arm64.tar.gz
+
+# Run (use sudo for MAC addresses and vendor info)
+sudo ./orangutan serve
+```
+
+### Windows
+
+Download `orangutan-windows-amd64.zip` from [GitHub Releases](https://github.com/291-Group/LAN-Orangutan/releases), extract, and run as Administrator.
+
+## Requirements
+
+- **nmap** must be installed:
+ - Linux: `sudo apt install nmap` or `sudo dnf install nmap`
+ - macOS: `brew install nmap`
+ - Windows: Download from [nmap.org](https://nmap.org/download.html)
+
+## Building from Source
+
+```bash
+git clone https://github.com/291-Group/LAN-Orangutan.git
+cd LAN-Orangutan
+go build -o orangutan ./cmd/orangutan
+```
+
+## Running as a Service
+
+### Linux (systemd)
+
+Create `/etc/systemd/system/lan-orangutan.service`:
+
+```ini
+[Unit]
+Description=LAN Orangutan Network Discovery
+After=network.target
+
+[Service]
+Type=simple
+ExecStart=/usr/local/bin/orangutan serve
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
+```
+
+Then:
+
+```bash
+sudo cp orangutan /usr/local/bin/
+sudo systemctl daemon-reload
+sudo systemctl enable lan-orangutan
+sudo systemctl start lan-orangutan
+```
+
+### macOS (launchd)
+
+Create `~/Library/LaunchAgents/com.291group.lan-orangutan.plist`:
+
+```xml
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.291group.lan-orangutan</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>/usr/local/bin/orangutan</string>
+ <string>serve</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <true/>
+</dict>
+</plist>
+```
+
+Then:
+
+```bash
+cp orangutan /usr/local/bin/
+launchctl load ~/Library/LaunchAgents/com.291group.lan-orangutan.plist
+```
+
+## Configuration
+
+Config file locations:
+- Linux: `~/.config/lan-orangutan/config.ini` or `/etc/lan-orangutan/config.ini` (as root)
+- macOS: `~/Library/Application Support/lan-orangutan/config.ini`
+- Windows: `%APPDATA%\lan-orangutan\config.ini`
+
+See `config.example.ini` for available options.
+
+## Firewall
+
+Allow port 291 (or your configured port):
+
+```bash
+# Linux (ufw)
+sudo ufw allow 291/tcp
+
+# Linux (firewalld)
+sudo firewall-cmd --add-port=291/tcp --permanent
+sudo firewall-cmd --reload
+```
+
+## Verify Installation
+
+```bash
+orangutan version
+orangutan status
+curl http://localhost:291/
+```
diff --git a/docs/LO1.png b/docs/LO1.png
new file mode 100644
index 0000000..f35133f
Binary files /dev/null and b/docs/LO1.png differ
diff --git a/docs/LO2.png b/docs/LO2.png
new file mode 100644
index 0000000..e58966e
Binary files /dev/null and b/docs/LO2.png differ
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
new file mode 100644
index 0000000..b3bb744
--- /dev/null
+++ b/docs/TROUBLESHOOTING.md
@@ -0,0 +1,140 @@
+# Troubleshooting
+
+## No MAC addresses or vendor info
+
+MAC addresses and vendor information require elevated privileges to read the ARP table.
+
+**Solution:** Run with sudo (or as Administrator on Windows):
+
+```bash
+# Linux/macOS
+sudo orangutan scan
+sudo orangutan serve
+
+# Windows - run Command Prompt as Administrator
+orangutan.exe scan
+```
+
+## Service won't start
+
+```bash
+# Check service status
+sudo systemctl status lan-orangutan
+
+# View logs
+sudo journalctl -u lan-orangutan -n 50
+
+# Check if binary exists and is executable
+ls -la /usr/local/bin/orangutan
+```
+
+## Port already in use
+
+```bash
+# Check what's using the port
+sudo ss -tulnp | grep :291
+
+# Use a different port
+orangutan serve --port 8080
+```
+
+Or change the port in your config file.
+
+## No devices found
+
+1. **Check nmap is installed:**
+ ```bash
+ which nmap
+ nmap --version
+ ```
+
+2. **Test nmap directly:**
+ ```bash
+ sudo nmap -sn 192.168.1.0/24
+ ```
+
+3. **Check network detection:**
+ ```bash
+ orangutan status
+ ```
+
+4. **Scan a specific network:**
+ ```bash
+ sudo orangutan scan 192.168.1.0/24
+ ```
+
+## Can't access web UI
+
+1. **Check if server is running:**
+ ```bash
+ orangutan status
+ # or
+ curl http://localhost:291/
+ ```
+
+2. **Check firewall:**
+ ```bash
+ # Linux (ufw)
+ sudo ufw status
+ sudo ufw allow 291/tcp
+
+ # Linux (firewalld)
+ sudo firewall-cmd --list-ports
+ sudo firewall-cmd --add-port=291/tcp --permanent
+ ```
+
+3. **Check if binding to correct address:**
+ ```bash
+ # Allow external access
+ orangutan serve --bind 0.0.0.0
+ ```
+
+## Tailscale not detected
+
+1. **Check Tailscale is installed and running:**
+ ```bash
+ tailscale status
+ ```
+
+2. **On macOS, ensure CLI is available:**
+ ```bash
+ # If using Tailscale app from App Store
+ /Applications/Tailscale.app/Contents/MacOS/Tailscale status
+ ```
+
+## Rate limiting errors
+
+If you see "Rate limited" errors when scanning, wait 30 seconds between scans. This prevents overloading your network.
+
+## Data not persisting
+
+Check that the data directory exists and is writable:
+
+```bash
+# Linux
+ls -la ~/.local/share/lan-orangutan/
+# or as root
+ls -la /var/lib/lan-orangutan/
+
+# macOS
+ls -la ~/Library/Application\ Support/lan-orangutan/
+```
+
+## View debug output
+
+```bash
+# Run with verbose output
+orangutan scan -v
+
+# Check version
+orangutan version
+```
+
+## Still having issues?
+
+1. Check the [GitHub Issues](https://github.com/291-Group/LAN-Orangutan/issues)
+2. Open a new issue with:
+ - Your OS and version
+ - Output of `orangutan version`
+ - Output of `orangutan status`
+ - Steps to reproduce the problem
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..ad8ee31
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,10 @@
+module github.com/291-Group/LAN-Orangutan
+
+go 1.22
+
+require github.com/spf13/cobra v1.10.2
+
+require (
+ github.com/inconshreveable/mousetrap v1.1.0 // indirect
+ github.com/spf13/pflag v1.0.9 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..a6ee3e0
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,10 @@
+github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
+github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
+github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
+github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
+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=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000..1030239
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,143 @@
+#!/bin/bash
+set -e
+
+INSTALL_DIR="/opt/lan-orangutan"
+CONFIG_DIR="/etc/lan-orangutan"
+DATA_DIR="/var/lib/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 "================================"
+echo ""
+
+[[ $EUID -ne 0 ]] && { echo -e "${RED}✗${NC} Run as root (sudo)"; exit 1; }
+
+# Check OS
+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
+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"
+
+# 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
+ case "$choice" in
+ 1) PORT=2910 ;;
+ 2) PORT=8090 ;;
+ 3)
+ read -p "Port: " PORT
+ # Validate custom port is a number between 1-65535
+ if [[ ! "$PORT" =~ ^[0-9]+$ ]] || [[ "$PORT" -lt 1 ]] || [[ "$PORT" -gt 65535 ]]; then
+ echo -e "${YELLOW}!${NC} Invalid port '$PORT', using 2910"
+ PORT=2910
+ fi
+ ;;
+ *) PORT=2910 ;;
+ esac
+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
+
+echo -e "${GREEN}✓${NC} Files installed"
+
+# Create config
+cat > "$CONFIG_DIR/config.ini" << EOF
+[server]
+port = $PORT
+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
+EOF
+echo -e "${GREEN}✓${NC} Config created"
+
+# Firewall
+if command -v ufw &>/dev/null && ufw status | grep -q "active"; then
+ read -p "Configure ufw for port $PORT? [y/N]: " fw
+ [[ "$fw" =~ ^[Yy]$ ]] && { ufw allow "$PORT/tcp"; echo -e "${GREEN}✓${NC} Firewall configured"; }
+fi
+
+# Install service
+cp "$SOURCE_DIR/systemd/lan-orangutan.service" /etc/systemd/system/
+systemctl daemon-reload
+systemctl enable "$SERVICE_NAME"
+systemctl start "$SERVICE_NAME"
+sleep 2
+
+if systemctl is-active --quiet "$SERVICE_NAME"; then
+ echo -e "${GREEN}✓${NC} Service started"
+else
+ echo -e "${RED}✗${NC} Service failed. Check: journalctl -u $SERVICE_NAME"
+ exit 1
+fi
+
+IP=$(ip route get 1.1.1.1 2>/dev/null | grep -oP 'src \K\S+' || hostname -I | awk '{print $1}')
+
+echo ""
+echo "========================================"
+echo -e "${GREEN}🦧 LAN Orangutan installed!${NC}"
+echo "========================================"
+echo ""
+echo -e "Web UI: ${BLUE}http://$IP:$PORT${NC}"
+echo ""
+echo "CLI: orangutan scan all"
+echo " orangutan list"
+echo " orangutan help"
+echo ""
diff --git a/internal/api/api.go b/internal/api/api.go
new file mode 100644
index 0000000..ebf4d5e
--- /dev/null
+++ b/internal/api/api.go
@@ -0,0 +1,297 @@
+// Package api implements the REST API endpoints
+package api
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "time"
+
+ "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"
+)
+
+// Handler handles API requests
+type Handler struct {
+ store *storage.Storage
+ cfg *config.Config
+ scanner *scanner.Scanner
+}
+
+// NewHandler creates a new API handler
+func NewHandler(store *storage.Storage, cfg *config.Config) *Handler {
+ return &Handler{
+ store: store,
+ cfg: cfg,
+ scanner: scanner.New(cfg.Scanning.MinScanInterval),
+ }
+}
+
+// ServeHTTP implements http.Handler
+func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Set JSON content type for all API responses
+ w.Header().Set("Content-Type", "application/json")
+
+ // CSRF protection for mutating requests
+ if r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodDelete {
+ contentType := r.Header.Get("Content-Type")
+ xRequestedWith := r.Header.Get("X-Requested-With")
+
+ if !strings.Contains(contentType, "application/json") && xRequestedWith != "XMLHttpRequest" {
+ h.error(w, http.StatusForbidden, "CSRF protection: requires Content-Type: application/json or X-Requested-With header")
+ return
+ }
+ }
+
+ // Route to handler
+ path := strings.TrimPrefix(r.URL.Path, "/api/")
+ path = strings.TrimSuffix(path, "/")
+
+ switch {
+ case path == "devices":
+ h.handleDevices(w, r)
+ case path == "device":
+ h.handleDevice(w, r)
+ case path == "networks":
+ h.handleNetworks(w, r)
+ case path == "scan":
+ h.handleScan(w, r)
+ case path == "tailscale":
+ h.handleTailscale(w, r)
+ case path == "stats":
+ h.handleStats(w, r)
+ case path == "status":
+ h.handleStatus(w, r)
+ case path == "settings":
+ h.handleSettings(w, r)
+ default:
+ h.error(w, http.StatusNotFound, "endpoint not found")
+ }
+}
+
+// handleDevices handles GET /api/devices
+func (h *Handler) handleDevices(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ devices := h.store.GetDevices()
+ h.success(w, devices)
+}
+
+// handleDevice handles GET/POST/DELETE /api/device
+func (h *Handler) handleDevice(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ ip := r.URL.Query().Get("ip")
+ if ip == "" {
+ h.error(w, http.StatusBadRequest, "ip parameter required")
+ return
+ }
+ device := h.store.GetDevice(ip)
+ if device == nil {
+ h.error(w, http.StatusNotFound, "device not found")
+ return
+ }
+ h.success(w, device)
+
+ case http.MethodPost:
+ var req struct {
+ IP string `json:"ip"`
+ Label *string `json:"label"`
+ Notes *string `json:"notes"`
+ Group *string `json:"group"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ h.error(w, http.StatusBadRequest, "invalid JSON")
+ return
+ }
+
+ // Get IP from query if not in body
+ ip := req.IP
+ if ip == "" {
+ ip = r.URL.Query().Get("ip")
+ }
+ if ip == "" {
+ h.error(w, http.StatusBadRequest, "ip required")
+ return
+ }
+
+ if err := h.store.UpdateDeviceFields(ip, req.Label, req.Notes, req.Group); err != nil {
+ h.error(w, http.StatusNotFound, err.Error())
+ return
+ }
+ h.success(w, map[string]string{"message": "device updated"})
+
+ case http.MethodDelete:
+ ip := r.URL.Query().Get("ip")
+ if ip == "" {
+ h.error(w, http.StatusBadRequest, "ip parameter required")
+ return
+ }
+ if err := h.store.DeleteDevice(ip); err != nil {
+ h.error(w, http.StatusNotFound, err.Error())
+ return
+ }
+ h.success(w, map[string]string{"message": "device deleted"})
+
+ default:
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// handleNetworks handles GET /api/networks
+func (h *Handler) handleNetworks(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ networks, err := network.DetectNetworks()
+ if err != nil {
+ h.error(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+ h.success(w, networks)
+}
+
+// handleScan handles GET /api/scan
+func (h *Handler) handleScan(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ cidr := r.URL.Query().Get("network")
+ if cidr == "" {
+ h.error(w, http.StatusBadRequest, "network parameter required")
+ return
+ }
+
+ // Validate CIDR
+ if !network.ValidateCIDR(cidr) {
+ h.error(w, http.StatusBadRequest, "invalid CIDR format")
+ return
+ }
+
+ // Check rate limit
+ lastScan := h.store.GetLastScan(cidr)
+ canScan, waitTime := h.scanner.CheckRateLimit(lastScan)
+ if !canScan {
+ h.error(w, http.StatusTooManyRequests,
+ "rate limited, wait "+waitTime.Round(time.Second).String())
+ return
+ }
+
+ // Perform scan
+ ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
+ defer cancel()
+
+ result, err := h.scanner.Scan(ctx, cidr)
+ if err != nil {
+ h.error(w, http.StatusInternalServerError, err.Error())
+ return
+ }
+
+ if !result.Success {
+ h.error(w, http.StatusInternalServerError, result.Error)
+ return
+ }
+
+ // Merge devices into storage
+ if err := h.store.MergeDevices(result.Devices); err != nil {
+ h.error(w, http.StatusInternalServerError, "failed to save devices")
+ return
+ }
+
+ // Update last scan time
+ h.store.SetLastScan(cidr, time.Now())
+
+ h.success(w, result)
+}
+
+// handleTailscale handles GET /api/tailscale
+func (h *Handler) handleTailscale(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ status := network.GetTailscaleStatus()
+ h.success(w, status)
+}
+
+// handleStats handles GET /api/stats
+func (h *Handler) handleStats(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ stats := h.store.GetStats()
+ h.success(w, stats)
+}
+
+// handleStatus handles GET /api/status
+func (h *Handler) handleStatus(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ return
+ }
+
+ status := map[string]interface{}{
+ "server": "running",
+ "timestamp": time.Now().Format(time.RFC3339),
+ "config": map[string]interface{}{
+ "port": h.cfg.Server.Port,
+ "bind": h.cfg.Server.BindAddress,
+ "api_enabled": h.cfg.Server.EnableAPI,
+ },
+ }
+ h.success(w, status)
+}
+
+// handleSettings handles GET/POST /api/settings
+func (h *Handler) handleSettings(w http.ResponseWriter, r *http.Request) {
+ switch r.Method {
+ case http.MethodGet:
+ settings := map[string]interface{}{
+ "theme": h.cfg.UI.Theme,
+ "scan_interval": h.cfg.Scanning.ScanInterval,
+ "retention_days": h.cfg.Storage.RetentionDays,
+ }
+ h.success(w, settings)
+
+ case http.MethodPost:
+ // Settings update would require config file write
+ // For now, return not implemented
+ h.error(w, http.StatusNotImplemented, "settings update not yet implemented")
+
+ default:
+ h.error(w, http.StatusMethodNotAllowed, "method not allowed")
+ }
+}
+
+// success sends a successful JSON response
+func (h *Handler) success(w http.ResponseWriter, data interface{}) {
+ resp := types.APIResponse{
+ Success: true,
+ Data: data,
+ }
+ json.NewEncoder(w).Encode(resp)
+}
+
+// error sends an error JSON response
+func (h *Handler) error(w http.ResponseWriter, status int, message string) {
+ w.WriteHeader(status)
+ resp := types.APIResponse{
+ Success: false,
+ Error: message,
+ }
+ json.NewEncoder(w).Encode(resp)
+}
diff --git a/internal/cli/config.go b/internal/cli/config.go
new file mode 100644
index 0000000..9d37363
--- /dev/null
+++ b/internal/cli/config.go
@@ -0,0 +1,48 @@
+package cli
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+)
+
+var configCmd = &cobra.Command{
+ Use: "config",
+ Short: "Display current configuration",
+ RunE: runConfig,
+}
+
+func runConfig(cmd *cobra.Command, args []string) error {
+ fmt.Println("=== LAN Orangutan Configuration ===")
+ fmt.Printf("Config file: %s\n", cfgFile)
+ fmt.Println()
+
+ fmt.Println("[server]")
+ 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)
+ fmt.Println()
+
+ fmt.Println("[scanning]")
+ fmt.Printf(" scan_interval = %d\n", cfg.Scanning.ScanInterval)
+ fmt.Printf(" min_scan_interval = %d\n", cfg.Scanning.MinScanInterval)
+ fmt.Printf(" enable_port_scan = %v\n", cfg.Scanning.EnablePortScan)
+ fmt.Printf(" port_scan_range = %s\n", cfg.Scanning.PortScanRange)
+ fmt.Println()
+
+ fmt.Println("[storage]")
+ fmt.Printf(" max_devices = %d\n", cfg.Storage.MaxDevices)
+ fmt.Printf(" retention_days = %d\n", cfg.Storage.RetentionDays)
+ fmt.Printf(" data_dir = %s\n", cfg.Storage.DataDir)
+ fmt.Println()
+
+ fmt.Println("[tailscale]")
+ fmt.Printf(" enable = %v\n", cfg.Tailscale.Enable)
+ fmt.Printf(" auto_detect = %v\n", cfg.Tailscale.AutoDetect)
+ fmt.Println()
+
+ fmt.Println("[ui]")
+ fmt.Printf(" theme = %s\n", cfg.UI.Theme)
+
+ return nil
+}
diff --git a/internal/cli/export.go b/internal/cli/export.go
new file mode 100644
index 0000000..0c0e857
--- /dev/null
+++ b/internal/cli/export.go
@@ -0,0 +1,107 @@
+package cli
+
+import (
+ "encoding/csv"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+var exportCmd = &cobra.Command{
+ Use: "export <file>",
+ Short: "Export devices to CSV file",
+ Args: cobra.ExactArgs(1),
+ RunE: runExport,
+}
+
+func runExport(cmd *cobra.Command, args []string) error {
+ outputPath := args[0]
+
+ // Validate path (prevent path traversal)
+ absPath, err := filepath.Abs(outputPath)
+ if err != nil {
+ return fmt.Errorf("invalid path: %w", err)
+ }
+
+ // Ensure parent directory exists
+ dir := filepath.Dir(absPath)
+ if _, err := os.Stat(dir); os.IsNotExist(err) {
+ return fmt.Errorf("directory does not exist: %s", dir)
+ }
+
+ // Initialize storage
+ store, err := storage.New(cfg.DevicesFile(), cfg.StateFile())
+ if err != nil {
+ return fmt.Errorf("failed to initialize storage: %w", err)
+ }
+
+ devices := store.GetDevices()
+
+ // Convert to slice and sort by IP
+ var deviceList []*types.Device
+ for _, d := range devices {
+ deviceList = append(deviceList, d)
+ }
+ sort.Slice(deviceList, func(i, j int) bool {
+ return ipToSortKey(deviceList[i].IP) < ipToSortKey(deviceList[j].IP)
+ })
+
+ // Create output file
+ file, err := os.Create(absPath)
+ if err != nil {
+ return fmt.Errorf("failed to create file: %w", err)
+ }
+ defer file.Close()
+
+ // Write CSV
+ w := csv.NewWriter(file)
+ defer w.Flush()
+
+ // Header
+ if err := w.Write([]string{
+ "IP Address",
+ "MAC Address",
+ "Hostname",
+ "Vendor",
+ "Label",
+ "Notes",
+ "Group",
+ "First Seen",
+ "Last Seen",
+ "Status",
+ }); err != nil {
+ return fmt.Errorf("failed to write header: %w", err)
+ }
+
+ // Data rows
+ for _, d := range deviceList {
+ status := "offline"
+ if d.IsOnline() {
+ status = "online"
+ }
+
+ if err := w.Write([]string{
+ d.IP,
+ d.MAC,
+ d.Hostname,
+ d.Vendor,
+ 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,
+ }); err != nil {
+ return fmt.Errorf("failed to write row: %w", err)
+ }
+ }
+
+ fmt.Printf("Exported %d devices to %s\n", len(deviceList), absPath)
+ return nil
+}
diff --git a/internal/cli/list.go b/internal/cli/list.go
new file mode 100644
index 0000000..6a61e80
--- /dev/null
+++ b/internal/cli/list.go
@@ -0,0 +1,169 @@
+package cli
+
+import (
+ "encoding/csv"
+ "fmt"
+ "net"
+ "os"
+ "sort"
+ "strings"
+ "text/tabwriter"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+var (
+ listOnline bool
+ listOffline bool
+ listGroup string
+ listFormat string
+)
+
+var listCmd = &cobra.Command{
+ Use: "list",
+ Short: "List discovered devices",
+ Long: `List all discovered devices with optional filtering by status or group.`,
+ RunE: runList,
+}
+
+func init() {
+ listCmd.Flags().BoolVar(&listOnline, "online", false, "Show only online devices")
+ listCmd.Flags().BoolVar(&listOffline, "offline", false, "Show only offline devices")
+ listCmd.Flags().StringVar(&listGroup, "group", "", "Filter by group")
+ listCmd.Flags().StringVar(&listFormat, "format", "table", "Output format (table, csv, json)")
+}
+
+func runList(cmd *cobra.Command, args []string) error {
+ // Initialize storage
+ store, err := storage.New(cfg.DevicesFile(), cfg.StateFile())
+ if err != nil {
+ return fmt.Errorf("failed to initialize storage: %w", err)
+ }
+
+ devices := store.GetDevices()
+
+ // Convert to slice and filter
+ var filtered []*types.Device
+ for _, d := range devices {
+ // Apply filters
+ if listOnline && !d.IsOnline() {
+ continue
+ }
+ if listOffline && d.IsOnline() {
+ continue
+ }
+ if listGroup != "" && !strings.EqualFold(d.Group, listGroup) {
+ continue
+ }
+ filtered = append(filtered, d)
+ }
+
+ // Sort by IP
+ sort.Slice(filtered, func(i, j int) bool {
+ return ipToSortKey(filtered[i].IP) < ipToSortKey(filtered[j].IP)
+ })
+
+ // Output based on format
+ switch listFormat {
+ case "csv":
+ return outputCSV(filtered)
+ case "json":
+ return outputJSON(filtered)
+ default:
+ return outputTable(filtered)
+ }
+}
+
+func outputTable(devices []*types.Device) error {
+ if len(devices) == 0 {
+ fmt.Println("No devices found")
+ return nil
+ }
+
+ w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
+ fmt.Fprintln(w, "IP\tMAC\tHOSTNAME\tVENDOR\tLABEL\tGROUP\tSTATUS")
+ fmt.Fprintln(w, "--\t---\t--------\t------\t-----\t-----\t------")
+
+ for _, d := range devices {
+ status := "offline"
+ if d.IsRecent() {
+ status = "online"
+ } else if d.IsOnline() {
+ status = "seen"
+ }
+
+ hostname := d.Hostname
+ if len(hostname) > 25 {
+ hostname = hostname[:22] + "..."
+ }
+
+ vendor := d.Vendor
+ if len(vendor) > 20 {
+ vendor = vendor[:17] + "..."
+ }
+
+ fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
+ d.IP, d.MAC, hostname, vendor, d.Label, d.Group, status)
+ }
+
+ return w.Flush()
+}
+
+func outputCSV(devices []*types.Device) error {
+ w := csv.NewWriter(os.Stdout)
+ defer w.Flush()
+
+ // Header
+ if err := w.Write([]string{"IP", "MAC", "Hostname", "Vendor", "Label", "Notes", "Group", "First Seen", "Last Seen"}); err != nil {
+ return err
+ }
+
+ for _, d := range devices {
+ if err := w.Write([]string{
+ d.IP,
+ d.MAC,
+ d.Hostname,
+ d.Vendor,
+ d.Label,
+ d.Notes,
+ d.Group,
+ d.FirstSeen.Format("2006-01-02 15:04:05"),
+ d.LastSeen.Format("2006-01-02 15:04:05"),
+ }); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
+
+func outputJSON(devices []*types.Device) error {
+ // Simple JSON output
+ fmt.Println("[")
+ for i, d := range devices {
+ comma := ","
+ if i == len(devices)-1 {
+ 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)
+ }
+ fmt.Println("]")
+ return nil
+}
+
+// ipToSortKey converts an IP to a sortable integer
+func ipToSortKey(ipStr string) int64 {
+ ip := net.ParseIP(ipStr)
+ if ip == nil {
+ return 0x7FFFFFFFFFFFFFFF // Sort invalid IPs last
+ }
+ ip = ip.To4()
+ if ip == nil {
+ return 0x7FFFFFFFFFFFFFFF
+ }
+ return int64(ip[0])<<24 | int64(ip[1])<<16 | int64(ip[2])<<8 | int64(ip[3])
+}
diff --git a/internal/cli/networks.go b/internal/cli/networks.go
new file mode 100644
index 0000000..75715cc
--- /dev/null
+++ b/internal/cli/networks.go
@@ -0,0 +1,57 @@
+package cli
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/network"
+)
+
+var networksCmd = &cobra.Command{
+ Use: "networks",
+ Short: "List detected network interfaces",
+ RunE: runNetworks,
+}
+
+func runNetworks(cmd *cobra.Command, args []string) error {
+ networks, err := network.DetectNetworks()
+ if err != nil {
+ return fmt.Errorf("failed to detect networks: %w", err)
+ }
+
+ if len(networks) == 0 {
+ fmt.Println("No networks detected")
+ return nil
+ }
+
+ fmt.Println("Detected Networks:")
+ fmt.Println()
+
+ for _, n := range networks {
+ fmt.Printf(" %s\n", n.CIDR)
+ fmt.Printf(" Interface: %s\n", n.Interface)
+ fmt.Printf(" Type: %s\n", n.FriendlyName)
+ fmt.Printf(" IP: %s\n", n.IP)
+ if n.IsTailscale {
+ fmt.Printf(" Tailscale: yes\n")
+ }
+ if n.IsWireless {
+ fmt.Printf(" Wireless: yes\n")
+ }
+ fmt.Println()
+ }
+
+ // Show gateway and DNS
+ gateway, err := network.GetDefaultGateway()
+ if err == nil && gateway != "" {
+ fmt.Printf("Default Gateway: %s\n", gateway)
+ }
+
+ dns := network.GetDNSServers()
+ if len(dns) > 0 {
+ fmt.Printf("DNS Servers: %v\n", dns)
+ }
+
+ return nil
+}
diff --git a/internal/cli/root.go b/internal/cli/root.go
new file mode 100644
index 0000000..039ec62
--- /dev/null
+++ b/internal/cli/root.go
@@ -0,0 +1,58 @@
+// Package cli implements the command-line interface
+package cli
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/config"
+)
+
+var (
+ cfgFile string
+ cfg *config.Config
+)
+
+// rootCmd represents the base command
+var rootCmd = &cobra.Command{
+ Use: "orangutan",
+ Short: "LAN Orangutan - Network Discovery Tool",
+ 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 adds all child commands and runs the CLI
+func Execute() {
+ if err := rootCmd.Execute(); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func init() {
+ cobra.OnInitialize(initConfig)
+
+ rootCmd.PersistentFlags().StringVar(&cfgFile, "config", config.GetDefaultConfigFile(), "config file path")
+
+ // Add subcommands
+ rootCmd.AddCommand(scanCmd)
+ rootCmd.AddCommand(listCmd)
+ rootCmd.AddCommand(statusCmd)
+ rootCmd.AddCommand(networksCmd)
+ rootCmd.AddCommand(exportCmd)
+ rootCmd.AddCommand(configCmd)
+ rootCmd.AddCommand(serveCmd)
+ rootCmd.AddCommand(versionCmd)
+}
+
+func initConfig() {
+ var err error
+ cfg, err = config.Load(cfgFile)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error loading config: %v\n", err)
+ os.Exit(1)
+ }
+}
diff --git a/internal/cli/scan.go b/internal/cli/scan.go
new file mode 100644
index 0000000..83b365c
--- /dev/null
+++ b/internal/cli/scan.go
@@ -0,0 +1,170 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "runtime"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/network"
+ "github.com/291-Group/LAN-Orangutan/internal/scanner"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+)
+
+var scanCmd = &cobra.Command{
+ Use: "scan [network|all]",
+ Short: "Scan network for devices",
+ Long: `Scan a network for devices using nmap or arp-scan.
+Specify a network CIDR (e.g., 192.168.1.0/24) or 'all' to scan all detected networks.
+If no argument is provided, scans the first detected network.`,
+ Args: cobra.MaximumNArgs(1),
+ RunE: runScan,
+}
+
+func runScan(cmd *cobra.Command, args []string) error {
+ // Initialize storage
+ store, err := storage.New(cfg.DevicesFile(), cfg.StateFile())
+ if err != nil {
+ return fmt.Errorf("failed to initialize storage: %w", err)
+ }
+
+ // Create scanner
+ s := scanner.New(cfg.Scanning.MinScanInterval)
+
+ // Determine networks to scan
+ var networks []string
+
+ if len(args) == 0 || args[0] == "" {
+ // Scan first detected network
+ detected, err := network.DetectNetworks()
+ if err != nil {
+ return fmt.Errorf("failed to detect networks: %w", err)
+ }
+ if len(detected) == 0 {
+ return fmt.Errorf("no networks detected")
+ }
+ // Skip Tailscale by default
+ for _, n := range detected {
+ if !n.IsTailscale {
+ networks = append(networks, n.CIDR)
+ break
+ }
+ }
+ if len(networks) == 0 {
+ networks = append(networks, detected[0].CIDR)
+ }
+ } else if args[0] == "all" {
+ // Scan all detected networks
+ detected, err := network.DetectNetworks()
+ if err != nil {
+ return fmt.Errorf("failed to detect networks: %w", err)
+ }
+ for _, n := range detected {
+ networks = append(networks, n.CIDR)
+ }
+ } else {
+ // Scan specified network
+ if !network.ValidateCIDR(args[0]) {
+ return fmt.Errorf("invalid CIDR: %s", args[0])
+ }
+ networks = append(networks, args[0])
+ }
+
+ if len(networks) == 0 {
+ return fmt.Errorf("no networks to scan")
+ }
+
+ // Scan each network
+ for _, cidr := range networks {
+ // Check rate limit
+ lastScan := store.GetLastScan(cidr)
+ canScan, waitTime := s.CheckRateLimit(lastScan)
+ if !canScan {
+ fmt.Printf("Rate limited for %s, wait %.0f seconds\n", cidr, waitTime.Seconds())
+ continue
+ }
+
+ fmt.Printf("Scanning %s...\n", cidr)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+ result, err := s.Scan(ctx, cidr)
+ cancel()
+
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error scanning %s: %v\n", cidr, err)
+ continue
+ }
+
+ if !result.Success {
+ fmt.Fprintf(os.Stderr, "Scan failed for %s: %s\n", cidr, result.Error)
+ continue
+ }
+
+ // Merge devices
+ if err := store.MergeDevices(result.Devices); err != nil {
+ fmt.Fprintf(os.Stderr, "Error saving devices: %v\n", err)
+ continue
+ }
+
+ // Update last scan time
+ if err := store.SetLastScan(cidr, time.Now()); err != nil {
+ fmt.Fprintf(os.Stderr, "Error updating scan state: %v\n", err)
+ }
+
+ fmt.Printf("Found %d devices using %s (%.2fs)\n\n", result.DeviceCount, result.Scanner, result.Duration)
+
+ // Display found devices
+ if len(result.Devices) > 0 {
+ fmt.Printf("%-16s %-18s %-20s %s\n", "IP", "MAC", "HOSTNAME", "VENDOR")
+ fmt.Printf("%-16s %-18s %-20s %s\n", "──────────────", "─────────────────", "───────────────────", "──────────────────────")
+ hasMac := false
+ for _, d := range result.Devices {
+ hostname := d.Hostname
+ if hostname == "" {
+ hostname = "-"
+ }
+ vendor := d.Vendor
+ if vendor == "" {
+ vendor = "-"
+ }
+ mac := d.MAC
+ if mac == "" {
+ mac = "-"
+ } else {
+ hasMac = true
+ }
+ fmt.Printf("%-16s %-18s %-20s %s\n", d.IP, mac, truncate(hostname, 20), truncate(vendor, 30))
+ }
+ fmt.Println()
+
+ // Warn if no MAC addresses found (permission issue)
+ if !hasMac && os.Getuid() != 0 {
+ switch runtime.GOOS {
+ case "darwin":
+ fmt.Println("Note: Run with sudo to get MAC addresses and vendor info:")
+ fmt.Println(" sudo ./orangutan scan")
+ case "linux":
+ fmt.Println("Note: Run with sudo for MAC addresses and vendor info:")
+ fmt.Println(" sudo orangutan scan")
+ }
+ fmt.Println()
+ }
+ }
+ }
+
+ return nil
+}
+
+// truncate shortens a string to maxLen, adding "..." if truncated
+func truncate(s string, maxLen int) string {
+ if len(s) <= maxLen {
+ return s
+ }
+ if maxLen <= 3 {
+ return s[:maxLen]
+ }
+ return s[:maxLen-3] + "..."
+}
diff --git a/internal/cli/serve.go b/internal/cli/serve.go
new file mode 100644
index 0000000..d9ddcb1
--- /dev/null
+++ b/internal/cli/serve.go
@@ -0,0 +1,103 @@
+package cli
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/api"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+ "github.com/291-Group/LAN-Orangutan/internal/web"
+)
+
+var (
+ servePort int
+ serveBind string
+)
+
+var serveCmd = &cobra.Command{
+ Use: "serve",
+ Short: "Start the web server",
+ Long: `Start the LAN Orangutan web server with REST API and dashboard.`,
+ RunE: runServe,
+}
+
+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)")
+}
+
+func runServe(cmd *cobra.Command, args []string) error {
+ // Use flags or config
+ port := cfg.Server.Port
+ if servePort > 0 {
+ port = servePort
+ }
+ bind := cfg.Server.BindAddress
+ if serveBind != "" {
+ bind = serveBind
+ }
+
+ // Initialize storage
+ store, err := storage.New(cfg.DevicesFile(), cfg.StateFile())
+ if err != nil {
+ return fmt.Errorf("failed to initialize storage: %w", err)
+ }
+
+ // Create HTTP handler
+ mux := http.NewServeMux()
+
+ // Register API routes
+ apiHandler := api.NewHandler(store, cfg)
+ mux.Handle("/api/", apiHandler)
+
+ // Register web routes
+ webHandler := web.NewHandler(store, cfg, Version)
+ mux.Handle("/", webHandler)
+
+ // Create server
+ addr := fmt.Sprintf("%s:%d", bind, port)
+ server := &http.Server{
+ Addr: addr,
+ Handler: mux,
+ ReadTimeout: 30 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ IdleTimeout: 60 * time.Second,
+ }
+
+ // Handle shutdown gracefully
+ done := make(chan bool, 1)
+ quit := make(chan os.Signal, 1)
+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
+
+ go func() {
+ <-quit
+ fmt.Println("\nShutting down server...")
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ server.SetKeepAlivesEnabled(false)
+ if err := server.Shutdown(ctx); err != nil {
+ fmt.Fprintf(os.Stderr, "Error shutting down: %v\n", err)
+ }
+ close(done)
+ }()
+
+ fmt.Printf("Starting LAN Orangutan server on http://%s\n", addr)
+ fmt.Println("Press Ctrl+C to stop")
+
+ if err := server.ListenAndServe(); err != http.ErrServerClosed {
+ return fmt.Errorf("server error: %w", err)
+ }
+
+ <-done
+ fmt.Println("Server stopped")
+ return nil
+}
diff --git a/internal/cli/status.go b/internal/cli/status.go
new file mode 100644
index 0000000..85ac800
--- /dev/null
+++ b/internal/cli/status.go
@@ -0,0 +1,142 @@
+package cli
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "runtime"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/291-Group/LAN-Orangutan/internal/network"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+)
+
+var statusCmd = &cobra.Command{
+ Use: "status",
+ Short: "Show system and service status",
+ RunE: runStatus,
+}
+
+func runStatus(cmd *cobra.Command, args []string) error {
+ fmt.Println("=== LAN Orangutan Status ===")
+ fmt.Println()
+
+ // System info
+ fmt.Println("System:")
+ fmt.Printf(" Go Version: %s\n", runtime.Version())
+ fmt.Printf(" OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
+
+ // Check tools
+ fmt.Println()
+ fmt.Println("Tools:")
+ checkTool("nmap")
+ checkTool("arp-scan")
+ checkTool("tailscale")
+
+ // Storage
+ fmt.Println()
+ fmt.Println("Storage:")
+ store, err := storage.New(cfg.DevicesFile(), cfg.StateFile())
+ if err != nil {
+ fmt.Printf(" Error: %v\n", err)
+ } else {
+ stats := store.GetStats()
+ fmt.Printf(" Devices: %d total (%d online, %d offline)\n", stats.Total, stats.Online, stats.Offline)
+ fmt.Printf(" Data directory: %s\n", cfg.Storage.DataDir)
+ }
+
+ // Networks
+ fmt.Println()
+ fmt.Println("Networks:")
+ networks, err := network.DetectNetworks()
+ if err != nil {
+ fmt.Printf(" Error detecting: %v\n", err)
+ } else {
+ for _, n := range networks {
+ flags := []string{}
+ if n.IsTailscale {
+ flags = append(flags, "tailscale")
+ }
+ if n.IsWireless {
+ flags = append(flags, "wireless")
+ }
+ flagStr := ""
+ if len(flags) > 0 {
+ flagStr = " [" + strings.Join(flags, ", ") + "]"
+ }
+ fmt.Printf(" %s (%s)%s\n", n.CIDR, n.Interface, flagStr)
+ }
+ }
+
+ // Tailscale
+ fmt.Println()
+ fmt.Println("Tailscale:")
+ ts := network.GetTailscaleStatus()
+ if !ts.Installed {
+ fmt.Println(" Not installed")
+ } else if !ts.Running {
+ fmt.Println(" Installed but not running")
+ } else {
+ fmt.Printf(" Status: %s\n", ts.BackendState)
+ fmt.Printf(" IP: %s\n", ts.SelfIP)
+ fmt.Printf(" Hostname: %s\n", ts.SelfHostname)
+ fmt.Printf(" Peers: %d\n", ts.PeerCount)
+ }
+
+ // Server config
+ fmt.Println()
+ fmt.Println("Server:")
+ fmt.Printf(" Port: %d\n", cfg.Server.Port)
+ fmt.Printf(" Bind: %s\n", cfg.Server.BindAddress)
+ fmt.Printf(" API enabled: %v\n", cfg.Server.EnableAPI)
+
+ return nil
+}
+
+func checkTool(name string) {
+ path, err := exec.LookPath(name)
+ if err != nil {
+ fmt.Printf(" %s: not found\n", name)
+ } else {
+ // Get version
+ version := getToolVersion(name)
+ if version != "" {
+ fmt.Printf(" %s: %s (%s)\n", name, version, path)
+ } else {
+ fmt.Printf(" %s: %s\n", name, path)
+ }
+ }
+}
+
+func getToolVersion(name string) string {
+ var cmd *exec.Cmd
+ switch name {
+ case "nmap":
+ cmd = exec.Command("nmap", "--version")
+ case "arp-scan":
+ cmd = exec.Command("arp-scan", "--version")
+ case "tailscale":
+ cmd = exec.Command("tailscale", "--version")
+ default:
+ return ""
+ }
+
+ output, err := cmd.Output()
+ if err != nil {
+ return ""
+ }
+
+ // Extract first line
+ lines := strings.Split(string(output), "\n")
+ if len(lines) > 0 {
+ return strings.TrimSpace(lines[0])
+ }
+ return ""
+}
+
+func fileExists(path string) bool {
+ _, err := os.Stat(path)
+ return err == nil
+}
diff --git a/internal/cli/version.go b/internal/cli/version.go
new file mode 100644
index 0000000..37c0fd2
--- /dev/null
+++ b/internal/cli/version.go
@@ -0,0 +1,27 @@
+package cli
+
+import (
+ "fmt"
+ "runtime"
+
+ "github.com/spf13/cobra"
+)
+
+// Version information (set via ldflags at build time)
+var (
+ Version = "dev"
+ Commit = "unknown"
+ BuildDate = "unknown"
+)
+
+var versionCmd = &cobra.Command{
+ Use: "version",
+ Short: "Print version information",
+ Run: func(cmd *cobra.Command, args []string) {
+ fmt.Printf("LAN Orangutan %s\n", Version)
+ fmt.Printf(" Commit: %s\n", Commit)
+ fmt.Printf(" Built: %s\n", BuildDate)
+ fmt.Printf(" Go: %s\n", runtime.Version())
+ fmt.Printf(" OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
+ },
+}
diff --git a/internal/config/config.go b/internal/config/config.go
new file mode 100644
index 0000000..6225375
--- /dev/null
+++ b/internal/config/config.go
@@ -0,0 +1,272 @@
+// Package config handles configuration loading and management
+package config
+
+import (
+ "bufio"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+)
+
+// GetDefaultDataDir returns the appropriate default data directory for the current OS
+func GetDefaultDataDir() string {
+ switch runtime.GOOS {
+ case "darwin":
+ // macOS: use Application Support
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "/tmp/lan-orangutan"
+ }
+ return filepath.Join(home, "Library", "Application Support", "lan-orangutan")
+
+ case "windows":
+ // Windows: use AppData
+ appData := os.Getenv("APPDATA")
+ if appData == "" {
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "C:\\lan-orangutan"
+ }
+ return filepath.Join(home, "AppData", "Roaming", "lan-orangutan")
+ }
+ return filepath.Join(appData, "lan-orangutan")
+
+ default:
+ // Linux and others
+ // Use /var/lib if running as root, otherwise use user's local share
+ if os.Getuid() == 0 {
+ return "/var/lib/lan-orangutan"
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "/tmp/lan-orangutan"
+ }
+ return filepath.Join(home, ".local", "share", "lan-orangutan")
+ }
+}
+
+// GetDefaultConfigFile returns the appropriate default config file path for the current OS
+func GetDefaultConfigFile() string {
+ switch runtime.GOOS {
+ case "darwin":
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "/tmp/lan-orangutan/config.ini"
+ }
+ return filepath.Join(home, "Library", "Application Support", "lan-orangutan", "config.ini")
+
+ case "windows":
+ appData := os.Getenv("APPDATA")
+ if appData == "" {
+ return "C:\\lan-orangutan\\config.ini"
+ }
+ return filepath.Join(appData, "lan-orangutan", "config.ini")
+
+ default:
+ // Linux: use /etc if running as root, otherwise use user config
+ if os.Getuid() == 0 {
+ return "/etc/lan-orangutan/config.ini"
+ }
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return "/tmp/lan-orangutan/config.ini"
+ }
+ return filepath.Join(home, ".config", "lan-orangutan", "config.ini")
+ }
+}
+
+// Config holds all application configuration
+type Config struct {
+ Server ServerConfig
+ Scanning ScanningConfig
+ Storage StorageConfig
+ Tailscale TailscaleConfig
+ UI UIConfig
+}
+
+// ServerConfig holds web server settings
+type ServerConfig struct {
+ Port int
+ BindAddress string
+ EnableAPI bool
+}
+
+// ScanningConfig holds scanner settings
+type ScanningConfig struct {
+ ScanInterval int
+ MinScanInterval int
+ EnablePortScan bool
+ PortScanRange string
+}
+
+// StorageConfig holds data storage settings
+type StorageConfig struct {
+ MaxDevices int
+ RetentionDays int
+ DataDir string
+}
+
+// TailscaleConfig holds Tailscale integration settings
+type TailscaleConfig struct {
+ Enable bool
+ AutoDetect bool
+}
+
+// UIConfig holds user interface settings
+type UIConfig struct {
+ Theme string
+}
+
+// Default returns a Config with default values
+func Default() *Config {
+ return &Config{
+ Server: ServerConfig{
+ Port: 291,
+ BindAddress: "0.0.0.0",
+ EnableAPI: true,
+ },
+ Scanning: ScanningConfig{
+ ScanInterval: 300,
+ MinScanInterval: 30,
+ EnablePortScan: false,
+ PortScanRange: "1-1024",
+ },
+ Storage: StorageConfig{
+ MaxDevices: 1000,
+ RetentionDays: 90,
+ DataDir: GetDefaultDataDir(),
+ },
+ Tailscale: TailscaleConfig{
+ Enable: true,
+ AutoDetect: true,
+ },
+ UI: UIConfig{
+ Theme: "auto",
+ },
+ }
+}
+
+// Load reads configuration from an INI file
+func Load(path string) (*Config, error) {
+ cfg := Default()
+
+ file, err := os.Open(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return cfg, nil // Return defaults if file doesn't exist
+ }
+ return nil, fmt.Errorf("failed to open config: %w", err)
+ }
+ defer file.Close()
+
+ var currentSection string
+ scanner := bufio.NewScanner(file)
+
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+
+ // Skip empty lines and comments
+ if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
+ continue
+ }
+
+ // Section header
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ currentSection = strings.ToLower(line[1 : len(line)-1])
+ continue
+ }
+
+ // Key-value pair
+ parts := strings.SplitN(line, "=", 2)
+ if len(parts) != 2 {
+ continue
+ }
+
+ key := strings.TrimSpace(strings.ToLower(parts[0]))
+ value := strings.TrimSpace(parts[1])
+
+ cfg.setValue(currentSection, key, value)
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("failed to read config: %w", err)
+ }
+
+ return cfg, nil
+}
+
+// setValue sets a configuration value based on section and key
+func (c *Config) setValue(section, key, value string) {
+ switch section {
+ case "server":
+ switch key {
+ case "port":
+ if v, err := strconv.Atoi(value); err == nil {
+ c.Server.Port = v
+ }
+ case "bind_address":
+ c.Server.BindAddress = value
+ case "enable_api":
+ c.Server.EnableAPI = parseBool(value)
+ }
+ case "scanning":
+ switch key {
+ case "scan_interval":
+ if v, err := strconv.Atoi(value); err == nil {
+ c.Scanning.ScanInterval = v
+ }
+ case "min_scan_interval":
+ if v, err := strconv.Atoi(value); err == nil {
+ c.Scanning.MinScanInterval = v
+ }
+ case "enable_port_scan":
+ c.Scanning.EnablePortScan = parseBool(value)
+ case "port_scan_range":
+ c.Scanning.PortScanRange = value
+ }
+ case "storage":
+ switch key {
+ case "max_devices":
+ if v, err := strconv.Atoi(value); err == nil {
+ c.Storage.MaxDevices = v
+ }
+ case "retention_days":
+ if v, err := strconv.Atoi(value); err == nil {
+ c.Storage.RetentionDays = v
+ }
+ case "data_dir":
+ c.Storage.DataDir = value
+ }
+ case "tailscale":
+ switch key {
+ case "enable":
+ c.Tailscale.Enable = parseBool(value)
+ case "auto_detect":
+ c.Tailscale.AutoDetect = parseBool(value)
+ }
+ case "ui":
+ switch key {
+ case "theme":
+ c.UI.Theme = value
+ }
+ }
+}
+
+// DevicesFile returns the full path to the devices JSON file
+func (c *Config) DevicesFile() string {
+ return filepath.Join(c.Storage.DataDir, "devices.json")
+}
+
+// StateFile returns the full path to the scan state file
+func (c *Config) StateFile() string {
+ return filepath.Join(c.Storage.DataDir, "scan_state.json")
+}
+
+// parseBool parses common boolean representations
+func parseBool(s string) bool {
+ s = strings.ToLower(s)
+ return s == "true" || s == "yes" || s == "1" || s == "on"
+}
diff --git a/internal/network/detect.go b/internal/network/detect.go
new file mode 100644
index 0000000..accac68
--- /dev/null
+++ b/internal/network/detect.go
@@ -0,0 +1,272 @@
+// Package network handles network interface detection and utilities
+package network
+
+import (
+ "encoding/json"
+ "fmt"
+ "net"
+ "os/exec"
+ "runtime"
+ "strings"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// DetectNetworks discovers available network interfaces and their CIDRs
+// Uses Go's standard library for cross-platform compatibility
+func DetectNetworks() ([]types.Network, error) {
+ ifaces, err := net.Interfaces()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get interfaces: %w", err)
+ }
+
+ var networks []types.Network
+ for _, iface := range ifaces {
+ // Skip loopback and down interfaces
+ if iface.Flags&net.FlagLoopback != 0 {
+ continue
+ }
+ if iface.Flags&net.FlagUp == 0 {
+ continue
+ }
+
+ addrs, err := iface.Addrs()
+ if err != nil {
+ continue
+ }
+
+ for _, addr := range addrs {
+ ipNet, ok := addr.(*net.IPNet)
+ if !ok {
+ continue
+ }
+
+ // Skip IPv6
+ if ipNet.IP.To4() == nil {
+ continue
+ }
+
+ // Calculate network CIDR
+ ones, _ := ipNet.Mask.Size()
+ networkIP := ipNet.IP.Mask(ipNet.Mask)
+ cidr := fmt.Sprintf("%s/%d", networkIP.String(), ones)
+
+ network := types.Network{
+ CIDR: cidr,
+ Interface: iface.Name,
+ FriendlyName: getFriendlyName(iface.Name),
+ IP: ipNet.IP.String(),
+ IsTailscale: isTailscaleInterface(iface.Name),
+ IsWireless: isWirelessInterface(iface.Name),
+ }
+ networks = append(networks, network)
+ }
+ }
+
+ return networks, nil
+}
+
+// calculateCIDR calculates the network CIDR from an IP and prefix length
+func calculateCIDR(ip string, prefixLen int) string {
+ parsedIP := net.ParseIP(ip)
+ if parsedIP == nil {
+ return ""
+ }
+
+ ipv4 := parsedIP.To4()
+ if ipv4 == nil {
+ return ""
+ }
+
+ // Create subnet mask
+ mask := net.CIDRMask(prefixLen, 32)
+
+ // Calculate network address
+ network := make(net.IP, 4)
+ for i := 0; i < 4; i++ {
+ network[i] = ipv4[i] & mask[i]
+ }
+
+ return fmt.Sprintf("%s/%d", network.String(), prefixLen)
+}
+
+// getFriendlyName returns a user-friendly name for an interface
+func getFriendlyName(ifname string) string {
+ switch {
+ case strings.HasPrefix(ifname, "tailscale") || ifname == "utun4":
+ return "Tailscale VPN"
+ case strings.HasPrefix(ifname, "wlan") || strings.HasPrefix(ifname, "wlp"):
+ return "Wi-Fi"
+ case strings.HasPrefix(ifname, "eth") || strings.HasPrefix(ifname, "enp") || strings.HasPrefix(ifname, "eno"):
+ return "Ethernet"
+ // macOS interfaces
+ case ifname == "en0":
+ return "Wi-Fi" // Usually Wi-Fi on macOS
+ case strings.HasPrefix(ifname, "en"):
+ return "Ethernet" // Other en* interfaces are usually Ethernet
+ case strings.HasPrefix(ifname, "bridge"):
+ return "Bridge"
+ case strings.HasPrefix(ifname, "br"):
+ return "Bridge"
+ case strings.HasPrefix(ifname, "docker"):
+ return "Docker"
+ case strings.HasPrefix(ifname, "veth"):
+ return "Virtual Ethernet"
+ case strings.HasPrefix(ifname, "virbr"):
+ return "Virtual Bridge"
+ case strings.HasPrefix(ifname, "utun"):
+ return "VPN Tunnel"
+ case strings.HasPrefix(ifname, "awdl"):
+ return "Apple Wireless Direct"
+ case strings.HasPrefix(ifname, "llw"):
+ return "Low Latency WLAN"
+ default:
+ return ifname
+ }
+}
+
+// isTailscaleInterface returns true if the interface is a Tailscale interface
+func isTailscaleInterface(ifname string) bool {
+ return strings.HasPrefix(ifname, "tailscale") || ifname == "utun4"
+}
+
+// isWirelessInterface returns true if the interface is a wireless interface
+func isWirelessInterface(ifname string) bool {
+ // Linux wireless interfaces
+ if strings.HasPrefix(ifname, "wlan") || strings.HasPrefix(ifname, "wlp") {
+ return true
+ }
+ // macOS - en0 is usually Wi-Fi
+ if ifname == "en0" {
+ return true
+ }
+ return false
+}
+
+// GetDefaultGateway returns the default gateway IP
+func GetDefaultGateway() (string, error) {
+ var cmd *exec.Cmd
+
+ switch runtime.GOOS {
+ case "darwin":
+ // macOS: use netstat
+ cmd = exec.Command("netstat", "-rn")
+ case "linux":
+ // Linux: try ip command first
+ cmd = exec.Command("ip", "-j", "route", "show", "default")
+ default:
+ // Fallback for other systems
+ cmd = exec.Command("netstat", "-rn")
+ }
+
+ output, err := cmd.Output()
+ if err != nil {
+ return "", fmt.Errorf("failed to get default route: %w", err)
+ }
+
+ if runtime.GOOS == "linux" {
+ // Parse JSON output from ip command
+ var routes []struct {
+ Gateway string `json:"gateway"`
+ }
+ if err := json.Unmarshal(output, &routes); err == nil && len(routes) > 0 {
+ return routes[0].Gateway, nil
+ }
+ }
+
+ // Parse netstat output (works on macOS and as fallback)
+ lines := strings.Split(string(output), "\n")
+ for _, line := range lines {
+ fields := strings.Fields(line)
+ if len(fields) >= 2 && (fields[0] == "default" || fields[0] == "0.0.0.0") {
+ gateway := fields[1]
+ if net.ParseIP(gateway) != nil {
+ return gateway, nil
+ }
+ }
+ }
+
+ return "", nil
+}
+
+// GetDNSServers returns configured DNS servers
+func GetDNSServers() []string {
+ // Try systemd-resolved first
+ cmd := exec.Command("resolvectl", "status")
+ output, err := cmd.Output()
+ if err == nil {
+ return parseDNSFromResolvectl(string(output))
+ }
+
+ // Fallback to /etc/resolv.conf
+ return parseDNSFromResolvConf()
+}
+
+func parseDNSFromResolvectl(output string) []string {
+ var servers []string
+ lines := strings.Split(output, "\n")
+ for _, line := range lines {
+ if strings.Contains(line, "DNS Servers:") {
+ parts := strings.SplitN(line, ":", 2)
+ if len(parts) == 2 {
+ for _, s := range strings.Fields(parts[1]) {
+ if net.ParseIP(s) != nil {
+ servers = append(servers, s)
+ }
+ }
+ }
+ }
+ }
+ return servers
+}
+
+func parseDNSFromResolvConf() []string {
+ cmd := exec.Command("grep", "nameserver", "/etc/resolv.conf")
+ output, err := cmd.Output()
+ if err != nil {
+ return nil
+ }
+
+ var servers []string
+ lines := strings.Split(string(output), "\n")
+ for _, line := range lines {
+ fields := strings.Fields(line)
+ if len(fields) >= 2 && fields[0] == "nameserver" {
+ if net.ParseIP(fields[1]) != nil {
+ servers = append(servers, fields[1])
+ }
+ }
+ }
+ return servers
+}
+
+// ValidateCIDR checks if a CIDR string is valid
+func ValidateCIDR(cidr string) bool {
+ _, _, err := net.ParseCIDR(cidr)
+ return err == nil
+}
+
+// ParseIPRange parses a port range string (e.g., "1-1024")
+func ParsePortRange(rangeStr string) (start, end int, err error) {
+ parts := strings.Split(rangeStr, "-")
+ if len(parts) != 2 {
+ return 0, 0, fmt.Errorf("invalid port range format")
+ }
+
+ var startPort, endPort int
+ if _, err := fmt.Sscanf(parts[0], "%d", &startPort); err != nil {
+ return 0, 0, fmt.Errorf("invalid start port")
+ }
+ if _, err := fmt.Sscanf(parts[1], "%d", &endPort); err != nil {
+ return 0, 0, fmt.Errorf("invalid end port")
+ }
+
+ if startPort < 1 || startPort > 65535 || endPort < 1 || endPort > 65535 {
+ return 0, 0, fmt.Errorf("port out of range")
+ }
+ if startPort > endPort {
+ return 0, 0, fmt.Errorf("start port greater than end port")
+ }
+
+ return startPort, endPort, nil
+}
diff --git a/internal/network/tailscale.go b/internal/network/tailscale.go
new file mode 100644
index 0000000..1e87ff3
--- /dev/null
+++ b/internal/network/tailscale.go
@@ -0,0 +1,124 @@
+package network
+
+import (
+ "encoding/json"
+ "os/exec"
+ "runtime"
+ "strings"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// tailscaleStatusJSON represents the JSON output from `tailscale status --json`
+type tailscaleStatusJSON struct {
+ Version string `json:"Version"`
+ BackendState string `json:"BackendState"`
+ CurrentTailnet struct {
+ Name string `json:"Name"`
+ } `json:"CurrentTailnet"`
+ Self struct {
+ DNSName string `json:"DNSName"`
+ TailscaleIPs []string `json:"TailscaleIPs"`
+ } `json:"Self"`
+ Peer map[string]struct {
+ HostName string `json:"HostName"`
+ } `json:"Peer"`
+ ExitNodeStatus struct {
+ ID string `json:"ID"`
+ } `json:"ExitNodeStatus"`
+}
+
+// findTailscaleBinary finds the tailscale CLI binary path
+func findTailscaleBinary() string {
+ // First check if it's in PATH
+ if path, err := exec.LookPath("tailscale"); err == nil {
+ return path
+ }
+
+ // Check platform-specific locations
+ switch runtime.GOOS {
+ case "darwin":
+ // macOS: Tailscale app installs CLI here
+ paths := []string{
+ "/Applications/Tailscale.app/Contents/MacOS/Tailscale",
+ "/usr/local/bin/tailscale",
+ }
+ for _, p := range paths {
+ if _, err := exec.LookPath(p); err == nil {
+ return p
+ }
+ }
+ case "windows":
+ paths := []string{
+ `C:\Program Files\Tailscale\tailscale.exe`,
+ `C:\Program Files (x86)\Tailscale\tailscale.exe`,
+ }
+ for _, p := range paths {
+ if _, err := exec.LookPath(p); err == nil {
+ return p
+ }
+ }
+ }
+
+ return ""
+}
+
+// GetTailscaleStatus returns the current Tailscale status
+func GetTailscaleStatus() types.TailscaleStatus {
+ status := types.TailscaleStatus{}
+
+ // Check if tailscale is installed
+ tailscaleBin := findTailscaleBinary()
+ if tailscaleBin == "" {
+ status.Installed = false
+ return status
+ }
+ status.Installed = true
+
+ // Get tailscale status
+ cmd := exec.Command(tailscaleBin, "status", "--json")
+ output, err := cmd.Output()
+ if err != nil {
+ // Tailscale is installed but not running or not connected
+ status.Running = false
+ return status
+ }
+
+ var tsStatus tailscaleStatusJSON
+ if err := json.Unmarshal(output, &tsStatus); err != nil {
+ status.Running = false
+ return status
+ }
+
+ status.Running = true
+ status.Version = tsStatus.Version
+ status.BackendState = tsStatus.BackendState
+ status.TailnetName = tsStatus.CurrentTailnet.Name
+ status.PeerCount = len(tsStatus.Peer)
+
+ // Get self info
+ if len(tsStatus.Self.TailscaleIPs) > 0 {
+ status.SelfIP = tsStatus.Self.TailscaleIPs[0]
+ }
+ if tsStatus.Self.DNSName != "" {
+ // Remove trailing dot and tailnet suffix
+ hostname := strings.TrimSuffix(tsStatus.Self.DNSName, ".")
+ parts := strings.Split(hostname, ".")
+ if len(parts) > 0 {
+ status.SelfHostname = parts[0]
+ }
+ }
+
+ // Check for exit node
+ if tsStatus.ExitNodeStatus.ID != "" {
+ status.ExitNode = tsStatus.ExitNodeStatus.ID
+ }
+
+ return status
+}
+
+// IsTailscaleConnected returns true if Tailscale is connected
+func IsTailscaleConnected() bool {
+ status := GetTailscaleStatus()
+ return status.Installed && status.Running && status.BackendState == "Running"
+}
diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go
new file mode 100644
index 0000000..d5b374b
--- /dev/null
+++ b/internal/scanner/scanner.go
@@ -0,0 +1,360 @@
+// Package scanner handles network device discovery using nmap and arp-scan
+package scanner
+
+import (
+ "context"
+ "encoding/xml"
+ "fmt"
+ "net"
+ "os/exec"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// Scanner performs network scans
+type Scanner struct {
+ minInterval time.Duration
+}
+
+// New creates a new Scanner
+func New(minIntervalSeconds int) *Scanner {
+ return &Scanner{
+ minInterval: time.Duration(minIntervalSeconds) * time.Second,
+ }
+}
+
+// nmapRun represents the root element of nmap XML output
+type nmapRun struct {
+ XMLName xml.Name `xml:"nmaprun"`
+ Hosts []nmapHost `xml:"host"`
+}
+
+// nmapHost represents a host element in nmap XML output
+type nmapHost struct {
+ Status nmapStatus `xml:"status"`
+ Addresses []nmapAddress `xml:"address"`
+ Hostnames nmapHostnames `xml:"hostnames"`
+ Times nmapTimes `xml:"times"`
+}
+
+// nmapStatus represents the host status
+type nmapStatus struct {
+ State string `xml:"state,attr"`
+}
+
+// nmapAddress represents an address element
+type nmapAddress struct {
+ Addr string `xml:"addr,attr"`
+ AddrType string `xml:"addrtype,attr"`
+ Vendor string `xml:"vendor,attr"`
+}
+
+// nmapHostnames contains hostname information
+type nmapHostnames struct {
+ Hostnames []nmapHostname `xml:"hostname"`
+}
+
+// nmapHostname represents a single hostname
+type nmapHostname struct {
+ Name string `xml:"name,attr"`
+ Type string `xml:"type,attr"`
+}
+
+// nmapTimes contains timing information
+type nmapTimes struct {
+ SRTT string `xml:"srtt,attr"`
+}
+
+// Scan performs a network scan on the given CIDR
+func (s *Scanner) Scan(ctx context.Context, cidr string) (*types.ScanResult, error) {
+ // Validate CIDR
+ _, _, err := net.ParseCIDR(cidr)
+ if err != nil {
+ return nil, fmt.Errorf("invalid CIDR: %w", err)
+ }
+
+ startTime := time.Now()
+
+ // Try nmap first
+ devices, scanner, err := s.scanWithNmap(ctx, cidr)
+ if err != nil {
+ // Fallback to arp-scan
+ devices, scanner, err = s.scanWithArpScan(ctx, cidr)
+ if err != nil {
+ return &types.ScanResult{
+ Success: false,
+ Error: err.Error(),
+ Network: cidr,
+ Timestamp: time.Now(),
+ }, nil
+ }
+ }
+
+ duration := time.Since(startTime).Seconds()
+
+ return &types.ScanResult{
+ Success: true,
+ Devices: devices,
+ DeviceCount: len(devices),
+ Network: cidr,
+ Scanner: scanner,
+ Duration: duration,
+ Timestamp: time.Now(),
+ }, nil
+}
+
+// scanWithNmap performs a scan using nmap
+func (s *Scanner) scanWithNmap(ctx context.Context, cidr string) ([]types.Device, string, error) {
+ // Check if nmap is available
+ if _, err := exec.LookPath("nmap"); err != nil {
+ return nil, "", fmt.Errorf("nmap not found")
+ }
+
+ // Run nmap with ping scan and XML output
+ cmd := exec.CommandContext(ctx, "nmap", "-sn", "-oX", "-", cidr)
+ output, err := cmd.Output()
+ if err != nil {
+ return nil, "", fmt.Errorf("nmap failed: %w", err)
+ }
+
+ // Parse XML output
+ var result nmapRun
+ if err := xml.Unmarshal(output, &result); err != nil {
+ return nil, "", fmt.Errorf("failed to parse nmap output: %w", err)
+ }
+
+ var devices []types.Device
+ for _, host := range result.Hosts {
+ if host.Status.State != "up" {
+ continue
+ }
+
+ device := types.Device{}
+
+ // Extract addresses
+ for _, addr := range host.Addresses {
+ switch addr.AddrType {
+ case "ipv4":
+ device.IP = addr.Addr
+ case "mac":
+ device.MAC = addr.Addr
+ if addr.Vendor != "" {
+ device.Vendor = addr.Vendor
+ }
+ }
+ }
+
+ if device.IP == "" {
+ continue
+ }
+
+ // Get vendor from MAC if not set
+ if device.Vendor == "" && device.MAC != "" {
+ device.Vendor = GetMACVendor(device.MAC)
+ }
+
+ // Extract hostname
+ for _, hostname := range host.Hostnames.Hostnames {
+ if hostname.Name != "" {
+ device.Hostname = hostname.Name
+ break
+ }
+ }
+
+ // Try reverse DNS if no hostname
+ if device.Hostname == "" {
+ device.Hostname = reverseDNS(device.IP)
+ }
+
+ // Parse response time
+ if host.Times.SRTT != "" {
+ if srtt, err := parseResponseTime(host.Times.SRTT); err == nil {
+ device.ResponseTime = &srtt
+ }
+ }
+
+ devices = append(devices, device)
+ }
+
+ return devices, "nmap", nil
+}
+
+// scanWithArpScan performs a scan using arp-scan
+func (s *Scanner) scanWithArpScan(ctx context.Context, cidr string) ([]types.Device, string, error) {
+ // Check if arp-scan is available
+ if _, err := exec.LookPath("arp-scan"); err != nil {
+ return nil, "", fmt.Errorf("arp-scan not found")
+ }
+
+ // Extract interface from CIDR if possible
+ iface := getInterfaceForCIDR(ctx, cidr)
+
+ // Run arp-scan
+ args := []string{"--localnet", "-q"}
+ if iface != "" {
+ args = append(args, "-I", iface)
+ }
+ cmd := exec.CommandContext(ctx, "arp-scan", args...)
+ output, err := cmd.Output()
+ if err != nil {
+ return nil, "", fmt.Errorf("arp-scan failed: %w", err)
+ }
+
+ // Parse output (format: IP\tMAC\tVendor)
+ var devices []types.Device
+ lines := strings.Split(string(output), "\n")
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+ if line == "" || strings.HasPrefix(line, "Interface:") || strings.HasPrefix(line, "Starting") || strings.HasPrefix(line, "Ending") {
+ continue
+ }
+
+ parts := strings.Split(line, "\t")
+ if len(parts) < 2 {
+ continue
+ }
+
+ ip := strings.TrimSpace(parts[0])
+ mac := strings.TrimSpace(parts[1])
+
+ // Validate IP
+ if net.ParseIP(ip) == nil {
+ continue
+ }
+
+ device := types.Device{
+ IP: ip,
+ MAC: mac,
+ }
+
+ // Get vendor
+ if len(parts) >= 3 {
+ device.Vendor = strings.TrimSpace(parts[2])
+ }
+ if device.Vendor == "" {
+ device.Vendor = GetMACVendor(mac)
+ }
+
+ // Try reverse DNS
+ device.Hostname = reverseDNS(ip)
+
+ devices = append(devices, device)
+ }
+
+ return devices, "arp-scan", nil
+}
+
+// reverseDNS performs a reverse DNS lookup
+func reverseDNS(ip string) string {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+
+ done := make(chan string, 1)
+ go func() {
+ names, err := net.LookupAddr(ip)
+ if err != nil || len(names) == 0 {
+ done <- ""
+ return
+ }
+ // Remove trailing dot
+ hostname := strings.TrimSuffix(names[0], ".")
+ done <- hostname
+ }()
+
+ select {
+ case <-ctx.Done():
+ return ""
+ case hostname := <-done:
+ return hostname
+ }
+}
+
+// parseResponseTime parses nmap SRTT value (microseconds) to milliseconds
+func parseResponseTime(srtt string) (float64, error) {
+ var usec int
+ if _, err := fmt.Sscanf(srtt, "%d", &usec); err != nil {
+ return 0, err
+ }
+ return float64(usec) / 1000.0, nil
+}
+
+// CheckRateLimit checks if a scan can proceed based on rate limiting
+func (s *Scanner) CheckRateLimit(lastScan time.Time) (bool, time.Duration) {
+ if lastScan.IsZero() {
+ return true, 0
+ }
+
+ elapsed := time.Since(lastScan)
+ if elapsed >= s.minInterval {
+ return true, 0
+ }
+
+ return false, s.minInterval - elapsed
+}
+
+// getInterfaceForCIDR tries to determine which network interface to use for a given CIDR
+func getInterfaceForCIDR(ctx context.Context, cidr string) string {
+ targetIP := strings.Split(cidr, "/")[0]
+
+ switch runtime.GOOS {
+ case "linux":
+ // Linux: use ip route get
+ cmd := exec.CommandContext(ctx, "ip", "route", "get", targetIP)
+ if output, err := cmd.Output(); err == nil {
+ parts := strings.Fields(string(output))
+ for i, p := range parts {
+ if p == "dev" && i+1 < len(parts) {
+ return parts[i+1]
+ }
+ }
+ }
+
+ case "darwin":
+ // macOS: use route get
+ cmd := exec.CommandContext(ctx, "route", "-n", "get", targetIP)
+ if output, err := cmd.Output(); err == nil {
+ lines := strings.Split(string(output), "\n")
+ for _, line := range lines {
+ if strings.Contains(line, "interface:") {
+ parts := strings.Fields(line)
+ if len(parts) >= 2 {
+ return parts[len(parts)-1]
+ }
+ }
+ }
+ }
+ }
+
+ // Fallback: try to find an interface that matches the CIDR using Go's net package
+ _, cidrNet, err := net.ParseCIDR(cidr)
+ if err != nil {
+ return ""
+ }
+
+ ifaces, err := net.Interfaces()
+ if err != nil {
+ return ""
+ }
+
+ for _, iface := range ifaces {
+ if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
+ continue
+ }
+ addrs, err := iface.Addrs()
+ if err != nil {
+ continue
+ }
+ for _, addr := range addrs {
+ if ipNet, ok := addr.(*net.IPNet); ok {
+ if cidrNet.Contains(ipNet.IP) {
+ return iface.Name
+ }
+ }
+ }
+ }
+
+ return ""
+}
diff --git a/internal/scanner/vendor.go b/internal/scanner/vendor.go
new file mode 100644
index 0000000..f6ac7e9
--- /dev/null
+++ b/internal/scanner/vendor.go
@@ -0,0 +1,84 @@
+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",
+}
+
+// GetMACVendor looks up the vendor for a MAC address
+func GetMACVendor(mac string) string {
+ if mac == "" {
+ return "Unknown"
+ }
+
+ // Normalize MAC address format
+ mac = strings.ToUpper(strings.ReplaceAll(mac, "-", ":"))
+
+ // Get prefix (first 8 characters: XX:XX:XX)
+ if len(mac) < 8 {
+ return "Unknown"
+ }
+ prefix := mac[:8]
+
+ if vendor, ok := macVendors[prefix]; ok {
+ return vendor
+ }
+ return "Unknown"
+}
diff --git a/internal/storage/storage.go b/internal/storage/storage.go
new file mode 100644
index 0000000..35a1b50
--- /dev/null
+++ b/internal/storage/storage.go
@@ -0,0 +1,280 @@
+// Package storage handles device persistence and state management
+package storage
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+// Storage manages device data persistence
+type Storage struct {
+ devicesFile string
+ stateFile string
+ mu sync.RWMutex
+ devices map[string]*types.Device
+ state *types.ScanState
+}
+
+// New creates a new Storage instance
+func New(devicesFile, stateFile string) (*Storage, error) {
+ s := &Storage{
+ devicesFile: devicesFile,
+ stateFile: stateFile,
+ devices: make(map[string]*types.Device),
+ state: &types.ScanState{
+ LastScan: make(map[string]time.Time),
+ },
+ }
+
+ // Ensure directories exist
+ if err := os.MkdirAll(filepath.Dir(devicesFile), 0755); err != nil {
+ return nil, fmt.Errorf("failed to create data directory: %w", err)
+ }
+
+ // Load existing data
+ if err := s.loadDevices(); err != nil && !os.IsNotExist(err) {
+ return nil, fmt.Errorf("failed to load devices: %w", err)
+ }
+ if err := s.loadState(); err != nil && !os.IsNotExist(err) {
+ return nil, fmt.Errorf("failed to load state: %w", err)
+ }
+
+ return s, nil
+}
+
+// loadDevices reads devices from the JSON file
+func (s *Storage) loadDevices() error {
+ data, err := os.ReadFile(s.devicesFile)
+ if err != nil {
+ return err
+ }
+
+ if len(data) == 0 {
+ return nil
+ }
+
+ return json.Unmarshal(data, &s.devices)
+}
+
+// loadState reads scan state from the JSON file
+func (s *Storage) loadState() error {
+ data, err := os.ReadFile(s.stateFile)
+ if err != nil {
+ return err
+ }
+
+ if len(data) == 0 {
+ return nil
+ }
+
+ return json.Unmarshal(data, &s.state)
+}
+
+// saveDevices writes devices to the JSON file atomically
+func (s *Storage) saveDevices() error {
+ data, err := json.MarshalIndent(s.devices, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal devices: %w", err)
+ }
+
+ return atomicWrite(s.devicesFile, data)
+}
+
+// saveState writes scan state to the JSON file atomically
+func (s *Storage) saveState() error {
+ data, err := json.MarshalIndent(s.state, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal state: %w", err)
+ }
+
+ return atomicWrite(s.stateFile, data)
+}
+
+// atomicWrite writes data to a file atomically using a temp file
+func atomicWrite(path string, data []byte) error {
+ dir := filepath.Dir(path)
+ tempFile, err := os.CreateTemp(dir, ".tmp-*")
+ if err != nil {
+ return fmt.Errorf("failed to create temp file: %w", err)
+ }
+ tempPath := tempFile.Name()
+
+ // Clean up temp file on error
+ defer func() {
+ if tempPath != "" {
+ os.Remove(tempPath)
+ }
+ }()
+
+ if _, err := tempFile.Write(data); err != nil {
+ tempFile.Close()
+ return fmt.Errorf("failed to write temp file: %w", err)
+ }
+
+ if err := tempFile.Sync(); err != nil {
+ tempFile.Close()
+ return fmt.Errorf("failed to sync temp file: %w", err)
+ }
+
+ if err := tempFile.Close(); err != nil {
+ return fmt.Errorf("failed to close temp file: %w", err)
+ }
+
+ if err := os.Rename(tempPath, path); err != nil {
+ return fmt.Errorf("failed to rename temp file: %w", err)
+ }
+
+ tempPath = "" // Prevent cleanup of renamed file
+ return nil
+}
+
+// GetDevices returns all devices
+func (s *Storage) GetDevices() map[string]*types.Device {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ result := make(map[string]*types.Device, len(s.devices))
+ for k, v := range s.devices {
+ result[k] = v
+ }
+ return result
+}
+
+// GetDevice returns a single device by IP
+func (s *Storage) GetDevice(ip string) *types.Device {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.devices[ip]
+}
+
+// UpdateDevice updates or creates a device
+func (s *Storage) UpdateDevice(device *types.Device) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // Preserve existing user data if device exists
+ if existing, ok := s.devices[device.IP]; ok {
+ if device.Label == "" {
+ device.Label = existing.Label
+ }
+ if device.Notes == "" {
+ device.Notes = existing.Notes
+ }
+ if device.Group == "" {
+ device.Group = existing.Group
+ }
+ if device.FirstSeen.IsZero() {
+ device.FirstSeen = existing.FirstSeen
+ }
+ }
+
+ s.devices[device.IP] = device
+ return s.saveDevices()
+}
+
+// UpdateDeviceFields updates specific fields of a device
+func (s *Storage) UpdateDeviceFields(ip string, label, notes, group *string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ device, ok := s.devices[ip]
+ if !ok {
+ return fmt.Errorf("device not found: %s", ip)
+ }
+
+ if label != nil {
+ device.Label = *label
+ }
+ if notes != nil {
+ device.Notes = *notes
+ }
+ if group != nil {
+ device.Group = *group
+ }
+
+ return s.saveDevices()
+}
+
+// DeleteDevice removes a device by IP
+func (s *Storage) DeleteDevice(ip string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if _, ok := s.devices[ip]; !ok {
+ return fmt.Errorf("device not found: %s", ip)
+ }
+
+ delete(s.devices, ip)
+ return s.saveDevices()
+}
+
+// MergeDevices merges discovered devices with existing data
+func (s *Storage) MergeDevices(discovered []types.Device) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ now := time.Now()
+ for _, d := range discovered {
+ if existing, ok := s.devices[d.IP]; ok {
+ // Update existing device, preserve user data
+ existing.MAC = d.MAC
+ existing.Hostname = d.Hostname
+ existing.Vendor = d.Vendor
+ existing.LastSeen = now
+ existing.ResponseTime = d.ResponseTime
+ } else {
+ // New device
+ d.FirstSeen = now
+ d.LastSeen = now
+ s.devices[d.IP] = &d
+ }
+ }
+
+ return s.saveDevices()
+}
+
+// GetLastScan returns the last scan time for a network
+func (s *Storage) GetLastScan(network string) time.Time {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return s.state.LastScan[network]
+}
+
+// SetLastScan updates the last scan time for a network
+func (s *Storage) SetLastScan(network string, t time.Time) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.state.LastScan[network] = t
+ return s.saveState()
+}
+
+// GetStats returns device statistics
+func (s *Storage) GetStats() types.DeviceStats {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ stats := types.DeviceStats{
+ Groups: make(map[string]int),
+ }
+
+ for _, d := range s.devices {
+ stats.Total++
+ if d.IsOnline() {
+ stats.Online++
+ } else {
+ stats.Offline++
+ }
+ if d.Group != "" {
+ stats.Groups[d.Group]++
+ }
+ }
+
+ return stats
+}
diff --git a/internal/types/types.go b/internal/types/types.go
new file mode 100644
index 0000000..e451369
--- /dev/null
+++ b/internal/types/types.go
@@ -0,0 +1,83 @@
+// Package types defines the core domain types for LAN Orangutan
+package types
+
+import "time"
+
+// Device represents a discovered network device
+type Device struct {
+ IP string `json:"ip"`
+ MAC string `json:"mac"`
+ Hostname string `json:"hostname"`
+ Vendor string `json:"vendor"`
+ Label string `json:"label"`
+ Notes string `json:"notes"`
+ Group string `json:"group"`
+ FirstSeen time.Time `json:"first_seen"`
+ LastSeen time.Time `json:"last_seen"`
+ ResponseTime *float64 `json:"response_time,omitempty"`
+}
+
+// IsOnline returns true if the device was seen within the last hour
+func (d *Device) IsOnline() bool {
+ return time.Since(d.LastSeen) < time.Hour
+}
+
+// IsRecent returns true if the device was seen within the last 5 minutes
+func (d *Device) IsRecent() bool {
+ return time.Since(d.LastSeen) < 5*time.Minute
+}
+
+// Network represents a detected network interface
+type Network struct {
+ CIDR string `json:"cidr"`
+ Interface string `json:"interface"`
+ FriendlyName string `json:"friendly_name"`
+ IP string `json:"ip"`
+ IsTailscale bool `json:"is_tailscale"`
+ IsWireless bool `json:"is_wireless"`
+}
+
+// ScanState holds the last scan time for rate limiting
+type ScanState struct {
+ LastScan map[string]time.Time `json:"last_scan"`
+}
+
+// ScanResult represents the outcome of a network scan
+type ScanResult struct {
+ Success bool `json:"success"`
+ Error string `json:"error,omitempty"`
+ Devices []Device `json:"devices"`
+ DeviceCount int `json:"device_count"`
+ Network string `json:"network"`
+ Scanner string `json:"scanner"`
+ Duration float64 `json:"duration"`
+ Timestamp time.Time `json:"timestamp"`
+}
+
+// TailscaleStatus represents Tailscale connection status
+type TailscaleStatus struct {
+ Installed bool `json:"installed"`
+ Running bool `json:"running"`
+ BackendState string `json:"backend_state"`
+ Version string `json:"version"`
+ TailnetName string `json:"tailnet_name"`
+ SelfIP string `json:"self_ip"`
+ SelfHostname string `json:"self_hostname"`
+ PeerCount int `json:"peer_count"`
+ ExitNode string `json:"exit_node,omitempty"`
+}
+
+// APIResponse is the standard API response wrapper
+type APIResponse struct {
+ Success bool `json:"success"`
+ Data interface{} `json:"data,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// DeviceStats holds device statistics for the dashboard
+type DeviceStats struct {
+ Total int `json:"total"`
+ Online int `json:"online"`
+ Offline int `json:"offline"`
+ Groups map[string]int `json:"groups"`
+}
diff --git a/internal/web/handler.go b/internal/web/handler.go
new file mode 100644
index 0000000..1665383
--- /dev/null
+++ b/internal/web/handler.go
@@ -0,0 +1,256 @@
+// Package web handles the web UI and static assets
+package web
+
+import (
+ "bytes"
+ "embed"
+ "fmt"
+ "html/template"
+ "io/fs"
+ "net/http"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/291-Group/LAN-Orangutan/internal/config"
+ "github.com/291-Group/LAN-Orangutan/internal/network"
+ "github.com/291-Group/LAN-Orangutan/internal/storage"
+ "github.com/291-Group/LAN-Orangutan/internal/types"
+)
+
+//go:embed static/*
+var staticFS embed.FS
+
+//go:embed templates/*
+var templateFS embed.FS
+
+// Handler handles web requests
+type Handler struct {
+ store *storage.Storage
+ cfg *config.Config
+ version string
+ templates *template.Template
+ staticFS http.Handler
+}
+
+// PageData holds data passed to templates
+type PageData struct {
+ Title string
+ Theme string
+ Version string
+ Devices []*DeviceView
+ Networks []types.Network
+ Tailscale types.TailscaleStatus
+ Stats types.DeviceStats
+ Groups []string
+ CurrentGroup string
+ Error string
+}
+
+// DeviceView is a device with computed display properties
+type DeviceView struct {
+ *types.Device
+ Status string
+ StatusClass string
+ TimeAgo string
+ LastSeenUnix int64
+}
+
+// NewHandler creates a new web handler
+func NewHandler(store *storage.Storage, cfg *config.Config, version string) *Handler {
+ // Parse templates with custom functions
+ funcMap := template.FuncMap{
+ "timeAgo": timeAgo,
+ "lower": strings.ToLower,
+ }
+
+ 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)))
+
+ return &Handler{
+ store: store,
+ cfg: cfg,
+ version: version,
+ templates: tmpl,
+ staticFS: staticHandler,
+ }
+}
+
+// ServeHTTP implements http.Handler
+func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ path := r.URL.Path
+
+ // Static files
+ if strings.HasPrefix(path, "/static/") {
+ h.staticFS.ServeHTTP(w, r)
+ return
+ }
+
+ // Routes
+ switch path {
+ case "/", "/index.html":
+ h.handleIndex(w, r)
+ case "/settings", "/settings.html":
+ h.handleSettings(w, r)
+ default:
+ http.NotFound(w, r)
+ }
+}
+
+// handleIndex renders the main dashboard
+func (h *Handler) handleIndex(w http.ResponseWriter, r *http.Request) {
+ // Get devices
+ devices := h.store.GetDevices()
+
+ // Convert to view models
+ var deviceViews []*DeviceView
+ groupSet := make(map[string]bool)
+
+ for _, d := range devices {
+ dv := &DeviceView{
+ Device: d,
+ TimeAgo: timeAgo(d.LastSeen),
+ LastSeenUnix: d.LastSeen.Unix(),
+ }
+
+ if d.IsRecent() {
+ dv.Status = "online"
+ dv.StatusClass = "status-online"
+ } else if d.IsOnline() {
+ dv.Status = "seen"
+ dv.StatusClass = "status-seen"
+ } else {
+ dv.Status = "offline"
+ dv.StatusClass = "status-offline"
+ }
+
+ deviceViews = append(deviceViews, dv)
+
+ if d.Group != "" {
+ groupSet[d.Group] = true
+ }
+ }
+
+ // Sort by IP
+ sort.Slice(deviceViews, func(i, j int) bool {
+ return ipToLong(deviceViews[i].IP) < ipToLong(deviceViews[j].IP)
+ })
+
+ // Get groups
+ var groups []string
+ for g := range groupSet {
+ groups = append(groups, g)
+ }
+ sort.Strings(groups)
+
+ // Get networks
+ networks, _ := network.DetectNetworks()
+
+ // Get Tailscale status
+ tailscale := network.GetTailscaleStatus()
+
+ // Get stats
+ stats := h.store.GetStats()
+
+ data := PageData{
+ Title: "LAN Orangutan",
+ Theme: h.cfg.UI.Theme,
+ Devices: deviceViews,
+ Networks: networks,
+ Tailscale: tailscale,
+ Stats: stats,
+ Groups: groups,
+ }
+
+ // Buffer the template output to avoid superfluous WriteHeader on error
+ var buf bytes.Buffer
+ if err := h.templates.ExecuteTemplate(&buf, "index.html", data); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ buf.WriteTo(w)
+}
+
+// handleSettings renders the settings page
+func (h *Handler) handleSettings(w http.ResponseWriter, r *http.Request) {
+ // Get Tailscale status
+ tailscale := network.GetTailscaleStatus()
+
+ // Get stats
+ stats := h.store.GetStats()
+
+ data := PageData{
+ Title: "Settings - LAN Orangutan",
+ Theme: h.cfg.UI.Theme,
+ Version: h.version,
+ Tailscale: tailscale,
+ Stats: stats,
+ }
+
+ // Buffer the template output to avoid superfluous WriteHeader on error
+ var buf bytes.Buffer
+ if err := h.templates.ExecuteTemplate(&buf, "settings.html", data); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ buf.WriteTo(w)
+}
+
+// timeAgo returns a human-readable time difference
+func timeAgo(t time.Time) string {
+ if t.IsZero() {
+ return "never"
+ }
+
+ diff := time.Since(t)
+
+ switch {
+ case diff < time.Minute:
+ return "just now"
+ case diff < time.Hour:
+ mins := int(diff.Minutes())
+ if mins == 1 {
+ return "1 min ago"
+ }
+ return fmt.Sprintf("%d min ago", mins)
+ case diff < 24*time.Hour:
+ hours := int(diff.Hours())
+ if hours == 1 {
+ return "1 hr ago"
+ }
+ return fmt.Sprintf("%d hr ago", hours)
+ case diff < 7*24*time.Hour:
+ days := int(diff.Hours() / 24)
+ if days == 1 {
+ return "1 day ago"
+ }
+ return fmt.Sprintf("%d days ago", days)
+ default:
+ return t.Format("Jan 2, 2006")
+ }
+}
+
+// ipToLong converts an IP string to a sortable integer
+func ipToLong(ip string) int64 {
+ parts := strings.Split(ip, ".")
+ if len(parts) != 4 {
+ return 0x7FFFFFFFFFFFFFFF
+ }
+
+ var result int64
+ for i, p := range parts {
+ var n int
+ for _, c := range p {
+ if c >= '0' && c <= '9' {
+ n = n*10 + int(c-'0')
+ }
+ }
+ result |= int64(n) << (24 - 8*i)
+ }
+ return result
+}
diff --git a/internal/web/static/app.js b/internal/web/static/app.js
new file mode 100644
index 0000000..fd559b9
--- /dev/null
+++ b/internal/web/static/app.js
@@ -0,0 +1,412 @@
+// Theme toggle
+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);
+}
+
+// Initialize theme
+(function() {
+ const saved = localStorage.getItem('theme');
+ if (saved) document.documentElement.setAttribute('data-theme', saved);
+})();
+
+// Toast notifications
+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);
+}
+
+// API helper
+async function api(action, params = {}, method = 'GET') {
+ let url = `/api/${action}`;
+ const options = { method };
+ if (method === 'GET') {
+ const queryParams = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
+ if (queryParams) url += `?${queryParams}`;
+ } else {
+ options.headers = { 'Content-Type': 'application/json' };
+ options.body = JSON.stringify(params);
+ }
+ try {
+ const response = await fetch(url, options);
+ const text = await response.text();
+ if (!response.ok) {
+ // Try to parse error from response body
+ try {
+ const errData = JSON.parse(text);
+ if (response.status === 429) {
+ throw new Error(errData.error || 'Rate limited - please wait before scanning again');
+ }
+ throw new Error(errData.error || `HTTP error: ${response.status}`);
+ } catch (parseErr) {
+ if (parseErr.message.includes('Rate limited') || parseErr.message.includes('rate limited')) {
+ throw parseErr;
+ }
+ throw new Error(`HTTP error: ${response.status}`);
+ }
+ }
+ if (!text) throw new Error('Empty response');
+ return JSON.parse(text);
+ } catch (error) {
+ console.error('API error:', error);
+ throw error;
+ }
+}
+
+// Network scanning
+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.data?.device_count || 0} devices`, 'success');
+ setTimeout(() => location.reload(), 1000);
+ } else {
+ showToast(result.error || 'Scan failed', 'error');
+ }
+ } catch (e) {
+ const isRateLimit = e.message.toLowerCase().includes('rate limit');
+ showToast(isRateLimit ? e.message : 'Scan failed: ' + e.message, isRateLimit ? 'warning' : '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) {
+ showToast('Scan complete', 'success');
+ setTimeout(() => location.reload(), 1000);
+ } else {
+ showToast(result.error || 'Scan failed', 'error');
+ }
+ } catch (e) {
+ const isRateLimit = e.message.toLowerCase().includes('rate limit');
+ showToast(isRateLimit ? e.message : 'Scan failed: ' + e.message, isRateLimit ? 'warning' : 'error');
+ } finally {
+ if (progress) progress.style.display = 'none';
+ }
+}
+
+// Device filtering
+function filterDevices() {
+ const search = (document.getElementById('device-search')?.value || '').toLowerCase();
+ const statusFilter = document.getElementById('device-filter')?.value || 'all';
+ const groupFilter = document.getElementById('group-filter')?.value || 'all';
+
+ let visible = 0;
+ document.querySelectorAll('.device-row').forEach(row => {
+ const text = [row.dataset.ip, row.dataset.hostname, row.dataset.mac, row.dataset.vendor, row.dataset.label].join(' ').toLowerCase();
+ const status = row.dataset.status;
+ const group = row.dataset.group || '';
+
+ const matchSearch = !search || text.includes(search);
+ const matchStatus = statusFilter === 'all' ||
+ (statusFilter === 'online' && (status === 'online' || status === 'recent')) ||
+ (statusFilter === 'offline' && status === 'offline');
+ const matchGroup = groupFilter === 'all' || group === groupFilter;
+
+ const show = matchSearch && matchStatus && matchGroup;
+ row.style.display = show ? '' : 'none';
+ if (show) visible++;
+ });
+
+ const countEl = document.getElementById('device-count');
+ if (countEl) countEl.textContent = `Showing ${visible} devices`;
+}
+
+// Device editing
+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.dataset.group || '';
+ document.getElementById('edit-notes').value = row.dataset.notes || '';
+ 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/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();
+ filterDevices(); // Update count
+ } else {
+ showToast(result.error || 'Failed to delete', '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');
+ // Update data attribute
+ const row = select.closest('.device-row');
+ if (row) row.dataset.group = group;
+ } else {
+ showToast(result.error || 'Failed to update', 'error');
+ }
+ } catch (e) {
+ showToast('Failed to update group', 'error');
+ }
+}
+
+// Copy to clipboard
+function copyToClipboard(text, event) {
+ navigator.clipboard.writeText(text).then(() => {
+ // Show feedback at cursor position
+ const feedback = document.createElement('div');
+ feedback.className = 'copy-feedback';
+ feedback.textContent = 'Copied!';
+ feedback.style.left = event.pageX + 'px';
+ feedback.style.top = (event.pageY - 30) + 'px';
+ document.body.appendChild(feedback);
+ setTimeout(() => feedback.remove(), 800);
+ }).catch(() => {
+ showToast('Failed to copy', 'error');
+ });
+}
+
+// Export devices
+function exportDevices(format) {
+ const rows = document.querySelectorAll('.device-row');
+ const devices = [];
+
+ rows.forEach(row => {
+ if (row.style.display !== 'none') {
+ devices.push({
+ ip: row.dataset.ip,
+ hostname: row.querySelector('.hostname-cell')?.textContent?.trim() || '',
+ mac: row.dataset.mac?.toUpperCase() || '',
+ vendor: row.querySelector('.vendor-cell')?.textContent?.trim() || '',
+ label: row.dataset.labelOriginal || '',
+ group: row.dataset.group || '',
+ status: row.dataset.status || ''
+ });
+ }
+ });
+
+ let content, filename, type;
+
+ if (format === 'csv') {
+ const headers = ['IP', 'Hostname', 'MAC', 'Vendor', 'Label', 'Group', 'Status'];
+ const csvRows = [headers.join(',')];
+ devices.forEach(d => {
+ csvRows.push([d.ip, d.hostname, d.mac, d.vendor, d.label, d.group, d.status]
+ .map(v => `"${(v || '').replace(/"/g, '""')}"`)
+ .join(','));
+ });
+ content = csvRows.join('\n');
+ filename = 'devices.csv';
+ type = 'text/csv';
+ } else {
+ content = JSON.stringify(devices, null, 2);
+ filename = 'devices.json';
+ type = 'application/json';
+ }
+
+ const blob = new Blob([content], { type });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ a.click();
+ URL.revokeObjectURL(url);
+
+ toggleDropdown('export-menu');
+ showToast(`Exported ${devices.length} devices`, 'success');
+}
+
+// Dropdown toggle
+function toggleDropdown(id) {
+ const menu = document.getElementById(id);
+ if (menu) {
+ menu.classList.toggle('show');
+ // Close on click outside
+ if (menu.classList.contains('show')) {
+ setTimeout(() => {
+ document.addEventListener('click', function closeDropdown(e) {
+ if (!menu.contains(e.target)) {
+ menu.classList.remove('show');
+ document.removeEventListener('click', closeDropdown);
+ }
+ });
+ }, 0);
+ }
+ }
+}
+
+// Table sorting
+let sortColumn = null;
+let sortAsc = true;
+
+function sortTable(column) {
+ const tbody = document.getElementById('devices-tbody');
+ if (!tbody) return;
+
+ if (sortColumn === column) {
+ sortAsc = !sortAsc;
+ } else {
+ sortColumn = column;
+ sortAsc = true;
+ }
+
+ const rows = Array.from(tbody.querySelectorAll('.device-row'));
+
+ rows.sort((a, b) => {
+ let valA, valB;
+
+ switch (column) {
+ case 'ip':
+ // Sort IP addresses numerically
+ valA = a.dataset.ip.split('.').map(n => n.padStart(3, '0')).join('');
+ valB = b.dataset.ip.split('.').map(n => n.padStart(3, '0')).join('');
+ break;
+ case 'hostname':
+ valA = a.dataset.hostname || 'zzz';
+ valB = b.dataset.hostname || 'zzz';
+ break;
+ case 'mac':
+ valA = a.dataset.mac || 'zzz';
+ valB = b.dataset.mac || 'zzz';
+ break;
+ case 'vendor':
+ valA = a.dataset.vendor || 'zzz';
+ valB = b.dataset.vendor || 'zzz';
+ break;
+ case 'status':
+ const order = { online: 0, recent: 1, offline: 2 };
+ valA = order[a.dataset.status] ?? 3;
+ valB = order[b.dataset.status] ?? 3;
+ break;
+ case 'lastseen':
+ valA = parseInt(a.dataset.lastseen) || 0;
+ valB = parseInt(b.dataset.lastseen) || 0;
+ break;
+ default:
+ valA = a.dataset[column] || '';
+ valB = b.dataset[column] || '';
+ }
+
+ if (valA < valB) return sortAsc ? -1 : 1;
+ if (valA > valB) return sortAsc ? 1 : -1;
+ return 0;
+ });
+
+ rows.forEach(row => tbody.appendChild(row));
+
+ // Update sort indicators
+ document.querySelectorAll('.table th').forEach(th => th.classList.remove('sorted'));
+}
+
+// Auto-refresh
+let autoRefreshInterval = null;
+
+function toggleAutoRefresh() {
+ const toggle = document.getElementById('auto-refresh-toggle');
+ if (!toggle) return;
+
+ if (autoRefreshInterval) {
+ clearInterval(autoRefreshInterval);
+ autoRefreshInterval = null;
+ toggle.classList.remove('active');
+ localStorage.setItem('autoRefresh', 'false');
+ } else {
+ autoRefreshInterval = setInterval(() => location.reload(), 30000);
+ toggle.classList.add('active');
+ localStorage.setItem('autoRefresh', 'true');
+ showToast('Auto-refresh enabled (30s)', 'info');
+ }
+}
+
+// Initialize auto-refresh from localStorage
+(function() {
+ if (localStorage.getItem('autoRefresh') === 'true') {
+ const toggle = document.getElementById('auto-refresh-toggle');
+ if (toggle) {
+ toggle.classList.add('active');
+ autoRefreshInterval = setInterval(() => location.reload(), 30000);
+ }
+ }
+})();
+
+// Keyboard shortcuts
+document.addEventListener('keydown', e => {
+ // Ignore if typing in input
+ if (e.target.matches('input, textarea, select')) return;
+
+ switch (e.key.toLowerCase()) {
+ case '/':
+ e.preventDefault();
+ document.getElementById('device-search')?.focus();
+ break;
+ case 'r':
+ location.reload();
+ break;
+ case 't':
+ toggleTheme();
+ break;
+ case 'escape':
+ closeModal();
+ break;
+ }
+});
+
+// Close modal on backdrop click
+document.addEventListener('click', e => {
+ if (e.target.classList.contains('modal')) closeModal();
+});
+
+// Close modal on Escape
+document.addEventListener('keydown', e => {
+ if (e.key === 'Escape') closeModal();
+});
diff --git a/internal/web/static/orangutan.svg b/internal/web/static/orangutan.svg
new file mode 100644
index 0000000..156d467
--- /dev/null
+++ b/internal/web/static/orangutan.svg
@@ -0,0 +1,23 @@
+<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/internal/web/static/style.css b/internal/web/static/style.css
new file mode 100644
index 0000000..5d4a4e8
--- /dev/null
+++ b/internal/web/static/style.css
@@ -0,0 +1,939 @@
+:root,
+[data-theme="light"] {
+ --bg-primary: #ffffff;
+ --bg-secondary: #f8fafc;
+ --bg-tertiary: #f1f5f9;
+ --text-primary: #0f172a;
+ --text-secondary: #475569;
+ --text-muted: #94a3b8;
+ --border-color: #e2e8f0;
+ --accent-primary: #f97316;
+ --accent-secondary: #06b6d4;
+ --accent-hover: #ea580c;
+ --success: #22c55e;
+ --success-bg: rgba(34, 197, 94, 0.1);
+ --warning: #f59e0b;
+ --warning-bg: rgba(245, 158, 11, 0.1);
+ --danger: #ef4444;
+ --danger-bg: rgba(239, 68, 68, 0.1);
+ --card-shadow: 0 1px 3px rgba(0,0,0,0.1), 0 1px 2px rgba(0,0,0,0.06);
+ --card-shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
+ --header-bg: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
+ --header-text: #ffffff;
+ --radius-sm: 6px;
+ --radius-md: 10px;
+ --radius-lg: 16px;
+ --transition: all 0.2s ease;
+}
+
+[data-theme="dark"],
+html[data-theme="dark"] {
+ --bg-primary: #0f172a;
+ --bg-secondary: #1e293b;
+ --bg-tertiary: #334155;
+ --text-primary: #f1f5f9;
+ --text-secondary: #cbd5e1;
+ --text-muted: #64748b;
+ --border-color: #334155;
+ --card-shadow: 0 1px 3px rgba(0,0,0,0.3);
+ --card-shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.4);
+ --header-bg: linear-gradient(135deg, #0f172a 0%, #020617 100%);
+}
+
+@media (prefers-color-scheme: dark) {
+ [data-theme="auto"] {
+ --bg-primary: #0f172a;
+ --bg-secondary: #1e293b;
+ --bg-tertiary: #334155;
+ --text-primary: #f1f5f9;
+ --text-secondary: #cbd5e1;
+ --text-muted: #64748b;
+ --border-color: #334155;
+ --card-shadow: 0 1px 3px rgba(0,0,0,0.3);
+ --card-shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.4);
+ --header-bg: linear-gradient(135deg, #0f172a 0%, #020617 100%);
+ }
+}
+
+*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
+
+body {
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', sans-serif;
+ background: var(--bg-secondary);
+ color: var(--text-primary);
+ line-height: 1.6;
+ -webkit-font-smoothing: antialiased;
+}
+
+a { color: var(--accent-primary); text-decoration: none; transition: var(--transition); }
+a:hover { color: var(--accent-hover); }
+
+/* Header */
+.header {
+ background: var(--header-bg);
+ color: var(--header-text);
+ padding: 0 2rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ height: 64px;
+ position: sticky;
+ top: 0;
+ z-index: 100;
+ box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);
+}
+
+.header-brand {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ color: inherit;
+ text-decoration: none;
+}
+
+.header-brand:hover {
+ color: inherit;
+ opacity: 0.9;
+}
+
+.logo {
+ font-size: 2rem;
+ filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
+}
+
+.header h1 {
+ font-size: 1.25rem;
+ font-weight: 700;
+ letter-spacing: -0.025em;
+}
+
+.header-nav {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.nav-link {
+ color: var(--header-text);
+ opacity: 0.8;
+ padding: 0.5rem 1rem;
+ border-radius: var(--radius-md);
+ transition: var(--transition);
+ font-weight: 500;
+ font-size: 0.9rem;
+}
+
+.nav-link:hover, .nav-link.active {
+ opacity: 1;
+ background: rgba(255,255,255,0.15);
+ color: var(--header-text);
+}
+
+.theme-toggle {
+ background: rgba(255,255,255,0.1);
+ border: none;
+ color: var(--header-text);
+ font-size: 1.1rem;
+ cursor: pointer;
+ padding: 0.5rem 0.75rem;
+ border-radius: var(--radius-sm);
+ transition: var(--transition);
+}
+
+.theme-toggle:hover {
+ background: rgba(255,255,255,0.2);
+}
+
+/* Main Content */
+.main {
+ max-width: 1600px;
+ margin: 0 auto;
+ padding: 2rem;
+}
+
+.section {
+ margin-bottom: 2rem;
+ animation: fadeIn 0.3s ease;
+}
+
+@keyframes fadeIn {
+ from { opacity: 0; transform: translateY(10px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.section-title {
+ font-size: 1.25rem;
+ font-weight: 700;
+ margin-bottom: 1rem;
+ color: var(--text-primary);
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.section-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 1rem;
+ margin-bottom: 1.5rem;
+}
+
+.section-actions {
+ display: flex;
+ gap: 0.75rem;
+ flex-wrap: wrap;
+ align-items: center;
+}
+
+/* Cards */
+.card {
+ background: var(--bg-primary);
+ border-radius: var(--radius-lg);
+ padding: 1.5rem;
+ box-shadow: var(--card-shadow);
+ border: 1px solid var(--border-color);
+ transition: var(--transition);
+}
+
+.card:hover {
+ box-shadow: var(--card-shadow-lg);
+ transform: translateY(-2px);
+}
+
+.card-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 1rem;
+}
+
+.card-footer {
+ margin-top: 1.25rem;
+ padding-top: 1rem;
+ border-top: 1px solid var(--border-color);
+}
+
+/* Network Cards */
+.network-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: 1.25rem;
+}
+
+.network-card {
+ position: relative;
+ overflow: hidden;
+}
+
+.network-card::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 4px;
+ background: var(--accent-primary);
+}
+
+.network-card.tailscale::before {
+ background: var(--accent-secondary);
+}
+
+.network-name {
+ font-weight: 700;
+ font-size: 1.1rem;
+}
+
+.network-detail {
+ display: flex;
+ justify-content: space-between;
+ padding: 0.5rem 0;
+ font-size: 0.9rem;
+ border-bottom: 1px dashed var(--border-color);
+}
+
+.network-detail:last-child {
+ border-bottom: none;
+}
+
+.network-detail .label {
+ color: var(--text-muted);
+ font-weight: 500;
+}
+
+.network-detail .value {
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+/* Stats Bar */
+.stats-bar {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 1.25rem;
+}
+
+.stat-card {
+ background: var(--bg-primary);
+ border-radius: var(--radius-lg);
+ padding: 1.5rem;
+ box-shadow: var(--card-shadow);
+ border: 1px solid var(--border-color);
+ text-align: center;
+ transition: var(--transition);
+}
+
+.stat-card:hover {
+ transform: translateY(-2px);
+ box-shadow: var(--card-shadow-lg);
+}
+
+.stat-icon {
+ font-size: 2rem;
+ margin-bottom: 0.5rem;
+}
+
+.stat-value {
+ font-size: 2.5rem;
+ font-weight: 800;
+ display: block;
+ line-height: 1;
+ margin-bottom: 0.25rem;
+}
+
+.stat-value.online { color: var(--success); }
+.stat-value.warning { color: var(--warning); }
+.stat-value.danger { color: var(--danger); }
+
+.stat-label {
+ font-size: 0.85rem;
+ color: var(--text-muted);
+ font-weight: 500;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+
+/* Status Badges */
+.status-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.35rem;
+ padding: 0.25rem 0.75rem;
+ border-radius: 9999px;
+ font-size: 0.75rem;
+ font-weight: 600;
+ text-transform: uppercase;
+}
+
+.status-badge.online {
+ background: var(--success-bg);
+ color: var(--success);
+}
+
+.status-badge.recent {
+ background: var(--warning-bg);
+ color: var(--warning);
+}
+
+.status-badge.offline {
+ background: var(--bg-tertiary);
+ color: var(--text-muted);
+}
+
+/* Table */
+.table-container {
+ background: var(--bg-primary);
+ border-radius: var(--radius-lg);
+ overflow: hidden;
+ box-shadow: var(--card-shadow);
+ border: 1px solid var(--border-color);
+}
+
+.table-toolbar {
+ padding: 1rem 1.25rem;
+ background: var(--bg-tertiary);
+ border-bottom: 1px solid var(--border-color);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 1rem;
+ flex-wrap: wrap;
+}
+
+.table-info {
+ font-size: 0.9rem;
+ color: var(--text-secondary);
+}
+
+.table {
+ width: 100%;
+ border-collapse: collapse;
+}
+
+.table th, .table td {
+ padding: 1rem 1.25rem;
+ text-align: left;
+ border-bottom: 1px solid var(--border-color);
+}
+
+.table th {
+ background: var(--bg-tertiary);
+ font-weight: 600;
+ font-size: 0.8rem;
+ color: var(--text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ white-space: nowrap;
+ cursor: pointer;
+ user-select: none;
+ transition: var(--transition);
+}
+
+.table th:hover {
+ background: var(--bg-secondary);
+}
+
+.table th .sort-icon {
+ margin-left: 0.5rem;
+ opacity: 0.5;
+}
+
+.table th.sorted .sort-icon {
+ opacity: 1;
+}
+
+.table tbody tr {
+ transition: var(--transition);
+}
+
+.table tbody tr:hover {
+ background: var(--bg-secondary);
+}
+
+.table tbody tr:last-child td {
+ border-bottom: none;
+}
+
+.ip-cell {
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 0.9rem;
+ font-weight: 600;
+}
+
+.mac-cell {
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 0.85rem;
+ color: var(--text-secondary);
+}
+
+.time-cell {
+ color: var(--text-muted);
+ font-size: 0.85rem;
+}
+
+.status-indicator {
+ width: 10px;
+ height: 10px;
+ border-radius: 50%;
+ display: inline-block;
+ margin-right: 0.5rem;
+}
+
+.status-indicator.online {
+ background: var(--success);
+ box-shadow: 0 0 0 3px var(--success-bg);
+}
+
+.status-indicator.recent {
+ background: var(--warning);
+ box-shadow: 0 0 0 3px var(--warning-bg);
+}
+
+.status-indicator.offline {
+ background: var(--text-muted);
+}
+
+.device-row.online {
+ border-left: 3px solid var(--success);
+}
+
+.device-row.recent {
+ border-left: 3px solid var(--warning);
+}
+
+.device-row.offline {
+ border-left: 3px solid transparent;
+}
+
+.hostname-cell {
+ max-width: 200px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.vendor-cell {
+ max-width: 180px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--text-secondary);
+ font-size: 0.9rem;
+}
+
+.label-cell {
+ font-weight: 500;
+ color: var(--accent-primary);
+}
+
+.notes-indicator {
+ margin-left: 0.5rem;
+ cursor: help;
+ opacity: 0.7;
+}
+
+.notes-indicator:hover {
+ opacity: 1;
+}
+
+/* Action Buttons */
+.actions-cell {
+ white-space: nowrap;
+}
+
+.btn-icon {
+ background: none;
+ border: none;
+ padding: 0.5rem;
+ cursor: pointer;
+ color: var(--text-muted);
+ font-size: 1rem;
+ border-radius: var(--radius-sm);
+ transition: var(--transition);
+ line-height: 1;
+}
+
+.btn-icon:hover {
+ color: var(--text-primary);
+ background: var(--bg-tertiary);
+}
+
+.btn-icon.danger:hover {
+ color: var(--danger);
+ background: var(--danger-bg);
+}
+
+.btn-icon.success:hover {
+ color: var(--success);
+ background: var(--success-bg);
+}
+
+/* Forms */
+.input, .select {
+ padding: 0.65rem 1rem;
+ border: 2px solid var(--border-color);
+ border-radius: var(--radius-md);
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ font-size: 0.95rem;
+ width: 100%;
+ transition: var(--transition);
+}
+
+.input:focus, .select:focus {
+ outline: none;
+ border-color: var(--accent-primary);
+ box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.1);
+}
+
+.input::placeholder {
+ color: var(--text-muted);
+}
+
+.search-input {
+ width: 250px;
+ padding-left: 2.5rem;
+ 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' d='M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z'%3E%3C/path%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: 0.75rem center;
+ background-size: 1.25rem;
+}
+
+.form-group {
+ margin-bottom: 1.25rem;
+}
+
+.form-group label {
+ display: block;
+ margin-bottom: 0.5rem;
+ font-weight: 600;
+ font-size: 0.9rem;
+ color: var(--text-secondary);
+}
+
+/* Buttons */
+.btn {
+ padding: 0.65rem 1.25rem;
+ border: 2px solid var(--border-color);
+ border-radius: var(--radius-md);
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ font-size: 0.95rem;
+ font-weight: 600;
+ cursor: pointer;
+ transition: var(--transition);
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.btn:hover {
+ background: var(--bg-tertiary);
+ transform: translateY(-1px);
+}
+
+.btn-primary {
+ background: var(--accent-primary);
+ border-color: var(--accent-primary);
+ color: white;
+}
+
+.btn-primary:hover {
+ background: var(--accent-hover);
+ border-color: var(--accent-hover);
+}
+
+.btn-sm {
+ padding: 0.4rem 0.85rem;
+ font-size: 0.85rem;
+}
+
+.btn-lg {
+ padding: 0.85rem 2rem;
+ font-size: 1rem;
+}
+
+.btn-ghost {
+ background: transparent;
+ border-color: transparent;
+}
+
+.btn-ghost:hover {
+ background: var(--bg-tertiary);
+}
+
+/* Group Select */
+.group-select {
+ padding: 0.35rem 0.75rem;
+ border: 1px solid var(--border-color);
+ border-radius: var(--radius-sm);
+ background: var(--bg-primary);
+ color: var(--text-primary);
+ font-size: 0.85rem;
+ cursor: pointer;
+ transition: var(--transition);
+}
+
+.group-select:focus {
+ border-color: var(--accent-primary);
+ outline: none;
+}
+
+/* Modal */
+.modal {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background: rgba(0, 0, 0, 0.6);
+ backdrop-filter: blur(4px);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1000;
+ animation: fadeIn 0.2s ease;
+}
+
+.modal-content {
+ background: var(--bg-primary);
+ border-radius: var(--radius-lg);
+ width: 90%;
+ max-width: 480px;
+ max-height: 90vh;
+ overflow: auto;
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
+ animation: slideUp 0.3s ease;
+}
+
+@keyframes slideUp {
+ from { opacity: 0; transform: translateY(20px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.modal-header {
+ padding: 1.25rem 1.5rem;
+ border-bottom: 1px solid var(--border-color);
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+}
+
+.modal-header h3 {
+ font-size: 1.15rem;
+ font-weight: 700;
+}
+
+.modal-close {
+ background: none;
+ border: none;
+ font-size: 1.5rem;
+ cursor: pointer;
+ color: var(--text-muted);
+ padding: 0.25rem;
+ line-height: 1;
+ transition: var(--transition);
+}
+
+.modal-close:hover {
+ color: var(--text-primary);
+}
+
+.modal-body {
+ padding: 1.5rem;
+}
+
+.modal-footer {
+ padding: 1rem 1.5rem;
+ border-top: 1px solid var(--border-color);
+ display: flex;
+ justify-content: flex-end;
+ gap: 0.75rem;
+ background: var(--bg-secondary);
+}
+
+/* Toast */
+.toast {
+ position: fixed;
+ bottom: 2rem;
+ right: 2rem;
+ padding: 1rem 1.5rem;
+ background: var(--text-primary);
+ color: var(--bg-primary);
+ border-radius: var(--radius-md);
+ transform: translateY(100px);
+ opacity: 0;
+ transition: all 0.3s ease;
+ z-index: 1100;
+ font-weight: 500;
+ box-shadow: 0 10px 25px rgba(0,0,0,0.2);
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+}
+
+.toast.show {
+ transform: translateY(0);
+ opacity: 1;
+}
+
+.toast.success {
+ background: var(--success);
+ color: white;
+}
+
+.toast.error {
+ background: var(--danger);
+ color: white;
+}
+
+/* Scan Progress */
+.scan-progress {
+ position: fixed;
+ top: 80px;
+ left: 50%;
+ transform: translateX(-50%);
+ background: var(--bg-primary);
+ padding: 1rem 1.75rem;
+ border-radius: var(--radius-lg);
+ box-shadow: 0 10px 40px rgba(0,0,0,0.15);
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ z-index: 200;
+ border: 1px solid var(--border-color);
+}
+
+.scan-spinner {
+ width: 24px;
+ height: 24px;
+ border: 3px solid var(--border-color);
+ border-top-color: var(--accent-primary);
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+}
+
+@keyframes spin {
+ to { transform: rotate(360deg); }
+}
+
+/* Empty State */
+.empty-state {
+ text-align: center;
+ padding: 4rem 2rem;
+ color: var(--text-muted);
+}
+
+.empty-state-icon {
+ font-size: 4rem;
+ margin-bottom: 1rem;
+ opacity: 0.5;
+}
+
+.empty-state h3 {
+ font-size: 1.25rem;
+ color: var(--text-secondary);
+ margin-bottom: 0.5rem;
+}
+
+/* Auto Refresh Toggle */
+.auto-refresh {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ font-size: 0.9rem;
+ color: var(--text-secondary);
+}
+
+.toggle-switch {
+ position: relative;
+ width: 44px;
+ height: 24px;
+ background: var(--bg-tertiary);
+ border-radius: 12px;
+ cursor: pointer;
+ transition: var(--transition);
+}
+
+.toggle-switch.active {
+ background: var(--success);
+}
+
+.toggle-switch::after {
+ content: '';
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 20px;
+ height: 20px;
+ background: white;
+ border-radius: 50%;
+ transition: var(--transition);
+ box-shadow: 0 1px 3px rgba(0,0,0,0.2);
+}
+
+.toggle-switch.active::after {
+ left: 22px;
+}
+
+/* Export Dropdown */
+.dropdown {
+ position: relative;
+}
+
+.dropdown-menu {
+ position: absolute;
+ top: 100%;
+ right: 0;
+ margin-top: 0.5rem;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-color);
+ border-radius: var(--radius-md);
+ box-shadow: var(--card-shadow-lg);
+ min-width: 160px;
+ z-index: 50;
+ display: none;
+}
+
+.dropdown-menu.show {
+ display: block;
+ animation: fadeIn 0.15s ease;
+}
+
+.dropdown-item {
+ display: block;
+ padding: 0.65rem 1rem;
+ color: var(--text-primary);
+ font-size: 0.9rem;
+ transition: var(--transition);
+ cursor: pointer;
+}
+
+.dropdown-item:hover {
+ background: var(--bg-secondary);
+}
+
+/* Footer */
+.footer {
+ text-align: center;
+ padding: 2rem;
+ color: var(--text-muted);
+ font-size: 0.9rem;
+ border-top: 1px solid var(--border-color);
+ margin-top: 2rem;
+}
+
+/* Keyboard Hint */
+.kbd {
+ display: inline-block;
+ padding: 0.2rem 0.5rem;
+ font-size: 0.75rem;
+ font-family: monospace;
+ background: var(--bg-tertiary);
+ border: 1px solid var(--border-color);
+ border-radius: 4px;
+ color: var(--text-secondary);
+}
+
+/* Responsive */
+@media (max-width: 1024px) {
+ .main { padding: 1.5rem; }
+ .network-cards { grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); }
+ .stats-bar { grid-template-columns: repeat(2, 1fr); }
+}
+
+@media (max-width: 768px) {
+ .header { padding: 0 1rem; }
+ .header h1 { display: none; }
+ .main { padding: 1rem; }
+ .section-header { flex-direction: column; align-items: stretch; }
+ .section-actions { justify-content: space-between; }
+ .table-container { overflow-x: auto; }
+ .table th, .table td { padding: 0.75rem; }
+ .search-input { width: 100%; }
+ .stat-card { padding: 1rem; }
+ .stat-value { font-size: 1.75rem; }
+ .toast { left: 1rem; right: 1rem; bottom: 1rem; }
+}
+
+/* Copy Animation */
+.copy-feedback {
+ position: fixed;
+ background: var(--text-primary);
+ color: var(--bg-primary);
+ padding: 0.5rem 1rem;
+ border-radius: var(--radius-sm);
+ font-size: 0.85rem;
+ z-index: 1200;
+ animation: copyPop 0.8s ease forwards;
+}
+
+@keyframes copyPop {
+ 0% { opacity: 0; transform: translateY(10px); }
+ 20% { opacity: 1; transform: translateY(0); }
+ 80% { opacity: 1; }
+ 100% { opacity: 0; transform: translateY(-10px); }
+}
diff --git a/internal/web/templates/index.html b/internal/web/templates/index.html
new file mode 100644
index 0000000..cdd49ea
--- /dev/null
+++ b/internal/web/templates/index.html
@@ -0,0 +1,271 @@
+<!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>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>">
+</head>
+<body>
+ <header class="header">
+ <a href="/" class="header-brand">
+ <span class="logo">🦧</span>
+ <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>
+ <button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme (T)">◐</button>
+ </nav>
+ </header>
+
+ <main class="main">
+ <!-- Stats Section -->
+ <section class="section">
+ <div class="stats-bar">
+ <div class="stat-card">
+ <div class="stat-icon">📊</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>
+ <span class="stat-value online">{{.Stats.Online}}</span>
+ <span class="stat-label">Online</span>
+ </div>
+ <div class="stat-card">
+ <div class="stat-icon">⚪</div>
+ <span class="stat-value">{{.Stats.Offline}}</span>
+ <span class="stat-label">Offline</span>
+ </div>
+ <div class="stat-card">
+ <div class="stat-icon">🌐</div>
+ <span class="stat-value">{{len .Networks}}</span>
+ <span class="stat-label">Networks</span>
+ </div>
+ </div>
+ </section>
+
+ <!-- Networks Section -->
+ <section class="section">
+ <h2 class="section-title">Networks</h2>
+ <div class="network-cards">
+ {{range .Networks}}
+ <div class="card network-card {{if .IsTailscale}}tailscale{{end}}">
+ <div class="card-header">
+ <span class="network-name">{{.FriendlyName}}</span>
+ <span class="status-badge online">Active</span>
+ </div>
+ <div class="card-body">
+ <div class="network-detail">
+ <span class="label">Network</span>
+ <span class="value">{{.CIDR}}</span>
+ </div>
+ <div class="network-detail">
+ <span class="label">Interface</span>
+ <span class="value">{{.Interface}}</span>
+ </div>
+ <div class="network-detail">
+ <span class="label">Your IP</span>
+ <span class="value">{{.IP}}</span>
+ </div>
+ </div>
+ <div class="card-footer">
+ <button class="btn btn-primary btn-sm" onclick="scanNetwork('{{.CIDR}}')">Scan Network</button>
+ </div>
+ </div>
+ {{end}}
+
+ {{if and .Tailscale.Installed .Tailscale.Running}}
+ <div class="card network-card tailscale">
+ <div class="card-header">
+ <span class="network-name">Tailscale VPN</span>
+ <span class="status-badge online">Connected</span>
+ </div>
+ <div class="card-body">
+ {{if .Tailscale.SelfIP}}
+ <div class="network-detail">
+ <span class="label">Your IP</span>
+ <span class="value">{{.Tailscale.SelfIP}}</span>
+ </div>
+ {{end}}
+ <div class="network-detail">
+ <span class="label">Peers</span>
+ <span class="value">{{.Tailscale.PeerCount}} devices</span>
+ </div>
+ </div>
+ </div>
+ {{end}}
+ </div>
+ </section>
+
+ <!-- Devices Section -->
+ <section class="section">
+ <div class="section-header">
+ <h2 class="section-title">Discovered Devices</h2>
+ <div class="section-actions">
+ <div class="auto-refresh">
+ <span>Auto-refresh</span>
+ <div class="toggle-switch" id="auto-refresh-toggle" onclick="toggleAutoRefresh()"></div>
+ </div>
+ <input type="text" id="device-search" class="input search-input" placeholder="Search devices..." oninput="filterDevices()">
+ <select id="device-filter" class="select" style="width:auto" onchange="filterDevices()">
+ <option value="all">All Status</option>
+ <option value="online">Online</option>
+ <option value="offline">Offline</option>
+ </select>
+ <select id="group-filter" class="select" style="width:auto" onchange="filterDevices()">
+ <option value="all">All Groups</option>
+ <option value="Server">Server</option>
+ <option value="Desktop">Desktop</option>
+ <option value="Laptop">Laptop</option>
+ <option value="Mobile">Mobile</option>
+ <option value="IoT">IoT</option>
+ <option value="Network">Network</option>
+ <option value="Pi">Pi</option>
+ </select>
+ <div class="dropdown">
+ <button class="btn" onclick="toggleDropdown('export-menu')">Export</button>
+ <div id="export-menu" class="dropdown-menu">
+ <a class="dropdown-item" onclick="exportDevices('csv')">Export as CSV</a>
+ <a class="dropdown-item" onclick="exportDevices('json')">Export as JSON</a>
+ </div>
+ </div>
+ <button class="btn btn-primary" onclick="scanAllNetworks()">Scan All</button>
+ </div>
+ </div>
+
+ <div class="table-container">
+ <div class="table-toolbar">
+ <span class="table-info" id="device-count">Showing {{len .Devices}} devices</span>
+ </div>
+ <table class="table" id="devices-table">
+ <thead>
+ <tr>
+ <th onclick="sortTable('status')">Status <span class="sort-icon">↕</span></th>
+ <th onclick="sortTable('ip')">IP Address <span class="sort-icon">↕</span></th>
+ <th onclick="sortTable('hostname')">Hostname <span class="sort-icon">↕</span></th>
+ <th onclick="sortTable('mac')">MAC Address <span class="sort-icon">↕</span></th>
+ <th onclick="sortTable('vendor')">Vendor <span class="sort-icon">↕</span></th>
+ <th>Label</th>
+ <th>Group</th>
+ <th onclick="sortTable('lastseen')">Last Seen <span class="sort-icon">↕</span></th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody id="devices-tbody">
+ {{range .Devices}}
+ <tr class="device-row {{.StatusClass}}"
+ data-ip="{{.IP}}"
+ data-hostname="{{lower .Hostname}}"
+ data-mac="{{lower .MAC}}"
+ data-vendor="{{lower .Vendor}}"
+ data-label="{{lower .Label}}"
+ data-label-original="{{.Label}}"
+ data-notes="{{.Notes}}"
+ data-group="{{.Group}}"
+ data-status="{{.Status}}"
+ data-lastseen="{{.LastSeenUnix}}">
+ <td>
+ <span class="status-indicator {{.StatusClass}}"></span>
+ </td>
+ <td class="ip-cell">
+ <span class="copyable" onclick="copyToClipboard('{{.IP}}', event)" title="Click to copy">{{.IP}}</span>
+ </td>
+ <td class="hostname-cell">{{if .Hostname}}{{.Hostname}}{{else}}<span style="color:var(--text-muted)">-</span>{{end}}</td>
+ <td class="mac-cell">
+ {{if .MAC}}<span class="copyable" onclick="copyToClipboard('{{.MAC}}', event)" title="Click to copy">{{.MAC}}</span>{{else}}<span style="color:var(--text-muted)">-</span>{{end}}
+ </td>
+ <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>
+ <select class="group-select" data-ip="{{.IP}}" onchange="updateDeviceGroup(this)">
+ <option value="">-</option>
+ <option value="Server" {{if eq .Group "Server"}}selected{{end}}>Server</option>
+ <option value="Desktop" {{if eq .Group "Desktop"}}selected{{end}}>Desktop</option>
+ <option value="Laptop" {{if eq .Group "Laptop"}}selected{{end}}>Laptop</option>
+ <option value="Mobile" {{if eq .Group "Mobile"}}selected{{end}}>Mobile</option>
+ <option value="IoT" {{if eq .Group "IoT"}}selected{{end}}>IoT</option>
+ <option value="Network" {{if eq .Group "Network"}}selected{{end}}>Network</option>
+ <option value="Pi" {{if eq .Group "Pi"}}selected{{end}}>Pi</option>
+ </select>
+ </td>
+ <td class="time-cell">{{.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>
+ </td>
+ </tr>
+ {{end}}
+ </tbody>
+ </table>
+ </div>
+ {{if not .Devices}}
+ <div class="empty-state">
+ <div class="empty-state-icon">🔍</div>
+ <h3>No devices discovered yet</h3>
+ <p>Click "Scan All" to discover devices on your network.</p>
+ </div>
+ {{end}}
+ </section>
+ </main>
+
+ <!-- Edit Modal -->
+ <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" placeholder="Add notes about this device..."></textarea>
+ </div>
+ </form>
+ </div>
+ <div class="modal-footer">
+ <button class="btn" onclick="closeModal()">Cancel</button>
+ <button class="btn btn-primary" onclick="saveDevice()">Save Changes</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 network...</span>
+ </div>
+
+ <footer class="footer">
+ <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>
+
+ <script src="/static/app.js"></script>
+</body>
+</html>
diff --git a/internal/web/templates/settings.html b/internal/web/templates/settings.html
new file mode 100644
index 0000000..2701f39
--- /dev/null
+++ b/internal/web/templates/settings.html
@@ -0,0 +1,142 @@
+<!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>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>">
+</head>
+<body>
+ <header class="header">
+ <a href="/" class="header-brand">
+ <span class="logo">🦧</span>
+ <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>
+ <button class="theme-toggle" onclick="toggleTheme()" title="Toggle theme">◐</button>
+ </nav>
+ </header>
+
+ <main class="main">
+ {{if .Error}}
+ <div class="alert alert-error">{{.Error}}</div>
+ {{end}}
+
+ <section class="section">
+ <h2 class="section-title">System Information</h2>
+ <div class="card">
+ <div class="status-row">
+ <span class="status-label">Version:</span>
+ <span class="status-value">{{if .Version}}{{.Version}}{{else}}dev{{end}}</span>
+ </div>
+ <div class="status-row">
+ <span class="status-label">Total Devices:</span>
+ <span class="status-value">{{.Stats.Total}}</span>
+ </div>
+ <div class="status-row">
+ <span class="status-label">Online:</span>
+ <span class="status-value online">{{.Stats.Online}}</span>
+ </div>
+ <div class="status-row">
+ <span class="status-label">Offline:</span>
+ <span class="status-value">{{.Stats.Offline}}</span>
+ </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>
+ {{if .Tailscale.Running}}
+ <span class="status-value online">✓ Connected</span>
+ {{else if .Tailscale.Installed}}
+ <span class="status-value offline">✗ Disconnected</span>
+ {{else}}
+ <span class="status-value warning">Not Installed</span>
+ {{end}}
+ </div>
+ {{if .Tailscale.SelfIP}}
+ <div class="status-row">
+ <span class="status-label">IP:</span>
+ <span class="status-value">{{.Tailscale.SelfIP}}</span>
+ </div>
+ {{end}}
+ {{if .Tailscale.SelfHostname}}
+ <div class="status-row">
+ <span class="status-label">Hostname:</span>
+ <span class="status-value">{{.Tailscale.SelfHostname}}</span>
+ </div>
+ {{end}}
+ {{if .Tailscale.Running}}
+ <div class="status-row">
+ <span class="status-label">Peers:</span>
+ <span class="status-value">{{.Tailscale.PeerCount}}</span>
+ </div>
+ {{end}}
+ </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" {{if eq .Theme "light"}}checked{{end}} onchange="setTheme('light')"> Light
+ </label>
+ <label class="radio-label">
+ <input type="radio" name="theme" value="dark" {{if eq .Theme "dark"}}checked{{end}} onchange="setTheme('dark')"> Dark
+ </label>
+ <label class="radio-label">
+ <input type="radio" name="theme" value="auto" {{if eq .Theme "auto"}}checked{{end}} onchange="setTheme('auto')"> Auto
+ </label>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="section">
+ <h2 class="section-title">Data Management</h2>
+ <div class="card">
+ <div class="form-group">
+ <button class="btn btn-primary" onclick="exportDevices()">Export Devices (CSV)</button>
+ <p class="form-help">Download all device data as a CSV file.</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="section">
+ <h2 class="section-title">About</h2>
+ <div class="card">
+ <p>LAN Orangutan is a network discovery and monitoring tool that helps you keep track of devices on your local network.</p>
+ <p style="margin-top: 1rem;">
+ <a href="https://github.com/291-Group/LAN-Orangutan" target="_blank">GitHub</a> ·
+ <a href="https://291group.com" target="_blank">291 Group</a>
+ </p>
+ </div>
+ </section>
+ </main>
+
+ <footer class="footer">
+ <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);
+ }
+
+ function exportDevices() {
+ window.location.href = '/api/devices?format=csv';
+ }
+ </script>
+</body>
+</html>
diff --git a/scanner/requirements.txt b/scanner/requirements.txt
new file mode 100644
index 0000000..218f8b5
--- /dev/null
+++ b/scanner/requirements.txt
@@ -0,0 +1,2 @@
+# LAN Orangutan Scanner Dependencies
+# Uses Python standard library - no external dependencies required
diff --git a/scanner/scan.py b/scanner/scan.py
new file mode 100755
index 0000000..9b8838d
--- /dev/null
+++ b/scanner/scan.py
@@ -0,0 +1,318 @@
+#!/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
new file mode 100755
index 0000000..8550b19
--- /dev/null
+++ b/scanner/utils.py
@@ -0,0 +1,255 @@
+#!/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/start-server.sh b/scripts/start-server.sh
new file mode 100755
index 0000000..cf1d32f
--- /dev/null
+++ b/scripts/start-server.sh
@@ -0,0 +1,30 @@
+#!/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/snap/snapcraft.yaml b/snap/snapcraft.yaml
new file mode 100644
index 0000000..274549b
--- /dev/null
+++ b/snap/snapcraft.yaml
@@ -0,0 +1,58 @@
+name: lan-orangutan
+base: core22
+version: git
+summary: Network discovery and device tracking tool
+description: |
+ LAN Orangutan is a lightweight network discovery and device tracking tool
+ with a web dashboard and CLI. Discover devices on your local network,
+ track online/offline status, and organize with labels and groups.
+
+ Features:
+ - Automatic network device discovery using nmap
+ - Web dashboard for viewing and managing devices
+ - CLI for scripting and automation
+ - Device labeling and grouping
+ - Tailscale integration
+
+grade: stable
+confinement: strict
+
+architectures:
+ - build-on: amd64
+ - build-on: arm64
+
+apps:
+ lan-orangutan:
+ command: bin/orangutan
+ plugs:
+ - network
+ - network-bind
+ - network-observe
+ daemon: simple
+ restart-condition: on-failure
+
+ cli:
+ command: bin/orangutan
+ plugs:
+ - network
+ - network-observe
+
+parts:
+ orangutan:
+ plugin: go
+ source: .
+ build-snaps:
+ - go/1.22/stable
+ override-build: |
+ go build -ldflags="-s -w" -o $SNAPCRAFT_PART_INSTALL/bin/orangutan ./cmd/orangutan
+
+ nmap:
+ plugin: nil
+ stage-packages:
+ - nmap
+
+layout:
+ /etc/lan-orangutan:
+ bind: $SNAP_DATA/config
+ /var/lib/lan-orangutan:
+ bind: $SNAP_DATA/data
diff --git a/systemd/lan-orangutan.service b/systemd/lan-orangutan.service
new file mode 100644
index 0000000..46212de
--- /dev/null
+++ b/systemd/lan-orangutan.service
@@ -0,0 +1,24 @@
+[Unit]
+Description=LAN Orangutan Network Discovery
+Documentation=https://github.com/291-Group/LAN-Orangutan
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=root
+Group=root
+WorkingDirectory=/opt/lan-orangutan
+ExecStart=/opt/lan-orangutan/scripts/start-server.sh
+Restart=on-failure
+RestartSec=10
+StandardOutput=journal
+StandardError=journal
+NoNewPrivileges=true
+ProtectSystem=strict
+ProtectHome=true
+ReadWritePaths=/var/lib/lan-orangutan /etc/lan-orangutan
+PrivateTmp=true
+
+[Install]
+WantedBy=multi-user.target
diff --git a/uninstall.sh b/uninstall.sh
new file mode 100755
index 0000000..6ee15c1
--- /dev/null
+++ b/uninstall.sh
@@ -0,0 +1,57 @@
+#!/bin/bash
+set -e
+
+INSTALL_DIR="/opt/lan-orangutan"
+CONFIG_DIR="/etc/lan-orangutan"
+DATA_DIR="/var/lib/lan-orangutan"
+SERVICE_NAME="lan-orangutan"
+
+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 "================================"
+echo ""
+
+# Read configured port before removing config (for firewall cleanup)
+CONFIGURED_PORT=""
+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
+[[ ! "$confirm" =~ ^[Yy]$ ]] && { echo "Aborted."; exit 0; }
+
+# Stop service
+systemctl stop "$SERVICE_NAME" 2>/dev/null || true
+systemctl disable "$SERVICE_NAME" 2>/dev/null || true
+rm -f /etc/systemd/system/lan-orangutan.service
+systemctl daemon-reload
+echo -e "${GREEN}✓${NC} Service removed"
+
+# Remove files
+rm -f /usr/local/bin/orangutan
+rm -rf "$INSTALL_DIR"
+rm -rf "$CONFIG_DIR"
+echo -e "${GREEN}✓${NC} Files removed"
+
+# Data
+read -p "Remove device data ($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
+if command -v ufw &>/dev/null; then
+ ufw delete allow 291/tcp 2>/dev/null || true
+ ufw delete allow 2910/tcp 2>/dev/null || true
+ ufw delete allow 8090/tcp 2>/dev/null || true
+ # Also remove custom configured port if different from defaults
+ if [[ -n "$CONFIGURED_PORT" ]] && [[ "$CONFIGURED_PORT" != "291" ]] && [[ "$CONFIGURED_PORT" != "2910" ]] && [[ "$CONFIGURED_PORT" != "8090" ]]; then
+ ufw delete allow "$CONFIGURED_PORT/tcp" 2>/dev/null || true
+ fi
+fi
+
+echo ""
+echo -e "${GREEN}🦧 LAN Orangutan uninstalled${NC}"
+echo ""
diff --git a/web/api.php b/web/api.php
new file mode 100644
index 0000000..63566e1
--- /dev/null
+++ b/web/api.php
@@ -0,0 +1,333 @@
+<?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
new file mode 100644
index 0000000..8251412
--- /dev/null
+++ b/web/assets/app.js
@@ -0,0 +1,172 @@
+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
new file mode 100644
index 0000000..156d467
--- /dev/null
+++ b/web/assets/orangutan.svg
@@ -0,0 +1,23 @@
+<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
new file mode 100644
index 0000000..969c407
--- /dev/null
+++ b/web/assets/style.css
@@ -0,0 +1,141 @@
+: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
new file mode 100644
index 0000000..bed0e0b
--- /dev/null
+++ b/web/index.php
@@ -0,0 +1,264 @@
+<?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
new file mode 100644
index 0000000..7184b72
--- /dev/null
+++ b/web/settings.php
@@ -0,0 +1,270 @@
+<?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>