From fda3ea9799a7638114e59b2354468a67e5b5d301 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:46:23 +0330 Subject: [PATCH] refactor: clarify service boundaries and unify project tooling --- .github/workflows/checks.yml | 5 +- AGENTS.md | 22 +- CHANGELOG.md | 13 + CONTRIBUTING.md | 18 +- Makefile | 61 +++- README.md | 94 ++--- SECURITY.md | 13 +- cmd/routershelf-smb/main.go | 104 ------ cmd/routershelf-smb/service.go | 91 +++++ cmd/routershelf-smb/storage.go | 47 +++ cmd/routershelf/listener.go | 27 ++ cmd/routershelf/main.go | 343 +++--------------- docs/architecture.md | 45 +-- docs/examples/status-dashboard.md | 4 +- docs/getting-started.md | 9 +- docs/operations.md | 2 +- docs/smb.md | 2 +- go.mod | 6 +- internal/smbwire/UPSTREAM.md | 2 + .../smbwire/{routershelf.go => access.go} | 0 .../{routershelf_test.go => policy_test.go} | 0 internal/web/doc.go | 4 + internal/web/handler.go | 143 ++++++++ .../web/handler_test.go | 38 +- internal/web/listing.go | 49 +++ internal/web/redirect.go | 29 ++ internal/web/static.go | 64 ++++ .../web}/static_test.go | 6 +- project.json | 7 +- scripts/check_repository.py | 67 ++++ scripts/tests/test_repository.py | 56 +++ 31 files changed, 832 insertions(+), 539 deletions(-) create mode 100644 cmd/routershelf-smb/service.go create mode 100644 cmd/routershelf-smb/storage.go create mode 100644 cmd/routershelf/listener.go rename internal/smbwire/{routershelf.go => access.go} (100%) rename internal/smbwire/{routershelf_test.go => policy_test.go} (100%) create mode 100644 internal/web/doc.go create mode 100644 internal/web/handler.go rename cmd/routershelf/main_test.go => internal/web/handler_test.go (64%) create mode 100644 internal/web/listing.go create mode 100644 internal/web/redirect.go create mode 100644 internal/web/static.go rename {cmd/routershelf => internal/web}/static_test.go (98%) create mode 100644 scripts/check_repository.py create mode 100644 scripts/tests/test_repository.py diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 30f06a2..df73028 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -12,6 +12,5 @@ jobs: - uses: actions/setup-go@v5 with: go-version: '1.26.x' - - run: make test - - run: make build-mipsle build-smb-mipsle - - run: go test -race ./cmd/routershelf-smb ./internal/smbwire + - run: make check + - run: make build build-router diff --git a/AGENTS.md b/AGENTS.md index 620d33b..14b152d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ These instructions apply to the entire repository. Read any more specific `AGENT ## Project and entry points -RouterShelf is a read-only Go HTTP/HTTPS server for USB storage on constrained Linux routers. It provides NAIS directory listings and static pages from the **same shared root**. The original deployment used Padavan-derived firmware and a MikroTik gateway; this is not universal firmware support. +RouterShelf has independent Go services for public read-only HTTP/HTTPS and private authenticated SMB storage on constrained Linux routers. The web service provides NAIS directory listings and static pages from the **same shared root**. The original deployment used Padavan-derived firmware and a MikroTik gateway; this is not universal firmware support. Read the relevant guide before changing a component: @@ -17,11 +17,14 @@ Read the relevant guide before changing a component: ## Repository layout -- `cmd/routershelf/`: application, environment/flag parsing, handler and configuration tests. -- `cmd/routershelf-smb/`, `internal/smbwire/`: independent private SMB executable and adapted Apache-2.0 protocol implementation. Read `docs/smb.md`, `docs/smb-implementation.md`, `docs/smb-validation.md` and `internal/smbwire/UPSTREAM.md` before changing it; preserve license/provenance. +- `cmd/routershelf/`: web process startup, TLS, bounded listeners, environment/flag parsing and configuration tests. +- `internal/web/`: public HTTP handlers, listings, static-file policy, redirect and behavior tests. +- `cmd/routershelf-smb/`: independent private SMB executable; `main.go` owns CLI/runtime setup, `config.go` private JSON validation, `service.go` serving/storage monitoring, and `storage.go` mount/privilege operations. +- `internal/smbwire/`: adapted Apache-2.0 protocol implementation. Read `docs/smb.md`, `docs/smb-implementation.md`, `docs/smb-validation.md` and `internal/smbwire/UPSTREAM.md` before changing it; preserve license/provenance. - `internal/theme/assets.go`: embeds assets under `internal/theme/nais/`. - `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle. - `scripts/nat-plan.sh`: prints gateway configuration guidance; it does not modify the gateway. +- `scripts/check_repository.py`: checks Git-visible source paths, local documentation links and service metadata without opening ignored private files. - `scripts/stress_test.py` and `scripts/tests/`: bounded load runner and localhost-only runner tests. Read `docs/stress-testing.md`; writing/editing the tool does not imply permission to load a live target. - `.env.example`: tracked configuration template; `.env` is private and ignored. - `examples/status-dashboard/`: independent historical BusyBox/Netcat example, with its guide in `docs/examples/`. Do not expose it using the public server's NAT rules. @@ -57,7 +60,10 @@ Preserve these unless the user explicitly requests a change: Run from the repository root using Go 1.26 or a newer toolchain verified against the target kernel: ```sh -make test # shell syntax, config validation, Python runner tests, Go tests +make test # shell/config checks, Python tool tests, Go tests +make check # test plus format, docs/hygiene, vet and race checks +make build # both native executables under dist/ +make build-router # both static MIPS little-endian soft-float executables make test-stress-tool # Python localhost-only tests; no live-router requests make check-shell # syntax only; does not execute deployment make check-config # side-effect-free validation using .env.example @@ -84,6 +90,12 @@ Before publishing or refreshing a public archive, exclude private env, keys, cac ## SMB independence -Keep SMB JSON/account/source policy and supervision independent of the web env, domain, certificates, public NAT and compatibility paths. SMB is experimental until actual native Finder and target checks are observed. Run `make build-smb-mipsle` in addition to the web build and SMB race tests for relevant changes. NT hashes are password-equivalent secrets; never publish actual configs. Only localhost native-client tests are implicitly part of local validation; target writes/execution require authorization. +Keep SMB JSON/account/source policy and supervision independent of the web env, domain, certificates, public NAT and compatibility paths. SMB remains experimental; docs/smb-validation.md records observed native Finder/target smoke checks and unperformed failure/load/reboot checks. Run `make build-smb-mipsle` in addition to the web build and SMB race tests for relevant changes. NT hashes are password-equivalent secrets; never publish actual configs. Only localhost native-client tests are implicitly part of local validation; target writes/execution require authorization. Explicit SMB disk-root sharing requires `allow_storage_root`, deliberate public-overlap acknowledgment, and descriptor-safe protected-path exclusions. Preserve alias/ancestor-rename protection; a lexical path filter alone is insufficient. Record observed exFAT timestamp limitations without raising process privileges or acknowledging metadata changes that did not occur. + +## Structural maintenance + +Keep the commands independent. Public HTTP behavior and its tests belong in `internal/web`; startup and configuration stay command-local. Avoid shared privilege/config/supervisor abstractions where ordering and policy differ. Retain upstream SMB source and tests together for auditability; local policy helpers are in `access.go` with regression coverage in `policy_test.go`. Preserve renamed-source provenance in UPSTREAM.md. + +CI runs `make check` and `make build build-router`. Existing per-service build targets remain compatible. There is no automatic deployment or release workflow. Follow CONTRIBUTING.md for reviewed source exports; a hygiene check does not replace a secret/content review. Never delete ignored private files, outputs or user data as a repository cleanup. diff --git a/CHANGELOG.md b/CHANGELOG.md index 982eb32..2eaac5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## Unreleased +### Structure and maintenance + +- Separate public HTTP behavior/tests into `internal/web`, with command-local startup and configuration. +- Organize SMB CLI, service loop and storage/privilege operations into focused command-local files; name local protocol policy helpers by responsibility. +- Add shared local/CI check targets, native and combined router builds, and public-source/documentation consistency checks. +- Clarify independent setup paths and current validation limits. CLI, configuration formats and deployed installation paths remain compatible. + +### Private SMB + +- Add the independent experimental authenticated SMB executable, private JSON configuration and USB-aware supervisor. +- Support explicit read-only/read-write sharing, signed sessions and an opt-in protected disk-root view. +- Record local/native and authorized target smoke results, exFAT timestamp limitations and remaining failure/load/reboot checks. + ### Stress testing - Added a bounded read-only Python runner with phased concurrency, rate caps, optional router telemetry and stop thresholds. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 00d8cf4..43a7c4d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,11 +2,11 @@ ## Development -Use Go 1.26 or a newer toolchain verified against the target kernel, and Python 3.10+ for the stress-runner tests. From the repository root, run `make test` and `make build-mipsle`. Keep changes focused and describe user-visible behavior and validation. A desktop cross-build proves compilation, not target-kernel compatibility or successful boot persistence. +Use Go 1.26 or a newer toolchain verified against the target kernel, and Python 3.10+ for the stress-runner tests. From the repository root, run `make check` and `make build build-router`. Keep changes focused and describe user-visible behavior and validation. A desktop cross-build proves compilation, not target-kernel compatibility or successful boot persistence. -Application changes belong in `cmd/routershelf`. Theme changes belong in `internal/theme/nais`; retain the upstream license and document local adaptations. Padavan-specific lifecycle rules belong in `deploy/padavan`. Keep the legacy status dashboard independent under `examples/status-dashboard`. +HTTP response behavior and its tests belong in `internal/web`; web process startup/configuration belongs in `cmd/routershelf`. SMB startup/configuration/storage monitoring stays in `cmd/routershelf-smb`, separate from its adapted protocol implementation in `internal/smbwire`. Theme changes belong in `internal/theme/nais`; retain the upstream license and document local adaptations. Padavan-specific lifecycle rules belong in `deploy/padavan`. Keep the legacy status dashboard independent under `examples/status-dashboard`. -Run `--check-config` against a private env to validate without touching firewall, processes, or the disk. Do not run deployment scripts on a device merely to test formatting. Inspect the real mount, firewall, interface names, and firmware hooks before any target installation. The example supervisor is administrator-controlled shell code, not an untrusted input format. +Run the web supervisor’s `--check-config` against a trusted private env to validate without touching firewall, processes, or the disk. Do not run deployment scripts on a device merely to test formatting. Inspect the real mount, firewall, interface names, and firmware hooks before any target installation. The example supervisor is administrator-controlled shell code, not an untrusted input format. ## Verification @@ -18,7 +18,7 @@ Record which checks actually ran. Do not claim a reboot or certificate renewal p Never attach private keys, certificate caches, full router exports, USB files, usernames/passwords, public-IP deployment values, or unredacted logs/screenshots. Use the example subnet, documentation IP range, and `files.example.com` in public issues. A sanitized minimal configuration is more useful than a full device dump. -Before the first publication, review staged files and metadata, configure the actual Git remote, and replace publication placeholders where needed. There is no automatic deploy or publish action in this project. +Before publication, review staged files and metadata and verify the intended repository identity. There is no automatic deploy or publish action in this project. Stress-runner changes should be tested with `make test-stress-tool` against localhost and synthetic telemetry, not by loading the live deployment. Only run a live workload when requested, with the target and bounds clear. See [stress testing](docs/stress-testing.md). @@ -26,4 +26,12 @@ Stress-runner changes should be tested with `make test-stress-tool` against loca Keep `cmd/routershelf-smb` independent of web configuration/certificates/public exposure. Protocol code in `internal/smbwire` is an adapted Apache-2.0 dependency; preserve its license, provenance and adaptation inventory. Run `make test`, `go test -race ./cmd/routershelf-smb ./internal/smbwire`, and `make build-mipsle build-smb-mipsle`. Add meaningful authentication/signing, read-only, confinement, sharing/locking, file mutation, interruption and bounded-resource tests for affected behavior. Never replace disk metadata with successful volatile writes. -Native macOS checks are opt-in: build the desktop SMB executable and run `python3 -B scripts/test_smb_macos.py /absolute/path/to/routershelf-smb`; it mounts only a temporary localhost share with synthetic credentials. Repeat with `--read-only` to check native mutation refusals. Native Finder GUI, actual exFAT, router kernel, resource/coexistence, USB loss, reboot and interrupted native-client tests are separate checks and must be recorded honestly. Read-only router inspection does not authorize executing a new binary or writing test data there. Keep real `smb.json`, hashes and logs private. +Native macOS checks are opt-in: use `make build` to build the desktop SMB executable and run `python3 -B scripts/test_smb_macos.py /absolute/path/to/routershelf-smb`; it mounts only a temporary localhost share with synthetic credentials. Repeat with `--read-only` to check native mutation refusals and `--disk-root` for the explicit protected root view. Native Finder GUI, actual exFAT, router kernel, resource/coexistence, USB loss, reboot and interrupted native-client tests are separate checks and must be recorded honestly. Read-only router inspection does not authorize executing a new binary or writing test data there. Keep real `smb.json`, hashes and logs private. + +## Local workflow and source distribution + +`make test` runs the routine suite, including localhost stress-runner tests and disposable-Git-tree checks for the repository checker. `make check` adds formatting, Git-visible path/documentation/metadata checks, `go vet`, and race tests for all packages; CI uses the same target. `make build` builds both native commands, and `make build-router` builds both static Linux/MIPS LE soft-float commands. The original per-service cross-build targets remain available. Native macOS mounting and any live/device checks are opt-in and separate from CI. + +Builds and diagnostics belong in ignored `dist/` and `outputs/`. Do not delete private settings, operator notes or data during cleanup. Keep the useful standalone dashboard tutorial under `examples/`; it is not a third RouterShelf service. No dependency update is implied by structural refactoring. + +For an authorized source export, review a committed revision with `git ls-tree -r --name-only REVISION`, including templates, licenses and third-party notices. Export that reviewed revision with `git archive`; do not zip the working directory. `git archive` excludes untracked/ignored data but still includes any secrets committed in that revision, so review contents before sharing. Build outputs are packaged separately only when a binary distribution is requested, with all applicable project, embedded-source and pinned-module licenses. See [third-party notices](THIRD_PARTY_NOTICES.md). No release packaging or publication is performed by a build target. diff --git a/Makefile b/Makefile index 771bf21..8ac5d2b 100644 --- a/Makefile +++ b/Makefile @@ -1,22 +1,52 @@ GO ?= go PYTHON ?= python3 -BINARY := dist/routershelf-linux-mipsle +SERVICES := routershelf routershelf-smb +HOST_BINARIES := $(addprefix dist/,$(SERVICES)) +MIPS_BINARIES := $(addsuffix -linux-mipsle,$(HOST_BINARIES)) -.PHONY: test build-mipsle check-shell check-config nat-plan test-stress-tool build-smb-mipsle +.PHONY: test check check-shell check-config check-format check-docs vet test-race test-repository \ + build build-mipsle build-smb-mipsle build-router nat-plan test-stress-tool -test: check-shell check-config test-stress-tool +test: check-shell check-config test-stress-tool test-repository $(GO) test ./... -check-shell: - sh -n deploy/padavan/supervisor.example.sh - sh -n deploy/padavan/smb-supervisor.example.sh - sh -n scripts/nat-plan.sh - sh -n examples/status-dashboard/scripts/status-service.sh - sh -n examples/status-dashboard/scripts/status-response.sh +# CI and the local full check use the same commands. No deployment is performed. +check: test check-format check-docs vet test-race -build-mipsle: - mkdir -p dist - GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o $(BINARY) ./cmd/routershelf +check-shell: + @for script in deploy/padavan/*.sh scripts/*.sh examples/status-dashboard/scripts/*.sh examples/status-dashboard/config.example.sh; do \ + sh -n "$$script" || exit; \ + done + +check-format: + @unformatted=$$(gofmt -l cmd internal) && { test -z "$$unformatted" || { echo "Run go fmt ./...: $$unformatted"; exit 1; }; } + +check-docs: + $(PYTHON) -B scripts/check_repository.py + +vet: + $(GO) vet ./... + +test-race: + $(GO) test -race ./... + +# Native executables are useful for local development and macOS client checks. +build: $(HOST_BINARIES) + +# Preserve the existing per-service targets and artifact names. +build-mipsle: dist/routershelf-linux-mipsle +build-smb-mipsle: dist/routershelf-smb-linux-mipsle +build-router: $(MIPS_BINARIES) + +# Always rebuild: a package depends on embedded assets and transitive sources. +.PHONY: $(HOST_BINARIES) $(MIPS_BINARIES) +$(HOST_BINARIES): + @mkdir -p dist + CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o $@ ./cmd/$(notdir $@) + +$(MIPS_BINARIES): dist/%-linux-mipsle: + @mkdir -p dist + GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o $@ ./cmd/$* check-config: ROUTERSHELF_ENV_FILE="$(CURDIR)/.env.example" sh deploy/padavan/supervisor.example.sh --check-config @@ -25,8 +55,7 @@ nat-plan: sh scripts/nat-plan.sh test-stress-tool: - $(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_*.py' -v + $(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_stress_test.py' -v -build-smb-mipsle: - mkdir -p dist - GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o dist/routershelf-smb-linux-mipsle ./cmd/routershelf-smb +test-repository: + $(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_repository.py' -v diff --git a/README.md b/README.md index 643d7c0..21adbc4 100644 --- a/README.md +++ b/README.md @@ -1,85 +1,63 @@ # RouterShelf -**USB file sharing for small Linux routers: public read-only web access and optional private Finder access over SMB.** +USB file sharing for small Linux routers, with two independently runnable Go services: -RouterShelf serves a chosen directory with a dark [NAIS](https://github.com/meghdadfadaee/nais) listing, file downloads, copied links, and DPL playlists. It uses a small Go executable, automatic Let's Encrypt certificates, and an optional Padavan-style supervisor. A MikroTik gateway provides public port forwarding and LAN hairpin access. +| Service | Access | Start here | +| --- | --- | --- | +| `routershelf` | Public, unauthenticated, read-only HTTP/HTTPS | [Web setup](docs/getting-started.md) | +| `routershelf-smb` | Private, authenticated SMB for Finder; read-only by default, optional writes | [SMB setup](docs/smb.md) | -This repository includes the implementation and the practical guide for configuring, operating, backing up, and removing it. It also preserves an earlier LAN status-dashboard experiment as a standalone example. +Run either service or both. SMB requires no web configuration, public domain, or certificates. Each service has its own configuration, account policy, supervisor, and update/recovery procedure. -RouterShelf is one product with two independently runnable executables. The web service remains public, unauthenticated and read-only. The new experimental `routershelf-smb` service provides authenticated browsing and optional file management through Finder, without a web domain or certificates. +The web service provides [NAIS](https://github.com/meghdadfadaee/nais) directory listings, downloads, copied links, DPL playlists, static pages, HEAD/byte ranges, and automatic HTTPS for one hostname. The experimental SMB service lets Finder browse and manage explicitly selected storage using macOS's built-in client. -For private Finder access, start with the [SMB guide](docs/smb.md), [implementation decision](docs/smb-implementation.md), and [validation limits](docs/smb-validation.md). +**The web root is public.** HTTPS protects transport but adds no authentication. Keep private SMB folders separate by default; deliberately overlapping storage can publish uploaded content immediately. Read [security boundaries](SECURITY.md) before installation. -## Capabilities +## Setup and operation -- Directory navigation and file downloads, with HEAD and byte-range support. -- Static pages from the same root: automatic `index.html` and inline HTML/CSS/JavaScript/assets. -- Automatic HTTPS for one configured hostname; HTTP challenge handling and HTTPS redirects. -- Embedded theme assets; no nginx, PHP runtime, database, or frontend build required. -- GET/HEAD only, hidden-path filtering, escaped filenames, and filesystem root confinement. -- Optional independent SMB executable with signed authentication, explicit folder selection and read-only/read-write modes. -- Optional USB-aware restart supervision and dedicated IPv4/IPv6 firewall rules on the tested firmware. +For web sharing, follow [network and storage preparation](docs/network-and-storage.md), then [installation](docs/getting-started.md). Configure a private copy of [`.env.example`](.env.example); [configuration](docs/configuration.md) covers environment values, flags and reload. The [operations guide](docs/operations.md) covers health checks, troubleshooting, updates, rollback and removal. [Static pages](docs/static-pages.md) explains index precedence and inline assets. -The public file service has **no authentication**. HTTPS protects transport; every file placed in the shared directory is available to anyone who can reach the service. Read [security boundaries](SECURITY.md) before deploying. +For Finder, follow the [SMB guide](docs/smb.md): build, choose storage, create credentials, configure a private copy of [`.smb.example.json`](.smb.example.json), and install its independent supervisor. The same guide covers permissions, status, troubleshooting, updates and removal. SMB is private by default and must not inherit public web forwarding. -## Get started +The Padavan deployment examples are optional and firmware-specific. A gateway such as MikroTik can forward public HTTP/HTTPS; a gateway is not needed for local SMB. No runtime, compiler, package installation, or shared library is required on the router. -1. Read the [network and storage guide](docs/network-and-storage.md) to identify the gateway, service host, USB mount, and access accounts. -2. Follow [installation and HTTPS setup](docs/getting-started.md), replacing every example value with private deployment settings. -3. Use the [operations guide](docs/operations.md) for health checks, backups, updates, rollback, and removal. +## Development -Build and test from the repository root: +Use Go 1.26 and Python 3.10+ on the development computer. From the repository root: ```sh -make test -make build-mipsle -make build-smb-mipsle # optional independent Finder service +make test # Go tests, shell/config checks, Python tool tests +make check # Also formatting, docs/source hygiene, vet and race tests +make build # Native dist/routershelf and dist/routershelf-smb +make build-router # Both static Linux/MIPS LE soft-float executables ``` -The cross-build writes `dist/routershelf-linux-mipsle`. The deployment guide explains its installed filename and router paths. Configure deployment without editing source or supervisor code: +The existing `make build-mipsle` and `make build-smb-mipsle` targets remain available independently. Builds go under ignored `dist/`; private configurations and local reports stay ignored. Nothing here deploys automatically. See [contributing](CONTRIBUTING.md) for validation, native-client checks and distribution guidance. -```sh -cp .env.example .env -# Edit .env privately, then validate it and print the gateway plan. -ROUTERSHELF_ENV_FILE="$PWD/.env" sh deploy/padavan/supervisor.example.sh --check-config -make nat-plan -``` - -Read [environment configuration](docs/configuration.md) for available values, precedence, installation, and reloading. `.env` is ignored by Git; `.env.example` is tracked. Gateway changes are still applied manually from the printed plan. - -See [static-page behavior](docs/static-pages.md) for index precedence and supported assets. - -Use the [stress-test guide](docs/stress-testing.md) for bounded load phases, router telemetry and private reports. The runner uses Python 3.10+ with no third-party packages. - -## Repository layout +## Code and documentation ```text -cmd/routershelf/ HTTP/HTTPS application and behavior tests -cmd/routershelf-smb/ Independent private SMB executable and config tests -internal/smbwire/ Adapted Apache-2.0 SMB protocol source and tests -internal/theme/nais/ Licensed NAIS assets embedded in the executable -internal/theme/assets.go Asset embedding boundary -deploy/padavan/ Environment-driven firmware supervisor -examples/status-dashboard/ Separate legacy BusyBox/Netcat dashboard -docs/ Setup, operations, architecture, and deployment history -.github/ CI and issue/pull-request templates -scripts/nat-plan.sh Gateway plan derived from private environment -.env.example Public web configuration template -.smb.example.json Public SMB template; real credentials stay private -Makefile Local checks and MIPS little-endian build -project.json Project identity and compatibility metadata +cmd/routershelf/ Web configuration, startup, TLS and connection limits +cmd/routershelf-smb/ SMB configuration, startup and storage supervision +internal/web/ Public HTTP handlers, listings, static files and tests +internal/theme/ Embedded NAIS assets and their license +internal/smbwire/ Adapted SMB protocol implementation, license and tests +deploy/padavan/ Independent firmware supervisor examples +scripts/ Local checks, gateway planning and test tools +docs/ User guides, architecture and validation records +examples/ Separate historical LAN status-dashboard tutorial ``` -See [architecture](docs/architecture.md) for the separation between application, theme, firmware, and gateway responsibilities. The [deployment history](docs/deployment-history.md) records work completed on the original hardware and what remains unverified. The [status dashboard tutorial](docs/examples/status-dashboard.md) describes the earlier LAN-only example; it is not the public HTTPS server. +Read [architecture](docs/architecture.md) for responsibilities and dependency boundaries. [Web deployment history](docs/deployment-history.md) and [SMB validation](docs/smb-validation.md) distinguish observed results from remaining hardware checks. The [SMB implementation decision](docs/smb-implementation.md) records backend tradeoffs and maintenance obligations. [Stress testing](docs/stress-testing.md) describes the opt-in bounded load tool; local tests do not authorize live load. -## Compatibility and validation +## Compatibility and limitations -The original deployment used a Neterbit NW-651D with Padavan-derived firmware, Linux 3.4.113, BusyBox 1.24.2, about 128 MiB RAM, and a MIPS little-endian CPU. Its gateway was a MikroTik LHG5 running RouterOS 6.49.22. The tested compiler was Go 1.26.5. Other router firmware, CPU architectures, and newer toolchains require target testing. +Observed target: Padavan-derived firmware, MediaTek MT7621 MIPS little-endian, Linux 3.4.113, BusyBox 1.24.2, approximately 128 MiB RAM, no swap, and exFAT USB storage. The recorded toolchain is Go 1.26.5. Other firmware, architectures and toolchains require target testing. -On the original device, HTTPS issuance, trusted downloads, HTTP redirects, read-only access checks, theme rendering, and a playlist download were checked. Full reboot, future certificate renewal, sustained load, and authenticated FTP transfer were not verified. The environment-driven supervisor is validated separately; hardware validation is recorded in the deployment history. +Web HTTPS and read-only operations have been observed on that target. SMB authentication, protected disk-root access, small checksum-verified transfers, Finder copy/Quick Look and independent restart have also been observed. exFAT refused arbitrary timestamp restoration by the non-root SMB account. SMB remains experimental; full reboot, USB-loss recovery, large native transfers, complete Mac metadata compatibility and sustained combined load remain unverified. Compilation and desktop tests alone do not prove device compatibility. -## Contributing and publishing +## License and distribution -Read [CONTRIBUTING.md](CONTRIBUTING.md). Keep deployment configuration, certificate caches, keys, router exports, USB data, logs, and generated binaries out of Git. All tracked deployment examples use placeholder values. This local repository has no configured remote and has not been published. +RouterShelf project code is [MIT licensed](LICENSE). Embedded SMB code retains [Apache-2.0](internal/smbwire/LICENSE); NAIS retains its [MIT license](internal/theme/nais/LICENSE). Preserve [third-party notices](THIRD_PARTY_NOTICES.md) and module license obligations when distributing. -Project code is [MIT licensed](LICENSE); the embedded SMB implementation retains its [Apache-2.0 license](internal/smbwire/LICENSE). NAIS retains its [upstream MIT license](internal/theme/nais/LICENSE). Dependency and theme attribution is collected in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). +Keep configuration, NT hashes, passwords, certificates, router exports, USB data and diagnostics out of source archives. Read [contribution and distribution guidance](CONTRIBUTING.md) before sharing source or binaries. Project identity and compatibility metadata are in [project.json](project.json); no remote or release is assumed. diff --git a/SECURITY.md b/SECURITY.md index c549e90..73c3a0d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,17 +1,12 @@ # RouterShelf security boundaries -## Original LAN status dashboard - -The BusyBox/Netcat example has no authentication or TLS and runs with the SSH account's privileges. It is suitable only for a trusted, firewall-restricted LAN. Its paths are fixed and never evaluated as shell input, but serial Netcat handling and per-line reads can be monopolized by a hostile client. Do not expose it through WAN forwarding or a public tunnel. This dashboard was removed from the original router. - -Configuration is administrator-controlled shell code. Confirm command lines before trusting PID files. Firewall changes are not transactional; verify them after updates and never flush unrelated rules. - ## Public directory server Public access is intentionally unauthenticated and read-only. HTTPS encrypts transport; it does not restrict who may download the files. All current and future content in the selected root, including filenames and directory structure, is public. - Only GET/HEAD are accepted. HTML and recognized web assets are served inline with MIME sniffing disabled; other files remain attachment downloads. This is not an upload API or a server-side application runtime. - `os.OpenRoot` constrains file access; dot-prefixed paths, traversal components, escaping symlinks, and nonregular files are rejected/omitted. Hidden files are not a substitute for storing secrets outside the root. +- Existing filesystem edge case: regular-file validation happens after opening. On filesystems that support named pipes, a pipe can block the request before it is rejected. Keep special files out of the public root; the observed exFAT target does not support creating these Unix file types. This requires a separate behavior/security fix. - The application drops privileges to UID/GID 65534. The custom `/_nais/` namespace serves only administrator-embedded theme assets; user files never become executable theme scripts. - The HTTP fallback redirects to a fixed domain. ACME certificate issuance is limited to the configured domain. TLS validation remains enabled for outbound CA access. - Timeouts, connection bounds, a listing cap, and a Go memory target reduce resource consumption but are not a complete denial-of-service defense or hard quota. Large traffic can overwhelm a small router or home uplink. @@ -36,3 +31,9 @@ Private JSON contains a password-equivalent NT hash: require protected file mode Server-local locks do not coordinate FTP/SFTP/local writers or multiple independent SMB processes. Interrupted writes can leave partial files; exFAT/power loss has no transactional recovery guarantee. Back up data, preserve sources and verify transfers before replacement. Bounds and the Go memory target cannot prevent all resource exhaustion. This backend needs independent security review and target validation before stronger support claims. See [SMB security and limitations](docs/smb.md#privacy-and-filesystem-behavior). An explicitly enabled disk-root SMB view keeps mandatory service directories and configured protected subtrees hidden and inaccessible. Parent descriptors are pinned with os.Root; symlinks and hard-linked regular files are refused in that view, and protected ancestors cannot be renamed/deleted. `allow_storage_root` and public-overlap acknowledgment are required; default private-folder policy remains unchanged. This application boundary does not isolate secrets from other broadly authorized exFAT accounts. + +## Original LAN status dashboard + +The BusyBox/Netcat example has no authentication or TLS and runs with the SSH account's privileges. It is suitable only for a trusted, firewall-restricted LAN. Its paths are fixed and never evaluated as shell input, but serial Netcat handling and per-line reads can be monopolized by a hostile client. Do not expose it through WAN forwarding or a public tunnel. This dashboard was removed from the original router. + +Configuration is administrator-controlled shell code. Confirm command lines before trusting PID files. Firewall changes are not transactional; verify them after updates and never flush unrelated rules. diff --git a/cmd/routershelf-smb/main.go b/cmd/routershelf-smb/main.go index bcb5677..4fd41cd 100644 --- a/cmd/routershelf-smb/main.go +++ b/cmd/routershelf-smb/main.go @@ -1,126 +1,22 @@ -// routershelf-smb is an independent private file service. It never changes -// firewall, routing, firmware settings, or the web service. package main import ( - "bufio" "context" "encoding/hex" "errors" "fmt" "io" "log" - "net" "os" "os/signal" "runtime" "runtime/debug" "strings" "syscall" - "time" smb "routershelf/internal/smbwire" ) -func mounted(path string) bool { - if runtime.GOOS != "linux" { - return true - } - f, err := os.Open("/proc/mounts") - if err != nil { - return false - } - defer f.Close() - sc := bufio.NewScanner(f) - for sc.Scan() { - v := strings.Fields(sc.Text()) - if len(v) > 1 { - p := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(v[1]) - if p == path { - return true - } - } - } - return false -} -func drop(c config) error { - if os.Geteuid() != 0 { - if os.Geteuid() != c.UID || os.Getegid() != c.GID { - return errors.New("run as configured uid/gid or start as root to bind and drop privileges") - } - return nil - } - if err := syscall.Setgroups([]int{}); err != nil { - return err - } - if err := syscall.Setgid(c.GID); err != nil { - return err - } - return syscall.Setuid(c.UID) -} -func serve(ctx context.Context, c config) error { - if !mounted(c.Mount) { - return errors.New("expected USB mount is unavailable; refusing underlying mount directory") - } - initial, err := os.Stat(c.Root) - if err != nil { - return errors.New("share unavailable") - } - ln, err := net.Listen("tcp4", c.Listen) - if err != nil { - return errors.New("cannot bind SMB listener; check address, privileges and existing SMB services") - } - defer ln.Close() - if err := drop(c); err != nil { - return fmt.Errorf("cannot drop SMB privileges: %w", err) - } - // Confirm the dropped account can read this directory before announcing ready. - d, err := os.Open(c.Root) - if err != nil { - return errors.New("share is unreadable by configured account") - } - _, err = d.Readdirnames(1) - d.Close() - if err != nil && err != io.EOF { - return errors.New("share cannot be listed") - } - ctx, cancel := context.WithCancel(ctx) - defer cancel() - lost := make(chan struct{}) - go func() { - ticker := time.NewTicker(2 * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - current, err := os.Stat(c.Root) - if err != nil || !os.SameFile(initial, current) || !mounted(c.Mount) { - close(lost) - cancel() - return - } - } - } - }() - var diagnostic func(string, ...any) - if c.Diagnostics { - diagnostic = log.Printf - } - err = smb.Serve(ctx, ln, smb.Config{ProtectedPaths: c.protectedRelative, ExpectedRoot: initial, Ready: func() { - log.Print("SMB ready; authenticated signing required; read_only=", c.ReadOnly) - if c.ready != nil { - c.ready() - } - }, Logf: diagnostic, Root: c.Root, Share: c.Share, User: c.User, NTHash: c.ntHash, Allow: c.prefixes, ReadOnly: c.ReadOnly, DiskMetadata: true, CaseInsensitive: c.CaseInsensitive}) - select { - case <-lost: - return errors.New("USB storage disappeared or changed; sessions closed; reconnect after storage recovers") - default: - return err - } -} func run() error { if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help" || os.Args[1] == "-help") { fmt.Println("RouterShelf SMB (experimental)\nUsage: routershelf-smb -config /absolute/private/smb.json [-check-config]\n routershelf-smb -hash-password < password-from-hidden-prompt\nRS_SMB_CONFIG supplies the default config path. No web configuration is required.\nSee docs/smb.md for Finder setup, permissions, updates and recovery.") diff --git a/cmd/routershelf-smb/service.go b/cmd/routershelf-smb/service.go new file mode 100644 index 0000000..661a90b --- /dev/null +++ b/cmd/routershelf-smb/service.go @@ -0,0 +1,91 @@ +package main + +import ( + "context" + "errors" + "fmt" + "io" + "log" + "net" + "os" + "time" + + smb "routershelf/internal/smbwire" +) + +func serve(ctx context.Context, c config) error { + if !mounted(c.Mount) { + return errors.New("expected USB mount is unavailable; refusing underlying mount directory") + } + initial, err := os.Stat(c.Root) + if err != nil { + return errors.New("share unavailable") + } + ln, err := net.Listen("tcp4", c.Listen) + if err != nil { + return errors.New("cannot bind SMB listener; check address, privileges and existing SMB services") + } + defer ln.Close() + if err := drop(c); err != nil { + return fmt.Errorf("cannot drop SMB privileges: %w", err) + } + // Confirm the dropped account can read this directory before announcing ready. + d, err := os.Open(c.Root) + if err != nil { + return errors.New("share is unreadable by configured account") + } + _, err = d.Readdirnames(1) + d.Close() + if err != nil && err != io.EOF { + return errors.New("share cannot be listed") + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + lost := make(chan struct{}) + go func() { + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + current, err := os.Stat(c.Root) + if err != nil || !os.SameFile(initial, current) || !mounted(c.Mount) { + close(lost) + cancel() + return + } + } + } + }() + var diagnostic func(string, ...any) + if c.Diagnostics { + diagnostic = log.Printf + } + err = smb.Serve(ctx, ln, smb.Config{ + ProtectedPaths: c.protectedRelative, + ExpectedRoot: initial, + Ready: func() { + log.Print("SMB ready; authenticated signing required; read_only=", c.ReadOnly) + if c.ready != nil { + c.ready() + } + }, + Logf: diagnostic, + Root: c.Root, + Share: c.Share, + User: c.User, + NTHash: c.ntHash, + Allow: c.prefixes, + ReadOnly: c.ReadOnly, + DiskMetadata: true, + CaseInsensitive: c.CaseInsensitive, + }) + select { + case <-lost: + return errors.New("USB storage disappeared or changed; sessions closed; reconnect after storage recovers") + default: + return err + } +} diff --git a/cmd/routershelf-smb/storage.go b/cmd/routershelf-smb/storage.go new file mode 100644 index 0000000..cfc1494 --- /dev/null +++ b/cmd/routershelf-smb/storage.go @@ -0,0 +1,47 @@ +package main + +import ( + "bufio" + "errors" + "os" + "runtime" + "strings" + "syscall" +) + +func mounted(path string) bool { + if runtime.GOOS != "linux" { + return true + } + f, err := os.Open("/proc/mounts") + if err != nil { + return false + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + v := strings.Fields(sc.Text()) + if len(v) > 1 { + p := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(v[1]) + if p == path { + return true + } + } + } + return false +} +func drop(c config) error { + if os.Geteuid() != 0 { + if os.Geteuid() != c.UID || os.Getegid() != c.GID { + return errors.New("run as configured uid/gid or start as root to bind and drop privileges") + } + return nil + } + if err := syscall.Setgroups([]int{}); err != nil { + return err + } + if err := syscall.Setgid(c.GID); err != nil { + return err + } + return syscall.Setuid(c.UID) +} diff --git a/cmd/routershelf/listener.go b/cmd/routershelf/listener.go new file mode 100644 index 0000000..41b74fd --- /dev/null +++ b/cmd/routershelf/listener.go @@ -0,0 +1,27 @@ +package main + +import ( + "net" + "sync" +) + +type boundedListener struct { + net.Listener + slots chan struct{} +} +type boundedConn struct { + net.Conn + release func() + once sync.Once +} + +func (c *boundedConn) Close() error { err := c.Conn.Close(); c.once.Do(c.release); return err } +func (l *boundedListener) Accept() (net.Conn, error) { + l.slots <- struct{}{} + c, e := l.Listener.Accept() + if e != nil { + <-l.slots + return nil, e + } + return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil +} diff --git a/cmd/routershelf/main.go b/cmd/routershelf/main.go index f9a6849..d8cf85c 100644 --- a/cmd/routershelf/main.go +++ b/cmd/routershelf/main.go @@ -1,338 +1,81 @@ package main import ( - "bytes" "crypto/tls" - "fmt" - "html/template" - "io" "log" - "mime" "net" "net/http" - "net/url" "os" - "path" - "sort" - "strings" - "sync" "syscall" "time" "golang.org/x/crypto/acme/autocert" - "routershelf/internal/theme" + "routershelf/internal/web" ) -type entry struct { - Name, Size, Modified string - Link template.URL - Dir bool - Inline bool -} -type page struct { - Path string - Parent template.URL - Entries []entry - Truncated bool -} - -var listing = template.Must(template.New("listing").Parse(`
{{if .Parent}}../
-{{end}}{{range .Entries}}{{.Name}}{{if .Dir}}/{{end}} {{.Modified}} {{.Size}}
-{{else}}This folder is empty.
-{{end}}{{if .Truncated}}Only the first 5,000 entries are displayed.
-{{end}}`))
-
-func escapedPath(p string) template.URL {
- parts := strings.Split(p, "/")
- for i := range parts {
- parts[i] = url.PathEscape(parts[i])
- }
- return template.URL(strings.Join(parts, "/"))
-}
-func sizeLabel(n int64) string {
- if n < 1024 {
- return fmt.Sprintf("%d B", n)
- }
- for _, u := range []struct {
- n int64
- s string
- }{{1 << 30, "GiB"}, {1 << 20, "MiB"}, {1 << 10, "KiB"}} {
- if n >= u.n {
- return fmt.Sprintf("%.1f %s", float64(n)/float64(u.n), u.s)
- }
- }
- return ""
-}
-func handler(rootPath string) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("X-Content-Type-Options", "nosniff")
- w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; script-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'")
- w.Header().Set("Referrer-Policy", "no-referrer")
- if r.Method != http.MethodGet && r.Method != http.MethodHead {
- w.Header().Set("Allow", "GET, HEAD")
- http.Error(w, "Read-only service", 405)
- return
- }
- if strings.HasPrefix(r.URL.Path, "/_nais/") {
- name := strings.TrimPrefix(r.URL.Path, "/_nais/")
- types := map[string]string{"autoindex.css": "text/css; charset=utf-8", "autoindex.js": "text/javascript; charset=utf-8", "favicon.ico": "image/x-icon", "favicon.png": "image/png"}
- contentType, ok := types[name]
- if !ok {
- http.NotFound(w, r)
- return
- }
- data, err := theme.Files.ReadFile("nais/" + name)
- if err != nil {
- http.NotFound(w, r)
- return
- }
- w.Header().Set("Content-Type", contentType)
- w.Header().Set("Cache-Control", "no-cache")
- http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(data))
- return
- }
- p := r.URL.Path
- if strings.ContainsAny(p, "\\\x00\r\n") {
- http.Error(w, "Invalid path", 400)
- return
- }
- for _, part := range strings.Split(p, "/") {
- if strings.HasPrefix(part, ".") {
- http.NotFound(w, r)
- return
- }
- }
- name := strings.TrimPrefix(p, "/")
- if name == "" {
- name = "."
- }
- root, err := os.OpenRoot(rootPath)
- if err != nil {
- http.Error(w, "Storage unavailable", 503)
- return
- }
- defer root.Close()
- f, err := root.Open(name)
- if err != nil {
- http.NotFound(w, r)
- return
- }
- defer f.Close()
- info, err := f.Stat()
- if err != nil {
- http.NotFound(w, r)
- return
- }
- if info.IsDir() {
- if !strings.HasSuffix(p, "/") {
- http.Redirect(w, r, string(escapedPath(p+"/")), 301)
- return
- }
- index, indexErr := root.Open(path.Join(name, "index.html"))
- if indexErr == nil {
- defer index.Close()
- indexInfo, statErr := index.Stat()
- if statErr == nil && indexInfo.Mode().IsRegular() {
- serveFile(w, r, "index.html", indexInfo, index)
- return
- }
- }
- rows, err := f.ReadDir(5000)
- if err != nil && err != io.EOF {
- http.Error(w, "Cannot list folder", 500)
- return
- }
- pg := page{Path: p, Truncated: len(rows) == 5000}
- if p != "/" {
- parent := path.Dir(strings.TrimSuffix(p, "/"))
- if parent != "/" {
- parent += "/"
- }
- pg.Parent = escapedPath(parent)
- }
- for _, row := range rows {
- if strings.HasPrefix(row.Name(), ".") {
- continue
- }
- st, err := root.Stat(path.Join(name, row.Name()))
- if err != nil || (!st.IsDir() && !st.Mode().IsRegular()) {
- continue
- }
- link := p + row.Name()
- label := sizeLabel(st.Size())
- if st.IsDir() {
- link += "/"
- label = "—"
- }
- pg.Entries = append(pg.Entries, entry{Name: row.Name(), Size: label, Modified: st.ModTime().UTC().Format("2006-01-02 15:04 UTC"), Link: escapedPath(link), Dir: st.IsDir(), Inline: inlineType(row.Name()) != ""})
- }
- sort.Slice(pg.Entries, func(i, j int) bool {
- if pg.Entries[i].Dir != pg.Entries[j].Dir {
- return pg.Entries[i].Dir
- }
- return pg.Entries[i].Name < pg.Entries[j].Name
- })
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.Header().Set("Cache-Control", "no-store")
- if r.Method == http.MethodGet {
- if err := listing.Execute(w, pg); err != nil {
- log.Print("listing response interrupted")
- }
- }
- return
- }
- if !info.Mode().IsRegular() {
- http.NotFound(w, r)
- return
- }
- serveFile(w, r, name, info, f)
- })
-}
-
-type boundedListener struct {
- net.Listener
- slots chan struct{}
-}
-type boundedConn struct {
- net.Conn
- release func()
- once sync.Once
-}
-
-func (c *boundedConn) Close() error { err := c.Conn.Close(); c.once.Do(c.release); return err }
-func (l *boundedListener) Accept() (net.Conn, error) {
- l.slots <- struct{}{}
- c, e := l.Listener.Accept()
- if e != nil {
- <-l.slots
- return nil, e
- }
- return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil
-}
func main() {
cfg, err := parseConfig(os.Args[1:])
if err != nil {
log.Fatal(err)
}
- root, addr, domain, httpAddr, cache, drop := &cfg.root, &cfg.listen, &cfg.domain, &cfg.httpListen, &cfg.certCache, &cfg.drop
- r, e := os.OpenRoot(*root)
- if e != nil {
+ root, err := os.OpenRoot(cfg.root)
+ if err != nil {
log.Fatal("public directory unavailable")
}
- r.Close()
- if *drop {
- if e = syscall.Setgroups([]int{}); e != nil {
- log.Fatal(e)
+ root.Close()
+ if cfg.drop {
+ if err = syscall.Setgroups([]int{}); err != nil {
+ log.Fatal(err)
}
- if e = syscall.Setgid(65534); e != nil {
- log.Fatal(e)
+ if err = syscall.Setgid(65534); err != nil {
+ log.Fatal(err)
}
- if e = syscall.Setuid(65534); e != nil {
- log.Fatal(e)
+ if err = syscall.Setuid(65534); err != nil {
+ log.Fatal(err)
}
}
- l, e := net.Listen("tcp4", *addr)
- if e != nil {
- log.Fatal(e)
+ listener, err := net.Listen("tcp4", cfg.listen)
+ if err != nil {
+ log.Fatal(err)
}
- contentHandler := handler(*root)
+ contentHandler := web.Handler(cfg.root)
var manager *autocert.Manager
- if *domain != "" {
- if *cache == "" {
+ if cfg.domain != "" {
+ if cfg.certCache == "" {
log.Fatal("-cert-cache is required for HTTPS")
}
- manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(*domain), Cache: autocert.DirCache(*cache)}
- redirect := redirectHandler(*domain)
- hl, err := net.Listen("tcp4", *httpAddr)
+ manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(cfg.domain), Cache: autocert.DirCache(cfg.certCache)}
+ redirect := web.RedirectHandler(cfg.domain)
+ httpListener, err := net.Listen("tcp4", cfg.httpListen)
if err != nil {
log.Fatal(err)
}
- hs := &http.Server{Handler: manager.HTTPHandler(redirect), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 16 * 1024}
- go func() { log.Fatal(hs.Serve(&boundedListener{hl, make(chan struct{}, 16)})) }()
+ challengeServer := &http.Server{
+ Handler: manager.HTTPHandler(redirect),
+ ReadHeaderTimeout: 5 * time.Second,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 15 * time.Second,
+ IdleTimeout: 15 * time.Second,
+ MaxHeaderBytes: 16 * 1024,
+ }
+ go func() { log.Fatal(challengeServer.Serve(&boundedListener{httpListener, make(chan struct{}, 16)})) }()
}
- s := &http.Server{Handler: contentHandler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Minute, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 16 * 1024}
- log.Printf("Read-only public directory listening on %s (domain=%s)", *addr, *domain)
+ server := &http.Server{
+ Handler: contentHandler,
+ ReadHeaderTimeout: 5 * time.Second,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 15 * time.Minute,
+ IdleTimeout: 15 * time.Second,
+ MaxHeaderBytes: 16 * 1024,
+ }
+ log.Printf("Read-only public directory listening on %s (domain=%s)", cfg.listen, cfg.domain)
if manager != nil {
- s.TLSConfig = manager.TLSConfig()
- s.TLSConfig.MinVersion = tls.VersionTLS12
+ server.TLSConfig = manager.TLSConfig()
+ server.TLSConfig.MinVersion = tls.VersionTLS12
// HTTP/1.1 plus ACME ALPN; bound connections remain effective for all clients.
- s.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"}
- log.Fatal(s.ServeTLS(&boundedListener{l, make(chan struct{}, 32)}, "", ""))
+ server.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"}
+ log.Fatal(server.ServeTLS(&boundedListener{listener, make(chan struct{}, 32)}, "", ""))
}
- log.Fatal(s.Serve(&boundedListener{l, make(chan struct{}, 32)}))
-}
-
-func redirectHandler(domain string) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- host := r.Host
- if h, _, err := net.SplitHostPort(host); err == nil {
- host = h
- }
- if !strings.EqualFold(host, domain) {
- http.Error(w, "Unknown host", http.StatusMisdirectedRequest)
- return
- }
- if r.Method != http.MethodGet && r.Method != http.MethodHead {
- w.Header().Set("Allow", "GET, HEAD")
- http.Error(w, "Read-only service", 405)
- return
- }
- target := url.URL{Scheme: "https", Host: domain, Path: r.URL.Path, RawPath: r.URL.RawPath, RawQuery: r.URL.RawQuery}
- http.Redirect(w, r, target.String(), http.StatusPermanentRedirect)
- })
-}
-
-// Static assets are identified explicitly; unrecognized files remain downloads.
-func inlineType(name string) string {
- switch strings.ToLower(path.Ext(name)) {
- case ".html", ".htm":
- return "text/html; charset=utf-8"
- case ".css":
- return "text/css; charset=utf-8"
- case ".js", ".mjs":
- return "text/javascript; charset=utf-8"
- case ".json", ".map":
- return "application/json"
- case ".png":
- return "image/png"
- case ".jpg", ".jpeg":
- return "image/jpeg"
- case ".gif":
- return "image/gif"
- case ".webp":
- return "image/webp"
- case ".avif":
- return "image/avif"
- case ".svg":
- return "image/svg+xml"
- case ".ico":
- return "image/x-icon"
- case ".woff":
- return "font/woff"
- case ".woff2":
- return "font/woff2"
- case ".ttf":
- return "font/ttf"
- case ".otf":
- return "font/otf"
- case ".wasm":
- return "application/wasm"
- default:
- return ""
- }
-}
-func serveFile(w http.ResponseWriter, r *http.Request, name string, info os.FileInfo, f io.ReadSeeker) {
- contentType := inlineType(name)
- if contentType == "" {
- w.Header().Set("Content-Type", "application/octet-stream")
- w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": info.Name()}))
- } else {
- w.Header().Set("Content-Type", contentType)
- w.Header().Del("Content-Disposition")
- // Published static pages may use inline scripts/styles and external assets.
- // Directory listings retain their stricter policy; no server-side code runs.
- w.Header().Set("Content-Security-Policy", "object-src 'none'; frame-ancestors 'none'; base-uri 'self'")
- }
- http.ServeContent(w, r, info.Name(), info.ModTime(), f)
+ log.Fatal(server.Serve(&boundedListener{listener, make(chan struct{}, 32)}))
}
diff --git a/docs/architecture.md b/docs/architecture.md
index 90b8239..8ce35a3 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,35 +1,38 @@
# Architecture
-RouterShelf has independent web and SMB service executables within these operational layers:
+RouterShelf is one Go module with two independent commands. Each owns its configuration and process lifecycle. Small command-local files keep startup concerns together; only the HTTP response layer and the substantial SMB protocol implementation need separate internal packages.
-| Layer | Responsibility | Repository location |
+| Component | Responsibility | Location |
| --- | --- | --- |
-| Go application | Safe directory reads, HTTP responses, TLS and ACME, connection limits, privilege drop | `cmd/routershelf` |
-| Private SMB application | Independent account/config, selected root, signed SMB, write policy and privilege drop | `cmd/routershelf-smb`, `internal/smbwire` |
-| Embedded theme | NAIS styling, favicon, copied links, playlist generation | `internal/theme` |
-| Router lifecycle | USB checks, process restart, time startup, host firewall hooks, flash persistence | `deploy/padavan` |
-| Network gateway | Public DNS destination, destination NAT, LAN hairpin reply routing | Configuration documented in `docs/getting-started.md` |
+| Web command | Environment/flag validation, privilege drop, listeners, connection bounds, TLS and ACME | `cmd/routershelf` |
+| Public HTTP | Filesystem confinement, methods, listings, static pages, download headers and HTTPS redirects | `internal/web` |
+| Embedded theme | NAIS CSS/JavaScript, favicon, copied links and playlists | `internal/theme` |
+| SMB command | Private JSON validation, credentials CLI, listener/privilege setup, mount/root monitoring | `cmd/routershelf-smb` |
+| SMB protocol | Authentication, signing, permissions, bounded operations, locks and protected storage view | `internal/smbwire` |
+| Router lifecycle | Independently runnable firmware supervisors; web firewall/time hooks | `deploy/padavan` |
+| Gateway planning | Print administrator-reviewed public web NAT guidance; never apply it | `scripts/nat-plan.sh` |
+
+## Dependencies and access policy
```text
-Browser -> gateway TCP 80/443 -> storage host TCP 10080/10443
- |
- RouterShelf
- / \
- shared directory private ACME cache
- |
- USB filesystem
+routershelf command -> internal/web -> internal/theme
+ -> x/crypto/acme/autocert
+
+routershelf-smb command -> internal/smbwire -> x/crypto, x/sys
```
-The gateway plan is generated from `.env` by `scripts/nat-plan.sh`, rather than auto-applied: changing a gateway requires matching its actual interfaces, existing NAT/filter rules, and public address. The Go application does not change routing, configure DHCP, or provision FTP accounts.
+Neither executable imports the other service. There is no shared configuration or lifecycle abstraction: web environment/shell policy and SMB protected JSON have different compatibility and trust contracts. Similar-looking privilege handling also has different ordering: web drops before binding unprivileged ports; SMB binds its private listener before dropping so it can use TCP 445.
-The `deploy/padavan` script loads a private environment file for one firmware family. Its installed names remain `public-share-service.sh`, `public-directory`, and `/tmp/public-share-*` for compatibility with the existing deployed system and instructions. Renaming the repository is not a live-router migration.
+The HTTP handler opens an `os.Root` per request and preserves current removable-storage behavior. SMB pins its selected root for a session-serving lifetime and exits when mount/root identity changes. Its protected disk-root view adds descriptor-based exclusions; see the [adaptation inventory](../internal/smbwire/UPSTREAM.md). Both may use the same physical disk, so resource pressure and explicitly overlapping data remain shared operational risks.
-The legacy dashboard is a separate Netcat/shell example, with its own configuration and security assumptions. Its code remains in `examples/status-dashboard` and its guide in `docs/examples/status-dashboard.md`. It was removed from the original router and must never inherit the public server's port-forwarding policy.
+## Deployment boundaries
-The Go module path is currently `routershelf`, a local standalone module identity. If a real repository remote is established later, change the module path and the `routershelf/internal/theme` import together if a hosted module path is desired. No remote namespace is assumed.
+Public web traffic can follow `Browser -> gateway TCP 80/443 -> storage-host HTTP/HTTPS listeners`. Certificate/account cache, binary and configuration belong outside the public root. The [configuration reference](configuration.md) describes the environment contract.
-Read [setup](getting-started.md), [operations](operations.md), and [security](../SECURITY.md) for configuration and maintenance boundaries.
+Private access follows `Finder -> specific private IPv4 SMB listener -> selected USB directory`. It requires no domain, certificates, NTP startup or gateway forwarding. The SMB supervisor uses its own executable/config paths and `/tmp/routershelf-smb/` lock. It does not source the web environment, change firewall rules or signal the web service. Administrators restrict the listener with their own service-scoped firewall policy; see [SMB setup](smb.md).
-## Independent private SMB path
+The web supervisor's installed compatibility names remain `public-share-service.sh`, `public-directory` and `/tmp/public-share-*`. Repository organization does not migrate deployed installations. Padavan hooks, flash persistence and BusyBox details remain platform-specific and should not become application responsibilities. The Go commands do not provision DHCP, alter routing/NAT or create FTP accounts.
-`Finder -> specific private IPv4 SMB listener -> os.Root selected private USB folder`. This path needs no web server, certificates, NTP startup or gateway NAT. The SMB supervisor uses its own JSON path, executable, process tree and `/tmp/routershelf-smb/` lock. It never sources the web environment, changes firewall rules or signals the web service. The web binary does not import SMB code. Both may access USB storage, so resource pressure and deliberately overlapping data remain shared operational risks. See [SMB setup and lifecycle](smb.md) and [implementation decision](smb-implementation.md).
+The module path remains `routershelf`; no hosted namespace is assumed. The [legacy dashboard](../examples/status-dashboard/README.md) is a standalone historical tutorial with separate security assumptions and no Go dependency. It must not inherit public forwarding.
+
+Read [web setup](getting-started.md), [web operation](operations.md), [SMB setup and operation](smb.md), and [security](../SECURITY.md) for user procedures. Validation history records observations; it is not the installation source of truth.
diff --git a/docs/examples/status-dashboard.md b/docs/examples/status-dashboard.md
index 1fbc2f1..720bf94 100644
--- a/docs/examples/status-dashboard.md
+++ b/docs/examples/status-dashboard.md
@@ -14,7 +14,7 @@ LAN browser -> router TCP port 8080 -> Netcat -> shell request handler
+-> HTTP headers + HTML response
```
-The router's management panel remains on its existing port. The new service does not change DHCP, routing, Wi-Fi settings, credentials, or the panel. Being in a directory opened by PhpStorm does not mean the router runs PHP.
+The router's management panel remains on its existing port. The new service does not change DHCP, routing, Wi-Fi settings, credentials, or the panel. The handler executes only the installed shell script; it does not run PHP.
The browser requests `/` or `/status`. The handler reads a fixed request path, gathers metrics, sends a response, and exits. Netcat waits for the next client. With no browser open, no periodic probe runs.
@@ -278,7 +278,7 @@ Remove only this project's directory after reviewing its contents, then save sto
- Review `git status` and `git diff --cached` before committing.
- `.gitignore` does not remove files already tracked. If a secret was committed, remove it from history as appropriate and rotate the exposed credential before publishing.
- State compatibility and testing limits honestly. A sample based on one router is not universal support.
-- Choose a license. This project includes MIT; review that choice before publication.
+- Retain the project MIT license and applicable third-party notices in distributions.
For repository-wide contribution and publication guidance, return to the repository root and read [CONTRIBUTING.md](../../CONTRIBUTING.md). Keep this example under `examples/status-dashboard`; do not initialize a nested Git repository or publish private deployment configuration.
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 3ed3534..39bc166 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -2,7 +2,6 @@
For authenticated Finder access without web setup, follow the independent [SMB installation guide](smb.md). This page installs the public web service.
-
## Architecture and paths
```text
@@ -32,10 +31,8 @@ The certificates directory is private administrative material, despite its locat
Build on a computer with Go, not on the router. The tested build used Go 1.26.5 and pinned dependencies in `go.mod`/`go.sum`. Confirm the current toolchain's compatibility with the target's old kernel before upgrading. The program uses `os.OpenRoot` to enforce the shared-directory boundary.
```sh
-mkdir -p dist
-go test ./...
-GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 \
- go build -trimpath -ldflags='-s -w' -o dist/routershelf-linux-mipsle ./cmd/routershelf
+make test
+make build-mipsle
```
Use `mipsle` only for the matching target CPU. The binary has no PHP, nginx, or dynamically linked runtime requirement. Preserve dependency checksums. Rebuild and test for other devices rather than downloading an arbitrary executable.
@@ -149,7 +146,7 @@ Compare the download with its source. Use normal trusted certificate validation.
The Go executable embeds the theme files under `internal/theme/nais`: `autoindex.css`, `autoindex.js`, and favicons. The listing references them under `/_nais/`. This reproduces the theme without nginx's `sub_filter` or its installer. Folder links remain navigable; regular files carry `data-file="true"` and download attributes. The script uses that marker for copied links and DPL playlists, including extensionless files.
-The bundled integration adjusts row width and the mobile heading, changes the footer to read-only storage, and adds copy feedback/fallback handling. The HTML template escapes names. Assets have explicit MIME types; HTML and recognized CSS/JavaScript/image/font assets are served inline with explicit MIME types; other files use `application/octet-stream` and attachment disposition. A directory with a readable regular `index.html` displays that page instead of its listing. PHP/CGI are not executed. The listing retains its strict CSP; static pages permit inline scripts/styles and external assets, with object embedding and framing blocked.
+The bundled integration adjusts row width and the mobile heading, adds copy feedback, and uses a read-only footer. HTTP listing/rendering lives in `internal/web`; licensed assets remain in `internal/theme/nais`. See [static pages](static-pages.md) for index precedence, inline MIME types, downloads and content policy. These rules apply to the same public root.
To update the style, review upstream changes, copy the intended assets to this source tree, retain the NAIS license, preserve the integration changes, rebuild, and deploy using the rollback procedure. Do not publish the upstream landing page as the directory listing.
diff --git a/docs/operations.md b/docs/operations.md
index c10d746..e230abc 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -2,7 +2,6 @@
This page covers the existing web installation. SMB has separate [status, update, rollback and removal procedures](smb.md#install-status-update-and-remove); stopping or updating one service does not operate the other.
-
## Routine care
| Frequency / event | Check |
@@ -102,6 +101,7 @@ If public access is malfunctioning or unintended, disable the service's TCP 80/4
| Renewal fails | Service downtime, USB/cache unavailable, inaccurate time, old DNS/NAT address, blocked challenge, or CA rate limit |
| Folder/file missing | Wrong root/mount, dot-prefixed name, outside symlink, nonregular file, read permission, or 5,000-entry truncation |
| FTP login works but upload fails | Account path/write permissions, read-only disk, or passive data ports; perform a real upload/download test |
+| Request hangs on a special file | The web handler opens before checking file type; a named pipe can block on filesystems that support it. Keep special files out of the public root; this existing edge case needs a separate fix |
| Style missing | Failed `/_nais/` asset request, MIME/CSP issue, stale browser cache, or binary built without intended assets |
| Copy button reports failure | Browser clipboard permission/support; test paste manually and try a supported secure browser |
| Service returns after stopping child | Expected supervisor restart; stop the parent to stop the whole service |
diff --git a/docs/smb.md b/docs/smb.md
index e6994de..0309863 100644
--- a/docs/smb.md
+++ b/docs/smb.md
@@ -37,7 +37,7 @@ On the development computer, with Go 1.26+:
make test
make build-smb-mipsle
# For a local desktop executable:
-go build -o dist/routershelf-smb ./cmd/routershelf-smb
+make dist/routershelf-smb
umask 077
cp .smb.example.json smb.json
chmod 600 smb.json
diff --git a/go.mod b/go.mod
index 3c5734e..e8dc517 100644
--- a/go.mod
+++ b/go.mod
@@ -2,10 +2,12 @@ module routershelf
go 1.26.0
-require golang.org/x/crypto v0.57.0
+require (
+ golang.org/x/crypto v0.57.0
+ golang.org/x/sys v0.48.0
+)
require (
golang.org/x/net v0.58.0 // indirect
- golang.org/x/sys v0.48.0
golang.org/x/text v0.42.0 // indirect
)
diff --git a/internal/smbwire/UPSTREAM.md b/internal/smbwire/UPSTREAM.md
index ee6297b..ea00295 100644
--- a/internal/smbwire/UPSTREAM.md
+++ b/internal/smbwire/UPSTREAM.md
@@ -16,3 +16,5 @@ Review upstream changes and security issues before updating. Reapply/review each
The initial 16-credit adaptation stalled the native macOS client before mkdir; 128 credits passed the local native smoke check. Credits bound the request window, while the synchronous parser and frame/I/O limits independently bound allocations. Preserve this native-client regression check when tuning credits.
RouterShelf also adds `guarded_root.go` and its tests for explicit disk-root views: protected relative subtrees are hidden/blocked, aliases refused, protected ancestors cannot be renamed/deleted, and parent descriptors are pinned with os.Root. Cross-directory rename and descriptor timestamp operations use BSD-licensed golang.org/x/sys/unix. Default subdirectory shares preserve the original os.Root behavior.
+
+Source organization: RouterShelf-only share/lock helpers live in `access.go` (formerly `routershelf.go`); additional policy tests live in `policy_test.go` (formerly `routershelf_test.go`). Upstream file names and retained tests remain intact. These naming changes do not change the protocol.
diff --git a/internal/smbwire/routershelf.go b/internal/smbwire/access.go
similarity index 100%
rename from internal/smbwire/routershelf.go
rename to internal/smbwire/access.go
diff --git a/internal/smbwire/routershelf_test.go b/internal/smbwire/policy_test.go
similarity index 100%
rename from internal/smbwire/routershelf_test.go
rename to internal/smbwire/policy_test.go
diff --git a/internal/web/doc.go b/internal/web/doc.go
new file mode 100644
index 0000000..96ffacf
--- /dev/null
+++ b/internal/web/doc.go
@@ -0,0 +1,4 @@
+// Package web serves RouterShelf's public, unauthenticated read-only HTTP
+// content. Process startup, TLS certificates and deployment policy belong to
+// the routershelf command and its optional platform supervisor.
+package web
diff --git a/internal/web/handler.go b/internal/web/handler.go
new file mode 100644
index 0000000..94baf57
--- /dev/null
+++ b/internal/web/handler.go
@@ -0,0 +1,143 @@
+package web
+
+import (
+ "bytes"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "path"
+ "sort"
+ "strings"
+ "time"
+
+ "routershelf/internal/theme"
+)
+
+// Handler serves public read-only content from rootPath, reopening the root
+// for each request so removable storage does not retain a stale descriptor.
+func Handler(rootPath string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; script-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ w.Header().Set("Allow", "GET, HEAD")
+ http.Error(w, "Read-only service", 405)
+ return
+ }
+ if strings.HasPrefix(r.URL.Path, "/_nais/") {
+ name := strings.TrimPrefix(r.URL.Path, "/_nais/")
+ types := map[string]string{"autoindex.css": "text/css; charset=utf-8", "autoindex.js": "text/javascript; charset=utf-8", "favicon.ico": "image/x-icon", "favicon.png": "image/png"}
+ contentType, ok := types[name]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ data, err := theme.Files.ReadFile("nais/" + name)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", contentType)
+ w.Header().Set("Cache-Control", "no-cache")
+ http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(data))
+ return
+ }
+ p := r.URL.Path
+ if strings.ContainsAny(p, "\\\x00\r\n") {
+ http.Error(w, "Invalid path", 400)
+ return
+ }
+ for _, part := range strings.Split(p, "/") {
+ if strings.HasPrefix(part, ".") {
+ http.NotFound(w, r)
+ return
+ }
+ }
+ name := strings.TrimPrefix(p, "/")
+ if name == "" {
+ name = "."
+ }
+ root, err := os.OpenRoot(rootPath)
+ if err != nil {
+ http.Error(w, "Storage unavailable", 503)
+ return
+ }
+ defer root.Close()
+ f, err := root.Open(name)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if info.IsDir() {
+ if !strings.HasSuffix(p, "/") {
+ http.Redirect(w, r, string(escapedPath(p+"/")), 301)
+ return
+ }
+ index, indexErr := root.Open(path.Join(name, "index.html"))
+ if indexErr == nil {
+ defer index.Close()
+ indexInfo, statErr := index.Stat()
+ if statErr == nil && indexInfo.Mode().IsRegular() {
+ serveFile(w, r, "index.html", indexInfo, index)
+ return
+ }
+ }
+ rows, err := f.ReadDir(5000)
+ if err != nil && err != io.EOF {
+ http.Error(w, "Cannot list folder", 500)
+ return
+ }
+ pg := page{Path: p, Truncated: len(rows) == 5000}
+ if p != "/" {
+ parent := path.Dir(strings.TrimSuffix(p, "/"))
+ if parent != "/" {
+ parent += "/"
+ }
+ pg.Parent = escapedPath(parent)
+ }
+ for _, row := range rows {
+ if strings.HasPrefix(row.Name(), ".") {
+ continue
+ }
+ st, err := root.Stat(path.Join(name, row.Name()))
+ if err != nil || (!st.IsDir() && !st.Mode().IsRegular()) {
+ continue
+ }
+ link := p + row.Name()
+ label := sizeLabel(st.Size())
+ if st.IsDir() {
+ link += "/"
+ label = "—"
+ }
+ pg.Entries = append(pg.Entries, entry{Name: row.Name(), Size: label, Modified: st.ModTime().UTC().Format("2006-01-02 15:04 UTC"), Link: escapedPath(link), Dir: st.IsDir(), Inline: inlineType(row.Name()) != ""})
+ }
+ sort.Slice(pg.Entries, func(i, j int) bool {
+ if pg.Entries[i].Dir != pg.Entries[j].Dir {
+ return pg.Entries[i].Dir
+ }
+ return pg.Entries[i].Name < pg.Entries[j].Name
+ })
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "no-store")
+ if r.Method == http.MethodGet {
+ if err := listing.Execute(w, pg); err != nil {
+ log.Print("listing response interrupted")
+ }
+ }
+ return
+ }
+ if !info.Mode().IsRegular() {
+ http.NotFound(w, r)
+ return
+ }
+ serveFile(w, r, name, info, f)
+ })
+}
diff --git a/cmd/routershelf/main_test.go b/internal/web/handler_test.go
similarity index 64%
rename from cmd/routershelf/main_test.go
rename to internal/web/handler_test.go
index 1edf6b0..6215e0d 100644
--- a/cmd/routershelf/main_test.go
+++ b/internal/web/handler_test.go
@@ -1,4 +1,4 @@
-package main
+package web
import (
"net/http/httptest"
@@ -17,7 +17,7 @@ func TestFileScopeAndMethods(t *testing.T) {
os.Symlink(outside, filepath.Join(root, "escape.txt"))
os.Mkdir(filepath.Join(root, "sub"), 0700)
os.WriteFile(filepath.Join(root, "<&.txt"), []byte("safe"), 0600)
- h := handler(root)
+ h := Handler(root)
for _, tc := range []struct {
method, url string
code int
@@ -54,7 +54,7 @@ func TestFileScopeAndMethods(t *testing.T) {
}
func TestHTTPSRedirect(t *testing.T) {
- h := redirectHandler("files.example.com")
+ h := RedirectHandler("files.example.com")
for _, tc := range []struct {
target, method string
status int
@@ -71,3 +71,35 @@ func TestHTTPSRedirect(t *testing.T) {
}
}
}
+
+// Exercise the embedding boundary after moving HTTP behavior out of the command.
+func TestEmbeddedAssetsAndReservedNamespace(t *testing.T) {
+ h := Handler(filepath.Join(t.TempDir(), "unavailable-storage"))
+ for _, tc := range []struct{ name, contentType string }{
+ {"autoindex.css", "text/css; charset=utf-8"},
+ {"autoindex.js", "text/javascript; charset=utf-8"},
+ {"favicon.ico", "image/x-icon"},
+ {"favicon.png", "image/png"},
+ } {
+ for _, method := range []string{"GET", "HEAD"} {
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest(method, "/_nais/"+tc.name, nil))
+ if w.Code != 200 || w.Header().Get("Content-Type") != tc.contentType {
+ t.Fatalf("%s %s: status=%d type=%q", method, tc.name, w.Code, w.Header().Get("Content-Type"))
+ }
+ if (method == "HEAD") != (w.Body.Len() == 0) {
+ t.Fatalf("%s %s: unexpected body length %d", method, tc.name, w.Body.Len())
+ }
+ if w.Header().Get("X-Content-Type-Options") != "nosniff" {
+ t.Fatal("asset MIME protection missing")
+ }
+ }
+ }
+ for _, target := range []string{"/_nais/LICENSE", "/_nais/../secret", "/_nais/nested/autoindex.js"} {
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
+ if w.Code != 404 {
+ t.Fatalf("reserved namespace exposed %s: %d", target, w.Code)
+ }
+ }
+}
diff --git a/internal/web/listing.go b/internal/web/listing.go
new file mode 100644
index 0000000..c2e25ed
--- /dev/null
+++ b/internal/web/listing.go
@@ -0,0 +1,49 @@
+package web
+
+import (
+ "fmt"
+ "html/template"
+ "net/url"
+ "strings"
+)
+
+type entry struct {
+ Name, Size, Modified string
+ Link template.URL
+ Dir bool
+ Inline bool
+}
+type page struct {
+ Path string
+ Parent template.URL
+ Entries []entry
+ Truncated bool
+}
+
+var listing = template.Must(template.New("listing").Parse(`{{if .Parent}}../
+{{end}}{{range .Entries}}{{.Name}}{{if .Dir}}/{{end}} {{.Modified}} {{.Size}}
+{{else}}This folder is empty.
+{{end}}{{if .Truncated}}Only the first 5,000 entries are displayed.
+{{end}}`))
+
+func escapedPath(p string) template.URL {
+ parts := strings.Split(p, "/")
+ for i := range parts {
+ parts[i] = url.PathEscape(parts[i])
+ }
+ return template.URL(strings.Join(parts, "/"))
+}
+func sizeLabel(n int64) string {
+ if n < 1024 {
+ return fmt.Sprintf("%d B", n)
+ }
+ for _, u := range []struct {
+ n int64
+ s string
+ }{{1 << 30, "GiB"}, {1 << 20, "MiB"}, {1 << 10, "KiB"}} {
+ if n >= u.n {
+ return fmt.Sprintf("%.1f %s", float64(n)/float64(u.n), u.s)
+ }
+ }
+ return ""
+}
diff --git a/internal/web/redirect.go b/internal/web/redirect.go
new file mode 100644
index 0000000..c2cdec0
--- /dev/null
+++ b/internal/web/redirect.go
@@ -0,0 +1,29 @@
+package web
+
+import (
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+// RedirectHandler redirects allowed read requests to the configured HTTPS host.
+func RedirectHandler(domain string) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ host := r.Host
+ if h, _, err := net.SplitHostPort(host); err == nil {
+ host = h
+ }
+ if !strings.EqualFold(host, domain) {
+ http.Error(w, "Unknown host", http.StatusMisdirectedRequest)
+ return
+ }
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ w.Header().Set("Allow", "GET, HEAD")
+ http.Error(w, "Read-only service", 405)
+ return
+ }
+ target := url.URL{Scheme: "https", Host: domain, Path: r.URL.Path, RawPath: r.URL.RawPath, RawQuery: r.URL.RawQuery}
+ http.Redirect(w, r, target.String(), http.StatusPermanentRedirect)
+ })
+}
diff --git a/internal/web/static.go b/internal/web/static.go
new file mode 100644
index 0000000..266775b
--- /dev/null
+++ b/internal/web/static.go
@@ -0,0 +1,64 @@
+package web
+
+import (
+ "io"
+ "mime"
+ "net/http"
+ "os"
+ "path"
+ "strings"
+)
+
+// Static assets are identified explicitly; unrecognized files remain downloads.
+func inlineType(name string) string {
+ switch strings.ToLower(path.Ext(name)) {
+ case ".html", ".htm":
+ return "text/html; charset=utf-8"
+ case ".css":
+ return "text/css; charset=utf-8"
+ case ".js", ".mjs":
+ return "text/javascript; charset=utf-8"
+ case ".json", ".map":
+ return "application/json"
+ case ".png":
+ return "image/png"
+ case ".jpg", ".jpeg":
+ return "image/jpeg"
+ case ".gif":
+ return "image/gif"
+ case ".webp":
+ return "image/webp"
+ case ".avif":
+ return "image/avif"
+ case ".svg":
+ return "image/svg+xml"
+ case ".ico":
+ return "image/x-icon"
+ case ".woff":
+ return "font/woff"
+ case ".woff2":
+ return "font/woff2"
+ case ".ttf":
+ return "font/ttf"
+ case ".otf":
+ return "font/otf"
+ case ".wasm":
+ return "application/wasm"
+ default:
+ return ""
+ }
+}
+func serveFile(w http.ResponseWriter, r *http.Request, name string, info os.FileInfo, f io.ReadSeeker) {
+ contentType := inlineType(name)
+ if contentType == "" {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": info.Name()}))
+ } else {
+ w.Header().Set("Content-Type", contentType)
+ w.Header().Del("Content-Disposition")
+ // Published static pages may use inline scripts/styles and external assets.
+ // Directory listings retain their stricter policy; no server-side code runs.
+ w.Header().Set("Content-Security-Policy", "object-src 'none'; frame-ancestors 'none'; base-uri 'self'")
+ }
+ http.ServeContent(w, r, info.Name(), info.ModTime(), f)
+}
diff --git a/cmd/routershelf/static_test.go b/internal/web/static_test.go
similarity index 98%
rename from cmd/routershelf/static_test.go
rename to internal/web/static_test.go
index 217bd12..08b2f15 100644
--- a/cmd/routershelf/static_test.go
+++ b/internal/web/static_test.go
@@ -1,4 +1,4 @@
-package main
+package web
import (
"net/http/httptest"
@@ -17,7 +17,7 @@ func TestStaticPagesAndAssets(t *testing.T) {
t.Fatal(err)
}
}
- h := handler(root)
+ h := Handler(root)
for _, tc := range []struct {
url, ctype, body string
code int
@@ -62,7 +62,7 @@ func TestEscapingIndexSymlinkAndRootIndex(t *testing.T) {
outside := filepath.Join(t.TempDir(), "secret.html")
os.WriteFile(outside, []byte("private page"), 0600)
os.Symlink(outside, filepath.Join(root, "index.html"))
- h := handler(root)
+ h := Handler(root)
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if w.Code != 200 || strings.Contains(w.Body.String(), "private page") {
diff --git a/project.json b/project.json
index 5c946ee..362393f 100644
--- a/project.json
+++ b/project.json
@@ -8,7 +8,7 @@
"minimumGoVersion": "1.26.0",
"testedGoVersion": "1.26.5",
"entrypoint": "cmd/routershelf",
- "documentation": "docs/getting-started.md",
+ "documentation": "README.md",
"topics": [
"router",
"file-sharing",
@@ -37,13 +37,14 @@
"entrypoint": "cmd/routershelf",
"configuration": ".env.example",
"access": "public unauthenticated read-only",
- "targetStatus": "observed; see docs/deployment-history.md"
+ "targetStatus": "observed; see docs/deployment-history.md",
+ "documentation": "docs/getting-started.md"
},
"smb": {
"entrypoint": "cmd/routershelf-smb",
"configuration": ".smb.example.json",
"access": "private authenticated; read-only by default",
- "targetStatus": "experimental; cross-build only pending target execution approval",
+ "targetStatus": "experimental; target smoke checks observed; see docs/smb-validation.md",
"documentation": "docs/smb.md"
}
}
diff --git a/scripts/check_repository.py b/scripts/check_repository.py
new file mode 100644
index 0000000..371e799
--- /dev/null
+++ b/scripts/check_repository.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python3
+"""Check public source paths, local Markdown links, and metadata references.
+
+Reads Git-visible files only; ignored private configuration and outputs are never
+opened. This is a hygiene check, not a substitute for reviewing secrets or a
+release archive. Run from any directory within the checkout.
+"""
+import json
+from pathlib import Path
+import re
+import subprocess
+from urllib.parse import unquote, urlsplit
+
+
+def main():
+ root = Path(subprocess.check_output(
+ ["git", "rev-parse", "--show-toplevel"], text=True).strip())
+ names = subprocess.check_output(
+ ["git", "ls-files", "--cached", "--others", "--exclude-standard", "-z"],
+ cwd=root).decode().split("\0")
+ errors = []
+ for name in sorted(set(names) - {""}):
+ path = root / name
+ if path.is_symlink():
+ errors.append(f"{name}: symlinks are not supported in public source checks")
+ continue
+ if not path.is_file(): # Deletions and renames not yet staged.
+ continue
+ parts = Path(name).parts
+ base = path.name
+ private = (
+ any(part in {"dist", "outputs", ".idea", "__pycache__", "certificates"}
+ for part in parts)
+ or (base.startswith(".env") and name != ".env.example")
+ or (base.startswith(".smb.") and name != ".smb.example.json")
+ or base in {"smb.json", "config.sh", "supervisor.private.sh"}
+ or path.suffix in {".key", ".pem", ".pcap", ".backup", ".log", ".pid"}
+ )
+ if private:
+ errors.append(f"{name}: private/generated material in public source set")
+ continue
+ if path.suffix != ".md":
+ continue
+ # Inline Markdown links; skip web links, anchors, and fenced examples.
+ content = re.sub(r"```.*?```", "", path.read_text(), flags=re.S)
+ for match in re.finditer(r"\]\((<[^>]+>|[^\s)]+)\)", content):
+ target = match[1].strip("<>")
+ url = urlsplit(target)
+ if url.scheme or url.netloc or not url.path:
+ continue
+ destination = (path.parent / unquote(url.path)).resolve()
+ if not destination.is_relative_to(root) or not destination.exists():
+ errors.append(f"{name}: broken local link {target}")
+ if errors:
+ raise SystemExit("\n".join(errors))
+ metadata = json.loads((root / "project.json").read_text())
+ for service in metadata["services"].values():
+ for key in ("entrypoint", "configuration", "documentation"):
+ if key in service and not (root / service[key]).exists():
+ errors.append(f"project.json: missing {key} {service[key]}")
+ if errors:
+ raise SystemExit("\n".join(errors))
+ print("Public source paths, local documentation links and service metadata valid")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/tests/test_repository.py b/scripts/tests/test_repository.py
new file mode 100644
index 0000000..3011c0a
--- /dev/null
+++ b/scripts/tests/test_repository.py
@@ -0,0 +1,56 @@
+"""Exercise the repository checker against disposable Git working trees."""
+import json
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+CHECKER = Path(__file__).resolve().parents[1] / "check_repository.py"
+
+
+class RepositoryChecks(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="routershelf-source-check-")
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ subprocess.run(["git", "init", "--quiet", str(self.root)], check=True)
+ (self.root / ".gitignore").write_text(".env\noutputs/\n")
+ (self.root / "README.md").write_text("[Guide](guide.md)\n")
+ (self.root / "guide.md").write_text("Public guide\n")
+ (self.root / "project.json").write_text(json.dumps({
+ "services": {"web": {"entrypoint": "README.md",
+ "configuration": "guide.md"}}}))
+
+ def check(self):
+ return subprocess.run([sys.executable, "-B", str(CHECKER)],
+ cwd=self.root, capture_output=True, text=True)
+
+ def test_ignored_private_data_is_excluded(self):
+ (self.root / ".env").write_text("do not read or expose this private value")
+ (self.root / "outputs").mkdir()
+ (self.root / "outputs" / "private.md").write_text("[Broken](absent)")
+ result = self.check()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertNotIn("private value", result.stdout + result.stderr)
+
+ def test_broken_links_and_private_source_are_rejected(self):
+ (self.root / "README.md").write_text("[Missing](absent.md)\n")
+ (self.root / "account.key").write_text("must never appear in diagnostics")
+ result = self.check()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("broken local link absent.md", result.stderr)
+ self.assertIn("account.key: private/generated", result.stderr)
+ self.assertNotIn("must never appear", result.stdout + result.stderr)
+
+ def test_symlink_cannot_open_ignored_private_data(self):
+ (self.root / ".env").write_text("private-data-sentinel")
+ (self.root / "leak.md").symlink_to(".env")
+ result = self.check()
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn("leak.md: symlinks", result.stderr)
+ self.assertNotIn("private-data-sentinel", result.stdout + result.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()