From 416f3181ccf704339c955714d8b65f553b1c1098 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:52:02 +1000 Subject: [PATCH 01/19] Add a UEVR mod manager: install, play in VR and remove from Frame Control Installed Unreal Engine games get a "VR mod" button. ui/frame_mods.py runs on the Frame: it downloads the pinned official UEVR 1.05 release and Microsoft's .NET 6 runtimes (hash-checked, safely unpacked) into the game's Proton prefix with a receipt; starts the game, runs the injector in the game's own Wine session and presses OpenVR + Inject with XSendEvent (gamescope keeps real input on the game); confirms UEVRBackend.dll is loaded and SteamVR counts frames; and removes exactly what it added. Verified on a real Frame 2026-09-29 with Gravitas, through the UI: install, four injections (three from a cold start), remove back to the pre-install prefix listing. The headset was unworn, so the VR image, tracking and controls are not verified. Part of #26. Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 2 +- docs/evidence/mods-2026-09-29.md | 78 ++++++ docs/how-the-frame-works.md | 1 + docs/img/uevr-dialog.png | Bin 0 -> 34646 bytes docs/mods.md | 89 ++++++- docs/steam-games.md | 6 +- tests/test_mods.py | 270 +++++++++++++++++++ ui/frame_mods.py | 437 +++++++++++++++++++++++++++++++ ui/index.html | 62 ++++- ui/server.py | 25 +- 10 files changed, 943 insertions(+), 27 deletions(-) create mode 100644 docs/evidence/mods-2026-09-29.md create mode 100644 docs/img/uevr-dialog.png create mode 100644 tests/test_mods.py create mode 100644 ui/frame_mods.py diff --git a/README.md b/README.md index cc952d0..eb425ad 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ Frame's software fits together, all checked against a real headset and labelled | [Sideloading Linux and Windows games](docs/sideloading.md) | A .zip, folder or .exe as a Steam Devkit Game, runtime detection | | [Install links for websites](docs/web-install.md) | `frame-control://install` links and manifests, the rules, a button to paste | | [Steam games](docs/steam-games.md) · [VR video](docs/vr-video.md) · [WebXR in Chromium](docs/webxr-chromium.md) | Installing and buying, watching VR180/360, the Chromium build | -| [VR mods and custom songs](docs/mods.md) | Per-game feasibility, real-Frame results and blockers; no installer yet | +| [VR mods and custom songs](docs/mods.md) | UEVR for Unreal games from Frame Control (install, play in VR, remove), the per-game table, Beat Saber blockers | | [SSH](docs/ssh.md) · [Streaming](docs/streaming.md) · [Files](docs/file-transfer.md) · [Panels](docs/panels.md) · [Tailscale](docs/tailscale.md) | Topic notes | | [Frame Control for iPhone](docs/iphone.md) | The iPhone and iPad app, how it runs the server on the Frame, pairing | | [Recovery and OS images](docs/recovery-and-images.md) | Where to download the Frame's OS, what's inside, testing without the headset | diff --git a/docs/evidence/mods-2026-09-29.md b/docs/evidence/mods-2026-09-29.md new file mode 100644 index 0000000..0015ec1 --- /dev/null +++ b/docs/evidence/mods-2026-09-29.md @@ -0,0 +1,78 @@ +# UEVR from Frame Control, 2026-09-29 + +**Verified observations**, with limits below. Same device and software as +[2026-09-28](mods-2026-09-28.md): aarch64, SteamOS `0.4.1`, BUILD_ID +`20260925.6191901`, Proton `11.0-2c` ARM64, SteamVR `2.18.1`. Times are the +Frame's AEST clock. Headset tests ran under the shared +`/tmp/frame-test.lock`, taken 11:13–11:28 and 11:33–11:49. Battery 45 % → +93 %, on charge throughout. + +**Not observed:** the VR image, head tracking and controller input. SteamVR +reported `activity_level` 3 (user interaction timeout; the headset was not +being worn) with `average_target_fps` 1. Every `frame_vrshot.py` stereo +capture was a uniform dark frame. Frame submits prove the app is presenting +to SteamVR, not that the image is correct. + +## Manual injection (11:13–11:28) + +Game launched with `steam steam://rungameid/1067310`. `UEVRInjector.exe` was +started with the game process's Wine variables, and its WPF window drew +through DXVK's D3D9. It listed `Drop-Win64-Shipping (pid: 320) (SkyArk +(64-bit, PCD3D_SM5))`, a Wine-side process id. + +- `--attach=Drop-Win64-Shipping` didn't inject. The button still read + **Inject**, and the saved `OpenVRRadio=True` in `AppData/Local/praydog/…/user.config` + was not restored on the next start. +- XTest clicks landed on the game: `XQueryPointer` reported child + `0x2000001` (the game) at the injector's coordinates, and + `XLowerWindow`/`XRaiseWindow`/`XSetInputFocus` didn't change that. +- `XSendEvent` button events to the injector window worked. After OpenVR and + Inject, `/proc//maps` contained + `drive_c/frame26/uevr/UEVRBackend.dll` and `openvr_api.dll`, next to + Proton's `vrclient_x64.dll`. UEVR's log: + +```text +[11:17:32.948] Hooking D3D11 +[11:17:33.020] Hooked DirectX 11 +[11:17:34.263] Framework initialized +[11:17:34.475] [VR] Requested runtime: openvr_api.dll +[11:17:39.791] UGameViewportClient::Draw called for the first time. +[11:17:39.792] is stereo enabled called! +``` + +It also logged repeated `Failed to initialize Framework on DirectX 12` (probing +before it chose D3D11) and failed Unreal scans, for example `Failed to locate +r.EnableStereoEmulation cvar` and `Failed to find FSceneView constructor`. +SteamVR loaded UEVR's action manifest and `bindings_oculus_touch.json` for +`steam.app.1067310`. `vrcmd --stats` then showed `"key" : +"steam.app.1067310"` with `frame_submits` 4439, then 5506 a few seconds later. + +A second session's injector exited within about 20 seconds. The third, +started fresh, injected again (`frame_submits` 1412). After the game was +stopped, a plain launch had no UEVR modules and no SteamVR scene app. All test +files were removed. + +## Through Frame Control (11:33–11:49) + +Local `ui/server.py` against the `frame` alias. First the API, then the +page's **VR mod** dialog, driven with a headless Chromium: + +| Step | Result | +|---|---| +| `status` for 2177750 (HL2 VR) | `eligible: false`; `install` refused ("doesn't look like an Unreal Engine game") | +| `install` for 1067310 | 3 s. Three downloads, hashes matched, receipt written | +| `start`, game running | First run refused: `the UEVR window is 960 px wide, not 625`. It was measured before WPF laid it out; `start` now waits for the width to settle. Rerun: injected, `frame_submits` 27 (36 s) | +| `uninstall` while running | Refused: "the game is running; quit it first" | +| `start`, game not running | Launched the game, injected, `frame_submits` 45 (55 s) | +| UI: Remove, Install | Worked; the prefix listing matched its pre-install state except an empty `UnrealVRMod`, which uninstall now also removes | +| UI: Play in VR | Failed once: the injector died with `Process terminated. … Resource name: Arg_AccessViolationException`, after `Fontconfig error: No writable cache directories` (it had no `HOME`). Fixed by keeping the normal environment under the game's; `start` also retries up to three times | +| UI: Play in VR ×4 | 4 of 4 injected. The three cold starts took 54, 58 and 58 s; frame submits 56, 71, 80 | +| UI: Remove | `drive_c`, `AppData/Roaming` and `AppData/Local` listings matched the pre-install state; download cache and receipt gone | + +## Left on the Frame + +- Gravitas (free, 7.4 GB, installed 2026-09-28 for this work) is still + installed; nothing else from this work is left. +- No `UEVRInjector.exe` or game processes were left running. Steam and + SteamVR were running at the end. +- The test lock was released at 11:49. diff --git a/docs/how-the-frame-works.md b/docs/how-the-frame-works.md index 5c392d1..863b527 100644 --- a/docs/how-the-frame-works.md +++ b/docs/how-the-frame-works.md @@ -47,6 +47,7 @@ Lepton (Android 11, podman container "lepton-dev") ← its own panel, app 305600 | The Steam client runs with `-cef-enable-debugging`, so its UI answers Chrome DevTools on loopback `127.0.0.1:8080`. The `SharedJSContext` page has `appStore` (owned apps), `downloadsStore` and `SteamClient.*`. `steam steam://install/` over SSH installs an owned game; when the options dialog shows (state 7), `SteamClient.Installs.ContinueInstall()` accepts it. **Verified 2026-09-25** with Balatro and Broforce. The Frame rating is `steam_hw_compat_category_packed >> 8 & 3`. | [steam-games.md](steam-games.md), `ui/frame_steam.py` | | Chromium Flatpak 154 has **no immersive WebXR**: `navigator.xr` exists, but `isSessionSupported("immersive-vr")` returns `false`. Web VR180 players (DL8/DeoVR embeds) still play video inline as a flat, pannable view, and their VR button opens a tab on immersiveweb.dev. Forcing it doesn't help. `--enable-features=OpenXR,WebXR --force-webxr-runtime=openxr`, with `/opt/steamvr` and `XR_RUNTIME_JSON` exposed to the Flatpak, still returns `false`. The aarch64 Linux binary has no OpenXR code at all (no `XR_RUNTIME_JSON`, `xrGetInstanceProcAddr` or loader strings), even though `chrome://flags` lists `#webxr-runtime` → OpenXR. **Why (verified against source 2026-09-25):** M154 is the first release that compiles OpenXR on Linux (`enable_openxr` includes `is_linux`, `checkout_openxr` is true in Flathub's tarball, and Flathub's GN args don't turn it off). But `content/services/isolated_xr_device/xr_runtime_provider.cc` only creates an OpenXR device under `ENABLE_OPENXR && IS_WIN`, on 154, 155 and `main`. Nothing on Linux calls the OpenXR code, so the linker drops it. The missing pieces are two unmerged Gerrit CLs (bug 506004811): [8132979](https://chromium-review.googlesource.com/c/chromium/src/+/8132979) wires the provider on Linux (with `kOpenXR` still off by default, so it needs `--enable-features=OpenXR`), and [8441736](https://chromium-review.googlesource.com/c/chromium/src/+/8441736) runs the XR service in a sandbox that allows SteamVR's sockets. The Frame does have an aarch64 runtime: `~/.config/openxr/1/active_runtime.json` → SteamVR `bin/linuxarm64/vrclient.so`. To watch in 3D, use a native player, or a Chromium built with those two CLs ([webxr-chromium.md](webxr-chromium.md)). That build (156.0.8071.0, arm64) reports `immersive-vr` as supported and starts a session that SteamVR takes as its scene app. With the headset on, the WebXR samples scene and three.js's stereo 360 video demo showed in 3D (verified 2026-09-26, seccomp sandbox off). Started with `--remote-debugging-port=9222`, Chromium answers DevTools on loopback. **Verified 2026-09-25**, BUILD_ID 20260922.6101926. | Web video, [panels.md](panels.md) | | **DeoVR (Steam app 837380, Windows/Unity) runs immersively** under Proton ARM64 + FEX: Unity's OpenVR XR plugin finds `OpenVR Headset(Steam Frame)` and the `frame_controller`, the GPU shows as Turnip Adreno 750, and AVPro Video decodes through `MF-MediaEngine-Hardware`. It played 7680×3840 and 8192×4096 H.265 VR180 SBS streams in dome/fisheye mode (`FirstFrameReady`). Unity's own `VideoPlayer` (used for grid thumbnails) fails with `0xc00d36bb`, so thumbnail previews stay blank. The first launch takes about 45 s (`ComputeShaders: InitAsync`). Log: `compatdata/837380/pfx/drive_c/users/steamuser/AppData/LocalLow/Deo VR/Deo VR/Player.log`. **Verified 2026-09-25**, BUILD_ID 20260922.6101926. | [vr-video.md](vr-video.md) | +| **A second Windows program can join a running Proton game.** Copy `WINEPREFIX`, `WINEDLLPATH`, `WINEDLLOVERRIDES`, `PATH` (Proton's `files/bin-arm64` comes first) and `DISPLAY` from `/proc//environ`, keeping your own `HOME` and the rest, and run `wine prog.exe` from an ordinary SSH shell. It shares the game's wineserver (outside the pressure-vessel container). Don't copy `WINESERVERSOCKET`, which is an inherited fd. A game's windows live on gamescope's X display for that app (`:1` for Gravitas), where the full-screen game keeps the pointer and focus: XTest clicks and restacking don't reach other windows, but `XSendEvent` button events sent to a window do. `xwd` captures WPF/DXVK windows but shows Vulkan game windows as black. **Verified 2026-09-29**, BUILD_ID 20260925.6191901, Proton 11.0-2c ARM64. | [mods.md](mods.md) | | **Wolvic (VR browser APK) runs in Lepton against SteamVR's OpenXR**, with limits. The stock Lynx build aborts (`Runtime doesn't support selected swapChain color format`: it wants `GL_RGBA8`), and the stock Quest build fails with `XR_ERROR_API_VERSION_UNSUPPORTED`. Patching `DeviceDelegateOpenXR::GetSwapChainCreateInfo` in the Lynx build's `libnative-lib.so` to `GL_SRGB8_ALPHA8` (0x8C43) and re-signing fixes start-up. The Gecko engine then segfaults in `libxul`. The Chromium-engine build (Lynx v1.3-chromium) browses fine as an immersive app. Its page reports `isSessionSupported("immersive-vr") == true`, and `requestSession` succeeds, running about 36 rAF/s, but the headset shows **black** for WebXR content, or Wolvic's loading spinner that never clears, until the session is ended. Video decodes on the software `OMX.google.h264.decoder`. Tapping the URL bar's selection menu crashes it (no clipboard service). Open URLs with `am start -a VIEW -n com.igalia.wolvic/.VRBrowserActivity -d ` over the instance's ADB. DevTools is at `localabstract:content_shell_devtools_remote`. **Verified 2026-09-25**, BUILD_ID 20260922.6101926. | Web VR video, [apks.md](apks.md) | | Tailscale runs without root as a userspace `tailscaled` user service (static arm64 build in `~/.local/share/tailscale`, lingering on). In userspace mode, inbound tailnet connections reach the Frame's **loopback**, so every port, including DevTools on 8080, is reachable from the tailnet. **Verified 2026-09-25.** | [tailscale.md](tailscale.md), `scripts/tailscale-on-frame.sh` | | **T3 Code desktop runs natively.** The stock release `T3-Code-0.0.42-arm64.AppImage` in `~/Applications/T3CodeDesktop/` starts with no extra setup: glibc 2.39, `libfuse.so.2`, GTK 3, NSS and libsecret are on the image. `panel-on-frame.sh --name t3code-desktop -- '~/Applications/T3CodeDesktop/T3-Code.AppImage'` gives it its own panel (`valve.steam.desktopgame.2000281357`, `--ozone-platform=x11`). Its bundled server listens on `127.0.0.1:3773` and shows up in onboarding as the `frame` computer, with `passwordStore: gnome-libsecret`. The image has no agent CLI and no `node`. Agents run through the LAN CLIProxyAPI (`llm-proxy.lan:8317`, which resolves on the Frame). Claude Code 2.1.283 comes from `claude.ai/install.sh`, and Codex 0.157.1 from the `codex-aarch64-unknown-linux-musl` release tarball, both into `~/.local/bin`. `with-cliproxy` and a mode-600 `~/.config/cliproxyapi/secrets.env` are copied from the Mac. The wrappers `claude-cliproxy` and `codex-cliproxy` (a `-c model_provider=cliproxy`, `wire_api="responses"`, `env_key="CLIPROXY_API_KEY"`) are set as `providers.claudeAgent.binaryPath` and `providers.codex.binaryPath` in `~/.t3/userdata/settings.json`, and T3 picked that up without a restart. Through the wrappers, `claude auth status` reports `loggedIn: true` (`oauth_token`), and both CLIs answered a prompt with `kimi-k3`. `gamescopectl screenshot` captured another layer (the Lepton T3 app) rather than this panel. `DISPLAY=:0 xwd -id ` piped to `ffmpeg` captures the window itself (1920×1080). **Verified 2026-09-26**, BUILD_ID 20260922.6101926. | Running T3 Code as a host on the Frame | diff --git a/docs/img/uevr-dialog.png b/docs/img/uevr-dialog.png new file mode 100644 index 0000000000000000000000000000000000000000..42849222ea671aab47b33cdeaf780e33f5e4e8ed GIT binary patch literal 34646 zcmc$_Q(&ag)+QXYW81cEcASo_j-7OD+Z|gS+pIVp+qP{_^*R6d-_2ak)Lpr1?{}|f zJy;P+3Q`DgxNsmKAPC>3#eaZ+fH8xBfMUXc0Uvpa<&6aaK?eCQE~4t5b>0Q(jc%Fq z^);{|#xD#3Mgn1sOpLtl;xL45vhM0?|Mk?d*0Iqcu%d(GW`u2qZJO4*K@dn8fZU53 z4(6!%C8VeLqwLprw?xD_=B=mwK~)VQwTF2VgNo{!s*co}prAr~CLs+CE=gnv5oEX2 z^77Hy#NF3d-U@wC5}$t3@`{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wkmPsyay-i~!tkN$_4H!$FQQ3bGy&=Nvk;Gghx;?nB;(IBB0ae1Q(VdF}2}WK3 zHR>V#r{MCxs;EJM%EbQ%*8KnH4|fgp&a8BI=jYcY{6(qzm;x%JWJGcbxd1mxr6Y+}<7 g_yY3pV+#y~b}4|&Tl)G2_zsBF7kRNCA_jr~2LKWwHUIzs literal 0 HcmV?d00001 diff --git a/docs/mods.md b/docs/mods.md index 27a7c2a..c25aed6 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -1,11 +1,14 @@ # Flat-to-VR mods and Beat Saber songs -**Status: feasibility work, not an installer.** Frame Control does not yet -manage mods or Beat Saber songs. [Issue #26](https://github.com/saphid/frame-control/issues/26) -stays open: neither UEVR injection nor Beat Saber custom-song playback has -been verified on this Frame. Alex has an owned copy on a Quest 2; that copy -has not been inspected. There is no Mods button until the underlying -install, playback and removal have been checked. +**Status: UEVR works from Frame Control for Unreal Engine games; Beat Saber +songs are blocked.** Installed games have a **VR mod** button. It installs +UEVR, starts the game with UEVR injected, and removes UEVR again. That whole +loop was run on a real Frame on 2026-09-29 with Gravitas, from the app's own +UI ([evidence](evidence/mods-2026-09-29.md)). The headset was unworn, so +the VR image, head tracking and controls haven't been seen yet. Beat Saber +custom songs need an owned Beat Saber on the Frame, which there isn't +([below](#beat-saber-songs-first)). +[Issue #26](https://github.com/saphid/frame-control/issues/26) stays open for those. The mod manager must be Frame Control's own implementation. Mods and songs are permitted third-party content; BSManager, ModsBeforeFriday, MO2 and other @@ -15,27 +18,82 @@ unofficial mod mirrors are part of this work. ## Per-game support -Checked 2026-09-28 on SteamOS **0.4.1**, BUILD_ID **20260925.6191901**, aarch64, -with **Proton 11.0-2c ARM64** and SteamVR **2.18.1**. “Verified” describes only +Checked 2026-09-28 and 2026-09-29 on SteamOS **0.4.1**, BUILD_ID +**20260925.6191901**, aarch64, with **Proton 11.0-2c ARM64** and SteamVR **2.18.1**. “Verified” describes only the observation stated, not a promise that the game is playable. “Documented” means an upstream source describes it; “inferred” means it still needs a test. | Game / build | Mod or content | Evidence and support status | Next check | |---|---|---|---| | Half-Life 2: VR Mod – Episode One, Steam 2177750, build 25413453 | Official Steam community mod, shared base depot 658920 build 25413418 | **Verified: startup only.** Already installed; launched through Proton ARM64. The stereo headset capture showed its first-time setup, and SteamVR loaded `bindings_frame.json`. Gameplay, controller interaction, fresh installation and removal are unverified. | Complete first-time setup and play a level before offering a tested install shortcut. | -| Gravitas, Steam 1067310, Windows | UEVR 1.05 | **Verified: prerequisites and windows only.** Free Steam install completed. The game produced a `SkyArk (64-bit, PCD3D_SM5)` window. UEVR needed .NET; with official .NET 6.0.36 libraries it produced a `UEVR` window. A combined run exited 1 with X11 errors before injection was verified. **Inferred: compatibility remains unknown**, not proven broken. | Retry during a stable headset session; verify injection, stereo scene output, controls and removal. | +| Gravitas, Steam 1067310, Windows, Unreal Engine 4 | UEVR 1.05, from Frame Control | **Verified 2026-09-29: installs, injects, SteamVR receives frames, removes cleanly.** Through the app's UI: install, then three cold **Play in VR** runs (54–58 s each) all loaded `UEVRBackend.dll` into the game, and SteamVR's compositor counted frame submits for `steam.app.1067310`. Remove restored the prefix to its pre-install file listing. **Not seen:** the stereo image, head tracking and controls (headset unworn). | Wear the headset: check the image, tracking, UEVR's in-headset menu and controller input. | | Beat Saber, Steam 620980, Windows / Proton | Basic custom songs; later SongCore and version-matched mods | **Verified: absent from the 868-game library returned by this Frame.** Store metadata lists Windows, not Linux. **Documented:** the PC game reads basic maps from `Beat Saber_Data/CustomLevels` without a mod manager. Playback on Frame is unverified. | An already-owned, legitimately installed copy is required. Do not buy it as part of this task. | | Beat Saber, claimed native ARM64 build | Custom songs / native mods | **Inferred: unverified.** The research mentions this build but supplies no verified official distributable or tested layout. CPU architecture alone does not identify Android versus Linux, the game version or the mod ABI. | Establish official provenance, ownership, binary type and version before touching files. Do not apply Quest patches to an unidentified build. | -| Beat Saber, Alex's Quest 2 copy | Custom songs / Android mods | **Documented: owner-reported copy on Quest 2**, currently charging. No APK, version or installed mods inspected; no Frame playback verified. This does not establish ownership of the Steam build. | When the Quest is available, inspect the owned copy's version and supported transfer path, then test Lepton/OpenXR compatibility without bypassing entitlement checks. | +| Beat Saber, Alex's Quest 2 copy | Custom songs / Android mods | **Documented: owner-reported copy on Quest 2.** Not reachable on 2026-09-29 (no device on `adb` from the Mac). No APK, version or installed mods inspected; no Frame playback verified. A Quest copy is a Meta store purchase; copying it to another headset would need its entitlement check to pass there, which this work won't work around. This does not establish ownership of the Steam build. | When the Quest is available, inspect the owned copy's version and supported transfer path, then test Lepton/OpenXR compatibility without bypassing entitlement checks. | | Hogwarts Legacy, Steam 990080 | R.E.A.L. | **Verified: listed in this Frame's owned library, not installed.** Official release access and redistribution permission were not established; the referenced author Patreon page returned HTTP 403. No archive downloaded or game tested. | Obtain a current free release from the author and confirm its terms before any test. A news report saying “free” is not a redistribution grant. | | Horizon Zero Dawn, Steam 1151640; Horizon Forbidden West, Steam 2420110 | R.E.A.L. | **Verified: both listed as owned, neither installed.** Same source/permission blocker as above; runtime support is unverified. | Check each game's supported version against an accessible official release. | | Half-Life 2 VR / other OpenVR games | OpenComposite, per-game replacement | **Documented:** forwards OpenVR calls to OpenXR. **Inferred: Frame compatibility unknown.** Not installed or tested. HL2 VR reached setup with the shipped OpenVR path already. | Test a specific game and replacement DLL only if needed; preserve its original DLL. Never switch the shared headset's runtime globally. | | Doom / Quake / Half-Life Team Beef ports | Author's VR ports plus separately owned or free game data | **Inferred: untested.** Android ARM64 support does not establish OpenXR extension or controller compatibility on Lepton. | Choose an official release and legally usable data set, then test that exact port. | | Skyrim VR, Steam 611670 | SKSEVR / HIGGS / PLANCK stack | **Verified: Skyrim VR is absent from this library.** Owning flat Skyrim or Special Edition is not the VR game's entitlement. Runtime and mod support are unverified. | An already-owned VR copy and version-matched official mod releases are required. | -The [test record](evidence/mods-2026-09-28.md) distinguishes process startup, -visible output and failures. It also records a SteamVR restart during the -shared session, which prevents attributing the failed UEVR attempt to FEX. +The test records ([2026-09-28](evidence/mods-2026-09-28.md), +[2026-09-29](evidence/mods-2026-09-29.md)) distinguish process startup, +visible output, injection and failures. + +## UEVR from Frame Control + +![The VR mod dialog while UEVR runs in Gravitas](img/uevr-dialog.png) + +**Get games → an installed game → VR mod.** The dialog says whether the game +can take UEVR, then offers **Install UEVR**, **▶ Play in VR** and **Remove +UEVR**. The server route is `POST /api/mods {"action": "status" | "install" | +"start" | "uninstall", "appid": …}`, and the work happens on the Frame in +[`ui/frame_mods.py`](../ui/frame_mods.py). It uses only the standard library, +like `frame_steam.py`. + +- **Which games.** Unreal Engine games, recognised by their + `…/Binaries/Win64/*-Win64-Shipping.exe` (inferred as the general rule; checked + with Gravitas, and HL2 VR is correctly refused). The game needs a Proton + prefix, so it must have been played once. +- **Install.** Downloads praydog's [UEVR 1.05 release](https://github.com/praydog/UEVR/releases/tag/1.05) + and Microsoft's Windows x64 .NET 6.0.36 and Windows Desktop runtimes (the + injector is a .NET 6 WPF app, and Proton ships no .NET). Each file is + checked against its pinned SHA-256 (UEVR) or SHA-512 (.NET, from Microsoft's + release metadata) before use. Archives are unpacked into a staging folder, + rejecting entries that escape it, symlinks and oversized contents, and + then moved into `/drive_c/frame-control/`. Nothing goes into the + game's own folder. A receipt in `~/.local/share/frame-control/mods/` lists + what to remove, including UEVR's own settings folders only if they didn't + exist before. Install and remove refuse while the game is running. +- **Play in VR.** Launches the game through Steam if it isn't running and + waits for its window. It then starts `UEVRInjector.exe` with the game's own + Proton, prefix and Wine settings, read from the game process, so both are in + one Wine session. It presses **OpenVR** and **Inject**, confirms that + `UEVRBackend.dll` is mapped into the game, and reads SteamVR's frame count + for the app (`vrcmd --stats`). +- **Remove.** Deletes what the receipt lists, then the download cache once + no game uses it. Verified: the prefix's file listing matched its + pre-install state afterwards. + +Things found on the way (verified 2026-09-29): + +- Under gamescope, the full-screen game keeps the pointer and focus, and + XTest clicks, raising or refocusing the injector window don't change that. + So in the headset you couldn't click the injector yourself, and Frame + Control sends X `ButtonPress`/`ButtonRelease` events straight to the + injector's window instead. The positions are for UEVR 1.05's layout; the + window first maps at 960 px wide and settles at 625 px. `start` refuses to + click if it doesn't settle at that width. +- The injector's `--attach=` didn't inject under Wine. It also + didn't restore the OpenVR choice it had saved, so Frame Control chooses + OpenVR every time. +- With only the game's variables (no `HOME`), the injector hit an + `AccessViolationException` in .NET at startup. With the normal environment + underneath, all four later starts worked. `start` also retries a + crashed injector up to three times. +- UEVR's DirectX 12 probing logs errors before it settles on DirectX 11 for + Gravitas, and some of its Unreal engine scans fail on this older UE4 game. + Neither stopped the injection. ## Beat Saber: songs first @@ -62,7 +120,10 @@ or dependency for Frame Control. ## Requirements for our manager -These are **planned**, not implemented or verified: +For UEVR, items 1–5 are implemented in `frame_mods.py` and covered by +fake-library tests (`tests/test_mods.py`), apart from checking ownership +through Steam; item 6 is met for Gravitas. Beat Saber songs would need the +same, and none of it is built for them: 1. Resolve the selected Steam game's real library, installed build, executable architecture and Proton prefix. Confirm ownership through Steam; a directory diff --git a/docs/steam-games.md b/docs/steam-games.md index 068a153..1e48ee1 100644 --- a/docs/steam-games.md +++ b/docs/steam-games.md @@ -4,9 +4,9 @@ Frame Control's **Get games** section lists the games you own with each one's Steam Frame rating, installs them on the Frame, and searches the Steam store. This page covers how it works underneath, so you can do the same from a shell. -For flat-to-VR mods and Beat Saber custom songs, see the -[per-game feasibility table](mods.md). Mod support is separate from Steam's -Frame rating; there is no mod installer yet. +Installed Unreal Engine games also have a **VR mod** button that installs, +starts and removes UEVR; see [VR mods](mods.md) for how it works and the +per-game table. Mod support is separate from Steam's Frame rating. ## How it works diff --git a/tests/test_mods.py b/tests/test_mods.py new file mode 100644 index 0000000..b4b5e41 --- /dev/null +++ b/tests/test_mods.py @@ -0,0 +1,270 @@ +"""VR mod (UEVR) checks that need no headset or network: a fake Steam library on disk. + +Run: python3 -m unittest discover -s tests +""" +import hashlib +import io +import itertools +import json +import stat +import subprocess +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "ui")) + +import frame_mods # noqa: E402 +import test_server # noqa: E402 (not `from … import`, or unittest runs ServerGuards twice) + +APPID = 1067310 + + +def zip_bytes(files, links=()): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as z: + for name, data in files.items(): + z.writestr(name, data) + for name in links: + info = zipfile.ZipInfo(name) + info.external_attr = (stat.S_IFLNK | 0o777) << 16 + z.writestr(info, "/etc/passwd") + return buf.getvalue() + + +class FakeLibrary(unittest.TestCase): + """A Steam library with Gravitas's real layout, and pinned downloads served from memory.""" + + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + home = Path(tmp.name) + self.steam = home / ".local/share/Steam" + apps = self.steam / "steamapps" + (apps / "common/Gravitas/SkyArk/Binaries/Win64").mkdir(parents=True) + (apps / "common/Gravitas/SkyArk/Binaries/Win64/Drop-Win64-Shipping.exe").write_bytes(b"MZ" * 100) + (apps / "common/Gravitas/Drop.exe").write_bytes(b"MZ") + self.prefix = apps / f"compatdata/{APPID}/pfx" + for sub in ("Roaming", "Local"): + (self.prefix / "drive_c/users/steamuser/AppData" / sub).mkdir(parents=True) + (apps / f"appmanifest_{APPID}.acf").write_text( + f'"AppState"\n{{\n\t"appid"\t\t"{APPID}"\n\t"name"\t\t"Gravitas"\n\t"installdir"\t\t"Gravitas"\n}}\n') + for name, value in (("STEAM", self.steam), ("CACHE", home / ".cache/frame-control/mods"), + ("RECEIPTS", home / ".local/share/frame-control/mods")): + p = mock.patch.object(frame_mods, name, value) + p.start() + self.addCleanup(p.stop) + self.running = None + p = mock.patch.object(frame_mods, "game_pid", side_effect=lambda exe: self.running) + p.start() + self.addCleanup(p.stop) + self.downloads = {frame_mods.UEVR["url"]: zip_bytes({"UEVRInjector.exe": b"MZ", "UEVRBackend.dll": b"MZ", + "openvr_api.dll": b"MZ"})} + for url, _ in frame_mods.DOTNET["files"]: + self.downloads[url] = zip_bytes({"shared/Microsoft.NETCore.App/6.0.36/x.dll": b"MZ"}) + self.pin(self.downloads) + + def pin(self, downloads): + """Serve these bytes and pin their real hashes in place of the published ones.""" + uevr = dict(frame_mods.UEVR, sha256=hashlib.sha256(downloads[frame_mods.UEVR["url"]]).hexdigest()) + dotnet = dict(frame_mods.DOTNET, files=[(u, hashlib.sha512(downloads[u]).hexdigest()) + for u, _ in frame_mods.DOTNET["files"]]) + for name, value in (("UEVR", uevr), ("DOTNET", dotnet)): + p = mock.patch.object(frame_mods, name, value) + p.start() + self.addCleanup(p.stop) + p = mock.patch.object(frame_mods.urllib.request, "urlopen", + side_effect=lambda url, timeout: io.BytesIO(downloads[url])) + self.urlopen = p.start() + self.addCleanup(p.stop) + + def managed(self): + return self.prefix / "drive_c/frame-control" + + +class Status(FakeLibrary): + def test_unreal_game_is_eligible_and_not_installed(self): + st = frame_mods.status(APPID) + self.assertEqual((st["eligible"], st["exe"], st["installed"], st["running"], st["prefix"]), + (True, "Drop-Win64-Shipping.exe", False, False, True)) + + def test_game_without_unreal_binary_is_refused(self): + (self.steam / "steamapps/common/Gravitas/SkyArk/Binaries/Win64/Drop-Win64-Shipping.exe").unlink() + self.assertFalse(frame_mods.status(APPID)["eligible"]) + with self.assertRaisesRegex(frame_mods.Fail, "Unreal Engine"): + frame_mods.install(APPID) + self.urlopen.assert_not_called() + + def test_uninstalled_game(self): + with self.assertRaisesRegex(frame_mods.Fail, "isn't installed"): + frame_mods.status(620) + + +class InstallUninstall(FakeLibrary): + def test_install_then_uninstall_leaves_prefix_as_found(self): + before = sorted(p.relative_to(self.prefix) for p in self.prefix.rglob("*")) + res = frame_mods.install(APPID) + self.assertTrue(res["installed"]) + self.assertTrue((self.managed() / "uevr-1.05/UEVRInjector.exe").is_file()) + self.assertTrue((self.managed() / "dotnet-6.0.36/shared/Microsoft.NETCore.App/6.0.36/x.dll").is_file()) + self.assertFalse(list(self.managed().glob(".staging-*"))) + # What UEVR writes on its first injection. + roaming = self.prefix / "drive_c/users/steamuser/AppData/Roaming/UnrealVRMod/Drop-Win64-Shipping" + roaming.mkdir(parents=True) + (roaming / "log.txt").write_text("x") + (self.prefix / "drive_c/users/steamuser/AppData/Local/praydog/x").mkdir(parents=True) + frame_mods.uninstall(APPID) + after = sorted(p.relative_to(self.prefix) for p in self.prefix.rglob("*")) + self.assertEqual(after, before) + self.assertFalse(frame_mods.CACHE.exists(), "the downloads go once no game uses them") + self.assertIsNone(frame_mods.read_receipt(APPID)) + + def test_existing_uevr_settings_survive_uninstall(self): + profile = self.prefix / "drive_c/users/steamuser/AppData/Roaming/UnrealVRMod/Drop-Win64-Shipping" + profile.mkdir(parents=True) + (profile / "config.txt").write_text("mine") + frame_mods.install(APPID) + frame_mods.uninstall(APPID) + self.assertEqual((profile / "config.txt").read_text(), "mine") + + def test_second_install_is_a_no_op(self): + frame_mods.install(APPID) + calls = self.urlopen.call_count + self.assertIn("already installed", frame_mods.install(APPID)["message"]) + self.assertEqual(self.urlopen.call_count, calls) + + def test_refuses_while_game_runs(self): + self.running = 4242 + with self.assertRaisesRegex(frame_mods.Fail, "running"): + frame_mods.install(APPID) + self.running = None + frame_mods.install(APPID) + self.running = 4242 + with self.assertRaisesRegex(frame_mods.Fail, "running"): + frame_mods.uninstall(APPID) + self.assertTrue((self.managed() / "uevr-1.05").is_dir()) + + def test_needs_a_prefix(self): + import shutil + shutil.rmtree(self.prefix.parent) + with self.assertRaisesRegex(frame_mods.Fail, "play it once"): + frame_mods.install(APPID) + + def test_receipt_cannot_point_outside_the_prefix(self): + frame_mods.install(APPID) + r = frame_mods.read_receipt(APPID) + victim = self.steam / "steamapps/common/Gravitas" + r["remove"].append(str(self.prefix / "../../../common/Gravitas")) + frame_mods.receipt_path(APPID).write_text(json.dumps(r)) + with self.assertRaisesRegex(frame_mods.Fail, "outside"): + frame_mods.uninstall(APPID) + self.assertTrue(victim.is_dir()) + self.assertTrue((self.managed() / "uevr-1.05").is_dir(), "nothing removed when the receipt is bad") + + +class Downloads(FakeLibrary): + def test_hash_mismatch_deletes_and_installs_nothing(self): + self.downloads[frame_mods.UEVR["url"]] = zip_bytes({"UEVRInjector.exe": b"tampered"}) + with self.assertRaisesRegex(frame_mods.Fail, "doesn't match"): + frame_mods.install(APPID) + self.assertFalse((frame_mods.CACHE / "UEVR.zip").exists()) + self.assertFalse(self.managed().exists()) + self.assertIsNone(frame_mods.read_receipt(APPID)) + + def test_archive_escaping_its_folder_is_refused(self): + for bad in (zip_bytes({"UEVRInjector.exe": b"MZ", "../../evil.dll": b"MZ"}), + zip_bytes({"UEVRInjector.exe": b"MZ"}, links=["openvr_api.dll"])): + downloads = dict(self.downloads, **{frame_mods.UEVR["url"]: bad}) + self.pin(downloads) + with self.subTest(), self.assertRaises(frame_mods.Fail): + frame_mods.install(APPID) + self.assertFalse((self.prefix / "drive_c/evil.dll").exists()) + self.assertFalse(list(self.managed().glob("*")) if self.managed().exists() else []) + import shutil + shutil.rmtree(frame_mods.CACHE, ignore_errors=True) + + def test_oversized_archive_is_refused(self): + with mock.patch.object(frame_mods, "MAX_UNPACKED", 3): + with self.assertRaisesRegex(frame_mods.Fail, "more than expected"): + frame_mods.install(APPID) + + +class Start(FakeLibrary): + def test_needs_install_first(self): + with self.assertRaisesRegex(frame_mods.Fail, "isn't installed"): + frame_mods.start(APPID) + + def test_refuses_to_click_an_unexpected_layout(self): + frame_mods.install(APPID) + self.running = 4242 + env = "WINEPREFIX=/x\0DISPLAY=:1\0WINESERVERSOCKET=17\0PATH=/p\0" + windows = [[(1, "SkyArk", 1280)], [(1, "SkyArk", 1280)], [(1, "SkyArk", 1280), (2, "UEVR", 700)]] + with mock.patch("builtins.open", mock.mock_open(read_data=env)), \ + mock.patch.object(frame_mods, "loaded", return_value=False), \ + mock.patch.object(frame_mods, "x11_windows", side_effect=lambda d: windows.pop(0) if len(windows) > 1 else windows[0]), \ + mock.patch.object(frame_mods.subprocess, "Popen") as popen, \ + mock.patch.object(frame_mods, "x_click") as click, \ + mock.patch.object(frame_mods.os, "killpg") as kill, \ + mock.patch.object(frame_mods.time, "time", side_effect=itertools.count(0, 5)), \ + mock.patch.object(frame_mods.time, "sleep"): + popen.return_value.poll.return_value = None # the injector stays up + with self.assertRaisesRegex(frame_mods.Fail, "700 px"): + frame_mods.start(APPID) + click.assert_not_called() + kill.assert_called_once_with(popen.return_value.pid, frame_mods.signal.SIGKILL) + env_used = popen.call_args.kwargs["env"] + self.assertNotIn("WINESERVERSOCKET", env_used, "an inherited fd number means nothing to a new process") + self.assertEqual(env_used["DOTNET_ROOT"], "C:\\frame-control\\dotnet-6.0.36") + self.assertEqual(env_used["WINEPREFIX"], "/x") + self.assertIn("HOME", env_used, "fontconfig needs a HOME for its cache") + + def test_injector_that_keeps_crashing_is_reported(self): + frame_mods.install(APPID) + self.running = 4242 + with mock.patch("builtins.open", mock.mock_open(read_data="WINEPREFIX=/x\0DISPLAY=:1\0")), \ + mock.patch.object(frame_mods, "loaded", return_value=False), \ + mock.patch.object(frame_mods, "x11_windows", return_value=[(1, "SkyArk", 1280)]), \ + mock.patch.object(frame_mods.subprocess, "Popen") as popen, \ + mock.patch.object(frame_mods, "x_click") as click, \ + mock.patch.object(frame_mods.time, "sleep"): + popen.return_value.poll.return_value = 134 # died before showing its window + with self.assertRaisesRegex(frame_mods.Fail, "crashed on start 3 times"): + frame_mods.start(APPID) + self.assertEqual(popen.call_count, 3) + click.assert_not_called() + + +class Helper(unittest.TestCase): + def test_bad_usage_prints_json_error(self): + for args in ([], ["install"], ["install", "12x"], ["remove", "620"]): + out = subprocess.run([sys.executable, str(ROOT / "ui" / "frame_mods.py"), *args], + capture_output=True, text=True, timeout=30) + self.assertEqual(out.returncode, 1, args) + self.assertIn("error", json.loads(out.stdout), args) + + +class ModRoutes(test_server.ServerGuards): + """Reuses ServerGuards' server (unresolvable SSH alias); validation runs before any SSH.""" + + def test_mod_input_validation(self): + for body in ({"action": "install", "appid": "1; reboot"}, {"action": "install", "appid": ""}, + {"action": "delete", "appid": "1067310"}, {"appid": "1067310"}): + status, payload = self.post("/api/mods", body) + self.assertEqual(status, 400, f"{body} -> {payload}") + + def test_needs_custom_header(self): + self.assertEqual(self.request("POST", "/api/mods", {"action": "status", "appid": "1"})[0], 403) + + def test_runs_the_mods_helper_with_its_timeout(self): + import server + with mock.patch.object(server, "steam_frame", return_value={"ok": 1}) as run: + self.assertEqual(server.mods({"action": "install", "appid": "1067310"}), {"ok": 1}) + run.assert_called_once_with("install", "1067310", timeout=600, script="frame_mods.py") + + +for name in [n for n in dir(test_server.ServerGuards) if n.startswith("test_")]: + setattr(ModRoutes, name, None) diff --git a/ui/frame_mods.py b/ui/frame_mods.py new file mode 100644 index 0000000..f4db415 --- /dev/null +++ b/ui/frame_mods.py @@ -0,0 +1,437 @@ +#!/usr/bin/env python3 +"""Runs ON the Frame (piped over SSH): UEVR, a flat-to-VR mod for Unreal games. + +Usage: python3 - status APPID # can UEVR run here, is it installed, is the game running + python3 - install APPID # download the pinned official release into the game's prefix + python3 - start APPID # launch the game if needed, inject UEVR, confirm SteamVR frames + python3 - uninstall APPID # remove exactly what install (and UEVR's first run) created +Prints one JSON object. Errors are {"error": "..."} with exit status 1. + +Verified 2026-09-29 on SteamOS 0.4.1 (build 20260925.6191901), Proton 11.0 +ARM64 and SteamVR 2.18.1 with Gravitas (1067310): UEVR 1.05's injector runs in +the game's own Wine session, and after OpenVR + Inject the game loads +UEVRBackend.dll and SteamVR counts frame submits for it. Stereo image, head +tracking and controls were not seen: the headset was unworn (docs/mods.md). + +Nothing here is bundled. UEVR comes from praydog's GitHub release, and the +Windows .NET 6 runtime it needs from Microsoft's release metadata URLs, each +checked against a pinned hash. Files live in /drive_c/frame-control, +never in the game's own folder, and a receipt records what to remove. +""" +import hashlib +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import time +import urllib.request +import zipfile +from pathlib import Path + +HOME = Path.home() +STEAM = HOME / ".local/share/Steam" +CACHE = HOME / ".cache/frame-control/mods" +RECEIPTS = HOME / ".local/share/frame-control/mods" +VRCMD = "/opt/steamvr/bin/linuxarm64/vrcmd" +MANAGED = "frame-control" # drive_c/ inside the game's prefix + +UEVR = {"version": "1.05", "dir": "uevr-1.05", + "url": "https://github.com/praydog/UEVR/releases/download/1.05/UEVR.zip", + "sha256": "af4f2f91306802d7ee4e8497d483a547ac8e9a3067dbafb81324100524215d3c"} +# UEVRInjector.exe is a .NET 6 WPF app; Proton ships no .NET. These are the +# win-x64 ZIPs listed in builds.dotnet.microsoft.com/dotnet/release-metadata/6.0/releases.json. +DOTNET = {"version": "6.0.36", "dir": "dotnet-6.0.36", "files": [ + ("https://builds.dotnet.microsoft.com/dotnet/Runtime/6.0.36/dotnet-runtime-6.0.36-win-x64.zip", + "935db5c6cee19f2c016e67168bfae7b491044735de76c673abb3b125dd325fd5e779d7efe12ba80178d46689ae70a25e558a3fa846417d44c5f4ca256e7f4bf2"), + ("https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/6.0.36/windowsdesktop-runtime-6.0.36-win-x64.zip", + "cee88fef07643dceb3d34ea71b64eeae85b8e39e7042bc4d35bc3a1f1df29373681dc48e31c01c9f593ec412699f6762b6fc5817433283c89df35a27ce8885bf")]} +MAX_UNPACKED = 600 << 20 # the three archives unpack to about 190 MB + +# UEVR 1.05's injector window (625 px wide), in window coordinates. Under +# gamescope the full-screen game keeps the pointer and focus, so real clicks +# can't reach the injector; XSendEvent to its window does. It doesn't restore +# its saved runtime choice under Wine, and --attach didn't inject, so choose +# OpenVR (SteamVR's own API) and press Inject every time. +INJECTOR_WIDTH = 625 +CLICK_OPENVR, CLICK_INJECT = (125, 137), (365, 113) +# The game's environment the injector needs to join its Wine session. Not +# WINESERVERSOCKET and friends: those are inherited file descriptors. +GAME_ENV = re.compile(r"(WINEPREFIX|WINEDLLPATH|WINEDLLOVERRIDES|WINEFSYNC|WINEDEBUG|PATH|DISPLAY|" + r"XDG_RUNTIME_DIR|PROTON_VR_RUNTIME|FEX_APP_CONFIG|FEX_APP_CONFIG_LOCATION|" + r"SteamAppId|SteamGameId|STEAM_COMPAT_DATA_PATH|WINE_LARGE_ADDRESS_AWARE)=") + + +class Fail(Exception): + pass + + +def libraries(): + """Steam library folders: the default one plus any in libraryfolders.vdf.""" + libs = [STEAM] + try: + text = (STEAM / "steamapps/libraryfolders.vdf").read_text(errors="replace") + libs += [Path(p.replace("\\\\", "\\")) for p in re.findall(r'"path"\s+"([^"]+)"', text)] + except OSError: + pass + seen, out = set(), [] + for lib in libs: + key = os.path.realpath(lib) + if key not in seen: + seen.add(key) + out.append(lib) + return out + + +def game(appid): + """Where the game is installed and its Proton prefix, from its app manifest.""" + for lib in libraries(): + manifest = lib / f"steamapps/appmanifest_{appid}.acf" + try: + text = manifest.read_text(errors="replace") + except OSError: + continue + m = re.search(r'"installdir"\s+"([^"]+)"', text) + if not m: + continue + name = re.search(r'"name"\s+"([^"]*)"', text) + return {"name": name.group(1) if name else str(appid), + "dir": lib / "steamapps/common" / m.group(1), + "prefix": lib / f"steamapps/compatdata/{appid}/pfx"} + raise Fail(f"app {appid} isn't installed on this Frame") + + +def shipping_exe(game_dir): + """The Unreal Engine game binary (…/Binaries/Win64/*-Win64-Shipping.exe), or None.""" + found = [p for p in game_dir.glob("*/Binaries/Win64/*.exe") if p.name.lower().endswith("-win64-shipping.exe")] + found += [p for p in game_dir.glob("Binaries/Win64/*.exe") if p.name.lower().endswith("-win64-shipping.exe")] + return max(found, key=lambda p: p.stat().st_size) if found else None + + +def game_pid(exe_name): + """The running Wine process for this .exe (its cmdline is the Windows path).""" + want = "\\" + exe_name.lower() + for d in Path("/proc").iterdir(): + if not d.name.isdigit(): + continue + try: + cmd = (d / "cmdline").read_bytes().split(b"\0")[0].decode(errors="replace").lower() + except OSError: + continue + if cmd.endswith(want): + return int(d.name) + return None + + +def loaded(pid, name): + try: + return any(line.rstrip().endswith("/" + name) for line in open(f"/proc/{pid}/maps")) + except OSError: + return False + + +def receipt_path(appid): + return RECEIPTS / f"{appid}-uevr.json" + + +def read_receipt(appid): + try: + return json.loads(receipt_path(appid).read_text()) + except (OSError, ValueError): + return None + + +def managed_dir(g): + return g["prefix"] / "drive_c" / MANAGED + + +def user_dirs(g, exe): + """What UEVR itself writes into the prefix when it first runs.""" + user = g["prefix"] / "drive_c/users/steamuser/AppData" + return {"profile": user / "Roaming/UnrealVRMod" / exe.stem, # per-game settings and log.txt + "injector": user / "Local/praydog"} # the injector's own settings + + +def status(appid): + g = game(appid) + exe = shipping_exe(g["dir"]) + r = read_receipt(appid) + pid = game_pid(exe.name) if exe else None + return {"appid": appid, "name": g["name"], "mod": "UEVR", "version": UEVR["version"], + "eligible": bool(exe), "exe": exe.name if exe else None, + "prefix": g["prefix"].is_dir(), "installed": bool(r), + "running": bool(pid), "injected": bool(pid and loaded(pid, "UEVRBackend.dll"))} + + +def fetch(url, digest, algo): + """Download into the cache once, and check its hash every time it's used.""" + CACHE.mkdir(parents=True, exist_ok=True) + path = CACHE / url.rsplit("/", 1)[1] + if not path.exists(): + part = path.with_suffix(path.suffix + ".part") + try: + with urllib.request.urlopen(url, timeout=60) as r, open(part, "wb") as f: + shutil.copyfileobj(r, f, 1 << 20) + except OSError as e: + part.unlink(missing_ok=True) + raise Fail(f"download failed: {url}: {e}") + part.rename(path) + h = hashlib.new(algo) + with open(path, "rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): + h.update(block) + if h.hexdigest() != digest: + path.unlink() + raise Fail(f"{path.name} doesn't match its published {algo}; deleted it, try again") + return path + + +def unpack(archive, dest, budget): + """Extract a ZIP into dest, refusing anything that would land outside it.""" + root = os.path.realpath(dest) + with zipfile.ZipFile(archive) as z: + for info in z.infolist(): + target = os.path.realpath(os.path.join(dest, info.filename)) + if target != root and not target.startswith(root + os.sep): + raise Fail(f"{archive.name} has an entry outside its folder: {info.filename}") + if (info.external_attr >> 16) & 0o170000 == 0o120000: + raise Fail(f"{archive.name} contains a symlink: {info.filename}") + budget -= info.file_size + if budget < 0: + raise Fail(f"{archive.name} unpacks to more than expected") + z.extractall(dest) + return budget + + +def install(appid): + g = game(appid) + exe = shipping_exe(g["dir"]) + if not exe: + raise Fail(f"{g['name']} doesn't look like an Unreal Engine game (no *-Win64-Shipping.exe), so UEVR can't hook it") + if not g["prefix"].is_dir(): + raise Fail(f"{g['name']} has no Proton prefix yet; play it once, then add the mod") + if game_pid(exe.name): + raise Fail(f"{g['name']} is running; quit it first") + if read_receipt(appid): + return {"message": f"UEVR {UEVR['version']} is already installed for {g['name']}", **status(appid)} + archives = [(fetch(UEVR["url"], UEVR["sha256"], "sha256"), UEVR["dir"])] + archives += [(fetch(url, digest, "sha512"), DOTNET["dir"]) for url, digest in DOTNET["files"]] + base = managed_dir(g) + dirs = user_dirs(g, exe) + fresh = [str(d) for d in (dirs["profile"].parent, base) if not d.exists()] # remove on uninstall if empty + stage = base / f".staging-{os.getpid()}" + shutil.rmtree(stage, ignore_errors=True) + try: + budget = MAX_UNPACKED + for archive, sub in archives: + budget = unpack(archive, stage / sub, budget) + if not (stage / UEVR["dir"] / "UEVRInjector.exe").is_file(): + raise Fail("UEVR.zip has no UEVRInjector.exe") + for sub in (UEVR["dir"], DOTNET["dir"]): + shutil.rmtree(base / sub, ignore_errors=True) + (stage / sub).rename(base / sub) + finally: + shutil.rmtree(stage, ignore_errors=True) + if str(base) in fresh: + try: + base.rmdir() # only succeeds if the install failed and left it empty + except OSError: + pass + receipt = {"appid": appid, "mod": "UEVR", "version": UEVR["version"], "exe": exe.name, + "installed": int(time.time()), "prefix": str(g["prefix"]), + "remove": [str(base / UEVR["dir"]), str(base / DOTNET["dir"])], + # Parents that didn't exist yet (UEVR makes UnrealVRMod), deepest first. + "remove_if_empty": fresh, + # UEVR creates these on first injection. Remove them on uninstall + # only if they weren't there before, so earlier settings survive. + "remove_if_created": {k: str(v) for k, v in dirs.items() if not v.exists()}, + "sources": [UEVR["url"]] + [u for u, _ in DOTNET["files"]]} + RECEIPTS.mkdir(parents=True, exist_ok=True) + tmp = receipt_path(appid).with_suffix(".tmp") + tmp.write_text(json.dumps(receipt, indent=1)) + tmp.rename(receipt_path(appid)) + return {"message": f"Installed UEVR {UEVR['version']} for {g['name']}", **status(appid)} + + +def x11_windows(display): + """(id, name, width) for each named top-level window, via xwininfo.""" + try: + out = subprocess.run(["xwininfo", "-root", "-tree"], env={**os.environ, "DISPLAY": display}, + capture_output=True, text=True, timeout=10).stdout + except (OSError, subprocess.TimeoutExpired): + return [] + return [(int(m[1], 16), m[2], int(m[3])) for m in re.finditer(r'(0x[0-9a-f]+) "([^"]*)":.*?\)\s+(\d+)x\d+', out)] + + +def x_click(display, window, points): + """Send ButtonPress/Release straight to a window (gamescope blocks real input to it).""" + import ctypes as C + x11 = C.CDLL("libX11.so.6") + x11.XOpenDisplay.restype = C.c_void_p + + class Button(C.Structure): + _fields_ = [("type", C.c_int), ("serial", C.c_ulong), ("send_event", C.c_int), ("display", C.c_void_p), + ("window", C.c_ulong), ("root", C.c_ulong), ("subwindow", C.c_ulong), ("time", C.c_ulong), + ("x", C.c_int), ("y", C.c_int), ("x_root", C.c_int), ("y_root", C.c_int), + ("state", C.c_uint), ("button", C.c_uint), ("same_screen", C.c_int)] + + class Event(C.Union): + _fields_ = [("xbutton", Button), ("pad", C.c_long * 24)] + + d = x11.XOpenDisplay(display.encode()) + if not d: + raise Fail(f"can't open X display {display}") + d = C.c_void_p(d) + root = x11.XDefaultRootWindow(d) + ox, oy, child = C.c_int(), C.c_int(), C.c_ulong() + x11.XTranslateCoordinates(d, C.c_ulong(window), C.c_ulong(root), 0, 0, C.byref(ox), C.byref(oy), C.byref(child)) + for x, y in points: + for kind, mask, state in ((4, 1 << 2, 0), (5, 1 << 3, 1 << 8)): # press, then release with Button1 held + e = Event() + b = e.xbutton + b.type, b.send_event, b.window, b.root, b.x, b.y = kind, 1, window, root, x, y + b.x_root, b.y_root, b.state, b.button, b.same_screen = x + ox.value, y + oy.value, state, 1, 1 + x11.XSendEvent(d, C.c_ulong(window), 1, C.c_long(mask), C.byref(e)) + x11.XFlush(d) + time.sleep(0.15) + time.sleep(1.5) + x11.XCloseDisplay(d) + + +def frame_submits(appid): + """SteamVR's count of frames the app has submitted, or None if it isn't a scene app.""" + try: + stats = json.loads(subprocess.run([VRCMD, "--stats"], capture_output=True, text=True, timeout=15).stdout) + except (OSError, ValueError, subprocess.TimeoutExpired): + return None + return next((s.get("frame_submits") for s in stats if s.get("key") == f"steam.app.{appid}"), None) + + +def wait(what, seconds, check, step=2): + end = time.time() + seconds + while time.time() < end: + v = check() + if v: + return v + time.sleep(step) + raise Fail(f"timed out waiting for {what}") + + +def start(appid): + g = game(appid) + r = read_receipt(appid) + if not r: + raise Fail(f"UEVR isn't installed for {g['name']}") + exe = r["exe"] + pid = game_pid(exe) + if pid and loaded(pid, "UEVRBackend.dll"): + return {"message": f"UEVR is already running in {g['name']}", "frame_submits": frame_submits(appid), **status(appid)} + if not pid: + subprocess.Popen(["steam", f"steam://rungameid/{appid}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env={**os.environ, "DISPLAY": os.environ.get("DISPLAY", ":0")}, start_new_session=True) + pid = wait(f"{g['name']} to start", 120, lambda: game_pid(exe)) + env = dict(line.split("=", 1) for line in open(f"/proc/{pid}/environ").read().split("\0") + if GAME_ENV.match(line)) + display = env.get("DISPLAY") + if not display or "WINEPREFIX" not in env: + raise Fail(f"{exe} doesn't look like a Proton game process") + # The game needs its D3D11 window before UEVR can hook it. Proton's own + # helper windows ("Steam", "Default IME", …) are small. + wait("the game window", 90, lambda: any(w[2] >= 640 and w[1] != "UEVR" for w in x11_windows(display))) + time.sleep(10) + root = f"C:\\{MANAGED}\\{DOTNET['dir']}" + # Our own environment (HOME and the rest) under the game's Wine settings: + # with only the game's variables, fontconfig had no cache directory. + env = {**os.environ, **env, "DOTNET_ROOT": root, "DOTNET_ROOT_X64": root} + # The .NET injector sometimes dies at startup under Wine and FEX (an + # AccessViolationException, 2026-09-29), so give it a few tries. + for attempt in range(3): + before = {w[0] for w in x11_windows(display) if w[1] == "UEVR"} + log = open(CACHE / f"injector-{appid}.log", "w") if CACHE.is_dir() else subprocess.DEVNULL + injector = subprocess.Popen(["wine", f"C:\\{MANAGED}\\{UEVR['dir']}\\UEVRInjector.exe"], env=env, + stdout=log, stderr=log, stdin=subprocess.DEVNULL, start_new_session=True, + cwd=str(Path(r["prefix"]) / "drive_c" / MANAGED / UEVR["dir"])) + try: + win = wait("the UEVR injector window", 90, + lambda: injector.poll() is not None or next( + (w for w in x11_windows(display) if w[1] == "UEVR" and w[0] not in before), None)) + except Fail: + os.killpg(injector.pid, signal.SIGKILL) + raise + if win is not True: + break + else: + raise Fail(f"the UEVR injector crashed on start {attempt + 1} times; " + f"its log is in ~/.cache/frame-control/mods/injector-{appid}.log") + try: + # It maps at a default size, then WPF lays it out (seen: 960 px, then 625). + try: + wait("the UEVR window's layout", 30, + lambda: any(w[0] == win[0] and w[2] == INJECTOR_WIDTH for w in x11_windows(display)), step=1) + except Fail: + width = next((w[2] for w in x11_windows(display) if w[0] == win[0]), "?") + raise Fail(f"the UEVR window is {width} px wide, not {INJECTOR_WIDTH}; " + "its layout changed, so not clicking blind") from None + time.sleep(5) # let it fill its process list + x_click(display, win[0], [CLICK_OPENVR, CLICK_INJECT]) + try: + wait("UEVRBackend.dll to load in the game", 45, lambda: loaded(pid, "UEVRBackend.dll")) + except Fail: + raise Fail(f"UEVR didn't inject into {exe}. Its log is in ~/.cache/frame-control/mods/injector-{appid}.log") from None + except Fail: + os.killpg(injector.pid, signal.SIGKILL) # don't leave an injector window behind a failed start + raise + submits = None + try: + submits = wait("SteamVR frames", 30, lambda: frame_submits(appid)) + except Fail: + pass + return {"message": f"UEVR injected into {g['name']}" + ("; SteamVR is receiving its frames" if submits else + "; SteamVR hasn't reported frames from it yet"), + "frame_submits": submits, **status(appid)} + + +def uninstall(appid): + r = read_receipt(appid) + if not r: + raise Fail(f"UEVR isn't installed for app {appid}") + if game_pid(r["exe"]): + raise Fail("the game is running; quit it first") + prefix = os.path.realpath(r["prefix"]) + targets = list(r.get("remove", [])) + list(r.get("remove_if_created", {}).values()) + for t in targets: # a receipt only ever points inside this game's prefix + real = os.path.realpath(t) + if not real.startswith(prefix + os.sep): + raise Fail(f"receipt lists a path outside the game's prefix: {t}") + for t in targets: + shutil.rmtree(t, ignore_errors=True) + for t in r.get("remove_if_empty", []): + if os.path.realpath(t).startswith(prefix + os.sep): + try: + os.rmdir(t) + except OSError: + pass # something else lives there now + receipt_path(appid).unlink() + if not any(RECEIPTS.glob("*-uevr.json")): # no other game uses the downloads + shutil.rmtree(CACHE, ignore_errors=True) + try: + RECEIPTS.rmdir() + except OSError: + pass + return {"message": "Removed UEVR", "appid": appid, "removed": targets} + + +def main(argv): + if len(argv) != 2 or argv[0] not in ("status", "install", "start", "uninstall") or not argv[1].isdigit(): + raise Fail("usage: status|install|start|uninstall APPID") + return {"status": status, "install": install, "start": start, "uninstall": uninstall}[argv[0]](int(argv[1])) + + +if __name__ == "__main__": + try: + print(json.dumps(main(sys.argv[1:]))) + except Fail as e: + print(json.dumps({"error": str(e)})) + sys.exit(1) diff --git a/ui/index.html b/ui/index.html index 8ac1265..3cacd4e 100644 --- a/ui/index.html +++ b/ui/index.html @@ -254,10 +254,10 @@ .and-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 2fr); gap: 22px; align-items: start; } .and-col { display: grid; gap: 22px; align-content: start; } .rep-item .s { white-space: normal; } - #repDlg, #titleDlg, #wiDlg, #pwDlg, #apkAltDlg { background: #1e2329; color: var(--text); border: 1px solid rgba(255,255,255,.1); border-radius: 4px; + #repDlg, #titleDlg, #wiDlg, #pwDlg, #apkAltDlg, #modDlg { background: #1e2329; color: var(--text); border: 1px solid rgba(255,255,255,.1); border-radius: 4px; padding: 22px; width: min(560px, 92vw); box-shadow: 0 20px 60px rgba(0,0,0,.6); } - #repDlg::backdrop, #titleDlg::backdrop, #wiDlg::backdrop, #pwDlg::backdrop, #apkAltDlg::backdrop { background: rgba(0,0,0,.55); } - #repDlg h2, #titleDlg h2, #wiDlg h2, #pwDlg h2, #apkAltDlg h2 { margin: 0 0 14px; font-size: 15px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--bright); } + #repDlg::backdrop, #titleDlg::backdrop, #wiDlg::backdrop, #pwDlg::backdrop, #apkAltDlg::backdrop, #modDlg::backdrop { background: rgba(0,0,0,.55); } + #repDlg h2, #titleDlg h2, #wiDlg h2, #pwDlg h2, #apkAltDlg h2, #modDlg h2 { margin: 0 0 14px; font-size: 15px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--bright); } #repForm label, #titleForm label { display: block; font-size: 12.5px; color: var(--muted); margin-top: 10px; } #repForm label input[type=text], #repForm textarea, #titleForm label input, #titleForm label select { margin-top: 5px; } #titleForm select { width: 100%; background: rgba(0,0,0,.28); color: var(--text); border: 1px solid transparent; @@ -666,6 +666,20 @@
+ +

Play in VR with UEVR

+

+

UEVR by praydog turns many Unreal Engine games into VR games. Frame Control downloads + the official UEVR 1.05 release and Microsoft's .NET 6 runtime it needs (about 70 MB), checks their hashes, + and keeps them in this game's Proton prefix, not the game's folder. Remove takes them out again.

+

Tested on the Frame with one game so far. Whether a game looks and plays right in VR varies; + UEVR's own menu in the headset has the per-game settings.

+
+ + + +
+

Report an APK

@@ -1701,7 +1715,8 @@ function gameButtons(id, name, free) { const open = ``; if (d && d.appid === id) return `${d.paused ? "Paused" : "Downloading"} ${d.percent ?? 0}%`; if (g && g.installed) return `Installed` + - ``; + `` + + ``; if (g) return ``; return `${free ? "Get" : "Buy"} on Steam ↗${open}`; } @@ -1773,6 +1788,45 @@ document.body.addEventListener("click", async e => { }); loadOwned(); +// ---- VR mod (UEVR) for one installed game; frame_mods.py does the work ---- +const mod = { appid: null, name: "" }; +function showMod(st, note) { + const busy = note === null; + $("modTitle").textContent = `${mod.name} in VR`; + $("modState").textContent = !st ? "Checking the game on the Frame…" + : !st.eligible ? "This doesn't look like an Unreal Engine game, so UEVR can't run it." + : !st.prefix ? "Play the game once first, so Steam sets up its Proton prefix." + : st.injected ? "UEVR is running in the game now. Put on the headset." + : st.installed ? `UEVR ${st.version} is installed for this game.${st.running ? " The game is running; Play in VR adds UEVR to it." : ""}` + : `UEVR ${st.version} isn't installed for this game yet.`; + $("modMsg").textContent = busy ? "Working… this can take a few minutes" : note || ""; + const ok = st && st.eligible && st.prefix; + $("modInstall").hidden = !ok || st.installed; $("modStart").hidden = !ok || !st.installed || st.injected; + $("modRemove").hidden = !st || !st.installed; + for (const b of ["modInstall", "modStart", "modRemove"]) $(b).disabled = busy || (b === "modRemove" && st && st.running); +} +async function modAction(action, label) { + const appid = mod.appid; + showMod(mod.st, null); + const res = await act(`${label} for ${mod.name}`, () => api("/api/mods", { action, appid })); + if (appid !== mod.appid) return; + try { mod.st = await api("/api/mods", { action: "status", appid }); } catch {} + showMod(mod.st, res ? res.message : "Didn't work; the log has the reason"); +} +document.body.addEventListener("click", async e => { + const b = e.target.closest("[data-mod]"); if (!b) return; + mod.appid = b.dataset.mod; mod.name = b.dataset.name; mod.st = null; + showMod(null, ""); + $("modDlg").showModal(); + const appid = mod.appid; + try { const st = await api("/api/mods", { action: "status", appid }); if (appid === mod.appid) { mod.st = st; showMod(st, ""); } } + catch (err) { if (appid === mod.appid) $("modState").textContent = err.message; } +}); +$("modInstall").onclick = () => modAction("install", "Install UEVR"); +$("modStart").onclick = () => modAction("start", "Start UEVR"); +$("modRemove").onclick = () => modAction("uninstall", "Remove UEVR"); +$("modClose").onclick = () => $("modDlg").close(); + // ---- Android apps (own Lepton instance each) + catalogue ---- const VLABEL = { works: "Works on Frame", likely: "Should work", maybe: "Might work", unlikely: "Probably crashes", no: "Won't work" }; const cat = { apps: null, q: "", cat: "", v: new Set(["works", "likely"]), shown: 0, results: [] }; diff --git a/ui/server.py b/ui/server.py index dd86ff6..052ac31 100755 --- a/ui/server.py +++ b/ui/server.py @@ -407,13 +407,14 @@ def launch(body): return {"message": f"Launching {appid}"} -def steam_frame(*args, timeout=40): - """Run frame_steam.py on the Frame (it drives the Steam client) and return its JSON.""" +def steam_frame(*args, timeout=40, script="frame_steam.py"): + """Run frame_steam.py (it drives the Steam client), or another on-Frame + helper with the same JSON contract, on the Frame and return its JSON.""" try: out = ssh("python3 - " + " ".join(map(shlex.quote, args)), - stdin=(HERE / "frame_steam.py").read_text(), timeout=timeout) + stdin=(HERE / script).read_text(), timeout=timeout) except Failure as e: - # frame_steam.py prints {"error": ...} on stdout when it fails, but ssh() + # The helper prints {"error": ...} on stdout when it fails, but ssh() # reports stderr instead if there was any, so look in both. for line in [*reversed(getattr(e, "stdout", "").splitlines()), *reversed(str(e).splitlines())]: try: @@ -434,6 +435,20 @@ def steam(body): return steam_frame(action, appid) +# Downloads are about 70 MB; starting waits for the game, the injector and SteamVR. +MOD_TIMEOUT = {"status": 40, "install": 600, "start": 360, "uninstall": 60} + + +def mods(body): + """UEVR for one installed Unreal game: status, install, start (inject) or uninstall.""" + appid, action = str(body.get("appid", "")), body.get("action") + if not APPID.match(appid): + raise Failure("bad appid", 400) + if action not in MOD_TIMEOUT: + raise Failure("action must be " + ", ".join(MOD_TIMEOUT), 400) + return steam_frame(action, appid, timeout=MOD_TIMEOUT[action], script="frame_mods.py") + + def steam_search(query): q = parse_qs(query) cc = (q.get("cc") or [""])[0].upper() @@ -1227,7 +1242,7 @@ def _sweep_one(prefix, d): pass -POST = {"/api/android/display": android_display, "/api/android": android, "/api/titles": titles, "/api/launch": launch, "/api/steam": steam, "/api/volume": set_volume, "/api/clipboard": clipboard, +POST = {"/api/android/display": android_display, "/api/android": android, "/api/titles": titles, "/api/launch": launch, "/api/steam": steam, "/api/mods": mods, "/api/volume": set_volume, "/api/clipboard": clipboard, "/api/flatpak": flatpak, "/api/open": open_thing, "/api/shots/save": save_shots, "/api/webinstall/check": webinstall_check, "/api/webinstall/start": webinstall_start, "/api/webinstall/cancel": webinstall_cancel} From e3176a2de8999c3bfaf1dec1cfdcbd04bcbc4f9c Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 29 Sep 2026 12:53:28 +1000 Subject: [PATCH 02/19] UEVR: inject with Frame Control's own script instead of UEVR's GUI injector UEVR's .NET injector, driven with XSendEvent, injected in only 6 of 8 cold starts on the Frame: in bad sessions every new injector ignored input or never showed a window. start() now runs frame_inject.py under python.org's embeddable Python (pinned SHA-256) in the game's Wine session, repeating the frontend's own Inject steps: nullify VR plugins, load openvr_api.dll, set Frontend_RequestedRuntime, load UEVRBackend.dll. Verified 9/9 cold starts in 33-35 s and a clean UI install/play/remove cycle. No .NET download any more (47 MB installed instead of about 190 MB). Also from the SWE-2 Max review: one mod action at a time (flock), a download size cap, errors always reported as JSON, a receipt can't name another app's prefix, 0 frames counts as an answer, and a longer server timeout for start. Part of #26. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/evidence/mods-2026-09-29.md | 37 +++- docs/img/uevr-dialog.png | Bin 34646 -> 33395 bytes docs/mods.md | 67 ++++--- tests/test_mods.py | 135 +++++++++----- ui/frame_mods.py | 303 ++++++++++++++++++------------- ui/index.html | 5 +- ui/server.py | 2 +- 7 files changed, 348 insertions(+), 201 deletions(-) diff --git a/docs/evidence/mods-2026-09-29.md b/docs/evidence/mods-2026-09-29.md index 0015ec1..b94c8b8 100644 --- a/docs/evidence/mods-2026-09-29.md +++ b/docs/evidence/mods-2026-09-29.md @@ -4,7 +4,8 @@ [2026-09-28](mods-2026-09-28.md): aarch64, SteamOS `0.4.1`, BUILD_ID `20260925.6191901`, Proton `11.0-2c` ARM64, SteamVR `2.18.1`. Times are the Frame's AEST clock. Headset tests ran under the shared -`/tmp/frame-test.lock`, taken 11:13–11:28 and 11:33–11:49. Battery 45 % → +`/tmp/frame-test.lock`, taken 11:13–11:28, 11:33–11:49, 12:02–12:40 and +12:44–12:52. Battery 45 % → 93 %, on charge throughout. **Not observed:** the VR image, head tracking and controller input. SteamVR @@ -69,10 +70,42 @@ page's **VR mod** dialog, driven with a headless Chromium: | UI: Play in VR ×4 | 4 of 4 injected. The three cold starts took 54, 58 and 58 s; frame submits 56, 71, 80 | | UI: Remove | `drive_c`, `AppData/Roaming` and `AppData/Local` listings matched the pre-install state; download cache and receipt gone | +## The GUI injector wasn't reliable (12:02–12:40) + +After review fixes, cold starts through the API with UEVR's own injector: + +- Batches of 4, 6 and 8 runs: 3/4, 4/6 and 6/8 injected. A retry that + relaunched the injector didn't rescue a bad session. In both failures of + the last batch, the first injector ignored the clicks and the next two + never showed a window within 60 s. +- Captures of the ignoring injector (`xwd`) showed its first-drawn frame, + with OpenVR still unselected. The injector's log had no error. + +Lock released at 12:40 before redesigning. + +## Frame Control's own injector (12:44–12:52) + +`start` now runs `frame_inject.py` under python.org's embeddable Python +3.14.7 (SHA-256 `d297e5ff…1f15`, matching python.org's release-file API), in +the game's Wine session. The old install was removed and the new one +installed without the headset lock, since neither launches anything. The +prefix listing after removal matched the pre-install state; the new install +is 47 MB. + +| Step | Result | +|---|---| +| API `start`, cold | Injected in 35 s, `frame_submits` 39. UEVR log: `Hooked DirectX 11`, `Framework initialized`, `Requested runtime: openvr_api.dll`; `config.txt` has `Frontend_RequestedRuntime=openvr_api.dll` | +| API `start` ×8, cold | **8/8** injected, 33–34 s each; `frame_submits` 33–42 at the check | +| UI: dialog while running | "UEVR is running in the game now." Remove disabled (screenshot in `docs/img/uevr-dialog.png`) | +| UI: Remove → Install → Play in VR → Remove | Each worked; Play in VR injected (`frame_submits` 106 a few seconds later) | +| After the last Remove | `drive_c`, `AppData/Roaming` and `AppData/Local` listings matched the pre-install state; download cache and receipts gone; no game or `python.exe` processes. The empty `/tmp/frame-control-mods.lock` was deleted by hand (tmpfs) | + +Battery 98–100 % on charge. Lock released at 12:52. + ## Left on the Frame - Gravitas (free, 7.4 GB, installed 2026-09-28 for this work) is still installed; nothing else from this work is left. - No `UEVRInjector.exe` or game processes were left running. Steam and SteamVR were running at the end. -- The test lock was released at 11:49. +- The test lock was released at 12:52. diff --git a/docs/img/uevr-dialog.png b/docs/img/uevr-dialog.png index 42849222ea671aab47b33cdeaf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>Ct(Upn91{ob6|MCf%L=vt8N*_i+yl?!w0K`B>c6NRZ#E;I^ zHo9<|EtOg_+p6k`V)KUfFLED((DwM_AE*@9^fyMSDU**@6B}tMYqT^BA-uC|y)hYa z^FqLb66I2TMdN+%D(&5Tr5V`P94+hRb?N_^e9rnl&&3h0-_*V?bX^jf%GsUwu)j4S z{$Xx^FgxM@+09PjV{@~(=1JeHuwFSaisJ|3E2^!AAZr#*U7Ke0jy;~3dw}XMmmP)uo`Xjc6 z=MzEy8zSPGoI9jrne|lnRXi;C6fjo)er^@{p6 zuYDuiopc-7kJs6HKMea*(zFHBQ%h4C+qbe@DUGXMzx=S>keaA5KD)qHuaFwN8P$KH zb$>WoCK{FqU>-&M*4vPV_#R?TQ3WPZKJJ?9~vodpSDHFF850M?n(Cs554S zDFkqqC#VEDa+Ba9GTL^Ad&f>3=d6${McWmliN&40pf=c|$CoFhy&ESD{`t4Oy0MF~^=drBXlT$&?;f^ca!+FC+^O9MVG+p?Za=o^rb{;^C`cbi-~=fbS-Xz*3|bOO6F&C-yNL z@5hnc<@t(%{GWP387`dk)XwvQvQ(L4t*P*c4cP~h~ zATAD##$}3YA4xUa5T5TF(uu%(OGKH;m6)jk>_&X>ex;O!Hm)gY7cU>LYkjRMCC^2z zPn=C^Yz#_CnevhRl5r0dv_iyIf6dMx`zsim+uH|(hRVl_w}nQs!(0e9Hr0{vmct1( zhOuwkmPsyay-i~!tkN$_4H!$FQQ3bGy&=Nvk;Gghx;?nB;(IBB0ae1Q(VdF}2}WK3 zHR>V#r{MCxs;EJM%EbQ%*8KnH4|fgp&a8BI=jYcY{6(qzm;x%JWJGcbxd1mxr6Y+}<7 g_yY3pV+#y~b}4|&Tl)G2_zsBF7kRNCA_jr~2LKWwHUIzs diff --git a/docs/mods.md b/docs/mods.md index c25aed6..d6e7f91 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -26,7 +26,7 @@ means an upstream source describes it; “inferred” means it still needs a tes | Game / build | Mod or content | Evidence and support status | Next check | |---|---|---|---| | Half-Life 2: VR Mod – Episode One, Steam 2177750, build 25413453 | Official Steam community mod, shared base depot 658920 build 25413418 | **Verified: startup only.** Already installed; launched through Proton ARM64. The stereo headset capture showed its first-time setup, and SteamVR loaded `bindings_frame.json`. Gameplay, controller interaction, fresh installation and removal are unverified. | Complete first-time setup and play a level before offering a tested install shortcut. | -| Gravitas, Steam 1067310, Windows, Unreal Engine 4 | UEVR 1.05, from Frame Control | **Verified 2026-09-29: installs, injects, SteamVR receives frames, removes cleanly.** Through the app's UI: install, then three cold **Play in VR** runs (54–58 s each) all loaded `UEVRBackend.dll` into the game, and SteamVR's compositor counted frame submits for `steam.app.1067310`. Remove restored the prefix to its pre-install file listing. **Not seen:** the stereo image, head tracking and controls (headset unworn). | Wear the headset: check the image, tracking, UEVR's in-headset menu and controller input. | +| Gravitas, Steam 1067310, Windows, Unreal Engine 4 | UEVR 1.05, from Frame Control | **Verified 2026-09-29: installs, injects, SteamVR receives frames, removes cleanly.** Nine cold **Play in VR** runs (33–35 s each), then the full cycle again from the app's UI, all loaded `UEVRBackend.dll` into the game, with UEVR logging `Hooked DirectX 11` and `Requested runtime: openvr_api.dll`. SteamVR's compositor counted frame submits for `steam.app.1067310`. Remove restored the prefix to its pre-install file listing. **Not seen:** the stereo image, head tracking and controls (headset unworn). | Wear the headset: check the image, tracking, UEVR's in-headset menu and controller input. | | Beat Saber, Steam 620980, Windows / Proton | Basic custom songs; later SongCore and version-matched mods | **Verified: absent from the 868-game library returned by this Frame.** Store metadata lists Windows, not Linux. **Documented:** the PC game reads basic maps from `Beat Saber_Data/CustomLevels` without a mod manager. Playback on Frame is unverified. | An already-owned, legitimately installed copy is required. Do not buy it as part of this task. | | Beat Saber, claimed native ARM64 build | Custom songs / native mods | **Inferred: unverified.** The research mentions this build but supplies no verified official distributable or tested layout. CPU architecture alone does not identify Android versus Linux, the game version or the mod ABI. | Establish official provenance, ownership, binary type and version before touching files. Do not apply Quest patches to an unidentified build. | | Beat Saber, Alex's Quest 2 copy | Custom songs / Android mods | **Documented: owner-reported copy on Quest 2.** Not reachable on 2026-09-29 (no device on `adb` from the Mac). No APK, version or installed mods inspected; no Frame playback verified. A Quest copy is a Meta store purchase; copying it to another headset would need its entitlement check to pass there, which this work won't work around. This does not establish ownership of the Steam build. | When the Quest is available, inspect the owned copy's version and supported transfer path, then test Lepton/OpenXR compatibility without bypassing entitlement checks. | @@ -56,41 +56,46 @@ like `frame_steam.py`. with Gravitas, and HL2 VR is correctly refused). The game needs a Proton prefix, so it must have been played once. - **Install.** Downloads praydog's [UEVR 1.05 release](https://github.com/praydog/UEVR/releases/tag/1.05) - and Microsoft's Windows x64 .NET 6.0.36 and Windows Desktop runtimes (the - injector is a .NET 6 WPF app, and Proton ships no .NET). Each file is - checked against its pinned SHA-256 (UEVR) or SHA-512 (.NET, from Microsoft's - release metadata) before use. Archives are unpacked into a staging folder, - rejecting entries that escape it, symlinks and oversized contents, and - then moved into `/drive_c/frame-control/`. Nothing goes into the + and python.org's [Windows x64 embeddable Python 3.14.7](https://www.python.org/downloads/release/python-3147/). + Each is checked against a pinned SHA-256; Python's comes from python.org's + release-file API. Archives are unpacked into a staging folder, rejecting + entries that escape it, symlinks and oversized contents, then moved into + `/drive_c/frame-control/` (about 47 MB). Nothing goes into the game's own folder. A receipt in `~/.local/share/frame-control/mods/` lists what to remove, including UEVR's own settings folders only if they didn't - exist before. Install and remove refuse while the game is running. + exist before. Install and remove refuse while the game is running, and only + one mod action runs at a time. - **Play in VR.** Launches the game through Steam if it isn't running and - waits for its window. It then starts `UEVRInjector.exe` with the game's own - Proton, prefix and Wine settings, read from the game process, so both are in - one Wine session. It presses **OpenVR** and **Inject**, confirms that - `UEVRBackend.dll` is mapped into the game, and reads SteamVR's frame count - for the app (`vrcmd --stats`). + waits for its window. It then runs a short script under that Python, with + the game's Proton, prefix and Wine settings read from the game process, so + both share one Wine session. The script repeats what UEVR's own injector does + when you press Inject with OpenVR chosen: load `UEVRPluginNullifier.dll` and + call its `nullify`, load `openvr_api.dll`, set `Frontend_RequestedRuntime` in + UEVR's per-game `config.txt`, then load `UEVRBackend.dll`. Each load is a + `LoadLibraryW` remote thread, as in the frontend's `Injector.cs`. `start` + then checks that `UEVRBackend.dll` is mapped into the game and reads + SteamVR's frame count for the app (`vrcmd --stats`). - **Remove.** Deletes what the receipt lists, then the download cache once no game uses it. Verified: the prefix's file listing matched its pre-install state afterwards. -Things found on the way (verified 2026-09-29): +Why not UEVR's own injector (verified 2026-09-29): -- Under gamescope, the full-screen game keeps the pointer and focus, and - XTest clicks, raising or refocusing the injector window don't change that. - So in the headset you couldn't click the injector yourself, and Frame - Control sends X `ButtonPress`/`ButtonRelease` events straight to the - injector's window instead. The positions are for UEVR 1.05's layout; the - window first maps at 960 px wide and settles at 625 px. `start` refuses to - click if it doesn't settle at that width. -- The injector's `--attach=` didn't inject under Wine. It also - didn't restore the OpenVR choice it had saved, so Frame Control chooses - OpenVR every time. -- With only the game's variables (no `HOME`), the injector hit an - `AccessViolationException` in .NET at startup. With the normal environment - underneath, all four later starts worked. `start` also retries a - crashed injector up to three times. +- It's a .NET 6 WPF app, so it needs Microsoft's .NET runtimes (about 70 MB + of downloads) in the prefix. +- Under gamescope, the full-screen game keeps the pointer and focus. XTest + clicks, raising or refocusing the injector window don't change that, so in + the headset you can't click it. Sending X `ButtonPress`/`ButtonRelease` + events straight to its window does work. +- `--attach=` didn't inject under Wine, and it didn't restore its + saved OpenVR choice. +- Driven that way, it injected in 6 of 8 cold starts. In a bad session every + new injector ignored input or never showed its window, even after + relaunching. Its process list reads each process's main window title, a + cross-process window message; a window that isn't answering would block its + UI thread (inferred from the frontend's source, not proven). Without a + `HOME` it also died in .NET at startup. +- Frame Control's own script injected in 9 of 9 cold starts, in 33–35 s. - UEVR's DirectX 12 probing logs errors before it settles on DirectX 11 for Gravitas, and some of its Unreal engine scans fail on this older UE4 game. Neither stopped the injection. @@ -152,7 +157,11 @@ same, and none of it is built for them: - [UEVR 1.05 official release](https://github.com/praydog/UEVR/releases/tag/1.05) and [author's usage instructions](https://github.com/praydog/UEVR#getting-started). - [Microsoft .NET 6 release metadata](https://builds.dotnet.microsoft.com/dotnet/release-metadata/6.0/releases.json), - including the SHA-512 hashes used for the test runtimes. + including the SHA-512 hashes used for the injector tests. +- [UEVR frontend source](https://github.com/praydog/UEVR-Frontend): `UEVR/MainWindow.xaml.cs` + (`Inject_Clicked`) and `UEVR/Injector.cs`, the steps `frame_inject.py` follows. +- [python.org release-file API](https://www.python.org/api/v2/downloads/release_file/) for the + embeddable Python's `sha256_sum`. - [OpenComposite's OpenXR branch](https://gitlab.com/znixian/OpenOVR/-/tree/openxr), including per-game installation and the need to preserve original DLLs. - [R.E.A.L. author post referenced by the research](https://www.patreon.com/realvr/posts/but-wheres-link-165840151) diff --git a/tests/test_mods.py b/tests/test_mods.py index b4b5e41..b0ad78f 100644 --- a/tests/test_mods.py +++ b/tests/test_mods.py @@ -64,17 +64,15 @@ class FakeLibrary(unittest.TestCase): self.addCleanup(p.stop) self.downloads = {frame_mods.UEVR["url"]: zip_bytes({"UEVRInjector.exe": b"MZ", "UEVRBackend.dll": b"MZ", "openvr_api.dll": b"MZ"})} - for url, _ in frame_mods.DOTNET["files"]: - self.downloads[url] = zip_bytes({"shared/Microsoft.NETCore.App/6.0.36/x.dll": b"MZ"}) + self.downloads[frame_mods.PYTHON["url"]] = zip_bytes({"python.exe": b"MZ", "python314.zip": b"PK"}) self.pin(self.downloads) def pin(self, downloads): """Serve these bytes and pin their real hashes in place of the published ones.""" - uevr = dict(frame_mods.UEVR, sha256=hashlib.sha256(downloads[frame_mods.UEVR["url"]]).hexdigest()) - dotnet = dict(frame_mods.DOTNET, files=[(u, hashlib.sha512(downloads[u]).hexdigest()) - for u, _ in frame_mods.DOTNET["files"]]) - for name, value in (("UEVR", uevr), ("DOTNET", dotnet)): - p = mock.patch.object(frame_mods, name, value) + for name in ("UEVR", "PYTHON"): + pinned = getattr(frame_mods, name) + p = mock.patch.object(frame_mods, name, + dict(pinned, sha256=hashlib.sha256(downloads[pinned["url"]]).hexdigest())) p.start() self.addCleanup(p.stop) p = mock.patch.object(frame_mods.urllib.request, "urlopen", @@ -109,8 +107,9 @@ class InstallUninstall(FakeLibrary): before = sorted(p.relative_to(self.prefix) for p in self.prefix.rglob("*")) res = frame_mods.install(APPID) self.assertTrue(res["installed"]) - self.assertTrue((self.managed() / "uevr-1.05/UEVRInjector.exe").is_file()) - self.assertTrue((self.managed() / "dotnet-6.0.36/shared/Microsoft.NETCore.App/6.0.36/x.dll").is_file()) + self.assertTrue((self.managed() / "uevr-1.05/UEVRBackend.dll").is_file()) + self.assertTrue((self.managed() / "python-3.14.7/python.exe").is_file()) + self.assertIn("UEVRBackend.dll", (self.managed() / "python-3.14.7/frame_inject.py").read_text()) self.assertFalse(list(self.managed().glob(".staging-*"))) # What UEVR writes on its first injection. roaming = self.prefix / "drive_c/users/steamuser/AppData/Roaming/UnrealVRMod/Drop-Win64-Shipping" @@ -166,9 +165,19 @@ class InstallUninstall(FakeLibrary): self.assertTrue((self.managed() / "uevr-1.05").is_dir(), "nothing removed when the receipt is bad") + def test_receipt_cannot_name_another_prefix(self): + frame_mods.install(APPID) + r = frame_mods.read_receipt(APPID) + r["prefix"] = "/" + frame_mods.receipt_path(APPID).write_text(json.dumps(r)) + with self.assertRaisesRegex(frame_mods.Fail, "isn't app"): + frame_mods.uninstall(APPID) + self.assertTrue((self.managed() / "uevr-1.05").is_dir()) + + class Downloads(FakeLibrary): def test_hash_mismatch_deletes_and_installs_nothing(self): - self.downloads[frame_mods.UEVR["url"]] = zip_bytes({"UEVRInjector.exe": b"tampered"}) + self.downloads[frame_mods.UEVR["url"]] = zip_bytes({"UEVRBackend.dll": b"tampered"}) with self.assertRaisesRegex(frame_mods.Fail, "doesn't match"): frame_mods.install(APPID) self.assertFalse((frame_mods.CACHE / "UEVR.zip").exists()) @@ -176,8 +185,8 @@ class Downloads(FakeLibrary): self.assertIsNone(frame_mods.read_receipt(APPID)) def test_archive_escaping_its_folder_is_refused(self): - for bad in (zip_bytes({"UEVRInjector.exe": b"MZ", "../../evil.dll": b"MZ"}), - zip_bytes({"UEVRInjector.exe": b"MZ"}, links=["openvr_api.dll"])): + for bad in (zip_bytes({"UEVRBackend.dll": b"MZ", "../../evil.dll": b"MZ"}), + zip_bytes({"UEVRBackend.dll": b"MZ"}, links=["openvr_api.dll"])): downloads = dict(self.downloads, **{frame_mods.UEVR["url"]: bad}) self.pin(downloads) with self.subTest(), self.assertRaises(frame_mods.Fail): @@ -193,52 +202,88 @@ class Downloads(FakeLibrary): frame_mods.install(APPID) + def test_oversized_download_is_stopped(self): + with mock.patch.object(frame_mods, "MAX_DOWNLOAD", 10): + with self.assertRaisesRegex(frame_mods.Fail, "bigger than expected"): + frame_mods.install(APPID) + self.assertFalse(list(frame_mods.CACHE.glob("*"))) + + +class Actions(FakeLibrary): + def test_one_change_at_a_time(self): + lock = Path(tempfile.mkdtemp()) / "mods.lock" + with mock.patch.object(frame_mods, "LOCK", lock), open(lock, "w") as held: + frame_mods.fcntl.flock(held, frame_mods.fcntl.LOCK_EX) + with self.assertRaisesRegex(frame_mods.Fail, "another mod action"): + frame_mods.main(["install", str(APPID)]) + self.assertFalse(frame_mods.status(APPID)["installed"]) + self.assertEqual(frame_mods.main(["status", str(APPID)])["appid"], APPID, "status never waits") + + def test_zero_frames_is_an_answer(self): + stats = json.dumps([{"key": f"steam.app.{APPID}", "frame_submits": 0}, {"operation": "status"}]) + with mock.patch.object(frame_mods.subprocess, "run", return_value=mock.Mock(stdout=stats)): + self.assertEqual(frame_mods.wait("frames", 5, lambda: frame_mods.frame_submits(APPID)), 0) + with mock.patch.object(frame_mods.subprocess, "run", return_value=mock.Mock(stdout='{"odd": 1}')): + self.assertIsNone(frame_mods.frame_submits(APPID)) + + class Start(FakeLibrary): + def environ(self, text): + """The game's /proc//environ; every other file reads normally.""" + real = frame_mods.Path.read_text + return mock.patch.object(frame_mods.Path, "read_text", autospec=True, side_effect=lambda path, *a, **k: + text if str(path).startswith("/proc/") else real(path, *a, **k)) + def test_needs_install_first(self): with self.assertRaisesRegex(frame_mods.Fail, "isn't installed"): frame_mods.start(APPID) - def test_refuses_to_click_an_unexpected_layout(self): + def run_start(self, reply, loaded=(False, True, True, True)): frame_mods.install(APPID) self.running = 4242 env = "WINEPREFIX=/x\0DISPLAY=:1\0WINESERVERSOCKET=17\0PATH=/p\0" - windows = [[(1, "SkyArk", 1280)], [(1, "SkyArk", 1280)], [(1, "SkyArk", 1280), (2, "UEVR", 700)]] - with mock.patch("builtins.open", mock.mock_open(read_data=env)), \ - mock.patch.object(frame_mods, "loaded", return_value=False), \ - mock.patch.object(frame_mods, "x11_windows", side_effect=lambda d: windows.pop(0) if len(windows) > 1 else windows[0]), \ - mock.patch.object(frame_mods.subprocess, "Popen") as popen, \ - mock.patch.object(frame_mods, "x_click") as click, \ - mock.patch.object(frame_mods.os, "killpg") as kill, \ - mock.patch.object(frame_mods.time, "time", side_effect=itertools.count(0, 5)), \ - mock.patch.object(frame_mods.time, "sleep"): - popen.return_value.poll.return_value = None # the injector stays up - with self.assertRaisesRegex(frame_mods.Fail, "700 px"): - frame_mods.start(APPID) - click.assert_not_called() - kill.assert_called_once_with(popen.return_value.pid, frame_mods.signal.SIGKILL) - env_used = popen.call_args.kwargs["env"] - self.assertNotIn("WINESERVERSOCKET", env_used, "an inherited fd number means nothing to a new process") - self.assertEqual(env_used["DOTNET_ROOT"], "C:\\frame-control\\dotnet-6.0.36") - self.assertEqual(env_used["WINEPREFIX"], "/x") - self.assertIn("HOME", env_used, "fontconfig needs a HOME for its cache") - - def test_injector_that_keeps_crashing_is_reported(self): - frame_mods.install(APPID) - self.running = 4242 - with mock.patch("builtins.open", mock.mock_open(read_data="WINEPREFIX=/x\0DISPLAY=:1\0")), \ - mock.patch.object(frame_mods, "loaded", return_value=False), \ + with self.environ(env), \ + mock.patch.object(frame_mods, "loaded", side_effect=list(loaded) + [True] * 5), \ mock.patch.object(frame_mods, "x11_windows", return_value=[(1, "SkyArk", 1280)]), \ - mock.patch.object(frame_mods.subprocess, "Popen") as popen, \ - mock.patch.object(frame_mods, "x_click") as click, \ + mock.patch.object(frame_mods.subprocess, "run", return_value=mock.Mock(stdout=reply, stderr="")) as run, \ + mock.patch.object(frame_mods, "frame_submits", return_value=7), \ mock.patch.object(frame_mods.time, "sleep"): - popen.return_value.poll.return_value = 134 # died before showing its window - with self.assertRaisesRegex(frame_mods.Fail, "crashed on start 3 times"): - frame_mods.start(APPID) - self.assertEqual(popen.call_count, 3) - click.assert_not_called() + return frame_mods.start(APPID), run + + def test_injects_with_the_games_wine_settings(self): + res, run = self.run_start('noise\n{"pid": 320}\n') + self.assertEqual((res["frame_submits"], res["message"]), (7, "UEVR injected into Gravitas; SteamVR is receiving its frames")) + cmd, env = run.call_args.args[0], run.call_args.kwargs["env"] + self.assertEqual(cmd[:2], ["wine", "C:\\frame-control\\python-3.14.7\\python.exe"]) + self.assertEqual(cmd[3:], ["Drop-Win64-Shipping.exe", "C:\\frame-control\\uevr-1.05", + "C:\\users\\steamuser\\AppData\\Roaming\\UnrealVRMod\\Drop-Win64-Shipping"]) + self.assertEqual(env["WINEPREFIX"], "/x") + self.assertNotIn("WINESERVERSOCKET", env, "an inherited fd number means nothing to a new process") + self.assertIn("HOME", env, "fontconfig needs a HOME for its cache") + + def test_reports_the_injection_error(self): + with self.assertRaisesRegex(frame_mods.Fail, "couldn't open"): + self.run_start('{"error": "couldn\'t open Drop-Win64-Shipping.exe (5)"}\n') + + def test_success_is_checked_in_the_game(self): + with self.assertRaisesRegex(frame_mods.Fail, "has no UEVRBackend.dll"): + with mock.patch.object(frame_mods.time, "time", side_effect=itertools.count(0, 5)): + self.run_start('{"pid": 320}\n', loaded=[False] * 40) + + def test_inject_script_is_valid_python(self): + compile(frame_mods.INJECT_PY, "frame_inject.py", "exec") class Helper(unittest.TestCase): + def test_unexpected_errors_are_still_json(self): + # A receipt from another version, without "exe": a KeyError, not a traceback. + script = (ROOT / "ui" / "frame_mods.py").read_text().replace( + "def read_receipt(appid):", "def read_receipt(appid):\n return {'prefix': '/x'}\n\n\ndef _unused(appid):") + out = subprocess.run([sys.executable, "-", "uninstall", "1"], input=script, + capture_output=True, text=True, timeout=30, env={"HOME": tempfile.mkdtemp()}) + self.assertEqual(out.returncode, 1, out.stderr) + self.assertIn("KeyError", json.loads(out.stdout)["error"]) + def test_bad_usage_prints_json_error(self): for args in ([], ["install"], ["install", "12x"], ["remove", "620"]): out = subprocess.run([sys.executable, str(ROOT / "ui" / "frame_mods.py"), *args], diff --git a/ui/frame_mods.py b/ui/frame_mods.py index f4db415..1aebbf7 100644 --- a/ui/frame_mods.py +++ b/ui/frame_mods.py @@ -8,22 +8,26 @@ Usage: python3 - status APPID # can UEVR run here, is it installed, is the g Prints one JSON object. Errors are {"error": "..."} with exit status 1. Verified 2026-09-29 on SteamOS 0.4.1 (build 20260925.6191901), Proton 11.0 -ARM64 and SteamVR 2.18.1 with Gravitas (1067310): UEVR 1.05's injector runs in -the game's own Wine session, and after OpenVR + Inject the game loads -UEVRBackend.dll and SteamVR counts frame submits for it. Stereo image, head -tracking and controls were not seen: the headset was unworn (docs/mods.md). +ARM64 and SteamVR 2.18.1 with Gravitas (1067310): after injection the game has +UEVRBackend.dll loaded and SteamVR counts frame submits for it. Stereo image, +head tracking and controls were not seen: the headset was unworn (docs/mods.md). -Nothing here is bundled. UEVR comes from praydog's GitHub release, and the -Windows .NET 6 runtime it needs from Microsoft's release metadata URLs, each -checked against a pinned hash. Files live in /drive_c/frame-control, -never in the game's own folder, and a receipt records what to remove. +UEVR's own injector (a .NET WPF app) is not used. Under Wine and FEX it hung +or ignored input in about one session in four, and gamescope keeps real input +away from it. Instead the official Windows embeddable Python runs INJECT_PY in +the game's Wine session, doing what the injector does on Inject. + +Nothing here is bundled. UEVR comes from praydog's GitHub release and Python +from python.org, each checked against a pinned hash. Files live in +/drive_c/frame-control, never in the game's own folder, and a receipt +records what to remove. """ +import fcntl import hashlib import json import os import re import shutil -import signal import subprocess import sys import time @@ -35,35 +39,122 @@ HOME = Path.home() STEAM = HOME / ".local/share/Steam" CACHE = HOME / ".cache/frame-control/mods" RECEIPTS = HOME / ".local/share/frame-control/mods" +LOCK = Path("/tmp/frame-control-mods.lock") # tmpfs: gone at reboot, never left in ~ VRCMD = "/opt/steamvr/bin/linuxarm64/vrcmd" MANAGED = "frame-control" # drive_c/ inside the game's prefix UEVR = {"version": "1.05", "dir": "uevr-1.05", "url": "https://github.com/praydog/UEVR/releases/download/1.05/UEVR.zip", "sha256": "af4f2f91306802d7ee4e8497d483a547ac8e9a3067dbafb81324100524215d3c"} -# UEVRInjector.exe is a .NET 6 WPF app; Proton ships no .NET. These are the -# win-x64 ZIPs listed in builds.dotnet.microsoft.com/dotnet/release-metadata/6.0/releases.json. -DOTNET = {"version": "6.0.36", "dir": "dotnet-6.0.36", "files": [ - ("https://builds.dotnet.microsoft.com/dotnet/Runtime/6.0.36/dotnet-runtime-6.0.36-win-x64.zip", - "935db5c6cee19f2c016e67168bfae7b491044735de76c673abb3b125dd325fd5e779d7efe12ba80178d46689ae70a25e558a3fa846417d44c5f4ca256e7f4bf2"), - ("https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/6.0.36/windowsdesktop-runtime-6.0.36-win-x64.zip", - "cee88fef07643dceb3d34ea71b64eeae85b8e39e7042bc4d35bc3a1f1df29373681dc48e31c01c9f593ec412699f6762b6fc5817433283c89df35a27ce8885bf")]} -MAX_UNPACKED = 600 << 20 # the three archives unpack to about 190 MB +# Windows x64 embeddable Python, to run INJECT_PY. Hash from python.org's +# release-file API (sha256_sum). +PYTHON = {"version": "3.14.7", "dir": "python-3.14.7", + "url": "https://www.python.org/ftp/python/3.14.7/python-3.14.7-embed-amd64.zip", + "sha256": "d297e5ff019966817ad8502465176139f2d3d840fa4ed84b13bed399a6ab1f15"} +MAX_UNPACKED = 200 << 20 # the two archives unpack to about 50 MB +MAX_DOWNLOAD = 50 << 20 # each archive is 7–13 MB -# UEVR 1.05's injector window (625 px wide), in window coordinates. Under -# gamescope the full-screen game keeps the pointer and focus, so real clicks -# can't reach the injector; XSendEvent to its window does. It doesn't restore -# its saved runtime choice under Wine, and --attach didn't inject, so choose -# OpenVR (SteamVR's own API) and press Inject every time. -INJECTOR_WIDTH = 625 -CLICK_OPENVR, CLICK_INJECT = (125, 137), (365, 113) -# The game's environment the injector needs to join its Wine session. Not +# The game's environment a second program needs to join its Wine session. Not # WINESERVERSOCKET and friends: those are inherited file descriptors. GAME_ENV = re.compile(r"(WINEPREFIX|WINEDLLPATH|WINEDLLOVERRIDES|WINEFSYNC|WINEDEBUG|PATH|DISPLAY|" r"XDG_RUNTIME_DIR|PROTON_VR_RUNTIME|FEX_APP_CONFIG|FEX_APP_CONFIG_LOCATION|" r"SteamAppId|SteamGameId|STEAM_COMPAT_DATA_PATH|WINE_LARGE_ADDRESS_AWARE)=") +# Runs under Windows Python in the game's Wine session: the steps of UEVR +# 1.05's frontend (UEVR/MainWindow.xaml.cs Inject_Clicked, UEVR/Injector.cs) +# with "Nullify VR plugins" on and the OpenVR runtime. Prints one JSON line. +INJECT_PY = r""" +import ctypes, json, os, sys +from ctypes import wintypes as W +exe, uevr, profile = sys.argv[1:4] +k32 = ctypes.WinDLL("kernel32", use_last_error=True) +k32.OpenProcess.restype = W.HANDLE +k32.VirtualAllocEx.restype = ctypes.c_void_p +k32.VirtualAllocEx.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.c_size_t, W.DWORD, W.DWORD] +k32.WriteProcessMemory.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] +k32.CreateRemoteThread.restype = W.HANDLE +k32.CreateRemoteThread.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p, + W.DWORD, ctypes.c_void_p] +k32.GetModuleHandleW.restype = W.HMODULE +k32.GetProcAddress.restype = ctypes.c_void_p +k32.GetProcAddress.argtypes = [W.HMODULE, ctypes.c_char_p] +k32.LoadLibraryW.restype = W.HMODULE +k32.CreateToolhelp32Snapshot.restype = W.HANDLE + +class Entry(ctypes.Structure): # PROCESSENTRY32W + _fields_ = [("size", W.DWORD), ("usage", W.DWORD), ("pid", W.DWORD), ("heap", ctypes.c_void_p), + ("module", W.DWORD), ("threads", W.DWORD), ("parent", W.DWORD), ("prio", ctypes.c_long), + ("flags", W.DWORD), ("name", W.WCHAR * 260)] + +class Module(ctypes.Structure): # MODULEENTRY32W + _fields_ = [("size", W.DWORD), ("mid", W.DWORD), ("pid", W.DWORD), ("glbl", W.DWORD), ("proc", W.DWORD), + ("base", ctypes.c_void_p), ("bytes", W.DWORD), ("handle", W.HMODULE), + ("name", W.WCHAR * 256), ("path", W.WCHAR * 260)] + +def fail(msg): + print(json.dumps({"error": msg})); sys.exit(1) + +def find_pid(): + snap = k32.CreateToolhelp32Snapshot(2, 0) # TH32CS_SNAPPROCESS + e = Entry(); e.size = ctypes.sizeof(e) + ok = k32.Process32FirstW(snap, ctypes.byref(e)) + while ok: + if e.name.lower() == exe.lower(): + k32.CloseHandle(snap); return e.pid + ok = k32.Process32NextW(snap, ctypes.byref(e)) + k32.CloseHandle(snap) + +def module_base(pid, path): + snap = k32.CreateToolhelp32Snapshot(0x18, pid) # TH32CS_SNAPMODULE | SNAPMODULE32 + m = Module(); m.size = ctypes.sizeof(m) + ok = k32.Module32FirstW(snap, ctypes.byref(m)) + while ok: + if m.path.lower() == path.lower(): + k32.CloseHandle(snap); return m.base + ok = k32.Module32NextW(snap, ctypes.byref(m)) + k32.CloseHandle(snap) + +def remote_call(proc, fn, arg=None, wait_ms=10000): + t = k32.CreateRemoteThread(proc, None, 0, fn, arg, 0, None) + if not t: + fail(f"CreateRemoteThread failed ({ctypes.get_last_error()})") + k32.WaitForSingleObject(t, wait_ms); k32.CloseHandle(t) + +def inject(proc, pid, name): + path = os.path.join(uevr, name) + data = ctypes.create_unicode_buffer(path) + mem = k32.VirtualAllocEx(proc, None, ctypes.sizeof(data), 0x3000, 0x04) # commit|reserve, read/write + if not mem or not k32.WriteProcessMemory(proc, mem, data, ctypes.sizeof(data), None): + fail(f"couldn't write into {exe} ({ctypes.get_last_error()})") + remote_call(proc, k32.GetProcAddress(k32.GetModuleHandleW("kernel32.dll"), b"LoadLibraryW"), mem) + base = module_base(pid, path) + if not base: + fail(f"{name} didn't load into {exe}") + return path, base + +pid = find_pid() +if not pid: + fail(f"{exe} isn't running") +proc = k32.OpenProcess(0x1F0FFF, False, pid) # PROCESS_ALL_ACCESS +if not proc: + fail(f"couldn't open {exe} ({ctypes.get_last_error()})") +path, base = inject(proc, pid, "UEVRPluginNullifier.dll") +local = k32.LoadLibraryW(path) +offset = k32.GetProcAddress(local, b"nullify") - local # same DLL, same layout in both processes +remote_call(proc, base + offset, wait_ms=2000) +inject(proc, pid, "openvr_api.dll") +# The frontend saves the runtime choice in the per-game config before UEVRBackend reads it. +os.makedirs(profile, exist_ok=True) +cfg = os.path.join(profile, "config.txt") +lines = open(cfg).read().splitlines() if os.path.exists(cfg) else [] +lines = [l for l in lines if not l.startswith("Frontend_RequestedRuntime=")] + ["Frontend_RequestedRuntime=openvr_api.dll"] +open(cfg, "w").write("\n".join(lines) + "\n") +inject(proc, pid, "UEVRBackend.dll") +print(json.dumps({"pid": pid})) +""" + + class Fail(Exception): pass @@ -173,8 +264,11 @@ def fetch(url, digest, algo): part = path.with_suffix(path.suffix + ".part") try: with urllib.request.urlopen(url, timeout=60) as r, open(part, "wb") as f: - shutil.copyfileobj(r, f, 1 << 20) - except OSError as e: + for block in iter(lambda: r.read(1 << 20), b""): + if f.tell() + len(block) > MAX_DOWNLOAD: + raise Fail(f"{url} is bigger than expected; stopped the download") + f.write(block) + except (OSError, Fail) as e: part.unlink(missing_ok=True) raise Fail(f"download failed: {url}: {e}") part.rename(path) @@ -217,7 +311,7 @@ def install(appid): if read_receipt(appid): return {"message": f"UEVR {UEVR['version']} is already installed for {g['name']}", **status(appid)} archives = [(fetch(UEVR["url"], UEVR["sha256"], "sha256"), UEVR["dir"])] - archives += [(fetch(url, digest, "sha512"), DOTNET["dir"]) for url, digest in DOTNET["files"]] + archives.append((fetch(PYTHON["url"], PYTHON["sha256"], "sha256"), PYTHON["dir"])) base = managed_dir(g) dirs = user_dirs(g, exe) fresh = [str(d) for d in (dirs["profile"].parent, base) if not d.exists()] # remove on uninstall if empty @@ -227,9 +321,13 @@ def install(appid): budget = MAX_UNPACKED for archive, sub in archives: budget = unpack(archive, stage / sub, budget) - if not (stage / UEVR["dir"] / "UEVRInjector.exe").is_file(): - raise Fail("UEVR.zip has no UEVRInjector.exe") - for sub in (UEVR["dir"], DOTNET["dir"]): + for need in (stage / UEVR["dir"] / "UEVRBackend.dll", stage / PYTHON["dir"] / "python.exe"): + if not need.is_file(): + raise Fail(f"the download has no {need.name}") + if game_pid(exe.name): # it may have started during the download + raise Fail(f"{g['name']} started; quit it first") + (stage / PYTHON["dir"] / "frame_inject.py").write_text(INJECT_PY) + for sub in (UEVR["dir"], PYTHON["dir"]): shutil.rmtree(base / sub, ignore_errors=True) (stage / sub).rename(base / sub) finally: @@ -241,13 +339,13 @@ def install(appid): pass receipt = {"appid": appid, "mod": "UEVR", "version": UEVR["version"], "exe": exe.name, "installed": int(time.time()), "prefix": str(g["prefix"]), - "remove": [str(base / UEVR["dir"]), str(base / DOTNET["dir"])], + "remove": [str(base / UEVR["dir"]), str(base / PYTHON["dir"])], # Parents that didn't exist yet (UEVR makes UnrealVRMod), deepest first. "remove_if_empty": fresh, # UEVR creates these on first injection. Remove them on uninstall # only if they weren't there before, so earlier settings survive. "remove_if_created": {k: str(v) for k, v in dirs.items() if not v.exists()}, - "sources": [UEVR["url"]] + [u for u, _ in DOTNET["files"]]} + "sources": [UEVR["url"], PYTHON["url"]]} RECEIPTS.mkdir(parents=True, exist_ok=True) tmp = receipt_path(appid).with_suffix(".tmp") tmp.write_text(json.dumps(receipt, indent=1)) @@ -265,55 +363,22 @@ def x11_windows(display): return [(int(m[1], 16), m[2], int(m[3])) for m in re.finditer(r'(0x[0-9a-f]+) "([^"]*)":.*?\)\s+(\d+)x\d+', out)] -def x_click(display, window, points): - """Send ButtonPress/Release straight to a window (gamescope blocks real input to it).""" - import ctypes as C - x11 = C.CDLL("libX11.so.6") - x11.XOpenDisplay.restype = C.c_void_p - - class Button(C.Structure): - _fields_ = [("type", C.c_int), ("serial", C.c_ulong), ("send_event", C.c_int), ("display", C.c_void_p), - ("window", C.c_ulong), ("root", C.c_ulong), ("subwindow", C.c_ulong), ("time", C.c_ulong), - ("x", C.c_int), ("y", C.c_int), ("x_root", C.c_int), ("y_root", C.c_int), - ("state", C.c_uint), ("button", C.c_uint), ("same_screen", C.c_int)] - - class Event(C.Union): - _fields_ = [("xbutton", Button), ("pad", C.c_long * 24)] - - d = x11.XOpenDisplay(display.encode()) - if not d: - raise Fail(f"can't open X display {display}") - d = C.c_void_p(d) - root = x11.XDefaultRootWindow(d) - ox, oy, child = C.c_int(), C.c_int(), C.c_ulong() - x11.XTranslateCoordinates(d, C.c_ulong(window), C.c_ulong(root), 0, 0, C.byref(ox), C.byref(oy), C.byref(child)) - for x, y in points: - for kind, mask, state in ((4, 1 << 2, 0), (5, 1 << 3, 1 << 8)): # press, then release with Button1 held - e = Event() - b = e.xbutton - b.type, b.send_event, b.window, b.root, b.x, b.y = kind, 1, window, root, x, y - b.x_root, b.y_root, b.state, b.button, b.same_screen = x + ox.value, y + oy.value, state, 1, 1 - x11.XSendEvent(d, C.c_ulong(window), 1, C.c_long(mask), C.byref(e)) - x11.XFlush(d) - time.sleep(0.15) - time.sleep(1.5) - x11.XCloseDisplay(d) - - def frame_submits(appid): """SteamVR's count of frames the app has submitted, or None if it isn't a scene app.""" try: stats = json.loads(subprocess.run([VRCMD, "--stats"], capture_output=True, text=True, timeout=15).stdout) except (OSError, ValueError, subprocess.TimeoutExpired): return None - return next((s.get("frame_submits") for s in stats if s.get("key") == f"steam.app.{appid}"), None) + if not isinstance(stats, list): + return None + return next((s.get("frame_submits") for s in stats if isinstance(s, dict) and s.get("key") == f"steam.app.{appid}"), None) def wait(what, seconds, check, step=2): end = time.time() + seconds while time.time() < end: v = check() - if v: + if v is not None and v is not False: # 0 frames is still an answer return v time.sleep(step) raise Fail(f"timed out waiting for {what}") @@ -332,64 +397,43 @@ def start(appid): subprocess.Popen(["steam", f"steam://rungameid/{appid}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env={**os.environ, "DISPLAY": os.environ.get("DISPLAY", ":0")}, start_new_session=True) pid = wait(f"{g['name']} to start", 120, lambda: game_pid(exe)) - env = dict(line.split("=", 1) for line in open(f"/proc/{pid}/environ").read().split("\0") - if GAME_ENV.match(line)) - display = env.get("DISPLAY") - if not display or "WINEPREFIX" not in env: - raise Fail(f"{exe} doesn't look like a Proton game process") - # The game needs its D3D11 window before UEVR can hook it. Proton's own - # helper windows ("Steam", "Default IME", …) are small. - wait("the game window", 90, lambda: any(w[2] >= 640 and w[1] != "UEVR" for w in x11_windows(display))) - time.sleep(10) - root = f"C:\\{MANAGED}\\{DOTNET['dir']}" - # Our own environment (HOME and the rest) under the game's Wine settings: - # with only the game's variables, fontconfig had no cache directory. - env = {**os.environ, **env, "DOTNET_ROOT": root, "DOTNET_ROOT_X64": root} - # The .NET injector sometimes dies at startup under Wine and FEX (an - # AccessViolationException, 2026-09-29), so give it a few tries. - for attempt in range(3): - before = {w[0] for w in x11_windows(display) if w[1] == "UEVR"} - log = open(CACHE / f"injector-{appid}.log", "w") if CACHE.is_dir() else subprocess.DEVNULL - injector = subprocess.Popen(["wine", f"C:\\{MANAGED}\\{UEVR['dir']}\\UEVRInjector.exe"], env=env, - stdout=log, stderr=log, stdin=subprocess.DEVNULL, start_new_session=True, - cwd=str(Path(r["prefix"]) / "drive_c" / MANAGED / UEVR["dir"])) - try: - win = wait("the UEVR injector window", 90, - lambda: injector.poll() is not None or next( - (w for w in x11_windows(display) if w[1] == "UEVR" and w[0] not in before), None)) - except Fail: - os.killpg(injector.pid, signal.SIGKILL) - raise - if win is not True: - break - else: - raise Fail(f"the UEVR injector crashed on start {attempt + 1} times; " - f"its log is in ~/.cache/frame-control/mods/injector-{appid}.log") try: - # It maps at a default size, then WPF lays it out (seen: 960 px, then 625). - try: - wait("the UEVR window's layout", 30, - lambda: any(w[0] == win[0] and w[2] == INJECTOR_WIDTH for w in x11_windows(display)), step=1) - except Fail: - width = next((w[2] for w in x11_windows(display) if w[0] == win[0]), "?") - raise Fail(f"the UEVR window is {width} px wide, not {INJECTOR_WIDTH}; " - "its layout changed, so not clicking blind") from None - time.sleep(5) # let it fill its process list - x_click(display, win[0], [CLICK_OPENVR, CLICK_INJECT]) - try: - wait("UEVRBackend.dll to load in the game", 45, lambda: loaded(pid, "UEVRBackend.dll")) - except Fail: - raise Fail(f"UEVR didn't inject into {exe}. Its log is in ~/.cache/frame-control/mods/injector-{appid}.log") from None + environ = Path(f"/proc/{pid}/environ").read_text(errors="replace") + except OSError: + raise Fail(f"{exe} exited") from None + game_env = dict(line.split("=", 1) for line in environ.split("\0") if GAME_ENV.match(line)) + display = game_env.get("DISPLAY") + if not display or "WINEPREFIX" not in game_env: + raise Fail(f"{exe} doesn't look like a Proton game process") + # UEVR hooks the game's D3D11/12 device, so wait for its window. Proton's + # own helper windows ("Steam", "Default IME", …) are small. + wait("the game window", 90, lambda: any(w[2] >= 640 for w in x11_windows(display))) + time.sleep(10) + # Our own environment (HOME and the rest) under the game's Wine settings. + env = {**os.environ, **game_env} + base = f"C:\\{MANAGED}" + profile = f"C:\\users\\steamuser\\AppData\\Roaming\\UnrealVRMod\\{Path(exe).stem}" + try: + out = subprocess.run(["wine", f"{base}\\{PYTHON['dir']}\\python.exe", f"{base}\\{PYTHON['dir']}\\frame_inject.py", + exe, f"{base}\\{UEVR['dir']}", profile], env=env, capture_output=True, text=True, + timeout=120, stdin=subprocess.DEVNULL, + cwd=str(Path(r["prefix"]) / "drive_c" / MANAGED)) + except subprocess.TimeoutExpired: + raise Fail("the injection step didn't finish in 2 minutes") from None + reply = next((json.loads(l) for l in reversed(out.stdout.splitlines()) if l.startswith("{")), None) + if not reply or "error" in reply: + raise Fail("UEVR injection failed: " + (reply or {}).get("error", (out.stderr.strip().splitlines() or ["no output"])[-1])) + try: + wait("UEVRBackend.dll to load in the game", 20, lambda: loaded(pid, "UEVRBackend.dll")) except Fail: - os.killpg(injector.pid, signal.SIGKILL) # don't leave an injector window behind a failed start - raise + raise Fail(f"the injection reported success but {exe} has no UEVRBackend.dll") from None submits = None try: submits = wait("SteamVR frames", 30, lambda: frame_submits(appid)) except Fail: pass - return {"message": f"UEVR injected into {g['name']}" + ("; SteamVR is receiving its frames" if submits else - "; SteamVR hasn't reported frames from it yet"), + return {"message": f"UEVR injected into {g['name']}" + ("; SteamVR is receiving its frames" if submits is not None + else "; SteamVR hasn't reported frames from it yet"), "frame_submits": submits, **status(appid)} @@ -400,6 +444,8 @@ def uninstall(appid): if game_pid(r["exe"]): raise Fail("the game is running; quit it first") prefix = os.path.realpath(r["prefix"]) + if not prefix.endswith(f"/steamapps/compatdata/{appid}/pfx"): + raise Fail(f"receipt names a prefix that isn't app {appid}'s: {r['prefix']}") targets = list(r.get("remove", [])) + list(r.get("remove_if_created", {}).values()) for t in targets: # a receipt only ever points inside this game's prefix real = os.path.realpath(t) @@ -426,7 +472,17 @@ def uninstall(appid): def main(argv): if len(argv) != 2 or argv[0] not in ("status", "install", "start", "uninstall") or not argv[1].isdigit(): raise Fail("usage: status|install|start|uninstall APPID") - return {"status": status, "install": install, "start": start, "uninstall": uninstall}[argv[0]](int(argv[1])) + action = {"status": status, "install": install, "start": start, "uninstall": uninstall}[argv[0]] + if action is status: + return status(int(argv[1])) + # One change at a time, or an uninstall could delete what an install is moving in. + LOCK.parent.mkdir(parents=True, exist_ok=True) + with open(LOCK, "w") as lock: + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + raise Fail("another mod action is still running on the Frame; try again when it finishes") from None + return action(int(argv[1])) if __name__ == "__main__": @@ -435,3 +491,6 @@ if __name__ == "__main__": except Fail as e: print(json.dumps({"error": str(e)})) sys.exit(1) + except Exception as e: # still one JSON object, for the server to show + print(json.dumps({"error": f"{type(e).__name__}: {e}"})) + sys.exit(1) diff --git a/ui/index.html b/ui/index.html index 3cacd4e..4990255 100644 --- a/ui/index.html +++ b/ui/index.html @@ -670,8 +670,9 @@

Play in VR with UEVR

UEVR by praydog turns many Unreal Engine games into VR games. Frame Control downloads - the official UEVR 1.05 release and Microsoft's .NET 6 runtime it needs (about 70 MB), checks their hashes, - and keeps them in this game's Proton prefix, not the game's folder. Remove takes them out again.

+ the official UEVR 1.05 release and python.org's Windows Python, which it uses to load UEVR into the game + (about 20 MB), checks their hashes, and keeps them in this game's Proton prefix, not the game's folder. + Remove takes them out again.

Tested on the Frame with one game so far. Whether a game looks and plays right in VR varies; UEVR's own menu in the headset has the per-game settings.

diff --git a/ui/server.py b/ui/server.py index 052ac31..711d390 100755 --- a/ui/server.py +++ b/ui/server.py @@ -436,7 +436,7 @@ def steam(body): # Downloads are about 70 MB; starting waits for the game, the injector and SteamVR. -MOD_TIMEOUT = {"status": 40, "install": 600, "start": 360, "uninstall": 60} +MOD_TIMEOUT = {"status": 40, "install": 600, "start": 900, "uninstall": 60} def mods(body): From 2f056dbcffa3c0e6f86ccb3ad3cf1651b7ad91e1 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:04:12 +1000 Subject: [PATCH 03/19] UEVR: address the second review; recheck on the Frame frame_inject.py declares every Win32 signature, checks each result, frees its remote buffers and closes handles. Uninstall only accepts our folder and UEVR's own per-game settings folders, and keeps the receipt if anything can't be removed. The injector's reply is parsed defensively. Rechecked on a real Frame: install, three cold starts injected (33-35 s), clean uninstall. Part of #26. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/evidence/mods-2026-09-29.md | 19 ++++- docs/mods.md | 4 +- tests/test_mods.py | 21 ++++- ui/frame_mods.py | 140 +++++++++++++++++++------------ ui/server.py | 2 +- 5 files changed, 126 insertions(+), 60 deletions(-) diff --git a/docs/evidence/mods-2026-09-29.md b/docs/evidence/mods-2026-09-29.md index b94c8b8..605a6c2 100644 --- a/docs/evidence/mods-2026-09-29.md +++ b/docs/evidence/mods-2026-09-29.md @@ -4,8 +4,8 @@ [2026-09-28](mods-2026-09-28.md): aarch64, SteamOS `0.4.1`, BUILD_ID `20260925.6191901`, Proton `11.0-2c` ARM64, SteamVR `2.18.1`. Times are the Frame's AEST clock. Headset tests ran under the shared -`/tmp/frame-test.lock`, taken 11:13–11:28, 11:33–11:49, 12:02–12:40 and -12:44–12:52. Battery 45 % → +`/tmp/frame-test.lock`, taken 11:13–11:28, 11:33–11:49, 12:02–12:40, +12:44–12:52 and 13:01–13:03. Battery 45 % → 93 %, on charge throughout. **Not observed:** the VR image, head tracking and controller input. SteamVR @@ -66,7 +66,7 @@ page's **VR mod** dialog, driven with a headless Chromium: | `uninstall` while running | Refused: "the game is running; quit it first" | | `start`, game not running | Launched the game, injected, `frame_submits` 45 (55 s) | | UI: Remove, Install | Worked; the prefix listing matched its pre-install state except an empty `UnrealVRMod`, which uninstall now also removes | -| UI: Play in VR | Failed once: the injector died with `Process terminated. … Resource name: Arg_AccessViolationException`, after `Fontconfig error: No writable cache directories` (it had no `HOME`). Fixed by keeping the normal environment under the game's; `start` also retries up to three times | +| UI: Play in VR | Failed once: the injector died with `Process terminated. … Resource name: Arg_AccessViolationException`, after `Fontconfig error: No writable cache directories` (it had no `HOME`). Fixed by keeping the normal environment under the game's (the relaunch-on-failure added next is gone with the GUI injector; see below) | | UI: Play in VR ×4 | 4 of 4 injected. The three cold starts took 54, 58 and 58 s; frame submits 56, 71, 80 | | UI: Remove | `drive_c`, `AppData/Roaming` and `AppData/Local` listings matched the pre-install state; download cache and receipt gone | @@ -102,10 +102,21 @@ is 47 MB. Battery 98–100 % on charge. Lock released at 12:52. +## After the second review (13:01–13:03) + +`frame_inject.py` now declares every Win32 signature, checks each result, +frees its remote buffers and closes its handles; uninstall accepts only our +folder and UEVR's own settings folders. Rechecked: install; three cold starts +injected in 35, 34 and 33 s (`frame_submits` 42, 38, 47), UEVR logging +`Framework initialized` and `Requested runtime: openvr_api.dll`; uninstall +left `drive_c`, `AppData/Roaming` and `AppData/Local` as before, with no cache, +receipts or processes. Frame Control's injector total: 12 of 12 cold starts +through the API, plus the UI run. + ## Left on the Frame - Gravitas (free, 7.4 GB, installed 2026-09-28 for this work) is still installed; nothing else from this work is left. - No `UEVRInjector.exe` or game processes were left running. Steam and SteamVR were running at the end. -- The test lock was released at 12:52. +- The test lock was released at 13:03. diff --git a/docs/mods.md b/docs/mods.md index d6e7f91..8fb7a9c 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -26,7 +26,7 @@ means an upstream source describes it; “inferred” means it still needs a tes | Game / build | Mod or content | Evidence and support status | Next check | |---|---|---|---| | Half-Life 2: VR Mod – Episode One, Steam 2177750, build 25413453 | Official Steam community mod, shared base depot 658920 build 25413418 | **Verified: startup only.** Already installed; launched through Proton ARM64. The stereo headset capture showed its first-time setup, and SteamVR loaded `bindings_frame.json`. Gameplay, controller interaction, fresh installation and removal are unverified. | Complete first-time setup and play a level before offering a tested install shortcut. | -| Gravitas, Steam 1067310, Windows, Unreal Engine 4 | UEVR 1.05, from Frame Control | **Verified 2026-09-29: installs, injects, SteamVR receives frames, removes cleanly.** Nine cold **Play in VR** runs (33–35 s each), then the full cycle again from the app's UI, all loaded `UEVRBackend.dll` into the game, with UEVR logging `Hooked DirectX 11` and `Requested runtime: openvr_api.dll`. SteamVR's compositor counted frame submits for `steam.app.1067310`. Remove restored the prefix to its pre-install file listing. **Not seen:** the stereo image, head tracking and controls (headset unworn). | Wear the headset: check the image, tracking, UEVR's in-headset menu and controller input. | +| Gravitas, Steam 1067310, Windows, Unreal Engine 4 | UEVR 1.05, from Frame Control | **Verified 2026-09-29: installs, injects, SteamVR receives frames, removes cleanly.** Twelve cold **Play in VR** runs (33–35 s each), and the full cycle from the app's UI, all loaded `UEVRBackend.dll` into the game, with UEVR logging `Hooked DirectX 11` and `Requested runtime: openvr_api.dll`. SteamVR's compositor counted frame submits for `steam.app.1067310`. Remove restored the prefix to its pre-install file listing. **Not seen:** the stereo image, head tracking and controls (headset unworn). | Wear the headset: check the image, tracking, UEVR's in-headset menu and controller input. | | Beat Saber, Steam 620980, Windows / Proton | Basic custom songs; later SongCore and version-matched mods | **Verified: absent from the 868-game library returned by this Frame.** Store metadata lists Windows, not Linux. **Documented:** the PC game reads basic maps from `Beat Saber_Data/CustomLevels` without a mod manager. Playback on Frame is unverified. | An already-owned, legitimately installed copy is required. Do not buy it as part of this task. | | Beat Saber, claimed native ARM64 build | Custom songs / native mods | **Inferred: unverified.** The research mentions this build but supplies no verified official distributable or tested layout. CPU architecture alone does not identify Android versus Linux, the game version or the mod ABI. | Establish official provenance, ownership, binary type and version before touching files. Do not apply Quest patches to an unidentified build. | | Beat Saber, Alex's Quest 2 copy | Custom songs / Android mods | **Documented: owner-reported copy on Quest 2.** Not reachable on 2026-09-29 (no device on `adb` from the Mac). No APK, version or installed mods inspected; no Frame playback verified. A Quest copy is a Meta store purchase; copying it to another headset would need its entitlement check to pass there, which this work won't work around. This does not establish ownership of the Steam build. | When the Quest is available, inspect the owned copy's version and supported transfer path, then test Lepton/OpenXR compatibility without bypassing entitlement checks. | @@ -95,7 +95,7 @@ Why not UEVR's own injector (verified 2026-09-29): cross-process window message; a window that isn't answering would block its UI thread (inferred from the frontend's source, not proven). Without a `HOME` it also died in .NET at startup. -- Frame Control's own script injected in 9 of 9 cold starts, in 33–35 s. +- Frame Control's own script injected in 12 of 12 cold starts through the API, in 33–35 s, and again from the UI. - UEVR's DirectX 12 probing logs errors before it settles on DirectX 11 for Gravitas, and some of its Unreal engine scans fail on this older UE4 game. Neither stopped the injection. diff --git a/tests/test_mods.py b/tests/test_mods.py index b0ad78f..3a656d9 100644 --- a/tests/test_mods.py +++ b/tests/test_mods.py @@ -159,12 +159,31 @@ class InstallUninstall(FakeLibrary): victim = self.steam / "steamapps/common/Gravitas" r["remove"].append(str(self.prefix / "../../../common/Gravitas")) frame_mods.receipt_path(APPID).write_text(json.dumps(r)) - with self.assertRaisesRegex(frame_mods.Fail, "outside"): + with self.assertRaisesRegex(frame_mods.Fail, "didn't create"): frame_mods.uninstall(APPID) self.assertTrue(victim.is_dir()) self.assertTrue((self.managed() / "uevr-1.05").is_dir(), "nothing removed when the receipt is bad") + def test_receipt_cannot_delete_other_things_in_the_prefix(self): + frame_mods.install(APPID) + r = frame_mods.read_receipt(APPID) + users = self.prefix / "drive_c/users" + r["remove"].append(str(users)) + frame_mods.receipt_path(APPID).write_text(json.dumps(r)) + with self.assertRaisesRegex(frame_mods.Fail, "didn't create"): + frame_mods.uninstall(APPID) + self.assertTrue(users.is_dir()) + + def test_failed_removal_keeps_the_receipt(self): + frame_mods.install(APPID) + with mock.patch.object(frame_mods.shutil, "rmtree"): # e.g. a permission error, swallowed + with self.assertRaisesRegex(frame_mods.Fail, "couldn't remove"): + frame_mods.uninstall(APPID) + self.assertIsNotNone(frame_mods.read_receipt(APPID), "Remove can be tried again") + frame_mods.uninstall(APPID) + self.assertFalse(self.managed().exists()) + def test_receipt_cannot_name_another_prefix(self): frame_mods.install(APPID) r = frame_mods.read_receipt(APPID) diff --git a/ui/frame_mods.py b/ui/frame_mods.py index 1aebbf7..482b2ea 100644 --- a/ui/frame_mods.py +++ b/ui/frame_mods.py @@ -69,18 +69,25 @@ import ctypes, json, os, sys from ctypes import wintypes as W exe, uevr, profile = sys.argv[1:4] k32 = ctypes.WinDLL("kernel32", use_last_error=True) -k32.OpenProcess.restype = W.HANDLE -k32.VirtualAllocEx.restype = ctypes.c_void_p -k32.VirtualAllocEx.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.c_size_t, W.DWORD, W.DWORD] -k32.WriteProcessMemory.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p] -k32.CreateRemoteThread.restype = W.HANDLE -k32.CreateRemoteThread.argtypes = [W.HANDLE, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_void_p, - W.DWORD, ctypes.c_void_p] -k32.GetModuleHandleW.restype = W.HMODULE -k32.GetProcAddress.restype = ctypes.c_void_p -k32.GetProcAddress.argtypes = [W.HMODULE, ctypes.c_char_p] -k32.LoadLibraryW.restype = W.HMODULE -k32.CreateToolhelp32Snapshot.restype = W.HANDLE +H, P, SZ = W.HANDLE, ctypes.c_void_p, ctypes.c_size_t +for name, res, args in ( + ("OpenProcess", H, [W.DWORD, W.BOOL, W.DWORD]), + ("CloseHandle", W.BOOL, [H]), + ("VirtualAllocEx", P, [H, P, SZ, W.DWORD, W.DWORD]), + ("VirtualFreeEx", W.BOOL, [H, P, SZ, W.DWORD]), + ("WriteProcessMemory", W.BOOL, [H, P, P, SZ, P]), + ("CreateRemoteThread", H, [H, P, SZ, P, P, W.DWORD, P]), + ("WaitForSingleObject", W.DWORD, [H, W.DWORD]), + ("GetModuleHandleW", W.HMODULE, [W.LPCWSTR]), + ("LoadLibraryW", W.HMODULE, [W.LPCWSTR]), + ("FreeLibrary", W.BOOL, [W.HMODULE]), + ("GetProcAddress", P, [W.HMODULE, ctypes.c_char_p]), + ("CreateToolhelp32Snapshot", H, [W.DWORD, W.DWORD]), + ("Process32FirstW", W.BOOL, [H, P]), ("Process32NextW", W.BOOL, [H, P]), + ("Module32FirstW", W.BOOL, [H, P]), ("Module32NextW", W.BOOL, [H, P])): + fn = getattr(k32, name) + fn.restype, fn.argtypes = res, args +INVALID = ctypes.c_void_p(-1).value class Entry(ctypes.Structure): # PROCESSENTRY32W _fields_ = [("size", W.DWORD), ("usage", W.DWORD), ("pid", W.DWORD), ("heap", ctypes.c_void_p), @@ -93,56 +100,68 @@ class Module(ctypes.Structure): # MODULEENTRY32W ("name", W.WCHAR * 256), ("path", W.WCHAR * 260)] def fail(msg): - print(json.dumps({"error": msg})); sys.exit(1) + print(json.dumps({"error": f"{msg} (Windows error {ctypes.get_last_error()})"})); sys.exit(1) -def find_pid(): - snap = k32.CreateToolhelp32Snapshot(2, 0) # TH32CS_SNAPPROCESS - e = Entry(); e.size = ctypes.sizeof(e) - ok = k32.Process32FirstW(snap, ctypes.byref(e)) - while ok: - if e.name.lower() == exe.lower(): - k32.CloseHandle(snap); return e.pid - ok = k32.Process32NextW(snap, ctypes.byref(e)) - k32.CloseHandle(snap) +def snapshot(flags, pid, entry, first, next_, match): + snap = k32.CreateToolhelp32Snapshot(flags, pid) + if not snap or snap == INVALID: + fail("couldn't list processes") + try: + entry.size = ctypes.sizeof(entry) + ok = first(snap, ctypes.byref(entry)) + while ok: + if match(entry): + return entry + ok = next_(snap, ctypes.byref(entry)) + finally: + k32.CloseHandle(snap) -def module_base(pid, path): - snap = k32.CreateToolhelp32Snapshot(0x18, pid) # TH32CS_SNAPMODULE | SNAPMODULE32 - m = Module(); m.size = ctypes.sizeof(m) - ok = k32.Module32FirstW(snap, ctypes.byref(m)) - while ok: - if m.path.lower() == path.lower(): - k32.CloseHandle(snap); return m.base - ok = k32.Module32NextW(snap, ctypes.byref(m)) - k32.CloseHandle(snap) - -def remote_call(proc, fn, arg=None, wait_ms=10000): +def remote_call(proc, fn, arg, wait_ms): t = k32.CreateRemoteThread(proc, None, 0, fn, arg, 0, None) if not t: - fail(f"CreateRemoteThread failed ({ctypes.get_last_error()})") - k32.WaitForSingleObject(t, wait_ms); k32.CloseHandle(t) + fail("CreateRemoteThread failed") + try: + return k32.WaitForSingleObject(t, wait_ms) == 0 # WAIT_OBJECT_0 + finally: + k32.CloseHandle(t) def inject(proc, pid, name): path = os.path.join(uevr, name) data = ctypes.create_unicode_buffer(path) mem = k32.VirtualAllocEx(proc, None, ctypes.sizeof(data), 0x3000, 0x04) # commit|reserve, read/write - if not mem or not k32.WriteProcessMemory(proc, mem, data, ctypes.sizeof(data), None): - fail(f"couldn't write into {exe} ({ctypes.get_last_error()})") - remote_call(proc, k32.GetProcAddress(k32.GetModuleHandleW("kernel32.dll"), b"LoadLibraryW"), mem) - base = module_base(pid, path) - if not base: + if not mem: + fail(f"couldn't allocate in {exe}") + try: + if not k32.WriteProcessMemory(proc, mem, data, ctypes.sizeof(data), None): + fail(f"couldn't write into {exe}") + load = k32.GetProcAddress(k32.GetModuleHandleW("kernel32.dll"), b"LoadLibraryW") + if not remote_call(proc, load, mem, 30000): + fail(f"loading {name} into {exe} didn't finish in 30 s") + finally: + k32.VirtualFreeEx(proc, mem, 0, 0x8000) # MEM_RELEASE + m = snapshot(0x18, pid, Module(), k32.Module32FirstW, k32.Module32NextW, # TH32CS_SNAPMODULE | SNAPMODULE32 + lambda m: m.path.lower() == path.lower()) + if not m: fail(f"{name} didn't load into {exe}") - return path, base + return path, m.base -pid = find_pid() -if not pid: +e = snapshot(2, 0, Entry(), k32.Process32FirstW, k32.Process32NextW, # TH32CS_SNAPPROCESS + lambda e: e.name.lower() == exe.lower()) +if not e: fail(f"{exe} isn't running") +pid = e.pid proc = k32.OpenProcess(0x1F0FFF, False, pid) # PROCESS_ALL_ACCESS if not proc: - fail(f"couldn't open {exe} ({ctypes.get_last_error()})") + fail(f"couldn't open {exe}") path, base = inject(proc, pid, "UEVRPluginNullifier.dll") local = k32.LoadLibraryW(path) -offset = k32.GetProcAddress(local, b"nullify") - local # same DLL, same layout in both processes -remote_call(proc, base + offset, wait_ms=2000) +fn = local and k32.GetProcAddress(local, b"nullify") +if not fn: + fail("couldn't find UEVRPluginNullifier.dll's nullify") +offset = fn - local # same DLL, same layout in both processes +k32.FreeLibrary(local) +# The frontend waits 2 s for nullify and carries on either way; so do we, but say so. +nullified = remote_call(proc, base + offset, None, 2000) inject(proc, pid, "openvr_api.dll") # The frontend saves the runtime choice in the per-game config before UEVRBackend reads it. os.makedirs(profile, exist_ok=True) @@ -151,7 +170,8 @@ lines = open(cfg).read().splitlines() if os.path.exists(cfg) else [] lines = [l for l in lines if not l.startswith("Frontend_RequestedRuntime=")] + ["Frontend_RequestedRuntime=openvr_api.dll"] open(cfg, "w").write("\n".join(lines) + "\n") inject(proc, pid, "UEVRBackend.dll") -print(json.dumps({"pid": pid})) +k32.CloseHandle(proc) +print(json.dumps({"pid": pid, "nullified": nullified})) """ @@ -420,7 +440,15 @@ def start(appid): cwd=str(Path(r["prefix"]) / "drive_c" / MANAGED)) except subprocess.TimeoutExpired: raise Fail("the injection step didn't finish in 2 minutes") from None - reply = next((json.loads(l) for l in reversed(out.stdout.splitlines()) if l.startswith("{")), None) + reply = None + for line in reversed(out.stdout.splitlines()): + try: + reply = json.loads(line) + break + except ValueError: + continue + if not isinstance(reply, dict): + reply = None if not reply or "error" in reply: raise Fail("UEVR injection failed: " + (reply or {}).get("error", (out.stderr.strip().splitlines() or ["no output"])[-1])) try: @@ -446,15 +474,23 @@ def uninstall(appid): prefix = os.path.realpath(r["prefix"]) if not prefix.endswith(f"/steamapps/compatdata/{appid}/pfx"): raise Fail(f"receipt names a prefix that isn't app {appid}'s: {r['prefix']}") + # Only ever our folder and UEVR's own settings folders for this game, even + # if the receipt says otherwise. + managed = os.path.join(prefix, "drive_c", MANAGED) + uevr_dirs = {os.path.realpath(str(d)) for d in user_dirs({"prefix": Path(prefix)}, Path(r["exe"])).values()} targets = list(r.get("remove", [])) + list(r.get("remove_if_created", {}).values()) - for t in targets: # a receipt only ever points inside this game's prefix + for t in targets: real = os.path.realpath(t) - if not real.startswith(prefix + os.sep): - raise Fail(f"receipt lists a path outside the game's prefix: {t}") + if not (real.startswith(managed + os.sep) or real in uevr_dirs): + raise Fail(f"receipt lists a path Frame Control didn't create: {t}") for t in targets: shutil.rmtree(t, ignore_errors=True) + left = [t for t in targets if os.path.lexists(t)] + if left: # keep the receipt, so Remove can be tried again + raise Fail("couldn't remove " + ", ".join(left)) + parents = {os.path.realpath(os.path.join(prefix, "drive_c/users/steamuser/AppData/Roaming/UnrealVRMod")), managed} for t in r.get("remove_if_empty", []): - if os.path.realpath(t).startswith(prefix + os.sep): + if os.path.realpath(t) in parents: try: os.rmdir(t) except OSError: diff --git a/ui/server.py b/ui/server.py index 711d390..057425e 100755 --- a/ui/server.py +++ b/ui/server.py @@ -435,7 +435,7 @@ def steam(body): return steam_frame(action, appid) -# Downloads are about 70 MB; starting waits for the game, the injector and SteamVR. +# Downloads are about 20 MB; starting waits for the game, the injection and SteamVR. MOD_TIMEOUT = {"status": 40, "install": 600, "start": 900, "uninstall": 60} From 8051687e1eccb919f1832c8cdb6f5b66cf5aa191 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:18:58 +1000 Subject: [PATCH 04/19] CI: stop recurring false failures on main and pull requests - checks: the runner's packages.microsoft.com apt source now 403s, failing `apt-get update` and with it "Install zsh"; tolerate the refresh error (Ubuntu's lists still update and the install still fails if it can't). - e2e: a failed quiet image build is rebuilt with the full log, but the script exited 2 even when that rebuild succeeded; only fail if it fails. - ArtworkTests: a timed-out lookup gives its resolver slot back from its own thread, which a busy macOS runner may schedule after the next test starts. Wait for every slot before each test, and always return slots a test took, so one late thread can't cascade into three failures. - release: tagged builds no longer re-upload the installers as workflow artifacts (they are attached to the release; the artifact finalize timed out on v0.3.0). Pull requests build installers only when the Electron app, the macOS helper it compiles, or the workflow changes. - checks and release: a newer push to a pull request cancels the older run. Co-Authored-By: Claude Opus 5.5 (1M context) --- .github/workflows/checks.yml | 13 ++++++++-- .github/workflows/release.yml | 14 +++++++++-- scripts/e2e.sh | 3 ++- tests/test_frame_android_library.py | 37 ++++++++++++++++++++++------- 4 files changed, 54 insertions(+), 13 deletions(-) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index f131fe4..b7624f0 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -5,6 +5,11 @@ on: branches: [main] pull_request: +# A newer push to the same pull request supersedes a run still in progress. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + jobs: checks: runs-on: ubuntu-latest @@ -17,7 +22,9 @@ jobs: with: node-version: "24" - name: Install zsh - run: sudo apt-get update -qq && sudo apt-get install -y -qq zsh + # The runner image's third-party apt sources (packages.microsoft.com) sometimes + # fail to refresh; Ubuntu's own lists still update, and the install fails if not. + run: (sudo apt-get update -qq || true) && sudo apt-get install -y -qq zsh - name: Script syntax run: | sh -n ui/local-bin/ssh @@ -84,6 +91,8 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install zsh - run: sudo apt-get update -qq && sudo apt-get install -y -qq zsh + # The runner image's third-party apt sources (packages.microsoft.com) sometimes + # fail to refresh; Ubuntu's own lists still update, and the install fails if not. + run: (sudo apt-get update -qq || true) && sudo apt-get install -y -qq zsh - name: End-to-end tests run: scripts/e2e.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 04cfeaf..dcb37fd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,14 +2,22 @@ name: release # Pushing a v* tag builds Frame Control for macOS, Windows and Linux and attaches # the installers to that tag's GitHub release (created as a draft if missing). -# Pull requests that touch the app build the same installers as artifacts. +# Pull requests that change how the installers are built (the Electron app, the +# macOS helper it compiles, or this workflow) build the same installers as +# artifacts. ui/, scripts/, frame/ and apk-catalog/ are copied in as they are and +# are tested by the checks workflow; run this one by hand to package them early. on: push: tags: ["v*"] pull_request: - paths: ["app/**", "ui/**", "scripts/**", "frame/**", "apk-catalog/**", ".github/workflows/release.yml"] + paths: ["app/**", "mac/frame-mac-view/**", ".github/workflows/release.yml"] workflow_dispatch: +# A newer push to the same pull request supersedes a build still in progress. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + permissions: contents: write @@ -49,7 +57,9 @@ jobs: tag="${GITHUB_REF_NAME}" gh release view "$tag" >/dev/null 2>&1 || gh release create "$tag" --draft --title "Frame Control ${tag#v}" --notes "" gh release upload "$tag" ${{ matrix.files }} --clobber + # Tagged builds are attached to the release above; only other builds need artifacts. - uses: actions/upload-artifact@v4 + if: ${{ !startsWith(github.ref, 'refs/tags/') }} with: name: frame-control-${{ matrix.os }} path: | diff --git a/scripts/e2e.sh b/scripts/e2e.sh index c8d4ef0..75ad349 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -23,7 +23,8 @@ started=$SECONDS print "==> Building fakeframe-frame (from $base) and fakeframe-host" # Quiet when it works; if a build fails, build again with the full log so CI shows why. -build() { docker build -q "$@" >/dev/null || { docker build --progress=plain "$@"; exit 2 } } +# That second build also rides out a flaky package mirror: only its failure is fatal. +build() { docker build -q "$@" >/dev/null || docker build --progress=plain "$@" || exit 2 } build --build-arg BASE="$base" -t fakeframe-frame -f tests/fakeframe/Containerfile tests/fakeframe build -t fakeframe-host -f tests/fakeframe/host.Containerfile tests/fakeframe diff --git a/tests/test_frame_android_library.py b/tests/test_frame_android_library.py index cdf51c0..537e46a 100644 --- a/tests/test_frame_android_library.py +++ b/tests/test_frame_android_library.py @@ -120,7 +120,27 @@ class LauncherTests(unittest.TestCase): FIXTURES = ROOT / 'tests/fixtures/library' +def wait_for_idle_resolvers(timeout=10): + # Name lookups that outlast their deadline give their slot back from their own thread, + # which a busy runner may not schedule before the next test; wait until all are back. + from apk_sources import _images + held = [] + try: + end = time.monotonic() + timeout + while _images._resolvers.acquire(timeout=max(0, end - time.monotonic())): + held.append(1) + if len(held) == 4: + return + raise AssertionError('artwork name lookups from an earlier test are still running') + finally: + for _ in held: + _images._resolvers.release() + + class ArtworkTests(unittest.TestCase): + def setUp(self): + wait_for_idle_resolvers() + def test_source_inputs_and_url(self): from apk_sources import _images data = (FIXTURES / 'icon.png').read_bytes() @@ -231,10 +251,7 @@ class ArtworkTests(unittest.TestCase): self.assertEqual(sum('Too many' in e for e in errors), 2) finally: gate.set() - deadline = time.monotonic() + 5 - while time.monotonic() < deadline and not _images._resolvers.acquire(blocking=False): - time.sleep(0.01) - _images._resolvers.release() # the stuck lookups finished and gave their slots back + wait_for_idle_resolvers() # the stuck lookups finished and gave their slots back def test_resolver_slot_released_when_thread_cannot_start(self): from apk_sources import _images @@ -242,10 +259,14 @@ class ArtworkTests(unittest.TestCase): for _ in range(6): with self.assertRaises(RuntimeError): _images.get('https://example.org/a.png', deadline=time.monotonic() + 1) - for _ in range(4): # every slot came back - self.assertTrue(_images._resolvers.acquire(blocking=False)) - for _ in range(4): - _images._resolvers.release() + held = 0 + try: + while held < 4 and _images._resolvers.acquire(blocking=False): + held += 1 + self.assertEqual(held, 4) # every slot came back + finally: + for _ in range(held): # even on failure, so later tests don't inherit the leak + _images._resolvers.release() def test_deadline_covers_name_resolution(self): import threading From d6fb5e917a48af00f048ec582ae3fb6843ea974e Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:18:59 +1000 Subject: [PATCH 05/19] UEVR helper tests: import and skip cleanly on Windows frame_mods runs on the Frame, but the server tests import it on every desktop OS; the module-level `import fcntl` failed test discovery on Windows. Import it where the lock is taken, as frame_panels and frame_vr do. Skip the Frame-side helper tests on Windows, as test_input does for the input agent: they rely on /proc, flock and POSIX prefix paths. The server routes and the usage-error check still run there. Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/test_mods.py | 5 ++++- ui/frame_mods.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test_mods.py b/tests/test_mods.py index 3a656d9..fc76fec 100644 --- a/tests/test_mods.py +++ b/tests/test_mods.py @@ -36,6 +36,7 @@ def zip_bytes(files, links=()): return buf.getvalue() +@unittest.skipIf(sys.platform == "win32", "the helper runs on the Frame (Linux): /proc, flock and POSIX prefix paths") class FakeLibrary(unittest.TestCase): """A Steam library with Gravitas's real layout, and pinned downloads served from memory.""" @@ -230,9 +231,10 @@ class Downloads(FakeLibrary): class Actions(FakeLibrary): def test_one_change_at_a_time(self): + import fcntl lock = Path(tempfile.mkdtemp()) / "mods.lock" with mock.patch.object(frame_mods, "LOCK", lock), open(lock, "w") as held: - frame_mods.fcntl.flock(held, frame_mods.fcntl.LOCK_EX) + fcntl.flock(held, fcntl.LOCK_EX) with self.assertRaisesRegex(frame_mods.Fail, "another mod action"): frame_mods.main(["install", str(APPID)]) self.assertFalse(frame_mods.status(APPID)["installed"]) @@ -294,6 +296,7 @@ class Start(FakeLibrary): class Helper(unittest.TestCase): + @unittest.skipIf(sys.platform == "win32", "uninstall takes the flock lock, which only exists on the Frame (Linux)") def test_unexpected_errors_are_still_json(self): # A receipt from another version, without "exe": a KeyError, not a traceback. script = (ROOT / "ui" / "frame_mods.py").read_text().replace( diff --git a/ui/frame_mods.py b/ui/frame_mods.py index 482b2ea..4f42f6f 100644 --- a/ui/frame_mods.py +++ b/ui/frame_mods.py @@ -22,7 +22,6 @@ from python.org, each checked against a pinned hash. Files live in /drive_c/frame-control, never in the game's own folder, and a receipt records what to remove. """ -import fcntl import hashlib import json import os @@ -511,6 +510,7 @@ def main(argv): action = {"status": status, "install": install, "start": start, "uninstall": uninstall}[argv[0]] if action is status: return status(int(argv[1])) + import fcntl # only on the Frame; the server and its tests also import this module on Windows # One change at a time, or an uninstall could delete what an install is moving in. LOCK.parent.mkdir(parents=True, exist_ok=True) with open(LOCK, "w") as lock: From 3f20e5f9d343223bba994876d0461821e590c159 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Wed, 30 Sep 2026 12:29:56 +1000 Subject: [PATCH 06/19] Windows test VM: a driver script and how to set one up scripts/windows-vm.sh drives a dockur/windows Windows 11 VM from the Mac over ssh -J: start/stop, PowerShell, copy files in, screenshots via QEMU's screendump, clicks and scrolls replayed by a scheduled task in the signed-in session, QEMU key names, and a tagged, removable headset key for tests against a real Frame. docs/testing.md explains setting it up (Windows from Microsoft, loopback-only ports) and the pitfalls found reproducing the Windows "RDP not working" report. docs/streaming.md records what Remote Desktop from Windows does against the Frame's xrdp (verified 2026-09-30). Co-Authored-By: Claude Opus 5.5 (1M context) --- README.md | 2 +- docs/streaming.md | 9 +++ docs/testing.md | 72 ++++++++++++++++++++++++ scripts/windows-vm.sh | 128 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 210 insertions(+), 1 deletion(-) create mode 100755 scripts/windows-vm.sh diff --git a/README.md b/README.md index fb40d32..d42fb43 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ Frame's software fits together, all checked against a real headset and labelled | [Frame Control for iPhone](docs/iphone.md) | The iPhone and iPad app, how it runs the server on the Frame, pairing | | [Recovery and OS images](docs/recovery-and-images.md) | Where to download the Frame's OS, what's inside, testing without the headset | | [AI agents and assistant](docs/agents.md) | Key-free MCP tools, human approvals, and an opt-in assistant panel | -| [Testing](docs/testing.md) | Unit tests, end-to-end tests against a fake Frame in Docker, and the headset smoke test | +| [Testing](docs/testing.md) | Unit tests, end-to-end tests against a fake Frame in Docker, the headset smoke test and a Windows test VM | | [Open questions](docs/open-questions.md) | What's still unchecked |
diff --git a/docs/streaming.md b/docs/streaming.md index 773e698..b810934 100644 --- a/docs/streaming.md +++ b/docs/streaming.md @@ -21,6 +21,15 @@ The confidence labels are the same as in [ssh.md](ssh.md). | **ADB + scrcpy (Lepton only)** | A mirror of the Android container | **Guess** | `brew install scrcpy android-platform-tools`, then `adb connect frame.local:5555` while Lepton Development is running ([adb_lepton](https://partner.steamgames.com/doc/steamhardware/steamframe/adb_lepton)), then `scrcpy`. This only shows Android apps, not SteamOS. | | VNC server on the Frame (krfb / wayvnc) | A mirror of the Plasma desktop | **Inferred (SteamOS)** | Deck users run krfb in Desktop Mode ([one.vg](https://one.vg/blog/remote-control-your-steam-deck)). On the Frame, the in-headset desktop is a virtual screen, and krfb isn't known to be preinstalled. RDP and Steam Link cover this case, so it's not recommended. | +**RDP from Windows, verified 2026-09-30:** Windows 11 25H2's Remote Desktop +(`mstsc`) against BUILD_ID 20260925.6191901. xrdp picks TLS, not NLA, so +Remote Desktop never asks for a user or password. It warns that the certificate +(`www.xrdp.org`) can't be verified. After **Yes**, xrdp shows its own "Login to +frame" box with the username blank. Any user but `steamos` gets "User does not +exist, or could not be authenticated". Signing in as `steamos` with the +Developer Mode password is still unchecked: the Frame's log showed no +successful xrdp login up to that date. + **Recommendation for A:** start with Steam Link for macOS, because Valve documents it. Use Windows App (RDP) when you want a proper Linux desktop on the Mac with keyboard, mouse, and clipboard. diff --git a/docs/testing.md b/docs/testing.md index 82a1826..61c4168 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -8,6 +8,7 @@ A fourth, a SteamOS VM, may come later ([issue #6](https://github.com/saphid/ste | Unit tests (`tests/*.py`) | `python3 -m unittest discover -s tests` | Nothing | Parsing, validation, request guards; SSH and HTTP are mocked | | Fake Frame (`tests/e2e`) | `scripts/e2e.sh` | Linux with Docker | The real server and scripts against a container that behaves like a Frame | | Headset smoke test | `scripts/frame-smoke.sh` | A Frame on the `frame` alias | Install, launch and remove on the real device, recorded with its BUILD_ID | +| [Windows test VM](#windows-test-vm) | `scripts/windows-vm.sh` | A Linux machine with KVM and Docker | The Windows build on a real Windows desktop, against a real Frame when needed | ## Unit tests @@ -163,6 +164,77 @@ refuses ids with a hyphen (`missing/invalid arguments`), which the fake had accepted. The fake now refuses them the same way, and Frame Control makes ids Steam accepts. +## Windows test VM + +The unit tests run on Windows in CI, but the app itself doesn't. Anything that +depends on the Windows desktop (Remote Desktop, the installer, the bundled +Python, file dialogs) needs a real Windows machine. This is a Windows 11 VM in a +[dockur/windows](https://github.com/dockur/windows) container on a Linux machine +with KVM, driven from the Mac with `scripts/windows-vm.sh`. + +Setting it up, once, on the Linux machine: + +- **Windows comes from Microsoft.** The container downloads the Windows 11 + image from Microsoft on first start. Windows runs unactivated, which is fine + for testing. Don't use activation workarounds or third-party Windows images. +- **Publish its ports on loopback only.** Map `127.0.0.1:2222:22` (SSH), + `127.0.0.1:8006:8006` (the web console) and, if you need it, + `127.0.0.1:13389:3389`. The Mac reaches them through `ssh -J`. Use + `restart: "no"` and `stop_grace_period: 2m` so it only runs when someone is + testing, and a `docker stop` shuts Windows down cleanly. +- **Give it SSH on first sign-in.** The container runs `/oem/install.bat` + once. Have it add the OpenSSH Server capability, start `sshd`, set PowerShell + as its default shell, and put a dedicated public key (for example + `~/.ssh/id_ed25519_winvm` on the Mac) in + `C:\ProgramData\ssh\administrators_authorized_keys`. +- Give it 4 cores, 8 GB of memory and a 32 GB disk. That's enough for the app + and the tests. + +Using it, with `WINVM_HOST` set to the Linux machine's ssh alias: + +```sh +scripts/windows-vm.sh up # start it and wait for SSH (1-2 minutes) +scripts/windows-vm.sh put Frame-Control-Setup-x64.exe +scripts/windows-vm.sh ps 'Start-Process "$env:USERPROFILE\Downloads\Frame-Control-Setup-x64.exe" /S -Wait' +scripts/windows-vm.sh shot screen.png # what's on its screen +scripts/windows-vm.sh click 723 359 # screen pixels, as in the screenshot +scripts/windows-vm.sh keys s t e a m o s ret # QEMU key names +scripts/windows-vm.sh down # shut Windows down +``` + +- **Clicks go through a scheduled task.** Commands over SSH run in a + session with no desktop, so `click` and `scroll` write the position to a + file, and a scheduled task running as the signed-in user replays it. The + VM's screen must be signed in; it is after `up`. QEMU's own `mouse_move` is + relative and drifts, so the script doesn't use it. +- **Screenshots may not show the pointer.** Check the result of a click (a + menu that opens, a button that changes) rather than the pointer's position. +- **Windows' `ssh` waits for stdin.** The script closes it for every command. + Do the same if you run `ssh` in the VM by hand. +- **Starting the app.** Run Frame Control in the signed-in session, not over + SSH. Use its Start-menu shortcut via `click`, or a scheduled task like the + one `click` uses. + +**Testing against a real Frame.** The VM reaches the headset on the LAN like +any other computer. Set up Frame Control in the VM once, then: + +```sh +scripts/windows-vm.sh frame-key add # let the VM's key into the headset +# ... test ... +scripts/windows-vm.sh frame-key remove # and take it out again +``` + +`frame-key` tags the key `windows-vm-test` in the headset's +`authorized_keys`, and `remove` deletes only that line. Follow the shared-device +procedure in [Headset smoke test](#headset-smoke-test) before installing or +launching anything on the headset. + +**Verified 2026-09-30:** Windows 11 Pro 25H2 (build 26200) against a Frame on +BUILD_ID 20260925.6191901. The script was used to install Frame Control 0.4.0, +connect it to the Frame and reproduce a Remote Desktop report from +screenshots. It also took Windows-side logs, and `frame-key` left +`authorized_keys` byte-for-byte as it was. + ## Owned media player `tests/test_media.py` covers layout evidence and overrides, OU eye ordering, diff --git a/scripts/windows-vm.sh b/scripts/windows-vm.sh new file mode 100755 index 0000000..441504d --- /dev/null +++ b/scripts/windows-vm.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env zsh +# Mac or Linux: drive a Windows 11 test VM for Frame Control's Windows build. +# The VM is a dockur/windows container on another machine; this reaches it over +# SSH through that machine. See docs/testing.md#windows-test-vm. +# +# Usage: scripts/windows-vm.sh [args] +# up | down | status start it (waits for SSH), shut Windows down cleanly, show state +# ps '' run PowerShell as the VM's user +# put [] copy a file in (default: the user's Downloads) +# shot save the VM's screen +# click click screen pixel x,y in the signed-in session +# scroll turn the wheel n notches at x,y (negative scrolls down) +# keys ... type QEMU key names: a, shift-a, ret, tab, esc, spc ... +# frame-key add|remove let the VM's Frame Control key into the headset (`frame` +# alias) for a test run, then take it out again +# +# Set WINVM_HOST to the ssh alias of the machine running the container. Optional: +# WINVM_CONTAINER (frame-winvm), WINVM_USER (frame), WINVM_PORT (2222: the VM's +# sshd, published on that machine's loopback), WINVM_KEY (~/.ssh/id_ed25519_winvm). +set -euo pipefail +setopt extendedglob + +host=${WINVM_HOST:?set WINVM_HOST to the ssh alias of the machine running the VM} +ctr=${WINVM_CONTAINER:-frame-winvm} +user=${WINVM_USER:-frame} +port=${WINVM_PORT:-2222} +key=${WINVM_KEY:-$HOME/.ssh/id_ed25519_winvm} +opts=(-o ConnectTimeout=20 -o StrictHostKeyChecking=accept-new + -o UserKnownHostsFile=${TMPDIR:-/tmp}/windows-vm-known_hosts -i $key -J $host) +TAG=windows-vm-test # comment on the VM's key in the headset's authorized_keys + +die() { print -u2 "windows-vm: $*"; exit 1 } +int() { [[ $1 == (-|)<-> ]] || die "not a whole number: $1" } + +# Windows' OpenSSH waits for stdin to close, so it always gets /dev/null. The +# script travels UTF-16 base64-encoded, so no quoting survives two shells. +vm_ps() { + local b64=$(print -rn -- "\$ProgressPreference = 'SilentlyContinue'"$'\n'"$1" | + iconv -f UTF-8 -t UTF-16LE | base64 | tr -d '\n') + ssh $opts -p $port $user@127.0.0.1 "powershell -NoProfile -NonInteractive -EncodedCommand $b64" /dev/null } + +# Input has to come from the signed-in desktop session, not SSH's session 0, so +# a scheduled task running as the user replays one click or wheel turn written +# to input.txt, then deletes the file to say it's done. +INPUT_PS1='$a = (Get-Content "$PSScriptRoot\input.txt").Trim() -split "\s+" +Add-Type -Namespace WinVm -Name Input -MemberDefinition @" +[DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); +[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); +[DllImport("user32.dll")] public static extern void mouse_event(uint flags, int dx, int dy, int data, System.IntPtr extra); +"@ +[WinVm.Input]::SetProcessDPIAware() | Out-Null +[WinVm.Input]::SetCursorPos([int]$a[0], [int]$a[1]) | Out-Null +Start-Sleep -Milliseconds 150 +if ($a[2] -eq "click") { + [WinVm.Input]::mouse_event(0x2, 0, 0, 0, [IntPtr]::Zero); Start-Sleep -Milliseconds 60 + [WinVm.Input]::mouse_event(0x4, 0, 0, 0, [IntPtr]::Zero) +} else { [WinVm.Input]::mouse_event(0x800, 0, 0, 120 * [int]$a[3], [IntPtr]::Zero) } +Remove-Item "$PSScriptRoot\input.txt"' + +pointer() { # x y click|wheel [notches] + local b64=$(print -rn -- $INPUT_PS1 | base64 | tr -d '\n') + vm_ps '$d = Join-Path $env:LOCALAPPDATA "windows-vm" +New-Item -ItemType Directory -Force $d | Out-Null +[IO.File]::WriteAllText("$d\input.ps1", [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'$b64'"))) +$act = New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$d\input.ps1`"" +$who = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive +Register-ScheduledTask -TaskName WindowsVmInput -Action $act -Principal $who -Force | Out-Null +Set-Content "$d\input.txt" "'"$*"'" +Start-ScheduledTask -TaskName WindowsVmInput +foreach ($i in 1..50) { if (-not (Test-Path "$d\input.txt")) { exit 0 }; Start-Sleep -Milliseconds 200 } +Remove-Item "$d\input.txt" -ErrorAction SilentlyContinue +Write-Error "no input after 10 s: is $env:USERNAME signed in on the VM screen?"; exit 1' +} + +(( $# )) || die "usage: see the top of $0" +cmd=$1; shift +case $cmd in + up) + ssh $host "docker start $ctr" >/dev/null + for i in {1..60}; do + vm_ps 'exit 0' 2>/dev/null && { print "up"; exit 0 } + sleep 5 + done + die "Windows didn't answer on SSH within 5 minutes" ;; + down) # the container turns SIGTERM into an ACPI shutdown and waits for Windows + ssh $host "docker stop -t 150 $ctr" >/dev/null && print "down" ;; + status) ssh $host "docker ps -a --filter 'name=^$ctr\$' --format '{{.Names}}: {{.Status}}'" ;; + ps) (( $# == 1 )) || die "usage: ps ''"; vm_ps "$1" ;; + put) + [[ -f ${1:-} ]] || die "usage: put []" + scp -q $opts -P $port $1 "$user@127.0.0.1:${2:-C:/Users/$user/Downloads}/${1:t}" " + print "screendump /tmp/windows-vm-shot.ppm" | monitor + sleep 1 + ssh $host "docker exec $ctr sh -c 'cat /tmp/windows-vm-shot.ppm && rm /tmp/windows-vm-shot.ppm'" | python3 -c ' +import re, struct, sys, zlib +d = sys.stdin.buffer.read() +m = re.match(rb"P6\s+(\d+)\s+(\d+)\s+255\s", d) or sys.exit("windows-vm: no screen dump") +w, h = int(m[1]), int(m[2]); px = d[m.end():] +raw = b"".join(b"\0" + px[y * w * 3:(y + 1) * w * 3] for y in range(h)) +chunk = lambda t, b: struct.pack(">I", len(b)) + t + b + struct.pack(">I", zlib.crc32(t + b)) +open(sys.argv[1], "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")) +' $1 + print $1 ;; + click) (( $# == 2 )) || die "usage: click "; int $1; int $2; pointer $1 $2 click ;; + scroll) (( $# == 3 )) || die "usage: scroll "; int $1; int $2; int $3; pointer $1 $2 wheel $3 ;; + keys) + (( $# )) || die "usage: keys ..." + for k; do [[ $k == [a-z0-9_.,/=-]## ]] || die "not a QEMU key name: $k"; done + for k; do print "sendkey $k"; done | monitor ;; + frame-key) + pub=$(vm_ps 'Get-Content (Join-Path $env:USERPROFILE ".ssh\id_ed25519_frame.pub")' | tr -d '\r') + pub=${${(z)pub}[1,2]} + [[ $pub == ssh-ed25519\ * ]] || die "the VM has no Frame Control key yet: run Set Up Connection in the app first" + case ${1:-} in + add) ssh frame "grep -qxF '$pub $TAG' ~/.ssh/authorized_keys || echo '$pub $TAG' >> ~/.ssh/authorized_keys" \$f.tmp; chmod 600 \$f.tmp; mv \$f.tmp \$f" Date: Wed, 30 Sep 2026 20:24:48 +1000 Subject: [PATCH 07/19] Docs: signing in over RDP as steamos reaches a Plasma desktop (verified) Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/streaming.md | 9 +++++++-- docs/testing.md | 6 +++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/streaming.md b/docs/streaming.md index b810934..48290f4 100644 --- a/docs/streaming.md +++ b/docs/streaming.md @@ -27,8 +27,13 @@ Remote Desktop never asks for a user or password. It warns that the certificate (`www.xrdp.org`) can't be verified. After **Yes**, xrdp shows its own "Login to frame" box with the username blank. Any user but `steamos` gets "User does not exist, or could not be authenticated". Signing in as `steamos` with the -Developer Mode password is still unchecked: the Frame's log showed no -successful xrdp login up to that date. +Developer Mode password opens a Plasma (X11) desktop within about 6 seconds. +It's a new session on display `:10`, separate from what the headset shows, +and it uses about 1.3 GB of the Frame's memory. Closing Remote Desktop leaves +it running, and the next sign-in reconnects to it. To end it, find its +session with `loginctl list-sessions` over SSH (its leader is `xrdp-sesexec`) +and run `loginctl terminate-session `; the headset's own session keeps +running. **Recommendation for A:** start with Steam Link for macOS, because Valve documents it. Use Windows App (RDP) when you want a proper Linux desktop on the diff --git a/docs/testing.md b/docs/testing.md index 61c4168..5b120a7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -231,9 +231,9 @@ launching anything on the headset. **Verified 2026-09-30:** Windows 11 Pro 25H2 (build 26200) against a Frame on BUILD_ID 20260925.6191901. The script was used to install Frame Control 0.4.0, -connect it to the Frame and reproduce a Remote Desktop report from -screenshots. It also took Windows-side logs, and `frame-key` left -`authorized_keys` byte-for-byte as it was. +connect it to the Frame and follow Remote Desktop through to the Frame's +desktop ([what it does](streaming.md#a-see-and-control-the-frame-from-the-mac)). +`frame-key` left `authorized_keys` byte-for-byte as it was. ## Owned media player From 895cc0ebbd3b0186912ea52e90bd59906d477d02 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:32:35 +1000 Subject: [PATCH 08/19] windows-vm.sh: review fixes for the headset key and input helper - frame-key remove deletes only the exact line add wrote, through a private temporary file, and leaves authorized_keys alone if it can't read or rewrite it. add checks the VM's key is a plain ed25519 key, keeps a last line without a newline intact, and doesn't duplicate a key the headset already trusts. - The input helper stops on any error before acknowledging, refuses a second click while one is in flight, and coordinates are bounded. - Host, container and user names are checked before they reach a remote shell; PowerShell errors come back as plain text. - docs/testing.md says what frame-key does and doesn't undo. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/testing.md | 16 ++++++++++----- scripts/windows-vm.sh | 47 ++++++++++++++++++++++++++++++------------- 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index 5b120a7..8595f9e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -205,8 +205,9 @@ scripts/windows-vm.sh down # shut Windows down - **Clicks go through a scheduled task.** Commands over SSH run in a session with no desktop, so `click` and `scroll` write the position to a file, and a scheduled task running as the signed-in user replays it. The - VM's screen must be signed in; it is after `up`. QEMU's own `mouse_move` is - relative and drifts, so the script doesn't use it. + VM's screen must be signed in; it is after `up`. One click or scroll at a + time: they share that task. QEMU's own `mouse_move` is relative and drifts, + so the script doesn't use it. - **Screenshots may not show the pointer.** Check the result of a click (a menu that opens, a button that changes) rather than the pointer's position. - **Windows' `ssh` waits for stdin.** The script closes it for every command. @@ -216,7 +217,10 @@ scripts/windows-vm.sh down # shut Windows down one `click` uses. **Testing against a real Frame.** The VM reaches the headset on the LAN like -any other computer. Set up Frame Control in the VM once, then: +any other computer. Run **Set Up Connection** in the VM's Frame Control once; +that makes the VM's key. So the VM doesn't keep access between test runs, +take that key's line out of the headset's `~/.ssh/authorized_keys` afterwards. +Then, around each run: ```sh scripts/windows-vm.sh frame-key add # let the VM's key into the headset @@ -224,8 +228,10 @@ scripts/windows-vm.sh frame-key add # let the VM's key into the headset scripts/windows-vm.sh frame-key remove # and take it out again ``` -`frame-key` tags the key `windows-vm-test` in the headset's -`authorized_keys`, and `remove` deletes only that line. Follow the shared-device +`add` appends the VM's key tagged `windows-vm-test`, unless the headset +already trusts that key through another line. `remove` deletes only the exact +line `add` wrote, so it doesn't undo what Set Up Connection did, and it leaves +the file alone if it can't rewrite it. Follow the shared-device procedure in [Headset smoke test](#headset-smoke-test) before installing or launching anything on the headset. diff --git a/scripts/windows-vm.sh b/scripts/windows-vm.sh index 441504d..d64aa47 100755 --- a/scripts/windows-vm.sh +++ b/scripts/windows-vm.sh @@ -30,14 +30,17 @@ opts=(-o ConnectTimeout=20 -o StrictHostKeyChecking=accept-new TAG=windows-vm-test # comment on the VM's key in the headset's authorized_keys die() { print -u2 "windows-vm: $*"; exit 1 } -int() { [[ $1 == (-|)<-> ]] || die "not a whole number: $1" } +int() { [[ $1 == (-|)<-99999> ]] || die "not a whole number (up to 99999): $1" } +# These go into commands run by a shell on the other machine, so keep them plain. +for v in $host $ctr $user; do [[ $v == [A-Za-z0-9_.]##[A-Za-z0-9_.-]# ]] || die "not a plain name: $v"; done +[[ $port == <1-65535> ]] || die "WINVM_PORT isn't a port: $port" # Windows' OpenSSH waits for stdin to close, so it always gets /dev/null. The # script travels UTF-16 base64-encoded, so no quoting survives two shells. vm_ps() { local b64=$(print -rn -- "\$ProgressPreference = 'SilentlyContinue'"$'\n'"$1" | iconv -f UTF-8 -t UTF-16LE | base64 | tr -d '\n') - ssh $opts -p $port $user@127.0.0.1 "powershell -NoProfile -NonInteractive -EncodedCommand $b64" /d # Input has to come from the signed-in desktop session, not SSH's session 0, so # a scheduled task running as the user replays one click or wheel turn written -# to input.txt, then deletes the file to say it's done. -INPUT_PS1='$a = (Get-Content "$PSScriptRoot\input.txt").Trim() -split "\s+" +# to input.txt, then deletes the file to say it's done. Any error stops it +# before that, so the caller times out instead of reporting a click. +INPUT_PS1='$ErrorActionPreference = "Stop" +$a = (Get-Content "$PSScriptRoot\input.txt").Trim() -split "\s+" Add-Type -Namespace WinVm -Name Input -MemberDefinition @" [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y); [DllImport("user32.dll")] public static extern void mouse_event(uint flags, int dx, int dy, int data, System.IntPtr extra); "@ [WinVm.Input]::SetProcessDPIAware() | Out-Null -[WinVm.Input]::SetCursorPos([int]$a[0], [int]$a[1]) | Out-Null +if (-not [WinVm.Input]::SetCursorPos([int]$a[0], [int]$a[1])) { throw "SetCursorPos failed" } Start-Sleep -Milliseconds 150 if ($a[2] -eq "click") { [WinVm.Input]::mouse_event(0x2, 0, 0, 0, [IntPtr]::Zero); Start-Sleep -Milliseconds 60 @@ -65,6 +70,8 @@ pointer() { # x y click|wheel [notches] local b64=$(print -rn -- $INPUT_PS1 | base64 | tr -d '\n') vm_ps '$d = Join-Path $env:LOCALAPPDATA "windows-vm" New-Item -ItemType Directory -Force $d | Out-Null +$busy = Get-Item "$d\input.txt" -ErrorAction SilentlyContinue +if ($busy -and $busy.LastWriteTime -gt (Get-Date).AddSeconds(-15)) { [Console]::Error.WriteLine("windows-vm: another click or scroll is in progress"); exit 1 } [IO.File]::WriteAllText("$d\input.ps1", [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'$b64'"))) $act = New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$d\input.ps1`"" $who = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive @@ -73,7 +80,7 @@ Set-Content "$d\input.txt" "'"$*"'" Start-ScheduledTask -TaskName WindowsVmInput foreach ($i in 1..50) { if (-not (Test-Path "$d\input.txt")) { exit 0 }; Start-Sleep -Milliseconds 200 } Remove-Item "$d\input.txt" -ErrorAction SilentlyContinue -Write-Error "no input after 10 s: is $env:USERNAME signed in on the VM screen?"; exit 1' +[Console]::Error.WriteLine("windows-vm: no input after 10 s: is $env:USERNAME signed in on the VM screen, and is x,y on it?"); exit 1' } (( $# )) || die "usage: see the top of $0" @@ -115,14 +122,26 @@ open(sys.argv[1], "wb").write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack( for k; do [[ $k == [a-z0-9_.,/=-]## ]] || die "not a QEMU key name: $k"; done for k; do print "sendkey $k"; done | monitor ;; frame-key) - pub=$(vm_ps 'Get-Content (Join-Path $env:USERPROFILE ".ssh\id_ed25519_frame.pub")' | tr -d '\r') - pub=${${(z)pub}[1,2]} - [[ $pub == ssh-ed25519\ * ]] || die "the VM has no Frame Control key yet: run Set Up Connection in the app first" - case ${1:-} in - add) ssh frame "grep -qxF '$pub $TAG' ~/.ssh/authorized_keys || echo '$pub $TAG' >> ~/.ssh/authorized_keys" \$f.tmp; chmod 600 \$f.tmp; mv \$f.tmp \$f" > "$f" # a last line without a newline would swallow ours + echo "$3" >> "$f" +else + t=$(mktemp "$f.XXXXXX") || exit 1 + grep -vxF "$3" "$f" > "$t" # 0: lines left, 1: none left, more: couldn't read or write + if [ $? -gt 1 ] || ! chmod 600 "$t" || ! mv "$t" "$f"; then + rm -f "$t"; echo "couldn't rewrite $f; it's unchanged" >&2; exit 1 + fi +fi +EOF print "frame-key $1: done" ;; *) die "unknown command: $cmd (see the top of $0)" ;; esac From bd24436fbc265054d00fcd69c8ee8337cc7c8316 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:39:07 +1000 Subject: [PATCH 09/19] windows-vm.sh: an atomic click lock, and setup errors fail the click input.txt is now created with CreateNew, so only one request can hold it; a lock older than 15 s is treated as left by a dead run. The outer PowerShell stops on any error, says why in one line, releases the lock and exits 1. docs/testing.md names both keys Set Up Connection can add to the headset. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/testing.md | 9 ++++++--- scripts/windows-vm.sh | 18 ++++++++++++------ 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index 8595f9e..3b6db77 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -218,9 +218,12 @@ scripts/windows-vm.sh down # shut Windows down **Testing against a real Frame.** The VM reaches the headset on the LAN like any other computer. Run **Set Up Connection** in the VM's Frame Control once; -that makes the VM's key. So the VM doesn't keep access between test runs, -take that key's line out of the headset's `~/.ssh/authorized_keys` afterwards. -Then, around each run: +that makes the VM's keys. So the VM doesn't keep access between test runs, +afterwards take the lines it added out of the headset's +`~/.ssh/authorized_keys`: the ones matching the VM's +`~/.ssh/id_ed25519_frame.pub` and, if pairing made one, +`~/.ssh/id_rsa_frame_devkit.pub`. Check that `ssh -o BatchMode=yes frame true` +in the VM now fails. Then, around each run: ```sh scripts/windows-vm.sh frame-key add # let the VM's key into the headset diff --git a/scripts/windows-vm.sh b/scripts/windows-vm.sh index d64aa47..2065d6b 100755 --- a/scripts/windows-vm.sh +++ b/scripts/windows-vm.sh @@ -68,18 +68,24 @@ Remove-Item "$PSScriptRoot\input.txt"' pointer() { # x y click|wheel [notches] local b64=$(print -rn -- $INPUT_PS1 | base64 | tr -d '\n') - vm_ps '$d = Join-Path $env:LOCALAPPDATA "windows-vm" + vm_ps '$ErrorActionPreference = "Stop" +$d = Join-Path $env:LOCALAPPDATA "windows-vm"; $req = "$d\input.txt"; $held = $false +trap { [Console]::Error.WriteLine("windows-vm: $_"); if ($held) { Remove-Item $req -ErrorAction SilentlyContinue }; exit 1 } New-Item -ItemType Directory -Force $d | Out-Null -$busy = Get-Item "$d\input.txt" -ErrorAction SilentlyContinue -if ($busy -and $busy.LastWriteTime -gt (Get-Date).AddSeconds(-15)) { [Console]::Error.WriteLine("windows-vm: another click or scroll is in progress"); exit 1 } +$old = Get-Item $req -ErrorAction SilentlyContinue # left behind by a run that died +if ($old -and $old.LastWriteTime -lt (Get-Date).AddSeconds(-15)) { Remove-Item $req } +# Creating input.txt is the lock: CreateNew fails if another request already has it. +try { $f = [IO.File]::Open($req, "CreateNew", "Write") } +catch { [Console]::Error.WriteLine("windows-vm: another click or scroll is in progress"); exit 1 } +$held = $true +$text = [Text.Encoding]::ASCII.GetBytes("'"$*"'"); $f.Write($text, 0, $text.Length); $f.Close() [IO.File]::WriteAllText("$d\input.ps1", [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'$b64'"))) $act = New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$d\input.ps1`"" $who = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive Register-ScheduledTask -TaskName WindowsVmInput -Action $act -Principal $who -Force | Out-Null -Set-Content "$d\input.txt" "'"$*"'" Start-ScheduledTask -TaskName WindowsVmInput -foreach ($i in 1..50) { if (-not (Test-Path "$d\input.txt")) { exit 0 }; Start-Sleep -Milliseconds 200 } -Remove-Item "$d\input.txt" -ErrorAction SilentlyContinue +foreach ($i in 1..50) { if (-not (Test-Path $req)) { exit 0 }; Start-Sleep -Milliseconds 200 } +Remove-Item $req -ErrorAction SilentlyContinue [Console]::Error.WriteLine("windows-vm: no input after 10 s: is $env:USERNAME signed in on the VM screen, and is x,y on it?"); exit 1' } From 924e37aa30d048f9de6640b4c5f3ba553b0ee94d Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:44:35 +1000 Subject: [PATCH 10/19] windows-vm.sh: serialise clicks with a named mutex instead of a lock file Windows releases the mutex when the request's process ends, so there's no stale lock to recover and no window where two requests can take each other's. Requests sent together now run one after another. Co-Authored-By: Claude Opus 5.5 (1M context) --- docs/testing.md | 6 +++--- scripts/windows-vm.sh | 17 ++++++++--------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index 3b6db77..ee32c2d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -205,9 +205,9 @@ scripts/windows-vm.sh down # shut Windows down - **Clicks go through a scheduled task.** Commands over SSH run in a session with no desktop, so `click` and `scroll` write the position to a file, and a scheduled task running as the signed-in user replays it. The - VM's screen must be signed in; it is after `up`. One click or scroll at a - time: they share that task. QEMU's own `mouse_move` is relative and drifts, - so the script doesn't use it. + VM's screen must be signed in; it is after `up`. Clicks and scrolls sent at + the same time run one after another. QEMU's own `mouse_move` is relative + and drifts, so the script doesn't use it. - **Screenshots may not show the pointer.** Check the result of a click (a menu that opens, a button that changes) rather than the pointer's position. - **Windows' `ssh` waits for stdin.** The script closes it for every command. diff --git a/scripts/windows-vm.sh b/scripts/windows-vm.sh index 2065d6b..be4f077 100755 --- a/scripts/windows-vm.sh +++ b/scripts/windows-vm.sh @@ -69,16 +69,15 @@ Remove-Item "$PSScriptRoot\input.txt"' pointer() { # x y click|wheel [notches] local b64=$(print -rn -- $INPUT_PS1 | base64 | tr -d '\n') vm_ps '$ErrorActionPreference = "Stop" -$d = Join-Path $env:LOCALAPPDATA "windows-vm"; $req = "$d\input.txt"; $held = $false -trap { [Console]::Error.WriteLine("windows-vm: $_"); if ($held) { Remove-Item $req -ErrorAction SilentlyContinue }; exit 1 } +$d = Join-Path $env:LOCALAPPDATA "windows-vm"; $req = "$d\input.txt"; $mine = $false +trap { [Console]::Error.WriteLine("windows-vm: $_"); if ($mine) { Remove-Item $req -ErrorAction SilentlyContinue }; exit 1 } +# One request at a time: the helper, the task and input.txt are shared. Windows +# frees the mutex when this process ends, however it ends. +$lock = New-Object Threading.Mutex($false, "windows-vm-input") +try { $mine = $lock.WaitOne(15000) } catch [Threading.AbandonedMutexException] { $mine = $true } +if (-not $mine) { [Console]::Error.WriteLine("windows-vm: another click or scroll is still in progress"); exit 1 } New-Item -ItemType Directory -Force $d | Out-Null -$old = Get-Item $req -ErrorAction SilentlyContinue # left behind by a run that died -if ($old -and $old.LastWriteTime -lt (Get-Date).AddSeconds(-15)) { Remove-Item $req } -# Creating input.txt is the lock: CreateNew fails if another request already has it. -try { $f = [IO.File]::Open($req, "CreateNew", "Write") } -catch { [Console]::Error.WriteLine("windows-vm: another click or scroll is in progress"); exit 1 } -$held = $true -$text = [Text.Encoding]::ASCII.GetBytes("'"$*"'"); $f.Write($text, 0, $text.Length); $f.Close() +[IO.File]::WriteAllText($req, "'"$*"'") [IO.File]::WriteAllText("$d\input.ps1", [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'$b64'"))) $act = New-ScheduledTaskAction -Execute powershell.exe -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$d\input.ps1`"" $who = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive From 73b97fedc535fe69b9ea67788550cc123bfeda2a Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Wed, 30 Sep 2026 20:50:13 +1000 Subject: [PATCH 11/19] windows-vm.sh: stop the input helper before giving up on a click On a timeout or a setup error the request now stops the scheduled task and waits for it to end before releasing the mutex, so a stalled helper can't act later inside another request. Co-Authored-By: Claude Opus 5.5 (1M context) --- scripts/windows-vm.sh | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/scripts/windows-vm.sh b/scripts/windows-vm.sh index be4f077..ff6db1c 100755 --- a/scripts/windows-vm.sh +++ b/scripts/windows-vm.sh @@ -70,7 +70,16 @@ pointer() { # x y click|wheel [notches] local b64=$(print -rn -- $INPUT_PS1 | base64 | tr -d '\n') vm_ps '$ErrorActionPreference = "Stop" $d = Join-Path $env:LOCALAPPDATA "windows-vm"; $req = "$d\input.txt"; $mine = $false -trap { [Console]::Error.WriteLine("windows-vm: $_"); if ($mine) { Remove-Item $req -ErrorAction SilentlyContinue }; exit 1 } +# Giving up: end the helper first, or it could wake up and act in a later request. +function Abandon { + Stop-ScheduledTask -TaskName WindowsVmInput -ErrorAction SilentlyContinue + foreach ($i in 1..25) { + if ((Get-ScheduledTask -TaskName WindowsVmInput -ErrorAction SilentlyContinue).State -ne "Running") { break } + Start-Sleep -Milliseconds 200 + } + Remove-Item $req -ErrorAction SilentlyContinue +} +trap { [Console]::Error.WriteLine("windows-vm: $_"); if ($mine) { Abandon }; exit 1 } # One request at a time: the helper, the task and input.txt are shared. Windows # frees the mutex when this process ends, however it ends. $lock = New-Object Threading.Mutex($false, "windows-vm-input") @@ -84,7 +93,7 @@ $who = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive Register-ScheduledTask -TaskName WindowsVmInput -Action $act -Principal $who -Force | Out-Null Start-ScheduledTask -TaskName WindowsVmInput foreach ($i in 1..50) { if (-not (Test-Path $req)) { exit 0 }; Start-Sleep -Milliseconds 200 } -Remove-Item $req -ErrorAction SilentlyContinue +Abandon [Console]::Error.WriteLine("windows-vm: no input after 10 s: is $env:USERNAME signed in on the VM screen, and is x,y on it?"); exit 1' } From 84912ea4e193e8211ef6cdaf2b2f1eec57e28f10 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 12:46:35 +1100 Subject: [PATCH 12/19] Store: repositories behind a login, and a GitHub token in source settings F-Droid repositories can now be added with HTTP basic auth, either as https://user:pass@host/fdroid/repo (as F-Droid's client accepts) or with separate username/password fields (store form, server API, and the CLI's --username/--password-stdin). The login is stripped from the saved URL and kept in a new shared module, apk_sources/_credentials.py, which writes source-credentials.json in the data folder with mode 0600. A credential is only ever added per request to its exact origin (scheme, host, port): redirects elsewhere get nothing and have Authorization removed. HTTPS only. 401 (or 403 with a login) on add gives a "check the username and password" error and saves nothing; signature, pin, TOFU, hash and rollback checks are unchanged. Removing a repository deletes its login. GitHub gets a user-settable token (FRAME_GITHUB_TOKEN still wins), sent as Bearer only to api.github.com. If GitHub answers 401, the request is retried once without it and the rejection is reported in source settings. The source list shows only whether a token is set, never its value. Co-Authored-By: Claude Opus 5.5 --- tests/test_apk_search.py | 2 +- tests/test_fdroid_sources.py | 12 +- tests/test_source_logins.py | 391 +++++++++++++++++++++++++++++++++ ui/apk_sources/__init__.py | 4 + ui/apk_sources/_credentials.py | 198 +++++++++++++++++ ui/apk_sources/_images.py | 8 +- ui/apk_sources/_web.py | 16 +- ui/apk_sources/fdroid.py | 90 ++++++-- ui/apk_sources/github.py | 96 +++++++- ui/apk_sources/search.py | 8 + ui/index.html | 22 +- ui/server.py | 30 ++- 12 files changed, 833 insertions(+), 44 deletions(-) create mode 100644 tests/test_source_logins.py create mode 100644 ui/apk_sources/_credentials.py diff --git a/tests/test_apk_search.py b/tests/test_apk_search.py index 6b4e3ed..29f8511 100644 --- a/tests/test_apk_search.py +++ b/tests/test_apk_search.py @@ -325,7 +325,7 @@ class EndpointTests(SettingsTest): mod.add_repo.side_effect = SourceError('repository fingerprint mismatch') job = self.wait(self.request('POST', '/api/sources', {'action': 'add', 'url': link})[1]['job']) self.assertEqual(job['error'], 'repository fingerprint mismatch') # no "SourceError:" prefix - for url in ('http://repo.example/repo', 'fdroidrepo://repo.example/repo', 'https://u@repo.example/'): + for url in ('http://repo.example/repo', 'fdroidrepo://repo.example/repo', 'https://repo.example:x/'): self.assertEqual(self.request('POST', '/api/sources', {'action': 'add', 'url': url})[0], 400) self.assertEqual(self.request('POST', '/api/sources', {'action': 'remove', 'source': 'fdroid'})[0], 200) mod.remove_repo.assert_called_once_with(source_id='fdroid') diff --git a/tests/test_fdroid_sources.py b/tests/test_fdroid_sources.py index 6ec0b2b..3f18e63 100644 --- a/tests/test_fdroid_sources.py +++ b/tests/test_fdroid_sources.py @@ -81,7 +81,7 @@ class Repositories(unittest.TestCase): state.clear() self.addCleanup(state.clear) - def fetch(self, url, path, maximum): + def fetch(self, url, path, maximum, auth=None): name = url.rsplit('/', 1)[-1] if self.v1 and name == 'entry.jar': raise urllib.error.HTTPError(url, 404, 'missing', None, None) @@ -311,7 +311,7 @@ class Repositories(unittest.TestCase): source = self.add() other = dict(source, id='other-repo') started, release = threading.Event(), threading.Event() - def fetch(url, path, maximum): + def fetch(url, path, maximum, auth=None): if threading.current_thread().name == 'slow': started.set() release.wait(5) @@ -355,7 +355,7 @@ class Repositories(unittest.TestCase): self.files['entry.jar'], _ = entry_jar(50) source = fdroid.add_repo(URL) jars = {'older': entry_jar(100)[0], 'newer': entry_jar(200)[0]} - def fetch(url, path, maximum): + def fetch(url, path, maximum, auth=None): name = threading.current_thread().name if name in jars and url.endswith('entry.jar'): Path(path).write_bytes(jars[name]) @@ -401,7 +401,7 @@ class Repositories(unittest.TestCase): source = dict(id='overlap', name='Overlap', url=URL, fingerprint=None) self.v1 = True inner = [] - def fetch(url, path, maximum): + def fetch(url, path, maximum, auth=None): if url.endswith('index-v1.jar') and not inner: inner.append(1) # the v1 load passed its fallback check; a v2 load finishes now self.v1 = False @@ -471,7 +471,7 @@ class Repositories(unittest.TestCase): source = self.add() self.expire(source) release = threading.Event() - def slow(url, path, maximum): + def slow(url, path, maximum, auth=None): release.wait(5) self.fetch(url, path, maximum) self.fetch_mock.side_effect = slow @@ -528,7 +528,7 @@ class Repositories(unittest.TestCase): self.expire(source) before = self.fetch_mock.call_count release = __import__('threading').Event() - def slow(url, path, maximum): + def slow(url, path, maximum, auth=None): release.wait(5) self.fetch(url, path, maximum) self.fetch_mock.side_effect = slow diff --git a/tests/test_source_logins.py b/tests/test_source_logins.py new file mode 100644 index 0000000..3187992 --- /dev/null +++ b/tests/test_source_logins.py @@ -0,0 +1,391 @@ +"""Repositories and sources behind a login: F-Droid basic auth and GitHub tokens. + +A fake HTTPS layer stands in for the network (urllib's real redirect, error and +request processing still run), so these tests see every request and its headers. +""" +import sandbox # noqa: F401 (first: keeps tests off real data and services) +import base64 +import contextlib +import http.client +import io +import json +import os +from pathlib import Path +import stat +import sys +import tempfile +import threading +import time +import unittest +from unittest.mock import patch +import urllib.request +import urllib.response + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'ui')) +from apk_sources import SourceAuthError, SourceError, _credentials, _images, _web, fdroid, github, search +import server + +FIXTURES = Path(__file__).parent / 'fixtures' / 'fdroid' +PIN = (FIXTURES / 'fingerprint.txt').read_text().strip() +REPO = 'https://repo.example/fdroid/repo/' +USER, PASSWORD = 'alice', 's3cr@t-pässword' +TOKEN = 'ghp_frameControlTestToken0123456789' +SECRETS = (PASSWORD, TOKEN, base64.b64encode((USER + ':' + PASSWORD).encode()).decode()) +REAL_BUILD_OPENER = urllib.request.build_opener + + +def basic(user, password): + return 'Basic ' + base64.b64encode((user + ':' + password).encode()).decode() + + +class FakeHTTPS(urllib.request.HTTPSHandler): + """Answers https requests from route(url, authorization) -> (status, headers, body).""" + + def __init__(self, route): + super().__init__() + self.route, self.seen = route, [] + + def https_open(self, req): + auth = req.get_header('Authorization') + self.seen.append((req.full_url, auth)) + status, headers, body = self.route(req.full_url, auth) + message = http.client.HTTPMessage() + for key, value in headers.items(): + message[key] = value + response = urllib.response.addinfourl(io.BytesIO(body), message, req.full_url, status) + response.msg = 'fake' + return response + + +class Base(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + for name, value in [('data_dir', lambda *p: self.root.joinpath('data', *p)), + ('cache_dir', lambda *p: self.root.joinpath('cache', *p))]: + mock = patch.object(fdroid.frame_host, name, value) + mock.start() + self.addCleanup(mock.stop) + self.web = FakeHTTPS(self.route) + mock = patch('urllib.request.build_opener', lambda *handlers: REAL_BUILD_OPENER(*handlers, self.web)) + mock.start() + self.addCleanup(mock.stop) + mock = patch.dict(os.environ, {github.ENV: ''}) + mock.start() + self.addCleanup(mock.stop) + for state in (_web._limited, fdroid._stale, fdroid._retry_at, fdroid._refreshing, github._rejected): + state.clear() + self.addCleanup(state.clear) + self.stderr = io.StringIO() + mock = patch('sys.stderr', self.stderr) + mock.start() + self.addCleanup(mock.stop) + + def route(self, url, auth): + raise AssertionError('unexpected request ' + url) + + def assertNoSecrets(self, *texts): + for text in texts: + for secret in SECRETS + (USER + ':',): + self.assertNotIn(secret, text) + + def disk(self): + """Everything saved under the data and cache folders except the credentials file.""" + out = [] + for path in self.root.rglob('*'): + if path.is_file() and path.name != 'source-credentials.json': + out.append(path.read_bytes().decode('utf-8', 'replace')) + return '\n'.join(out) + + def credentials_file(self): + return self.root / 'data' / 'source-credentials.json' + + +class Repository(Base): + """A repository at REPO that wants USER and PASSWORD.""" + def setUp(self): + super().setUp() + self.login = basic(USER, PASSWORD) + self.redirect = None # file name -> absolute URL it redirects to + self.forbidden = 401 + + def serve(self, name): + return (FIXTURES / ('example.apk' if name.endswith('.apk') else name)).read_bytes() + + def route(self, url, auth): + for mirror in ('https://mirror.example/fdroid/repo/', 'https://repo.example/elsewhere/'): + if url.startswith(mirror): # serves anyone; a login must never get here unless same-origin + return 200, {}, self.serve(url[len(mirror):]) + self.assertTrue(url.startswith(REPO), url) + if auth != self.login: + return self.forbidden, {'WWW-Authenticate': 'Basic realm="repo"'}, b'no' + name = url[len(REPO):] + if self.redirect and name in self.redirect: + return 302, {'Location': self.redirect[name]}, b'' + return 200, {}, self.serve(name) + + def add(self, **kw): + return fdroid.add_repo('https://alice:s3cr%40t-p%C3%A4ssword@repo.example/fdroid/repo', PIN, **kw) + + +class RepositoryLogin(Repository): + def test_add_search_download_with_login_in_the_url(self): + source = self.add() + self.assertEqual(source['url'], REPO) + self.assertEqual(source['fingerprint'], PIN) + saved = fdroid.user_repos()[0] + self.assertEqual(saved['url'], REPO) + self.assertNotIn('login', saved) + self.assertEqual(len(fdroid.search(source, 'example offline')), 1) + downloaded = fdroid.download(source, 'org.example.app', 1) + self.assertTrue(downloaded['verified']) + self.assertTrue(self.web.seen) + self.assertTrue(all(auth == self.login for url, auth in self.web.seen)) + self.assertTrue(all('@' not in url for url, auth in self.web.seen)) # never in the URL + self.assertTrue(next(s for s in fdroid.sources() if s['id'] == source['id'])['login']) + self.assertNoSecrets(json.dumps(source), json.dumps(fdroid.sources()), self.disk(), self.stderr.getvalue()) + # The settings file holds no part of the login; the credentials file holds it, privately. + settings = (self.root / 'data' / 'apk-repos.json').read_text() + self.assertNotIn(USER, settings) + self.assertTrue(self.credentials_file().is_file()) + if os.name != 'nt': + self.assertEqual(stat.S_IMODE(self.credentials_file().stat().st_mode), 0o600) + + def test_login_given_apart_and_saved_login_reused_on_refresh(self): + source = fdroid.add_repo(REPO, PIN, username=USER, password=PASSWORD) + self.assertEqual(source['url'], REPO) + self.web.seen.clear() + fdroid._load(fdroid.user_repos()[0], force=True) # as a background refresh would + self.assertTrue(self.web.seen) + self.assertTrue(all(auth == self.login for url, auth in self.web.seen)) + fdroid.add_repo(REPO) # re-adding without a login keeps the saved one + self.assertTrue(_credentials.has(source['id'])) + + def test_wrong_or_missing_login_saves_nothing(self): + for kw, message in [({'username': USER, 'password': 'wrong'}, 'check the username and password'), + ({}, 'needs a username and password')]: + with self.subTest(kw=kw): + with self.assertRaisesRegex(SourceAuthError, message) as caught: + fdroid.add_repo(REPO, PIN, **kw) + self.assertNoSecrets(str(caught.exception), repr(caught.exception)) + self.assertNotIn('wrong', str(caught.exception)) + self.assertEqual(fdroid.user_repos(), []) + self.assertFalse(self.credentials_file().exists()) + self.assertFalse((self.root / 'data' / 'apk-repo-state.json').exists()) + self.assertEqual(_web._limited, {}) # an auth failure isn't a rate limit + + def test_403_with_a_login_is_a_login_error_not_a_rate_limit(self): + self.forbidden = 403 + with self.assertRaisesRegex(SourceAuthError, 'check the username and password'): + fdroid.add_repo(REPO, PIN, username=USER, password='wrong') + self.assertEqual(_web._limited, {}) + self.assertEqual(fdroid.user_repos(), []) + + def test_signature_checks_still_apply(self): + with self.assertRaisesRegex(SourceError, 'fingerprint mismatch'): + fdroid.add_repo(REPO, '0' * 64, username=USER, password=PASSWORD) + self.assertEqual(fdroid.user_repos(), []) + self.assertFalse(self.credentials_file().exists()) + + def test_cross_origin_redirect_never_gets_the_login(self): + self.redirect = {'entry.jar': 'https://mirror.example/fdroid/repo/entry.jar', + 'index-v2.json': 'https://repo.example/elsewhere/index-v2.json'} + source = self.add() + self.assertEqual(source['fingerprint'], PIN) # the mirror's copy still had to verify + mirror = [auth for url, auth in self.web.seen if url.startswith('https://mirror.example/')] + same_origin = [auth for url, auth in self.web.seen if url.startswith('https://repo.example/elsewhere/')] + self.assertEqual(mirror, [None]) + self.assertEqual(same_origin, [self.login]) # same scheme, host and port: still that repository's + + def test_other_ports_and_http_never_get_the_login(self): + login = _credentials.basic(REPO, USER, PASSWORD) + for url in ('https://repo.example:8443/fdroid/repo/x', 'http://repo.example/fdroid/repo/x', + 'https://other.example/fdroid/repo/x', 'https://repo.example.evil/x'): + self.assertFalse(login.matches(url), url) + self.assertTrue(login.matches('https://REPO.example:443/anything')) + self.assertNoSecrets(repr(login)) + handler = _credentials.Handler(login) + req = urllib.request.Request('https://other.example/x', headers={'Authorization': 'Basic stale'}) + self.assertIsNone(handler.https_request(req).get_header('Authorization')) + + def test_http_and_bad_logins_are_refused_before_any_request(self): + for url, kw in [('http://alice:pw@repo.example/fdroid/repo', {}), + ('http://repo.example/fdroid/repo', {'username': USER, 'password': PASSWORD}), + (REPO, {'username': 'a:b', 'password': PASSWORD}), + (REPO, {'username': USER, 'password': 'x\r\nX-Evil: 1'}), + (REPO, {'password': PASSWORD}), + ('https://alice:pw@repo.example/fdroid/repo', {'username': 'bob'})]: + with self.subTest(url=url, kw=kw), self.assertRaises(SourceError) as caught: + fdroid.add_repo(url, PIN, **kw) + self.assertNotIn('pw', str(caught.exception).replace('password', '')) + self.assertNoSecrets(str(caught.exception)) + self.assertEqual(self.web.seen, []) + + def test_remove_deletes_the_login(self): + source = self.add() + other = _credentials.bearer('https://api.github.com/', TOKEN) + _credentials.put('github', other) + fdroid.remove_repo(source['id']) + self.assertFalse(_credentials.has(source['id'])) + self.assertNotIn(PASSWORD, self.credentials_file().read_text()) + _credentials.remove('github') + self.assertFalse(self.credentials_file().exists()) # nothing left: the file goes + + def test_cli_reads_the_password_from_stdin(self): + out = io.StringIO() + argv = ['fdroid.py', 'add', REPO, '--fingerprint', PIN, '--username', USER, '--password-stdin'] + with patch.object(sys, 'argv', argv), patch.object(sys, 'stdin', io.StringIO(PASSWORD + '\n')), \ + contextlib.redirect_stdout(out): + fdroid.main() + self.assertEqual(json.loads(out.getvalue())['url'], REPO) + self.assertNoSecrets(out.getvalue()) + self.assertTrue(_credentials.has(fdroid.user_repos()[0]['id'])) + + def test_artwork_from_the_repository_gets_the_login_and_only_there(self): + source = self.add() + self.assertEqual(_credentials.for_url(REPO + 'icons/a.png').header(), self.login) + self.assertTrue(_credentials.has(source['id'])) + self.assertIsNone(_credentials.for_url('https://repo.example/other/a.png')) # outside the repository + self.assertIsNone(_credentials.for_url('https://cdn.example/fdroid/repo/a.png')) + + +class GitHubToken(Base): + def setUp(self): + super().setUp() + self.accept = {TOKEN} + self.releases = json.dumps([]).encode() + + def route(self, url, auth): + if url.startswith('https://api.github.com/'): + if auth is not None and auth not in {'Bearer ' + t for t in self.accept}: + return 401, {}, b'{"message": "Bad credentials"}' + if url.endswith('/redirected'): + return 302, {'Location': 'https://github.com/landed'}, b'' + return 200, {}, self.releases + if url == 'https://github.com/landed': + return 200, {}, b'{"ok": true}' + raise AssertionError('unexpected request ' + url) + + def test_saved_token_goes_only_to_the_api(self): + github.set_token(TOKEN) + self.assertEqual(github._api('/repos/a/b/releases'), []) + self.assertEqual(self.web.seen, [('https://api.github.com/repos/a/b/releases', 'Bearer ' + TOKEN)]) + auth = github._credential(github._token()[0]) + self.assertEqual(_web.read('https://api.github.com/redirected', ('api.github.com', 'github.com'), auth=auth), + b'{"ok": true}') + self.assertEqual(self.web.seen[-2:], [('https://api.github.com/redirected', 'Bearer ' + TOKEN), + ('https://github.com/landed', None)]) # redirect: no token + status = github.sources()[0]['token'] + self.assertEqual(status, {'set': True, 'from': 'saved', 'rejected': False}) + self.assertNoSecrets(json.dumps(github.sources()), self.disk(), self.stderr.getvalue()) + if os.name != 'nt': + self.assertEqual(stat.S_IMODE(self.credentials_file().stat().st_mode), 0o600) + + def test_rejected_token_retries_once_without_it(self): + github.set_token(TOKEN) + self.accept = set() + self.assertEqual(github._api('/repos/a/b/releases'), []) + self.assertEqual([auth for _, auth in self.web.seen], ['Bearer ' + TOKEN, None]) + self.assertTrue(github.token_status()['rejected']) + self.assertIn('rejected', self.stderr.getvalue()) + self.assertNoSecrets(self.stderr.getvalue()) + self.web.seen.clear() + github._api('/repos/a/b/other') + self.assertEqual([auth for _, auth in self.web.seen], [None]) # not tried again this run + github.set_token(TOKEN) # saving it again gives it a fresh chance + self.assertFalse(github.token_status()['rejected']) + + def test_environment_variable_wins(self): + github.set_token(TOKEN) + env = 'ghp_fromTheEnvironment' + self.accept = {env} + with patch.dict(os.environ, {github.ENV: env}): + github._api('/repos/a/b/releases') + self.assertEqual(self.web.seen[-1][1], 'Bearer ' + env) + self.assertEqual(github.token_status(), {'set': True, 'from': 'env', 'rejected': False}) + self.assertEqual(github.token_status()['from'], 'saved') + + def test_clear_removes_it_from_disk(self): + github.set_token(TOKEN) + github.clear_token() + self.assertFalse(self.credentials_file().exists()) + self.assertEqual(github.token_status(), {'set': False, 'from': None, 'rejected': False}) + github._api('/repos/a/b/releases') + self.assertEqual(self.web.seen[-1][1], None) + + def test_bad_tokens_are_refused(self): + for token in ('', ' ', 'two words', 'x\nAuthorization: y'): + with self.subTest(token=token), self.assertRaises(SourceError): + github.set_token(token) + self.assertFalse(self.credentials_file().exists()) + + +class Endpoints(Repository): + """The server API: logins in, never out, in responses or the server log.""" + + def setUp(self): + super().setUp() + mock = patch.object(search, 'modules', return_value=([fdroid, github], [])) + mock.start() + self.addCleanup(mock.stop) + self.httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), server.Handler) + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + self.addCleanup(self.httpd.server_close) + self.addCleanup(self.httpd.shutdown) + + def request(self, method, path, body=None): + c = http.client.HTTPConnection('127.0.0.1', self.httpd.server_port) + c.request(method, path, json.dumps(body) if body is not None else None, + {'X-Frame-UI': '1', 'Content-Type': 'application/json'}) + r = c.getresponse() + raw = r.read().decode() + c.close() + self.replies.append(raw) + return r.status, json.loads(raw) + + def job(self, reply): + for _ in range(500): + job = self.request('GET', '/api/job?id=' + reply['job'])[1] + if job['done']: + return job + time.sleep(.01) + self.fail('job did not finish') + + def test_add_with_login_and_token_settings(self): + self.replies = [] + bad = self.job(self.request('POST', '/api/sources', {'action': 'add', 'url': REPO, 'fingerprint': PIN, + 'username': USER, 'password': 'wrong'})[1]) + self.assertIn('check the username and password', bad['error']) + self.assertEqual(fdroid.user_repos(), []) + code, reply = self.request('POST', '/api/sources', {'action': 'add', 'url': REPO, 'fingerprint': PIN, + 'username': USER, 'password': PASSWORD}) + self.assertEqual(code, 200) + job = self.job(reply) + self.assertIsNone(job['error']) + listed = self.request('GET', '/api/sources')[1]['sources'] + repo = next(s for s in listed if s['id'] == job['result']['source']['id']) + self.assertEqual((repo['url'], repo['login']), (REPO, True)) + self.assertEqual(self.request('POST', '/api/sources', {'action': 'set-token', 'source': 'github', + 'token': TOKEN})[0], 200) + github_row = next(s for s in self.request('GET', '/api/sources')[1]['sources'] if s['id'] == 'github') + self.assertEqual(github_row['token'], {'set': True, 'from': 'saved', 'rejected': False}) + self.assertEqual(self.request('POST', '/api/sources', {'action': 'set-token', 'source': 'fdroid', + 'token': TOKEN})[0], 400) + self.assertEqual(self.request('POST', '/api/sources', {'action': 'clear-token', 'source': 'github'})[0], 200) + self.assertFalse(_credentials.has('github')) + self.assertEqual(self.request('POST', '/api/sources', {'action': 'remove', 'source': repo['id']})[0], 200) + self.assertFalse(self.credentials_file().exists()) + self.assertNoSecrets(*self.replies, self.stderr.getvalue(), self.disk()) + + def test_login_in_the_url_is_accepted(self): + self.replies = [] + url = 'https://alice:s3cr%40t-p%C3%A4ssword@repo.example/fdroid/repo' + job = self.job(self.request('POST', '/api/sources', {'action': 'add', 'url': url, 'fingerprint': PIN})[1]) + self.assertIsNone(job['error']) + self.assertEqual(fdroid.user_repos()[0]['url'], REPO) + self.assertNoSecrets(*self.replies, self.stderr.getvalue()) + + +if __name__ == '__main__': + unittest.main() diff --git a/ui/apk_sources/__init__.py b/ui/apk_sources/__init__.py index f7e6b05..be9648c 100644 --- a/ui/apk_sources/__init__.py +++ b/ui/apk_sources/__init__.py @@ -45,6 +45,10 @@ class SourceError(Exception): """User-readable failure from a source (network, format, verification).""" +class SourceAuthError(SourceError): + """The server refused our login (HTTP 401, or 403 when a login was sent).""" + + class SourceLimited(SourceError): """The source's host asked us to slow down; retry_after is in seconds.""" diff --git a/ui/apk_sources/_credentials.py b/ui/apk_sources/_credentials.py new file mode 100644 index 0000000..063b837 --- /dev/null +++ b/ui/apk_sources/_credentials.py @@ -0,0 +1,198 @@ +"""Logins for sources behind one: HTTP basic auth and access tokens. + +Saved apart from the source settings, in frame_host.data_dir('source-credentials.json') +(mode 0600), keyed by a caller-chosen name: an F-Droid source id, 'github'. Each +credential belongs to one exact origin (https, host, port) and is only ever sent +to a request for that origin: Handler adds it to each request, redirects +included, and removes any Authorization header from every other request. + +Secrets leave this module only as an Authorization header value. Credential's +repr hides them, and nothing here puts them in an exception message. +""" +import base64 +import json +import os +import tempfile +import threading +import urllib.parse +import urllib.request + +import frame_host + +_lock = threading.RLock() +MAX = 4096 # longest username, password or token accepted + + +def _path(): + return frame_host.data_dir('source-credentials.json') + + +def origin(url): + """'https://host:port' for an https URL; ValueError for anything else.""" + p = urllib.parse.urlsplit(url) + port = p.port # raises ValueError on a bad port + if p.scheme.lower() != 'https' or not p.hostname: + raise ValueError('credentials are only sent over HTTPS') + host = p.hostname.lower() + return 'https://%s:%d' % ('[%s]' % host if ':' in host else host, port or 443) + + +def _check(value, what, allow_empty=False): + if not isinstance(value, str) or (not value and not allow_empty) or len(value) > MAX: + raise ValueError('invalid ' + what) + if any(ord(c) < 32 or ord(c) == 127 for c in value): + raise ValueError(what + ' must not contain control characters') + return value + + +class Credential: + """A username and password (basic) or a token (bearer) for one origin. + + scope is a URL prefix used only to pick a stored credential for a URL (for_url); + whether a request gets the credential depends on its origin alone.""" + __slots__ = ('origin', 'scope', 'username', '_secret') + + def __init__(self, scope, secret, username=None): + self.origin = origin(scope) + self.scope = scope + if username is not None: + _check(username, 'username') + if ':' in username: + raise ValueError('username must not contain ":"') + _check(secret, 'password', allow_empty=True) + else: + _check(secret, 'token') + if any(c.isspace() for c in secret): + raise ValueError('token must not contain spaces') + self.username, self._secret = username, secret + + @property + def kind(self): + return 'bearer' if self.username is None else 'basic' + + def header(self): + if self.username is None: + return 'Bearer ' + self._secret + return 'Basic ' + base64.b64encode((self.username + ':' + self._secret).encode('utf-8')).decode('ascii') + + def matches(self, url): + """True only for a URL on exactly this credential's origin.""" + try: + return origin(url) == self.origin + except ValueError: + return False + + def same(self, other): + return isinstance(other, Credential) and (self.origin, self.username, self._secret) == ( + other.origin, other.username, other._secret) + + def __repr__(self): + return '' % (self.kind, self.origin) + + def _json(self): + return {'scope': self.scope, 'username': self.username, 'secret': self._secret} + + +def basic(scope, username, password): + """Basic auth for scope's origin, e.g. basic('https://example.org/fdroid/repo/', 'me', 'pw').""" + return Credential(scope, password, username) + + +def bearer(scope, token): + """An access token for scope's origin, sent as 'Authorization: Bearer '.""" + return Credential(scope, token) + + +def _read(): + try: + with open(str(_path()), encoding='utf-8') as f: + data = json.load(f) + if not isinstance(data, dict): + raise ValueError + return data + except FileNotFoundError: + return {} + except (OSError, ValueError): + return {} # unreadable: as if none were saved; the next save rewrites it + + +def _save(data): + path = _path() + if not data: + try: + os.remove(str(path)) + except FileNotFoundError: + pass + return + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix='.credentials-', suffix='.part') # created 0600 + try: + with os.fdopen(fd, 'w', encoding='utf-8') as f: + json.dump(data, f, separators=(',', ':')) + os.chmod(tmp, 0o600) + os.replace(tmp, str(path)) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def get(key): + """The saved Credential for key, or None.""" + with _lock: + item = _read().get(key) + try: + return Credential(item['scope'], item['secret'], item.get('username')) + except (TypeError, KeyError, ValueError): + return None + + +def has(key): + return get(key) is not None + + +def put(key, credential): + if not isinstance(credential, Credential): + raise TypeError('put() needs a Credential') + with _lock: + data = _read() + data[key] = credential._json() + _save(data) + + +def remove(key): + """Delete key's credential from disk; True if there was one.""" + with _lock: + data = _read() + if key not in data: + return False + del data[key] + _save(data) + return True + + +def for_url(url): + """A saved credential whose origin matches url and whose scope url is under, or None.""" + with _lock: + keys = list(_read()) + for key in keys: + credential = get(key) + if credential and credential.matches(url) and url.startswith(credential.scope): + return credential + return None + + +class Handler(urllib.request.BaseHandler): + """Adds the credential to requests for its origin (redirects included) and strips + Authorization from every other request, so a redirect elsewhere never gets it.""" + handler_order = 900 # after the default processors + + def __init__(self, credential): + self.credential = credential + + def _request(self, req): + req.remove_header('Authorization') + if self.credential is not None and self.credential.matches(req.full_url): + req.add_unredirected_header('Authorization', self.credential.header()) + return req + + http_request = https_request = _request diff --git a/ui/apk_sources/_images.py b/ui/apk_sources/_images.py index da89453..b0244d5 100644 --- a/ui/apk_sources/_images.py +++ b/ui/apk_sources/_images.py @@ -9,7 +9,7 @@ import threading import time from urllib.parse import urljoin, urlsplit -from apk_sources import SourceError +from apk_sources import SourceError, _credentials _lock = threading.Lock() _urls = OrderedDict() @@ -141,7 +141,11 @@ def get(url, headers=None, redirects=3, deadline=None, limit=MAX_IMAGE): path = p.path or '/' if p.query: path += '?' + p.query - conn.request('GET', path, headers={'User-Agent': 'FrameControl/0.3.1', **(headers or {})}) + sent = {'User-Agent': 'FrameControl/0.3.1', **(headers or {})} + login = _credentials.for_url(url) # a repository behind a login: its own artwork only, per hop + if login: + sent['Authorization'] = login.header() + conn.request('GET', path, headers=sent) live[0].settimeout(min(10, left())) response = conn.getresponse() if response.status in (301, 302, 303, 307, 308) and redirects: diff --git a/ui/apk_sources/_web.py b/ui/apk_sources/_web.py index 1952e7d..d24207d 100644 --- a/ui/apk_sources/_web.py +++ b/ui/apk_sources/_web.py @@ -3,7 +3,7 @@ import hashlib, os, shutil, tempfile, threading, time, urllib.error, urllib.pars from email.utils import parsedate_to_datetime import frame_host -from . import SourceError, SourceLimited +from . import SourceAuthError, SourceError, SourceLimited, _credentials UA = 'FrameControl/0.1' APK_CAP = 2 * 1024 ** 3 # cached APKs across all sources, least recently used go first @@ -136,6 +136,8 @@ def checked_url(url, hosts): class Redirect(urllib.request.HTTPRedirectHandler): + """Only to the allowed hosts, and never carrying an Authorization header along: + a credential passed to open_url() is added again, by its Handler, only on its origin.""" def __init__(self, hosts): self.hosts = hosts @@ -147,13 +149,15 @@ class Redirect(urllib.request.HTTPRedirectHandler): return result -def open_url(url, hosts, headers=None): +def open_url(url, hosts, headers=None, auth=None): + """auth: an _credentials.Credential, sent only to requests on its own origin.""" checked_url(url, hosts) - return urllib.request.build_opener(Redirect(hosts)).open( + handlers = [Redirect(hosts)] + ([_credentials.Handler(auth)] if auth else []) + return urllib.request.build_opener(*handlers).open( urllib.request.Request(url, headers={'User-Agent': UA, **(headers or {})}), timeout=60) -def read(url, hosts, headers=None, ttl=3600, name=None, hint=''): +def read(url, hosts, headers=None, ttl=3600, name=None, hint='', auth=None): path = os.path.join(cache(), hashlib.sha256(url.encode()).hexdigest() + '.data') name = name or _host(url) or 'The source' @@ -171,7 +175,7 @@ def read(url, hosts, headers=None, ttl=3600, name=None, hint=''): if data is None: raise limited_error(name, wait, hint) return data - with open_url(url, hosts, headers) as r: + with open_url(url, hosts, headers, auth) as r: data = r.read(8 * 1024 * 1024 + 1) if len(data) > 8 * 1024 * 1024: raise SourceError('Source index is too large') @@ -185,6 +189,8 @@ def read(url, hosts, headers=None, ttl=3600, name=None, hint=''): os.remove(tmp) return data except urllib.error.HTTPError as e: + if e.code == 401: # not 403: GitHub also uses that for rate limits, token or not + raise SourceAuthError('%s refused the login (HTTP 401)' % name) from e if e.code in (403, 429): delay = throttle(url, e.headers) data = cached() diff --git a/ui/apk_sources/fdroid.py b/ui/apk_sources/fdroid.py index ff02cb4..1779bf3 100644 --- a/ui/apk_sources/fdroid.py +++ b/ui/apk_sources/fdroid.py @@ -20,7 +20,7 @@ import zipfile if __package__ in (None, ''): sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from apk_sources import SourceError, SourceLimited, _web +from apk_sources import SourceAuthError, SourceError, SourceLimited, _credentials, _web import frame_host from frame_apk_sign import _der_parts, _cert_key, der from frame_catalog import _IndexReader, _reduce_index, _sha256 @@ -71,6 +71,39 @@ def _url(url, fingerprint=None): return urllib.parse.urlunsplit(('https', p.netloc.lower(), p.path.rstrip('/') + '/', '', '')), pin +def _split_login(url, username=None, password=None): + """(url without user:pass, credential or None). The address may carry the login, as + F-Droid's client accepts (https://user:pass@host/fdroid/repo), or it may be given apart.""" + try: + p = urllib.parse.urlsplit(url) + p.port + except ValueError as e: + raise SourceError('invalid repository URL') from e + if '@' in p.netloc: + if p.username is None: + raise SourceError('invalid repository URL') + linked = urllib.parse.unquote(p.username), None if p.password is None else urllib.parse.unquote(p.password) + if username not in (None, '', linked[0]) or (linked[1] is not None and password not in (None, '', linked[1])): + raise SourceError('the address and the username/password fields disagree') + username = linked[0] + password = linked[1] if linked[1] is not None else password + url = urllib.parse.urlunsplit((p.scheme, p.netloc.rpartition('@')[2], p.path, p.query, p.fragment)) + if username in (None, ''): + if password: + raise SourceError('a password needs a username') + return url, None + clean, _ = _url(url) + try: + return url, _credentials.basic(clean, username, password or '') + except ValueError as e: + raise SourceError('cannot use that login: ' + str(e)) from None + + +def _login(source): + """The saved login for a user repository, or None.""" + return None if source.get('builtin') else _credentials.get(source['id']) + + def _child(base, name): name = str(name).lstrip('/') decoded = urllib.parse.unquote(name) @@ -91,14 +124,16 @@ class _HTTPSRedirect(urllib.request.HTTPRedirectHandler): return super().redirect_request(req, fp, code, msg, headers, newurl) -def _fetch(url, path, maximum): +def _fetch(url, path, maximum, auth=None): + """auth: the repository's login, sent only to its exact origin (never after a redirect elsewhere).""" host = urllib.parse.urlsplit(url).hostname wait = _web.wait_time(url) if wait: raise _web.limited_error(host, wait) request = urllib.request.Request(url, headers={'User-Agent': 'FrameControl/1.0'}) + handlers = [_HTTPSRedirect()] + ([_credentials.Handler(auth)] if auth else []) try: - with urllib.request.build_opener(_HTTPSRedirect()).open(request, timeout=60) as r, open(path, 'wb') as f: + with urllib.request.build_opener(*handlers).open(request, timeout=60) as r, open(path, 'wb') as f: total = 0 while True: chunk = r.read(1 << 20) @@ -109,6 +144,9 @@ def _fetch(url, path, maximum): raise SourceError('repository file exceeds size limit') f.write(chunk) except urllib.error.HTTPError as e: + if e.code == 401 or (e.code == 403 and auth): + raise SourceAuthError('The repository refused the login (HTTP %d); check the username and password' + % e.code if auth else 'This repository needs a username and password') from None if e.code in (403, 429): raise _web.limited_error(host, _web.throttle(url, e.headers)) from e raise @@ -342,7 +380,7 @@ def sources(): return [dict(id=i, kind=KIND, name=n, url=u, fingerprint=p, builtin=True, # The archive only holds superseded versions; it clutters search unless asked for. enabled=settings['enabled'].get(i, i != 'fdroid-archive'), trust='community') - for i, n, u, p in builtins] + settings['repos'] + for i, n, u, p in builtins] + [dict(s, login=_credentials.has(s['id'])) for s in settings['repos']] def _text(value): @@ -514,10 +552,12 @@ def _source_lock(source_id): return _load_locks.setdefault(source_id, threading.Lock()) -def _load(source, force=False): +def _load(source, force=False, auth=None): + """auth: a login to use instead of the saved one (while adding, before anything is saved).""" if not re.fullmatch(r'[a-z0-9-]+', source['id']): raise SourceError('invalid source id') _url(source['url'], source.get('fingerprint')) + auth = auth or _login(source) cache = frame_host.cache_dir('apk-sources', source['id'] + '.json') found = None if force else _cached(source, cache) if found: @@ -535,7 +575,7 @@ def _load(source, force=False): jar, raw = Path(tmp) / 'index.jar', Path(tmp) / 'index.json' v2 = True try: - _fetch(source['url'] + 'entry.jar', jar, 8 * 1024 * 1024) + _fetch(source['url'] + 'entry.jar', jar, 8 * 1024 * 1024, auth=auth) except urllib.error.HTTPError as e: if e.code not in (404, 410): raise @@ -543,7 +583,7 @@ def _load(source, force=False): raise SourceError('repository no longer serves its signed v2 index; ' 'refusing to fall back to the older v1 index') from e v2 = False - _fetch(source['url'] + 'index-v1.jar', jar, 256 * 1024 * 1024) + _fetch(source['url'] + 'index-v1.jar', jar, 256 * 1024 * 1024, auth=auth) content, pin = _jar(jar, 'index-v1.json', source.get('fingerprint')) timestamp = _v1(content, raw) _check_timestamp(source, timestamp) @@ -552,7 +592,7 @@ def _load(source, force=False): signed = json.loads(content) timestamp, entry = signed.get('timestamp'), signed['index'] _check_timestamp(source, timestamp) - _fetch(_child(source['url'], entry['name']), raw, 512 * 1024 * 1024) + _fetch(_child(source['url'], entry['name']), raw, 512 * 1024 * 1024, auth=auth) if _sha256(raw) != entry['sha256'] or (entry.get('size') is not None and raw.stat().st_size != entry['size']): raise SourceError('index SHA-256 or size mismatch') apps = _reduce(raw, source) @@ -572,7 +612,10 @@ def _load(source, force=False): raise SourceError('cannot load repository: ' + str(e)) from e -def add_repo(url, fingerprint=None, name=None): +def add_repo(url, fingerprint=None, name=None, username=None, password=None): + """Check and save a repository. A login (in the URL or apart) is kept out of the + saved URL, in _credentials, and saved only once the repository's index verified.""" + url, login = _split_login(url, username, password) url, pin = _url(url, fingerprint) with _LOCK: existing = next((s for s in _read()['repos'] if s['url'] == url), None) @@ -583,15 +626,26 @@ def add_repo(url, fingerprint=None, name=None): source = dict(id='fdroid-user-' + hashlib.sha256(url.encode()).hexdigest()[:20], kind=KIND, name=name or (existing or {}).get('name') or urllib.parse.urlsplit(url).hostname, url=url, builtin=False, enabled=True, trust='user', fingerprint=pin) - _, source['fingerprint'] = _load(source, force=True) # network work outside the settings lock + # Network work outside the settings lock; without a new login, a saved one (re-adding) is used. + _, source['fingerprint'] = _load(source, force=True, auth=login) source['trust_on_first_use'] = existing.get('trust_on_first_use', False) if existing else pin is None with _LOCK: settings = _read() current = next((s for s in settings['repos'] if s['id'] == source['id']), None) if current and current['fingerprint'] != source['fingerprint']: raise SourceError('repository already has a different pinned fingerprint; remove it first') - settings['repos'] = [s for s in settings['repos'] if s['id'] != source['id']] + [source] - _write(_storage(), settings) + previous = _credentials.get(source['id']) + if login: + _credentials.put(source['id'], login) + try: + settings['repos'] = [s for s in settings['repos'] if s['id'] != source['id']] + [source] + _write(_storage(), settings) + except BaseException: + if login and previous: # not saved after all: leave the login as it was + _credentials.put(source['id'], previous) + elif login: + _credentials.remove(source['id']) + raise return source @@ -602,6 +656,7 @@ def remove_repo(source_id): raise SourceError('unknown user repository') settings['repos'] = [s for s in settings['repos'] if s['id'] != source_id] _write(_storage(), settings) + _credentials.remove(source_id) with _state_file_lock(), _LOCK: # lock order: state file, then _LOCK states = _states() if states.pop(source_id, None) is not None: # re-adding is a deliberate new trust decision @@ -663,7 +718,7 @@ def download(source, entry_id, version_code=None): fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix='.part') os.close(fd) try: - _fetch(_child(source['url'], version['name']), tmp, 4 * 1024 ** 3) + _fetch(_child(source['url'], version['name']), tmp, 4 * 1024 ** 3, auth=_login(source)) if _sha256(tmp) != sha: raise SourceError('APK SHA-256 mismatch; download discarded') os.replace(tmp, path) @@ -684,6 +739,8 @@ def main(): add.add_argument('url') add.add_argument('--fingerprint') add.add_argument('--name') + add.add_argument('--username', help='for a repository behind a login (HTTP basic auth)') + add.add_argument('--password-stdin', action='store_true', help='read the password from the first line of stdin') sub.add_parser('list') remove = sub.add_parser('remove') remove.add_argument('source') @@ -702,7 +759,12 @@ def main(): def _cli(parser, args): try: if args.command == 'add': - result = add_repo(args.url, args.fingerprint, args.name) + password = None + if args.password_stdin: + if not args.username: + raise SourceError('--password-stdin needs --username') + password = sys.stdin.readline().rstrip('\r\n') + result = add_repo(args.url, args.fingerprint, args.name, args.username, password) elif args.command == 'list': result = sources() elif args.command == 'remove': diff --git a/ui/apk_sources/github.py b/ui/apk_sources/github.py index e636f2a..a12ed57 100644 --- a/ui/apk_sources/github.py +++ b/ui/apk_sources/github.py @@ -1,17 +1,77 @@ """Curated publisher releases; optional topic discovery is page-only.""" -import fnmatch, json, os, re, urllib.parse +import fnmatch, hashlib, json, os, re, sys, threading, urllib.parse -from . import SourceError, _web +from . import SourceAuthError, SourceError, _credentials, _web KIND = 'github' API = 'https://api.github.com' +ENV = 'FRAME_GITHUB_TOKEN' # wins over a token saved in source settings +CREDENTIAL = 'github' # _credentials key; only ever sent to api.github.com +_rejected = set() # SHA-256 of tokens GitHub answered 401 to (this run only) +_rejected_lock = threading.Lock() TOPICS = ('oculus-quest', 'openxr', 'quest') HOSTS = ('github.com', 'release-assets.githubusercontent.com', 'objects.githubusercontent.com') def sources(): return [{'id': KIND, 'kind': KIND, 'name': 'GitHub releases', 'url': 'https://github.com', - 'builtin': True, 'enabled': True, 'trust': 'community'}] + 'builtin': True, 'enabled': True, 'trust': 'community', 'token': token_status()}] + + +def _token(): + """(token, where it came from) or (None, None). The environment variable wins.""" + env = os.environ.get(ENV) + if env: + return env, 'env' + saved = _credentials.get(CREDENTIAL) + if saved and saved.kind == 'bearer': + return saved, 'saved' + return None, None + + +def _credential(token): + if isinstance(token, _credentials.Credential): + return token + try: + return _credentials.bearer(API + '/', token) + except ValueError as e: + raise SourceError('%s is not a usable GitHub token: %s' % (ENV, e)) from None + + +def _digest(credential): + return hashlib.sha256(credential.header().encode()).hexdigest() + + +def token_status(): + """Whether a token is set, where from, and whether GitHub rejected it; never the token.""" + token, where = _token() + rejected = False + if token is not None: + try: + with _rejected_lock: + rejected = _digest(_credential(token)) in _rejected + except SourceError: + rejected = True + return {'set': token is not None, 'from': where, 'rejected': rejected} + + +def set_token(token): + """Save a personal access token for api.github.com (FRAME_GITHUB_TOKEN still wins).""" + if not isinstance(token, str) or not token.strip(): + raise SourceError('Paste a GitHub token') + try: + credential = _credentials.bearer(API + '/', token.strip()) + except ValueError as e: + raise SourceError('That is not a usable GitHub token: ' + str(e)) from None + _credentials.put(CREDENTIAL, credential) + with _rejected_lock: + _rejected.discard(_digest(credential)) # a fresh chance + return {'message': 'GitHub token saved' + (' (%s is set and is used instead)' % ENV if os.environ.get(ENV) else '')} + + +def clear_token(): + _credentials.remove(CREDENTIAL) + return {'message': 'GitHub token removed'} def _curated(): @@ -20,13 +80,33 @@ def _curated(): def _api(path): + """GET from the GitHub API, with the user's token if there is one. If GitHub rejects + the token (401), retry once without it, like Obtainium, and remember the rejection.""" headers = {'Accept': 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28'} - token = os.environ.get('FRAME_GITHUB_TOKEN') - if token: - headers['Authorization'] = 'Bearer ' + token + token, _ = _token() + auth = _credential(token) if token is not None else None + with _rejected_lock: + if auth and _digest(auth) in _rejected: + auth = None # already refused this run: don't spend a request on it again + hint = ' (add a GitHub token in the store\'s source settings, or set %s, to raise the limit)' % ENV + if token is not None and not auth: + hint = ' (GitHub rejected your token; replace it in the store\'s source settings)' + + def get(auth): + return _web.read(API + path, ('api.github.com',), headers, name='GitHub', + hint='' if auth else hint, auth=auth) try: - return json.loads(_web.read(API + path, ('api.github.com',), headers, name='GitHub', - hint='' if token else ' (set FRAME_GITHUB_TOKEN to raise the limit)')) + try: + data = get(auth) + except SourceAuthError: + if not auth: + raise + with _rejected_lock: + _rejected.add(_digest(auth)) + print('GitHub rejected the access token (HTTP 401); continuing without it', file=sys.stderr) + hint = ' (GitHub rejected your token; replace it in the store\'s source settings)' + data = get(None) + return json.loads(data) except (ValueError, TypeError) as e: raise SourceError('Invalid GitHub response') from e diff --git a/ui/apk_sources/search.py b/ui/apk_sources/search.py index 883c08b..e987f03 100644 --- a/ui/apk_sources/search.py +++ b/ui/apk_sources/search.py @@ -113,6 +113,14 @@ def manage_repo(action, **kwargs): return getattr(module, action)(**kwargs) +def set_token(source_id, token): + """Save (token) or remove (None) a source's access token; status is in sources().""" + module, _ = resolve(source_id) + if not hasattr(module, 'set_token'): + raise SourceError('This source does not use an access token') + return module.set_token(token) if token is not None else module.clear_token() + + def normalise(name): return ' '.join(re.findall(r'\w+', unicodedata.normalize('NFKC', name or '').casefold())) diff --git a/ui/index.html b/ui/index.html index 8c5a705..62d93ee 100644 --- a/ui/index.html +++ b/ui/index.html @@ -611,6 +611,8 @@ .source-repo-form input { margin-top:7px; display:block; border-radius:6px; } .source-repo-form details { font-size:11px; color:var(--muted); } .source-repo-form button { justify-self:start; border-radius:6px; } + .source-token { display:flex; flex-wrap:wrap; align-items:center; gap:7px; margin:8px 0 4px; } + .source-token input { flex:1; min-width:150px; border-radius:6px; font-size:12px; } #appStore :focus-visible, .store-dialog :focus-visible, .store-tabs :focus-visible { outline:2px solid var(--link); outline-offset:4px; } .store-search input:focus-visible { outline:0!important; } @media(min-width:1400px) { .store-grid { grid-template-columns:repeat(5,minmax(0,1fr)); } } @@ -1207,7 +1209,7 @@
Your app shelves

A world of apps.

Choose where you discover games and apps. We bring them together for you.

-

Add a source

Have a favorite F-Droid repository? Add its address to browse its apps here.

Verify this source (optional)
+

Add a source

Have a favorite F-Droid repository? Add its address to browse its apps here.

Verify this source (optional)
This repository needs a login (optional)

Kept on this computer, apart from the address, and only sent to this repository over HTTPS.

@@ -3139,12 +3141,18 @@ function storeIcon(o) { return ` { if (e.target.matches?.(".store-art img, .store-icon img")) e.target.remove(); }, true); function sourceMark(s) { const name=storeName(s); return ``; } function sourceDescription(s) { return s.description || ({fdroid:"Independent, open-source apps",sidequest:"Discover something new in VR",itch:"Games from independent creators",github:"Direct from the people who make it"})[s.kind] || (s.name.includes("GitHub") ? "Direct from the people who make it" : s.name.includes("Droid") ? "Independent, open-source apps" : s.name.includes("SideQuest") ? "Discover something new in VR" : s.name.includes("itch") ? "Games from independent creators" : "Apps shared by this community"); } +// GitHub's optional access token: only whether one is set is ever shown, never its value. +function sourceToken(s) { + const t=s.token;if(!t)return ""; + const note=t.rejected ? "GitHub rejected this token, so searches continue without it. Replace or clear it." : t.from==="env" ? "Using the token from FRAME_GITHUB_TOKEN." : t.set ? "A token is saved." : "Optional: a token raises GitHub's limit of 60 requests an hour."; + return `
${t.from==="saved" ? `` : ""}
${esc(note)}`; +} async function loadSources() { try { const {sources} = await api("/api/sources"); sourceState.sources = sources; $("sourceFilter").innerHTML = `` + sources.filter(s=>s.enabled).map(s=>``).join(""); $("sourceFilter").value = sourceState.source; - $("sourcesList").innerHTML = sources.map(s=>`
${sourceMark(s.name)}
${esc(storeName(s.name))}

${esc(sourceDescription(s))}

${esc(({official:"Official store",community:"Community",user:"Added by you"})[s.trust] || "Community")}${s.builtin === false ? `` : ""}
`).join("") || `

Your sources will appear here when they are available.

`; + $("sourcesList").innerHTML = sources.map(s=>`
${sourceMark(s.name)}
${esc(storeName(s.name))}

${esc(sourceDescription(s))}

${esc(({official:"Official store",community:"Community",user:"Added by you"})[s.trust] || "Community")}${s.login ? " · Uses a login" : ""}${sourceToken(s)}${s.builtin === false ? `` : ""}
`).join("") || `

Your sources will appear here when they are available.

`; } catch (e) { $("sourceError").textContent = e.message; } } function storeCard(app) { @@ -3271,7 +3279,8 @@ $("detailBody").onclick=e=>{if(e.target.closest('[data-close]'))return $("appDet $("detailBody").onchange=e=>{if(e.target.name==='storeOffer'){sourceState.detail.choice=+e.target.value;renderAppDetail();loadOfferDetails();}}; $("sourcesOpen").onclick=()=>{loadSources();$('sourcesDialog').showModal();}; $("sourcesList").onchange=e=>{if(e.target.matches('[data-enable]'))changeSource({action:'enable',source:e.target.dataset.enable,enabled:e.target.checked});}; -$("sourcesList").onclick=e=>{const b=e.target.closest('[data-remove]');if(b)changeSource({action:'remove',source:b.dataset.remove});}; +$("sourcesList").onclick=e=>{const b=e.target.closest('[data-remove]');if(b)changeSource({action:'remove',source:b.dataset.remove});const c=e.target.closest('[data-clear-token]');if(c)changeSource({action:'clear-token',source:c.dataset.clearToken});}; +$("sourcesList").onsubmit=e=>{const f=e.target.closest('[data-token]');if(!f)return;e.preventDefault();const token=f.elements.token.value.trim();f.reset();if(token)changeSource({action:'set-token',source:f.dataset.token,token});}; async function addSource(body) { $("sourceError").textContent="Checking the repository. Large ones can take a minute…"; let error=""; @@ -3279,7 +3288,12 @@ async function addSource(body) { $("sourceError").textContent=result ? result.message : error || "We couldn't add that repository."; if(result){$("addSource").reset();sourceState.source='';await loadSources();await searchSources();} } -$("addSource").onsubmit=e=>{e.preventDefault();const f=new FormData(e.target);addSource({action:'add',url:f.get('url'),fingerprint:f.get('fingerprint')});}; +$("addSource").onsubmit=e=>{ + e.preventDefault();const f=new FormData(e.target);let url=f.get('url'),username=f.get('username'),password=f.get('password'); + // A login typed into the address moves to the login fields: the address is shown and logged, the login never. + try { const u=new URL(url); if(u.username||u.password){ username=username||decodeURIComponent(u.username); password=password||decodeURIComponent(u.password); u.username='';u.password='';url=u.href; } } catch {} + addSource({action:'add',url,fingerprint:f.get('fingerprint'),...(username ? {username,password} : {})}); +}; document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close()); $('appDetail').addEventListener('close',()=>{sourceState.detailRequest++;}); document.querySelectorAll('[data-store-tab]').forEach(b=>b.onclick=()=>{const browse=b.dataset.storeTab==='browse';$('appStore').hidden=!browse;$('androidLibrary').hidden=browse;$('repNew').hidden=browse;$('sourcesOpen').hidden=!browse;document.querySelectorAll('[data-store-tab]').forEach(t=>{t.classList.toggle('on',t===b);t.setAttribute('aria-pressed',t===b);});if(!browse)loadAndroid();}); diff --git a/ui/server.py b/ui/server.py index 07ca9f3..0d30986 100755 --- a/ui/server.py +++ b/ui/server.py @@ -2153,6 +2153,16 @@ def source_text(body, key, optional=False): return value.strip() +def login_text(body, key): + """A username, password or token: kept exactly (no stripping) and never echoed back.""" + value = body.get(key) + if value in (None, ''): + return None + if not isinstance(value, str) or len(value) > 4096: + raise Failure('Provide a valid ' + key, 400) + return value + + def source_search(query): args = parse_qs(query) q = args.get('q', [''])[0] @@ -2191,19 +2201,31 @@ def source_manage(body): if action == 'add': url = source_text(body, 'url') fingerprint, name = source_text(body, 'fingerprint', True), source_text(body, 'name', True) - parts = urlparse(url) - if parts.scheme not in ('https', 'fdroidrepos') or not parts.hostname or parts.username: - raise Failure('Use an HTTPS or fdroidrepos:// repository URL without credentials', 400) + username, password = login_text(body, 'username'), login_text(body, 'password') + try: + parts = urlparse(url) + parts.port + except ValueError: + raise Failure('Use an HTTPS or fdroidrepos:// repository URL', 400) from None + if parts.scheme not in ('https', 'fdroidrepos') or not parts.hostname: + raise Failure('Use an HTTPS or fdroidrepos:// repository URL', 400) apk_search.repo_module() # fail now if this build can't manage repositories def add(): # downloads and verifies the whole index: a job, not a request - source = apk_search.manage_repo('add_repo', url=url, fingerprint=fingerprint, name=name) + # A login (here or in the URL) is stored apart and never comes back in a response. + login = {'username': username, 'password': password} if username or password else {} + source = apk_search.manage_repo('add_repo', url=url, fingerprint=fingerprint, name=name, **login) message = 'Added ' + source['name'] if source.get('trust_on_first_use'): message += '. Trusted on first use: ' + source['fingerprint'].upper() return {'message': message, 'source': {k: source.get(k) for k in ('id', 'name', 'fingerprint', 'trust_on_first_use')}} return start_job('Add repository', add) + if action in ('set-token', 'clear-token'): + token = login_text(body, 'token') if action == 'set-token' else None + if action == 'set-token' and not token: + raise Failure('Paste a token', 400) + return apk_search.set_token(source_text(body, 'source'), token) if action == 'game-data': package = source_text(body, 'package') return start_job('Add game data', lambda: apk_search.add_game_data(package)) From fe73906f1f8a7c74e5ea5d02ab27e7e22b2945ae Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 12:46:35 +1100 Subject: [PATCH 13/19] Docs: repositories behind a login and GitHub tokens Co-Authored-By: Claude Opus 5.5 --- docs/apk-repos.md | 49 ++++++++++++++++++++++++++++++++++++++++++++- docs/apk-sources.md | 19 ++++++++++++++---- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/docs/apk-repos.md b/docs/apk-repos.md index 25a86dd..8edffee 100644 --- a/docs/apk-repos.md +++ b/docs/apk-repos.md @@ -58,8 +58,55 @@ form shows the pinned one ("Trusted on first use: …") so you can compare it. Re-adding an existing URL preserves its pin; changing it requires deliberately removing and re-adding it. +### Repositories behind a login + +Some self-hosted repositories sit behind HTTP basic auth. As in F-Droid's own +client, the login can be part of the address +(`https://user:pass@example.org/fdroid/repo`), or given separately: in the +store's **Add a source** form under "This repository needs a login", in the +server API (`username` and `password` beside `url`), or on the command line, +where the password is read from standard input so it stays out of shell history +and `ps`: + +```sh +printf '%s\n' "$PASSWORD" | python3 ui/apk_sources/fdroid.py add 'https://example.org/fdroid/repo' --username me --password-stdin +``` + +How the login is kept and used: + +- **Kept out of the address.** The `user:pass@` part is removed before anything + is saved, so the saved repository URL, its id, the source list, job results + and the page never contain it. The store only says "Uses a login". +- **Stored separately.** Logins live in + `frame_host.data_dir('source-credentials.json')` + (`~/Library/Application Support/Frame Control/source-credentials.json` on + macOS), written with mode 0600 and keyed by source id. They are stored in + plain text there, protected by file permissions only (on Windows, + the folder's normal ACLs). Removing the repository deletes its login, and + the file goes when the last login is removed. +- **HTTPS only.** An `http://` address with a login is refused before any request. +- **Exact origin only.** The `Authorization` header is added per request, and + only when the request's scheme, host and port match the repository's. A + redirect to another host or port gets no login, and that request's own + `Authorization` header is removed. A same-origin redirect still gets it. + The store's artwork proxy sends the login only for images under the + repository's own address on that origin. +- **Never echoed.** Logins are not written to logs, error messages, API + responses or the cache. The CLI prints only the saved source. +- **Checked before saving.** As with any repository, the whole index must + download and verify before anything is saved. HTTP 401 (or 403 when a login + was sent) stops the add with "check the username and password" and saves + nothing: no repository, no login, no rollback state. A 403 with a login is + not treated as rate limiting. +- **Same verification.** The login changes only who may download. Signature, + fingerprint pin or TOFU, index hash and rollback checks apply exactly as for + any other repository. + +Re-adding the same address with a new login replaces the saved one. Re-adding +it without a login keeps the saved one. + The API for the search/server integration is in `ui/apk_sources/fdroid.py`: -`add_repo(url, fingerprint=None, name=None)`, `remove_repo(source_id)`, +`add_repo(url, fingerprint=None, name=None, username=None, password=None)`, `remove_repo(source_id)`, `set_enabled(source_id, enabled)`, and `user_repos()`. The module also exposes `sources`, `search`, `details`, and `download` from the shared source contract. This change supplies the CLI and API; the integrated source-management UI is diff --git a/docs/apk-sources.md b/docs/apk-sources.md index 7caca71..07056c9 100644 --- a/docs/apk-sources.md +++ b/docs/apk-sources.md @@ -45,10 +45,21 @@ search. Results outside the curated list stay page-only, even if a repository claims an open-source license. This prevents an arbitrary tagged mirror from becoming a trusted downloader. Extend the curated JSON after provenance review. -Set optional `FRAME_GITHUB_TOKEN` in the process environment for a higher API -quota. Tokens are sent only to `api.github.com`, never written to the cache, -never sent to asset hosts, and removed on redirects. The adapter does not -read `gh` credentials automatically. Metadata is cached for one hour under +For a higher API quota, add a GitHub access token in the store's source +settings (the GitHub row's token field) or through the server API +(`POST /api/sources` with `action: "set-token"` or `"clear-token"` and +`source: "github"`). `FRAME_GITHUB_TOKEN` in the process environment still +works and wins over a saved token. A saved token is kept with repository +logins in `source-credentials.json` (mode 0600, see +[APK repositories](apk-repos.md#repositories-behind-a-login)). The source list +reports only whether a token is set, where it came from and whether GitHub +rejected it, never its value. Tokens are sent as `Authorization: Bearer` only to +`api.github.com`, never written to the cache, never sent to asset hosts (public +release downloads don't need them), and removed on redirects. If GitHub answers +401 to the token, the request is retried once without it, as Obtainium does. +The rejection is logged without the token and shown in source settings. The +token is not tried again until it is saved again or the app restarts. The +adapter does not read `gh` credentials automatically. Metadata is cached for one hour under `frame_host.cache_dir('apk-sources', 'publisher')`. A cold details request fetches at most ten releases. Rate-limit errors are surfaced without retry loops. Asset IDs and release tags are not Android version codes: metadata From 2d81c9211486649ad0315c06faac0a4641275e98 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:00:33 +1100 Subject: [PATCH 14/19] Source logins: fix review findings (artwork scope, file lock, page, backoff) - Artwork: a saved login is only sent for URLs under the repository by whole path segments. Paths with dot segments (plain or percent-encoded), encoded slashes/backslashes, double encoding or ';' get nothing, since a server could normalise them outside the repository. Checked again on every redirect hop; Handler(scoped=True) does the same for urllib callers. - Credentials file: every read-modify-write holds an inter-process lock (source-credentials.lock, flock or msvcrt), so the CLI and the app can't undo each other's saves or bring back a removed login. - Store page: a login typed into the address moves into the login fields, and out of the address field, before the add starts, and stays there if it fails. - Rate-limit backoff is keyed per login (anonymous or each token), so saving a GitHub token after anonymous requests were limited is used at once. Regression tests: outgoing artwork headers for traversal URLs and a redirect to one, two processes churning the credentials file, anonymous limit then token, and the page's login handling in node. Co-Authored-By: Claude Opus 5.5 --- docs/apk-repos.md | 11 ++- docs/apk-sources.md | 4 +- tests/page/source_login.mjs | 49 +++++++++++ tests/test_source_logins.py | 155 ++++++++++++++++++++++++++++++++- ui/apk_sources/_credentials.py | 87 ++++++++++++++++-- ui/apk_sources/_web.py | 25 ++++-- ui/apk_sources/fdroid.py | 4 +- ui/index.html | 18 +++- 8 files changed, 326 insertions(+), 27 deletions(-) create mode 100644 tests/page/source_login.mjs diff --git a/docs/apk-repos.md b/docs/apk-repos.md index 8edffee..d4cf795 100644 --- a/docs/apk-repos.md +++ b/docs/apk-repos.md @@ -83,14 +83,19 @@ How the login is kept and used: macOS), written with mode 0600 and keyed by source id. They are stored in plain text there, protected by file permissions only (on Windows, the folder's normal ACLs). Removing the repository deletes its login, and - the file goes when the last login is removed. + the file goes when the last login is removed. Each change holds a lock + file (`source-credentials.lock`), so the app and the command line can't undo + each other's saves or removals. - **HTTPS only.** An `http://` address with a login is refused before any request. - **Exact origin only.** The `Authorization` header is added per request, and only when the request's scheme, host and port match the repository's. A redirect to another host or port gets no login, and that request's own `Authorization` header is removed. A same-origin redirect still gets it. - The store's artwork proxy sends the login only for images under the - repository's own address on that origin. + The store's artwork proxy is stricter: it sends the login only for images + under the repository's address by whole path segments, checked again on + every redirect. Paths with `.` or `..` segments (plain or percent-encoded), + encoded `/` or `\`, double encoding or `;` get no login, since a server + could normalise them to a path outside the repository. - **Never echoed.** Logins are not written to logs, error messages, API responses or the cache. The CLI prints only the saved source. - **Checked before saving.** As with any repository, the whole index must diff --git a/docs/apk-sources.md b/docs/apk-sources.md index 07056c9..48e45be 100644 --- a/docs/apk-sources.md +++ b/docs/apk-sources.md @@ -58,7 +58,9 @@ rejected it, never its value. Tokens are sent as `Authorization: Bearer` only to release downloads don't need them), and removed on redirects. If GitHub answers 401 to the token, the request is retried once without it, as Obtainium does. The rejection is logged without the token and shown in source settings. The -token is not tried again until it is saved again or the app restarts. The +token is not tried again until it is saved again or the app restarts. Rate-limit +backoff is kept per login (anonymous, or each token), so saving a token after +anonymous requests were limited lets the next request go out with it. The adapter does not read `gh` credentials automatically. Metadata is cached for one hour under `frame_host.cache_dir('apk-sources', 'publisher')`. A cold details request fetches at most ten releases. Rate-limit errors are surfaced without retry diff --git a/tests/page/source_login.mjs b/tests/page/source_login.mjs new file mode 100644 index 0000000..84757ad --- /dev/null +++ b/tests/page/source_login.mjs @@ -0,0 +1,49 @@ +// The store's "Add a source" login handling and GitHub token field, run in node against +// the real functions from ui/index.html. A login typed into the address must leave the +// address field (into the login fields) before anything is sent, and stay out of it. +import { readFileSync } from "fs"; +const src = readFileSync(new URL("../../ui/index.html", import.meta.url), "utf8"); +const lines = src.split("\n"); +const fail = msg => { console.log("FAIL " + msg); process.exit(1); }; + +function grab(name) { + const start = lines.findIndex(l => new RegExp(`^(?:(?:async )?function ${name}\\(|const ${name} = )`).test(l)); + if (start < 0) fail(`no top-level ${name} in index.html`); + let depth = 0; + for (let i = start; i < lines.length; i++) { + for (const c of lines[i]) depth += c === "{" ? 1 : c === "}" ? -1 : 0; + if (depth <= 0) return lines.slice(start, i + 1).join("\n") + "\n"; + } + fail(`unbalanced ${name}`); +} +const { moveLogin, sourceToken } = new Function( + "const esc = s => String(s).replace(/[&<>\"']/g, c => `&#${c.charCodeAt(0)};`); const storeName = s => s;\n" + + grab("moveLogin") + grab("sourceToken") + "return { moveLogin, sourceToken };")(); + +function form(url, username = "", password = "") { + const details = { open: false }; + const field = value => ({ value, closest: () => details }); + return { details, elements: { url: field(url), username: field(username), password: field(password) } }; +} + +let f = form("https://alice:s3cr%40t@repo.example/fdroid/repo"); +moveLogin(f); +if (f.elements.url.value !== "https://repo.example/fdroid/repo") fail("address still holds the login: " + f.elements.url.value); +if (f.elements.username.value !== "alice" || f.elements.password.value !== "s3cr@t") fail("login not moved into its fields"); +if (!f.details.open) fail("login fields not shown"); + +f = form("https://alice:fromurl@repo.example/repo", "typed", "typedpw"); +moveLogin(f); +if (f.elements.url.value.includes("fromurl") || f.elements.username.value !== "typed" || f.elements.password.value !== "typedpw") + fail("typed login replaced, or address kept the login"); + +for (const url of ["https://repo.example/repo", "not a url"]) { + f = form(url); + moveLogin(f); + if (f.elements.url.value !== url || f.elements.username.value) fail("changed an address without a login: " + url); +} + +const html = sourceToken({ id: "github", name: "GitHub releases", token: { set: true, from: "saved", rejected: true } }); +if (!html.includes("rejected") || !html.includes('data-clear-token="github"')) fail("token row: " + html); +if (sourceToken({ id: "fdroid", name: "F-Droid" }) !== "") fail("token field on a source without one"); +console.log("ok"); diff --git a/tests/test_source_logins.py b/tests/test_source_logins.py index 3187992..c236bf8 100644 --- a/tests/test_source_logins.py +++ b/tests/test_source_logins.py @@ -11,18 +11,20 @@ import io import json import os from pathlib import Path +import shutil import stat +import subprocess import sys import tempfile import threading import time import unittest -from unittest.mock import patch +from unittest.mock import Mock, patch import urllib.request import urllib.response sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'ui')) -from apk_sources import SourceAuthError, SourceError, _credentials, _images, _web, fdroid, github, search +from apk_sources import SourceAuthError, SourceError, SourceLimited, _credentials, _images, _web, fdroid, github, search import server FIXTURES = Path(__file__).parent / 'fixtures' / 'fdroid' @@ -255,11 +257,14 @@ class GitHubToken(Base): super().setUp() self.accept = {TOKEN} self.releases = json.dumps([]).encode() + self.anonymous_limited = False def route(self, url, auth): if url.startswith('https://api.github.com/'): if auth is not None and auth not in {'Bearer ' + t for t in self.accept}: return 401, {}, b'{"message": "Bad credentials"}' + if auth is None and self.anonymous_limited: + return 403, {'X-RateLimit-Remaining': '0', 'X-RateLimit-Reset': str(int(time.time()) + 1800)}, b'{}' if url.endswith('/redirected'): return 302, {'Location': 'https://github.com/landed'}, b'' return 200, {}, self.releases @@ -314,6 +319,20 @@ class GitHubToken(Base): github._api('/repos/a/b/releases') self.assertEqual(self.web.seen[-1][1], None) + def test_saving_a_token_escapes_the_anonymous_rate_limit(self): + self.anonymous_limited = True + with self.assertRaisesRegex(SourceLimited, 'GitHub is limiting requests'): + github._api('/repos/a/b/releases') + self.assertEqual(self.web.seen[-1][1], None) + github.set_token(TOKEN) + self.assertEqual(github._api('/repos/a/b/other'), []) # tried, with the token's own quota + self.assertEqual(self.web.seen[-1], ('https://api.github.com/repos/a/b/other', 'Bearer ' + TOKEN)) + github.clear_token() + count = len(self.web.seen) + with self.assertRaisesRegex(SourceLimited, 'GitHub is limiting requests'): + github._api('/repos/a/b/third') + self.assertEqual(len(self.web.seen), count) # anonymous is still backing off: no request + def test_bad_tokens_are_refused(self): for token in ('', ' ', 'two words', 'x\nAuthorization: y'): with self.subTest(token=token), self.assertRaises(SourceError): @@ -321,6 +340,138 @@ class GitHubToken(Base): self.assertFalse(self.credentials_file().exists()) +PNG = b'\x89PNG\r\n\x1a\nfixture' +PRIVATE = 'https://repo.example/private/repo/' +TRAVERSALS = [PRIVATE + '%2e%2e/%2e%2e/evil/collect.png', PRIVATE + '%2E%2E/x.png', PRIVATE + '../../evil/x.png', + PRIVATE + './icons/a.png', PRIVATE + '..%2f..%2fevil/x.png', PRIVATE + 'a%5c..%5c..%5cevil.png', + PRIVATE + 'a;b/../../evil.png', PRIVATE + '%252e%252e/%252e%252e/evil.png', + 'https://repo.example/private/repository/x.png', 'https://repo.example/private/repo%2fx.png'] + + +class ArtworkScope(Base): + """The artwork proxy: actual outgoing headers, through _images.get's own HTTP code.""" + + def setUp(self): + super().setUp() + self.sent, self.redirects = [], {} + _credentials.put('fdroid-user-private', _credentials.basic(PRIVATE, USER, PASSWORD)) + test = self + + class Response: + def __init__(self, status, location=''): + self.status, self.location, self.body = status, location, PNG if status == 200 else b'' + + def getheader(self, name, default=''): + return self.location if name == 'Location' else default + + def read1(self, n): + chunk, self.body = self.body[:n], self.body[n:] + return chunk + + class Connection: + def __init__(self, host, port, timeout=None): + self.host, self.port = host, port + + def request(self, method, path, headers): + url = 'https://%s%s' % (self.host, path) + test.sent.append((url, headers.get('Authorization'))) + self.url = url + + def getresponse(self): + if self.url in test.redirects: + return Response(302, test.redirects[self.url]) + return Response(200) + + def close(self): + pass + + # A public address, no real socket or TLS, and Connection in place of http.client's. + for target, name, value in [(_images, '_resolve', lambda host, port, timeout: [(2, 1, 6, '', ('93.184.216.34', port))]), + (_images.socket, 'create_connection', lambda *a, **k: Mock()), + (_images.ssl, 'create_default_context', lambda: Mock()), + (_images.http.client, 'HTTPConnection', Connection)]: + mock = patch.object(target, name, value) + mock.start() + self.addCleanup(mock.stop) + + def test_artwork_in_the_repository_gets_the_login(self): + self.assertEqual(_images.get(PRIVATE + 'icons/a%20b.png'), PNG) + self.assertEqual(self.sent, [(PRIVATE + 'icons/a%20b.png', basic(USER, PASSWORD))]) + + def test_paths_a_server_could_normalise_outside_the_repository_get_nothing(self): + for url in TRAVERSALS: + with self.subTest(url=url): + self.sent.clear() + self.assertEqual(_images.get(url), PNG) + self.assertEqual(self.sent, [(url, None)]) + self.assertIsNone(_credentials.for_url(url)) + + def test_redirect_to_a_traversal_gets_nothing(self): + start = PRIVATE + 'icons/a.png' + self.redirects[start] = PRIVATE + '%2e%2e/%2e%2e/evil/collect.png' + self.assertEqual(_images.get(start), PNG) + self.assertEqual(self.sent, [(start, basic(USER, PASSWORD)), (self.redirects[start], None)]) + + +class ScopedHandler(Base): + """Handler(scoped=True), for callers (artwork-like) that must stay inside a scope, redirects included.""" + + def route(self, url, auth): + if url == PRIVATE + 'icons/a.png': + return 302, {'Location': PRIVATE + '%2e%2e/%2e%2e/evil/collect.png'}, b'' + return 200, {}, PNG + + def test_redirect_into_a_traversal_is_stripped(self): + login = _credentials.basic(PRIVATE, USER, PASSWORD) + opener = urllib.request.build_opener(_credentials.Handler(login, scoped=True)) + with opener.open(PRIVATE + 'icons/a.png') as r: + self.assertEqual(r.read(), PNG) + self.assertEqual(self.web.seen, [(PRIVATE + 'icons/a.png', basic(USER, PASSWORD)), + (PRIVATE + '%2e%2e/%2e%2e/evil/collect.png', None)]) + for url in TRAVERSALS: + self.assertFalse(_credentials.in_scope(login, url), url) + self.assertTrue(_credentials.in_scope(login, PRIVATE + 'a/b%20c.png?x=1')) + self.assertTrue(_credentials.in_scope(login, PRIVATE.rstrip('/'))) + + +CHURN = ''' +import sys +sys.path.insert(0, sys.argv[1]) +from apk_sources import _credentials +for i in range(int(sys.argv[3])): + key = sys.argv[2] + str(i) + _credentials.put(key, _credentials.basic('https://h.example/', 'u', 'p')) + if i % 2: + _credentials.remove(key) +''' + + +class TwoProcesses(Base): + def test_interleaved_saves_and_removals_are_not_lost(self): + ui = str(Path(__file__).resolve().parents[1] / 'ui') + env = dict(os.environ, FRAME_CONTROL_DATA_DIR=str(self.root / 'data')) + count = 60 + procs = [subprocess.Popen([sys.executable, '-c', CHURN, ui, prefix, str(count)], env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) for prefix in ('a', 'b')] + for p in procs: + out, err = p.communicate(timeout=120) + self.assertEqual(p.returncode, 0, err.decode()) + saved = set(json.loads(self.credentials_file().read_text())) + self.assertEqual(saved, {p + str(i) for p in 'ab' for i in range(0, count, 2)}) + if os.name != 'nt': + self.assertEqual(stat.S_IMODE(self.credentials_file().stat().st_mode), 0o600) + + +@unittest.skipUnless(shutil.which('node'), 'needs node') +class PageLogin(unittest.TestCase): + def test_login_leaves_the_address_field_before_sending(self): + """tests/page/source_login.mjs runs the real page functions from index.html.""" + r = subprocess.run(['node', str(Path(__file__).parent / 'page' / 'source_login.mjs')], + capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + self.assertIn('ok', r.stdout) + + class Endpoints(Repository): """The server API: logins in, never out, in responses or the server log.""" diff --git a/ui/apk_sources/_credentials.py b/ui/apk_sources/_credentials.py index 063b837..71c72a1 100644 --- a/ui/apk_sources/_credentials.py +++ b/ui/apk_sources/_credentials.py @@ -6,10 +6,19 @@ credential belongs to one exact origin (https, host, port) and is only ever sent to a request for that origin: Handler adds it to each request, redirects included, and removes any Authorization header from every other request. +Artwork (for_url, and Handler(..., scoped=True)) is stricter: the URL must also be +under the credential's scope by whole path segments, with no dot segments, encoded +slashes or ';' a server could normalise into a path outside it. + Secrets leave this module only as an Authorization header value. Credential's repr hides them, and nothing here puts them in an exception message. + +Each change is a read-modify-write under an inter-process lock (the CLI and the +app may both save), so one process can't undo another's save or removal. """ import base64 +import contextlib +import errno import json import os import tempfile @@ -27,6 +36,65 @@ def _path(): return frame_host.data_dir('source-credentials.json') +@contextlib.contextmanager +def _changing(): + """This thread, then this process, holds the credentials file for a read-modify-write.""" + path = _path().with_name('source-credentials.lock') + with _lock: + path.parent.mkdir(parents=True, exist_ok=True) + with open(str(path), 'a+b') as f: + if os.name == 'nt': + import msvcrt + while True: + try: + f.seek(0) + msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1) + break + except OSError as e: # LK_LOCK gives up after ~10 s of contention; keep waiting + if e.errno not in (errno.EACCES, errno.EDEADLK): + raise + try: + yield + finally: + f.seek(0) + msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + fcntl.flock(f.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(f.fileno(), fcntl.LOCK_UN) + + +def _segments(path): + """A URL path's decoded segments, or None if a server might read it as another path: + '.' or '..' (plain or percent-encoded), encoded '/' or '\\', '%' left after decoding + (double encoding), or ';' path parameters.""" + if ';' in path or '\\' in path: + return None + parts = [urllib.parse.unquote(part) for part in path.split('/')] + if any(part in ('.', '..') or '/' in part or '\\' in part or '%' in part or ';' in part for part in parts): + return None + return parts + + +def in_scope(credential, url): + """True if url is on credential's origin and under its scope by whole, plain path segments.""" + if credential is None or not credential.matches(url): + return False + try: + path, scope = urllib.parse.urlsplit(url).path, urllib.parse.urlsplit(credential.scope).path + except ValueError: + return False + parts, base = _segments(path), _segments(scope) + if parts is None or base is None: + return False + if base and base[-1] == '': + base = base[:-1] # 'https://h/repo/' covers '/repo/x', not '/repository' + return parts[:len(base)] == base + + def origin(url): """'https://host:port' for an https URL; ValueError for anything else.""" p = urllib.parse.urlsplit(url) @@ -153,7 +221,7 @@ def has(key): def put(key, credential): if not isinstance(credential, Credential): raise TypeError('put() needs a Credential') - with _lock: + with _changing(): data = _read() data[key] = credential._json() _save(data) @@ -161,7 +229,7 @@ def put(key, credential): def remove(key): """Delete key's credential from disk; True if there was one.""" - with _lock: + with _changing(): data = _read() if key not in data: return False @@ -171,27 +239,30 @@ def remove(key): def for_url(url): - """A saved credential whose origin matches url and whose scope url is under, or None.""" + """A saved credential url is in the scope of (see in_scope), or None. Call it again for + each redirect hop: the answer depends only on the URL being requested.""" with _lock: keys = list(_read()) for key in keys: credential = get(key) - if credential and credential.matches(url) and url.startswith(credential.scope): + if in_scope(credential, url): return credential return None class Handler(urllib.request.BaseHandler): """Adds the credential to requests for its origin (redirects included) and strips - Authorization from every other request, so a redirect elsewhere never gets it.""" + Authorization from every other request, so a redirect elsewhere never gets it. + scoped=True also requires each request, redirects included, to be in_scope.""" handler_order = 900 # after the default processors - def __init__(self, credential): - self.credential = credential + def __init__(self, credential, scoped=False): + self.credential, self.scoped = credential, scoped def _request(self, req): req.remove_header('Authorization') - if self.credential is not None and self.credential.matches(req.full_url): + allowed = in_scope if self.scoped else lambda c, url: c is not None and c.matches(url) + if allowed(self.credential, req.full_url): req.add_unredirected_header('Authorization', self.credential.header()) return req diff --git a/ui/apk_sources/_web.py b/ui/apk_sources/_web.py index d24207d..3aa528f 100644 --- a/ui/apk_sources/_web.py +++ b/ui/apk_sources/_web.py @@ -38,7 +38,7 @@ def release(path): else: _in_use.pop(path, None) BACKOFF = 600 # seconds to leave a host alone after 403/429 without Retry-After -_limited = {} # host -> time.time() before which we don't contact it +_limited = {} # host (+ login identity) -> time.time() before which we don't ask it with that login _limited_lock = threading.Lock() @@ -46,8 +46,16 @@ def _host(url): return (urllib.parse.urlsplit(url).hostname or '').lower() -def throttle(url, headers=None): - """Remember that url's host asked us to back off; return the delay in seconds.""" +def _who(url, auth=None): + """Backoff key: the host, per login. A token has its own quota, so anonymous + rate limiting mustn't hold back requests made with one (or the reverse).""" + if auth is None: + return _host(url) + return _host(url) + ' ' + hashlib.sha256(auth.header().encode()).hexdigest()[:16] + + +def throttle(url, headers=None, auth=None): + """Remember that url's host asked us (with this login) to back off; return the delay in seconds.""" headers = headers or {} now, delay = time.time(), None value = (headers.get('Retry-After') or '').strip() @@ -62,14 +70,15 @@ def throttle(url, headers=None): if delay is None and headers.get('X-RateLimit-Remaining') == '0' and reset.isdigit(): delay = int(reset) - now # GitHub delay = min(max(delay if delay is not None else BACKOFF, 1), 6 * 3600) + key = _who(url, auth) with _limited_lock: - _limited[_host(url)] = max(_limited.get(_host(url), 0), now + delay) + _limited[key] = max(_limited.get(key, 0), now + delay) return delay -def wait_time(url): +def wait_time(url, auth=None): with _limited_lock: - return max(0, _limited.get(_host(url), 0) - time.time()) + return max(0, _limited.get(_who(url, auth), 0) - time.time()) def limited_error(name, seconds, hint=''): @@ -169,7 +178,7 @@ def read(url, hosts, headers=None, ttl=3600, name=None, hint='', auth=None): if os.path.isfile(path) and time.time() - os.path.getmtime(path) < ttl: with open(path, 'rb') as f: return f.read() - wait = wait_time(url) + wait = wait_time(url, auth) if wait: data = cached() if data is None: @@ -192,7 +201,7 @@ def read(url, hosts, headers=None, ttl=3600, name=None, hint='', auth=None): if e.code == 401: # not 403: GitHub also uses that for rate limits, token or not raise SourceAuthError('%s refused the login (HTTP 401)' % name) from e if e.code in (403, 429): - delay = throttle(url, e.headers) + delay = throttle(url, e.headers, auth) data = cached() if data is None: raise limited_error(name, delay, hint) from e diff --git a/ui/apk_sources/fdroid.py b/ui/apk_sources/fdroid.py index 1779bf3..324d1ff 100644 --- a/ui/apk_sources/fdroid.py +++ b/ui/apk_sources/fdroid.py @@ -127,7 +127,7 @@ class _HTTPSRedirect(urllib.request.HTTPRedirectHandler): def _fetch(url, path, maximum, auth=None): """auth: the repository's login, sent only to its exact origin (never after a redirect elsewhere).""" host = urllib.parse.urlsplit(url).hostname - wait = _web.wait_time(url) + wait = _web.wait_time(url, auth) if wait: raise _web.limited_error(host, wait) request = urllib.request.Request(url, headers={'User-Agent': 'FrameControl/1.0'}) @@ -148,7 +148,7 @@ def _fetch(url, path, maximum, auth=None): raise SourceAuthError('The repository refused the login (HTTP %d); check the username and password' % e.code if auth else 'This repository needs a username and password') from None if e.code in (403, 429): - raise _web.limited_error(host, _web.throttle(url, e.headers)) from e + raise _web.limited_error(host, _web.throttle(url, e.headers, auth)) from e raise diff --git a/ui/index.html b/ui/index.html index 62d93ee..bb475ae 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3288,10 +3288,22 @@ async function addSource(body) { $("sourceError").textContent=result ? result.message : error || "We couldn't add that repository."; if(result){$("addSource").reset();sourceState.source='';await loadSources();await searchSources();} } +// A login typed into the address moves into the login fields, on the page too, before anything +// is sent: the address is shown and logged, the login never. It stays there if adding fails. +function moveLogin(form) { + const el=form.elements; + try { + const u=new URL(el.url.value); + if(!u.username && !u.password)return; + if(!el.username.value)el.username.value=decodeURIComponent(u.username); + if(!el.password.value)el.password.value=decodeURIComponent(u.password); + u.username='';u.password='';el.url.value=u.href; + el.username.closest('details').open=true; + } catch {} +} $("addSource").onsubmit=e=>{ - e.preventDefault();const f=new FormData(e.target);let url=f.get('url'),username=f.get('username'),password=f.get('password'); - // A login typed into the address moves to the login fields: the address is shown and logged, the login never. - try { const u=new URL(url); if(u.username||u.password){ username=username||decodeURIComponent(u.username); password=password||decodeURIComponent(u.password); u.username='';u.password='';url=u.href; } } catch {} + e.preventDefault();moveLogin(e.target); + const f=new FormData(e.target), url=f.get('url'), username=f.get('username'), password=f.get('password'); addSource({action:'add',url,fingerprint:f.get('fingerprint'),...(username ? {username,password} : {})}); }; document.querySelectorAll('[data-close]').forEach(b=>b.onclick=()=>$(b.dataset.close).close()); From e20225604d8f0d794fae01ece01cb5189574d322 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:12:10 +1100 Subject: [PATCH 15/19] Source logins: keep repository logins inside the repository directory - Every request made with an F-Droid repository's login (entry.jar, index, APKs), redirects included, now uses the scoped check: same origin and inside the repository directory by whole plain path segments. A same-origin redirect elsewhere on the server gets no login. - _child() refuses file names a server could normalise outside the repository: double-encoded dots, ';' path parameters, encoded slashes or backslashes (anything _credentials.path_segments rejects). - Store page: moveLogin() strips the login from the address with plain text matching first, then decodes with a fallback to the text as typed, so '100%done', '%FF' or an address the URL parser rejects can no longer leave the password in the field. Tests: outgoing headers for '%252e%252e/...' and '..;/...' payloads and a same-origin redirect outside the repository carry no Authorization; the page test covers undecodable and unparseable logins. Co-Authored-By: Claude Opus 5.5 --- docs/apk-repos.md | 19 ++++++++++--------- tests/page/source_login.mjs | 18 +++++++++++++++++- tests/test_source_logins.py | 26 +++++++++++++++++++++++++- ui/apk_sources/_credentials.py | 15 ++++++++------- ui/apk_sources/fdroid.py | 8 ++++++-- ui/index.html | 19 ++++++++++--------- 6 files changed, 76 insertions(+), 29 deletions(-) diff --git a/docs/apk-repos.md b/docs/apk-repos.md index d4cf795..66919d3 100644 --- a/docs/apk-repos.md +++ b/docs/apk-repos.md @@ -87,15 +87,16 @@ How the login is kept and used: file (`source-credentials.lock`), so the app and the command line can't undo each other's saves or removals. - **HTTPS only.** An `http://` address with a login is refused before any request. -- **Exact origin only.** The `Authorization` header is added per request, and - only when the request's scheme, host and port match the repository's. A - redirect to another host or port gets no login, and that request's own - `Authorization` header is removed. A same-origin redirect still gets it. - The store's artwork proxy is stricter: it sends the login only for images - under the repository's address by whole path segments, checked again on - every redirect. Paths with `.` or `..` segments (plain or percent-encoded), - encoded `/` or `\`, double encoding or `;` get no login, since a server - could normalise them to a path outside the repository. +- **Inside the repository only.** The `Authorization` header is decided + separately for every request, redirects included: index, `entry.jar`, + APKs and the store's artwork proxy. It is sent only when the request's + scheme, host and port match the repository's and its path is inside the + repository's directory by whole path segments. A redirect to another host + or port, or to another path on the same server, gets no login, and that + request's own `Authorization` header is removed. Paths with `.` or `..` + segments (plain or percent-encoded), encoded `/` or `\`, double encoding + or `;` get no login, since a server could normalise them to a path + outside the repository. Index file names like that are refused outright. - **Never echoed.** Logins are not written to logs, error messages, API responses or the cache. The CLI prints only the saved source. - **Checked before saving.** As with any repository, the whole index must diff --git a/tests/page/source_login.mjs b/tests/page/source_login.mjs index 84757ad..08cf9a5 100644 --- a/tests/page/source_login.mjs +++ b/tests/page/source_login.mjs @@ -37,7 +37,23 @@ moveLogin(f); if (f.elements.url.value.includes("fromurl") || f.elements.username.value !== "typed" || f.elements.password.value !== "typedpw") fail("typed login replaced, or address kept the login"); -for (const url of ["https://repo.example/repo", "not a url"]) { +// Undecodable logins and addresses the URL parser rejects still lose their login, decoded where possible. +for (const [url, address, user, pass] of [ + ["https://alice:100%done@repo.example/private/repo", "https://repo.example/private/repo", "alice", "100%done"], + ["https://alice:%FF@repo.example/private/repo", "https://repo.example/private/repo", "alice", "%FF"], + ["https://al%20ice:p%40ss:word@repo.example/r", "https://repo.example/r", "al ice", "p@ss:word"], + ["https://alice:s3cret@repo example/repo", "https://repo example/repo", "alice", "s3cret"], + ["fdroidrepos://alice:pw@repo.example/repo?fingerprint=AB", "fdroidrepos://repo.example/repo?fingerprint=AB", "alice", "pw"], + ["https://alice@repo.example/repo", "https://repo.example/repo", "alice", ""], +]) { + f = form(url); + moveLogin(f); + if (f.elements.url.value !== address) fail(`address kept the login: ${url} -> ${f.elements.url.value}`); + if (f.elements.username.value !== user || f.elements.password.value !== pass) + fail(`login for ${url}: ${f.elements.username.value} / ${f.elements.password.value}`); +} + +for (const url of ["https://repo.example/repo", "not a url", "https://repo.example/a@b"]) { f = form(url); moveLogin(f); if (f.elements.url.value !== url || f.elements.username.value) fail("changed an address without a login: " + url); diff --git a/tests/test_source_logins.py b/tests/test_source_logins.py index c236bf8..adff86f 100644 --- a/tests/test_source_logins.py +++ b/tests/test_source_logins.py @@ -198,7 +198,31 @@ class RepositoryLogin(Repository): mirror = [auth for url, auth in self.web.seen if url.startswith('https://mirror.example/')] same_origin = [auth for url, auth in self.web.seen if url.startswith('https://repo.example/elsewhere/')] self.assertEqual(mirror, [None]) - self.assertEqual(same_origin, [self.login]) # same scheme, host and port: still that repository's + self.assertEqual(same_origin, [None]) # same origin but outside the repository: no login either + + def test_traversal_names_are_refused_and_never_get_the_login(self): + for name in ('%252e%252e/%252e%252e/evil/collect.apk', '..;/..;/evil/collect.apk', 'a%2f..%2f..%2fevil.apk', + 'a%5c..%5cevil.apk', '%2e%2e/evil.apk', 'x;y.apk', '100%25.apk'): + with self.subTest(name=name), self.assertRaisesRegex(SourceError, 'unsafe|outside'): + fdroid._child(REPO, name) + self.assertEqual(fdroid._child(REPO, '/app/en-US/phoneScreenshots/#0 a.png'), + REPO + 'app/en-US/phoneScreenshots/%230%20a.png') + # Even if such a URL reached the downloader directly, the login stays home. + login = _credentials.basic(REPO, USER, PASSWORD) + for url in (REPO + '%252e%252e/%252e%252e/evil/collect.apk', REPO + '..;/..;/evil/collect.apk'): + with self.subTest(url=url), tempfile.TemporaryDirectory() as tmp: + self.web.seen.clear() + with contextlib.suppress(SourceError): # the repository answers 401 without the login + fdroid._fetch(url, Path(tmp) / 'out', 1 << 20, auth=login) + self.assertEqual(self.web.seen, [(url, None)]) + + def test_same_origin_redirect_outside_the_repository_gets_no_login(self): + self.redirect = {'example1.apk': 'https://repo.example/elsewhere/example1.apk'} + source = self.add() + self.web.seen.clear() + self.assertTrue(fdroid.download(source, 'org.example.app', 1)['verified']) + self.assertEqual(self.web.seen, [(REPO + 'example1.apk', self.login), + ('https://repo.example/elsewhere/example1.apk', None)]) def test_other_ports_and_http_never_get_the_login(self): login = _credentials.basic(REPO, USER, PASSWORD) diff --git a/ui/apk_sources/_credentials.py b/ui/apk_sources/_credentials.py index 71c72a1..55b9889 100644 --- a/ui/apk_sources/_credentials.py +++ b/ui/apk_sources/_credentials.py @@ -6,9 +6,10 @@ credential belongs to one exact origin (https, host, port) and is only ever sent to a request for that origin: Handler adds it to each request, redirects included, and removes any Authorization header from every other request. -Artwork (for_url, and Handler(..., scoped=True)) is stricter: the URL must also be -under the credential's scope by whole path segments, with no dot segments, encoded -slashes or ';' a server could normalise into a path outside it. +Scoped use (for_url, and Handler(..., scoped=True), which F-Droid repositories and +artwork use) is stricter: the URL must also be under the credential's scope by whole +path segments, with no dot segments, encoded slashes or ';' a server could normalise +into a path outside it. Origin-only matching suits a host-wide token (GitHub's API). Secrets leave this module only as an Authorization header value. Credential's repr hides them, and nothing here puts them in an exception message. @@ -67,7 +68,7 @@ def _changing(): fcntl.flock(f.fileno(), fcntl.LOCK_UN) -def _segments(path): +def path_segments(path): """A URL path's decoded segments, or None if a server might read it as another path: '.' or '..' (plain or percent-encoded), encoded '/' or '\\', '%' left after decoding (double encoding), or ';' path parameters.""" @@ -87,7 +88,7 @@ def in_scope(credential, url): path, scope = urllib.parse.urlsplit(url).path, urllib.parse.urlsplit(credential.scope).path except ValueError: return False - parts, base = _segments(path), _segments(scope) + parts, base = path_segments(path), path_segments(scope) if parts is None or base is None: return False if base and base[-1] == '': @@ -116,8 +117,8 @@ def _check(value, what, allow_empty=False): class Credential: """A username and password (basic) or a token (bearer) for one origin. - scope is a URL prefix used only to pick a stored credential for a URL (for_url); - whether a request gets the credential depends on its origin alone.""" + scope is the URL prefix it belongs under: in_scope checks it (by path segments), + matches() checks only the origin.""" __slots__ = ('origin', 'scope', 'username', '_secret') def __init__(self, scope, secret, username=None): diff --git a/ui/apk_sources/fdroid.py b/ui/apk_sources/fdroid.py index 324d1ff..8f89973 100644 --- a/ui/apk_sources/fdroid.py +++ b/ui/apk_sources/fdroid.py @@ -114,6 +114,9 @@ def _child(base, name): url = urllib.parse.urljoin(base, urllib.parse.quote(decoded, safe='/')) # names may contain '#' or spaces if not url.startswith(base) or urllib.parse.urlsplit(url).query or urllib.parse.urlsplit(url).fragment: raise SourceError('repository file is outside its repository') + # Nothing a server could normalise elsewhere: double-encoded dots, ';' parameters, encoded slashes. + if _credentials.path_segments(urllib.parse.urlsplit(url).path) is None: + raise SourceError('unsafe repository file name') return url @@ -125,13 +128,14 @@ class _HTTPSRedirect(urllib.request.HTTPRedirectHandler): def _fetch(url, path, maximum, auth=None): - """auth: the repository's login, sent only to its exact origin (never after a redirect elsewhere).""" + """auth: the repository's login, sent only inside the repository (its origin and directory, + by whole plain path segments), on every request including redirects.""" host = urllib.parse.urlsplit(url).hostname wait = _web.wait_time(url, auth) if wait: raise _web.limited_error(host, wait) request = urllib.request.Request(url, headers={'User-Agent': 'FrameControl/1.0'}) - handlers = [_HTTPSRedirect()] + ([_credentials.Handler(auth)] if auth else []) + handlers = [_HTTPSRedirect()] + ([_credentials.Handler(auth, scoped=True)] if auth else []) try: with urllib.request.build_opener(*handlers).open(request, timeout=60) as r, open(path, 'wb') as f: total = 0 diff --git a/ui/index.html b/ui/index.html index bb475ae..f343f5b 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3290,16 +3290,17 @@ async function addSource(body) { } // A login typed into the address moves into the login fields, on the page too, before anything // is sent: the address is shown and logged, the login never. It stays there if adding fails. +// Plain text, not the URL parser: an address it rejects (or a login it can't decode) must +// still lose its login first. Decoding falls back to the text as typed. function moveLogin(form) { - const el=form.elements; - try { - const u=new URL(el.url.value); - if(!u.username && !u.password)return; - if(!el.username.value)el.username.value=decodeURIComponent(u.username); - if(!el.password.value)el.password.value=decodeURIComponent(u.password); - u.username='';u.password='';el.url.value=u.href; - el.username.closest('details').open=true; - } catch {} + const el=form.elements, m=/^(\s*[a-z][a-z0-9+.-]*:\/\/)([^\/?#]*)@/i.exec(el.url.value); + if(!m)return; + el.url.value=m[1]+el.url.value.slice(m[0].length); + const decode=s=>{ try { return decodeURIComponent(s); } catch { return s; } }; + const at=m[2].indexOf(':'), user=at<0 ? m[2] : m[2].slice(0,at), pass=at<0 ? "" : m[2].slice(at+1); + if(!el.username.value)el.username.value=decode(user); + if(!el.password.value)el.password.value=decode(pass); + el.username.closest('details').open=true; } $("addSource").onsubmit=e=>{ e.preventDefault();moveLogin(e.target); From a94c45d0143b603566cf3b5c149e06b725bb1d16 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:26:18 +1100 Subject: [PATCH 16/19] Source logins: strip a pasted login even with tabs, newlines or backslashes in the address Co-Authored-By: Claude Opus 5.5 --- tests/page/source_login.mjs | 4 ++++ ui/index.html | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/page/source_login.mjs b/tests/page/source_login.mjs index 08cf9a5..8882e92 100644 --- a/tests/page/source_login.mjs +++ b/tests/page/source_login.mjs @@ -40,6 +40,10 @@ if (f.elements.url.value.includes("fromurl") || f.elements.username.value !== "t // Undecodable logins and addresses the URL parser rejects still lose their login, decoded where possible. for (const [url, address, user, pass] of [ ["https://alice:100%done@repo.example/private/repo", "https://repo.example/private/repo", "alice", "100%done"], + ["https:\t//alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], + ["ht\ntps://alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], + ["https:\\\\alice:s3cret@repo.example/repo", "https:\\\\repo.example/repo", "alice", "s3cret"], + ["https:alice:s3cret@repo.example/repo", "https:repo.example/repo", "alice", "s3cret"], ["https://alice:%FF@repo.example/private/repo", "https://repo.example/private/repo", "alice", "%FF"], ["https://al%20ice:p%40ss:word@repo.example/r", "https://repo.example/r", "al ice", "p@ss:word"], ["https://alice:s3cret@repo example/repo", "https://repo example/repo", "alice", "s3cret"], diff --git a/ui/index.html b/ui/index.html index f343f5b..1c43a7c 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3293,7 +3293,10 @@ async function addSource(body) { // Plain text, not the URL parser: an address it rejects (or a login it can't decode) must // still lose its login first. Decoding falls back to the text as typed. function moveLogin(form) { - const el=form.elements, m=/^(\s*[a-z][a-z0-9+.-]*:\/\/)([^\/?#]*)@/i.exec(el.url.value); + // URL parsers drop tabs and newlines and accept backslashes or no slashes after + // the scheme, so normalise those before looking for a login. + const el=form.elements; el.url.value=el.url.value.replace(/[\t\n\r]/g,''); + const m=/^(\s*[a-z][a-z0-9+.-]*:[\/\\]*)([^\/\\?#]*)@/i.exec(el.url.value); if(!m)return; el.url.value=m[1]+el.url.value.slice(m[0].length); const decode=s=>{ try { return decodeURIComponent(s); } catch { return s; } }; From 8347c2c3f7b174ea18793dad5d024e09d6051da3 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:30:54 +1100 Subject: [PATCH 17/19] Source logins: let the URL parser find a pasted login; text matching only as a fallback Co-Authored-By: Claude Opus 5.5 --- tests/page/source_login.mjs | 8 +++++--- ui/index.html | 24 ++++++++++++++++-------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/tests/page/source_login.mjs b/tests/page/source_login.mjs index 8882e92..d660877 100644 --- a/tests/page/source_login.mjs +++ b/tests/page/source_login.mjs @@ -42,8 +42,10 @@ for (const [url, address, user, pass] of [ ["https://alice:100%done@repo.example/private/repo", "https://repo.example/private/repo", "alice", "100%done"], ["https:\t//alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], ["ht\ntps://alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], - ["https:\\\\alice:s3cret@repo.example/repo", "https:\\\\repo.example/repo", "alice", "s3cret"], - ["https:alice:s3cret@repo.example/repo", "https:repo.example/repo", "alice", "s3cret"], + ["https:\\\\alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], + ["https:alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], + ["\u0000https://alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], + ["fdroidrepos://alice:p\\w@repo.example/repo", "fdroidrepos://repo.example/repo", "alice", "p\\w"], ["https://alice:%FF@repo.example/private/repo", "https://repo.example/private/repo", "alice", "%FF"], ["https://al%20ice:p%40ss:word@repo.example/r", "https://repo.example/r", "al ice", "p@ss:word"], ["https://alice:s3cret@repo example/repo", "https://repo example/repo", "alice", "s3cret"], @@ -57,7 +59,7 @@ for (const [url, address, user, pass] of [ fail(`login for ${url}: ${f.elements.username.value} / ${f.elements.password.value}`); } -for (const url of ["https://repo.example/repo", "not a url", "https://repo.example/a@b"]) { +for (const url of ["https://repo.example/repo", "not a url", "https://repo.example/a@b", "fdroidrepos:///a@b", "fdroidrepos:/a@b", "https://repo.example/r?x=a@b#c@d"]) { f = form(url); moveLogin(f); if (f.elements.url.value !== url || f.elements.username.value) fail("changed an address without a login: " + url); diff --git a/ui/index.html b/ui/index.html index 1c43a7c..f8aa672 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3293,14 +3293,22 @@ async function addSource(body) { // Plain text, not the URL parser: an address it rejects (or a login it can't decode) must // still lose its login first. Decoding falls back to the text as typed. function moveLogin(form) { - // URL parsers drop tabs and newlines and accept backslashes or no slashes after - // the scheme, so normalise those before looking for a login. - const el=form.elements; el.url.value=el.url.value.replace(/[\t\n\r]/g,''); - const m=/^(\s*[a-z][a-z0-9+.-]*:[\/\\]*)([^\/\\?#]*)@/i.exec(el.url.value); - if(!m)return; - el.url.value=m[1]+el.url.value.slice(m[0].length); - const decode=s=>{ try { return decodeURIComponent(s); } catch { return s; } }; - const at=m[2].indexOf(':'), user=at<0 ? m[2] : m[2].slice(0,at), pass=at<0 ? "" : m[2].slice(at+1); + // Normalise the way URL parsers do (trim C0 controls and spaces, drop tabs and + // newlines), then let the parser find the login so every address it accepts loses + // it. Text matching is only a fallback for addresses the parser rejects. + const el=form.elements, decode=s=>{ try { return decodeURIComponent(s); } catch { return s; } }; + el.url.value=el.url.value.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,'').replace(/[\t\n\r]/g,''); + let user, pass; + try { + const u=new URL(el.url.value); + if(!u.username && !u.password)return; + user=u.username; pass=u.password; u.username=''; u.password=''; el.url.value=u.href; + } catch { + const m=/^([a-z][a-z0-9+.-]*:\/\/)([^\/?#]*)@/i.exec(el.url.value); + if(!m)return; + el.url.value=m[1]+el.url.value.slice(m[0].length); + const at=m[2].indexOf(':'); user=at<0 ? m[2] : m[2].slice(0,at); pass=at<0 ? "" : m[2].slice(at+1); + } if(!el.username.value)el.username.value=decode(user); if(!el.password.value)el.password.value=decode(pass); el.username.closest('details').open=true; From 2f1aeaac72580b45d19c57b83800ab62eb36512f Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:35:50 +1100 Subject: [PATCH 18/19] Source logins: refuse an invalid address that holds a login; keep undecodable bytes as typed Co-Authored-By: Claude Opus 5.5 --- tests/page/source_login.mjs | 13 ++++++++--- ui/index.html | 46 ++++++++++++++++++++++--------------- 2 files changed, 37 insertions(+), 22 deletions(-) diff --git a/tests/page/source_login.mjs b/tests/page/source_login.mjs index d660877..dced308 100644 --- a/tests/page/source_login.mjs +++ b/tests/page/source_login.mjs @@ -18,7 +18,7 @@ function grab(name) { } const { moveLogin, sourceToken } = new Function( "const esc = s => String(s).replace(/[&<>\"']/g, c => `&#${c.charCodeAt(0)};`); const storeName = s => s;\n" + - grab("moveLogin") + grab("sourceToken") + "return { moveLogin, sourceToken };")(); + grab("decodeLenient") + grab("moveLogin") + grab("sourceToken") + "return { moveLogin, sourceToken };")(); function form(url, username = "", password = "") { const details = { open: false }; @@ -37,7 +37,7 @@ moveLogin(f); if (f.elements.url.value.includes("fromurl") || f.elements.username.value !== "typed" || f.elements.password.value !== "typedpw") fail("typed login replaced, or address kept the login"); -// Undecodable logins and addresses the URL parser rejects still lose their login, decoded where possible. +// Undecodable logins and unusual spellings the URL parser accepts still lose their login; undecodable bytes stay as typed. for (const [url, address, user, pass] of [ ["https://alice:100%done@repo.example/private/repo", "https://repo.example/private/repo", "alice", "100%done"], ["https:\t//alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], @@ -48,7 +48,7 @@ for (const [url, address, user, pass] of [ ["fdroidrepos://alice:p\\w@repo.example/repo", "fdroidrepos://repo.example/repo", "alice", "p\\w"], ["https://alice:%FF@repo.example/private/repo", "https://repo.example/private/repo", "alice", "%FF"], ["https://al%20ice:p%40ss:word@repo.example/r", "https://repo.example/r", "al ice", "p@ss:word"], - ["https://alice:s3cret@repo example/repo", "https://repo example/repo", "alice", "s3cret"], + ["https://alice:p%FF\u00e4@repo.example/repo", "https://repo.example/repo", "alice", "p%FF\u00e4"], ["fdroidrepos://alice:pw@repo.example/repo?fingerprint=AB", "fdroidrepos://repo.example/repo?fingerprint=AB", "alice", "pw"], ["https://alice@repo.example/repo", "https://repo.example/repo", "alice", ""], ]) { @@ -59,6 +59,13 @@ for (const [url, address, user, pass] of [ fail(`login for ${url}: ${f.elements.username.value} / ${f.elements.password.value}`); } +// An address the parser rejects that may hold a login is refused and left as typed, never sent. +for (const url of ["https://alice:s3cret@repo example/repo", "https:alice:s3cret@repo example/repo", "https://repo.example:bad\\a@b"]) { + f = form(url); + if (moveLogin(f) !== false) fail("accepted an invalid address with a login: " + url); + if (f.elements.username.value || f.elements.password.value) fail("guessed a login from an invalid address: " + url); +} + for (const url of ["https://repo.example/repo", "not a url", "https://repo.example/a@b", "fdroidrepos:///a@b", "fdroidrepos:/a@b", "https://repo.example/r?x=a@b#c@d"]) { f = form(url); moveLogin(f); diff --git a/ui/index.html b/ui/index.html index f8aa672..4d76b46 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3292,29 +3292,37 @@ async function addSource(body) { // is sent: the address is shown and logged, the login never. It stays there if adding fails. // Plain text, not the URL parser: an address it rejects (or a login it can't decode) must // still lose its login first. Decoding falls back to the text as typed. +// Percent-decode what decodes; keep any byte sequence that isn't UTF-8 as typed. +function decodeLenient(s) { + return s.replace(/(?:%[0-9a-f]{2})+/gi, run => { + let out='', i=0; + while(ii; j-=3){ try { out+=decodeURIComponent(run.slice(i,j)); break; } catch {} } + if(j>i) i=j; else { out+=run.slice(i,i+3); i+=3; } + } + return out; + }); +} +// Moves a login typed into the address into the login fields. Returns false for an +// address the URL parser rejects that may hold a login: it is refused, not sent. function moveLogin(form) { - // Normalise the way URL parsers do (trim C0 controls and spaces, drop tabs and - // newlines), then let the parser find the login so every address it accepts loses - // it. Text matching is only a fallback for addresses the parser rejects. - const el=form.elements, decode=s=>{ try { return decodeURIComponent(s); } catch { return s; } }; - el.url.value=el.url.value.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,'').replace(/[\t\n\r]/g,''); - let user, pass; - try { - const u=new URL(el.url.value); - if(!u.username && !u.password)return; - user=u.username; pass=u.password; u.username=''; u.password=''; el.url.value=u.href; - } catch { - const m=/^([a-z][a-z0-9+.-]*:\/\/)([^\/?#]*)@/i.exec(el.url.value); - if(!m)return; - el.url.value=m[1]+el.url.value.slice(m[0].length); - const at=m[2].indexOf(':'); user=at<0 ? m[2] : m[2].slice(0,at); pass=at<0 ? "" : m[2].slice(at+1); - } - if(!el.username.value)el.username.value=decode(user); - if(!el.password.value)el.password.value=decode(pass); + // Normalise the way URL parsers do: trim C0 controls and spaces, drop tabs and newlines. + const el=form.elements; + el.url.value=el.url.value.replace(/^[\u0000- ]+|[\u0000- ]+$/g,'').replace(/[\t\n\r]/g,''); + let u; + try { u=new URL(el.url.value); } catch { return !el.url.value.includes('@'); } + if(!u.username && !u.password)return true; + const user=decodeLenient(u.username), pass=decodeLenient(u.password); + u.username=''; u.password=''; el.url.value=u.href; + if(!el.username.value)el.username.value=user; + if(!el.password.value)el.password.value=pass; el.username.closest('details').open=true; + return true; } $("addSource").onsubmit=e=>{ - e.preventDefault();moveLogin(e.target); + e.preventDefault(); + if(!moveLogin(e.target)){ $("sourceError").textContent="That address isn't valid. Put the username and password in the login fields below, not in the address."; return; } const f=new FormData(e.target), url=f.get('url'), username=f.get('username'), password=f.get('password'); addSource({action:'add',url,fingerprint:f.get('fingerprint'),...(username ? {username,password} : {})}); }; From 4ecc03280e4f861fa58fb329fc581b36e67be6f3 Mon Sep 17 00:00:00 2001 From: saphid <4596216+saphid@users.noreply.github.com> Date: Tue, 13 Oct 2026 13:41:40 +1100 Subject: [PATCH 19/19] Source logins: refuse addresses with a backslash and a login; decode escapes in one pass Co-Authored-By: Claude Opus 5.5 --- tests/page/source_login.mjs | 7 ++++--- ui/index.html | 15 ++++++++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/tests/page/source_login.mjs b/tests/page/source_login.mjs index dced308..de8ab47 100644 --- a/tests/page/source_login.mjs +++ b/tests/page/source_login.mjs @@ -42,10 +42,8 @@ for (const [url, address, user, pass] of [ ["https://alice:100%done@repo.example/private/repo", "https://repo.example/private/repo", "alice", "100%done"], ["https:\t//alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], ["ht\ntps://alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], - ["https:\\\\alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], ["https:alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], ["\u0000https://alice:s3cret@repo.example/repo", "https://repo.example/repo", "alice", "s3cret"], - ["fdroidrepos://alice:p\\w@repo.example/repo", "fdroidrepos://repo.example/repo", "alice", "p\\w"], ["https://alice:%FF@repo.example/private/repo", "https://repo.example/private/repo", "alice", "%FF"], ["https://al%20ice:p%40ss:word@repo.example/r", "https://repo.example/r", "al ice", "p@ss:word"], ["https://alice:p%FF\u00e4@repo.example/repo", "https://repo.example/repo", "alice", "p%FF\u00e4"], @@ -60,7 +58,7 @@ for (const [url, address, user, pass] of [ } // An address the parser rejects that may hold a login is refused and left as typed, never sent. -for (const url of ["https://alice:s3cret@repo example/repo", "https:alice:s3cret@repo example/repo", "https://repo.example:bad\\a@b"]) { +for (const url of ["https://alice\\name:pw@repo.example/repo", "https:\\\\alice:s3cret@repo.example/repo", "fdroidrepos://alice:p\\w@repo.example/repo", "https://alice:s3cret@repo example/repo", "https:alice:s3cret@repo example/repo", "https://repo.example:bad\\a@b"]) { f = form(url); if (moveLogin(f) !== false) fail("accepted an invalid address with a login: " + url); if (f.elements.username.value || f.elements.password.value) fail("guessed a login from an invalid address: " + url); @@ -75,4 +73,7 @@ for (const url of ["https://repo.example/repo", "not a url", "https://repo.examp const html = sourceToken({ id: "github", name: "GitHub releases", token: { set: true, from: "saved", rejected: true } }); if (!html.includes("rejected") || !html.includes('data-clear-token="github"')) fail("token row: " + html); if (sourceToken({ id: "fdroid", name: "F-Droid" }) !== "") fail("token field on a source without one"); +const slow = "https://a:" + "%FF".repeat(4000) + "@repo.example/r", t0 = Date.now(); +f = form(slow); moveLogin(f); +if (Date.now() - t0 > 200 || f.elements.password.value !== "%FF".repeat(4000)) fail("decoding malformed escapes is slow or wrong"); console.log("ok"); diff --git a/ui/index.html b/ui/index.html index 4d76b46..ebca9d4 100644 --- a/ui/index.html +++ b/ui/index.html @@ -3293,13 +3293,15 @@ async function addSource(body) { // Plain text, not the URL parser: an address it rejects (or a login it can't decode) must // still lose its login first. Decoding falls back to the text as typed. // Percent-decode what decodes; keep any byte sequence that isn't UTF-8 as typed. +// One forward pass: each lead byte gives its sequence length (at most 4 bytes). function decodeLenient(s) { return s.replace(/(?:%[0-9a-f]{2})+/gi, run => { - let out='', i=0; - while(ii; j-=3){ try { out+=decodeURIComponent(run.slice(i,j)); break; } catch {} } - if(j>i) i=j; else { out+=run.slice(i,i+3); i+=3; } + const b=run.match(/%[0-9a-f]{2}/gi); let out='', i=0; + while(i=0xC2&&v<0xE0 ? 2 : v>=0xE0&&v<0xF0 ? 3 : v>=0xF0&&v<0xF5 ? 4 : 0; + if(n){ try { out+=decodeURIComponent(b.slice(i,i+n).join('')); i+=n; continue; } catch {} } + out+=b[i]; i++; } return out; }); @@ -3311,6 +3313,9 @@ function moveLogin(form) { const el=form.elements; el.url.value=el.url.value.replace(/^[\u0000- ]+|[\u0000- ]+$/g,'').replace(/[\t\n\r]/g,''); let u; + // A backslash and an '@' together are read differently by browsers and by the + // server, so the address can't be split safely: refuse it rather than guess. + if(el.url.value.includes('@') && el.url.value.includes('\\'))return false; try { u=new URL(el.url.value); } catch { return !el.url.value.includes('@'); } if(!u.username && !u.password)return true; const user=decodeLenient(u.username), pass=decodeLenient(u.password);