refactor: clarify service boundaries and unify project tooling
This commit is contained in:
31 files changed
+832
-539
No files matched your search
@@ -12,6 +12,5 @@ jobs:
|
|||||||
- uses: actions/setup-go@v5
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: '1.26.x'
|
go-version: '1.26.x'
|
||||||
- run: make test
|
- run: make check
|
||||||
- run: make build-mipsle build-smb-mipsle
|
- run: make build build-router
|
||||||
- run: go test -race ./cmd/routershelf-smb ./internal/smbwire
|
|
||||||
@@ -4,7 +4,7 @@ These instructions apply to the entire repository. Read any more specific `AGENT
|
|||||||
|
|
||||||
## Project and entry points
|
## 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:
|
Read the relevant guide before changing a component:
|
||||||
|
|
||||||
@@ -17,11 +17,14 @@ Read the relevant guide before changing a component:
|
|||||||
|
|
||||||
## Repository layout
|
## Repository layout
|
||||||
|
|
||||||
- `cmd/routershelf/`: application, environment/flag parsing, handler and configuration tests.
|
- `cmd/routershelf/`: web process startup, TLS, bounded listeners, environment/flag parsing 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.
|
- `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/`.
|
- `internal/theme/assets.go`: embeds assets under `internal/theme/nais/`.
|
||||||
- `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle.
|
- `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle.
|
||||||
- `scripts/nat-plan.sh`: prints gateway configuration guidance; it does not modify the gateway.
|
- `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.
|
- `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.
|
- `.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.
|
- `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:
|
Run from the repository root using Go 1.26 or a newer toolchain verified against the target kernel:
|
||||||
|
|
||||||
```sh
|
```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 test-stress-tool # Python localhost-only tests; no live-router requests
|
||||||
make check-shell # syntax only; does not execute deployment
|
make check-shell # syntax only; does not execute deployment
|
||||||
make check-config # side-effect-free validation using .env.example
|
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
|
## 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.
|
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.
|
||||||
@@ -2,6 +2,19 @@
|
|||||||
|
|
||||||
## Unreleased
|
## 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
|
### Stress testing
|
||||||
|
|
||||||
- Added a bounded read-only Python runner with phased concurrency, rate caps, optional router telemetry and stop thresholds.
|
- Added a bounded read-only Python runner with phased concurrency, rate caps, optional router telemetry and stop thresholds.
|
||||||
|
|||||||
+13
-5
@@ -2,11 +2,11 @@
|
|||||||
|
|
||||||
## Development
|
## 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
|
## 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.
|
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).
|
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.
|
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.
|
||||||
@@ -1,22 +1,52 @@
|
|||||||
GO ?= go
|
GO ?= go
|
||||||
PYTHON ?= python3
|
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 ./...
|
$(GO) test ./...
|
||||||
|
|
||||||
check-shell:
|
# CI and the local full check use the same commands. No deployment is performed.
|
||||||
sh -n deploy/padavan/supervisor.example.sh
|
check: test check-format check-docs vet test-race
|
||||||
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
|
|
||||||
|
|
||||||
build-mipsle:
|
check-shell:
|
||||||
mkdir -p dist
|
@for script in deploy/padavan/*.sh scripts/*.sh examples/status-dashboard/scripts/*.sh examples/status-dashboard/config.example.sh; do \
|
||||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o $(BINARY) ./cmd/routershelf
|
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:
|
check-config:
|
||||||
ROUTERSHELF_ENV_FILE="$(CURDIR)/.env.example" sh deploy/padavan/supervisor.example.sh --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
|
sh scripts/nat-plan.sh
|
||||||
|
|
||||||
test-stress-tool:
|
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:
|
test-repository:
|
||||||
mkdir -p dist
|
$(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_repository.py' -v
|
||||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o dist/routershelf-smb-linux-mipsle ./cmd/routershelf-smb
|
|
||||||
@@ -1,85 +1,63 @@
|
|||||||
# RouterShelf
|
# 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.
|
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.
|
||||||
- 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.
|
|
||||||
|
|
||||||
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.
|
## Development
|
||||||
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.
|
|
||||||
|
|
||||||
Build and test from the repository root:
|
Use Go 1.26 and Python 3.10+ on the development computer. From the repository root:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make test
|
make test # Go tests, shell/config checks, Python tool tests
|
||||||
make build-mipsle
|
make check # Also formatting, docs/source hygiene, vet and race tests
|
||||||
make build-smb-mipsle # optional independent Finder service
|
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
|
## Code and documentation
|
||||||
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
|
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cmd/routershelf/ HTTP/HTTPS application and behavior tests
|
cmd/routershelf/ Web configuration, startup, TLS and connection limits
|
||||||
cmd/routershelf-smb/ Independent private SMB executable and config tests
|
cmd/routershelf-smb/ SMB configuration, startup and storage supervision
|
||||||
internal/smbwire/ Adapted Apache-2.0 SMB protocol source and tests
|
internal/web/ Public HTTP handlers, listings, static files and tests
|
||||||
internal/theme/nais/ Licensed NAIS assets embedded in the executable
|
internal/theme/ Embedded NAIS assets and their license
|
||||||
internal/theme/assets.go Asset embedding boundary
|
internal/smbwire/ Adapted SMB protocol implementation, license and tests
|
||||||
deploy/padavan/ Environment-driven firmware supervisor
|
deploy/padavan/ Independent firmware supervisor examples
|
||||||
examples/status-dashboard/ Separate legacy BusyBox/Netcat dashboard
|
scripts/ Local checks, gateway planning and test tools
|
||||||
docs/ Setup, operations, architecture, and deployment history
|
docs/ User guides, architecture and validation records
|
||||||
.github/ CI and issue/pull-request templates
|
examples/ Separate historical LAN status-dashboard tutorial
|
||||||
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
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
||||||
+7
-6
@@ -1,17 +1,12 @@
|
|||||||
# RouterShelf security boundaries
|
# 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 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.
|
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.
|
- 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.
|
- `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 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.
|
- 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.
|
- 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).
|
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.
|
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.
|
||||||
@@ -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
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"runtime"
|
"runtime"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
|
||||||
|
|
||||||
smb "routershelf/internal/smbwire"
|
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 {
|
func run() error {
|
||||||
if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help" || os.Args[1] == "-help") {
|
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.")
|
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.")
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
+43
-300
@@ -1,338 +1,81 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
|
||||||
"html/template"
|
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"mime"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
"path"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"golang.org/x/crypto/acme/autocert"
|
"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(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Index of {{.Path}}</title><link rel="stylesheet" href="/_nais/autoindex.css"><link rel="icon" href="/_nais/favicon.ico"></head><body><h1><span>Index of {{.Path}}</span></h1><pre>{{if .Parent}}<a href="../">../</a>
|
|
||||||
{{end}}{{range .Entries}}<a href="{{.Link}}"{{if not .Dir}} data-file="true"{{if not .Inline}} download{{end}}{{end}}>{{.Name}}{{if .Dir}}/{{end}}</a> {{.Modified}} {{.Size}}
|
|
||||||
{{else}}This folder is empty.
|
|
||||||
{{end}}{{if .Truncated}}Only the first 5,000 entries are displayed.
|
|
||||||
{{end}}</pre><script src="/_nais/autoindex.js" defer></script></body></html>`))
|
|
||||||
|
|
||||||
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() {
|
func main() {
|
||||||
cfg, err := parseConfig(os.Args[1:])
|
cfg, err := parseConfig(os.Args[1:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
root, addr, domain, httpAddr, cache, drop := &cfg.root, &cfg.listen, &cfg.domain, &cfg.httpListen, &cfg.certCache, &cfg.drop
|
root, err := os.OpenRoot(cfg.root)
|
||||||
r, e := os.OpenRoot(*root)
|
if err != nil {
|
||||||
if e != nil {
|
|
||||||
log.Fatal("public directory unavailable")
|
log.Fatal("public directory unavailable")
|
||||||
}
|
}
|
||||||
r.Close()
|
root.Close()
|
||||||
if *drop {
|
if cfg.drop {
|
||||||
if e = syscall.Setgroups([]int{}); e != nil {
|
if err = syscall.Setgroups([]int{}); err != nil {
|
||||||
log.Fatal(e)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
if e = syscall.Setgid(65534); e != nil {
|
if err = syscall.Setgid(65534); err != nil {
|
||||||
log.Fatal(e)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
if e = syscall.Setuid(65534); e != nil {
|
if err = syscall.Setuid(65534); err != nil {
|
||||||
log.Fatal(e)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
l, e := net.Listen("tcp4", *addr)
|
listener, err := net.Listen("tcp4", cfg.listen)
|
||||||
if e != nil {
|
if err != nil {
|
||||||
log.Fatal(e)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
contentHandler := handler(*root)
|
contentHandler := web.Handler(cfg.root)
|
||||||
var manager *autocert.Manager
|
var manager *autocert.Manager
|
||||||
if *domain != "" {
|
if cfg.domain != "" {
|
||||||
if *cache == "" {
|
if cfg.certCache == "" {
|
||||||
log.Fatal("-cert-cache is required for HTTPS")
|
log.Fatal("-cert-cache is required for HTTPS")
|
||||||
}
|
}
|
||||||
manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(*domain), Cache: autocert.DirCache(*cache)}
|
manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(cfg.domain), Cache: autocert.DirCache(cfg.certCache)}
|
||||||
redirect := redirectHandler(*domain)
|
redirect := web.RedirectHandler(cfg.domain)
|
||||||
hl, err := net.Listen("tcp4", *httpAddr)
|
httpListener, err := net.Listen("tcp4", cfg.httpListen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
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}
|
challengeServer := &http.Server{
|
||||||
go func() { log.Fatal(hs.Serve(&boundedListener{hl, make(chan struct{}, 16)})) }()
|
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}
|
server := &http.Server{
|
||||||
log.Printf("Read-only public directory listening on %s (domain=%s)", *addr, *domain)
|
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 {
|
if manager != nil {
|
||||||
s.TLSConfig = manager.TLSConfig()
|
server.TLSConfig = manager.TLSConfig()
|
||||||
s.TLSConfig.MinVersion = tls.VersionTLS12
|
server.TLSConfig.MinVersion = tls.VersionTLS12
|
||||||
// HTTP/1.1 plus ACME ALPN; bound connections remain effective for all clients.
|
// HTTP/1.1 plus ACME ALPN; bound connections remain effective for all clients.
|
||||||
s.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"}
|
server.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"}
|
||||||
log.Fatal(s.ServeTLS(&boundedListener{l, make(chan struct{}, 32)}, "", ""))
|
log.Fatal(server.ServeTLS(&boundedListener{listener, make(chan struct{}, 32)}, "", ""))
|
||||||
}
|
}
|
||||||
log.Fatal(s.Serve(&boundedListener{l, make(chan struct{}, 32)}))
|
log.Fatal(server.Serve(&boundedListener{listener, 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)
|
|
||||||
}
|
}
|
||||||
+24
-21
@@ -1,35 +1,38 @@
|
|||||||
# Architecture
|
# 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` |
|
| Web command | Environment/flag validation, privilege drop, listeners, connection bounds, TLS and ACME | `cmd/routershelf` |
|
||||||
| Private SMB application | Independent account/config, selected root, signed SMB, write policy and privilege drop | `cmd/routershelf-smb`, `internal/smbwire` |
|
| Public HTTP | Filesystem confinement, methods, listings, static pages, download headers and HTTPS redirects | `internal/web` |
|
||||||
| Embedded theme | NAIS styling, favicon, copied links, playlist generation | `internal/theme` |
|
| Embedded theme | NAIS CSS/JavaScript, favicon, copied links and playlists | `internal/theme` |
|
||||||
| Router lifecycle | USB checks, process restart, time startup, host firewall hooks, flash persistence | `deploy/padavan` |
|
| SMB command | Private JSON validation, credentials CLI, listener/privilege setup, mount/root monitoring | `cmd/routershelf-smb` |
|
||||||
| Network gateway | Public DNS destination, destination NAT, LAN hairpin reply routing | Configuration documented in `docs/getting-started.md` |
|
| 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
|
```text
|
||||||
Browser -> gateway TCP 80/443 -> storage host TCP 10080/10443
|
routershelf command -> internal/web -> internal/theme
|
||||||
|
|
-> x/crypto/acme/autocert
|
||||||
RouterShelf
|
|
||||||
/ \
|
routershelf-smb command -> internal/smbwire -> x/crypto, x/sys
|
||||||
shared directory private ACME cache
|
|
||||||
|
|
|
||||||
USB filesystem
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
||||||
@@ -14,7 +14,7 @@ LAN browser -> router TCP port 8080 -> Netcat -> shell request handler
|
|||||||
+-> HTTP headers + HTML response
|
+-> 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.
|
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.
|
- 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.
|
- `.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.
|
- 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
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
|
## Architecture and paths
|
||||||
|
|
||||||
```text
|
```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.
|
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
|
```sh
|
||||||
mkdir -p dist
|
make test
|
||||||
go test ./...
|
make build-mipsle
|
||||||
GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 \
|
|
||||||
go build -trimpath -ldflags='-s -w' -o dist/routershelf-linux-mipsle ./cmd/routershelf
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
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 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -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.
|
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
|
## Routine care
|
||||||
|
|
||||||
| Frequency / event | Check |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| Service returns after stopping child | Expected supervisor restart; stop the parent to stop the whole service |
|
||||||
|
|||||||
+1
-1
@@ -37,7 +37,7 @@ On the development computer, with Go 1.26+:
|
|||||||
make test
|
make test
|
||||||
make build-smb-mipsle
|
make build-smb-mipsle
|
||||||
# For a local desktop executable:
|
# For a local desktop executable:
|
||||||
go build -o dist/routershelf-smb ./cmd/routershelf-smb
|
make dist/routershelf-smb
|
||||||
umask 077
|
umask 077
|
||||||
cp .smb.example.json smb.json
|
cp .smb.example.json smb.json
|
||||||
chmod 600 smb.json
|
chmod 600 smb.json
|
||||||
|
|||||||
@@ -2,10 +2,12 @@ module routershelf
|
|||||||
|
|
||||||
go 1.26.0
|
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 (
|
require (
|
||||||
golang.org/x/net v0.58.0 // indirect
|
golang.org/x/net v0.58.0 // indirect
|
||||||
golang.org/x/sys v0.48.0
|
|
||||||
golang.org/x/text v0.42.0 // indirect
|
golang.org/x/text v0.42.0 // indirect
|
||||||
)
|
)
|
||||||
@@ -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.
|
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.
|
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.
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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
|
||||||
@@ -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)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package main
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -17,7 +17,7 @@ func TestFileScopeAndMethods(t *testing.T) {
|
|||||||
os.Symlink(outside, filepath.Join(root, "escape.txt"))
|
os.Symlink(outside, filepath.Join(root, "escape.txt"))
|
||||||
os.Mkdir(filepath.Join(root, "sub"), 0700)
|
os.Mkdir(filepath.Join(root, "sub"), 0700)
|
||||||
os.WriteFile(filepath.Join(root, "<&.txt"), []byte("safe"), 0600)
|
os.WriteFile(filepath.Join(root, "<&.txt"), []byte("safe"), 0600)
|
||||||
h := handler(root)
|
h := Handler(root)
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
method, url string
|
method, url string
|
||||||
code int
|
code int
|
||||||
@@ -54,7 +54,7 @@ func TestFileScopeAndMethods(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestHTTPSRedirect(t *testing.T) {
|
func TestHTTPSRedirect(t *testing.T) {
|
||||||
h := redirectHandler("files.example.com")
|
h := RedirectHandler("files.example.com")
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
target, method string
|
target, method string
|
||||||
status int
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Index of {{.Path}}</title><link rel="stylesheet" href="/_nais/autoindex.css"><link rel="icon" href="/_nais/favicon.ico"></head><body><h1><span>Index of {{.Path}}</span></h1><pre>{{if .Parent}}<a href="../">../</a>
|
||||||
|
{{end}}{{range .Entries}}<a href="{{.Link}}"{{if not .Dir}} data-file="true"{{if not .Inline}} download{{end}}{{end}}>{{.Name}}{{if .Dir}}/{{end}}</a> {{.Modified}} {{.Size}}
|
||||||
|
{{else}}This folder is empty.
|
||||||
|
{{end}}{{if .Truncated}}Only the first 5,000 entries are displayed.
|
||||||
|
{{end}}</pre><script src="/_nais/autoindex.js" defer></script></body></html>`))
|
||||||
|
|
||||||
|
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 ""
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package main
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -17,7 +17,7 @@ func TestStaticPagesAndAssets(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
h := handler(root)
|
h := Handler(root)
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
url, ctype, body string
|
url, ctype, body string
|
||||||
code int
|
code int
|
||||||
@@ -62,7 +62,7 @@ func TestEscapingIndexSymlinkAndRootIndex(t *testing.T) {
|
|||||||
outside := filepath.Join(t.TempDir(), "secret.html")
|
outside := filepath.Join(t.TempDir(), "secret.html")
|
||||||
os.WriteFile(outside, []byte("private page"), 0600)
|
os.WriteFile(outside, []byte("private page"), 0600)
|
||||||
os.Symlink(outside, filepath.Join(root, "index.html"))
|
os.Symlink(outside, filepath.Join(root, "index.html"))
|
||||||
h := handler(root)
|
h := Handler(root)
|
||||||
w := httptest.NewRecorder()
|
w := httptest.NewRecorder()
|
||||||
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
||||||
if w.Code != 200 || strings.Contains(w.Body.String(), "private page") {
|
if w.Code != 200 || strings.Contains(w.Body.String(), "private page") {
|
||||||
+4
-3
@@ -8,7 +8,7 @@
|
|||||||
"minimumGoVersion": "1.26.0",
|
"minimumGoVersion": "1.26.0",
|
||||||
"testedGoVersion": "1.26.5",
|
"testedGoVersion": "1.26.5",
|
||||||
"entrypoint": "cmd/routershelf",
|
"entrypoint": "cmd/routershelf",
|
||||||
"documentation": "docs/getting-started.md",
|
"documentation": "README.md",
|
||||||
"topics": [
|
"topics": [
|
||||||
"router",
|
"router",
|
||||||
"file-sharing",
|
"file-sharing",
|
||||||
@@ -37,13 +37,14 @@
|
|||||||
"entrypoint": "cmd/routershelf",
|
"entrypoint": "cmd/routershelf",
|
||||||
"configuration": ".env.example",
|
"configuration": ".env.example",
|
||||||
"access": "public unauthenticated read-only",
|
"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": {
|
"smb": {
|
||||||
"entrypoint": "cmd/routershelf-smb",
|
"entrypoint": "cmd/routershelf-smb",
|
||||||
"configuration": ".smb.example.json",
|
"configuration": ".smb.example.json",
|
||||||
"access": "private authenticated; read-only by default",
|
"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"
|
"documentation": "docs/smb.md"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
Reference in new issue
Block a user