diff --git a/README.md b/README.md index 9a1adcc..766b02b 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,8 @@ On native Linux, install uv, Node.js 24.x/npm, and Rust/Cargo before running `run_linkhub_ui.cmd --build ` calls `setup.cmd` before launching. Without `--build`, the launcher reuses existing artifacts, running setup -automatically if the LinkHub binary or compiled UI is missing. +automatically if the LinkHub binary or compiled UI is missing, or the binary +rejects the launcher's arguments. See the [launcher documentation](linkhub-ui/README.md#live-ui). Docker image builds: diff --git a/design/linkhub.md b/design/linkhub.md index 9efea91..5e5bd3a 100644 --- a/design/linkhub.md +++ b/design/linkhub.md @@ -144,6 +144,11 @@ Route-by-route invocation examples, request bodies, and CLI usage live in [linkhub/README.md](../linkhub/README.md); this document keeps the shared API semantics. +Before any vehicle heartbeat, MAVLink status has an empty `base_mode` mask and +`system_status=UNINIT`; generated dialect flag defaults must not imply an armed +vehicle. Consumers must still use connection/readiness and observed heartbeats +to distinguish unknown state from confirmed disarmed state. + ### Bluetooth bench motor `--motor-name-prefix` enables the external rotor-drive backend. It starts @@ -154,7 +159,9 @@ an explicit connection selects one exact ID, never another matching device. The Nordic UART service is verified at connection time. Connecting initializes the motor off. Switching devices first completes the previous motor's controlled stop and never starts the selected motor. -Scanning is rejected while running. +Scanning is rejected while connected and running. After Bluetooth loss, scanning +is allowed even if the last running command remains unconfirmed; scanning does +not clear that state. Explicit reconnection initializes the motor off. Every running command includes the connected `device_id`, speed percentage, direction, and a finite lease duration. The current motor is forward-only; @@ -192,6 +199,10 @@ A zero command does not establish zero mechanical RPM. Link loss, process crash, power loss, and the motor controller's own watchdog/braking behavior need motor-firmware/hardware protection. Write failures are reported as unconfirmed motor state; LinkHub does not send an abrupt brake as an error fallback. +On link/write failure the supervisor exits and releases the Bluetooth peripheral +and adapter handles. Cleanup failures are logged without clearing the original +unconfirmed motor state. A subsequent UI connection acquires fresh handles and +initializes the motor off; it never resumes the previous command. The browser renews a 2 s lease every 500 ms only for a motor it explicitly started. Closing its motor panel, hiding the tab, or a request failure revokes @@ -321,14 +332,22 @@ experiment without writing `mavlog.json`. The journal still holds the records. Phone browsers expose the camera only to secure contexts, so `serve --https-port PORT` also serves the full router over HTTPS. The self-signed certificate lives in `/tls/` and is regenerated only -when its host set (localhost plus the LAN address) changes, so a phone accepts -the certificate warning once. `GET /v1/camera` returns the phone URL -`https://:/camera`, a QR code SVG (`qr_svg`), the +when its host set changes, so a phone accepts the certificate warning once. +With `--listen 0.0.0.0` or `::`, the certificate covers `localhost`, `127.0.0.1`, +and `.local`, using the lowercase short OS hostname. Its identity +does not change when DHCP assigns a different LAN IP. An explicit non-loopback +`--listen IP` uses that IP instead of the computer name. +`GET /v1/camera` returns the phone URL +`https://.local:/camera` for all-interface listeners, +a QR code SVG (`qr_svg`), the connected phones (`phones`), and, while an experiment runs, its `experiment_id` and the recordings received so far (`videos`). When `--listen` is loopback or HTTPS is off, it returns `url: null` with a -`reason`. `--listen 0.0.0.0` resolves the LAN address from the default-route -interface. +`reason`. The client network must resolve the computer's `.local` name (normally +through mDNS); the certificate does not advertise a hostname or configure DNS. +Existing IP-based certificates regenerate once when switching to the hostname, +so clients must accept the new self-signed certificate. The certificate remains +self-signed, not publicly trusted. `GET /camera` serves a self-contained page (`linkhub/src/camera.html`). A phone enables its camera once (one permission prompt; reloads reconnect diff --git a/linkhub-ui/README.md b/linkhub-ui/README.md index 74b9859..22ca886 100644 --- a/linkhub-ui/README.md +++ b/linkhub-ui/README.md @@ -105,7 +105,9 @@ Add `--build` to run the complete project setup before launching `setup.cmd` owns tool installation, uv-managed Python, dependencies, and both builds; see the [root setup instructions](../README.md#running-tests). The launcher also runs setup automatically when either build artifact is -missing. With both artifacts present, a normal launch needs no Python or uv. +missing or the existing LinkHub binary rejects the launcher's arguments. It +checks argument compatibility with `serve --help` before opening connections. +With compatible artifacts present, a normal launch needs no Python or uv. `run_linkhub_ui.cmd` also: @@ -115,11 +117,36 @@ missing. With both artifacts present, a normal launch needs no Python or uv. telemetry radio; set a numeric baud only when intentionally restricting the scan; - defaults the HTTP port to `8999`; +- listens on `0.0.0.0` (all network interfaces) for HTTP and HTTPS. From another + device, use `http://.local:8999` or + `https://.local:9443`, not `0.0.0.0`. The HTTPS certificate and + camera QR code use that `.local` hostname; the client network must resolve it. + Windows Firewall must allow the selected ports on the trusted network. + See [phone HTTPS identity](../design/linkhub.md#phone-video); - serves `linkhub-ui\dist` through LinkHub's `--static-dir`; - enables the optional external motor backend with `--motor-name-prefix BLDC`, initially disconnected; - adds `--no-cache` so a browser refresh picks up a new build immediately. +For trusted LAN access, opt in to a persistent Windows Firewall rule: + +```powershell +.\run_linkhub_ui.cmd --configure-firewall auto +``` + +Approve the administrator prompt. Only the firewall helper is elevated; LinkHub +continues under the original user. The rule allows inbound TCP for this +checkout's LinkHub executable, using the selected HTTP and HTTPS ports, from +`LocalSubnet` on **Private** networks only. Repeating the option updates the +same `RAWES-LinkHub-Private-LAN` rule, including changed ports or executable path. +Normal launches never change firewall rules. Cancellation or configuration +failure prevents startup. Public networks, explicit block rules, and managed +firewall policy are not overridden; rule creation does not prove remote +reachability. Use only a trusted LAN, not Internet port forwarding. + +To remove the rule, run `Remove-NetFirewallRule -Name RAWES-LinkHub-Private-LAN` +in an administrator PowerShell. + ## Bluetooth motor panel Click **Motor**, then **Scan**, select the intended device by name and ID, and @@ -145,6 +172,10 @@ the supervisor starts controlled ramp-down on its next profile tick. Stops are not immediate; the request waits for the server-owned ramp to finish. There is no automatic restart after expiry, reconnect, or reopening the panel. Another client's running motor is displayed but never adopted for renewal. +Bluetooth loss revokes renewal and disables speed/start/stop controls. The panel +shows the motor state as unconfirmed, not off, and keeps Scan and Connect +available even if the last command was running or stopping. Reconnect explicitly, +then click Turn on to restart; reconnecting alone never resumes the motor. The offline demo shows the backend as unavailable and never accesses Bluetooth. Keep clear of the mechanism; a transport-level stop is not physical stop feedback. See [LinkHub motor semantics](../design/linkhub.md#bluetooth-bench-motor). @@ -169,6 +200,11 @@ Stop runs these steps in order: directory. With `run_linkhub_ui.cmd`, experiment directories land in `simulation/logs/linkhub/experiments/`. +An experiment started with no motor or vehicle connected can stop and save +without sending hardware commands. Initial MAVLink status has no mode flags +until a heartbeat arrives; absence of telemetry is not a disarm confirmation +for a previously connected vehicle. + If a step fails, for example the rotor is still turning or the motor stop times out, the experiment stays open so you can press Stop again. Experiment state lives on the server, so a page reload picks up a running experiment. diff --git a/linkhub-ui/src/motor-panel.ts b/linkhub-ui/src/motor-panel.ts index b5f8415..9396acf 100644 --- a/linkhub-ui/src/motor-panel.ts +++ b/linkhub-ui/src/motor-panel.ts @@ -248,6 +248,16 @@ export class MotorPanel { } private update(status: MotorStatus): void { + if (!status.available || !status.connected) { + if (this.status?.available && this.status.connected && status.available) { + this.write("Motor: Bluetooth disconnected; motor state is unconfirmed. Reconnect before restarting.", "error"); + } + if (this.ownedDevice) { + this.ownedDevice = null; + this.leaseDeadline = 0; + this.revision += 1; + } + } this.status = status; if (status.available && status.device_id && !Array.from(this.device.options).some((option) => option.value === status.device_id)) { this.device.add(new Option(`${status.device ?? "Motor"} (${status.device_id})`, status.device_id)); @@ -259,25 +269,29 @@ export class MotorPanel { const status = this.status; const available = status?.available === true; const connected = available && status.connected; - const running = available && status.running; + const running = connected && status.running; const busy = this.busy > 0; const speedText = `${this.speed.value}%`; if (this.speedValue.textContent !== speedText) this.speedValue.textContent = speedText; - const stateText = this.error + const disconnected = available && !connected; + const detail = this.error ?? (available ? status.error : null); + const stateText = disconnected + ? `Disconnected - motor state unconfirmed. Reconnect before restarting.${detail ? ` ${detail}` : ""}` + : this.error ?? (available ? status.error : null) ?? (status?.available === false ? "Motor backend disabled in LinkHub" : !status ? "Loading" : status.available && status.stopping ? `STOPPING - ${status.speed_percent}%` : running ? `ON - ${status.speed_percent}% -> ${status.target_speed_percent}%${this.ownedDevice ? "" : " (another client)"}` : connected ? `OFF - ${status.device}` : "Disconnected"); if (this.state.textContent !== stateText) this.state.textContent = stateText; - this.state.classList.toggle("error", Boolean(this.error || (available && status.error))); + this.state.classList.toggle("error", disconnected || Boolean(this.error || (available && status.error))); this.scanButton.disabled = !available || busy || running; this.device.disabled = !available || busy || running; this.connectButton.disabled = !available || busy || running || !this.device.value; this.experimentHint.hidden = this.experiment.running; this.onButton.disabled = !this.experiment.running || !connected || busy || running || Boolean(this.error) || this.device.value !== (available ? status.device_id : null) || Number(this.speed.value) === 0; - this.offButton.disabled = !available; + this.offButton.disabled = !connected; this.speed.disabled = !connected || busy || (running && !this.ownedDevice); } } diff --git a/linkhub-ui/tests/experiment.test.ts b/linkhub-ui/tests/experiment.test.ts index e12db1c..89e1347 100644 --- a/linkhub-ui/tests/experiment.test.ts +++ b/linkhub-ui/tests/experiment.test.ts @@ -9,7 +9,7 @@ const INFO: ExperimentInfo = { id: "e1", name: "Spin", description: "", run_id: "r1", started_at_ns: 0, start_cursor: "v1:1", directory: "x", }; -function motor(speed: number, stopping = false): MotorStatus { +function motor(speed: number, stopping = false): Extract { return { available: true, connected: true, device: "BLDC", device_id: "m1", running: speed > 0 && !stopping, stopping, speed_percent: speed, target_speed_percent: 0, @@ -94,6 +94,26 @@ describe("experiment controller", () => { expect(controller.running).toBe(true); }); + it("saves without hardware commands when no motor or vehicle has connected", async () => { + const { controller, api, passive, calls } = setup([]); + passive.phase = "idle"; + api.motorStatus.mockResolvedValue({ + ...motor(0), connected: false, device: null, device_id: null, + }); + api.status.mockResolvedValue({ + connected: false, ready: false, base_mode: "", received_messages: 0, + } as LinkHubStatus); + await controller.refresh(); + + await controller.stop(); + + expect(api.stopMotor).not.toHaveBeenCalled(); + expect(passive.stop).not.toHaveBeenCalled(); + expect(calls).toEqual(["save"]); + expect(controller.active).toBeNull(); + expect(controller.stage).toBe("idle"); + }); + it("refuses gated actions without an active experiment", async () => { const { controller, api } = setup([]); api.experiment.mockResolvedValue(null); diff --git a/linkhub-ui/tests/motor-panel.test.ts b/linkhub-ui/tests/motor-panel.test.ts index 66f7055..546f362 100644 --- a/linkhub-ui/tests/motor-panel.test.ts +++ b/linkhub-ui/tests/motor-panel.test.ts @@ -105,6 +105,72 @@ afterEach(() => { }); describe("Bluetooth motor panel", () => { + it.each([ + { running: false, stopping: false }, + { running: true, stopping: false }, + { running: true, stopping: true }, + ])("allows recovery after disconnect with last command $running/$stopping", async (lastCommand) => { + const { panel, api, elements, setStatus, write, speed } = setup(); + await vi.advanceTimersByTimeAsync(0); + setStatus({ + ...connected(), ...lastCommand, connected: false, + speed_percent: 30, target_speed_percent: 80, error: "Bluetooth motor is disconnected", + }); + await vi.advanceTimersByTimeAsync(500); + expect(elements.get("state")!.textContent).toContain("Disconnected - motor state unconfirmed"); + expect(elements.get("state")!.textContent).toContain("Bluetooth motor is disconnected"); + expect(elements.get("scan")!.disabled).toBe(false); + expect(elements.get("device")!.disabled).toBe(false); + expect(elements.get("connect")!.disabled).toBe(false); + expect(elements.get("on")!.disabled).toBe(true); + expect(elements.get("off")!.disabled).toBe(true); + expect(speed.disabled).toBe(true); + expect(api.stopMotor).not.toHaveBeenCalled(); + expect(write).toHaveBeenCalledTimes(1); + await panel.connect(); + expect(elements.get("on")!.disabled).toBe(false); + expect(api.runMotor).not.toHaveBeenCalled(); + panel.dispose(); + }); + + it("revokes its lease on Bluetooth loss without attempting an impossible stop or restarting", async () => { + const { panel, api, setStatus, elements } = setup(); + await panel.turnOn(); + setStatus({ + ...connected(), connected: false, running: true, speed_percent: 10, + target_speed_percent: 10, error: "Bluetooth motor is disconnected", + }); + api.stopMotor.mockRejectedValue(new Error("Bluetooth motor is disconnected")); + await vi.advanceTimersByTimeAsync(1500); + expect(api.runMotor).toHaveBeenCalledTimes(1); + expect(api.stopMotor).not.toHaveBeenCalled(); + expect(elements.get("connect")!.disabled).toBe(false); + await panel.connect(); + await vi.advanceTimersByTimeAsync(1500); + expect(api.runMotor).toHaveBeenCalledTimes(1); + await panel.turnOn(); + expect(api.runMotor).toHaveBeenCalledTimes(2); + panel.dispose(); + }); + + it("handles disconnect in a run response without retaining renewal ownership", async () => { + const { panel, api, setStatus, elements } = setup(); + const disconnected: MotorStatus = { + ...connected(), connected: false, running: true, error: "Bluetooth motor is disconnected", + }; + api.runMotor.mockImplementationOnce(async () => { + setStatus(disconnected); + return disconnected; + }); + await panel.turnOn(); + await vi.advanceTimersByTimeAsync(1500); + expect(api.runMotor).toHaveBeenCalledTimes(1); + expect(api.stopMotor).not.toHaveBeenCalled(); + expect(elements.get("on")!.disabled).toBe(true); + expect(elements.get("connect")!.disabled).toBe(false); + panel.dispose(); + }); + it("shows applied versus target commands and a server-owned stop", async () => { const { panel, elements, api, setStatus } = setup({ ...connected(), running: true, speed_percent: 30, target_speed_percent: 80, diff --git a/linkhub/Cargo.lock b/linkhub/Cargo.lock index fb1c461..6564b94 100644 --- a/linkhub/Cargo.lock +++ b/linkhub/Cargo.lock @@ -635,8 +635,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", ] [[package]] @@ -647,7 +663,7 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", ] [[package]] @@ -693,6 +709,17 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hostname" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" +dependencies = [ + "cfg-if", + "libc", + "windows-link", +] + [[package]] name = "http" version = "1.5.0" @@ -766,6 +793,21 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-util" version = "0.1.21" @@ -1033,6 +1075,7 @@ dependencies = [ "clap", "futures-util", "hex", + "hostname", "mavlink-protocol", "qrcode", "rcgen", @@ -1089,6 +1132,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + [[package]] name = "mach2" version = "0.4.3" @@ -1372,6 +1421,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1396,6 +1454,61 @@ dependencies = [ "memchr", ] +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "quote" version = "1.0.47" @@ -1405,12 +1518,47 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rcgen" version = "0.13.2" @@ -1475,16 +1623,21 @@ dependencies = [ "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-util", "js-sys", "log", "percent-encoding", "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", "serde", "serde_json", "serde_urlencoded", "sync_wrapper", "tokio", + "tokio-rustls", "tower", "tower-http", "tower-service", @@ -1527,6 +1680,12 @@ dependencies = [ "serde", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustc_version" version = "0.4.1" @@ -1570,6 +1729,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ + "web-time", "zeroize", ] @@ -1943,6 +2103,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.53.1" @@ -2250,6 +2416,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.129" @@ -2316,6 +2491,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "winapi-util" version = "0.1.11" @@ -2517,6 +2702,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" @@ -2561,6 +2752,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerofrom" version = "0.1.8" diff --git a/linkhub/Cargo.toml b/linkhub/Cargo.toml index 3cd67b4..be073c6 100644 --- a/linkhub/Cargo.toml +++ b/linkhub/Cargo.toml @@ -32,9 +32,11 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std" rcgen = { version = "0.13", default-features = false, features = ["ring", "pem"] } qrcode = { version = "0.14", default-features = false, features = ["svg"] } axum-server = { version = "0.9.2", features = ["tls-rustls-ring"] } +hostname = "0.4" [dev-dependencies] hex = "0.4" +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-manual-roots"] } tempfile = "3.23" tokio = { version = "1.48", features = ["test-util"] } tower = { version = "0.5", features = ["util"] } diff --git a/linkhub/src/http.rs b/linkhub/src/http.rs index c3ae320..41347c0 100644 --- a/linkhub/src/http.rs +++ b/linkhub/src/http.rs @@ -1,4 +1,10 @@ -use std::{collections::HashMap, net::SocketAddr, path::PathBuf, sync::Arc, time::Duration}; +use std::{ + collections::HashMap, + net::{IpAddr, SocketAddr}, + path::PathBuf, + sync::Arc, + time::Duration, +}; use axum::{ Json, Router, @@ -1506,10 +1512,11 @@ async fn camera_status(State(state): State>) -> Result let url = match state.camera { None => Err("HTTPS is off; start LinkHub with --https-port for phone cameras".to_owned()), Some(camera) => crate::tls::lan_host(camera.listen).map(|host| { - format!( - "https://{}/camera", - SocketAddr::new(host, camera.https_port) - ) + let authority = match host.parse::() { + Ok(address) => SocketAddr::new(address, camera.https_port).to_string(), + Err(_) => format!("{host}:{}", camera.https_port), + }; + format!("https://{authority}/camera") }), }; let (url, reason) = match url { @@ -1778,6 +1785,47 @@ mod tests { (status, serde_json::from_slice(&body).unwrap_or(Value::Null)) } + #[tokio::test] + async fn camera_urls_use_local_hostname_for_wildcard_listeners() { + let temp = TempDir::new().expect("temp directory"); + let config = JournalConfig::for_directory(temp.path().join("journal"), Uuid::new_v4()); + let (journal, task) = JournalHandle::start(config).await.expect("journal"); + let computer_name = hostname::get().unwrap().into_string().unwrap(); + let short_name = computer_name.split('.').next().unwrap().to_ascii_lowercase(); + let named_url = format!("https://{short_name}.local:9443/camera"); + for (listen, expected) in [ + ("0.0.0.0", named_url.as_str()), + ("::", named_url.as_str()), + ("192.168.1.20", "https://192.168.1.20:9443/camera"), + ("2001:db8::1", "https://[2001:db8::1]:9443/camera"), + ] { + let app = router_with_motor_and_static( + journal.clone(), + None, + None, + Some(ExperimentConfig { + directory: temp.path().join("experiments"), + camera: Some(CameraConfig { + listen: listen.parse().unwrap(), + https_port: 9443, + }), + }), + None, + false, + ); + let (status, camera) = json_response( + &app, + Request::get("/v1/camera").body(Body::empty()).unwrap(), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(camera["url"], expected, "{listen}"); + assert_eq!(camera["reason"], Value::Null); + assert!(camera["qr_svg"].as_str().unwrap().contains(", } +impl Default for LinkStatus { + fn default() -> Self { + Self { + connected: false, + ready: false, + phase: LinkPhase::Idle, + connection: String::new(), + port: None, + baud: None, + clock_epoch: 0, + target_system: 0, + target_component: 0, + // The generated flag default is SAFETY_ARMED, not an empty mask. + base_mode: MavModeFlag::empty(), + custom_mode: 0, + system_status: MavState::MAV_STATE_UNINIT, + latest_time_boot_ms: 0, + received_messages: 0, + transmitted_messages: 0, + received_bytes: 0, + transmitted_bytes: 0, + rx_bps: None, + tx_bps: None, + received_bytes_by_message: BTreeMap::new(), + transmitted_bytes_by_message: BTreeMap::new(), + rx_bps_by_message: BTreeMap::new(), + tx_bps_by_message: BTreeMap::new(), + dropped_frames: 0, + last_received_ns: None, + error: None, + last_error_stage: None, + last_error_ns: None, + attempts: 0, + consecutive_failures: 0, + connected_since_ns: None, + last_scan: None, + } + } +} + struct LinkThroughput { samples: VecDeque<(time::Instant, u64, u64)>, } @@ -1344,6 +1384,15 @@ mod tests { ); } + #[test] + fn initial_status_does_not_report_armed_without_a_heartbeat() { + let status = LinkStatus::default(); + let value = serde_json::to_value(&status).expect("status is serializable"); + assert!(!status.connected); + assert_eq!(status.received_messages, 0); + assert_eq!(value["base_mode"], ""); + } + #[test] fn throughput_new_connection_excludes_previous_traffic() { let start = time::Instant::now(); diff --git a/linkhub/src/motor.rs b/linkhub/src/motor.rs index 6f50029..65d21f6 100644 --- a/linkhub/src/motor.rs +++ b/linkhub/src/motor.rs @@ -406,8 +406,11 @@ impl MotorController { pub async fn scan(&self) -> Result, MotorError> { let _operation = self.inner.operation.lock().await; - if lock(&self.inner.state).running { - return Err(MotorError::Running); + { + let state = lock(&self.inner.state); + if state.connected && state.running { + return Err(MotorError::Running); + } } self.inner .backend @@ -808,6 +811,9 @@ async fn advance_motor( .await; if let Err(error) = result { record_motor_error(inner, &error).await; + if let Err(cleanup_error) = inner.backend.lock().await.disconnect().await { + tracing::error!(%cleanup_error, "Failed to release disconnected Bluetooth motor"); + } return Err(error); } if finished { @@ -1004,6 +1010,7 @@ mod bluetooth { } async fn disconnect(&mut self) -> Result<(), MotorError> { + self.adapter = None; let Some(peripheral) = self.peripheral.take() else { return Ok(()); }; @@ -1136,6 +1143,7 @@ mod tests { check_profile_step(&mut profile); assert!(!profile.segments.is_empty()); } + check_profile_step(&mut profile); assert!(profile.segments.is_empty()); assert_eq!(profile.position, f64::from(target)); @@ -1143,6 +1151,38 @@ mod tests { } } + #[tokio::test(start_paused = true)] + async fn link_loss_releases_backend_and_allows_scanning_and_reconnection() { + let backend = MockBackend::default(); + let fail_writes = Arc::clone(&backend.fail_writes); + let calls = Arc::clone(&backend.calls); + let motor = MotorController::with_backend(backend, MotorConfig::default(), None).unwrap(); + motor.connect().await.unwrap(); + motor + .set_running("motor-1", 50, MotorDirection::Forward, 2_000) + .await + .unwrap(); + assert_eq!(motor.scan().await, Err(MotorError::Running)); + *lock(&fail_writes) = true; + elapse(500).await; + let disconnected = motor.status(); + assert!(!disconnected.connected); + assert!(disconnected.running); + assert!(disconnected.error.is_some()); + assert_eq!(lock(&calls).last().unwrap(), "disconnect"); + let released_calls = lock(&calls).len(); + elapse(1_000).await; + assert_eq!(lock(&calls).len(), released_calls); + assert_eq!(motor.scan().await.unwrap().len(), 1); + assert_eq!(motor.status(), disconnected); + *lock(&fail_writes) = false; + motor.connect_device("motor-1".to_owned()).await.unwrap(); + assert!(motor.status().connected); + assert!(!motor.status().running); + assert!(motor.status().error.is_none()); + motor.close().await.unwrap(); + } + #[test] fn arbitrary_retargeting_preserves_command_and_rate_limits() { let mut profile = MotionProfile::default(); diff --git a/linkhub/src/tls.rs b/linkhub/src/tls.rs index 3c58d26..9d7b1fd 100644 --- a/linkhub/src/tls.rs +++ b/linkhub/src/tls.rs @@ -3,11 +3,7 @@ //! camera page is served over HTTPS with a certificate LinkHub generates and //! keeps under `/tls/` so phones accept it once per host set. -use std::{ - io, - net::{IpAddr, SocketAddr, UdpSocket}, - path::Path, -}; +use std::{io, net::IpAddr, path::Path}; use axum_server::tls_rustls::RustlsConfig; use tokio::fs; @@ -17,32 +13,44 @@ const KEY_FILE: &str = "key.pem"; const HOSTS_FILE: &str = "hosts.txt"; /// The address phones should use to reach a server listening on `listen`. -pub fn lan_host(listen: IpAddr) -> Result { +pub fn lan_host(listen: IpAddr) -> Result { if listen.is_loopback() { return Err(format!( "LinkHub listens on {listen} only; start it with --listen 0.0.0.0 for phones" )); } if !listen.is_unspecified() { - return Ok(listen); + return Ok(listen.to_string()); } - default_route_address().ok_or_else(|| "could not determine this machine's LAN address".into()) + let name = hostname::get() + .map_err(|error| format!("could not read this machine's computer name: {error}"))? + .into_string() + .map_err(|_| "this machine's computer name is not valid Unicode".to_owned())?; + local_hostname(&name) } -/// Address of the interface holding the default route. Connecting a UDP -/// socket only selects a route; no packet is sent. -fn default_route_address() -> Option { - let socket = UdpSocket::bind("0.0.0.0:0").ok()?; - socket.connect(SocketAddr::from(([192, 0, 2, 1], 9))).ok()?; - let address = socket.local_addr().ok()?.ip(); - (!address.is_loopback() && !address.is_unspecified()).then_some(address) +fn local_hostname(name: &str) -> Result { + let label = name.split('.').next().unwrap_or_default(); + if label.is_empty() + || label.len() > 63 + || !label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + || label.starts_with('-') + || label.ends_with('-') + { + return Err(format!( + "computer name {name:?} cannot be used as a .local DNS hostname" + )); + } + Ok(format!("{}.local", label.to_ascii_lowercase())) } /// Loads the persisted certificate, regenerating it when the host set changed. pub async fn load_or_create(directory: &Path, listen: IpAddr) -> io::Result { let mut hosts = vec!["localhost".to_owned(), "127.0.0.1".to_owned()]; - if let Ok(host) = lan_host(listen) { - hosts.push(host.to_string()); + if !listen.is_loopback() { + hosts.push(lan_host(listen).map_err(io::Error::other)?); } hosts.sort(); hosts.dedup(); @@ -73,10 +81,71 @@ mod tests { assert!(lan_host("127.0.0.1".parse().unwrap()).is_err()); assert_eq!( lan_host("192.168.1.20".parse().unwrap()), - Ok("192.168.1.20".parse().unwrap()) + Ok("192.168.1.20".to_owned()) ); } + #[test] + fn computer_names_use_a_single_local_suffix_and_valid_dns_labels() { + for name in ["BENCH-PC", "bench-pc.local", "bench-pc.example.com"] { + assert_eq!(local_hostname(name).unwrap(), "bench-pc.local"); + } + for name in [ + "", + ".local", + "-pc", + "pc-", + "bench_pc", + "pc name", + &"x".repeat(64), + ] { + assert!(local_hostname(name).is_err(), "{name}"); + } + } + + #[tokio::test] + async fn wildcard_certificate_authenticates_the_computer_local_hostname() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let temp = tempfile::tempdir().unwrap(); + let listen = "0.0.0.0".parse().unwrap(); + let host = lan_host(listen).unwrap(); + assert!(host.ends_with(".local")); + let config = load_or_create(temp.path(), listen).await.unwrap(); + let certificate = fs::read(temp.path().join(CERT_FILE)).await.unwrap(); + let hosts = fs::read_to_string(temp.path().join(HOSTS_FILE)) + .await + .unwrap(); + assert!(hosts.lines().any(|name| name == host)); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = listener.local_addr().unwrap(); + let server = axum_server::from_tcp_rustls(listener, config) + .unwrap() + .serve( + axum::Router::new() + .route("/", axum::routing::get(|| async { "ok" })) + .into_make_service(), + ); + let task = tokio::spawn(server); + let result = async { + reqwest::Client::builder() + .no_proxy() + .add_root_certificate(reqwest::Certificate::from_pem(&certificate).unwrap()) + .resolve(&host, address) + .timeout(std::time::Duration::from_secs(5)) + .build() + .unwrap() + .get(format!("https://{host}:{}/", address.port())) + .send() + .await? + .text() + .await + } + .await; + task.abort(); + assert_eq!(result.unwrap(), "ok"); + } + #[tokio::test] async fn reuses_certificate_until_hosts_change() { rustls::crypto::ring::default_provider() diff --git a/run_linkhub_ui.cmd b/run_linkhub_ui.cmd index b07b5db..eb33846 100644 --- a/run_linkhub_ui.cmd +++ b/run_linkhub_ui.cmd @@ -4,6 +4,8 @@ setlocal set "REPO=%~dp0" set "REPO=%REPO:~0,-1%" set "BUILD=0" +set "CONFIGURE_FIREWALL=0" +set "SETUP_DONE=0" set "CONNECTION=" set "BAUD=" set "PORT=" @@ -15,6 +17,11 @@ if /i "%~1"=="--build" ( shift goto parse_args ) +if /i "%~1"=="--configure-firewall" ( + set "CONFIGURE_FIREWALL=1" + shift + goto parse_args +) if not defined CONNECTION ( set "CONNECTION=%~1" ) else if not defined BAUD ( @@ -38,13 +45,14 @@ if not defined PORT set "PORT=8999" if not defined LINKHUB_HTTPS_PORT set "LINKHUB_HTTPS_PORT=9443" if not defined CONNECTION ( - echo Usage: %~nx0 [--build] ^ [baud] [port] + echo Usage: %~nx0 [--build] [--configure-firewall] ^ [baud] [port] echo. echo Hardware: echo %~nx0 auto echo %~nx0 COM7 echo %~nx0 COM7 57600 8999 echo %~nx0 --build auto + echo %~nx0 --configure-firewall auto echo %~nx0 ble:DroneBridge echo. echo SITL: @@ -55,6 +63,9 @@ if not defined CONNECTION ( exit /b 2 ) +set "BAUD_ARG=" +if /i not "%BAUD%"=="auto" set BAUD_ARG=--baud "%BAUD%" + if "%BUILD%"=="1" goto setup if not exist "%REPO%\linkhub\target\release\linkhub.exe" goto setup if not exist "%REPO%\linkhub-ui\dist\index.html" goto setup @@ -66,6 +77,7 @@ if errorlevel 1 ( echo ERROR: Project setup failed. LinkHub was not started. exit /b 1 ) +set "SETUP_DONE=1" :verify_build if not exist "%REPO%\linkhub\target\release\linkhub.exe" ( @@ -78,12 +90,34 @@ if not exist "%REPO%\linkhub-ui\dist\index.html" ( exit /b 1 ) -echo [INFO] Starting LinkHub on http://127.0.0.1:%PORT%/ -echo [INFO] LAN access: http port %PORT%, https port %LINKHUB_HTTPS_PORT% (phone cameras) +call :run_linkhub --help >nul +if not errorlevel 1 goto start +if "%SETUP_DONE%"=="1" ( + echo ERROR: Built LinkHub does not accept the launcher arguments. LinkHub was not started. + exit /b 1 +) +echo [INFO] Existing LinkHub does not accept the launcher arguments. Rebuilding through setup.cmd ... +goto setup + +:start +if "%CONFIGURE_FIREWALL%"=="1" ( + call powershell -NoProfile -ExecutionPolicy Bypass -File "%REPO%\scripts\configure_linkhub_firewall.ps1" -ProgramPath "%REPO%\linkhub\target\release\linkhub.exe" -HttpPort "%PORT%" -HttpsPort "%LINKHUB_HTTPS_PORT%" + if errorlevel 1 ( + echo ERROR: Firewall configuration failed or was cancelled. LinkHub was not started. + exit /b 1 + ) +) +echo [INFO] Starting LinkHub on http://0.0.0.0:%PORT%/ (all network interfaces) +echo [INFO] LAN access: http://%COMPUTERNAME%.local:%PORT%/ or https://%COMPUTERNAME%.local:%LINKHUB_HTTPS_PORT%/ (phone cameras) echo [INFO] Connection: %CONNECTION% Baud: %BAUD% echo [INFO] Press Ctrl+C to stop. -set "BAUD_ARG=" -if /i not "%BAUD%"=="auto" set BAUD_ARG=--baud "%BAUD%" +call :run_linkhub + +set "EXIT_CODE=%ERRORLEVEL%" +if not "%EXIT_CODE%"=="0" echo ERROR: LinkHub exited with code %EXIT_CODE%. +exit /b %EXIT_CODE% + +:run_linkhub call "%REPO%\linkhub\target\release\linkhub.exe" serve ^ --connection "%CONNECTION%" ^ %BAUD_ARG% ^ @@ -93,8 +127,5 @@ call "%REPO%\linkhub\target\release\linkhub.exe" serve ^ --data-dir "%REPO%\simulation\logs\linkhub" ^ --static-dir "%REPO%\linkhub-ui\dist" ^ --motor-name-prefix BLDC ^ - --no-cache - -set "EXIT_CODE=%ERRORLEVEL%" -if not "%EXIT_CODE%"=="0" echo ERROR: LinkHub exited with code %EXIT_CODE%. -exit /b %EXIT_CODE% + --no-cache %* +exit /b %ERRORLEVEL% diff --git a/scripts/configure_linkhub_firewall.ps1 b/scripts/configure_linkhub_firewall.ps1 new file mode 100644 index 0000000..3f62514 --- /dev/null +++ b/scripts/configure_linkhub_firewall.ps1 @@ -0,0 +1,62 @@ +[CmdletBinding(SupportsShouldProcess = $true)] +param( + [Parameter(Mandatory = $true)] + [string]$ProgramPath, + [ValidateRange(1, 65535)] + [int]$HttpPort = 8999, + [ValidateRange(1, 65535)] + [int]$HttpsPort = 9443 +) + +$ErrorActionPreference = 'Stop' +$env:PSModulePath = (Join-Path $PSHOME 'Modules') + [IO.Path]::PathSeparator + $env:PSModulePath +$program = (Resolve-Path -LiteralPath $ProgramPath).ProviderPath +if (-not (Test-Path -LiteralPath $program -PathType Leaf)) { + throw "LinkHub executable not found: $program" +} + +$principal = [Security.Principal.WindowsPrincipal]::new( + [Security.Principal.WindowsIdentity]::GetCurrent() +) +if (-not $WhatIfPreference -and -not $principal.IsInRole( + [Security.Principal.WindowsBuiltInRole]::Administrator +)) { + Write-Host '[INFO] Requesting administrator approval to configure Private LAN firewall access ...' + $arguments = '-NoProfile -ExecutionPolicy Bypass -File "{0}" -ProgramPath "{1}" -HttpPort {2} -HttpsPort {3}' -f ` + $PSCommandPath, $program, $HttpPort, $HttpsPort + $process = Start-Process -FilePath "$PSHOME\powershell.exe" -Verb RunAs ` + -ArgumentList $arguments -Wait -PassThru + if ($process.ExitCode -ne 0) { + throw "Elevated firewall configuration failed with exit code $($process.ExitCode)." + } + exit 0 +} + +$ruleName = 'RAWES-LinkHub-Private-LAN' +$existing = Get-NetFirewallRule -PolicyStore PersistentStore | + Where-Object { $_.Name -eq $ruleName } +$settings = @{ + Name = $ruleName + DisplayName = 'RAWES LinkHub (Private LAN)' + Description = 'Allow local-subnet access to LinkHub HTTP and HTTPS on Private networks only.' + PolicyStore = 'PersistentStore' + Enabled = 'True' + Direction = 'Inbound' + Action = 'Allow' + Profile = 'Private' + Program = $program + Protocol = 'TCP' + LocalPort = @($HttpPort, $HttpsPort) | Sort-Object -Unique + RemoteAddress = 'LocalSubnet' + EdgeTraversalPolicy = 'Block' + WhatIf = [bool]$WhatIfPreference +} +if ($existing) { + Set-NetFirewallRule @settings | Out-Null +} else { + New-NetFirewallRule @settings | Out-Null +} +if (-not $WhatIfPreference) { + Write-Host "[INFO] LinkHub firewall rule configured for Private LAN TCP ports $HttpPort and $HttpsPort." + Write-Host '[INFO] Public networks remain unchanged. Explicit block rules or managed policy may still prevent access.' +} diff --git a/tests/unit/test_windows_setup.py b/tests/unit/test_windows_setup.py index 4cd0999..a283b93 100644 --- a/tests/unit/test_windows_setup.py +++ b/tests/unit/test_windows_setup.py @@ -15,6 +15,7 @@ REPO = Path(__file__).resolve().parents[2] WINDOWS_ONLY = pytest.mark.skipif(sys.platform != "win32", reason="Windows bootstrap") +pytestmark = pytest.mark.timeout(60) def write_cmd(path: Path, source: str) -> None: @@ -23,7 +24,7 @@ def write_cmd(path: Path, source: str) -> None: @pytest.fixture -def bootstrap(tmp_path: Path) -> tuple[Path, Path, Path, dict[str, str]]: +def bootstrap(tmp_path: Path, mock_server_exe: Path) -> tuple[Path, Path, Path, dict[str, str]]: project = tmp_path / "project with spaces" project.mkdir() for name in ("setup.cmd", "setup.sh", "run_linkhub_ui.cmd", ".node-version", ".python-version"): @@ -50,6 +51,7 @@ def bootstrap(tmp_path: Path) -> tuple[Path, Path, Path, dict[str, str]]: "MOCK_CPP_READY": str(tmp_path / "cpp-ready"), "MOCK_CPP_ROOT": str(tmp_path / "visual studio"), "MOCK_PYTHON": str(project / ".tools" / "python" / "cpython-3.14" / "python.exe"), + "MOCK_SERVER_EXE": str(mock_server_exe), "UV_NO_SYNC": "1", }) for name in ("LINKHUB_CONNECTION", "LINKHUB_BAUD", "LINKHUB_PORT"): @@ -88,6 +90,10 @@ def bootstrap(tmp_path: Path) -> tuple[Path, Path, Path, dict[str, str]]: write_cmd(bin_dir / "powershell.cmd", r""" @echo off echo powershell %*>>"%MOCK_LOG%" + if /i "%~5"=="%MOCK_PROJECT%\scripts\configure_linkhub_firewall.ps1" ( + if "%MOCK_FAIL%"=="firewall" exit /b 23 + exit /b 0 + ) if "%MOCK_FAIL%"=="node-setup" exit /b 1 mkdir "%MOCK_PROJECT%\.tools\node" 2>nul copy /y "%MOCK_BIN%\node.template" "%MOCK_PROJECT%\.tools\node\node.cmd" >nul @@ -101,6 +107,7 @@ def bootstrap(tmp_path: Path) -> tuple[Path, Path, Path, dict[str, str]]: if "%MOCK_FAIL%"=="cargo" exit /b 15 if not defined MOCK_BUILD_ARTIFACTS exit /b 0 copy /y "%MOCK_SERVER_EXE%" "%MOCK_PROJECT%\linkhub\target\release\linkhub.exe" >nul + if exist "%MOCK_PROJECT%\linkhub\target\release\outdated" del "%MOCK_PROJECT%\linkhub\target\release\outdated" mkdir "%MOCK_PROJECT%\linkhub-ui\dist" 2>nul echo built>"%MOCK_PROJECT%\linkhub-ui\dist\index.html" exit /b 0 @@ -172,7 +179,6 @@ def run_script( cwd=project.parent, capture_output=True, text=True, - input="echo MOCK_SERVER %cmdcmdline%\nexit /b 7\n", timeout=20, ) @@ -430,10 +436,43 @@ def test_setup_repairs_an_existing_build_tools_installation_missing_sdk( assert any(line.startswith("visual-studio modify ") for line in commands(bootstrap)) +@pytest.fixture(scope="session") +def mock_server_exe(tmp_path_factory: pytest.TempPathFactory) -> Path: + if sys.platform != "win32": + pytest.skip("Windows launcher executable") + path = tmp_path_factory.mktemp("mock-linkhub") / "linkhub.exe" + source = r""" + public class MockLinkHub { + public static int Main(string[] args) { + if (System.Array.IndexOf(args, "--help") >= 0) { + if (System.Environment.GetEnvironmentVariable("MOCK_FAIL") == "server-help" + || System.IO.File.Exists(System.IO.Path.Combine( + System.AppDomain.CurrentDomain.BaseDirectory, "outdated"))) { + System.Console.Error.WriteLine("error: unexpected argument '--https-port' found"); + return 2; + } + return 0; + } + System.Console.WriteLine("MOCK_SERVER " + System.Environment.CommandLine); + return 7; + } + } + """ + result = subprocess.run( + [ + "powershell.exe", "-NoProfile", "-NonInteractive", "-Command", + "$source = [Console]::In.ReadToEnd(); " + f"Add-Type -TypeDefinition $source -OutputAssembly '{path}' -OutputType ConsoleApplication", + ], + input=source, capture_output=True, text=True, timeout=30, + ) + assert result.returncode == 0, result.stdout + result.stderr + return path + + def server_artifacts(bootstrap: tuple[Path, Path, Path, dict[str, str]]) -> None: project, _, _, env = bootstrap - env["MOCK_SERVER_EXE"] = env["COMSPEC"] - shutil.copy2(env["COMSPEC"], project / "linkhub" / "target" / "release" / "linkhub.exe") + shutil.copy2(env["MOCK_SERVER_EXE"], project / "linkhub" / "target" / "release" / "linkhub.exe") (project / "linkhub-ui" / "dist").mkdir(exist_ok=True) (project / "linkhub-ui" / "dist" / "index.html").write_text("built") @@ -457,11 +496,13 @@ def test_launcher_delegates_setup_and_preserves_connection_arguments( result = run_script(bootstrap, "run_linkhub_ui.cmd", *args) assert result.returncode == 7 assert 'uv python install --upgrade --no-bin --no-registry "3.14"' in commands(bootstrap) - assert "http://127.0.0.1:9123/" in result.stdout + assert "http://0.0.0.0:9123/ (all network interfaces)" in result.stdout assert "Connection: tcp:127.0.0.1:5760 Baud: auto" in result.stdout assert "MOCK_SERVER" in result.stdout - assert 'serve --connection "tcp:127.0.0.1:5760"' in result.stdout + assert 'serve ' in result.stdout + assert '--connection "tcp:127.0.0.1:5760"' in result.stdout assert '--port "9123"' in result.stdout + assert "--listen 0.0.0.0" in result.stdout assert "--baud" not in result.stdout @@ -477,6 +518,28 @@ def test_prebuilt_launcher_does_not_require_python_uv_or_winget( assert "MOCK_SERVER" in result.stdout +@WINDOWS_ONLY +@pytest.mark.parametrize("fails_after_build", [False, True]) +def test_launcher_rebuilds_incompatible_binary_before_starting( + bootstrap: tuple[Path, Path, Path, dict[str, str]], fails_after_build: bool, +): + installed_tools(bootstrap) + server_artifacts(bootstrap) + project, _, _, env = bootstrap + (project / "linkhub" / "target" / "release" / "outdated").touch() + env["MOCK_BUILD_ARTIFACTS"] = "1" + if fails_after_build: + env["MOCK_FAIL"] = "server-help" + result = run_script(bootstrap, "run_linkhub_ui.cmd", "auto") + assert result.returncode == (1 if fails_after_build else 7), result.stdout + result.stderr + assert "Existing LinkHub does not accept the launcher arguments" in result.stdout + assert sum(line.startswith("cargo build ") for line in commands(bootstrap)) == 1 + assert ("MOCK_SERVER" in result.stdout) is not fails_after_build + assert ("Starting LinkHub" in result.stdout) is not fails_after_build + if fails_after_build: + assert "Built LinkHub does not accept the launcher arguments" in result.stdout + + @WINDOWS_ONLY def test_launcher_preserves_environment_defaults_and_explicit_baud( bootstrap: tuple[Path, Path, Path, dict[str, str]], @@ -495,6 +558,83 @@ def test_launcher_preserves_environment_defaults_and_explicit_baud( assert not commands(bootstrap) +@WINDOWS_ONLY +@pytest.mark.parametrize("fails", [False, True]) +def test_launcher_configures_firewall_only_when_requested( + bootstrap: tuple[Path, Path, Path, dict[str, str]], fails: bool, +): + server_artifacts(bootstrap) + project, _, _, env = bootstrap + env["LINKHUB_HTTPS_PORT"] = "9444" + if fails: + env["MOCK_FAIL"] = "firewall" + result = run_script( + bootstrap, "run_linkhub_ui.cmd", "--configure-firewall", "auto", "auto", "9123", + ) + assert result.returncode == (1 if fails else 7), result.stdout + result.stderr + calls = commands(bootstrap) + assert len(calls) == 1 + assert f'-File "{project / "scripts" / "configure_linkhub_firewall.ps1"}"' in calls[0] + assert f'-ProgramPath "{project / "linkhub" / "target" / "release" / "linkhub.exe"}"' in calls[0] + assert '-HttpPort "9123" -HttpsPort "9444"' in calls[0] + assert ("MOCK_SERVER" in result.stdout) is not fails + if fails: + assert "Firewall configuration failed or was cancelled" in result.stdout + + +@WINDOWS_ONLY +@pytest.mark.parametrize("existing", [False, True]) +def test_firewall_helper_scopes_new_and_updated_rules_to_private_lan( + tmp_path: Path, mock_server_exe: Path, existing: bool, +): + wrapper = tmp_path / "mock-firewall.ps1" + wrapper.write_text(textwrap.dedent(r""" + function Get-NetFirewallRule { + param($PolicyStore) + if ($env:TEST_EXISTING -eq 'True') { + [pscustomobject]@{ Name = 'RAWES-LinkHub-Private-LAN' } + } + } + function Save-FirewallRule { + [CmdletBinding(SupportsShouldProcess = $true)] + param($Name, $DisplayName, $Description, $PolicyStore, $Enabled, + $Direction, $Action, $Profile, $Program, $Protocol, + $LocalPort, $RemoteAddress, $EdgeTraversalPolicy) + @{ + Operation = $MyInvocation.InvocationName + Settings = $PSBoundParameters + } | ConvertTo-Json -Depth 4 | Set-Content $env:TEST_RULE -WhatIf:$false + } + Set-Alias New-NetFirewallRule Save-FirewallRule + Set-Alias Set-NetFirewallRule Save-FirewallRule + & $args[0] -ProgramPath $args[1] -HttpPort 9123 -HttpsPort 9444 -WhatIf + """), encoding="ascii") + env = os.environ.copy() + env["TEST_EXISTING"] = str(existing) + rule_path = tmp_path / "rule.json" + env["TEST_RULE"] = str(rule_path) + result = subprocess.run( + ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(wrapper), + str(REPO / "scripts" / "configure_linkhub_firewall.ps1"), str(mock_server_exe)], + capture_output=True, text=True, env=env, timeout=20, + ) + assert result.returncode == 0, result.stdout + result.stderr + rule = json.loads(rule_path.read_text(encoding="utf-8-sig")) + assert rule["Operation"] == ("Set-NetFirewallRule" if existing else "New-NetFirewallRule") + settings = rule["Settings"] + assert settings["Program"] == str(mock_server_exe) + assert settings["LocalPort"] == [9123, 9444] + assert settings["Protocol"] == "TCP" + assert settings["Direction"] == "Inbound" + assert settings["Action"] == "Allow" + assert settings["Enabled"] == "True" + assert settings["Profile"] == "Private" + assert settings["RemoteAddress"] == "LocalSubnet" + assert settings["EdgeTraversalPolicy"] == "Block" + assert settings["PolicyStore"] == "PersistentStore" + assert settings["WhatIf"]["IsPresent"] is True + + @WINDOWS_ONLY def test_launcher_does_not_start_after_setup_failure( bootstrap: tuple[Path, Path, Path, dict[str, str]],